three.webgpu.js 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '170';
  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 LinearTransfer = 'linear';
  168. const SRGBTransfer = 'srgb';
  169. const ZeroStencilOp = 0;
  170. const KeepStencilOp = 7680;
  171. const ReplaceStencilOp = 7681;
  172. const IncrementStencilOp = 7682;
  173. const DecrementStencilOp = 7683;
  174. const IncrementWrapStencilOp = 34055;
  175. const DecrementWrapStencilOp = 34056;
  176. const InvertStencilOp = 5386;
  177. const NeverStencilFunc = 512;
  178. const LessStencilFunc = 513;
  179. const EqualStencilFunc = 514;
  180. const LessEqualStencilFunc = 515;
  181. const GreaterStencilFunc = 516;
  182. const NotEqualStencilFunc = 517;
  183. const GreaterEqualStencilFunc = 518;
  184. const AlwaysStencilFunc = 519;
  185. const NeverCompare = 512;
  186. const LessCompare = 513;
  187. const EqualCompare = 514;
  188. const LessEqualCompare = 515;
  189. const GreaterCompare = 516;
  190. const NotEqualCompare = 517;
  191. const GreaterEqualCompare = 518;
  192. const AlwaysCompare = 519;
  193. const StaticDrawUsage = 35044;
  194. const DynamicDrawUsage = 35048;
  195. const StreamDrawUsage = 35040;
  196. const StaticReadUsage = 35045;
  197. const DynamicReadUsage = 35049;
  198. const StreamReadUsage = 35041;
  199. const StaticCopyUsage = 35046;
  200. const DynamicCopyUsage = 35050;
  201. const StreamCopyUsage = 35042;
  202. const GLSL1 = '100';
  203. const GLSL3 = '300 es';
  204. const WebGLCoordinateSystem = 2000;
  205. const WebGPUCoordinateSystem = 2001;
  206. /**
  207. * https://github.com/mrdoob/eventdispatcher.js/
  208. */
  209. class EventDispatcher {
  210. addEventListener( type, listener ) {
  211. if ( this._listeners === undefined ) this._listeners = {};
  212. const listeners = this._listeners;
  213. if ( listeners[ type ] === undefined ) {
  214. listeners[ type ] = [];
  215. }
  216. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  217. listeners[ type ].push( listener );
  218. }
  219. }
  220. hasEventListener( type, listener ) {
  221. if ( this._listeners === undefined ) return false;
  222. const listeners = this._listeners;
  223. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  224. }
  225. removeEventListener( type, listener ) {
  226. if ( this._listeners === undefined ) return;
  227. const listeners = this._listeners;
  228. const listenerArray = listeners[ type ];
  229. if ( listenerArray !== undefined ) {
  230. const index = listenerArray.indexOf( listener );
  231. if ( index !== - 1 ) {
  232. listenerArray.splice( index, 1 );
  233. }
  234. }
  235. }
  236. dispatchEvent( event ) {
  237. if ( this._listeners === undefined ) return;
  238. const listeners = this._listeners;
  239. const listenerArray = listeners[ event.type ];
  240. if ( listenerArray !== undefined ) {
  241. event.target = this;
  242. // Make a copy, in case listeners are removed while iterating.
  243. const array = listenerArray.slice( 0 );
  244. for ( let i = 0, l = array.length; i < l; i ++ ) {
  245. array[ i ].call( this, event );
  246. }
  247. event.target = null;
  248. }
  249. }
  250. }
  251. 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' ];
  252. let _seed = 1234567;
  253. const DEG2RAD = Math.PI / 180;
  254. const RAD2DEG = 180 / Math.PI;
  255. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  256. function generateUUID() {
  257. const d0 = Math.random() * 0xffffffff | 0;
  258. const d1 = Math.random() * 0xffffffff | 0;
  259. const d2 = Math.random() * 0xffffffff | 0;
  260. const d3 = Math.random() * 0xffffffff | 0;
  261. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  262. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  263. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  264. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  265. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  266. return uuid.toLowerCase();
  267. }
  268. function clamp$1( value, min, max ) {
  269. return Math.max( min, Math.min( max, value ) );
  270. }
  271. // compute euclidean modulo of m % n
  272. // https://en.wikipedia.org/wiki/Modulo_operation
  273. function euclideanModulo( n, m ) {
  274. return ( ( n % m ) + m ) % m;
  275. }
  276. // Linear mapping from range <a1, a2> to range <b1, b2>
  277. function mapLinear( x, a1, a2, b1, b2 ) {
  278. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  279. }
  280. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  281. function inverseLerp( x, y, value ) {
  282. if ( x !== y ) {
  283. return ( value - x ) / ( y - x );
  284. } else {
  285. return 0;
  286. }
  287. }
  288. // https://en.wikipedia.org/wiki/Linear_interpolation
  289. function lerp( x, y, t ) {
  290. return ( 1 - t ) * x + t * y;
  291. }
  292. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  293. function damp( x, y, lambda, dt ) {
  294. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  295. }
  296. // https://www.desmos.com/calculator/vcsjnyz7x4
  297. function pingpong( x, length = 1 ) {
  298. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  299. }
  300. // http://en.wikipedia.org/wiki/Smoothstep
  301. function smoothstep$1( x, min, max ) {
  302. if ( x <= min ) return 0;
  303. if ( x >= max ) return 1;
  304. x = ( x - min ) / ( max - min );
  305. return x * x * ( 3 - 2 * x );
  306. }
  307. function smootherstep( x, min, max ) {
  308. if ( x <= min ) return 0;
  309. if ( x >= max ) return 1;
  310. x = ( x - min ) / ( max - min );
  311. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  312. }
  313. // Random integer from <low, high> interval
  314. function randInt( low, high ) {
  315. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  316. }
  317. // Random float from <low, high> interval
  318. function randFloat( low, high ) {
  319. return low + Math.random() * ( high - low );
  320. }
  321. // Random float from <-range/2, range/2> interval
  322. function randFloatSpread( range ) {
  323. return range * ( 0.5 - Math.random() );
  324. }
  325. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  326. function seededRandom( s ) {
  327. if ( s !== undefined ) _seed = s;
  328. // Mulberry32 generator
  329. let t = _seed += 0x6D2B79F5;
  330. t = Math.imul( t ^ t >>> 15, t | 1 );
  331. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  332. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  333. }
  334. function degToRad( degrees ) {
  335. return degrees * DEG2RAD;
  336. }
  337. function radToDeg( radians ) {
  338. return radians * RAD2DEG;
  339. }
  340. function isPowerOfTwo( value ) {
  341. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  342. }
  343. function ceilPowerOfTwo( value ) {
  344. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  345. }
  346. function floorPowerOfTwo( value ) {
  347. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  348. }
  349. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  350. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  351. // rotations are applied to the axes in the order specified by 'order'
  352. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  353. // angles are in radians
  354. const cos = Math.cos;
  355. const sin = Math.sin;
  356. const c2 = cos( b / 2 );
  357. const s2 = sin( b / 2 );
  358. const c13 = cos( ( a + c ) / 2 );
  359. const s13 = sin( ( a + c ) / 2 );
  360. const c1_3 = cos( ( a - c ) / 2 );
  361. const s1_3 = sin( ( a - c ) / 2 );
  362. const c3_1 = cos( ( c - a ) / 2 );
  363. const s3_1 = sin( ( c - a ) / 2 );
  364. switch ( order ) {
  365. case 'XYX':
  366. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  367. break;
  368. case 'YZY':
  369. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  370. break;
  371. case 'ZXZ':
  372. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  373. break;
  374. case 'XZX':
  375. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  376. break;
  377. case 'YXY':
  378. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  379. break;
  380. case 'ZYZ':
  381. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  382. break;
  383. default:
  384. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  385. }
  386. }
  387. function denormalize( value, array ) {
  388. switch ( array.constructor ) {
  389. case Float32Array:
  390. return value;
  391. case Uint32Array:
  392. return value / 4294967295.0;
  393. case Uint16Array:
  394. return value / 65535.0;
  395. case Uint8Array:
  396. return value / 255.0;
  397. case Int32Array:
  398. return Math.max( value / 2147483647.0, - 1.0 );
  399. case Int16Array:
  400. return Math.max( value / 32767.0, - 1.0 );
  401. case Int8Array:
  402. return Math.max( value / 127.0, - 1.0 );
  403. default:
  404. throw new Error( 'Invalid component type.' );
  405. }
  406. }
  407. function normalize$1( value, array ) {
  408. switch ( array.constructor ) {
  409. case Float32Array:
  410. return value;
  411. case Uint32Array:
  412. return Math.round( value * 4294967295.0 );
  413. case Uint16Array:
  414. return Math.round( value * 65535.0 );
  415. case Uint8Array:
  416. return Math.round( value * 255.0 );
  417. case Int32Array:
  418. return Math.round( value * 2147483647.0 );
  419. case Int16Array:
  420. return Math.round( value * 32767.0 );
  421. case Int8Array:
  422. return Math.round( value * 127.0 );
  423. default:
  424. throw new Error( 'Invalid component type.' );
  425. }
  426. }
  427. const MathUtils = {
  428. DEG2RAD: DEG2RAD,
  429. RAD2DEG: RAD2DEG,
  430. generateUUID: generateUUID,
  431. clamp: clamp$1,
  432. euclideanModulo: euclideanModulo,
  433. mapLinear: mapLinear,
  434. inverseLerp: inverseLerp,
  435. lerp: lerp,
  436. damp: damp,
  437. pingpong: pingpong,
  438. smoothstep: smoothstep$1,
  439. smootherstep: smootherstep,
  440. randInt: randInt,
  441. randFloat: randFloat,
  442. randFloatSpread: randFloatSpread,
  443. seededRandom: seededRandom,
  444. degToRad: degToRad,
  445. radToDeg: radToDeg,
  446. isPowerOfTwo: isPowerOfTwo,
  447. ceilPowerOfTwo: ceilPowerOfTwo,
  448. floorPowerOfTwo: floorPowerOfTwo,
  449. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  450. normalize: normalize$1,
  451. denormalize: denormalize
  452. };
  453. class Vector2 {
  454. constructor( x = 0, y = 0 ) {
  455. Vector2.prototype.isVector2 = true;
  456. this.x = x;
  457. this.y = y;
  458. }
  459. get width() {
  460. return this.x;
  461. }
  462. set width( value ) {
  463. this.x = value;
  464. }
  465. get height() {
  466. return this.y;
  467. }
  468. set height( value ) {
  469. this.y = value;
  470. }
  471. set( x, y ) {
  472. this.x = x;
  473. this.y = y;
  474. return this;
  475. }
  476. setScalar( scalar ) {
  477. this.x = scalar;
  478. this.y = scalar;
  479. return this;
  480. }
  481. setX( x ) {
  482. this.x = x;
  483. return this;
  484. }
  485. setY( y ) {
  486. this.y = y;
  487. return this;
  488. }
  489. setComponent( index, value ) {
  490. switch ( index ) {
  491. case 0: this.x = value; break;
  492. case 1: this.y = value; break;
  493. default: throw new Error( 'index is out of range: ' + index );
  494. }
  495. return this;
  496. }
  497. getComponent( index ) {
  498. switch ( index ) {
  499. case 0: return this.x;
  500. case 1: return this.y;
  501. default: throw new Error( 'index is out of range: ' + index );
  502. }
  503. }
  504. clone() {
  505. return new this.constructor( this.x, this.y );
  506. }
  507. copy( v ) {
  508. this.x = v.x;
  509. this.y = v.y;
  510. return this;
  511. }
  512. add( v ) {
  513. this.x += v.x;
  514. this.y += v.y;
  515. return this;
  516. }
  517. addScalar( s ) {
  518. this.x += s;
  519. this.y += s;
  520. return this;
  521. }
  522. addVectors( a, b ) {
  523. this.x = a.x + b.x;
  524. this.y = a.y + b.y;
  525. return this;
  526. }
  527. addScaledVector( v, s ) {
  528. this.x += v.x * s;
  529. this.y += v.y * s;
  530. return this;
  531. }
  532. sub( v ) {
  533. this.x -= v.x;
  534. this.y -= v.y;
  535. return this;
  536. }
  537. subScalar( s ) {
  538. this.x -= s;
  539. this.y -= s;
  540. return this;
  541. }
  542. subVectors( a, b ) {
  543. this.x = a.x - b.x;
  544. this.y = a.y - b.y;
  545. return this;
  546. }
  547. multiply( v ) {
  548. this.x *= v.x;
  549. this.y *= v.y;
  550. return this;
  551. }
  552. multiplyScalar( scalar ) {
  553. this.x *= scalar;
  554. this.y *= scalar;
  555. return this;
  556. }
  557. divide( v ) {
  558. this.x /= v.x;
  559. this.y /= v.y;
  560. return this;
  561. }
  562. divideScalar( scalar ) {
  563. return this.multiplyScalar( 1 / scalar );
  564. }
  565. applyMatrix3( m ) {
  566. const x = this.x, y = this.y;
  567. const e = m.elements;
  568. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  569. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  570. return this;
  571. }
  572. min( v ) {
  573. this.x = Math.min( this.x, v.x );
  574. this.y = Math.min( this.y, v.y );
  575. return this;
  576. }
  577. max( v ) {
  578. this.x = Math.max( this.x, v.x );
  579. this.y = Math.max( this.y, v.y );
  580. return this;
  581. }
  582. clamp( min, max ) {
  583. // assumes min < max, componentwise
  584. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  585. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  586. return this;
  587. }
  588. clampScalar( minVal, maxVal ) {
  589. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  590. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  591. return this;
  592. }
  593. clampLength( min, max ) {
  594. const length = this.length();
  595. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  596. }
  597. floor() {
  598. this.x = Math.floor( this.x );
  599. this.y = Math.floor( this.y );
  600. return this;
  601. }
  602. ceil() {
  603. this.x = Math.ceil( this.x );
  604. this.y = Math.ceil( this.y );
  605. return this;
  606. }
  607. round() {
  608. this.x = Math.round( this.x );
  609. this.y = Math.round( this.y );
  610. return this;
  611. }
  612. roundToZero() {
  613. this.x = Math.trunc( this.x );
  614. this.y = Math.trunc( this.y );
  615. return this;
  616. }
  617. negate() {
  618. this.x = - this.x;
  619. this.y = - this.y;
  620. return this;
  621. }
  622. dot( v ) {
  623. return this.x * v.x + this.y * v.y;
  624. }
  625. cross( v ) {
  626. return this.x * v.y - this.y * v.x;
  627. }
  628. lengthSq() {
  629. return this.x * this.x + this.y * this.y;
  630. }
  631. length() {
  632. return Math.sqrt( this.x * this.x + this.y * this.y );
  633. }
  634. manhattanLength() {
  635. return Math.abs( this.x ) + Math.abs( this.y );
  636. }
  637. normalize() {
  638. return this.divideScalar( this.length() || 1 );
  639. }
  640. angle() {
  641. // computes the angle in radians with respect to the positive x-axis
  642. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  643. return angle;
  644. }
  645. angleTo( v ) {
  646. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  647. if ( denominator === 0 ) return Math.PI / 2;
  648. const theta = this.dot( v ) / denominator;
  649. // clamp, to handle numerical problems
  650. return Math.acos( clamp$1( theta, - 1, 1 ) );
  651. }
  652. distanceTo( v ) {
  653. return Math.sqrt( this.distanceToSquared( v ) );
  654. }
  655. distanceToSquared( v ) {
  656. const dx = this.x - v.x, dy = this.y - v.y;
  657. return dx * dx + dy * dy;
  658. }
  659. manhattanDistanceTo( v ) {
  660. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  661. }
  662. setLength( length ) {
  663. return this.normalize().multiplyScalar( length );
  664. }
  665. lerp( v, alpha ) {
  666. this.x += ( v.x - this.x ) * alpha;
  667. this.y += ( v.y - this.y ) * alpha;
  668. return this;
  669. }
  670. lerpVectors( v1, v2, alpha ) {
  671. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  672. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  673. return this;
  674. }
  675. equals( v ) {
  676. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  677. }
  678. fromArray( array, offset = 0 ) {
  679. this.x = array[ offset ];
  680. this.y = array[ offset + 1 ];
  681. return this;
  682. }
  683. toArray( array = [], offset = 0 ) {
  684. array[ offset ] = this.x;
  685. array[ offset + 1 ] = this.y;
  686. return array;
  687. }
  688. fromBufferAttribute( attribute, index ) {
  689. this.x = attribute.getX( index );
  690. this.y = attribute.getY( index );
  691. return this;
  692. }
  693. rotateAround( center, angle ) {
  694. const c = Math.cos( angle ), s = Math.sin( angle );
  695. const x = this.x - center.x;
  696. const y = this.y - center.y;
  697. this.x = x * c - y * s + center.x;
  698. this.y = x * s + y * c + center.y;
  699. return this;
  700. }
  701. random() {
  702. this.x = Math.random();
  703. this.y = Math.random();
  704. return this;
  705. }
  706. *[ Symbol.iterator ]() {
  707. yield this.x;
  708. yield this.y;
  709. }
  710. }
  711. class Matrix3 {
  712. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  713. Matrix3.prototype.isMatrix3 = true;
  714. this.elements = [
  715. 1, 0, 0,
  716. 0, 1, 0,
  717. 0, 0, 1
  718. ];
  719. if ( n11 !== undefined ) {
  720. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  721. }
  722. }
  723. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  724. const te = this.elements;
  725. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  726. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  727. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  728. return this;
  729. }
  730. identity() {
  731. this.set(
  732. 1, 0, 0,
  733. 0, 1, 0,
  734. 0, 0, 1
  735. );
  736. return this;
  737. }
  738. copy( m ) {
  739. const te = this.elements;
  740. const me = m.elements;
  741. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  742. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  743. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  744. return this;
  745. }
  746. extractBasis( xAxis, yAxis, zAxis ) {
  747. xAxis.setFromMatrix3Column( this, 0 );
  748. yAxis.setFromMatrix3Column( this, 1 );
  749. zAxis.setFromMatrix3Column( this, 2 );
  750. return this;
  751. }
  752. setFromMatrix4( m ) {
  753. const me = m.elements;
  754. this.set(
  755. me[ 0 ], me[ 4 ], me[ 8 ],
  756. me[ 1 ], me[ 5 ], me[ 9 ],
  757. me[ 2 ], me[ 6 ], me[ 10 ]
  758. );
  759. return this;
  760. }
  761. multiply( m ) {
  762. return this.multiplyMatrices( this, m );
  763. }
  764. premultiply( m ) {
  765. return this.multiplyMatrices( m, this );
  766. }
  767. multiplyMatrices( a, b ) {
  768. const ae = a.elements;
  769. const be = b.elements;
  770. const te = this.elements;
  771. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  772. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  773. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  774. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  775. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  776. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  777. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  778. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  779. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  780. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  781. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  782. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  783. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  784. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  785. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  786. return this;
  787. }
  788. multiplyScalar( s ) {
  789. const te = this.elements;
  790. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  791. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  792. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  793. return this;
  794. }
  795. determinant() {
  796. const te = this.elements;
  797. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  798. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  799. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  800. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  801. }
  802. invert() {
  803. const te = this.elements,
  804. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  805. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  806. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  807. t11 = n33 * n22 - n32 * n23,
  808. t12 = n32 * n13 - n33 * n12,
  809. t13 = n23 * n12 - n22 * n13,
  810. det = n11 * t11 + n21 * t12 + n31 * t13;
  811. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  812. const detInv = 1 / det;
  813. te[ 0 ] = t11 * detInv;
  814. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  815. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  816. te[ 3 ] = t12 * detInv;
  817. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  818. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  819. te[ 6 ] = t13 * detInv;
  820. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  821. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  822. return this;
  823. }
  824. transpose() {
  825. let tmp;
  826. const m = this.elements;
  827. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  828. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  829. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  830. return this;
  831. }
  832. getNormalMatrix( matrix4 ) {
  833. return this.setFromMatrix4( matrix4 ).invert().transpose();
  834. }
  835. transposeIntoArray( r ) {
  836. const m = this.elements;
  837. r[ 0 ] = m[ 0 ];
  838. r[ 1 ] = m[ 3 ];
  839. r[ 2 ] = m[ 6 ];
  840. r[ 3 ] = m[ 1 ];
  841. r[ 4 ] = m[ 4 ];
  842. r[ 5 ] = m[ 7 ];
  843. r[ 6 ] = m[ 2 ];
  844. r[ 7 ] = m[ 5 ];
  845. r[ 8 ] = m[ 8 ];
  846. return this;
  847. }
  848. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  849. const c = Math.cos( rotation );
  850. const s = Math.sin( rotation );
  851. this.set(
  852. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  853. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  854. 0, 0, 1
  855. );
  856. return this;
  857. }
  858. //
  859. scale( sx, sy ) {
  860. this.premultiply( _m3.makeScale( sx, sy ) );
  861. return this;
  862. }
  863. rotate( theta ) {
  864. this.premultiply( _m3.makeRotation( - theta ) );
  865. return this;
  866. }
  867. translate( tx, ty ) {
  868. this.premultiply( _m3.makeTranslation( tx, ty ) );
  869. return this;
  870. }
  871. // for 2D Transforms
  872. makeTranslation( x, y ) {
  873. if ( x.isVector2 ) {
  874. this.set(
  875. 1, 0, x.x,
  876. 0, 1, x.y,
  877. 0, 0, 1
  878. );
  879. } else {
  880. this.set(
  881. 1, 0, x,
  882. 0, 1, y,
  883. 0, 0, 1
  884. );
  885. }
  886. return this;
  887. }
  888. makeRotation( theta ) {
  889. // counterclockwise
  890. const c = Math.cos( theta );
  891. const s = Math.sin( theta );
  892. this.set(
  893. c, - s, 0,
  894. s, c, 0,
  895. 0, 0, 1
  896. );
  897. return this;
  898. }
  899. makeScale( x, y ) {
  900. this.set(
  901. x, 0, 0,
  902. 0, y, 0,
  903. 0, 0, 1
  904. );
  905. return this;
  906. }
  907. //
  908. equals( matrix ) {
  909. const te = this.elements;
  910. const me = matrix.elements;
  911. for ( let i = 0; i < 9; i ++ ) {
  912. if ( te[ i ] !== me[ i ] ) return false;
  913. }
  914. return true;
  915. }
  916. fromArray( array, offset = 0 ) {
  917. for ( let i = 0; i < 9; i ++ ) {
  918. this.elements[ i ] = array[ i + offset ];
  919. }
  920. return this;
  921. }
  922. toArray( array = [], offset = 0 ) {
  923. const te = this.elements;
  924. array[ offset ] = te[ 0 ];
  925. array[ offset + 1 ] = te[ 1 ];
  926. array[ offset + 2 ] = te[ 2 ];
  927. array[ offset + 3 ] = te[ 3 ];
  928. array[ offset + 4 ] = te[ 4 ];
  929. array[ offset + 5 ] = te[ 5 ];
  930. array[ offset + 6 ] = te[ 6 ];
  931. array[ offset + 7 ] = te[ 7 ];
  932. array[ offset + 8 ] = te[ 8 ];
  933. return array;
  934. }
  935. clone() {
  936. return new this.constructor().fromArray( this.elements );
  937. }
  938. }
  939. const _m3 = /*@__PURE__*/ new Matrix3();
  940. function arrayNeedsUint32$1( array ) {
  941. // assumes larger values usually on last
  942. for ( let i = array.length - 1; i >= 0; -- i ) {
  943. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  944. }
  945. return false;
  946. }
  947. const TYPED_ARRAYS = {
  948. Int8Array: Int8Array,
  949. Uint8Array: Uint8Array,
  950. Uint8ClampedArray: Uint8ClampedArray,
  951. Int16Array: Int16Array,
  952. Uint16Array: Uint16Array,
  953. Int32Array: Int32Array,
  954. Uint32Array: Uint32Array,
  955. Float32Array: Float32Array,
  956. Float64Array: Float64Array
  957. };
  958. function getTypedArray( type, buffer ) {
  959. return new TYPED_ARRAYS[ type ]( buffer );
  960. }
  961. function createElementNS( name ) {
  962. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  963. }
  964. function createCanvasElement() {
  965. const canvas = createElementNS( 'canvas' );
  966. canvas.style.display = 'block';
  967. return canvas;
  968. }
  969. const _cache$2 = {};
  970. function warnOnce( message ) {
  971. if ( message in _cache$2 ) return;
  972. _cache$2[ message ] = true;
  973. console.warn( message );
  974. }
  975. const ColorManagement = {
  976. enabled: true,
  977. workingColorSpace: LinearSRGBColorSpace,
  978. /**
  979. * Implementations of supported color spaces.
  980. *
  981. * Required:
  982. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  983. * - whitePoint: reference white [ x y ]
  984. * - transfer: transfer function (pre-defined)
  985. * - toXYZ: Matrix3 RGB to XYZ transform
  986. * - fromXYZ: Matrix3 XYZ to RGB transform
  987. * - luminanceCoefficients: RGB luminance coefficients
  988. *
  989. * Optional:
  990. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  991. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  992. *
  993. * Reference:
  994. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  995. */
  996. spaces: {},
  997. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  998. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  999. return color;
  1000. }
  1001. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  1002. color.r = SRGBToLinear( color.r );
  1003. color.g = SRGBToLinear( color.g );
  1004. color.b = SRGBToLinear( color.b );
  1005. }
  1006. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  1007. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  1008. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  1009. }
  1010. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  1011. color.r = LinearToSRGB( color.r );
  1012. color.g = LinearToSRGB( color.g );
  1013. color.b = LinearToSRGB( color.b );
  1014. }
  1015. return color;
  1016. },
  1017. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1018. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1019. },
  1020. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1021. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1022. },
  1023. getPrimaries: function ( colorSpace ) {
  1024. return this.spaces[ colorSpace ].primaries;
  1025. },
  1026. getTransfer: function ( colorSpace ) {
  1027. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1028. return this.spaces[ colorSpace ].transfer;
  1029. },
  1030. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  1031. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  1032. },
  1033. define: function ( colorSpaces ) {
  1034. Object.assign( this.spaces, colorSpaces );
  1035. },
  1036. // Internal APIs
  1037. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  1038. return targetMatrix
  1039. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  1040. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  1041. },
  1042. _getDrawingBufferColorSpace: function ( colorSpace ) {
  1043. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  1044. },
  1045. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  1046. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  1047. }
  1048. };
  1049. function SRGBToLinear( c ) {
  1050. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1051. }
  1052. function LinearToSRGB( c ) {
  1053. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1054. }
  1055. /******************************************************************************
  1056. * sRGB definitions
  1057. */
  1058. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  1059. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  1060. const D65 = [ 0.3127, 0.3290 ];
  1061. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  1062. 0.4123908, 0.3575843, 0.1804808,
  1063. 0.2126390, 0.7151687, 0.0721923,
  1064. 0.0193308, 0.1191948, 0.9505322
  1065. );
  1066. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  1067. 3.2409699, - 1.5373832, - 0.4986108,
  1068. - 0.9692436, 1.8759675, 0.0415551,
  1069. 0.0556301, - 0.2039770, 1.0569715
  1070. );
  1071. ColorManagement.define( {
  1072. [ LinearSRGBColorSpace ]: {
  1073. primaries: REC709_PRIMARIES,
  1074. whitePoint: D65,
  1075. transfer: LinearTransfer,
  1076. toXYZ: LINEAR_REC709_TO_XYZ,
  1077. fromXYZ: XYZ_TO_LINEAR_REC709,
  1078. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1079. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  1080. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1081. },
  1082. [ SRGBColorSpace ]: {
  1083. primaries: REC709_PRIMARIES,
  1084. whitePoint: D65,
  1085. transfer: SRGBTransfer,
  1086. toXYZ: LINEAR_REC709_TO_XYZ,
  1087. fromXYZ: XYZ_TO_LINEAR_REC709,
  1088. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1089. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1090. },
  1091. } );
  1092. let _canvas;
  1093. class ImageUtils {
  1094. static getDataURL( image ) {
  1095. if ( /^data:/i.test( image.src ) ) {
  1096. return image.src;
  1097. }
  1098. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1099. return image.src;
  1100. }
  1101. let canvas;
  1102. if ( image instanceof HTMLCanvasElement ) {
  1103. canvas = image;
  1104. } else {
  1105. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1106. _canvas.width = image.width;
  1107. _canvas.height = image.height;
  1108. const context = _canvas.getContext( '2d' );
  1109. if ( image instanceof ImageData ) {
  1110. context.putImageData( image, 0, 0 );
  1111. } else {
  1112. context.drawImage( image, 0, 0, image.width, image.height );
  1113. }
  1114. canvas = _canvas;
  1115. }
  1116. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1117. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1118. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1119. } else {
  1120. return canvas.toDataURL( 'image/png' );
  1121. }
  1122. }
  1123. static sRGBToLinear( image ) {
  1124. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1125. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1126. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1127. const canvas = createElementNS( 'canvas' );
  1128. canvas.width = image.width;
  1129. canvas.height = image.height;
  1130. const context = canvas.getContext( '2d' );
  1131. context.drawImage( image, 0, 0, image.width, image.height );
  1132. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1133. const data = imageData.data;
  1134. for ( let i = 0; i < data.length; i ++ ) {
  1135. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1136. }
  1137. context.putImageData( imageData, 0, 0 );
  1138. return canvas;
  1139. } else if ( image.data ) {
  1140. const data = image.data.slice( 0 );
  1141. for ( let i = 0; i < data.length; i ++ ) {
  1142. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1143. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1144. } else {
  1145. // assuming float
  1146. data[ i ] = SRGBToLinear( data[ i ] );
  1147. }
  1148. }
  1149. return {
  1150. data: data,
  1151. width: image.width,
  1152. height: image.height
  1153. };
  1154. } else {
  1155. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1156. return image;
  1157. }
  1158. }
  1159. }
  1160. let _sourceId = 0;
  1161. class Source {
  1162. constructor( data = null ) {
  1163. this.isSource = true;
  1164. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1165. this.uuid = generateUUID();
  1166. this.data = data;
  1167. this.dataReady = true;
  1168. this.version = 0;
  1169. }
  1170. set needsUpdate( value ) {
  1171. if ( value === true ) this.version ++;
  1172. }
  1173. toJSON( meta ) {
  1174. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1175. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1176. return meta.images[ this.uuid ];
  1177. }
  1178. const output = {
  1179. uuid: this.uuid,
  1180. url: ''
  1181. };
  1182. const data = this.data;
  1183. if ( data !== null ) {
  1184. let url;
  1185. if ( Array.isArray( data ) ) {
  1186. // cube texture
  1187. url = [];
  1188. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1189. if ( data[ i ].isDataTexture ) {
  1190. url.push( serializeImage( data[ i ].image ) );
  1191. } else {
  1192. url.push( serializeImage( data[ i ] ) );
  1193. }
  1194. }
  1195. } else {
  1196. // texture
  1197. url = serializeImage( data );
  1198. }
  1199. output.url = url;
  1200. }
  1201. if ( ! isRootObject ) {
  1202. meta.images[ this.uuid ] = output;
  1203. }
  1204. return output;
  1205. }
  1206. }
  1207. function serializeImage( image ) {
  1208. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1209. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1210. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1211. // default images
  1212. return ImageUtils.getDataURL( image );
  1213. } else {
  1214. if ( image.data ) {
  1215. // images of DataTexture
  1216. return {
  1217. data: Array.from( image.data ),
  1218. width: image.width,
  1219. height: image.height,
  1220. type: image.data.constructor.name
  1221. };
  1222. } else {
  1223. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1224. return {};
  1225. }
  1226. }
  1227. }
  1228. let _textureId = 0;
  1229. class Texture extends EventDispatcher {
  1230. 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 ) {
  1231. super();
  1232. this.isTexture = true;
  1233. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1234. this.uuid = generateUUID();
  1235. this.name = '';
  1236. this.source = new Source( image );
  1237. this.mipmaps = [];
  1238. this.mapping = mapping;
  1239. this.channel = 0;
  1240. this.wrapS = wrapS;
  1241. this.wrapT = wrapT;
  1242. this.magFilter = magFilter;
  1243. this.minFilter = minFilter;
  1244. this.anisotropy = anisotropy;
  1245. this.format = format;
  1246. this.internalFormat = null;
  1247. this.type = type;
  1248. this.offset = new Vector2( 0, 0 );
  1249. this.repeat = new Vector2( 1, 1 );
  1250. this.center = new Vector2( 0, 0 );
  1251. this.rotation = 0;
  1252. this.matrixAutoUpdate = true;
  1253. this.matrix = new Matrix3();
  1254. this.generateMipmaps = true;
  1255. this.premultiplyAlpha = false;
  1256. this.flipY = true;
  1257. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1258. this.colorSpace = colorSpace;
  1259. this.userData = {};
  1260. this.version = 0;
  1261. this.onUpdate = null;
  1262. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1263. this.pmremVersion = 0; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1264. }
  1265. get image() {
  1266. return this.source.data;
  1267. }
  1268. set image( value = null ) {
  1269. this.source.data = value;
  1270. }
  1271. updateMatrix() {
  1272. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1273. }
  1274. clone() {
  1275. return new this.constructor().copy( this );
  1276. }
  1277. copy( source ) {
  1278. this.name = source.name;
  1279. this.source = source.source;
  1280. this.mipmaps = source.mipmaps.slice( 0 );
  1281. this.mapping = source.mapping;
  1282. this.channel = source.channel;
  1283. this.wrapS = source.wrapS;
  1284. this.wrapT = source.wrapT;
  1285. this.magFilter = source.magFilter;
  1286. this.minFilter = source.minFilter;
  1287. this.anisotropy = source.anisotropy;
  1288. this.format = source.format;
  1289. this.internalFormat = source.internalFormat;
  1290. this.type = source.type;
  1291. this.offset.copy( source.offset );
  1292. this.repeat.copy( source.repeat );
  1293. this.center.copy( source.center );
  1294. this.rotation = source.rotation;
  1295. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1296. this.matrix.copy( source.matrix );
  1297. this.generateMipmaps = source.generateMipmaps;
  1298. this.premultiplyAlpha = source.premultiplyAlpha;
  1299. this.flipY = source.flipY;
  1300. this.unpackAlignment = source.unpackAlignment;
  1301. this.colorSpace = source.colorSpace;
  1302. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1303. this.needsUpdate = true;
  1304. return this;
  1305. }
  1306. toJSON( meta ) {
  1307. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1308. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1309. return meta.textures[ this.uuid ];
  1310. }
  1311. const output = {
  1312. metadata: {
  1313. version: 4.6,
  1314. type: 'Texture',
  1315. generator: 'Texture.toJSON'
  1316. },
  1317. uuid: this.uuid,
  1318. name: this.name,
  1319. image: this.source.toJSON( meta ).uuid,
  1320. mapping: this.mapping,
  1321. channel: this.channel,
  1322. repeat: [ this.repeat.x, this.repeat.y ],
  1323. offset: [ this.offset.x, this.offset.y ],
  1324. center: [ this.center.x, this.center.y ],
  1325. rotation: this.rotation,
  1326. wrap: [ this.wrapS, this.wrapT ],
  1327. format: this.format,
  1328. internalFormat: this.internalFormat,
  1329. type: this.type,
  1330. colorSpace: this.colorSpace,
  1331. minFilter: this.minFilter,
  1332. magFilter: this.magFilter,
  1333. anisotropy: this.anisotropy,
  1334. flipY: this.flipY,
  1335. generateMipmaps: this.generateMipmaps,
  1336. premultiplyAlpha: this.premultiplyAlpha,
  1337. unpackAlignment: this.unpackAlignment
  1338. };
  1339. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1340. if ( ! isRootObject ) {
  1341. meta.textures[ this.uuid ] = output;
  1342. }
  1343. return output;
  1344. }
  1345. dispose() {
  1346. this.dispatchEvent( { type: 'dispose' } );
  1347. }
  1348. transformUv( uv ) {
  1349. if ( this.mapping !== UVMapping ) return uv;
  1350. uv.applyMatrix3( this.matrix );
  1351. if ( uv.x < 0 || uv.x > 1 ) {
  1352. switch ( this.wrapS ) {
  1353. case RepeatWrapping:
  1354. uv.x = uv.x - Math.floor( uv.x );
  1355. break;
  1356. case ClampToEdgeWrapping:
  1357. uv.x = uv.x < 0 ? 0 : 1;
  1358. break;
  1359. case MirroredRepeatWrapping:
  1360. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1361. uv.x = Math.ceil( uv.x ) - uv.x;
  1362. } else {
  1363. uv.x = uv.x - Math.floor( uv.x );
  1364. }
  1365. break;
  1366. }
  1367. }
  1368. if ( uv.y < 0 || uv.y > 1 ) {
  1369. switch ( this.wrapT ) {
  1370. case RepeatWrapping:
  1371. uv.y = uv.y - Math.floor( uv.y );
  1372. break;
  1373. case ClampToEdgeWrapping:
  1374. uv.y = uv.y < 0 ? 0 : 1;
  1375. break;
  1376. case MirroredRepeatWrapping:
  1377. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1378. uv.y = Math.ceil( uv.y ) - uv.y;
  1379. } else {
  1380. uv.y = uv.y - Math.floor( uv.y );
  1381. }
  1382. break;
  1383. }
  1384. }
  1385. if ( this.flipY ) {
  1386. uv.y = 1 - uv.y;
  1387. }
  1388. return uv;
  1389. }
  1390. set needsUpdate( value ) {
  1391. if ( value === true ) {
  1392. this.version ++;
  1393. this.source.needsUpdate = true;
  1394. }
  1395. }
  1396. set needsPMREMUpdate( value ) {
  1397. if ( value === true ) {
  1398. this.pmremVersion ++;
  1399. }
  1400. }
  1401. }
  1402. Texture.DEFAULT_IMAGE = null;
  1403. Texture.DEFAULT_MAPPING = UVMapping;
  1404. Texture.DEFAULT_ANISOTROPY = 1;
  1405. class Vector4 {
  1406. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1407. Vector4.prototype.isVector4 = true;
  1408. this.x = x;
  1409. this.y = y;
  1410. this.z = z;
  1411. this.w = w;
  1412. }
  1413. get width() {
  1414. return this.z;
  1415. }
  1416. set width( value ) {
  1417. this.z = value;
  1418. }
  1419. get height() {
  1420. return this.w;
  1421. }
  1422. set height( value ) {
  1423. this.w = value;
  1424. }
  1425. set( x, y, z, w ) {
  1426. this.x = x;
  1427. this.y = y;
  1428. this.z = z;
  1429. this.w = w;
  1430. return this;
  1431. }
  1432. setScalar( scalar ) {
  1433. this.x = scalar;
  1434. this.y = scalar;
  1435. this.z = scalar;
  1436. this.w = scalar;
  1437. return this;
  1438. }
  1439. setX( x ) {
  1440. this.x = x;
  1441. return this;
  1442. }
  1443. setY( y ) {
  1444. this.y = y;
  1445. return this;
  1446. }
  1447. setZ( z ) {
  1448. this.z = z;
  1449. return this;
  1450. }
  1451. setW( w ) {
  1452. this.w = w;
  1453. return this;
  1454. }
  1455. setComponent( index, value ) {
  1456. switch ( index ) {
  1457. case 0: this.x = value; break;
  1458. case 1: this.y = value; break;
  1459. case 2: this.z = value; break;
  1460. case 3: this.w = value; break;
  1461. default: throw new Error( 'index is out of range: ' + index );
  1462. }
  1463. return this;
  1464. }
  1465. getComponent( index ) {
  1466. switch ( index ) {
  1467. case 0: return this.x;
  1468. case 1: return this.y;
  1469. case 2: return this.z;
  1470. case 3: return this.w;
  1471. default: throw new Error( 'index is out of range: ' + index );
  1472. }
  1473. }
  1474. clone() {
  1475. return new this.constructor( this.x, this.y, this.z, this.w );
  1476. }
  1477. copy( v ) {
  1478. this.x = v.x;
  1479. this.y = v.y;
  1480. this.z = v.z;
  1481. this.w = ( v.w !== undefined ) ? v.w : 1;
  1482. return this;
  1483. }
  1484. add( v ) {
  1485. this.x += v.x;
  1486. this.y += v.y;
  1487. this.z += v.z;
  1488. this.w += v.w;
  1489. return this;
  1490. }
  1491. addScalar( s ) {
  1492. this.x += s;
  1493. this.y += s;
  1494. this.z += s;
  1495. this.w += s;
  1496. return this;
  1497. }
  1498. addVectors( a, b ) {
  1499. this.x = a.x + b.x;
  1500. this.y = a.y + b.y;
  1501. this.z = a.z + b.z;
  1502. this.w = a.w + b.w;
  1503. return this;
  1504. }
  1505. addScaledVector( v, s ) {
  1506. this.x += v.x * s;
  1507. this.y += v.y * s;
  1508. this.z += v.z * s;
  1509. this.w += v.w * s;
  1510. return this;
  1511. }
  1512. sub( v ) {
  1513. this.x -= v.x;
  1514. this.y -= v.y;
  1515. this.z -= v.z;
  1516. this.w -= v.w;
  1517. return this;
  1518. }
  1519. subScalar( s ) {
  1520. this.x -= s;
  1521. this.y -= s;
  1522. this.z -= s;
  1523. this.w -= s;
  1524. return this;
  1525. }
  1526. subVectors( a, b ) {
  1527. this.x = a.x - b.x;
  1528. this.y = a.y - b.y;
  1529. this.z = a.z - b.z;
  1530. this.w = a.w - b.w;
  1531. return this;
  1532. }
  1533. multiply( v ) {
  1534. this.x *= v.x;
  1535. this.y *= v.y;
  1536. this.z *= v.z;
  1537. this.w *= v.w;
  1538. return this;
  1539. }
  1540. multiplyScalar( scalar ) {
  1541. this.x *= scalar;
  1542. this.y *= scalar;
  1543. this.z *= scalar;
  1544. this.w *= scalar;
  1545. return this;
  1546. }
  1547. applyMatrix4( m ) {
  1548. const x = this.x, y = this.y, z = this.z, w = this.w;
  1549. const e = m.elements;
  1550. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1551. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1552. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1553. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1554. return this;
  1555. }
  1556. divide( v ) {
  1557. this.x /= v.x;
  1558. this.y /= v.y;
  1559. this.z /= v.z;
  1560. this.w /= v.w;
  1561. return this;
  1562. }
  1563. divideScalar( scalar ) {
  1564. return this.multiplyScalar( 1 / scalar );
  1565. }
  1566. setAxisAngleFromQuaternion( q ) {
  1567. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1568. // q is assumed to be normalized
  1569. this.w = 2 * Math.acos( q.w );
  1570. const s = Math.sqrt( 1 - q.w * q.w );
  1571. if ( s < 0.0001 ) {
  1572. this.x = 1;
  1573. this.y = 0;
  1574. this.z = 0;
  1575. } else {
  1576. this.x = q.x / s;
  1577. this.y = q.y / s;
  1578. this.z = q.z / s;
  1579. }
  1580. return this;
  1581. }
  1582. setAxisAngleFromRotationMatrix( m ) {
  1583. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1584. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1585. let angle, x, y, z; // variables for result
  1586. const epsilon = 0.01, // margin to allow for rounding errors
  1587. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1588. te = m.elements,
  1589. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1590. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1591. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1592. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1593. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1594. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1595. // singularity found
  1596. // first check for identity matrix which must have +1 for all terms
  1597. // in leading diagonal and zero in other terms
  1598. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1599. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1600. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1601. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1602. // this singularity is identity matrix so angle = 0
  1603. this.set( 1, 0, 0, 0 );
  1604. return this; // zero angle, arbitrary axis
  1605. }
  1606. // otherwise this singularity is angle = 180
  1607. angle = Math.PI;
  1608. const xx = ( m11 + 1 ) / 2;
  1609. const yy = ( m22 + 1 ) / 2;
  1610. const zz = ( m33 + 1 ) / 2;
  1611. const xy = ( m12 + m21 ) / 4;
  1612. const xz = ( m13 + m31 ) / 4;
  1613. const yz = ( m23 + m32 ) / 4;
  1614. if ( ( xx > yy ) && ( xx > zz ) ) {
  1615. // m11 is the largest diagonal term
  1616. if ( xx < epsilon ) {
  1617. x = 0;
  1618. y = 0.707106781;
  1619. z = 0.707106781;
  1620. } else {
  1621. x = Math.sqrt( xx );
  1622. y = xy / x;
  1623. z = xz / x;
  1624. }
  1625. } else if ( yy > zz ) {
  1626. // m22 is the largest diagonal term
  1627. if ( yy < epsilon ) {
  1628. x = 0.707106781;
  1629. y = 0;
  1630. z = 0.707106781;
  1631. } else {
  1632. y = Math.sqrt( yy );
  1633. x = xy / y;
  1634. z = yz / y;
  1635. }
  1636. } else {
  1637. // m33 is the largest diagonal term so base result on this
  1638. if ( zz < epsilon ) {
  1639. x = 0.707106781;
  1640. y = 0.707106781;
  1641. z = 0;
  1642. } else {
  1643. z = Math.sqrt( zz );
  1644. x = xz / z;
  1645. y = yz / z;
  1646. }
  1647. }
  1648. this.set( x, y, z, angle );
  1649. return this; // return 180 deg rotation
  1650. }
  1651. // as we have reached here there are no singularities so we can handle normally
  1652. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1653. ( m13 - m31 ) * ( m13 - m31 ) +
  1654. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1655. if ( Math.abs( s ) < 0.001 ) s = 1;
  1656. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1657. // caught by singularity test above, but I've left it in just in case
  1658. this.x = ( m32 - m23 ) / s;
  1659. this.y = ( m13 - m31 ) / s;
  1660. this.z = ( m21 - m12 ) / s;
  1661. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1662. return this;
  1663. }
  1664. setFromMatrixPosition( m ) {
  1665. const e = m.elements;
  1666. this.x = e[ 12 ];
  1667. this.y = e[ 13 ];
  1668. this.z = e[ 14 ];
  1669. this.w = e[ 15 ];
  1670. return this;
  1671. }
  1672. min( v ) {
  1673. this.x = Math.min( this.x, v.x );
  1674. this.y = Math.min( this.y, v.y );
  1675. this.z = Math.min( this.z, v.z );
  1676. this.w = Math.min( this.w, v.w );
  1677. return this;
  1678. }
  1679. max( v ) {
  1680. this.x = Math.max( this.x, v.x );
  1681. this.y = Math.max( this.y, v.y );
  1682. this.z = Math.max( this.z, v.z );
  1683. this.w = Math.max( this.w, v.w );
  1684. return this;
  1685. }
  1686. clamp( min, max ) {
  1687. // assumes min < max, componentwise
  1688. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1689. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1690. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1691. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1692. return this;
  1693. }
  1694. clampScalar( minVal, maxVal ) {
  1695. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1696. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1697. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1698. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1699. return this;
  1700. }
  1701. clampLength( min, max ) {
  1702. const length = this.length();
  1703. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1704. }
  1705. floor() {
  1706. this.x = Math.floor( this.x );
  1707. this.y = Math.floor( this.y );
  1708. this.z = Math.floor( this.z );
  1709. this.w = Math.floor( this.w );
  1710. return this;
  1711. }
  1712. ceil() {
  1713. this.x = Math.ceil( this.x );
  1714. this.y = Math.ceil( this.y );
  1715. this.z = Math.ceil( this.z );
  1716. this.w = Math.ceil( this.w );
  1717. return this;
  1718. }
  1719. round() {
  1720. this.x = Math.round( this.x );
  1721. this.y = Math.round( this.y );
  1722. this.z = Math.round( this.z );
  1723. this.w = Math.round( this.w );
  1724. return this;
  1725. }
  1726. roundToZero() {
  1727. this.x = Math.trunc( this.x );
  1728. this.y = Math.trunc( this.y );
  1729. this.z = Math.trunc( this.z );
  1730. this.w = Math.trunc( this.w );
  1731. return this;
  1732. }
  1733. negate() {
  1734. this.x = - this.x;
  1735. this.y = - this.y;
  1736. this.z = - this.z;
  1737. this.w = - this.w;
  1738. return this;
  1739. }
  1740. dot( v ) {
  1741. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1742. }
  1743. lengthSq() {
  1744. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1745. }
  1746. length() {
  1747. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1748. }
  1749. manhattanLength() {
  1750. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1751. }
  1752. normalize() {
  1753. return this.divideScalar( this.length() || 1 );
  1754. }
  1755. setLength( length ) {
  1756. return this.normalize().multiplyScalar( length );
  1757. }
  1758. lerp( v, alpha ) {
  1759. this.x += ( v.x - this.x ) * alpha;
  1760. this.y += ( v.y - this.y ) * alpha;
  1761. this.z += ( v.z - this.z ) * alpha;
  1762. this.w += ( v.w - this.w ) * alpha;
  1763. return this;
  1764. }
  1765. lerpVectors( v1, v2, alpha ) {
  1766. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1767. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1768. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1769. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1770. return this;
  1771. }
  1772. equals( v ) {
  1773. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1774. }
  1775. fromArray( array, offset = 0 ) {
  1776. this.x = array[ offset ];
  1777. this.y = array[ offset + 1 ];
  1778. this.z = array[ offset + 2 ];
  1779. this.w = array[ offset + 3 ];
  1780. return this;
  1781. }
  1782. toArray( array = [], offset = 0 ) {
  1783. array[ offset ] = this.x;
  1784. array[ offset + 1 ] = this.y;
  1785. array[ offset + 2 ] = this.z;
  1786. array[ offset + 3 ] = this.w;
  1787. return array;
  1788. }
  1789. fromBufferAttribute( attribute, index ) {
  1790. this.x = attribute.getX( index );
  1791. this.y = attribute.getY( index );
  1792. this.z = attribute.getZ( index );
  1793. this.w = attribute.getW( index );
  1794. return this;
  1795. }
  1796. random() {
  1797. this.x = Math.random();
  1798. this.y = Math.random();
  1799. this.z = Math.random();
  1800. this.w = Math.random();
  1801. return this;
  1802. }
  1803. *[ Symbol.iterator ]() {
  1804. yield this.x;
  1805. yield this.y;
  1806. yield this.z;
  1807. yield this.w;
  1808. }
  1809. }
  1810. /*
  1811. In options, we can specify:
  1812. * Texture parameters for an auto-generated target texture
  1813. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1814. */
  1815. class RenderTarget extends EventDispatcher {
  1816. constructor( width = 1, height = 1, options = {} ) {
  1817. super();
  1818. this.isRenderTarget = true;
  1819. this.width = width;
  1820. this.height = height;
  1821. this.depth = 1;
  1822. this.scissor = new Vector4( 0, 0, width, height );
  1823. this.scissorTest = false;
  1824. this.viewport = new Vector4( 0, 0, width, height );
  1825. const image = { width: width, height: height, depth: 1 };
  1826. options = Object.assign( {
  1827. generateMipmaps: false,
  1828. internalFormat: null,
  1829. minFilter: LinearFilter,
  1830. depthBuffer: true,
  1831. stencilBuffer: false,
  1832. resolveDepthBuffer: true,
  1833. resolveStencilBuffer: true,
  1834. depthTexture: null,
  1835. samples: 0,
  1836. count: 1
  1837. }, options );
  1838. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1839. texture.flipY = false;
  1840. texture.generateMipmaps = options.generateMipmaps;
  1841. texture.internalFormat = options.internalFormat;
  1842. this.textures = [];
  1843. const count = options.count;
  1844. for ( let i = 0; i < count; i ++ ) {
  1845. this.textures[ i ] = texture.clone();
  1846. this.textures[ i ].isRenderTargetTexture = true;
  1847. }
  1848. this.depthBuffer = options.depthBuffer;
  1849. this.stencilBuffer = options.stencilBuffer;
  1850. this.resolveDepthBuffer = options.resolveDepthBuffer;
  1851. this.resolveStencilBuffer = options.resolveStencilBuffer;
  1852. this.depthTexture = options.depthTexture;
  1853. this.samples = options.samples;
  1854. }
  1855. get texture() {
  1856. return this.textures[ 0 ];
  1857. }
  1858. set texture( value ) {
  1859. this.textures[ 0 ] = value;
  1860. }
  1861. setSize( width, height, depth = 1 ) {
  1862. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1863. this.width = width;
  1864. this.height = height;
  1865. this.depth = depth;
  1866. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1867. this.textures[ i ].image.width = width;
  1868. this.textures[ i ].image.height = height;
  1869. this.textures[ i ].image.depth = depth;
  1870. }
  1871. this.dispose();
  1872. }
  1873. this.viewport.set( 0, 0, width, height );
  1874. this.scissor.set( 0, 0, width, height );
  1875. }
  1876. clone() {
  1877. return new this.constructor().copy( this );
  1878. }
  1879. copy( source ) {
  1880. this.width = source.width;
  1881. this.height = source.height;
  1882. this.depth = source.depth;
  1883. this.scissor.copy( source.scissor );
  1884. this.scissorTest = source.scissorTest;
  1885. this.viewport.copy( source.viewport );
  1886. this.textures.length = 0;
  1887. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1888. this.textures[ i ] = source.textures[ i ].clone();
  1889. this.textures[ i ].isRenderTargetTexture = true;
  1890. }
  1891. // ensure image object is not shared, see #20328
  1892. const image = Object.assign( {}, source.texture.image );
  1893. this.texture.source = new Source( image );
  1894. this.depthBuffer = source.depthBuffer;
  1895. this.stencilBuffer = source.stencilBuffer;
  1896. this.resolveDepthBuffer = source.resolveDepthBuffer;
  1897. this.resolveStencilBuffer = source.resolveStencilBuffer;
  1898. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1899. this.samples = source.samples;
  1900. return this;
  1901. }
  1902. dispose() {
  1903. this.dispatchEvent( { type: 'dispose' } );
  1904. }
  1905. }
  1906. class WebGLRenderTarget extends RenderTarget {
  1907. constructor( width = 1, height = 1, options = {} ) {
  1908. super( width, height, options );
  1909. this.isWebGLRenderTarget = true;
  1910. }
  1911. }
  1912. class DataArrayTexture extends Texture {
  1913. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1914. super( null );
  1915. this.isDataArrayTexture = true;
  1916. this.image = { data, width, height, depth };
  1917. this.magFilter = NearestFilter;
  1918. this.minFilter = NearestFilter;
  1919. this.wrapR = ClampToEdgeWrapping;
  1920. this.generateMipmaps = false;
  1921. this.flipY = false;
  1922. this.unpackAlignment = 1;
  1923. this.layerUpdates = new Set();
  1924. }
  1925. addLayerUpdate( layerIndex ) {
  1926. this.layerUpdates.add( layerIndex );
  1927. }
  1928. clearLayerUpdates() {
  1929. this.layerUpdates.clear();
  1930. }
  1931. }
  1932. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1933. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1934. super( width, height, options );
  1935. this.isWebGLArrayRenderTarget = true;
  1936. this.depth = depth;
  1937. this.texture = new DataArrayTexture( null, width, height, depth );
  1938. this.texture.isRenderTargetTexture = true;
  1939. }
  1940. }
  1941. class Data3DTexture extends Texture {
  1942. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1943. // We're going to add .setXXX() methods for setting properties later.
  1944. // Users can still set in DataTexture3D directly.
  1945. //
  1946. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1947. // texture.anisotropy = 16;
  1948. //
  1949. // See #14839
  1950. super( null );
  1951. this.isData3DTexture = true;
  1952. this.image = { data, width, height, depth };
  1953. this.magFilter = NearestFilter;
  1954. this.minFilter = NearestFilter;
  1955. this.wrapR = ClampToEdgeWrapping;
  1956. this.generateMipmaps = false;
  1957. this.flipY = false;
  1958. this.unpackAlignment = 1;
  1959. }
  1960. }
  1961. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1962. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1963. super( width, height, options );
  1964. this.isWebGL3DRenderTarget = true;
  1965. this.depth = depth;
  1966. this.texture = new Data3DTexture( null, width, height, depth );
  1967. this.texture.isRenderTargetTexture = true;
  1968. }
  1969. }
  1970. class Quaternion {
  1971. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1972. this.isQuaternion = true;
  1973. this._x = x;
  1974. this._y = y;
  1975. this._z = z;
  1976. this._w = w;
  1977. }
  1978. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1979. // fuzz-free, array-based Quaternion SLERP operation
  1980. let x0 = src0[ srcOffset0 + 0 ],
  1981. y0 = src0[ srcOffset0 + 1 ],
  1982. z0 = src0[ srcOffset0 + 2 ],
  1983. w0 = src0[ srcOffset0 + 3 ];
  1984. const x1 = src1[ srcOffset1 + 0 ],
  1985. y1 = src1[ srcOffset1 + 1 ],
  1986. z1 = src1[ srcOffset1 + 2 ],
  1987. w1 = src1[ srcOffset1 + 3 ];
  1988. if ( t === 0 ) {
  1989. dst[ dstOffset + 0 ] = x0;
  1990. dst[ dstOffset + 1 ] = y0;
  1991. dst[ dstOffset + 2 ] = z0;
  1992. dst[ dstOffset + 3 ] = w0;
  1993. return;
  1994. }
  1995. if ( t === 1 ) {
  1996. dst[ dstOffset + 0 ] = x1;
  1997. dst[ dstOffset + 1 ] = y1;
  1998. dst[ dstOffset + 2 ] = z1;
  1999. dst[ dstOffset + 3 ] = w1;
  2000. return;
  2001. }
  2002. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2003. let s = 1 - t;
  2004. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2005. dir = ( cos >= 0 ? 1 : - 1 ),
  2006. sqrSin = 1 - cos * cos;
  2007. // Skip the Slerp for tiny steps to avoid numeric problems:
  2008. if ( sqrSin > Number.EPSILON ) {
  2009. const sin = Math.sqrt( sqrSin ),
  2010. len = Math.atan2( sin, cos * dir );
  2011. s = Math.sin( s * len ) / sin;
  2012. t = Math.sin( t * len ) / sin;
  2013. }
  2014. const tDir = t * dir;
  2015. x0 = x0 * s + x1 * tDir;
  2016. y0 = y0 * s + y1 * tDir;
  2017. z0 = z0 * s + z1 * tDir;
  2018. w0 = w0 * s + w1 * tDir;
  2019. // Normalize in case we just did a lerp:
  2020. if ( s === 1 - t ) {
  2021. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2022. x0 *= f;
  2023. y0 *= f;
  2024. z0 *= f;
  2025. w0 *= f;
  2026. }
  2027. }
  2028. dst[ dstOffset ] = x0;
  2029. dst[ dstOffset + 1 ] = y0;
  2030. dst[ dstOffset + 2 ] = z0;
  2031. dst[ dstOffset + 3 ] = w0;
  2032. }
  2033. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2034. const x0 = src0[ srcOffset0 ];
  2035. const y0 = src0[ srcOffset0 + 1 ];
  2036. const z0 = src0[ srcOffset0 + 2 ];
  2037. const w0 = src0[ srcOffset0 + 3 ];
  2038. const x1 = src1[ srcOffset1 ];
  2039. const y1 = src1[ srcOffset1 + 1 ];
  2040. const z1 = src1[ srcOffset1 + 2 ];
  2041. const w1 = src1[ srcOffset1 + 3 ];
  2042. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2043. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2044. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2045. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2046. return dst;
  2047. }
  2048. get x() {
  2049. return this._x;
  2050. }
  2051. set x( value ) {
  2052. this._x = value;
  2053. this._onChangeCallback();
  2054. }
  2055. get y() {
  2056. return this._y;
  2057. }
  2058. set y( value ) {
  2059. this._y = value;
  2060. this._onChangeCallback();
  2061. }
  2062. get z() {
  2063. return this._z;
  2064. }
  2065. set z( value ) {
  2066. this._z = value;
  2067. this._onChangeCallback();
  2068. }
  2069. get w() {
  2070. return this._w;
  2071. }
  2072. set w( value ) {
  2073. this._w = value;
  2074. this._onChangeCallback();
  2075. }
  2076. set( x, y, z, w ) {
  2077. this._x = x;
  2078. this._y = y;
  2079. this._z = z;
  2080. this._w = w;
  2081. this._onChangeCallback();
  2082. return this;
  2083. }
  2084. clone() {
  2085. return new this.constructor( this._x, this._y, this._z, this._w );
  2086. }
  2087. copy( quaternion ) {
  2088. this._x = quaternion.x;
  2089. this._y = quaternion.y;
  2090. this._z = quaternion.z;
  2091. this._w = quaternion.w;
  2092. this._onChangeCallback();
  2093. return this;
  2094. }
  2095. setFromEuler( euler, update = true ) {
  2096. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2097. // http://www.mathworks.com/matlabcentral/fileexchange/
  2098. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2099. // content/SpinCalc.m
  2100. const cos = Math.cos;
  2101. const sin = Math.sin;
  2102. const c1 = cos( x / 2 );
  2103. const c2 = cos( y / 2 );
  2104. const c3 = cos( z / 2 );
  2105. const s1 = sin( x / 2 );
  2106. const s2 = sin( y / 2 );
  2107. const s3 = sin( z / 2 );
  2108. switch ( order ) {
  2109. case 'XYZ':
  2110. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2111. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2112. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2113. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2114. break;
  2115. case 'YXZ':
  2116. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2117. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2118. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2119. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2120. break;
  2121. case 'ZXY':
  2122. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2123. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2124. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2125. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2126. break;
  2127. case 'ZYX':
  2128. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2129. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2130. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2131. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2132. break;
  2133. case 'YZX':
  2134. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2135. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2136. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2137. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2138. break;
  2139. case 'XZY':
  2140. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2141. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2142. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2143. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2144. break;
  2145. default:
  2146. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2147. }
  2148. if ( update === true ) this._onChangeCallback();
  2149. return this;
  2150. }
  2151. setFromAxisAngle( axis, angle ) {
  2152. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2153. // assumes axis is normalized
  2154. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2155. this._x = axis.x * s;
  2156. this._y = axis.y * s;
  2157. this._z = axis.z * s;
  2158. this._w = Math.cos( halfAngle );
  2159. this._onChangeCallback();
  2160. return this;
  2161. }
  2162. setFromRotationMatrix( m ) {
  2163. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2164. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2165. const te = m.elements,
  2166. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2167. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2168. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2169. trace = m11 + m22 + m33;
  2170. if ( trace > 0 ) {
  2171. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2172. this._w = 0.25 / s;
  2173. this._x = ( m32 - m23 ) * s;
  2174. this._y = ( m13 - m31 ) * s;
  2175. this._z = ( m21 - m12 ) * s;
  2176. } else if ( m11 > m22 && m11 > m33 ) {
  2177. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2178. this._w = ( m32 - m23 ) / s;
  2179. this._x = 0.25 * s;
  2180. this._y = ( m12 + m21 ) / s;
  2181. this._z = ( m13 + m31 ) / s;
  2182. } else if ( m22 > m33 ) {
  2183. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2184. this._w = ( m13 - m31 ) / s;
  2185. this._x = ( m12 + m21 ) / s;
  2186. this._y = 0.25 * s;
  2187. this._z = ( m23 + m32 ) / s;
  2188. } else {
  2189. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2190. this._w = ( m21 - m12 ) / s;
  2191. this._x = ( m13 + m31 ) / s;
  2192. this._y = ( m23 + m32 ) / s;
  2193. this._z = 0.25 * s;
  2194. }
  2195. this._onChangeCallback();
  2196. return this;
  2197. }
  2198. setFromUnitVectors( vFrom, vTo ) {
  2199. // assumes direction vectors vFrom and vTo are normalized
  2200. let r = vFrom.dot( vTo ) + 1;
  2201. if ( r < Number.EPSILON ) {
  2202. // vFrom and vTo point in opposite directions
  2203. r = 0;
  2204. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2205. this._x = - vFrom.y;
  2206. this._y = vFrom.x;
  2207. this._z = 0;
  2208. this._w = r;
  2209. } else {
  2210. this._x = 0;
  2211. this._y = - vFrom.z;
  2212. this._z = vFrom.y;
  2213. this._w = r;
  2214. }
  2215. } else {
  2216. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2217. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2218. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2219. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2220. this._w = r;
  2221. }
  2222. return this.normalize();
  2223. }
  2224. angleTo( q ) {
  2225. return 2 * Math.acos( Math.abs( clamp$1( this.dot( q ), - 1, 1 ) ) );
  2226. }
  2227. rotateTowards( q, step ) {
  2228. const angle = this.angleTo( q );
  2229. if ( angle === 0 ) return this;
  2230. const t = Math.min( 1, step / angle );
  2231. this.slerp( q, t );
  2232. return this;
  2233. }
  2234. identity() {
  2235. return this.set( 0, 0, 0, 1 );
  2236. }
  2237. invert() {
  2238. // quaternion is assumed to have unit length
  2239. return this.conjugate();
  2240. }
  2241. conjugate() {
  2242. this._x *= - 1;
  2243. this._y *= - 1;
  2244. this._z *= - 1;
  2245. this._onChangeCallback();
  2246. return this;
  2247. }
  2248. dot( v ) {
  2249. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2250. }
  2251. lengthSq() {
  2252. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2253. }
  2254. length() {
  2255. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2256. }
  2257. normalize() {
  2258. let l = this.length();
  2259. if ( l === 0 ) {
  2260. this._x = 0;
  2261. this._y = 0;
  2262. this._z = 0;
  2263. this._w = 1;
  2264. } else {
  2265. l = 1 / l;
  2266. this._x = this._x * l;
  2267. this._y = this._y * l;
  2268. this._z = this._z * l;
  2269. this._w = this._w * l;
  2270. }
  2271. this._onChangeCallback();
  2272. return this;
  2273. }
  2274. multiply( q ) {
  2275. return this.multiplyQuaternions( this, q );
  2276. }
  2277. premultiply( q ) {
  2278. return this.multiplyQuaternions( q, this );
  2279. }
  2280. multiplyQuaternions( a, b ) {
  2281. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2282. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2283. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2284. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2285. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2286. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2287. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2288. this._onChangeCallback();
  2289. return this;
  2290. }
  2291. slerp( qb, t ) {
  2292. if ( t === 0 ) return this;
  2293. if ( t === 1 ) return this.copy( qb );
  2294. const x = this._x, y = this._y, z = this._z, w = this._w;
  2295. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2296. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2297. if ( cosHalfTheta < 0 ) {
  2298. this._w = - qb._w;
  2299. this._x = - qb._x;
  2300. this._y = - qb._y;
  2301. this._z = - qb._z;
  2302. cosHalfTheta = - cosHalfTheta;
  2303. } else {
  2304. this.copy( qb );
  2305. }
  2306. if ( cosHalfTheta >= 1.0 ) {
  2307. this._w = w;
  2308. this._x = x;
  2309. this._y = y;
  2310. this._z = z;
  2311. return this;
  2312. }
  2313. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2314. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2315. const s = 1 - t;
  2316. this._w = s * w + t * this._w;
  2317. this._x = s * x + t * this._x;
  2318. this._y = s * y + t * this._y;
  2319. this._z = s * z + t * this._z;
  2320. this.normalize(); // normalize calls _onChangeCallback()
  2321. return this;
  2322. }
  2323. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2324. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2325. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2326. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2327. this._w = ( w * ratioA + this._w * ratioB );
  2328. this._x = ( x * ratioA + this._x * ratioB );
  2329. this._y = ( y * ratioA + this._y * ratioB );
  2330. this._z = ( z * ratioA + this._z * ratioB );
  2331. this._onChangeCallback();
  2332. return this;
  2333. }
  2334. slerpQuaternions( qa, qb, t ) {
  2335. return this.copy( qa ).slerp( qb, t );
  2336. }
  2337. random() {
  2338. // sets this quaternion to a uniform random unit quaternnion
  2339. // Ken Shoemake
  2340. // Uniform random rotations
  2341. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2342. const theta1 = 2 * Math.PI * Math.random();
  2343. const theta2 = 2 * Math.PI * Math.random();
  2344. const x0 = Math.random();
  2345. const r1 = Math.sqrt( 1 - x0 );
  2346. const r2 = Math.sqrt( x0 );
  2347. return this.set(
  2348. r1 * Math.sin( theta1 ),
  2349. r1 * Math.cos( theta1 ),
  2350. r2 * Math.sin( theta2 ),
  2351. r2 * Math.cos( theta2 ),
  2352. );
  2353. }
  2354. equals( quaternion ) {
  2355. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2356. }
  2357. fromArray( array, offset = 0 ) {
  2358. this._x = array[ offset ];
  2359. this._y = array[ offset + 1 ];
  2360. this._z = array[ offset + 2 ];
  2361. this._w = array[ offset + 3 ];
  2362. this._onChangeCallback();
  2363. return this;
  2364. }
  2365. toArray( array = [], offset = 0 ) {
  2366. array[ offset ] = this._x;
  2367. array[ offset + 1 ] = this._y;
  2368. array[ offset + 2 ] = this._z;
  2369. array[ offset + 3 ] = this._w;
  2370. return array;
  2371. }
  2372. fromBufferAttribute( attribute, index ) {
  2373. this._x = attribute.getX( index );
  2374. this._y = attribute.getY( index );
  2375. this._z = attribute.getZ( index );
  2376. this._w = attribute.getW( index );
  2377. this._onChangeCallback();
  2378. return this;
  2379. }
  2380. toJSON() {
  2381. return this.toArray();
  2382. }
  2383. _onChange( callback ) {
  2384. this._onChangeCallback = callback;
  2385. return this;
  2386. }
  2387. _onChangeCallback() {}
  2388. *[ Symbol.iterator ]() {
  2389. yield this._x;
  2390. yield this._y;
  2391. yield this._z;
  2392. yield this._w;
  2393. }
  2394. }
  2395. class Vector3 {
  2396. constructor( x = 0, y = 0, z = 0 ) {
  2397. Vector3.prototype.isVector3 = true;
  2398. this.x = x;
  2399. this.y = y;
  2400. this.z = z;
  2401. }
  2402. set( x, y, z ) {
  2403. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2404. this.x = x;
  2405. this.y = y;
  2406. this.z = z;
  2407. return this;
  2408. }
  2409. setScalar( scalar ) {
  2410. this.x = scalar;
  2411. this.y = scalar;
  2412. this.z = scalar;
  2413. return this;
  2414. }
  2415. setX( x ) {
  2416. this.x = x;
  2417. return this;
  2418. }
  2419. setY( y ) {
  2420. this.y = y;
  2421. return this;
  2422. }
  2423. setZ( z ) {
  2424. this.z = z;
  2425. return this;
  2426. }
  2427. setComponent( index, value ) {
  2428. switch ( index ) {
  2429. case 0: this.x = value; break;
  2430. case 1: this.y = value; break;
  2431. case 2: this.z = value; break;
  2432. default: throw new Error( 'index is out of range: ' + index );
  2433. }
  2434. return this;
  2435. }
  2436. getComponent( index ) {
  2437. switch ( index ) {
  2438. case 0: return this.x;
  2439. case 1: return this.y;
  2440. case 2: return this.z;
  2441. default: throw new Error( 'index is out of range: ' + index );
  2442. }
  2443. }
  2444. clone() {
  2445. return new this.constructor( this.x, this.y, this.z );
  2446. }
  2447. copy( v ) {
  2448. this.x = v.x;
  2449. this.y = v.y;
  2450. this.z = v.z;
  2451. return this;
  2452. }
  2453. add( v ) {
  2454. this.x += v.x;
  2455. this.y += v.y;
  2456. this.z += v.z;
  2457. return this;
  2458. }
  2459. addScalar( s ) {
  2460. this.x += s;
  2461. this.y += s;
  2462. this.z += s;
  2463. return this;
  2464. }
  2465. addVectors( a, b ) {
  2466. this.x = a.x + b.x;
  2467. this.y = a.y + b.y;
  2468. this.z = a.z + b.z;
  2469. return this;
  2470. }
  2471. addScaledVector( v, s ) {
  2472. this.x += v.x * s;
  2473. this.y += v.y * s;
  2474. this.z += v.z * s;
  2475. return this;
  2476. }
  2477. sub( v ) {
  2478. this.x -= v.x;
  2479. this.y -= v.y;
  2480. this.z -= v.z;
  2481. return this;
  2482. }
  2483. subScalar( s ) {
  2484. this.x -= s;
  2485. this.y -= s;
  2486. this.z -= s;
  2487. return this;
  2488. }
  2489. subVectors( a, b ) {
  2490. this.x = a.x - b.x;
  2491. this.y = a.y - b.y;
  2492. this.z = a.z - b.z;
  2493. return this;
  2494. }
  2495. multiply( v ) {
  2496. this.x *= v.x;
  2497. this.y *= v.y;
  2498. this.z *= v.z;
  2499. return this;
  2500. }
  2501. multiplyScalar( scalar ) {
  2502. this.x *= scalar;
  2503. this.y *= scalar;
  2504. this.z *= scalar;
  2505. return this;
  2506. }
  2507. multiplyVectors( a, b ) {
  2508. this.x = a.x * b.x;
  2509. this.y = a.y * b.y;
  2510. this.z = a.z * b.z;
  2511. return this;
  2512. }
  2513. applyEuler( euler ) {
  2514. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2515. }
  2516. applyAxisAngle( axis, angle ) {
  2517. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2518. }
  2519. applyMatrix3( m ) {
  2520. const x = this.x, y = this.y, z = this.z;
  2521. const e = m.elements;
  2522. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2523. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2524. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2525. return this;
  2526. }
  2527. applyNormalMatrix( m ) {
  2528. return this.applyMatrix3( m ).normalize();
  2529. }
  2530. applyMatrix4( m ) {
  2531. const x = this.x, y = this.y, z = this.z;
  2532. const e = m.elements;
  2533. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2534. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2535. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2536. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2537. return this;
  2538. }
  2539. applyQuaternion( q ) {
  2540. // quaternion q is assumed to have unit length
  2541. const vx = this.x, vy = this.y, vz = this.z;
  2542. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2543. // t = 2 * cross( q.xyz, v );
  2544. const tx = 2 * ( qy * vz - qz * vy );
  2545. const ty = 2 * ( qz * vx - qx * vz );
  2546. const tz = 2 * ( qx * vy - qy * vx );
  2547. // v + q.w * t + cross( q.xyz, t );
  2548. this.x = vx + qw * tx + qy * tz - qz * ty;
  2549. this.y = vy + qw * ty + qz * tx - qx * tz;
  2550. this.z = vz + qw * tz + qx * ty - qy * tx;
  2551. return this;
  2552. }
  2553. project( camera ) {
  2554. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2555. }
  2556. unproject( camera ) {
  2557. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2558. }
  2559. transformDirection( m ) {
  2560. // input: THREE.Matrix4 affine matrix
  2561. // vector interpreted as a direction
  2562. const x = this.x, y = this.y, z = this.z;
  2563. const e = m.elements;
  2564. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2565. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2566. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2567. return this.normalize();
  2568. }
  2569. divide( v ) {
  2570. this.x /= v.x;
  2571. this.y /= v.y;
  2572. this.z /= v.z;
  2573. return this;
  2574. }
  2575. divideScalar( scalar ) {
  2576. return this.multiplyScalar( 1 / scalar );
  2577. }
  2578. min( v ) {
  2579. this.x = Math.min( this.x, v.x );
  2580. this.y = Math.min( this.y, v.y );
  2581. this.z = Math.min( this.z, v.z );
  2582. return this;
  2583. }
  2584. max( v ) {
  2585. this.x = Math.max( this.x, v.x );
  2586. this.y = Math.max( this.y, v.y );
  2587. this.z = Math.max( this.z, v.z );
  2588. return this;
  2589. }
  2590. clamp( min, max ) {
  2591. // assumes min < max, componentwise
  2592. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2593. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2594. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2595. return this;
  2596. }
  2597. clampScalar( minVal, maxVal ) {
  2598. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2599. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2600. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2601. return this;
  2602. }
  2603. clampLength( min, max ) {
  2604. const length = this.length();
  2605. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2606. }
  2607. floor() {
  2608. this.x = Math.floor( this.x );
  2609. this.y = Math.floor( this.y );
  2610. this.z = Math.floor( this.z );
  2611. return this;
  2612. }
  2613. ceil() {
  2614. this.x = Math.ceil( this.x );
  2615. this.y = Math.ceil( this.y );
  2616. this.z = Math.ceil( this.z );
  2617. return this;
  2618. }
  2619. round() {
  2620. this.x = Math.round( this.x );
  2621. this.y = Math.round( this.y );
  2622. this.z = Math.round( this.z );
  2623. return this;
  2624. }
  2625. roundToZero() {
  2626. this.x = Math.trunc( this.x );
  2627. this.y = Math.trunc( this.y );
  2628. this.z = Math.trunc( this.z );
  2629. return this;
  2630. }
  2631. negate() {
  2632. this.x = - this.x;
  2633. this.y = - this.y;
  2634. this.z = - this.z;
  2635. return this;
  2636. }
  2637. dot( v ) {
  2638. return this.x * v.x + this.y * v.y + this.z * v.z;
  2639. }
  2640. // TODO lengthSquared?
  2641. lengthSq() {
  2642. return this.x * this.x + this.y * this.y + this.z * this.z;
  2643. }
  2644. length() {
  2645. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2646. }
  2647. manhattanLength() {
  2648. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2649. }
  2650. normalize() {
  2651. return this.divideScalar( this.length() || 1 );
  2652. }
  2653. setLength( length ) {
  2654. return this.normalize().multiplyScalar( length );
  2655. }
  2656. lerp( v, alpha ) {
  2657. this.x += ( v.x - this.x ) * alpha;
  2658. this.y += ( v.y - this.y ) * alpha;
  2659. this.z += ( v.z - this.z ) * alpha;
  2660. return this;
  2661. }
  2662. lerpVectors( v1, v2, alpha ) {
  2663. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2664. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2665. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2666. return this;
  2667. }
  2668. cross( v ) {
  2669. return this.crossVectors( this, v );
  2670. }
  2671. crossVectors( a, b ) {
  2672. const ax = a.x, ay = a.y, az = a.z;
  2673. const bx = b.x, by = b.y, bz = b.z;
  2674. this.x = ay * bz - az * by;
  2675. this.y = az * bx - ax * bz;
  2676. this.z = ax * by - ay * bx;
  2677. return this;
  2678. }
  2679. projectOnVector( v ) {
  2680. const denominator = v.lengthSq();
  2681. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2682. const scalar = v.dot( this ) / denominator;
  2683. return this.copy( v ).multiplyScalar( scalar );
  2684. }
  2685. projectOnPlane( planeNormal ) {
  2686. _vector$c.copy( this ).projectOnVector( planeNormal );
  2687. return this.sub( _vector$c );
  2688. }
  2689. reflect( normal ) {
  2690. // reflect incident vector off plane orthogonal to normal
  2691. // normal is assumed to have unit length
  2692. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2693. }
  2694. angleTo( v ) {
  2695. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2696. if ( denominator === 0 ) return Math.PI / 2;
  2697. const theta = this.dot( v ) / denominator;
  2698. // clamp, to handle numerical problems
  2699. return Math.acos( clamp$1( theta, - 1, 1 ) );
  2700. }
  2701. distanceTo( v ) {
  2702. return Math.sqrt( this.distanceToSquared( v ) );
  2703. }
  2704. distanceToSquared( v ) {
  2705. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2706. return dx * dx + dy * dy + dz * dz;
  2707. }
  2708. manhattanDistanceTo( v ) {
  2709. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2710. }
  2711. setFromSpherical( s ) {
  2712. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2713. }
  2714. setFromSphericalCoords( radius, phi, theta ) {
  2715. const sinPhiRadius = Math.sin( phi ) * radius;
  2716. this.x = sinPhiRadius * Math.sin( theta );
  2717. this.y = Math.cos( phi ) * radius;
  2718. this.z = sinPhiRadius * Math.cos( theta );
  2719. return this;
  2720. }
  2721. setFromCylindrical( c ) {
  2722. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2723. }
  2724. setFromCylindricalCoords( radius, theta, y ) {
  2725. this.x = radius * Math.sin( theta );
  2726. this.y = y;
  2727. this.z = radius * Math.cos( theta );
  2728. return this;
  2729. }
  2730. setFromMatrixPosition( m ) {
  2731. const e = m.elements;
  2732. this.x = e[ 12 ];
  2733. this.y = e[ 13 ];
  2734. this.z = e[ 14 ];
  2735. return this;
  2736. }
  2737. setFromMatrixScale( m ) {
  2738. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2739. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2740. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2741. this.x = sx;
  2742. this.y = sy;
  2743. this.z = sz;
  2744. return this;
  2745. }
  2746. setFromMatrixColumn( m, index ) {
  2747. return this.fromArray( m.elements, index * 4 );
  2748. }
  2749. setFromMatrix3Column( m, index ) {
  2750. return this.fromArray( m.elements, index * 3 );
  2751. }
  2752. setFromEuler( e ) {
  2753. this.x = e._x;
  2754. this.y = e._y;
  2755. this.z = e._z;
  2756. return this;
  2757. }
  2758. setFromColor( c ) {
  2759. this.x = c.r;
  2760. this.y = c.g;
  2761. this.z = c.b;
  2762. return this;
  2763. }
  2764. equals( v ) {
  2765. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2766. }
  2767. fromArray( array, offset = 0 ) {
  2768. this.x = array[ offset ];
  2769. this.y = array[ offset + 1 ];
  2770. this.z = array[ offset + 2 ];
  2771. return this;
  2772. }
  2773. toArray( array = [], offset = 0 ) {
  2774. array[ offset ] = this.x;
  2775. array[ offset + 1 ] = this.y;
  2776. array[ offset + 2 ] = this.z;
  2777. return array;
  2778. }
  2779. fromBufferAttribute( attribute, index ) {
  2780. this.x = attribute.getX( index );
  2781. this.y = attribute.getY( index );
  2782. this.z = attribute.getZ( index );
  2783. return this;
  2784. }
  2785. random() {
  2786. this.x = Math.random();
  2787. this.y = Math.random();
  2788. this.z = Math.random();
  2789. return this;
  2790. }
  2791. randomDirection() {
  2792. // https://mathworld.wolfram.com/SpherePointPicking.html
  2793. const theta = Math.random() * Math.PI * 2;
  2794. const u = Math.random() * 2 - 1;
  2795. const c = Math.sqrt( 1 - u * u );
  2796. this.x = c * Math.cos( theta );
  2797. this.y = u;
  2798. this.z = c * Math.sin( theta );
  2799. return this;
  2800. }
  2801. *[ Symbol.iterator ]() {
  2802. yield this.x;
  2803. yield this.y;
  2804. yield this.z;
  2805. }
  2806. }
  2807. const _vector$c = /*@__PURE__*/ new Vector3();
  2808. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2809. class Box3 {
  2810. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2811. this.isBox3 = true;
  2812. this.min = min;
  2813. this.max = max;
  2814. }
  2815. set( min, max ) {
  2816. this.min.copy( min );
  2817. this.max.copy( max );
  2818. return this;
  2819. }
  2820. setFromArray( array ) {
  2821. this.makeEmpty();
  2822. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2823. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2824. }
  2825. return this;
  2826. }
  2827. setFromBufferAttribute( attribute ) {
  2828. this.makeEmpty();
  2829. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2830. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2831. }
  2832. return this;
  2833. }
  2834. setFromPoints( points ) {
  2835. this.makeEmpty();
  2836. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2837. this.expandByPoint( points[ i ] );
  2838. }
  2839. return this;
  2840. }
  2841. setFromCenterAndSize( center, size ) {
  2842. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2843. this.min.copy( center ).sub( halfSize );
  2844. this.max.copy( center ).add( halfSize );
  2845. return this;
  2846. }
  2847. setFromObject( object, precise = false ) {
  2848. this.makeEmpty();
  2849. return this.expandByObject( object, precise );
  2850. }
  2851. clone() {
  2852. return new this.constructor().copy( this );
  2853. }
  2854. copy( box ) {
  2855. this.min.copy( box.min );
  2856. this.max.copy( box.max );
  2857. return this;
  2858. }
  2859. makeEmpty() {
  2860. this.min.x = this.min.y = this.min.z = + Infinity;
  2861. this.max.x = this.max.y = this.max.z = - Infinity;
  2862. return this;
  2863. }
  2864. isEmpty() {
  2865. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2866. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2867. }
  2868. getCenter( target ) {
  2869. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2870. }
  2871. getSize( target ) {
  2872. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2873. }
  2874. expandByPoint( point ) {
  2875. this.min.min( point );
  2876. this.max.max( point );
  2877. return this;
  2878. }
  2879. expandByVector( vector ) {
  2880. this.min.sub( vector );
  2881. this.max.add( vector );
  2882. return this;
  2883. }
  2884. expandByScalar( scalar ) {
  2885. this.min.addScalar( - scalar );
  2886. this.max.addScalar( scalar );
  2887. return this;
  2888. }
  2889. expandByObject( object, precise = false ) {
  2890. // Computes the world-axis-aligned bounding box of an object (including its children),
  2891. // accounting for both the object's, and children's, world transforms
  2892. object.updateWorldMatrix( false, false );
  2893. const geometry = object.geometry;
  2894. if ( geometry !== undefined ) {
  2895. const positionAttribute = geometry.getAttribute( 'position' );
  2896. // precise AABB computation based on vertex data requires at least a position attribute.
  2897. // instancing isn't supported so far and uses the normal (conservative) code path.
  2898. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2899. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2900. if ( object.isMesh === true ) {
  2901. object.getVertexPosition( i, _vector$b );
  2902. } else {
  2903. _vector$b.fromBufferAttribute( positionAttribute, i );
  2904. }
  2905. _vector$b.applyMatrix4( object.matrixWorld );
  2906. this.expandByPoint( _vector$b );
  2907. }
  2908. } else {
  2909. if ( object.boundingBox !== undefined ) {
  2910. // object-level bounding box
  2911. if ( object.boundingBox === null ) {
  2912. object.computeBoundingBox();
  2913. }
  2914. _box$4.copy( object.boundingBox );
  2915. } else {
  2916. // geometry-level bounding box
  2917. if ( geometry.boundingBox === null ) {
  2918. geometry.computeBoundingBox();
  2919. }
  2920. _box$4.copy( geometry.boundingBox );
  2921. }
  2922. _box$4.applyMatrix4( object.matrixWorld );
  2923. this.union( _box$4 );
  2924. }
  2925. }
  2926. const children = object.children;
  2927. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2928. this.expandByObject( children[ i ], precise );
  2929. }
  2930. return this;
  2931. }
  2932. containsPoint( point ) {
  2933. return point.x >= this.min.x && point.x <= this.max.x &&
  2934. point.y >= this.min.y && point.y <= this.max.y &&
  2935. point.z >= this.min.z && point.z <= this.max.z;
  2936. }
  2937. containsBox( box ) {
  2938. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2939. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2940. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2941. }
  2942. getParameter( point, target ) {
  2943. // This can potentially have a divide by zero if the box
  2944. // has a size dimension of 0.
  2945. return target.set(
  2946. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2947. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2948. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2949. );
  2950. }
  2951. intersectsBox( box ) {
  2952. // using 6 splitting planes to rule out intersections.
  2953. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  2954. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  2955. box.max.z >= this.min.z && box.min.z <= this.max.z;
  2956. }
  2957. intersectsSphere( sphere ) {
  2958. // Find the point on the AABB closest to the sphere center.
  2959. this.clampPoint( sphere.center, _vector$b );
  2960. // If that point is inside the sphere, the AABB and sphere intersect.
  2961. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2962. }
  2963. intersectsPlane( plane ) {
  2964. // We compute the minimum and maximum dot product values. If those values
  2965. // are on the same side (back or front) of the plane, then there is no intersection.
  2966. let min, max;
  2967. if ( plane.normal.x > 0 ) {
  2968. min = plane.normal.x * this.min.x;
  2969. max = plane.normal.x * this.max.x;
  2970. } else {
  2971. min = plane.normal.x * this.max.x;
  2972. max = plane.normal.x * this.min.x;
  2973. }
  2974. if ( plane.normal.y > 0 ) {
  2975. min += plane.normal.y * this.min.y;
  2976. max += plane.normal.y * this.max.y;
  2977. } else {
  2978. min += plane.normal.y * this.max.y;
  2979. max += plane.normal.y * this.min.y;
  2980. }
  2981. if ( plane.normal.z > 0 ) {
  2982. min += plane.normal.z * this.min.z;
  2983. max += plane.normal.z * this.max.z;
  2984. } else {
  2985. min += plane.normal.z * this.max.z;
  2986. max += plane.normal.z * this.min.z;
  2987. }
  2988. return ( min <= - plane.constant && max >= - plane.constant );
  2989. }
  2990. intersectsTriangle( triangle ) {
  2991. if ( this.isEmpty() ) {
  2992. return false;
  2993. }
  2994. // compute box center and extents
  2995. this.getCenter( _center );
  2996. _extents.subVectors( this.max, _center );
  2997. // translate triangle to aabb origin
  2998. _v0$2.subVectors( triangle.a, _center );
  2999. _v1$7.subVectors( triangle.b, _center );
  3000. _v2$4.subVectors( triangle.c, _center );
  3001. // compute edge vectors for triangle
  3002. _f0.subVectors( _v1$7, _v0$2 );
  3003. _f1.subVectors( _v2$4, _v1$7 );
  3004. _f2.subVectors( _v0$2, _v2$4 );
  3005. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3006. // 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
  3007. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3008. let axes = [
  3009. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3010. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3011. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3012. ];
  3013. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3014. return false;
  3015. }
  3016. // test 3 face normals from the aabb
  3017. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3018. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3019. return false;
  3020. }
  3021. // finally testing the face normal of the triangle
  3022. // use already existing triangle edge vectors here
  3023. _triangleNormal.crossVectors( _f0, _f1 );
  3024. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3025. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  3026. }
  3027. clampPoint( point, target ) {
  3028. return target.copy( point ).clamp( this.min, this.max );
  3029. }
  3030. distanceToPoint( point ) {
  3031. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3032. }
  3033. getBoundingSphere( target ) {
  3034. if ( this.isEmpty() ) {
  3035. target.makeEmpty();
  3036. } else {
  3037. this.getCenter( target.center );
  3038. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3039. }
  3040. return target;
  3041. }
  3042. intersect( box ) {
  3043. this.min.max( box.min );
  3044. this.max.min( box.max );
  3045. // 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.
  3046. if ( this.isEmpty() ) this.makeEmpty();
  3047. return this;
  3048. }
  3049. union( box ) {
  3050. this.min.min( box.min );
  3051. this.max.max( box.max );
  3052. return this;
  3053. }
  3054. applyMatrix4( matrix ) {
  3055. // transform of empty box is an empty box.
  3056. if ( this.isEmpty() ) return this;
  3057. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3058. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3059. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3060. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3061. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3062. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3063. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3064. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3065. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3066. this.setFromPoints( _points );
  3067. return this;
  3068. }
  3069. translate( offset ) {
  3070. this.min.add( offset );
  3071. this.max.add( offset );
  3072. return this;
  3073. }
  3074. equals( box ) {
  3075. return box.min.equals( this.min ) && box.max.equals( this.max );
  3076. }
  3077. }
  3078. const _points = [
  3079. /*@__PURE__*/ new Vector3(),
  3080. /*@__PURE__*/ new Vector3(),
  3081. /*@__PURE__*/ new Vector3(),
  3082. /*@__PURE__*/ new Vector3(),
  3083. /*@__PURE__*/ new Vector3(),
  3084. /*@__PURE__*/ new Vector3(),
  3085. /*@__PURE__*/ new Vector3(),
  3086. /*@__PURE__*/ new Vector3()
  3087. ];
  3088. const _vector$b = /*@__PURE__*/ new Vector3();
  3089. const _box$4 = /*@__PURE__*/ new Box3();
  3090. // triangle centered vertices
  3091. const _v0$2 = /*@__PURE__*/ new Vector3();
  3092. const _v1$7 = /*@__PURE__*/ new Vector3();
  3093. const _v2$4 = /*@__PURE__*/ new Vector3();
  3094. // triangle edge vectors
  3095. const _f0 = /*@__PURE__*/ new Vector3();
  3096. const _f1 = /*@__PURE__*/ new Vector3();
  3097. const _f2 = /*@__PURE__*/ new Vector3();
  3098. const _center = /*@__PURE__*/ new Vector3();
  3099. const _extents = /*@__PURE__*/ new Vector3();
  3100. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3101. const _testAxis = /*@__PURE__*/ new Vector3();
  3102. function satForAxes( axes, v0, v1, v2, extents ) {
  3103. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3104. _testAxis.fromArray( axes, i );
  3105. // project the aabb onto the separating axis
  3106. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3107. // project all 3 vertices of the triangle onto the separating axis
  3108. const p0 = v0.dot( _testAxis );
  3109. const p1 = v1.dot( _testAxis );
  3110. const p2 = v2.dot( _testAxis );
  3111. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3112. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3113. // points of the projected triangle are outside the projected half-length of the aabb
  3114. // the axis is separating and we can exit
  3115. return false;
  3116. }
  3117. }
  3118. return true;
  3119. }
  3120. const _box$3 = /*@__PURE__*/ new Box3();
  3121. const _v1$6 = /*@__PURE__*/ new Vector3();
  3122. const _v2$3 = /*@__PURE__*/ new Vector3();
  3123. class Sphere {
  3124. constructor( center = new Vector3(), radius = - 1 ) {
  3125. this.isSphere = true;
  3126. this.center = center;
  3127. this.radius = radius;
  3128. }
  3129. set( center, radius ) {
  3130. this.center.copy( center );
  3131. this.radius = radius;
  3132. return this;
  3133. }
  3134. setFromPoints( points, optionalCenter ) {
  3135. const center = this.center;
  3136. if ( optionalCenter !== undefined ) {
  3137. center.copy( optionalCenter );
  3138. } else {
  3139. _box$3.setFromPoints( points ).getCenter( center );
  3140. }
  3141. let maxRadiusSq = 0;
  3142. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3143. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3144. }
  3145. this.radius = Math.sqrt( maxRadiusSq );
  3146. return this;
  3147. }
  3148. copy( sphere ) {
  3149. this.center.copy( sphere.center );
  3150. this.radius = sphere.radius;
  3151. return this;
  3152. }
  3153. isEmpty() {
  3154. return ( this.radius < 0 );
  3155. }
  3156. makeEmpty() {
  3157. this.center.set( 0, 0, 0 );
  3158. this.radius = - 1;
  3159. return this;
  3160. }
  3161. containsPoint( point ) {
  3162. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3163. }
  3164. distanceToPoint( point ) {
  3165. return ( point.distanceTo( this.center ) - this.radius );
  3166. }
  3167. intersectsSphere( sphere ) {
  3168. const radiusSum = this.radius + sphere.radius;
  3169. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3170. }
  3171. intersectsBox( box ) {
  3172. return box.intersectsSphere( this );
  3173. }
  3174. intersectsPlane( plane ) {
  3175. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3176. }
  3177. clampPoint( point, target ) {
  3178. const deltaLengthSq = this.center.distanceToSquared( point );
  3179. target.copy( point );
  3180. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3181. target.sub( this.center ).normalize();
  3182. target.multiplyScalar( this.radius ).add( this.center );
  3183. }
  3184. return target;
  3185. }
  3186. getBoundingBox( target ) {
  3187. if ( this.isEmpty() ) {
  3188. // Empty sphere produces empty bounding box
  3189. target.makeEmpty();
  3190. return target;
  3191. }
  3192. target.set( this.center, this.center );
  3193. target.expandByScalar( this.radius );
  3194. return target;
  3195. }
  3196. applyMatrix4( matrix ) {
  3197. this.center.applyMatrix4( matrix );
  3198. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3199. return this;
  3200. }
  3201. translate( offset ) {
  3202. this.center.add( offset );
  3203. return this;
  3204. }
  3205. expandByPoint( point ) {
  3206. if ( this.isEmpty() ) {
  3207. this.center.copy( point );
  3208. this.radius = 0;
  3209. return this;
  3210. }
  3211. _v1$6.subVectors( point, this.center );
  3212. const lengthSq = _v1$6.lengthSq();
  3213. if ( lengthSq > ( this.radius * this.radius ) ) {
  3214. // calculate the minimal sphere
  3215. const length = Math.sqrt( lengthSq );
  3216. const delta = ( length - this.radius ) * 0.5;
  3217. this.center.addScaledVector( _v1$6, delta / length );
  3218. this.radius += delta;
  3219. }
  3220. return this;
  3221. }
  3222. union( sphere ) {
  3223. if ( sphere.isEmpty() ) {
  3224. return this;
  3225. }
  3226. if ( this.isEmpty() ) {
  3227. this.copy( sphere );
  3228. return this;
  3229. }
  3230. if ( this.center.equals( sphere.center ) === true ) {
  3231. this.radius = Math.max( this.radius, sphere.radius );
  3232. } else {
  3233. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3234. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3235. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3236. }
  3237. return this;
  3238. }
  3239. equals( sphere ) {
  3240. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3241. }
  3242. clone() {
  3243. return new this.constructor().copy( this );
  3244. }
  3245. }
  3246. const _vector$a = /*@__PURE__*/ new Vector3();
  3247. const _segCenter = /*@__PURE__*/ new Vector3();
  3248. const _segDir = /*@__PURE__*/ new Vector3();
  3249. const _diff = /*@__PURE__*/ new Vector3();
  3250. const _edge1 = /*@__PURE__*/ new Vector3();
  3251. const _edge2 = /*@__PURE__*/ new Vector3();
  3252. const _normal$2 = /*@__PURE__*/ new Vector3();
  3253. class Ray {
  3254. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3255. this.origin = origin;
  3256. this.direction = direction;
  3257. }
  3258. set( origin, direction ) {
  3259. this.origin.copy( origin );
  3260. this.direction.copy( direction );
  3261. return this;
  3262. }
  3263. copy( ray ) {
  3264. this.origin.copy( ray.origin );
  3265. this.direction.copy( ray.direction );
  3266. return this;
  3267. }
  3268. at( t, target ) {
  3269. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3270. }
  3271. lookAt( v ) {
  3272. this.direction.copy( v ).sub( this.origin ).normalize();
  3273. return this;
  3274. }
  3275. recast( t ) {
  3276. this.origin.copy( this.at( t, _vector$a ) );
  3277. return this;
  3278. }
  3279. closestPointToPoint( point, target ) {
  3280. target.subVectors( point, this.origin );
  3281. const directionDistance = target.dot( this.direction );
  3282. if ( directionDistance < 0 ) {
  3283. return target.copy( this.origin );
  3284. }
  3285. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3286. }
  3287. distanceToPoint( point ) {
  3288. return Math.sqrt( this.distanceSqToPoint( point ) );
  3289. }
  3290. distanceSqToPoint( point ) {
  3291. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3292. // point behind the ray
  3293. if ( directionDistance < 0 ) {
  3294. return this.origin.distanceToSquared( point );
  3295. }
  3296. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3297. return _vector$a.distanceToSquared( point );
  3298. }
  3299. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3300. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3301. // It returns the min distance between the ray and the segment
  3302. // defined by v0 and v1
  3303. // It can also set two optional targets :
  3304. // - The closest point on the ray
  3305. // - The closest point on the segment
  3306. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3307. _segDir.copy( v1 ).sub( v0 ).normalize();
  3308. _diff.copy( this.origin ).sub( _segCenter );
  3309. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3310. const a01 = - this.direction.dot( _segDir );
  3311. const b0 = _diff.dot( this.direction );
  3312. const b1 = - _diff.dot( _segDir );
  3313. const c = _diff.lengthSq();
  3314. const det = Math.abs( 1 - a01 * a01 );
  3315. let s0, s1, sqrDist, extDet;
  3316. if ( det > 0 ) {
  3317. // The ray and segment are not parallel.
  3318. s0 = a01 * b1 - b0;
  3319. s1 = a01 * b0 - b1;
  3320. extDet = segExtent * det;
  3321. if ( s0 >= 0 ) {
  3322. if ( s1 >= - extDet ) {
  3323. if ( s1 <= extDet ) {
  3324. // region 0
  3325. // Minimum at interior points of ray and segment.
  3326. const invDet = 1 / det;
  3327. s0 *= invDet;
  3328. s1 *= invDet;
  3329. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3330. } else {
  3331. // region 1
  3332. s1 = segExtent;
  3333. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3334. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3335. }
  3336. } else {
  3337. // region 5
  3338. s1 = - segExtent;
  3339. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3340. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3341. }
  3342. } else {
  3343. if ( s1 <= - extDet ) {
  3344. // region 4
  3345. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3346. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3347. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3348. } else if ( s1 <= extDet ) {
  3349. // region 3
  3350. s0 = 0;
  3351. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3352. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3353. } else {
  3354. // region 2
  3355. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3356. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3357. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3358. }
  3359. }
  3360. } else {
  3361. // Ray and segment are parallel.
  3362. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3363. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3364. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3365. }
  3366. if ( optionalPointOnRay ) {
  3367. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3368. }
  3369. if ( optionalPointOnSegment ) {
  3370. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3371. }
  3372. return sqrDist;
  3373. }
  3374. intersectSphere( sphere, target ) {
  3375. _vector$a.subVectors( sphere.center, this.origin );
  3376. const tca = _vector$a.dot( this.direction );
  3377. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3378. const radius2 = sphere.radius * sphere.radius;
  3379. if ( d2 > radius2 ) return null;
  3380. const thc = Math.sqrt( radius2 - d2 );
  3381. // t0 = first intersect point - entrance on front of sphere
  3382. const t0 = tca - thc;
  3383. // t1 = second intersect point - exit point on back of sphere
  3384. const t1 = tca + thc;
  3385. // test to see if t1 is behind the ray - if so, return null
  3386. if ( t1 < 0 ) return null;
  3387. // test to see if t0 is behind the ray:
  3388. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3389. // in order to always return an intersect point that is in front of the ray.
  3390. if ( t0 < 0 ) return this.at( t1, target );
  3391. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3392. return this.at( t0, target );
  3393. }
  3394. intersectsSphere( sphere ) {
  3395. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3396. }
  3397. distanceToPlane( plane ) {
  3398. const denominator = plane.normal.dot( this.direction );
  3399. if ( denominator === 0 ) {
  3400. // line is coplanar, return origin
  3401. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3402. return 0;
  3403. }
  3404. // Null is preferable to undefined since undefined means.... it is undefined
  3405. return null;
  3406. }
  3407. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3408. // Return if the ray never intersects the plane
  3409. return t >= 0 ? t : null;
  3410. }
  3411. intersectPlane( plane, target ) {
  3412. const t = this.distanceToPlane( plane );
  3413. if ( t === null ) {
  3414. return null;
  3415. }
  3416. return this.at( t, target );
  3417. }
  3418. intersectsPlane( plane ) {
  3419. // check if the ray lies on the plane first
  3420. const distToPoint = plane.distanceToPoint( this.origin );
  3421. if ( distToPoint === 0 ) {
  3422. return true;
  3423. }
  3424. const denominator = plane.normal.dot( this.direction );
  3425. if ( denominator * distToPoint < 0 ) {
  3426. return true;
  3427. }
  3428. // ray origin is behind the plane (and is pointing behind it)
  3429. return false;
  3430. }
  3431. intersectBox( box, target ) {
  3432. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3433. const invdirx = 1 / this.direction.x,
  3434. invdiry = 1 / this.direction.y,
  3435. invdirz = 1 / this.direction.z;
  3436. const origin = this.origin;
  3437. if ( invdirx >= 0 ) {
  3438. tmin = ( box.min.x - origin.x ) * invdirx;
  3439. tmax = ( box.max.x - origin.x ) * invdirx;
  3440. } else {
  3441. tmin = ( box.max.x - origin.x ) * invdirx;
  3442. tmax = ( box.min.x - origin.x ) * invdirx;
  3443. }
  3444. if ( invdiry >= 0 ) {
  3445. tymin = ( box.min.y - origin.y ) * invdiry;
  3446. tymax = ( box.max.y - origin.y ) * invdiry;
  3447. } else {
  3448. tymin = ( box.max.y - origin.y ) * invdiry;
  3449. tymax = ( box.min.y - origin.y ) * invdiry;
  3450. }
  3451. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3452. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3453. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3454. if ( invdirz >= 0 ) {
  3455. tzmin = ( box.min.z - origin.z ) * invdirz;
  3456. tzmax = ( box.max.z - origin.z ) * invdirz;
  3457. } else {
  3458. tzmin = ( box.max.z - origin.z ) * invdirz;
  3459. tzmax = ( box.min.z - origin.z ) * invdirz;
  3460. }
  3461. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3462. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3463. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3464. //return point closest to the ray (positive side)
  3465. if ( tmax < 0 ) return null;
  3466. return this.at( tmin >= 0 ? tmin : tmax, target );
  3467. }
  3468. intersectsBox( box ) {
  3469. return this.intersectBox( box, _vector$a ) !== null;
  3470. }
  3471. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3472. // Compute the offset origin, edges, and normal.
  3473. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3474. _edge1.subVectors( b, a );
  3475. _edge2.subVectors( c, a );
  3476. _normal$2.crossVectors( _edge1, _edge2 );
  3477. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3478. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3479. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3480. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3481. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3482. let DdN = this.direction.dot( _normal$2 );
  3483. let sign;
  3484. if ( DdN > 0 ) {
  3485. if ( backfaceCulling ) return null;
  3486. sign = 1;
  3487. } else if ( DdN < 0 ) {
  3488. sign = - 1;
  3489. DdN = - DdN;
  3490. } else {
  3491. return null;
  3492. }
  3493. _diff.subVectors( this.origin, a );
  3494. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3495. // b1 < 0, no intersection
  3496. if ( DdQxE2 < 0 ) {
  3497. return null;
  3498. }
  3499. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3500. // b2 < 0, no intersection
  3501. if ( DdE1xQ < 0 ) {
  3502. return null;
  3503. }
  3504. // b1+b2 > 1, no intersection
  3505. if ( DdQxE2 + DdE1xQ > DdN ) {
  3506. return null;
  3507. }
  3508. // Line intersects triangle, check if ray does.
  3509. const QdN = - sign * _diff.dot( _normal$2 );
  3510. // t < 0, no intersection
  3511. if ( QdN < 0 ) {
  3512. return null;
  3513. }
  3514. // Ray intersects triangle.
  3515. return this.at( QdN / DdN, target );
  3516. }
  3517. applyMatrix4( matrix4 ) {
  3518. this.origin.applyMatrix4( matrix4 );
  3519. this.direction.transformDirection( matrix4 );
  3520. return this;
  3521. }
  3522. equals( ray ) {
  3523. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3524. }
  3525. clone() {
  3526. return new this.constructor().copy( this );
  3527. }
  3528. }
  3529. class Matrix4 {
  3530. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3531. Matrix4.prototype.isMatrix4 = true;
  3532. this.elements = [
  3533. 1, 0, 0, 0,
  3534. 0, 1, 0, 0,
  3535. 0, 0, 1, 0,
  3536. 0, 0, 0, 1
  3537. ];
  3538. if ( n11 !== undefined ) {
  3539. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3540. }
  3541. }
  3542. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3543. const te = this.elements;
  3544. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3545. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3546. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3547. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3548. return this;
  3549. }
  3550. identity() {
  3551. this.set(
  3552. 1, 0, 0, 0,
  3553. 0, 1, 0, 0,
  3554. 0, 0, 1, 0,
  3555. 0, 0, 0, 1
  3556. );
  3557. return this;
  3558. }
  3559. clone() {
  3560. return new Matrix4().fromArray( this.elements );
  3561. }
  3562. copy( m ) {
  3563. const te = this.elements;
  3564. const me = m.elements;
  3565. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3566. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3567. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3568. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3569. return this;
  3570. }
  3571. copyPosition( m ) {
  3572. const te = this.elements, me = m.elements;
  3573. te[ 12 ] = me[ 12 ];
  3574. te[ 13 ] = me[ 13 ];
  3575. te[ 14 ] = me[ 14 ];
  3576. return this;
  3577. }
  3578. setFromMatrix3( m ) {
  3579. const me = m.elements;
  3580. this.set(
  3581. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3582. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3583. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3584. 0, 0, 0, 1
  3585. );
  3586. return this;
  3587. }
  3588. extractBasis( xAxis, yAxis, zAxis ) {
  3589. xAxis.setFromMatrixColumn( this, 0 );
  3590. yAxis.setFromMatrixColumn( this, 1 );
  3591. zAxis.setFromMatrixColumn( this, 2 );
  3592. return this;
  3593. }
  3594. makeBasis( xAxis, yAxis, zAxis ) {
  3595. this.set(
  3596. xAxis.x, yAxis.x, zAxis.x, 0,
  3597. xAxis.y, yAxis.y, zAxis.y, 0,
  3598. xAxis.z, yAxis.z, zAxis.z, 0,
  3599. 0, 0, 0, 1
  3600. );
  3601. return this;
  3602. }
  3603. extractRotation( m ) {
  3604. // this method does not support reflection matrices
  3605. const te = this.elements;
  3606. const me = m.elements;
  3607. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3608. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3609. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3610. te[ 0 ] = me[ 0 ] * scaleX;
  3611. te[ 1 ] = me[ 1 ] * scaleX;
  3612. te[ 2 ] = me[ 2 ] * scaleX;
  3613. te[ 3 ] = 0;
  3614. te[ 4 ] = me[ 4 ] * scaleY;
  3615. te[ 5 ] = me[ 5 ] * scaleY;
  3616. te[ 6 ] = me[ 6 ] * scaleY;
  3617. te[ 7 ] = 0;
  3618. te[ 8 ] = me[ 8 ] * scaleZ;
  3619. te[ 9 ] = me[ 9 ] * scaleZ;
  3620. te[ 10 ] = me[ 10 ] * scaleZ;
  3621. te[ 11 ] = 0;
  3622. te[ 12 ] = 0;
  3623. te[ 13 ] = 0;
  3624. te[ 14 ] = 0;
  3625. te[ 15 ] = 1;
  3626. return this;
  3627. }
  3628. makeRotationFromEuler( euler ) {
  3629. const te = this.elements;
  3630. const x = euler.x, y = euler.y, z = euler.z;
  3631. const a = Math.cos( x ), b = Math.sin( x );
  3632. const c = Math.cos( y ), d = Math.sin( y );
  3633. const e = Math.cos( z ), f = Math.sin( z );
  3634. if ( euler.order === 'XYZ' ) {
  3635. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3636. te[ 0 ] = c * e;
  3637. te[ 4 ] = - c * f;
  3638. te[ 8 ] = d;
  3639. te[ 1 ] = af + be * d;
  3640. te[ 5 ] = ae - bf * d;
  3641. te[ 9 ] = - b * c;
  3642. te[ 2 ] = bf - ae * d;
  3643. te[ 6 ] = be + af * d;
  3644. te[ 10 ] = a * c;
  3645. } else if ( euler.order === 'YXZ' ) {
  3646. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3647. te[ 0 ] = ce + df * b;
  3648. te[ 4 ] = de * b - cf;
  3649. te[ 8 ] = a * d;
  3650. te[ 1 ] = a * f;
  3651. te[ 5 ] = a * e;
  3652. te[ 9 ] = - b;
  3653. te[ 2 ] = cf * b - de;
  3654. te[ 6 ] = df + ce * b;
  3655. te[ 10 ] = a * c;
  3656. } else if ( euler.order === 'ZXY' ) {
  3657. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3658. te[ 0 ] = ce - df * b;
  3659. te[ 4 ] = - a * f;
  3660. te[ 8 ] = de + cf * b;
  3661. te[ 1 ] = cf + de * b;
  3662. te[ 5 ] = a * e;
  3663. te[ 9 ] = df - ce * b;
  3664. te[ 2 ] = - a * d;
  3665. te[ 6 ] = b;
  3666. te[ 10 ] = a * c;
  3667. } else if ( euler.order === 'ZYX' ) {
  3668. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3669. te[ 0 ] = c * e;
  3670. te[ 4 ] = be * d - af;
  3671. te[ 8 ] = ae * d + bf;
  3672. te[ 1 ] = c * f;
  3673. te[ 5 ] = bf * d + ae;
  3674. te[ 9 ] = af * d - be;
  3675. te[ 2 ] = - d;
  3676. te[ 6 ] = b * c;
  3677. te[ 10 ] = a * c;
  3678. } else if ( euler.order === 'YZX' ) {
  3679. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3680. te[ 0 ] = c * e;
  3681. te[ 4 ] = bd - ac * f;
  3682. te[ 8 ] = bc * f + ad;
  3683. te[ 1 ] = f;
  3684. te[ 5 ] = a * e;
  3685. te[ 9 ] = - b * e;
  3686. te[ 2 ] = - d * e;
  3687. te[ 6 ] = ad * f + bc;
  3688. te[ 10 ] = ac - bd * f;
  3689. } else if ( euler.order === 'XZY' ) {
  3690. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3691. te[ 0 ] = c * e;
  3692. te[ 4 ] = - f;
  3693. te[ 8 ] = d * e;
  3694. te[ 1 ] = ac * f + bd;
  3695. te[ 5 ] = a * e;
  3696. te[ 9 ] = ad * f - bc;
  3697. te[ 2 ] = bc * f - ad;
  3698. te[ 6 ] = b * e;
  3699. te[ 10 ] = bd * f + ac;
  3700. }
  3701. // bottom row
  3702. te[ 3 ] = 0;
  3703. te[ 7 ] = 0;
  3704. te[ 11 ] = 0;
  3705. // last column
  3706. te[ 12 ] = 0;
  3707. te[ 13 ] = 0;
  3708. te[ 14 ] = 0;
  3709. te[ 15 ] = 1;
  3710. return this;
  3711. }
  3712. makeRotationFromQuaternion( q ) {
  3713. return this.compose( _zero, q, _one );
  3714. }
  3715. lookAt( eye, target, up ) {
  3716. const te = this.elements;
  3717. _z.subVectors( eye, target );
  3718. if ( _z.lengthSq() === 0 ) {
  3719. // eye and target are in the same position
  3720. _z.z = 1;
  3721. }
  3722. _z.normalize();
  3723. _x.crossVectors( up, _z );
  3724. if ( _x.lengthSq() === 0 ) {
  3725. // up and z are parallel
  3726. if ( Math.abs( up.z ) === 1 ) {
  3727. _z.x += 0.0001;
  3728. } else {
  3729. _z.z += 0.0001;
  3730. }
  3731. _z.normalize();
  3732. _x.crossVectors( up, _z );
  3733. }
  3734. _x.normalize();
  3735. _y.crossVectors( _z, _x );
  3736. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3737. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3738. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3739. return this;
  3740. }
  3741. multiply( m ) {
  3742. return this.multiplyMatrices( this, m );
  3743. }
  3744. premultiply( m ) {
  3745. return this.multiplyMatrices( m, this );
  3746. }
  3747. multiplyMatrices( a, b ) {
  3748. const ae = a.elements;
  3749. const be = b.elements;
  3750. const te = this.elements;
  3751. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3752. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3753. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3754. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3755. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3756. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3757. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3758. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3759. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3760. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3761. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3762. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3763. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3764. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3765. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3766. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3767. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3768. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3769. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3770. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3771. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3772. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3773. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3774. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3775. return this;
  3776. }
  3777. multiplyScalar( s ) {
  3778. const te = this.elements;
  3779. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3780. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3781. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3782. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3783. return this;
  3784. }
  3785. determinant() {
  3786. const te = this.elements;
  3787. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3788. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3789. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3790. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3791. //TODO: make this more efficient
  3792. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3793. return (
  3794. n41 * (
  3795. + n14 * n23 * n32
  3796. - n13 * n24 * n32
  3797. - n14 * n22 * n33
  3798. + n12 * n24 * n33
  3799. + n13 * n22 * n34
  3800. - n12 * n23 * n34
  3801. ) +
  3802. n42 * (
  3803. + n11 * n23 * n34
  3804. - n11 * n24 * n33
  3805. + n14 * n21 * n33
  3806. - n13 * n21 * n34
  3807. + n13 * n24 * n31
  3808. - n14 * n23 * n31
  3809. ) +
  3810. n43 * (
  3811. + n11 * n24 * n32
  3812. - n11 * n22 * n34
  3813. - n14 * n21 * n32
  3814. + n12 * n21 * n34
  3815. + n14 * n22 * n31
  3816. - n12 * n24 * n31
  3817. ) +
  3818. n44 * (
  3819. - n13 * n22 * n31
  3820. - n11 * n23 * n32
  3821. + n11 * n22 * n33
  3822. + n13 * n21 * n32
  3823. - n12 * n21 * n33
  3824. + n12 * n23 * n31
  3825. )
  3826. );
  3827. }
  3828. transpose() {
  3829. const te = this.elements;
  3830. let tmp;
  3831. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3832. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3833. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3834. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3835. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3836. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3837. return this;
  3838. }
  3839. setPosition( x, y, z ) {
  3840. const te = this.elements;
  3841. if ( x.isVector3 ) {
  3842. te[ 12 ] = x.x;
  3843. te[ 13 ] = x.y;
  3844. te[ 14 ] = x.z;
  3845. } else {
  3846. te[ 12 ] = x;
  3847. te[ 13 ] = y;
  3848. te[ 14 ] = z;
  3849. }
  3850. return this;
  3851. }
  3852. invert() {
  3853. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3854. const te = this.elements,
  3855. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3856. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3857. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3858. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3859. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3860. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3861. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3862. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3863. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3864. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3865. const detInv = 1 / det;
  3866. te[ 0 ] = t11 * detInv;
  3867. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3868. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3869. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3870. te[ 4 ] = t12 * detInv;
  3871. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3872. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3873. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3874. te[ 8 ] = t13 * detInv;
  3875. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3876. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3877. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3878. te[ 12 ] = t14 * detInv;
  3879. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3880. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3881. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3882. return this;
  3883. }
  3884. scale( v ) {
  3885. const te = this.elements;
  3886. const x = v.x, y = v.y, z = v.z;
  3887. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3888. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3889. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3890. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3891. return this;
  3892. }
  3893. getMaxScaleOnAxis() {
  3894. const te = this.elements;
  3895. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3896. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3897. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3898. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3899. }
  3900. makeTranslation( x, y, z ) {
  3901. if ( x.isVector3 ) {
  3902. this.set(
  3903. 1, 0, 0, x.x,
  3904. 0, 1, 0, x.y,
  3905. 0, 0, 1, x.z,
  3906. 0, 0, 0, 1
  3907. );
  3908. } else {
  3909. this.set(
  3910. 1, 0, 0, x,
  3911. 0, 1, 0, y,
  3912. 0, 0, 1, z,
  3913. 0, 0, 0, 1
  3914. );
  3915. }
  3916. return this;
  3917. }
  3918. makeRotationX( theta ) {
  3919. const c = Math.cos( theta ), s = Math.sin( theta );
  3920. this.set(
  3921. 1, 0, 0, 0,
  3922. 0, c, - s, 0,
  3923. 0, s, c, 0,
  3924. 0, 0, 0, 1
  3925. );
  3926. return this;
  3927. }
  3928. makeRotationY( theta ) {
  3929. const c = Math.cos( theta ), s = Math.sin( theta );
  3930. this.set(
  3931. c, 0, s, 0,
  3932. 0, 1, 0, 0,
  3933. - s, 0, c, 0,
  3934. 0, 0, 0, 1
  3935. );
  3936. return this;
  3937. }
  3938. makeRotationZ( theta ) {
  3939. const c = Math.cos( theta ), s = Math.sin( theta );
  3940. this.set(
  3941. c, - s, 0, 0,
  3942. s, c, 0, 0,
  3943. 0, 0, 1, 0,
  3944. 0, 0, 0, 1
  3945. );
  3946. return this;
  3947. }
  3948. makeRotationAxis( axis, angle ) {
  3949. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3950. const c = Math.cos( angle );
  3951. const s = Math.sin( angle );
  3952. const t = 1 - c;
  3953. const x = axis.x, y = axis.y, z = axis.z;
  3954. const tx = t * x, ty = t * y;
  3955. this.set(
  3956. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3957. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3958. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3959. 0, 0, 0, 1
  3960. );
  3961. return this;
  3962. }
  3963. makeScale( x, y, z ) {
  3964. this.set(
  3965. x, 0, 0, 0,
  3966. 0, y, 0, 0,
  3967. 0, 0, z, 0,
  3968. 0, 0, 0, 1
  3969. );
  3970. return this;
  3971. }
  3972. makeShear( xy, xz, yx, yz, zx, zy ) {
  3973. this.set(
  3974. 1, yx, zx, 0,
  3975. xy, 1, zy, 0,
  3976. xz, yz, 1, 0,
  3977. 0, 0, 0, 1
  3978. );
  3979. return this;
  3980. }
  3981. compose( position, quaternion, scale ) {
  3982. const te = this.elements;
  3983. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3984. const x2 = x + x, y2 = y + y, z2 = z + z;
  3985. const xx = x * x2, xy = x * y2, xz = x * z2;
  3986. const yy = y * y2, yz = y * z2, zz = z * z2;
  3987. const wx = w * x2, wy = w * y2, wz = w * z2;
  3988. const sx = scale.x, sy = scale.y, sz = scale.z;
  3989. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3990. te[ 1 ] = ( xy + wz ) * sx;
  3991. te[ 2 ] = ( xz - wy ) * sx;
  3992. te[ 3 ] = 0;
  3993. te[ 4 ] = ( xy - wz ) * sy;
  3994. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3995. te[ 6 ] = ( yz + wx ) * sy;
  3996. te[ 7 ] = 0;
  3997. te[ 8 ] = ( xz + wy ) * sz;
  3998. te[ 9 ] = ( yz - wx ) * sz;
  3999. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4000. te[ 11 ] = 0;
  4001. te[ 12 ] = position.x;
  4002. te[ 13 ] = position.y;
  4003. te[ 14 ] = position.z;
  4004. te[ 15 ] = 1;
  4005. return this;
  4006. }
  4007. decompose( position, quaternion, scale ) {
  4008. const te = this.elements;
  4009. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4010. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4011. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4012. // if determine is negative, we need to invert one scale
  4013. const det = this.determinant();
  4014. if ( det < 0 ) sx = - sx;
  4015. position.x = te[ 12 ];
  4016. position.y = te[ 13 ];
  4017. position.z = te[ 14 ];
  4018. // scale the rotation part
  4019. _m1$3.copy( this );
  4020. const invSX = 1 / sx;
  4021. const invSY = 1 / sy;
  4022. const invSZ = 1 / sz;
  4023. _m1$3.elements[ 0 ] *= invSX;
  4024. _m1$3.elements[ 1 ] *= invSX;
  4025. _m1$3.elements[ 2 ] *= invSX;
  4026. _m1$3.elements[ 4 ] *= invSY;
  4027. _m1$3.elements[ 5 ] *= invSY;
  4028. _m1$3.elements[ 6 ] *= invSY;
  4029. _m1$3.elements[ 8 ] *= invSZ;
  4030. _m1$3.elements[ 9 ] *= invSZ;
  4031. _m1$3.elements[ 10 ] *= invSZ;
  4032. quaternion.setFromRotationMatrix( _m1$3 );
  4033. scale.x = sx;
  4034. scale.y = sy;
  4035. scale.z = sz;
  4036. return this;
  4037. }
  4038. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4039. const te = this.elements;
  4040. const x = 2 * near / ( right - left );
  4041. const y = 2 * near / ( top - bottom );
  4042. const a = ( right + left ) / ( right - left );
  4043. const b = ( top + bottom ) / ( top - bottom );
  4044. let c, d;
  4045. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4046. c = - ( far + near ) / ( far - near );
  4047. d = ( - 2 * far * near ) / ( far - near );
  4048. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4049. c = - far / ( far - near );
  4050. d = ( - far * near ) / ( far - near );
  4051. } else {
  4052. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4053. }
  4054. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4055. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4056. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4057. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4058. return this;
  4059. }
  4060. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4061. const te = this.elements;
  4062. const w = 1.0 / ( right - left );
  4063. const h = 1.0 / ( top - bottom );
  4064. const p = 1.0 / ( far - near );
  4065. const x = ( right + left ) * w;
  4066. const y = ( top + bottom ) * h;
  4067. let z, zInv;
  4068. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4069. z = ( far + near ) * p;
  4070. zInv = - 2 * p;
  4071. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4072. z = near * p;
  4073. zInv = - 1 * p;
  4074. } else {
  4075. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4076. }
  4077. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4078. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4079. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4080. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4081. return this;
  4082. }
  4083. equals( matrix ) {
  4084. const te = this.elements;
  4085. const me = matrix.elements;
  4086. for ( let i = 0; i < 16; i ++ ) {
  4087. if ( te[ i ] !== me[ i ] ) return false;
  4088. }
  4089. return true;
  4090. }
  4091. fromArray( array, offset = 0 ) {
  4092. for ( let i = 0; i < 16; i ++ ) {
  4093. this.elements[ i ] = array[ i + offset ];
  4094. }
  4095. return this;
  4096. }
  4097. toArray( array = [], offset = 0 ) {
  4098. const te = this.elements;
  4099. array[ offset ] = te[ 0 ];
  4100. array[ offset + 1 ] = te[ 1 ];
  4101. array[ offset + 2 ] = te[ 2 ];
  4102. array[ offset + 3 ] = te[ 3 ];
  4103. array[ offset + 4 ] = te[ 4 ];
  4104. array[ offset + 5 ] = te[ 5 ];
  4105. array[ offset + 6 ] = te[ 6 ];
  4106. array[ offset + 7 ] = te[ 7 ];
  4107. array[ offset + 8 ] = te[ 8 ];
  4108. array[ offset + 9 ] = te[ 9 ];
  4109. array[ offset + 10 ] = te[ 10 ];
  4110. array[ offset + 11 ] = te[ 11 ];
  4111. array[ offset + 12 ] = te[ 12 ];
  4112. array[ offset + 13 ] = te[ 13 ];
  4113. array[ offset + 14 ] = te[ 14 ];
  4114. array[ offset + 15 ] = te[ 15 ];
  4115. return array;
  4116. }
  4117. }
  4118. const _v1$5 = /*@__PURE__*/ new Vector3();
  4119. const _m1$3 = /*@__PURE__*/ new Matrix4();
  4120. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4121. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4122. const _x = /*@__PURE__*/ new Vector3();
  4123. const _y = /*@__PURE__*/ new Vector3();
  4124. const _z = /*@__PURE__*/ new Vector3();
  4125. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4126. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4127. class Euler {
  4128. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4129. this.isEuler = true;
  4130. this._x = x;
  4131. this._y = y;
  4132. this._z = z;
  4133. this._order = order;
  4134. }
  4135. get x() {
  4136. return this._x;
  4137. }
  4138. set x( value ) {
  4139. this._x = value;
  4140. this._onChangeCallback();
  4141. }
  4142. get y() {
  4143. return this._y;
  4144. }
  4145. set y( value ) {
  4146. this._y = value;
  4147. this._onChangeCallback();
  4148. }
  4149. get z() {
  4150. return this._z;
  4151. }
  4152. set z( value ) {
  4153. this._z = value;
  4154. this._onChangeCallback();
  4155. }
  4156. get order() {
  4157. return this._order;
  4158. }
  4159. set order( value ) {
  4160. this._order = value;
  4161. this._onChangeCallback();
  4162. }
  4163. set( x, y, z, order = this._order ) {
  4164. this._x = x;
  4165. this._y = y;
  4166. this._z = z;
  4167. this._order = order;
  4168. this._onChangeCallback();
  4169. return this;
  4170. }
  4171. clone() {
  4172. return new this.constructor( this._x, this._y, this._z, this._order );
  4173. }
  4174. copy( euler ) {
  4175. this._x = euler._x;
  4176. this._y = euler._y;
  4177. this._z = euler._z;
  4178. this._order = euler._order;
  4179. this._onChangeCallback();
  4180. return this;
  4181. }
  4182. setFromRotationMatrix( m, order = this._order, update = true ) {
  4183. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4184. const te = m.elements;
  4185. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4186. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4187. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4188. switch ( order ) {
  4189. case 'XYZ':
  4190. this._y = Math.asin( clamp$1( m13, - 1, 1 ) );
  4191. if ( Math.abs( m13 ) < 0.9999999 ) {
  4192. this._x = Math.atan2( - m23, m33 );
  4193. this._z = Math.atan2( - m12, m11 );
  4194. } else {
  4195. this._x = Math.atan2( m32, m22 );
  4196. this._z = 0;
  4197. }
  4198. break;
  4199. case 'YXZ':
  4200. this._x = Math.asin( - clamp$1( m23, - 1, 1 ) );
  4201. if ( Math.abs( m23 ) < 0.9999999 ) {
  4202. this._y = Math.atan2( m13, m33 );
  4203. this._z = Math.atan2( m21, m22 );
  4204. } else {
  4205. this._y = Math.atan2( - m31, m11 );
  4206. this._z = 0;
  4207. }
  4208. break;
  4209. case 'ZXY':
  4210. this._x = Math.asin( clamp$1( m32, - 1, 1 ) );
  4211. if ( Math.abs( m32 ) < 0.9999999 ) {
  4212. this._y = Math.atan2( - m31, m33 );
  4213. this._z = Math.atan2( - m12, m22 );
  4214. } else {
  4215. this._y = 0;
  4216. this._z = Math.atan2( m21, m11 );
  4217. }
  4218. break;
  4219. case 'ZYX':
  4220. this._y = Math.asin( - clamp$1( m31, - 1, 1 ) );
  4221. if ( Math.abs( m31 ) < 0.9999999 ) {
  4222. this._x = Math.atan2( m32, m33 );
  4223. this._z = Math.atan2( m21, m11 );
  4224. } else {
  4225. this._x = 0;
  4226. this._z = Math.atan2( - m12, m22 );
  4227. }
  4228. break;
  4229. case 'YZX':
  4230. this._z = Math.asin( clamp$1( m21, - 1, 1 ) );
  4231. if ( Math.abs( m21 ) < 0.9999999 ) {
  4232. this._x = Math.atan2( - m23, m22 );
  4233. this._y = Math.atan2( - m31, m11 );
  4234. } else {
  4235. this._x = 0;
  4236. this._y = Math.atan2( m13, m33 );
  4237. }
  4238. break;
  4239. case 'XZY':
  4240. this._z = Math.asin( - clamp$1( m12, - 1, 1 ) );
  4241. if ( Math.abs( m12 ) < 0.9999999 ) {
  4242. this._x = Math.atan2( m32, m22 );
  4243. this._y = Math.atan2( m13, m11 );
  4244. } else {
  4245. this._x = Math.atan2( - m23, m33 );
  4246. this._y = 0;
  4247. }
  4248. break;
  4249. default:
  4250. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4251. }
  4252. this._order = order;
  4253. if ( update === true ) this._onChangeCallback();
  4254. return this;
  4255. }
  4256. setFromQuaternion( q, order, update ) {
  4257. _matrix$2.makeRotationFromQuaternion( q );
  4258. return this.setFromRotationMatrix( _matrix$2, order, update );
  4259. }
  4260. setFromVector3( v, order = this._order ) {
  4261. return this.set( v.x, v.y, v.z, order );
  4262. }
  4263. reorder( newOrder ) {
  4264. // WARNING: this discards revolution information -bhouston
  4265. _quaternion$3.setFromEuler( this );
  4266. return this.setFromQuaternion( _quaternion$3, newOrder );
  4267. }
  4268. equals( euler ) {
  4269. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4270. }
  4271. fromArray( array ) {
  4272. this._x = array[ 0 ];
  4273. this._y = array[ 1 ];
  4274. this._z = array[ 2 ];
  4275. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4276. this._onChangeCallback();
  4277. return this;
  4278. }
  4279. toArray( array = [], offset = 0 ) {
  4280. array[ offset ] = this._x;
  4281. array[ offset + 1 ] = this._y;
  4282. array[ offset + 2 ] = this._z;
  4283. array[ offset + 3 ] = this._order;
  4284. return array;
  4285. }
  4286. _onChange( callback ) {
  4287. this._onChangeCallback = callback;
  4288. return this;
  4289. }
  4290. _onChangeCallback() {}
  4291. *[ Symbol.iterator ]() {
  4292. yield this._x;
  4293. yield this._y;
  4294. yield this._z;
  4295. yield this._order;
  4296. }
  4297. }
  4298. Euler.DEFAULT_ORDER = 'XYZ';
  4299. class Layers {
  4300. constructor() {
  4301. this.mask = 1 | 0;
  4302. }
  4303. set( channel ) {
  4304. this.mask = ( 1 << channel | 0 ) >>> 0;
  4305. }
  4306. enable( channel ) {
  4307. this.mask |= 1 << channel | 0;
  4308. }
  4309. enableAll() {
  4310. this.mask = 0xffffffff | 0;
  4311. }
  4312. toggle( channel ) {
  4313. this.mask ^= 1 << channel | 0;
  4314. }
  4315. disable( channel ) {
  4316. this.mask &= ~ ( 1 << channel | 0 );
  4317. }
  4318. disableAll() {
  4319. this.mask = 0;
  4320. }
  4321. test( layers ) {
  4322. return ( this.mask & layers.mask ) !== 0;
  4323. }
  4324. isEnabled( channel ) {
  4325. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4326. }
  4327. }
  4328. let _object3DId = 0;
  4329. const _v1$4 = /*@__PURE__*/ new Vector3();
  4330. const _q1 = /*@__PURE__*/ new Quaternion();
  4331. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4332. const _target$1 = /*@__PURE__*/ new Vector3();
  4333. const _position$3 = /*@__PURE__*/ new Vector3();
  4334. const _scale$2 = /*@__PURE__*/ new Vector3();
  4335. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4336. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4337. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4338. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4339. const _addedEvent = { type: 'added' };
  4340. const _removedEvent = { type: 'removed' };
  4341. const _childaddedEvent = { type: 'childadded', child: null };
  4342. const _childremovedEvent = { type: 'childremoved', child: null };
  4343. class Object3D extends EventDispatcher {
  4344. constructor() {
  4345. super();
  4346. this.isObject3D = true;
  4347. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4348. this.uuid = generateUUID();
  4349. this.name = '';
  4350. this.type = 'Object3D';
  4351. this.parent = null;
  4352. this.children = [];
  4353. this.up = Object3D.DEFAULT_UP.clone();
  4354. const position = new Vector3();
  4355. const rotation = new Euler();
  4356. const quaternion = new Quaternion();
  4357. const scale = new Vector3( 1, 1, 1 );
  4358. function onRotationChange() {
  4359. quaternion.setFromEuler( rotation, false );
  4360. }
  4361. function onQuaternionChange() {
  4362. rotation.setFromQuaternion( quaternion, undefined, false );
  4363. }
  4364. rotation._onChange( onRotationChange );
  4365. quaternion._onChange( onQuaternionChange );
  4366. Object.defineProperties( this, {
  4367. position: {
  4368. configurable: true,
  4369. enumerable: true,
  4370. value: position
  4371. },
  4372. rotation: {
  4373. configurable: true,
  4374. enumerable: true,
  4375. value: rotation
  4376. },
  4377. quaternion: {
  4378. configurable: true,
  4379. enumerable: true,
  4380. value: quaternion
  4381. },
  4382. scale: {
  4383. configurable: true,
  4384. enumerable: true,
  4385. value: scale
  4386. },
  4387. modelViewMatrix: {
  4388. value: new Matrix4()
  4389. },
  4390. normalMatrix: {
  4391. value: new Matrix3()
  4392. }
  4393. } );
  4394. this.matrix = new Matrix4();
  4395. this.matrixWorld = new Matrix4();
  4396. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4397. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4398. this.matrixWorldNeedsUpdate = false;
  4399. this.layers = new Layers();
  4400. this.visible = true;
  4401. this.castShadow = false;
  4402. this.receiveShadow = false;
  4403. this.frustumCulled = true;
  4404. this.renderOrder = 0;
  4405. this.animations = [];
  4406. this.userData = {};
  4407. }
  4408. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4409. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4410. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4411. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4412. applyMatrix4( matrix ) {
  4413. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4414. this.matrix.premultiply( matrix );
  4415. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4416. }
  4417. applyQuaternion( q ) {
  4418. this.quaternion.premultiply( q );
  4419. return this;
  4420. }
  4421. setRotationFromAxisAngle( axis, angle ) {
  4422. // assumes axis is normalized
  4423. this.quaternion.setFromAxisAngle( axis, angle );
  4424. }
  4425. setRotationFromEuler( euler ) {
  4426. this.quaternion.setFromEuler( euler, true );
  4427. }
  4428. setRotationFromMatrix( m ) {
  4429. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4430. this.quaternion.setFromRotationMatrix( m );
  4431. }
  4432. setRotationFromQuaternion( q ) {
  4433. // assumes q is normalized
  4434. this.quaternion.copy( q );
  4435. }
  4436. rotateOnAxis( axis, angle ) {
  4437. // rotate object on axis in object space
  4438. // axis is assumed to be normalized
  4439. _q1.setFromAxisAngle( axis, angle );
  4440. this.quaternion.multiply( _q1 );
  4441. return this;
  4442. }
  4443. rotateOnWorldAxis( axis, angle ) {
  4444. // rotate object on axis in world space
  4445. // axis is assumed to be normalized
  4446. // method assumes no rotated parent
  4447. _q1.setFromAxisAngle( axis, angle );
  4448. this.quaternion.premultiply( _q1 );
  4449. return this;
  4450. }
  4451. rotateX( angle ) {
  4452. return this.rotateOnAxis( _xAxis, angle );
  4453. }
  4454. rotateY( angle ) {
  4455. return this.rotateOnAxis( _yAxis, angle );
  4456. }
  4457. rotateZ( angle ) {
  4458. return this.rotateOnAxis( _zAxis, angle );
  4459. }
  4460. translateOnAxis( axis, distance ) {
  4461. // translate object by distance along axis in object space
  4462. // axis is assumed to be normalized
  4463. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4464. this.position.add( _v1$4.multiplyScalar( distance ) );
  4465. return this;
  4466. }
  4467. translateX( distance ) {
  4468. return this.translateOnAxis( _xAxis, distance );
  4469. }
  4470. translateY( distance ) {
  4471. return this.translateOnAxis( _yAxis, distance );
  4472. }
  4473. translateZ( distance ) {
  4474. return this.translateOnAxis( _zAxis, distance );
  4475. }
  4476. localToWorld( vector ) {
  4477. this.updateWorldMatrix( true, false );
  4478. return vector.applyMatrix4( this.matrixWorld );
  4479. }
  4480. worldToLocal( vector ) {
  4481. this.updateWorldMatrix( true, false );
  4482. return vector.applyMatrix4( _m1$2.copy( this.matrixWorld ).invert() );
  4483. }
  4484. lookAt( x, y, z ) {
  4485. // This method does not support objects having non-uniformly-scaled parent(s)
  4486. if ( x.isVector3 ) {
  4487. _target$1.copy( x );
  4488. } else {
  4489. _target$1.set( x, y, z );
  4490. }
  4491. const parent = this.parent;
  4492. this.updateWorldMatrix( true, false );
  4493. _position$3.setFromMatrixPosition( this.matrixWorld );
  4494. if ( this.isCamera || this.isLight ) {
  4495. _m1$2.lookAt( _position$3, _target$1, this.up );
  4496. } else {
  4497. _m1$2.lookAt( _target$1, _position$3, this.up );
  4498. }
  4499. this.quaternion.setFromRotationMatrix( _m1$2 );
  4500. if ( parent ) {
  4501. _m1$2.extractRotation( parent.matrixWorld );
  4502. _q1.setFromRotationMatrix( _m1$2 );
  4503. this.quaternion.premultiply( _q1.invert() );
  4504. }
  4505. }
  4506. add( object ) {
  4507. if ( arguments.length > 1 ) {
  4508. for ( let i = 0; i < arguments.length; i ++ ) {
  4509. this.add( arguments[ i ] );
  4510. }
  4511. return this;
  4512. }
  4513. if ( object === this ) {
  4514. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4515. return this;
  4516. }
  4517. if ( object && object.isObject3D ) {
  4518. object.removeFromParent();
  4519. object.parent = this;
  4520. this.children.push( object );
  4521. object.dispatchEvent( _addedEvent );
  4522. _childaddedEvent.child = object;
  4523. this.dispatchEvent( _childaddedEvent );
  4524. _childaddedEvent.child = null;
  4525. } else {
  4526. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4527. }
  4528. return this;
  4529. }
  4530. remove( object ) {
  4531. if ( arguments.length > 1 ) {
  4532. for ( let i = 0; i < arguments.length; i ++ ) {
  4533. this.remove( arguments[ i ] );
  4534. }
  4535. return this;
  4536. }
  4537. const index = this.children.indexOf( object );
  4538. if ( index !== - 1 ) {
  4539. object.parent = null;
  4540. this.children.splice( index, 1 );
  4541. object.dispatchEvent( _removedEvent );
  4542. _childremovedEvent.child = object;
  4543. this.dispatchEvent( _childremovedEvent );
  4544. _childremovedEvent.child = null;
  4545. }
  4546. return this;
  4547. }
  4548. removeFromParent() {
  4549. const parent = this.parent;
  4550. if ( parent !== null ) {
  4551. parent.remove( this );
  4552. }
  4553. return this;
  4554. }
  4555. clear() {
  4556. return this.remove( ... this.children );
  4557. }
  4558. attach( object ) {
  4559. // adds object as a child of this, while maintaining the object's world transform
  4560. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4561. this.updateWorldMatrix( true, false );
  4562. _m1$2.copy( this.matrixWorld ).invert();
  4563. if ( object.parent !== null ) {
  4564. object.parent.updateWorldMatrix( true, false );
  4565. _m1$2.multiply( object.parent.matrixWorld );
  4566. }
  4567. object.applyMatrix4( _m1$2 );
  4568. object.removeFromParent();
  4569. object.parent = this;
  4570. this.children.push( object );
  4571. object.updateWorldMatrix( false, true );
  4572. object.dispatchEvent( _addedEvent );
  4573. _childaddedEvent.child = object;
  4574. this.dispatchEvent( _childaddedEvent );
  4575. _childaddedEvent.child = null;
  4576. return this;
  4577. }
  4578. getObjectById( id ) {
  4579. return this.getObjectByProperty( 'id', id );
  4580. }
  4581. getObjectByName( name ) {
  4582. return this.getObjectByProperty( 'name', name );
  4583. }
  4584. getObjectByProperty( name, value ) {
  4585. if ( this[ name ] === value ) return this;
  4586. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4587. const child = this.children[ i ];
  4588. const object = child.getObjectByProperty( name, value );
  4589. if ( object !== undefined ) {
  4590. return object;
  4591. }
  4592. }
  4593. return undefined;
  4594. }
  4595. getObjectsByProperty( name, value, result = [] ) {
  4596. if ( this[ name ] === value ) result.push( this );
  4597. const children = this.children;
  4598. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4599. children[ i ].getObjectsByProperty( name, value, result );
  4600. }
  4601. return result;
  4602. }
  4603. getWorldPosition( target ) {
  4604. this.updateWorldMatrix( true, false );
  4605. return target.setFromMatrixPosition( this.matrixWorld );
  4606. }
  4607. getWorldQuaternion( target ) {
  4608. this.updateWorldMatrix( true, false );
  4609. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4610. return target;
  4611. }
  4612. getWorldScale( target ) {
  4613. this.updateWorldMatrix( true, false );
  4614. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4615. return target;
  4616. }
  4617. getWorldDirection( target ) {
  4618. this.updateWorldMatrix( true, false );
  4619. const e = this.matrixWorld.elements;
  4620. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4621. }
  4622. raycast( /* raycaster, intersects */ ) {}
  4623. traverse( callback ) {
  4624. callback( this );
  4625. const children = this.children;
  4626. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4627. children[ i ].traverse( callback );
  4628. }
  4629. }
  4630. traverseVisible( callback ) {
  4631. if ( this.visible === false ) return;
  4632. callback( this );
  4633. const children = this.children;
  4634. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4635. children[ i ].traverseVisible( callback );
  4636. }
  4637. }
  4638. traverseAncestors( callback ) {
  4639. const parent = this.parent;
  4640. if ( parent !== null ) {
  4641. callback( parent );
  4642. parent.traverseAncestors( callback );
  4643. }
  4644. }
  4645. updateMatrix() {
  4646. this.matrix.compose( this.position, this.quaternion, this.scale );
  4647. this.matrixWorldNeedsUpdate = true;
  4648. }
  4649. updateMatrixWorld( force ) {
  4650. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4651. if ( this.matrixWorldNeedsUpdate || force ) {
  4652. if ( this.matrixWorldAutoUpdate === true ) {
  4653. if ( this.parent === null ) {
  4654. this.matrixWorld.copy( this.matrix );
  4655. } else {
  4656. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4657. }
  4658. }
  4659. this.matrixWorldNeedsUpdate = false;
  4660. force = true;
  4661. }
  4662. // make sure descendants are updated if required
  4663. const children = this.children;
  4664. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4665. const child = children[ i ];
  4666. child.updateMatrixWorld( force );
  4667. }
  4668. }
  4669. updateWorldMatrix( updateParents, updateChildren ) {
  4670. const parent = this.parent;
  4671. if ( updateParents === true && parent !== null ) {
  4672. parent.updateWorldMatrix( true, false );
  4673. }
  4674. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4675. if ( this.matrixWorldAutoUpdate === true ) {
  4676. if ( this.parent === null ) {
  4677. this.matrixWorld.copy( this.matrix );
  4678. } else {
  4679. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4680. }
  4681. }
  4682. // make sure descendants are updated
  4683. if ( updateChildren === true ) {
  4684. const children = this.children;
  4685. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4686. const child = children[ i ];
  4687. child.updateWorldMatrix( false, true );
  4688. }
  4689. }
  4690. }
  4691. toJSON( meta ) {
  4692. // meta is a string when called from JSON.stringify
  4693. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4694. const output = {};
  4695. // meta is a hash used to collect geometries, materials.
  4696. // not providing it implies that this is the root object
  4697. // being serialized.
  4698. if ( isRootObject ) {
  4699. // initialize meta obj
  4700. meta = {
  4701. geometries: {},
  4702. materials: {},
  4703. textures: {},
  4704. images: {},
  4705. shapes: {},
  4706. skeletons: {},
  4707. animations: {},
  4708. nodes: {}
  4709. };
  4710. output.metadata = {
  4711. version: 4.6,
  4712. type: 'Object',
  4713. generator: 'Object3D.toJSON'
  4714. };
  4715. }
  4716. // standard Object3D serialization
  4717. const object = {};
  4718. object.uuid = this.uuid;
  4719. object.type = this.type;
  4720. if ( this.name !== '' ) object.name = this.name;
  4721. if ( this.castShadow === true ) object.castShadow = true;
  4722. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4723. if ( this.visible === false ) object.visible = false;
  4724. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4725. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4726. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4727. object.layers = this.layers.mask;
  4728. object.matrix = this.matrix.toArray();
  4729. object.up = this.up.toArray();
  4730. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4731. // object specific properties
  4732. if ( this.isInstancedMesh ) {
  4733. object.type = 'InstancedMesh';
  4734. object.count = this.count;
  4735. object.instanceMatrix = this.instanceMatrix.toJSON();
  4736. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4737. }
  4738. if ( this.isBatchedMesh ) {
  4739. object.type = 'BatchedMesh';
  4740. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4741. object.sortObjects = this.sortObjects;
  4742. object.drawRanges = this._drawRanges;
  4743. object.reservedRanges = this._reservedRanges;
  4744. object.visibility = this._visibility;
  4745. object.active = this._active;
  4746. object.bounds = this._bounds.map( bound => ( {
  4747. boxInitialized: bound.boxInitialized,
  4748. boxMin: bound.box.min.toArray(),
  4749. boxMax: bound.box.max.toArray(),
  4750. sphereInitialized: bound.sphereInitialized,
  4751. sphereRadius: bound.sphere.radius,
  4752. sphereCenter: bound.sphere.center.toArray()
  4753. } ) );
  4754. object.maxInstanceCount = this._maxInstanceCount;
  4755. object.maxVertexCount = this._maxVertexCount;
  4756. object.maxIndexCount = this._maxIndexCount;
  4757. object.geometryInitialized = this._geometryInitialized;
  4758. object.geometryCount = this._geometryCount;
  4759. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4760. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  4761. if ( this.boundingSphere !== null ) {
  4762. object.boundingSphere = {
  4763. center: object.boundingSphere.center.toArray(),
  4764. radius: object.boundingSphere.radius
  4765. };
  4766. }
  4767. if ( this.boundingBox !== null ) {
  4768. object.boundingBox = {
  4769. min: object.boundingBox.min.toArray(),
  4770. max: object.boundingBox.max.toArray()
  4771. };
  4772. }
  4773. }
  4774. //
  4775. function serialize( library, element ) {
  4776. if ( library[ element.uuid ] === undefined ) {
  4777. library[ element.uuid ] = element.toJSON( meta );
  4778. }
  4779. return element.uuid;
  4780. }
  4781. if ( this.isScene ) {
  4782. if ( this.background ) {
  4783. if ( this.background.isColor ) {
  4784. object.background = this.background.toJSON();
  4785. } else if ( this.background.isTexture ) {
  4786. object.background = this.background.toJSON( meta ).uuid;
  4787. }
  4788. }
  4789. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4790. object.environment = this.environment.toJSON( meta ).uuid;
  4791. }
  4792. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4793. object.geometry = serialize( meta.geometries, this.geometry );
  4794. const parameters = this.geometry.parameters;
  4795. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4796. const shapes = parameters.shapes;
  4797. if ( Array.isArray( shapes ) ) {
  4798. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4799. const shape = shapes[ i ];
  4800. serialize( meta.shapes, shape );
  4801. }
  4802. } else {
  4803. serialize( meta.shapes, shapes );
  4804. }
  4805. }
  4806. }
  4807. if ( this.isSkinnedMesh ) {
  4808. object.bindMode = this.bindMode;
  4809. object.bindMatrix = this.bindMatrix.toArray();
  4810. if ( this.skeleton !== undefined ) {
  4811. serialize( meta.skeletons, this.skeleton );
  4812. object.skeleton = this.skeleton.uuid;
  4813. }
  4814. }
  4815. if ( this.material !== undefined ) {
  4816. if ( Array.isArray( this.material ) ) {
  4817. const uuids = [];
  4818. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4819. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4820. }
  4821. object.material = uuids;
  4822. } else {
  4823. object.material = serialize( meta.materials, this.material );
  4824. }
  4825. }
  4826. //
  4827. if ( this.children.length > 0 ) {
  4828. object.children = [];
  4829. for ( let i = 0; i < this.children.length; i ++ ) {
  4830. object.children.push( this.children[ i ].toJSON( meta ).object );
  4831. }
  4832. }
  4833. //
  4834. if ( this.animations.length > 0 ) {
  4835. object.animations = [];
  4836. for ( let i = 0; i < this.animations.length; i ++ ) {
  4837. const animation = this.animations[ i ];
  4838. object.animations.push( serialize( meta.animations, animation ) );
  4839. }
  4840. }
  4841. if ( isRootObject ) {
  4842. const geometries = extractFromCache( meta.geometries );
  4843. const materials = extractFromCache( meta.materials );
  4844. const textures = extractFromCache( meta.textures );
  4845. const images = extractFromCache( meta.images );
  4846. const shapes = extractFromCache( meta.shapes );
  4847. const skeletons = extractFromCache( meta.skeletons );
  4848. const animations = extractFromCache( meta.animations );
  4849. const nodes = extractFromCache( meta.nodes );
  4850. if ( geometries.length > 0 ) output.geometries = geometries;
  4851. if ( materials.length > 0 ) output.materials = materials;
  4852. if ( textures.length > 0 ) output.textures = textures;
  4853. if ( images.length > 0 ) output.images = images;
  4854. if ( shapes.length > 0 ) output.shapes = shapes;
  4855. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4856. if ( animations.length > 0 ) output.animations = animations;
  4857. if ( nodes.length > 0 ) output.nodes = nodes;
  4858. }
  4859. output.object = object;
  4860. return output;
  4861. // extract data from the cache hash
  4862. // remove metadata on each item
  4863. // and return as array
  4864. function extractFromCache( cache ) {
  4865. const values = [];
  4866. for ( const key in cache ) {
  4867. const data = cache[ key ];
  4868. delete data.metadata;
  4869. values.push( data );
  4870. }
  4871. return values;
  4872. }
  4873. }
  4874. clone( recursive ) {
  4875. return new this.constructor().copy( this, recursive );
  4876. }
  4877. copy( source, recursive = true ) {
  4878. this.name = source.name;
  4879. this.up.copy( source.up );
  4880. this.position.copy( source.position );
  4881. this.rotation.order = source.rotation.order;
  4882. this.quaternion.copy( source.quaternion );
  4883. this.scale.copy( source.scale );
  4884. this.matrix.copy( source.matrix );
  4885. this.matrixWorld.copy( source.matrixWorld );
  4886. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4887. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4888. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4889. this.layers.mask = source.layers.mask;
  4890. this.visible = source.visible;
  4891. this.castShadow = source.castShadow;
  4892. this.receiveShadow = source.receiveShadow;
  4893. this.frustumCulled = source.frustumCulled;
  4894. this.renderOrder = source.renderOrder;
  4895. this.animations = source.animations.slice();
  4896. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4897. if ( recursive === true ) {
  4898. for ( let i = 0; i < source.children.length; i ++ ) {
  4899. const child = source.children[ i ];
  4900. this.add( child.clone() );
  4901. }
  4902. }
  4903. return this;
  4904. }
  4905. }
  4906. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4907. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4908. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4909. const _v0$1 = /*@__PURE__*/ new Vector3();
  4910. const _v1$3 = /*@__PURE__*/ new Vector3();
  4911. const _v2$2 = /*@__PURE__*/ new Vector3();
  4912. const _v3$2 = /*@__PURE__*/ new Vector3();
  4913. const _vab = /*@__PURE__*/ new Vector3();
  4914. const _vac = /*@__PURE__*/ new Vector3();
  4915. const _vbc = /*@__PURE__*/ new Vector3();
  4916. const _vap = /*@__PURE__*/ new Vector3();
  4917. const _vbp = /*@__PURE__*/ new Vector3();
  4918. const _vcp = /*@__PURE__*/ new Vector3();
  4919. const _v40 = /*@__PURE__*/ new Vector4();
  4920. const _v41 = /*@__PURE__*/ new Vector4();
  4921. const _v42 = /*@__PURE__*/ new Vector4();
  4922. class Triangle {
  4923. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4924. this.a = a;
  4925. this.b = b;
  4926. this.c = c;
  4927. }
  4928. static getNormal( a, b, c, target ) {
  4929. target.subVectors( c, b );
  4930. _v0$1.subVectors( a, b );
  4931. target.cross( _v0$1 );
  4932. const targetLengthSq = target.lengthSq();
  4933. if ( targetLengthSq > 0 ) {
  4934. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4935. }
  4936. return target.set( 0, 0, 0 );
  4937. }
  4938. // static/instance method to calculate barycentric coordinates
  4939. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4940. static getBarycoord( point, a, b, c, target ) {
  4941. _v0$1.subVectors( c, a );
  4942. _v1$3.subVectors( b, a );
  4943. _v2$2.subVectors( point, a );
  4944. const dot00 = _v0$1.dot( _v0$1 );
  4945. const dot01 = _v0$1.dot( _v1$3 );
  4946. const dot02 = _v0$1.dot( _v2$2 );
  4947. const dot11 = _v1$3.dot( _v1$3 );
  4948. const dot12 = _v1$3.dot( _v2$2 );
  4949. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4950. // collinear or singular triangle
  4951. if ( denom === 0 ) {
  4952. target.set( 0, 0, 0 );
  4953. return null;
  4954. }
  4955. const invDenom = 1 / denom;
  4956. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4957. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4958. // barycentric coordinates must always sum to 1
  4959. return target.set( 1 - u - v, v, u );
  4960. }
  4961. static containsPoint( point, a, b, c ) {
  4962. // if the triangle is degenerate then we can't contain a point
  4963. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4964. return false;
  4965. }
  4966. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4967. }
  4968. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4969. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4970. target.x = 0;
  4971. target.y = 0;
  4972. if ( 'z' in target ) target.z = 0;
  4973. if ( 'w' in target ) target.w = 0;
  4974. return null;
  4975. }
  4976. target.setScalar( 0 );
  4977. target.addScaledVector( v1, _v3$2.x );
  4978. target.addScaledVector( v2, _v3$2.y );
  4979. target.addScaledVector( v3, _v3$2.z );
  4980. return target;
  4981. }
  4982. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  4983. _v40.setScalar( 0 );
  4984. _v41.setScalar( 0 );
  4985. _v42.setScalar( 0 );
  4986. _v40.fromBufferAttribute( attr, i1 );
  4987. _v41.fromBufferAttribute( attr, i2 );
  4988. _v42.fromBufferAttribute( attr, i3 );
  4989. target.setScalar( 0 );
  4990. target.addScaledVector( _v40, barycoord.x );
  4991. target.addScaledVector( _v41, barycoord.y );
  4992. target.addScaledVector( _v42, barycoord.z );
  4993. return target;
  4994. }
  4995. static isFrontFacing( a, b, c, direction ) {
  4996. _v0$1.subVectors( c, b );
  4997. _v1$3.subVectors( a, b );
  4998. // strictly front facing
  4999. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5000. }
  5001. set( a, b, c ) {
  5002. this.a.copy( a );
  5003. this.b.copy( b );
  5004. this.c.copy( c );
  5005. return this;
  5006. }
  5007. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5008. this.a.copy( points[ i0 ] );
  5009. this.b.copy( points[ i1 ] );
  5010. this.c.copy( points[ i2 ] );
  5011. return this;
  5012. }
  5013. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  5014. this.a.fromBufferAttribute( attribute, i0 );
  5015. this.b.fromBufferAttribute( attribute, i1 );
  5016. this.c.fromBufferAttribute( attribute, i2 );
  5017. return this;
  5018. }
  5019. clone() {
  5020. return new this.constructor().copy( this );
  5021. }
  5022. copy( triangle ) {
  5023. this.a.copy( triangle.a );
  5024. this.b.copy( triangle.b );
  5025. this.c.copy( triangle.c );
  5026. return this;
  5027. }
  5028. getArea() {
  5029. _v0$1.subVectors( this.c, this.b );
  5030. _v1$3.subVectors( this.a, this.b );
  5031. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5032. }
  5033. getMidpoint( target ) {
  5034. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5035. }
  5036. getNormal( target ) {
  5037. return Triangle.getNormal( this.a, this.b, this.c, target );
  5038. }
  5039. getPlane( target ) {
  5040. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5041. }
  5042. getBarycoord( point, target ) {
  5043. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5044. }
  5045. getInterpolation( point, v1, v2, v3, target ) {
  5046. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5047. }
  5048. containsPoint( point ) {
  5049. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5050. }
  5051. isFrontFacing( direction ) {
  5052. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5053. }
  5054. intersectsBox( box ) {
  5055. return box.intersectsTriangle( this );
  5056. }
  5057. closestPointToPoint( p, target ) {
  5058. const a = this.a, b = this.b, c = this.c;
  5059. let v, w;
  5060. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5061. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5062. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5063. // basically, we're distinguishing which of the voronoi regions of the triangle
  5064. // the point lies in with the minimum amount of redundant computation.
  5065. _vab.subVectors( b, a );
  5066. _vac.subVectors( c, a );
  5067. _vap.subVectors( p, a );
  5068. const d1 = _vab.dot( _vap );
  5069. const d2 = _vac.dot( _vap );
  5070. if ( d1 <= 0 && d2 <= 0 ) {
  5071. // vertex region of A; barycentric coords (1, 0, 0)
  5072. return target.copy( a );
  5073. }
  5074. _vbp.subVectors( p, b );
  5075. const d3 = _vab.dot( _vbp );
  5076. const d4 = _vac.dot( _vbp );
  5077. if ( d3 >= 0 && d4 <= d3 ) {
  5078. // vertex region of B; barycentric coords (0, 1, 0)
  5079. return target.copy( b );
  5080. }
  5081. const vc = d1 * d4 - d3 * d2;
  5082. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5083. v = d1 / ( d1 - d3 );
  5084. // edge region of AB; barycentric coords (1-v, v, 0)
  5085. return target.copy( a ).addScaledVector( _vab, v );
  5086. }
  5087. _vcp.subVectors( p, c );
  5088. const d5 = _vab.dot( _vcp );
  5089. const d6 = _vac.dot( _vcp );
  5090. if ( d6 >= 0 && d5 <= d6 ) {
  5091. // vertex region of C; barycentric coords (0, 0, 1)
  5092. return target.copy( c );
  5093. }
  5094. const vb = d5 * d2 - d1 * d6;
  5095. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5096. w = d2 / ( d2 - d6 );
  5097. // edge region of AC; barycentric coords (1-w, 0, w)
  5098. return target.copy( a ).addScaledVector( _vac, w );
  5099. }
  5100. const va = d3 * d6 - d5 * d4;
  5101. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5102. _vbc.subVectors( c, b );
  5103. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5104. // edge region of BC; barycentric coords (0, 1-w, w)
  5105. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5106. }
  5107. // face region
  5108. const denom = 1 / ( va + vb + vc );
  5109. // u = va * denom
  5110. v = vb * denom;
  5111. w = vc * denom;
  5112. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5113. }
  5114. equals( triangle ) {
  5115. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5116. }
  5117. }
  5118. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5119. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5120. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5121. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5122. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5123. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5124. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5125. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5126. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5127. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5128. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5129. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5130. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5131. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5132. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5133. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5134. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5135. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5136. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5137. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5138. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5139. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5140. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5141. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5142. const _hslA = { h: 0, s: 0, l: 0 };
  5143. const _hslB = { h: 0, s: 0, l: 0 };
  5144. function hue2rgb( p, q, t ) {
  5145. if ( t < 0 ) t += 1;
  5146. if ( t > 1 ) t -= 1;
  5147. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5148. if ( t < 1 / 2 ) return q;
  5149. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5150. return p;
  5151. }
  5152. class Color {
  5153. constructor( r, g, b ) {
  5154. this.isColor = true;
  5155. this.r = 1;
  5156. this.g = 1;
  5157. this.b = 1;
  5158. return this.set( r, g, b );
  5159. }
  5160. set( r, g, b ) {
  5161. if ( g === undefined && b === undefined ) {
  5162. // r is THREE.Color, hex or string
  5163. const value = r;
  5164. if ( value && value.isColor ) {
  5165. this.copy( value );
  5166. } else if ( typeof value === 'number' ) {
  5167. this.setHex( value );
  5168. } else if ( typeof value === 'string' ) {
  5169. this.setStyle( value );
  5170. }
  5171. } else {
  5172. this.setRGB( r, g, b );
  5173. }
  5174. return this;
  5175. }
  5176. setScalar( scalar ) {
  5177. this.r = scalar;
  5178. this.g = scalar;
  5179. this.b = scalar;
  5180. return this;
  5181. }
  5182. setHex( hex, colorSpace = SRGBColorSpace ) {
  5183. hex = Math.floor( hex );
  5184. this.r = ( hex >> 16 & 255 ) / 255;
  5185. this.g = ( hex >> 8 & 255 ) / 255;
  5186. this.b = ( hex & 255 ) / 255;
  5187. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5188. return this;
  5189. }
  5190. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5191. this.r = r;
  5192. this.g = g;
  5193. this.b = b;
  5194. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5195. return this;
  5196. }
  5197. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5198. // h,s,l ranges are in 0.0 - 1.0
  5199. h = euclideanModulo( h, 1 );
  5200. s = clamp$1( s, 0, 1 );
  5201. l = clamp$1( l, 0, 1 );
  5202. if ( s === 0 ) {
  5203. this.r = this.g = this.b = l;
  5204. } else {
  5205. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5206. const q = ( 2 * l ) - p;
  5207. this.r = hue2rgb( q, p, h + 1 / 3 );
  5208. this.g = hue2rgb( q, p, h );
  5209. this.b = hue2rgb( q, p, h - 1 / 3 );
  5210. }
  5211. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5212. return this;
  5213. }
  5214. setStyle( style, colorSpace = SRGBColorSpace ) {
  5215. function handleAlpha( string ) {
  5216. if ( string === undefined ) return;
  5217. if ( parseFloat( string ) < 1 ) {
  5218. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5219. }
  5220. }
  5221. let m;
  5222. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5223. // rgb / hsl
  5224. let color;
  5225. const name = m[ 1 ];
  5226. const components = m[ 2 ];
  5227. switch ( name ) {
  5228. case 'rgb':
  5229. case 'rgba':
  5230. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5231. // rgb(255,0,0) rgba(255,0,0,0.5)
  5232. handleAlpha( color[ 4 ] );
  5233. return this.setRGB(
  5234. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5235. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5236. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5237. colorSpace
  5238. );
  5239. }
  5240. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5241. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5242. handleAlpha( color[ 4 ] );
  5243. return this.setRGB(
  5244. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5245. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5246. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5247. colorSpace
  5248. );
  5249. }
  5250. break;
  5251. case 'hsl':
  5252. case 'hsla':
  5253. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5254. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5255. handleAlpha( color[ 4 ] );
  5256. return this.setHSL(
  5257. parseFloat( color[ 1 ] ) / 360,
  5258. parseFloat( color[ 2 ] ) / 100,
  5259. parseFloat( color[ 3 ] ) / 100,
  5260. colorSpace
  5261. );
  5262. }
  5263. break;
  5264. default:
  5265. console.warn( 'THREE.Color: Unknown color model ' + style );
  5266. }
  5267. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5268. // hex color
  5269. const hex = m[ 1 ];
  5270. const size = hex.length;
  5271. if ( size === 3 ) {
  5272. // #ff0
  5273. return this.setRGB(
  5274. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5275. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5276. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5277. colorSpace
  5278. );
  5279. } else if ( size === 6 ) {
  5280. // #ff0000
  5281. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5282. } else {
  5283. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5284. }
  5285. } else if ( style && style.length > 0 ) {
  5286. return this.setColorName( style, colorSpace );
  5287. }
  5288. return this;
  5289. }
  5290. setColorName( style, colorSpace = SRGBColorSpace ) {
  5291. // color keywords
  5292. const hex = _colorKeywords[ style.toLowerCase() ];
  5293. if ( hex !== undefined ) {
  5294. // red
  5295. this.setHex( hex, colorSpace );
  5296. } else {
  5297. // unknown color
  5298. console.warn( 'THREE.Color: Unknown color ' + style );
  5299. }
  5300. return this;
  5301. }
  5302. clone() {
  5303. return new this.constructor( this.r, this.g, this.b );
  5304. }
  5305. copy( color ) {
  5306. this.r = color.r;
  5307. this.g = color.g;
  5308. this.b = color.b;
  5309. return this;
  5310. }
  5311. copySRGBToLinear( color ) {
  5312. this.r = SRGBToLinear( color.r );
  5313. this.g = SRGBToLinear( color.g );
  5314. this.b = SRGBToLinear( color.b );
  5315. return this;
  5316. }
  5317. copyLinearToSRGB( color ) {
  5318. this.r = LinearToSRGB( color.r );
  5319. this.g = LinearToSRGB( color.g );
  5320. this.b = LinearToSRGB( color.b );
  5321. return this;
  5322. }
  5323. convertSRGBToLinear() {
  5324. this.copySRGBToLinear( this );
  5325. return this;
  5326. }
  5327. convertLinearToSRGB() {
  5328. this.copyLinearToSRGB( this );
  5329. return this;
  5330. }
  5331. getHex( colorSpace = SRGBColorSpace ) {
  5332. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5333. 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 ) );
  5334. }
  5335. getHexString( colorSpace = SRGBColorSpace ) {
  5336. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5337. }
  5338. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5339. // h,s,l ranges are in 0.0 - 1.0
  5340. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5341. const r = _color.r, g = _color.g, b = _color.b;
  5342. const max = Math.max( r, g, b );
  5343. const min = Math.min( r, g, b );
  5344. let hue, saturation;
  5345. const lightness = ( min + max ) / 2.0;
  5346. if ( min === max ) {
  5347. hue = 0;
  5348. saturation = 0;
  5349. } else {
  5350. const delta = max - min;
  5351. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5352. switch ( max ) {
  5353. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5354. case g: hue = ( b - r ) / delta + 2; break;
  5355. case b: hue = ( r - g ) / delta + 4; break;
  5356. }
  5357. hue /= 6;
  5358. }
  5359. target.h = hue;
  5360. target.s = saturation;
  5361. target.l = lightness;
  5362. return target;
  5363. }
  5364. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5365. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5366. target.r = _color.r;
  5367. target.g = _color.g;
  5368. target.b = _color.b;
  5369. return target;
  5370. }
  5371. getStyle( colorSpace = SRGBColorSpace ) {
  5372. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5373. const r = _color.r, g = _color.g, b = _color.b;
  5374. if ( colorSpace !== SRGBColorSpace ) {
  5375. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5376. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5377. }
  5378. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5379. }
  5380. offsetHSL( h, s, l ) {
  5381. this.getHSL( _hslA );
  5382. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5383. }
  5384. add( color ) {
  5385. this.r += color.r;
  5386. this.g += color.g;
  5387. this.b += color.b;
  5388. return this;
  5389. }
  5390. addColors( color1, color2 ) {
  5391. this.r = color1.r + color2.r;
  5392. this.g = color1.g + color2.g;
  5393. this.b = color1.b + color2.b;
  5394. return this;
  5395. }
  5396. addScalar( s ) {
  5397. this.r += s;
  5398. this.g += s;
  5399. this.b += s;
  5400. return this;
  5401. }
  5402. sub( color ) {
  5403. this.r = Math.max( 0, this.r - color.r );
  5404. this.g = Math.max( 0, this.g - color.g );
  5405. this.b = Math.max( 0, this.b - color.b );
  5406. return this;
  5407. }
  5408. multiply( color ) {
  5409. this.r *= color.r;
  5410. this.g *= color.g;
  5411. this.b *= color.b;
  5412. return this;
  5413. }
  5414. multiplyScalar( s ) {
  5415. this.r *= s;
  5416. this.g *= s;
  5417. this.b *= s;
  5418. return this;
  5419. }
  5420. lerp( color, alpha ) {
  5421. this.r += ( color.r - this.r ) * alpha;
  5422. this.g += ( color.g - this.g ) * alpha;
  5423. this.b += ( color.b - this.b ) * alpha;
  5424. return this;
  5425. }
  5426. lerpColors( color1, color2, alpha ) {
  5427. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5428. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5429. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5430. return this;
  5431. }
  5432. lerpHSL( color, alpha ) {
  5433. this.getHSL( _hslA );
  5434. color.getHSL( _hslB );
  5435. const h = lerp( _hslA.h, _hslB.h, alpha );
  5436. const s = lerp( _hslA.s, _hslB.s, alpha );
  5437. const l = lerp( _hslA.l, _hslB.l, alpha );
  5438. this.setHSL( h, s, l );
  5439. return this;
  5440. }
  5441. setFromVector3( v ) {
  5442. this.r = v.x;
  5443. this.g = v.y;
  5444. this.b = v.z;
  5445. return this;
  5446. }
  5447. applyMatrix3( m ) {
  5448. const r = this.r, g = this.g, b = this.b;
  5449. const e = m.elements;
  5450. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5451. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5452. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5453. return this;
  5454. }
  5455. equals( c ) {
  5456. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5457. }
  5458. fromArray( array, offset = 0 ) {
  5459. this.r = array[ offset ];
  5460. this.g = array[ offset + 1 ];
  5461. this.b = array[ offset + 2 ];
  5462. return this;
  5463. }
  5464. toArray( array = [], offset = 0 ) {
  5465. array[ offset ] = this.r;
  5466. array[ offset + 1 ] = this.g;
  5467. array[ offset + 2 ] = this.b;
  5468. return array;
  5469. }
  5470. fromBufferAttribute( attribute, index ) {
  5471. this.r = attribute.getX( index );
  5472. this.g = attribute.getY( index );
  5473. this.b = attribute.getZ( index );
  5474. return this;
  5475. }
  5476. toJSON() {
  5477. return this.getHex();
  5478. }
  5479. *[ Symbol.iterator ]() {
  5480. yield this.r;
  5481. yield this.g;
  5482. yield this.b;
  5483. }
  5484. }
  5485. const _color = /*@__PURE__*/ new Color();
  5486. Color.NAMES = _colorKeywords;
  5487. let _materialId = 0;
  5488. class Material extends EventDispatcher {
  5489. static get type() {
  5490. return 'Material';
  5491. }
  5492. get type() {
  5493. return this.constructor.type;
  5494. }
  5495. set type( _value ) { /* */ }
  5496. constructor() {
  5497. super();
  5498. this.isMaterial = true;
  5499. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5500. this.uuid = generateUUID();
  5501. this.name = '';
  5502. this.blending = NormalBlending;
  5503. this.side = FrontSide;
  5504. this.vertexColors = false;
  5505. this.opacity = 1;
  5506. this.transparent = false;
  5507. this.alphaHash = false;
  5508. this.blendSrc = SrcAlphaFactor;
  5509. this.blendDst = OneMinusSrcAlphaFactor;
  5510. this.blendEquation = AddEquation;
  5511. this.blendSrcAlpha = null;
  5512. this.blendDstAlpha = null;
  5513. this.blendEquationAlpha = null;
  5514. this.blendColor = new Color( 0, 0, 0 );
  5515. this.blendAlpha = 0;
  5516. this.depthFunc = LessEqualDepth;
  5517. this.depthTest = true;
  5518. this.depthWrite = true;
  5519. this.stencilWriteMask = 0xff;
  5520. this.stencilFunc = AlwaysStencilFunc;
  5521. this.stencilRef = 0;
  5522. this.stencilFuncMask = 0xff;
  5523. this.stencilFail = KeepStencilOp;
  5524. this.stencilZFail = KeepStencilOp;
  5525. this.stencilZPass = KeepStencilOp;
  5526. this.stencilWrite = false;
  5527. this.clippingPlanes = null;
  5528. this.clipIntersection = false;
  5529. this.clipShadows = false;
  5530. this.shadowSide = null;
  5531. this.colorWrite = true;
  5532. this.precision = null; // override the renderer's default precision for this material
  5533. this.polygonOffset = false;
  5534. this.polygonOffsetFactor = 0;
  5535. this.polygonOffsetUnits = 0;
  5536. this.dithering = false;
  5537. this.alphaToCoverage = false;
  5538. this.premultipliedAlpha = false;
  5539. this.forceSinglePass = false;
  5540. this.visible = true;
  5541. this.toneMapped = true;
  5542. this.userData = {};
  5543. this.version = 0;
  5544. this._alphaTest = 0;
  5545. }
  5546. get alphaTest() {
  5547. return this._alphaTest;
  5548. }
  5549. set alphaTest( value ) {
  5550. if ( this._alphaTest > 0 !== value > 0 ) {
  5551. this.version ++;
  5552. }
  5553. this._alphaTest = value;
  5554. }
  5555. // onBeforeRender and onBeforeCompile only supported in WebGLRenderer
  5556. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5557. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5558. customProgramCacheKey() {
  5559. return this.onBeforeCompile.toString();
  5560. }
  5561. setValues( values ) {
  5562. if ( values === undefined ) return;
  5563. for ( const key in values ) {
  5564. const newValue = values[ key ];
  5565. if ( newValue === undefined ) {
  5566. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5567. continue;
  5568. }
  5569. const currentValue = this[ key ];
  5570. if ( currentValue === undefined ) {
  5571. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5572. continue;
  5573. }
  5574. if ( currentValue && currentValue.isColor ) {
  5575. currentValue.set( newValue );
  5576. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5577. currentValue.copy( newValue );
  5578. } else {
  5579. this[ key ] = newValue;
  5580. }
  5581. }
  5582. }
  5583. toJSON( meta ) {
  5584. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5585. if ( isRootObject ) {
  5586. meta = {
  5587. textures: {},
  5588. images: {}
  5589. };
  5590. }
  5591. const data = {
  5592. metadata: {
  5593. version: 4.6,
  5594. type: 'Material',
  5595. generator: 'Material.toJSON'
  5596. }
  5597. };
  5598. // standard Material serialization
  5599. data.uuid = this.uuid;
  5600. data.type = this.type;
  5601. if ( this.name !== '' ) data.name = this.name;
  5602. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5603. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5604. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5605. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5606. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5607. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5608. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5609. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5610. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5611. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5612. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5613. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5614. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5615. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5616. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5617. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5618. }
  5619. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5620. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5621. }
  5622. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5623. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5624. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5625. }
  5626. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5627. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5628. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5629. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5630. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5631. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5632. }
  5633. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5634. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5635. }
  5636. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5637. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5638. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5639. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5640. }
  5641. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5642. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5643. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5644. if ( this.lightMap && this.lightMap.isTexture ) {
  5645. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5646. data.lightMapIntensity = this.lightMapIntensity;
  5647. }
  5648. if ( this.aoMap && this.aoMap.isTexture ) {
  5649. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5650. data.aoMapIntensity = this.aoMapIntensity;
  5651. }
  5652. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5653. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5654. data.bumpScale = this.bumpScale;
  5655. }
  5656. if ( this.normalMap && this.normalMap.isTexture ) {
  5657. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5658. data.normalMapType = this.normalMapType;
  5659. data.normalScale = this.normalScale.toArray();
  5660. }
  5661. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5662. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5663. data.displacementScale = this.displacementScale;
  5664. data.displacementBias = this.displacementBias;
  5665. }
  5666. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5667. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5668. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5669. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5670. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5671. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5672. if ( this.envMap && this.envMap.isTexture ) {
  5673. data.envMap = this.envMap.toJSON( meta ).uuid;
  5674. if ( this.combine !== undefined ) data.combine = this.combine;
  5675. }
  5676. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5677. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5678. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5679. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5680. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5681. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5682. }
  5683. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5684. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5685. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5686. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5687. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5688. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5689. if ( this.size !== undefined ) data.size = this.size;
  5690. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5691. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5692. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5693. if ( this.side !== FrontSide ) data.side = this.side;
  5694. if ( this.vertexColors === true ) data.vertexColors = true;
  5695. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5696. if ( this.transparent === true ) data.transparent = true;
  5697. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5698. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5699. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5700. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5701. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5702. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5703. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5704. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5705. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5706. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5707. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5708. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5709. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5710. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5711. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5712. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5713. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5714. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5715. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5716. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5717. // rotation (SpriteMaterial)
  5718. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5719. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5720. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5721. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5722. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5723. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5724. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5725. if ( this.scale !== undefined ) data.scale = this.scale;
  5726. if ( this.dithering === true ) data.dithering = true;
  5727. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5728. if ( this.alphaHash === true ) data.alphaHash = true;
  5729. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5730. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5731. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5732. if ( this.wireframe === true ) data.wireframe = true;
  5733. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5734. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5735. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5736. if ( this.flatShading === true ) data.flatShading = true;
  5737. if ( this.visible === false ) data.visible = false;
  5738. if ( this.toneMapped === false ) data.toneMapped = false;
  5739. if ( this.fog === false ) data.fog = false;
  5740. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5741. // TODO: Copied from Object3D.toJSON
  5742. function extractFromCache( cache ) {
  5743. const values = [];
  5744. for ( const key in cache ) {
  5745. const data = cache[ key ];
  5746. delete data.metadata;
  5747. values.push( data );
  5748. }
  5749. return values;
  5750. }
  5751. if ( isRootObject ) {
  5752. const textures = extractFromCache( meta.textures );
  5753. const images = extractFromCache( meta.images );
  5754. if ( textures.length > 0 ) data.textures = textures;
  5755. if ( images.length > 0 ) data.images = images;
  5756. }
  5757. return data;
  5758. }
  5759. clone() {
  5760. return new this.constructor().copy( this );
  5761. }
  5762. copy( source ) {
  5763. this.name = source.name;
  5764. this.blending = source.blending;
  5765. this.side = source.side;
  5766. this.vertexColors = source.vertexColors;
  5767. this.opacity = source.opacity;
  5768. this.transparent = source.transparent;
  5769. this.blendSrc = source.blendSrc;
  5770. this.blendDst = source.blendDst;
  5771. this.blendEquation = source.blendEquation;
  5772. this.blendSrcAlpha = source.blendSrcAlpha;
  5773. this.blendDstAlpha = source.blendDstAlpha;
  5774. this.blendEquationAlpha = source.blendEquationAlpha;
  5775. this.blendColor.copy( source.blendColor );
  5776. this.blendAlpha = source.blendAlpha;
  5777. this.depthFunc = source.depthFunc;
  5778. this.depthTest = source.depthTest;
  5779. this.depthWrite = source.depthWrite;
  5780. this.stencilWriteMask = source.stencilWriteMask;
  5781. this.stencilFunc = source.stencilFunc;
  5782. this.stencilRef = source.stencilRef;
  5783. this.stencilFuncMask = source.stencilFuncMask;
  5784. this.stencilFail = source.stencilFail;
  5785. this.stencilZFail = source.stencilZFail;
  5786. this.stencilZPass = source.stencilZPass;
  5787. this.stencilWrite = source.stencilWrite;
  5788. const srcPlanes = source.clippingPlanes;
  5789. let dstPlanes = null;
  5790. if ( srcPlanes !== null ) {
  5791. const n = srcPlanes.length;
  5792. dstPlanes = new Array( n );
  5793. for ( let i = 0; i !== n; ++ i ) {
  5794. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5795. }
  5796. }
  5797. this.clippingPlanes = dstPlanes;
  5798. this.clipIntersection = source.clipIntersection;
  5799. this.clipShadows = source.clipShadows;
  5800. this.shadowSide = source.shadowSide;
  5801. this.colorWrite = source.colorWrite;
  5802. this.precision = source.precision;
  5803. this.polygonOffset = source.polygonOffset;
  5804. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5805. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5806. this.dithering = source.dithering;
  5807. this.alphaTest = source.alphaTest;
  5808. this.alphaHash = source.alphaHash;
  5809. this.alphaToCoverage = source.alphaToCoverage;
  5810. this.premultipliedAlpha = source.premultipliedAlpha;
  5811. this.forceSinglePass = source.forceSinglePass;
  5812. this.visible = source.visible;
  5813. this.toneMapped = source.toneMapped;
  5814. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5815. return this;
  5816. }
  5817. dispose() {
  5818. this.dispatchEvent( { type: 'dispose' } );
  5819. }
  5820. set needsUpdate( value ) {
  5821. if ( value === true ) this.version ++;
  5822. }
  5823. onBuild( /* shaderobject, renderer */ ) {
  5824. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5825. }
  5826. }
  5827. class MeshBasicMaterial extends Material {
  5828. static get type() {
  5829. return 'MeshBasicMaterial';
  5830. }
  5831. constructor( parameters ) {
  5832. super();
  5833. this.isMeshBasicMaterial = true;
  5834. this.color = new Color( 0xffffff ); // emissive
  5835. this.map = null;
  5836. this.lightMap = null;
  5837. this.lightMapIntensity = 1.0;
  5838. this.aoMap = null;
  5839. this.aoMapIntensity = 1.0;
  5840. this.specularMap = null;
  5841. this.alphaMap = null;
  5842. this.envMap = null;
  5843. this.envMapRotation = new Euler();
  5844. this.combine = MultiplyOperation;
  5845. this.reflectivity = 1;
  5846. this.refractionRatio = 0.98;
  5847. this.wireframe = false;
  5848. this.wireframeLinewidth = 1;
  5849. this.wireframeLinecap = 'round';
  5850. this.wireframeLinejoin = 'round';
  5851. this.fog = true;
  5852. this.setValues( parameters );
  5853. }
  5854. copy( source ) {
  5855. super.copy( source );
  5856. this.color.copy( source.color );
  5857. this.map = source.map;
  5858. this.lightMap = source.lightMap;
  5859. this.lightMapIntensity = source.lightMapIntensity;
  5860. this.aoMap = source.aoMap;
  5861. this.aoMapIntensity = source.aoMapIntensity;
  5862. this.specularMap = source.specularMap;
  5863. this.alphaMap = source.alphaMap;
  5864. this.envMap = source.envMap;
  5865. this.envMapRotation.copy( source.envMapRotation );
  5866. this.combine = source.combine;
  5867. this.reflectivity = source.reflectivity;
  5868. this.refractionRatio = source.refractionRatio;
  5869. this.wireframe = source.wireframe;
  5870. this.wireframeLinewidth = source.wireframeLinewidth;
  5871. this.wireframeLinecap = source.wireframeLinecap;
  5872. this.wireframeLinejoin = source.wireframeLinejoin;
  5873. this.fog = source.fog;
  5874. return this;
  5875. }
  5876. }
  5877. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5878. const _tables = /*@__PURE__*/ _generateTables();
  5879. function _generateTables() {
  5880. // float32 to float16 helpers
  5881. const buffer = new ArrayBuffer( 4 );
  5882. const floatView = new Float32Array( buffer );
  5883. const uint32View = new Uint32Array( buffer );
  5884. const baseTable = new Uint32Array( 512 );
  5885. const shiftTable = new Uint32Array( 512 );
  5886. for ( let i = 0; i < 256; ++ i ) {
  5887. const e = i - 127;
  5888. // very small number (0, -0)
  5889. if ( e < - 27 ) {
  5890. baseTable[ i ] = 0x0000;
  5891. baseTable[ i | 0x100 ] = 0x8000;
  5892. shiftTable[ i ] = 24;
  5893. shiftTable[ i | 0x100 ] = 24;
  5894. // small number (denorm)
  5895. } else if ( e < - 14 ) {
  5896. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5897. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5898. shiftTable[ i ] = - e - 1;
  5899. shiftTable[ i | 0x100 ] = - e - 1;
  5900. // normal number
  5901. } else if ( e <= 15 ) {
  5902. baseTable[ i ] = ( e + 15 ) << 10;
  5903. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5904. shiftTable[ i ] = 13;
  5905. shiftTable[ i | 0x100 ] = 13;
  5906. // large number (Infinity, -Infinity)
  5907. } else if ( e < 128 ) {
  5908. baseTable[ i ] = 0x7c00;
  5909. baseTable[ i | 0x100 ] = 0xfc00;
  5910. shiftTable[ i ] = 24;
  5911. shiftTable[ i | 0x100 ] = 24;
  5912. // stay (NaN, Infinity, -Infinity)
  5913. } else {
  5914. baseTable[ i ] = 0x7c00;
  5915. baseTable[ i | 0x100 ] = 0xfc00;
  5916. shiftTable[ i ] = 13;
  5917. shiftTable[ i | 0x100 ] = 13;
  5918. }
  5919. }
  5920. // float16 to float32 helpers
  5921. const mantissaTable = new Uint32Array( 2048 );
  5922. const exponentTable = new Uint32Array( 64 );
  5923. const offsetTable = new Uint32Array( 64 );
  5924. for ( let i = 1; i < 1024; ++ i ) {
  5925. let m = i << 13; // zero pad mantissa bits
  5926. let e = 0; // zero exponent
  5927. // normalized
  5928. while ( ( m & 0x00800000 ) === 0 ) {
  5929. m <<= 1;
  5930. e -= 0x00800000; // decrement exponent
  5931. }
  5932. m &= ~ 0x00800000; // clear leading 1 bit
  5933. e += 0x38800000; // adjust bias
  5934. mantissaTable[ i ] = m | e;
  5935. }
  5936. for ( let i = 1024; i < 2048; ++ i ) {
  5937. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5938. }
  5939. for ( let i = 1; i < 31; ++ i ) {
  5940. exponentTable[ i ] = i << 23;
  5941. }
  5942. exponentTable[ 31 ] = 0x47800000;
  5943. exponentTable[ 32 ] = 0x80000000;
  5944. for ( let i = 33; i < 63; ++ i ) {
  5945. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5946. }
  5947. exponentTable[ 63 ] = 0xc7800000;
  5948. for ( let i = 1; i < 64; ++ i ) {
  5949. if ( i !== 32 ) {
  5950. offsetTable[ i ] = 1024;
  5951. }
  5952. }
  5953. return {
  5954. floatView: floatView,
  5955. uint32View: uint32View,
  5956. baseTable: baseTable,
  5957. shiftTable: shiftTable,
  5958. mantissaTable: mantissaTable,
  5959. exponentTable: exponentTable,
  5960. offsetTable: offsetTable
  5961. };
  5962. }
  5963. // float32 to float16
  5964. function toHalfFloat( val ) {
  5965. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5966. val = clamp$1( val, - 65504, 65504 );
  5967. _tables.floatView[ 0 ] = val;
  5968. const f = _tables.uint32View[ 0 ];
  5969. const e = ( f >> 23 ) & 0x1ff;
  5970. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5971. }
  5972. // float16 to float32
  5973. function fromHalfFloat( val ) {
  5974. const m = val >> 10;
  5975. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5976. return _tables.floatView[ 0 ];
  5977. }
  5978. const DataUtils = {
  5979. toHalfFloat: toHalfFloat,
  5980. fromHalfFloat: fromHalfFloat,
  5981. };
  5982. const _vector$9 = /*@__PURE__*/ new Vector3();
  5983. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5984. class BufferAttribute {
  5985. constructor( array, itemSize, normalized = false ) {
  5986. if ( Array.isArray( array ) ) {
  5987. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5988. }
  5989. this.isBufferAttribute = true;
  5990. this.name = '';
  5991. this.array = array;
  5992. this.itemSize = itemSize;
  5993. this.count = array !== undefined ? array.length / itemSize : 0;
  5994. this.normalized = normalized;
  5995. this.usage = StaticDrawUsage;
  5996. this.updateRanges = [];
  5997. this.gpuType = FloatType;
  5998. this.version = 0;
  5999. }
  6000. onUploadCallback() {}
  6001. set needsUpdate( value ) {
  6002. if ( value === true ) this.version ++;
  6003. }
  6004. setUsage( value ) {
  6005. this.usage = value;
  6006. return this;
  6007. }
  6008. addUpdateRange( start, count ) {
  6009. this.updateRanges.push( { start, count } );
  6010. }
  6011. clearUpdateRanges() {
  6012. this.updateRanges.length = 0;
  6013. }
  6014. copy( source ) {
  6015. this.name = source.name;
  6016. this.array = new source.array.constructor( source.array );
  6017. this.itemSize = source.itemSize;
  6018. this.count = source.count;
  6019. this.normalized = source.normalized;
  6020. this.usage = source.usage;
  6021. this.gpuType = source.gpuType;
  6022. return this;
  6023. }
  6024. copyAt( index1, attribute, index2 ) {
  6025. index1 *= this.itemSize;
  6026. index2 *= attribute.itemSize;
  6027. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  6028. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  6029. }
  6030. return this;
  6031. }
  6032. copyArray( array ) {
  6033. this.array.set( array );
  6034. return this;
  6035. }
  6036. applyMatrix3( m ) {
  6037. if ( this.itemSize === 2 ) {
  6038. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6039. _vector2$1.fromBufferAttribute( this, i );
  6040. _vector2$1.applyMatrix3( m );
  6041. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6042. }
  6043. } else if ( this.itemSize === 3 ) {
  6044. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6045. _vector$9.fromBufferAttribute( this, i );
  6046. _vector$9.applyMatrix3( m );
  6047. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6048. }
  6049. }
  6050. return this;
  6051. }
  6052. applyMatrix4( m ) {
  6053. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6054. _vector$9.fromBufferAttribute( this, i );
  6055. _vector$9.applyMatrix4( m );
  6056. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6057. }
  6058. return this;
  6059. }
  6060. applyNormalMatrix( m ) {
  6061. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6062. _vector$9.fromBufferAttribute( this, i );
  6063. _vector$9.applyNormalMatrix( m );
  6064. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6065. }
  6066. return this;
  6067. }
  6068. transformDirection( m ) {
  6069. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6070. _vector$9.fromBufferAttribute( this, i );
  6071. _vector$9.transformDirection( m );
  6072. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6073. }
  6074. return this;
  6075. }
  6076. set( value, offset = 0 ) {
  6077. // Matching BufferAttribute constructor, do not normalize the array.
  6078. this.array.set( value, offset );
  6079. return this;
  6080. }
  6081. getComponent( index, component ) {
  6082. let value = this.array[ index * this.itemSize + component ];
  6083. if ( this.normalized ) value = denormalize( value, this.array );
  6084. return value;
  6085. }
  6086. setComponent( index, component, value ) {
  6087. if ( this.normalized ) value = normalize$1( value, this.array );
  6088. this.array[ index * this.itemSize + component ] = value;
  6089. return this;
  6090. }
  6091. getX( index ) {
  6092. let x = this.array[ index * this.itemSize ];
  6093. if ( this.normalized ) x = denormalize( x, this.array );
  6094. return x;
  6095. }
  6096. setX( index, x ) {
  6097. if ( this.normalized ) x = normalize$1( x, this.array );
  6098. this.array[ index * this.itemSize ] = x;
  6099. return this;
  6100. }
  6101. getY( index ) {
  6102. let y = this.array[ index * this.itemSize + 1 ];
  6103. if ( this.normalized ) y = denormalize( y, this.array );
  6104. return y;
  6105. }
  6106. setY( index, y ) {
  6107. if ( this.normalized ) y = normalize$1( y, this.array );
  6108. this.array[ index * this.itemSize + 1 ] = y;
  6109. return this;
  6110. }
  6111. getZ( index ) {
  6112. let z = this.array[ index * this.itemSize + 2 ];
  6113. if ( this.normalized ) z = denormalize( z, this.array );
  6114. return z;
  6115. }
  6116. setZ( index, z ) {
  6117. if ( this.normalized ) z = normalize$1( z, this.array );
  6118. this.array[ index * this.itemSize + 2 ] = z;
  6119. return this;
  6120. }
  6121. getW( index ) {
  6122. let w = this.array[ index * this.itemSize + 3 ];
  6123. if ( this.normalized ) w = denormalize( w, this.array );
  6124. return w;
  6125. }
  6126. setW( index, w ) {
  6127. if ( this.normalized ) w = normalize$1( w, this.array );
  6128. this.array[ index * this.itemSize + 3 ] = w;
  6129. return this;
  6130. }
  6131. setXY( index, x, y ) {
  6132. index *= this.itemSize;
  6133. if ( this.normalized ) {
  6134. x = normalize$1( x, this.array );
  6135. y = normalize$1( y, this.array );
  6136. }
  6137. this.array[ index + 0 ] = x;
  6138. this.array[ index + 1 ] = y;
  6139. return this;
  6140. }
  6141. setXYZ( index, x, y, z ) {
  6142. index *= this.itemSize;
  6143. if ( this.normalized ) {
  6144. x = normalize$1( x, this.array );
  6145. y = normalize$1( y, this.array );
  6146. z = normalize$1( z, this.array );
  6147. }
  6148. this.array[ index + 0 ] = x;
  6149. this.array[ index + 1 ] = y;
  6150. this.array[ index + 2 ] = z;
  6151. return this;
  6152. }
  6153. setXYZW( index, x, y, z, w ) {
  6154. index *= this.itemSize;
  6155. if ( this.normalized ) {
  6156. x = normalize$1( x, this.array );
  6157. y = normalize$1( y, this.array );
  6158. z = normalize$1( z, this.array );
  6159. w = normalize$1( w, this.array );
  6160. }
  6161. this.array[ index + 0 ] = x;
  6162. this.array[ index + 1 ] = y;
  6163. this.array[ index + 2 ] = z;
  6164. this.array[ index + 3 ] = w;
  6165. return this;
  6166. }
  6167. onUpload( callback ) {
  6168. this.onUploadCallback = callback;
  6169. return this;
  6170. }
  6171. clone() {
  6172. return new this.constructor( this.array, this.itemSize ).copy( this );
  6173. }
  6174. toJSON() {
  6175. const data = {
  6176. itemSize: this.itemSize,
  6177. type: this.array.constructor.name,
  6178. array: Array.from( this.array ),
  6179. normalized: this.normalized
  6180. };
  6181. if ( this.name !== '' ) data.name = this.name;
  6182. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6183. return data;
  6184. }
  6185. }
  6186. //
  6187. class Int8BufferAttribute extends BufferAttribute {
  6188. constructor( array, itemSize, normalized ) {
  6189. super( new Int8Array( array ), itemSize, normalized );
  6190. }
  6191. }
  6192. class Uint8BufferAttribute extends BufferAttribute {
  6193. constructor( array, itemSize, normalized ) {
  6194. super( new Uint8Array( array ), itemSize, normalized );
  6195. }
  6196. }
  6197. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6198. constructor( array, itemSize, normalized ) {
  6199. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6200. }
  6201. }
  6202. class Int16BufferAttribute extends BufferAttribute {
  6203. constructor( array, itemSize, normalized ) {
  6204. super( new Int16Array( array ), itemSize, normalized );
  6205. }
  6206. }
  6207. class Uint16BufferAttribute extends BufferAttribute {
  6208. constructor( array, itemSize, normalized ) {
  6209. super( new Uint16Array( array ), itemSize, normalized );
  6210. }
  6211. }
  6212. class Int32BufferAttribute extends BufferAttribute {
  6213. constructor( array, itemSize, normalized ) {
  6214. super( new Int32Array( array ), itemSize, normalized );
  6215. }
  6216. }
  6217. class Uint32BufferAttribute extends BufferAttribute {
  6218. constructor( array, itemSize, normalized ) {
  6219. super( new Uint32Array( array ), itemSize, normalized );
  6220. }
  6221. }
  6222. class Float16BufferAttribute extends BufferAttribute {
  6223. constructor( array, itemSize, normalized ) {
  6224. super( new Uint16Array( array ), itemSize, normalized );
  6225. this.isFloat16BufferAttribute = true;
  6226. }
  6227. getX( index ) {
  6228. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6229. if ( this.normalized ) x = denormalize( x, this.array );
  6230. return x;
  6231. }
  6232. setX( index, x ) {
  6233. if ( this.normalized ) x = normalize$1( x, this.array );
  6234. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6235. return this;
  6236. }
  6237. getY( index ) {
  6238. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6239. if ( this.normalized ) y = denormalize( y, this.array );
  6240. return y;
  6241. }
  6242. setY( index, y ) {
  6243. if ( this.normalized ) y = normalize$1( y, this.array );
  6244. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6245. return this;
  6246. }
  6247. getZ( index ) {
  6248. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6249. if ( this.normalized ) z = denormalize( z, this.array );
  6250. return z;
  6251. }
  6252. setZ( index, z ) {
  6253. if ( this.normalized ) z = normalize$1( z, this.array );
  6254. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6255. return this;
  6256. }
  6257. getW( index ) {
  6258. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6259. if ( this.normalized ) w = denormalize( w, this.array );
  6260. return w;
  6261. }
  6262. setW( index, w ) {
  6263. if ( this.normalized ) w = normalize$1( w, this.array );
  6264. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6265. return this;
  6266. }
  6267. setXY( index, x, y ) {
  6268. index *= this.itemSize;
  6269. if ( this.normalized ) {
  6270. x = normalize$1( x, this.array );
  6271. y = normalize$1( y, this.array );
  6272. }
  6273. this.array[ index + 0 ] = toHalfFloat( x );
  6274. this.array[ index + 1 ] = toHalfFloat( y );
  6275. return this;
  6276. }
  6277. setXYZ( index, x, y, z ) {
  6278. index *= this.itemSize;
  6279. if ( this.normalized ) {
  6280. x = normalize$1( x, this.array );
  6281. y = normalize$1( y, this.array );
  6282. z = normalize$1( z, this.array );
  6283. }
  6284. this.array[ index + 0 ] = toHalfFloat( x );
  6285. this.array[ index + 1 ] = toHalfFloat( y );
  6286. this.array[ index + 2 ] = toHalfFloat( z );
  6287. return this;
  6288. }
  6289. setXYZW( index, x, y, z, w ) {
  6290. index *= this.itemSize;
  6291. if ( this.normalized ) {
  6292. x = normalize$1( x, this.array );
  6293. y = normalize$1( y, this.array );
  6294. z = normalize$1( z, this.array );
  6295. w = normalize$1( w, this.array );
  6296. }
  6297. this.array[ index + 0 ] = toHalfFloat( x );
  6298. this.array[ index + 1 ] = toHalfFloat( y );
  6299. this.array[ index + 2 ] = toHalfFloat( z );
  6300. this.array[ index + 3 ] = toHalfFloat( w );
  6301. return this;
  6302. }
  6303. }
  6304. class Float32BufferAttribute extends BufferAttribute {
  6305. constructor( array, itemSize, normalized ) {
  6306. super( new Float32Array( array ), itemSize, normalized );
  6307. }
  6308. }
  6309. let _id$9 = 0;
  6310. const _m1$1 = /*@__PURE__*/ new Matrix4();
  6311. const _obj = /*@__PURE__*/ new Object3D();
  6312. const _offset = /*@__PURE__*/ new Vector3();
  6313. const _box$2 = /*@__PURE__*/ new Box3();
  6314. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6315. const _vector$8 = /*@__PURE__*/ new Vector3();
  6316. class BufferGeometry extends EventDispatcher {
  6317. constructor() {
  6318. super();
  6319. this.isBufferGeometry = true;
  6320. Object.defineProperty( this, 'id', { value: _id$9 ++ } );
  6321. this.uuid = generateUUID();
  6322. this.name = '';
  6323. this.type = 'BufferGeometry';
  6324. this.index = null;
  6325. this.indirect = null;
  6326. this.attributes = {};
  6327. this.morphAttributes = {};
  6328. this.morphTargetsRelative = false;
  6329. this.groups = [];
  6330. this.boundingBox = null;
  6331. this.boundingSphere = null;
  6332. this.drawRange = { start: 0, count: Infinity };
  6333. this.userData = {};
  6334. }
  6335. getIndex() {
  6336. return this.index;
  6337. }
  6338. setIndex( index ) {
  6339. if ( Array.isArray( index ) ) {
  6340. this.index = new ( arrayNeedsUint32$1( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6341. } else {
  6342. this.index = index;
  6343. }
  6344. return this;
  6345. }
  6346. setIndirect( indirect ) {
  6347. this.indirect = indirect;
  6348. return this;
  6349. }
  6350. getIndirect() {
  6351. return this.indirect;
  6352. }
  6353. getAttribute( name ) {
  6354. return this.attributes[ name ];
  6355. }
  6356. setAttribute( name, attribute ) {
  6357. this.attributes[ name ] = attribute;
  6358. return this;
  6359. }
  6360. deleteAttribute( name ) {
  6361. delete this.attributes[ name ];
  6362. return this;
  6363. }
  6364. hasAttribute( name ) {
  6365. return this.attributes[ name ] !== undefined;
  6366. }
  6367. addGroup( start, count, materialIndex = 0 ) {
  6368. this.groups.push( {
  6369. start: start,
  6370. count: count,
  6371. materialIndex: materialIndex
  6372. } );
  6373. }
  6374. clearGroups() {
  6375. this.groups = [];
  6376. }
  6377. setDrawRange( start, count ) {
  6378. this.drawRange.start = start;
  6379. this.drawRange.count = count;
  6380. }
  6381. applyMatrix4( matrix ) {
  6382. const position = this.attributes.position;
  6383. if ( position !== undefined ) {
  6384. position.applyMatrix4( matrix );
  6385. position.needsUpdate = true;
  6386. }
  6387. const normal = this.attributes.normal;
  6388. if ( normal !== undefined ) {
  6389. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6390. normal.applyNormalMatrix( normalMatrix );
  6391. normal.needsUpdate = true;
  6392. }
  6393. const tangent = this.attributes.tangent;
  6394. if ( tangent !== undefined ) {
  6395. tangent.transformDirection( matrix );
  6396. tangent.needsUpdate = true;
  6397. }
  6398. if ( this.boundingBox !== null ) {
  6399. this.computeBoundingBox();
  6400. }
  6401. if ( this.boundingSphere !== null ) {
  6402. this.computeBoundingSphere();
  6403. }
  6404. return this;
  6405. }
  6406. applyQuaternion( q ) {
  6407. _m1$1.makeRotationFromQuaternion( q );
  6408. this.applyMatrix4( _m1$1 );
  6409. return this;
  6410. }
  6411. rotateX( angle ) {
  6412. // rotate geometry around world x-axis
  6413. _m1$1.makeRotationX( angle );
  6414. this.applyMatrix4( _m1$1 );
  6415. return this;
  6416. }
  6417. rotateY( angle ) {
  6418. // rotate geometry around world y-axis
  6419. _m1$1.makeRotationY( angle );
  6420. this.applyMatrix4( _m1$1 );
  6421. return this;
  6422. }
  6423. rotateZ( angle ) {
  6424. // rotate geometry around world z-axis
  6425. _m1$1.makeRotationZ( angle );
  6426. this.applyMatrix4( _m1$1 );
  6427. return this;
  6428. }
  6429. translate( x, y, z ) {
  6430. // translate geometry
  6431. _m1$1.makeTranslation( x, y, z );
  6432. this.applyMatrix4( _m1$1 );
  6433. return this;
  6434. }
  6435. scale( x, y, z ) {
  6436. // scale geometry
  6437. _m1$1.makeScale( x, y, z );
  6438. this.applyMatrix4( _m1$1 );
  6439. return this;
  6440. }
  6441. lookAt( vector ) {
  6442. _obj.lookAt( vector );
  6443. _obj.updateMatrix();
  6444. this.applyMatrix4( _obj.matrix );
  6445. return this;
  6446. }
  6447. center() {
  6448. this.computeBoundingBox();
  6449. this.boundingBox.getCenter( _offset ).negate();
  6450. this.translate( _offset.x, _offset.y, _offset.z );
  6451. return this;
  6452. }
  6453. setFromPoints( points ) {
  6454. const positionAttribute = this.getAttribute( 'position' );
  6455. if ( positionAttribute === undefined ) {
  6456. const position = [];
  6457. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6458. const point = points[ i ];
  6459. position.push( point.x, point.y, point.z || 0 );
  6460. }
  6461. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6462. } else {
  6463. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  6464. const point = points[ i ];
  6465. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  6466. }
  6467. if ( points.length > positionAttribute.count ) {
  6468. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  6469. }
  6470. positionAttribute.needsUpdate = true;
  6471. }
  6472. return this;
  6473. }
  6474. computeBoundingBox() {
  6475. if ( this.boundingBox === null ) {
  6476. this.boundingBox = new Box3();
  6477. }
  6478. const position = this.attributes.position;
  6479. const morphAttributesPosition = this.morphAttributes.position;
  6480. if ( position && position.isGLBufferAttribute ) {
  6481. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6482. this.boundingBox.set(
  6483. new Vector3( - Infinity, - Infinity, - Infinity ),
  6484. new Vector3( + Infinity, + Infinity, + Infinity )
  6485. );
  6486. return;
  6487. }
  6488. if ( position !== undefined ) {
  6489. this.boundingBox.setFromBufferAttribute( position );
  6490. // process morph attributes if present
  6491. if ( morphAttributesPosition ) {
  6492. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6493. const morphAttribute = morphAttributesPosition[ i ];
  6494. _box$2.setFromBufferAttribute( morphAttribute );
  6495. if ( this.morphTargetsRelative ) {
  6496. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6497. this.boundingBox.expandByPoint( _vector$8 );
  6498. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6499. this.boundingBox.expandByPoint( _vector$8 );
  6500. } else {
  6501. this.boundingBox.expandByPoint( _box$2.min );
  6502. this.boundingBox.expandByPoint( _box$2.max );
  6503. }
  6504. }
  6505. }
  6506. } else {
  6507. this.boundingBox.makeEmpty();
  6508. }
  6509. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6510. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6511. }
  6512. }
  6513. computeBoundingSphere() {
  6514. if ( this.boundingSphere === null ) {
  6515. this.boundingSphere = new Sphere();
  6516. }
  6517. const position = this.attributes.position;
  6518. const morphAttributesPosition = this.morphAttributes.position;
  6519. if ( position && position.isGLBufferAttribute ) {
  6520. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6521. this.boundingSphere.set( new Vector3(), Infinity );
  6522. return;
  6523. }
  6524. if ( position ) {
  6525. // first, find the center of the bounding sphere
  6526. const center = this.boundingSphere.center;
  6527. _box$2.setFromBufferAttribute( position );
  6528. // process morph attributes if present
  6529. if ( morphAttributesPosition ) {
  6530. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6531. const morphAttribute = morphAttributesPosition[ i ];
  6532. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6533. if ( this.morphTargetsRelative ) {
  6534. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6535. _box$2.expandByPoint( _vector$8 );
  6536. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6537. _box$2.expandByPoint( _vector$8 );
  6538. } else {
  6539. _box$2.expandByPoint( _boxMorphTargets.min );
  6540. _box$2.expandByPoint( _boxMorphTargets.max );
  6541. }
  6542. }
  6543. }
  6544. _box$2.getCenter( center );
  6545. // second, try to find a boundingSphere with a radius smaller than the
  6546. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6547. let maxRadiusSq = 0;
  6548. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6549. _vector$8.fromBufferAttribute( position, i );
  6550. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6551. }
  6552. // process morph attributes if present
  6553. if ( morphAttributesPosition ) {
  6554. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6555. const morphAttribute = morphAttributesPosition[ i ];
  6556. const morphTargetsRelative = this.morphTargetsRelative;
  6557. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6558. _vector$8.fromBufferAttribute( morphAttribute, j );
  6559. if ( morphTargetsRelative ) {
  6560. _offset.fromBufferAttribute( position, j );
  6561. _vector$8.add( _offset );
  6562. }
  6563. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6564. }
  6565. }
  6566. }
  6567. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6568. if ( isNaN( this.boundingSphere.radius ) ) {
  6569. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6570. }
  6571. }
  6572. }
  6573. computeTangents() {
  6574. const index = this.index;
  6575. const attributes = this.attributes;
  6576. // based on http://www.terathon.com/code/tangent.html
  6577. // (per vertex tangents)
  6578. if ( index === null ||
  6579. attributes.position === undefined ||
  6580. attributes.normal === undefined ||
  6581. attributes.uv === undefined ) {
  6582. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6583. return;
  6584. }
  6585. const positionAttribute = attributes.position;
  6586. const normalAttribute = attributes.normal;
  6587. const uvAttribute = attributes.uv;
  6588. if ( this.hasAttribute( 'tangent' ) === false ) {
  6589. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6590. }
  6591. const tangentAttribute = this.getAttribute( 'tangent' );
  6592. const tan1 = [], tan2 = [];
  6593. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6594. tan1[ i ] = new Vector3();
  6595. tan2[ i ] = new Vector3();
  6596. }
  6597. const vA = new Vector3(),
  6598. vB = new Vector3(),
  6599. vC = new Vector3(),
  6600. uvA = new Vector2(),
  6601. uvB = new Vector2(),
  6602. uvC = new Vector2(),
  6603. sdir = new Vector3(),
  6604. tdir = new Vector3();
  6605. function handleTriangle( a, b, c ) {
  6606. vA.fromBufferAttribute( positionAttribute, a );
  6607. vB.fromBufferAttribute( positionAttribute, b );
  6608. vC.fromBufferAttribute( positionAttribute, c );
  6609. uvA.fromBufferAttribute( uvAttribute, a );
  6610. uvB.fromBufferAttribute( uvAttribute, b );
  6611. uvC.fromBufferAttribute( uvAttribute, c );
  6612. vB.sub( vA );
  6613. vC.sub( vA );
  6614. uvB.sub( uvA );
  6615. uvC.sub( uvA );
  6616. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6617. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6618. if ( ! isFinite( r ) ) return;
  6619. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6620. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6621. tan1[ a ].add( sdir );
  6622. tan1[ b ].add( sdir );
  6623. tan1[ c ].add( sdir );
  6624. tan2[ a ].add( tdir );
  6625. tan2[ b ].add( tdir );
  6626. tan2[ c ].add( tdir );
  6627. }
  6628. let groups = this.groups;
  6629. if ( groups.length === 0 ) {
  6630. groups = [ {
  6631. start: 0,
  6632. count: index.count
  6633. } ];
  6634. }
  6635. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6636. const group = groups[ i ];
  6637. const start = group.start;
  6638. const count = group.count;
  6639. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6640. handleTriangle(
  6641. index.getX( j + 0 ),
  6642. index.getX( j + 1 ),
  6643. index.getX( j + 2 )
  6644. );
  6645. }
  6646. }
  6647. const tmp = new Vector3(), tmp2 = new Vector3();
  6648. const n = new Vector3(), n2 = new Vector3();
  6649. function handleVertex( v ) {
  6650. n.fromBufferAttribute( normalAttribute, v );
  6651. n2.copy( n );
  6652. const t = tan1[ v ];
  6653. // Gram-Schmidt orthogonalize
  6654. tmp.copy( t );
  6655. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6656. // Calculate handedness
  6657. tmp2.crossVectors( n2, t );
  6658. const test = tmp2.dot( tan2[ v ] );
  6659. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6660. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6661. }
  6662. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6663. const group = groups[ i ];
  6664. const start = group.start;
  6665. const count = group.count;
  6666. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6667. handleVertex( index.getX( j + 0 ) );
  6668. handleVertex( index.getX( j + 1 ) );
  6669. handleVertex( index.getX( j + 2 ) );
  6670. }
  6671. }
  6672. }
  6673. computeVertexNormals() {
  6674. const index = this.index;
  6675. const positionAttribute = this.getAttribute( 'position' );
  6676. if ( positionAttribute !== undefined ) {
  6677. let normalAttribute = this.getAttribute( 'normal' );
  6678. if ( normalAttribute === undefined ) {
  6679. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6680. this.setAttribute( 'normal', normalAttribute );
  6681. } else {
  6682. // reset existing normals to zero
  6683. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6684. normalAttribute.setXYZ( i, 0, 0, 0 );
  6685. }
  6686. }
  6687. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6688. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6689. const cb = new Vector3(), ab = new Vector3();
  6690. // indexed elements
  6691. if ( index ) {
  6692. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6693. const vA = index.getX( i + 0 );
  6694. const vB = index.getX( i + 1 );
  6695. const vC = index.getX( i + 2 );
  6696. pA.fromBufferAttribute( positionAttribute, vA );
  6697. pB.fromBufferAttribute( positionAttribute, vB );
  6698. pC.fromBufferAttribute( positionAttribute, vC );
  6699. cb.subVectors( pC, pB );
  6700. ab.subVectors( pA, pB );
  6701. cb.cross( ab );
  6702. nA.fromBufferAttribute( normalAttribute, vA );
  6703. nB.fromBufferAttribute( normalAttribute, vB );
  6704. nC.fromBufferAttribute( normalAttribute, vC );
  6705. nA.add( cb );
  6706. nB.add( cb );
  6707. nC.add( cb );
  6708. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6709. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6710. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6711. }
  6712. } else {
  6713. // non-indexed elements (unconnected triangle soup)
  6714. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6715. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6716. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6717. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6718. cb.subVectors( pC, pB );
  6719. ab.subVectors( pA, pB );
  6720. cb.cross( ab );
  6721. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6722. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6723. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6724. }
  6725. }
  6726. this.normalizeNormals();
  6727. normalAttribute.needsUpdate = true;
  6728. }
  6729. }
  6730. normalizeNormals() {
  6731. const normals = this.attributes.normal;
  6732. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6733. _vector$8.fromBufferAttribute( normals, i );
  6734. _vector$8.normalize();
  6735. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6736. }
  6737. }
  6738. toNonIndexed() {
  6739. function convertBufferAttribute( attribute, indices ) {
  6740. const array = attribute.array;
  6741. const itemSize = attribute.itemSize;
  6742. const normalized = attribute.normalized;
  6743. const array2 = new array.constructor( indices.length * itemSize );
  6744. let index = 0, index2 = 0;
  6745. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6746. if ( attribute.isInterleavedBufferAttribute ) {
  6747. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6748. } else {
  6749. index = indices[ i ] * itemSize;
  6750. }
  6751. for ( let j = 0; j < itemSize; j ++ ) {
  6752. array2[ index2 ++ ] = array[ index ++ ];
  6753. }
  6754. }
  6755. return new BufferAttribute( array2, itemSize, normalized );
  6756. }
  6757. //
  6758. if ( this.index === null ) {
  6759. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6760. return this;
  6761. }
  6762. const geometry2 = new BufferGeometry();
  6763. const indices = this.index.array;
  6764. const attributes = this.attributes;
  6765. // attributes
  6766. for ( const name in attributes ) {
  6767. const attribute = attributes[ name ];
  6768. const newAttribute = convertBufferAttribute( attribute, indices );
  6769. geometry2.setAttribute( name, newAttribute );
  6770. }
  6771. // morph attributes
  6772. const morphAttributes = this.morphAttributes;
  6773. for ( const name in morphAttributes ) {
  6774. const morphArray = [];
  6775. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6776. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6777. const attribute = morphAttribute[ i ];
  6778. const newAttribute = convertBufferAttribute( attribute, indices );
  6779. morphArray.push( newAttribute );
  6780. }
  6781. geometry2.morphAttributes[ name ] = morphArray;
  6782. }
  6783. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6784. // groups
  6785. const groups = this.groups;
  6786. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6787. const group = groups[ i ];
  6788. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6789. }
  6790. return geometry2;
  6791. }
  6792. toJSON() {
  6793. const data = {
  6794. metadata: {
  6795. version: 4.6,
  6796. type: 'BufferGeometry',
  6797. generator: 'BufferGeometry.toJSON'
  6798. }
  6799. };
  6800. // standard BufferGeometry serialization
  6801. data.uuid = this.uuid;
  6802. data.type = this.type;
  6803. if ( this.name !== '' ) data.name = this.name;
  6804. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6805. if ( this.parameters !== undefined ) {
  6806. const parameters = this.parameters;
  6807. for ( const key in parameters ) {
  6808. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6809. }
  6810. return data;
  6811. }
  6812. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6813. data.data = { attributes: {} };
  6814. const index = this.index;
  6815. if ( index !== null ) {
  6816. data.data.index = {
  6817. type: index.array.constructor.name,
  6818. array: Array.prototype.slice.call( index.array )
  6819. };
  6820. }
  6821. const attributes = this.attributes;
  6822. for ( const key in attributes ) {
  6823. const attribute = attributes[ key ];
  6824. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6825. }
  6826. const morphAttributes = {};
  6827. let hasMorphAttributes = false;
  6828. for ( const key in this.morphAttributes ) {
  6829. const attributeArray = this.morphAttributes[ key ];
  6830. const array = [];
  6831. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6832. const attribute = attributeArray[ i ];
  6833. array.push( attribute.toJSON( data.data ) );
  6834. }
  6835. if ( array.length > 0 ) {
  6836. morphAttributes[ key ] = array;
  6837. hasMorphAttributes = true;
  6838. }
  6839. }
  6840. if ( hasMorphAttributes ) {
  6841. data.data.morphAttributes = morphAttributes;
  6842. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6843. }
  6844. const groups = this.groups;
  6845. if ( groups.length > 0 ) {
  6846. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6847. }
  6848. const boundingSphere = this.boundingSphere;
  6849. if ( boundingSphere !== null ) {
  6850. data.data.boundingSphere = {
  6851. center: boundingSphere.center.toArray(),
  6852. radius: boundingSphere.radius
  6853. };
  6854. }
  6855. return data;
  6856. }
  6857. clone() {
  6858. return new this.constructor().copy( this );
  6859. }
  6860. copy( source ) {
  6861. // reset
  6862. this.index = null;
  6863. this.attributes = {};
  6864. this.morphAttributes = {};
  6865. this.groups = [];
  6866. this.boundingBox = null;
  6867. this.boundingSphere = null;
  6868. // used for storing cloned, shared data
  6869. const data = {};
  6870. // name
  6871. this.name = source.name;
  6872. // index
  6873. const index = source.index;
  6874. if ( index !== null ) {
  6875. this.setIndex( index.clone( data ) );
  6876. }
  6877. // attributes
  6878. const attributes = source.attributes;
  6879. for ( const name in attributes ) {
  6880. const attribute = attributes[ name ];
  6881. this.setAttribute( name, attribute.clone( data ) );
  6882. }
  6883. // morph attributes
  6884. const morphAttributes = source.morphAttributes;
  6885. for ( const name in morphAttributes ) {
  6886. const array = [];
  6887. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6888. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6889. array.push( morphAttribute[ i ].clone( data ) );
  6890. }
  6891. this.morphAttributes[ name ] = array;
  6892. }
  6893. this.morphTargetsRelative = source.morphTargetsRelative;
  6894. // groups
  6895. const groups = source.groups;
  6896. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6897. const group = groups[ i ];
  6898. this.addGroup( group.start, group.count, group.materialIndex );
  6899. }
  6900. // bounding box
  6901. const boundingBox = source.boundingBox;
  6902. if ( boundingBox !== null ) {
  6903. this.boundingBox = boundingBox.clone();
  6904. }
  6905. // bounding sphere
  6906. const boundingSphere = source.boundingSphere;
  6907. if ( boundingSphere !== null ) {
  6908. this.boundingSphere = boundingSphere.clone();
  6909. }
  6910. // draw range
  6911. this.drawRange.start = source.drawRange.start;
  6912. this.drawRange.count = source.drawRange.count;
  6913. // user data
  6914. this.userData = source.userData;
  6915. return this;
  6916. }
  6917. dispose() {
  6918. this.dispatchEvent( { type: 'dispose' } );
  6919. }
  6920. }
  6921. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6922. const _ray$3 = /*@__PURE__*/ new Ray();
  6923. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6924. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6925. const _vA$1 = /*@__PURE__*/ new Vector3();
  6926. const _vB$1 = /*@__PURE__*/ new Vector3();
  6927. const _vC$1 = /*@__PURE__*/ new Vector3();
  6928. const _tempA = /*@__PURE__*/ new Vector3();
  6929. const _morphA = /*@__PURE__*/ new Vector3();
  6930. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6931. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6932. class Mesh extends Object3D {
  6933. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6934. super();
  6935. this.isMesh = true;
  6936. this.type = 'Mesh';
  6937. this.geometry = geometry;
  6938. this.material = material;
  6939. this.updateMorphTargets();
  6940. }
  6941. copy( source, recursive ) {
  6942. super.copy( source, recursive );
  6943. if ( source.morphTargetInfluences !== undefined ) {
  6944. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6945. }
  6946. if ( source.morphTargetDictionary !== undefined ) {
  6947. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6948. }
  6949. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6950. this.geometry = source.geometry;
  6951. return this;
  6952. }
  6953. updateMorphTargets() {
  6954. const geometry = this.geometry;
  6955. const morphAttributes = geometry.morphAttributes;
  6956. const keys = Object.keys( morphAttributes );
  6957. if ( keys.length > 0 ) {
  6958. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6959. if ( morphAttribute !== undefined ) {
  6960. this.morphTargetInfluences = [];
  6961. this.morphTargetDictionary = {};
  6962. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6963. const name = morphAttribute[ m ].name || String( m );
  6964. this.morphTargetInfluences.push( 0 );
  6965. this.morphTargetDictionary[ name ] = m;
  6966. }
  6967. }
  6968. }
  6969. }
  6970. getVertexPosition( index, target ) {
  6971. const geometry = this.geometry;
  6972. const position = geometry.attributes.position;
  6973. const morphPosition = geometry.morphAttributes.position;
  6974. const morphTargetsRelative = geometry.morphTargetsRelative;
  6975. target.fromBufferAttribute( position, index );
  6976. const morphInfluences = this.morphTargetInfluences;
  6977. if ( morphPosition && morphInfluences ) {
  6978. _morphA.set( 0, 0, 0 );
  6979. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6980. const influence = morphInfluences[ i ];
  6981. const morphAttribute = morphPosition[ i ];
  6982. if ( influence === 0 ) continue;
  6983. _tempA.fromBufferAttribute( morphAttribute, index );
  6984. if ( morphTargetsRelative ) {
  6985. _morphA.addScaledVector( _tempA, influence );
  6986. } else {
  6987. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6988. }
  6989. }
  6990. target.add( _morphA );
  6991. }
  6992. return target;
  6993. }
  6994. raycast( raycaster, intersects ) {
  6995. const geometry = this.geometry;
  6996. const material = this.material;
  6997. const matrixWorld = this.matrixWorld;
  6998. if ( material === undefined ) return;
  6999. // test with bounding sphere in world space
  7000. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7001. _sphere$6.copy( geometry.boundingSphere );
  7002. _sphere$6.applyMatrix4( matrixWorld );
  7003. // check distance from ray origin to bounding sphere
  7004. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  7005. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  7006. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  7007. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  7008. }
  7009. // convert ray to local space of mesh
  7010. _inverseMatrix$3.copy( matrixWorld ).invert();
  7011. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  7012. // test with bounding box in local space
  7013. if ( geometry.boundingBox !== null ) {
  7014. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  7015. }
  7016. // test for intersections with geometry
  7017. this._computeIntersections( raycaster, intersects, _ray$3 );
  7018. }
  7019. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  7020. let intersection;
  7021. const geometry = this.geometry;
  7022. const material = this.material;
  7023. const index = geometry.index;
  7024. const position = geometry.attributes.position;
  7025. const uv = geometry.attributes.uv;
  7026. const uv1 = geometry.attributes.uv1;
  7027. const normal = geometry.attributes.normal;
  7028. const groups = geometry.groups;
  7029. const drawRange = geometry.drawRange;
  7030. if ( index !== null ) {
  7031. // indexed buffer geometry
  7032. if ( Array.isArray( material ) ) {
  7033. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7034. const group = groups[ i ];
  7035. const groupMaterial = material[ group.materialIndex ];
  7036. const start = Math.max( group.start, drawRange.start );
  7037. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7038. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7039. const a = index.getX( j );
  7040. const b = index.getX( j + 1 );
  7041. const c = index.getX( j + 2 );
  7042. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7043. if ( intersection ) {
  7044. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  7045. intersection.face.materialIndex = group.materialIndex;
  7046. intersects.push( intersection );
  7047. }
  7048. }
  7049. }
  7050. } else {
  7051. const start = Math.max( 0, drawRange.start );
  7052. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7053. for ( let i = start, il = end; i < il; i += 3 ) {
  7054. const a = index.getX( i );
  7055. const b = index.getX( i + 1 );
  7056. const c = index.getX( i + 2 );
  7057. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7058. if ( intersection ) {
  7059. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7060. intersects.push( intersection );
  7061. }
  7062. }
  7063. }
  7064. } else if ( position !== undefined ) {
  7065. // non-indexed buffer geometry
  7066. if ( Array.isArray( material ) ) {
  7067. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7068. const group = groups[ i ];
  7069. const groupMaterial = material[ group.materialIndex ];
  7070. const start = Math.max( group.start, drawRange.start );
  7071. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7072. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7073. const a = j;
  7074. const b = j + 1;
  7075. const c = j + 2;
  7076. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7077. if ( intersection ) {
  7078. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7079. intersection.face.materialIndex = group.materialIndex;
  7080. intersects.push( intersection );
  7081. }
  7082. }
  7083. }
  7084. } else {
  7085. const start = Math.max( 0, drawRange.start );
  7086. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7087. for ( let i = start, il = end; i < il; i += 3 ) {
  7088. const a = i;
  7089. const b = i + 1;
  7090. const c = i + 2;
  7091. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7092. if ( intersection ) {
  7093. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7094. intersects.push( intersection );
  7095. }
  7096. }
  7097. }
  7098. }
  7099. }
  7100. }
  7101. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7102. let intersect;
  7103. if ( material.side === BackSide ) {
  7104. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7105. } else {
  7106. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7107. }
  7108. if ( intersect === null ) return null;
  7109. _intersectionPointWorld.copy( point );
  7110. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7111. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7112. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7113. return {
  7114. distance: distance,
  7115. point: _intersectionPointWorld.clone(),
  7116. object: object
  7117. };
  7118. }
  7119. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7120. object.getVertexPosition( a, _vA$1 );
  7121. object.getVertexPosition( b, _vB$1 );
  7122. object.getVertexPosition( c, _vC$1 );
  7123. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7124. if ( intersection ) {
  7125. const barycoord = new Vector3();
  7126. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  7127. if ( uv ) {
  7128. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  7129. }
  7130. if ( uv1 ) {
  7131. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  7132. }
  7133. if ( normal ) {
  7134. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  7135. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7136. intersection.normal.multiplyScalar( - 1 );
  7137. }
  7138. }
  7139. const face = {
  7140. a: a,
  7141. b: b,
  7142. c: c,
  7143. normal: new Vector3(),
  7144. materialIndex: 0
  7145. };
  7146. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7147. intersection.face = face;
  7148. intersection.barycoord = barycoord;
  7149. }
  7150. return intersection;
  7151. }
  7152. class BoxGeometry extends BufferGeometry {
  7153. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7154. super();
  7155. this.type = 'BoxGeometry';
  7156. this.parameters = {
  7157. width: width,
  7158. height: height,
  7159. depth: depth,
  7160. widthSegments: widthSegments,
  7161. heightSegments: heightSegments,
  7162. depthSegments: depthSegments
  7163. };
  7164. const scope = this;
  7165. // segments
  7166. widthSegments = Math.floor( widthSegments );
  7167. heightSegments = Math.floor( heightSegments );
  7168. depthSegments = Math.floor( depthSegments );
  7169. // buffers
  7170. const indices = [];
  7171. const vertices = [];
  7172. const normals = [];
  7173. const uvs = [];
  7174. // helper variables
  7175. let numberOfVertices = 0;
  7176. let groupStart = 0;
  7177. // build each side of the box geometry
  7178. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7179. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7180. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7181. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7182. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7183. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7184. // build geometry
  7185. this.setIndex( indices );
  7186. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7187. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7188. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7189. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7190. const segmentWidth = width / gridX;
  7191. const segmentHeight = height / gridY;
  7192. const widthHalf = width / 2;
  7193. const heightHalf = height / 2;
  7194. const depthHalf = depth / 2;
  7195. const gridX1 = gridX + 1;
  7196. const gridY1 = gridY + 1;
  7197. let vertexCounter = 0;
  7198. let groupCount = 0;
  7199. const vector = new Vector3();
  7200. // generate vertices, normals and uvs
  7201. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7202. const y = iy * segmentHeight - heightHalf;
  7203. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7204. const x = ix * segmentWidth - widthHalf;
  7205. // set values to correct vector component
  7206. vector[ u ] = x * udir;
  7207. vector[ v ] = y * vdir;
  7208. vector[ w ] = depthHalf;
  7209. // now apply vector to vertex buffer
  7210. vertices.push( vector.x, vector.y, vector.z );
  7211. // set values to correct vector component
  7212. vector[ u ] = 0;
  7213. vector[ v ] = 0;
  7214. vector[ w ] = depth > 0 ? 1 : - 1;
  7215. // now apply vector to normal buffer
  7216. normals.push( vector.x, vector.y, vector.z );
  7217. // uvs
  7218. uvs.push( ix / gridX );
  7219. uvs.push( 1 - ( iy / gridY ) );
  7220. // counters
  7221. vertexCounter += 1;
  7222. }
  7223. }
  7224. // indices
  7225. // 1. you need three indices to draw a single face
  7226. // 2. a single segment consists of two faces
  7227. // 3. so we need to generate six (2*3) indices per segment
  7228. for ( let iy = 0; iy < gridY; iy ++ ) {
  7229. for ( let ix = 0; ix < gridX; ix ++ ) {
  7230. const a = numberOfVertices + ix + gridX1 * iy;
  7231. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7232. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7233. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7234. // faces
  7235. indices.push( a, b, d );
  7236. indices.push( b, c, d );
  7237. // increase counter
  7238. groupCount += 6;
  7239. }
  7240. }
  7241. // add a group to the geometry. this will ensure multi material support
  7242. scope.addGroup( groupStart, groupCount, materialIndex );
  7243. // calculate new start value for groups
  7244. groupStart += groupCount;
  7245. // update total number of vertices
  7246. numberOfVertices += vertexCounter;
  7247. }
  7248. }
  7249. copy( source ) {
  7250. super.copy( source );
  7251. this.parameters = Object.assign( {}, source.parameters );
  7252. return this;
  7253. }
  7254. static fromJSON( data ) {
  7255. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7256. }
  7257. }
  7258. /**
  7259. * Uniform Utilities
  7260. */
  7261. function cloneUniforms( src ) {
  7262. const dst = {};
  7263. for ( const u in src ) {
  7264. dst[ u ] = {};
  7265. for ( const p in src[ u ] ) {
  7266. const property = src[ u ][ p ];
  7267. if ( property && ( property.isColor ||
  7268. property.isMatrix3 || property.isMatrix4 ||
  7269. property.isVector2 || property.isVector3 || property.isVector4 ||
  7270. property.isTexture || property.isQuaternion ) ) {
  7271. if ( property.isRenderTargetTexture ) {
  7272. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7273. dst[ u ][ p ] = null;
  7274. } else {
  7275. dst[ u ][ p ] = property.clone();
  7276. }
  7277. } else if ( Array.isArray( property ) ) {
  7278. dst[ u ][ p ] = property.slice();
  7279. } else {
  7280. dst[ u ][ p ] = property;
  7281. }
  7282. }
  7283. }
  7284. return dst;
  7285. }
  7286. function cloneUniformsGroups( src ) {
  7287. const dst = [];
  7288. for ( let u = 0; u < src.length; u ++ ) {
  7289. dst.push( src[ u ].clone() );
  7290. }
  7291. return dst;
  7292. }
  7293. var default_vertex = /* glsl */`
  7294. void main() {
  7295. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  7296. }
  7297. `;
  7298. var default_fragment = /* glsl */`
  7299. void main() {
  7300. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  7301. }
  7302. `;
  7303. class ShaderMaterial extends Material {
  7304. static get type() {
  7305. return 'ShaderMaterial';
  7306. }
  7307. constructor( parameters ) {
  7308. super();
  7309. this.isShaderMaterial = true;
  7310. this.defines = {};
  7311. this.uniforms = {};
  7312. this.uniformsGroups = [];
  7313. this.vertexShader = default_vertex;
  7314. this.fragmentShader = default_fragment;
  7315. this.linewidth = 1;
  7316. this.wireframe = false;
  7317. this.wireframeLinewidth = 1;
  7318. this.fog = false; // set to use scene fog
  7319. this.lights = false; // set to use scene lights
  7320. this.clipping = false; // set to use user-defined clipping planes
  7321. this.forceSinglePass = true;
  7322. this.extensions = {
  7323. clipCullDistance: false, // set to use vertex shader clipping
  7324. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7325. };
  7326. // When rendered geometry doesn't include these attributes but the material does,
  7327. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7328. this.defaultAttributeValues = {
  7329. 'color': [ 1, 1, 1 ],
  7330. 'uv': [ 0, 0 ],
  7331. 'uv1': [ 0, 0 ]
  7332. };
  7333. this.index0AttributeName = undefined;
  7334. this.uniformsNeedUpdate = false;
  7335. this.glslVersion = null;
  7336. if ( parameters !== undefined ) {
  7337. this.setValues( parameters );
  7338. }
  7339. }
  7340. copy( source ) {
  7341. super.copy( source );
  7342. this.fragmentShader = source.fragmentShader;
  7343. this.vertexShader = source.vertexShader;
  7344. this.uniforms = cloneUniforms( source.uniforms );
  7345. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7346. this.defines = Object.assign( {}, source.defines );
  7347. this.wireframe = source.wireframe;
  7348. this.wireframeLinewidth = source.wireframeLinewidth;
  7349. this.fog = source.fog;
  7350. this.lights = source.lights;
  7351. this.clipping = source.clipping;
  7352. this.extensions = Object.assign( {}, source.extensions );
  7353. this.glslVersion = source.glslVersion;
  7354. return this;
  7355. }
  7356. toJSON( meta ) {
  7357. const data = super.toJSON( meta );
  7358. data.glslVersion = this.glslVersion;
  7359. data.uniforms = {};
  7360. for ( const name in this.uniforms ) {
  7361. const uniform = this.uniforms[ name ];
  7362. const value = uniform.value;
  7363. if ( value && value.isTexture ) {
  7364. data.uniforms[ name ] = {
  7365. type: 't',
  7366. value: value.toJSON( meta ).uuid
  7367. };
  7368. } else if ( value && value.isColor ) {
  7369. data.uniforms[ name ] = {
  7370. type: 'c',
  7371. value: value.getHex()
  7372. };
  7373. } else if ( value && value.isVector2 ) {
  7374. data.uniforms[ name ] = {
  7375. type: 'v2',
  7376. value: value.toArray()
  7377. };
  7378. } else if ( value && value.isVector3 ) {
  7379. data.uniforms[ name ] = {
  7380. type: 'v3',
  7381. value: value.toArray()
  7382. };
  7383. } else if ( value && value.isVector4 ) {
  7384. data.uniforms[ name ] = {
  7385. type: 'v4',
  7386. value: value.toArray()
  7387. };
  7388. } else if ( value && value.isMatrix3 ) {
  7389. data.uniforms[ name ] = {
  7390. type: 'm3',
  7391. value: value.toArray()
  7392. };
  7393. } else if ( value && value.isMatrix4 ) {
  7394. data.uniforms[ name ] = {
  7395. type: 'm4',
  7396. value: value.toArray()
  7397. };
  7398. } else {
  7399. data.uniforms[ name ] = {
  7400. value: value
  7401. };
  7402. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7403. }
  7404. }
  7405. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7406. data.vertexShader = this.vertexShader;
  7407. data.fragmentShader = this.fragmentShader;
  7408. data.lights = this.lights;
  7409. data.clipping = this.clipping;
  7410. const extensions = {};
  7411. for ( const key in this.extensions ) {
  7412. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7413. }
  7414. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7415. return data;
  7416. }
  7417. }
  7418. class Camera extends Object3D {
  7419. constructor() {
  7420. super();
  7421. this.isCamera = true;
  7422. this.type = 'Camera';
  7423. this.matrixWorldInverse = new Matrix4();
  7424. this.projectionMatrix = new Matrix4();
  7425. this.projectionMatrixInverse = new Matrix4();
  7426. this.coordinateSystem = WebGLCoordinateSystem;
  7427. }
  7428. copy( source, recursive ) {
  7429. super.copy( source, recursive );
  7430. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7431. this.projectionMatrix.copy( source.projectionMatrix );
  7432. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7433. this.coordinateSystem = source.coordinateSystem;
  7434. return this;
  7435. }
  7436. getWorldDirection( target ) {
  7437. return super.getWorldDirection( target ).negate();
  7438. }
  7439. updateMatrixWorld( force ) {
  7440. super.updateMatrixWorld( force );
  7441. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7442. }
  7443. updateWorldMatrix( updateParents, updateChildren ) {
  7444. super.updateWorldMatrix( updateParents, updateChildren );
  7445. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7446. }
  7447. clone() {
  7448. return new this.constructor().copy( this );
  7449. }
  7450. }
  7451. const _v3$1 = /*@__PURE__*/ new Vector3();
  7452. const _minTarget = /*@__PURE__*/ new Vector2();
  7453. const _maxTarget = /*@__PURE__*/ new Vector2();
  7454. class PerspectiveCamera extends Camera {
  7455. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7456. super();
  7457. this.isPerspectiveCamera = true;
  7458. this.type = 'PerspectiveCamera';
  7459. this.fov = fov;
  7460. this.zoom = 1;
  7461. this.near = near;
  7462. this.far = far;
  7463. this.focus = 10;
  7464. this.aspect = aspect;
  7465. this.view = null;
  7466. this.filmGauge = 35; // width of the film (default in millimeters)
  7467. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7468. this.updateProjectionMatrix();
  7469. }
  7470. copy( source, recursive ) {
  7471. super.copy( source, recursive );
  7472. this.fov = source.fov;
  7473. this.zoom = source.zoom;
  7474. this.near = source.near;
  7475. this.far = source.far;
  7476. this.focus = source.focus;
  7477. this.aspect = source.aspect;
  7478. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7479. this.filmGauge = source.filmGauge;
  7480. this.filmOffset = source.filmOffset;
  7481. return this;
  7482. }
  7483. /**
  7484. * Sets the FOV by focal length in respect to the current .filmGauge.
  7485. *
  7486. * The default film gauge is 35, so that the focal length can be specified for
  7487. * a 35mm (full frame) camera.
  7488. *
  7489. * Values for focal length and film gauge must have the same unit.
  7490. */
  7491. setFocalLength( focalLength ) {
  7492. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7493. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7494. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7495. this.updateProjectionMatrix();
  7496. }
  7497. /**
  7498. * Calculates the focal length from the current .fov and .filmGauge.
  7499. */
  7500. getFocalLength() {
  7501. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7502. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7503. }
  7504. getEffectiveFOV() {
  7505. return RAD2DEG * 2 * Math.atan(
  7506. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7507. }
  7508. getFilmWidth() {
  7509. // film not completely covered in portrait format (aspect < 1)
  7510. return this.filmGauge * Math.min( this.aspect, 1 );
  7511. }
  7512. getFilmHeight() {
  7513. // film not completely covered in landscape format (aspect > 1)
  7514. return this.filmGauge / Math.max( this.aspect, 1 );
  7515. }
  7516. /**
  7517. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7518. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7519. */
  7520. getViewBounds( distance, minTarget, maxTarget ) {
  7521. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7522. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7523. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7524. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7525. }
  7526. /**
  7527. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7528. * Copies the result into the target Vector2, where x is width and y is height.
  7529. */
  7530. getViewSize( distance, target ) {
  7531. this.getViewBounds( distance, _minTarget, _maxTarget );
  7532. return target.subVectors( _maxTarget, _minTarget );
  7533. }
  7534. /**
  7535. * Sets an offset in a larger frustum. This is useful for multi-window or
  7536. * multi-monitor/multi-machine setups.
  7537. *
  7538. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7539. * the monitors are in grid like this
  7540. *
  7541. * +---+---+---+
  7542. * | A | B | C |
  7543. * +---+---+---+
  7544. * | D | E | F |
  7545. * +---+---+---+
  7546. *
  7547. * then for each monitor you would call it like this
  7548. *
  7549. * const w = 1920;
  7550. * const h = 1080;
  7551. * const fullWidth = w * 3;
  7552. * const fullHeight = h * 2;
  7553. *
  7554. * --A--
  7555. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7556. * --B--
  7557. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7558. * --C--
  7559. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7560. * --D--
  7561. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7562. * --E--
  7563. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7564. * --F--
  7565. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7566. *
  7567. * Note there is no reason monitors have to be the same size or in a grid.
  7568. */
  7569. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7570. this.aspect = fullWidth / fullHeight;
  7571. if ( this.view === null ) {
  7572. this.view = {
  7573. enabled: true,
  7574. fullWidth: 1,
  7575. fullHeight: 1,
  7576. offsetX: 0,
  7577. offsetY: 0,
  7578. width: 1,
  7579. height: 1
  7580. };
  7581. }
  7582. this.view.enabled = true;
  7583. this.view.fullWidth = fullWidth;
  7584. this.view.fullHeight = fullHeight;
  7585. this.view.offsetX = x;
  7586. this.view.offsetY = y;
  7587. this.view.width = width;
  7588. this.view.height = height;
  7589. this.updateProjectionMatrix();
  7590. }
  7591. clearViewOffset() {
  7592. if ( this.view !== null ) {
  7593. this.view.enabled = false;
  7594. }
  7595. this.updateProjectionMatrix();
  7596. }
  7597. updateProjectionMatrix() {
  7598. const near = this.near;
  7599. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7600. let height = 2 * top;
  7601. let width = this.aspect * height;
  7602. let left = - 0.5 * width;
  7603. const view = this.view;
  7604. if ( this.view !== null && this.view.enabled ) {
  7605. const fullWidth = view.fullWidth,
  7606. fullHeight = view.fullHeight;
  7607. left += view.offsetX * width / fullWidth;
  7608. top -= view.offsetY * height / fullHeight;
  7609. width *= view.width / fullWidth;
  7610. height *= view.height / fullHeight;
  7611. }
  7612. const skew = this.filmOffset;
  7613. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7614. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7615. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7616. }
  7617. toJSON( meta ) {
  7618. const data = super.toJSON( meta );
  7619. data.object.fov = this.fov;
  7620. data.object.zoom = this.zoom;
  7621. data.object.near = this.near;
  7622. data.object.far = this.far;
  7623. data.object.focus = this.focus;
  7624. data.object.aspect = this.aspect;
  7625. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7626. data.object.filmGauge = this.filmGauge;
  7627. data.object.filmOffset = this.filmOffset;
  7628. return data;
  7629. }
  7630. }
  7631. const fov = - 90; // negative fov is not an error
  7632. const aspect = 1;
  7633. class CubeCamera extends Object3D {
  7634. constructor( near, far, renderTarget ) {
  7635. super();
  7636. this.type = 'CubeCamera';
  7637. this.renderTarget = renderTarget;
  7638. this.coordinateSystem = null;
  7639. this.activeMipmapLevel = 0;
  7640. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7641. cameraPX.layers = this.layers;
  7642. this.add( cameraPX );
  7643. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7644. cameraNX.layers = this.layers;
  7645. this.add( cameraNX );
  7646. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7647. cameraPY.layers = this.layers;
  7648. this.add( cameraPY );
  7649. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7650. cameraNY.layers = this.layers;
  7651. this.add( cameraNY );
  7652. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7653. cameraPZ.layers = this.layers;
  7654. this.add( cameraPZ );
  7655. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7656. cameraNZ.layers = this.layers;
  7657. this.add( cameraNZ );
  7658. }
  7659. updateCoordinateSystem() {
  7660. const coordinateSystem = this.coordinateSystem;
  7661. const cameras = this.children.concat();
  7662. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7663. for ( const camera of cameras ) this.remove( camera );
  7664. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7665. cameraPX.up.set( 0, 1, 0 );
  7666. cameraPX.lookAt( 1, 0, 0 );
  7667. cameraNX.up.set( 0, 1, 0 );
  7668. cameraNX.lookAt( - 1, 0, 0 );
  7669. cameraPY.up.set( 0, 0, - 1 );
  7670. cameraPY.lookAt( 0, 1, 0 );
  7671. cameraNY.up.set( 0, 0, 1 );
  7672. cameraNY.lookAt( 0, - 1, 0 );
  7673. cameraPZ.up.set( 0, 1, 0 );
  7674. cameraPZ.lookAt( 0, 0, 1 );
  7675. cameraNZ.up.set( 0, 1, 0 );
  7676. cameraNZ.lookAt( 0, 0, - 1 );
  7677. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7678. cameraPX.up.set( 0, - 1, 0 );
  7679. cameraPX.lookAt( - 1, 0, 0 );
  7680. cameraNX.up.set( 0, - 1, 0 );
  7681. cameraNX.lookAt( 1, 0, 0 );
  7682. cameraPY.up.set( 0, 0, 1 );
  7683. cameraPY.lookAt( 0, 1, 0 );
  7684. cameraNY.up.set( 0, 0, - 1 );
  7685. cameraNY.lookAt( 0, - 1, 0 );
  7686. cameraPZ.up.set( 0, - 1, 0 );
  7687. cameraPZ.lookAt( 0, 0, 1 );
  7688. cameraNZ.up.set( 0, - 1, 0 );
  7689. cameraNZ.lookAt( 0, 0, - 1 );
  7690. } else {
  7691. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7692. }
  7693. for ( const camera of cameras ) {
  7694. this.add( camera );
  7695. camera.updateMatrixWorld();
  7696. }
  7697. }
  7698. update( renderer, scene ) {
  7699. if ( this.parent === null ) this.updateMatrixWorld();
  7700. const { renderTarget, activeMipmapLevel } = this;
  7701. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7702. this.coordinateSystem = renderer.coordinateSystem;
  7703. this.updateCoordinateSystem();
  7704. }
  7705. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7706. const currentRenderTarget = renderer.getRenderTarget();
  7707. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7708. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7709. const currentXrEnabled = renderer.xr.enabled;
  7710. renderer.xr.enabled = false;
  7711. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7712. renderTarget.texture.generateMipmaps = false;
  7713. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7714. renderer.render( scene, cameraPX );
  7715. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7716. renderer.render( scene, cameraNX );
  7717. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7718. renderer.render( scene, cameraPY );
  7719. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7720. renderer.render( scene, cameraNY );
  7721. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7722. renderer.render( scene, cameraPZ );
  7723. // mipmaps are generated during the last call of render()
  7724. // at this point, all sides of the cube render target are defined
  7725. renderTarget.texture.generateMipmaps = generateMipmaps;
  7726. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7727. renderer.render( scene, cameraNZ );
  7728. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7729. renderer.xr.enabled = currentXrEnabled;
  7730. renderTarget.texture.needsPMREMUpdate = true;
  7731. }
  7732. }
  7733. class CubeTexture extends Texture {
  7734. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7735. images = images !== undefined ? images : [];
  7736. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7737. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7738. this.isCubeTexture = true;
  7739. this.flipY = false;
  7740. }
  7741. get images() {
  7742. return this.image;
  7743. }
  7744. set images( value ) {
  7745. this.image = value;
  7746. }
  7747. }
  7748. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7749. constructor( size = 1, options = {} ) {
  7750. super( size, size, options );
  7751. this.isWebGLCubeRenderTarget = true;
  7752. const image = { width: size, height: size, depth: 1 };
  7753. const images = [ image, image, image, image, image, image ];
  7754. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7755. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7756. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7757. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7758. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7759. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7760. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7761. this.texture.isRenderTargetTexture = true;
  7762. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7763. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7764. }
  7765. fromEquirectangularTexture( renderer, texture ) {
  7766. this.texture.type = texture.type;
  7767. this.texture.colorSpace = texture.colorSpace;
  7768. this.texture.generateMipmaps = texture.generateMipmaps;
  7769. this.texture.minFilter = texture.minFilter;
  7770. this.texture.magFilter = texture.magFilter;
  7771. const shader = {
  7772. uniforms: {
  7773. tEquirect: { value: null },
  7774. },
  7775. vertexShader: /* glsl */`
  7776. varying vec3 vWorldDirection;
  7777. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7778. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7779. }
  7780. void main() {
  7781. vWorldDirection = transformDirection( position, modelMatrix );
  7782. #include <begin_vertex>
  7783. #include <project_vertex>
  7784. }
  7785. `,
  7786. fragmentShader: /* glsl */`
  7787. uniform sampler2D tEquirect;
  7788. varying vec3 vWorldDirection;
  7789. #include <common>
  7790. void main() {
  7791. vec3 direction = normalize( vWorldDirection );
  7792. vec2 sampleUV = equirectUv( direction );
  7793. gl_FragColor = texture2D( tEquirect, sampleUV );
  7794. }
  7795. `
  7796. };
  7797. const geometry = new BoxGeometry( 5, 5, 5 );
  7798. const material = new ShaderMaterial( {
  7799. name: 'CubemapFromEquirect',
  7800. uniforms: cloneUniforms( shader.uniforms ),
  7801. vertexShader: shader.vertexShader,
  7802. fragmentShader: shader.fragmentShader,
  7803. side: BackSide,
  7804. blending: NoBlending
  7805. } );
  7806. material.uniforms.tEquirect.value = texture;
  7807. const mesh = new Mesh( geometry, material );
  7808. const currentMinFilter = texture.minFilter;
  7809. // Avoid blurred poles
  7810. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7811. const camera = new CubeCamera( 1, 10, this );
  7812. camera.update( renderer, mesh );
  7813. texture.minFilter = currentMinFilter;
  7814. mesh.geometry.dispose();
  7815. mesh.material.dispose();
  7816. return this;
  7817. }
  7818. clear( renderer, color, depth, stencil ) {
  7819. const currentRenderTarget = renderer.getRenderTarget();
  7820. for ( let i = 0; i < 6; i ++ ) {
  7821. renderer.setRenderTarget( this, i );
  7822. renderer.clear( color, depth, stencil );
  7823. }
  7824. renderer.setRenderTarget( currentRenderTarget );
  7825. }
  7826. }
  7827. class FogExp2 {
  7828. constructor( color, density = 0.00025 ) {
  7829. this.isFogExp2 = true;
  7830. this.name = '';
  7831. this.color = new Color( color );
  7832. this.density = density;
  7833. }
  7834. clone() {
  7835. return new FogExp2( this.color, this.density );
  7836. }
  7837. toJSON( /* meta */ ) {
  7838. return {
  7839. type: 'FogExp2',
  7840. name: this.name,
  7841. color: this.color.getHex(),
  7842. density: this.density
  7843. };
  7844. }
  7845. }
  7846. class Fog {
  7847. constructor( color, near = 1, far = 1000 ) {
  7848. this.isFog = true;
  7849. this.name = '';
  7850. this.color = new Color( color );
  7851. this.near = near;
  7852. this.far = far;
  7853. }
  7854. clone() {
  7855. return new Fog( this.color, this.near, this.far );
  7856. }
  7857. toJSON( /* meta */ ) {
  7858. return {
  7859. type: 'Fog',
  7860. name: this.name,
  7861. color: this.color.getHex(),
  7862. near: this.near,
  7863. far: this.far
  7864. };
  7865. }
  7866. }
  7867. class Scene extends Object3D {
  7868. constructor() {
  7869. super();
  7870. this.isScene = true;
  7871. this.type = 'Scene';
  7872. this.background = null;
  7873. this.environment = null;
  7874. this.fog = null;
  7875. this.backgroundBlurriness = 0;
  7876. this.backgroundIntensity = 1;
  7877. this.backgroundRotation = new Euler();
  7878. this.environmentIntensity = 1;
  7879. this.environmentRotation = new Euler();
  7880. this.overrideMaterial = null;
  7881. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  7882. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  7883. }
  7884. }
  7885. copy( source, recursive ) {
  7886. super.copy( source, recursive );
  7887. if ( source.background !== null ) this.background = source.background.clone();
  7888. if ( source.environment !== null ) this.environment = source.environment.clone();
  7889. if ( source.fog !== null ) this.fog = source.fog.clone();
  7890. this.backgroundBlurriness = source.backgroundBlurriness;
  7891. this.backgroundIntensity = source.backgroundIntensity;
  7892. this.backgroundRotation.copy( source.backgroundRotation );
  7893. this.environmentIntensity = source.environmentIntensity;
  7894. this.environmentRotation.copy( source.environmentRotation );
  7895. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  7896. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7897. return this;
  7898. }
  7899. toJSON( meta ) {
  7900. const data = super.toJSON( meta );
  7901. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  7902. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  7903. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  7904. data.object.backgroundRotation = this.backgroundRotation.toArray();
  7905. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  7906. data.object.environmentRotation = this.environmentRotation.toArray();
  7907. return data;
  7908. }
  7909. }
  7910. class InterleavedBuffer {
  7911. constructor( array, stride ) {
  7912. this.isInterleavedBuffer = true;
  7913. this.array = array;
  7914. this.stride = stride;
  7915. this.count = array !== undefined ? array.length / stride : 0;
  7916. this.usage = StaticDrawUsage;
  7917. this.updateRanges = [];
  7918. this.version = 0;
  7919. this.uuid = generateUUID();
  7920. }
  7921. onUploadCallback() {}
  7922. set needsUpdate( value ) {
  7923. if ( value === true ) this.version ++;
  7924. }
  7925. setUsage( value ) {
  7926. this.usage = value;
  7927. return this;
  7928. }
  7929. addUpdateRange( start, count ) {
  7930. this.updateRanges.push( { start, count } );
  7931. }
  7932. clearUpdateRanges() {
  7933. this.updateRanges.length = 0;
  7934. }
  7935. copy( source ) {
  7936. this.array = new source.array.constructor( source.array );
  7937. this.count = source.count;
  7938. this.stride = source.stride;
  7939. this.usage = source.usage;
  7940. return this;
  7941. }
  7942. copyAt( index1, attribute, index2 ) {
  7943. index1 *= this.stride;
  7944. index2 *= attribute.stride;
  7945. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  7946. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7947. }
  7948. return this;
  7949. }
  7950. set( value, offset = 0 ) {
  7951. this.array.set( value, offset );
  7952. return this;
  7953. }
  7954. clone( data ) {
  7955. if ( data.arrayBuffers === undefined ) {
  7956. data.arrayBuffers = {};
  7957. }
  7958. if ( this.array.buffer._uuid === undefined ) {
  7959. this.array.buffer._uuid = generateUUID();
  7960. }
  7961. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7962. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  7963. }
  7964. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  7965. const ib = new this.constructor( array, this.stride );
  7966. ib.setUsage( this.usage );
  7967. return ib;
  7968. }
  7969. onUpload( callback ) {
  7970. this.onUploadCallback = callback;
  7971. return this;
  7972. }
  7973. toJSON( data ) {
  7974. if ( data.arrayBuffers === undefined ) {
  7975. data.arrayBuffers = {};
  7976. }
  7977. // generate UUID for array buffer if necessary
  7978. if ( this.array.buffer._uuid === undefined ) {
  7979. this.array.buffer._uuid = generateUUID();
  7980. }
  7981. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7982. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  7983. }
  7984. //
  7985. return {
  7986. uuid: this.uuid,
  7987. buffer: this.array.buffer._uuid,
  7988. type: this.array.constructor.name,
  7989. stride: this.stride
  7990. };
  7991. }
  7992. }
  7993. const _vector$7 = /*@__PURE__*/ new Vector3();
  7994. class InterleavedBufferAttribute {
  7995. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  7996. this.isInterleavedBufferAttribute = true;
  7997. this.name = '';
  7998. this.data = interleavedBuffer;
  7999. this.itemSize = itemSize;
  8000. this.offset = offset;
  8001. this.normalized = normalized;
  8002. }
  8003. get count() {
  8004. return this.data.count;
  8005. }
  8006. get array() {
  8007. return this.data.array;
  8008. }
  8009. set needsUpdate( value ) {
  8010. this.data.needsUpdate = value;
  8011. }
  8012. applyMatrix4( m ) {
  8013. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  8014. _vector$7.fromBufferAttribute( this, i );
  8015. _vector$7.applyMatrix4( m );
  8016. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8017. }
  8018. return this;
  8019. }
  8020. applyNormalMatrix( m ) {
  8021. for ( let i = 0, l = this.count; i < l; i ++ ) {
  8022. _vector$7.fromBufferAttribute( this, i );
  8023. _vector$7.applyNormalMatrix( m );
  8024. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8025. }
  8026. return this;
  8027. }
  8028. transformDirection( m ) {
  8029. for ( let i = 0, l = this.count; i < l; i ++ ) {
  8030. _vector$7.fromBufferAttribute( this, i );
  8031. _vector$7.transformDirection( m );
  8032. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8033. }
  8034. return this;
  8035. }
  8036. getComponent( index, component ) {
  8037. let value = this.array[ index * this.data.stride + this.offset + component ];
  8038. if ( this.normalized ) value = denormalize( value, this.array );
  8039. return value;
  8040. }
  8041. setComponent( index, component, value ) {
  8042. if ( this.normalized ) value = normalize$1( value, this.array );
  8043. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  8044. return this;
  8045. }
  8046. setX( index, x ) {
  8047. if ( this.normalized ) x = normalize$1( x, this.array );
  8048. this.data.array[ index * this.data.stride + this.offset ] = x;
  8049. return this;
  8050. }
  8051. setY( index, y ) {
  8052. if ( this.normalized ) y = normalize$1( y, this.array );
  8053. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  8054. return this;
  8055. }
  8056. setZ( index, z ) {
  8057. if ( this.normalized ) z = normalize$1( z, this.array );
  8058. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  8059. return this;
  8060. }
  8061. setW( index, w ) {
  8062. if ( this.normalized ) w = normalize$1( w, this.array );
  8063. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  8064. return this;
  8065. }
  8066. getX( index ) {
  8067. let x = this.data.array[ index * this.data.stride + this.offset ];
  8068. if ( this.normalized ) x = denormalize( x, this.array );
  8069. return x;
  8070. }
  8071. getY( index ) {
  8072. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  8073. if ( this.normalized ) y = denormalize( y, this.array );
  8074. return y;
  8075. }
  8076. getZ( index ) {
  8077. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  8078. if ( this.normalized ) z = denormalize( z, this.array );
  8079. return z;
  8080. }
  8081. getW( index ) {
  8082. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  8083. if ( this.normalized ) w = denormalize( w, this.array );
  8084. return w;
  8085. }
  8086. setXY( index, x, y ) {
  8087. index = index * this.data.stride + this.offset;
  8088. if ( this.normalized ) {
  8089. x = normalize$1( x, this.array );
  8090. y = normalize$1( y, this.array );
  8091. }
  8092. this.data.array[ index + 0 ] = x;
  8093. this.data.array[ index + 1 ] = y;
  8094. return this;
  8095. }
  8096. setXYZ( index, x, y, z ) {
  8097. index = index * this.data.stride + this.offset;
  8098. if ( this.normalized ) {
  8099. x = normalize$1( x, this.array );
  8100. y = normalize$1( y, this.array );
  8101. z = normalize$1( z, this.array );
  8102. }
  8103. this.data.array[ index + 0 ] = x;
  8104. this.data.array[ index + 1 ] = y;
  8105. this.data.array[ index + 2 ] = z;
  8106. return this;
  8107. }
  8108. setXYZW( index, x, y, z, w ) {
  8109. index = index * this.data.stride + this.offset;
  8110. if ( this.normalized ) {
  8111. x = normalize$1( x, this.array );
  8112. y = normalize$1( y, this.array );
  8113. z = normalize$1( z, this.array );
  8114. w = normalize$1( w, this.array );
  8115. }
  8116. this.data.array[ index + 0 ] = x;
  8117. this.data.array[ index + 1 ] = y;
  8118. this.data.array[ index + 2 ] = z;
  8119. this.data.array[ index + 3 ] = w;
  8120. return this;
  8121. }
  8122. clone( data ) {
  8123. if ( data === undefined ) {
  8124. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  8125. const array = [];
  8126. for ( let i = 0; i < this.count; i ++ ) {
  8127. const index = i * this.data.stride + this.offset;
  8128. for ( let j = 0; j < this.itemSize; j ++ ) {
  8129. array.push( this.data.array[ index + j ] );
  8130. }
  8131. }
  8132. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  8133. } else {
  8134. if ( data.interleavedBuffers === undefined ) {
  8135. data.interleavedBuffers = {};
  8136. }
  8137. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8138. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  8139. }
  8140. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  8141. }
  8142. }
  8143. toJSON( data ) {
  8144. if ( data === undefined ) {
  8145. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  8146. const array = [];
  8147. for ( let i = 0; i < this.count; i ++ ) {
  8148. const index = i * this.data.stride + this.offset;
  8149. for ( let j = 0; j < this.itemSize; j ++ ) {
  8150. array.push( this.data.array[ index + j ] );
  8151. }
  8152. }
  8153. // de-interleave data and save it as an ordinary buffer attribute for now
  8154. return {
  8155. itemSize: this.itemSize,
  8156. type: this.array.constructor.name,
  8157. array: array,
  8158. normalized: this.normalized
  8159. };
  8160. } else {
  8161. // save as true interleaved attribute
  8162. if ( data.interleavedBuffers === undefined ) {
  8163. data.interleavedBuffers = {};
  8164. }
  8165. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8166. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  8167. }
  8168. return {
  8169. isInterleavedBufferAttribute: true,
  8170. itemSize: this.itemSize,
  8171. data: this.data.uuid,
  8172. offset: this.offset,
  8173. normalized: this.normalized
  8174. };
  8175. }
  8176. }
  8177. }
  8178. class SpriteMaterial extends Material {
  8179. static get type() {
  8180. return 'SpriteMaterial';
  8181. }
  8182. constructor( parameters ) {
  8183. super();
  8184. this.isSpriteMaterial = true;
  8185. this.color = new Color( 0xffffff );
  8186. this.map = null;
  8187. this.alphaMap = null;
  8188. this.rotation = 0;
  8189. this.sizeAttenuation = true;
  8190. this.transparent = true;
  8191. this.fog = true;
  8192. this.setValues( parameters );
  8193. }
  8194. copy( source ) {
  8195. super.copy( source );
  8196. this.color.copy( source.color );
  8197. this.map = source.map;
  8198. this.alphaMap = source.alphaMap;
  8199. this.rotation = source.rotation;
  8200. this.sizeAttenuation = source.sizeAttenuation;
  8201. this.fog = source.fog;
  8202. return this;
  8203. }
  8204. }
  8205. let _geometry$1;
  8206. const _intersectPoint = /*@__PURE__*/ new Vector3();
  8207. const _worldScale = /*@__PURE__*/ new Vector3();
  8208. const _mvPosition = /*@__PURE__*/ new Vector3();
  8209. const _alignedPosition = /*@__PURE__*/ new Vector2();
  8210. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  8211. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  8212. const _vA = /*@__PURE__*/ new Vector3();
  8213. const _vB = /*@__PURE__*/ new Vector3();
  8214. const _vC = /*@__PURE__*/ new Vector3();
  8215. const _uvA = /*@__PURE__*/ new Vector2();
  8216. const _uvB = /*@__PURE__*/ new Vector2();
  8217. const _uvC = /*@__PURE__*/ new Vector2();
  8218. class Sprite extends Object3D {
  8219. constructor( material = new SpriteMaterial() ) {
  8220. super();
  8221. this.isSprite = true;
  8222. this.type = 'Sprite';
  8223. if ( _geometry$1 === undefined ) {
  8224. _geometry$1 = new BufferGeometry();
  8225. const float32Array = new Float32Array( [
  8226. - 0.5, - 0.5, 0, 0, 0,
  8227. 0.5, - 0.5, 0, 1, 0,
  8228. 0.5, 0.5, 0, 1, 1,
  8229. - 0.5, 0.5, 0, 0, 1
  8230. ] );
  8231. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  8232. _geometry$1.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  8233. _geometry$1.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  8234. _geometry$1.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  8235. }
  8236. this.geometry = _geometry$1;
  8237. this.material = material;
  8238. this.center = new Vector2( 0.5, 0.5 );
  8239. }
  8240. raycast( raycaster, intersects ) {
  8241. if ( raycaster.camera === null ) {
  8242. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  8243. }
  8244. _worldScale.setFromMatrixScale( this.matrixWorld );
  8245. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  8246. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  8247. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  8248. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  8249. _worldScale.multiplyScalar( - _mvPosition.z );
  8250. }
  8251. const rotation = this.material.rotation;
  8252. let sin, cos;
  8253. if ( rotation !== 0 ) {
  8254. cos = Math.cos( rotation );
  8255. sin = Math.sin( rotation );
  8256. }
  8257. const center = this.center;
  8258. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8259. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8260. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8261. _uvA.set( 0, 0 );
  8262. _uvB.set( 1, 0 );
  8263. _uvC.set( 1, 1 );
  8264. // check first triangle
  8265. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  8266. if ( intersect === null ) {
  8267. // check second triangle
  8268. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8269. _uvB.set( 0, 1 );
  8270. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  8271. if ( intersect === null ) {
  8272. return;
  8273. }
  8274. }
  8275. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  8276. if ( distance < raycaster.near || distance > raycaster.far ) return;
  8277. intersects.push( {
  8278. distance: distance,
  8279. point: _intersectPoint.clone(),
  8280. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  8281. face: null,
  8282. object: this
  8283. } );
  8284. }
  8285. copy( source, recursive ) {
  8286. super.copy( source, recursive );
  8287. if ( source.center !== undefined ) this.center.copy( source.center );
  8288. this.material = source.material;
  8289. return this;
  8290. }
  8291. }
  8292. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  8293. // compute position in camera space
  8294. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  8295. // to check if rotation is not zero
  8296. if ( sin !== undefined ) {
  8297. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  8298. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  8299. } else {
  8300. _rotatedPosition.copy( _alignedPosition );
  8301. }
  8302. vertexPosition.copy( mvPosition );
  8303. vertexPosition.x += _rotatedPosition.x;
  8304. vertexPosition.y += _rotatedPosition.y;
  8305. // transform to world space
  8306. vertexPosition.applyMatrix4( _viewWorldMatrix );
  8307. }
  8308. const _v1$2 = /*@__PURE__*/ new Vector3();
  8309. const _v2$1 = /*@__PURE__*/ new Vector3();
  8310. class LOD extends Object3D {
  8311. constructor() {
  8312. super();
  8313. this._currentLevel = 0;
  8314. this.type = 'LOD';
  8315. Object.defineProperties( this, {
  8316. levels: {
  8317. enumerable: true,
  8318. value: []
  8319. },
  8320. isLOD: {
  8321. value: true,
  8322. }
  8323. } );
  8324. this.autoUpdate = true;
  8325. }
  8326. copy( source ) {
  8327. super.copy( source, false );
  8328. const levels = source.levels;
  8329. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8330. const level = levels[ i ];
  8331. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  8332. }
  8333. this.autoUpdate = source.autoUpdate;
  8334. return this;
  8335. }
  8336. addLevel( object, distance = 0, hysteresis = 0 ) {
  8337. distance = Math.abs( distance );
  8338. const levels = this.levels;
  8339. let l;
  8340. for ( l = 0; l < levels.length; l ++ ) {
  8341. if ( distance < levels[ l ].distance ) {
  8342. break;
  8343. }
  8344. }
  8345. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  8346. this.add( object );
  8347. return this;
  8348. }
  8349. removeLevel( distance ) {
  8350. const levels = this.levels;
  8351. for ( let i = 0; i < levels.length; i ++ ) {
  8352. if ( levels[ i ].distance === distance ) {
  8353. const removedElements = levels.splice( i, 1 );
  8354. this.remove( removedElements[ 0 ].object );
  8355. return true;
  8356. }
  8357. }
  8358. return false;
  8359. }
  8360. getCurrentLevel() {
  8361. return this._currentLevel;
  8362. }
  8363. getObjectForDistance( distance ) {
  8364. const levels = this.levels;
  8365. if ( levels.length > 0 ) {
  8366. let i, l;
  8367. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8368. let levelDistance = levels[ i ].distance;
  8369. if ( levels[ i ].object.visible ) {
  8370. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8371. }
  8372. if ( distance < levelDistance ) {
  8373. break;
  8374. }
  8375. }
  8376. return levels[ i - 1 ].object;
  8377. }
  8378. return null;
  8379. }
  8380. raycast( raycaster, intersects ) {
  8381. const levels = this.levels;
  8382. if ( levels.length > 0 ) {
  8383. _v1$2.setFromMatrixPosition( this.matrixWorld );
  8384. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  8385. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  8386. }
  8387. }
  8388. update( camera ) {
  8389. const levels = this.levels;
  8390. if ( levels.length > 1 ) {
  8391. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  8392. _v2$1.setFromMatrixPosition( this.matrixWorld );
  8393. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  8394. levels[ 0 ].object.visible = true;
  8395. let i, l;
  8396. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8397. let levelDistance = levels[ i ].distance;
  8398. if ( levels[ i ].object.visible ) {
  8399. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8400. }
  8401. if ( distance >= levelDistance ) {
  8402. levels[ i - 1 ].object.visible = false;
  8403. levels[ i ].object.visible = true;
  8404. } else {
  8405. break;
  8406. }
  8407. }
  8408. this._currentLevel = i - 1;
  8409. for ( ; i < l; i ++ ) {
  8410. levels[ i ].object.visible = false;
  8411. }
  8412. }
  8413. }
  8414. toJSON( meta ) {
  8415. const data = super.toJSON( meta );
  8416. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  8417. data.object.levels = [];
  8418. const levels = this.levels;
  8419. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8420. const level = levels[ i ];
  8421. data.object.levels.push( {
  8422. object: level.object.uuid,
  8423. distance: level.distance,
  8424. hysteresis: level.hysteresis
  8425. } );
  8426. }
  8427. return data;
  8428. }
  8429. }
  8430. const _basePosition = /*@__PURE__*/ new Vector3();
  8431. const _skinIndex = /*@__PURE__*/ new Vector4();
  8432. const _skinWeight = /*@__PURE__*/ new Vector4();
  8433. const _vector3 = /*@__PURE__*/ new Vector3();
  8434. const _matrix4 = /*@__PURE__*/ new Matrix4();
  8435. const _vertex = /*@__PURE__*/ new Vector3();
  8436. const _sphere$5 = /*@__PURE__*/ new Sphere();
  8437. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  8438. const _ray$2 = /*@__PURE__*/ new Ray();
  8439. class SkinnedMesh extends Mesh {
  8440. constructor( geometry, material ) {
  8441. super( geometry, material );
  8442. this.isSkinnedMesh = true;
  8443. this.type = 'SkinnedMesh';
  8444. this.bindMode = AttachedBindMode;
  8445. this.bindMatrix = new Matrix4();
  8446. this.bindMatrixInverse = new Matrix4();
  8447. this.boundingBox = null;
  8448. this.boundingSphere = null;
  8449. }
  8450. computeBoundingBox() {
  8451. const geometry = this.geometry;
  8452. if ( this.boundingBox === null ) {
  8453. this.boundingBox = new Box3();
  8454. }
  8455. this.boundingBox.makeEmpty();
  8456. const positionAttribute = geometry.getAttribute( 'position' );
  8457. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8458. this.getVertexPosition( i, _vertex );
  8459. this.boundingBox.expandByPoint( _vertex );
  8460. }
  8461. }
  8462. computeBoundingSphere() {
  8463. const geometry = this.geometry;
  8464. if ( this.boundingSphere === null ) {
  8465. this.boundingSphere = new Sphere();
  8466. }
  8467. this.boundingSphere.makeEmpty();
  8468. const positionAttribute = geometry.getAttribute( 'position' );
  8469. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8470. this.getVertexPosition( i, _vertex );
  8471. this.boundingSphere.expandByPoint( _vertex );
  8472. }
  8473. }
  8474. copy( source, recursive ) {
  8475. super.copy( source, recursive );
  8476. this.bindMode = source.bindMode;
  8477. this.bindMatrix.copy( source.bindMatrix );
  8478. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  8479. this.skeleton = source.skeleton;
  8480. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8481. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8482. return this;
  8483. }
  8484. raycast( raycaster, intersects ) {
  8485. const material = this.material;
  8486. const matrixWorld = this.matrixWorld;
  8487. if ( material === undefined ) return;
  8488. // test with bounding sphere in world space
  8489. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8490. _sphere$5.copy( this.boundingSphere );
  8491. _sphere$5.applyMatrix4( matrixWorld );
  8492. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  8493. // convert ray to local space of skinned mesh
  8494. _inverseMatrix$2.copy( matrixWorld ).invert();
  8495. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  8496. // test with bounding box in local space
  8497. if ( this.boundingBox !== null ) {
  8498. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  8499. }
  8500. // test for intersections with geometry
  8501. this._computeIntersections( raycaster, intersects, _ray$2 );
  8502. }
  8503. getVertexPosition( index, target ) {
  8504. super.getVertexPosition( index, target );
  8505. this.applyBoneTransform( index, target );
  8506. return target;
  8507. }
  8508. bind( skeleton, bindMatrix ) {
  8509. this.skeleton = skeleton;
  8510. if ( bindMatrix === undefined ) {
  8511. this.updateMatrixWorld( true );
  8512. this.skeleton.calculateInverses();
  8513. bindMatrix = this.matrixWorld;
  8514. }
  8515. this.bindMatrix.copy( bindMatrix );
  8516. this.bindMatrixInverse.copy( bindMatrix ).invert();
  8517. }
  8518. pose() {
  8519. this.skeleton.pose();
  8520. }
  8521. normalizeSkinWeights() {
  8522. const vector = new Vector4();
  8523. const skinWeight = this.geometry.attributes.skinWeight;
  8524. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  8525. vector.fromBufferAttribute( skinWeight, i );
  8526. const scale = 1.0 / vector.manhattanLength();
  8527. if ( scale !== Infinity ) {
  8528. vector.multiplyScalar( scale );
  8529. } else {
  8530. vector.set( 1, 0, 0, 0 ); // do something reasonable
  8531. }
  8532. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  8533. }
  8534. }
  8535. updateMatrixWorld( force ) {
  8536. super.updateMatrixWorld( force );
  8537. if ( this.bindMode === AttachedBindMode ) {
  8538. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  8539. } else if ( this.bindMode === DetachedBindMode ) {
  8540. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  8541. } else {
  8542. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  8543. }
  8544. }
  8545. applyBoneTransform( index, vector ) {
  8546. const skeleton = this.skeleton;
  8547. const geometry = this.geometry;
  8548. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  8549. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  8550. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  8551. vector.set( 0, 0, 0 );
  8552. for ( let i = 0; i < 4; i ++ ) {
  8553. const weight = _skinWeight.getComponent( i );
  8554. if ( weight !== 0 ) {
  8555. const boneIndex = _skinIndex.getComponent( i );
  8556. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  8557. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  8558. }
  8559. }
  8560. return vector.applyMatrix4( this.bindMatrixInverse );
  8561. }
  8562. }
  8563. class Bone extends Object3D {
  8564. constructor() {
  8565. super();
  8566. this.isBone = true;
  8567. this.type = 'Bone';
  8568. }
  8569. }
  8570. class DataTexture extends Texture {
  8571. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  8572. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  8573. this.isDataTexture = true;
  8574. this.image = { data: data, width: width, height: height };
  8575. this.generateMipmaps = false;
  8576. this.flipY = false;
  8577. this.unpackAlignment = 1;
  8578. }
  8579. }
  8580. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  8581. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  8582. class Skeleton {
  8583. constructor( bones = [], boneInverses = [] ) {
  8584. this.uuid = generateUUID();
  8585. this.bones = bones.slice( 0 );
  8586. this.boneInverses = boneInverses;
  8587. this.boneMatrices = null;
  8588. this.boneTexture = null;
  8589. this.init();
  8590. }
  8591. init() {
  8592. const bones = this.bones;
  8593. const boneInverses = this.boneInverses;
  8594. this.boneMatrices = new Float32Array( bones.length * 16 );
  8595. // calculate inverse bone matrices if necessary
  8596. if ( boneInverses.length === 0 ) {
  8597. this.calculateInverses();
  8598. } else {
  8599. // handle special case
  8600. if ( bones.length !== boneInverses.length ) {
  8601. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  8602. this.boneInverses = [];
  8603. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8604. this.boneInverses.push( new Matrix4() );
  8605. }
  8606. }
  8607. }
  8608. }
  8609. calculateInverses() {
  8610. this.boneInverses.length = 0;
  8611. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8612. const inverse = new Matrix4();
  8613. if ( this.bones[ i ] ) {
  8614. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  8615. }
  8616. this.boneInverses.push( inverse );
  8617. }
  8618. }
  8619. pose() {
  8620. // recover the bind-time world matrices
  8621. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8622. const bone = this.bones[ i ];
  8623. if ( bone ) {
  8624. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  8625. }
  8626. }
  8627. // compute the local matrices, positions, rotations and scales
  8628. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8629. const bone = this.bones[ i ];
  8630. if ( bone ) {
  8631. if ( bone.parent && bone.parent.isBone ) {
  8632. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  8633. bone.matrix.multiply( bone.matrixWorld );
  8634. } else {
  8635. bone.matrix.copy( bone.matrixWorld );
  8636. }
  8637. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  8638. }
  8639. }
  8640. }
  8641. update() {
  8642. const bones = this.bones;
  8643. const boneInverses = this.boneInverses;
  8644. const boneMatrices = this.boneMatrices;
  8645. const boneTexture = this.boneTexture;
  8646. // flatten bone matrices to array
  8647. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  8648. // compute the offset between the current and the original transform
  8649. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  8650. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  8651. _offsetMatrix.toArray( boneMatrices, i * 16 );
  8652. }
  8653. if ( boneTexture !== null ) {
  8654. boneTexture.needsUpdate = true;
  8655. }
  8656. }
  8657. clone() {
  8658. return new Skeleton( this.bones, this.boneInverses );
  8659. }
  8660. computeBoneTexture() {
  8661. // layout (1 matrix = 4 pixels)
  8662. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8663. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  8664. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  8665. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  8666. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  8667. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  8668. size = Math.ceil( size / 4 ) * 4;
  8669. size = Math.max( size, 4 );
  8670. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  8671. boneMatrices.set( this.boneMatrices ); // copy current values
  8672. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  8673. boneTexture.needsUpdate = true;
  8674. this.boneMatrices = boneMatrices;
  8675. this.boneTexture = boneTexture;
  8676. return this;
  8677. }
  8678. getBoneByName( name ) {
  8679. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8680. const bone = this.bones[ i ];
  8681. if ( bone.name === name ) {
  8682. return bone;
  8683. }
  8684. }
  8685. return undefined;
  8686. }
  8687. dispose( ) {
  8688. if ( this.boneTexture !== null ) {
  8689. this.boneTexture.dispose();
  8690. this.boneTexture = null;
  8691. }
  8692. }
  8693. fromJSON( json, bones ) {
  8694. this.uuid = json.uuid;
  8695. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  8696. const uuid = json.bones[ i ];
  8697. let bone = bones[ uuid ];
  8698. if ( bone === undefined ) {
  8699. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  8700. bone = new Bone();
  8701. }
  8702. this.bones.push( bone );
  8703. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  8704. }
  8705. this.init();
  8706. return this;
  8707. }
  8708. toJSON() {
  8709. const data = {
  8710. metadata: {
  8711. version: 4.6,
  8712. type: 'Skeleton',
  8713. generator: 'Skeleton.toJSON'
  8714. },
  8715. bones: [],
  8716. boneInverses: []
  8717. };
  8718. data.uuid = this.uuid;
  8719. const bones = this.bones;
  8720. const boneInverses = this.boneInverses;
  8721. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  8722. const bone = bones[ i ];
  8723. data.bones.push( bone.uuid );
  8724. const boneInverse = boneInverses[ i ];
  8725. data.boneInverses.push( boneInverse.toArray() );
  8726. }
  8727. return data;
  8728. }
  8729. }
  8730. class InstancedBufferAttribute extends BufferAttribute {
  8731. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  8732. super( array, itemSize, normalized );
  8733. this.isInstancedBufferAttribute = true;
  8734. this.meshPerAttribute = meshPerAttribute;
  8735. }
  8736. copy( source ) {
  8737. super.copy( source );
  8738. this.meshPerAttribute = source.meshPerAttribute;
  8739. return this;
  8740. }
  8741. toJSON() {
  8742. const data = super.toJSON();
  8743. data.meshPerAttribute = this.meshPerAttribute;
  8744. data.isInstancedBufferAttribute = true;
  8745. return data;
  8746. }
  8747. }
  8748. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  8749. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  8750. const _instanceIntersects = [];
  8751. const _box3 = /*@__PURE__*/ new Box3();
  8752. const _identity = /*@__PURE__*/ new Matrix4();
  8753. const _mesh$1 = /*@__PURE__*/ new Mesh();
  8754. const _sphere$4 = /*@__PURE__*/ new Sphere();
  8755. class InstancedMesh extends Mesh {
  8756. constructor( geometry, material, count ) {
  8757. super( geometry, material );
  8758. this.isInstancedMesh = true;
  8759. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  8760. this.instanceColor = null;
  8761. this.morphTexture = null;
  8762. this.count = count;
  8763. this.boundingBox = null;
  8764. this.boundingSphere = null;
  8765. for ( let i = 0; i < count; i ++ ) {
  8766. this.setMatrixAt( i, _identity );
  8767. }
  8768. }
  8769. computeBoundingBox() {
  8770. const geometry = this.geometry;
  8771. const count = this.count;
  8772. if ( this.boundingBox === null ) {
  8773. this.boundingBox = new Box3();
  8774. }
  8775. if ( geometry.boundingBox === null ) {
  8776. geometry.computeBoundingBox();
  8777. }
  8778. this.boundingBox.makeEmpty();
  8779. for ( let i = 0; i < count; i ++ ) {
  8780. this.getMatrixAt( i, _instanceLocalMatrix );
  8781. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  8782. this.boundingBox.union( _box3 );
  8783. }
  8784. }
  8785. computeBoundingSphere() {
  8786. const geometry = this.geometry;
  8787. const count = this.count;
  8788. if ( this.boundingSphere === null ) {
  8789. this.boundingSphere = new Sphere();
  8790. }
  8791. if ( geometry.boundingSphere === null ) {
  8792. geometry.computeBoundingSphere();
  8793. }
  8794. this.boundingSphere.makeEmpty();
  8795. for ( let i = 0; i < count; i ++ ) {
  8796. this.getMatrixAt( i, _instanceLocalMatrix );
  8797. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  8798. this.boundingSphere.union( _sphere$4 );
  8799. }
  8800. }
  8801. copy( source, recursive ) {
  8802. super.copy( source, recursive );
  8803. this.instanceMatrix.copy( source.instanceMatrix );
  8804. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  8805. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  8806. this.count = source.count;
  8807. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8808. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8809. return this;
  8810. }
  8811. getColorAt( index, color ) {
  8812. color.fromArray( this.instanceColor.array, index * 3 );
  8813. }
  8814. getMatrixAt( index, matrix ) {
  8815. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  8816. }
  8817. getMorphAt( index, object ) {
  8818. const objectInfluences = object.morphTargetInfluences;
  8819. const array = this.morphTexture.source.data.data;
  8820. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  8821. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  8822. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8823. objectInfluences[ i ] = array[ dataIndex + i ];
  8824. }
  8825. }
  8826. raycast( raycaster, intersects ) {
  8827. const matrixWorld = this.matrixWorld;
  8828. const raycastTimes = this.count;
  8829. _mesh$1.geometry = this.geometry;
  8830. _mesh$1.material = this.material;
  8831. if ( _mesh$1.material === undefined ) return;
  8832. // test with bounding sphere first
  8833. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8834. _sphere$4.copy( this.boundingSphere );
  8835. _sphere$4.applyMatrix4( matrixWorld );
  8836. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  8837. // now test each instance
  8838. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  8839. // calculate the world matrix for each instance
  8840. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  8841. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  8842. // the mesh represents this single instance
  8843. _mesh$1.matrixWorld = _instanceWorldMatrix;
  8844. _mesh$1.raycast( raycaster, _instanceIntersects );
  8845. // process the result of raycast
  8846. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  8847. const intersect = _instanceIntersects[ i ];
  8848. intersect.instanceId = instanceId;
  8849. intersect.object = this;
  8850. intersects.push( intersect );
  8851. }
  8852. _instanceIntersects.length = 0;
  8853. }
  8854. }
  8855. setColorAt( index, color ) {
  8856. if ( this.instanceColor === null ) {
  8857. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  8858. }
  8859. color.toArray( this.instanceColor.array, index * 3 );
  8860. }
  8861. setMatrixAt( index, matrix ) {
  8862. matrix.toArray( this.instanceMatrix.array, index * 16 );
  8863. }
  8864. setMorphAt( index, object ) {
  8865. const objectInfluences = object.morphTargetInfluences;
  8866. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  8867. if ( this.morphTexture === null ) {
  8868. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  8869. }
  8870. const array = this.morphTexture.source.data.data;
  8871. let morphInfluencesSum = 0;
  8872. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8873. morphInfluencesSum += objectInfluences[ i ];
  8874. }
  8875. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  8876. const dataIndex = len * index;
  8877. array[ dataIndex ] = morphBaseInfluence;
  8878. array.set( objectInfluences, dataIndex + 1 );
  8879. }
  8880. updateMorphTargets() {
  8881. }
  8882. dispose() {
  8883. this.dispatchEvent( { type: 'dispose' } );
  8884. if ( this.morphTexture !== null ) {
  8885. this.morphTexture.dispose();
  8886. this.morphTexture = null;
  8887. }
  8888. return this;
  8889. }
  8890. }
  8891. const _vector1 = /*@__PURE__*/ new Vector3();
  8892. const _vector2 = /*@__PURE__*/ new Vector3();
  8893. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8894. class Plane {
  8895. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8896. this.isPlane = true;
  8897. // normal is assumed to be normalized
  8898. this.normal = normal;
  8899. this.constant = constant;
  8900. }
  8901. set( normal, constant ) {
  8902. this.normal.copy( normal );
  8903. this.constant = constant;
  8904. return this;
  8905. }
  8906. setComponents( x, y, z, w ) {
  8907. this.normal.set( x, y, z );
  8908. this.constant = w;
  8909. return this;
  8910. }
  8911. setFromNormalAndCoplanarPoint( normal, point ) {
  8912. this.normal.copy( normal );
  8913. this.constant = - point.dot( this.normal );
  8914. return this;
  8915. }
  8916. setFromCoplanarPoints( a, b, c ) {
  8917. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8918. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8919. this.setFromNormalAndCoplanarPoint( normal, a );
  8920. return this;
  8921. }
  8922. copy( plane ) {
  8923. this.normal.copy( plane.normal );
  8924. this.constant = plane.constant;
  8925. return this;
  8926. }
  8927. normalize() {
  8928. // Note: will lead to a divide by zero if the plane is invalid.
  8929. const inverseNormalLength = 1.0 / this.normal.length();
  8930. this.normal.multiplyScalar( inverseNormalLength );
  8931. this.constant *= inverseNormalLength;
  8932. return this;
  8933. }
  8934. negate() {
  8935. this.constant *= - 1;
  8936. this.normal.negate();
  8937. return this;
  8938. }
  8939. distanceToPoint( point ) {
  8940. return this.normal.dot( point ) + this.constant;
  8941. }
  8942. distanceToSphere( sphere ) {
  8943. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8944. }
  8945. projectPoint( point, target ) {
  8946. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  8947. }
  8948. intersectLine( line, target ) {
  8949. const direction = line.delta( _vector1 );
  8950. const denominator = this.normal.dot( direction );
  8951. if ( denominator === 0 ) {
  8952. // line is coplanar, return origin
  8953. if ( this.distanceToPoint( line.start ) === 0 ) {
  8954. return target.copy( line.start );
  8955. }
  8956. // Unsure if this is the correct method to handle this case.
  8957. return null;
  8958. }
  8959. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8960. if ( t < 0 || t > 1 ) {
  8961. return null;
  8962. }
  8963. return target.copy( line.start ).addScaledVector( direction, t );
  8964. }
  8965. intersectsLine( line ) {
  8966. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8967. const startSign = this.distanceToPoint( line.start );
  8968. const endSign = this.distanceToPoint( line.end );
  8969. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8970. }
  8971. intersectsBox( box ) {
  8972. return box.intersectsPlane( this );
  8973. }
  8974. intersectsSphere( sphere ) {
  8975. return sphere.intersectsPlane( this );
  8976. }
  8977. coplanarPoint( target ) {
  8978. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8979. }
  8980. applyMatrix4( matrix, optionalNormalMatrix ) {
  8981. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  8982. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  8983. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8984. this.constant = - referencePoint.dot( normal );
  8985. return this;
  8986. }
  8987. translate( offset ) {
  8988. this.constant -= offset.dot( this.normal );
  8989. return this;
  8990. }
  8991. equals( plane ) {
  8992. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8993. }
  8994. clone() {
  8995. return new this.constructor().copy( this );
  8996. }
  8997. }
  8998. const _sphere$3 = /*@__PURE__*/ new Sphere();
  8999. const _vector$6 = /*@__PURE__*/ new Vector3();
  9000. class Frustum {
  9001. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  9002. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  9003. }
  9004. set( p0, p1, p2, p3, p4, p5 ) {
  9005. const planes = this.planes;
  9006. planes[ 0 ].copy( p0 );
  9007. planes[ 1 ].copy( p1 );
  9008. planes[ 2 ].copy( p2 );
  9009. planes[ 3 ].copy( p3 );
  9010. planes[ 4 ].copy( p4 );
  9011. planes[ 5 ].copy( p5 );
  9012. return this;
  9013. }
  9014. copy( frustum ) {
  9015. const planes = this.planes;
  9016. for ( let i = 0; i < 6; i ++ ) {
  9017. planes[ i ].copy( frustum.planes[ i ] );
  9018. }
  9019. return this;
  9020. }
  9021. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  9022. const planes = this.planes;
  9023. const me = m.elements;
  9024. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  9025. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  9026. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  9027. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  9028. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  9029. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  9030. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  9031. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  9032. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  9033. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9034. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  9035. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9036. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  9037. } else {
  9038. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  9039. }
  9040. return this;
  9041. }
  9042. intersectsObject( object ) {
  9043. if ( object.boundingSphere !== undefined ) {
  9044. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  9045. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  9046. } else {
  9047. const geometry = object.geometry;
  9048. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9049. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9050. }
  9051. return this.intersectsSphere( _sphere$3 );
  9052. }
  9053. intersectsSprite( sprite ) {
  9054. _sphere$3.center.set( 0, 0, 0 );
  9055. _sphere$3.radius = 0.7071067811865476;
  9056. _sphere$3.applyMatrix4( sprite.matrixWorld );
  9057. return this.intersectsSphere( _sphere$3 );
  9058. }
  9059. intersectsSphere( sphere ) {
  9060. const planes = this.planes;
  9061. const center = sphere.center;
  9062. const negRadius = - sphere.radius;
  9063. for ( let i = 0; i < 6; i ++ ) {
  9064. const distance = planes[ i ].distanceToPoint( center );
  9065. if ( distance < negRadius ) {
  9066. return false;
  9067. }
  9068. }
  9069. return true;
  9070. }
  9071. intersectsBox( box ) {
  9072. const planes = this.planes;
  9073. for ( let i = 0; i < 6; i ++ ) {
  9074. const plane = planes[ i ];
  9075. // corner at max distance
  9076. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9077. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9078. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9079. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  9080. return false;
  9081. }
  9082. }
  9083. return true;
  9084. }
  9085. containsPoint( point ) {
  9086. const planes = this.planes;
  9087. for ( let i = 0; i < 6; i ++ ) {
  9088. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9089. return false;
  9090. }
  9091. }
  9092. return true;
  9093. }
  9094. clone() {
  9095. return new this.constructor().copy( this );
  9096. }
  9097. }
  9098. function ascIdSort( a, b ) {
  9099. return a - b;
  9100. }
  9101. function sortOpaque( a, b ) {
  9102. return a.z - b.z;
  9103. }
  9104. function sortTransparent( a, b ) {
  9105. return b.z - a.z;
  9106. }
  9107. class MultiDrawRenderList {
  9108. constructor() {
  9109. this.index = 0;
  9110. this.pool = [];
  9111. this.list = [];
  9112. }
  9113. push( start, count, z, index ) {
  9114. const pool = this.pool;
  9115. const list = this.list;
  9116. if ( this.index >= pool.length ) {
  9117. pool.push( {
  9118. start: - 1,
  9119. count: - 1,
  9120. z: - 1,
  9121. index: - 1,
  9122. } );
  9123. }
  9124. const item = pool[ this.index ];
  9125. list.push( item );
  9126. this.index ++;
  9127. item.start = start;
  9128. item.count = count;
  9129. item.z = z;
  9130. item.index = index;
  9131. }
  9132. reset() {
  9133. this.list.length = 0;
  9134. this.index = 0;
  9135. }
  9136. }
  9137. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  9138. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  9139. const _frustum$1 = /*@__PURE__*/ new Frustum();
  9140. const _box$1 = /*@__PURE__*/ new Box3();
  9141. const _sphere$2 = /*@__PURE__*/ new Sphere();
  9142. const _vector$5 = /*@__PURE__*/ new Vector3();
  9143. const _forward = /*@__PURE__*/ new Vector3();
  9144. const _temp = /*@__PURE__*/ new Vector3();
  9145. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  9146. const _mesh = /*@__PURE__*/ new Mesh();
  9147. const _batchIntersects = [];
  9148. // copies data from attribute "src" into "target" starting at "targetOffset"
  9149. function copyAttributeData( src, target, targetOffset = 0 ) {
  9150. const itemSize = target.itemSize;
  9151. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  9152. // use the component getters and setters if the array data cannot
  9153. // be copied directly
  9154. const vertexCount = src.count;
  9155. for ( let i = 0; i < vertexCount; i ++ ) {
  9156. for ( let c = 0; c < itemSize; c ++ ) {
  9157. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  9158. }
  9159. }
  9160. } else {
  9161. // faster copy approach using typed array set function
  9162. target.array.set( src.array, targetOffset * itemSize );
  9163. }
  9164. target.needsUpdate = true;
  9165. }
  9166. // safely copies array contents to a potentially smaller array
  9167. function copyArrayContents( src, target ) {
  9168. if ( src.constructor !== target.constructor ) {
  9169. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  9170. const len = Math.min( src.length, target.length );
  9171. for ( let i = 0; i < len; i ++ ) {
  9172. target[ i ] = src[ i ];
  9173. }
  9174. } else {
  9175. // if the arrays use the same data layout we can use a fast block copy
  9176. const len = Math.min( src.length, target.length );
  9177. target.set( new src.constructor( src.buffer, 0, len ) );
  9178. }
  9179. }
  9180. class BatchedMesh extends Mesh {
  9181. get maxInstanceCount() {
  9182. return this._maxInstanceCount;
  9183. }
  9184. get instanceCount() {
  9185. return this._instanceInfo.length - this._availableInstanceIds.length;
  9186. }
  9187. get unusedVertexCount() {
  9188. return this._maxVertexCount - this._nextVertexStart;
  9189. }
  9190. get unusedIndexCount() {
  9191. return this._maxIndexCount - this._nextIndexStart;
  9192. }
  9193. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  9194. super( new BufferGeometry(), material );
  9195. this.isBatchedMesh = true;
  9196. this.perObjectFrustumCulled = true;
  9197. this.sortObjects = true;
  9198. this.boundingBox = null;
  9199. this.boundingSphere = null;
  9200. this.customSort = null;
  9201. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  9202. this._instanceInfo = [];
  9203. this._geometryInfo = [];
  9204. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  9205. this._availableInstanceIds = [];
  9206. this._availableGeometryIds = [];
  9207. // used to track where the next point is that geometry should be inserted
  9208. this._nextIndexStart = 0;
  9209. this._nextVertexStart = 0;
  9210. this._geometryCount = 0;
  9211. // flags
  9212. this._visibilityChanged = true;
  9213. this._geometryInitialized = false;
  9214. // cached user options
  9215. this._maxInstanceCount = maxInstanceCount;
  9216. this._maxVertexCount = maxVertexCount;
  9217. this._maxIndexCount = maxIndexCount;
  9218. // buffers for multi draw
  9219. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  9220. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  9221. this._multiDrawCount = 0;
  9222. this._multiDrawInstances = null;
  9223. // Local matrix per geometry by using data texture
  9224. this._matricesTexture = null;
  9225. this._indirectTexture = null;
  9226. this._colorsTexture = null;
  9227. this._initMatricesTexture();
  9228. this._initIndirectTexture();
  9229. }
  9230. _initMatricesTexture() {
  9231. // layout (1 matrix = 4 pixels)
  9232. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9233. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  9234. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  9235. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  9236. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  9237. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  9238. size = Math.ceil( size / 4 ) * 4;
  9239. size = Math.max( size, 4 );
  9240. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  9241. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  9242. this._matricesTexture = matricesTexture;
  9243. }
  9244. _initIndirectTexture() {
  9245. let size = Math.sqrt( this._maxInstanceCount );
  9246. size = Math.ceil( size );
  9247. const indirectArray = new Uint32Array( size * size );
  9248. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  9249. this._indirectTexture = indirectTexture;
  9250. }
  9251. _initColorsTexture() {
  9252. let size = Math.sqrt( this._maxInstanceCount );
  9253. size = Math.ceil( size );
  9254. // 4 floats per RGBA pixel initialized to white
  9255. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  9256. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  9257. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  9258. this._colorsTexture = colorsTexture;
  9259. }
  9260. _initializeGeometry( reference ) {
  9261. const geometry = this.geometry;
  9262. const maxVertexCount = this._maxVertexCount;
  9263. const maxIndexCount = this._maxIndexCount;
  9264. if ( this._geometryInitialized === false ) {
  9265. for ( const attributeName in reference.attributes ) {
  9266. const srcAttribute = reference.getAttribute( attributeName );
  9267. const { array, itemSize, normalized } = srcAttribute;
  9268. const dstArray = new array.constructor( maxVertexCount * itemSize );
  9269. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  9270. geometry.setAttribute( attributeName, dstAttribute );
  9271. }
  9272. if ( reference.getIndex() !== null ) {
  9273. // Reserve last u16 index for primitive restart.
  9274. const indexArray = maxVertexCount > 65535
  9275. ? new Uint32Array( maxIndexCount )
  9276. : new Uint16Array( maxIndexCount );
  9277. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  9278. }
  9279. this._geometryInitialized = true;
  9280. }
  9281. }
  9282. // Make sure the geometry is compatible with the existing combined geometry attributes
  9283. _validateGeometry( geometry ) {
  9284. // check to ensure the geometries are using consistent attributes and indices
  9285. const batchGeometry = this.geometry;
  9286. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  9287. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  9288. }
  9289. for ( const attributeName in batchGeometry.attributes ) {
  9290. if ( ! geometry.hasAttribute( attributeName ) ) {
  9291. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  9292. }
  9293. const srcAttribute = geometry.getAttribute( attributeName );
  9294. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9295. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  9296. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  9297. }
  9298. }
  9299. }
  9300. setCustomSort( func ) {
  9301. this.customSort = func;
  9302. return this;
  9303. }
  9304. computeBoundingBox() {
  9305. if ( this.boundingBox === null ) {
  9306. this.boundingBox = new Box3();
  9307. }
  9308. const boundingBox = this.boundingBox;
  9309. const instanceInfo = this._instanceInfo;
  9310. boundingBox.makeEmpty();
  9311. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9312. if ( instanceInfo[ i ].active === false ) continue;
  9313. const geometryId = instanceInfo[ i ].geometryIndex;
  9314. this.getMatrixAt( i, _matrix$1 );
  9315. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  9316. boundingBox.union( _box$1 );
  9317. }
  9318. }
  9319. computeBoundingSphere() {
  9320. if ( this.boundingSphere === null ) {
  9321. this.boundingSphere = new Sphere();
  9322. }
  9323. const boundingSphere = this.boundingSphere;
  9324. const instanceInfo = this._instanceInfo;
  9325. boundingSphere.makeEmpty();
  9326. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9327. if ( instanceInfo[ i ].active === false ) continue;
  9328. const geometryId = instanceInfo[ i ].geometryIndex;
  9329. this.getMatrixAt( i, _matrix$1 );
  9330. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9331. boundingSphere.union( _sphere$2 );
  9332. }
  9333. }
  9334. addInstance( geometryId ) {
  9335. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  9336. // ensure we're not over geometry
  9337. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  9338. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9339. }
  9340. const instanceInfo = {
  9341. visible: true,
  9342. active: true,
  9343. geometryIndex: geometryId,
  9344. };
  9345. let drawId = null;
  9346. // Prioritize using previously freed instance ids
  9347. if ( this._availableInstanceIds.length > 0 ) {
  9348. this._availableInstanceIds.sort( ascIdSort );
  9349. drawId = this._availableInstanceIds.shift();
  9350. this._instanceInfo[ drawId ] = instanceInfo;
  9351. } else {
  9352. drawId = this._instanceInfo.length;
  9353. this._instanceInfo.push( instanceInfo );
  9354. }
  9355. const matricesTexture = this._matricesTexture;
  9356. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  9357. matricesTexture.needsUpdate = true;
  9358. const colorsTexture = this._colorsTexture;
  9359. if ( colorsTexture ) {
  9360. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  9361. colorsTexture.needsUpdate = true;
  9362. }
  9363. this._visibilityChanged = true;
  9364. return drawId;
  9365. }
  9366. addGeometry( geometry, reservedVertexCount = - 1, reservedIndexCount = - 1 ) {
  9367. this._initializeGeometry( geometry );
  9368. this._validateGeometry( geometry );
  9369. const geometryInfo = {
  9370. // geometry information
  9371. vertexStart: - 1,
  9372. vertexCount: - 1,
  9373. reservedVertexCount: - 1,
  9374. indexStart: - 1,
  9375. indexCount: - 1,
  9376. reservedIndexCount: - 1,
  9377. // draw range information
  9378. start: - 1,
  9379. count: - 1,
  9380. // state
  9381. boundingBox: null,
  9382. boundingSphere: null,
  9383. active: true,
  9384. };
  9385. const geometryInfoList = this._geometryInfo;
  9386. geometryInfo.vertexStart = this._nextVertexStart;
  9387. geometryInfo.reservedVertexCount = reservedVertexCount === - 1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  9388. const index = geometry.getIndex();
  9389. const hasIndex = index !== null;
  9390. if ( hasIndex ) {
  9391. geometryInfo.indexStart = this._nextIndexStart;
  9392. geometryInfo.reservedIndexCount = reservedIndexCount === - 1 ? index.count : reservedIndexCount;
  9393. }
  9394. if (
  9395. geometryInfo.indexStart !== - 1 &&
  9396. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  9397. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  9398. ) {
  9399. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  9400. }
  9401. // update id
  9402. let geometryId;
  9403. if ( this._availableGeometryIds.length > 0 ) {
  9404. this._availableGeometryIds.sort( ascIdSort );
  9405. geometryId = this._availableGeometryIds.shift();
  9406. geometryInfoList[ geometryId ] = geometryInfo;
  9407. } else {
  9408. geometryId = this._geometryCount;
  9409. this._geometryCount ++;
  9410. geometryInfoList.push( geometryInfo );
  9411. }
  9412. // update the geometry
  9413. this.setGeometryAt( geometryId, geometry );
  9414. // increment the next geometry position
  9415. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  9416. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  9417. return geometryId;
  9418. }
  9419. setGeometryAt( geometryId, geometry ) {
  9420. if ( geometryId >= this._geometryCount ) {
  9421. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  9422. }
  9423. this._validateGeometry( geometry );
  9424. const batchGeometry = this.geometry;
  9425. const hasIndex = batchGeometry.getIndex() !== null;
  9426. const dstIndex = batchGeometry.getIndex();
  9427. const srcIndex = geometry.getIndex();
  9428. const geometryInfo = this._geometryInfo[ geometryId ];
  9429. if (
  9430. hasIndex &&
  9431. srcIndex.count > geometryInfo.reservedIndexCount ||
  9432. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  9433. ) {
  9434. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  9435. }
  9436. // copy geometry buffer data over
  9437. const vertexStart = geometryInfo.vertexStart;
  9438. const reservedVertexCount = geometryInfo.reservedVertexCount;
  9439. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  9440. for ( const attributeName in batchGeometry.attributes ) {
  9441. // copy attribute data
  9442. const srcAttribute = geometry.getAttribute( attributeName );
  9443. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9444. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  9445. // fill the rest in with zeroes
  9446. const itemSize = srcAttribute.itemSize;
  9447. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  9448. const index = vertexStart + i;
  9449. for ( let c = 0; c < itemSize; c ++ ) {
  9450. dstAttribute.setComponent( index, c, 0 );
  9451. }
  9452. }
  9453. dstAttribute.needsUpdate = true;
  9454. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  9455. }
  9456. // copy index
  9457. if ( hasIndex ) {
  9458. const indexStart = geometryInfo.indexStart;
  9459. const reservedIndexCount = geometryInfo.reservedIndexCount;
  9460. geometryInfo.indexCount = geometry.getIndex().count;
  9461. // copy index data over
  9462. for ( let i = 0; i < srcIndex.count; i ++ ) {
  9463. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  9464. }
  9465. // fill the rest in with zeroes
  9466. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  9467. dstIndex.setX( indexStart + i, vertexStart );
  9468. }
  9469. dstIndex.needsUpdate = true;
  9470. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  9471. }
  9472. // update the draw range
  9473. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  9474. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  9475. // store the bounding boxes
  9476. geometryInfo.boundingBox = null;
  9477. if ( geometry.boundingBox !== null ) {
  9478. geometryInfo.boundingBox = geometry.boundingBox.clone();
  9479. }
  9480. geometryInfo.boundingSphere = null;
  9481. if ( geometry.boundingSphere !== null ) {
  9482. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  9483. }
  9484. this._visibilityChanged = true;
  9485. return geometryId;
  9486. }
  9487. deleteGeometry( geometryId ) {
  9488. const geometryInfoList = this._geometryInfo;
  9489. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  9490. return this;
  9491. }
  9492. // delete any instances associated with this geometry
  9493. const instanceInfo = this._instanceInfo;
  9494. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9495. if ( instanceInfo[ i ].geometryIndex === geometryId ) {
  9496. this.deleteInstance( i );
  9497. }
  9498. }
  9499. geometryInfoList[ geometryId ].active = false;
  9500. this._availableGeometryIds.push( geometryId );
  9501. this._visibilityChanged = true;
  9502. return this;
  9503. }
  9504. deleteInstance( instanceId ) {
  9505. const instanceInfo = this._instanceInfo;
  9506. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9507. return this;
  9508. }
  9509. instanceInfo[ instanceId ].active = false;
  9510. this._availableInstanceIds.push( instanceId );
  9511. this._visibilityChanged = true;
  9512. return this;
  9513. }
  9514. optimize() {
  9515. // track the next indices to copy data to
  9516. let nextVertexStart = 0;
  9517. let nextIndexStart = 0;
  9518. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  9519. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  9520. const geometryInfoList = this._geometryInfo;
  9521. const indices = geometryInfoList
  9522. .map( ( e, i ) => i )
  9523. .sort( ( a, b ) => {
  9524. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  9525. } );
  9526. const geometry = this.geometry;
  9527. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  9528. // if a geometry range is inactive then don't copy anything
  9529. const index = indices[ i ];
  9530. const geometryInfo = geometryInfoList[ index ];
  9531. if ( geometryInfo.active === false ) {
  9532. continue;
  9533. }
  9534. // if a geometry contains an index buffer then shift it, as well
  9535. if ( geometry.index !== null ) {
  9536. if ( geometryInfo.indexStart !== nextIndexStart ) {
  9537. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  9538. const index = geometry.index;
  9539. const array = index.array;
  9540. // shift the index pointers based on how the vertex data will shift
  9541. // adjusting the index must happen first so the original vertex start value is available
  9542. const elementDelta = nextVertexStart - vertexStart;
  9543. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  9544. array[ j ] = array[ j ] + elementDelta;
  9545. }
  9546. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  9547. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  9548. geometryInfo.indexStart = nextIndexStart;
  9549. }
  9550. nextIndexStart += geometryInfo.reservedIndexCount;
  9551. }
  9552. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  9553. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  9554. const { vertexStart, reservedVertexCount } = geometryInfo;
  9555. const attributes = geometry.attributes;
  9556. for ( const key in attributes ) {
  9557. const attribute = attributes[ key ];
  9558. const { array, itemSize } = attribute;
  9559. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  9560. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  9561. }
  9562. geometryInfo.vertexStart = nextVertexStart;
  9563. }
  9564. nextVertexStart += geometryInfo.reservedVertexCount;
  9565. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  9566. // step the next geometry points to the shifted position
  9567. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  9568. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  9569. }
  9570. return this;
  9571. }
  9572. // get bounding box and compute it if it doesn't exist
  9573. getBoundingBoxAt( geometryId, target ) {
  9574. if ( geometryId >= this._geometryCount ) {
  9575. return null;
  9576. }
  9577. // compute bounding box
  9578. const geometry = this.geometry;
  9579. const geometryInfo = this._geometryInfo[ geometryId ];
  9580. if ( geometryInfo.boundingBox === null ) {
  9581. const box = new Box3();
  9582. const index = geometry.index;
  9583. const position = geometry.attributes.position;
  9584. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  9585. let iv = i;
  9586. if ( index ) {
  9587. iv = index.getX( iv );
  9588. }
  9589. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  9590. }
  9591. geometryInfo.boundingBox = box;
  9592. }
  9593. target.copy( geometryInfo.boundingBox );
  9594. return target;
  9595. }
  9596. // get bounding sphere and compute it if it doesn't exist
  9597. getBoundingSphereAt( geometryId, target ) {
  9598. if ( geometryId >= this._geometryCount ) {
  9599. return null;
  9600. }
  9601. // compute bounding sphere
  9602. const geometry = this.geometry;
  9603. const geometryInfo = this._geometryInfo[ geometryId ];
  9604. if ( geometryInfo.boundingSphere === null ) {
  9605. const sphere = new Sphere();
  9606. this.getBoundingBoxAt( geometryId, _box$1 );
  9607. _box$1.getCenter( sphere.center );
  9608. const index = geometry.index;
  9609. const position = geometry.attributes.position;
  9610. let maxRadiusSq = 0;
  9611. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  9612. let iv = i;
  9613. if ( index ) {
  9614. iv = index.getX( iv );
  9615. }
  9616. _vector$5.fromBufferAttribute( position, iv );
  9617. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  9618. }
  9619. sphere.radius = Math.sqrt( maxRadiusSq );
  9620. geometryInfo.boundingSphere = sphere;
  9621. }
  9622. target.copy( geometryInfo.boundingSphere );
  9623. return target;
  9624. }
  9625. setMatrixAt( instanceId, matrix ) {
  9626. const instanceInfo = this._instanceInfo;
  9627. const matricesTexture = this._matricesTexture;
  9628. const matricesArray = this._matricesTexture.image.data;
  9629. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9630. return this;
  9631. }
  9632. matrix.toArray( matricesArray, instanceId * 16 );
  9633. matricesTexture.needsUpdate = true;
  9634. return this;
  9635. }
  9636. getMatrixAt( instanceId, matrix ) {
  9637. const instanceInfo = this._instanceInfo;
  9638. const matricesArray = this._matricesTexture.image.data;
  9639. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9640. return null;
  9641. }
  9642. return matrix.fromArray( matricesArray, instanceId * 16 );
  9643. }
  9644. setColorAt( instanceId, color ) {
  9645. if ( this._colorsTexture === null ) {
  9646. this._initColorsTexture();
  9647. }
  9648. const colorsTexture = this._colorsTexture;
  9649. const colorsArray = this._colorsTexture.image.data;
  9650. const instanceInfo = this._instanceInfo;
  9651. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9652. return this;
  9653. }
  9654. color.toArray( colorsArray, instanceId * 4 );
  9655. colorsTexture.needsUpdate = true;
  9656. return this;
  9657. }
  9658. getColorAt( instanceId, color ) {
  9659. const colorsArray = this._colorsTexture.image.data;
  9660. const instanceInfo = this._instanceInfo;
  9661. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9662. return null;
  9663. }
  9664. return color.fromArray( colorsArray, instanceId * 4 );
  9665. }
  9666. setVisibleAt( instanceId, value ) {
  9667. // if the geometry is out of range, not active, or visibility state
  9668. // does not change then return early
  9669. const instanceInfo = this._instanceInfo;
  9670. if (
  9671. instanceId >= instanceInfo.length ||
  9672. instanceInfo[ instanceId ].active === false ||
  9673. instanceInfo[ instanceId ].visible === value
  9674. ) {
  9675. return this;
  9676. }
  9677. instanceInfo[ instanceId ].visible = value;
  9678. this._visibilityChanged = true;
  9679. return this;
  9680. }
  9681. getVisibleAt( instanceId ) {
  9682. // return early if the geometry is out of range or not active
  9683. const instanceInfo = this._instanceInfo;
  9684. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9685. return false;
  9686. }
  9687. return instanceInfo[ instanceId ].visible;
  9688. }
  9689. setGeometryIdAt( instanceId, geometryId ) {
  9690. // return early if the geometry is out of range or not active
  9691. const instanceInfo = this._instanceInfo;
  9692. const geometryInfoList = this._geometryInfo;
  9693. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9694. return null;
  9695. }
  9696. // check if the provided geometryId is within the valid range
  9697. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  9698. return null;
  9699. }
  9700. instanceInfo[ instanceId ].geometryIndex = geometryId;
  9701. return this;
  9702. }
  9703. getGeometryIdAt( instanceId ) {
  9704. const instanceInfo = this._instanceInfo;
  9705. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9706. return - 1;
  9707. }
  9708. return instanceInfo[ instanceId ].geometryIndex;
  9709. }
  9710. getGeometryRangeAt( geometryId, target = {} ) {
  9711. if ( geometryId < 0 || geometryId >= this._geometryCount ) {
  9712. return null;
  9713. }
  9714. const geometryInfo = this._geometryInfo[ geometryId ];
  9715. target.vertexStart = geometryInfo.vertexStart;
  9716. target.vertexCount = geometryInfo.vertexCount;
  9717. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  9718. target.indexStart = geometryInfo.indexStart;
  9719. target.indexCount = geometryInfo.indexCount;
  9720. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  9721. target.start = geometryInfo.start;
  9722. target.count = geometryInfo.count;
  9723. return target;
  9724. }
  9725. setInstanceCount( maxInstanceCount ) {
  9726. // shrink the available instances as much as possible
  9727. const availableInstanceIds = this._availableInstanceIds;
  9728. const instanceInfo = this._instanceInfo;
  9729. availableInstanceIds.sort( ascIdSort );
  9730. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length ) {
  9731. instanceInfo.pop();
  9732. availableInstanceIds.pop();
  9733. }
  9734. // throw an error if it can't be shrunk to the desired size
  9735. if ( maxInstanceCount < instanceInfo.length ) {
  9736. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  9737. }
  9738. // copy the multi draw counts
  9739. const multiDrawCounts = new Int32Array( maxInstanceCount );
  9740. const multiDrawStarts = new Int32Array( maxInstanceCount );
  9741. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  9742. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  9743. this._multiDrawCounts = multiDrawCounts;
  9744. this._multiDrawStarts = multiDrawStarts;
  9745. this._maxInstanceCount = maxInstanceCount;
  9746. // update texture data for instance sampling
  9747. const indirectTexture = this._indirectTexture;
  9748. const matricesTexture = this._matricesTexture;
  9749. const colorsTexture = this._colorsTexture;
  9750. indirectTexture.dispose();
  9751. this._initIndirectTexture();
  9752. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  9753. matricesTexture.dispose();
  9754. this._initMatricesTexture();
  9755. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  9756. if ( colorsTexture ) {
  9757. colorsTexture.dispose();
  9758. this._initColorsTexture();
  9759. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  9760. }
  9761. }
  9762. setGeometrySize( maxVertexCount, maxIndexCount ) {
  9763. // Check if we can shrink to the requested vertex attribute size
  9764. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  9765. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  9766. if ( requiredVertexLength > maxVertexCount ) {
  9767. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  9768. }
  9769. // Check if we can shrink to the requested index attribute size
  9770. if ( this.geometry.index ) {
  9771. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  9772. if ( requiredIndexLength > maxIndexCount ) {
  9773. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  9774. }
  9775. }
  9776. //
  9777. // dispose of the previous geometry
  9778. const oldGeometry = this.geometry;
  9779. oldGeometry.dispose();
  9780. // recreate the geometry needed based on the previous variant
  9781. this._maxVertexCount = maxVertexCount;
  9782. this._maxIndexCount = maxIndexCount;
  9783. if ( this._geometryInitialized ) {
  9784. this._geometryInitialized = false;
  9785. this.geometry = new BufferGeometry();
  9786. this._initializeGeometry( oldGeometry );
  9787. }
  9788. // copy data from the previous geometry
  9789. const geometry = this.geometry;
  9790. if ( oldGeometry.index ) {
  9791. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  9792. }
  9793. for ( const key in oldGeometry.attributes ) {
  9794. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  9795. }
  9796. }
  9797. raycast( raycaster, intersects ) {
  9798. const instanceInfo = this._instanceInfo;
  9799. const geometryInfoList = this._geometryInfo;
  9800. const matrixWorld = this.matrixWorld;
  9801. const batchGeometry = this.geometry;
  9802. // iterate over each geometry
  9803. _mesh.material = this.material;
  9804. _mesh.geometry.index = batchGeometry.index;
  9805. _mesh.geometry.attributes = batchGeometry.attributes;
  9806. if ( _mesh.geometry.boundingBox === null ) {
  9807. _mesh.geometry.boundingBox = new Box3();
  9808. }
  9809. if ( _mesh.geometry.boundingSphere === null ) {
  9810. _mesh.geometry.boundingSphere = new Sphere();
  9811. }
  9812. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9813. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  9814. continue;
  9815. }
  9816. const geometryId = instanceInfo[ i ].geometryIndex;
  9817. const geometryInfo = geometryInfoList[ geometryId ];
  9818. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  9819. // get the intersects
  9820. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  9821. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  9822. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  9823. _mesh.raycast( raycaster, _batchIntersects );
  9824. // add batch id to the intersects
  9825. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  9826. const intersect = _batchIntersects[ j ];
  9827. intersect.object = this;
  9828. intersect.batchId = i;
  9829. intersects.push( intersect );
  9830. }
  9831. _batchIntersects.length = 0;
  9832. }
  9833. _mesh.material = null;
  9834. _mesh.geometry.index = null;
  9835. _mesh.geometry.attributes = {};
  9836. _mesh.geometry.setDrawRange( 0, Infinity );
  9837. }
  9838. copy( source ) {
  9839. super.copy( source );
  9840. this.geometry = source.geometry.clone();
  9841. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  9842. this.sortObjects = source.sortObjects;
  9843. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  9844. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  9845. this._geometryInfo = source._geometryInfo.map( info => ( {
  9846. ...info,
  9847. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  9848. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  9849. } ) );
  9850. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  9851. this._maxInstanceCount = source._maxInstanceCount;
  9852. this._maxVertexCount = source._maxVertexCount;
  9853. this._maxIndexCount = source._maxIndexCount;
  9854. this._geometryInitialized = source._geometryInitialized;
  9855. this._geometryCount = source._geometryCount;
  9856. this._multiDrawCounts = source._multiDrawCounts.slice();
  9857. this._multiDrawStarts = source._multiDrawStarts.slice();
  9858. this._matricesTexture = source._matricesTexture.clone();
  9859. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  9860. if ( this._colorsTexture !== null ) {
  9861. this._colorsTexture = source._colorsTexture.clone();
  9862. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  9863. }
  9864. return this;
  9865. }
  9866. dispose() {
  9867. // Assuming the geometry is not shared with other meshes
  9868. this.geometry.dispose();
  9869. this._matricesTexture.dispose();
  9870. this._matricesTexture = null;
  9871. this._indirectTexture.dispose();
  9872. this._indirectTexture = null;
  9873. if ( this._colorsTexture !== null ) {
  9874. this._colorsTexture.dispose();
  9875. this._colorsTexture = null;
  9876. }
  9877. return this;
  9878. }
  9879. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  9880. // if visibility has not changed and frustum culling and object sorting is not required
  9881. // then skip iterating over all items
  9882. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  9883. return;
  9884. }
  9885. // the indexed version of the multi draw function requires specifying the start
  9886. // offset in bytes.
  9887. const index = geometry.getIndex();
  9888. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  9889. const instanceInfo = this._instanceInfo;
  9890. const multiDrawStarts = this._multiDrawStarts;
  9891. const multiDrawCounts = this._multiDrawCounts;
  9892. const geometryInfoList = this._geometryInfo;
  9893. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  9894. const indirectTexture = this._indirectTexture;
  9895. const indirectArray = indirectTexture.image.data;
  9896. // prepare the frustum in the local frame
  9897. if ( perObjectFrustumCulled ) {
  9898. _matrix$1
  9899. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  9900. .multiply( this.matrixWorld );
  9901. _frustum$1.setFromProjectionMatrix(
  9902. _matrix$1,
  9903. renderer.coordinateSystem
  9904. );
  9905. }
  9906. let multiDrawCount = 0;
  9907. if ( this.sortObjects ) {
  9908. // get the camera position in the local frame
  9909. _matrix$1.copy( this.matrixWorld ).invert();
  9910. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  9911. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  9912. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9913. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  9914. const geometryId = instanceInfo[ i ].geometryIndex;
  9915. // get the bounds in world space
  9916. this.getMatrixAt( i, _matrix$1 );
  9917. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9918. // determine whether the batched geometry is within the frustum
  9919. let culled = false;
  9920. if ( perObjectFrustumCulled ) {
  9921. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9922. }
  9923. if ( ! culled ) {
  9924. // get the distance from camera used for sorting
  9925. const geometryInfo = geometryInfoList[ geometryId ];
  9926. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  9927. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  9928. }
  9929. }
  9930. }
  9931. // Sort the draw ranges and prep for rendering
  9932. const list = _renderList.list;
  9933. const customSort = this.customSort;
  9934. if ( customSort === null ) {
  9935. list.sort( material.transparent ? sortTransparent : sortOpaque );
  9936. } else {
  9937. customSort.call( this, list, camera );
  9938. }
  9939. for ( let i = 0, l = list.length; i < l; i ++ ) {
  9940. const item = list[ i ];
  9941. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  9942. multiDrawCounts[ multiDrawCount ] = item.count;
  9943. indirectArray[ multiDrawCount ] = item.index;
  9944. multiDrawCount ++;
  9945. }
  9946. _renderList.reset();
  9947. } else {
  9948. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9949. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  9950. const geometryId = instanceInfo[ i ].geometryIndex;
  9951. // determine whether the batched geometry is within the frustum
  9952. let culled = false;
  9953. if ( perObjectFrustumCulled ) {
  9954. // get the bounds in world space
  9955. this.getMatrixAt( i, _matrix$1 );
  9956. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9957. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9958. }
  9959. if ( ! culled ) {
  9960. const geometryInfo = geometryInfoList[ geometryId ];
  9961. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  9962. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  9963. indirectArray[ multiDrawCount ] = i;
  9964. multiDrawCount ++;
  9965. }
  9966. }
  9967. }
  9968. }
  9969. indirectTexture.needsUpdate = true;
  9970. this._multiDrawCount = multiDrawCount;
  9971. this._visibilityChanged = false;
  9972. }
  9973. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  9974. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  9975. }
  9976. }
  9977. class LineBasicMaterial extends Material {
  9978. static get type() {
  9979. return 'LineBasicMaterial';
  9980. }
  9981. constructor( parameters ) {
  9982. super();
  9983. this.isLineBasicMaterial = true;
  9984. this.color = new Color( 0xffffff );
  9985. this.map = null;
  9986. this.linewidth = 1;
  9987. this.linecap = 'round';
  9988. this.linejoin = 'round';
  9989. this.fog = true;
  9990. this.setValues( parameters );
  9991. }
  9992. copy( source ) {
  9993. super.copy( source );
  9994. this.color.copy( source.color );
  9995. this.map = source.map;
  9996. this.linewidth = source.linewidth;
  9997. this.linecap = source.linecap;
  9998. this.linejoin = source.linejoin;
  9999. this.fog = source.fog;
  10000. return this;
  10001. }
  10002. }
  10003. const _vStart = /*@__PURE__*/ new Vector3();
  10004. const _vEnd = /*@__PURE__*/ new Vector3();
  10005. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  10006. const _ray$1 = /*@__PURE__*/ new Ray();
  10007. const _sphere$1 = /*@__PURE__*/ new Sphere();
  10008. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  10009. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  10010. class Line extends Object3D {
  10011. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  10012. super();
  10013. this.isLine = true;
  10014. this.type = 'Line';
  10015. this.geometry = geometry;
  10016. this.material = material;
  10017. this.updateMorphTargets();
  10018. }
  10019. copy( source, recursive ) {
  10020. super.copy( source, recursive );
  10021. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  10022. this.geometry = source.geometry;
  10023. return this;
  10024. }
  10025. computeLineDistances() {
  10026. const geometry = this.geometry;
  10027. // we assume non-indexed geometry
  10028. if ( geometry.index === null ) {
  10029. const positionAttribute = geometry.attributes.position;
  10030. const lineDistances = [ 0 ];
  10031. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  10032. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  10033. _vEnd.fromBufferAttribute( positionAttribute, i );
  10034. lineDistances[ i ] = lineDistances[ i - 1 ];
  10035. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  10036. }
  10037. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  10038. } else {
  10039. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  10040. }
  10041. return this;
  10042. }
  10043. raycast( raycaster, intersects ) {
  10044. const geometry = this.geometry;
  10045. const matrixWorld = this.matrixWorld;
  10046. const threshold = raycaster.params.Line.threshold;
  10047. const drawRange = geometry.drawRange;
  10048. // Checking boundingSphere distance to ray
  10049. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10050. _sphere$1.copy( geometry.boundingSphere );
  10051. _sphere$1.applyMatrix4( matrixWorld );
  10052. _sphere$1.radius += threshold;
  10053. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  10054. //
  10055. _inverseMatrix$1.copy( matrixWorld ).invert();
  10056. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  10057. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  10058. const localThresholdSq = localThreshold * localThreshold;
  10059. const step = this.isLineSegments ? 2 : 1;
  10060. const index = geometry.index;
  10061. const attributes = geometry.attributes;
  10062. const positionAttribute = attributes.position;
  10063. if ( index !== null ) {
  10064. const start = Math.max( 0, drawRange.start );
  10065. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10066. for ( let i = start, l = end - 1; i < l; i += step ) {
  10067. const a = index.getX( i );
  10068. const b = index.getX( i + 1 );
  10069. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  10070. if ( intersect ) {
  10071. intersects.push( intersect );
  10072. }
  10073. }
  10074. if ( this.isLineLoop ) {
  10075. const a = index.getX( end - 1 );
  10076. const b = index.getX( start );
  10077. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  10078. if ( intersect ) {
  10079. intersects.push( intersect );
  10080. }
  10081. }
  10082. } else {
  10083. const start = Math.max( 0, drawRange.start );
  10084. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10085. for ( let i = start, l = end - 1; i < l; i += step ) {
  10086. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  10087. if ( intersect ) {
  10088. intersects.push( intersect );
  10089. }
  10090. }
  10091. if ( this.isLineLoop ) {
  10092. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  10093. if ( intersect ) {
  10094. intersects.push( intersect );
  10095. }
  10096. }
  10097. }
  10098. }
  10099. updateMorphTargets() {
  10100. const geometry = this.geometry;
  10101. const morphAttributes = geometry.morphAttributes;
  10102. const keys = Object.keys( morphAttributes );
  10103. if ( keys.length > 0 ) {
  10104. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10105. if ( morphAttribute !== undefined ) {
  10106. this.morphTargetInfluences = [];
  10107. this.morphTargetDictionary = {};
  10108. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10109. const name = morphAttribute[ m ].name || String( m );
  10110. this.morphTargetInfluences.push( 0 );
  10111. this.morphTargetDictionary[ name ] = m;
  10112. }
  10113. }
  10114. }
  10115. }
  10116. }
  10117. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  10118. const positionAttribute = object.geometry.attributes.position;
  10119. _vStart.fromBufferAttribute( positionAttribute, a );
  10120. _vEnd.fromBufferAttribute( positionAttribute, b );
  10121. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  10122. if ( distSq > thresholdSq ) return;
  10123. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  10124. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  10125. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10126. return {
  10127. distance: distance,
  10128. // What do we want? intersection point on the ray or on the segment??
  10129. // point: raycaster.ray.at( distance ),
  10130. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  10131. index: a,
  10132. face: null,
  10133. faceIndex: null,
  10134. barycoord: null,
  10135. object: object
  10136. };
  10137. }
  10138. const _start = /*@__PURE__*/ new Vector3();
  10139. const _end = /*@__PURE__*/ new Vector3();
  10140. class LineSegments extends Line {
  10141. constructor( geometry, material ) {
  10142. super( geometry, material );
  10143. this.isLineSegments = true;
  10144. this.type = 'LineSegments';
  10145. }
  10146. computeLineDistances() {
  10147. const geometry = this.geometry;
  10148. // we assume non-indexed geometry
  10149. if ( geometry.index === null ) {
  10150. const positionAttribute = geometry.attributes.position;
  10151. const lineDistances = [];
  10152. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  10153. _start.fromBufferAttribute( positionAttribute, i );
  10154. _end.fromBufferAttribute( positionAttribute, i + 1 );
  10155. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  10156. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  10157. }
  10158. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  10159. } else {
  10160. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  10161. }
  10162. return this;
  10163. }
  10164. }
  10165. class LineLoop extends Line {
  10166. constructor( geometry, material ) {
  10167. super( geometry, material );
  10168. this.isLineLoop = true;
  10169. this.type = 'LineLoop';
  10170. }
  10171. }
  10172. class PointsMaterial extends Material {
  10173. static get type() {
  10174. return 'PointsMaterial';
  10175. }
  10176. constructor( parameters ) {
  10177. super();
  10178. this.isPointsMaterial = true;
  10179. this.color = new Color( 0xffffff );
  10180. this.map = null;
  10181. this.alphaMap = null;
  10182. this.size = 1;
  10183. this.sizeAttenuation = true;
  10184. this.fog = true;
  10185. this.setValues( parameters );
  10186. }
  10187. copy( source ) {
  10188. super.copy( source );
  10189. this.color.copy( source.color );
  10190. this.map = source.map;
  10191. this.alphaMap = source.alphaMap;
  10192. this.size = source.size;
  10193. this.sizeAttenuation = source.sizeAttenuation;
  10194. this.fog = source.fog;
  10195. return this;
  10196. }
  10197. }
  10198. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  10199. const _ray = /*@__PURE__*/ new Ray();
  10200. const _sphere = /*@__PURE__*/ new Sphere();
  10201. const _position$2 = /*@__PURE__*/ new Vector3();
  10202. class Points extends Object3D {
  10203. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  10204. super();
  10205. this.isPoints = true;
  10206. this.type = 'Points';
  10207. this.geometry = geometry;
  10208. this.material = material;
  10209. this.updateMorphTargets();
  10210. }
  10211. copy( source, recursive ) {
  10212. super.copy( source, recursive );
  10213. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  10214. this.geometry = source.geometry;
  10215. return this;
  10216. }
  10217. raycast( raycaster, intersects ) {
  10218. const geometry = this.geometry;
  10219. const matrixWorld = this.matrixWorld;
  10220. const threshold = raycaster.params.Points.threshold;
  10221. const drawRange = geometry.drawRange;
  10222. // Checking boundingSphere distance to ray
  10223. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10224. _sphere.copy( geometry.boundingSphere );
  10225. _sphere.applyMatrix4( matrixWorld );
  10226. _sphere.radius += threshold;
  10227. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  10228. //
  10229. _inverseMatrix.copy( matrixWorld ).invert();
  10230. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  10231. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  10232. const localThresholdSq = localThreshold * localThreshold;
  10233. const index = geometry.index;
  10234. const attributes = geometry.attributes;
  10235. const positionAttribute = attributes.position;
  10236. if ( index !== null ) {
  10237. const start = Math.max( 0, drawRange.start );
  10238. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10239. for ( let i = start, il = end; i < il; i ++ ) {
  10240. const a = index.getX( i );
  10241. _position$2.fromBufferAttribute( positionAttribute, a );
  10242. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10243. }
  10244. } else {
  10245. const start = Math.max( 0, drawRange.start );
  10246. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10247. for ( let i = start, l = end; i < l; i ++ ) {
  10248. _position$2.fromBufferAttribute( positionAttribute, i );
  10249. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10250. }
  10251. }
  10252. }
  10253. updateMorphTargets() {
  10254. const geometry = this.geometry;
  10255. const morphAttributes = geometry.morphAttributes;
  10256. const keys = Object.keys( morphAttributes );
  10257. if ( keys.length > 0 ) {
  10258. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10259. if ( morphAttribute !== undefined ) {
  10260. this.morphTargetInfluences = [];
  10261. this.morphTargetDictionary = {};
  10262. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10263. const name = morphAttribute[ m ].name || String( m );
  10264. this.morphTargetInfluences.push( 0 );
  10265. this.morphTargetDictionary[ name ] = m;
  10266. }
  10267. }
  10268. }
  10269. }
  10270. }
  10271. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  10272. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  10273. if ( rayPointDistanceSq < localThresholdSq ) {
  10274. const intersectPoint = new Vector3();
  10275. _ray.closestPointToPoint( point, intersectPoint );
  10276. intersectPoint.applyMatrix4( matrixWorld );
  10277. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  10278. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10279. intersects.push( {
  10280. distance: distance,
  10281. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  10282. point: intersectPoint,
  10283. index: index,
  10284. face: null,
  10285. faceIndex: null,
  10286. barycoord: null,
  10287. object: object
  10288. } );
  10289. }
  10290. }
  10291. class Group extends Object3D {
  10292. constructor() {
  10293. super();
  10294. this.isGroup = true;
  10295. this.type = 'Group';
  10296. }
  10297. }
  10298. class VideoTexture extends Texture {
  10299. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10300. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10301. this.isVideoTexture = true;
  10302. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  10303. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  10304. this.generateMipmaps = false;
  10305. const scope = this;
  10306. function updateVideo() {
  10307. scope.needsUpdate = true;
  10308. video.requestVideoFrameCallback( updateVideo );
  10309. }
  10310. if ( 'requestVideoFrameCallback' in video ) {
  10311. video.requestVideoFrameCallback( updateVideo );
  10312. }
  10313. }
  10314. clone() {
  10315. return new this.constructor( this.image ).copy( this );
  10316. }
  10317. update() {
  10318. const video = this.image;
  10319. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  10320. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  10321. this.needsUpdate = true;
  10322. }
  10323. }
  10324. }
  10325. class FramebufferTexture extends Texture {
  10326. constructor( width, height ) {
  10327. super( { width, height } );
  10328. this.isFramebufferTexture = true;
  10329. this.magFilter = NearestFilter;
  10330. this.minFilter = NearestFilter;
  10331. this.generateMipmaps = false;
  10332. this.needsUpdate = true;
  10333. }
  10334. }
  10335. class CompressedTexture extends Texture {
  10336. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  10337. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10338. this.isCompressedTexture = true;
  10339. this.image = { width: width, height: height };
  10340. this.mipmaps = mipmaps;
  10341. // no flipping for cube textures
  10342. // (also flipping doesn't work for compressed textures )
  10343. this.flipY = false;
  10344. // can't generate mipmaps for compressed textures
  10345. // mips must be embedded in DDS files
  10346. this.generateMipmaps = false;
  10347. }
  10348. }
  10349. class CompressedArrayTexture extends CompressedTexture {
  10350. constructor( mipmaps, width, height, depth, format, type ) {
  10351. super( mipmaps, width, height, format, type );
  10352. this.isCompressedArrayTexture = true;
  10353. this.image.depth = depth;
  10354. this.wrapR = ClampToEdgeWrapping;
  10355. this.layerUpdates = new Set();
  10356. }
  10357. addLayerUpdate( layerIndex ) {
  10358. this.layerUpdates.add( layerIndex );
  10359. }
  10360. clearLayerUpdates() {
  10361. this.layerUpdates.clear();
  10362. }
  10363. }
  10364. class CompressedCubeTexture extends CompressedTexture {
  10365. constructor( images, format, type ) {
  10366. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  10367. this.isCompressedCubeTexture = true;
  10368. this.isCubeTexture = true;
  10369. this.image = images;
  10370. }
  10371. }
  10372. class CanvasTexture extends Texture {
  10373. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10374. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10375. this.isCanvasTexture = true;
  10376. this.needsUpdate = true;
  10377. }
  10378. }
  10379. class DepthTexture extends Texture {
  10380. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10381. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10382. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10383. }
  10384. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10385. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10386. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10387. this.isDepthTexture = true;
  10388. this.image = { width: width, height: height };
  10389. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10390. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10391. this.flipY = false;
  10392. this.generateMipmaps = false;
  10393. this.compareFunction = null;
  10394. }
  10395. copy( source ) {
  10396. super.copy( source );
  10397. this.compareFunction = source.compareFunction;
  10398. return this;
  10399. }
  10400. toJSON( meta ) {
  10401. const data = super.toJSON( meta );
  10402. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10403. return data;
  10404. }
  10405. }
  10406. /**
  10407. * Extensible curve object.
  10408. *
  10409. * Some common of curve methods:
  10410. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  10411. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  10412. * .getPoints(), .getSpacedPoints()
  10413. * .getLength()
  10414. * .updateArcLengths()
  10415. *
  10416. * This following curves inherit from THREE.Curve:
  10417. *
  10418. * -- 2D curves --
  10419. * THREE.ArcCurve
  10420. * THREE.CubicBezierCurve
  10421. * THREE.EllipseCurve
  10422. * THREE.LineCurve
  10423. * THREE.QuadraticBezierCurve
  10424. * THREE.SplineCurve
  10425. *
  10426. * -- 3D curves --
  10427. * THREE.CatmullRomCurve3
  10428. * THREE.CubicBezierCurve3
  10429. * THREE.LineCurve3
  10430. * THREE.QuadraticBezierCurve3
  10431. *
  10432. * A series of curves can be represented as a THREE.CurvePath.
  10433. *
  10434. **/
  10435. class Curve {
  10436. constructor() {
  10437. this.type = 'Curve';
  10438. this.arcLengthDivisions = 200;
  10439. }
  10440. // Virtual base class method to overwrite and implement in subclasses
  10441. // - t [0 .. 1]
  10442. getPoint( /* t, optionalTarget */ ) {
  10443. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  10444. return null;
  10445. }
  10446. // Get point at relative position in curve according to arc length
  10447. // - u [0 .. 1]
  10448. getPointAt( u, optionalTarget ) {
  10449. const t = this.getUtoTmapping( u );
  10450. return this.getPoint( t, optionalTarget );
  10451. }
  10452. // Get sequence of points using getPoint( t )
  10453. getPoints( divisions = 5 ) {
  10454. const points = [];
  10455. for ( let d = 0; d <= divisions; d ++ ) {
  10456. points.push( this.getPoint( d / divisions ) );
  10457. }
  10458. return points;
  10459. }
  10460. // Get sequence of points using getPointAt( u )
  10461. getSpacedPoints( divisions = 5 ) {
  10462. const points = [];
  10463. for ( let d = 0; d <= divisions; d ++ ) {
  10464. points.push( this.getPointAt( d / divisions ) );
  10465. }
  10466. return points;
  10467. }
  10468. // Get total curve arc length
  10469. getLength() {
  10470. const lengths = this.getLengths();
  10471. return lengths[ lengths.length - 1 ];
  10472. }
  10473. // Get list of cumulative segment lengths
  10474. getLengths( divisions = this.arcLengthDivisions ) {
  10475. if ( this.cacheArcLengths &&
  10476. ( this.cacheArcLengths.length === divisions + 1 ) &&
  10477. ! this.needsUpdate ) {
  10478. return this.cacheArcLengths;
  10479. }
  10480. this.needsUpdate = false;
  10481. const cache = [];
  10482. let current, last = this.getPoint( 0 );
  10483. let sum = 0;
  10484. cache.push( 0 );
  10485. for ( let p = 1; p <= divisions; p ++ ) {
  10486. current = this.getPoint( p / divisions );
  10487. sum += current.distanceTo( last );
  10488. cache.push( sum );
  10489. last = current;
  10490. }
  10491. this.cacheArcLengths = cache;
  10492. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  10493. }
  10494. updateArcLengths() {
  10495. this.needsUpdate = true;
  10496. this.getLengths();
  10497. }
  10498. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  10499. getUtoTmapping( u, distance ) {
  10500. const arcLengths = this.getLengths();
  10501. let i = 0;
  10502. const il = arcLengths.length;
  10503. let targetArcLength; // The targeted u distance value to get
  10504. if ( distance ) {
  10505. targetArcLength = distance;
  10506. } else {
  10507. targetArcLength = u * arcLengths[ il - 1 ];
  10508. }
  10509. // binary search for the index with largest value smaller than target u distance
  10510. let low = 0, high = il - 1, comparison;
  10511. while ( low <= high ) {
  10512. 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
  10513. comparison = arcLengths[ i ] - targetArcLength;
  10514. if ( comparison < 0 ) {
  10515. low = i + 1;
  10516. } else if ( comparison > 0 ) {
  10517. high = i - 1;
  10518. } else {
  10519. high = i;
  10520. break;
  10521. // DONE
  10522. }
  10523. }
  10524. i = high;
  10525. if ( arcLengths[ i ] === targetArcLength ) {
  10526. return i / ( il - 1 );
  10527. }
  10528. // we could get finer grain at lengths, or use simple interpolation between two points
  10529. const lengthBefore = arcLengths[ i ];
  10530. const lengthAfter = arcLengths[ i + 1 ];
  10531. const segmentLength = lengthAfter - lengthBefore;
  10532. // determine where we are between the 'before' and 'after' points
  10533. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  10534. // add that fractional amount to t
  10535. const t = ( i + segmentFraction ) / ( il - 1 );
  10536. return t;
  10537. }
  10538. // Returns a unit vector tangent at t
  10539. // In case any sub curve does not implement its tangent derivation,
  10540. // 2 points a small delta apart will be used to find its gradient
  10541. // which seems to give a reasonable approximation
  10542. getTangent( t, optionalTarget ) {
  10543. const delta = 0.0001;
  10544. let t1 = t - delta;
  10545. let t2 = t + delta;
  10546. // Capping in case of danger
  10547. if ( t1 < 0 ) t1 = 0;
  10548. if ( t2 > 1 ) t2 = 1;
  10549. const pt1 = this.getPoint( t1 );
  10550. const pt2 = this.getPoint( t2 );
  10551. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  10552. tangent.copy( pt2 ).sub( pt1 ).normalize();
  10553. return tangent;
  10554. }
  10555. getTangentAt( u, optionalTarget ) {
  10556. const t = this.getUtoTmapping( u );
  10557. return this.getTangent( t, optionalTarget );
  10558. }
  10559. computeFrenetFrames( segments, closed ) {
  10560. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  10561. const normal = new Vector3();
  10562. const tangents = [];
  10563. const normals = [];
  10564. const binormals = [];
  10565. const vec = new Vector3();
  10566. const mat = new Matrix4();
  10567. // compute the tangent vectors for each segment on the curve
  10568. for ( let i = 0; i <= segments; i ++ ) {
  10569. const u = i / segments;
  10570. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  10571. }
  10572. // select an initial normal vector perpendicular to the first tangent vector,
  10573. // and in the direction of the minimum tangent xyz component
  10574. normals[ 0 ] = new Vector3();
  10575. binormals[ 0 ] = new Vector3();
  10576. let min = Number.MAX_VALUE;
  10577. const tx = Math.abs( tangents[ 0 ].x );
  10578. const ty = Math.abs( tangents[ 0 ].y );
  10579. const tz = Math.abs( tangents[ 0 ].z );
  10580. if ( tx <= min ) {
  10581. min = tx;
  10582. normal.set( 1, 0, 0 );
  10583. }
  10584. if ( ty <= min ) {
  10585. min = ty;
  10586. normal.set( 0, 1, 0 );
  10587. }
  10588. if ( tz <= min ) {
  10589. normal.set( 0, 0, 1 );
  10590. }
  10591. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  10592. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  10593. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  10594. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  10595. for ( let i = 1; i <= segments; i ++ ) {
  10596. normals[ i ] = normals[ i - 1 ].clone();
  10597. binormals[ i ] = binormals[ i - 1 ].clone();
  10598. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  10599. if ( vec.length() > Number.EPSILON ) {
  10600. vec.normalize();
  10601. const theta = Math.acos( clamp$1( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  10602. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  10603. }
  10604. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10605. }
  10606. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  10607. if ( closed === true ) {
  10608. let theta = Math.acos( clamp$1( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  10609. theta /= segments;
  10610. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  10611. theta = - theta;
  10612. }
  10613. for ( let i = 1; i <= segments; i ++ ) {
  10614. // twist a little...
  10615. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  10616. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10617. }
  10618. }
  10619. return {
  10620. tangents: tangents,
  10621. normals: normals,
  10622. binormals: binormals
  10623. };
  10624. }
  10625. clone() {
  10626. return new this.constructor().copy( this );
  10627. }
  10628. copy( source ) {
  10629. this.arcLengthDivisions = source.arcLengthDivisions;
  10630. return this;
  10631. }
  10632. toJSON() {
  10633. const data = {
  10634. metadata: {
  10635. version: 4.6,
  10636. type: 'Curve',
  10637. generator: 'Curve.toJSON'
  10638. }
  10639. };
  10640. data.arcLengthDivisions = this.arcLengthDivisions;
  10641. data.type = this.type;
  10642. return data;
  10643. }
  10644. fromJSON( json ) {
  10645. this.arcLengthDivisions = json.arcLengthDivisions;
  10646. return this;
  10647. }
  10648. }
  10649. class EllipseCurve extends Curve {
  10650. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  10651. super();
  10652. this.isEllipseCurve = true;
  10653. this.type = 'EllipseCurve';
  10654. this.aX = aX;
  10655. this.aY = aY;
  10656. this.xRadius = xRadius;
  10657. this.yRadius = yRadius;
  10658. this.aStartAngle = aStartAngle;
  10659. this.aEndAngle = aEndAngle;
  10660. this.aClockwise = aClockwise;
  10661. this.aRotation = aRotation;
  10662. }
  10663. getPoint( t, optionalTarget = new Vector2() ) {
  10664. const point = optionalTarget;
  10665. const twoPi = Math.PI * 2;
  10666. let deltaAngle = this.aEndAngle - this.aStartAngle;
  10667. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  10668. // ensures that deltaAngle is 0 .. 2 PI
  10669. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  10670. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  10671. if ( deltaAngle < Number.EPSILON ) {
  10672. if ( samePoints ) {
  10673. deltaAngle = 0;
  10674. } else {
  10675. deltaAngle = twoPi;
  10676. }
  10677. }
  10678. if ( this.aClockwise === true && ! samePoints ) {
  10679. if ( deltaAngle === twoPi ) {
  10680. deltaAngle = - twoPi;
  10681. } else {
  10682. deltaAngle = deltaAngle - twoPi;
  10683. }
  10684. }
  10685. const angle = this.aStartAngle + t * deltaAngle;
  10686. let x = this.aX + this.xRadius * Math.cos( angle );
  10687. let y = this.aY + this.yRadius * Math.sin( angle );
  10688. if ( this.aRotation !== 0 ) {
  10689. const cos = Math.cos( this.aRotation );
  10690. const sin = Math.sin( this.aRotation );
  10691. const tx = x - this.aX;
  10692. const ty = y - this.aY;
  10693. // Rotate the point about the center of the ellipse.
  10694. x = tx * cos - ty * sin + this.aX;
  10695. y = tx * sin + ty * cos + this.aY;
  10696. }
  10697. return point.set( x, y );
  10698. }
  10699. copy( source ) {
  10700. super.copy( source );
  10701. this.aX = source.aX;
  10702. this.aY = source.aY;
  10703. this.xRadius = source.xRadius;
  10704. this.yRadius = source.yRadius;
  10705. this.aStartAngle = source.aStartAngle;
  10706. this.aEndAngle = source.aEndAngle;
  10707. this.aClockwise = source.aClockwise;
  10708. this.aRotation = source.aRotation;
  10709. return this;
  10710. }
  10711. toJSON() {
  10712. const data = super.toJSON();
  10713. data.aX = this.aX;
  10714. data.aY = this.aY;
  10715. data.xRadius = this.xRadius;
  10716. data.yRadius = this.yRadius;
  10717. data.aStartAngle = this.aStartAngle;
  10718. data.aEndAngle = this.aEndAngle;
  10719. data.aClockwise = this.aClockwise;
  10720. data.aRotation = this.aRotation;
  10721. return data;
  10722. }
  10723. fromJSON( json ) {
  10724. super.fromJSON( json );
  10725. this.aX = json.aX;
  10726. this.aY = json.aY;
  10727. this.xRadius = json.xRadius;
  10728. this.yRadius = json.yRadius;
  10729. this.aStartAngle = json.aStartAngle;
  10730. this.aEndAngle = json.aEndAngle;
  10731. this.aClockwise = json.aClockwise;
  10732. this.aRotation = json.aRotation;
  10733. return this;
  10734. }
  10735. }
  10736. class ArcCurve extends EllipseCurve {
  10737. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  10738. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  10739. this.isArcCurve = true;
  10740. this.type = 'ArcCurve';
  10741. }
  10742. }
  10743. /**
  10744. * Centripetal CatmullRom Curve - which is useful for avoiding
  10745. * cusps and self-intersections in non-uniform catmull rom curves.
  10746. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  10747. *
  10748. * curve.type accepts centripetal(default), chordal and catmullrom
  10749. * curve.tension is used for catmullrom which defaults to 0.5
  10750. */
  10751. /*
  10752. Based on an optimized c++ solution in
  10753. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  10754. - http://ideone.com/NoEbVM
  10755. This CubicPoly class could be used for reusing some variables and calculations,
  10756. but for three.js curve use, it could be possible inlined and flatten into a single function call
  10757. which can be placed in CurveUtils.
  10758. */
  10759. function CubicPoly() {
  10760. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  10761. /*
  10762. * Compute coefficients for a cubic polynomial
  10763. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  10764. * such that
  10765. * p(0) = x0, p(1) = x1
  10766. * and
  10767. * p'(0) = t0, p'(1) = t1.
  10768. */
  10769. function init( x0, x1, t0, t1 ) {
  10770. c0 = x0;
  10771. c1 = t0;
  10772. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  10773. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  10774. }
  10775. return {
  10776. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  10777. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  10778. },
  10779. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  10780. // compute tangents when parameterized in [t1,t2]
  10781. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  10782. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  10783. // rescale tangents for parametrization in [0,1]
  10784. t1 *= dt1;
  10785. t2 *= dt1;
  10786. init( x1, x2, t1, t2 );
  10787. },
  10788. calc: function ( t ) {
  10789. const t2 = t * t;
  10790. const t3 = t2 * t;
  10791. return c0 + c1 * t + c2 * t2 + c3 * t3;
  10792. }
  10793. };
  10794. }
  10795. //
  10796. const tmp = /*@__PURE__*/ new Vector3();
  10797. const px = /*@__PURE__*/ new CubicPoly();
  10798. const py = /*@__PURE__*/ new CubicPoly();
  10799. const pz = /*@__PURE__*/ new CubicPoly();
  10800. class CatmullRomCurve3 extends Curve {
  10801. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  10802. super();
  10803. this.isCatmullRomCurve3 = true;
  10804. this.type = 'CatmullRomCurve3';
  10805. this.points = points;
  10806. this.closed = closed;
  10807. this.curveType = curveType;
  10808. this.tension = tension;
  10809. }
  10810. getPoint( t, optionalTarget = new Vector3() ) {
  10811. const point = optionalTarget;
  10812. const points = this.points;
  10813. const l = points.length;
  10814. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  10815. let intPoint = Math.floor( p );
  10816. let weight = p - intPoint;
  10817. if ( this.closed ) {
  10818. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  10819. } else if ( weight === 0 && intPoint === l - 1 ) {
  10820. intPoint = l - 2;
  10821. weight = 1;
  10822. }
  10823. let p0, p3; // 4 points (p1 & p2 defined below)
  10824. if ( this.closed || intPoint > 0 ) {
  10825. p0 = points[ ( intPoint - 1 ) % l ];
  10826. } else {
  10827. // extrapolate first point
  10828. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  10829. p0 = tmp;
  10830. }
  10831. const p1 = points[ intPoint % l ];
  10832. const p2 = points[ ( intPoint + 1 ) % l ];
  10833. if ( this.closed || intPoint + 2 < l ) {
  10834. p3 = points[ ( intPoint + 2 ) % l ];
  10835. } else {
  10836. // extrapolate last point
  10837. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  10838. p3 = tmp;
  10839. }
  10840. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  10841. // init Centripetal / Chordal Catmull-Rom
  10842. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  10843. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  10844. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  10845. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  10846. // safety check for repeated points
  10847. if ( dt1 < 1e-4 ) dt1 = 1.0;
  10848. if ( dt0 < 1e-4 ) dt0 = dt1;
  10849. if ( dt2 < 1e-4 ) dt2 = dt1;
  10850. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  10851. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  10852. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  10853. } else if ( this.curveType === 'catmullrom' ) {
  10854. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  10855. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  10856. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  10857. }
  10858. point.set(
  10859. px.calc( weight ),
  10860. py.calc( weight ),
  10861. pz.calc( weight )
  10862. );
  10863. return point;
  10864. }
  10865. copy( source ) {
  10866. super.copy( source );
  10867. this.points = [];
  10868. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10869. const point = source.points[ i ];
  10870. this.points.push( point.clone() );
  10871. }
  10872. this.closed = source.closed;
  10873. this.curveType = source.curveType;
  10874. this.tension = source.tension;
  10875. return this;
  10876. }
  10877. toJSON() {
  10878. const data = super.toJSON();
  10879. data.points = [];
  10880. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10881. const point = this.points[ i ];
  10882. data.points.push( point.toArray() );
  10883. }
  10884. data.closed = this.closed;
  10885. data.curveType = this.curveType;
  10886. data.tension = this.tension;
  10887. return data;
  10888. }
  10889. fromJSON( json ) {
  10890. super.fromJSON( json );
  10891. this.points = [];
  10892. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  10893. const point = json.points[ i ];
  10894. this.points.push( new Vector3().fromArray( point ) );
  10895. }
  10896. this.closed = json.closed;
  10897. this.curveType = json.curveType;
  10898. this.tension = json.tension;
  10899. return this;
  10900. }
  10901. }
  10902. /**
  10903. * Bezier Curves formulas obtained from
  10904. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  10905. */
  10906. function CatmullRom( t, p0, p1, p2, p3 ) {
  10907. const v0 = ( p2 - p0 ) * 0.5;
  10908. const v1 = ( p3 - p1 ) * 0.5;
  10909. const t2 = t * t;
  10910. const t3 = t * t2;
  10911. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  10912. }
  10913. //
  10914. function QuadraticBezierP0( t, p ) {
  10915. const k = 1 - t;
  10916. return k * k * p;
  10917. }
  10918. function QuadraticBezierP1( t, p ) {
  10919. return 2 * ( 1 - t ) * t * p;
  10920. }
  10921. function QuadraticBezierP2( t, p ) {
  10922. return t * t * p;
  10923. }
  10924. function QuadraticBezier( t, p0, p1, p2 ) {
  10925. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  10926. QuadraticBezierP2( t, p2 );
  10927. }
  10928. //
  10929. function CubicBezierP0( t, p ) {
  10930. const k = 1 - t;
  10931. return k * k * k * p;
  10932. }
  10933. function CubicBezierP1( t, p ) {
  10934. const k = 1 - t;
  10935. return 3 * k * k * t * p;
  10936. }
  10937. function CubicBezierP2( t, p ) {
  10938. return 3 * ( 1 - t ) * t * t * p;
  10939. }
  10940. function CubicBezierP3( t, p ) {
  10941. return t * t * t * p;
  10942. }
  10943. function CubicBezier( t, p0, p1, p2, p3 ) {
  10944. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  10945. CubicBezierP3( t, p3 );
  10946. }
  10947. class CubicBezierCurve extends Curve {
  10948. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  10949. super();
  10950. this.isCubicBezierCurve = true;
  10951. this.type = 'CubicBezierCurve';
  10952. this.v0 = v0;
  10953. this.v1 = v1;
  10954. this.v2 = v2;
  10955. this.v3 = v3;
  10956. }
  10957. getPoint( t, optionalTarget = new Vector2() ) {
  10958. const point = optionalTarget;
  10959. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10960. point.set(
  10961. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10962. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  10963. );
  10964. return point;
  10965. }
  10966. copy( source ) {
  10967. super.copy( source );
  10968. this.v0.copy( source.v0 );
  10969. this.v1.copy( source.v1 );
  10970. this.v2.copy( source.v2 );
  10971. this.v3.copy( source.v3 );
  10972. return this;
  10973. }
  10974. toJSON() {
  10975. const data = super.toJSON();
  10976. data.v0 = this.v0.toArray();
  10977. data.v1 = this.v1.toArray();
  10978. data.v2 = this.v2.toArray();
  10979. data.v3 = this.v3.toArray();
  10980. return data;
  10981. }
  10982. fromJSON( json ) {
  10983. super.fromJSON( json );
  10984. this.v0.fromArray( json.v0 );
  10985. this.v1.fromArray( json.v1 );
  10986. this.v2.fromArray( json.v2 );
  10987. this.v3.fromArray( json.v3 );
  10988. return this;
  10989. }
  10990. }
  10991. class CubicBezierCurve3 extends Curve {
  10992. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  10993. super();
  10994. this.isCubicBezierCurve3 = true;
  10995. this.type = 'CubicBezierCurve3';
  10996. this.v0 = v0;
  10997. this.v1 = v1;
  10998. this.v2 = v2;
  10999. this.v3 = v3;
  11000. }
  11001. getPoint( t, optionalTarget = new Vector3() ) {
  11002. const point = optionalTarget;
  11003. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  11004. point.set(
  11005. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  11006. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  11007. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  11008. );
  11009. return point;
  11010. }
  11011. copy( source ) {
  11012. super.copy( source );
  11013. this.v0.copy( source.v0 );
  11014. this.v1.copy( source.v1 );
  11015. this.v2.copy( source.v2 );
  11016. this.v3.copy( source.v3 );
  11017. return this;
  11018. }
  11019. toJSON() {
  11020. const data = super.toJSON();
  11021. data.v0 = this.v0.toArray();
  11022. data.v1 = this.v1.toArray();
  11023. data.v2 = this.v2.toArray();
  11024. data.v3 = this.v3.toArray();
  11025. return data;
  11026. }
  11027. fromJSON( json ) {
  11028. super.fromJSON( json );
  11029. this.v0.fromArray( json.v0 );
  11030. this.v1.fromArray( json.v1 );
  11031. this.v2.fromArray( json.v2 );
  11032. this.v3.fromArray( json.v3 );
  11033. return this;
  11034. }
  11035. }
  11036. class LineCurve extends Curve {
  11037. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  11038. super();
  11039. this.isLineCurve = true;
  11040. this.type = 'LineCurve';
  11041. this.v1 = v1;
  11042. this.v2 = v2;
  11043. }
  11044. getPoint( t, optionalTarget = new Vector2() ) {
  11045. const point = optionalTarget;
  11046. if ( t === 1 ) {
  11047. point.copy( this.v2 );
  11048. } else {
  11049. point.copy( this.v2 ).sub( this.v1 );
  11050. point.multiplyScalar( t ).add( this.v1 );
  11051. }
  11052. return point;
  11053. }
  11054. // Line curve is linear, so we can overwrite default getPointAt
  11055. getPointAt( u, optionalTarget ) {
  11056. return this.getPoint( u, optionalTarget );
  11057. }
  11058. getTangent( t, optionalTarget = new Vector2() ) {
  11059. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  11060. }
  11061. getTangentAt( u, optionalTarget ) {
  11062. return this.getTangent( u, optionalTarget );
  11063. }
  11064. copy( source ) {
  11065. super.copy( source );
  11066. this.v1.copy( source.v1 );
  11067. this.v2.copy( source.v2 );
  11068. return this;
  11069. }
  11070. toJSON() {
  11071. const data = super.toJSON();
  11072. data.v1 = this.v1.toArray();
  11073. data.v2 = this.v2.toArray();
  11074. return data;
  11075. }
  11076. fromJSON( json ) {
  11077. super.fromJSON( json );
  11078. this.v1.fromArray( json.v1 );
  11079. this.v2.fromArray( json.v2 );
  11080. return this;
  11081. }
  11082. }
  11083. class LineCurve3 extends Curve {
  11084. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  11085. super();
  11086. this.isLineCurve3 = true;
  11087. this.type = 'LineCurve3';
  11088. this.v1 = v1;
  11089. this.v2 = v2;
  11090. }
  11091. getPoint( t, optionalTarget = new Vector3() ) {
  11092. const point = optionalTarget;
  11093. if ( t === 1 ) {
  11094. point.copy( this.v2 );
  11095. } else {
  11096. point.copy( this.v2 ).sub( this.v1 );
  11097. point.multiplyScalar( t ).add( this.v1 );
  11098. }
  11099. return point;
  11100. }
  11101. // Line curve is linear, so we can overwrite default getPointAt
  11102. getPointAt( u, optionalTarget ) {
  11103. return this.getPoint( u, optionalTarget );
  11104. }
  11105. getTangent( t, optionalTarget = new Vector3() ) {
  11106. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  11107. }
  11108. getTangentAt( u, optionalTarget ) {
  11109. return this.getTangent( u, optionalTarget );
  11110. }
  11111. copy( source ) {
  11112. super.copy( source );
  11113. this.v1.copy( source.v1 );
  11114. this.v2.copy( source.v2 );
  11115. return this;
  11116. }
  11117. toJSON() {
  11118. const data = super.toJSON();
  11119. data.v1 = this.v1.toArray();
  11120. data.v2 = this.v2.toArray();
  11121. return data;
  11122. }
  11123. fromJSON( json ) {
  11124. super.fromJSON( json );
  11125. this.v1.fromArray( json.v1 );
  11126. this.v2.fromArray( json.v2 );
  11127. return this;
  11128. }
  11129. }
  11130. class QuadraticBezierCurve extends Curve {
  11131. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  11132. super();
  11133. this.isQuadraticBezierCurve = true;
  11134. this.type = 'QuadraticBezierCurve';
  11135. this.v0 = v0;
  11136. this.v1 = v1;
  11137. this.v2 = v2;
  11138. }
  11139. getPoint( t, optionalTarget = new Vector2() ) {
  11140. const point = optionalTarget;
  11141. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  11142. point.set(
  11143. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  11144. QuadraticBezier( t, v0.y, v1.y, v2.y )
  11145. );
  11146. return point;
  11147. }
  11148. copy( source ) {
  11149. super.copy( source );
  11150. this.v0.copy( source.v0 );
  11151. this.v1.copy( source.v1 );
  11152. this.v2.copy( source.v2 );
  11153. return this;
  11154. }
  11155. toJSON() {
  11156. const data = super.toJSON();
  11157. data.v0 = this.v0.toArray();
  11158. data.v1 = this.v1.toArray();
  11159. data.v2 = this.v2.toArray();
  11160. return data;
  11161. }
  11162. fromJSON( json ) {
  11163. super.fromJSON( json );
  11164. this.v0.fromArray( json.v0 );
  11165. this.v1.fromArray( json.v1 );
  11166. this.v2.fromArray( json.v2 );
  11167. return this;
  11168. }
  11169. }
  11170. class QuadraticBezierCurve3 extends Curve {
  11171. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  11172. super();
  11173. this.isQuadraticBezierCurve3 = true;
  11174. this.type = 'QuadraticBezierCurve3';
  11175. this.v0 = v0;
  11176. this.v1 = v1;
  11177. this.v2 = v2;
  11178. }
  11179. getPoint( t, optionalTarget = new Vector3() ) {
  11180. const point = optionalTarget;
  11181. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  11182. point.set(
  11183. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  11184. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  11185. QuadraticBezier( t, v0.z, v1.z, v2.z )
  11186. );
  11187. return point;
  11188. }
  11189. copy( source ) {
  11190. super.copy( source );
  11191. this.v0.copy( source.v0 );
  11192. this.v1.copy( source.v1 );
  11193. this.v2.copy( source.v2 );
  11194. return this;
  11195. }
  11196. toJSON() {
  11197. const data = super.toJSON();
  11198. data.v0 = this.v0.toArray();
  11199. data.v1 = this.v1.toArray();
  11200. data.v2 = this.v2.toArray();
  11201. return data;
  11202. }
  11203. fromJSON( json ) {
  11204. super.fromJSON( json );
  11205. this.v0.fromArray( json.v0 );
  11206. this.v1.fromArray( json.v1 );
  11207. this.v2.fromArray( json.v2 );
  11208. return this;
  11209. }
  11210. }
  11211. class SplineCurve extends Curve {
  11212. constructor( points = [] ) {
  11213. super();
  11214. this.isSplineCurve = true;
  11215. this.type = 'SplineCurve';
  11216. this.points = points;
  11217. }
  11218. getPoint( t, optionalTarget = new Vector2() ) {
  11219. const point = optionalTarget;
  11220. const points = this.points;
  11221. const p = ( points.length - 1 ) * t;
  11222. const intPoint = Math.floor( p );
  11223. const weight = p - intPoint;
  11224. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  11225. const p1 = points[ intPoint ];
  11226. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  11227. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  11228. point.set(
  11229. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  11230. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  11231. );
  11232. return point;
  11233. }
  11234. copy( source ) {
  11235. super.copy( source );
  11236. this.points = [];
  11237. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  11238. const point = source.points[ i ];
  11239. this.points.push( point.clone() );
  11240. }
  11241. return this;
  11242. }
  11243. toJSON() {
  11244. const data = super.toJSON();
  11245. data.points = [];
  11246. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  11247. const point = this.points[ i ];
  11248. data.points.push( point.toArray() );
  11249. }
  11250. return data;
  11251. }
  11252. fromJSON( json ) {
  11253. super.fromJSON( json );
  11254. this.points = [];
  11255. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  11256. const point = json.points[ i ];
  11257. this.points.push( new Vector2().fromArray( point ) );
  11258. }
  11259. return this;
  11260. }
  11261. }
  11262. var Curves = /*#__PURE__*/Object.freeze({
  11263. __proto__: null,
  11264. ArcCurve: ArcCurve,
  11265. CatmullRomCurve3: CatmullRomCurve3,
  11266. CubicBezierCurve: CubicBezierCurve,
  11267. CubicBezierCurve3: CubicBezierCurve3,
  11268. EllipseCurve: EllipseCurve,
  11269. LineCurve: LineCurve,
  11270. LineCurve3: LineCurve3,
  11271. QuadraticBezierCurve: QuadraticBezierCurve,
  11272. QuadraticBezierCurve3: QuadraticBezierCurve3,
  11273. SplineCurve: SplineCurve
  11274. });
  11275. /**************************************************************
  11276. * Curved Path - a curve path is simply a array of connected
  11277. * curves, but retains the api of a curve
  11278. **************************************************************/
  11279. class CurvePath extends Curve {
  11280. constructor() {
  11281. super();
  11282. this.type = 'CurvePath';
  11283. this.curves = [];
  11284. this.autoClose = false; // Automatically closes the path
  11285. }
  11286. add( curve ) {
  11287. this.curves.push( curve );
  11288. }
  11289. closePath() {
  11290. // Add a line curve if start and end of lines are not connected
  11291. const startPoint = this.curves[ 0 ].getPoint( 0 );
  11292. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  11293. if ( ! startPoint.equals( endPoint ) ) {
  11294. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  11295. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  11296. }
  11297. return this;
  11298. }
  11299. // To get accurate point with reference to
  11300. // entire path distance at time t,
  11301. // following has to be done:
  11302. // 1. Length of each sub path have to be known
  11303. // 2. Locate and identify type of curve
  11304. // 3. Get t for the curve
  11305. // 4. Return curve.getPointAt(t')
  11306. getPoint( t, optionalTarget ) {
  11307. const d = t * this.getLength();
  11308. const curveLengths = this.getCurveLengths();
  11309. let i = 0;
  11310. // To think about boundaries points.
  11311. while ( i < curveLengths.length ) {
  11312. if ( curveLengths[ i ] >= d ) {
  11313. const diff = curveLengths[ i ] - d;
  11314. const curve = this.curves[ i ];
  11315. const segmentLength = curve.getLength();
  11316. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  11317. return curve.getPointAt( u, optionalTarget );
  11318. }
  11319. i ++;
  11320. }
  11321. return null;
  11322. // loop where sum != 0, sum > d , sum+1 <d
  11323. }
  11324. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11325. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11326. // getPoint() depends on getLength
  11327. getLength() {
  11328. const lens = this.getCurveLengths();
  11329. return lens[ lens.length - 1 ];
  11330. }
  11331. // cacheLengths must be recalculated.
  11332. updateArcLengths() {
  11333. this.needsUpdate = true;
  11334. this.cacheLengths = null;
  11335. this.getCurveLengths();
  11336. }
  11337. // Compute lengths and cache them
  11338. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11339. getCurveLengths() {
  11340. // We use cache values if curves and cache array are same length
  11341. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  11342. return this.cacheLengths;
  11343. }
  11344. // Get length of sub-curve
  11345. // Push sums into cached array
  11346. const lengths = [];
  11347. let sums = 0;
  11348. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11349. sums += this.curves[ i ].getLength();
  11350. lengths.push( sums );
  11351. }
  11352. this.cacheLengths = lengths;
  11353. return lengths;
  11354. }
  11355. getSpacedPoints( divisions = 40 ) {
  11356. const points = [];
  11357. for ( let i = 0; i <= divisions; i ++ ) {
  11358. points.push( this.getPoint( i / divisions ) );
  11359. }
  11360. if ( this.autoClose ) {
  11361. points.push( points[ 0 ] );
  11362. }
  11363. return points;
  11364. }
  11365. getPoints( divisions = 12 ) {
  11366. const points = [];
  11367. let last;
  11368. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  11369. const curve = curves[ i ];
  11370. const resolution = curve.isEllipseCurve ? divisions * 2
  11371. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  11372. : curve.isSplineCurve ? divisions * curve.points.length
  11373. : divisions;
  11374. const pts = curve.getPoints( resolution );
  11375. for ( let j = 0; j < pts.length; j ++ ) {
  11376. const point = pts[ j ];
  11377. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  11378. points.push( point );
  11379. last = point;
  11380. }
  11381. }
  11382. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  11383. points.push( points[ 0 ] );
  11384. }
  11385. return points;
  11386. }
  11387. copy( source ) {
  11388. super.copy( source );
  11389. this.curves = [];
  11390. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  11391. const curve = source.curves[ i ];
  11392. this.curves.push( curve.clone() );
  11393. }
  11394. this.autoClose = source.autoClose;
  11395. return this;
  11396. }
  11397. toJSON() {
  11398. const data = super.toJSON();
  11399. data.autoClose = this.autoClose;
  11400. data.curves = [];
  11401. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11402. const curve = this.curves[ i ];
  11403. data.curves.push( curve.toJSON() );
  11404. }
  11405. return data;
  11406. }
  11407. fromJSON( json ) {
  11408. super.fromJSON( json );
  11409. this.autoClose = json.autoClose;
  11410. this.curves = [];
  11411. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  11412. const curve = json.curves[ i ];
  11413. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  11414. }
  11415. return this;
  11416. }
  11417. }
  11418. class Path extends CurvePath {
  11419. constructor( points ) {
  11420. super();
  11421. this.type = 'Path';
  11422. this.currentPoint = new Vector2();
  11423. if ( points ) {
  11424. this.setFromPoints( points );
  11425. }
  11426. }
  11427. setFromPoints( points ) {
  11428. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  11429. for ( let i = 1, l = points.length; i < l; i ++ ) {
  11430. this.lineTo( points[ i ].x, points[ i ].y );
  11431. }
  11432. return this;
  11433. }
  11434. moveTo( x, y ) {
  11435. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  11436. return this;
  11437. }
  11438. lineTo( x, y ) {
  11439. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  11440. this.curves.push( curve );
  11441. this.currentPoint.set( x, y );
  11442. return this;
  11443. }
  11444. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  11445. const curve = new QuadraticBezierCurve(
  11446. this.currentPoint.clone(),
  11447. new Vector2( aCPx, aCPy ),
  11448. new Vector2( aX, aY )
  11449. );
  11450. this.curves.push( curve );
  11451. this.currentPoint.set( aX, aY );
  11452. return this;
  11453. }
  11454. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  11455. const curve = new CubicBezierCurve(
  11456. this.currentPoint.clone(),
  11457. new Vector2( aCP1x, aCP1y ),
  11458. new Vector2( aCP2x, aCP2y ),
  11459. new Vector2( aX, aY )
  11460. );
  11461. this.curves.push( curve );
  11462. this.currentPoint.set( aX, aY );
  11463. return this;
  11464. }
  11465. splineThru( pts /*Array of Vector*/ ) {
  11466. const npts = [ this.currentPoint.clone() ].concat( pts );
  11467. const curve = new SplineCurve( npts );
  11468. this.curves.push( curve );
  11469. this.currentPoint.copy( pts[ pts.length - 1 ] );
  11470. return this;
  11471. }
  11472. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11473. const x0 = this.currentPoint.x;
  11474. const y0 = this.currentPoint.y;
  11475. this.absarc( aX + x0, aY + y0, aRadius,
  11476. aStartAngle, aEndAngle, aClockwise );
  11477. return this;
  11478. }
  11479. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11480. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  11481. return this;
  11482. }
  11483. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11484. const x0 = this.currentPoint.x;
  11485. const y0 = this.currentPoint.y;
  11486. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11487. return this;
  11488. }
  11489. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11490. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11491. if ( this.curves.length > 0 ) {
  11492. // if a previous curve is present, attempt to join
  11493. const firstPoint = curve.getPoint( 0 );
  11494. if ( ! firstPoint.equals( this.currentPoint ) ) {
  11495. this.lineTo( firstPoint.x, firstPoint.y );
  11496. }
  11497. }
  11498. this.curves.push( curve );
  11499. const lastPoint = curve.getPoint( 1 );
  11500. this.currentPoint.copy( lastPoint );
  11501. return this;
  11502. }
  11503. copy( source ) {
  11504. super.copy( source );
  11505. this.currentPoint.copy( source.currentPoint );
  11506. return this;
  11507. }
  11508. toJSON() {
  11509. const data = super.toJSON();
  11510. data.currentPoint = this.currentPoint.toArray();
  11511. return data;
  11512. }
  11513. fromJSON( json ) {
  11514. super.fromJSON( json );
  11515. this.currentPoint.fromArray( json.currentPoint );
  11516. return this;
  11517. }
  11518. }
  11519. class LatheGeometry extends BufferGeometry {
  11520. 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 ) {
  11521. super();
  11522. this.type = 'LatheGeometry';
  11523. this.parameters = {
  11524. points: points,
  11525. segments: segments,
  11526. phiStart: phiStart,
  11527. phiLength: phiLength
  11528. };
  11529. segments = Math.floor( segments );
  11530. // clamp phiLength so it's in range of [ 0, 2PI ]
  11531. phiLength = clamp$1( phiLength, 0, Math.PI * 2 );
  11532. // buffers
  11533. const indices = [];
  11534. const vertices = [];
  11535. const uvs = [];
  11536. const initNormals = [];
  11537. const normals = [];
  11538. // helper variables
  11539. const inverseSegments = 1.0 / segments;
  11540. const vertex = new Vector3();
  11541. const uv = new Vector2();
  11542. const normal = new Vector3();
  11543. const curNormal = new Vector3();
  11544. const prevNormal = new Vector3();
  11545. let dx = 0;
  11546. let dy = 0;
  11547. // pre-compute normals for initial "meridian"
  11548. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11549. switch ( j ) {
  11550. case 0: // special handling for 1st vertex on path
  11551. dx = points[ j + 1 ].x - points[ j ].x;
  11552. dy = points[ j + 1 ].y - points[ j ].y;
  11553. normal.x = dy * 1.0;
  11554. normal.y = - dx;
  11555. normal.z = dy * 0.0;
  11556. prevNormal.copy( normal );
  11557. normal.normalize();
  11558. initNormals.push( normal.x, normal.y, normal.z );
  11559. break;
  11560. case ( points.length - 1 ): // special handling for last Vertex on path
  11561. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  11562. break;
  11563. default: // default handling for all vertices in between
  11564. dx = points[ j + 1 ].x - points[ j ].x;
  11565. dy = points[ j + 1 ].y - points[ j ].y;
  11566. normal.x = dy * 1.0;
  11567. normal.y = - dx;
  11568. normal.z = dy * 0.0;
  11569. curNormal.copy( normal );
  11570. normal.x += prevNormal.x;
  11571. normal.y += prevNormal.y;
  11572. normal.z += prevNormal.z;
  11573. normal.normalize();
  11574. initNormals.push( normal.x, normal.y, normal.z );
  11575. prevNormal.copy( curNormal );
  11576. }
  11577. }
  11578. // generate vertices, uvs and normals
  11579. for ( let i = 0; i <= segments; i ++ ) {
  11580. const phi = phiStart + i * inverseSegments * phiLength;
  11581. const sin = Math.sin( phi );
  11582. const cos = Math.cos( phi );
  11583. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11584. // vertex
  11585. vertex.x = points[ j ].x * sin;
  11586. vertex.y = points[ j ].y;
  11587. vertex.z = points[ j ].x * cos;
  11588. vertices.push( vertex.x, vertex.y, vertex.z );
  11589. // uv
  11590. uv.x = i / segments;
  11591. uv.y = j / ( points.length - 1 );
  11592. uvs.push( uv.x, uv.y );
  11593. // normal
  11594. const x = initNormals[ 3 * j + 0 ] * sin;
  11595. const y = initNormals[ 3 * j + 1 ];
  11596. const z = initNormals[ 3 * j + 0 ] * cos;
  11597. normals.push( x, y, z );
  11598. }
  11599. }
  11600. // indices
  11601. for ( let i = 0; i < segments; i ++ ) {
  11602. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  11603. const base = j + i * points.length;
  11604. const a = base;
  11605. const b = base + points.length;
  11606. const c = base + points.length + 1;
  11607. const d = base + 1;
  11608. // faces
  11609. indices.push( a, b, d );
  11610. indices.push( c, d, b );
  11611. }
  11612. }
  11613. // build geometry
  11614. this.setIndex( indices );
  11615. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11616. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11617. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11618. }
  11619. copy( source ) {
  11620. super.copy( source );
  11621. this.parameters = Object.assign( {}, source.parameters );
  11622. return this;
  11623. }
  11624. static fromJSON( data ) {
  11625. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  11626. }
  11627. }
  11628. class CapsuleGeometry extends LatheGeometry {
  11629. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  11630. const path = new Path();
  11631. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  11632. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  11633. super( path.getPoints( capSegments ), radialSegments );
  11634. this.type = 'CapsuleGeometry';
  11635. this.parameters = {
  11636. radius: radius,
  11637. length: length,
  11638. capSegments: capSegments,
  11639. radialSegments: radialSegments,
  11640. };
  11641. }
  11642. static fromJSON( data ) {
  11643. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  11644. }
  11645. }
  11646. class CircleGeometry extends BufferGeometry {
  11647. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11648. super();
  11649. this.type = 'CircleGeometry';
  11650. this.parameters = {
  11651. radius: radius,
  11652. segments: segments,
  11653. thetaStart: thetaStart,
  11654. thetaLength: thetaLength
  11655. };
  11656. segments = Math.max( 3, segments );
  11657. // buffers
  11658. const indices = [];
  11659. const vertices = [];
  11660. const normals = [];
  11661. const uvs = [];
  11662. // helper variables
  11663. const vertex = new Vector3();
  11664. const uv = new Vector2();
  11665. // center point
  11666. vertices.push( 0, 0, 0 );
  11667. normals.push( 0, 0, 1 );
  11668. uvs.push( 0.5, 0.5 );
  11669. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  11670. const segment = thetaStart + s / segments * thetaLength;
  11671. // vertex
  11672. vertex.x = radius * Math.cos( segment );
  11673. vertex.y = radius * Math.sin( segment );
  11674. vertices.push( vertex.x, vertex.y, vertex.z );
  11675. // normal
  11676. normals.push( 0, 0, 1 );
  11677. // uvs
  11678. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  11679. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  11680. uvs.push( uv.x, uv.y );
  11681. }
  11682. // indices
  11683. for ( let i = 1; i <= segments; i ++ ) {
  11684. indices.push( i, i + 1, 0 );
  11685. }
  11686. // build geometry
  11687. this.setIndex( indices );
  11688. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11689. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11690. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11691. }
  11692. copy( source ) {
  11693. super.copy( source );
  11694. this.parameters = Object.assign( {}, source.parameters );
  11695. return this;
  11696. }
  11697. static fromJSON( data ) {
  11698. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  11699. }
  11700. }
  11701. class CylinderGeometry extends BufferGeometry {
  11702. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11703. super();
  11704. this.type = 'CylinderGeometry';
  11705. this.parameters = {
  11706. radiusTop: radiusTop,
  11707. radiusBottom: radiusBottom,
  11708. height: height,
  11709. radialSegments: radialSegments,
  11710. heightSegments: heightSegments,
  11711. openEnded: openEnded,
  11712. thetaStart: thetaStart,
  11713. thetaLength: thetaLength
  11714. };
  11715. const scope = this;
  11716. radialSegments = Math.floor( radialSegments );
  11717. heightSegments = Math.floor( heightSegments );
  11718. // buffers
  11719. const indices = [];
  11720. const vertices = [];
  11721. const normals = [];
  11722. const uvs = [];
  11723. // helper variables
  11724. let index = 0;
  11725. const indexArray = [];
  11726. const halfHeight = height / 2;
  11727. let groupStart = 0;
  11728. // generate geometry
  11729. generateTorso();
  11730. if ( openEnded === false ) {
  11731. if ( radiusTop > 0 ) generateCap( true );
  11732. if ( radiusBottom > 0 ) generateCap( false );
  11733. }
  11734. // build geometry
  11735. this.setIndex( indices );
  11736. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11737. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11738. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11739. function generateTorso() {
  11740. const normal = new Vector3();
  11741. const vertex = new Vector3();
  11742. let groupCount = 0;
  11743. // this will be used to calculate the normal
  11744. const slope = ( radiusBottom - radiusTop ) / height;
  11745. // generate vertices, normals and uvs
  11746. for ( let y = 0; y <= heightSegments; y ++ ) {
  11747. const indexRow = [];
  11748. const v = y / heightSegments;
  11749. // calculate the radius of the current row
  11750. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  11751. for ( let x = 0; x <= radialSegments; x ++ ) {
  11752. const u = x / radialSegments;
  11753. const theta = u * thetaLength + thetaStart;
  11754. const sinTheta = Math.sin( theta );
  11755. const cosTheta = Math.cos( theta );
  11756. // vertex
  11757. vertex.x = radius * sinTheta;
  11758. vertex.y = - v * height + halfHeight;
  11759. vertex.z = radius * cosTheta;
  11760. vertices.push( vertex.x, vertex.y, vertex.z );
  11761. // normal
  11762. normal.set( sinTheta, slope, cosTheta ).normalize();
  11763. normals.push( normal.x, normal.y, normal.z );
  11764. // uv
  11765. uvs.push( u, 1 - v );
  11766. // save index of vertex in respective row
  11767. indexRow.push( index ++ );
  11768. }
  11769. // now save vertices of the row in our index array
  11770. indexArray.push( indexRow );
  11771. }
  11772. // generate indices
  11773. for ( let x = 0; x < radialSegments; x ++ ) {
  11774. for ( let y = 0; y < heightSegments; y ++ ) {
  11775. // we use the index array to access the correct indices
  11776. const a = indexArray[ y ][ x ];
  11777. const b = indexArray[ y + 1 ][ x ];
  11778. const c = indexArray[ y + 1 ][ x + 1 ];
  11779. const d = indexArray[ y ][ x + 1 ];
  11780. // faces
  11781. if ( radiusTop > 0 || y !== 0 ) {
  11782. indices.push( a, b, d );
  11783. groupCount += 3;
  11784. }
  11785. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  11786. indices.push( b, c, d );
  11787. groupCount += 3;
  11788. }
  11789. }
  11790. }
  11791. // add a group to the geometry. this will ensure multi material support
  11792. scope.addGroup( groupStart, groupCount, 0 );
  11793. // calculate new start value for groups
  11794. groupStart += groupCount;
  11795. }
  11796. function generateCap( top ) {
  11797. // save the index of the first center vertex
  11798. const centerIndexStart = index;
  11799. const uv = new Vector2();
  11800. const vertex = new Vector3();
  11801. let groupCount = 0;
  11802. const radius = ( top === true ) ? radiusTop : radiusBottom;
  11803. const sign = ( top === true ) ? 1 : - 1;
  11804. // first we generate the center vertex data of the cap.
  11805. // because the geometry needs one set of uvs per face,
  11806. // we must generate a center vertex per face/segment
  11807. for ( let x = 1; x <= radialSegments; x ++ ) {
  11808. // vertex
  11809. vertices.push( 0, halfHeight * sign, 0 );
  11810. // normal
  11811. normals.push( 0, sign, 0 );
  11812. // uv
  11813. uvs.push( 0.5, 0.5 );
  11814. // increase index
  11815. index ++;
  11816. }
  11817. // save the index of the last center vertex
  11818. const centerIndexEnd = index;
  11819. // now we generate the surrounding vertices, normals and uvs
  11820. for ( let x = 0; x <= radialSegments; x ++ ) {
  11821. const u = x / radialSegments;
  11822. const theta = u * thetaLength + thetaStart;
  11823. const cosTheta = Math.cos( theta );
  11824. const sinTheta = Math.sin( theta );
  11825. // vertex
  11826. vertex.x = radius * sinTheta;
  11827. vertex.y = halfHeight * sign;
  11828. vertex.z = radius * cosTheta;
  11829. vertices.push( vertex.x, vertex.y, vertex.z );
  11830. // normal
  11831. normals.push( 0, sign, 0 );
  11832. // uv
  11833. uv.x = ( cosTheta * 0.5 ) + 0.5;
  11834. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  11835. uvs.push( uv.x, uv.y );
  11836. // increase index
  11837. index ++;
  11838. }
  11839. // generate indices
  11840. for ( let x = 0; x < radialSegments; x ++ ) {
  11841. const c = centerIndexStart + x;
  11842. const i = centerIndexEnd + x;
  11843. if ( top === true ) {
  11844. // face top
  11845. indices.push( i, i + 1, c );
  11846. } else {
  11847. // face bottom
  11848. indices.push( i + 1, i, c );
  11849. }
  11850. groupCount += 3;
  11851. }
  11852. // add a group to the geometry. this will ensure multi material support
  11853. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  11854. // calculate new start value for groups
  11855. groupStart += groupCount;
  11856. }
  11857. }
  11858. copy( source ) {
  11859. super.copy( source );
  11860. this.parameters = Object.assign( {}, source.parameters );
  11861. return this;
  11862. }
  11863. static fromJSON( data ) {
  11864. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11865. }
  11866. }
  11867. class ConeGeometry extends CylinderGeometry {
  11868. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11869. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  11870. this.type = 'ConeGeometry';
  11871. this.parameters = {
  11872. radius: radius,
  11873. height: height,
  11874. radialSegments: radialSegments,
  11875. heightSegments: heightSegments,
  11876. openEnded: openEnded,
  11877. thetaStart: thetaStart,
  11878. thetaLength: thetaLength
  11879. };
  11880. }
  11881. static fromJSON( data ) {
  11882. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11883. }
  11884. }
  11885. class PolyhedronGeometry extends BufferGeometry {
  11886. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  11887. super();
  11888. this.type = 'PolyhedronGeometry';
  11889. this.parameters = {
  11890. vertices: vertices,
  11891. indices: indices,
  11892. radius: radius,
  11893. detail: detail
  11894. };
  11895. // default buffer data
  11896. const vertexBuffer = [];
  11897. const uvBuffer = [];
  11898. // the subdivision creates the vertex buffer data
  11899. subdivide( detail );
  11900. // all vertices should lie on a conceptual sphere with a given radius
  11901. applyRadius( radius );
  11902. // finally, create the uv data
  11903. generateUVs();
  11904. // build non-indexed geometry
  11905. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  11906. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  11907. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  11908. if ( detail === 0 ) {
  11909. this.computeVertexNormals(); // flat normals
  11910. } else {
  11911. this.normalizeNormals(); // smooth normals
  11912. }
  11913. // helper functions
  11914. function subdivide( detail ) {
  11915. const a = new Vector3();
  11916. const b = new Vector3();
  11917. const c = new Vector3();
  11918. // iterate over all faces and apply a subdivision with the given detail value
  11919. for ( let i = 0; i < indices.length; i += 3 ) {
  11920. // get the vertices of the face
  11921. getVertexByIndex( indices[ i + 0 ], a );
  11922. getVertexByIndex( indices[ i + 1 ], b );
  11923. getVertexByIndex( indices[ i + 2 ], c );
  11924. // perform subdivision
  11925. subdivideFace( a, b, c, detail );
  11926. }
  11927. }
  11928. function subdivideFace( a, b, c, detail ) {
  11929. const cols = detail + 1;
  11930. // we use this multidimensional array as a data structure for creating the subdivision
  11931. const v = [];
  11932. // construct all of the vertices for this subdivision
  11933. for ( let i = 0; i <= cols; i ++ ) {
  11934. v[ i ] = [];
  11935. const aj = a.clone().lerp( c, i / cols );
  11936. const bj = b.clone().lerp( c, i / cols );
  11937. const rows = cols - i;
  11938. for ( let j = 0; j <= rows; j ++ ) {
  11939. if ( j === 0 && i === cols ) {
  11940. v[ i ][ j ] = aj;
  11941. } else {
  11942. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  11943. }
  11944. }
  11945. }
  11946. // construct all of the faces
  11947. for ( let i = 0; i < cols; i ++ ) {
  11948. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  11949. const k = Math.floor( j / 2 );
  11950. if ( j % 2 === 0 ) {
  11951. pushVertex( v[ i ][ k + 1 ] );
  11952. pushVertex( v[ i + 1 ][ k ] );
  11953. pushVertex( v[ i ][ k ] );
  11954. } else {
  11955. pushVertex( v[ i ][ k + 1 ] );
  11956. pushVertex( v[ i + 1 ][ k + 1 ] );
  11957. pushVertex( v[ i + 1 ][ k ] );
  11958. }
  11959. }
  11960. }
  11961. }
  11962. function applyRadius( radius ) {
  11963. const vertex = new Vector3();
  11964. // iterate over the entire buffer and apply the radius to each vertex
  11965. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11966. vertex.x = vertexBuffer[ i + 0 ];
  11967. vertex.y = vertexBuffer[ i + 1 ];
  11968. vertex.z = vertexBuffer[ i + 2 ];
  11969. vertex.normalize().multiplyScalar( radius );
  11970. vertexBuffer[ i + 0 ] = vertex.x;
  11971. vertexBuffer[ i + 1 ] = vertex.y;
  11972. vertexBuffer[ i + 2 ] = vertex.z;
  11973. }
  11974. }
  11975. function generateUVs() {
  11976. const vertex = new Vector3();
  11977. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11978. vertex.x = vertexBuffer[ i + 0 ];
  11979. vertex.y = vertexBuffer[ i + 1 ];
  11980. vertex.z = vertexBuffer[ i + 2 ];
  11981. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  11982. const v = inclination( vertex ) / Math.PI + 0.5;
  11983. uvBuffer.push( u, 1 - v );
  11984. }
  11985. correctUVs();
  11986. correctSeam();
  11987. }
  11988. function correctSeam() {
  11989. // handle case when face straddles the seam, see #3269
  11990. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  11991. // uv data of a single face
  11992. const x0 = uvBuffer[ i + 0 ];
  11993. const x1 = uvBuffer[ i + 2 ];
  11994. const x2 = uvBuffer[ i + 4 ];
  11995. const max = Math.max( x0, x1, x2 );
  11996. const min = Math.min( x0, x1, x2 );
  11997. // 0.9 is somewhat arbitrary
  11998. if ( max > 0.9 && min < 0.1 ) {
  11999. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  12000. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  12001. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  12002. }
  12003. }
  12004. }
  12005. function pushVertex( vertex ) {
  12006. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  12007. }
  12008. function getVertexByIndex( index, vertex ) {
  12009. const stride = index * 3;
  12010. vertex.x = vertices[ stride + 0 ];
  12011. vertex.y = vertices[ stride + 1 ];
  12012. vertex.z = vertices[ stride + 2 ];
  12013. }
  12014. function correctUVs() {
  12015. const a = new Vector3();
  12016. const b = new Vector3();
  12017. const c = new Vector3();
  12018. const centroid = new Vector3();
  12019. const uvA = new Vector2();
  12020. const uvB = new Vector2();
  12021. const uvC = new Vector2();
  12022. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  12023. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  12024. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  12025. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  12026. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  12027. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  12028. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  12029. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  12030. const azi = azimuth( centroid );
  12031. correctUV( uvA, j + 0, a, azi );
  12032. correctUV( uvB, j + 2, b, azi );
  12033. correctUV( uvC, j + 4, c, azi );
  12034. }
  12035. }
  12036. function correctUV( uv, stride, vector, azimuth ) {
  12037. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  12038. uvBuffer[ stride ] = uv.x - 1;
  12039. }
  12040. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  12041. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  12042. }
  12043. }
  12044. // Angle around the Y axis, counter-clockwise when looking from above.
  12045. function azimuth( vector ) {
  12046. return Math.atan2( vector.z, - vector.x );
  12047. }
  12048. // Angle above the XZ plane.
  12049. function inclination( vector ) {
  12050. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  12051. }
  12052. }
  12053. copy( source ) {
  12054. super.copy( source );
  12055. this.parameters = Object.assign( {}, source.parameters );
  12056. return this;
  12057. }
  12058. static fromJSON( data ) {
  12059. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  12060. }
  12061. }
  12062. class DodecahedronGeometry extends PolyhedronGeometry {
  12063. constructor( radius = 1, detail = 0 ) {
  12064. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  12065. const r = 1 / t;
  12066. const vertices = [
  12067. // (±1, ±1, ±1)
  12068. - 1, - 1, - 1, - 1, - 1, 1,
  12069. - 1, 1, - 1, - 1, 1, 1,
  12070. 1, - 1, - 1, 1, - 1, 1,
  12071. 1, 1, - 1, 1, 1, 1,
  12072. // (0, ±1/φ, ±φ)
  12073. 0, - r, - t, 0, - r, t,
  12074. 0, r, - t, 0, r, t,
  12075. // (±1/φ, ±φ, 0)
  12076. - r, - t, 0, - r, t, 0,
  12077. r, - t, 0, r, t, 0,
  12078. // (±φ, 0, ±1/φ)
  12079. - t, 0, - r, t, 0, - r,
  12080. - t, 0, r, t, 0, r
  12081. ];
  12082. const indices = [
  12083. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  12084. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  12085. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  12086. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  12087. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  12088. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  12089. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  12090. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  12091. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  12092. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  12093. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  12094. 1, 12, 14, 1, 14, 5, 1, 5, 9
  12095. ];
  12096. super( vertices, indices, radius, detail );
  12097. this.type = 'DodecahedronGeometry';
  12098. this.parameters = {
  12099. radius: radius,
  12100. detail: detail
  12101. };
  12102. }
  12103. static fromJSON( data ) {
  12104. return new DodecahedronGeometry( data.radius, data.detail );
  12105. }
  12106. }
  12107. const _v0 = /*@__PURE__*/ new Vector3();
  12108. const _v1$1 = /*@__PURE__*/ new Vector3();
  12109. const _normal$1 = /*@__PURE__*/ new Vector3();
  12110. const _triangle = /*@__PURE__*/ new Triangle();
  12111. class EdgesGeometry extends BufferGeometry {
  12112. constructor( geometry = null, thresholdAngle = 1 ) {
  12113. super();
  12114. this.type = 'EdgesGeometry';
  12115. this.parameters = {
  12116. geometry: geometry,
  12117. thresholdAngle: thresholdAngle
  12118. };
  12119. if ( geometry !== null ) {
  12120. const precisionPoints = 4;
  12121. const precision = Math.pow( 10, precisionPoints );
  12122. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  12123. const indexAttr = geometry.getIndex();
  12124. const positionAttr = geometry.getAttribute( 'position' );
  12125. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  12126. const indexArr = [ 0, 0, 0 ];
  12127. const vertKeys = [ 'a', 'b', 'c' ];
  12128. const hashes = new Array( 3 );
  12129. const edgeData = {};
  12130. const vertices = [];
  12131. for ( let i = 0; i < indexCount; i += 3 ) {
  12132. if ( indexAttr ) {
  12133. indexArr[ 0 ] = indexAttr.getX( i );
  12134. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  12135. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  12136. } else {
  12137. indexArr[ 0 ] = i;
  12138. indexArr[ 1 ] = i + 1;
  12139. indexArr[ 2 ] = i + 2;
  12140. }
  12141. const { a, b, c } = _triangle;
  12142. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  12143. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  12144. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  12145. _triangle.getNormal( _normal$1 );
  12146. // create hashes for the edge from the vertices
  12147. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  12148. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  12149. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  12150. // skip degenerate triangles
  12151. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  12152. continue;
  12153. }
  12154. // iterate over every edge
  12155. for ( let j = 0; j < 3; j ++ ) {
  12156. // get the first and next vertex making up the edge
  12157. const jNext = ( j + 1 ) % 3;
  12158. const vecHash0 = hashes[ j ];
  12159. const vecHash1 = hashes[ jNext ];
  12160. const v0 = _triangle[ vertKeys[ j ] ];
  12161. const v1 = _triangle[ vertKeys[ jNext ] ];
  12162. const hash = `${ vecHash0 }_${ vecHash1 }`;
  12163. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  12164. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  12165. // if we found a sibling edge add it into the vertex array if
  12166. // it meets the angle threshold and delete the edge from the map.
  12167. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  12168. vertices.push( v0.x, v0.y, v0.z );
  12169. vertices.push( v1.x, v1.y, v1.z );
  12170. }
  12171. edgeData[ reverseHash ] = null;
  12172. } else if ( ! ( hash in edgeData ) ) {
  12173. // if we've already got an edge here then skip adding a new one
  12174. edgeData[ hash ] = {
  12175. index0: indexArr[ j ],
  12176. index1: indexArr[ jNext ],
  12177. normal: _normal$1.clone(),
  12178. };
  12179. }
  12180. }
  12181. }
  12182. // iterate over all remaining, unmatched edges and add them to the vertex array
  12183. for ( const key in edgeData ) {
  12184. if ( edgeData[ key ] ) {
  12185. const { index0, index1 } = edgeData[ key ];
  12186. _v0.fromBufferAttribute( positionAttr, index0 );
  12187. _v1$1.fromBufferAttribute( positionAttr, index1 );
  12188. vertices.push( _v0.x, _v0.y, _v0.z );
  12189. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  12190. }
  12191. }
  12192. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  12193. }
  12194. }
  12195. copy( source ) {
  12196. super.copy( source );
  12197. this.parameters = Object.assign( {}, source.parameters );
  12198. return this;
  12199. }
  12200. }
  12201. class Shape extends Path {
  12202. constructor( points ) {
  12203. super( points );
  12204. this.uuid = generateUUID();
  12205. this.type = 'Shape';
  12206. this.holes = [];
  12207. }
  12208. getPointsHoles( divisions ) {
  12209. const holesPts = [];
  12210. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12211. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  12212. }
  12213. return holesPts;
  12214. }
  12215. // get points of shape and holes (keypoints based on segments parameter)
  12216. extractPoints( divisions ) {
  12217. return {
  12218. shape: this.getPoints( divisions ),
  12219. holes: this.getPointsHoles( divisions )
  12220. };
  12221. }
  12222. copy( source ) {
  12223. super.copy( source );
  12224. this.holes = [];
  12225. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  12226. const hole = source.holes[ i ];
  12227. this.holes.push( hole.clone() );
  12228. }
  12229. return this;
  12230. }
  12231. toJSON() {
  12232. const data = super.toJSON();
  12233. data.uuid = this.uuid;
  12234. data.holes = [];
  12235. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12236. const hole = this.holes[ i ];
  12237. data.holes.push( hole.toJSON() );
  12238. }
  12239. return data;
  12240. }
  12241. fromJSON( json ) {
  12242. super.fromJSON( json );
  12243. this.uuid = json.uuid;
  12244. this.holes = [];
  12245. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  12246. const hole = json.holes[ i ];
  12247. this.holes.push( new Path().fromJSON( hole ) );
  12248. }
  12249. return this;
  12250. }
  12251. }
  12252. /**
  12253. * Port from https://github.com/mapbox/earcut (v2.2.4)
  12254. */
  12255. const Earcut = {
  12256. triangulate: function ( data, holeIndices, dim = 2 ) {
  12257. const hasHoles = holeIndices && holeIndices.length;
  12258. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  12259. let outerNode = linkedList( data, 0, outerLen, dim, true );
  12260. const triangles = [];
  12261. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  12262. let minX, minY, maxX, maxY, x, y, invSize;
  12263. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  12264. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  12265. if ( data.length > 80 * dim ) {
  12266. minX = maxX = data[ 0 ];
  12267. minY = maxY = data[ 1 ];
  12268. for ( let i = dim; i < outerLen; i += dim ) {
  12269. x = data[ i ];
  12270. y = data[ i + 1 ];
  12271. if ( x < minX ) minX = x;
  12272. if ( y < minY ) minY = y;
  12273. if ( x > maxX ) maxX = x;
  12274. if ( y > maxY ) maxY = y;
  12275. }
  12276. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  12277. invSize = Math.max( maxX - minX, maxY - minY );
  12278. invSize = invSize !== 0 ? 32767 / invSize : 0;
  12279. }
  12280. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  12281. return triangles;
  12282. }
  12283. };
  12284. // create a circular doubly linked list from polygon points in the specified winding order
  12285. function linkedList( data, start, end, dim, clockwise ) {
  12286. let i, last;
  12287. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  12288. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12289. } else {
  12290. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12291. }
  12292. if ( last && equals$1( last, last.next ) ) {
  12293. removeNode( last );
  12294. last = last.next;
  12295. }
  12296. return last;
  12297. }
  12298. // eliminate colinear or duplicate points
  12299. function filterPoints( start, end ) {
  12300. if ( ! start ) return start;
  12301. if ( ! end ) end = start;
  12302. let p = start,
  12303. again;
  12304. do {
  12305. again = false;
  12306. if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  12307. removeNode( p );
  12308. p = end = p.prev;
  12309. if ( p === p.next ) break;
  12310. again = true;
  12311. } else {
  12312. p = p.next;
  12313. }
  12314. } while ( again || p !== end );
  12315. return end;
  12316. }
  12317. // main ear slicing loop which triangulates a polygon (given as a linked list)
  12318. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  12319. if ( ! ear ) return;
  12320. // interlink polygon nodes in z-order
  12321. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  12322. let stop = ear,
  12323. prev, next;
  12324. // iterate through ears, slicing them one by one
  12325. while ( ear.prev !== ear.next ) {
  12326. prev = ear.prev;
  12327. next = ear.next;
  12328. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  12329. // cut off the triangle
  12330. triangles.push( prev.i / dim | 0 );
  12331. triangles.push( ear.i / dim | 0 );
  12332. triangles.push( next.i / dim | 0 );
  12333. removeNode( ear );
  12334. // skipping the next vertex leads to less sliver triangles
  12335. ear = next.next;
  12336. stop = next.next;
  12337. continue;
  12338. }
  12339. ear = next;
  12340. // if we looped through the whole remaining polygon and can't find any more ears
  12341. if ( ear === stop ) {
  12342. // try filtering points and slicing again
  12343. if ( ! pass ) {
  12344. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  12345. // if this didn't work, try curing all small self-intersections locally
  12346. } else if ( pass === 1 ) {
  12347. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  12348. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  12349. // as a last resort, try splitting the remaining polygon into two
  12350. } else if ( pass === 2 ) {
  12351. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  12352. }
  12353. break;
  12354. }
  12355. }
  12356. }
  12357. // check whether a polygon node forms a valid ear with adjacent nodes
  12358. function isEar( ear ) {
  12359. const a = ear.prev,
  12360. b = ear,
  12361. c = ear.next;
  12362. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12363. // now make sure we don't have other points inside the potential ear
  12364. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12365. // triangle bbox; min & max are calculated like this for speed
  12366. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12367. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12368. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12369. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12370. let p = c.next;
  12371. while ( p !== a ) {
  12372. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  12373. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  12374. area( p.prev, p, p.next ) >= 0 ) return false;
  12375. p = p.next;
  12376. }
  12377. return true;
  12378. }
  12379. function isEarHashed( ear, minX, minY, invSize ) {
  12380. const a = ear.prev,
  12381. b = ear,
  12382. c = ear.next;
  12383. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12384. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12385. // triangle bbox; min & max are calculated like this for speed
  12386. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12387. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12388. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12389. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12390. // z-order range for the current triangle bbox;
  12391. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  12392. maxZ = zOrder( x1, y1, minX, minY, invSize );
  12393. let p = ear.prevZ,
  12394. n = ear.nextZ;
  12395. // look for points inside the triangle in both directions
  12396. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  12397. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12398. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12399. p = p.prevZ;
  12400. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12401. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12402. n = n.nextZ;
  12403. }
  12404. // look for remaining points in decreasing z-order
  12405. while ( p && p.z >= minZ ) {
  12406. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12407. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12408. p = p.prevZ;
  12409. }
  12410. // look for remaining points in increasing z-order
  12411. while ( n && n.z <= maxZ ) {
  12412. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12413. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12414. n = n.nextZ;
  12415. }
  12416. return true;
  12417. }
  12418. // go through all polygon nodes and cure small local self-intersections
  12419. function cureLocalIntersections( start, triangles, dim ) {
  12420. let p = start;
  12421. do {
  12422. const a = p.prev,
  12423. b = p.next.next;
  12424. if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  12425. triangles.push( a.i / dim | 0 );
  12426. triangles.push( p.i / dim | 0 );
  12427. triangles.push( b.i / dim | 0 );
  12428. // remove two nodes involved
  12429. removeNode( p );
  12430. removeNode( p.next );
  12431. p = start = b;
  12432. }
  12433. p = p.next;
  12434. } while ( p !== start );
  12435. return filterPoints( p );
  12436. }
  12437. // try splitting polygon into two and triangulate them independently
  12438. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  12439. // look for a valid diagonal that divides the polygon into two
  12440. let a = start;
  12441. do {
  12442. let b = a.next.next;
  12443. while ( b !== a.prev ) {
  12444. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  12445. // split the polygon in two by the diagonal
  12446. let c = splitPolygon( a, b );
  12447. // filter colinear points around the cuts
  12448. a = filterPoints( a, a.next );
  12449. c = filterPoints( c, c.next );
  12450. // run earcut on each half
  12451. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  12452. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  12453. return;
  12454. }
  12455. b = b.next;
  12456. }
  12457. a = a.next;
  12458. } while ( a !== start );
  12459. }
  12460. // link every hole into the outer loop, producing a single-ring polygon without holes
  12461. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  12462. const queue = [];
  12463. let i, len, start, end, list;
  12464. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  12465. start = holeIndices[ i ] * dim;
  12466. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  12467. list = linkedList( data, start, end, dim, false );
  12468. if ( list === list.next ) list.steiner = true;
  12469. queue.push( getLeftmost( list ) );
  12470. }
  12471. queue.sort( compareX );
  12472. // process holes from left to right
  12473. for ( i = 0; i < queue.length; i ++ ) {
  12474. outerNode = eliminateHole( queue[ i ], outerNode );
  12475. }
  12476. return outerNode;
  12477. }
  12478. function compareX( a, b ) {
  12479. return a.x - b.x;
  12480. }
  12481. // find a bridge between vertices that connects hole with an outer ring and link it
  12482. function eliminateHole( hole, outerNode ) {
  12483. const bridge = findHoleBridge( hole, outerNode );
  12484. if ( ! bridge ) {
  12485. return outerNode;
  12486. }
  12487. const bridgeReverse = splitPolygon( bridge, hole );
  12488. // filter collinear points around the cuts
  12489. filterPoints( bridgeReverse, bridgeReverse.next );
  12490. return filterPoints( bridge, bridge.next );
  12491. }
  12492. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  12493. function findHoleBridge( hole, outerNode ) {
  12494. let p = outerNode,
  12495. qx = - Infinity,
  12496. m;
  12497. const hx = hole.x, hy = hole.y;
  12498. // find a segment intersected by a ray from the hole's leftmost point to the left;
  12499. // segment's endpoint with lesser x will be potential connection point
  12500. do {
  12501. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  12502. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  12503. if ( x <= hx && x > qx ) {
  12504. qx = x;
  12505. m = p.x < p.next.x ? p : p.next;
  12506. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  12507. }
  12508. }
  12509. p = p.next;
  12510. } while ( p !== outerNode );
  12511. if ( ! m ) return null;
  12512. // look for points inside the triangle of hole point, segment intersection and endpoint;
  12513. // if there are no points found, we have a valid connection;
  12514. // otherwise choose the point of the minimum angle with the ray as connection point
  12515. const stop = m,
  12516. mx = m.x,
  12517. my = m.y;
  12518. let tanMin = Infinity, tan;
  12519. p = m;
  12520. do {
  12521. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  12522. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  12523. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  12524. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  12525. m = p;
  12526. tanMin = tan;
  12527. }
  12528. }
  12529. p = p.next;
  12530. } while ( p !== stop );
  12531. return m;
  12532. }
  12533. // whether sector in vertex m contains sector in vertex p in the same coordinates
  12534. function sectorContainsSector( m, p ) {
  12535. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  12536. }
  12537. // interlink polygon nodes in z-order
  12538. function indexCurve( start, minX, minY, invSize ) {
  12539. let p = start;
  12540. do {
  12541. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  12542. p.prevZ = p.prev;
  12543. p.nextZ = p.next;
  12544. p = p.next;
  12545. } while ( p !== start );
  12546. p.prevZ.nextZ = null;
  12547. p.prevZ = null;
  12548. sortLinked( p );
  12549. }
  12550. // Simon Tatham's linked list merge sort algorithm
  12551. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  12552. function sortLinked( list ) {
  12553. let i, p, q, e, tail, numMerges, pSize, qSize,
  12554. inSize = 1;
  12555. do {
  12556. p = list;
  12557. list = null;
  12558. tail = null;
  12559. numMerges = 0;
  12560. while ( p ) {
  12561. numMerges ++;
  12562. q = p;
  12563. pSize = 0;
  12564. for ( i = 0; i < inSize; i ++ ) {
  12565. pSize ++;
  12566. q = q.nextZ;
  12567. if ( ! q ) break;
  12568. }
  12569. qSize = inSize;
  12570. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  12571. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  12572. e = p;
  12573. p = p.nextZ;
  12574. pSize --;
  12575. } else {
  12576. e = q;
  12577. q = q.nextZ;
  12578. qSize --;
  12579. }
  12580. if ( tail ) tail.nextZ = e;
  12581. else list = e;
  12582. e.prevZ = tail;
  12583. tail = e;
  12584. }
  12585. p = q;
  12586. }
  12587. tail.nextZ = null;
  12588. inSize *= 2;
  12589. } while ( numMerges > 1 );
  12590. return list;
  12591. }
  12592. // z-order of a point given coords and inverse of the longer side of data bbox
  12593. function zOrder( x, y, minX, minY, invSize ) {
  12594. // coords are transformed into non-negative 15-bit integer range
  12595. x = ( x - minX ) * invSize | 0;
  12596. y = ( y - minY ) * invSize | 0;
  12597. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  12598. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  12599. x = ( x | ( x << 2 ) ) & 0x33333333;
  12600. x = ( x | ( x << 1 ) ) & 0x55555555;
  12601. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  12602. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  12603. y = ( y | ( y << 2 ) ) & 0x33333333;
  12604. y = ( y | ( y << 1 ) ) & 0x55555555;
  12605. return x | ( y << 1 );
  12606. }
  12607. // find the leftmost node of a polygon ring
  12608. function getLeftmost( start ) {
  12609. let p = start,
  12610. leftmost = start;
  12611. do {
  12612. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  12613. p = p.next;
  12614. } while ( p !== start );
  12615. return leftmost;
  12616. }
  12617. // check if a point lies within a convex triangle
  12618. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  12619. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  12620. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  12621. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  12622. }
  12623. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  12624. function isValidDiagonal( a, b ) {
  12625. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  12626. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  12627. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  12628. equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  12629. }
  12630. // signed area of a triangle
  12631. function area( p, q, r ) {
  12632. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  12633. }
  12634. // check if two points are equal
  12635. function equals$1( p1, p2 ) {
  12636. return p1.x === p2.x && p1.y === p2.y;
  12637. }
  12638. // check if two segments intersect
  12639. function intersects( p1, q1, p2, q2 ) {
  12640. const o1 = sign$1( area( p1, q1, p2 ) );
  12641. const o2 = sign$1( area( p1, q1, q2 ) );
  12642. const o3 = sign$1( area( p2, q2, p1 ) );
  12643. const o4 = sign$1( area( p2, q2, q1 ) );
  12644. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  12645. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  12646. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  12647. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  12648. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  12649. return false;
  12650. }
  12651. // for collinear points p, q, r, check if point q lies on segment pr
  12652. function onSegment( p, q, r ) {
  12653. 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 );
  12654. }
  12655. function sign$1( num ) {
  12656. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  12657. }
  12658. // check if a polygon diagonal intersects any polygon segments
  12659. function intersectsPolygon( a, b ) {
  12660. let p = a;
  12661. do {
  12662. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  12663. intersects( p, p.next, a, b ) ) return true;
  12664. p = p.next;
  12665. } while ( p !== a );
  12666. return false;
  12667. }
  12668. // check if a polygon diagonal is locally inside the polygon
  12669. function locallyInside( a, b ) {
  12670. return area( a.prev, a, a.next ) < 0 ?
  12671. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  12672. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  12673. }
  12674. // check if the middle point of a polygon diagonal is inside the polygon
  12675. function middleInside( a, b ) {
  12676. let p = a,
  12677. inside = false;
  12678. const px = ( a.x + b.x ) / 2,
  12679. py = ( a.y + b.y ) / 2;
  12680. do {
  12681. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  12682. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  12683. inside = ! inside;
  12684. p = p.next;
  12685. } while ( p !== a );
  12686. return inside;
  12687. }
  12688. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  12689. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  12690. function splitPolygon( a, b ) {
  12691. const a2 = new Node$1( a.i, a.x, a.y ),
  12692. b2 = new Node$1( b.i, b.x, b.y ),
  12693. an = a.next,
  12694. bp = b.prev;
  12695. a.next = b;
  12696. b.prev = a;
  12697. a2.next = an;
  12698. an.prev = a2;
  12699. b2.next = a2;
  12700. a2.prev = b2;
  12701. bp.next = b2;
  12702. b2.prev = bp;
  12703. return b2;
  12704. }
  12705. // create a node and optionally link it with previous one (in a circular doubly linked list)
  12706. function insertNode( i, x, y, last ) {
  12707. const p = new Node$1( i, x, y );
  12708. if ( ! last ) {
  12709. p.prev = p;
  12710. p.next = p;
  12711. } else {
  12712. p.next = last.next;
  12713. p.prev = last;
  12714. last.next.prev = p;
  12715. last.next = p;
  12716. }
  12717. return p;
  12718. }
  12719. function removeNode( p ) {
  12720. p.next.prev = p.prev;
  12721. p.prev.next = p.next;
  12722. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  12723. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  12724. }
  12725. function Node$1( i, x, y ) {
  12726. // vertex index in coordinates array
  12727. this.i = i;
  12728. // vertex coordinates
  12729. this.x = x;
  12730. this.y = y;
  12731. // previous and next vertex nodes in a polygon ring
  12732. this.prev = null;
  12733. this.next = null;
  12734. // z-order curve value
  12735. this.z = 0;
  12736. // previous and next nodes in z-order
  12737. this.prevZ = null;
  12738. this.nextZ = null;
  12739. // indicates whether this is a steiner point
  12740. this.steiner = false;
  12741. }
  12742. function signedArea( data, start, end, dim ) {
  12743. let sum = 0;
  12744. for ( let i = start, j = end - dim; i < end; i += dim ) {
  12745. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  12746. j = i;
  12747. }
  12748. return sum;
  12749. }
  12750. class ShapeUtils {
  12751. // calculate area of the contour polygon
  12752. static area( contour ) {
  12753. const n = contour.length;
  12754. let a = 0.0;
  12755. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  12756. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  12757. }
  12758. return a * 0.5;
  12759. }
  12760. static isClockWise( pts ) {
  12761. return ShapeUtils.area( pts ) < 0;
  12762. }
  12763. static triangulateShape( contour, holes ) {
  12764. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  12765. const holeIndices = []; // array of hole indices
  12766. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  12767. removeDupEndPts( contour );
  12768. addContour( vertices, contour );
  12769. //
  12770. let holeIndex = contour.length;
  12771. holes.forEach( removeDupEndPts );
  12772. for ( let i = 0; i < holes.length; i ++ ) {
  12773. holeIndices.push( holeIndex );
  12774. holeIndex += holes[ i ].length;
  12775. addContour( vertices, holes[ i ] );
  12776. }
  12777. //
  12778. const triangles = Earcut.triangulate( vertices, holeIndices );
  12779. //
  12780. for ( let i = 0; i < triangles.length; i += 3 ) {
  12781. faces.push( triangles.slice( i, i + 3 ) );
  12782. }
  12783. return faces;
  12784. }
  12785. }
  12786. function removeDupEndPts( points ) {
  12787. const l = points.length;
  12788. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  12789. points.pop();
  12790. }
  12791. }
  12792. function addContour( vertices, contour ) {
  12793. for ( let i = 0; i < contour.length; i ++ ) {
  12794. vertices.push( contour[ i ].x );
  12795. vertices.push( contour[ i ].y );
  12796. }
  12797. }
  12798. /**
  12799. * Creates extruded geometry from a path shape.
  12800. *
  12801. * parameters = {
  12802. *
  12803. * curveSegments: <int>, // number of points on the curves
  12804. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  12805. * depth: <float>, // Depth to extrude the shape
  12806. *
  12807. * bevelEnabled: <bool>, // turn on bevel
  12808. * bevelThickness: <float>, // how deep into the original shape bevel goes
  12809. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  12810. * bevelOffset: <float>, // how far from shape outline does bevel start
  12811. * bevelSegments: <int>, // number of bevel layers
  12812. *
  12813. * extrudePath: <THREE.Curve> // curve to extrude shape along
  12814. *
  12815. * UVGenerator: <Object> // object that provides UV generator functions
  12816. *
  12817. * }
  12818. */
  12819. class ExtrudeGeometry extends BufferGeometry {
  12820. 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 = {} ) {
  12821. super();
  12822. this.type = 'ExtrudeGeometry';
  12823. this.parameters = {
  12824. shapes: shapes,
  12825. options: options
  12826. };
  12827. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  12828. const scope = this;
  12829. const verticesArray = [];
  12830. const uvArray = [];
  12831. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  12832. const shape = shapes[ i ];
  12833. addShape( shape );
  12834. }
  12835. // build geometry
  12836. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  12837. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  12838. this.computeVertexNormals();
  12839. // functions
  12840. function addShape( shape ) {
  12841. const placeholder = [];
  12842. // options
  12843. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  12844. const steps = options.steps !== undefined ? options.steps : 1;
  12845. const depth = options.depth !== undefined ? options.depth : 1;
  12846. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  12847. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  12848. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  12849. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  12850. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  12851. const extrudePath = options.extrudePath;
  12852. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  12853. //
  12854. let extrudePts, extrudeByPath = false;
  12855. let splineTube, binormal, normal, position2;
  12856. if ( extrudePath ) {
  12857. extrudePts = extrudePath.getSpacedPoints( steps );
  12858. extrudeByPath = true;
  12859. bevelEnabled = false; // bevels not supported for path extrusion
  12860. // SETUP TNB variables
  12861. // TODO1 - have a .isClosed in spline?
  12862. splineTube = extrudePath.computeFrenetFrames( steps, false );
  12863. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  12864. binormal = new Vector3();
  12865. normal = new Vector3();
  12866. position2 = new Vector3();
  12867. }
  12868. // Safeguards if bevels are not enabled
  12869. if ( ! bevelEnabled ) {
  12870. bevelSegments = 0;
  12871. bevelThickness = 0;
  12872. bevelSize = 0;
  12873. bevelOffset = 0;
  12874. }
  12875. // Variables initialization
  12876. const shapePoints = shape.extractPoints( curveSegments );
  12877. let vertices = shapePoints.shape;
  12878. const holes = shapePoints.holes;
  12879. const reverse = ! ShapeUtils.isClockWise( vertices );
  12880. if ( reverse ) {
  12881. vertices = vertices.reverse();
  12882. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  12883. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12884. const ahole = holes[ h ];
  12885. if ( ShapeUtils.isClockWise( ahole ) ) {
  12886. holes[ h ] = ahole.reverse();
  12887. }
  12888. }
  12889. }
  12890. const faces = ShapeUtils.triangulateShape( vertices, holes );
  12891. /* Vertices */
  12892. const contour = vertices; // vertices has all points but contour has only points of circumference
  12893. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12894. const ahole = holes[ h ];
  12895. vertices = vertices.concat( ahole );
  12896. }
  12897. function scalePt2( pt, vec, size ) {
  12898. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  12899. return pt.clone().addScaledVector( vec, size );
  12900. }
  12901. const vlen = vertices.length, flen = faces.length;
  12902. // Find directions for point movement
  12903. function getBevelVec( inPt, inPrev, inNext ) {
  12904. // computes for inPt the corresponding point inPt' on a new contour
  12905. // shifted by 1 unit (length of normalized vector) to the left
  12906. // if we walk along contour clockwise, this new contour is outside the old one
  12907. //
  12908. // inPt' is the intersection of the two lines parallel to the two
  12909. // adjacent edges of inPt at a distance of 1 unit on the left side.
  12910. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  12911. // good reading for geometry algorithms (here: line-line intersection)
  12912. // http://geomalgorithms.com/a05-_intersect-1.html
  12913. const v_prev_x = inPt.x - inPrev.x,
  12914. v_prev_y = inPt.y - inPrev.y;
  12915. const v_next_x = inNext.x - inPt.x,
  12916. v_next_y = inNext.y - inPt.y;
  12917. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  12918. // check for collinear edges
  12919. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12920. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  12921. // not collinear
  12922. // length of vectors for normalizing
  12923. const v_prev_len = Math.sqrt( v_prev_lensq );
  12924. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  12925. // shift adjacent points by unit vectors to the left
  12926. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  12927. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  12928. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  12929. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  12930. // scaling factor for v_prev to intersection point
  12931. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  12932. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  12933. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12934. // vector from inPt to intersection point
  12935. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  12936. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  12937. // Don't normalize!, otherwise sharp corners become ugly
  12938. // but prevent crazy spikes
  12939. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  12940. if ( v_trans_lensq <= 2 ) {
  12941. return new Vector2( v_trans_x, v_trans_y );
  12942. } else {
  12943. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  12944. }
  12945. } else {
  12946. // handle special case of collinear edges
  12947. let direction_eq = false; // assumes: opposite
  12948. if ( v_prev_x > Number.EPSILON ) {
  12949. if ( v_next_x > Number.EPSILON ) {
  12950. direction_eq = true;
  12951. }
  12952. } else {
  12953. if ( v_prev_x < - Number.EPSILON ) {
  12954. if ( v_next_x < - Number.EPSILON ) {
  12955. direction_eq = true;
  12956. }
  12957. } else {
  12958. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  12959. direction_eq = true;
  12960. }
  12961. }
  12962. }
  12963. if ( direction_eq ) {
  12964. // console.log("Warning: lines are a straight sequence");
  12965. v_trans_x = - v_prev_y;
  12966. v_trans_y = v_prev_x;
  12967. shrink_by = Math.sqrt( v_prev_lensq );
  12968. } else {
  12969. // console.log("Warning: lines are a straight spike");
  12970. v_trans_x = v_prev_x;
  12971. v_trans_y = v_prev_y;
  12972. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  12973. }
  12974. }
  12975. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  12976. }
  12977. const contourMovements = [];
  12978. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12979. if ( j === il ) j = 0;
  12980. if ( k === il ) k = 0;
  12981. // (j)---(i)---(k)
  12982. // console.log('i,j,k', i, j , k)
  12983. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  12984. }
  12985. const holesMovements = [];
  12986. let oneHoleMovements, verticesMovements = contourMovements.concat();
  12987. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12988. const ahole = holes[ h ];
  12989. oneHoleMovements = [];
  12990. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12991. if ( j === il ) j = 0;
  12992. if ( k === il ) k = 0;
  12993. // (j)---(i)---(k)
  12994. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  12995. }
  12996. holesMovements.push( oneHoleMovements );
  12997. verticesMovements = verticesMovements.concat( oneHoleMovements );
  12998. }
  12999. // Loop bevelSegments, 1 for the front, 1 for the back
  13000. for ( let b = 0; b < bevelSegments; b ++ ) {
  13001. //for ( b = bevelSegments; b > 0; b -- ) {
  13002. const t = b / bevelSegments;
  13003. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  13004. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  13005. // contract shape
  13006. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  13007. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  13008. v( vert.x, vert.y, - z );
  13009. }
  13010. // expand holes
  13011. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13012. const ahole = holes[ h ];
  13013. oneHoleMovements = holesMovements[ h ];
  13014. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  13015. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  13016. v( vert.x, vert.y, - z );
  13017. }
  13018. }
  13019. }
  13020. const bs = bevelSize + bevelOffset;
  13021. // Back facing vertices
  13022. for ( let i = 0; i < vlen; i ++ ) {
  13023. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  13024. if ( ! extrudeByPath ) {
  13025. v( vert.x, vert.y, 0 );
  13026. } else {
  13027. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  13028. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  13029. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  13030. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  13031. v( position2.x, position2.y, position2.z );
  13032. }
  13033. }
  13034. // Add stepped vertices...
  13035. // Including front facing vertices
  13036. for ( let s = 1; s <= steps; s ++ ) {
  13037. for ( let i = 0; i < vlen; i ++ ) {
  13038. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  13039. if ( ! extrudeByPath ) {
  13040. v( vert.x, vert.y, depth / steps * s );
  13041. } else {
  13042. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  13043. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  13044. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  13045. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  13046. v( position2.x, position2.y, position2.z );
  13047. }
  13048. }
  13049. }
  13050. // Add bevel segments planes
  13051. //for ( b = 1; b <= bevelSegments; b ++ ) {
  13052. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  13053. const t = b / bevelSegments;
  13054. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  13055. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  13056. // contract shape
  13057. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  13058. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  13059. v( vert.x, vert.y, depth + z );
  13060. }
  13061. // expand holes
  13062. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13063. const ahole = holes[ h ];
  13064. oneHoleMovements = holesMovements[ h ];
  13065. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  13066. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  13067. if ( ! extrudeByPath ) {
  13068. v( vert.x, vert.y, depth + z );
  13069. } else {
  13070. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  13071. }
  13072. }
  13073. }
  13074. }
  13075. /* Faces */
  13076. // Top and bottom faces
  13077. buildLidFaces();
  13078. // Sides faces
  13079. buildSideFaces();
  13080. ///// Internal functions
  13081. function buildLidFaces() {
  13082. const start = verticesArray.length / 3;
  13083. if ( bevelEnabled ) {
  13084. let layer = 0; // steps + 1
  13085. let offset = vlen * layer;
  13086. // Bottom faces
  13087. for ( let i = 0; i < flen; i ++ ) {
  13088. const face = faces[ i ];
  13089. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  13090. }
  13091. layer = steps + bevelSegments * 2;
  13092. offset = vlen * layer;
  13093. // Top faces
  13094. for ( let i = 0; i < flen; i ++ ) {
  13095. const face = faces[ i ];
  13096. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  13097. }
  13098. } else {
  13099. // Bottom faces
  13100. for ( let i = 0; i < flen; i ++ ) {
  13101. const face = faces[ i ];
  13102. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  13103. }
  13104. // Top faces
  13105. for ( let i = 0; i < flen; i ++ ) {
  13106. const face = faces[ i ];
  13107. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  13108. }
  13109. }
  13110. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  13111. }
  13112. // Create faces for the z-sides of the shape
  13113. function buildSideFaces() {
  13114. const start = verticesArray.length / 3;
  13115. let layeroffset = 0;
  13116. sidewalls( contour, layeroffset );
  13117. layeroffset += contour.length;
  13118. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13119. const ahole = holes[ h ];
  13120. sidewalls( ahole, layeroffset );
  13121. //, true
  13122. layeroffset += ahole.length;
  13123. }
  13124. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  13125. }
  13126. function sidewalls( contour, layeroffset ) {
  13127. let i = contour.length;
  13128. while ( -- i >= 0 ) {
  13129. const j = i;
  13130. let k = i - 1;
  13131. if ( k < 0 ) k = contour.length - 1;
  13132. //console.log('b', i,j, i-1, k,vertices.length);
  13133. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  13134. const slen1 = vlen * s;
  13135. const slen2 = vlen * ( s + 1 );
  13136. const a = layeroffset + j + slen1,
  13137. b = layeroffset + k + slen1,
  13138. c = layeroffset + k + slen2,
  13139. d = layeroffset + j + slen2;
  13140. f4( a, b, c, d );
  13141. }
  13142. }
  13143. }
  13144. function v( x, y, z ) {
  13145. placeholder.push( x );
  13146. placeholder.push( y );
  13147. placeholder.push( z );
  13148. }
  13149. function f3( a, b, c ) {
  13150. addVertex( a );
  13151. addVertex( b );
  13152. addVertex( c );
  13153. const nextIndex = verticesArray.length / 3;
  13154. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  13155. addUV( uvs[ 0 ] );
  13156. addUV( uvs[ 1 ] );
  13157. addUV( uvs[ 2 ] );
  13158. }
  13159. function f4( a, b, c, d ) {
  13160. addVertex( a );
  13161. addVertex( b );
  13162. addVertex( d );
  13163. addVertex( b );
  13164. addVertex( c );
  13165. addVertex( d );
  13166. const nextIndex = verticesArray.length / 3;
  13167. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  13168. addUV( uvs[ 0 ] );
  13169. addUV( uvs[ 1 ] );
  13170. addUV( uvs[ 3 ] );
  13171. addUV( uvs[ 1 ] );
  13172. addUV( uvs[ 2 ] );
  13173. addUV( uvs[ 3 ] );
  13174. }
  13175. function addVertex( index ) {
  13176. verticesArray.push( placeholder[ index * 3 + 0 ] );
  13177. verticesArray.push( placeholder[ index * 3 + 1 ] );
  13178. verticesArray.push( placeholder[ index * 3 + 2 ] );
  13179. }
  13180. function addUV( vector2 ) {
  13181. uvArray.push( vector2.x );
  13182. uvArray.push( vector2.y );
  13183. }
  13184. }
  13185. }
  13186. copy( source ) {
  13187. super.copy( source );
  13188. this.parameters = Object.assign( {}, source.parameters );
  13189. return this;
  13190. }
  13191. toJSON() {
  13192. const data = super.toJSON();
  13193. const shapes = this.parameters.shapes;
  13194. const options = this.parameters.options;
  13195. return toJSON$1( shapes, options, data );
  13196. }
  13197. static fromJSON( data, shapes ) {
  13198. const geometryShapes = [];
  13199. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13200. const shape = shapes[ data.shapes[ j ] ];
  13201. geometryShapes.push( shape );
  13202. }
  13203. const extrudePath = data.options.extrudePath;
  13204. if ( extrudePath !== undefined ) {
  13205. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  13206. }
  13207. return new ExtrudeGeometry( geometryShapes, data.options );
  13208. }
  13209. }
  13210. const WorldUVGenerator = {
  13211. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  13212. const a_x = vertices[ indexA * 3 ];
  13213. const a_y = vertices[ indexA * 3 + 1 ];
  13214. const b_x = vertices[ indexB * 3 ];
  13215. const b_y = vertices[ indexB * 3 + 1 ];
  13216. const c_x = vertices[ indexC * 3 ];
  13217. const c_y = vertices[ indexC * 3 + 1 ];
  13218. return [
  13219. new Vector2( a_x, a_y ),
  13220. new Vector2( b_x, b_y ),
  13221. new Vector2( c_x, c_y )
  13222. ];
  13223. },
  13224. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  13225. const a_x = vertices[ indexA * 3 ];
  13226. const a_y = vertices[ indexA * 3 + 1 ];
  13227. const a_z = vertices[ indexA * 3 + 2 ];
  13228. const b_x = vertices[ indexB * 3 ];
  13229. const b_y = vertices[ indexB * 3 + 1 ];
  13230. const b_z = vertices[ indexB * 3 + 2 ];
  13231. const c_x = vertices[ indexC * 3 ];
  13232. const c_y = vertices[ indexC * 3 + 1 ];
  13233. const c_z = vertices[ indexC * 3 + 2 ];
  13234. const d_x = vertices[ indexD * 3 ];
  13235. const d_y = vertices[ indexD * 3 + 1 ];
  13236. const d_z = vertices[ indexD * 3 + 2 ];
  13237. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  13238. return [
  13239. new Vector2( a_x, 1 - a_z ),
  13240. new Vector2( b_x, 1 - b_z ),
  13241. new Vector2( c_x, 1 - c_z ),
  13242. new Vector2( d_x, 1 - d_z )
  13243. ];
  13244. } else {
  13245. return [
  13246. new Vector2( a_y, 1 - a_z ),
  13247. new Vector2( b_y, 1 - b_z ),
  13248. new Vector2( c_y, 1 - c_z ),
  13249. new Vector2( d_y, 1 - d_z )
  13250. ];
  13251. }
  13252. }
  13253. };
  13254. function toJSON$1( shapes, options, data ) {
  13255. data.shapes = [];
  13256. if ( Array.isArray( shapes ) ) {
  13257. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13258. const shape = shapes[ i ];
  13259. data.shapes.push( shape.uuid );
  13260. }
  13261. } else {
  13262. data.shapes.push( shapes.uuid );
  13263. }
  13264. data.options = Object.assign( {}, options );
  13265. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  13266. return data;
  13267. }
  13268. class IcosahedronGeometry extends PolyhedronGeometry {
  13269. constructor( radius = 1, detail = 0 ) {
  13270. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13271. const vertices = [
  13272. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  13273. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  13274. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  13275. ];
  13276. const indices = [
  13277. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  13278. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  13279. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  13280. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  13281. ];
  13282. super( vertices, indices, radius, detail );
  13283. this.type = 'IcosahedronGeometry';
  13284. this.parameters = {
  13285. radius: radius,
  13286. detail: detail
  13287. };
  13288. }
  13289. static fromJSON( data ) {
  13290. return new IcosahedronGeometry( data.radius, data.detail );
  13291. }
  13292. }
  13293. class OctahedronGeometry extends PolyhedronGeometry {
  13294. constructor( radius = 1, detail = 0 ) {
  13295. const vertices = [
  13296. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  13297. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  13298. ];
  13299. const indices = [
  13300. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  13301. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  13302. 1, 3, 4, 1, 4, 2
  13303. ];
  13304. super( vertices, indices, radius, detail );
  13305. this.type = 'OctahedronGeometry';
  13306. this.parameters = {
  13307. radius: radius,
  13308. detail: detail
  13309. };
  13310. }
  13311. static fromJSON( data ) {
  13312. return new OctahedronGeometry( data.radius, data.detail );
  13313. }
  13314. }
  13315. class PlaneGeometry extends BufferGeometry {
  13316. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  13317. super();
  13318. this.type = 'PlaneGeometry';
  13319. this.parameters = {
  13320. width: width,
  13321. height: height,
  13322. widthSegments: widthSegments,
  13323. heightSegments: heightSegments
  13324. };
  13325. const width_half = width / 2;
  13326. const height_half = height / 2;
  13327. const gridX = Math.floor( widthSegments );
  13328. const gridY = Math.floor( heightSegments );
  13329. const gridX1 = gridX + 1;
  13330. const gridY1 = gridY + 1;
  13331. const segment_width = width / gridX;
  13332. const segment_height = height / gridY;
  13333. //
  13334. const indices = [];
  13335. const vertices = [];
  13336. const normals = [];
  13337. const uvs = [];
  13338. for ( let iy = 0; iy < gridY1; iy ++ ) {
  13339. const y = iy * segment_height - height_half;
  13340. for ( let ix = 0; ix < gridX1; ix ++ ) {
  13341. const x = ix * segment_width - width_half;
  13342. vertices.push( x, - y, 0 );
  13343. normals.push( 0, 0, 1 );
  13344. uvs.push( ix / gridX );
  13345. uvs.push( 1 - ( iy / gridY ) );
  13346. }
  13347. }
  13348. for ( let iy = 0; iy < gridY; iy ++ ) {
  13349. for ( let ix = 0; ix < gridX; ix ++ ) {
  13350. const a = ix + gridX1 * iy;
  13351. const b = ix + gridX1 * ( iy + 1 );
  13352. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13353. const d = ( ix + 1 ) + gridX1 * iy;
  13354. indices.push( a, b, d );
  13355. indices.push( b, c, d );
  13356. }
  13357. }
  13358. this.setIndex( indices );
  13359. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13360. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13361. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13362. }
  13363. copy( source ) {
  13364. super.copy( source );
  13365. this.parameters = Object.assign( {}, source.parameters );
  13366. return this;
  13367. }
  13368. static fromJSON( data ) {
  13369. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  13370. }
  13371. }
  13372. class RingGeometry extends BufferGeometry {
  13373. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13374. super();
  13375. this.type = 'RingGeometry';
  13376. this.parameters = {
  13377. innerRadius: innerRadius,
  13378. outerRadius: outerRadius,
  13379. thetaSegments: thetaSegments,
  13380. phiSegments: phiSegments,
  13381. thetaStart: thetaStart,
  13382. thetaLength: thetaLength
  13383. };
  13384. thetaSegments = Math.max( 3, thetaSegments );
  13385. phiSegments = Math.max( 1, phiSegments );
  13386. // buffers
  13387. const indices = [];
  13388. const vertices = [];
  13389. const normals = [];
  13390. const uvs = [];
  13391. // some helper variables
  13392. let radius = innerRadius;
  13393. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  13394. const vertex = new Vector3();
  13395. const uv = new Vector2();
  13396. // generate vertices, normals and uvs
  13397. for ( let j = 0; j <= phiSegments; j ++ ) {
  13398. for ( let i = 0; i <= thetaSegments; i ++ ) {
  13399. // values are generate from the inside of the ring to the outside
  13400. const segment = thetaStart + i / thetaSegments * thetaLength;
  13401. // vertex
  13402. vertex.x = radius * Math.cos( segment );
  13403. vertex.y = radius * Math.sin( segment );
  13404. vertices.push( vertex.x, vertex.y, vertex.z );
  13405. // normal
  13406. normals.push( 0, 0, 1 );
  13407. // uv
  13408. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  13409. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  13410. uvs.push( uv.x, uv.y );
  13411. }
  13412. // increase the radius for next row of vertices
  13413. radius += radiusStep;
  13414. }
  13415. // indices
  13416. for ( let j = 0; j < phiSegments; j ++ ) {
  13417. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  13418. for ( let i = 0; i < thetaSegments; i ++ ) {
  13419. const segment = i + thetaSegmentLevel;
  13420. const a = segment;
  13421. const b = segment + thetaSegments + 1;
  13422. const c = segment + thetaSegments + 2;
  13423. const d = segment + 1;
  13424. // faces
  13425. indices.push( a, b, d );
  13426. indices.push( b, c, d );
  13427. }
  13428. }
  13429. // build geometry
  13430. this.setIndex( indices );
  13431. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13432. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13433. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13434. }
  13435. copy( source ) {
  13436. super.copy( source );
  13437. this.parameters = Object.assign( {}, source.parameters );
  13438. return this;
  13439. }
  13440. static fromJSON( data ) {
  13441. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  13442. }
  13443. }
  13444. class ShapeGeometry extends BufferGeometry {
  13445. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  13446. super();
  13447. this.type = 'ShapeGeometry';
  13448. this.parameters = {
  13449. shapes: shapes,
  13450. curveSegments: curveSegments
  13451. };
  13452. // buffers
  13453. const indices = [];
  13454. const vertices = [];
  13455. const normals = [];
  13456. const uvs = [];
  13457. // helper variables
  13458. let groupStart = 0;
  13459. let groupCount = 0;
  13460. // allow single and array values for "shapes" parameter
  13461. if ( Array.isArray( shapes ) === false ) {
  13462. addShape( shapes );
  13463. } else {
  13464. for ( let i = 0; i < shapes.length; i ++ ) {
  13465. addShape( shapes[ i ] );
  13466. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  13467. groupStart += groupCount;
  13468. groupCount = 0;
  13469. }
  13470. }
  13471. // build geometry
  13472. this.setIndex( indices );
  13473. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13474. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13475. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13476. // helper functions
  13477. function addShape( shape ) {
  13478. const indexOffset = vertices.length / 3;
  13479. const points = shape.extractPoints( curveSegments );
  13480. let shapeVertices = points.shape;
  13481. const shapeHoles = points.holes;
  13482. // check direction of vertices
  13483. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  13484. shapeVertices = shapeVertices.reverse();
  13485. }
  13486. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13487. const shapeHole = shapeHoles[ i ];
  13488. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  13489. shapeHoles[ i ] = shapeHole.reverse();
  13490. }
  13491. }
  13492. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  13493. // join vertices of inner and outer paths to a single array
  13494. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13495. const shapeHole = shapeHoles[ i ];
  13496. shapeVertices = shapeVertices.concat( shapeHole );
  13497. }
  13498. // vertices, normals, uvs
  13499. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  13500. const vertex = shapeVertices[ i ];
  13501. vertices.push( vertex.x, vertex.y, 0 );
  13502. normals.push( 0, 0, 1 );
  13503. uvs.push( vertex.x, vertex.y ); // world uvs
  13504. }
  13505. // indices
  13506. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  13507. const face = faces[ i ];
  13508. const a = face[ 0 ] + indexOffset;
  13509. const b = face[ 1 ] + indexOffset;
  13510. const c = face[ 2 ] + indexOffset;
  13511. indices.push( a, b, c );
  13512. groupCount += 3;
  13513. }
  13514. }
  13515. }
  13516. copy( source ) {
  13517. super.copy( source );
  13518. this.parameters = Object.assign( {}, source.parameters );
  13519. return this;
  13520. }
  13521. toJSON() {
  13522. const data = super.toJSON();
  13523. const shapes = this.parameters.shapes;
  13524. return toJSON( shapes, data );
  13525. }
  13526. static fromJSON( data, shapes ) {
  13527. const geometryShapes = [];
  13528. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13529. const shape = shapes[ data.shapes[ j ] ];
  13530. geometryShapes.push( shape );
  13531. }
  13532. return new ShapeGeometry( geometryShapes, data.curveSegments );
  13533. }
  13534. }
  13535. function toJSON( shapes, data ) {
  13536. data.shapes = [];
  13537. if ( Array.isArray( shapes ) ) {
  13538. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13539. const shape = shapes[ i ];
  13540. data.shapes.push( shape.uuid );
  13541. }
  13542. } else {
  13543. data.shapes.push( shapes.uuid );
  13544. }
  13545. return data;
  13546. }
  13547. class SphereGeometry extends BufferGeometry {
  13548. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  13549. super();
  13550. this.type = 'SphereGeometry';
  13551. this.parameters = {
  13552. radius: radius,
  13553. widthSegments: widthSegments,
  13554. heightSegments: heightSegments,
  13555. phiStart: phiStart,
  13556. phiLength: phiLength,
  13557. thetaStart: thetaStart,
  13558. thetaLength: thetaLength
  13559. };
  13560. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  13561. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  13562. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  13563. let index = 0;
  13564. const grid = [];
  13565. const vertex = new Vector3();
  13566. const normal = new Vector3();
  13567. // buffers
  13568. const indices = [];
  13569. const vertices = [];
  13570. const normals = [];
  13571. const uvs = [];
  13572. // generate vertices, normals and uvs
  13573. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  13574. const verticesRow = [];
  13575. const v = iy / heightSegments;
  13576. // special case for the poles
  13577. let uOffset = 0;
  13578. if ( iy === 0 && thetaStart === 0 ) {
  13579. uOffset = 0.5 / widthSegments;
  13580. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  13581. uOffset = - 0.5 / widthSegments;
  13582. }
  13583. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  13584. const u = ix / widthSegments;
  13585. // vertex
  13586. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13587. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  13588. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13589. vertices.push( vertex.x, vertex.y, vertex.z );
  13590. // normal
  13591. normal.copy( vertex ).normalize();
  13592. normals.push( normal.x, normal.y, normal.z );
  13593. // uv
  13594. uvs.push( u + uOffset, 1 - v );
  13595. verticesRow.push( index ++ );
  13596. }
  13597. grid.push( verticesRow );
  13598. }
  13599. // indices
  13600. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  13601. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  13602. const a = grid[ iy ][ ix + 1 ];
  13603. const b = grid[ iy ][ ix ];
  13604. const c = grid[ iy + 1 ][ ix ];
  13605. const d = grid[ iy + 1 ][ ix + 1 ];
  13606. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  13607. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  13608. }
  13609. }
  13610. // build geometry
  13611. this.setIndex( indices );
  13612. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13613. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13614. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13615. }
  13616. copy( source ) {
  13617. super.copy( source );
  13618. this.parameters = Object.assign( {}, source.parameters );
  13619. return this;
  13620. }
  13621. static fromJSON( data ) {
  13622. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  13623. }
  13624. }
  13625. class TetrahedronGeometry extends PolyhedronGeometry {
  13626. constructor( radius = 1, detail = 0 ) {
  13627. const vertices = [
  13628. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  13629. ];
  13630. const indices = [
  13631. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  13632. ];
  13633. super( vertices, indices, radius, detail );
  13634. this.type = 'TetrahedronGeometry';
  13635. this.parameters = {
  13636. radius: radius,
  13637. detail: detail
  13638. };
  13639. }
  13640. static fromJSON( data ) {
  13641. return new TetrahedronGeometry( data.radius, data.detail );
  13642. }
  13643. }
  13644. class TorusGeometry extends BufferGeometry {
  13645. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  13646. super();
  13647. this.type = 'TorusGeometry';
  13648. this.parameters = {
  13649. radius: radius,
  13650. tube: tube,
  13651. radialSegments: radialSegments,
  13652. tubularSegments: tubularSegments,
  13653. arc: arc
  13654. };
  13655. radialSegments = Math.floor( radialSegments );
  13656. tubularSegments = Math.floor( tubularSegments );
  13657. // buffers
  13658. const indices = [];
  13659. const vertices = [];
  13660. const normals = [];
  13661. const uvs = [];
  13662. // helper variables
  13663. const center = new Vector3();
  13664. const vertex = new Vector3();
  13665. const normal = new Vector3();
  13666. // generate vertices, normals and uvs
  13667. for ( let j = 0; j <= radialSegments; j ++ ) {
  13668. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13669. const u = i / tubularSegments * arc;
  13670. const v = j / radialSegments * Math.PI * 2;
  13671. // vertex
  13672. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  13673. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  13674. vertex.z = tube * Math.sin( v );
  13675. vertices.push( vertex.x, vertex.y, vertex.z );
  13676. // normal
  13677. center.x = radius * Math.cos( u );
  13678. center.y = radius * Math.sin( u );
  13679. normal.subVectors( vertex, center ).normalize();
  13680. normals.push( normal.x, normal.y, normal.z );
  13681. // uv
  13682. uvs.push( i / tubularSegments );
  13683. uvs.push( j / radialSegments );
  13684. }
  13685. }
  13686. // generate indices
  13687. for ( let j = 1; j <= radialSegments; j ++ ) {
  13688. for ( let i = 1; i <= tubularSegments; i ++ ) {
  13689. // indices
  13690. const a = ( tubularSegments + 1 ) * j + i - 1;
  13691. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  13692. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  13693. const d = ( tubularSegments + 1 ) * j + i;
  13694. // faces
  13695. indices.push( a, b, d );
  13696. indices.push( b, c, d );
  13697. }
  13698. }
  13699. // build geometry
  13700. this.setIndex( indices );
  13701. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13702. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13703. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13704. }
  13705. copy( source ) {
  13706. super.copy( source );
  13707. this.parameters = Object.assign( {}, source.parameters );
  13708. return this;
  13709. }
  13710. static fromJSON( data ) {
  13711. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  13712. }
  13713. }
  13714. class TorusKnotGeometry extends BufferGeometry {
  13715. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  13716. super();
  13717. this.type = 'TorusKnotGeometry';
  13718. this.parameters = {
  13719. radius: radius,
  13720. tube: tube,
  13721. tubularSegments: tubularSegments,
  13722. radialSegments: radialSegments,
  13723. p: p,
  13724. q: q
  13725. };
  13726. tubularSegments = Math.floor( tubularSegments );
  13727. radialSegments = Math.floor( radialSegments );
  13728. // buffers
  13729. const indices = [];
  13730. const vertices = [];
  13731. const normals = [];
  13732. const uvs = [];
  13733. // helper variables
  13734. const vertex = new Vector3();
  13735. const normal = new Vector3();
  13736. const P1 = new Vector3();
  13737. const P2 = new Vector3();
  13738. const B = new Vector3();
  13739. const T = new Vector3();
  13740. const N = new Vector3();
  13741. // generate vertices, normals and uvs
  13742. for ( let i = 0; i <= tubularSegments; ++ i ) {
  13743. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  13744. const u = i / tubularSegments * p * Math.PI * 2;
  13745. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  13746. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  13747. calculatePositionOnCurve( u, p, q, radius, P1 );
  13748. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  13749. // calculate orthonormal basis
  13750. T.subVectors( P2, P1 );
  13751. N.addVectors( P2, P1 );
  13752. B.crossVectors( T, N );
  13753. N.crossVectors( B, T );
  13754. // normalize B, N. T can be ignored, we don't use it
  13755. B.normalize();
  13756. N.normalize();
  13757. for ( let j = 0; j <= radialSegments; ++ j ) {
  13758. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  13759. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  13760. const v = j / radialSegments * Math.PI * 2;
  13761. const cx = - tube * Math.cos( v );
  13762. const cy = tube * Math.sin( v );
  13763. // now calculate the final vertex position.
  13764. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  13765. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  13766. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  13767. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  13768. vertices.push( vertex.x, vertex.y, vertex.z );
  13769. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  13770. normal.subVectors( vertex, P1 ).normalize();
  13771. normals.push( normal.x, normal.y, normal.z );
  13772. // uv
  13773. uvs.push( i / tubularSegments );
  13774. uvs.push( j / radialSegments );
  13775. }
  13776. }
  13777. // generate indices
  13778. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13779. for ( let i = 1; i <= radialSegments; i ++ ) {
  13780. // indices
  13781. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13782. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13783. const c = ( radialSegments + 1 ) * j + i;
  13784. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13785. // faces
  13786. indices.push( a, b, d );
  13787. indices.push( b, c, d );
  13788. }
  13789. }
  13790. // build geometry
  13791. this.setIndex( indices );
  13792. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13793. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13794. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13795. // this function calculates the current position on the torus curve
  13796. function calculatePositionOnCurve( u, p, q, radius, position ) {
  13797. const cu = Math.cos( u );
  13798. const su = Math.sin( u );
  13799. const quOverP = q / p * u;
  13800. const cs = Math.cos( quOverP );
  13801. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  13802. position.y = radius * ( 2 + cs ) * su * 0.5;
  13803. position.z = radius * Math.sin( quOverP ) * 0.5;
  13804. }
  13805. }
  13806. copy( source ) {
  13807. super.copy( source );
  13808. this.parameters = Object.assign( {}, source.parameters );
  13809. return this;
  13810. }
  13811. static fromJSON( data ) {
  13812. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  13813. }
  13814. }
  13815. class TubeGeometry extends BufferGeometry {
  13816. 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 ) {
  13817. super();
  13818. this.type = 'TubeGeometry';
  13819. this.parameters = {
  13820. path: path,
  13821. tubularSegments: tubularSegments,
  13822. radius: radius,
  13823. radialSegments: radialSegments,
  13824. closed: closed
  13825. };
  13826. const frames = path.computeFrenetFrames( tubularSegments, closed );
  13827. // expose internals
  13828. this.tangents = frames.tangents;
  13829. this.normals = frames.normals;
  13830. this.binormals = frames.binormals;
  13831. // helper variables
  13832. const vertex = new Vector3();
  13833. const normal = new Vector3();
  13834. const uv = new Vector2();
  13835. let P = new Vector3();
  13836. // buffer
  13837. const vertices = [];
  13838. const normals = [];
  13839. const uvs = [];
  13840. const indices = [];
  13841. // create buffer data
  13842. generateBufferData();
  13843. // build geometry
  13844. this.setIndex( indices );
  13845. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13846. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13847. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13848. // functions
  13849. function generateBufferData() {
  13850. for ( let i = 0; i < tubularSegments; i ++ ) {
  13851. generateSegment( i );
  13852. }
  13853. // if the geometry is not closed, generate the last row of vertices and normals
  13854. // at the regular position on the given path
  13855. //
  13856. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  13857. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  13858. // uvs are generated in a separate function.
  13859. // this makes it easy compute correct values for closed geometries
  13860. generateUVs();
  13861. // finally create faces
  13862. generateIndices();
  13863. }
  13864. function generateSegment( i ) {
  13865. // we use getPointAt to sample evenly distributed points from the given path
  13866. P = path.getPointAt( i / tubularSegments, P );
  13867. // retrieve corresponding normal and binormal
  13868. const N = frames.normals[ i ];
  13869. const B = frames.binormals[ i ];
  13870. // generate normals and vertices for the current segment
  13871. for ( let j = 0; j <= radialSegments; j ++ ) {
  13872. const v = j / radialSegments * Math.PI * 2;
  13873. const sin = Math.sin( v );
  13874. const cos = - Math.cos( v );
  13875. // normal
  13876. normal.x = ( cos * N.x + sin * B.x );
  13877. normal.y = ( cos * N.y + sin * B.y );
  13878. normal.z = ( cos * N.z + sin * B.z );
  13879. normal.normalize();
  13880. normals.push( normal.x, normal.y, normal.z );
  13881. // vertex
  13882. vertex.x = P.x + radius * normal.x;
  13883. vertex.y = P.y + radius * normal.y;
  13884. vertex.z = P.z + radius * normal.z;
  13885. vertices.push( vertex.x, vertex.y, vertex.z );
  13886. }
  13887. }
  13888. function generateIndices() {
  13889. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13890. for ( let i = 1; i <= radialSegments; i ++ ) {
  13891. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13892. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13893. const c = ( radialSegments + 1 ) * j + i;
  13894. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13895. // faces
  13896. indices.push( a, b, d );
  13897. indices.push( b, c, d );
  13898. }
  13899. }
  13900. }
  13901. function generateUVs() {
  13902. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13903. for ( let j = 0; j <= radialSegments; j ++ ) {
  13904. uv.x = i / tubularSegments;
  13905. uv.y = j / radialSegments;
  13906. uvs.push( uv.x, uv.y );
  13907. }
  13908. }
  13909. }
  13910. }
  13911. copy( source ) {
  13912. super.copy( source );
  13913. this.parameters = Object.assign( {}, source.parameters );
  13914. return this;
  13915. }
  13916. toJSON() {
  13917. const data = super.toJSON();
  13918. data.path = this.parameters.path.toJSON();
  13919. return data;
  13920. }
  13921. static fromJSON( data ) {
  13922. // This only works for built-in curves (e.g. CatmullRomCurve3).
  13923. // User defined curves or instances of CurvePath will not be deserialized.
  13924. return new TubeGeometry(
  13925. new Curves[ data.path.type ]().fromJSON( data.path ),
  13926. data.tubularSegments,
  13927. data.radius,
  13928. data.radialSegments,
  13929. data.closed
  13930. );
  13931. }
  13932. }
  13933. class WireframeGeometry extends BufferGeometry {
  13934. constructor( geometry = null ) {
  13935. super();
  13936. this.type = 'WireframeGeometry';
  13937. this.parameters = {
  13938. geometry: geometry
  13939. };
  13940. if ( geometry !== null ) {
  13941. // buffer
  13942. const vertices = [];
  13943. const edges = new Set();
  13944. // helper variables
  13945. const start = new Vector3();
  13946. const end = new Vector3();
  13947. if ( geometry.index !== null ) {
  13948. // indexed BufferGeometry
  13949. const position = geometry.attributes.position;
  13950. const indices = geometry.index;
  13951. let groups = geometry.groups;
  13952. if ( groups.length === 0 ) {
  13953. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  13954. }
  13955. // create a data structure that contains all edges without duplicates
  13956. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  13957. const group = groups[ o ];
  13958. const groupStart = group.start;
  13959. const groupCount = group.count;
  13960. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  13961. for ( let j = 0; j < 3; j ++ ) {
  13962. const index1 = indices.getX( i + j );
  13963. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  13964. start.fromBufferAttribute( position, index1 );
  13965. end.fromBufferAttribute( position, index2 );
  13966. if ( isUniqueEdge( start, end, edges ) === true ) {
  13967. vertices.push( start.x, start.y, start.z );
  13968. vertices.push( end.x, end.y, end.z );
  13969. }
  13970. }
  13971. }
  13972. }
  13973. } else {
  13974. // non-indexed BufferGeometry
  13975. const position = geometry.attributes.position;
  13976. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  13977. for ( let j = 0; j < 3; j ++ ) {
  13978. // three edges per triangle, an edge is represented as (index1, index2)
  13979. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  13980. const index1 = 3 * i + j;
  13981. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  13982. start.fromBufferAttribute( position, index1 );
  13983. end.fromBufferAttribute( position, index2 );
  13984. if ( isUniqueEdge( start, end, edges ) === true ) {
  13985. vertices.push( start.x, start.y, start.z );
  13986. vertices.push( end.x, end.y, end.z );
  13987. }
  13988. }
  13989. }
  13990. }
  13991. // build geometry
  13992. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13993. }
  13994. }
  13995. copy( source ) {
  13996. super.copy( source );
  13997. this.parameters = Object.assign( {}, source.parameters );
  13998. return this;
  13999. }
  14000. }
  14001. function isUniqueEdge( start, end, edges ) {
  14002. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  14003. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  14004. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  14005. return false;
  14006. } else {
  14007. edges.add( hash1 );
  14008. edges.add( hash2 );
  14009. return true;
  14010. }
  14011. }
  14012. var Geometries$1 = /*#__PURE__*/Object.freeze({
  14013. __proto__: null,
  14014. BoxGeometry: BoxGeometry,
  14015. CapsuleGeometry: CapsuleGeometry,
  14016. CircleGeometry: CircleGeometry,
  14017. ConeGeometry: ConeGeometry,
  14018. CylinderGeometry: CylinderGeometry,
  14019. DodecahedronGeometry: DodecahedronGeometry,
  14020. EdgesGeometry: EdgesGeometry,
  14021. ExtrudeGeometry: ExtrudeGeometry,
  14022. IcosahedronGeometry: IcosahedronGeometry,
  14023. LatheGeometry: LatheGeometry,
  14024. OctahedronGeometry: OctahedronGeometry,
  14025. PlaneGeometry: PlaneGeometry,
  14026. PolyhedronGeometry: PolyhedronGeometry,
  14027. RingGeometry: RingGeometry,
  14028. ShapeGeometry: ShapeGeometry,
  14029. SphereGeometry: SphereGeometry,
  14030. TetrahedronGeometry: TetrahedronGeometry,
  14031. TorusGeometry: TorusGeometry,
  14032. TorusKnotGeometry: TorusKnotGeometry,
  14033. TubeGeometry: TubeGeometry,
  14034. WireframeGeometry: WireframeGeometry
  14035. });
  14036. class ShadowMaterial extends Material {
  14037. static get type() {
  14038. return 'ShadowMaterial';
  14039. }
  14040. constructor( parameters ) {
  14041. super();
  14042. this.isShadowMaterial = true;
  14043. this.color = new Color( 0x000000 );
  14044. this.transparent = true;
  14045. this.fog = true;
  14046. this.setValues( parameters );
  14047. }
  14048. copy( source ) {
  14049. super.copy( source );
  14050. this.color.copy( source.color );
  14051. this.fog = source.fog;
  14052. return this;
  14053. }
  14054. }
  14055. class RawShaderMaterial extends ShaderMaterial {
  14056. static get type() {
  14057. return 'RawShaderMaterial';
  14058. }
  14059. constructor( parameters ) {
  14060. super( parameters );
  14061. this.isRawShaderMaterial = true;
  14062. }
  14063. }
  14064. class MeshStandardMaterial extends Material {
  14065. static get type() {
  14066. return 'MeshStandardMaterial';
  14067. }
  14068. constructor( parameters ) {
  14069. super();
  14070. this.isMeshStandardMaterial = true;
  14071. this.defines = { 'STANDARD': '' };
  14072. this.color = new Color( 0xffffff ); // diffuse
  14073. this.roughness = 1.0;
  14074. this.metalness = 0.0;
  14075. this.map = null;
  14076. this.lightMap = null;
  14077. this.lightMapIntensity = 1.0;
  14078. this.aoMap = null;
  14079. this.aoMapIntensity = 1.0;
  14080. this.emissive = new Color( 0x000000 );
  14081. this.emissiveIntensity = 1.0;
  14082. this.emissiveMap = null;
  14083. this.bumpMap = null;
  14084. this.bumpScale = 1;
  14085. this.normalMap = null;
  14086. this.normalMapType = TangentSpaceNormalMap;
  14087. this.normalScale = new Vector2( 1, 1 );
  14088. this.displacementMap = null;
  14089. this.displacementScale = 1;
  14090. this.displacementBias = 0;
  14091. this.roughnessMap = null;
  14092. this.metalnessMap = null;
  14093. this.alphaMap = null;
  14094. this.envMap = null;
  14095. this.envMapRotation = new Euler();
  14096. this.envMapIntensity = 1.0;
  14097. this.wireframe = false;
  14098. this.wireframeLinewidth = 1;
  14099. this.wireframeLinecap = 'round';
  14100. this.wireframeLinejoin = 'round';
  14101. this.flatShading = false;
  14102. this.fog = true;
  14103. this.setValues( parameters );
  14104. }
  14105. copy( source ) {
  14106. super.copy( source );
  14107. this.defines = { 'STANDARD': '' };
  14108. this.color.copy( source.color );
  14109. this.roughness = source.roughness;
  14110. this.metalness = source.metalness;
  14111. this.map = source.map;
  14112. this.lightMap = source.lightMap;
  14113. this.lightMapIntensity = source.lightMapIntensity;
  14114. this.aoMap = source.aoMap;
  14115. this.aoMapIntensity = source.aoMapIntensity;
  14116. this.emissive.copy( source.emissive );
  14117. this.emissiveMap = source.emissiveMap;
  14118. this.emissiveIntensity = source.emissiveIntensity;
  14119. this.bumpMap = source.bumpMap;
  14120. this.bumpScale = source.bumpScale;
  14121. this.normalMap = source.normalMap;
  14122. this.normalMapType = source.normalMapType;
  14123. this.normalScale.copy( source.normalScale );
  14124. this.displacementMap = source.displacementMap;
  14125. this.displacementScale = source.displacementScale;
  14126. this.displacementBias = source.displacementBias;
  14127. this.roughnessMap = source.roughnessMap;
  14128. this.metalnessMap = source.metalnessMap;
  14129. this.alphaMap = source.alphaMap;
  14130. this.envMap = source.envMap;
  14131. this.envMapRotation.copy( source.envMapRotation );
  14132. this.envMapIntensity = source.envMapIntensity;
  14133. this.wireframe = source.wireframe;
  14134. this.wireframeLinewidth = source.wireframeLinewidth;
  14135. this.wireframeLinecap = source.wireframeLinecap;
  14136. this.wireframeLinejoin = source.wireframeLinejoin;
  14137. this.flatShading = source.flatShading;
  14138. this.fog = source.fog;
  14139. return this;
  14140. }
  14141. }
  14142. class MeshPhysicalMaterial extends MeshStandardMaterial {
  14143. static get type() {
  14144. return 'MeshPhysicalMaterial';
  14145. }
  14146. constructor( parameters ) {
  14147. super();
  14148. this.isMeshPhysicalMaterial = true;
  14149. this.defines = {
  14150. 'STANDARD': '',
  14151. 'PHYSICAL': ''
  14152. };
  14153. this.anisotropyRotation = 0;
  14154. this.anisotropyMap = null;
  14155. this.clearcoatMap = null;
  14156. this.clearcoatRoughness = 0.0;
  14157. this.clearcoatRoughnessMap = null;
  14158. this.clearcoatNormalScale = new Vector2( 1, 1 );
  14159. this.clearcoatNormalMap = null;
  14160. this.ior = 1.5;
  14161. Object.defineProperty( this, 'reflectivity', {
  14162. get: function () {
  14163. return ( clamp$1( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  14164. },
  14165. set: function ( reflectivity ) {
  14166. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  14167. }
  14168. } );
  14169. this.iridescenceMap = null;
  14170. this.iridescenceIOR = 1.3;
  14171. this.iridescenceThicknessRange = [ 100, 400 ];
  14172. this.iridescenceThicknessMap = null;
  14173. this.sheenColor = new Color( 0x000000 );
  14174. this.sheenColorMap = null;
  14175. this.sheenRoughness = 1.0;
  14176. this.sheenRoughnessMap = null;
  14177. this.transmissionMap = null;
  14178. this.thickness = 0;
  14179. this.thicknessMap = null;
  14180. this.attenuationDistance = Infinity;
  14181. this.attenuationColor = new Color( 1, 1, 1 );
  14182. this.specularIntensity = 1.0;
  14183. this.specularIntensityMap = null;
  14184. this.specularColor = new Color( 1, 1, 1 );
  14185. this.specularColorMap = null;
  14186. this._anisotropy = 0;
  14187. this._clearcoat = 0;
  14188. this._dispersion = 0;
  14189. this._iridescence = 0;
  14190. this._sheen = 0.0;
  14191. this._transmission = 0;
  14192. this.setValues( parameters );
  14193. }
  14194. get anisotropy() {
  14195. return this._anisotropy;
  14196. }
  14197. set anisotropy( value ) {
  14198. if ( this._anisotropy > 0 !== value > 0 ) {
  14199. this.version ++;
  14200. }
  14201. this._anisotropy = value;
  14202. }
  14203. get clearcoat() {
  14204. return this._clearcoat;
  14205. }
  14206. set clearcoat( value ) {
  14207. if ( this._clearcoat > 0 !== value > 0 ) {
  14208. this.version ++;
  14209. }
  14210. this._clearcoat = value;
  14211. }
  14212. get iridescence() {
  14213. return this._iridescence;
  14214. }
  14215. set iridescence( value ) {
  14216. if ( this._iridescence > 0 !== value > 0 ) {
  14217. this.version ++;
  14218. }
  14219. this._iridescence = value;
  14220. }
  14221. get dispersion() {
  14222. return this._dispersion;
  14223. }
  14224. set dispersion( value ) {
  14225. if ( this._dispersion > 0 !== value > 0 ) {
  14226. this.version ++;
  14227. }
  14228. this._dispersion = value;
  14229. }
  14230. get sheen() {
  14231. return this._sheen;
  14232. }
  14233. set sheen( value ) {
  14234. if ( this._sheen > 0 !== value > 0 ) {
  14235. this.version ++;
  14236. }
  14237. this._sheen = value;
  14238. }
  14239. get transmission() {
  14240. return this._transmission;
  14241. }
  14242. set transmission( value ) {
  14243. if ( this._transmission > 0 !== value > 0 ) {
  14244. this.version ++;
  14245. }
  14246. this._transmission = value;
  14247. }
  14248. copy( source ) {
  14249. super.copy( source );
  14250. this.defines = {
  14251. 'STANDARD': '',
  14252. 'PHYSICAL': ''
  14253. };
  14254. this.anisotropy = source.anisotropy;
  14255. this.anisotropyRotation = source.anisotropyRotation;
  14256. this.anisotropyMap = source.anisotropyMap;
  14257. this.clearcoat = source.clearcoat;
  14258. this.clearcoatMap = source.clearcoatMap;
  14259. this.clearcoatRoughness = source.clearcoatRoughness;
  14260. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  14261. this.clearcoatNormalMap = source.clearcoatNormalMap;
  14262. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  14263. this.dispersion = source.dispersion;
  14264. this.ior = source.ior;
  14265. this.iridescence = source.iridescence;
  14266. this.iridescenceMap = source.iridescenceMap;
  14267. this.iridescenceIOR = source.iridescenceIOR;
  14268. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  14269. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  14270. this.sheen = source.sheen;
  14271. this.sheenColor.copy( source.sheenColor );
  14272. this.sheenColorMap = source.sheenColorMap;
  14273. this.sheenRoughness = source.sheenRoughness;
  14274. this.sheenRoughnessMap = source.sheenRoughnessMap;
  14275. this.transmission = source.transmission;
  14276. this.transmissionMap = source.transmissionMap;
  14277. this.thickness = source.thickness;
  14278. this.thicknessMap = source.thicknessMap;
  14279. this.attenuationDistance = source.attenuationDistance;
  14280. this.attenuationColor.copy( source.attenuationColor );
  14281. this.specularIntensity = source.specularIntensity;
  14282. this.specularIntensityMap = source.specularIntensityMap;
  14283. this.specularColor.copy( source.specularColor );
  14284. this.specularColorMap = source.specularColorMap;
  14285. return this;
  14286. }
  14287. }
  14288. class MeshPhongMaterial extends Material {
  14289. static get type() {
  14290. return 'MeshPhongMaterial';
  14291. }
  14292. constructor( parameters ) {
  14293. super();
  14294. this.isMeshPhongMaterial = true;
  14295. this.color = new Color( 0xffffff ); // diffuse
  14296. this.specular = new Color( 0x111111 );
  14297. this.shininess = 30;
  14298. this.map = null;
  14299. this.lightMap = null;
  14300. this.lightMapIntensity = 1.0;
  14301. this.aoMap = null;
  14302. this.aoMapIntensity = 1.0;
  14303. this.emissive = new Color( 0x000000 );
  14304. this.emissiveIntensity = 1.0;
  14305. this.emissiveMap = null;
  14306. this.bumpMap = null;
  14307. this.bumpScale = 1;
  14308. this.normalMap = null;
  14309. this.normalMapType = TangentSpaceNormalMap;
  14310. this.normalScale = new Vector2( 1, 1 );
  14311. this.displacementMap = null;
  14312. this.displacementScale = 1;
  14313. this.displacementBias = 0;
  14314. this.specularMap = null;
  14315. this.alphaMap = null;
  14316. this.envMap = null;
  14317. this.envMapRotation = new Euler();
  14318. this.combine = MultiplyOperation;
  14319. this.reflectivity = 1;
  14320. this.refractionRatio = 0.98;
  14321. this.wireframe = false;
  14322. this.wireframeLinewidth = 1;
  14323. this.wireframeLinecap = 'round';
  14324. this.wireframeLinejoin = 'round';
  14325. this.flatShading = false;
  14326. this.fog = true;
  14327. this.setValues( parameters );
  14328. }
  14329. copy( source ) {
  14330. super.copy( source );
  14331. this.color.copy( source.color );
  14332. this.specular.copy( source.specular );
  14333. this.shininess = source.shininess;
  14334. this.map = source.map;
  14335. this.lightMap = source.lightMap;
  14336. this.lightMapIntensity = source.lightMapIntensity;
  14337. this.aoMap = source.aoMap;
  14338. this.aoMapIntensity = source.aoMapIntensity;
  14339. this.emissive.copy( source.emissive );
  14340. this.emissiveMap = source.emissiveMap;
  14341. this.emissiveIntensity = source.emissiveIntensity;
  14342. this.bumpMap = source.bumpMap;
  14343. this.bumpScale = source.bumpScale;
  14344. this.normalMap = source.normalMap;
  14345. this.normalMapType = source.normalMapType;
  14346. this.normalScale.copy( source.normalScale );
  14347. this.displacementMap = source.displacementMap;
  14348. this.displacementScale = source.displacementScale;
  14349. this.displacementBias = source.displacementBias;
  14350. this.specularMap = source.specularMap;
  14351. this.alphaMap = source.alphaMap;
  14352. this.envMap = source.envMap;
  14353. this.envMapRotation.copy( source.envMapRotation );
  14354. this.combine = source.combine;
  14355. this.reflectivity = source.reflectivity;
  14356. this.refractionRatio = source.refractionRatio;
  14357. this.wireframe = source.wireframe;
  14358. this.wireframeLinewidth = source.wireframeLinewidth;
  14359. this.wireframeLinecap = source.wireframeLinecap;
  14360. this.wireframeLinejoin = source.wireframeLinejoin;
  14361. this.flatShading = source.flatShading;
  14362. this.fog = source.fog;
  14363. return this;
  14364. }
  14365. }
  14366. class MeshToonMaterial extends Material {
  14367. static get type() {
  14368. return 'MeshToonMaterial';
  14369. }
  14370. constructor( parameters ) {
  14371. super();
  14372. this.isMeshToonMaterial = true;
  14373. this.defines = { 'TOON': '' };
  14374. this.color = new Color( 0xffffff );
  14375. this.map = null;
  14376. this.gradientMap = null;
  14377. this.lightMap = null;
  14378. this.lightMapIntensity = 1.0;
  14379. this.aoMap = null;
  14380. this.aoMapIntensity = 1.0;
  14381. this.emissive = new Color( 0x000000 );
  14382. this.emissiveIntensity = 1.0;
  14383. this.emissiveMap = null;
  14384. this.bumpMap = null;
  14385. this.bumpScale = 1;
  14386. this.normalMap = null;
  14387. this.normalMapType = TangentSpaceNormalMap;
  14388. this.normalScale = new Vector2( 1, 1 );
  14389. this.displacementMap = null;
  14390. this.displacementScale = 1;
  14391. this.displacementBias = 0;
  14392. this.alphaMap = null;
  14393. this.wireframe = false;
  14394. this.wireframeLinewidth = 1;
  14395. this.wireframeLinecap = 'round';
  14396. this.wireframeLinejoin = 'round';
  14397. this.fog = true;
  14398. this.setValues( parameters );
  14399. }
  14400. copy( source ) {
  14401. super.copy( source );
  14402. this.color.copy( source.color );
  14403. this.map = source.map;
  14404. this.gradientMap = source.gradientMap;
  14405. this.lightMap = source.lightMap;
  14406. this.lightMapIntensity = source.lightMapIntensity;
  14407. this.aoMap = source.aoMap;
  14408. this.aoMapIntensity = source.aoMapIntensity;
  14409. this.emissive.copy( source.emissive );
  14410. this.emissiveMap = source.emissiveMap;
  14411. this.emissiveIntensity = source.emissiveIntensity;
  14412. this.bumpMap = source.bumpMap;
  14413. this.bumpScale = source.bumpScale;
  14414. this.normalMap = source.normalMap;
  14415. this.normalMapType = source.normalMapType;
  14416. this.normalScale.copy( source.normalScale );
  14417. this.displacementMap = source.displacementMap;
  14418. this.displacementScale = source.displacementScale;
  14419. this.displacementBias = source.displacementBias;
  14420. this.alphaMap = source.alphaMap;
  14421. this.wireframe = source.wireframe;
  14422. this.wireframeLinewidth = source.wireframeLinewidth;
  14423. this.wireframeLinecap = source.wireframeLinecap;
  14424. this.wireframeLinejoin = source.wireframeLinejoin;
  14425. this.fog = source.fog;
  14426. return this;
  14427. }
  14428. }
  14429. class MeshNormalMaterial extends Material {
  14430. static get type() {
  14431. return 'MeshNormalMaterial';
  14432. }
  14433. constructor( parameters ) {
  14434. super();
  14435. this.isMeshNormalMaterial = true;
  14436. this.bumpMap = null;
  14437. this.bumpScale = 1;
  14438. this.normalMap = null;
  14439. this.normalMapType = TangentSpaceNormalMap;
  14440. this.normalScale = new Vector2( 1, 1 );
  14441. this.displacementMap = null;
  14442. this.displacementScale = 1;
  14443. this.displacementBias = 0;
  14444. this.wireframe = false;
  14445. this.wireframeLinewidth = 1;
  14446. this.flatShading = false;
  14447. this.setValues( parameters );
  14448. }
  14449. copy( source ) {
  14450. super.copy( source );
  14451. this.bumpMap = source.bumpMap;
  14452. this.bumpScale = source.bumpScale;
  14453. this.normalMap = source.normalMap;
  14454. this.normalMapType = source.normalMapType;
  14455. this.normalScale.copy( source.normalScale );
  14456. this.displacementMap = source.displacementMap;
  14457. this.displacementScale = source.displacementScale;
  14458. this.displacementBias = source.displacementBias;
  14459. this.wireframe = source.wireframe;
  14460. this.wireframeLinewidth = source.wireframeLinewidth;
  14461. this.flatShading = source.flatShading;
  14462. return this;
  14463. }
  14464. }
  14465. class MeshLambertMaterial extends Material {
  14466. static get type() {
  14467. return 'MeshLambertMaterial';
  14468. }
  14469. constructor( parameters ) {
  14470. super();
  14471. this.isMeshLambertMaterial = true;
  14472. this.color = new Color( 0xffffff ); // diffuse
  14473. this.map = null;
  14474. this.lightMap = null;
  14475. this.lightMapIntensity = 1.0;
  14476. this.aoMap = null;
  14477. this.aoMapIntensity = 1.0;
  14478. this.emissive = new Color( 0x000000 );
  14479. this.emissiveIntensity = 1.0;
  14480. this.emissiveMap = null;
  14481. this.bumpMap = null;
  14482. this.bumpScale = 1;
  14483. this.normalMap = null;
  14484. this.normalMapType = TangentSpaceNormalMap;
  14485. this.normalScale = new Vector2( 1, 1 );
  14486. this.displacementMap = null;
  14487. this.displacementScale = 1;
  14488. this.displacementBias = 0;
  14489. this.specularMap = null;
  14490. this.alphaMap = null;
  14491. this.envMap = null;
  14492. this.envMapRotation = new Euler();
  14493. this.combine = MultiplyOperation;
  14494. this.reflectivity = 1;
  14495. this.refractionRatio = 0.98;
  14496. this.wireframe = false;
  14497. this.wireframeLinewidth = 1;
  14498. this.wireframeLinecap = 'round';
  14499. this.wireframeLinejoin = 'round';
  14500. this.flatShading = false;
  14501. this.fog = true;
  14502. this.setValues( parameters );
  14503. }
  14504. copy( source ) {
  14505. super.copy( source );
  14506. this.color.copy( source.color );
  14507. this.map = source.map;
  14508. this.lightMap = source.lightMap;
  14509. this.lightMapIntensity = source.lightMapIntensity;
  14510. this.aoMap = source.aoMap;
  14511. this.aoMapIntensity = source.aoMapIntensity;
  14512. this.emissive.copy( source.emissive );
  14513. this.emissiveMap = source.emissiveMap;
  14514. this.emissiveIntensity = source.emissiveIntensity;
  14515. this.bumpMap = source.bumpMap;
  14516. this.bumpScale = source.bumpScale;
  14517. this.normalMap = source.normalMap;
  14518. this.normalMapType = source.normalMapType;
  14519. this.normalScale.copy( source.normalScale );
  14520. this.displacementMap = source.displacementMap;
  14521. this.displacementScale = source.displacementScale;
  14522. this.displacementBias = source.displacementBias;
  14523. this.specularMap = source.specularMap;
  14524. this.alphaMap = source.alphaMap;
  14525. this.envMap = source.envMap;
  14526. this.envMapRotation.copy( source.envMapRotation );
  14527. this.combine = source.combine;
  14528. this.reflectivity = source.reflectivity;
  14529. this.refractionRatio = source.refractionRatio;
  14530. this.wireframe = source.wireframe;
  14531. this.wireframeLinewidth = source.wireframeLinewidth;
  14532. this.wireframeLinecap = source.wireframeLinecap;
  14533. this.wireframeLinejoin = source.wireframeLinejoin;
  14534. this.flatShading = source.flatShading;
  14535. this.fog = source.fog;
  14536. return this;
  14537. }
  14538. }
  14539. class MeshDepthMaterial extends Material {
  14540. static get type() {
  14541. return 'MeshDepthMaterial';
  14542. }
  14543. constructor( parameters ) {
  14544. super();
  14545. this.isMeshDepthMaterial = true;
  14546. this.depthPacking = BasicDepthPacking;
  14547. this.map = null;
  14548. this.alphaMap = null;
  14549. this.displacementMap = null;
  14550. this.displacementScale = 1;
  14551. this.displacementBias = 0;
  14552. this.wireframe = false;
  14553. this.wireframeLinewidth = 1;
  14554. this.setValues( parameters );
  14555. }
  14556. copy( source ) {
  14557. super.copy( source );
  14558. this.depthPacking = source.depthPacking;
  14559. this.map = source.map;
  14560. this.alphaMap = source.alphaMap;
  14561. this.displacementMap = source.displacementMap;
  14562. this.displacementScale = source.displacementScale;
  14563. this.displacementBias = source.displacementBias;
  14564. this.wireframe = source.wireframe;
  14565. this.wireframeLinewidth = source.wireframeLinewidth;
  14566. return this;
  14567. }
  14568. }
  14569. class MeshDistanceMaterial extends Material {
  14570. static get type() {
  14571. return 'MeshDistanceMaterial';
  14572. }
  14573. constructor( parameters ) {
  14574. super();
  14575. this.isMeshDistanceMaterial = true;
  14576. this.map = null;
  14577. this.alphaMap = null;
  14578. this.displacementMap = null;
  14579. this.displacementScale = 1;
  14580. this.displacementBias = 0;
  14581. this.setValues( parameters );
  14582. }
  14583. copy( source ) {
  14584. super.copy( source );
  14585. this.map = source.map;
  14586. this.alphaMap = source.alphaMap;
  14587. this.displacementMap = source.displacementMap;
  14588. this.displacementScale = source.displacementScale;
  14589. this.displacementBias = source.displacementBias;
  14590. return this;
  14591. }
  14592. }
  14593. class MeshMatcapMaterial extends Material {
  14594. static get type() {
  14595. return 'MeshMatcapMaterial';
  14596. }
  14597. constructor( parameters ) {
  14598. super();
  14599. this.isMeshMatcapMaterial = true;
  14600. this.defines = { 'MATCAP': '' };
  14601. this.color = new Color( 0xffffff ); // diffuse
  14602. this.matcap = null;
  14603. this.map = null;
  14604. this.bumpMap = null;
  14605. this.bumpScale = 1;
  14606. this.normalMap = null;
  14607. this.normalMapType = TangentSpaceNormalMap;
  14608. this.normalScale = new Vector2( 1, 1 );
  14609. this.displacementMap = null;
  14610. this.displacementScale = 1;
  14611. this.displacementBias = 0;
  14612. this.alphaMap = null;
  14613. this.flatShading = false;
  14614. this.fog = true;
  14615. this.setValues( parameters );
  14616. }
  14617. copy( source ) {
  14618. super.copy( source );
  14619. this.defines = { 'MATCAP': '' };
  14620. this.color.copy( source.color );
  14621. this.matcap = source.matcap;
  14622. this.map = source.map;
  14623. this.bumpMap = source.bumpMap;
  14624. this.bumpScale = source.bumpScale;
  14625. this.normalMap = source.normalMap;
  14626. this.normalMapType = source.normalMapType;
  14627. this.normalScale.copy( source.normalScale );
  14628. this.displacementMap = source.displacementMap;
  14629. this.displacementScale = source.displacementScale;
  14630. this.displacementBias = source.displacementBias;
  14631. this.alphaMap = source.alphaMap;
  14632. this.flatShading = source.flatShading;
  14633. this.fog = source.fog;
  14634. return this;
  14635. }
  14636. }
  14637. class LineDashedMaterial extends LineBasicMaterial {
  14638. static get type() {
  14639. return 'LineDashedMaterial';
  14640. }
  14641. constructor( parameters ) {
  14642. super();
  14643. this.isLineDashedMaterial = true;
  14644. this.scale = 1;
  14645. this.dashSize = 3;
  14646. this.gapSize = 1;
  14647. this.setValues( parameters );
  14648. }
  14649. copy( source ) {
  14650. super.copy( source );
  14651. this.scale = source.scale;
  14652. this.dashSize = source.dashSize;
  14653. this.gapSize = source.gapSize;
  14654. return this;
  14655. }
  14656. }
  14657. // converts an array to a specific type
  14658. function convertArray( array, type, forceClone ) {
  14659. if ( ! array || // let 'undefined' and 'null' pass
  14660. ! forceClone && array.constructor === type ) return array;
  14661. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  14662. return new type( array ); // create typed array
  14663. }
  14664. return Array.prototype.slice.call( array ); // create Array
  14665. }
  14666. function isTypedArray( object ) {
  14667. return ArrayBuffer.isView( object ) &&
  14668. ! ( object instanceof DataView );
  14669. }
  14670. // returns an array by which times and values can be sorted
  14671. function getKeyframeOrder( times ) {
  14672. function compareTime( i, j ) {
  14673. return times[ i ] - times[ j ];
  14674. }
  14675. const n = times.length;
  14676. const result = new Array( n );
  14677. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  14678. result.sort( compareTime );
  14679. return result;
  14680. }
  14681. // uses the array previously returned by 'getKeyframeOrder' to sort data
  14682. function sortedArray( values, stride, order ) {
  14683. const nValues = values.length;
  14684. const result = new values.constructor( nValues );
  14685. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  14686. const srcOffset = order[ i ] * stride;
  14687. for ( let j = 0; j !== stride; ++ j ) {
  14688. result[ dstOffset ++ ] = values[ srcOffset + j ];
  14689. }
  14690. }
  14691. return result;
  14692. }
  14693. // function for parsing AOS keyframe formats
  14694. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  14695. let i = 1, key = jsonKeys[ 0 ];
  14696. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  14697. key = jsonKeys[ i ++ ];
  14698. }
  14699. if ( key === undefined ) return; // no data
  14700. let value = key[ valuePropertyName ];
  14701. if ( value === undefined ) return; // no data
  14702. if ( Array.isArray( value ) ) {
  14703. do {
  14704. value = key[ valuePropertyName ];
  14705. if ( value !== undefined ) {
  14706. times.push( key.time );
  14707. values.push.apply( values, value ); // push all elements
  14708. }
  14709. key = jsonKeys[ i ++ ];
  14710. } while ( key !== undefined );
  14711. } else if ( value.toArray !== undefined ) {
  14712. // ...assume THREE.Math-ish
  14713. do {
  14714. value = key[ valuePropertyName ];
  14715. if ( value !== undefined ) {
  14716. times.push( key.time );
  14717. value.toArray( values, values.length );
  14718. }
  14719. key = jsonKeys[ i ++ ];
  14720. } while ( key !== undefined );
  14721. } else {
  14722. // otherwise push as-is
  14723. do {
  14724. value = key[ valuePropertyName ];
  14725. if ( value !== undefined ) {
  14726. times.push( key.time );
  14727. values.push( value );
  14728. }
  14729. key = jsonKeys[ i ++ ];
  14730. } while ( key !== undefined );
  14731. }
  14732. }
  14733. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  14734. const clip = sourceClip.clone();
  14735. clip.name = name;
  14736. const tracks = [];
  14737. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14738. const track = clip.tracks[ i ];
  14739. const valueSize = track.getValueSize();
  14740. const times = [];
  14741. const values = [];
  14742. for ( let j = 0; j < track.times.length; ++ j ) {
  14743. const frame = track.times[ j ] * fps;
  14744. if ( frame < startFrame || frame >= endFrame ) continue;
  14745. times.push( track.times[ j ] );
  14746. for ( let k = 0; k < valueSize; ++ k ) {
  14747. values.push( track.values[ j * valueSize + k ] );
  14748. }
  14749. }
  14750. if ( times.length === 0 ) continue;
  14751. track.times = convertArray( times, track.times.constructor );
  14752. track.values = convertArray( values, track.values.constructor );
  14753. tracks.push( track );
  14754. }
  14755. clip.tracks = tracks;
  14756. // find minimum .times value across all tracks in the trimmed clip
  14757. let minStartTime = Infinity;
  14758. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14759. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  14760. minStartTime = clip.tracks[ i ].times[ 0 ];
  14761. }
  14762. }
  14763. // shift all tracks such that clip begins at t=0
  14764. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14765. clip.tracks[ i ].shift( - 1 * minStartTime );
  14766. }
  14767. clip.resetDuration();
  14768. return clip;
  14769. }
  14770. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  14771. if ( fps <= 0 ) fps = 30;
  14772. const numTracks = referenceClip.tracks.length;
  14773. const referenceTime = referenceFrame / fps;
  14774. // Make each track's values relative to the values at the reference frame
  14775. for ( let i = 0; i < numTracks; ++ i ) {
  14776. const referenceTrack = referenceClip.tracks[ i ];
  14777. const referenceTrackType = referenceTrack.ValueTypeName;
  14778. // Skip this track if it's non-numeric
  14779. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  14780. // Find the track in the target clip whose name and type matches the reference track
  14781. const targetTrack = targetClip.tracks.find( function ( track ) {
  14782. return track.name === referenceTrack.name
  14783. && track.ValueTypeName === referenceTrackType;
  14784. } );
  14785. if ( targetTrack === undefined ) continue;
  14786. let referenceOffset = 0;
  14787. const referenceValueSize = referenceTrack.getValueSize();
  14788. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14789. referenceOffset = referenceValueSize / 3;
  14790. }
  14791. let targetOffset = 0;
  14792. const targetValueSize = targetTrack.getValueSize();
  14793. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14794. targetOffset = targetValueSize / 3;
  14795. }
  14796. const lastIndex = referenceTrack.times.length - 1;
  14797. let referenceValue;
  14798. // Find the value to subtract out of the track
  14799. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  14800. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  14801. const startIndex = referenceOffset;
  14802. const endIndex = referenceValueSize - referenceOffset;
  14803. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14804. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  14805. // Reference frame is after the last keyframe, so just use the last keyframe
  14806. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  14807. const endIndex = startIndex + referenceValueSize - referenceOffset;
  14808. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14809. } else {
  14810. // Interpolate to the reference value
  14811. const interpolant = referenceTrack.createInterpolant();
  14812. const startIndex = referenceOffset;
  14813. const endIndex = referenceValueSize - referenceOffset;
  14814. interpolant.evaluate( referenceTime );
  14815. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  14816. }
  14817. // Conjugate the quaternion
  14818. if ( referenceTrackType === 'quaternion' ) {
  14819. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  14820. referenceQuat.toArray( referenceValue );
  14821. }
  14822. // Subtract the reference value from all of the track values
  14823. const numTimes = targetTrack.times.length;
  14824. for ( let j = 0; j < numTimes; ++ j ) {
  14825. const valueStart = j * targetValueSize + targetOffset;
  14826. if ( referenceTrackType === 'quaternion' ) {
  14827. // Multiply the conjugate for quaternion track types
  14828. Quaternion.multiplyQuaternionsFlat(
  14829. targetTrack.values,
  14830. valueStart,
  14831. referenceValue,
  14832. 0,
  14833. targetTrack.values,
  14834. valueStart
  14835. );
  14836. } else {
  14837. const valueEnd = targetValueSize - targetOffset * 2;
  14838. // Subtract each value for all other numeric track types
  14839. for ( let k = 0; k < valueEnd; ++ k ) {
  14840. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  14841. }
  14842. }
  14843. }
  14844. }
  14845. targetClip.blendMode = AdditiveAnimationBlendMode;
  14846. return targetClip;
  14847. }
  14848. const AnimationUtils = {
  14849. convertArray: convertArray,
  14850. isTypedArray: isTypedArray,
  14851. getKeyframeOrder: getKeyframeOrder,
  14852. sortedArray: sortedArray,
  14853. flattenJSON: flattenJSON,
  14854. subclip: subclip,
  14855. makeClipAdditive: makeClipAdditive
  14856. };
  14857. /**
  14858. * Abstract base class of interpolants over parametric samples.
  14859. *
  14860. * The parameter domain is one dimensional, typically the time or a path
  14861. * along a curve defined by the data.
  14862. *
  14863. * The sample values can have any dimensionality and derived classes may
  14864. * apply special interpretations to the data.
  14865. *
  14866. * This class provides the interval seek in a Template Method, deferring
  14867. * the actual interpolation to derived classes.
  14868. *
  14869. * Time complexity is O(1) for linear access crossing at most two points
  14870. * and O(log N) for random access, where N is the number of positions.
  14871. *
  14872. * References:
  14873. *
  14874. * http://www.oodesign.com/template-method-pattern.html
  14875. *
  14876. */
  14877. class Interpolant {
  14878. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14879. this.parameterPositions = parameterPositions;
  14880. this._cachedIndex = 0;
  14881. this.resultBuffer = resultBuffer !== undefined ?
  14882. resultBuffer : new sampleValues.constructor( sampleSize );
  14883. this.sampleValues = sampleValues;
  14884. this.valueSize = sampleSize;
  14885. this.settings = null;
  14886. this.DefaultSettings_ = {};
  14887. }
  14888. evaluate( t ) {
  14889. const pp = this.parameterPositions;
  14890. let i1 = this._cachedIndex,
  14891. t1 = pp[ i1 ],
  14892. t0 = pp[ i1 - 1 ];
  14893. validate_interval: {
  14894. seek: {
  14895. let right;
  14896. linear_scan: {
  14897. //- See http://jsperf.com/comparison-to-undefined/3
  14898. //- slower code:
  14899. //-
  14900. //- if ( t >= t1 || t1 === undefined ) {
  14901. forward_scan: if ( ! ( t < t1 ) ) {
  14902. for ( let giveUpAt = i1 + 2; ; ) {
  14903. if ( t1 === undefined ) {
  14904. if ( t < t0 ) break forward_scan;
  14905. // after end
  14906. i1 = pp.length;
  14907. this._cachedIndex = i1;
  14908. return this.copySampleValue_( i1 - 1 );
  14909. }
  14910. if ( i1 === giveUpAt ) break; // this loop
  14911. t0 = t1;
  14912. t1 = pp[ ++ i1 ];
  14913. if ( t < t1 ) {
  14914. // we have arrived at the sought interval
  14915. break seek;
  14916. }
  14917. }
  14918. // prepare binary search on the right side of the index
  14919. right = pp.length;
  14920. break linear_scan;
  14921. }
  14922. //- slower code:
  14923. //- if ( t < t0 || t0 === undefined ) {
  14924. if ( ! ( t >= t0 ) ) {
  14925. // looping?
  14926. const t1global = pp[ 1 ];
  14927. if ( t < t1global ) {
  14928. i1 = 2; // + 1, using the scan for the details
  14929. t0 = t1global;
  14930. }
  14931. // linear reverse scan
  14932. for ( let giveUpAt = i1 - 2; ; ) {
  14933. if ( t0 === undefined ) {
  14934. // before start
  14935. this._cachedIndex = 0;
  14936. return this.copySampleValue_( 0 );
  14937. }
  14938. if ( i1 === giveUpAt ) break; // this loop
  14939. t1 = t0;
  14940. t0 = pp[ -- i1 - 1 ];
  14941. if ( t >= t0 ) {
  14942. // we have arrived at the sought interval
  14943. break seek;
  14944. }
  14945. }
  14946. // prepare binary search on the left side of the index
  14947. right = i1;
  14948. i1 = 0;
  14949. break linear_scan;
  14950. }
  14951. // the interval is valid
  14952. break validate_interval;
  14953. } // linear scan
  14954. // binary search
  14955. while ( i1 < right ) {
  14956. const mid = ( i1 + right ) >>> 1;
  14957. if ( t < pp[ mid ] ) {
  14958. right = mid;
  14959. } else {
  14960. i1 = mid + 1;
  14961. }
  14962. }
  14963. t1 = pp[ i1 ];
  14964. t0 = pp[ i1 - 1 ];
  14965. // check boundary cases, again
  14966. if ( t0 === undefined ) {
  14967. this._cachedIndex = 0;
  14968. return this.copySampleValue_( 0 );
  14969. }
  14970. if ( t1 === undefined ) {
  14971. i1 = pp.length;
  14972. this._cachedIndex = i1;
  14973. return this.copySampleValue_( i1 - 1 );
  14974. }
  14975. } // seek
  14976. this._cachedIndex = i1;
  14977. this.intervalChanged_( i1, t0, t1 );
  14978. } // validate_interval
  14979. return this.interpolate_( i1, t0, t, t1 );
  14980. }
  14981. getSettings_() {
  14982. return this.settings || this.DefaultSettings_;
  14983. }
  14984. copySampleValue_( index ) {
  14985. // copies a sample value to the result buffer
  14986. const result = this.resultBuffer,
  14987. values = this.sampleValues,
  14988. stride = this.valueSize,
  14989. offset = index * stride;
  14990. for ( let i = 0; i !== stride; ++ i ) {
  14991. result[ i ] = values[ offset + i ];
  14992. }
  14993. return result;
  14994. }
  14995. // Template methods for derived classes:
  14996. interpolate_( /* i1, t0, t, t1 */ ) {
  14997. throw new Error( 'call to abstract method' );
  14998. // implementations shall return this.resultBuffer
  14999. }
  15000. intervalChanged_( /* i1, t0, t1 */ ) {
  15001. // empty
  15002. }
  15003. }
  15004. /**
  15005. * Fast and simple cubic spline interpolant.
  15006. *
  15007. * It was derived from a Hermitian construction setting the first derivative
  15008. * at each sample position to the linear slope between neighboring positions
  15009. * over their parameter interval.
  15010. */
  15011. class CubicInterpolant extends Interpolant {
  15012. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15013. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15014. this._weightPrev = - 0;
  15015. this._offsetPrev = - 0;
  15016. this._weightNext = - 0;
  15017. this._offsetNext = - 0;
  15018. this.DefaultSettings_ = {
  15019. endingStart: ZeroCurvatureEnding,
  15020. endingEnd: ZeroCurvatureEnding
  15021. };
  15022. }
  15023. intervalChanged_( i1, t0, t1 ) {
  15024. const pp = this.parameterPositions;
  15025. let iPrev = i1 - 2,
  15026. iNext = i1 + 1,
  15027. tPrev = pp[ iPrev ],
  15028. tNext = pp[ iNext ];
  15029. if ( tPrev === undefined ) {
  15030. switch ( this.getSettings_().endingStart ) {
  15031. case ZeroSlopeEnding:
  15032. // f'(t0) = 0
  15033. iPrev = i1;
  15034. tPrev = 2 * t0 - t1;
  15035. break;
  15036. case WrapAroundEnding:
  15037. // use the other end of the curve
  15038. iPrev = pp.length - 2;
  15039. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  15040. break;
  15041. default: // ZeroCurvatureEnding
  15042. // f''(t0) = 0 a.k.a. Natural Spline
  15043. iPrev = i1;
  15044. tPrev = t1;
  15045. }
  15046. }
  15047. if ( tNext === undefined ) {
  15048. switch ( this.getSettings_().endingEnd ) {
  15049. case ZeroSlopeEnding:
  15050. // f'(tN) = 0
  15051. iNext = i1;
  15052. tNext = 2 * t1 - t0;
  15053. break;
  15054. case WrapAroundEnding:
  15055. // use the other end of the curve
  15056. iNext = 1;
  15057. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  15058. break;
  15059. default: // ZeroCurvatureEnding
  15060. // f''(tN) = 0, a.k.a. Natural Spline
  15061. iNext = i1 - 1;
  15062. tNext = t0;
  15063. }
  15064. }
  15065. const halfDt = ( t1 - t0 ) * 0.5,
  15066. stride = this.valueSize;
  15067. this._weightPrev = halfDt / ( t0 - tPrev );
  15068. this._weightNext = halfDt / ( tNext - t1 );
  15069. this._offsetPrev = iPrev * stride;
  15070. this._offsetNext = iNext * stride;
  15071. }
  15072. interpolate_( i1, t0, t, t1 ) {
  15073. const result = this.resultBuffer,
  15074. values = this.sampleValues,
  15075. stride = this.valueSize,
  15076. o1 = i1 * stride, o0 = o1 - stride,
  15077. oP = this._offsetPrev, oN = this._offsetNext,
  15078. wP = this._weightPrev, wN = this._weightNext,
  15079. p = ( t - t0 ) / ( t1 - t0 ),
  15080. pp = p * p,
  15081. ppp = pp * p;
  15082. // evaluate polynomials
  15083. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  15084. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  15085. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  15086. const sN = wN * ppp - wN * pp;
  15087. // combine data linearly
  15088. for ( let i = 0; i !== stride; ++ i ) {
  15089. result[ i ] =
  15090. sP * values[ oP + i ] +
  15091. s0 * values[ o0 + i ] +
  15092. s1 * values[ o1 + i ] +
  15093. sN * values[ oN + i ];
  15094. }
  15095. return result;
  15096. }
  15097. }
  15098. class LinearInterpolant extends Interpolant {
  15099. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15100. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15101. }
  15102. interpolate_( i1, t0, t, t1 ) {
  15103. const result = this.resultBuffer,
  15104. values = this.sampleValues,
  15105. stride = this.valueSize,
  15106. offset1 = i1 * stride,
  15107. offset0 = offset1 - stride,
  15108. weight1 = ( t - t0 ) / ( t1 - t0 ),
  15109. weight0 = 1 - weight1;
  15110. for ( let i = 0; i !== stride; ++ i ) {
  15111. result[ i ] =
  15112. values[ offset0 + i ] * weight0 +
  15113. values[ offset1 + i ] * weight1;
  15114. }
  15115. return result;
  15116. }
  15117. }
  15118. /**
  15119. *
  15120. * Interpolant that evaluates to the sample value at the position preceding
  15121. * the parameter.
  15122. */
  15123. class DiscreteInterpolant extends Interpolant {
  15124. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15125. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15126. }
  15127. interpolate_( i1 /*, t0, t, t1 */ ) {
  15128. return this.copySampleValue_( i1 - 1 );
  15129. }
  15130. }
  15131. class KeyframeTrack {
  15132. constructor( name, times, values, interpolation ) {
  15133. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  15134. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  15135. this.name = name;
  15136. this.times = convertArray( times, this.TimeBufferType );
  15137. this.values = convertArray( values, this.ValueBufferType );
  15138. this.setInterpolation( interpolation || this.DefaultInterpolation );
  15139. }
  15140. // Serialization (in static context, because of constructor invocation
  15141. // and automatic invocation of .toJSON):
  15142. static toJSON( track ) {
  15143. const trackType = track.constructor;
  15144. let json;
  15145. // derived classes can define a static toJSON method
  15146. if ( trackType.toJSON !== this.toJSON ) {
  15147. json = trackType.toJSON( track );
  15148. } else {
  15149. // by default, we assume the data can be serialized as-is
  15150. json = {
  15151. 'name': track.name,
  15152. 'times': convertArray( track.times, Array ),
  15153. 'values': convertArray( track.values, Array )
  15154. };
  15155. const interpolation = track.getInterpolation();
  15156. if ( interpolation !== track.DefaultInterpolation ) {
  15157. json.interpolation = interpolation;
  15158. }
  15159. }
  15160. json.type = track.ValueTypeName; // mandatory
  15161. return json;
  15162. }
  15163. InterpolantFactoryMethodDiscrete( result ) {
  15164. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  15165. }
  15166. InterpolantFactoryMethodLinear( result ) {
  15167. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15168. }
  15169. InterpolantFactoryMethodSmooth( result ) {
  15170. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  15171. }
  15172. setInterpolation( interpolation ) {
  15173. let factoryMethod;
  15174. switch ( interpolation ) {
  15175. case InterpolateDiscrete:
  15176. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  15177. break;
  15178. case InterpolateLinear:
  15179. factoryMethod = this.InterpolantFactoryMethodLinear;
  15180. break;
  15181. case InterpolateSmooth:
  15182. factoryMethod = this.InterpolantFactoryMethodSmooth;
  15183. break;
  15184. }
  15185. if ( factoryMethod === undefined ) {
  15186. const message = 'unsupported interpolation for ' +
  15187. this.ValueTypeName + ' keyframe track named ' + this.name;
  15188. if ( this.createInterpolant === undefined ) {
  15189. // fall back to default, unless the default itself is messed up
  15190. if ( interpolation !== this.DefaultInterpolation ) {
  15191. this.setInterpolation( this.DefaultInterpolation );
  15192. } else {
  15193. throw new Error( message ); // fatal, in this case
  15194. }
  15195. }
  15196. console.warn( 'THREE.KeyframeTrack:', message );
  15197. return this;
  15198. }
  15199. this.createInterpolant = factoryMethod;
  15200. return this;
  15201. }
  15202. getInterpolation() {
  15203. switch ( this.createInterpolant ) {
  15204. case this.InterpolantFactoryMethodDiscrete:
  15205. return InterpolateDiscrete;
  15206. case this.InterpolantFactoryMethodLinear:
  15207. return InterpolateLinear;
  15208. case this.InterpolantFactoryMethodSmooth:
  15209. return InterpolateSmooth;
  15210. }
  15211. }
  15212. getValueSize() {
  15213. return this.values.length / this.times.length;
  15214. }
  15215. // move all keyframes either forwards or backwards in time
  15216. shift( timeOffset ) {
  15217. if ( timeOffset !== 0.0 ) {
  15218. const times = this.times;
  15219. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  15220. times[ i ] += timeOffset;
  15221. }
  15222. }
  15223. return this;
  15224. }
  15225. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  15226. scale( timeScale ) {
  15227. if ( timeScale !== 1.0 ) {
  15228. const times = this.times;
  15229. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  15230. times[ i ] *= timeScale;
  15231. }
  15232. }
  15233. return this;
  15234. }
  15235. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  15236. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  15237. trim( startTime, endTime ) {
  15238. const times = this.times,
  15239. nKeys = times.length;
  15240. let from = 0,
  15241. to = nKeys - 1;
  15242. while ( from !== nKeys && times[ from ] < startTime ) {
  15243. ++ from;
  15244. }
  15245. while ( to !== - 1 && times[ to ] > endTime ) {
  15246. -- to;
  15247. }
  15248. ++ to; // inclusive -> exclusive bound
  15249. if ( from !== 0 || to !== nKeys ) {
  15250. // empty tracks are forbidden, so keep at least one keyframe
  15251. if ( from >= to ) {
  15252. to = Math.max( to, 1 );
  15253. from = to - 1;
  15254. }
  15255. const stride = this.getValueSize();
  15256. this.times = times.slice( from, to );
  15257. this.values = this.values.slice( from * stride, to * stride );
  15258. }
  15259. return this;
  15260. }
  15261. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  15262. validate() {
  15263. let valid = true;
  15264. const valueSize = this.getValueSize();
  15265. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  15266. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  15267. valid = false;
  15268. }
  15269. const times = this.times,
  15270. values = this.values,
  15271. nKeys = times.length;
  15272. if ( nKeys === 0 ) {
  15273. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  15274. valid = false;
  15275. }
  15276. let prevTime = null;
  15277. for ( let i = 0; i !== nKeys; i ++ ) {
  15278. const currTime = times[ i ];
  15279. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15280. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  15281. valid = false;
  15282. break;
  15283. }
  15284. if ( prevTime !== null && prevTime > currTime ) {
  15285. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  15286. valid = false;
  15287. break;
  15288. }
  15289. prevTime = currTime;
  15290. }
  15291. if ( values !== undefined ) {
  15292. if ( isTypedArray( values ) ) {
  15293. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  15294. const value = values[ i ];
  15295. if ( isNaN( value ) ) {
  15296. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  15297. valid = false;
  15298. break;
  15299. }
  15300. }
  15301. }
  15302. }
  15303. return valid;
  15304. }
  15305. // removes equivalent sequential keys as common in morph target sequences
  15306. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15307. optimize() {
  15308. // times or values may be shared with other tracks, so overwriting is unsafe
  15309. const times = this.times.slice(),
  15310. values = this.values.slice(),
  15311. stride = this.getValueSize(),
  15312. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15313. lastIndex = times.length - 1;
  15314. let writeIndex = 1;
  15315. for ( let i = 1; i < lastIndex; ++ i ) {
  15316. let keep = false;
  15317. const time = times[ i ];
  15318. const timeNext = times[ i + 1 ];
  15319. // remove adjacent keyframes scheduled at the same time
  15320. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  15321. if ( ! smoothInterpolation ) {
  15322. // remove unnecessary keyframes same as their neighbors
  15323. const offset = i * stride,
  15324. offsetP = offset - stride,
  15325. offsetN = offset + stride;
  15326. for ( let j = 0; j !== stride; ++ j ) {
  15327. const value = values[ offset + j ];
  15328. if ( value !== values[ offsetP + j ] ||
  15329. value !== values[ offsetN + j ] ) {
  15330. keep = true;
  15331. break;
  15332. }
  15333. }
  15334. } else {
  15335. keep = true;
  15336. }
  15337. }
  15338. // in-place compaction
  15339. if ( keep ) {
  15340. if ( i !== writeIndex ) {
  15341. times[ writeIndex ] = times[ i ];
  15342. const readOffset = i * stride,
  15343. writeOffset = writeIndex * stride;
  15344. for ( let j = 0; j !== stride; ++ j ) {
  15345. values[ writeOffset + j ] = values[ readOffset + j ];
  15346. }
  15347. }
  15348. ++ writeIndex;
  15349. }
  15350. }
  15351. // flush last keyframe (compaction looks ahead)
  15352. if ( lastIndex > 0 ) {
  15353. times[ writeIndex ] = times[ lastIndex ];
  15354. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  15355. values[ writeOffset + j ] = values[ readOffset + j ];
  15356. }
  15357. ++ writeIndex;
  15358. }
  15359. if ( writeIndex !== times.length ) {
  15360. this.times = times.slice( 0, writeIndex );
  15361. this.values = values.slice( 0, writeIndex * stride );
  15362. } else {
  15363. this.times = times;
  15364. this.values = values;
  15365. }
  15366. return this;
  15367. }
  15368. clone() {
  15369. const times = this.times.slice();
  15370. const values = this.values.slice();
  15371. const TypedKeyframeTrack = this.constructor;
  15372. const track = new TypedKeyframeTrack( this.name, times, values );
  15373. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  15374. track.createInterpolant = this.createInterpolant;
  15375. return track;
  15376. }
  15377. }
  15378. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  15379. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  15380. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  15381. /**
  15382. * A Track of Boolean keyframe values.
  15383. */
  15384. class BooleanKeyframeTrack extends KeyframeTrack {
  15385. // No interpolation parameter because only InterpolateDiscrete is valid.
  15386. constructor( name, times, values ) {
  15387. super( name, times, values );
  15388. }
  15389. }
  15390. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  15391. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  15392. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15393. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15394. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15395. /**
  15396. * A Track of keyframe values that represent color.
  15397. */
  15398. class ColorKeyframeTrack extends KeyframeTrack {}
  15399. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  15400. /**
  15401. * A Track of numeric keyframe values.
  15402. */
  15403. class NumberKeyframeTrack extends KeyframeTrack {}
  15404. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  15405. /**
  15406. * Spherical linear unit quaternion interpolant.
  15407. */
  15408. class QuaternionLinearInterpolant extends Interpolant {
  15409. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15410. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15411. }
  15412. interpolate_( i1, t0, t, t1 ) {
  15413. const result = this.resultBuffer,
  15414. values = this.sampleValues,
  15415. stride = this.valueSize,
  15416. alpha = ( t - t0 ) / ( t1 - t0 );
  15417. let offset = i1 * stride;
  15418. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  15419. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  15420. }
  15421. return result;
  15422. }
  15423. }
  15424. /**
  15425. * A Track of quaternion keyframe values.
  15426. */
  15427. class QuaternionKeyframeTrack extends KeyframeTrack {
  15428. InterpolantFactoryMethodLinear( result ) {
  15429. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15430. }
  15431. }
  15432. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  15433. // ValueBufferType is inherited
  15434. // DefaultInterpolation is inherited;
  15435. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15436. /**
  15437. * A Track that interpolates Strings
  15438. */
  15439. class StringKeyframeTrack extends KeyframeTrack {
  15440. // No interpolation parameter because only InterpolateDiscrete is valid.
  15441. constructor( name, times, values ) {
  15442. super( name, times, values );
  15443. }
  15444. }
  15445. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  15446. StringKeyframeTrack.prototype.ValueBufferType = Array;
  15447. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15448. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15449. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15450. /**
  15451. * A Track of vectored keyframe values.
  15452. */
  15453. class VectorKeyframeTrack extends KeyframeTrack {}
  15454. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  15455. class AnimationClip {
  15456. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  15457. this.name = name;
  15458. this.tracks = tracks;
  15459. this.duration = duration;
  15460. this.blendMode = blendMode;
  15461. this.uuid = generateUUID();
  15462. // this means it should figure out its duration by scanning the tracks
  15463. if ( this.duration < 0 ) {
  15464. this.resetDuration();
  15465. }
  15466. }
  15467. static parse( json ) {
  15468. const tracks = [],
  15469. jsonTracks = json.tracks,
  15470. frameTime = 1.0 / ( json.fps || 1.0 );
  15471. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15472. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  15473. }
  15474. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  15475. clip.uuid = json.uuid;
  15476. return clip;
  15477. }
  15478. static toJSON( clip ) {
  15479. const tracks = [],
  15480. clipTracks = clip.tracks;
  15481. const json = {
  15482. 'name': clip.name,
  15483. 'duration': clip.duration,
  15484. 'tracks': tracks,
  15485. 'uuid': clip.uuid,
  15486. 'blendMode': clip.blendMode
  15487. };
  15488. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15489. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15490. }
  15491. return json;
  15492. }
  15493. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  15494. const numMorphTargets = morphTargetSequence.length;
  15495. const tracks = [];
  15496. for ( let i = 0; i < numMorphTargets; i ++ ) {
  15497. let times = [];
  15498. let values = [];
  15499. times.push(
  15500. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15501. i,
  15502. ( i + 1 ) % numMorphTargets );
  15503. values.push( 0, 1, 0 );
  15504. const order = getKeyframeOrder( times );
  15505. times = sortedArray( times, 1, order );
  15506. values = sortedArray( values, 1, order );
  15507. // if there is a key at the first frame, duplicate it as the
  15508. // last frame as well for perfect loop.
  15509. if ( ! noLoop && times[ 0 ] === 0 ) {
  15510. times.push( numMorphTargets );
  15511. values.push( values[ 0 ] );
  15512. }
  15513. tracks.push(
  15514. new NumberKeyframeTrack(
  15515. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15516. times, values
  15517. ).scale( 1.0 / fps ) );
  15518. }
  15519. return new this( name, - 1, tracks );
  15520. }
  15521. static findByName( objectOrClipArray, name ) {
  15522. let clipArray = objectOrClipArray;
  15523. if ( ! Array.isArray( objectOrClipArray ) ) {
  15524. const o = objectOrClipArray;
  15525. clipArray = o.geometry && o.geometry.animations || o.animations;
  15526. }
  15527. for ( let i = 0; i < clipArray.length; i ++ ) {
  15528. if ( clipArray[ i ].name === name ) {
  15529. return clipArray[ i ];
  15530. }
  15531. }
  15532. return null;
  15533. }
  15534. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  15535. const animationToMorphTargets = {};
  15536. // tested with https://regex101.com/ on trick sequences
  15537. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  15538. const pattern = /^([\w-]*?)([\d]+)$/;
  15539. // sort morph target names into animation groups based
  15540. // patterns like Walk_001, Walk_002, Run_001, Run_002
  15541. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  15542. const morphTarget = morphTargets[ i ];
  15543. const parts = morphTarget.name.match( pattern );
  15544. if ( parts && parts.length > 1 ) {
  15545. const name = parts[ 1 ];
  15546. let animationMorphTargets = animationToMorphTargets[ name ];
  15547. if ( ! animationMorphTargets ) {
  15548. animationToMorphTargets[ name ] = animationMorphTargets = [];
  15549. }
  15550. animationMorphTargets.push( morphTarget );
  15551. }
  15552. }
  15553. const clips = [];
  15554. for ( const name in animationToMorphTargets ) {
  15555. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  15556. }
  15557. return clips;
  15558. }
  15559. // parse the animation.hierarchy format
  15560. static parseAnimation( animation, bones ) {
  15561. if ( ! animation ) {
  15562. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  15563. return null;
  15564. }
  15565. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  15566. // only return track if there are actually keys.
  15567. if ( animationKeys.length !== 0 ) {
  15568. const times = [];
  15569. const values = [];
  15570. flattenJSON( animationKeys, times, values, propertyName );
  15571. // empty keys are filtered out, so check again
  15572. if ( times.length !== 0 ) {
  15573. destTracks.push( new trackType( trackName, times, values ) );
  15574. }
  15575. }
  15576. };
  15577. const tracks = [];
  15578. const clipName = animation.name || 'default';
  15579. const fps = animation.fps || 30;
  15580. const blendMode = animation.blendMode;
  15581. // automatic length determination in AnimationClip.
  15582. let duration = animation.length || - 1;
  15583. const hierarchyTracks = animation.hierarchy || [];
  15584. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  15585. const animationKeys = hierarchyTracks[ h ].keys;
  15586. // skip empty tracks
  15587. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  15588. // process morph targets
  15589. if ( animationKeys[ 0 ].morphTargets ) {
  15590. // figure out all morph targets used in this track
  15591. const morphTargetNames = {};
  15592. let k;
  15593. for ( k = 0; k < animationKeys.length; k ++ ) {
  15594. if ( animationKeys[ k ].morphTargets ) {
  15595. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  15596. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  15597. }
  15598. }
  15599. }
  15600. // create a track for each morph target with all zero
  15601. // morphTargetInfluences except for the keys in which
  15602. // the morphTarget is named.
  15603. for ( const morphTargetName in morphTargetNames ) {
  15604. const times = [];
  15605. const values = [];
  15606. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  15607. const animationKey = animationKeys[ k ];
  15608. times.push( animationKey.time );
  15609. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  15610. }
  15611. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  15612. }
  15613. duration = morphTargetNames.length * fps;
  15614. } else {
  15615. // ...assume skeletal animation
  15616. const boneName = '.bones[' + bones[ h ].name + ']';
  15617. addNonemptyTrack(
  15618. VectorKeyframeTrack, boneName + '.position',
  15619. animationKeys, 'pos', tracks );
  15620. addNonemptyTrack(
  15621. QuaternionKeyframeTrack, boneName + '.quaternion',
  15622. animationKeys, 'rot', tracks );
  15623. addNonemptyTrack(
  15624. VectorKeyframeTrack, boneName + '.scale',
  15625. animationKeys, 'scl', tracks );
  15626. }
  15627. }
  15628. if ( tracks.length === 0 ) {
  15629. return null;
  15630. }
  15631. const clip = new this( clipName, duration, tracks, blendMode );
  15632. return clip;
  15633. }
  15634. resetDuration() {
  15635. const tracks = this.tracks;
  15636. let duration = 0;
  15637. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  15638. const track = this.tracks[ i ];
  15639. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  15640. }
  15641. this.duration = duration;
  15642. return this;
  15643. }
  15644. trim() {
  15645. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15646. this.tracks[ i ].trim( 0, this.duration );
  15647. }
  15648. return this;
  15649. }
  15650. validate() {
  15651. let valid = true;
  15652. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15653. valid = valid && this.tracks[ i ].validate();
  15654. }
  15655. return valid;
  15656. }
  15657. optimize() {
  15658. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15659. this.tracks[ i ].optimize();
  15660. }
  15661. return this;
  15662. }
  15663. clone() {
  15664. const tracks = [];
  15665. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15666. tracks.push( this.tracks[ i ].clone() );
  15667. }
  15668. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  15669. }
  15670. toJSON() {
  15671. return this.constructor.toJSON( this );
  15672. }
  15673. }
  15674. function getTrackTypeForValueTypeName( typeName ) {
  15675. switch ( typeName.toLowerCase() ) {
  15676. case 'scalar':
  15677. case 'double':
  15678. case 'float':
  15679. case 'number':
  15680. case 'integer':
  15681. return NumberKeyframeTrack;
  15682. case 'vector':
  15683. case 'vector2':
  15684. case 'vector3':
  15685. case 'vector4':
  15686. return VectorKeyframeTrack;
  15687. case 'color':
  15688. return ColorKeyframeTrack;
  15689. case 'quaternion':
  15690. return QuaternionKeyframeTrack;
  15691. case 'bool':
  15692. case 'boolean':
  15693. return BooleanKeyframeTrack;
  15694. case 'string':
  15695. return StringKeyframeTrack;
  15696. }
  15697. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  15698. }
  15699. function parseKeyframeTrack( json ) {
  15700. if ( json.type === undefined ) {
  15701. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  15702. }
  15703. const trackType = getTrackTypeForValueTypeName( json.type );
  15704. if ( json.times === undefined ) {
  15705. const times = [], values = [];
  15706. flattenJSON( json.keys, times, values, 'value' );
  15707. json.times = times;
  15708. json.values = values;
  15709. }
  15710. // derived classes can define a static parse method
  15711. if ( trackType.parse !== undefined ) {
  15712. return trackType.parse( json );
  15713. } else {
  15714. // by default, we assume a constructor compatible with the base
  15715. return new trackType( json.name, json.times, json.values, json.interpolation );
  15716. }
  15717. }
  15718. const Cache = {
  15719. enabled: false,
  15720. files: {},
  15721. add: function ( key, file ) {
  15722. if ( this.enabled === false ) return;
  15723. // console.log( 'THREE.Cache', 'Adding key:', key );
  15724. this.files[ key ] = file;
  15725. },
  15726. get: function ( key ) {
  15727. if ( this.enabled === false ) return;
  15728. // console.log( 'THREE.Cache', 'Checking key:', key );
  15729. return this.files[ key ];
  15730. },
  15731. remove: function ( key ) {
  15732. delete this.files[ key ];
  15733. },
  15734. clear: function () {
  15735. this.files = {};
  15736. }
  15737. };
  15738. class LoadingManager {
  15739. constructor( onLoad, onProgress, onError ) {
  15740. const scope = this;
  15741. let isLoading = false;
  15742. let itemsLoaded = 0;
  15743. let itemsTotal = 0;
  15744. let urlModifier = undefined;
  15745. const handlers = [];
  15746. // Refer to #5689 for the reason why we don't set .onStart
  15747. // in the constructor
  15748. this.onStart = undefined;
  15749. this.onLoad = onLoad;
  15750. this.onProgress = onProgress;
  15751. this.onError = onError;
  15752. this.itemStart = function ( url ) {
  15753. itemsTotal ++;
  15754. if ( isLoading === false ) {
  15755. if ( scope.onStart !== undefined ) {
  15756. scope.onStart( url, itemsLoaded, itemsTotal );
  15757. }
  15758. }
  15759. isLoading = true;
  15760. };
  15761. this.itemEnd = function ( url ) {
  15762. itemsLoaded ++;
  15763. if ( scope.onProgress !== undefined ) {
  15764. scope.onProgress( url, itemsLoaded, itemsTotal );
  15765. }
  15766. if ( itemsLoaded === itemsTotal ) {
  15767. isLoading = false;
  15768. if ( scope.onLoad !== undefined ) {
  15769. scope.onLoad();
  15770. }
  15771. }
  15772. };
  15773. this.itemError = function ( url ) {
  15774. if ( scope.onError !== undefined ) {
  15775. scope.onError( url );
  15776. }
  15777. };
  15778. this.resolveURL = function ( url ) {
  15779. if ( urlModifier ) {
  15780. return urlModifier( url );
  15781. }
  15782. return url;
  15783. };
  15784. this.setURLModifier = function ( transform ) {
  15785. urlModifier = transform;
  15786. return this;
  15787. };
  15788. this.addHandler = function ( regex, loader ) {
  15789. handlers.push( regex, loader );
  15790. return this;
  15791. };
  15792. this.removeHandler = function ( regex ) {
  15793. const index = handlers.indexOf( regex );
  15794. if ( index !== - 1 ) {
  15795. handlers.splice( index, 2 );
  15796. }
  15797. return this;
  15798. };
  15799. this.getHandler = function ( file ) {
  15800. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  15801. const regex = handlers[ i ];
  15802. const loader = handlers[ i + 1 ];
  15803. if ( regex.global ) regex.lastIndex = 0; // see #17920
  15804. if ( regex.test( file ) ) {
  15805. return loader;
  15806. }
  15807. }
  15808. return null;
  15809. };
  15810. }
  15811. }
  15812. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  15813. class Loader {
  15814. constructor( manager ) {
  15815. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  15816. this.crossOrigin = 'anonymous';
  15817. this.withCredentials = false;
  15818. this.path = '';
  15819. this.resourcePath = '';
  15820. this.requestHeader = {};
  15821. }
  15822. load( /* url, onLoad, onProgress, onError */ ) {}
  15823. loadAsync( url, onProgress ) {
  15824. const scope = this;
  15825. return new Promise( function ( resolve, reject ) {
  15826. scope.load( url, resolve, onProgress, reject );
  15827. } );
  15828. }
  15829. parse( /* data */ ) {}
  15830. setCrossOrigin( crossOrigin ) {
  15831. this.crossOrigin = crossOrigin;
  15832. return this;
  15833. }
  15834. setWithCredentials( value ) {
  15835. this.withCredentials = value;
  15836. return this;
  15837. }
  15838. setPath( path ) {
  15839. this.path = path;
  15840. return this;
  15841. }
  15842. setResourcePath( resourcePath ) {
  15843. this.resourcePath = resourcePath;
  15844. return this;
  15845. }
  15846. setRequestHeader( requestHeader ) {
  15847. this.requestHeader = requestHeader;
  15848. return this;
  15849. }
  15850. }
  15851. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  15852. const loading = {};
  15853. class HttpError extends Error {
  15854. constructor( message, response ) {
  15855. super( message );
  15856. this.response = response;
  15857. }
  15858. }
  15859. class FileLoader extends Loader {
  15860. constructor( manager ) {
  15861. super( manager );
  15862. }
  15863. load( url, onLoad, onProgress, onError ) {
  15864. if ( url === undefined ) url = '';
  15865. if ( this.path !== undefined ) url = this.path + url;
  15866. url = this.manager.resolveURL( url );
  15867. const cached = Cache.get( url );
  15868. if ( cached !== undefined ) {
  15869. this.manager.itemStart( url );
  15870. setTimeout( () => {
  15871. if ( onLoad ) onLoad( cached );
  15872. this.manager.itemEnd( url );
  15873. }, 0 );
  15874. return cached;
  15875. }
  15876. // Check if request is duplicate
  15877. if ( loading[ url ] !== undefined ) {
  15878. loading[ url ].push( {
  15879. onLoad: onLoad,
  15880. onProgress: onProgress,
  15881. onError: onError
  15882. } );
  15883. return;
  15884. }
  15885. // Initialise array for duplicate requests
  15886. loading[ url ] = [];
  15887. loading[ url ].push( {
  15888. onLoad: onLoad,
  15889. onProgress: onProgress,
  15890. onError: onError,
  15891. } );
  15892. // create request
  15893. const req = new Request( url, {
  15894. headers: new Headers( this.requestHeader ),
  15895. credentials: this.withCredentials ? 'include' : 'same-origin',
  15896. // An abort controller could be added within a future PR
  15897. } );
  15898. // record states ( avoid data race )
  15899. const mimeType = this.mimeType;
  15900. const responseType = this.responseType;
  15901. // start the fetch
  15902. fetch( req )
  15903. .then( response => {
  15904. if ( response.status === 200 || response.status === 0 ) {
  15905. // Some browsers return HTTP Status 0 when using non-http protocol
  15906. // e.g. 'file://' or 'data://'. Handle as success.
  15907. if ( response.status === 0 ) {
  15908. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  15909. }
  15910. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  15911. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  15912. return response;
  15913. }
  15914. const callbacks = loading[ url ];
  15915. const reader = response.body.getReader();
  15916. // Nginx needs X-File-Size check
  15917. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  15918. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  15919. const total = contentLength ? parseInt( contentLength ) : 0;
  15920. const lengthComputable = total !== 0;
  15921. let loaded = 0;
  15922. // periodically read data into the new stream tracking while download progress
  15923. const stream = new ReadableStream( {
  15924. start( controller ) {
  15925. readData();
  15926. function readData() {
  15927. reader.read().then( ( { done, value } ) => {
  15928. if ( done ) {
  15929. controller.close();
  15930. } else {
  15931. loaded += value.byteLength;
  15932. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  15933. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15934. const callback = callbacks[ i ];
  15935. if ( callback.onProgress ) callback.onProgress( event );
  15936. }
  15937. controller.enqueue( value );
  15938. readData();
  15939. }
  15940. }, ( e ) => {
  15941. controller.error( e );
  15942. } );
  15943. }
  15944. }
  15945. } );
  15946. return new Response( stream );
  15947. } else {
  15948. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  15949. }
  15950. } )
  15951. .then( response => {
  15952. switch ( responseType ) {
  15953. case 'arraybuffer':
  15954. return response.arrayBuffer();
  15955. case 'blob':
  15956. return response.blob();
  15957. case 'document':
  15958. return response.text()
  15959. .then( text => {
  15960. const parser = new DOMParser();
  15961. return parser.parseFromString( text, mimeType );
  15962. } );
  15963. case 'json':
  15964. return response.json();
  15965. default:
  15966. if ( mimeType === undefined ) {
  15967. return response.text();
  15968. } else {
  15969. // sniff encoding
  15970. const re = /charset="?([^;"\s]*)"?/i;
  15971. const exec = re.exec( mimeType );
  15972. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  15973. const decoder = new TextDecoder( label );
  15974. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  15975. }
  15976. }
  15977. } )
  15978. .then( data => {
  15979. // Add to cache only on HTTP success, so that we do not cache
  15980. // error response bodies as proper responses to requests.
  15981. Cache.add( url, data );
  15982. const callbacks = loading[ url ];
  15983. delete loading[ url ];
  15984. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15985. const callback = callbacks[ i ];
  15986. if ( callback.onLoad ) callback.onLoad( data );
  15987. }
  15988. } )
  15989. .catch( err => {
  15990. // Abort errors and other errors are handled the same
  15991. const callbacks = loading[ url ];
  15992. if ( callbacks === undefined ) {
  15993. // When onLoad was called and url was deleted in `loading`
  15994. this.manager.itemError( url );
  15995. throw err;
  15996. }
  15997. delete loading[ url ];
  15998. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15999. const callback = callbacks[ i ];
  16000. if ( callback.onError ) callback.onError( err );
  16001. }
  16002. this.manager.itemError( url );
  16003. } )
  16004. .finally( () => {
  16005. this.manager.itemEnd( url );
  16006. } );
  16007. this.manager.itemStart( url );
  16008. }
  16009. setResponseType( value ) {
  16010. this.responseType = value;
  16011. return this;
  16012. }
  16013. setMimeType( value ) {
  16014. this.mimeType = value;
  16015. return this;
  16016. }
  16017. }
  16018. class AnimationLoader extends Loader {
  16019. constructor( manager ) {
  16020. super( manager );
  16021. }
  16022. load( url, onLoad, onProgress, onError ) {
  16023. const scope = this;
  16024. const loader = new FileLoader( this.manager );
  16025. loader.setPath( this.path );
  16026. loader.setRequestHeader( this.requestHeader );
  16027. loader.setWithCredentials( this.withCredentials );
  16028. loader.load( url, function ( text ) {
  16029. try {
  16030. onLoad( scope.parse( JSON.parse( text ) ) );
  16031. } catch ( e ) {
  16032. if ( onError ) {
  16033. onError( e );
  16034. } else {
  16035. console.error( e );
  16036. }
  16037. scope.manager.itemError( url );
  16038. }
  16039. }, onProgress, onError );
  16040. }
  16041. parse( json ) {
  16042. const animations = [];
  16043. for ( let i = 0; i < json.length; i ++ ) {
  16044. const clip = AnimationClip.parse( json[ i ] );
  16045. animations.push( clip );
  16046. }
  16047. return animations;
  16048. }
  16049. }
  16050. /**
  16051. * Abstract Base class to block based textures loader (dds, pvr, ...)
  16052. *
  16053. * Sub classes have to implement the parse() method which will be used in load().
  16054. */
  16055. class CompressedTextureLoader extends Loader {
  16056. constructor( manager ) {
  16057. super( manager );
  16058. }
  16059. load( url, onLoad, onProgress, onError ) {
  16060. const scope = this;
  16061. const images = [];
  16062. const texture = new CompressedTexture();
  16063. const loader = new FileLoader( this.manager );
  16064. loader.setPath( this.path );
  16065. loader.setResponseType( 'arraybuffer' );
  16066. loader.setRequestHeader( this.requestHeader );
  16067. loader.setWithCredentials( scope.withCredentials );
  16068. let loaded = 0;
  16069. function loadTexture( i ) {
  16070. loader.load( url[ i ], function ( buffer ) {
  16071. const texDatas = scope.parse( buffer, true );
  16072. images[ i ] = {
  16073. width: texDatas.width,
  16074. height: texDatas.height,
  16075. format: texDatas.format,
  16076. mipmaps: texDatas.mipmaps
  16077. };
  16078. loaded += 1;
  16079. if ( loaded === 6 ) {
  16080. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  16081. texture.image = images;
  16082. texture.format = texDatas.format;
  16083. texture.needsUpdate = true;
  16084. if ( onLoad ) onLoad( texture );
  16085. }
  16086. }, onProgress, onError );
  16087. }
  16088. if ( Array.isArray( url ) ) {
  16089. for ( let i = 0, il = url.length; i < il; ++ i ) {
  16090. loadTexture( i );
  16091. }
  16092. } else {
  16093. // compressed cubemap texture stored in a single DDS file
  16094. loader.load( url, function ( buffer ) {
  16095. const texDatas = scope.parse( buffer, true );
  16096. if ( texDatas.isCubemap ) {
  16097. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  16098. for ( let f = 0; f < faces; f ++ ) {
  16099. images[ f ] = { mipmaps: [] };
  16100. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  16101. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  16102. images[ f ].format = texDatas.format;
  16103. images[ f ].width = texDatas.width;
  16104. images[ f ].height = texDatas.height;
  16105. }
  16106. }
  16107. texture.image = images;
  16108. } else {
  16109. texture.image.width = texDatas.width;
  16110. texture.image.height = texDatas.height;
  16111. texture.mipmaps = texDatas.mipmaps;
  16112. }
  16113. if ( texDatas.mipmapCount === 1 ) {
  16114. texture.minFilter = LinearFilter;
  16115. }
  16116. texture.format = texDatas.format;
  16117. texture.needsUpdate = true;
  16118. if ( onLoad ) onLoad( texture );
  16119. }, onProgress, onError );
  16120. }
  16121. return texture;
  16122. }
  16123. }
  16124. class ImageLoader extends Loader {
  16125. constructor( manager ) {
  16126. super( manager );
  16127. }
  16128. load( url, onLoad, onProgress, onError ) {
  16129. if ( this.path !== undefined ) url = this.path + url;
  16130. url = this.manager.resolveURL( url );
  16131. const scope = this;
  16132. const cached = Cache.get( url );
  16133. if ( cached !== undefined ) {
  16134. scope.manager.itemStart( url );
  16135. setTimeout( function () {
  16136. if ( onLoad ) onLoad( cached );
  16137. scope.manager.itemEnd( url );
  16138. }, 0 );
  16139. return cached;
  16140. }
  16141. const image = createElementNS( 'img' );
  16142. function onImageLoad() {
  16143. removeEventListeners();
  16144. Cache.add( url, this );
  16145. if ( onLoad ) onLoad( this );
  16146. scope.manager.itemEnd( url );
  16147. }
  16148. function onImageError( event ) {
  16149. removeEventListeners();
  16150. if ( onError ) onError( event );
  16151. scope.manager.itemError( url );
  16152. scope.manager.itemEnd( url );
  16153. }
  16154. function removeEventListeners() {
  16155. image.removeEventListener( 'load', onImageLoad, false );
  16156. image.removeEventListener( 'error', onImageError, false );
  16157. }
  16158. image.addEventListener( 'load', onImageLoad, false );
  16159. image.addEventListener( 'error', onImageError, false );
  16160. if ( url.slice( 0, 5 ) !== 'data:' ) {
  16161. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  16162. }
  16163. scope.manager.itemStart( url );
  16164. image.src = url;
  16165. return image;
  16166. }
  16167. }
  16168. class CubeTextureLoader extends Loader {
  16169. constructor( manager ) {
  16170. super( manager );
  16171. }
  16172. load( urls, onLoad, onProgress, onError ) {
  16173. const texture = new CubeTexture();
  16174. texture.colorSpace = SRGBColorSpace;
  16175. const loader = new ImageLoader( this.manager );
  16176. loader.setCrossOrigin( this.crossOrigin );
  16177. loader.setPath( this.path );
  16178. let loaded = 0;
  16179. function loadTexture( i ) {
  16180. loader.load( urls[ i ], function ( image ) {
  16181. texture.images[ i ] = image;
  16182. loaded ++;
  16183. if ( loaded === 6 ) {
  16184. texture.needsUpdate = true;
  16185. if ( onLoad ) onLoad( texture );
  16186. }
  16187. }, undefined, onError );
  16188. }
  16189. for ( let i = 0; i < urls.length; ++ i ) {
  16190. loadTexture( i );
  16191. }
  16192. return texture;
  16193. }
  16194. }
  16195. /**
  16196. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  16197. *
  16198. * Sub classes have to implement the parse() method which will be used in load().
  16199. */
  16200. class DataTextureLoader extends Loader {
  16201. constructor( manager ) {
  16202. super( manager );
  16203. }
  16204. load( url, onLoad, onProgress, onError ) {
  16205. const scope = this;
  16206. const texture = new DataTexture();
  16207. const loader = new FileLoader( this.manager );
  16208. loader.setResponseType( 'arraybuffer' );
  16209. loader.setRequestHeader( this.requestHeader );
  16210. loader.setPath( this.path );
  16211. loader.setWithCredentials( scope.withCredentials );
  16212. loader.load( url, function ( buffer ) {
  16213. let texData;
  16214. try {
  16215. texData = scope.parse( buffer );
  16216. } catch ( error ) {
  16217. if ( onError !== undefined ) {
  16218. onError( error );
  16219. } else {
  16220. console.error( error );
  16221. return;
  16222. }
  16223. }
  16224. if ( texData.image !== undefined ) {
  16225. texture.image = texData.image;
  16226. } else if ( texData.data !== undefined ) {
  16227. texture.image.width = texData.width;
  16228. texture.image.height = texData.height;
  16229. texture.image.data = texData.data;
  16230. }
  16231. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  16232. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  16233. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  16234. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  16235. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  16236. if ( texData.colorSpace !== undefined ) {
  16237. texture.colorSpace = texData.colorSpace;
  16238. }
  16239. if ( texData.flipY !== undefined ) {
  16240. texture.flipY = texData.flipY;
  16241. }
  16242. if ( texData.format !== undefined ) {
  16243. texture.format = texData.format;
  16244. }
  16245. if ( texData.type !== undefined ) {
  16246. texture.type = texData.type;
  16247. }
  16248. if ( texData.mipmaps !== undefined ) {
  16249. texture.mipmaps = texData.mipmaps;
  16250. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  16251. }
  16252. if ( texData.mipmapCount === 1 ) {
  16253. texture.minFilter = LinearFilter;
  16254. }
  16255. if ( texData.generateMipmaps !== undefined ) {
  16256. texture.generateMipmaps = texData.generateMipmaps;
  16257. }
  16258. texture.needsUpdate = true;
  16259. if ( onLoad ) onLoad( texture, texData );
  16260. }, onProgress, onError );
  16261. return texture;
  16262. }
  16263. }
  16264. class TextureLoader extends Loader {
  16265. constructor( manager ) {
  16266. super( manager );
  16267. }
  16268. load( url, onLoad, onProgress, onError ) {
  16269. const texture = new Texture();
  16270. const loader = new ImageLoader( this.manager );
  16271. loader.setCrossOrigin( this.crossOrigin );
  16272. loader.setPath( this.path );
  16273. loader.load( url, function ( image ) {
  16274. texture.image = image;
  16275. texture.needsUpdate = true;
  16276. if ( onLoad !== undefined ) {
  16277. onLoad( texture );
  16278. }
  16279. }, onProgress, onError );
  16280. return texture;
  16281. }
  16282. }
  16283. class Light extends Object3D {
  16284. constructor( color, intensity = 1 ) {
  16285. super();
  16286. this.isLight = true;
  16287. this.type = 'Light';
  16288. this.color = new Color( color );
  16289. this.intensity = intensity;
  16290. }
  16291. dispose() {
  16292. // Empty here in base class; some subclasses override.
  16293. }
  16294. copy( source, recursive ) {
  16295. super.copy( source, recursive );
  16296. this.color.copy( source.color );
  16297. this.intensity = source.intensity;
  16298. return this;
  16299. }
  16300. toJSON( meta ) {
  16301. const data = super.toJSON( meta );
  16302. data.object.color = this.color.getHex();
  16303. data.object.intensity = this.intensity;
  16304. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  16305. if ( this.distance !== undefined ) data.object.distance = this.distance;
  16306. if ( this.angle !== undefined ) data.object.angle = this.angle;
  16307. if ( this.decay !== undefined ) data.object.decay = this.decay;
  16308. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  16309. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  16310. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  16311. return data;
  16312. }
  16313. }
  16314. class HemisphereLight extends Light {
  16315. constructor( skyColor, groundColor, intensity ) {
  16316. super( skyColor, intensity );
  16317. this.isHemisphereLight = true;
  16318. this.type = 'HemisphereLight';
  16319. this.position.copy( Object3D.DEFAULT_UP );
  16320. this.updateMatrix();
  16321. this.groundColor = new Color( groundColor );
  16322. }
  16323. copy( source, recursive ) {
  16324. super.copy( source, recursive );
  16325. this.groundColor.copy( source.groundColor );
  16326. return this;
  16327. }
  16328. }
  16329. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  16330. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  16331. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  16332. class LightShadow {
  16333. constructor( camera ) {
  16334. this.camera = camera;
  16335. this.intensity = 1;
  16336. this.bias = 0;
  16337. this.normalBias = 0;
  16338. this.radius = 1;
  16339. this.blurSamples = 8;
  16340. this.mapSize = new Vector2( 512, 512 );
  16341. this.map = null;
  16342. this.mapPass = null;
  16343. this.matrix = new Matrix4();
  16344. this.autoUpdate = true;
  16345. this.needsUpdate = false;
  16346. this._frustum = new Frustum();
  16347. this._frameExtents = new Vector2( 1, 1 );
  16348. this._viewportCount = 1;
  16349. this._viewports = [
  16350. new Vector4( 0, 0, 1, 1 )
  16351. ];
  16352. }
  16353. getViewportCount() {
  16354. return this._viewportCount;
  16355. }
  16356. getFrustum() {
  16357. return this._frustum;
  16358. }
  16359. updateMatrices( light ) {
  16360. const shadowCamera = this.camera;
  16361. const shadowMatrix = this.matrix;
  16362. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  16363. shadowCamera.position.copy( _lightPositionWorld$1 );
  16364. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  16365. shadowCamera.lookAt( _lookTarget$1 );
  16366. shadowCamera.updateMatrixWorld();
  16367. _projScreenMatrix$2.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16368. this._frustum.setFromProjectionMatrix( _projScreenMatrix$2 );
  16369. shadowMatrix.set(
  16370. 0.5, 0.0, 0.0, 0.5,
  16371. 0.0, 0.5, 0.0, 0.5,
  16372. 0.0, 0.0, 0.5, 0.5,
  16373. 0.0, 0.0, 0.0, 1.0
  16374. );
  16375. shadowMatrix.multiply( _projScreenMatrix$2 );
  16376. }
  16377. getViewport( viewportIndex ) {
  16378. return this._viewports[ viewportIndex ];
  16379. }
  16380. getFrameExtents() {
  16381. return this._frameExtents;
  16382. }
  16383. dispose() {
  16384. if ( this.map ) {
  16385. this.map.dispose();
  16386. }
  16387. if ( this.mapPass ) {
  16388. this.mapPass.dispose();
  16389. }
  16390. }
  16391. copy( source ) {
  16392. this.camera = source.camera.clone();
  16393. this.intensity = source.intensity;
  16394. this.bias = source.bias;
  16395. this.radius = source.radius;
  16396. this.mapSize.copy( source.mapSize );
  16397. return this;
  16398. }
  16399. clone() {
  16400. return new this.constructor().copy( this );
  16401. }
  16402. toJSON() {
  16403. const object = {};
  16404. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  16405. if ( this.bias !== 0 ) object.bias = this.bias;
  16406. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  16407. if ( this.radius !== 1 ) object.radius = this.radius;
  16408. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  16409. object.camera = this.camera.toJSON( false ).object;
  16410. delete object.camera.matrix;
  16411. return object;
  16412. }
  16413. }
  16414. class SpotLightShadow extends LightShadow {
  16415. constructor() {
  16416. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  16417. this.isSpotLightShadow = true;
  16418. this.focus = 1;
  16419. }
  16420. updateMatrices( light ) {
  16421. const camera = this.camera;
  16422. const fov = RAD2DEG * 2 * light.angle * this.focus;
  16423. const aspect = this.mapSize.width / this.mapSize.height;
  16424. const far = light.distance || camera.far;
  16425. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  16426. camera.fov = fov;
  16427. camera.aspect = aspect;
  16428. camera.far = far;
  16429. camera.updateProjectionMatrix();
  16430. }
  16431. super.updateMatrices( light );
  16432. }
  16433. copy( source ) {
  16434. super.copy( source );
  16435. this.focus = source.focus;
  16436. return this;
  16437. }
  16438. }
  16439. class SpotLight extends Light {
  16440. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  16441. super( color, intensity );
  16442. this.isSpotLight = true;
  16443. this.type = 'SpotLight';
  16444. this.position.copy( Object3D.DEFAULT_UP );
  16445. this.updateMatrix();
  16446. this.target = new Object3D();
  16447. this.distance = distance;
  16448. this.angle = angle;
  16449. this.penumbra = penumbra;
  16450. this.decay = decay;
  16451. this.map = null;
  16452. this.shadow = new SpotLightShadow();
  16453. }
  16454. get power() {
  16455. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16456. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  16457. return this.intensity * Math.PI;
  16458. }
  16459. set power( power ) {
  16460. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16461. this.intensity = power / Math.PI;
  16462. }
  16463. dispose() {
  16464. this.shadow.dispose();
  16465. }
  16466. copy( source, recursive ) {
  16467. super.copy( source, recursive );
  16468. this.distance = source.distance;
  16469. this.angle = source.angle;
  16470. this.penumbra = source.penumbra;
  16471. this.decay = source.decay;
  16472. this.target = source.target.clone();
  16473. this.shadow = source.shadow.clone();
  16474. return this;
  16475. }
  16476. }
  16477. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  16478. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  16479. const _lookTarget = /*@__PURE__*/ new Vector3();
  16480. class PointLightShadow extends LightShadow {
  16481. constructor() {
  16482. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  16483. this.isPointLightShadow = true;
  16484. this._frameExtents = new Vector2( 4, 2 );
  16485. this._viewportCount = 6;
  16486. this._viewports = [
  16487. // These viewports map a cube-map onto a 2D texture with the
  16488. // following orientation:
  16489. //
  16490. // xzXZ
  16491. // y Y
  16492. //
  16493. // X - Positive x direction
  16494. // x - Negative x direction
  16495. // Y - Positive y direction
  16496. // y - Negative y direction
  16497. // Z - Positive z direction
  16498. // z - Negative z direction
  16499. // positive X
  16500. new Vector4( 2, 1, 1, 1 ),
  16501. // negative X
  16502. new Vector4( 0, 1, 1, 1 ),
  16503. // positive Z
  16504. new Vector4( 3, 1, 1, 1 ),
  16505. // negative Z
  16506. new Vector4( 1, 1, 1, 1 ),
  16507. // positive Y
  16508. new Vector4( 3, 0, 1, 1 ),
  16509. // negative Y
  16510. new Vector4( 1, 0, 1, 1 )
  16511. ];
  16512. this._cubeDirections = [
  16513. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  16514. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  16515. ];
  16516. this._cubeUps = [
  16517. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  16518. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  16519. ];
  16520. }
  16521. updateMatrices( light, viewportIndex = 0 ) {
  16522. const camera = this.camera;
  16523. const shadowMatrix = this.matrix;
  16524. const far = light.distance || camera.far;
  16525. if ( far !== camera.far ) {
  16526. camera.far = far;
  16527. camera.updateProjectionMatrix();
  16528. }
  16529. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16530. camera.position.copy( _lightPositionWorld );
  16531. _lookTarget.copy( camera.position );
  16532. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  16533. camera.up.copy( this._cubeUps[ viewportIndex ] );
  16534. camera.lookAt( _lookTarget );
  16535. camera.updateMatrixWorld();
  16536. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16537. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16538. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  16539. }
  16540. }
  16541. class PointLight extends Light {
  16542. constructor( color, intensity, distance = 0, decay = 2 ) {
  16543. super( color, intensity );
  16544. this.isPointLight = true;
  16545. this.type = 'PointLight';
  16546. this.distance = distance;
  16547. this.decay = decay;
  16548. this.shadow = new PointLightShadow();
  16549. }
  16550. get power() {
  16551. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16552. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  16553. return this.intensity * 4 * Math.PI;
  16554. }
  16555. set power( power ) {
  16556. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16557. this.intensity = power / ( 4 * Math.PI );
  16558. }
  16559. dispose() {
  16560. this.shadow.dispose();
  16561. }
  16562. copy( source, recursive ) {
  16563. super.copy( source, recursive );
  16564. this.distance = source.distance;
  16565. this.decay = source.decay;
  16566. this.shadow = source.shadow.clone();
  16567. return this;
  16568. }
  16569. }
  16570. class OrthographicCamera extends Camera {
  16571. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  16572. super();
  16573. this.isOrthographicCamera = true;
  16574. this.type = 'OrthographicCamera';
  16575. this.zoom = 1;
  16576. this.view = null;
  16577. this.left = left;
  16578. this.right = right;
  16579. this.top = top;
  16580. this.bottom = bottom;
  16581. this.near = near;
  16582. this.far = far;
  16583. this.updateProjectionMatrix();
  16584. }
  16585. copy( source, recursive ) {
  16586. super.copy( source, recursive );
  16587. this.left = source.left;
  16588. this.right = source.right;
  16589. this.top = source.top;
  16590. this.bottom = source.bottom;
  16591. this.near = source.near;
  16592. this.far = source.far;
  16593. this.zoom = source.zoom;
  16594. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16595. return this;
  16596. }
  16597. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16598. if ( this.view === null ) {
  16599. this.view = {
  16600. enabled: true,
  16601. fullWidth: 1,
  16602. fullHeight: 1,
  16603. offsetX: 0,
  16604. offsetY: 0,
  16605. width: 1,
  16606. height: 1
  16607. };
  16608. }
  16609. this.view.enabled = true;
  16610. this.view.fullWidth = fullWidth;
  16611. this.view.fullHeight = fullHeight;
  16612. this.view.offsetX = x;
  16613. this.view.offsetY = y;
  16614. this.view.width = width;
  16615. this.view.height = height;
  16616. this.updateProjectionMatrix();
  16617. }
  16618. clearViewOffset() {
  16619. if ( this.view !== null ) {
  16620. this.view.enabled = false;
  16621. }
  16622. this.updateProjectionMatrix();
  16623. }
  16624. updateProjectionMatrix() {
  16625. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  16626. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  16627. const cx = ( this.right + this.left ) / 2;
  16628. const cy = ( this.top + this.bottom ) / 2;
  16629. let left = cx - dx;
  16630. let right = cx + dx;
  16631. let top = cy + dy;
  16632. let bottom = cy - dy;
  16633. if ( this.view !== null && this.view.enabled ) {
  16634. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  16635. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  16636. left += scaleW * this.view.offsetX;
  16637. right = left + scaleW * this.view.width;
  16638. top -= scaleH * this.view.offsetY;
  16639. bottom = top - scaleH * this.view.height;
  16640. }
  16641. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  16642. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16643. }
  16644. toJSON( meta ) {
  16645. const data = super.toJSON( meta );
  16646. data.object.zoom = this.zoom;
  16647. data.object.left = this.left;
  16648. data.object.right = this.right;
  16649. data.object.top = this.top;
  16650. data.object.bottom = this.bottom;
  16651. data.object.near = this.near;
  16652. data.object.far = this.far;
  16653. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16654. return data;
  16655. }
  16656. }
  16657. class DirectionalLightShadow extends LightShadow {
  16658. constructor() {
  16659. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  16660. this.isDirectionalLightShadow = true;
  16661. }
  16662. }
  16663. class DirectionalLight extends Light {
  16664. constructor( color, intensity ) {
  16665. super( color, intensity );
  16666. this.isDirectionalLight = true;
  16667. this.type = 'DirectionalLight';
  16668. this.position.copy( Object3D.DEFAULT_UP );
  16669. this.updateMatrix();
  16670. this.target = new Object3D();
  16671. this.shadow = new DirectionalLightShadow();
  16672. }
  16673. dispose() {
  16674. this.shadow.dispose();
  16675. }
  16676. copy( source ) {
  16677. super.copy( source );
  16678. this.target = source.target.clone();
  16679. this.shadow = source.shadow.clone();
  16680. return this;
  16681. }
  16682. }
  16683. class AmbientLight extends Light {
  16684. constructor( color, intensity ) {
  16685. super( color, intensity );
  16686. this.isAmbientLight = true;
  16687. this.type = 'AmbientLight';
  16688. }
  16689. }
  16690. class RectAreaLight extends Light {
  16691. constructor( color, intensity, width = 10, height = 10 ) {
  16692. super( color, intensity );
  16693. this.isRectAreaLight = true;
  16694. this.type = 'RectAreaLight';
  16695. this.width = width;
  16696. this.height = height;
  16697. }
  16698. get power() {
  16699. // compute the light's luminous power (in lumens) from its intensity (in nits)
  16700. return this.intensity * this.width * this.height * Math.PI;
  16701. }
  16702. set power( power ) {
  16703. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  16704. this.intensity = power / ( this.width * this.height * Math.PI );
  16705. }
  16706. copy( source ) {
  16707. super.copy( source );
  16708. this.width = source.width;
  16709. this.height = source.height;
  16710. return this;
  16711. }
  16712. toJSON( meta ) {
  16713. const data = super.toJSON( meta );
  16714. data.object.width = this.width;
  16715. data.object.height = this.height;
  16716. return data;
  16717. }
  16718. }
  16719. /**
  16720. * Primary reference:
  16721. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16722. *
  16723. * Secondary reference:
  16724. * https://www.ppsloan.org/publications/StupidSH36.pdf
  16725. */
  16726. // 3-band SH defined by 9 coefficients
  16727. class SphericalHarmonics3 {
  16728. constructor() {
  16729. this.isSphericalHarmonics3 = true;
  16730. this.coefficients = [];
  16731. for ( let i = 0; i < 9; i ++ ) {
  16732. this.coefficients.push( new Vector3() );
  16733. }
  16734. }
  16735. set( coefficients ) {
  16736. for ( let i = 0; i < 9; i ++ ) {
  16737. this.coefficients[ i ].copy( coefficients[ i ] );
  16738. }
  16739. return this;
  16740. }
  16741. zero() {
  16742. for ( let i = 0; i < 9; i ++ ) {
  16743. this.coefficients[ i ].set( 0, 0, 0 );
  16744. }
  16745. return this;
  16746. }
  16747. // get the radiance in the direction of the normal
  16748. // target is a Vector3
  16749. getAt( normal, target ) {
  16750. // normal is assumed to be unit length
  16751. const x = normal.x, y = normal.y, z = normal.z;
  16752. const coeff = this.coefficients;
  16753. // band 0
  16754. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  16755. // band 1
  16756. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  16757. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  16758. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  16759. // band 2
  16760. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  16761. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  16762. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  16763. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  16764. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  16765. return target;
  16766. }
  16767. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  16768. // target is a Vector3
  16769. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16770. getIrradianceAt( normal, target ) {
  16771. // normal is assumed to be unit length
  16772. const x = normal.x, y = normal.y, z = normal.z;
  16773. const coeff = this.coefficients;
  16774. // band 0
  16775. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  16776. // band 1
  16777. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  16778. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  16779. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  16780. // band 2
  16781. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  16782. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  16783. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  16784. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  16785. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  16786. return target;
  16787. }
  16788. add( sh ) {
  16789. for ( let i = 0; i < 9; i ++ ) {
  16790. this.coefficients[ i ].add( sh.coefficients[ i ] );
  16791. }
  16792. return this;
  16793. }
  16794. addScaledSH( sh, s ) {
  16795. for ( let i = 0; i < 9; i ++ ) {
  16796. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  16797. }
  16798. return this;
  16799. }
  16800. scale( s ) {
  16801. for ( let i = 0; i < 9; i ++ ) {
  16802. this.coefficients[ i ].multiplyScalar( s );
  16803. }
  16804. return this;
  16805. }
  16806. lerp( sh, alpha ) {
  16807. for ( let i = 0; i < 9; i ++ ) {
  16808. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  16809. }
  16810. return this;
  16811. }
  16812. equals( sh ) {
  16813. for ( let i = 0; i < 9; i ++ ) {
  16814. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  16815. return false;
  16816. }
  16817. }
  16818. return true;
  16819. }
  16820. copy( sh ) {
  16821. return this.set( sh.coefficients );
  16822. }
  16823. clone() {
  16824. return new this.constructor().copy( this );
  16825. }
  16826. fromArray( array, offset = 0 ) {
  16827. const coefficients = this.coefficients;
  16828. for ( let i = 0; i < 9; i ++ ) {
  16829. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  16830. }
  16831. return this;
  16832. }
  16833. toArray( array = [], offset = 0 ) {
  16834. const coefficients = this.coefficients;
  16835. for ( let i = 0; i < 9; i ++ ) {
  16836. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  16837. }
  16838. return array;
  16839. }
  16840. // evaluate the basis functions
  16841. // shBasis is an Array[ 9 ]
  16842. static getBasisAt( normal, shBasis ) {
  16843. // normal is assumed to be unit length
  16844. const x = normal.x, y = normal.y, z = normal.z;
  16845. // band 0
  16846. shBasis[ 0 ] = 0.282095;
  16847. // band 1
  16848. shBasis[ 1 ] = 0.488603 * y;
  16849. shBasis[ 2 ] = 0.488603 * z;
  16850. shBasis[ 3 ] = 0.488603 * x;
  16851. // band 2
  16852. shBasis[ 4 ] = 1.092548 * x * y;
  16853. shBasis[ 5 ] = 1.092548 * y * z;
  16854. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  16855. shBasis[ 7 ] = 1.092548 * x * z;
  16856. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  16857. }
  16858. }
  16859. class LightProbe extends Light {
  16860. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  16861. super( undefined, intensity );
  16862. this.isLightProbe = true;
  16863. this.sh = sh;
  16864. }
  16865. copy( source ) {
  16866. super.copy( source );
  16867. this.sh.copy( source.sh );
  16868. return this;
  16869. }
  16870. fromJSON( json ) {
  16871. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  16872. this.sh.fromArray( json.sh );
  16873. return this;
  16874. }
  16875. toJSON( meta ) {
  16876. const data = super.toJSON( meta );
  16877. data.object.sh = this.sh.toArray();
  16878. return data;
  16879. }
  16880. }
  16881. class MaterialLoader extends Loader {
  16882. constructor( manager ) {
  16883. super( manager );
  16884. this.textures = {};
  16885. }
  16886. load( url, onLoad, onProgress, onError ) {
  16887. const scope = this;
  16888. const loader = new FileLoader( scope.manager );
  16889. loader.setPath( scope.path );
  16890. loader.setRequestHeader( scope.requestHeader );
  16891. loader.setWithCredentials( scope.withCredentials );
  16892. loader.load( url, function ( text ) {
  16893. try {
  16894. onLoad( scope.parse( JSON.parse( text ) ) );
  16895. } catch ( e ) {
  16896. if ( onError ) {
  16897. onError( e );
  16898. } else {
  16899. console.error( e );
  16900. }
  16901. scope.manager.itemError( url );
  16902. }
  16903. }, onProgress, onError );
  16904. }
  16905. parse( json ) {
  16906. const textures = this.textures;
  16907. function getTexture( name ) {
  16908. if ( textures[ name ] === undefined ) {
  16909. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16910. }
  16911. return textures[ name ];
  16912. }
  16913. const material = this.createMaterialFromType( json.type );
  16914. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16915. if ( json.name !== undefined ) material.name = json.name;
  16916. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  16917. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16918. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16919. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  16920. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  16921. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  16922. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16923. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  16924. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  16925. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  16926. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16927. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  16928. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  16929. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  16930. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  16931. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  16932. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  16933. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  16934. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  16935. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  16936. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  16937. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  16938. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  16939. if ( json.fog !== undefined ) material.fog = json.fog;
  16940. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  16941. if ( json.blending !== undefined ) material.blending = json.blending;
  16942. if ( json.combine !== undefined ) material.combine = json.combine;
  16943. if ( json.side !== undefined ) material.side = json.side;
  16944. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  16945. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16946. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16947. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16948. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  16949. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  16950. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16951. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16952. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16953. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  16954. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  16955. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  16956. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  16957. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  16958. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  16959. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  16960. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  16961. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  16962. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  16963. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  16964. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  16965. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  16966. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  16967. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  16968. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  16969. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16970. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16971. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16972. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16973. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  16974. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  16975. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  16976. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  16977. if ( json.scale !== undefined ) material.scale = json.scale;
  16978. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  16979. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  16980. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  16981. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  16982. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  16983. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  16984. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  16985. if ( json.visible !== undefined ) material.visible = json.visible;
  16986. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  16987. if ( json.userData !== undefined ) material.userData = json.userData;
  16988. if ( json.vertexColors !== undefined ) {
  16989. if ( typeof json.vertexColors === 'number' ) {
  16990. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  16991. } else {
  16992. material.vertexColors = json.vertexColors;
  16993. }
  16994. }
  16995. // Shader Material
  16996. if ( json.uniforms !== undefined ) {
  16997. for ( const name in json.uniforms ) {
  16998. const uniform = json.uniforms[ name ];
  16999. material.uniforms[ name ] = {};
  17000. switch ( uniform.type ) {
  17001. case 't':
  17002. material.uniforms[ name ].value = getTexture( uniform.value );
  17003. break;
  17004. case 'c':
  17005. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  17006. break;
  17007. case 'v2':
  17008. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  17009. break;
  17010. case 'v3':
  17011. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  17012. break;
  17013. case 'v4':
  17014. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  17015. break;
  17016. case 'm3':
  17017. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  17018. break;
  17019. case 'm4':
  17020. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  17021. break;
  17022. default:
  17023. material.uniforms[ name ].value = uniform.value;
  17024. }
  17025. }
  17026. }
  17027. if ( json.defines !== undefined ) material.defines = json.defines;
  17028. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  17029. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  17030. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  17031. if ( json.extensions !== undefined ) {
  17032. for ( const key in json.extensions ) {
  17033. material.extensions[ key ] = json.extensions[ key ];
  17034. }
  17035. }
  17036. if ( json.lights !== undefined ) material.lights = json.lights;
  17037. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  17038. // for PointsMaterial
  17039. if ( json.size !== undefined ) material.size = json.size;
  17040. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  17041. // maps
  17042. if ( json.map !== undefined ) material.map = getTexture( json.map );
  17043. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  17044. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  17045. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  17046. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  17047. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  17048. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  17049. if ( json.normalScale !== undefined ) {
  17050. let normalScale = json.normalScale;
  17051. if ( Array.isArray( normalScale ) === false ) {
  17052. // Blender exporter used to export a scalar. See #7459
  17053. normalScale = [ normalScale, normalScale ];
  17054. }
  17055. material.normalScale = new Vector2().fromArray( normalScale );
  17056. }
  17057. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  17058. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  17059. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  17060. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  17061. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  17062. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  17063. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  17064. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  17065. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  17066. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  17067. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  17068. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  17069. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  17070. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  17071. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  17072. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  17073. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  17074. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  17075. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  17076. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  17077. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  17078. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  17079. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  17080. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  17081. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  17082. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  17083. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  17084. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  17085. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  17086. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  17087. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  17088. return material;
  17089. }
  17090. setTextures( value ) {
  17091. this.textures = value;
  17092. return this;
  17093. }
  17094. createMaterialFromType( type ) {
  17095. return MaterialLoader.createMaterialFromType( type );
  17096. }
  17097. static createMaterialFromType( type ) {
  17098. const materialLib = {
  17099. ShadowMaterial,
  17100. SpriteMaterial,
  17101. RawShaderMaterial,
  17102. ShaderMaterial,
  17103. PointsMaterial,
  17104. MeshPhysicalMaterial,
  17105. MeshStandardMaterial,
  17106. MeshPhongMaterial,
  17107. MeshToonMaterial,
  17108. MeshNormalMaterial,
  17109. MeshLambertMaterial,
  17110. MeshDepthMaterial,
  17111. MeshDistanceMaterial,
  17112. MeshBasicMaterial,
  17113. MeshMatcapMaterial,
  17114. LineDashedMaterial,
  17115. LineBasicMaterial,
  17116. Material
  17117. };
  17118. return new materialLib[ type ]();
  17119. }
  17120. }
  17121. class LoaderUtils {
  17122. static decodeText( array ) { // @deprecated, r165
  17123. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  17124. if ( typeof TextDecoder !== 'undefined' ) {
  17125. return new TextDecoder().decode( array );
  17126. }
  17127. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  17128. // throws a "maximum call stack size exceeded" error for large arrays.
  17129. let s = '';
  17130. for ( let i = 0, il = array.length; i < il; i ++ ) {
  17131. // Implicitly assumes little-endian.
  17132. s += String.fromCharCode( array[ i ] );
  17133. }
  17134. try {
  17135. // merges multi-byte utf-8 characters.
  17136. return decodeURIComponent( escape( s ) );
  17137. } catch ( e ) { // see #16358
  17138. return s;
  17139. }
  17140. }
  17141. static extractUrlBase( url ) {
  17142. const index = url.lastIndexOf( '/' );
  17143. if ( index === - 1 ) return './';
  17144. return url.slice( 0, index + 1 );
  17145. }
  17146. static resolveURL( url, path ) {
  17147. // Invalid URL
  17148. if ( typeof url !== 'string' || url === '' ) return '';
  17149. // Host Relative URL
  17150. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  17151. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  17152. }
  17153. // Absolute URL http://,https://,//
  17154. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  17155. // Data URI
  17156. if ( /^data:.*,.*$/i.test( url ) ) return url;
  17157. // Blob URL
  17158. if ( /^blob:.*$/i.test( url ) ) return url;
  17159. // Relative URL
  17160. return path + url;
  17161. }
  17162. }
  17163. class InstancedBufferGeometry extends BufferGeometry {
  17164. constructor() {
  17165. super();
  17166. this.isInstancedBufferGeometry = true;
  17167. this.type = 'InstancedBufferGeometry';
  17168. this.instanceCount = Infinity;
  17169. }
  17170. copy( source ) {
  17171. super.copy( source );
  17172. this.instanceCount = source.instanceCount;
  17173. return this;
  17174. }
  17175. toJSON() {
  17176. const data = super.toJSON();
  17177. data.instanceCount = this.instanceCount;
  17178. data.isInstancedBufferGeometry = true;
  17179. return data;
  17180. }
  17181. }
  17182. class BufferGeometryLoader extends Loader {
  17183. constructor( manager ) {
  17184. super( manager );
  17185. }
  17186. load( url, onLoad, onProgress, onError ) {
  17187. const scope = this;
  17188. const loader = new FileLoader( scope.manager );
  17189. loader.setPath( scope.path );
  17190. loader.setRequestHeader( scope.requestHeader );
  17191. loader.setWithCredentials( scope.withCredentials );
  17192. loader.load( url, function ( text ) {
  17193. try {
  17194. onLoad( scope.parse( JSON.parse( text ) ) );
  17195. } catch ( e ) {
  17196. if ( onError ) {
  17197. onError( e );
  17198. } else {
  17199. console.error( e );
  17200. }
  17201. scope.manager.itemError( url );
  17202. }
  17203. }, onProgress, onError );
  17204. }
  17205. parse( json ) {
  17206. const interleavedBufferMap = {};
  17207. const arrayBufferMap = {};
  17208. function getInterleavedBuffer( json, uuid ) {
  17209. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  17210. const interleavedBuffers = json.interleavedBuffers;
  17211. const interleavedBuffer = interleavedBuffers[ uuid ];
  17212. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  17213. const array = getTypedArray( interleavedBuffer.type, buffer );
  17214. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  17215. ib.uuid = interleavedBuffer.uuid;
  17216. interleavedBufferMap[ uuid ] = ib;
  17217. return ib;
  17218. }
  17219. function getArrayBuffer( json, uuid ) {
  17220. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  17221. const arrayBuffers = json.arrayBuffers;
  17222. const arrayBuffer = arrayBuffers[ uuid ];
  17223. const ab = new Uint32Array( arrayBuffer ).buffer;
  17224. arrayBufferMap[ uuid ] = ab;
  17225. return ab;
  17226. }
  17227. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  17228. const index = json.data.index;
  17229. if ( index !== undefined ) {
  17230. const typedArray = getTypedArray( index.type, index.array );
  17231. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  17232. }
  17233. const attributes = json.data.attributes;
  17234. for ( const key in attributes ) {
  17235. const attribute = attributes[ key ];
  17236. let bufferAttribute;
  17237. if ( attribute.isInterleavedBufferAttribute ) {
  17238. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17239. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17240. } else {
  17241. const typedArray = getTypedArray( attribute.type, attribute.array );
  17242. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  17243. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  17244. }
  17245. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17246. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  17247. geometry.setAttribute( key, bufferAttribute );
  17248. }
  17249. const morphAttributes = json.data.morphAttributes;
  17250. if ( morphAttributes ) {
  17251. for ( const key in morphAttributes ) {
  17252. const attributeArray = morphAttributes[ key ];
  17253. const array = [];
  17254. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  17255. const attribute = attributeArray[ i ];
  17256. let bufferAttribute;
  17257. if ( attribute.isInterleavedBufferAttribute ) {
  17258. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17259. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17260. } else {
  17261. const typedArray = getTypedArray( attribute.type, attribute.array );
  17262. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  17263. }
  17264. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17265. array.push( bufferAttribute );
  17266. }
  17267. geometry.morphAttributes[ key ] = array;
  17268. }
  17269. }
  17270. const morphTargetsRelative = json.data.morphTargetsRelative;
  17271. if ( morphTargetsRelative ) {
  17272. geometry.morphTargetsRelative = true;
  17273. }
  17274. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  17275. if ( groups !== undefined ) {
  17276. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  17277. const group = groups[ i ];
  17278. geometry.addGroup( group.start, group.count, group.materialIndex );
  17279. }
  17280. }
  17281. const boundingSphere = json.data.boundingSphere;
  17282. if ( boundingSphere !== undefined ) {
  17283. const center = new Vector3();
  17284. if ( boundingSphere.center !== undefined ) {
  17285. center.fromArray( boundingSphere.center );
  17286. }
  17287. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  17288. }
  17289. if ( json.name ) geometry.name = json.name;
  17290. if ( json.userData ) geometry.userData = json.userData;
  17291. return geometry;
  17292. }
  17293. }
  17294. class ObjectLoader extends Loader {
  17295. constructor( manager ) {
  17296. super( manager );
  17297. }
  17298. load( url, onLoad, onProgress, onError ) {
  17299. const scope = this;
  17300. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17301. this.resourcePath = this.resourcePath || path;
  17302. const loader = new FileLoader( this.manager );
  17303. loader.setPath( this.path );
  17304. loader.setRequestHeader( this.requestHeader );
  17305. loader.setWithCredentials( this.withCredentials );
  17306. loader.load( url, function ( text ) {
  17307. let json = null;
  17308. try {
  17309. json = JSON.parse( text );
  17310. } catch ( error ) {
  17311. if ( onError !== undefined ) onError( error );
  17312. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  17313. return;
  17314. }
  17315. const metadata = json.metadata;
  17316. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17317. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  17318. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17319. return;
  17320. }
  17321. scope.parse( json, onLoad );
  17322. }, onProgress, onError );
  17323. }
  17324. async loadAsync( url, onProgress ) {
  17325. const scope = this;
  17326. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17327. this.resourcePath = this.resourcePath || path;
  17328. const loader = new FileLoader( this.manager );
  17329. loader.setPath( this.path );
  17330. loader.setRequestHeader( this.requestHeader );
  17331. loader.setWithCredentials( this.withCredentials );
  17332. const text = await loader.loadAsync( url, onProgress );
  17333. const json = JSON.parse( text );
  17334. const metadata = json.metadata;
  17335. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17336. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17337. }
  17338. return await scope.parseAsync( json );
  17339. }
  17340. parse( json, onLoad ) {
  17341. const animations = this.parseAnimations( json.animations );
  17342. const shapes = this.parseShapes( json.shapes );
  17343. const geometries = this.parseGeometries( json.geometries, shapes );
  17344. const images = this.parseImages( json.images, function () {
  17345. if ( onLoad !== undefined ) onLoad( object );
  17346. } );
  17347. const textures = this.parseTextures( json.textures, images );
  17348. const materials = this.parseMaterials( json.materials, textures );
  17349. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17350. const skeletons = this.parseSkeletons( json.skeletons, object );
  17351. this.bindSkeletons( object, skeletons );
  17352. this.bindLightTargets( object );
  17353. //
  17354. if ( onLoad !== undefined ) {
  17355. let hasImages = false;
  17356. for ( const uuid in images ) {
  17357. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  17358. hasImages = true;
  17359. break;
  17360. }
  17361. }
  17362. if ( hasImages === false ) onLoad( object );
  17363. }
  17364. return object;
  17365. }
  17366. async parseAsync( json ) {
  17367. const animations = this.parseAnimations( json.animations );
  17368. const shapes = this.parseShapes( json.shapes );
  17369. const geometries = this.parseGeometries( json.geometries, shapes );
  17370. const images = await this.parseImagesAsync( json.images );
  17371. const textures = this.parseTextures( json.textures, images );
  17372. const materials = this.parseMaterials( json.materials, textures );
  17373. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17374. const skeletons = this.parseSkeletons( json.skeletons, object );
  17375. this.bindSkeletons( object, skeletons );
  17376. this.bindLightTargets( object );
  17377. return object;
  17378. }
  17379. parseShapes( json ) {
  17380. const shapes = {};
  17381. if ( json !== undefined ) {
  17382. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17383. const shape = new Shape().fromJSON( json[ i ] );
  17384. shapes[ shape.uuid ] = shape;
  17385. }
  17386. }
  17387. return shapes;
  17388. }
  17389. parseSkeletons( json, object ) {
  17390. const skeletons = {};
  17391. const bones = {};
  17392. // generate bone lookup table
  17393. object.traverse( function ( child ) {
  17394. if ( child.isBone ) bones[ child.uuid ] = child;
  17395. } );
  17396. // create skeletons
  17397. if ( json !== undefined ) {
  17398. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17399. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  17400. skeletons[ skeleton.uuid ] = skeleton;
  17401. }
  17402. }
  17403. return skeletons;
  17404. }
  17405. parseGeometries( json, shapes ) {
  17406. const geometries = {};
  17407. if ( json !== undefined ) {
  17408. const bufferGeometryLoader = new BufferGeometryLoader();
  17409. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17410. let geometry;
  17411. const data = json[ i ];
  17412. switch ( data.type ) {
  17413. case 'BufferGeometry':
  17414. case 'InstancedBufferGeometry':
  17415. geometry = bufferGeometryLoader.parse( data );
  17416. break;
  17417. default:
  17418. if ( data.type in Geometries$1 ) {
  17419. geometry = Geometries$1[ data.type ].fromJSON( data, shapes );
  17420. } else {
  17421. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  17422. }
  17423. }
  17424. geometry.uuid = data.uuid;
  17425. if ( data.name !== undefined ) geometry.name = data.name;
  17426. if ( data.userData !== undefined ) geometry.userData = data.userData;
  17427. geometries[ data.uuid ] = geometry;
  17428. }
  17429. }
  17430. return geometries;
  17431. }
  17432. parseMaterials( json, textures ) {
  17433. const cache = {}; // MultiMaterial
  17434. const materials = {};
  17435. if ( json !== undefined ) {
  17436. const loader = new MaterialLoader();
  17437. loader.setTextures( textures );
  17438. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17439. const data = json[ i ];
  17440. if ( cache[ data.uuid ] === undefined ) {
  17441. cache[ data.uuid ] = loader.parse( data );
  17442. }
  17443. materials[ data.uuid ] = cache[ data.uuid ];
  17444. }
  17445. }
  17446. return materials;
  17447. }
  17448. parseAnimations( json ) {
  17449. const animations = {};
  17450. if ( json !== undefined ) {
  17451. for ( let i = 0; i < json.length; i ++ ) {
  17452. const data = json[ i ];
  17453. const clip = AnimationClip.parse( data );
  17454. animations[ clip.uuid ] = clip;
  17455. }
  17456. }
  17457. return animations;
  17458. }
  17459. parseImages( json, onLoad ) {
  17460. const scope = this;
  17461. const images = {};
  17462. let loader;
  17463. function loadImage( url ) {
  17464. scope.manager.itemStart( url );
  17465. return loader.load( url, function () {
  17466. scope.manager.itemEnd( url );
  17467. }, undefined, function () {
  17468. scope.manager.itemError( url );
  17469. scope.manager.itemEnd( url );
  17470. } );
  17471. }
  17472. function deserializeImage( image ) {
  17473. if ( typeof image === 'string' ) {
  17474. const url = image;
  17475. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17476. return loadImage( path );
  17477. } else {
  17478. if ( image.data ) {
  17479. return {
  17480. data: getTypedArray( image.type, image.data ),
  17481. width: image.width,
  17482. height: image.height
  17483. };
  17484. } else {
  17485. return null;
  17486. }
  17487. }
  17488. }
  17489. if ( json !== undefined && json.length > 0 ) {
  17490. const manager = new LoadingManager( onLoad );
  17491. loader = new ImageLoader( manager );
  17492. loader.setCrossOrigin( this.crossOrigin );
  17493. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17494. const image = json[ i ];
  17495. const url = image.url;
  17496. if ( Array.isArray( url ) ) {
  17497. // load array of images e.g CubeTexture
  17498. const imageArray = [];
  17499. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17500. const currentUrl = url[ j ];
  17501. const deserializedImage = deserializeImage( currentUrl );
  17502. if ( deserializedImage !== null ) {
  17503. if ( deserializedImage instanceof HTMLImageElement ) {
  17504. imageArray.push( deserializedImage );
  17505. } else {
  17506. // special case: handle array of data textures for cube textures
  17507. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17508. }
  17509. }
  17510. }
  17511. images[ image.uuid ] = new Source( imageArray );
  17512. } else {
  17513. // load single image
  17514. const deserializedImage = deserializeImage( image.url );
  17515. images[ image.uuid ] = new Source( deserializedImage );
  17516. }
  17517. }
  17518. }
  17519. return images;
  17520. }
  17521. async parseImagesAsync( json ) {
  17522. const scope = this;
  17523. const images = {};
  17524. let loader;
  17525. async function deserializeImage( image ) {
  17526. if ( typeof image === 'string' ) {
  17527. const url = image;
  17528. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17529. return await loader.loadAsync( path );
  17530. } else {
  17531. if ( image.data ) {
  17532. return {
  17533. data: getTypedArray( image.type, image.data ),
  17534. width: image.width,
  17535. height: image.height
  17536. };
  17537. } else {
  17538. return null;
  17539. }
  17540. }
  17541. }
  17542. if ( json !== undefined && json.length > 0 ) {
  17543. loader = new ImageLoader( this.manager );
  17544. loader.setCrossOrigin( this.crossOrigin );
  17545. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17546. const image = json[ i ];
  17547. const url = image.url;
  17548. if ( Array.isArray( url ) ) {
  17549. // load array of images e.g CubeTexture
  17550. const imageArray = [];
  17551. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17552. const currentUrl = url[ j ];
  17553. const deserializedImage = await deserializeImage( currentUrl );
  17554. if ( deserializedImage !== null ) {
  17555. if ( deserializedImage instanceof HTMLImageElement ) {
  17556. imageArray.push( deserializedImage );
  17557. } else {
  17558. // special case: handle array of data textures for cube textures
  17559. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17560. }
  17561. }
  17562. }
  17563. images[ image.uuid ] = new Source( imageArray );
  17564. } else {
  17565. // load single image
  17566. const deserializedImage = await deserializeImage( image.url );
  17567. images[ image.uuid ] = new Source( deserializedImage );
  17568. }
  17569. }
  17570. }
  17571. return images;
  17572. }
  17573. parseTextures( json, images ) {
  17574. function parseConstant( value, type ) {
  17575. if ( typeof value === 'number' ) return value;
  17576. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17577. return type[ value ];
  17578. }
  17579. const textures = {};
  17580. if ( json !== undefined ) {
  17581. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17582. const data = json[ i ];
  17583. if ( data.image === undefined ) {
  17584. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17585. }
  17586. if ( images[ data.image ] === undefined ) {
  17587. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17588. }
  17589. const source = images[ data.image ];
  17590. const image = source.data;
  17591. let texture;
  17592. if ( Array.isArray( image ) ) {
  17593. texture = new CubeTexture();
  17594. if ( image.length === 6 ) texture.needsUpdate = true;
  17595. } else {
  17596. if ( image && image.data ) {
  17597. texture = new DataTexture();
  17598. } else {
  17599. texture = new Texture();
  17600. }
  17601. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  17602. }
  17603. texture.source = source;
  17604. texture.uuid = data.uuid;
  17605. if ( data.name !== undefined ) texture.name = data.name;
  17606. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  17607. if ( data.channel !== undefined ) texture.channel = data.channel;
  17608. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17609. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17610. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  17611. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  17612. if ( data.wrap !== undefined ) {
  17613. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  17614. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  17615. }
  17616. if ( data.format !== undefined ) texture.format = data.format;
  17617. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  17618. if ( data.type !== undefined ) texture.type = data.type;
  17619. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  17620. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  17621. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  17622. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17623. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17624. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  17625. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  17626. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  17627. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  17628. if ( data.userData !== undefined ) texture.userData = data.userData;
  17629. textures[ data.uuid ] = texture;
  17630. }
  17631. }
  17632. return textures;
  17633. }
  17634. parseObject( data, geometries, materials, textures, animations ) {
  17635. let object;
  17636. function getGeometry( name ) {
  17637. if ( geometries[ name ] === undefined ) {
  17638. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17639. }
  17640. return geometries[ name ];
  17641. }
  17642. function getMaterial( name ) {
  17643. if ( name === undefined ) return undefined;
  17644. if ( Array.isArray( name ) ) {
  17645. const array = [];
  17646. for ( let i = 0, l = name.length; i < l; i ++ ) {
  17647. const uuid = name[ i ];
  17648. if ( materials[ uuid ] === undefined ) {
  17649. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  17650. }
  17651. array.push( materials[ uuid ] );
  17652. }
  17653. return array;
  17654. }
  17655. if ( materials[ name ] === undefined ) {
  17656. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17657. }
  17658. return materials[ name ];
  17659. }
  17660. function getTexture( uuid ) {
  17661. if ( textures[ uuid ] === undefined ) {
  17662. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  17663. }
  17664. return textures[ uuid ];
  17665. }
  17666. let geometry, material;
  17667. switch ( data.type ) {
  17668. case 'Scene':
  17669. object = new Scene();
  17670. if ( data.background !== undefined ) {
  17671. if ( Number.isInteger( data.background ) ) {
  17672. object.background = new Color( data.background );
  17673. } else {
  17674. object.background = getTexture( data.background );
  17675. }
  17676. }
  17677. if ( data.environment !== undefined ) {
  17678. object.environment = getTexture( data.environment );
  17679. }
  17680. if ( data.fog !== undefined ) {
  17681. if ( data.fog.type === 'Fog' ) {
  17682. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17683. } else if ( data.fog.type === 'FogExp2' ) {
  17684. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17685. }
  17686. if ( data.fog.name !== '' ) {
  17687. object.fog.name = data.fog.name;
  17688. }
  17689. }
  17690. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  17691. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  17692. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  17693. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  17694. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  17695. break;
  17696. case 'PerspectiveCamera':
  17697. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17698. if ( data.focus !== undefined ) object.focus = data.focus;
  17699. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17700. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17701. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17702. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17703. break;
  17704. case 'OrthographicCamera':
  17705. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17706. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17707. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17708. break;
  17709. case 'AmbientLight':
  17710. object = new AmbientLight( data.color, data.intensity );
  17711. break;
  17712. case 'DirectionalLight':
  17713. object = new DirectionalLight( data.color, data.intensity );
  17714. object.target = data.target || '';
  17715. break;
  17716. case 'PointLight':
  17717. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17718. break;
  17719. case 'RectAreaLight':
  17720. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  17721. break;
  17722. case 'SpotLight':
  17723. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17724. object.target = data.target || '';
  17725. break;
  17726. case 'HemisphereLight':
  17727. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17728. break;
  17729. case 'LightProbe':
  17730. object = new LightProbe().fromJSON( data );
  17731. break;
  17732. case 'SkinnedMesh':
  17733. geometry = getGeometry( data.geometry );
  17734. material = getMaterial( data.material );
  17735. object = new SkinnedMesh( geometry, material );
  17736. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  17737. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  17738. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  17739. break;
  17740. case 'Mesh':
  17741. geometry = getGeometry( data.geometry );
  17742. material = getMaterial( data.material );
  17743. object = new Mesh( geometry, material );
  17744. break;
  17745. case 'InstancedMesh':
  17746. geometry = getGeometry( data.geometry );
  17747. material = getMaterial( data.material );
  17748. const count = data.count;
  17749. const instanceMatrix = data.instanceMatrix;
  17750. const instanceColor = data.instanceColor;
  17751. object = new InstancedMesh( geometry, material, count );
  17752. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  17753. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  17754. break;
  17755. case 'BatchedMesh':
  17756. geometry = getGeometry( data.geometry );
  17757. material = getMaterial( data.material );
  17758. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  17759. object.geometry = geometry;
  17760. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  17761. object.sortObjects = data.sortObjects;
  17762. object._drawRanges = data.drawRanges;
  17763. object._reservedRanges = data.reservedRanges;
  17764. object._visibility = data.visibility;
  17765. object._active = data.active;
  17766. object._bounds = data.bounds.map( bound => {
  17767. const box = new Box3();
  17768. box.min.fromArray( bound.boxMin );
  17769. box.max.fromArray( bound.boxMax );
  17770. const sphere = new Sphere();
  17771. sphere.radius = bound.sphereRadius;
  17772. sphere.center.fromArray( bound.sphereCenter );
  17773. return {
  17774. boxInitialized: bound.boxInitialized,
  17775. box: box,
  17776. sphereInitialized: bound.sphereInitialized,
  17777. sphere: sphere
  17778. };
  17779. } );
  17780. object._maxInstanceCount = data.maxInstanceCount;
  17781. object._maxVertexCount = data.maxVertexCount;
  17782. object._maxIndexCount = data.maxIndexCount;
  17783. object._geometryInitialized = data.geometryInitialized;
  17784. object._geometryCount = data.geometryCount;
  17785. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  17786. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  17787. break;
  17788. case 'LOD':
  17789. object = new LOD();
  17790. break;
  17791. case 'Line':
  17792. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  17793. break;
  17794. case 'LineLoop':
  17795. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  17796. break;
  17797. case 'LineSegments':
  17798. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17799. break;
  17800. case 'PointCloud':
  17801. case 'Points':
  17802. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17803. break;
  17804. case 'Sprite':
  17805. object = new Sprite( getMaterial( data.material ) );
  17806. break;
  17807. case 'Group':
  17808. object = new Group();
  17809. break;
  17810. case 'Bone':
  17811. object = new Bone();
  17812. break;
  17813. default:
  17814. object = new Object3D();
  17815. }
  17816. object.uuid = data.uuid;
  17817. if ( data.name !== undefined ) object.name = data.name;
  17818. if ( data.matrix !== undefined ) {
  17819. object.matrix.fromArray( data.matrix );
  17820. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  17821. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  17822. } else {
  17823. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17824. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17825. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17826. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17827. }
  17828. if ( data.up !== undefined ) object.up.fromArray( data.up );
  17829. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17830. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17831. if ( data.shadow ) {
  17832. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  17833. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17834. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  17835. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17836. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17837. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17838. }
  17839. if ( data.visible !== undefined ) object.visible = data.visible;
  17840. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  17841. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  17842. if ( data.userData !== undefined ) object.userData = data.userData;
  17843. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  17844. if ( data.children !== undefined ) {
  17845. const children = data.children;
  17846. for ( let i = 0; i < children.length; i ++ ) {
  17847. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  17848. }
  17849. }
  17850. if ( data.animations !== undefined ) {
  17851. const objectAnimations = data.animations;
  17852. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  17853. const uuid = objectAnimations[ i ];
  17854. object.animations.push( animations[ uuid ] );
  17855. }
  17856. }
  17857. if ( data.type === 'LOD' ) {
  17858. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  17859. const levels = data.levels;
  17860. for ( let l = 0; l < levels.length; l ++ ) {
  17861. const level = levels[ l ];
  17862. const child = object.getObjectByProperty( 'uuid', level.object );
  17863. if ( child !== undefined ) {
  17864. object.addLevel( child, level.distance, level.hysteresis );
  17865. }
  17866. }
  17867. }
  17868. return object;
  17869. }
  17870. bindSkeletons( object, skeletons ) {
  17871. if ( Object.keys( skeletons ).length === 0 ) return;
  17872. object.traverse( function ( child ) {
  17873. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  17874. const skeleton = skeletons[ child.skeleton ];
  17875. if ( skeleton === undefined ) {
  17876. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  17877. } else {
  17878. child.bind( skeleton, child.bindMatrix );
  17879. }
  17880. }
  17881. } );
  17882. }
  17883. bindLightTargets( object ) {
  17884. object.traverse( function ( child ) {
  17885. if ( child.isDirectionalLight || child.isSpotLight ) {
  17886. const uuid = child.target;
  17887. const target = object.getObjectByProperty( 'uuid', uuid );
  17888. if ( target !== undefined ) {
  17889. child.target = target;
  17890. } else {
  17891. child.target = new Object3D();
  17892. }
  17893. }
  17894. } );
  17895. }
  17896. }
  17897. const TEXTURE_MAPPING = {
  17898. UVMapping: UVMapping,
  17899. CubeReflectionMapping: CubeReflectionMapping,
  17900. CubeRefractionMapping: CubeRefractionMapping,
  17901. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  17902. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  17903. CubeUVReflectionMapping: CubeUVReflectionMapping
  17904. };
  17905. const TEXTURE_WRAPPING = {
  17906. RepeatWrapping: RepeatWrapping,
  17907. ClampToEdgeWrapping: ClampToEdgeWrapping,
  17908. MirroredRepeatWrapping: MirroredRepeatWrapping
  17909. };
  17910. const TEXTURE_FILTER = {
  17911. NearestFilter: NearestFilter,
  17912. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  17913. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  17914. LinearFilter: LinearFilter,
  17915. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  17916. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  17917. };
  17918. class ImageBitmapLoader extends Loader {
  17919. constructor( manager ) {
  17920. super( manager );
  17921. this.isImageBitmapLoader = true;
  17922. if ( typeof createImageBitmap === 'undefined' ) {
  17923. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  17924. }
  17925. if ( typeof fetch === 'undefined' ) {
  17926. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  17927. }
  17928. this.options = { premultiplyAlpha: 'none' };
  17929. }
  17930. setOptions( options ) {
  17931. this.options = options;
  17932. return this;
  17933. }
  17934. load( url, onLoad, onProgress, onError ) {
  17935. if ( url === undefined ) url = '';
  17936. if ( this.path !== undefined ) url = this.path + url;
  17937. url = this.manager.resolveURL( url );
  17938. const scope = this;
  17939. const cached = Cache.get( url );
  17940. if ( cached !== undefined ) {
  17941. scope.manager.itemStart( url );
  17942. // If cached is a promise, wait for it to resolve
  17943. if ( cached.then ) {
  17944. cached.then( imageBitmap => {
  17945. if ( onLoad ) onLoad( imageBitmap );
  17946. scope.manager.itemEnd( url );
  17947. } ).catch( e => {
  17948. if ( onError ) onError( e );
  17949. } );
  17950. return;
  17951. }
  17952. // If cached is not a promise (i.e., it's already an imageBitmap)
  17953. setTimeout( function () {
  17954. if ( onLoad ) onLoad( cached );
  17955. scope.manager.itemEnd( url );
  17956. }, 0 );
  17957. return cached;
  17958. }
  17959. const fetchOptions = {};
  17960. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  17961. fetchOptions.headers = this.requestHeader;
  17962. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  17963. return res.blob();
  17964. } ).then( function ( blob ) {
  17965. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  17966. } ).then( function ( imageBitmap ) {
  17967. Cache.add( url, imageBitmap );
  17968. if ( onLoad ) onLoad( imageBitmap );
  17969. scope.manager.itemEnd( url );
  17970. return imageBitmap;
  17971. } ).catch( function ( e ) {
  17972. if ( onError ) onError( e );
  17973. Cache.remove( url );
  17974. scope.manager.itemError( url );
  17975. scope.manager.itemEnd( url );
  17976. } );
  17977. Cache.add( url, promise );
  17978. scope.manager.itemStart( url );
  17979. }
  17980. }
  17981. let _context;
  17982. class AudioContext {
  17983. static getContext() {
  17984. if ( _context === undefined ) {
  17985. _context = new ( window.AudioContext || window.webkitAudioContext )();
  17986. }
  17987. return _context;
  17988. }
  17989. static setContext( value ) {
  17990. _context = value;
  17991. }
  17992. }
  17993. class AudioLoader extends Loader {
  17994. constructor( manager ) {
  17995. super( manager );
  17996. }
  17997. load( url, onLoad, onProgress, onError ) {
  17998. const scope = this;
  17999. const loader = new FileLoader( this.manager );
  18000. loader.setResponseType( 'arraybuffer' );
  18001. loader.setPath( this.path );
  18002. loader.setRequestHeader( this.requestHeader );
  18003. loader.setWithCredentials( this.withCredentials );
  18004. loader.load( url, function ( buffer ) {
  18005. try {
  18006. // Create a copy of the buffer. The `decodeAudioData` method
  18007. // detaches the buffer when complete, preventing reuse.
  18008. const bufferCopy = buffer.slice( 0 );
  18009. const context = AudioContext.getContext();
  18010. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  18011. onLoad( audioBuffer );
  18012. } ).catch( handleError );
  18013. } catch ( e ) {
  18014. handleError( e );
  18015. }
  18016. }, onProgress, onError );
  18017. function handleError( e ) {
  18018. if ( onError ) {
  18019. onError( e );
  18020. } else {
  18021. console.error( e );
  18022. }
  18023. scope.manager.itemError( url );
  18024. }
  18025. }
  18026. }
  18027. const _eyeRight = /*@__PURE__*/ new Matrix4();
  18028. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  18029. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  18030. class StereoCamera {
  18031. constructor() {
  18032. this.type = 'StereoCamera';
  18033. this.aspect = 1;
  18034. this.eyeSep = 0.064;
  18035. this.cameraL = new PerspectiveCamera();
  18036. this.cameraL.layers.enable( 1 );
  18037. this.cameraL.matrixAutoUpdate = false;
  18038. this.cameraR = new PerspectiveCamera();
  18039. this.cameraR.layers.enable( 2 );
  18040. this.cameraR.matrixAutoUpdate = false;
  18041. this._cache = {
  18042. focus: null,
  18043. fov: null,
  18044. aspect: null,
  18045. near: null,
  18046. far: null,
  18047. zoom: null,
  18048. eyeSep: null
  18049. };
  18050. }
  18051. update( camera ) {
  18052. const cache = this._cache;
  18053. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  18054. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  18055. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  18056. if ( needsUpdate ) {
  18057. cache.focus = camera.focus;
  18058. cache.fov = camera.fov;
  18059. cache.aspect = camera.aspect * this.aspect;
  18060. cache.near = camera.near;
  18061. cache.far = camera.far;
  18062. cache.zoom = camera.zoom;
  18063. cache.eyeSep = this.eyeSep;
  18064. // Off-axis stereoscopic effect based on
  18065. // http://paulbourke.net/stereographics/stereorender/
  18066. _projectionMatrix.copy( camera.projectionMatrix );
  18067. const eyeSepHalf = cache.eyeSep / 2;
  18068. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  18069. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  18070. let xmin, xmax;
  18071. // translate xOffset
  18072. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  18073. _eyeRight.elements[ 12 ] = eyeSepHalf;
  18074. // for left eye
  18075. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  18076. xmax = ymax * cache.aspect + eyeSepOnProjection;
  18077. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  18078. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  18079. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  18080. // for right eye
  18081. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  18082. xmax = ymax * cache.aspect - eyeSepOnProjection;
  18083. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  18084. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  18085. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  18086. }
  18087. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  18088. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  18089. }
  18090. }
  18091. class ArrayCamera extends PerspectiveCamera {
  18092. constructor( array = [] ) {
  18093. super();
  18094. this.isArrayCamera = true;
  18095. this.cameras = array;
  18096. }
  18097. }
  18098. class Clock {
  18099. constructor( autoStart = true ) {
  18100. this.autoStart = autoStart;
  18101. this.startTime = 0;
  18102. this.oldTime = 0;
  18103. this.elapsedTime = 0;
  18104. this.running = false;
  18105. }
  18106. start() {
  18107. this.startTime = now();
  18108. this.oldTime = this.startTime;
  18109. this.elapsedTime = 0;
  18110. this.running = true;
  18111. }
  18112. stop() {
  18113. this.getElapsedTime();
  18114. this.running = false;
  18115. this.autoStart = false;
  18116. }
  18117. getElapsedTime() {
  18118. this.getDelta();
  18119. return this.elapsedTime;
  18120. }
  18121. getDelta() {
  18122. let diff = 0;
  18123. if ( this.autoStart && ! this.running ) {
  18124. this.start();
  18125. return 0;
  18126. }
  18127. if ( this.running ) {
  18128. const newTime = now();
  18129. diff = ( newTime - this.oldTime ) / 1000;
  18130. this.oldTime = newTime;
  18131. this.elapsedTime += diff;
  18132. }
  18133. return diff;
  18134. }
  18135. }
  18136. function now() {
  18137. return performance.now();
  18138. }
  18139. const _position$1 = /*@__PURE__*/ new Vector3();
  18140. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  18141. const _scale$1 = /*@__PURE__*/ new Vector3();
  18142. const _orientation$1 = /*@__PURE__*/ new Vector3();
  18143. class AudioListener extends Object3D {
  18144. constructor() {
  18145. super();
  18146. this.type = 'AudioListener';
  18147. this.context = AudioContext.getContext();
  18148. this.gain = this.context.createGain();
  18149. this.gain.connect( this.context.destination );
  18150. this.filter = null;
  18151. this.timeDelta = 0;
  18152. // private
  18153. this._clock = new Clock();
  18154. }
  18155. getInput() {
  18156. return this.gain;
  18157. }
  18158. removeFilter() {
  18159. if ( this.filter !== null ) {
  18160. this.gain.disconnect( this.filter );
  18161. this.filter.disconnect( this.context.destination );
  18162. this.gain.connect( this.context.destination );
  18163. this.filter = null;
  18164. }
  18165. return this;
  18166. }
  18167. getFilter() {
  18168. return this.filter;
  18169. }
  18170. setFilter( value ) {
  18171. if ( this.filter !== null ) {
  18172. this.gain.disconnect( this.filter );
  18173. this.filter.disconnect( this.context.destination );
  18174. } else {
  18175. this.gain.disconnect( this.context.destination );
  18176. }
  18177. this.filter = value;
  18178. this.gain.connect( this.filter );
  18179. this.filter.connect( this.context.destination );
  18180. return this;
  18181. }
  18182. getMasterVolume() {
  18183. return this.gain.gain.value;
  18184. }
  18185. setMasterVolume( value ) {
  18186. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18187. return this;
  18188. }
  18189. updateMatrixWorld( force ) {
  18190. super.updateMatrixWorld( force );
  18191. const listener = this.context.listener;
  18192. const up = this.up;
  18193. this.timeDelta = this._clock.getDelta();
  18194. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  18195. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  18196. if ( listener.positionX ) {
  18197. // code path for Chrome (see #14393)
  18198. const endTime = this.context.currentTime + this.timeDelta;
  18199. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  18200. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  18201. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  18202. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  18203. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  18204. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  18205. listener.upX.linearRampToValueAtTime( up.x, endTime );
  18206. listener.upY.linearRampToValueAtTime( up.y, endTime );
  18207. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  18208. } else {
  18209. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  18210. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  18211. }
  18212. }
  18213. }
  18214. class Audio extends Object3D {
  18215. constructor( listener ) {
  18216. super();
  18217. this.type = 'Audio';
  18218. this.listener = listener;
  18219. this.context = listener.context;
  18220. this.gain = this.context.createGain();
  18221. this.gain.connect( listener.getInput() );
  18222. this.autoplay = false;
  18223. this.buffer = null;
  18224. this.detune = 0;
  18225. this.loop = false;
  18226. this.loopStart = 0;
  18227. this.loopEnd = 0;
  18228. this.offset = 0;
  18229. this.duration = undefined;
  18230. this.playbackRate = 1;
  18231. this.isPlaying = false;
  18232. this.hasPlaybackControl = true;
  18233. this.source = null;
  18234. this.sourceType = 'empty';
  18235. this._startedAt = 0;
  18236. this._progress = 0;
  18237. this._connected = false;
  18238. this.filters = [];
  18239. }
  18240. getOutput() {
  18241. return this.gain;
  18242. }
  18243. setNodeSource( audioNode ) {
  18244. this.hasPlaybackControl = false;
  18245. this.sourceType = 'audioNode';
  18246. this.source = audioNode;
  18247. this.connect();
  18248. return this;
  18249. }
  18250. setMediaElementSource( mediaElement ) {
  18251. this.hasPlaybackControl = false;
  18252. this.sourceType = 'mediaNode';
  18253. this.source = this.context.createMediaElementSource( mediaElement );
  18254. this.connect();
  18255. return this;
  18256. }
  18257. setMediaStreamSource( mediaStream ) {
  18258. this.hasPlaybackControl = false;
  18259. this.sourceType = 'mediaStreamNode';
  18260. this.source = this.context.createMediaStreamSource( mediaStream );
  18261. this.connect();
  18262. return this;
  18263. }
  18264. setBuffer( audioBuffer ) {
  18265. this.buffer = audioBuffer;
  18266. this.sourceType = 'buffer';
  18267. if ( this.autoplay ) this.play();
  18268. return this;
  18269. }
  18270. play( delay = 0 ) {
  18271. if ( this.isPlaying === true ) {
  18272. console.warn( 'THREE.Audio: Audio is already playing.' );
  18273. return;
  18274. }
  18275. if ( this.hasPlaybackControl === false ) {
  18276. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18277. return;
  18278. }
  18279. this._startedAt = this.context.currentTime + delay;
  18280. const source = this.context.createBufferSource();
  18281. source.buffer = this.buffer;
  18282. source.loop = this.loop;
  18283. source.loopStart = this.loopStart;
  18284. source.loopEnd = this.loopEnd;
  18285. source.onended = this.onEnded.bind( this );
  18286. source.start( this._startedAt, this._progress + this.offset, this.duration );
  18287. this.isPlaying = true;
  18288. this.source = source;
  18289. this.setDetune( this.detune );
  18290. this.setPlaybackRate( this.playbackRate );
  18291. return this.connect();
  18292. }
  18293. pause() {
  18294. if ( this.hasPlaybackControl === false ) {
  18295. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18296. return;
  18297. }
  18298. if ( this.isPlaying === true ) {
  18299. // update current progress
  18300. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  18301. if ( this.loop === true ) {
  18302. // ensure _progress does not exceed duration with looped audios
  18303. this._progress = this._progress % ( this.duration || this.buffer.duration );
  18304. }
  18305. this.source.stop();
  18306. this.source.onended = null;
  18307. this.isPlaying = false;
  18308. }
  18309. return this;
  18310. }
  18311. stop( delay = 0 ) {
  18312. if ( this.hasPlaybackControl === false ) {
  18313. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18314. return;
  18315. }
  18316. this._progress = 0;
  18317. if ( this.source !== null ) {
  18318. this.source.stop( this.context.currentTime + delay );
  18319. this.source.onended = null;
  18320. }
  18321. this.isPlaying = false;
  18322. return this;
  18323. }
  18324. connect() {
  18325. if ( this.filters.length > 0 ) {
  18326. this.source.connect( this.filters[ 0 ] );
  18327. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18328. this.filters[ i - 1 ].connect( this.filters[ i ] );
  18329. }
  18330. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  18331. } else {
  18332. this.source.connect( this.getOutput() );
  18333. }
  18334. this._connected = true;
  18335. return this;
  18336. }
  18337. disconnect() {
  18338. if ( this._connected === false ) {
  18339. return;
  18340. }
  18341. if ( this.filters.length > 0 ) {
  18342. this.source.disconnect( this.filters[ 0 ] );
  18343. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18344. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  18345. }
  18346. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  18347. } else {
  18348. this.source.disconnect( this.getOutput() );
  18349. }
  18350. this._connected = false;
  18351. return this;
  18352. }
  18353. getFilters() {
  18354. return this.filters;
  18355. }
  18356. setFilters( value ) {
  18357. if ( ! value ) value = [];
  18358. if ( this._connected === true ) {
  18359. this.disconnect();
  18360. this.filters = value.slice();
  18361. this.connect();
  18362. } else {
  18363. this.filters = value.slice();
  18364. }
  18365. return this;
  18366. }
  18367. setDetune( value ) {
  18368. this.detune = value;
  18369. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  18370. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  18371. }
  18372. return this;
  18373. }
  18374. getDetune() {
  18375. return this.detune;
  18376. }
  18377. getFilter() {
  18378. return this.getFilters()[ 0 ];
  18379. }
  18380. setFilter( filter ) {
  18381. return this.setFilters( filter ? [ filter ] : [] );
  18382. }
  18383. setPlaybackRate( value ) {
  18384. if ( this.hasPlaybackControl === false ) {
  18385. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18386. return;
  18387. }
  18388. this.playbackRate = value;
  18389. if ( this.isPlaying === true ) {
  18390. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  18391. }
  18392. return this;
  18393. }
  18394. getPlaybackRate() {
  18395. return this.playbackRate;
  18396. }
  18397. onEnded() {
  18398. this.isPlaying = false;
  18399. }
  18400. getLoop() {
  18401. if ( this.hasPlaybackControl === false ) {
  18402. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18403. return false;
  18404. }
  18405. return this.loop;
  18406. }
  18407. setLoop( value ) {
  18408. if ( this.hasPlaybackControl === false ) {
  18409. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18410. return;
  18411. }
  18412. this.loop = value;
  18413. if ( this.isPlaying === true ) {
  18414. this.source.loop = this.loop;
  18415. }
  18416. return this;
  18417. }
  18418. setLoopStart( value ) {
  18419. this.loopStart = value;
  18420. return this;
  18421. }
  18422. setLoopEnd( value ) {
  18423. this.loopEnd = value;
  18424. return this;
  18425. }
  18426. getVolume() {
  18427. return this.gain.gain.value;
  18428. }
  18429. setVolume( value ) {
  18430. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18431. return this;
  18432. }
  18433. }
  18434. const _position = /*@__PURE__*/ new Vector3();
  18435. const _quaternion = /*@__PURE__*/ new Quaternion();
  18436. const _scale = /*@__PURE__*/ new Vector3();
  18437. const _orientation = /*@__PURE__*/ new Vector3();
  18438. class PositionalAudio extends Audio {
  18439. constructor( listener ) {
  18440. super( listener );
  18441. this.panner = this.context.createPanner();
  18442. this.panner.panningModel = 'HRTF';
  18443. this.panner.connect( this.gain );
  18444. }
  18445. connect() {
  18446. super.connect();
  18447. this.panner.connect( this.gain );
  18448. }
  18449. disconnect() {
  18450. super.disconnect();
  18451. this.panner.disconnect( this.gain );
  18452. }
  18453. getOutput() {
  18454. return this.panner;
  18455. }
  18456. getRefDistance() {
  18457. return this.panner.refDistance;
  18458. }
  18459. setRefDistance( value ) {
  18460. this.panner.refDistance = value;
  18461. return this;
  18462. }
  18463. getRolloffFactor() {
  18464. return this.panner.rolloffFactor;
  18465. }
  18466. setRolloffFactor( value ) {
  18467. this.panner.rolloffFactor = value;
  18468. return this;
  18469. }
  18470. getDistanceModel() {
  18471. return this.panner.distanceModel;
  18472. }
  18473. setDistanceModel( value ) {
  18474. this.panner.distanceModel = value;
  18475. return this;
  18476. }
  18477. getMaxDistance() {
  18478. return this.panner.maxDistance;
  18479. }
  18480. setMaxDistance( value ) {
  18481. this.panner.maxDistance = value;
  18482. return this;
  18483. }
  18484. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  18485. this.panner.coneInnerAngle = coneInnerAngle;
  18486. this.panner.coneOuterAngle = coneOuterAngle;
  18487. this.panner.coneOuterGain = coneOuterGain;
  18488. return this;
  18489. }
  18490. updateMatrixWorld( force ) {
  18491. super.updateMatrixWorld( force );
  18492. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  18493. this.matrixWorld.decompose( _position, _quaternion, _scale );
  18494. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  18495. const panner = this.panner;
  18496. if ( panner.positionX ) {
  18497. // code path for Chrome and Firefox (see #14393)
  18498. const endTime = this.context.currentTime + this.listener.timeDelta;
  18499. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  18500. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  18501. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  18502. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  18503. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  18504. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  18505. } else {
  18506. panner.setPosition( _position.x, _position.y, _position.z );
  18507. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  18508. }
  18509. }
  18510. }
  18511. class AudioAnalyser {
  18512. constructor( audio, fftSize = 2048 ) {
  18513. this.analyser = audio.context.createAnalyser();
  18514. this.analyser.fftSize = fftSize;
  18515. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  18516. audio.getOutput().connect( this.analyser );
  18517. }
  18518. getFrequencyData() {
  18519. this.analyser.getByteFrequencyData( this.data );
  18520. return this.data;
  18521. }
  18522. getAverageFrequency() {
  18523. let value = 0;
  18524. const data = this.getFrequencyData();
  18525. for ( let i = 0; i < data.length; i ++ ) {
  18526. value += data[ i ];
  18527. }
  18528. return value / data.length;
  18529. }
  18530. }
  18531. class PropertyMixer {
  18532. constructor( binding, typeName, valueSize ) {
  18533. this.binding = binding;
  18534. this.valueSize = valueSize;
  18535. let mixFunction,
  18536. mixFunctionAdditive,
  18537. setIdentity;
  18538. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  18539. //
  18540. // interpolators can use .buffer as their .result
  18541. // the data then goes to 'incoming'
  18542. //
  18543. // 'accu0' and 'accu1' are used frame-interleaved for
  18544. // the cumulative result and are compared to detect
  18545. // changes
  18546. //
  18547. // 'orig' stores the original state of the property
  18548. //
  18549. // 'add' is used for additive cumulative results
  18550. //
  18551. // 'work' is optional and is only present for quaternion types. It is used
  18552. // to store intermediate quaternion multiplication results
  18553. switch ( typeName ) {
  18554. case 'quaternion':
  18555. mixFunction = this._slerp;
  18556. mixFunctionAdditive = this._slerpAdditive;
  18557. setIdentity = this._setAdditiveIdentityQuaternion;
  18558. this.buffer = new Float64Array( valueSize * 6 );
  18559. this._workIndex = 5;
  18560. break;
  18561. case 'string':
  18562. case 'bool':
  18563. mixFunction = this._select;
  18564. // Use the regular mix function and for additive on these types,
  18565. // additive is not relevant for non-numeric types
  18566. mixFunctionAdditive = this._select;
  18567. setIdentity = this._setAdditiveIdentityOther;
  18568. this.buffer = new Array( valueSize * 5 );
  18569. break;
  18570. default:
  18571. mixFunction = this._lerp;
  18572. mixFunctionAdditive = this._lerpAdditive;
  18573. setIdentity = this._setAdditiveIdentityNumeric;
  18574. this.buffer = new Float64Array( valueSize * 5 );
  18575. }
  18576. this._mixBufferRegion = mixFunction;
  18577. this._mixBufferRegionAdditive = mixFunctionAdditive;
  18578. this._setIdentity = setIdentity;
  18579. this._origIndex = 3;
  18580. this._addIndex = 4;
  18581. this.cumulativeWeight = 0;
  18582. this.cumulativeWeightAdditive = 0;
  18583. this.useCount = 0;
  18584. this.referenceCount = 0;
  18585. }
  18586. // accumulate data in the 'incoming' region into 'accu<i>'
  18587. accumulate( accuIndex, weight ) {
  18588. // note: happily accumulating nothing when weight = 0, the caller knows
  18589. // the weight and shouldn't have made the call in the first place
  18590. const buffer = this.buffer,
  18591. stride = this.valueSize,
  18592. offset = accuIndex * stride + stride;
  18593. let currentWeight = this.cumulativeWeight;
  18594. if ( currentWeight === 0 ) {
  18595. // accuN := incoming * weight
  18596. for ( let i = 0; i !== stride; ++ i ) {
  18597. buffer[ offset + i ] = buffer[ i ];
  18598. }
  18599. currentWeight = weight;
  18600. } else {
  18601. // accuN := accuN + incoming * weight
  18602. currentWeight += weight;
  18603. const mix = weight / currentWeight;
  18604. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  18605. }
  18606. this.cumulativeWeight = currentWeight;
  18607. }
  18608. // accumulate data in the 'incoming' region into 'add'
  18609. accumulateAdditive( weight ) {
  18610. const buffer = this.buffer,
  18611. stride = this.valueSize,
  18612. offset = stride * this._addIndex;
  18613. if ( this.cumulativeWeightAdditive === 0 ) {
  18614. // add = identity
  18615. this._setIdentity();
  18616. }
  18617. // add := add + incoming * weight
  18618. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  18619. this.cumulativeWeightAdditive += weight;
  18620. }
  18621. // apply the state of 'accu<i>' to the binding when accus differ
  18622. apply( accuIndex ) {
  18623. const stride = this.valueSize,
  18624. buffer = this.buffer,
  18625. offset = accuIndex * stride + stride,
  18626. weight = this.cumulativeWeight,
  18627. weightAdditive = this.cumulativeWeightAdditive,
  18628. binding = this.binding;
  18629. this.cumulativeWeight = 0;
  18630. this.cumulativeWeightAdditive = 0;
  18631. if ( weight < 1 ) {
  18632. // accuN := accuN + original * ( 1 - cumulativeWeight )
  18633. const originalValueOffset = stride * this._origIndex;
  18634. this._mixBufferRegion(
  18635. buffer, offset, originalValueOffset, 1 - weight, stride );
  18636. }
  18637. if ( weightAdditive > 0 ) {
  18638. // accuN := accuN + additive accuN
  18639. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  18640. }
  18641. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  18642. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  18643. // value has changed -> update scene graph
  18644. binding.setValue( buffer, offset );
  18645. break;
  18646. }
  18647. }
  18648. }
  18649. // remember the state of the bound property and copy it to both accus
  18650. saveOriginalState() {
  18651. const binding = this.binding;
  18652. const buffer = this.buffer,
  18653. stride = this.valueSize,
  18654. originalValueOffset = stride * this._origIndex;
  18655. binding.getValue( buffer, originalValueOffset );
  18656. // accu[0..1] := orig -- initially detect changes against the original
  18657. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  18658. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  18659. }
  18660. // Add to identity for additive
  18661. this._setIdentity();
  18662. this.cumulativeWeight = 0;
  18663. this.cumulativeWeightAdditive = 0;
  18664. }
  18665. // apply the state previously taken via 'saveOriginalState' to the binding
  18666. restoreOriginalState() {
  18667. const originalValueOffset = this.valueSize * 3;
  18668. this.binding.setValue( this.buffer, originalValueOffset );
  18669. }
  18670. _setAdditiveIdentityNumeric() {
  18671. const startIndex = this._addIndex * this.valueSize;
  18672. const endIndex = startIndex + this.valueSize;
  18673. for ( let i = startIndex; i < endIndex; i ++ ) {
  18674. this.buffer[ i ] = 0;
  18675. }
  18676. }
  18677. _setAdditiveIdentityQuaternion() {
  18678. this._setAdditiveIdentityNumeric();
  18679. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  18680. }
  18681. _setAdditiveIdentityOther() {
  18682. const startIndex = this._origIndex * this.valueSize;
  18683. const targetIndex = this._addIndex * this.valueSize;
  18684. for ( let i = 0; i < this.valueSize; i ++ ) {
  18685. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  18686. }
  18687. }
  18688. // mix functions
  18689. _select( buffer, dstOffset, srcOffset, t, stride ) {
  18690. if ( t >= 0.5 ) {
  18691. for ( let i = 0; i !== stride; ++ i ) {
  18692. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  18693. }
  18694. }
  18695. }
  18696. _slerp( buffer, dstOffset, srcOffset, t ) {
  18697. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  18698. }
  18699. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18700. const workOffset = this._workIndex * stride;
  18701. // Store result in intermediate buffer offset
  18702. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  18703. // Slerp to the intermediate result
  18704. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  18705. }
  18706. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  18707. const s = 1 - t;
  18708. for ( let i = 0; i !== stride; ++ i ) {
  18709. const j = dstOffset + i;
  18710. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  18711. }
  18712. }
  18713. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18714. for ( let i = 0; i !== stride; ++ i ) {
  18715. const j = dstOffset + i;
  18716. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  18717. }
  18718. }
  18719. }
  18720. // Characters [].:/ are reserved for track binding syntax.
  18721. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  18722. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  18723. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  18724. // only latin characters, and the unicode \p{L} is not yet supported. So
  18725. // instead, we exclude reserved characters and match everything else.
  18726. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  18727. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18728. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  18729. // be matched to parse the rest of the track name.
  18730. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  18731. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  18732. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  18733. // Object on target node, and accessor. May not contain reserved
  18734. // characters. Accessor may contain any character except closing bracket.
  18735. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  18736. // Property and accessor. May not contain reserved characters. Accessor may
  18737. // contain any non-bracket characters.
  18738. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  18739. const _trackRe = new RegExp( ''
  18740. + '^'
  18741. + _directoryRe
  18742. + _nodeRe
  18743. + _objectRe
  18744. + _propertyRe
  18745. + '$'
  18746. );
  18747. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  18748. class Composite {
  18749. constructor( targetGroup, path, optionalParsedPath ) {
  18750. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  18751. this._targetGroup = targetGroup;
  18752. this._bindings = targetGroup.subscribe_( path, parsedPath );
  18753. }
  18754. getValue( array, offset ) {
  18755. this.bind(); // bind all binding
  18756. const firstValidIndex = this._targetGroup.nCachedObjects_,
  18757. binding = this._bindings[ firstValidIndex ];
  18758. // and only call .getValue on the first
  18759. if ( binding !== undefined ) binding.getValue( array, offset );
  18760. }
  18761. setValue( array, offset ) {
  18762. const bindings = this._bindings;
  18763. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18764. bindings[ i ].setValue( array, offset );
  18765. }
  18766. }
  18767. bind() {
  18768. const bindings = this._bindings;
  18769. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18770. bindings[ i ].bind();
  18771. }
  18772. }
  18773. unbind() {
  18774. const bindings = this._bindings;
  18775. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18776. bindings[ i ].unbind();
  18777. }
  18778. }
  18779. }
  18780. // Note: This class uses a State pattern on a per-method basis:
  18781. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18782. // prototype version of these methods with one that represents
  18783. // the bound state. When the property is not found, the methods
  18784. // become no-ops.
  18785. class PropertyBinding {
  18786. constructor( rootNode, path, parsedPath ) {
  18787. this.path = path;
  18788. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  18789. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  18790. this.rootNode = rootNode;
  18791. // initial state of these methods that calls 'bind'
  18792. this.getValue = this._getValue_unbound;
  18793. this.setValue = this._setValue_unbound;
  18794. }
  18795. static create( root, path, parsedPath ) {
  18796. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  18797. return new PropertyBinding( root, path, parsedPath );
  18798. } else {
  18799. return new PropertyBinding.Composite( root, path, parsedPath );
  18800. }
  18801. }
  18802. /**
  18803. * Replaces spaces with underscores and removes unsupported characters from
  18804. * node names, to ensure compatibility with parseTrackName().
  18805. *
  18806. * @param {string} name Node name to be sanitized.
  18807. * @return {string}
  18808. */
  18809. static sanitizeNodeName( name ) {
  18810. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  18811. }
  18812. static parseTrackName( trackName ) {
  18813. const matches = _trackRe.exec( trackName );
  18814. if ( matches === null ) {
  18815. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  18816. }
  18817. const results = {
  18818. // directoryName: matches[ 1 ], // (tschw) currently unused
  18819. nodeName: matches[ 2 ],
  18820. objectName: matches[ 3 ],
  18821. objectIndex: matches[ 4 ],
  18822. propertyName: matches[ 5 ], // required
  18823. propertyIndex: matches[ 6 ]
  18824. };
  18825. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  18826. if ( lastDot !== undefined && lastDot !== - 1 ) {
  18827. const objectName = results.nodeName.substring( lastDot + 1 );
  18828. // Object names must be checked against an allowlist. Otherwise, there
  18829. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  18830. // 'bar' could be the objectName, or part of a nodeName (which can
  18831. // include '.' characters).
  18832. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  18833. results.nodeName = results.nodeName.substring( 0, lastDot );
  18834. results.objectName = objectName;
  18835. }
  18836. }
  18837. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  18838. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  18839. }
  18840. return results;
  18841. }
  18842. static findNode( root, nodeName ) {
  18843. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  18844. return root;
  18845. }
  18846. // search into skeleton bones.
  18847. if ( root.skeleton ) {
  18848. const bone = root.skeleton.getBoneByName( nodeName );
  18849. if ( bone !== undefined ) {
  18850. return bone;
  18851. }
  18852. }
  18853. // search into node subtree.
  18854. if ( root.children ) {
  18855. const searchNodeSubtree = function ( children ) {
  18856. for ( let i = 0; i < children.length; i ++ ) {
  18857. const childNode = children[ i ];
  18858. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  18859. return childNode;
  18860. }
  18861. const result = searchNodeSubtree( childNode.children );
  18862. if ( result ) return result;
  18863. }
  18864. return null;
  18865. };
  18866. const subTreeNode = searchNodeSubtree( root.children );
  18867. if ( subTreeNode ) {
  18868. return subTreeNode;
  18869. }
  18870. }
  18871. return null;
  18872. }
  18873. // these are used to "bind" a nonexistent property
  18874. _getValue_unavailable() {}
  18875. _setValue_unavailable() {}
  18876. // Getters
  18877. _getValue_direct( buffer, offset ) {
  18878. buffer[ offset ] = this.targetObject[ this.propertyName ];
  18879. }
  18880. _getValue_array( buffer, offset ) {
  18881. const source = this.resolvedProperty;
  18882. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  18883. buffer[ offset ++ ] = source[ i ];
  18884. }
  18885. }
  18886. _getValue_arrayElement( buffer, offset ) {
  18887. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  18888. }
  18889. _getValue_toArray( buffer, offset ) {
  18890. this.resolvedProperty.toArray( buffer, offset );
  18891. }
  18892. // Direct
  18893. _setValue_direct( buffer, offset ) {
  18894. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18895. }
  18896. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  18897. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18898. this.targetObject.needsUpdate = true;
  18899. }
  18900. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18901. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18902. this.targetObject.matrixWorldNeedsUpdate = true;
  18903. }
  18904. // EntireArray
  18905. _setValue_array( buffer, offset ) {
  18906. const dest = this.resolvedProperty;
  18907. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18908. dest[ i ] = buffer[ offset ++ ];
  18909. }
  18910. }
  18911. _setValue_array_setNeedsUpdate( buffer, offset ) {
  18912. const dest = this.resolvedProperty;
  18913. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18914. dest[ i ] = buffer[ offset ++ ];
  18915. }
  18916. this.targetObject.needsUpdate = true;
  18917. }
  18918. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18919. const dest = this.resolvedProperty;
  18920. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18921. dest[ i ] = buffer[ offset ++ ];
  18922. }
  18923. this.targetObject.matrixWorldNeedsUpdate = true;
  18924. }
  18925. // ArrayElement
  18926. _setValue_arrayElement( buffer, offset ) {
  18927. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18928. }
  18929. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  18930. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18931. this.targetObject.needsUpdate = true;
  18932. }
  18933. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18934. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18935. this.targetObject.matrixWorldNeedsUpdate = true;
  18936. }
  18937. // HasToFromArray
  18938. _setValue_fromArray( buffer, offset ) {
  18939. this.resolvedProperty.fromArray( buffer, offset );
  18940. }
  18941. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  18942. this.resolvedProperty.fromArray( buffer, offset );
  18943. this.targetObject.needsUpdate = true;
  18944. }
  18945. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18946. this.resolvedProperty.fromArray( buffer, offset );
  18947. this.targetObject.matrixWorldNeedsUpdate = true;
  18948. }
  18949. _getValue_unbound( targetArray, offset ) {
  18950. this.bind();
  18951. this.getValue( targetArray, offset );
  18952. }
  18953. _setValue_unbound( sourceArray, offset ) {
  18954. this.bind();
  18955. this.setValue( sourceArray, offset );
  18956. }
  18957. // create getter / setter pair for a property in the scene graph
  18958. bind() {
  18959. let targetObject = this.node;
  18960. const parsedPath = this.parsedPath;
  18961. const objectName = parsedPath.objectName;
  18962. const propertyName = parsedPath.propertyName;
  18963. let propertyIndex = parsedPath.propertyIndex;
  18964. if ( ! targetObject ) {
  18965. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  18966. this.node = targetObject;
  18967. }
  18968. // set fail state so we can just 'return' on error
  18969. this.getValue = this._getValue_unavailable;
  18970. this.setValue = this._setValue_unavailable;
  18971. // ensure there is a value node
  18972. if ( ! targetObject ) {
  18973. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  18974. return;
  18975. }
  18976. if ( objectName ) {
  18977. let objectIndex = parsedPath.objectIndex;
  18978. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  18979. switch ( objectName ) {
  18980. case 'materials':
  18981. if ( ! targetObject.material ) {
  18982. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18983. return;
  18984. }
  18985. if ( ! targetObject.material.materials ) {
  18986. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  18987. return;
  18988. }
  18989. targetObject = targetObject.material.materials;
  18990. break;
  18991. case 'bones':
  18992. if ( ! targetObject.skeleton ) {
  18993. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  18994. return;
  18995. }
  18996. // potential future optimization: skip this if propertyIndex is already an integer
  18997. // and convert the integer string to a true integer.
  18998. targetObject = targetObject.skeleton.bones;
  18999. // support resolving morphTarget names into indices.
  19000. for ( let i = 0; i < targetObject.length; i ++ ) {
  19001. if ( targetObject[ i ].name === objectIndex ) {
  19002. objectIndex = i;
  19003. break;
  19004. }
  19005. }
  19006. break;
  19007. case 'map':
  19008. if ( 'map' in targetObject ) {
  19009. targetObject = targetObject.map;
  19010. break;
  19011. }
  19012. if ( ! targetObject.material ) {
  19013. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  19014. return;
  19015. }
  19016. if ( ! targetObject.material.map ) {
  19017. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  19018. return;
  19019. }
  19020. targetObject = targetObject.material.map;
  19021. break;
  19022. default:
  19023. if ( targetObject[ objectName ] === undefined ) {
  19024. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  19025. return;
  19026. }
  19027. targetObject = targetObject[ objectName ];
  19028. }
  19029. if ( objectIndex !== undefined ) {
  19030. if ( targetObject[ objectIndex ] === undefined ) {
  19031. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  19032. return;
  19033. }
  19034. targetObject = targetObject[ objectIndex ];
  19035. }
  19036. }
  19037. // resolve property
  19038. const nodeProperty = targetObject[ propertyName ];
  19039. if ( nodeProperty === undefined ) {
  19040. const nodeName = parsedPath.nodeName;
  19041. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  19042. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  19043. return;
  19044. }
  19045. // determine versioning scheme
  19046. let versioning = this.Versioning.None;
  19047. this.targetObject = targetObject;
  19048. if ( targetObject.needsUpdate !== undefined ) { // material
  19049. versioning = this.Versioning.NeedsUpdate;
  19050. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  19051. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  19052. }
  19053. // determine how the property gets bound
  19054. let bindingType = this.BindingType.Direct;
  19055. if ( propertyIndex !== undefined ) {
  19056. // access a sub element of the property array (only primitives are supported right now)
  19057. if ( propertyName === 'morphTargetInfluences' ) {
  19058. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  19059. // support resolving morphTarget names into indices.
  19060. if ( ! targetObject.geometry ) {
  19061. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  19062. return;
  19063. }
  19064. if ( ! targetObject.geometry.morphAttributes ) {
  19065. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  19066. return;
  19067. }
  19068. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  19069. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  19070. }
  19071. }
  19072. bindingType = this.BindingType.ArrayElement;
  19073. this.resolvedProperty = nodeProperty;
  19074. this.propertyIndex = propertyIndex;
  19075. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  19076. // must use copy for Object3D.Euler/Quaternion
  19077. bindingType = this.BindingType.HasFromToArray;
  19078. this.resolvedProperty = nodeProperty;
  19079. } else if ( Array.isArray( nodeProperty ) ) {
  19080. bindingType = this.BindingType.EntireArray;
  19081. this.resolvedProperty = nodeProperty;
  19082. } else {
  19083. this.propertyName = propertyName;
  19084. }
  19085. // select getter / setter
  19086. this.getValue = this.GetterByBindingType[ bindingType ];
  19087. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  19088. }
  19089. unbind() {
  19090. this.node = null;
  19091. // back to the prototype version of getValue / setValue
  19092. // note: avoiding to mutate the shape of 'this' via 'delete'
  19093. this.getValue = this._getValue_unbound;
  19094. this.setValue = this._setValue_unbound;
  19095. }
  19096. }
  19097. PropertyBinding.Composite = Composite;
  19098. PropertyBinding.prototype.BindingType = {
  19099. Direct: 0,
  19100. EntireArray: 1,
  19101. ArrayElement: 2,
  19102. HasFromToArray: 3
  19103. };
  19104. PropertyBinding.prototype.Versioning = {
  19105. None: 0,
  19106. NeedsUpdate: 1,
  19107. MatrixWorldNeedsUpdate: 2
  19108. };
  19109. PropertyBinding.prototype.GetterByBindingType = [
  19110. PropertyBinding.prototype._getValue_direct,
  19111. PropertyBinding.prototype._getValue_array,
  19112. PropertyBinding.prototype._getValue_arrayElement,
  19113. PropertyBinding.prototype._getValue_toArray,
  19114. ];
  19115. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  19116. [
  19117. // Direct
  19118. PropertyBinding.prototype._setValue_direct,
  19119. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  19120. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  19121. ], [
  19122. // EntireArray
  19123. PropertyBinding.prototype._setValue_array,
  19124. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  19125. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  19126. ], [
  19127. // ArrayElement
  19128. PropertyBinding.prototype._setValue_arrayElement,
  19129. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  19130. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  19131. ], [
  19132. // HasToFromArray
  19133. PropertyBinding.prototype._setValue_fromArray,
  19134. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  19135. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  19136. ]
  19137. ];
  19138. /**
  19139. *
  19140. * A group of objects that receives a shared animation state.
  19141. *
  19142. * Usage:
  19143. *
  19144. * - Add objects you would otherwise pass as 'root' to the
  19145. * constructor or the .clipAction method of AnimationMixer.
  19146. *
  19147. * - Instead pass this object as 'root'.
  19148. *
  19149. * - You can also add and remove objects later when the mixer
  19150. * is running.
  19151. *
  19152. * Note:
  19153. *
  19154. * Objects of this class appear as one object to the mixer,
  19155. * so cache control of the individual objects must be done
  19156. * on the group.
  19157. *
  19158. * Limitation:
  19159. *
  19160. * - The animated properties must be compatible among the
  19161. * all objects in the group.
  19162. *
  19163. * - A single property can either be controlled through a
  19164. * target group or directly, but not both.
  19165. */
  19166. class AnimationObjectGroup {
  19167. constructor() {
  19168. this.isAnimationObjectGroup = true;
  19169. this.uuid = generateUUID();
  19170. // cached objects followed by the active ones
  19171. this._objects = Array.prototype.slice.call( arguments );
  19172. this.nCachedObjects_ = 0; // threshold
  19173. // note: read by PropertyBinding.Composite
  19174. const indices = {};
  19175. this._indicesByUUID = indices; // for bookkeeping
  19176. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19177. indices[ arguments[ i ].uuid ] = i;
  19178. }
  19179. this._paths = []; // inside: string
  19180. this._parsedPaths = []; // inside: { we don't care, here }
  19181. this._bindings = []; // inside: Array< PropertyBinding >
  19182. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  19183. const scope = this;
  19184. this.stats = {
  19185. objects: {
  19186. get total() {
  19187. return scope._objects.length;
  19188. },
  19189. get inUse() {
  19190. return this.total - scope.nCachedObjects_;
  19191. }
  19192. },
  19193. get bindingsPerObject() {
  19194. return scope._bindings.length;
  19195. }
  19196. };
  19197. }
  19198. add() {
  19199. const objects = this._objects,
  19200. indicesByUUID = this._indicesByUUID,
  19201. paths = this._paths,
  19202. parsedPaths = this._parsedPaths,
  19203. bindings = this._bindings,
  19204. nBindings = bindings.length;
  19205. let knownObject = undefined,
  19206. nObjects = objects.length,
  19207. nCachedObjects = this.nCachedObjects_;
  19208. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19209. const object = arguments[ i ],
  19210. uuid = object.uuid;
  19211. let index = indicesByUUID[ uuid ];
  19212. if ( index === undefined ) {
  19213. // unknown object -> add it to the ACTIVE region
  19214. index = nObjects ++;
  19215. indicesByUUID[ uuid ] = index;
  19216. objects.push( object );
  19217. // accounting is done, now do the same for all bindings
  19218. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19219. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  19220. }
  19221. } else if ( index < nCachedObjects ) {
  19222. knownObject = objects[ index ];
  19223. // move existing object to the ACTIVE region
  19224. const firstActiveIndex = -- nCachedObjects,
  19225. lastCachedObject = objects[ firstActiveIndex ];
  19226. indicesByUUID[ lastCachedObject.uuid ] = index;
  19227. objects[ index ] = lastCachedObject;
  19228. indicesByUUID[ uuid ] = firstActiveIndex;
  19229. objects[ firstActiveIndex ] = object;
  19230. // accounting is done, now do the same for all bindings
  19231. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19232. const bindingsForPath = bindings[ j ],
  19233. lastCached = bindingsForPath[ firstActiveIndex ];
  19234. let binding = bindingsForPath[ index ];
  19235. bindingsForPath[ index ] = lastCached;
  19236. if ( binding === undefined ) {
  19237. // since we do not bother to create new bindings
  19238. // for objects that are cached, the binding may
  19239. // or may not exist
  19240. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  19241. }
  19242. bindingsForPath[ firstActiveIndex ] = binding;
  19243. }
  19244. } else if ( objects[ index ] !== knownObject ) {
  19245. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  19246. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  19247. } // else the object is already where we want it to be
  19248. } // for arguments
  19249. this.nCachedObjects_ = nCachedObjects;
  19250. }
  19251. remove() {
  19252. const objects = this._objects,
  19253. indicesByUUID = this._indicesByUUID,
  19254. bindings = this._bindings,
  19255. nBindings = bindings.length;
  19256. let nCachedObjects = this.nCachedObjects_;
  19257. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19258. const object = arguments[ i ],
  19259. uuid = object.uuid,
  19260. index = indicesByUUID[ uuid ];
  19261. if ( index !== undefined && index >= nCachedObjects ) {
  19262. // move existing object into the CACHED region
  19263. const lastCachedIndex = nCachedObjects ++,
  19264. firstActiveObject = objects[ lastCachedIndex ];
  19265. indicesByUUID[ firstActiveObject.uuid ] = index;
  19266. objects[ index ] = firstActiveObject;
  19267. indicesByUUID[ uuid ] = lastCachedIndex;
  19268. objects[ lastCachedIndex ] = object;
  19269. // accounting is done, now do the same for all bindings
  19270. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19271. const bindingsForPath = bindings[ j ],
  19272. firstActive = bindingsForPath[ lastCachedIndex ],
  19273. binding = bindingsForPath[ index ];
  19274. bindingsForPath[ index ] = firstActive;
  19275. bindingsForPath[ lastCachedIndex ] = binding;
  19276. }
  19277. }
  19278. } // for arguments
  19279. this.nCachedObjects_ = nCachedObjects;
  19280. }
  19281. // remove & forget
  19282. uncache() {
  19283. const objects = this._objects,
  19284. indicesByUUID = this._indicesByUUID,
  19285. bindings = this._bindings,
  19286. nBindings = bindings.length;
  19287. let nCachedObjects = this.nCachedObjects_,
  19288. nObjects = objects.length;
  19289. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19290. const object = arguments[ i ],
  19291. uuid = object.uuid,
  19292. index = indicesByUUID[ uuid ];
  19293. if ( index !== undefined ) {
  19294. delete indicesByUUID[ uuid ];
  19295. if ( index < nCachedObjects ) {
  19296. // object is cached, shrink the CACHED region
  19297. const firstActiveIndex = -- nCachedObjects,
  19298. lastCachedObject = objects[ firstActiveIndex ],
  19299. lastIndex = -- nObjects,
  19300. lastObject = objects[ lastIndex ];
  19301. // last cached object takes this object's place
  19302. indicesByUUID[ lastCachedObject.uuid ] = index;
  19303. objects[ index ] = lastCachedObject;
  19304. // last object goes to the activated slot and pop
  19305. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19306. objects[ firstActiveIndex ] = lastObject;
  19307. objects.pop();
  19308. // accounting is done, now do the same for all bindings
  19309. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19310. const bindingsForPath = bindings[ j ],
  19311. lastCached = bindingsForPath[ firstActiveIndex ],
  19312. last = bindingsForPath[ lastIndex ];
  19313. bindingsForPath[ index ] = lastCached;
  19314. bindingsForPath[ firstActiveIndex ] = last;
  19315. bindingsForPath.pop();
  19316. }
  19317. } else {
  19318. // object is active, just swap with the last and pop
  19319. const lastIndex = -- nObjects,
  19320. lastObject = objects[ lastIndex ];
  19321. if ( lastIndex > 0 ) {
  19322. indicesByUUID[ lastObject.uuid ] = index;
  19323. }
  19324. objects[ index ] = lastObject;
  19325. objects.pop();
  19326. // accounting is done, now do the same for all bindings
  19327. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19328. const bindingsForPath = bindings[ j ];
  19329. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19330. bindingsForPath.pop();
  19331. }
  19332. } // cached or active
  19333. } // if object is known
  19334. } // for arguments
  19335. this.nCachedObjects_ = nCachedObjects;
  19336. }
  19337. // Internal interface used by befriended PropertyBinding.Composite:
  19338. subscribe_( path, parsedPath ) {
  19339. // returns an array of bindings for the given path that is changed
  19340. // according to the contained objects in the group
  19341. const indicesByPath = this._bindingsIndicesByPath;
  19342. let index = indicesByPath[ path ];
  19343. const bindings = this._bindings;
  19344. if ( index !== undefined ) return bindings[ index ];
  19345. const paths = this._paths,
  19346. parsedPaths = this._parsedPaths,
  19347. objects = this._objects,
  19348. nObjects = objects.length,
  19349. nCachedObjects = this.nCachedObjects_,
  19350. bindingsForPath = new Array( nObjects );
  19351. index = bindings.length;
  19352. indicesByPath[ path ] = index;
  19353. paths.push( path );
  19354. parsedPaths.push( parsedPath );
  19355. bindings.push( bindingsForPath );
  19356. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  19357. const object = objects[ i ];
  19358. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  19359. }
  19360. return bindingsForPath;
  19361. }
  19362. unsubscribe_( path ) {
  19363. // tells the group to forget about a property path and no longer
  19364. // update the array previously obtained with 'subscribe_'
  19365. const indicesByPath = this._bindingsIndicesByPath,
  19366. index = indicesByPath[ path ];
  19367. if ( index !== undefined ) {
  19368. const paths = this._paths,
  19369. parsedPaths = this._parsedPaths,
  19370. bindings = this._bindings,
  19371. lastBindingsIndex = bindings.length - 1,
  19372. lastBindings = bindings[ lastBindingsIndex ],
  19373. lastBindingsPath = path[ lastBindingsIndex ];
  19374. indicesByPath[ lastBindingsPath ] = index;
  19375. bindings[ index ] = lastBindings;
  19376. bindings.pop();
  19377. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  19378. parsedPaths.pop();
  19379. paths[ index ] = paths[ lastBindingsIndex ];
  19380. paths.pop();
  19381. }
  19382. }
  19383. }
  19384. class AnimationAction {
  19385. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  19386. this._mixer = mixer;
  19387. this._clip = clip;
  19388. this._localRoot = localRoot;
  19389. this.blendMode = blendMode;
  19390. const tracks = clip.tracks,
  19391. nTracks = tracks.length,
  19392. interpolants = new Array( nTracks );
  19393. const interpolantSettings = {
  19394. endingStart: ZeroCurvatureEnding,
  19395. endingEnd: ZeroCurvatureEnding
  19396. };
  19397. for ( let i = 0; i !== nTracks; ++ i ) {
  19398. const interpolant = tracks[ i ].createInterpolant( null );
  19399. interpolants[ i ] = interpolant;
  19400. interpolant.settings = interpolantSettings;
  19401. }
  19402. this._interpolantSettings = interpolantSettings;
  19403. this._interpolants = interpolants; // bound by the mixer
  19404. // inside: PropertyMixer (managed by the mixer)
  19405. this._propertyBindings = new Array( nTracks );
  19406. this._cacheIndex = null; // for the memory manager
  19407. this._byClipCacheIndex = null; // for the memory manager
  19408. this._timeScaleInterpolant = null;
  19409. this._weightInterpolant = null;
  19410. this.loop = LoopRepeat;
  19411. this._loopCount = - 1;
  19412. // global mixer time when the action is to be started
  19413. // it's set back to 'null' upon start of the action
  19414. this._startTime = null;
  19415. // scaled local time of the action
  19416. // gets clamped or wrapped to 0..clip.duration according to loop
  19417. this.time = 0;
  19418. this.timeScale = 1;
  19419. this._effectiveTimeScale = 1;
  19420. this.weight = 1;
  19421. this._effectiveWeight = 1;
  19422. this.repetitions = Infinity; // no. of repetitions when looping
  19423. this.paused = false; // true -> zero effective time scale
  19424. this.enabled = true; // false -> zero effective weight
  19425. this.clampWhenFinished = false;// keep feeding the last frame?
  19426. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  19427. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  19428. }
  19429. // State & Scheduling
  19430. play() {
  19431. this._mixer._activateAction( this );
  19432. return this;
  19433. }
  19434. stop() {
  19435. this._mixer._deactivateAction( this );
  19436. return this.reset();
  19437. }
  19438. reset() {
  19439. this.paused = false;
  19440. this.enabled = true;
  19441. this.time = 0; // restart clip
  19442. this._loopCount = - 1;// forget previous loops
  19443. this._startTime = null;// forget scheduling
  19444. return this.stopFading().stopWarping();
  19445. }
  19446. isRunning() {
  19447. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  19448. this._startTime === null && this._mixer._isActiveAction( this );
  19449. }
  19450. // return true when play has been called
  19451. isScheduled() {
  19452. return this._mixer._isActiveAction( this );
  19453. }
  19454. startAt( time ) {
  19455. this._startTime = time;
  19456. return this;
  19457. }
  19458. setLoop( mode, repetitions ) {
  19459. this.loop = mode;
  19460. this.repetitions = repetitions;
  19461. return this;
  19462. }
  19463. // Weight
  19464. // set the weight stopping any scheduled fading
  19465. // although .enabled = false yields an effective weight of zero, this
  19466. // method does *not* change .enabled, because it would be confusing
  19467. setEffectiveWeight( weight ) {
  19468. this.weight = weight;
  19469. // note: same logic as when updated at runtime
  19470. this._effectiveWeight = this.enabled ? weight : 0;
  19471. return this.stopFading();
  19472. }
  19473. // return the weight considering fading and .enabled
  19474. getEffectiveWeight() {
  19475. return this._effectiveWeight;
  19476. }
  19477. fadeIn( duration ) {
  19478. return this._scheduleFading( duration, 0, 1 );
  19479. }
  19480. fadeOut( duration ) {
  19481. return this._scheduleFading( duration, 1, 0 );
  19482. }
  19483. crossFadeFrom( fadeOutAction, duration, warp ) {
  19484. fadeOutAction.fadeOut( duration );
  19485. this.fadeIn( duration );
  19486. if ( warp ) {
  19487. const fadeInDuration = this._clip.duration,
  19488. fadeOutDuration = fadeOutAction._clip.duration,
  19489. startEndRatio = fadeOutDuration / fadeInDuration,
  19490. endStartRatio = fadeInDuration / fadeOutDuration;
  19491. fadeOutAction.warp( 1.0, startEndRatio, duration );
  19492. this.warp( endStartRatio, 1.0, duration );
  19493. }
  19494. return this;
  19495. }
  19496. crossFadeTo( fadeInAction, duration, warp ) {
  19497. return fadeInAction.crossFadeFrom( this, duration, warp );
  19498. }
  19499. stopFading() {
  19500. const weightInterpolant = this._weightInterpolant;
  19501. if ( weightInterpolant !== null ) {
  19502. this._weightInterpolant = null;
  19503. this._mixer._takeBackControlInterpolant( weightInterpolant );
  19504. }
  19505. return this;
  19506. }
  19507. // Time Scale Control
  19508. // set the time scale stopping any scheduled warping
  19509. // although .paused = true yields an effective time scale of zero, this
  19510. // method does *not* change .paused, because it would be confusing
  19511. setEffectiveTimeScale( timeScale ) {
  19512. this.timeScale = timeScale;
  19513. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  19514. return this.stopWarping();
  19515. }
  19516. // return the time scale considering warping and .paused
  19517. getEffectiveTimeScale() {
  19518. return this._effectiveTimeScale;
  19519. }
  19520. setDuration( duration ) {
  19521. this.timeScale = this._clip.duration / duration;
  19522. return this.stopWarping();
  19523. }
  19524. syncWith( action ) {
  19525. this.time = action.time;
  19526. this.timeScale = action.timeScale;
  19527. return this.stopWarping();
  19528. }
  19529. halt( duration ) {
  19530. return this.warp( this._effectiveTimeScale, 0, duration );
  19531. }
  19532. warp( startTimeScale, endTimeScale, duration ) {
  19533. const mixer = this._mixer,
  19534. now = mixer.time,
  19535. timeScale = this.timeScale;
  19536. let interpolant = this._timeScaleInterpolant;
  19537. if ( interpolant === null ) {
  19538. interpolant = mixer._lendControlInterpolant();
  19539. this._timeScaleInterpolant = interpolant;
  19540. }
  19541. const times = interpolant.parameterPositions,
  19542. values = interpolant.sampleValues;
  19543. times[ 0 ] = now;
  19544. times[ 1 ] = now + duration;
  19545. values[ 0 ] = startTimeScale / timeScale;
  19546. values[ 1 ] = endTimeScale / timeScale;
  19547. return this;
  19548. }
  19549. stopWarping() {
  19550. const timeScaleInterpolant = this._timeScaleInterpolant;
  19551. if ( timeScaleInterpolant !== null ) {
  19552. this._timeScaleInterpolant = null;
  19553. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  19554. }
  19555. return this;
  19556. }
  19557. // Object Accessors
  19558. getMixer() {
  19559. return this._mixer;
  19560. }
  19561. getClip() {
  19562. return this._clip;
  19563. }
  19564. getRoot() {
  19565. return this._localRoot || this._mixer._root;
  19566. }
  19567. // Interna
  19568. _update( time, deltaTime, timeDirection, accuIndex ) {
  19569. // called by the mixer
  19570. if ( ! this.enabled ) {
  19571. // call ._updateWeight() to update ._effectiveWeight
  19572. this._updateWeight( time );
  19573. return;
  19574. }
  19575. const startTime = this._startTime;
  19576. if ( startTime !== null ) {
  19577. // check for scheduled start of action
  19578. const timeRunning = ( time - startTime ) * timeDirection;
  19579. if ( timeRunning < 0 || timeDirection === 0 ) {
  19580. deltaTime = 0;
  19581. } else {
  19582. this._startTime = null; // unschedule
  19583. deltaTime = timeDirection * timeRunning;
  19584. }
  19585. }
  19586. // apply time scale and advance time
  19587. deltaTime *= this._updateTimeScale( time );
  19588. const clipTime = this._updateTime( deltaTime );
  19589. // note: _updateTime may disable the action resulting in
  19590. // an effective weight of 0
  19591. const weight = this._updateWeight( time );
  19592. if ( weight > 0 ) {
  19593. const interpolants = this._interpolants;
  19594. const propertyMixers = this._propertyBindings;
  19595. switch ( this.blendMode ) {
  19596. case AdditiveAnimationBlendMode:
  19597. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19598. interpolants[ j ].evaluate( clipTime );
  19599. propertyMixers[ j ].accumulateAdditive( weight );
  19600. }
  19601. break;
  19602. case NormalAnimationBlendMode:
  19603. default:
  19604. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19605. interpolants[ j ].evaluate( clipTime );
  19606. propertyMixers[ j ].accumulate( accuIndex, weight );
  19607. }
  19608. }
  19609. }
  19610. }
  19611. _updateWeight( time ) {
  19612. let weight = 0;
  19613. if ( this.enabled ) {
  19614. weight = this.weight;
  19615. const interpolant = this._weightInterpolant;
  19616. if ( interpolant !== null ) {
  19617. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19618. weight *= interpolantValue;
  19619. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19620. this.stopFading();
  19621. if ( interpolantValue === 0 ) {
  19622. // faded out, disable
  19623. this.enabled = false;
  19624. }
  19625. }
  19626. }
  19627. }
  19628. this._effectiveWeight = weight;
  19629. return weight;
  19630. }
  19631. _updateTimeScale( time ) {
  19632. let timeScale = 0;
  19633. if ( ! this.paused ) {
  19634. timeScale = this.timeScale;
  19635. const interpolant = this._timeScaleInterpolant;
  19636. if ( interpolant !== null ) {
  19637. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19638. timeScale *= interpolantValue;
  19639. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19640. this.stopWarping();
  19641. if ( timeScale === 0 ) {
  19642. // motion has halted, pause
  19643. this.paused = true;
  19644. } else {
  19645. // warp done - apply final time scale
  19646. this.timeScale = timeScale;
  19647. }
  19648. }
  19649. }
  19650. }
  19651. this._effectiveTimeScale = timeScale;
  19652. return timeScale;
  19653. }
  19654. _updateTime( deltaTime ) {
  19655. const duration = this._clip.duration;
  19656. const loop = this.loop;
  19657. let time = this.time + deltaTime;
  19658. let loopCount = this._loopCount;
  19659. const pingPong = ( loop === LoopPingPong );
  19660. if ( deltaTime === 0 ) {
  19661. if ( loopCount === - 1 ) return time;
  19662. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  19663. }
  19664. if ( loop === LoopOnce ) {
  19665. if ( loopCount === - 1 ) {
  19666. // just started
  19667. this._loopCount = 0;
  19668. this._setEndings( true, true, false );
  19669. }
  19670. handle_stop: {
  19671. if ( time >= duration ) {
  19672. time = duration;
  19673. } else if ( time < 0 ) {
  19674. time = 0;
  19675. } else {
  19676. this.time = time;
  19677. break handle_stop;
  19678. }
  19679. if ( this.clampWhenFinished ) this.paused = true;
  19680. else this.enabled = false;
  19681. this.time = time;
  19682. this._mixer.dispatchEvent( {
  19683. type: 'finished', action: this,
  19684. direction: deltaTime < 0 ? - 1 : 1
  19685. } );
  19686. }
  19687. } else { // repetitive Repeat or PingPong
  19688. if ( loopCount === - 1 ) {
  19689. // just started
  19690. if ( deltaTime >= 0 ) {
  19691. loopCount = 0;
  19692. this._setEndings( true, this.repetitions === 0, pingPong );
  19693. } else {
  19694. // when looping in reverse direction, the initial
  19695. // transition through zero counts as a repetition,
  19696. // so leave loopCount at -1
  19697. this._setEndings( this.repetitions === 0, true, pingPong );
  19698. }
  19699. }
  19700. if ( time >= duration || time < 0 ) {
  19701. // wrap around
  19702. const loopDelta = Math.floor( time / duration ); // signed
  19703. time -= duration * loopDelta;
  19704. loopCount += Math.abs( loopDelta );
  19705. const pending = this.repetitions - loopCount;
  19706. if ( pending <= 0 ) {
  19707. // have to stop (switch state, clamp time, fire event)
  19708. if ( this.clampWhenFinished ) this.paused = true;
  19709. else this.enabled = false;
  19710. time = deltaTime > 0 ? duration : 0;
  19711. this.time = time;
  19712. this._mixer.dispatchEvent( {
  19713. type: 'finished', action: this,
  19714. direction: deltaTime > 0 ? 1 : - 1
  19715. } );
  19716. } else {
  19717. // keep running
  19718. if ( pending === 1 ) {
  19719. // entering the last round
  19720. const atStart = deltaTime < 0;
  19721. this._setEndings( atStart, ! atStart, pingPong );
  19722. } else {
  19723. this._setEndings( false, false, pingPong );
  19724. }
  19725. this._loopCount = loopCount;
  19726. this.time = time;
  19727. this._mixer.dispatchEvent( {
  19728. type: 'loop', action: this, loopDelta: loopDelta
  19729. } );
  19730. }
  19731. } else {
  19732. this.time = time;
  19733. }
  19734. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  19735. // invert time for the "pong round"
  19736. return duration - time;
  19737. }
  19738. }
  19739. return time;
  19740. }
  19741. _setEndings( atStart, atEnd, pingPong ) {
  19742. const settings = this._interpolantSettings;
  19743. if ( pingPong ) {
  19744. settings.endingStart = ZeroSlopeEnding;
  19745. settings.endingEnd = ZeroSlopeEnding;
  19746. } else {
  19747. // assuming for LoopOnce atStart == atEnd == true
  19748. if ( atStart ) {
  19749. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19750. } else {
  19751. settings.endingStart = WrapAroundEnding;
  19752. }
  19753. if ( atEnd ) {
  19754. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19755. } else {
  19756. settings.endingEnd = WrapAroundEnding;
  19757. }
  19758. }
  19759. }
  19760. _scheduleFading( duration, weightNow, weightThen ) {
  19761. const mixer = this._mixer, now = mixer.time;
  19762. let interpolant = this._weightInterpolant;
  19763. if ( interpolant === null ) {
  19764. interpolant = mixer._lendControlInterpolant();
  19765. this._weightInterpolant = interpolant;
  19766. }
  19767. const times = interpolant.parameterPositions,
  19768. values = interpolant.sampleValues;
  19769. times[ 0 ] = now;
  19770. values[ 0 ] = weightNow;
  19771. times[ 1 ] = now + duration;
  19772. values[ 1 ] = weightThen;
  19773. return this;
  19774. }
  19775. }
  19776. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  19777. class AnimationMixer extends EventDispatcher {
  19778. constructor( root ) {
  19779. super();
  19780. this._root = root;
  19781. this._initMemoryManager();
  19782. this._accuIndex = 0;
  19783. this.time = 0;
  19784. this.timeScale = 1.0;
  19785. }
  19786. _bindAction( action, prototypeAction ) {
  19787. const root = action._localRoot || this._root,
  19788. tracks = action._clip.tracks,
  19789. nTracks = tracks.length,
  19790. bindings = action._propertyBindings,
  19791. interpolants = action._interpolants,
  19792. rootUuid = root.uuid,
  19793. bindingsByRoot = this._bindingsByRootAndName;
  19794. let bindingsByName = bindingsByRoot[ rootUuid ];
  19795. if ( bindingsByName === undefined ) {
  19796. bindingsByName = {};
  19797. bindingsByRoot[ rootUuid ] = bindingsByName;
  19798. }
  19799. for ( let i = 0; i !== nTracks; ++ i ) {
  19800. const track = tracks[ i ],
  19801. trackName = track.name;
  19802. let binding = bindingsByName[ trackName ];
  19803. if ( binding !== undefined ) {
  19804. ++ binding.referenceCount;
  19805. bindings[ i ] = binding;
  19806. } else {
  19807. binding = bindings[ i ];
  19808. if ( binding !== undefined ) {
  19809. // existing binding, make sure the cache knows
  19810. if ( binding._cacheIndex === null ) {
  19811. ++ binding.referenceCount;
  19812. this._addInactiveBinding( binding, rootUuid, trackName );
  19813. }
  19814. continue;
  19815. }
  19816. const path = prototypeAction && prototypeAction.
  19817. _propertyBindings[ i ].binding.parsedPath;
  19818. binding = new PropertyMixer(
  19819. PropertyBinding.create( root, trackName, path ),
  19820. track.ValueTypeName, track.getValueSize() );
  19821. ++ binding.referenceCount;
  19822. this._addInactiveBinding( binding, rootUuid, trackName );
  19823. bindings[ i ] = binding;
  19824. }
  19825. interpolants[ i ].resultBuffer = binding.buffer;
  19826. }
  19827. }
  19828. _activateAction( action ) {
  19829. if ( ! this._isActiveAction( action ) ) {
  19830. if ( action._cacheIndex === null ) {
  19831. // this action has been forgotten by the cache, but the user
  19832. // appears to be still using it -> rebind
  19833. const rootUuid = ( action._localRoot || this._root ).uuid,
  19834. clipUuid = action._clip.uuid,
  19835. actionsForClip = this._actionsByClip[ clipUuid ];
  19836. this._bindAction( action,
  19837. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19838. this._addInactiveAction( action, clipUuid, rootUuid );
  19839. }
  19840. const bindings = action._propertyBindings;
  19841. // increment reference counts / sort out state
  19842. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19843. const binding = bindings[ i ];
  19844. if ( binding.useCount ++ === 0 ) {
  19845. this._lendBinding( binding );
  19846. binding.saveOriginalState();
  19847. }
  19848. }
  19849. this._lendAction( action );
  19850. }
  19851. }
  19852. _deactivateAction( action ) {
  19853. if ( this._isActiveAction( action ) ) {
  19854. const bindings = action._propertyBindings;
  19855. // decrement reference counts / sort out state
  19856. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19857. const binding = bindings[ i ];
  19858. if ( -- binding.useCount === 0 ) {
  19859. binding.restoreOriginalState();
  19860. this._takeBackBinding( binding );
  19861. }
  19862. }
  19863. this._takeBackAction( action );
  19864. }
  19865. }
  19866. // Memory manager
  19867. _initMemoryManager() {
  19868. this._actions = []; // 'nActiveActions' followed by inactive ones
  19869. this._nActiveActions = 0;
  19870. this._actionsByClip = {};
  19871. // inside:
  19872. // {
  19873. // knownActions: Array< AnimationAction > - used as prototypes
  19874. // actionByRoot: AnimationAction - lookup
  19875. // }
  19876. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19877. this._nActiveBindings = 0;
  19878. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19879. this._controlInterpolants = []; // same game as above
  19880. this._nActiveControlInterpolants = 0;
  19881. const scope = this;
  19882. this.stats = {
  19883. actions: {
  19884. get total() {
  19885. return scope._actions.length;
  19886. },
  19887. get inUse() {
  19888. return scope._nActiveActions;
  19889. }
  19890. },
  19891. bindings: {
  19892. get total() {
  19893. return scope._bindings.length;
  19894. },
  19895. get inUse() {
  19896. return scope._nActiveBindings;
  19897. }
  19898. },
  19899. controlInterpolants: {
  19900. get total() {
  19901. return scope._controlInterpolants.length;
  19902. },
  19903. get inUse() {
  19904. return scope._nActiveControlInterpolants;
  19905. }
  19906. }
  19907. };
  19908. }
  19909. // Memory management for AnimationAction objects
  19910. _isActiveAction( action ) {
  19911. const index = action._cacheIndex;
  19912. return index !== null && index < this._nActiveActions;
  19913. }
  19914. _addInactiveAction( action, clipUuid, rootUuid ) {
  19915. const actions = this._actions,
  19916. actionsByClip = this._actionsByClip;
  19917. let actionsForClip = actionsByClip[ clipUuid ];
  19918. if ( actionsForClip === undefined ) {
  19919. actionsForClip = {
  19920. knownActions: [ action ],
  19921. actionByRoot: {}
  19922. };
  19923. action._byClipCacheIndex = 0;
  19924. actionsByClip[ clipUuid ] = actionsForClip;
  19925. } else {
  19926. const knownActions = actionsForClip.knownActions;
  19927. action._byClipCacheIndex = knownActions.length;
  19928. knownActions.push( action );
  19929. }
  19930. action._cacheIndex = actions.length;
  19931. actions.push( action );
  19932. actionsForClip.actionByRoot[ rootUuid ] = action;
  19933. }
  19934. _removeInactiveAction( action ) {
  19935. const actions = this._actions,
  19936. lastInactiveAction = actions[ actions.length - 1 ],
  19937. cacheIndex = action._cacheIndex;
  19938. lastInactiveAction._cacheIndex = cacheIndex;
  19939. actions[ cacheIndex ] = lastInactiveAction;
  19940. actions.pop();
  19941. action._cacheIndex = null;
  19942. const clipUuid = action._clip.uuid,
  19943. actionsByClip = this._actionsByClip,
  19944. actionsForClip = actionsByClip[ clipUuid ],
  19945. knownActionsForClip = actionsForClip.knownActions,
  19946. lastKnownAction =
  19947. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19948. byClipCacheIndex = action._byClipCacheIndex;
  19949. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19950. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19951. knownActionsForClip.pop();
  19952. action._byClipCacheIndex = null;
  19953. const actionByRoot = actionsForClip.actionByRoot,
  19954. rootUuid = ( action._localRoot || this._root ).uuid;
  19955. delete actionByRoot[ rootUuid ];
  19956. if ( knownActionsForClip.length === 0 ) {
  19957. delete actionsByClip[ clipUuid ];
  19958. }
  19959. this._removeInactiveBindingsForAction( action );
  19960. }
  19961. _removeInactiveBindingsForAction( action ) {
  19962. const bindings = action._propertyBindings;
  19963. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19964. const binding = bindings[ i ];
  19965. if ( -- binding.referenceCount === 0 ) {
  19966. this._removeInactiveBinding( binding );
  19967. }
  19968. }
  19969. }
  19970. _lendAction( action ) {
  19971. // [ active actions | inactive actions ]
  19972. // [ active actions >| inactive actions ]
  19973. // s a
  19974. // <-swap->
  19975. // a s
  19976. const actions = this._actions,
  19977. prevIndex = action._cacheIndex,
  19978. lastActiveIndex = this._nActiveActions ++,
  19979. firstInactiveAction = actions[ lastActiveIndex ];
  19980. action._cacheIndex = lastActiveIndex;
  19981. actions[ lastActiveIndex ] = action;
  19982. firstInactiveAction._cacheIndex = prevIndex;
  19983. actions[ prevIndex ] = firstInactiveAction;
  19984. }
  19985. _takeBackAction( action ) {
  19986. // [ active actions | inactive actions ]
  19987. // [ active actions |< inactive actions ]
  19988. // a s
  19989. // <-swap->
  19990. // s a
  19991. const actions = this._actions,
  19992. prevIndex = action._cacheIndex,
  19993. firstInactiveIndex = -- this._nActiveActions,
  19994. lastActiveAction = actions[ firstInactiveIndex ];
  19995. action._cacheIndex = firstInactiveIndex;
  19996. actions[ firstInactiveIndex ] = action;
  19997. lastActiveAction._cacheIndex = prevIndex;
  19998. actions[ prevIndex ] = lastActiveAction;
  19999. }
  20000. // Memory management for PropertyMixer objects
  20001. _addInactiveBinding( binding, rootUuid, trackName ) {
  20002. const bindingsByRoot = this._bindingsByRootAndName,
  20003. bindings = this._bindings;
  20004. let bindingByName = bindingsByRoot[ rootUuid ];
  20005. if ( bindingByName === undefined ) {
  20006. bindingByName = {};
  20007. bindingsByRoot[ rootUuid ] = bindingByName;
  20008. }
  20009. bindingByName[ trackName ] = binding;
  20010. binding._cacheIndex = bindings.length;
  20011. bindings.push( binding );
  20012. }
  20013. _removeInactiveBinding( binding ) {
  20014. const bindings = this._bindings,
  20015. propBinding = binding.binding,
  20016. rootUuid = propBinding.rootNode.uuid,
  20017. trackName = propBinding.path,
  20018. bindingsByRoot = this._bindingsByRootAndName,
  20019. bindingByName = bindingsByRoot[ rootUuid ],
  20020. lastInactiveBinding = bindings[ bindings.length - 1 ],
  20021. cacheIndex = binding._cacheIndex;
  20022. lastInactiveBinding._cacheIndex = cacheIndex;
  20023. bindings[ cacheIndex ] = lastInactiveBinding;
  20024. bindings.pop();
  20025. delete bindingByName[ trackName ];
  20026. if ( Object.keys( bindingByName ).length === 0 ) {
  20027. delete bindingsByRoot[ rootUuid ];
  20028. }
  20029. }
  20030. _lendBinding( binding ) {
  20031. const bindings = this._bindings,
  20032. prevIndex = binding._cacheIndex,
  20033. lastActiveIndex = this._nActiveBindings ++,
  20034. firstInactiveBinding = bindings[ lastActiveIndex ];
  20035. binding._cacheIndex = lastActiveIndex;
  20036. bindings[ lastActiveIndex ] = binding;
  20037. firstInactiveBinding._cacheIndex = prevIndex;
  20038. bindings[ prevIndex ] = firstInactiveBinding;
  20039. }
  20040. _takeBackBinding( binding ) {
  20041. const bindings = this._bindings,
  20042. prevIndex = binding._cacheIndex,
  20043. firstInactiveIndex = -- this._nActiveBindings,
  20044. lastActiveBinding = bindings[ firstInactiveIndex ];
  20045. binding._cacheIndex = firstInactiveIndex;
  20046. bindings[ firstInactiveIndex ] = binding;
  20047. lastActiveBinding._cacheIndex = prevIndex;
  20048. bindings[ prevIndex ] = lastActiveBinding;
  20049. }
  20050. // Memory management of Interpolants for weight and time scale
  20051. _lendControlInterpolant() {
  20052. const interpolants = this._controlInterpolants,
  20053. lastActiveIndex = this._nActiveControlInterpolants ++;
  20054. let interpolant = interpolants[ lastActiveIndex ];
  20055. if ( interpolant === undefined ) {
  20056. interpolant = new LinearInterpolant(
  20057. new Float32Array( 2 ), new Float32Array( 2 ),
  20058. 1, _controlInterpolantsResultBuffer );
  20059. interpolant.__cacheIndex = lastActiveIndex;
  20060. interpolants[ lastActiveIndex ] = interpolant;
  20061. }
  20062. return interpolant;
  20063. }
  20064. _takeBackControlInterpolant( interpolant ) {
  20065. const interpolants = this._controlInterpolants,
  20066. prevIndex = interpolant.__cacheIndex,
  20067. firstInactiveIndex = -- this._nActiveControlInterpolants,
  20068. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  20069. interpolant.__cacheIndex = firstInactiveIndex;
  20070. interpolants[ firstInactiveIndex ] = interpolant;
  20071. lastActiveInterpolant.__cacheIndex = prevIndex;
  20072. interpolants[ prevIndex ] = lastActiveInterpolant;
  20073. }
  20074. // return an action for a clip optionally using a custom root target
  20075. // object (this method allocates a lot of dynamic memory in case a
  20076. // previously unknown clip/root combination is specified)
  20077. clipAction( clip, optionalRoot, blendMode ) {
  20078. const root = optionalRoot || this._root,
  20079. rootUuid = root.uuid;
  20080. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  20081. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  20082. const actionsForClip = this._actionsByClip[ clipUuid ];
  20083. let prototypeAction = null;
  20084. if ( blendMode === undefined ) {
  20085. if ( clipObject !== null ) {
  20086. blendMode = clipObject.blendMode;
  20087. } else {
  20088. blendMode = NormalAnimationBlendMode;
  20089. }
  20090. }
  20091. if ( actionsForClip !== undefined ) {
  20092. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  20093. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  20094. return existingAction;
  20095. }
  20096. // we know the clip, so we don't have to parse all
  20097. // the bindings again but can just copy
  20098. prototypeAction = actionsForClip.knownActions[ 0 ];
  20099. // also, take the clip from the prototype action
  20100. if ( clipObject === null )
  20101. clipObject = prototypeAction._clip;
  20102. }
  20103. // clip must be known when specified via string
  20104. if ( clipObject === null ) return null;
  20105. // allocate all resources required to run it
  20106. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  20107. this._bindAction( newAction, prototypeAction );
  20108. // and make the action known to the memory manager
  20109. this._addInactiveAction( newAction, clipUuid, rootUuid );
  20110. return newAction;
  20111. }
  20112. // get an existing action
  20113. existingAction( clip, optionalRoot ) {
  20114. const root = optionalRoot || this._root,
  20115. rootUuid = root.uuid,
  20116. clipObject = typeof clip === 'string' ?
  20117. AnimationClip.findByName( root, clip ) : clip,
  20118. clipUuid = clipObject ? clipObject.uuid : clip,
  20119. actionsForClip = this._actionsByClip[ clipUuid ];
  20120. if ( actionsForClip !== undefined ) {
  20121. return actionsForClip.actionByRoot[ rootUuid ] || null;
  20122. }
  20123. return null;
  20124. }
  20125. // deactivates all previously scheduled actions
  20126. stopAllAction() {
  20127. const actions = this._actions,
  20128. nActions = this._nActiveActions;
  20129. for ( let i = nActions - 1; i >= 0; -- i ) {
  20130. actions[ i ].stop();
  20131. }
  20132. return this;
  20133. }
  20134. // advance the time and update apply the animation
  20135. update( deltaTime ) {
  20136. deltaTime *= this.timeScale;
  20137. const actions = this._actions,
  20138. nActions = this._nActiveActions,
  20139. time = this.time += deltaTime,
  20140. timeDirection = Math.sign( deltaTime ),
  20141. accuIndex = this._accuIndex ^= 1;
  20142. // run active actions
  20143. for ( let i = 0; i !== nActions; ++ i ) {
  20144. const action = actions[ i ];
  20145. action._update( time, deltaTime, timeDirection, accuIndex );
  20146. }
  20147. // update scene graph
  20148. const bindings = this._bindings,
  20149. nBindings = this._nActiveBindings;
  20150. for ( let i = 0; i !== nBindings; ++ i ) {
  20151. bindings[ i ].apply( accuIndex );
  20152. }
  20153. return this;
  20154. }
  20155. // Allows you to seek to a specific time in an animation.
  20156. setTime( timeInSeconds ) {
  20157. this.time = 0; // Zero out time attribute for AnimationMixer object;
  20158. for ( let i = 0; i < this._actions.length; i ++ ) {
  20159. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  20160. }
  20161. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  20162. }
  20163. // return this mixer's root target object
  20164. getRoot() {
  20165. return this._root;
  20166. }
  20167. // free all resources specific to a particular clip
  20168. uncacheClip( clip ) {
  20169. const actions = this._actions,
  20170. clipUuid = clip.uuid,
  20171. actionsByClip = this._actionsByClip,
  20172. actionsForClip = actionsByClip[ clipUuid ];
  20173. if ( actionsForClip !== undefined ) {
  20174. // note: just calling _removeInactiveAction would mess up the
  20175. // iteration state and also require updating the state we can
  20176. // just throw away
  20177. const actionsToRemove = actionsForClip.knownActions;
  20178. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  20179. const action = actionsToRemove[ i ];
  20180. this._deactivateAction( action );
  20181. const cacheIndex = action._cacheIndex,
  20182. lastInactiveAction = actions[ actions.length - 1 ];
  20183. action._cacheIndex = null;
  20184. action._byClipCacheIndex = null;
  20185. lastInactiveAction._cacheIndex = cacheIndex;
  20186. actions[ cacheIndex ] = lastInactiveAction;
  20187. actions.pop();
  20188. this._removeInactiveBindingsForAction( action );
  20189. }
  20190. delete actionsByClip[ clipUuid ];
  20191. }
  20192. }
  20193. // free all resources specific to a particular root target object
  20194. uncacheRoot( root ) {
  20195. const rootUuid = root.uuid,
  20196. actionsByClip = this._actionsByClip;
  20197. for ( const clipUuid in actionsByClip ) {
  20198. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  20199. action = actionByRoot[ rootUuid ];
  20200. if ( action !== undefined ) {
  20201. this._deactivateAction( action );
  20202. this._removeInactiveAction( action );
  20203. }
  20204. }
  20205. const bindingsByRoot = this._bindingsByRootAndName,
  20206. bindingByName = bindingsByRoot[ rootUuid ];
  20207. if ( bindingByName !== undefined ) {
  20208. for ( const trackName in bindingByName ) {
  20209. const binding = bindingByName[ trackName ];
  20210. binding.restoreOriginalState();
  20211. this._removeInactiveBinding( binding );
  20212. }
  20213. }
  20214. }
  20215. // remove a targeted clip from the cache
  20216. uncacheAction( clip, optionalRoot ) {
  20217. const action = this.existingAction( clip, optionalRoot );
  20218. if ( action !== null ) {
  20219. this._deactivateAction( action );
  20220. this._removeInactiveAction( action );
  20221. }
  20222. }
  20223. }
  20224. let Uniform$1 = class Uniform {
  20225. constructor( value ) {
  20226. this.value = value;
  20227. }
  20228. clone() {
  20229. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  20230. }
  20231. };
  20232. let _id$8 = 0;
  20233. let UniformsGroup$1 = class UniformsGroup extends EventDispatcher {
  20234. constructor() {
  20235. super();
  20236. this.isUniformsGroup = true;
  20237. Object.defineProperty( this, 'id', { value: _id$8 ++ } );
  20238. this.name = '';
  20239. this.usage = StaticDrawUsage;
  20240. this.uniforms = [];
  20241. }
  20242. add( uniform ) {
  20243. this.uniforms.push( uniform );
  20244. return this;
  20245. }
  20246. remove( uniform ) {
  20247. const index = this.uniforms.indexOf( uniform );
  20248. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  20249. return this;
  20250. }
  20251. setName( name ) {
  20252. this.name = name;
  20253. return this;
  20254. }
  20255. setUsage( value ) {
  20256. this.usage = value;
  20257. return this;
  20258. }
  20259. dispose() {
  20260. this.dispatchEvent( { type: 'dispose' } );
  20261. return this;
  20262. }
  20263. copy( source ) {
  20264. this.name = source.name;
  20265. this.usage = source.usage;
  20266. const uniformsSource = source.uniforms;
  20267. this.uniforms.length = 0;
  20268. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  20269. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  20270. for ( let j = 0; j < uniforms.length; j ++ ) {
  20271. this.uniforms.push( uniforms[ j ].clone() );
  20272. }
  20273. }
  20274. return this;
  20275. }
  20276. clone() {
  20277. return new this.constructor().copy( this );
  20278. }
  20279. };
  20280. class InstancedInterleavedBuffer extends InterleavedBuffer {
  20281. constructor( array, stride, meshPerAttribute = 1 ) {
  20282. super( array, stride );
  20283. this.isInstancedInterleavedBuffer = true;
  20284. this.meshPerAttribute = meshPerAttribute;
  20285. }
  20286. copy( source ) {
  20287. super.copy( source );
  20288. this.meshPerAttribute = source.meshPerAttribute;
  20289. return this;
  20290. }
  20291. clone( data ) {
  20292. const ib = super.clone( data );
  20293. ib.meshPerAttribute = this.meshPerAttribute;
  20294. return ib;
  20295. }
  20296. toJSON( data ) {
  20297. const json = super.toJSON( data );
  20298. json.isInstancedInterleavedBuffer = true;
  20299. json.meshPerAttribute = this.meshPerAttribute;
  20300. return json;
  20301. }
  20302. }
  20303. class GLBufferAttribute {
  20304. constructor( buffer, type, itemSize, elementSize, count ) {
  20305. this.isGLBufferAttribute = true;
  20306. this.name = '';
  20307. this.buffer = buffer;
  20308. this.type = type;
  20309. this.itemSize = itemSize;
  20310. this.elementSize = elementSize;
  20311. this.count = count;
  20312. this.version = 0;
  20313. }
  20314. set needsUpdate( value ) {
  20315. if ( value === true ) this.version ++;
  20316. }
  20317. setBuffer( buffer ) {
  20318. this.buffer = buffer;
  20319. return this;
  20320. }
  20321. setType( type, elementSize ) {
  20322. this.type = type;
  20323. this.elementSize = elementSize;
  20324. return this;
  20325. }
  20326. setItemSize( itemSize ) {
  20327. this.itemSize = itemSize;
  20328. return this;
  20329. }
  20330. setCount( count ) {
  20331. this.count = count;
  20332. return this;
  20333. }
  20334. }
  20335. const _matrix = /*@__PURE__*/ new Matrix4();
  20336. class Raycaster {
  20337. constructor( origin, direction, near = 0, far = Infinity ) {
  20338. this.ray = new Ray( origin, direction );
  20339. // direction is assumed to be normalized (for accurate distance calculations)
  20340. this.near = near;
  20341. this.far = far;
  20342. this.camera = null;
  20343. this.layers = new Layers();
  20344. this.params = {
  20345. Mesh: {},
  20346. Line: { threshold: 1 },
  20347. LOD: {},
  20348. Points: { threshold: 1 },
  20349. Sprite: {}
  20350. };
  20351. }
  20352. set( origin, direction ) {
  20353. // direction is assumed to be normalized (for accurate distance calculations)
  20354. this.ray.set( origin, direction );
  20355. }
  20356. setFromCamera( coords, camera ) {
  20357. if ( camera.isPerspectiveCamera ) {
  20358. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20359. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20360. this.camera = camera;
  20361. } else if ( camera.isOrthographicCamera ) {
  20362. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20363. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20364. this.camera = camera;
  20365. } else {
  20366. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  20367. }
  20368. }
  20369. setFromXRController( controller ) {
  20370. _matrix.identity().extractRotation( controller.matrixWorld );
  20371. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  20372. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  20373. return this;
  20374. }
  20375. intersectObject( object, recursive = true, intersects = [] ) {
  20376. intersect( object, this, intersects, recursive );
  20377. intersects.sort( ascSort );
  20378. return intersects;
  20379. }
  20380. intersectObjects( objects, recursive = true, intersects = [] ) {
  20381. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  20382. intersect( objects[ i ], this, intersects, recursive );
  20383. }
  20384. intersects.sort( ascSort );
  20385. return intersects;
  20386. }
  20387. }
  20388. function ascSort( a, b ) {
  20389. return a.distance - b.distance;
  20390. }
  20391. function intersect( object, raycaster, intersects, recursive ) {
  20392. let propagate = true;
  20393. if ( object.layers.test( raycaster.layers ) ) {
  20394. const result = object.raycast( raycaster, intersects );
  20395. if ( result === false ) propagate = false;
  20396. }
  20397. if ( propagate === true && recursive === true ) {
  20398. const children = object.children;
  20399. for ( let i = 0, l = children.length; i < l; i ++ ) {
  20400. intersect( children[ i ], raycaster, intersects, true );
  20401. }
  20402. }
  20403. }
  20404. /**
  20405. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  20406. *
  20407. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  20408. * theta (the azimuthal angle) is measured from the positive z-axis.
  20409. */
  20410. class Spherical {
  20411. constructor( radius = 1, phi = 0, theta = 0 ) {
  20412. this.radius = radius;
  20413. this.phi = phi; // polar angle
  20414. this.theta = theta; // azimuthal angle
  20415. return this;
  20416. }
  20417. set( radius, phi, theta ) {
  20418. this.radius = radius;
  20419. this.phi = phi;
  20420. this.theta = theta;
  20421. return this;
  20422. }
  20423. copy( other ) {
  20424. this.radius = other.radius;
  20425. this.phi = other.phi;
  20426. this.theta = other.theta;
  20427. return this;
  20428. }
  20429. // restrict phi to be between EPS and PI-EPS
  20430. makeSafe() {
  20431. const EPS = 0.000001;
  20432. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  20433. return this;
  20434. }
  20435. setFromVector3( v ) {
  20436. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20437. }
  20438. setFromCartesianCoords( x, y, z ) {
  20439. this.radius = Math.sqrt( x * x + y * y + z * z );
  20440. if ( this.radius === 0 ) {
  20441. this.theta = 0;
  20442. this.phi = 0;
  20443. } else {
  20444. this.theta = Math.atan2( x, z );
  20445. this.phi = Math.acos( clamp$1( y / this.radius, - 1, 1 ) );
  20446. }
  20447. return this;
  20448. }
  20449. clone() {
  20450. return new this.constructor().copy( this );
  20451. }
  20452. }
  20453. /**
  20454. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  20455. */
  20456. class Cylindrical {
  20457. constructor( radius = 1, theta = 0, y = 0 ) {
  20458. this.radius = radius; // distance from the origin to a point in the x-z plane
  20459. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  20460. this.y = y; // height above the x-z plane
  20461. return this;
  20462. }
  20463. set( radius, theta, y ) {
  20464. this.radius = radius;
  20465. this.theta = theta;
  20466. this.y = y;
  20467. return this;
  20468. }
  20469. copy( other ) {
  20470. this.radius = other.radius;
  20471. this.theta = other.theta;
  20472. this.y = other.y;
  20473. return this;
  20474. }
  20475. setFromVector3( v ) {
  20476. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20477. }
  20478. setFromCartesianCoords( x, y, z ) {
  20479. this.radius = Math.sqrt( x * x + z * z );
  20480. this.theta = Math.atan2( x, z );
  20481. this.y = y;
  20482. return this;
  20483. }
  20484. clone() {
  20485. return new this.constructor().copy( this );
  20486. }
  20487. }
  20488. class Matrix2 {
  20489. constructor( n11, n12, n21, n22 ) {
  20490. Matrix2.prototype.isMatrix2 = true;
  20491. this.elements = [
  20492. 1, 0,
  20493. 0, 1,
  20494. ];
  20495. if ( n11 !== undefined ) {
  20496. this.set( n11, n12, n21, n22 );
  20497. }
  20498. }
  20499. identity() {
  20500. this.set(
  20501. 1, 0,
  20502. 0, 1,
  20503. );
  20504. return this;
  20505. }
  20506. fromArray( array, offset = 0 ) {
  20507. for ( let i = 0; i < 4; i ++ ) {
  20508. this.elements[ i ] = array[ i + offset ];
  20509. }
  20510. return this;
  20511. }
  20512. set( n11, n12, n21, n22 ) {
  20513. const te = this.elements;
  20514. te[ 0 ] = n11; te[ 2 ] = n12;
  20515. te[ 1 ] = n21; te[ 3 ] = n22;
  20516. return this;
  20517. }
  20518. }
  20519. const _vector$4 = /*@__PURE__*/ new Vector2();
  20520. class Box2 {
  20521. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  20522. this.isBox2 = true;
  20523. this.min = min;
  20524. this.max = max;
  20525. }
  20526. set( min, max ) {
  20527. this.min.copy( min );
  20528. this.max.copy( max );
  20529. return this;
  20530. }
  20531. setFromPoints( points ) {
  20532. this.makeEmpty();
  20533. for ( let i = 0, il = points.length; i < il; i ++ ) {
  20534. this.expandByPoint( points[ i ] );
  20535. }
  20536. return this;
  20537. }
  20538. setFromCenterAndSize( center, size ) {
  20539. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  20540. this.min.copy( center ).sub( halfSize );
  20541. this.max.copy( center ).add( halfSize );
  20542. return this;
  20543. }
  20544. clone() {
  20545. return new this.constructor().copy( this );
  20546. }
  20547. copy( box ) {
  20548. this.min.copy( box.min );
  20549. this.max.copy( box.max );
  20550. return this;
  20551. }
  20552. makeEmpty() {
  20553. this.min.x = this.min.y = + Infinity;
  20554. this.max.x = this.max.y = - Infinity;
  20555. return this;
  20556. }
  20557. isEmpty() {
  20558. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  20559. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  20560. }
  20561. getCenter( target ) {
  20562. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  20563. }
  20564. getSize( target ) {
  20565. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  20566. }
  20567. expandByPoint( point ) {
  20568. this.min.min( point );
  20569. this.max.max( point );
  20570. return this;
  20571. }
  20572. expandByVector( vector ) {
  20573. this.min.sub( vector );
  20574. this.max.add( vector );
  20575. return this;
  20576. }
  20577. expandByScalar( scalar ) {
  20578. this.min.addScalar( - scalar );
  20579. this.max.addScalar( scalar );
  20580. return this;
  20581. }
  20582. containsPoint( point ) {
  20583. return point.x >= this.min.x && point.x <= this.max.x &&
  20584. point.y >= this.min.y && point.y <= this.max.y;
  20585. }
  20586. containsBox( box ) {
  20587. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  20588. this.min.y <= box.min.y && box.max.y <= this.max.y;
  20589. }
  20590. getParameter( point, target ) {
  20591. // This can potentially have a divide by zero if the box
  20592. // has a size dimension of 0.
  20593. return target.set(
  20594. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  20595. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  20596. );
  20597. }
  20598. intersectsBox( box ) {
  20599. // using 4 splitting planes to rule out intersections
  20600. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  20601. box.max.y >= this.min.y && box.min.y <= this.max.y;
  20602. }
  20603. clampPoint( point, target ) {
  20604. return target.copy( point ).clamp( this.min, this.max );
  20605. }
  20606. distanceToPoint( point ) {
  20607. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  20608. }
  20609. intersect( box ) {
  20610. this.min.max( box.min );
  20611. this.max.min( box.max );
  20612. if ( this.isEmpty() ) this.makeEmpty();
  20613. return this;
  20614. }
  20615. union( box ) {
  20616. this.min.min( box.min );
  20617. this.max.max( box.max );
  20618. return this;
  20619. }
  20620. translate( offset ) {
  20621. this.min.add( offset );
  20622. this.max.add( offset );
  20623. return this;
  20624. }
  20625. equals( box ) {
  20626. return box.min.equals( this.min ) && box.max.equals( this.max );
  20627. }
  20628. }
  20629. const _startP = /*@__PURE__*/ new Vector3();
  20630. const _startEnd = /*@__PURE__*/ new Vector3();
  20631. class Line3 {
  20632. constructor( start = new Vector3(), end = new Vector3() ) {
  20633. this.start = start;
  20634. this.end = end;
  20635. }
  20636. set( start, end ) {
  20637. this.start.copy( start );
  20638. this.end.copy( end );
  20639. return this;
  20640. }
  20641. copy( line ) {
  20642. this.start.copy( line.start );
  20643. this.end.copy( line.end );
  20644. return this;
  20645. }
  20646. getCenter( target ) {
  20647. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  20648. }
  20649. delta( target ) {
  20650. return target.subVectors( this.end, this.start );
  20651. }
  20652. distanceSq() {
  20653. return this.start.distanceToSquared( this.end );
  20654. }
  20655. distance() {
  20656. return this.start.distanceTo( this.end );
  20657. }
  20658. at( t, target ) {
  20659. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20660. }
  20661. closestPointToPointParameter( point, clampToLine ) {
  20662. _startP.subVectors( point, this.start );
  20663. _startEnd.subVectors( this.end, this.start );
  20664. const startEnd2 = _startEnd.dot( _startEnd );
  20665. const startEnd_startP = _startEnd.dot( _startP );
  20666. let t = startEnd_startP / startEnd2;
  20667. if ( clampToLine ) {
  20668. t = clamp$1( t, 0, 1 );
  20669. }
  20670. return t;
  20671. }
  20672. closestPointToPoint( point, clampToLine, target ) {
  20673. const t = this.closestPointToPointParameter( point, clampToLine );
  20674. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20675. }
  20676. applyMatrix4( matrix ) {
  20677. this.start.applyMatrix4( matrix );
  20678. this.end.applyMatrix4( matrix );
  20679. return this;
  20680. }
  20681. equals( line ) {
  20682. return line.start.equals( this.start ) && line.end.equals( this.end );
  20683. }
  20684. clone() {
  20685. return new this.constructor().copy( this );
  20686. }
  20687. }
  20688. const _vector$3 = /*@__PURE__*/ new Vector3();
  20689. class SpotLightHelper extends Object3D {
  20690. constructor( light, color ) {
  20691. super();
  20692. this.light = light;
  20693. this.matrixAutoUpdate = false;
  20694. this.color = color;
  20695. this.type = 'SpotLightHelper';
  20696. const geometry = new BufferGeometry();
  20697. const positions = [
  20698. 0, 0, 0, 0, 0, 1,
  20699. 0, 0, 0, 1, 0, 1,
  20700. 0, 0, 0, - 1, 0, 1,
  20701. 0, 0, 0, 0, 1, 1,
  20702. 0, 0, 0, 0, - 1, 1
  20703. ];
  20704. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  20705. const p1 = ( i / l ) * Math.PI * 2;
  20706. const p2 = ( j / l ) * Math.PI * 2;
  20707. positions.push(
  20708. Math.cos( p1 ), Math.sin( p1 ), 1,
  20709. Math.cos( p2 ), Math.sin( p2 ), 1
  20710. );
  20711. }
  20712. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20713. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20714. this.cone = new LineSegments( geometry, material );
  20715. this.add( this.cone );
  20716. this.update();
  20717. }
  20718. dispose() {
  20719. this.cone.geometry.dispose();
  20720. this.cone.material.dispose();
  20721. }
  20722. update() {
  20723. this.light.updateWorldMatrix( true, false );
  20724. this.light.target.updateWorldMatrix( true, false );
  20725. // update the local matrix based on the parent and light target transforms
  20726. if ( this.parent ) {
  20727. this.parent.updateWorldMatrix( true );
  20728. this.matrix
  20729. .copy( this.parent.matrixWorld )
  20730. .invert()
  20731. .multiply( this.light.matrixWorld );
  20732. } else {
  20733. this.matrix.copy( this.light.matrixWorld );
  20734. }
  20735. this.matrixWorld.copy( this.light.matrixWorld );
  20736. const coneLength = this.light.distance ? this.light.distance : 1000;
  20737. const coneWidth = coneLength * Math.tan( this.light.angle );
  20738. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20739. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  20740. this.cone.lookAt( _vector$3 );
  20741. if ( this.color !== undefined ) {
  20742. this.cone.material.color.set( this.color );
  20743. } else {
  20744. this.cone.material.color.copy( this.light.color );
  20745. }
  20746. }
  20747. }
  20748. const _vector$2 = /*@__PURE__*/ new Vector3();
  20749. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  20750. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  20751. class SkeletonHelper extends LineSegments {
  20752. constructor( object ) {
  20753. const bones = getBoneList( object );
  20754. const geometry = new BufferGeometry();
  20755. const vertices = [];
  20756. const colors = [];
  20757. const color1 = new Color( 0, 0, 1 );
  20758. const color2 = new Color( 0, 1, 0 );
  20759. for ( let i = 0; i < bones.length; i ++ ) {
  20760. const bone = bones[ i ];
  20761. if ( bone.parent && bone.parent.isBone ) {
  20762. vertices.push( 0, 0, 0 );
  20763. vertices.push( 0, 0, 0 );
  20764. colors.push( color1.r, color1.g, color1.b );
  20765. colors.push( color2.r, color2.g, color2.b );
  20766. }
  20767. }
  20768. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20769. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20770. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  20771. super( geometry, material );
  20772. this.isSkeletonHelper = true;
  20773. this.type = 'SkeletonHelper';
  20774. this.root = object;
  20775. this.bones = bones;
  20776. this.matrix = object.matrixWorld;
  20777. this.matrixAutoUpdate = false;
  20778. }
  20779. updateMatrixWorld( force ) {
  20780. const bones = this.bones;
  20781. const geometry = this.geometry;
  20782. const position = geometry.getAttribute( 'position' );
  20783. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  20784. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  20785. const bone = bones[ i ];
  20786. if ( bone.parent && bone.parent.isBone ) {
  20787. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  20788. _vector$2.setFromMatrixPosition( _boneMatrix );
  20789. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  20790. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  20791. _vector$2.setFromMatrixPosition( _boneMatrix );
  20792. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  20793. j += 2;
  20794. }
  20795. }
  20796. geometry.getAttribute( 'position' ).needsUpdate = true;
  20797. super.updateMatrixWorld( force );
  20798. }
  20799. dispose() {
  20800. this.geometry.dispose();
  20801. this.material.dispose();
  20802. }
  20803. }
  20804. function getBoneList( object ) {
  20805. const boneList = [];
  20806. if ( object.isBone === true ) {
  20807. boneList.push( object );
  20808. }
  20809. for ( let i = 0; i < object.children.length; i ++ ) {
  20810. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  20811. }
  20812. return boneList;
  20813. }
  20814. class PointLightHelper extends Mesh {
  20815. constructor( light, sphereSize, color ) {
  20816. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  20817. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20818. super( geometry, material );
  20819. this.light = light;
  20820. this.color = color;
  20821. this.type = 'PointLightHelper';
  20822. this.matrix = this.light.matrixWorld;
  20823. this.matrixAutoUpdate = false;
  20824. this.update();
  20825. /*
  20826. // TODO: delete this comment?
  20827. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20828. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20829. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20830. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20831. const d = light.distance;
  20832. if ( d === 0.0 ) {
  20833. this.lightDistance.visible = false;
  20834. } else {
  20835. this.lightDistance.scale.set( d, d, d );
  20836. }
  20837. this.add( this.lightDistance );
  20838. */
  20839. }
  20840. dispose() {
  20841. this.geometry.dispose();
  20842. this.material.dispose();
  20843. }
  20844. update() {
  20845. this.light.updateWorldMatrix( true, false );
  20846. if ( this.color !== undefined ) {
  20847. this.material.color.set( this.color );
  20848. } else {
  20849. this.material.color.copy( this.light.color );
  20850. }
  20851. /*
  20852. const d = this.light.distance;
  20853. if ( d === 0.0 ) {
  20854. this.lightDistance.visible = false;
  20855. } else {
  20856. this.lightDistance.visible = true;
  20857. this.lightDistance.scale.set( d, d, d );
  20858. }
  20859. */
  20860. }
  20861. }
  20862. const _vector$1 = /*@__PURE__*/ new Vector3();
  20863. const _color1 = /*@__PURE__*/ new Color();
  20864. const _color2 = /*@__PURE__*/ new Color();
  20865. class HemisphereLightHelper extends Object3D {
  20866. constructor( light, size, color ) {
  20867. super();
  20868. this.light = light;
  20869. this.matrix = light.matrixWorld;
  20870. this.matrixAutoUpdate = false;
  20871. this.color = color;
  20872. this.type = 'HemisphereLightHelper';
  20873. const geometry = new OctahedronGeometry( size );
  20874. geometry.rotateY( Math.PI * 0.5 );
  20875. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20876. if ( this.color === undefined ) this.material.vertexColors = true;
  20877. const position = geometry.getAttribute( 'position' );
  20878. const colors = new Float32Array( position.count * 3 );
  20879. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  20880. this.add( new Mesh( geometry, this.material ) );
  20881. this.update();
  20882. }
  20883. dispose() {
  20884. this.children[ 0 ].geometry.dispose();
  20885. this.children[ 0 ].material.dispose();
  20886. }
  20887. update() {
  20888. const mesh = this.children[ 0 ];
  20889. if ( this.color !== undefined ) {
  20890. this.material.color.set( this.color );
  20891. } else {
  20892. const colors = mesh.geometry.getAttribute( 'color' );
  20893. _color1.copy( this.light.color );
  20894. _color2.copy( this.light.groundColor );
  20895. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  20896. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  20897. colors.setXYZ( i, color.r, color.g, color.b );
  20898. }
  20899. colors.needsUpdate = true;
  20900. }
  20901. this.light.updateWorldMatrix( true, false );
  20902. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20903. }
  20904. }
  20905. class GridHelper extends LineSegments {
  20906. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  20907. color1 = new Color( color1 );
  20908. color2 = new Color( color2 );
  20909. const center = divisions / 2;
  20910. const step = size / divisions;
  20911. const halfSize = size / 2;
  20912. const vertices = [], colors = [];
  20913. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  20914. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  20915. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  20916. const color = i === center ? color1 : color2;
  20917. color.toArray( colors, j ); j += 3;
  20918. color.toArray( colors, j ); j += 3;
  20919. color.toArray( colors, j ); j += 3;
  20920. color.toArray( colors, j ); j += 3;
  20921. }
  20922. const geometry = new BufferGeometry();
  20923. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20924. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20925. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20926. super( geometry, material );
  20927. this.type = 'GridHelper';
  20928. }
  20929. dispose() {
  20930. this.geometry.dispose();
  20931. this.material.dispose();
  20932. }
  20933. }
  20934. class PolarGridHelper extends LineSegments {
  20935. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  20936. color1 = new Color( color1 );
  20937. color2 = new Color( color2 );
  20938. const vertices = [];
  20939. const colors = [];
  20940. // create the sectors
  20941. if ( sectors > 1 ) {
  20942. for ( let i = 0; i < sectors; i ++ ) {
  20943. const v = ( i / sectors ) * ( Math.PI * 2 );
  20944. const x = Math.sin( v ) * radius;
  20945. const z = Math.cos( v ) * radius;
  20946. vertices.push( 0, 0, 0 );
  20947. vertices.push( x, 0, z );
  20948. const color = ( i & 1 ) ? color1 : color2;
  20949. colors.push( color.r, color.g, color.b );
  20950. colors.push( color.r, color.g, color.b );
  20951. }
  20952. }
  20953. // create the rings
  20954. for ( let i = 0; i < rings; i ++ ) {
  20955. const color = ( i & 1 ) ? color1 : color2;
  20956. const r = radius - ( radius / rings * i );
  20957. for ( let j = 0; j < divisions; j ++ ) {
  20958. // first vertex
  20959. let v = ( j / divisions ) * ( Math.PI * 2 );
  20960. let x = Math.sin( v ) * r;
  20961. let z = Math.cos( v ) * r;
  20962. vertices.push( x, 0, z );
  20963. colors.push( color.r, color.g, color.b );
  20964. // second vertex
  20965. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  20966. x = Math.sin( v ) * r;
  20967. z = Math.cos( v ) * r;
  20968. vertices.push( x, 0, z );
  20969. colors.push( color.r, color.g, color.b );
  20970. }
  20971. }
  20972. const geometry = new BufferGeometry();
  20973. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20974. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20975. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20976. super( geometry, material );
  20977. this.type = 'PolarGridHelper';
  20978. }
  20979. dispose() {
  20980. this.geometry.dispose();
  20981. this.material.dispose();
  20982. }
  20983. }
  20984. const _v1 = /*@__PURE__*/ new Vector3();
  20985. const _v2 = /*@__PURE__*/ new Vector3();
  20986. const _v3 = /*@__PURE__*/ new Vector3();
  20987. class DirectionalLightHelper extends Object3D {
  20988. constructor( light, size, color ) {
  20989. super();
  20990. this.light = light;
  20991. this.matrix = light.matrixWorld;
  20992. this.matrixAutoUpdate = false;
  20993. this.color = color;
  20994. this.type = 'DirectionalLightHelper';
  20995. if ( size === undefined ) size = 1;
  20996. let geometry = new BufferGeometry();
  20997. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  20998. - size, size, 0,
  20999. size, size, 0,
  21000. size, - size, 0,
  21001. - size, - size, 0,
  21002. - size, size, 0
  21003. ], 3 ) );
  21004. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  21005. this.lightPlane = new Line( geometry, material );
  21006. this.add( this.lightPlane );
  21007. geometry = new BufferGeometry();
  21008. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  21009. this.targetLine = new Line( geometry, material );
  21010. this.add( this.targetLine );
  21011. this.update();
  21012. }
  21013. dispose() {
  21014. this.lightPlane.geometry.dispose();
  21015. this.lightPlane.material.dispose();
  21016. this.targetLine.geometry.dispose();
  21017. this.targetLine.material.dispose();
  21018. }
  21019. update() {
  21020. this.light.updateWorldMatrix( true, false );
  21021. this.light.target.updateWorldMatrix( true, false );
  21022. _v1.setFromMatrixPosition( this.light.matrixWorld );
  21023. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  21024. _v3.subVectors( _v2, _v1 );
  21025. this.lightPlane.lookAt( _v2 );
  21026. if ( this.color !== undefined ) {
  21027. this.lightPlane.material.color.set( this.color );
  21028. this.targetLine.material.color.set( this.color );
  21029. } else {
  21030. this.lightPlane.material.color.copy( this.light.color );
  21031. this.targetLine.material.color.copy( this.light.color );
  21032. }
  21033. this.targetLine.lookAt( _v2 );
  21034. this.targetLine.scale.z = _v3.length();
  21035. }
  21036. }
  21037. const _vector = /*@__PURE__*/ new Vector3();
  21038. const _camera$1 = /*@__PURE__*/ new Camera();
  21039. /**
  21040. * - shows frustum, line of sight and up of the camera
  21041. * - suitable for fast updates
  21042. * - based on frustum visualization in lightgl.js shadowmap example
  21043. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  21044. */
  21045. class CameraHelper extends LineSegments {
  21046. constructor( camera ) {
  21047. const geometry = new BufferGeometry();
  21048. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  21049. const vertices = [];
  21050. const colors = [];
  21051. const pointMap = {};
  21052. // near
  21053. addLine( 'n1', 'n2' );
  21054. addLine( 'n2', 'n4' );
  21055. addLine( 'n4', 'n3' );
  21056. addLine( 'n3', 'n1' );
  21057. // far
  21058. addLine( 'f1', 'f2' );
  21059. addLine( 'f2', 'f4' );
  21060. addLine( 'f4', 'f3' );
  21061. addLine( 'f3', 'f1' );
  21062. // sides
  21063. addLine( 'n1', 'f1' );
  21064. addLine( 'n2', 'f2' );
  21065. addLine( 'n3', 'f3' );
  21066. addLine( 'n4', 'f4' );
  21067. // cone
  21068. addLine( 'p', 'n1' );
  21069. addLine( 'p', 'n2' );
  21070. addLine( 'p', 'n3' );
  21071. addLine( 'p', 'n4' );
  21072. // up
  21073. addLine( 'u1', 'u2' );
  21074. addLine( 'u2', 'u3' );
  21075. addLine( 'u3', 'u1' );
  21076. // target
  21077. addLine( 'c', 't' );
  21078. addLine( 'p', 'c' );
  21079. // cross
  21080. addLine( 'cn1', 'cn2' );
  21081. addLine( 'cn3', 'cn4' );
  21082. addLine( 'cf1', 'cf2' );
  21083. addLine( 'cf3', 'cf4' );
  21084. function addLine( a, b ) {
  21085. addPoint( a );
  21086. addPoint( b );
  21087. }
  21088. function addPoint( id ) {
  21089. vertices.push( 0, 0, 0 );
  21090. colors.push( 0, 0, 0 );
  21091. if ( pointMap[ id ] === undefined ) {
  21092. pointMap[ id ] = [];
  21093. }
  21094. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  21095. }
  21096. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21097. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21098. super( geometry, material );
  21099. this.type = 'CameraHelper';
  21100. this.camera = camera;
  21101. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  21102. this.matrix = camera.matrixWorld;
  21103. this.matrixAutoUpdate = false;
  21104. this.pointMap = pointMap;
  21105. this.update();
  21106. // colors
  21107. const colorFrustum = new Color( 0xffaa00 );
  21108. const colorCone = new Color( 0xff0000 );
  21109. const colorUp = new Color( 0x00aaff );
  21110. const colorTarget = new Color( 0xffffff );
  21111. const colorCross = new Color( 0x333333 );
  21112. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  21113. }
  21114. setColors( frustum, cone, up, target, cross ) {
  21115. const geometry = this.geometry;
  21116. const colorAttribute = geometry.getAttribute( 'color' );
  21117. // near
  21118. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  21119. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  21120. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  21121. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  21122. // far
  21123. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  21124. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  21125. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  21126. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  21127. // sides
  21128. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  21129. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  21130. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  21131. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  21132. // cone
  21133. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  21134. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  21135. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  21136. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  21137. // up
  21138. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  21139. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  21140. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  21141. // target
  21142. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  21143. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  21144. // cross
  21145. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  21146. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  21147. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  21148. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  21149. colorAttribute.needsUpdate = true;
  21150. }
  21151. update() {
  21152. const geometry = this.geometry;
  21153. const pointMap = this.pointMap;
  21154. const w = 1, h = 1;
  21155. // we need just camera projection matrix inverse
  21156. // world matrix must be identity
  21157. _camera$1.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  21158. // center / target
  21159. setPoint( 'c', pointMap, geometry, _camera$1, 0, 0, - 1 );
  21160. setPoint( 't', pointMap, geometry, _camera$1, 0, 0, 1 );
  21161. // near
  21162. setPoint( 'n1', pointMap, geometry, _camera$1, - w, - h, - 1 );
  21163. setPoint( 'n2', pointMap, geometry, _camera$1, w, - h, - 1 );
  21164. setPoint( 'n3', pointMap, geometry, _camera$1, - w, h, - 1 );
  21165. setPoint( 'n4', pointMap, geometry, _camera$1, w, h, - 1 );
  21166. // far
  21167. setPoint( 'f1', pointMap, geometry, _camera$1, - w, - h, 1 );
  21168. setPoint( 'f2', pointMap, geometry, _camera$1, w, - h, 1 );
  21169. setPoint( 'f3', pointMap, geometry, _camera$1, - w, h, 1 );
  21170. setPoint( 'f4', pointMap, geometry, _camera$1, w, h, 1 );
  21171. // up
  21172. setPoint( 'u1', pointMap, geometry, _camera$1, w * 0.7, h * 1.1, - 1 );
  21173. setPoint( 'u2', pointMap, geometry, _camera$1, - w * 0.7, h * 1.1, - 1 );
  21174. setPoint( 'u3', pointMap, geometry, _camera$1, 0, h * 2, - 1 );
  21175. // cross
  21176. setPoint( 'cf1', pointMap, geometry, _camera$1, - w, 0, 1 );
  21177. setPoint( 'cf2', pointMap, geometry, _camera$1, w, 0, 1 );
  21178. setPoint( 'cf3', pointMap, geometry, _camera$1, 0, - h, 1 );
  21179. setPoint( 'cf4', pointMap, geometry, _camera$1, 0, h, 1 );
  21180. setPoint( 'cn1', pointMap, geometry, _camera$1, - w, 0, - 1 );
  21181. setPoint( 'cn2', pointMap, geometry, _camera$1, w, 0, - 1 );
  21182. setPoint( 'cn3', pointMap, geometry, _camera$1, 0, - h, - 1 );
  21183. setPoint( 'cn4', pointMap, geometry, _camera$1, 0, h, - 1 );
  21184. geometry.getAttribute( 'position' ).needsUpdate = true;
  21185. }
  21186. dispose() {
  21187. this.geometry.dispose();
  21188. this.material.dispose();
  21189. }
  21190. }
  21191. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  21192. _vector.set( x, y, z ).unproject( camera );
  21193. const points = pointMap[ point ];
  21194. if ( points !== undefined ) {
  21195. const position = geometry.getAttribute( 'position' );
  21196. for ( let i = 0, l = points.length; i < l; i ++ ) {
  21197. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  21198. }
  21199. }
  21200. }
  21201. const _box = /*@__PURE__*/ new Box3();
  21202. class BoxHelper extends LineSegments {
  21203. constructor( object, color = 0xffff00 ) {
  21204. 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 ] );
  21205. const positions = new Float32Array( 8 * 3 );
  21206. const geometry = new BufferGeometry();
  21207. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21208. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  21209. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21210. this.object = object;
  21211. this.type = 'BoxHelper';
  21212. this.matrixAutoUpdate = false;
  21213. this.update();
  21214. }
  21215. update( object ) {
  21216. if ( object !== undefined ) {
  21217. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  21218. }
  21219. if ( this.object !== undefined ) {
  21220. _box.setFromObject( this.object );
  21221. }
  21222. if ( _box.isEmpty() ) return;
  21223. const min = _box.min;
  21224. const max = _box.max;
  21225. /*
  21226. 5____4
  21227. 1/___0/|
  21228. | 6__|_7
  21229. 2/___3/
  21230. 0: max.x, max.y, max.z
  21231. 1: min.x, max.y, max.z
  21232. 2: min.x, min.y, max.z
  21233. 3: max.x, min.y, max.z
  21234. 4: max.x, max.y, min.z
  21235. 5: min.x, max.y, min.z
  21236. 6: min.x, min.y, min.z
  21237. 7: max.x, min.y, min.z
  21238. */
  21239. const position = this.geometry.attributes.position;
  21240. const array = position.array;
  21241. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  21242. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  21243. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  21244. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  21245. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  21246. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  21247. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  21248. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  21249. position.needsUpdate = true;
  21250. this.geometry.computeBoundingSphere();
  21251. }
  21252. setFromObject( object ) {
  21253. this.object = object;
  21254. this.update();
  21255. return this;
  21256. }
  21257. copy( source, recursive ) {
  21258. super.copy( source, recursive );
  21259. this.object = source.object;
  21260. return this;
  21261. }
  21262. dispose() {
  21263. this.geometry.dispose();
  21264. this.material.dispose();
  21265. }
  21266. }
  21267. class Box3Helper extends LineSegments {
  21268. constructor( box, color = 0xffff00 ) {
  21269. 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 ] );
  21270. 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 ];
  21271. const geometry = new BufferGeometry();
  21272. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21273. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21274. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21275. this.box = box;
  21276. this.type = 'Box3Helper';
  21277. this.geometry.computeBoundingSphere();
  21278. }
  21279. updateMatrixWorld( force ) {
  21280. const box = this.box;
  21281. if ( box.isEmpty() ) return;
  21282. box.getCenter( this.position );
  21283. box.getSize( this.scale );
  21284. this.scale.multiplyScalar( 0.5 );
  21285. super.updateMatrixWorld( force );
  21286. }
  21287. dispose() {
  21288. this.geometry.dispose();
  21289. this.material.dispose();
  21290. }
  21291. }
  21292. class PlaneHelper extends Line {
  21293. constructor( plane, size = 1, hex = 0xffff00 ) {
  21294. const color = hex;
  21295. 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 ];
  21296. const geometry = new BufferGeometry();
  21297. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21298. geometry.computeBoundingSphere();
  21299. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21300. this.type = 'PlaneHelper';
  21301. this.plane = plane;
  21302. this.size = size;
  21303. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  21304. const geometry2 = new BufferGeometry();
  21305. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  21306. geometry2.computeBoundingSphere();
  21307. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  21308. }
  21309. updateMatrixWorld( force ) {
  21310. this.position.set( 0, 0, 0 );
  21311. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  21312. this.lookAt( this.plane.normal );
  21313. this.translateZ( - this.plane.constant );
  21314. super.updateMatrixWorld( force );
  21315. }
  21316. dispose() {
  21317. this.geometry.dispose();
  21318. this.material.dispose();
  21319. this.children[ 0 ].geometry.dispose();
  21320. this.children[ 0 ].material.dispose();
  21321. }
  21322. }
  21323. const _axis = /*@__PURE__*/ new Vector3();
  21324. let _lineGeometry, _coneGeometry;
  21325. class ArrowHelper extends Object3D {
  21326. // dir is assumed to be normalized
  21327. 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 ) {
  21328. super();
  21329. this.type = 'ArrowHelper';
  21330. if ( _lineGeometry === undefined ) {
  21331. _lineGeometry = new BufferGeometry();
  21332. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  21333. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21334. _coneGeometry.translate( 0, - 0.5, 0 );
  21335. }
  21336. this.position.copy( origin );
  21337. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21338. this.line.matrixAutoUpdate = false;
  21339. this.add( this.line );
  21340. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  21341. this.cone.matrixAutoUpdate = false;
  21342. this.add( this.cone );
  21343. this.setDirection( dir );
  21344. this.setLength( length, headLength, headWidth );
  21345. }
  21346. setDirection( dir ) {
  21347. // dir is assumed to be normalized
  21348. if ( dir.y > 0.99999 ) {
  21349. this.quaternion.set( 0, 0, 0, 1 );
  21350. } else if ( dir.y < - 0.99999 ) {
  21351. this.quaternion.set( 1, 0, 0, 0 );
  21352. } else {
  21353. _axis.set( dir.z, 0, - dir.x ).normalize();
  21354. const radians = Math.acos( dir.y );
  21355. this.quaternion.setFromAxisAngle( _axis, radians );
  21356. }
  21357. }
  21358. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21359. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  21360. this.line.updateMatrix();
  21361. this.cone.scale.set( headWidth, headLength, headWidth );
  21362. this.cone.position.y = length;
  21363. this.cone.updateMatrix();
  21364. }
  21365. setColor( color ) {
  21366. this.line.material.color.set( color );
  21367. this.cone.material.color.set( color );
  21368. }
  21369. copy( source ) {
  21370. super.copy( source, false );
  21371. this.line.copy( source.line );
  21372. this.cone.copy( source.cone );
  21373. return this;
  21374. }
  21375. dispose() {
  21376. this.line.geometry.dispose();
  21377. this.line.material.dispose();
  21378. this.cone.geometry.dispose();
  21379. this.cone.material.dispose();
  21380. }
  21381. }
  21382. class AxesHelper extends LineSegments {
  21383. constructor( size = 1 ) {
  21384. const vertices = [
  21385. 0, 0, 0, size, 0, 0,
  21386. 0, 0, 0, 0, size, 0,
  21387. 0, 0, 0, 0, 0, size
  21388. ];
  21389. const colors = [
  21390. 1, 0, 0, 1, 0.6, 0,
  21391. 0, 1, 0, 0.6, 1, 0,
  21392. 0, 0, 1, 0, 0.6, 1
  21393. ];
  21394. const geometry = new BufferGeometry();
  21395. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21396. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21397. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21398. super( geometry, material );
  21399. this.type = 'AxesHelper';
  21400. }
  21401. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  21402. const color = new Color();
  21403. const array = this.geometry.attributes.color.array;
  21404. color.set( xAxisColor );
  21405. color.toArray( array, 0 );
  21406. color.toArray( array, 3 );
  21407. color.set( yAxisColor );
  21408. color.toArray( array, 6 );
  21409. color.toArray( array, 9 );
  21410. color.set( zAxisColor );
  21411. color.toArray( array, 12 );
  21412. color.toArray( array, 15 );
  21413. this.geometry.attributes.color.needsUpdate = true;
  21414. return this;
  21415. }
  21416. dispose() {
  21417. this.geometry.dispose();
  21418. this.material.dispose();
  21419. }
  21420. }
  21421. class ShapePath {
  21422. constructor() {
  21423. this.type = 'ShapePath';
  21424. this.color = new Color();
  21425. this.subPaths = [];
  21426. this.currentPath = null;
  21427. }
  21428. moveTo( x, y ) {
  21429. this.currentPath = new Path();
  21430. this.subPaths.push( this.currentPath );
  21431. this.currentPath.moveTo( x, y );
  21432. return this;
  21433. }
  21434. lineTo( x, y ) {
  21435. this.currentPath.lineTo( x, y );
  21436. return this;
  21437. }
  21438. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21439. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21440. return this;
  21441. }
  21442. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21443. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21444. return this;
  21445. }
  21446. splineThru( pts ) {
  21447. this.currentPath.splineThru( pts );
  21448. return this;
  21449. }
  21450. toShapes( isCCW ) {
  21451. function toShapesNoHoles( inSubpaths ) {
  21452. const shapes = [];
  21453. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21454. const tmpPath = inSubpaths[ i ];
  21455. const tmpShape = new Shape();
  21456. tmpShape.curves = tmpPath.curves;
  21457. shapes.push( tmpShape );
  21458. }
  21459. return shapes;
  21460. }
  21461. function isPointInsidePolygon( inPt, inPolygon ) {
  21462. const polyLen = inPolygon.length;
  21463. // inPt on polygon contour => immediate success or
  21464. // toggling of inside/outside at every single! intersection point of an edge
  21465. // with the horizontal line through inPt, left of inPt
  21466. // not counting lowerY endpoints of edges and whole edges on that line
  21467. let inside = false;
  21468. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21469. let edgeLowPt = inPolygon[ p ];
  21470. let edgeHighPt = inPolygon[ q ];
  21471. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  21472. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  21473. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21474. // not parallel
  21475. if ( edgeDy < 0 ) {
  21476. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21477. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21478. }
  21479. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21480. if ( inPt.y === edgeLowPt.y ) {
  21481. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21482. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21483. } else {
  21484. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21485. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21486. if ( perpEdge < 0 ) continue;
  21487. inside = ! inside; // true intersection left of inPt
  21488. }
  21489. } else {
  21490. // parallel or collinear
  21491. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21492. // edge lies on the same horizontal line as inPt
  21493. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21494. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21495. // continue;
  21496. }
  21497. }
  21498. return inside;
  21499. }
  21500. const isClockWise = ShapeUtils.isClockWise;
  21501. const subPaths = this.subPaths;
  21502. if ( subPaths.length === 0 ) return [];
  21503. let solid, tmpPath, tmpShape;
  21504. const shapes = [];
  21505. if ( subPaths.length === 1 ) {
  21506. tmpPath = subPaths[ 0 ];
  21507. tmpShape = new Shape();
  21508. tmpShape.curves = tmpPath.curves;
  21509. shapes.push( tmpShape );
  21510. return shapes;
  21511. }
  21512. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21513. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21514. // console.log("Holes first", holesFirst);
  21515. const betterShapeHoles = [];
  21516. const newShapes = [];
  21517. let newShapeHoles = [];
  21518. let mainIdx = 0;
  21519. let tmpPoints;
  21520. newShapes[ mainIdx ] = undefined;
  21521. newShapeHoles[ mainIdx ] = [];
  21522. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  21523. tmpPath = subPaths[ i ];
  21524. tmpPoints = tmpPath.getPoints();
  21525. solid = isClockWise( tmpPoints );
  21526. solid = isCCW ? ! solid : solid;
  21527. if ( solid ) {
  21528. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21529. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21530. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21531. if ( holesFirst ) mainIdx ++;
  21532. newShapeHoles[ mainIdx ] = [];
  21533. //console.log('cw', i);
  21534. } else {
  21535. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21536. //console.log('ccw', i);
  21537. }
  21538. }
  21539. // only Holes? -> probably all Shapes with wrong orientation
  21540. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21541. if ( newShapes.length > 1 ) {
  21542. let ambiguous = false;
  21543. let toChange = 0;
  21544. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21545. betterShapeHoles[ sIdx ] = [];
  21546. }
  21547. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21548. const sho = newShapeHoles[ sIdx ];
  21549. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21550. const ho = sho[ hIdx ];
  21551. let hole_unassigned = true;
  21552. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21553. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21554. if ( sIdx !== s2Idx ) toChange ++;
  21555. if ( hole_unassigned ) {
  21556. hole_unassigned = false;
  21557. betterShapeHoles[ s2Idx ].push( ho );
  21558. } else {
  21559. ambiguous = true;
  21560. }
  21561. }
  21562. }
  21563. if ( hole_unassigned ) {
  21564. betterShapeHoles[ sIdx ].push( ho );
  21565. }
  21566. }
  21567. }
  21568. if ( toChange > 0 && ambiguous === false ) {
  21569. newShapeHoles = betterShapeHoles;
  21570. }
  21571. }
  21572. let tmpHoles;
  21573. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  21574. tmpShape = newShapes[ i ].s;
  21575. shapes.push( tmpShape );
  21576. tmpHoles = newShapeHoles[ i ];
  21577. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21578. tmpShape.holes.push( tmpHoles[ j ].h );
  21579. }
  21580. }
  21581. //console.log("shape", shapes);
  21582. return shapes;
  21583. }
  21584. }
  21585. class Controls extends EventDispatcher {
  21586. constructor( object, domElement = null ) {
  21587. super();
  21588. this.object = object;
  21589. this.domElement = domElement;
  21590. this.enabled = true;
  21591. this.state = - 1;
  21592. this.keys = {};
  21593. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  21594. this.touches = { ONE: null, TWO: null };
  21595. }
  21596. connect() {}
  21597. disconnect() {}
  21598. dispose() {}
  21599. update( /* delta */ ) {}
  21600. }
  21601. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  21602. constructor( width = 1, height = 1, count = 1, options = {} ) {
  21603. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  21604. super( width, height, { ...options, count } );
  21605. this.isWebGLMultipleRenderTargets = true;
  21606. }
  21607. get texture() {
  21608. return this.textures;
  21609. }
  21610. }
  21611. const refreshUniforms = [
  21612. 'alphaMap',
  21613. 'alphaTest',
  21614. 'anisotropy',
  21615. 'anisotropyMap',
  21616. 'anisotropyRotation',
  21617. 'aoMap',
  21618. 'attenuationColor',
  21619. 'attenuationDistance',
  21620. 'bumpMap',
  21621. 'clearcoat',
  21622. 'clearcoatMap',
  21623. 'clearcoatNormalMap',
  21624. 'clearcoatNormalScale',
  21625. 'clearcoatRoughness',
  21626. 'color',
  21627. 'dispersion',
  21628. 'displacementMap',
  21629. 'emissive',
  21630. 'emissiveMap',
  21631. 'envMap',
  21632. 'gradientMap',
  21633. 'ior',
  21634. 'iridescence',
  21635. 'iridescenceIOR',
  21636. 'iridescenceMap',
  21637. 'iridescenceThicknessMap',
  21638. 'lightMap',
  21639. 'map',
  21640. 'matcap',
  21641. 'metalness',
  21642. 'metalnessMap',
  21643. 'normalMap',
  21644. 'normalScale',
  21645. 'opacity',
  21646. 'roughness',
  21647. 'roughnessMap',
  21648. 'sheen',
  21649. 'sheenColor',
  21650. 'sheenColorMap',
  21651. 'sheenRoughnessMap',
  21652. 'shininess',
  21653. 'specular',
  21654. 'specularColor',
  21655. 'specularColorMap',
  21656. 'specularIntensity',
  21657. 'specularIntensityMap',
  21658. 'specularMap',
  21659. 'thickness',
  21660. 'transmission',
  21661. 'transmissionMap'
  21662. ];
  21663. class NodeMaterialObserver {
  21664. constructor( builder ) {
  21665. this.renderObjects = new WeakMap();
  21666. this.hasNode = this.containsNode( builder );
  21667. this.hasAnimation = builder.object.isSkinnedMesh === true;
  21668. this.refreshUniforms = refreshUniforms;
  21669. this.renderId = 0;
  21670. }
  21671. firstInitialization( renderObject ) {
  21672. const hasInitialized = this.renderObjects.has( renderObject );
  21673. if ( hasInitialized === false ) {
  21674. this.getRenderObjectData( renderObject );
  21675. return true;
  21676. }
  21677. return false;
  21678. }
  21679. getRenderObjectData( renderObject ) {
  21680. let data = this.renderObjects.get( renderObject );
  21681. if ( data === undefined ) {
  21682. const { geometry, material } = renderObject;
  21683. data = {
  21684. material: this.getMaterialData( material ),
  21685. geometry: {
  21686. attributes: this.getAttributesData( geometry.attributes ),
  21687. indexVersion: geometry.index ? geometry.index.version : null,
  21688. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  21689. },
  21690. worldMatrix: renderObject.object.matrixWorld.clone()
  21691. };
  21692. if ( renderObject.object.center ) {
  21693. data.center = renderObject.object.center.clone();
  21694. }
  21695. if ( renderObject.object.morphTargetInfluences ) {
  21696. data.morphTargetInfluences = renderObject.object.morphTargetInfluences.slice();
  21697. }
  21698. if ( renderObject.bundle !== null ) {
  21699. data.version = renderObject.bundle.version;
  21700. }
  21701. if ( data.material.transmission > 0 ) {
  21702. const { width, height } = renderObject.context;
  21703. data.bufferWidth = width;
  21704. data.bufferHeight = height;
  21705. }
  21706. this.renderObjects.set( renderObject, data );
  21707. }
  21708. return data;
  21709. }
  21710. getAttributesData( attributes ) {
  21711. const attributesData = {};
  21712. for ( const name in attributes ) {
  21713. const attribute = attributes[ name ];
  21714. attributesData[ name ] = {
  21715. version: attribute.version
  21716. };
  21717. }
  21718. return attributesData;
  21719. }
  21720. containsNode( builder ) {
  21721. const material = builder.material;
  21722. for ( const property in material ) {
  21723. if ( material[ property ] && material[ property ].isNode )
  21724. return true;
  21725. }
  21726. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  21727. return true;
  21728. return false;
  21729. }
  21730. getMaterialData( material ) {
  21731. const data = {};
  21732. for ( const property of this.refreshUniforms ) {
  21733. const value = material[ property ];
  21734. if ( value === null || value === undefined ) continue;
  21735. if ( typeof value === 'object' && value.clone !== undefined ) {
  21736. if ( value.isTexture === true ) {
  21737. data[ property ] = { id: value.id, version: value.version };
  21738. } else {
  21739. data[ property ] = value.clone();
  21740. }
  21741. } else {
  21742. data[ property ] = value;
  21743. }
  21744. }
  21745. return data;
  21746. }
  21747. equals( renderObject ) {
  21748. const { object, material, geometry } = renderObject;
  21749. const renderObjectData = this.getRenderObjectData( renderObject );
  21750. // world matrix
  21751. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  21752. renderObjectData.worldMatrix.copy( object.matrixWorld );
  21753. return false;
  21754. }
  21755. // material
  21756. const materialData = renderObjectData.material;
  21757. for ( const property in materialData ) {
  21758. const value = materialData[ property ];
  21759. const mtlValue = material[ property ];
  21760. if ( value.equals !== undefined ) {
  21761. if ( value.equals( mtlValue ) === false ) {
  21762. value.copy( mtlValue );
  21763. return false;
  21764. }
  21765. } else if ( mtlValue.isTexture === true ) {
  21766. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  21767. value.id = mtlValue.id;
  21768. value.version = mtlValue.version;
  21769. return false;
  21770. }
  21771. } else if ( value !== mtlValue ) {
  21772. materialData[ property ] = mtlValue;
  21773. return false;
  21774. }
  21775. }
  21776. if ( materialData.transmission > 0 ) {
  21777. const { width, height } = renderObject.context;
  21778. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  21779. renderObjectData.bufferWidth = width;
  21780. renderObjectData.bufferHeight = height;
  21781. return false;
  21782. }
  21783. }
  21784. // geometry
  21785. const storedGeometryData = renderObjectData.geometry;
  21786. const attributes = geometry.attributes;
  21787. const storedAttributes = storedGeometryData.attributes;
  21788. const storedAttributeNames = Object.keys( storedAttributes );
  21789. const currentAttributeNames = Object.keys( attributes );
  21790. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  21791. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  21792. return false;
  21793. }
  21794. // Compare each attribute
  21795. for ( const name of storedAttributeNames ) {
  21796. const storedAttributeData = storedAttributes[ name ];
  21797. const attribute = attributes[ name ];
  21798. if ( attribute === undefined ) {
  21799. // Attribute was removed
  21800. delete storedAttributes[ name ];
  21801. return false;
  21802. }
  21803. if ( storedAttributeData.version !== attribute.version ) {
  21804. storedAttributeData.version = attribute.version;
  21805. return false;
  21806. }
  21807. }
  21808. // Check index
  21809. const index = geometry.index;
  21810. const storedIndexVersion = storedGeometryData.indexVersion;
  21811. const currentIndexVersion = index ? index.version : null;
  21812. if ( storedIndexVersion !== currentIndexVersion ) {
  21813. storedGeometryData.indexVersion = currentIndexVersion;
  21814. return false;
  21815. }
  21816. // Check drawRange
  21817. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  21818. storedGeometryData.drawRange.start = geometry.drawRange.start;
  21819. storedGeometryData.drawRange.count = geometry.drawRange.count;
  21820. return false;
  21821. }
  21822. // morph targets
  21823. if ( renderObjectData.morphTargetInfluences ) {
  21824. let morphChanged = false;
  21825. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  21826. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  21827. morphChanged = true;
  21828. }
  21829. }
  21830. if ( morphChanged ) return true;
  21831. }
  21832. // center
  21833. if ( renderObjectData.center ) {
  21834. if ( renderObjectData.center.equals( object.center ) === false ) {
  21835. renderObjectData.center.copy( object.center );
  21836. return true;
  21837. }
  21838. }
  21839. // bundle
  21840. if ( renderObject.bundle !== null ) {
  21841. renderObjectData.version = renderObject.bundle.version;
  21842. }
  21843. return true;
  21844. }
  21845. needsRefresh( renderObject, nodeFrame ) {
  21846. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  21847. return true;
  21848. const { renderId } = nodeFrame;
  21849. if ( this.renderId !== renderId ) {
  21850. this.renderId = renderId;
  21851. return true;
  21852. }
  21853. const isStatic = renderObject.object.static === true;
  21854. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  21855. if ( isStatic || isBundle )
  21856. return false;
  21857. const notEqual = this.equals( renderObject ) !== true;
  21858. return notEqual;
  21859. }
  21860. }
  21861. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  21862. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  21863. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  21864. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  21865. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  21866. function cyrb53( value, seed = 0 ) {
  21867. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  21868. if ( value instanceof Array ) {
  21869. for ( let i = 0, val; i < value.length; i ++ ) {
  21870. val = value[ i ];
  21871. h1 = Math.imul( h1 ^ val, 2654435761 );
  21872. h2 = Math.imul( h2 ^ val, 1597334677 );
  21873. }
  21874. } else {
  21875. for ( let i = 0, ch; i < value.length; i ++ ) {
  21876. ch = value.charCodeAt( i );
  21877. h1 = Math.imul( h1 ^ ch, 2654435761 );
  21878. h2 = Math.imul( h2 ^ ch, 1597334677 );
  21879. }
  21880. }
  21881. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  21882. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  21883. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  21884. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  21885. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  21886. }
  21887. const hashString = ( str ) => cyrb53( str );
  21888. const hashArray = ( array ) => cyrb53( array );
  21889. const hash$1 = ( ...params ) => cyrb53( params );
  21890. function getCacheKey$1( object, force = false ) {
  21891. const values = [];
  21892. if ( object.isNode === true ) {
  21893. values.push( object.id );
  21894. object = object.getSelf();
  21895. }
  21896. for ( const { property, childNode } of getNodeChildren( object ) ) {
  21897. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  21898. }
  21899. return cyrb53( values );
  21900. }
  21901. function* getNodeChildren( node, toJSON = false ) {
  21902. for ( const property in node ) {
  21903. // Ignore private properties.
  21904. if ( property.startsWith( '_' ) === true ) continue;
  21905. const object = node[ property ];
  21906. if ( Array.isArray( object ) === true ) {
  21907. for ( let i = 0; i < object.length; i ++ ) {
  21908. const child = object[ i ];
  21909. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21910. yield { property, index: i, childNode: child };
  21911. }
  21912. }
  21913. } else if ( object && object.isNode === true ) {
  21914. yield { property, childNode: object };
  21915. } else if ( typeof object === 'object' ) {
  21916. for ( const subProperty in object ) {
  21917. const child = object[ subProperty ];
  21918. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21919. yield { property, index: subProperty, childNode: child };
  21920. }
  21921. }
  21922. }
  21923. }
  21924. }
  21925. function getValueType( value ) {
  21926. if ( value === undefined || value === null ) return null;
  21927. const typeOf = typeof value;
  21928. if ( value.isNode === true ) {
  21929. return 'node';
  21930. } else if ( typeOf === 'number' ) {
  21931. return 'float';
  21932. } else if ( typeOf === 'boolean' ) {
  21933. return 'bool';
  21934. } else if ( typeOf === 'string' ) {
  21935. return 'string';
  21936. } else if ( typeOf === 'function' ) {
  21937. return 'shader';
  21938. } else if ( value.isVector2 === true ) {
  21939. return 'vec2';
  21940. } else if ( value.isVector3 === true ) {
  21941. return 'vec3';
  21942. } else if ( value.isVector4 === true ) {
  21943. return 'vec4';
  21944. } else if ( value.isMatrix3 === true ) {
  21945. return 'mat3';
  21946. } else if ( value.isMatrix4 === true ) {
  21947. return 'mat4';
  21948. } else if ( value.isColor === true ) {
  21949. return 'color';
  21950. } else if ( value instanceof ArrayBuffer ) {
  21951. return 'ArrayBuffer';
  21952. }
  21953. return null;
  21954. }
  21955. function getValueFromType( type, ...params ) {
  21956. const last4 = type ? type.slice( - 4 ) : undefined;
  21957. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  21958. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  21959. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  21960. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  21961. }
  21962. if ( type === 'color' ) {
  21963. return new Color( ...params );
  21964. } else if ( last4 === 'vec2' ) {
  21965. return new Vector2( ...params );
  21966. } else if ( last4 === 'vec3' ) {
  21967. return new Vector3( ...params );
  21968. } else if ( last4 === 'vec4' ) {
  21969. return new Vector4( ...params );
  21970. } else if ( last4 === 'mat3' ) {
  21971. return new Matrix3( ...params );
  21972. } else if ( last4 === 'mat4' ) {
  21973. return new Matrix4( ...params );
  21974. } else if ( type === 'bool' ) {
  21975. return params[ 0 ] || false;
  21976. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  21977. return params[ 0 ] || 0;
  21978. } else if ( type === 'string' ) {
  21979. return params[ 0 ] || '';
  21980. } else if ( type === 'ArrayBuffer' ) {
  21981. return base64ToArrayBuffer( params[ 0 ] );
  21982. }
  21983. return null;
  21984. }
  21985. function arrayBufferToBase64( arrayBuffer ) {
  21986. let chars = '';
  21987. const array = new Uint8Array( arrayBuffer );
  21988. for ( let i = 0; i < array.length; i ++ ) {
  21989. chars += String.fromCharCode( array[ i ] );
  21990. }
  21991. return btoa( chars );
  21992. }
  21993. function base64ToArrayBuffer( base64 ) {
  21994. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  21995. }
  21996. var NodeUtils = /*#__PURE__*/Object.freeze({
  21997. __proto__: null,
  21998. arrayBufferToBase64: arrayBufferToBase64,
  21999. base64ToArrayBuffer: base64ToArrayBuffer,
  22000. getCacheKey: getCacheKey$1,
  22001. getNodeChildren: getNodeChildren,
  22002. getValueFromType: getValueFromType,
  22003. getValueType: getValueType,
  22004. hash: hash$1,
  22005. hashArray: hashArray,
  22006. hashString: hashString
  22007. });
  22008. const NodeShaderStage = {
  22009. VERTEX: 'vertex',
  22010. FRAGMENT: 'fragment'
  22011. };
  22012. const NodeUpdateType = {
  22013. NONE: 'none',
  22014. FRAME: 'frame',
  22015. RENDER: 'render',
  22016. OBJECT: 'object'
  22017. };
  22018. const NodeType = {
  22019. BOOLEAN: 'bool',
  22020. INTEGER: 'int',
  22021. FLOAT: 'float',
  22022. VECTOR2: 'vec2',
  22023. VECTOR3: 'vec3',
  22024. VECTOR4: 'vec4',
  22025. MATRIX2: 'mat2',
  22026. MATRIX3: 'mat3',
  22027. MATRIX4: 'mat4'
  22028. };
  22029. const defaultShaderStages = [ 'fragment', 'vertex' ];
  22030. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  22031. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  22032. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  22033. let _nodeId = 0;
  22034. class Node extends EventDispatcher {
  22035. static get type() {
  22036. return 'Node';
  22037. }
  22038. constructor( nodeType = null ) {
  22039. super();
  22040. this.nodeType = nodeType;
  22041. this.updateType = NodeUpdateType.NONE;
  22042. this.updateBeforeType = NodeUpdateType.NONE;
  22043. this.updateAfterType = NodeUpdateType.NONE;
  22044. this.uuid = MathUtils.generateUUID();
  22045. this.version = 0;
  22046. this._cacheKey = null;
  22047. this._cacheKeyVersion = 0;
  22048. this.global = false;
  22049. this.isNode = true;
  22050. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  22051. }
  22052. set needsUpdate( value ) {
  22053. if ( value === true ) {
  22054. this.version ++;
  22055. }
  22056. }
  22057. get type() {
  22058. return this.constructor.type;
  22059. }
  22060. onUpdate( callback, updateType ) {
  22061. this.updateType = updateType;
  22062. this.update = callback.bind( this.getSelf() );
  22063. return this;
  22064. }
  22065. onFrameUpdate( callback ) {
  22066. return this.onUpdate( callback, NodeUpdateType.FRAME );
  22067. }
  22068. onRenderUpdate( callback ) {
  22069. return this.onUpdate( callback, NodeUpdateType.RENDER );
  22070. }
  22071. onObjectUpdate( callback ) {
  22072. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  22073. }
  22074. onReference( callback ) {
  22075. this.updateReference = callback.bind( this.getSelf() );
  22076. return this;
  22077. }
  22078. getSelf() {
  22079. // Returns non-node object.
  22080. return this.self || this;
  22081. }
  22082. updateReference( /*state*/ ) {
  22083. return this;
  22084. }
  22085. isGlobal( /*builder*/ ) {
  22086. return this.global;
  22087. }
  22088. * getChildren() {
  22089. for ( const { childNode } of getNodeChildren( this ) ) {
  22090. yield childNode;
  22091. }
  22092. }
  22093. dispose() {
  22094. this.dispatchEvent( { type: 'dispose' } );
  22095. }
  22096. traverse( callback ) {
  22097. callback( this );
  22098. for ( const childNode of this.getChildren() ) {
  22099. childNode.traverse( callback );
  22100. }
  22101. }
  22102. getCacheKey( force = false ) {
  22103. force = force || this.version !== this._cacheKeyVersion;
  22104. if ( force === true || this._cacheKey === null ) {
  22105. this._cacheKey = getCacheKey$1( this, force );
  22106. this._cacheKeyVersion = this.version;
  22107. }
  22108. return this._cacheKey;
  22109. }
  22110. getScope() {
  22111. return this;
  22112. }
  22113. getHash( /*builder*/ ) {
  22114. return this.uuid;
  22115. }
  22116. getUpdateType() {
  22117. return this.updateType;
  22118. }
  22119. getUpdateBeforeType() {
  22120. return this.updateBeforeType;
  22121. }
  22122. getUpdateAfterType() {
  22123. return this.updateAfterType;
  22124. }
  22125. getElementType( builder ) {
  22126. const type = this.getNodeType( builder );
  22127. const elementType = builder.getElementType( type );
  22128. return elementType;
  22129. }
  22130. getNodeType( builder ) {
  22131. const nodeProperties = builder.getNodeProperties( this );
  22132. if ( nodeProperties.outputNode ) {
  22133. return nodeProperties.outputNode.getNodeType( builder );
  22134. }
  22135. return this.nodeType;
  22136. }
  22137. getShared( builder ) {
  22138. const hash = this.getHash( builder );
  22139. const nodeFromHash = builder.getNodeFromHash( hash );
  22140. return nodeFromHash || this;
  22141. }
  22142. setup( builder ) {
  22143. const nodeProperties = builder.getNodeProperties( this );
  22144. let index = 0;
  22145. for ( const childNode of this.getChildren() ) {
  22146. nodeProperties[ 'node' + index ++ ] = childNode;
  22147. }
  22148. // return a outputNode if exists
  22149. return null;
  22150. }
  22151. analyze( builder ) {
  22152. const usageCount = builder.increaseUsage( this );
  22153. if ( usageCount === 1 ) {
  22154. // node flow children
  22155. const nodeProperties = builder.getNodeProperties( this );
  22156. for ( const childNode of Object.values( nodeProperties ) ) {
  22157. if ( childNode && childNode.isNode === true ) {
  22158. childNode.build( builder );
  22159. }
  22160. }
  22161. }
  22162. }
  22163. generate( builder, output ) {
  22164. const { outputNode } = builder.getNodeProperties( this );
  22165. if ( outputNode && outputNode.isNode === true ) {
  22166. return outputNode.build( builder, output );
  22167. }
  22168. }
  22169. updateBefore( /*frame*/ ) {
  22170. console.warn( 'Abstract function.' );
  22171. }
  22172. updateAfter( /*frame*/ ) {
  22173. console.warn( 'Abstract function.' );
  22174. }
  22175. update( /*frame*/ ) {
  22176. console.warn( 'Abstract function.' );
  22177. }
  22178. build( builder, output = null ) {
  22179. const refNode = this.getShared( builder );
  22180. if ( this !== refNode ) {
  22181. return refNode.build( builder, output );
  22182. }
  22183. builder.addNode( this );
  22184. builder.addChain( this );
  22185. /* Build stages expected results:
  22186. - "setup" -> Node
  22187. - "analyze" -> null
  22188. - "generate" -> String
  22189. */
  22190. let result = null;
  22191. const buildStage = builder.getBuildStage();
  22192. if ( buildStage === 'setup' ) {
  22193. this.updateReference( builder );
  22194. const properties = builder.getNodeProperties( this );
  22195. if ( properties.initialized !== true ) {
  22196. const stackNodesBeforeSetup = builder.stack.nodes.length;
  22197. properties.initialized = true;
  22198. properties.outputNode = this.setup( builder );
  22199. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  22200. for ( const childNode of Object.values( properties ) ) {
  22201. if ( childNode && childNode.isNode === true ) {
  22202. childNode.build( builder );
  22203. }
  22204. }
  22205. }
  22206. } else if ( buildStage === 'analyze' ) {
  22207. this.analyze( builder );
  22208. } else if ( buildStage === 'generate' ) {
  22209. const isGenerateOnce = this.generate.length === 1;
  22210. if ( isGenerateOnce ) {
  22211. const type = this.getNodeType( builder );
  22212. const nodeData = builder.getDataFromNode( this );
  22213. result = nodeData.snippet;
  22214. if ( result === undefined ) {
  22215. result = this.generate( builder ) || '';
  22216. nodeData.snippet = result;
  22217. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  22218. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  22219. }
  22220. result = builder.format( result, type, output );
  22221. } else {
  22222. result = this.generate( builder, output ) || '';
  22223. }
  22224. }
  22225. builder.removeChain( this );
  22226. builder.addSequentialNode( this );
  22227. return result;
  22228. }
  22229. getSerializeChildren() {
  22230. return getNodeChildren( this );
  22231. }
  22232. serialize( json ) {
  22233. const nodeChildren = this.getSerializeChildren();
  22234. const inputNodes = {};
  22235. for ( const { property, index, childNode } of nodeChildren ) {
  22236. if ( index !== undefined ) {
  22237. if ( inputNodes[ property ] === undefined ) {
  22238. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  22239. }
  22240. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  22241. } else {
  22242. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  22243. }
  22244. }
  22245. if ( Object.keys( inputNodes ).length > 0 ) {
  22246. json.inputNodes = inputNodes;
  22247. }
  22248. }
  22249. deserialize( json ) {
  22250. if ( json.inputNodes !== undefined ) {
  22251. const nodes = json.meta.nodes;
  22252. for ( const property in json.inputNodes ) {
  22253. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  22254. const inputArray = [];
  22255. for ( const uuid of json.inputNodes[ property ] ) {
  22256. inputArray.push( nodes[ uuid ] );
  22257. }
  22258. this[ property ] = inputArray;
  22259. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  22260. const inputObject = {};
  22261. for ( const subProperty in json.inputNodes[ property ] ) {
  22262. const uuid = json.inputNodes[ property ][ subProperty ];
  22263. inputObject[ subProperty ] = nodes[ uuid ];
  22264. }
  22265. this[ property ] = inputObject;
  22266. } else {
  22267. const uuid = json.inputNodes[ property ];
  22268. this[ property ] = nodes[ uuid ];
  22269. }
  22270. }
  22271. }
  22272. }
  22273. toJSON( meta ) {
  22274. const { uuid, type } = this;
  22275. const isRoot = ( meta === undefined || typeof meta === 'string' );
  22276. if ( isRoot ) {
  22277. meta = {
  22278. textures: {},
  22279. images: {},
  22280. nodes: {}
  22281. };
  22282. }
  22283. // serialize
  22284. let data = meta.nodes[ uuid ];
  22285. if ( data === undefined ) {
  22286. data = {
  22287. uuid,
  22288. type,
  22289. meta,
  22290. metadata: {
  22291. version: 4.6,
  22292. type: 'Node',
  22293. generator: 'Node.toJSON'
  22294. }
  22295. };
  22296. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  22297. this.serialize( data );
  22298. delete data.meta;
  22299. }
  22300. // TODO: Copied from Object3D.toJSON
  22301. function extractFromCache( cache ) {
  22302. const values = [];
  22303. for ( const key in cache ) {
  22304. const data = cache[ key ];
  22305. delete data.metadata;
  22306. values.push( data );
  22307. }
  22308. return values;
  22309. }
  22310. if ( isRoot ) {
  22311. const textures = extractFromCache( meta.textures );
  22312. const images = extractFromCache( meta.images );
  22313. const nodes = extractFromCache( meta.nodes );
  22314. if ( textures.length > 0 ) data.textures = textures;
  22315. if ( images.length > 0 ) data.images = images;
  22316. if ( nodes.length > 0 ) data.nodes = nodes;
  22317. }
  22318. return data;
  22319. }
  22320. }
  22321. class ArrayElementNode extends Node {
  22322. static get type() {
  22323. return 'ArrayElementNode';
  22324. } // @TODO: If extending from TempNode it breaks webgpu_compute
  22325. constructor( node, indexNode ) {
  22326. super();
  22327. this.node = node;
  22328. this.indexNode = indexNode;
  22329. this.isArrayElementNode = true;
  22330. }
  22331. getNodeType( builder ) {
  22332. return this.node.getElementType( builder );
  22333. }
  22334. generate( builder ) {
  22335. const nodeSnippet = this.node.build( builder );
  22336. const indexSnippet = this.indexNode.build( builder, 'uint' );
  22337. return `${nodeSnippet}[ ${indexSnippet} ]`;
  22338. }
  22339. }
  22340. class ConvertNode extends Node {
  22341. static get type() {
  22342. return 'ConvertNode';
  22343. }
  22344. constructor( node, convertTo ) {
  22345. super();
  22346. this.node = node;
  22347. this.convertTo = convertTo;
  22348. }
  22349. getNodeType( builder ) {
  22350. const requestType = this.node.getNodeType( builder );
  22351. let convertTo = null;
  22352. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  22353. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  22354. convertTo = overloadingType;
  22355. }
  22356. }
  22357. return convertTo;
  22358. }
  22359. serialize( data ) {
  22360. super.serialize( data );
  22361. data.convertTo = this.convertTo;
  22362. }
  22363. deserialize( data ) {
  22364. super.deserialize( data );
  22365. this.convertTo = data.convertTo;
  22366. }
  22367. generate( builder, output ) {
  22368. const node = this.node;
  22369. const type = this.getNodeType( builder );
  22370. const snippet = node.build( builder, type );
  22371. return builder.format( snippet, type, output );
  22372. }
  22373. }
  22374. class TempNode extends Node {
  22375. static get type() {
  22376. return 'TempNode';
  22377. }
  22378. constructor( type ) {
  22379. super( type );
  22380. this.isTempNode = true;
  22381. }
  22382. hasDependencies( builder ) {
  22383. return builder.getDataFromNode( this ).usageCount > 1;
  22384. }
  22385. build( builder, output ) {
  22386. const buildStage = builder.getBuildStage();
  22387. if ( buildStage === 'generate' ) {
  22388. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  22389. const nodeData = builder.getDataFromNode( this );
  22390. if ( nodeData.propertyName !== undefined ) {
  22391. return builder.format( nodeData.propertyName, type, output );
  22392. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  22393. const snippet = super.build( builder, type );
  22394. const nodeVar = builder.getVarFromNode( this, null, type );
  22395. const propertyName = builder.getPropertyName( nodeVar );
  22396. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  22397. nodeData.snippet = snippet;
  22398. nodeData.propertyName = propertyName;
  22399. return builder.format( nodeData.propertyName, type, output );
  22400. }
  22401. }
  22402. return super.build( builder, output );
  22403. }
  22404. }
  22405. class JoinNode extends TempNode {
  22406. static get type() {
  22407. return 'JoinNode';
  22408. }
  22409. constructor( nodes = [], nodeType = null ) {
  22410. super( nodeType );
  22411. this.nodes = nodes;
  22412. }
  22413. getNodeType( builder ) {
  22414. if ( this.nodeType !== null ) {
  22415. return builder.getVectorType( this.nodeType );
  22416. }
  22417. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  22418. }
  22419. generate( builder, output ) {
  22420. const type = this.getNodeType( builder );
  22421. const nodes = this.nodes;
  22422. const primitiveType = builder.getComponentType( type );
  22423. const snippetValues = [];
  22424. for ( const input of nodes ) {
  22425. let inputSnippet = input.build( builder );
  22426. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  22427. if ( inputPrimitiveType !== primitiveType ) {
  22428. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  22429. }
  22430. snippetValues.push( inputSnippet );
  22431. }
  22432. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  22433. return builder.format( snippet, type, output );
  22434. }
  22435. }
  22436. const stringVectorComponents = vectorComponents.join( '' );
  22437. class SplitNode extends Node {
  22438. static get type() {
  22439. return 'SplitNode';
  22440. }
  22441. constructor( node, components = 'x' ) {
  22442. super();
  22443. this.node = node;
  22444. this.components = components;
  22445. this.isSplitNode = true;
  22446. }
  22447. getVectorLength() {
  22448. let vectorLength = this.components.length;
  22449. for ( const c of this.components ) {
  22450. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  22451. }
  22452. return vectorLength;
  22453. }
  22454. getComponentType( builder ) {
  22455. return builder.getComponentType( this.node.getNodeType( builder ) );
  22456. }
  22457. getNodeType( builder ) {
  22458. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  22459. }
  22460. generate( builder, output ) {
  22461. const node = this.node;
  22462. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  22463. let snippet = null;
  22464. if ( nodeTypeLength > 1 ) {
  22465. let type = null;
  22466. const componentsLength = this.getVectorLength();
  22467. if ( componentsLength >= nodeTypeLength ) {
  22468. // needed expand the input node
  22469. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  22470. }
  22471. const nodeSnippet = node.build( builder, type );
  22472. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  22473. // unnecessary swizzle
  22474. snippet = builder.format( nodeSnippet, type, output );
  22475. } else {
  22476. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  22477. }
  22478. } else {
  22479. // ignore .components if .node returns float/integer
  22480. snippet = node.build( builder, output );
  22481. }
  22482. return snippet;
  22483. }
  22484. serialize( data ) {
  22485. super.serialize( data );
  22486. data.components = this.components;
  22487. }
  22488. deserialize( data ) {
  22489. super.deserialize( data );
  22490. this.components = data.components;
  22491. }
  22492. }
  22493. class SetNode extends TempNode {
  22494. static get type() {
  22495. return 'SetNode';
  22496. }
  22497. constructor( sourceNode, components, targetNode ) {
  22498. super();
  22499. this.sourceNode = sourceNode;
  22500. this.components = components;
  22501. this.targetNode = targetNode;
  22502. }
  22503. getNodeType( builder ) {
  22504. return this.sourceNode.getNodeType( builder );
  22505. }
  22506. generate( builder ) {
  22507. const { sourceNode, components, targetNode } = this;
  22508. const sourceType = this.getNodeType( builder );
  22509. const targetType = builder.getTypeFromLength( components.length, targetNode.getNodeType( builder ) );
  22510. const targetSnippet = targetNode.build( builder, targetType );
  22511. const sourceSnippet = sourceNode.build( builder, sourceType );
  22512. const length = builder.getTypeLength( sourceType );
  22513. const snippetValues = [];
  22514. for ( let i = 0; i < length; i ++ ) {
  22515. const component = vectorComponents[ i ];
  22516. if ( component === components[ 0 ] ) {
  22517. snippetValues.push( targetSnippet );
  22518. i += components.length - 1;
  22519. } else {
  22520. snippetValues.push( sourceSnippet + '.' + component );
  22521. }
  22522. }
  22523. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22524. }
  22525. }
  22526. class FlipNode extends TempNode {
  22527. static get type() {
  22528. return 'FlipNode';
  22529. }
  22530. constructor( sourceNode, components ) {
  22531. super();
  22532. this.sourceNode = sourceNode;
  22533. this.components = components;
  22534. }
  22535. getNodeType( builder ) {
  22536. return this.sourceNode.getNodeType( builder );
  22537. }
  22538. generate( builder ) {
  22539. const { components, sourceNode } = this;
  22540. const sourceType = this.getNodeType( builder );
  22541. const sourceSnippet = sourceNode.build( builder );
  22542. const sourceCache = builder.getVarFromNode( this );
  22543. const sourceProperty = builder.getPropertyName( sourceCache );
  22544. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  22545. const length = builder.getTypeLength( sourceType );
  22546. const snippetValues = [];
  22547. let componentIndex = 0;
  22548. for ( let i = 0; i < length; i ++ ) {
  22549. const component = vectorComponents[ i ];
  22550. if ( component === components[ componentIndex ] ) {
  22551. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  22552. componentIndex ++;
  22553. } else {
  22554. snippetValues.push( sourceProperty + '.' + component );
  22555. }
  22556. }
  22557. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22558. }
  22559. }
  22560. class InputNode extends Node {
  22561. static get type() {
  22562. return 'InputNode';
  22563. }
  22564. constructor( value, nodeType = null ) {
  22565. super( nodeType );
  22566. this.isInputNode = true;
  22567. this.value = value;
  22568. this.precision = null;
  22569. }
  22570. getNodeType( /*builder*/ ) {
  22571. if ( this.nodeType === null ) {
  22572. return getValueType( this.value );
  22573. }
  22574. return this.nodeType;
  22575. }
  22576. getInputType( builder ) {
  22577. return this.getNodeType( builder );
  22578. }
  22579. setPrecision( precision ) {
  22580. this.precision = precision;
  22581. return this;
  22582. }
  22583. serialize( data ) {
  22584. super.serialize( data );
  22585. data.value = this.value;
  22586. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  22587. data.valueType = getValueType( this.value );
  22588. data.nodeType = this.nodeType;
  22589. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  22590. data.precision = this.precision;
  22591. }
  22592. deserialize( data ) {
  22593. super.deserialize( data );
  22594. this.nodeType = data.nodeType;
  22595. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  22596. this.precision = data.precision || null;
  22597. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  22598. }
  22599. generate( /*builder, output*/ ) {
  22600. console.warn( 'Abstract function.' );
  22601. }
  22602. }
  22603. class ConstNode extends InputNode {
  22604. static get type() {
  22605. return 'ConstNode';
  22606. }
  22607. constructor( value, nodeType = null ) {
  22608. super( value, nodeType );
  22609. this.isConstNode = true;
  22610. }
  22611. generateConst( builder ) {
  22612. return builder.generateConst( this.getNodeType( builder ), this.value );
  22613. }
  22614. generate( builder, output ) {
  22615. const type = this.getNodeType( builder );
  22616. return builder.format( this.generateConst( builder ), type, output );
  22617. }
  22618. }
  22619. //
  22620. let currentStack = null;
  22621. const NodeElements = new Map();
  22622. function addMethodChaining( name, nodeElement ) {
  22623. if ( NodeElements.has( name ) ) {
  22624. console.warn( `Redefinition of method chaining ${ name }` );
  22625. return;
  22626. }
  22627. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  22628. NodeElements.set( name, nodeElement );
  22629. }
  22630. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  22631. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  22632. const shaderNodeHandler = {
  22633. setup( NodeClosure, params ) {
  22634. const inputs = params.shift();
  22635. return NodeClosure( nodeObjects( inputs ), ...params );
  22636. },
  22637. get( node, prop, nodeObj ) {
  22638. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22639. if ( node.isStackNode !== true && prop === 'assign' ) {
  22640. return ( ...params ) => {
  22641. currentStack.assign( nodeObj, ...params );
  22642. return nodeObj;
  22643. };
  22644. } else if ( NodeElements.has( prop ) ) {
  22645. const nodeElement = NodeElements.get( prop );
  22646. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  22647. } else if ( prop === 'self' ) {
  22648. return node;
  22649. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  22650. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  22651. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  22652. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  22653. // accessing properties ( swizzle )
  22654. prop = parseSwizzle( prop );
  22655. return nodeObject( new SplitNode( nodeObj, prop ) );
  22656. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22657. // set properties ( swizzle ) and sort to xyzw sequence
  22658. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  22659. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  22660. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22661. // set properties ( swizzle ) and sort to xyzw sequence
  22662. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  22663. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  22664. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  22665. // accessing property
  22666. if ( prop === 'width' ) prop = 'x';
  22667. else if ( prop === 'height' ) prop = 'y';
  22668. else if ( prop === 'depth' ) prop = 'z';
  22669. return nodeObject( new SplitNode( node, prop ) );
  22670. } else if ( /^\d+$/.test( prop ) === true ) {
  22671. // accessing array
  22672. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  22673. }
  22674. }
  22675. return Reflect.get( node, prop, nodeObj );
  22676. },
  22677. set( node, prop, value, nodeObj ) {
  22678. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22679. // setting properties
  22680. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  22681. nodeObj[ prop ].assign( value );
  22682. return true;
  22683. }
  22684. }
  22685. return Reflect.set( node, prop, value, nodeObj );
  22686. }
  22687. };
  22688. const nodeObjectsCacheMap = new WeakMap();
  22689. const nodeBuilderFunctionsCacheMap = new WeakMap();
  22690. const ShaderNodeObject = function ( obj, altType = null ) {
  22691. const type = getValueType( obj );
  22692. if ( type === 'node' ) {
  22693. let nodeObject = nodeObjectsCacheMap.get( obj );
  22694. if ( nodeObject === undefined ) {
  22695. nodeObject = new Proxy( obj, shaderNodeHandler );
  22696. nodeObjectsCacheMap.set( obj, nodeObject );
  22697. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  22698. }
  22699. return nodeObject;
  22700. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  22701. return nodeObject( getConstNode( obj, altType ) );
  22702. } else if ( type === 'shader' ) {
  22703. return Fn( obj );
  22704. }
  22705. return obj;
  22706. };
  22707. const ShaderNodeObjects = function ( objects, altType = null ) {
  22708. for ( const name in objects ) {
  22709. objects[ name ] = nodeObject( objects[ name ], altType );
  22710. }
  22711. return objects;
  22712. };
  22713. const ShaderNodeArray = function ( array, altType = null ) {
  22714. const len = array.length;
  22715. for ( let i = 0; i < len; i ++ ) {
  22716. array[ i ] = nodeObject( array[ i ], altType );
  22717. }
  22718. return array;
  22719. };
  22720. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  22721. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  22722. if ( scope === null ) {
  22723. return ( ...params ) => {
  22724. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  22725. };
  22726. } else if ( factor !== null ) {
  22727. factor = nodeObject( factor );
  22728. return ( ...params ) => {
  22729. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  22730. };
  22731. } else {
  22732. return ( ...params ) => {
  22733. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  22734. };
  22735. }
  22736. };
  22737. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  22738. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  22739. };
  22740. class ShaderCallNodeInternal extends Node {
  22741. constructor( shaderNode, inputNodes ) {
  22742. super();
  22743. this.shaderNode = shaderNode;
  22744. this.inputNodes = inputNodes;
  22745. }
  22746. getNodeType( builder ) {
  22747. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  22748. }
  22749. call( builder ) {
  22750. const { shaderNode, inputNodes } = this;
  22751. const properties = builder.getNodeProperties( shaderNode );
  22752. if ( properties.onceOutput ) return properties.onceOutput;
  22753. //
  22754. let result = null;
  22755. if ( shaderNode.layout ) {
  22756. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  22757. if ( functionNodesCacheMap === undefined ) {
  22758. functionNodesCacheMap = new WeakMap();
  22759. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  22760. }
  22761. let functionNode = functionNodesCacheMap.get( shaderNode );
  22762. if ( functionNode === undefined ) {
  22763. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  22764. functionNodesCacheMap.set( shaderNode, functionNode );
  22765. }
  22766. if ( builder.currentFunctionNode !== null ) {
  22767. builder.currentFunctionNode.includes.push( functionNode );
  22768. }
  22769. result = nodeObject( functionNode.call( inputNodes ) );
  22770. } else {
  22771. const jsFunc = shaderNode.jsFunc;
  22772. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  22773. result = nodeObject( outputNode );
  22774. }
  22775. if ( shaderNode.once ) {
  22776. properties.onceOutput = result;
  22777. }
  22778. return result;
  22779. }
  22780. getOutputNode( builder ) {
  22781. const properties = builder.getNodeProperties( this );
  22782. if ( properties.outputNode === null ) {
  22783. properties.outputNode = this.setupOutput( builder );
  22784. }
  22785. return properties.outputNode;
  22786. }
  22787. setup( builder ) {
  22788. return this.getOutputNode( builder );
  22789. }
  22790. setupOutput( builder ) {
  22791. builder.addStack();
  22792. builder.stack.outputNode = this.call( builder );
  22793. return builder.removeStack();
  22794. }
  22795. generate( builder, output ) {
  22796. const outputNode = this.getOutputNode( builder );
  22797. return outputNode.build( builder, output );
  22798. }
  22799. }
  22800. class ShaderNodeInternal extends Node {
  22801. constructor( jsFunc, nodeType ) {
  22802. super( nodeType );
  22803. this.jsFunc = jsFunc;
  22804. this.layout = null;
  22805. this.global = true;
  22806. this.once = false;
  22807. }
  22808. setLayout( layout ) {
  22809. this.layout = layout;
  22810. return this;
  22811. }
  22812. call( inputs = null ) {
  22813. nodeObjects( inputs );
  22814. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  22815. }
  22816. setup() {
  22817. return this.call();
  22818. }
  22819. }
  22820. const bools = [ false, true ];
  22821. const uints = [ 0, 1, 2, 3 ];
  22822. const ints = [ - 1, - 2 ];
  22823. 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 ];
  22824. const boolsCacheMap = new Map();
  22825. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  22826. const uintsCacheMap = new Map();
  22827. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  22828. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  22829. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  22830. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  22831. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  22832. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  22833. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  22834. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  22835. const getConstNode = ( value, type ) => {
  22836. if ( constNodesCacheMap.has( value ) ) {
  22837. return constNodesCacheMap.get( value );
  22838. } else if ( value.isNode === true ) {
  22839. return value;
  22840. } else {
  22841. return new ConstNode( value, type );
  22842. }
  22843. };
  22844. const safeGetNodeType = ( node ) => {
  22845. try {
  22846. return node.getNodeType();
  22847. } catch ( _ ) {
  22848. return undefined;
  22849. }
  22850. };
  22851. const ConvertType = function ( type, cacheMap = null ) {
  22852. return ( ...params ) => {
  22853. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  22854. params = [ getValueFromType( type, ...params ) ];
  22855. }
  22856. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  22857. return nodeObject( cacheMap.get( params[ 0 ] ) );
  22858. }
  22859. if ( params.length === 1 ) {
  22860. const node = getConstNode( params[ 0 ], type );
  22861. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  22862. return nodeObject( new ConvertNode( node, type ) );
  22863. }
  22864. const nodes = params.map( param => getConstNode( param ) );
  22865. return nodeObject( new JoinNode( nodes, type ) );
  22866. };
  22867. };
  22868. // exports
  22869. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  22870. // utils
  22871. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  22872. // shader node base
  22873. function ShaderNode( jsFunc, nodeType ) {
  22874. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  22875. }
  22876. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  22877. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  22878. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  22879. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  22880. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  22881. const Fn = ( jsFunc, nodeType ) => {
  22882. const shaderNode = new ShaderNode( jsFunc, nodeType );
  22883. const fn = ( ...params ) => {
  22884. let inputs;
  22885. nodeObjects( params );
  22886. if ( params[ 0 ] && params[ 0 ].isNode ) {
  22887. inputs = [ ...params ];
  22888. } else {
  22889. inputs = params[ 0 ];
  22890. }
  22891. return shaderNode.call( inputs );
  22892. };
  22893. fn.shaderNode = shaderNode;
  22894. fn.setLayout = ( layout ) => {
  22895. shaderNode.setLayout( layout );
  22896. return fn;
  22897. };
  22898. fn.once = () => {
  22899. shaderNode.once = true;
  22900. return fn;
  22901. };
  22902. return fn;
  22903. };
  22904. const tslFn = ( ...params ) => { // @deprecated, r168
  22905. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  22906. return Fn( ...params );
  22907. };
  22908. //
  22909. addMethodChaining( 'toGlobal', ( node ) => {
  22910. node.global = true;
  22911. return node;
  22912. } );
  22913. //
  22914. const setCurrentStack = ( stack ) => {
  22915. currentStack = stack;
  22916. };
  22917. const getCurrentStack = () => currentStack;
  22918. const If = ( ...params ) => currentStack.If( ...params );
  22919. function append( node ) {
  22920. if ( currentStack ) currentStack.add( node );
  22921. return node;
  22922. }
  22923. addMethodChaining( 'append', append );
  22924. // types
  22925. const color = new ConvertType( 'color' );
  22926. const float = new ConvertType( 'float', cacheMaps.float );
  22927. const int = new ConvertType( 'int', cacheMaps.ints );
  22928. const uint = new ConvertType( 'uint', cacheMaps.uint );
  22929. const bool = new ConvertType( 'bool', cacheMaps.bool );
  22930. const vec2 = new ConvertType( 'vec2' );
  22931. const ivec2 = new ConvertType( 'ivec2' );
  22932. const uvec2 = new ConvertType( 'uvec2' );
  22933. const bvec2 = new ConvertType( 'bvec2' );
  22934. const vec3 = new ConvertType( 'vec3' );
  22935. const ivec3 = new ConvertType( 'ivec3' );
  22936. const uvec3 = new ConvertType( 'uvec3' );
  22937. const bvec3 = new ConvertType( 'bvec3' );
  22938. const vec4 = new ConvertType( 'vec4' );
  22939. const ivec4 = new ConvertType( 'ivec4' );
  22940. const uvec4 = new ConvertType( 'uvec4' );
  22941. const bvec4 = new ConvertType( 'bvec4' );
  22942. const mat2 = new ConvertType( 'mat2' );
  22943. const mat3 = new ConvertType( 'mat3' );
  22944. const mat4 = new ConvertType( 'mat4' );
  22945. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  22946. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  22947. addMethodChaining( 'toColor', color );
  22948. addMethodChaining( 'toFloat', float );
  22949. addMethodChaining( 'toInt', int );
  22950. addMethodChaining( 'toUint', uint );
  22951. addMethodChaining( 'toBool', bool );
  22952. addMethodChaining( 'toVec2', vec2 );
  22953. addMethodChaining( 'toIVec2', ivec2 );
  22954. addMethodChaining( 'toUVec2', uvec2 );
  22955. addMethodChaining( 'toBVec2', bvec2 );
  22956. addMethodChaining( 'toVec3', vec3 );
  22957. addMethodChaining( 'toIVec3', ivec3 );
  22958. addMethodChaining( 'toUVec3', uvec3 );
  22959. addMethodChaining( 'toBVec3', bvec3 );
  22960. addMethodChaining( 'toVec4', vec4 );
  22961. addMethodChaining( 'toIVec4', ivec4 );
  22962. addMethodChaining( 'toUVec4', uvec4 );
  22963. addMethodChaining( 'toBVec4', bvec4 );
  22964. addMethodChaining( 'toMat2', mat2 );
  22965. addMethodChaining( 'toMat3', mat3 );
  22966. addMethodChaining( 'toMat4', mat4 );
  22967. // basic nodes
  22968. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  22969. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  22970. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  22971. addMethodChaining( 'element', element );
  22972. addMethodChaining( 'convert', convert );
  22973. class UniformGroupNode extends Node {
  22974. static get type() {
  22975. return 'UniformGroupNode';
  22976. }
  22977. constructor( name, shared = false, order = 1 ) {
  22978. super( 'string' );
  22979. this.name = name;
  22980. this.version = 0;
  22981. this.shared = shared;
  22982. this.order = order;
  22983. this.isUniformGroup = true;
  22984. }
  22985. set needsUpdate( value ) {
  22986. if ( value === true ) this.version ++;
  22987. }
  22988. serialize( data ) {
  22989. super.serialize( data );
  22990. data.name = this.name;
  22991. data.version = this.version;
  22992. data.shared = this.shared;
  22993. }
  22994. deserialize( data ) {
  22995. super.deserialize( data );
  22996. this.name = data.name;
  22997. this.version = data.version;
  22998. this.shared = data.shared;
  22999. }
  23000. }
  23001. const uniformGroup = ( name ) => new UniformGroupNode( name );
  23002. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  23003. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  23004. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  23005. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  23006. class UniformNode extends InputNode {
  23007. static get type() {
  23008. return 'UniformNode';
  23009. }
  23010. constructor( value, nodeType = null ) {
  23011. super( value, nodeType );
  23012. this.isUniformNode = true;
  23013. this.name = '';
  23014. this.groupNode = objectGroup;
  23015. }
  23016. label( name ) {
  23017. this.name = name;
  23018. return this;
  23019. }
  23020. setGroup( group ) {
  23021. this.groupNode = group;
  23022. return this;
  23023. }
  23024. getGroup() {
  23025. return this.groupNode;
  23026. }
  23027. getUniformHash( builder ) {
  23028. return this.getHash( builder );
  23029. }
  23030. onUpdate( callback, updateType ) {
  23031. const self = this.getSelf();
  23032. callback = callback.bind( self );
  23033. return super.onUpdate( ( frame ) => {
  23034. const value = callback( frame, self );
  23035. if ( value !== undefined ) {
  23036. this.value = value;
  23037. }
  23038. }, updateType );
  23039. }
  23040. generate( builder, output ) {
  23041. const type = this.getNodeType( builder );
  23042. const hash = this.getUniformHash( builder );
  23043. let sharedNode = builder.getNodeFromHash( hash );
  23044. if ( sharedNode === undefined ) {
  23045. builder.setHashNode( this, hash );
  23046. sharedNode = this;
  23047. }
  23048. const sharedNodeType = sharedNode.getInputType( builder );
  23049. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  23050. const propertyName = builder.getPropertyName( nodeUniform );
  23051. if ( builder.context.label !== undefined ) delete builder.context.label;
  23052. return builder.format( propertyName, type, output );
  23053. }
  23054. }
  23055. const uniform = ( arg1, arg2 ) => {
  23056. const nodeType = getConstNodeType( arg2 || arg1 );
  23057. // @TODO: get ConstNode from .traverse() in the future
  23058. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  23059. return nodeObject( new UniformNode( value, nodeType ) );
  23060. };
  23061. class PropertyNode extends Node {
  23062. static get type() {
  23063. return 'PropertyNode';
  23064. }
  23065. constructor( nodeType, name = null, varying = false ) {
  23066. super( nodeType );
  23067. this.name = name;
  23068. this.varying = varying;
  23069. this.isPropertyNode = true;
  23070. }
  23071. getHash( builder ) {
  23072. return this.name || super.getHash( builder );
  23073. }
  23074. isGlobal( /*builder*/ ) {
  23075. return true;
  23076. }
  23077. generate( builder ) {
  23078. let nodeVar;
  23079. if ( this.varying === true ) {
  23080. nodeVar = builder.getVaryingFromNode( this, this.name );
  23081. nodeVar.needsInterpolation = true;
  23082. } else {
  23083. nodeVar = builder.getVarFromNode( this, this.name );
  23084. }
  23085. return builder.getPropertyName( nodeVar );
  23086. }
  23087. }
  23088. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  23089. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  23090. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  23091. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  23092. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  23093. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  23094. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  23095. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  23096. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  23097. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  23098. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  23099. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  23100. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  23101. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  23102. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  23103. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  23104. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  23105. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  23106. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  23107. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  23108. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  23109. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  23110. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  23111. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  23112. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  23113. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  23114. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  23115. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  23116. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  23117. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  23118. class AssignNode extends TempNode {
  23119. static get type() {
  23120. return 'AssignNode';
  23121. }
  23122. constructor( targetNode, sourceNode ) {
  23123. super();
  23124. this.targetNode = targetNode;
  23125. this.sourceNode = sourceNode;
  23126. }
  23127. hasDependencies() {
  23128. return false;
  23129. }
  23130. getNodeType( builder, output ) {
  23131. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  23132. }
  23133. needsSplitAssign( builder ) {
  23134. const { targetNode } = this;
  23135. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  23136. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  23137. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  23138. return assignDiferentVector;
  23139. }
  23140. return false;
  23141. }
  23142. generate( builder, output ) {
  23143. const { targetNode, sourceNode } = this;
  23144. const needsSplitAssign = this.needsSplitAssign( builder );
  23145. const targetType = targetNode.getNodeType( builder );
  23146. const target = targetNode.context( { assign: true } ).build( builder );
  23147. const source = sourceNode.build( builder, targetType );
  23148. const sourceType = sourceNode.getNodeType( builder );
  23149. const nodeData = builder.getDataFromNode( this );
  23150. //
  23151. let snippet;
  23152. if ( nodeData.initialized === true ) {
  23153. if ( output !== 'void' ) {
  23154. snippet = target;
  23155. }
  23156. } else if ( needsSplitAssign ) {
  23157. const sourceVar = builder.getVarFromNode( this, null, targetType );
  23158. const sourceProperty = builder.getPropertyName( sourceVar );
  23159. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  23160. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  23161. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  23162. const component = targetNode.components[ i ];
  23163. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  23164. }
  23165. if ( output !== 'void' ) {
  23166. snippet = target;
  23167. }
  23168. } else {
  23169. snippet = `${ target } = ${ source }`;
  23170. if ( output === 'void' || sourceType === 'void' ) {
  23171. builder.addLineFlowCode( snippet, this );
  23172. if ( output !== 'void' ) {
  23173. snippet = target;
  23174. }
  23175. }
  23176. }
  23177. nodeData.initialized = true;
  23178. return builder.format( snippet, targetType, output );
  23179. }
  23180. }
  23181. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  23182. addMethodChaining( 'assign', assign );
  23183. class FunctionCallNode extends TempNode {
  23184. static get type() {
  23185. return 'FunctionCallNode';
  23186. }
  23187. constructor( functionNode = null, parameters = {} ) {
  23188. super();
  23189. this.functionNode = functionNode;
  23190. this.parameters = parameters;
  23191. }
  23192. setParameters( parameters ) {
  23193. this.parameters = parameters;
  23194. return this;
  23195. }
  23196. getParameters() {
  23197. return this.parameters;
  23198. }
  23199. getNodeType( builder ) {
  23200. return this.functionNode.getNodeType( builder );
  23201. }
  23202. generate( builder ) {
  23203. const params = [];
  23204. const functionNode = this.functionNode;
  23205. const inputs = functionNode.getInputs( builder );
  23206. const parameters = this.parameters;
  23207. const generateInput = ( node, inputNode ) => {
  23208. const type = inputNode.type;
  23209. const pointer = type === 'pointer';
  23210. let output;
  23211. if ( pointer ) output = '&' + node.build( builder );
  23212. else output = node.build( builder, type );
  23213. return output;
  23214. };
  23215. if ( Array.isArray( parameters ) ) {
  23216. for ( let i = 0; i < parameters.length; i ++ ) {
  23217. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  23218. }
  23219. } else {
  23220. for ( const inputNode of inputs ) {
  23221. const node = parameters[ inputNode.name ];
  23222. if ( node !== undefined ) {
  23223. params.push( generateInput( node, inputNode ) );
  23224. } else {
  23225. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  23226. }
  23227. }
  23228. }
  23229. const functionName = functionNode.build( builder, 'property' );
  23230. return `${functionName}( ${params.join( ', ' )} )`;
  23231. }
  23232. }
  23233. const call = ( func, ...params ) => {
  23234. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  23235. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  23236. };
  23237. addMethodChaining( 'call', call );
  23238. class OperatorNode extends TempNode {
  23239. static get type() {
  23240. return 'OperatorNode';
  23241. }
  23242. constructor( op, aNode, bNode, ...params ) {
  23243. super();
  23244. if ( params.length > 0 ) {
  23245. let finalOp = new OperatorNode( op, aNode, bNode );
  23246. for ( let i = 0; i < params.length - 1; i ++ ) {
  23247. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  23248. }
  23249. aNode = finalOp;
  23250. bNode = params[ params.length - 1 ];
  23251. }
  23252. this.op = op;
  23253. this.aNode = aNode;
  23254. this.bNode = bNode;
  23255. }
  23256. getNodeType( builder, output ) {
  23257. const op = this.op;
  23258. const aNode = this.aNode;
  23259. const bNode = this.bNode;
  23260. const typeA = aNode.getNodeType( builder );
  23261. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  23262. if ( typeA === 'void' || typeB === 'void' ) {
  23263. return 'void';
  23264. } else if ( op === '%' ) {
  23265. return typeA;
  23266. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  23267. return builder.getIntegerType( typeA );
  23268. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  23269. return 'bool';
  23270. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  23271. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  23272. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  23273. } else {
  23274. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  23275. return typeB;
  23276. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  23277. // matrix x vector
  23278. return builder.getVectorFromMatrix( typeA );
  23279. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  23280. // vector x matrix
  23281. return builder.getVectorFromMatrix( typeB );
  23282. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  23283. // anytype x anytype: use the greater length vector
  23284. return typeB;
  23285. }
  23286. return typeA;
  23287. }
  23288. }
  23289. generate( builder, output ) {
  23290. const op = this.op;
  23291. const aNode = this.aNode;
  23292. const bNode = this.bNode;
  23293. const type = this.getNodeType( builder, output );
  23294. let typeA = null;
  23295. let typeB = null;
  23296. if ( type !== 'void' ) {
  23297. typeA = aNode.getNodeType( builder );
  23298. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  23299. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  23300. if ( builder.isVector( typeA ) ) {
  23301. typeB = typeA;
  23302. } else if ( typeA !== typeB ) {
  23303. typeA = typeB = 'float';
  23304. }
  23305. } else if ( op === '>>' || op === '<<' ) {
  23306. typeA = type;
  23307. typeB = builder.changeComponentType( typeB, 'uint' );
  23308. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  23309. // matrix x vector
  23310. typeB = builder.getVectorFromMatrix( typeA );
  23311. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  23312. // vector x matrix
  23313. typeA = builder.getVectorFromMatrix( typeB );
  23314. } else {
  23315. // anytype x anytype
  23316. typeA = typeB = type;
  23317. }
  23318. } else {
  23319. typeA = typeB = type;
  23320. }
  23321. const a = aNode.build( builder, typeA );
  23322. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  23323. const outputLength = builder.getTypeLength( output );
  23324. const fnOpSnippet = builder.getFunctionOperator( op );
  23325. if ( output !== 'void' ) {
  23326. if ( op === '<' && outputLength > 1 ) {
  23327. if ( builder.useComparisonMethod ) {
  23328. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  23329. } else {
  23330. return builder.format( `( ${ a } < ${ b } )`, type, output );
  23331. }
  23332. } else if ( op === '<=' && outputLength > 1 ) {
  23333. if ( builder.useComparisonMethod ) {
  23334. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  23335. } else {
  23336. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  23337. }
  23338. } else if ( op === '>' && outputLength > 1 ) {
  23339. if ( builder.useComparisonMethod ) {
  23340. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  23341. } else {
  23342. return builder.format( `( ${ a } > ${ b } )`, type, output );
  23343. }
  23344. } else if ( op === '>=' && outputLength > 1 ) {
  23345. if ( builder.useComparisonMethod ) {
  23346. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  23347. } else {
  23348. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  23349. }
  23350. } else if ( op === '!' || op === '~' ) {
  23351. return builder.format( `(${op}${a})`, typeA, output );
  23352. } else if ( fnOpSnippet ) {
  23353. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  23354. } else {
  23355. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  23356. }
  23357. } else if ( typeA !== 'void' ) {
  23358. if ( fnOpSnippet ) {
  23359. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  23360. } else {
  23361. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  23362. }
  23363. }
  23364. }
  23365. serialize( data ) {
  23366. super.serialize( data );
  23367. data.op = this.op;
  23368. }
  23369. deserialize( data ) {
  23370. super.deserialize( data );
  23371. this.op = data.op;
  23372. }
  23373. }
  23374. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  23375. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  23376. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  23377. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  23378. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  23379. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  23380. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  23381. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  23382. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  23383. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  23384. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  23385. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  23386. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  23387. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  23388. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  23389. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  23390. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  23391. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  23392. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  23393. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  23394. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  23395. addMethodChaining( 'add', add );
  23396. addMethodChaining( 'sub', sub );
  23397. addMethodChaining( 'mul', mul );
  23398. addMethodChaining( 'div', div );
  23399. addMethodChaining( 'modInt', modInt );
  23400. addMethodChaining( 'equal', equal );
  23401. addMethodChaining( 'notEqual', notEqual );
  23402. addMethodChaining( 'lessThan', lessThan );
  23403. addMethodChaining( 'greaterThan', greaterThan );
  23404. addMethodChaining( 'lessThanEqual', lessThanEqual );
  23405. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  23406. addMethodChaining( 'and', and );
  23407. addMethodChaining( 'or', or );
  23408. addMethodChaining( 'not', not );
  23409. addMethodChaining( 'xor', xor );
  23410. addMethodChaining( 'bitAnd', bitAnd );
  23411. addMethodChaining( 'bitNot', bitNot );
  23412. addMethodChaining( 'bitOr', bitOr );
  23413. addMethodChaining( 'bitXor', bitXor );
  23414. addMethodChaining( 'shiftLeft', shiftLeft );
  23415. addMethodChaining( 'shiftRight', shiftRight );
  23416. const remainder = ( ...params ) => { // @deprecated, r168
  23417. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  23418. return modInt( ...params );
  23419. };
  23420. addMethodChaining( 'remainder', remainder );
  23421. class MathNode extends TempNode {
  23422. static get type() {
  23423. return 'MathNode';
  23424. }
  23425. constructor( method, aNode, bNode = null, cNode = null ) {
  23426. super();
  23427. this.method = method;
  23428. this.aNode = aNode;
  23429. this.bNode = bNode;
  23430. this.cNode = cNode;
  23431. }
  23432. getInputType( builder ) {
  23433. const aType = this.aNode.getNodeType( builder );
  23434. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  23435. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  23436. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  23437. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  23438. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  23439. if ( aLen > bLen && aLen > cLen ) {
  23440. return aType;
  23441. } else if ( bLen > cLen ) {
  23442. return bType;
  23443. } else if ( cLen > aLen ) {
  23444. return cType;
  23445. }
  23446. return aType;
  23447. }
  23448. getNodeType( builder ) {
  23449. const method = this.method;
  23450. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  23451. return 'float';
  23452. } else if ( method === MathNode.CROSS ) {
  23453. return 'vec3';
  23454. } else if ( method === MathNode.ALL ) {
  23455. return 'bool';
  23456. } else if ( method === MathNode.EQUALS ) {
  23457. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  23458. } else if ( method === MathNode.MOD ) {
  23459. return this.aNode.getNodeType( builder );
  23460. } else {
  23461. return this.getInputType( builder );
  23462. }
  23463. }
  23464. generate( builder, output ) {
  23465. const method = this.method;
  23466. const type = this.getNodeType( builder );
  23467. const inputType = this.getInputType( builder );
  23468. const a = this.aNode;
  23469. const b = this.bNode;
  23470. const c = this.cNode;
  23471. const isWebGL = builder.renderer.isWebGLRenderer === true;
  23472. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  23473. // dir can be either a direction vector or a normal vector
  23474. // upper-left 3x3 of matrix is assumed to be orthogonal
  23475. let tA = a;
  23476. let tB = b;
  23477. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  23478. tB = vec4( vec3( tB ), 0.0 );
  23479. } else {
  23480. tA = vec4( vec3( tA ), 0.0 );
  23481. }
  23482. const mulNode = mul( tA, tB ).xyz;
  23483. return normalize( mulNode ).build( builder, output );
  23484. } else if ( method === MathNode.NEGATE ) {
  23485. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  23486. } else if ( method === MathNode.ONE_MINUS ) {
  23487. return sub( 1.0, a ).build( builder, output );
  23488. } else if ( method === MathNode.RECIPROCAL ) {
  23489. return div( 1.0, a ).build( builder, output );
  23490. } else if ( method === MathNode.DIFFERENCE ) {
  23491. return abs( sub( a, b ) ).build( builder, output );
  23492. } else {
  23493. const params = [];
  23494. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  23495. params.push(
  23496. a.build( builder, type ),
  23497. b.build( builder, type )
  23498. );
  23499. } else if ( isWebGL && method === MathNode.STEP ) {
  23500. params.push(
  23501. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  23502. b.build( builder, inputType )
  23503. );
  23504. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  23505. params.push(
  23506. a.build( builder, inputType ),
  23507. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  23508. );
  23509. } else if ( method === MathNode.REFRACT ) {
  23510. params.push(
  23511. a.build( builder, inputType ),
  23512. b.build( builder, inputType ),
  23513. c.build( builder, 'float' )
  23514. );
  23515. } else if ( method === MathNode.MIX ) {
  23516. params.push(
  23517. a.build( builder, inputType ),
  23518. b.build( builder, inputType ),
  23519. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  23520. );
  23521. } else {
  23522. params.push( a.build( builder, inputType ) );
  23523. if ( b !== null ) params.push( b.build( builder, inputType ) );
  23524. if ( c !== null ) params.push( c.build( builder, inputType ) );
  23525. }
  23526. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  23527. }
  23528. }
  23529. serialize( data ) {
  23530. super.serialize( data );
  23531. data.method = this.method;
  23532. }
  23533. deserialize( data ) {
  23534. super.deserialize( data );
  23535. this.method = data.method;
  23536. }
  23537. }
  23538. // 1 input
  23539. MathNode.ALL = 'all';
  23540. MathNode.ANY = 'any';
  23541. MathNode.EQUALS = 'equals';
  23542. MathNode.RADIANS = 'radians';
  23543. MathNode.DEGREES = 'degrees';
  23544. MathNode.EXP = 'exp';
  23545. MathNode.EXP2 = 'exp2';
  23546. MathNode.LOG = 'log';
  23547. MathNode.LOG2 = 'log2';
  23548. MathNode.SQRT = 'sqrt';
  23549. MathNode.INVERSE_SQRT = 'inversesqrt';
  23550. MathNode.FLOOR = 'floor';
  23551. MathNode.CEIL = 'ceil';
  23552. MathNode.NORMALIZE = 'normalize';
  23553. MathNode.FRACT = 'fract';
  23554. MathNode.SIN = 'sin';
  23555. MathNode.COS = 'cos';
  23556. MathNode.TAN = 'tan';
  23557. MathNode.ASIN = 'asin';
  23558. MathNode.ACOS = 'acos';
  23559. MathNode.ATAN = 'atan';
  23560. MathNode.ABS = 'abs';
  23561. MathNode.SIGN = 'sign';
  23562. MathNode.LENGTH = 'length';
  23563. MathNode.NEGATE = 'negate';
  23564. MathNode.ONE_MINUS = 'oneMinus';
  23565. MathNode.DFDX = 'dFdx';
  23566. MathNode.DFDY = 'dFdy';
  23567. MathNode.ROUND = 'round';
  23568. MathNode.RECIPROCAL = 'reciprocal';
  23569. MathNode.TRUNC = 'trunc';
  23570. MathNode.FWIDTH = 'fwidth';
  23571. MathNode.BITCAST = 'bitcast';
  23572. MathNode.TRANSPOSE = 'transpose';
  23573. // 2 inputs
  23574. MathNode.ATAN2 = 'atan2';
  23575. MathNode.MIN = 'min';
  23576. MathNode.MAX = 'max';
  23577. MathNode.MOD = 'mod';
  23578. MathNode.STEP = 'step';
  23579. MathNode.REFLECT = 'reflect';
  23580. MathNode.DISTANCE = 'distance';
  23581. MathNode.DIFFERENCE = 'difference';
  23582. MathNode.DOT = 'dot';
  23583. MathNode.CROSS = 'cross';
  23584. MathNode.POW = 'pow';
  23585. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  23586. // 3 inputs
  23587. MathNode.MIX = 'mix';
  23588. MathNode.CLAMP = 'clamp';
  23589. MathNode.REFRACT = 'refract';
  23590. MathNode.SMOOTHSTEP = 'smoothstep';
  23591. MathNode.FACEFORWARD = 'faceforward';
  23592. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  23593. const INFINITY = /*@__PURE__*/ float( 1e6 );
  23594. const PI = /*@__PURE__*/ float( Math.PI );
  23595. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  23596. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  23597. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  23598. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  23599. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  23600. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  23601. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  23602. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  23603. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  23604. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  23605. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  23606. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  23607. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  23608. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  23609. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  23610. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  23611. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  23612. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  23613. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  23614. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  23615. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  23616. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  23617. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  23618. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  23619. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  23620. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  23621. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  23622. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  23623. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  23624. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  23625. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  23626. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  23627. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  23628. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  23629. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  23630. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  23631. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  23632. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  23633. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  23634. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  23635. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  23636. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  23637. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  23638. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  23639. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  23640. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  23641. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  23642. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  23643. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  23644. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  23645. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  23646. const lengthSq = ( a ) => dot( a, a );
  23647. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  23648. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  23649. const saturate = ( value ) => clamp( value );
  23650. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  23651. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  23652. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  23653. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  23654. const a = 12.9898, b = 78.233, c = 43758.5453;
  23655. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  23656. return fract( sin( sn ).mul( c ) );
  23657. } );
  23658. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  23659. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  23660. addMethodChaining( 'all', all );
  23661. addMethodChaining( 'any', any );
  23662. addMethodChaining( 'equals', equals );
  23663. addMethodChaining( 'radians', radians );
  23664. addMethodChaining( 'degrees', degrees );
  23665. addMethodChaining( 'exp', exp );
  23666. addMethodChaining( 'exp2', exp2 );
  23667. addMethodChaining( 'log', log );
  23668. addMethodChaining( 'log2', log2 );
  23669. addMethodChaining( 'sqrt', sqrt );
  23670. addMethodChaining( 'inverseSqrt', inverseSqrt );
  23671. addMethodChaining( 'floor', floor );
  23672. addMethodChaining( 'ceil', ceil );
  23673. addMethodChaining( 'normalize', normalize );
  23674. addMethodChaining( 'fract', fract );
  23675. addMethodChaining( 'sin', sin );
  23676. addMethodChaining( 'cos', cos );
  23677. addMethodChaining( 'tan', tan );
  23678. addMethodChaining( 'asin', asin );
  23679. addMethodChaining( 'acos', acos );
  23680. addMethodChaining( 'atan', atan );
  23681. addMethodChaining( 'abs', abs );
  23682. addMethodChaining( 'sign', sign );
  23683. addMethodChaining( 'length', length );
  23684. addMethodChaining( 'lengthSq', lengthSq );
  23685. addMethodChaining( 'negate', negate );
  23686. addMethodChaining( 'oneMinus', oneMinus );
  23687. addMethodChaining( 'dFdx', dFdx );
  23688. addMethodChaining( 'dFdy', dFdy );
  23689. addMethodChaining( 'round', round );
  23690. addMethodChaining( 'reciprocal', reciprocal );
  23691. addMethodChaining( 'trunc', trunc );
  23692. addMethodChaining( 'fwidth', fwidth );
  23693. addMethodChaining( 'atan2', atan2 );
  23694. addMethodChaining( 'min', min$1 );
  23695. addMethodChaining( 'max', max$1 );
  23696. addMethodChaining( 'mod', mod );
  23697. addMethodChaining( 'step', step );
  23698. addMethodChaining( 'reflect', reflect );
  23699. addMethodChaining( 'distance', distance );
  23700. addMethodChaining( 'dot', dot );
  23701. addMethodChaining( 'cross', cross );
  23702. addMethodChaining( 'pow', pow );
  23703. addMethodChaining( 'pow2', pow2 );
  23704. addMethodChaining( 'pow3', pow3 );
  23705. addMethodChaining( 'pow4', pow4 );
  23706. addMethodChaining( 'transformDirection', transformDirection );
  23707. addMethodChaining( 'mix', mixElement );
  23708. addMethodChaining( 'clamp', clamp );
  23709. addMethodChaining( 'refract', refract );
  23710. addMethodChaining( 'smoothstep', smoothstepElement );
  23711. addMethodChaining( 'faceForward', faceForward );
  23712. addMethodChaining( 'difference', difference );
  23713. addMethodChaining( 'saturate', saturate );
  23714. addMethodChaining( 'cbrt', cbrt );
  23715. addMethodChaining( 'transpose', transpose );
  23716. addMethodChaining( 'rand', rand );
  23717. class ConditionalNode extends Node {
  23718. static get type() {
  23719. return 'ConditionalNode';
  23720. }
  23721. constructor( condNode, ifNode, elseNode = null ) {
  23722. super();
  23723. this.condNode = condNode;
  23724. this.ifNode = ifNode;
  23725. this.elseNode = elseNode;
  23726. }
  23727. getNodeType( builder ) {
  23728. const ifType = this.ifNode.getNodeType( builder );
  23729. if ( this.elseNode !== null ) {
  23730. const elseType = this.elseNode.getNodeType( builder );
  23731. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  23732. return elseType;
  23733. }
  23734. }
  23735. return ifType;
  23736. }
  23737. setup( builder ) {
  23738. const condNode = this.condNode.cache();
  23739. const ifNode = this.ifNode.cache();
  23740. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  23741. //
  23742. const currentNodeBlock = builder.context.nodeBlock;
  23743. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  23744. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  23745. //
  23746. const properties = builder.getNodeProperties( this );
  23747. properties.condNode = condNode;
  23748. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  23749. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  23750. }
  23751. generate( builder, output ) {
  23752. const type = this.getNodeType( builder );
  23753. const nodeData = builder.getDataFromNode( this );
  23754. if ( nodeData.nodeProperty !== undefined ) {
  23755. return nodeData.nodeProperty;
  23756. }
  23757. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  23758. const needsOutput = output !== 'void';
  23759. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  23760. nodeData.nodeProperty = nodeProperty;
  23761. const nodeSnippet = condNode.build( builder, 'bool' );
  23762. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  23763. let ifSnippet = ifNode.build( builder, type );
  23764. if ( ifSnippet ) {
  23765. if ( needsOutput ) {
  23766. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  23767. } else {
  23768. ifSnippet = 'return ' + ifSnippet + ';';
  23769. }
  23770. }
  23771. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  23772. if ( elseNode !== null ) {
  23773. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  23774. let elseSnippet = elseNode.build( builder, type );
  23775. if ( elseSnippet ) {
  23776. if ( needsOutput ) {
  23777. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  23778. } else {
  23779. elseSnippet = 'return ' + elseSnippet + ';';
  23780. }
  23781. }
  23782. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  23783. } else {
  23784. builder.addFlowCode( '\n\n' );
  23785. }
  23786. return builder.format( nodeProperty, type, output );
  23787. }
  23788. }
  23789. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  23790. addMethodChaining( 'select', select );
  23791. //
  23792. const cond = ( ...params ) => { // @deprecated, r168
  23793. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  23794. return select( ...params );
  23795. };
  23796. addMethodChaining( 'cond', cond );
  23797. class ContextNode extends Node {
  23798. static get type() {
  23799. return 'ContextNode';
  23800. }
  23801. constructor( node, value = {} ) {
  23802. super();
  23803. this.isContextNode = true;
  23804. this.node = node;
  23805. this.value = value;
  23806. }
  23807. getScope() {
  23808. return this.node.getScope();
  23809. }
  23810. getNodeType( builder ) {
  23811. return this.node.getNodeType( builder );
  23812. }
  23813. analyze( builder ) {
  23814. this.node.build( builder );
  23815. }
  23816. setup( builder ) {
  23817. const previousContext = builder.getContext();
  23818. builder.setContext( { ...builder.context, ...this.value } );
  23819. const node = this.node.build( builder );
  23820. builder.setContext( previousContext );
  23821. return node;
  23822. }
  23823. generate( builder, output ) {
  23824. const previousContext = builder.getContext();
  23825. builder.setContext( { ...builder.context, ...this.value } );
  23826. const snippet = this.node.build( builder, output );
  23827. builder.setContext( previousContext );
  23828. return snippet;
  23829. }
  23830. }
  23831. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  23832. const label = ( node, name ) => context( node, { label: name } );
  23833. addMethodChaining( 'context', context );
  23834. addMethodChaining( 'label', label );
  23835. class VarNode extends Node {
  23836. static get type() {
  23837. return 'VarNode';
  23838. }
  23839. constructor( node, name = null ) {
  23840. super();
  23841. this.node = node;
  23842. this.name = name;
  23843. this.global = true;
  23844. this.isVarNode = true;
  23845. }
  23846. getHash( builder ) {
  23847. return this.name || super.getHash( builder );
  23848. }
  23849. getNodeType( builder ) {
  23850. return this.node.getNodeType( builder );
  23851. }
  23852. generate( builder ) {
  23853. const { node, name } = this;
  23854. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  23855. const propertyName = builder.getPropertyName( nodeVar );
  23856. const snippet = node.build( builder, nodeVar.type );
  23857. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  23858. return propertyName;
  23859. }
  23860. }
  23861. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  23862. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  23863. // Deprecated
  23864. const temp = ( node ) => { // @deprecated, r170
  23865. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  23866. return createVar( node );
  23867. };
  23868. addMethodChaining( 'temp', temp );
  23869. class VaryingNode extends Node {
  23870. static get type() {
  23871. return 'VaryingNode';
  23872. }
  23873. constructor( node, name = null ) {
  23874. super();
  23875. this.node = node;
  23876. this.name = name;
  23877. this.isVaryingNode = true;
  23878. }
  23879. isGlobal() {
  23880. return true;
  23881. }
  23882. getHash( builder ) {
  23883. return this.name || super.getHash( builder );
  23884. }
  23885. getNodeType( builder ) {
  23886. // VaryingNode is auto type
  23887. return this.node.getNodeType( builder );
  23888. }
  23889. setupVarying( builder ) {
  23890. const properties = builder.getNodeProperties( this );
  23891. let varying = properties.varying;
  23892. if ( varying === undefined ) {
  23893. const name = this.name;
  23894. const type = this.getNodeType( builder );
  23895. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  23896. properties.node = this.node;
  23897. }
  23898. // this property can be used to check if the varying can be optimized for a variable
  23899. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  23900. return varying;
  23901. }
  23902. setup( builder ) {
  23903. this.setupVarying( builder );
  23904. }
  23905. analyze( builder ) {
  23906. this.setupVarying( builder );
  23907. return this.node.analyze( builder );
  23908. }
  23909. generate( builder ) {
  23910. const properties = builder.getNodeProperties( this );
  23911. const varying = this.setupVarying( builder );
  23912. if ( properties.propertyName === undefined ) {
  23913. const type = this.getNodeType( builder );
  23914. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  23915. // force node run in vertex stage
  23916. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  23917. properties.propertyName = propertyName;
  23918. }
  23919. return builder.getPropertyName( varying );
  23920. }
  23921. }
  23922. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  23923. addMethodChaining( 'varying', varying );
  23924. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  23925. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  23926. const b = color.mul( 0.0773993808 );
  23927. const factor = color.lessThanEqual( 0.04045 );
  23928. const rgbResult = mix( a, b, factor );
  23929. return rgbResult;
  23930. } ).setLayout( {
  23931. name: 'sRGBTransferEOTF',
  23932. type: 'vec3',
  23933. inputs: [
  23934. { name: 'color', type: 'vec3' }
  23935. ]
  23936. } );
  23937. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  23938. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  23939. const b = color.mul( 12.92 );
  23940. const factor = color.lessThanEqual( 0.0031308 );
  23941. const rgbResult = mix( a, b, factor );
  23942. return rgbResult;
  23943. } ).setLayout( {
  23944. name: 'sRGBTransferOETF',
  23945. type: 'vec3',
  23946. inputs: [
  23947. { name: 'color', type: 'vec3' }
  23948. ]
  23949. } );
  23950. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  23951. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  23952. class ColorSpaceNode extends TempNode {
  23953. static get type() {
  23954. return 'ColorSpaceNode';
  23955. }
  23956. constructor( colorNode, source, target ) {
  23957. super( 'vec4' );
  23958. this.colorNode = colorNode;
  23959. this.source = source;
  23960. this.target = target;
  23961. }
  23962. resolveColorSpace( builder, colorSpace ) {
  23963. if ( colorSpace === WORKING_COLOR_SPACE ) {
  23964. return ColorManagement.workingColorSpace;
  23965. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  23966. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  23967. }
  23968. return colorSpace;
  23969. }
  23970. setup( builder ) {
  23971. const { colorNode } = this;
  23972. const source = this.resolveColorSpace( builder, this.source );
  23973. const target = this.resolveColorSpace( builder, this.target );
  23974. let outputNode = colorNode;
  23975. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  23976. return outputNode;
  23977. }
  23978. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  23979. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  23980. }
  23981. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  23982. outputNode = vec4(
  23983. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  23984. outputNode.a
  23985. );
  23986. }
  23987. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  23988. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  23989. }
  23990. return outputNode;
  23991. }
  23992. }
  23993. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  23994. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  23995. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  23996. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  23997. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  23998. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  23999. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  24000. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  24001. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  24002. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  24003. static get type() {
  24004. return 'ReferenceElementNode';
  24005. }
  24006. constructor( referenceNode, indexNode ) {
  24007. super( referenceNode, indexNode );
  24008. this.referenceNode = referenceNode;
  24009. this.isReferenceElementNode = true;
  24010. }
  24011. getNodeType() {
  24012. return this.referenceNode.uniformType;
  24013. }
  24014. generate( builder ) {
  24015. const snippet = super.generate( builder );
  24016. const arrayType = this.referenceNode.getNodeType();
  24017. const elementType = this.getNodeType();
  24018. return builder.format( snippet, arrayType, elementType );
  24019. }
  24020. };
  24021. class ReferenceBaseNode extends Node {
  24022. static get type() {
  24023. return 'ReferenceBaseNode';
  24024. }
  24025. constructor( property, uniformType, object = null, count = null ) {
  24026. super();
  24027. this.property = property;
  24028. this.uniformType = uniformType;
  24029. this.object = object;
  24030. this.count = count;
  24031. this.properties = property.split( '.' );
  24032. this.reference = object;
  24033. this.node = null;
  24034. this.group = null;
  24035. this.updateType = NodeUpdateType.OBJECT;
  24036. }
  24037. setGroup( group ) {
  24038. this.group = group;
  24039. return this;
  24040. }
  24041. element( indexNode ) {
  24042. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  24043. }
  24044. setNodeType( uniformType ) {
  24045. const node = uniform( null, uniformType ).getSelf();
  24046. if ( this.group !== null ) {
  24047. node.setGroup( this.group );
  24048. }
  24049. this.node = node;
  24050. }
  24051. getNodeType( builder ) {
  24052. if ( this.node === null ) {
  24053. this.updateReference( builder );
  24054. this.updateValue();
  24055. }
  24056. return this.node.getNodeType( builder );
  24057. }
  24058. getValueFromReference( object = this.reference ) {
  24059. const { properties } = this;
  24060. let value = object[ properties[ 0 ] ];
  24061. for ( let i = 1; i < properties.length; i ++ ) {
  24062. value = value[ properties[ i ] ];
  24063. }
  24064. return value;
  24065. }
  24066. updateReference( state ) {
  24067. this.reference = this.object !== null ? this.object : state.object;
  24068. return this.reference;
  24069. }
  24070. setup() {
  24071. this.updateValue();
  24072. return this.node;
  24073. }
  24074. update( /*frame*/ ) {
  24075. this.updateValue();
  24076. }
  24077. updateValue() {
  24078. if ( this.node === null ) this.setNodeType( this.uniformType );
  24079. const value = this.getValueFromReference();
  24080. if ( Array.isArray( value ) ) {
  24081. this.node.array = value;
  24082. } else {
  24083. this.node.value = value;
  24084. }
  24085. }
  24086. }
  24087. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  24088. class RendererReferenceNode extends ReferenceBaseNode {
  24089. static get type() {
  24090. return 'RendererReferenceNode';
  24091. }
  24092. constructor( property, inputType, renderer = null ) {
  24093. super( property, inputType, renderer );
  24094. this.renderer = renderer;
  24095. this.setGroup( renderGroup );
  24096. }
  24097. updateReference( state ) {
  24098. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  24099. return this.reference;
  24100. }
  24101. }
  24102. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  24103. class ToneMappingNode extends TempNode {
  24104. static get type() {
  24105. return 'ToneMappingNode';
  24106. }
  24107. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  24108. super( 'vec3' );
  24109. this.toneMapping = toneMapping;
  24110. this.exposureNode = exposureNode;
  24111. this.colorNode = colorNode;
  24112. }
  24113. getCacheKey() {
  24114. return hash$1( super.getCacheKey(), this.toneMapping );
  24115. }
  24116. setup( builder ) {
  24117. const colorNode = this.colorNode || builder.context.color;
  24118. const toneMapping = this.toneMapping;
  24119. if ( toneMapping === NoToneMapping ) return colorNode;
  24120. let outputNode = null;
  24121. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  24122. if ( toneMappingFn !== null ) {
  24123. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  24124. } else {
  24125. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  24126. outputNode = colorNode;
  24127. }
  24128. return outputNode;
  24129. }
  24130. }
  24131. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  24132. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  24133. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  24134. class BufferAttributeNode extends InputNode {
  24135. static get type() {
  24136. return 'BufferAttributeNode';
  24137. }
  24138. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  24139. super( value, bufferType );
  24140. this.isBufferNode = true;
  24141. this.bufferType = bufferType;
  24142. this.bufferStride = bufferStride;
  24143. this.bufferOffset = bufferOffset;
  24144. this.usage = StaticDrawUsage;
  24145. this.instanced = false;
  24146. this.attribute = null;
  24147. this.global = true;
  24148. if ( value && value.isBufferAttribute === true ) {
  24149. this.attribute = value;
  24150. this.usage = value.usage;
  24151. this.instanced = value.isInstancedBufferAttribute;
  24152. }
  24153. }
  24154. getHash( builder ) {
  24155. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  24156. let bufferData = builder.globalCache.getData( this.value );
  24157. if ( bufferData === undefined ) {
  24158. bufferData = {
  24159. node: this
  24160. };
  24161. builder.globalCache.setData( this.value, bufferData );
  24162. }
  24163. return bufferData.node.uuid;
  24164. }
  24165. return this.uuid;
  24166. }
  24167. getNodeType( builder ) {
  24168. if ( this.bufferType === null ) {
  24169. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  24170. }
  24171. return this.bufferType;
  24172. }
  24173. setup( builder ) {
  24174. if ( this.attribute !== null ) return;
  24175. const type = this.getNodeType( builder );
  24176. const array = this.value;
  24177. const itemSize = builder.getTypeLength( type );
  24178. const stride = this.bufferStride || itemSize;
  24179. const offset = this.bufferOffset;
  24180. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  24181. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  24182. buffer.setUsage( this.usage );
  24183. this.attribute = bufferAttribute;
  24184. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  24185. }
  24186. generate( builder ) {
  24187. const nodeType = this.getNodeType( builder );
  24188. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  24189. const propertyName = builder.getPropertyName( nodeAttribute );
  24190. let output = null;
  24191. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  24192. this.name = propertyName;
  24193. output = propertyName;
  24194. } else {
  24195. const nodeVarying = varying( this );
  24196. output = nodeVarying.build( builder, nodeType );
  24197. }
  24198. return output;
  24199. }
  24200. getInputType( /*builder*/ ) {
  24201. return 'bufferAttribute';
  24202. }
  24203. setUsage( value ) {
  24204. this.usage = value;
  24205. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  24206. this.attribute.usage = value;
  24207. }
  24208. return this;
  24209. }
  24210. setInstanced( value ) {
  24211. this.instanced = value;
  24212. return this;
  24213. }
  24214. }
  24215. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  24216. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  24217. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  24218. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  24219. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  24220. class ComputeNode extends Node {
  24221. static get type() {
  24222. return 'ComputeNode';
  24223. }
  24224. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  24225. super( 'void' );
  24226. this.isComputeNode = true;
  24227. this.computeNode = computeNode;
  24228. this.count = count;
  24229. this.workgroupSize = workgroupSize;
  24230. this.dispatchCount = 0;
  24231. this.version = 1;
  24232. this.updateBeforeType = NodeUpdateType.OBJECT;
  24233. this.onInitFunction = null;
  24234. this.updateDispatchCount();
  24235. }
  24236. dispose() {
  24237. this.dispatchEvent( { type: 'dispose' } );
  24238. }
  24239. set needsUpdate( value ) {
  24240. if ( value === true ) this.version ++;
  24241. }
  24242. updateDispatchCount() {
  24243. const { count, workgroupSize } = this;
  24244. let size = workgroupSize[ 0 ];
  24245. for ( let i = 1; i < workgroupSize.length; i ++ )
  24246. size *= workgroupSize[ i ];
  24247. this.dispatchCount = Math.ceil( count / size );
  24248. }
  24249. onInit( callback ) {
  24250. this.onInitFunction = callback;
  24251. return this;
  24252. }
  24253. updateBefore( { renderer } ) {
  24254. renderer.compute( this );
  24255. }
  24256. generate( builder ) {
  24257. const { shaderStage } = builder;
  24258. if ( shaderStage === 'compute' ) {
  24259. const snippet = this.computeNode.build( builder, 'void' );
  24260. if ( snippet !== '' ) {
  24261. builder.addLineFlowCode( snippet, this );
  24262. }
  24263. }
  24264. }
  24265. }
  24266. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  24267. addMethodChaining( 'compute', compute );
  24268. class CacheNode extends Node {
  24269. static get type() {
  24270. return 'CacheNode';
  24271. }
  24272. constructor( node, parent = true ) {
  24273. super();
  24274. this.node = node;
  24275. this.parent = parent;
  24276. this.isCacheNode = true;
  24277. }
  24278. getNodeType( builder ) {
  24279. return this.node.getNodeType( builder );
  24280. }
  24281. build( builder, ...params ) {
  24282. const previousCache = builder.getCache();
  24283. const cache = builder.getCacheFromNode( this, this.parent );
  24284. builder.setCache( cache );
  24285. const data = this.node.build( builder, ...params );
  24286. builder.setCache( previousCache );
  24287. return data;
  24288. }
  24289. }
  24290. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  24291. addMethodChaining( 'cache', cache );
  24292. class BypassNode extends Node {
  24293. static get type() {
  24294. return 'BypassNode';
  24295. }
  24296. constructor( returnNode, callNode ) {
  24297. super();
  24298. this.isBypassNode = true;
  24299. this.outputNode = returnNode;
  24300. this.callNode = callNode;
  24301. }
  24302. getNodeType( builder ) {
  24303. return this.outputNode.getNodeType( builder );
  24304. }
  24305. generate( builder ) {
  24306. const snippet = this.callNode.build( builder, 'void' );
  24307. if ( snippet !== '' ) {
  24308. builder.addLineFlowCode( snippet, this );
  24309. }
  24310. return this.outputNode.build( builder );
  24311. }
  24312. }
  24313. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  24314. addMethodChaining( 'bypass', bypass );
  24315. class RemapNode extends Node {
  24316. static get type() {
  24317. return 'RemapNode';
  24318. }
  24319. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  24320. super();
  24321. this.node = node;
  24322. this.inLowNode = inLowNode;
  24323. this.inHighNode = inHighNode;
  24324. this.outLowNode = outLowNode;
  24325. this.outHighNode = outHighNode;
  24326. this.doClamp = true;
  24327. }
  24328. setup() {
  24329. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  24330. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  24331. if ( doClamp === true ) t = t.clamp();
  24332. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  24333. }
  24334. }
  24335. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  24336. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  24337. addMethodChaining( 'remap', remap );
  24338. addMethodChaining( 'remapClamp', remapClamp );
  24339. class ExpressionNode extends Node {
  24340. static get type() {
  24341. return 'ExpressionNode';
  24342. }
  24343. constructor( snippet = '', nodeType = 'void' ) {
  24344. super( nodeType );
  24345. this.snippet = snippet;
  24346. }
  24347. generate( builder, output ) {
  24348. const type = this.getNodeType( builder );
  24349. const snippet = this.snippet;
  24350. if ( type === 'void' ) {
  24351. builder.addLineFlowCode( snippet, this );
  24352. } else {
  24353. return builder.format( `( ${ snippet } )`, type, output );
  24354. }
  24355. }
  24356. }
  24357. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  24358. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  24359. const Return = () => expression( 'return' ).append();
  24360. addMethodChaining( 'discard', Discard );
  24361. class RenderOutputNode extends TempNode {
  24362. static get type() {
  24363. return 'RenderOutputNode';
  24364. }
  24365. constructor( colorNode, toneMapping, outputColorSpace ) {
  24366. super( 'vec4' );
  24367. this.colorNode = colorNode;
  24368. this.toneMapping = toneMapping;
  24369. this.outputColorSpace = outputColorSpace;
  24370. this.isRenderOutput = true;
  24371. }
  24372. setup( { context } ) {
  24373. let outputNode = this.colorNode || context.color;
  24374. // tone mapping
  24375. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  24376. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  24377. if ( toneMapping !== NoToneMapping ) {
  24378. outputNode = outputNode.toneMapping( toneMapping );
  24379. }
  24380. // working to output color space
  24381. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  24382. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  24383. }
  24384. return outputNode;
  24385. }
  24386. }
  24387. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  24388. addMethodChaining( 'renderOutput', renderOutput );
  24389. // Non-PURE exports list, side-effects are required here.
  24390. // TSL Base Syntax
  24391. function addNodeElement( name/*, nodeElement*/ ) {
  24392. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  24393. }
  24394. class AttributeNode extends Node {
  24395. static get type() {
  24396. return 'AttributeNode';
  24397. }
  24398. constructor( attributeName, nodeType = null ) {
  24399. super( nodeType );
  24400. this.global = true;
  24401. this._attributeName = attributeName;
  24402. }
  24403. getHash( builder ) {
  24404. return this.getAttributeName( builder );
  24405. }
  24406. getNodeType( builder ) {
  24407. let nodeType = this.nodeType;
  24408. if ( nodeType === null ) {
  24409. const attributeName = this.getAttributeName( builder );
  24410. if ( builder.hasGeometryAttribute( attributeName ) ) {
  24411. const attribute = builder.geometry.getAttribute( attributeName );
  24412. nodeType = builder.getTypeFromAttribute( attribute );
  24413. } else {
  24414. nodeType = 'float';
  24415. }
  24416. }
  24417. return nodeType;
  24418. }
  24419. setAttributeName( attributeName ) {
  24420. this._attributeName = attributeName;
  24421. return this;
  24422. }
  24423. getAttributeName( /*builder*/ ) {
  24424. return this._attributeName;
  24425. }
  24426. generate( builder ) {
  24427. const attributeName = this.getAttributeName( builder );
  24428. const nodeType = this.getNodeType( builder );
  24429. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  24430. if ( geometryAttribute === true ) {
  24431. const attribute = builder.geometry.getAttribute( attributeName );
  24432. const attributeType = builder.getTypeFromAttribute( attribute );
  24433. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  24434. if ( builder.shaderStage === 'vertex' ) {
  24435. return builder.format( nodeAttribute.name, attributeType, nodeType );
  24436. } else {
  24437. const nodeVarying = varying( this );
  24438. return nodeVarying.build( builder, nodeType );
  24439. }
  24440. } else {
  24441. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  24442. return builder.generateConst( nodeType );
  24443. }
  24444. }
  24445. serialize( data ) {
  24446. super.serialize( data );
  24447. data.global = this.global;
  24448. data._attributeName = this._attributeName;
  24449. }
  24450. deserialize( data ) {
  24451. super.deserialize( data );
  24452. this.global = data.global;
  24453. this._attributeName = data._attributeName;
  24454. }
  24455. }
  24456. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  24457. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  24458. class TextureSizeNode extends Node {
  24459. static get type() {
  24460. return 'TextureSizeNode';
  24461. }
  24462. constructor( textureNode, levelNode = null ) {
  24463. super( 'uvec2' );
  24464. this.isTextureSizeNode = true;
  24465. this.textureNode = textureNode;
  24466. this.levelNode = levelNode;
  24467. }
  24468. generate( builder, output ) {
  24469. const textureProperty = this.textureNode.build( builder, 'property' );
  24470. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  24471. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  24472. }
  24473. }
  24474. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  24475. class MaxMipLevelNode extends UniformNode {
  24476. static get type() {
  24477. return 'MaxMipLevelNode';
  24478. }
  24479. constructor( textureNode ) {
  24480. super( 0 );
  24481. this._textureNode = textureNode;
  24482. this.updateType = NodeUpdateType.FRAME;
  24483. }
  24484. get textureNode() {
  24485. return this._textureNode;
  24486. }
  24487. get texture() {
  24488. return this._textureNode.value;
  24489. }
  24490. update() {
  24491. const texture = this.texture;
  24492. const images = texture.images;
  24493. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  24494. if ( image && image.width !== undefined ) {
  24495. const { width, height } = image;
  24496. this.value = Math.log2( Math.max( width, height ) );
  24497. }
  24498. }
  24499. }
  24500. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  24501. class TextureNode extends UniformNode {
  24502. static get type() {
  24503. return 'TextureNode';
  24504. }
  24505. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24506. super( value );
  24507. this.isTextureNode = true;
  24508. this.uvNode = uvNode;
  24509. this.levelNode = levelNode;
  24510. this.biasNode = biasNode;
  24511. this.compareNode = null;
  24512. this.depthNode = null;
  24513. this.gradNode = null;
  24514. this.sampler = true;
  24515. this.updateMatrix = false;
  24516. this.updateType = NodeUpdateType.NONE;
  24517. this.referenceNode = null;
  24518. this._value = value;
  24519. this._matrixUniform = null;
  24520. this.setUpdateMatrix( uvNode === null );
  24521. }
  24522. set value( value ) {
  24523. if ( this.referenceNode ) {
  24524. this.referenceNode.value = value;
  24525. } else {
  24526. this._value = value;
  24527. }
  24528. }
  24529. get value() {
  24530. return this.referenceNode ? this.referenceNode.value : this._value;
  24531. }
  24532. getUniformHash( /*builder*/ ) {
  24533. return this.value.uuid;
  24534. }
  24535. getNodeType( /*builder*/ ) {
  24536. if ( this.value.isDepthTexture === true ) return 'float';
  24537. if ( this.value.type === UnsignedIntType ) {
  24538. return 'uvec4';
  24539. } else if ( this.value.type === IntType ) {
  24540. return 'ivec4';
  24541. }
  24542. return 'vec4';
  24543. }
  24544. getInputType( /*builder*/ ) {
  24545. return 'texture';
  24546. }
  24547. getDefaultUV() {
  24548. return uv( this.value.channel );
  24549. }
  24550. updateReference( /*state*/ ) {
  24551. return this.value;
  24552. }
  24553. getTransformedUV( uvNode ) {
  24554. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  24555. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  24556. }
  24557. setUpdateMatrix( value ) {
  24558. this.updateMatrix = value;
  24559. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  24560. return this;
  24561. }
  24562. setupUV( builder, uvNode ) {
  24563. const texture = this.value;
  24564. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  24565. if ( this.sampler ) {
  24566. uvNode = uvNode.flipY();
  24567. } else {
  24568. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  24569. }
  24570. }
  24571. return uvNode;
  24572. }
  24573. setup( builder ) {
  24574. const properties = builder.getNodeProperties( this );
  24575. properties.referenceNode = this.referenceNode;
  24576. //
  24577. let uvNode = this.uvNode;
  24578. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  24579. uvNode = builder.context.getUV( this );
  24580. }
  24581. if ( ! uvNode ) uvNode = this.getDefaultUV();
  24582. if ( this.updateMatrix === true ) {
  24583. uvNode = this.getTransformedUV( uvNode );
  24584. }
  24585. uvNode = this.setupUV( builder, uvNode );
  24586. //
  24587. let levelNode = this.levelNode;
  24588. if ( levelNode === null && builder.context.getTextureLevel ) {
  24589. levelNode = builder.context.getTextureLevel( this );
  24590. }
  24591. //
  24592. properties.uvNode = uvNode;
  24593. properties.levelNode = levelNode;
  24594. properties.biasNode = this.biasNode;
  24595. properties.compareNode = this.compareNode;
  24596. properties.gradNode = this.gradNode;
  24597. properties.depthNode = this.depthNode;
  24598. }
  24599. generateUV( builder, uvNode ) {
  24600. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  24601. }
  24602. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  24603. const texture = this.value;
  24604. let snippet;
  24605. if ( levelSnippet ) {
  24606. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  24607. } else if ( biasSnippet ) {
  24608. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  24609. } else if ( gradSnippet ) {
  24610. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  24611. } else if ( compareSnippet ) {
  24612. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  24613. } else if ( this.sampler === false ) {
  24614. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  24615. } else {
  24616. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  24617. }
  24618. return snippet;
  24619. }
  24620. generate( builder, output ) {
  24621. const properties = builder.getNodeProperties( this );
  24622. const texture = this.value;
  24623. if ( ! texture || texture.isTexture !== true ) {
  24624. throw new Error( 'TextureNode: Need a three.js texture.' );
  24625. }
  24626. const textureProperty = super.generate( builder, 'property' );
  24627. if ( output === 'sampler' ) {
  24628. return textureProperty + '_sampler';
  24629. } else if ( builder.isReference( output ) ) {
  24630. return textureProperty;
  24631. } else {
  24632. const nodeData = builder.getDataFromNode( this );
  24633. let propertyName = nodeData.propertyName;
  24634. if ( propertyName === undefined ) {
  24635. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  24636. const uvSnippet = this.generateUV( builder, uvNode );
  24637. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  24638. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  24639. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24640. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  24641. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  24642. const nodeVar = builder.getVarFromNode( this );
  24643. propertyName = builder.getPropertyName( nodeVar );
  24644. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  24645. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  24646. nodeData.snippet = snippet;
  24647. nodeData.propertyName = propertyName;
  24648. }
  24649. let snippet = propertyName;
  24650. const nodeType = this.getNodeType( builder );
  24651. if ( builder.needsToWorkingColorSpace( texture ) ) {
  24652. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  24653. }
  24654. return builder.format( snippet, nodeType, output );
  24655. }
  24656. }
  24657. setSampler( value ) {
  24658. this.sampler = value;
  24659. return this;
  24660. }
  24661. getSampler() {
  24662. return this.sampler;
  24663. }
  24664. // @TODO: Move to TSL
  24665. uv( uvNode ) {
  24666. const textureNode = this.clone();
  24667. textureNode.uvNode = nodeObject( uvNode );
  24668. textureNode.referenceNode = this.getSelf();
  24669. return nodeObject( textureNode );
  24670. }
  24671. blur( amountNode ) {
  24672. const textureNode = this.clone();
  24673. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  24674. textureNode.referenceNode = this.getSelf();
  24675. return nodeObject( textureNode );
  24676. }
  24677. level( levelNode ) {
  24678. const textureNode = this.clone();
  24679. textureNode.levelNode = nodeObject( levelNode );
  24680. textureNode.referenceNode = this.getSelf();
  24681. return nodeObject( textureNode );
  24682. }
  24683. size( levelNode ) {
  24684. return textureSize( this, levelNode );
  24685. }
  24686. bias( biasNode ) {
  24687. const textureNode = this.clone();
  24688. textureNode.biasNode = nodeObject( biasNode );
  24689. textureNode.referenceNode = this.getSelf();
  24690. return nodeObject( textureNode );
  24691. }
  24692. compare( compareNode ) {
  24693. const textureNode = this.clone();
  24694. textureNode.compareNode = nodeObject( compareNode );
  24695. textureNode.referenceNode = this.getSelf();
  24696. return nodeObject( textureNode );
  24697. }
  24698. grad( gradNodeX, gradNodeY ) {
  24699. const textureNode = this.clone();
  24700. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  24701. textureNode.referenceNode = this.getSelf();
  24702. return nodeObject( textureNode );
  24703. }
  24704. depth( depthNode ) {
  24705. const textureNode = this.clone();
  24706. textureNode.depthNode = nodeObject( depthNode );
  24707. textureNode.referenceNode = this.getSelf();
  24708. return nodeObject( textureNode );
  24709. }
  24710. // --
  24711. serialize( data ) {
  24712. super.serialize( data );
  24713. data.value = this.value.toJSON( data.meta ).uuid;
  24714. data.sampler = this.sampler;
  24715. data.updateMatrix = this.updateMatrix;
  24716. data.updateType = this.updateType;
  24717. }
  24718. deserialize( data ) {
  24719. super.deserialize( data );
  24720. this.value = data.meta.textures[ data.value ];
  24721. this.sampler = data.sampler;
  24722. this.updateMatrix = data.updateMatrix;
  24723. this.updateType = data.updateType;
  24724. }
  24725. update() {
  24726. const texture = this.value;
  24727. const matrixUniform = this._matrixUniform;
  24728. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  24729. if ( texture.matrixAutoUpdate === true ) {
  24730. texture.updateMatrix();
  24731. }
  24732. }
  24733. clone() {
  24734. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  24735. newNode.sampler = this.sampler;
  24736. return newNode;
  24737. }
  24738. }
  24739. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  24740. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  24741. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  24742. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  24743. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  24744. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  24745. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  24746. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  24747. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  24748. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  24749. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  24750. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  24751. class Object3DNode extends Node {
  24752. static get type() {
  24753. return 'Object3DNode';
  24754. }
  24755. constructor( scope, object3d = null ) {
  24756. super();
  24757. this.scope = scope;
  24758. this.object3d = object3d;
  24759. this.updateType = NodeUpdateType.OBJECT;
  24760. this._uniformNode = new UniformNode( null );
  24761. }
  24762. getNodeType() {
  24763. const scope = this.scope;
  24764. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24765. return 'mat4';
  24766. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24767. return 'vec3';
  24768. }
  24769. }
  24770. update( frame ) {
  24771. const object = this.object3d;
  24772. const uniformNode = this._uniformNode;
  24773. const scope = this.scope;
  24774. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24775. uniformNode.value = object.matrixWorld;
  24776. } else if ( scope === Object3DNode.POSITION ) {
  24777. uniformNode.value = uniformNode.value || new Vector3();
  24778. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24779. } else if ( scope === Object3DNode.SCALE ) {
  24780. uniformNode.value = uniformNode.value || new Vector3();
  24781. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  24782. } else if ( scope === Object3DNode.DIRECTION ) {
  24783. uniformNode.value = uniformNode.value || new Vector3();
  24784. object.getWorldDirection( uniformNode.value );
  24785. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  24786. const camera = frame.camera;
  24787. uniformNode.value = uniformNode.value || new Vector3();
  24788. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24789. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  24790. }
  24791. }
  24792. generate( builder ) {
  24793. const scope = this.scope;
  24794. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24795. this._uniformNode.nodeType = 'mat4';
  24796. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24797. this._uniformNode.nodeType = 'vec3';
  24798. }
  24799. return this._uniformNode.build( builder );
  24800. }
  24801. serialize( data ) {
  24802. super.serialize( data );
  24803. data.scope = this.scope;
  24804. }
  24805. deserialize( data ) {
  24806. super.deserialize( data );
  24807. this.scope = data.scope;
  24808. }
  24809. }
  24810. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  24811. Object3DNode.POSITION = 'position';
  24812. Object3DNode.SCALE = 'scale';
  24813. Object3DNode.VIEW_POSITION = 'viewPosition';
  24814. Object3DNode.DIRECTION = 'direction';
  24815. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  24816. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  24817. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  24818. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  24819. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  24820. class ModelNode extends Object3DNode {
  24821. static get type() {
  24822. return 'ModelNode';
  24823. }
  24824. constructor( scope ) {
  24825. super( scope );
  24826. }
  24827. update( frame ) {
  24828. this.object3d = frame.object;
  24829. super.update( frame );
  24830. }
  24831. }
  24832. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  24833. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  24834. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  24835. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  24836. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  24837. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  24838. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  24839. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  24840. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24841. builder.context.isHighPrecisionModelViewMatrix = true;
  24842. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  24843. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24844. } );
  24845. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  24846. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24847. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  24848. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  24849. if ( isHighPrecisionModelViewMatrix !== true ) {
  24850. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24851. }
  24852. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  24853. } );
  24854. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  24855. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  24856. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  24857. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  24858. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  24859. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  24860. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  24861. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  24862. class FrontFacingNode extends Node {
  24863. static get type() {
  24864. return 'FrontFacingNode';
  24865. }
  24866. constructor() {
  24867. super( 'bool' );
  24868. this.isFrontFacingNode = true;
  24869. }
  24870. generate( builder ) {
  24871. const { renderer, material } = builder;
  24872. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  24873. if ( material.side === BackSide ) {
  24874. return 'false';
  24875. }
  24876. }
  24877. return builder.getFrontFacing();
  24878. }
  24879. }
  24880. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  24881. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  24882. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  24883. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  24884. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  24885. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  24886. return vec3( 0, 1, 0 );
  24887. }
  24888. return normalGeometry;
  24889. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  24890. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  24891. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24892. let node;
  24893. if ( builder.material.flatShading === true ) {
  24894. node = normalFlat;
  24895. } else {
  24896. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  24897. }
  24898. return node;
  24899. }, 'vec3' ).once() )().toVar( 'normalView' );
  24900. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  24901. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24902. return builder.context.setupNormal();
  24903. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  24904. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  24905. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24906. return builder.context.setupClearcoatNormal();
  24907. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  24908. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  24909. const m = mat3( matrix );
  24910. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  24911. return m.mul( transformedNormal ).xyz;
  24912. } );
  24913. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  24914. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  24915. if ( modelNormalViewMatrix !== null ) {
  24916. return modelNormalViewMatrix.transformDirection( normal );
  24917. }
  24918. //
  24919. const transformedNormal = modelNormalMatrix.mul( normal );
  24920. return cameraViewMatrix.transformDirection( transformedNormal );
  24921. } );
  24922. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  24923. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  24924. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  24925. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24926. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24927. class CubeTextureNode extends TextureNode {
  24928. static get type() {
  24929. return 'CubeTextureNode';
  24930. }
  24931. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24932. super( value, uvNode, levelNode, biasNode );
  24933. this.isCubeTextureNode = true;
  24934. }
  24935. getInputType( /*builder*/ ) {
  24936. return 'cubeTexture';
  24937. }
  24938. getDefaultUV() {
  24939. const texture = this.value;
  24940. if ( texture.mapping === CubeReflectionMapping ) {
  24941. return reflectVector;
  24942. } else if ( texture.mapping === CubeRefractionMapping ) {
  24943. return refractVector;
  24944. } else {
  24945. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  24946. return vec3( 0, 0, 0 );
  24947. }
  24948. }
  24949. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  24950. setupUV( builder, uvNode ) {
  24951. const texture = this.value;
  24952. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  24953. return vec3( uvNode.x.negate(), uvNode.yz );
  24954. } else {
  24955. return uvNode;
  24956. }
  24957. }
  24958. generateUV( builder, cubeUV ) {
  24959. return cubeUV.build( builder, 'vec3' );
  24960. }
  24961. }
  24962. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  24963. class BufferNode extends UniformNode {
  24964. static get type() {
  24965. return 'BufferNode';
  24966. }
  24967. constructor( value, bufferType, bufferCount = 0 ) {
  24968. super( value, bufferType );
  24969. this.isBufferNode = true;
  24970. this.bufferType = bufferType;
  24971. this.bufferCount = bufferCount;
  24972. }
  24973. getElementType( builder ) {
  24974. return this.getNodeType( builder );
  24975. }
  24976. getInputType( /*builder*/ ) {
  24977. return 'buffer';
  24978. }
  24979. }
  24980. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  24981. class UniformArrayElementNode extends ArrayElementNode {
  24982. static get type() {
  24983. return 'UniformArrayElementNode';
  24984. }
  24985. constructor( arrayBuffer, indexNode ) {
  24986. super( arrayBuffer, indexNode );
  24987. this.isArrayBufferElementNode = true;
  24988. }
  24989. generate( builder ) {
  24990. const snippet = super.generate( builder );
  24991. const type = this.getNodeType();
  24992. return builder.format( snippet, 'vec4', type );
  24993. }
  24994. }
  24995. class UniformArrayNode extends BufferNode {
  24996. static get type() {
  24997. return 'UniformArrayNode';
  24998. }
  24999. constructor( value, elementType = null ) {
  25000. super( null, 'vec4' );
  25001. this.array = value;
  25002. this.elementType = elementType;
  25003. this._elementType = null;
  25004. this._elementLength = 0;
  25005. this.updateType = NodeUpdateType.RENDER;
  25006. this.isArrayBufferNode = true;
  25007. }
  25008. getElementType() {
  25009. return this.elementType || this._elementType;
  25010. }
  25011. getElementLength() {
  25012. return this._elementLength;
  25013. }
  25014. update( /*frame*/ ) {
  25015. const { array, value } = this;
  25016. const elementLength = this.getElementLength();
  25017. const elementType = this.getElementType();
  25018. if ( elementLength === 1 ) {
  25019. for ( let i = 0; i < array.length; i ++ ) {
  25020. const index = i * 4;
  25021. value[ index ] = array[ i ];
  25022. }
  25023. } else if ( elementType === 'color' ) {
  25024. for ( let i = 0; i < array.length; i ++ ) {
  25025. const index = i * 4;
  25026. const vector = array[ i ];
  25027. value[ index ] = vector.r;
  25028. value[ index + 1 ] = vector.g;
  25029. value[ index + 2 ] = vector.b || 0;
  25030. //value[ index + 3 ] = vector.a || 0;
  25031. }
  25032. } else {
  25033. for ( let i = 0; i < array.length; i ++ ) {
  25034. const index = i * 4;
  25035. const vector = array[ i ];
  25036. value[ index ] = vector.x;
  25037. value[ index + 1 ] = vector.y;
  25038. value[ index + 2 ] = vector.z || 0;
  25039. value[ index + 3 ] = vector.w || 0;
  25040. }
  25041. }
  25042. }
  25043. setup( builder ) {
  25044. const length = this.array.length;
  25045. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  25046. this._elementLength = builder.getTypeLength( this._elementType );
  25047. let arrayType = Float32Array;
  25048. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  25049. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  25050. this.value = new arrayType( length * 4 );
  25051. this.bufferCount = length;
  25052. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  25053. return super.setup( builder );
  25054. }
  25055. element( indexNode ) {
  25056. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  25057. }
  25058. }
  25059. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  25060. //
  25061. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  25062. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  25063. return nodeObject( new UniformArrayNode( values, nodeType ) );
  25064. };
  25065. class ReferenceElementNode extends ArrayElementNode {
  25066. static get type() {
  25067. return 'ReferenceElementNode';
  25068. }
  25069. constructor( referenceNode, indexNode ) {
  25070. super( referenceNode, indexNode );
  25071. this.referenceNode = referenceNode;
  25072. this.isReferenceElementNode = true;
  25073. }
  25074. getNodeType() {
  25075. return this.referenceNode.uniformType;
  25076. }
  25077. generate( builder ) {
  25078. const snippet = super.generate( builder );
  25079. const arrayType = this.referenceNode.getNodeType();
  25080. const elementType = this.getNodeType();
  25081. return builder.format( snippet, arrayType, elementType );
  25082. }
  25083. }
  25084. // TODO: Extends this from ReferenceBaseNode
  25085. class ReferenceNode extends Node {
  25086. static get type() {
  25087. return 'ReferenceNode';
  25088. }
  25089. constructor( property, uniformType, object = null, count = null ) {
  25090. super();
  25091. this.property = property;
  25092. this.uniformType = uniformType;
  25093. this.object = object;
  25094. this.count = count;
  25095. this.properties = property.split( '.' );
  25096. this.reference = object;
  25097. this.node = null;
  25098. this.group = null;
  25099. this.name = null;
  25100. this.updateType = NodeUpdateType.OBJECT;
  25101. }
  25102. element( indexNode ) {
  25103. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  25104. }
  25105. setGroup( group ) {
  25106. this.group = group;
  25107. return this;
  25108. }
  25109. label( name ) {
  25110. this.name = name;
  25111. return this;
  25112. }
  25113. setNodeType( uniformType ) {
  25114. let node = null;
  25115. if ( this.count !== null ) {
  25116. node = buffer( null, uniformType, this.count );
  25117. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  25118. node = uniformArray( null, uniformType );
  25119. } else if ( uniformType === 'texture' ) {
  25120. node = texture( null );
  25121. } else if ( uniformType === 'cubeTexture' ) {
  25122. node = cubeTexture( null );
  25123. } else {
  25124. node = uniform( null, uniformType );
  25125. }
  25126. if ( this.group !== null ) {
  25127. node.setGroup( this.group );
  25128. }
  25129. if ( this.name !== null ) node.label( this.name );
  25130. this.node = node.getSelf();
  25131. }
  25132. getNodeType( builder ) {
  25133. if ( this.node === null ) {
  25134. this.updateReference( builder );
  25135. this.updateValue();
  25136. }
  25137. return this.node.getNodeType( builder );
  25138. }
  25139. getValueFromReference( object = this.reference ) {
  25140. const { properties } = this;
  25141. let value = object[ properties[ 0 ] ];
  25142. for ( let i = 1; i < properties.length; i ++ ) {
  25143. value = value[ properties[ i ] ];
  25144. }
  25145. return value;
  25146. }
  25147. updateReference( state ) {
  25148. this.reference = this.object !== null ? this.object : state.object;
  25149. return this.reference;
  25150. }
  25151. setup() {
  25152. this.updateValue();
  25153. return this.node;
  25154. }
  25155. update( /*frame*/ ) {
  25156. this.updateValue();
  25157. }
  25158. updateValue() {
  25159. if ( this.node === null ) this.setNodeType( this.uniformType );
  25160. const value = this.getValueFromReference();
  25161. if ( Array.isArray( value ) ) {
  25162. this.node.array = value;
  25163. } else {
  25164. this.node.value = value;
  25165. }
  25166. }
  25167. }
  25168. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  25169. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  25170. class MaterialReferenceNode extends ReferenceNode {
  25171. static get type() {
  25172. return 'MaterialReferenceNode';
  25173. }
  25174. constructor( property, inputType, material = null ) {
  25175. super( property, inputType, material );
  25176. this.material = material;
  25177. //this.updateType = NodeUpdateType.RENDER;
  25178. this.isMaterialReferenceNode = true;
  25179. }
  25180. /*setNodeType( node ) {
  25181. super.setNodeType( node );
  25182. this.node.groupNode = renderGroup;
  25183. }*/
  25184. updateReference( state ) {
  25185. this.reference = this.material !== null ? this.material : state.material;
  25186. return this.reference;
  25187. }
  25188. }
  25189. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  25190. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  25191. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  25192. builder.geometry.computeTangents();
  25193. }
  25194. return attribute( 'tangent', 'vec4' );
  25195. } )();
  25196. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  25197. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  25198. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  25199. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  25200. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  25201. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  25202. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  25203. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  25204. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  25205. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  25206. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  25207. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  25208. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  25209. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  25210. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  25211. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  25212. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  25213. let bentNormal = anisotropyB.cross( positionViewDirection );
  25214. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  25215. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  25216. return bentNormal;
  25217. } )();
  25218. // Normal Mapping Without Precomputed Tangents
  25219. // http://www.thetenthplanet.de/archives/1180
  25220. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  25221. const { eye_pos, surf_norm, mapN, uv } = inputs;
  25222. const q0 = eye_pos.dFdx();
  25223. const q1 = eye_pos.dFdy();
  25224. const st0 = uv.dFdx();
  25225. const st1 = uv.dFdy();
  25226. const N = surf_norm; // normalized
  25227. const q1perp = q1.cross( N );
  25228. const q0perp = N.cross( q0 );
  25229. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  25230. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  25231. const det = T.dot( T ).max( B.dot( B ) );
  25232. const scale = faceDirection.mul( det.inverseSqrt() );
  25233. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  25234. } );
  25235. class NormalMapNode extends TempNode {
  25236. static get type() {
  25237. return 'NormalMapNode';
  25238. }
  25239. constructor( node, scaleNode = null ) {
  25240. super( 'vec3' );
  25241. this.node = node;
  25242. this.scaleNode = scaleNode;
  25243. this.normalMapType = TangentSpaceNormalMap;
  25244. }
  25245. setup( builder ) {
  25246. const { normalMapType, scaleNode } = this;
  25247. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  25248. if ( scaleNode !== null ) {
  25249. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  25250. }
  25251. let outputNode = null;
  25252. if ( normalMapType === ObjectSpaceNormalMap ) {
  25253. outputNode = transformNormalToView( normalMap );
  25254. } else if ( normalMapType === TangentSpaceNormalMap ) {
  25255. const tangent = builder.hasGeometryAttribute( 'tangent' );
  25256. if ( tangent === true ) {
  25257. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  25258. } else {
  25259. outputNode = perturbNormal2Arb( {
  25260. eye_pos: positionView,
  25261. surf_norm: normalView,
  25262. mapN: normalMap,
  25263. uv: uv()
  25264. } );
  25265. }
  25266. }
  25267. return outputNode;
  25268. }
  25269. }
  25270. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  25271. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  25272. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  25273. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  25274. // It's used to preserve the same TextureNode instance
  25275. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  25276. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  25277. return vec2(
  25278. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  25279. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  25280. ).mul( bumpScale );
  25281. } );
  25282. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  25283. const perturbNormalArb = Fn( ( inputs ) => {
  25284. const { surf_pos, surf_norm, dHdxy } = inputs;
  25285. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  25286. const vSigmaX = surf_pos.dFdx().normalize();
  25287. const vSigmaY = surf_pos.dFdy().normalize();
  25288. const vN = surf_norm; // normalized
  25289. const R1 = vSigmaY.cross( vN );
  25290. const R2 = vN.cross( vSigmaX );
  25291. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  25292. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  25293. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  25294. } );
  25295. class BumpMapNode extends TempNode {
  25296. static get type() {
  25297. return 'BumpMapNode';
  25298. }
  25299. constructor( textureNode, scaleNode = null ) {
  25300. super( 'vec3' );
  25301. this.textureNode = textureNode;
  25302. this.scaleNode = scaleNode;
  25303. }
  25304. setup() {
  25305. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  25306. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  25307. return perturbNormalArb( {
  25308. surf_pos: positionView,
  25309. surf_norm: normalView,
  25310. dHdxy
  25311. } );
  25312. }
  25313. }
  25314. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  25315. const _propertyCache = new Map();
  25316. class MaterialNode extends Node {
  25317. static get type() {
  25318. return 'MaterialNode';
  25319. }
  25320. constructor( scope ) {
  25321. super();
  25322. this.scope = scope;
  25323. }
  25324. getCache( property, type ) {
  25325. let node = _propertyCache.get( property );
  25326. if ( node === undefined ) {
  25327. node = materialReference( property, type );
  25328. _propertyCache.set( property, node );
  25329. }
  25330. return node;
  25331. }
  25332. getFloat( property ) {
  25333. return this.getCache( property, 'float' );
  25334. }
  25335. getColor( property ) {
  25336. return this.getCache( property, 'color' );
  25337. }
  25338. getTexture( property ) {
  25339. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  25340. }
  25341. setup( builder ) {
  25342. const material = builder.context.material;
  25343. const scope = this.scope;
  25344. let node = null;
  25345. if ( scope === MaterialNode.COLOR ) {
  25346. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  25347. if ( material.map && material.map.isTexture === true ) {
  25348. node = colorNode.mul( this.getTexture( 'map' ) );
  25349. } else {
  25350. node = colorNode;
  25351. }
  25352. } else if ( scope === MaterialNode.OPACITY ) {
  25353. const opacityNode = this.getFloat( scope );
  25354. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  25355. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  25356. } else {
  25357. node = opacityNode;
  25358. }
  25359. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  25360. if ( material.specularMap && material.specularMap.isTexture === true ) {
  25361. node = this.getTexture( 'specular' ).r;
  25362. } else {
  25363. node = float( 1 );
  25364. }
  25365. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  25366. const specularIntensity = this.getFloat( scope );
  25367. if ( material.specularMap ) {
  25368. node = specularIntensity.mul( this.getTexture( scope ).a );
  25369. } else {
  25370. node = specularIntensity;
  25371. }
  25372. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  25373. const specularColorNode = this.getColor( scope );
  25374. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  25375. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  25376. } else {
  25377. node = specularColorNode;
  25378. }
  25379. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  25380. const roughnessNode = this.getFloat( scope );
  25381. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  25382. node = roughnessNode.mul( this.getTexture( scope ).g );
  25383. } else {
  25384. node = roughnessNode;
  25385. }
  25386. } else if ( scope === MaterialNode.METALNESS ) {
  25387. const metalnessNode = this.getFloat( scope );
  25388. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  25389. node = metalnessNode.mul( this.getTexture( scope ).b );
  25390. } else {
  25391. node = metalnessNode;
  25392. }
  25393. } else if ( scope === MaterialNode.EMISSIVE ) {
  25394. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  25395. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  25396. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  25397. node = emissiveNode.mul( this.getTexture( scope ) );
  25398. } else {
  25399. node = emissiveNode;
  25400. }
  25401. } else if ( scope === MaterialNode.NORMAL ) {
  25402. if ( material.normalMap ) {
  25403. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  25404. node.normalMapType = material.normalMapType;
  25405. } else if ( material.bumpMap ) {
  25406. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  25407. } else {
  25408. node = normalView;
  25409. }
  25410. } else if ( scope === MaterialNode.CLEARCOAT ) {
  25411. const clearcoatNode = this.getFloat( scope );
  25412. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  25413. node = clearcoatNode.mul( this.getTexture( scope ).r );
  25414. } else {
  25415. node = clearcoatNode;
  25416. }
  25417. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  25418. const clearcoatRoughnessNode = this.getFloat( scope );
  25419. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  25420. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  25421. } else {
  25422. node = clearcoatRoughnessNode;
  25423. }
  25424. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  25425. if ( material.clearcoatNormalMap ) {
  25426. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  25427. } else {
  25428. node = normalView;
  25429. }
  25430. } else if ( scope === MaterialNode.SHEEN ) {
  25431. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  25432. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  25433. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  25434. } else {
  25435. node = sheenNode;
  25436. }
  25437. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  25438. const sheenRoughnessNode = this.getFloat( scope );
  25439. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  25440. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  25441. } else {
  25442. node = sheenRoughnessNode;
  25443. }
  25444. node = node.clamp( 0.07, 1.0 );
  25445. } else if ( scope === MaterialNode.ANISOTROPY ) {
  25446. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  25447. const anisotropyPolar = this.getTexture( scope );
  25448. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  25449. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  25450. } else {
  25451. node = materialAnisotropyVector;
  25452. }
  25453. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  25454. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  25455. if ( material.iridescenceThicknessMap ) {
  25456. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  25457. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  25458. } else {
  25459. node = iridescenceThicknessMaximum;
  25460. }
  25461. } else if ( scope === MaterialNode.TRANSMISSION ) {
  25462. const transmissionNode = this.getFloat( scope );
  25463. if ( material.transmissionMap ) {
  25464. node = transmissionNode.mul( this.getTexture( scope ).r );
  25465. } else {
  25466. node = transmissionNode;
  25467. }
  25468. } else if ( scope === MaterialNode.THICKNESS ) {
  25469. const thicknessNode = this.getFloat( scope );
  25470. if ( material.thicknessMap ) {
  25471. node = thicknessNode.mul( this.getTexture( scope ).g );
  25472. } else {
  25473. node = thicknessNode;
  25474. }
  25475. } else if ( scope === MaterialNode.IOR ) {
  25476. node = this.getFloat( scope );
  25477. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  25478. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  25479. } else if ( scope === MaterialNode.AO_MAP ) {
  25480. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  25481. } else {
  25482. const outputType = this.getNodeType( builder );
  25483. node = this.getCache( scope, outputType );
  25484. }
  25485. return node;
  25486. }
  25487. }
  25488. MaterialNode.ALPHA_TEST = 'alphaTest';
  25489. MaterialNode.COLOR = 'color';
  25490. MaterialNode.OPACITY = 'opacity';
  25491. MaterialNode.SHININESS = 'shininess';
  25492. MaterialNode.SPECULAR = 'specular';
  25493. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  25494. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  25495. MaterialNode.SPECULAR_COLOR = 'specularColor';
  25496. MaterialNode.REFLECTIVITY = 'reflectivity';
  25497. MaterialNode.ROUGHNESS = 'roughness';
  25498. MaterialNode.METALNESS = 'metalness';
  25499. MaterialNode.NORMAL = 'normal';
  25500. MaterialNode.CLEARCOAT = 'clearcoat';
  25501. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  25502. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  25503. MaterialNode.EMISSIVE = 'emissive';
  25504. MaterialNode.ROTATION = 'rotation';
  25505. MaterialNode.SHEEN = 'sheen';
  25506. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  25507. MaterialNode.ANISOTROPY = 'anisotropy';
  25508. MaterialNode.IRIDESCENCE = 'iridescence';
  25509. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  25510. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  25511. MaterialNode.IOR = 'ior';
  25512. MaterialNode.TRANSMISSION = 'transmission';
  25513. MaterialNode.THICKNESS = 'thickness';
  25514. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  25515. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  25516. MaterialNode.LINE_SCALE = 'scale';
  25517. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  25518. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  25519. MaterialNode.LINE_WIDTH = 'linewidth';
  25520. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  25521. MaterialNode.POINT_WIDTH = 'pointWidth';
  25522. MaterialNode.DISPERSION = 'dispersion';
  25523. MaterialNode.LIGHT_MAP = 'light';
  25524. MaterialNode.AO_MAP = 'ao';
  25525. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  25526. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  25527. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  25528. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  25529. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  25530. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  25531. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  25532. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  25533. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  25534. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  25535. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  25536. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  25537. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  25538. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  25539. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  25540. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  25541. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  25542. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  25543. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  25544. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  25545. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  25546. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  25547. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  25548. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  25549. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  25550. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  25551. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  25552. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  25553. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  25554. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  25555. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  25556. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  25557. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  25558. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  25559. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  25560. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  25561. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  25562. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  25563. return frame.material;
  25564. } ).onRenderUpdate( function ( { material } ) {
  25565. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  25566. } );
  25567. class ModelViewProjectionNode extends TempNode {
  25568. static get type() {
  25569. return 'ModelViewProjectionNode';
  25570. }
  25571. constructor( positionNode = null ) {
  25572. super( 'vec4' );
  25573. this.positionNode = positionNode;
  25574. }
  25575. setup( builder ) {
  25576. if ( builder.shaderStage === 'fragment' ) {
  25577. return varying( builder.context.mvp );
  25578. }
  25579. const position = this.positionNode || positionLocal;
  25580. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  25581. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  25582. }
  25583. }
  25584. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  25585. class IndexNode extends Node {
  25586. static get type() {
  25587. return 'IndexNode';
  25588. }
  25589. constructor( scope ) {
  25590. super( 'uint' );
  25591. this.scope = scope;
  25592. this.isInstanceIndexNode = true;
  25593. }
  25594. generate( builder ) {
  25595. const nodeType = this.getNodeType( builder );
  25596. const scope = this.scope;
  25597. let propertyName;
  25598. if ( scope === IndexNode.VERTEX ) {
  25599. // The index of a vertex within a mesh.
  25600. propertyName = builder.getVertexIndex();
  25601. } else if ( scope === IndexNode.INSTANCE ) {
  25602. // The index of either a mesh instance or an invocation of a compute shader.
  25603. propertyName = builder.getInstanceIndex();
  25604. } else if ( scope === IndexNode.DRAW ) {
  25605. // The index of a draw call.
  25606. propertyName = builder.getDrawIndex();
  25607. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  25608. // The index of a compute invocation within the scope of a workgroup load.
  25609. propertyName = builder.getInvocationLocalIndex();
  25610. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  25611. // The index of a compute invocation within the scope of a subgroup.
  25612. propertyName = builder.getInvocationSubgroupIndex();
  25613. } else if ( scope === IndexNode.SUBGROUP ) {
  25614. // The index of the subgroup the current compute invocation belongs to.
  25615. propertyName = builder.getSubgroupIndex();
  25616. } else {
  25617. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  25618. }
  25619. let output;
  25620. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  25621. output = propertyName;
  25622. } else {
  25623. const nodeVarying = varying( this );
  25624. output = nodeVarying.build( builder, nodeType );
  25625. }
  25626. return output;
  25627. }
  25628. }
  25629. IndexNode.VERTEX = 'vertex';
  25630. IndexNode.INSTANCE = 'instance';
  25631. IndexNode.SUBGROUP = 'subgroup';
  25632. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  25633. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  25634. IndexNode.DRAW = 'draw';
  25635. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  25636. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  25637. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  25638. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  25639. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  25640. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  25641. class InstanceNode extends Node {
  25642. static get type() {
  25643. return 'InstanceNode';
  25644. }
  25645. constructor( instanceMesh ) {
  25646. super( 'void' );
  25647. this.instanceMesh = instanceMesh;
  25648. this.instanceMatrixNode = null;
  25649. this.instanceColorNode = null;
  25650. this.updateType = NodeUpdateType.FRAME;
  25651. this.buffer = null;
  25652. this.bufferColor = null;
  25653. }
  25654. setup( builder ) {
  25655. let instanceMatrixNode = this.instanceMatrixNode;
  25656. let instanceColorNode = this.instanceColorNode;
  25657. const instanceMesh = this.instanceMesh;
  25658. if ( instanceMatrixNode === null ) {
  25659. const instanceAttribute = instanceMesh.instanceMatrix;
  25660. // 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.
  25661. if ( instanceMesh.count <= 1000 ) {
  25662. instanceMatrixNode = buffer( instanceAttribute.array, 'mat4', Math.max( instanceMesh.count, 1 ) ).element( instanceIndex );
  25663. } else {
  25664. const buffer = new InstancedInterleavedBuffer( instanceAttribute.array, 16, 1 );
  25665. this.buffer = buffer;
  25666. const bufferFn = instanceAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25667. const instanceBuffers = [
  25668. // F.Signature -> bufferAttribute( array, type, stride, offset )
  25669. bufferFn( buffer, 'vec4', 16, 0 ),
  25670. bufferFn( buffer, 'vec4', 16, 4 ),
  25671. bufferFn( buffer, 'vec4', 16, 8 ),
  25672. bufferFn( buffer, 'vec4', 16, 12 )
  25673. ];
  25674. instanceMatrixNode = mat4( ...instanceBuffers );
  25675. }
  25676. this.instanceMatrixNode = instanceMatrixNode;
  25677. }
  25678. const instanceColorAttribute = instanceMesh.instanceColor;
  25679. if ( instanceColorAttribute && instanceColorNode === null ) {
  25680. const buffer = new InstancedBufferAttribute( instanceColorAttribute.array, 3 );
  25681. const bufferFn = instanceColorAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25682. this.bufferColor = buffer;
  25683. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  25684. this.instanceColorNode = instanceColorNode;
  25685. }
  25686. // POSITION
  25687. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  25688. positionLocal.assign( instancePosition );
  25689. // NORMAL
  25690. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25691. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  25692. // ASSIGNS
  25693. normalLocal.assign( instanceNormal );
  25694. }
  25695. // COLOR
  25696. if ( this.instanceColorNode !== null ) {
  25697. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  25698. }
  25699. }
  25700. update( /*frame*/ ) {
  25701. if ( this.instanceMesh.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMesh.instanceMatrix.version !== this.buffer.version ) {
  25702. this.buffer.version = this.instanceMesh.instanceMatrix.version;
  25703. }
  25704. if ( this.instanceMesh.instanceColor && this.instanceMesh.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceMesh.instanceColor.version !== this.bufferColor.version ) {
  25705. this.bufferColor.version = this.instanceMesh.instanceColor.version;
  25706. }
  25707. }
  25708. }
  25709. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  25710. class BatchNode extends Node {
  25711. static get type() {
  25712. return 'BatchNode';
  25713. }
  25714. constructor( batchMesh ) {
  25715. super( 'void' );
  25716. this.batchMesh = batchMesh;
  25717. this.batchingIdNode = null;
  25718. }
  25719. setup( builder ) {
  25720. // POSITION
  25721. if ( this.batchingIdNode === null ) {
  25722. if ( builder.getDrawIndex() === null ) {
  25723. this.batchingIdNode = instanceIndex;
  25724. } else {
  25725. this.batchingIdNode = drawIndex;
  25726. }
  25727. }
  25728. const getIndirectIndex = Fn( ( [ id ] ) => {
  25729. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  25730. const x = int( id ).modInt( int( size ) );
  25731. const y = int( id ).div( int( size ) );
  25732. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  25733. } ).setLayout( {
  25734. name: 'getIndirectIndex',
  25735. type: 'uint',
  25736. inputs: [
  25737. { name: 'id', type: 'int' }
  25738. ]
  25739. } );
  25740. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  25741. const matricesTexture = this.batchMesh._matricesTexture;
  25742. const size = textureSize( textureLoad( matricesTexture ), 0 );
  25743. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  25744. const x = j.modInt( size );
  25745. const y = j.div( int( size ) );
  25746. const batchingMatrix = mat4(
  25747. textureLoad( matricesTexture, ivec2( x, y ) ),
  25748. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  25749. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  25750. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  25751. );
  25752. const colorsTexture = this.batchMesh._colorsTexture;
  25753. if ( colorsTexture !== null ) {
  25754. const getBatchingColor = Fn( ( [ id ] ) => {
  25755. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  25756. const j = id;
  25757. const x = j.modInt( size );
  25758. const y = j.div( size );
  25759. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  25760. } ).setLayout( {
  25761. name: 'getBatchingColor',
  25762. type: 'vec3',
  25763. inputs: [
  25764. { name: 'id', type: 'int' }
  25765. ]
  25766. } );
  25767. const color = getBatchingColor( indirectId );
  25768. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  25769. }
  25770. const bm = mat3( batchingMatrix );
  25771. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  25772. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  25773. const batchingNormal = bm.mul( transformedNormal ).xyz;
  25774. normalLocal.assign( batchingNormal );
  25775. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25776. tangentLocal.mulAssign( bm );
  25777. }
  25778. }
  25779. }
  25780. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  25781. const _frameId = new WeakMap();
  25782. class SkinningNode extends Node {
  25783. static get type() {
  25784. return 'SkinningNode';
  25785. }
  25786. constructor( skinnedMesh, useReference = false ) {
  25787. super( 'void' );
  25788. this.skinnedMesh = skinnedMesh;
  25789. this.useReference = useReference;
  25790. this.updateType = NodeUpdateType.OBJECT;
  25791. //
  25792. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  25793. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  25794. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  25795. if ( useReference ) {
  25796. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  25797. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  25798. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25799. } else {
  25800. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  25801. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  25802. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  25803. }
  25804. this.bindMatrixNode = bindMatrixNode;
  25805. this.bindMatrixInverseNode = bindMatrixInverseNode;
  25806. this.boneMatricesNode = boneMatricesNode;
  25807. this.previousBoneMatricesNode = null;
  25808. }
  25809. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  25810. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25811. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25812. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25813. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25814. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25815. // POSITION
  25816. const skinVertex = bindMatrixNode.mul( position );
  25817. const skinned = add(
  25818. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  25819. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  25820. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  25821. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  25822. );
  25823. return bindMatrixInverseNode.mul( skinned ).xyz;
  25824. }
  25825. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  25826. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25827. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25828. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25829. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25830. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25831. // NORMAL
  25832. let skinMatrix = add(
  25833. skinWeightNode.x.mul( boneMatX ),
  25834. skinWeightNode.y.mul( boneMatY ),
  25835. skinWeightNode.z.mul( boneMatZ ),
  25836. skinWeightNode.w.mul( boneMatW )
  25837. );
  25838. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  25839. return skinMatrix.transformDirection( normal ).xyz;
  25840. }
  25841. getPreviousSkinnedPosition( builder ) {
  25842. const skinnedMesh = builder.object;
  25843. if ( this.previousBoneMatricesNode === null ) {
  25844. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  25845. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25846. }
  25847. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  25848. }
  25849. needsPreviousBoneMatrices( builder ) {
  25850. const mrt = builder.renderer.getMRT();
  25851. return mrt && mrt.has( 'velocity' );
  25852. }
  25853. setup( builder ) {
  25854. if ( this.needsPreviousBoneMatrices( builder ) ) {
  25855. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  25856. }
  25857. const skinPosition = this.getSkinnedPosition();
  25858. positionLocal.assign( skinPosition );
  25859. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25860. const skinNormal = this.getSkinnedNormal();
  25861. normalLocal.assign( skinNormal );
  25862. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25863. tangentLocal.assign( skinNormal );
  25864. }
  25865. }
  25866. }
  25867. generate( builder, output ) {
  25868. if ( output !== 'void' ) {
  25869. return positionLocal.build( builder, output );
  25870. }
  25871. }
  25872. update( frame ) {
  25873. const object = this.useReference ? frame.object : this.skinnedMesh;
  25874. const skeleton = object.skeleton;
  25875. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  25876. _frameId.set( skeleton, frame.frameId );
  25877. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  25878. skeleton.update();
  25879. }
  25880. }
  25881. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  25882. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  25883. class LoopNode extends Node {
  25884. static get type() {
  25885. return 'LoopNode';
  25886. }
  25887. constructor( params = [] ) {
  25888. super();
  25889. this.params = params;
  25890. }
  25891. getVarName( index ) {
  25892. return String.fromCharCode( 'i'.charCodeAt() + index );
  25893. }
  25894. getProperties( builder ) {
  25895. const properties = builder.getNodeProperties( this );
  25896. if ( properties.stackNode !== undefined ) return properties;
  25897. //
  25898. const inputs = {};
  25899. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25900. const param = this.params[ i ];
  25901. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  25902. const type = ( param.isNode !== true && param.type ) || 'int';
  25903. inputs[ name ] = expression( name, type );
  25904. }
  25905. const stack = builder.addStack(); // TODO: cache() it
  25906. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  25907. properties.stackNode = stack;
  25908. builder.removeStack();
  25909. return properties;
  25910. }
  25911. getNodeType( builder ) {
  25912. const { returnsNode } = this.getProperties( builder );
  25913. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  25914. }
  25915. setup( builder ) {
  25916. // setup properties
  25917. this.getProperties( builder );
  25918. }
  25919. generate( builder ) {
  25920. const properties = this.getProperties( builder );
  25921. const params = this.params;
  25922. const stackNode = properties.stackNode;
  25923. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  25924. const param = params[ i ];
  25925. let start = null, end = null, name = null, type = null, condition = null, update = null;
  25926. if ( param.isNode ) {
  25927. type = 'int';
  25928. name = this.getVarName( i );
  25929. start = '0';
  25930. end = param.build( builder, type );
  25931. condition = '<';
  25932. } else {
  25933. type = param.type || 'int';
  25934. name = param.name || this.getVarName( i );
  25935. start = param.start;
  25936. end = param.end;
  25937. condition = param.condition;
  25938. update = param.update;
  25939. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  25940. else if ( start && start.isNode ) start = start.build( builder, type );
  25941. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  25942. else if ( end && end.isNode ) end = end.build( builder, type );
  25943. if ( start !== undefined && end === undefined ) {
  25944. start = start + ' - 1';
  25945. end = '0';
  25946. condition = '>=';
  25947. } else if ( end !== undefined && start === undefined ) {
  25948. start = '0';
  25949. condition = '<';
  25950. }
  25951. if ( condition === undefined ) {
  25952. if ( Number( start ) > Number( end ) ) {
  25953. condition = '>=';
  25954. } else {
  25955. condition = '<';
  25956. }
  25957. }
  25958. }
  25959. const internalParam = { start, end, condition };
  25960. //
  25961. const startSnippet = internalParam.start;
  25962. const endSnippet = internalParam.end;
  25963. let declarationSnippet = '';
  25964. let conditionalSnippet = '';
  25965. let updateSnippet = '';
  25966. if ( ! update ) {
  25967. if ( type === 'int' || type === 'uint' ) {
  25968. if ( condition.includes( '<' ) ) update = '++';
  25969. else update = '--';
  25970. } else {
  25971. if ( condition.includes( '<' ) ) update = '+= 1.';
  25972. else update = '-= 1.';
  25973. }
  25974. }
  25975. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  25976. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  25977. updateSnippet += name + ' ' + update;
  25978. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  25979. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  25980. }
  25981. const stackSnippet = stackNode.build( builder, 'void' );
  25982. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  25983. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  25984. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25985. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  25986. }
  25987. builder.addFlowTab();
  25988. return returnsSnippet;
  25989. }
  25990. }
  25991. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  25992. const Continue = () => expression( 'continue' ).append();
  25993. const Break = () => expression( 'break' ).append();
  25994. //
  25995. const loop = ( ...params ) => { // @deprecated, r168
  25996. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  25997. return Loop( ...params );
  25998. };
  25999. const _morphTextures = /*@__PURE__*/ new WeakMap();
  26000. const _morphVec4 = /*@__PURE__*/ new Vector4();
  26001. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  26002. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  26003. const y = texelIndex.div( width );
  26004. const x = texelIndex.sub( y.mul( width ) );
  26005. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  26006. return bufferAttrib.mul( influence );
  26007. } );
  26008. function getEntry( geometry ) {
  26009. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  26010. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  26011. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  26012. // instead of using attributes, the WebGL 2 code path encodes morph targets
  26013. // into an array of data textures. Each layer represents a single morph target.
  26014. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  26015. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  26016. let entry = _morphTextures.get( geometry );
  26017. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  26018. if ( entry !== undefined ) entry.texture.dispose();
  26019. const morphTargets = geometry.morphAttributes.position || [];
  26020. const morphNormals = geometry.morphAttributes.normal || [];
  26021. const morphColors = geometry.morphAttributes.color || [];
  26022. let vertexDataCount = 0;
  26023. if ( hasMorphPosition === true ) vertexDataCount = 1;
  26024. if ( hasMorphNormals === true ) vertexDataCount = 2;
  26025. if ( hasMorphColors === true ) vertexDataCount = 3;
  26026. let width = geometry.attributes.position.count * vertexDataCount;
  26027. let height = 1;
  26028. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  26029. if ( width > maxTextureSize ) {
  26030. height = Math.ceil( width / maxTextureSize );
  26031. width = maxTextureSize;
  26032. }
  26033. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  26034. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  26035. bufferTexture.type = FloatType;
  26036. bufferTexture.needsUpdate = true;
  26037. // fill buffer
  26038. const vertexDataStride = vertexDataCount * 4;
  26039. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  26040. const morphTarget = morphTargets[ i ];
  26041. const morphNormal = morphNormals[ i ];
  26042. const morphColor = morphColors[ i ];
  26043. const offset = width * height * 4 * i;
  26044. for ( let j = 0; j < morphTarget.count; j ++ ) {
  26045. const stride = j * vertexDataStride;
  26046. if ( hasMorphPosition === true ) {
  26047. _morphVec4.fromBufferAttribute( morphTarget, j );
  26048. buffer[ offset + stride + 0 ] = _morphVec4.x;
  26049. buffer[ offset + stride + 1 ] = _morphVec4.y;
  26050. buffer[ offset + stride + 2 ] = _morphVec4.z;
  26051. buffer[ offset + stride + 3 ] = 0;
  26052. }
  26053. if ( hasMorphNormals === true ) {
  26054. _morphVec4.fromBufferAttribute( morphNormal, j );
  26055. buffer[ offset + stride + 4 ] = _morphVec4.x;
  26056. buffer[ offset + stride + 5 ] = _morphVec4.y;
  26057. buffer[ offset + stride + 6 ] = _morphVec4.z;
  26058. buffer[ offset + stride + 7 ] = 0;
  26059. }
  26060. if ( hasMorphColors === true ) {
  26061. _morphVec4.fromBufferAttribute( morphColor, j );
  26062. buffer[ offset + stride + 8 ] = _morphVec4.x;
  26063. buffer[ offset + stride + 9 ] = _morphVec4.y;
  26064. buffer[ offset + stride + 10 ] = _morphVec4.z;
  26065. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  26066. }
  26067. }
  26068. }
  26069. entry = {
  26070. count: morphTargetsCount,
  26071. texture: bufferTexture,
  26072. stride: vertexDataCount,
  26073. size: new Vector2( width, height )
  26074. };
  26075. _morphTextures.set( geometry, entry );
  26076. function disposeTexture() {
  26077. bufferTexture.dispose();
  26078. _morphTextures.delete( geometry );
  26079. geometry.removeEventListener( 'dispose', disposeTexture );
  26080. }
  26081. geometry.addEventListener( 'dispose', disposeTexture );
  26082. }
  26083. return entry;
  26084. }
  26085. class MorphNode extends Node {
  26086. static get type() {
  26087. return 'MorphNode';
  26088. }
  26089. constructor( mesh ) {
  26090. super( 'void' );
  26091. this.mesh = mesh;
  26092. this.morphBaseInfluence = uniform( 1 );
  26093. this.updateType = NodeUpdateType.OBJECT;
  26094. }
  26095. setup( builder ) {
  26096. const { geometry } = builder;
  26097. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  26098. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  26099. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  26100. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  26101. // nodes
  26102. const { texture: bufferMap, stride, size } = getEntry( geometry );
  26103. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  26104. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  26105. const width = int( size.width );
  26106. Loop( morphTargetsCount, ( { i } ) => {
  26107. const influence = float( 0 ).toVar();
  26108. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  26109. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  26110. } else {
  26111. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  26112. }
  26113. if ( hasMorphPosition === true ) {
  26114. positionLocal.addAssign( getMorph( {
  26115. bufferMap,
  26116. influence,
  26117. stride,
  26118. width,
  26119. depth: i,
  26120. offset: int( 0 )
  26121. } ) );
  26122. }
  26123. if ( hasMorphNormals === true ) {
  26124. normalLocal.addAssign( getMorph( {
  26125. bufferMap,
  26126. influence,
  26127. stride,
  26128. width,
  26129. depth: i,
  26130. offset: int( 1 )
  26131. } ) );
  26132. }
  26133. } );
  26134. }
  26135. update() {
  26136. const morphBaseInfluence = this.morphBaseInfluence;
  26137. if ( this.mesh.geometry.morphTargetsRelative ) {
  26138. morphBaseInfluence.value = 1;
  26139. } else {
  26140. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  26141. }
  26142. }
  26143. }
  26144. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  26145. class LightingNode extends Node {
  26146. static get type() {
  26147. return 'LightingNode';
  26148. }
  26149. constructor() {
  26150. super( 'vec3' );
  26151. this.isLightingNode = true;
  26152. }
  26153. generate( /*builder*/ ) {
  26154. console.warn( 'Abstract function.' );
  26155. }
  26156. }
  26157. class AONode extends LightingNode {
  26158. static get type() {
  26159. return 'AONode';
  26160. }
  26161. constructor( aoNode = null ) {
  26162. super();
  26163. this.aoNode = aoNode;
  26164. }
  26165. setup( builder ) {
  26166. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  26167. }
  26168. }
  26169. class LightingContextNode extends ContextNode {
  26170. static get type() {
  26171. return 'LightingContextNode';
  26172. }
  26173. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  26174. super( node );
  26175. this.lightingModel = lightingModel;
  26176. this.backdropNode = backdropNode;
  26177. this.backdropAlphaNode = backdropAlphaNode;
  26178. this._value = null;
  26179. }
  26180. getContext() {
  26181. const { backdropNode, backdropAlphaNode } = this;
  26182. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  26183. directSpecular = vec3().toVar( 'directSpecular' ),
  26184. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  26185. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  26186. const reflectedLight = {
  26187. directDiffuse,
  26188. directSpecular,
  26189. indirectDiffuse,
  26190. indirectSpecular
  26191. };
  26192. const context = {
  26193. radiance: vec3().toVar( 'radiance' ),
  26194. irradiance: vec3().toVar( 'irradiance' ),
  26195. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  26196. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  26197. reflectedLight,
  26198. backdrop: backdropNode,
  26199. backdropAlpha: backdropAlphaNode
  26200. };
  26201. return context;
  26202. }
  26203. setup( builder ) {
  26204. this.value = this._value || ( this._value = this.getContext() );
  26205. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  26206. return super.setup( builder );
  26207. }
  26208. }
  26209. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  26210. class IrradianceNode extends LightingNode {
  26211. static get type() {
  26212. return 'IrradianceNode';
  26213. }
  26214. constructor( node ) {
  26215. super();
  26216. this.node = node;
  26217. }
  26218. setup( builder ) {
  26219. builder.context.irradiance.addAssign( this.node );
  26220. }
  26221. }
  26222. let screenSizeVec, viewportVec;
  26223. class ScreenNode extends Node {
  26224. static get type() {
  26225. return 'ScreenNode';
  26226. }
  26227. constructor( scope ) {
  26228. super();
  26229. this.scope = scope;
  26230. this.isViewportNode = true;
  26231. }
  26232. getNodeType() {
  26233. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  26234. else return 'vec2';
  26235. }
  26236. getUpdateType() {
  26237. let updateType = NodeUpdateType.NONE;
  26238. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  26239. updateType = NodeUpdateType.RENDER;
  26240. }
  26241. this.updateType = updateType;
  26242. return updateType;
  26243. }
  26244. update( { renderer } ) {
  26245. const renderTarget = renderer.getRenderTarget();
  26246. if ( this.scope === ScreenNode.VIEWPORT ) {
  26247. if ( renderTarget !== null ) {
  26248. viewportVec.copy( renderTarget.viewport );
  26249. } else {
  26250. renderer.getViewport( viewportVec );
  26251. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  26252. }
  26253. } else {
  26254. if ( renderTarget !== null ) {
  26255. screenSizeVec.width = renderTarget.width;
  26256. screenSizeVec.height = renderTarget.height;
  26257. } else {
  26258. renderer.getDrawingBufferSize( screenSizeVec );
  26259. }
  26260. }
  26261. }
  26262. setup( /*builder*/ ) {
  26263. const scope = this.scope;
  26264. let output = null;
  26265. if ( scope === ScreenNode.SIZE ) {
  26266. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  26267. } else if ( scope === ScreenNode.VIEWPORT ) {
  26268. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  26269. } else {
  26270. output = vec2( screenCoordinate.div( screenSize ) );
  26271. }
  26272. return output;
  26273. }
  26274. generate( builder ) {
  26275. if ( this.scope === ScreenNode.COORDINATE ) {
  26276. let coord = builder.getFragCoord();
  26277. if ( builder.isFlipY() ) {
  26278. // follow webgpu standards
  26279. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  26280. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  26281. }
  26282. return coord;
  26283. }
  26284. return super.generate( builder );
  26285. }
  26286. }
  26287. ScreenNode.COORDINATE = 'coordinate';
  26288. ScreenNode.VIEWPORT = 'viewport';
  26289. ScreenNode.SIZE = 'size';
  26290. ScreenNode.UV = 'uv';
  26291. // Screen
  26292. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  26293. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  26294. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  26295. // Viewport
  26296. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  26297. const viewportSize = viewport.zw;
  26298. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  26299. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  26300. // Deprecated
  26301. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  26302. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  26303. return screenSize;
  26304. }, 'vec2' ).once() )();
  26305. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26306. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  26307. return screenUV;
  26308. }, 'vec2' ).once() )();
  26309. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26310. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  26311. return screenUV.flipY();
  26312. }, 'vec2' ).once() )();
  26313. const _size$4 = /*@__PURE__*/ new Vector2();
  26314. class ViewportTextureNode extends TextureNode {
  26315. static get type() {
  26316. return 'ViewportTextureNode';
  26317. }
  26318. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  26319. if ( framebufferTexture === null ) {
  26320. framebufferTexture = new FramebufferTexture();
  26321. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  26322. }
  26323. super( framebufferTexture, uvNode, levelNode );
  26324. this.generateMipmaps = false;
  26325. this.isOutputTextureNode = true;
  26326. this.updateBeforeType = NodeUpdateType.FRAME;
  26327. }
  26328. updateBefore( frame ) {
  26329. const renderer = frame.renderer;
  26330. renderer.getDrawingBufferSize( _size$4 );
  26331. //
  26332. const framebufferTexture = this.value;
  26333. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  26334. framebufferTexture.image.width = _size$4.width;
  26335. framebufferTexture.image.height = _size$4.height;
  26336. framebufferTexture.needsUpdate = true;
  26337. }
  26338. //
  26339. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  26340. framebufferTexture.generateMipmaps = this.generateMipmaps;
  26341. renderer.copyFramebufferToTexture( framebufferTexture );
  26342. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  26343. }
  26344. clone() {
  26345. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  26346. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  26347. return viewportTextureNode;
  26348. }
  26349. }
  26350. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  26351. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  26352. let sharedDepthbuffer = null;
  26353. class ViewportDepthTextureNode extends ViewportTextureNode {
  26354. static get type() {
  26355. return 'ViewportDepthTextureNode';
  26356. }
  26357. constructor( uvNode = screenUV, levelNode = null ) {
  26358. if ( sharedDepthbuffer === null ) {
  26359. sharedDepthbuffer = new DepthTexture();
  26360. }
  26361. super( uvNode, levelNode, sharedDepthbuffer );
  26362. }
  26363. }
  26364. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  26365. class ViewportDepthNode extends Node {
  26366. static get type() {
  26367. return 'ViewportDepthNode';
  26368. }
  26369. constructor( scope, valueNode = null ) {
  26370. super( 'float' );
  26371. this.scope = scope;
  26372. this.valueNode = valueNode;
  26373. this.isViewportDepthNode = true;
  26374. }
  26375. generate( builder ) {
  26376. const { scope } = this;
  26377. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26378. return builder.getFragDepth();
  26379. }
  26380. return super.generate( builder );
  26381. }
  26382. setup( { camera } ) {
  26383. const { scope } = this;
  26384. const value = this.valueNode;
  26385. let node = null;
  26386. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26387. if ( value !== null ) {
  26388. node = depthBase().assign( value );
  26389. }
  26390. } else if ( scope === ViewportDepthNode.DEPTH ) {
  26391. if ( camera.isPerspectiveCamera ) {
  26392. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  26393. } else {
  26394. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26395. }
  26396. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  26397. if ( value !== null ) {
  26398. if ( camera.isPerspectiveCamera ) {
  26399. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  26400. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  26401. } else {
  26402. node = value;
  26403. }
  26404. } else {
  26405. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26406. }
  26407. }
  26408. return node;
  26409. }
  26410. }
  26411. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  26412. ViewportDepthNode.DEPTH = 'depth';
  26413. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  26414. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  26415. // -near maps to 0; -far maps to 1
  26416. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  26417. // maps orthographic depth in [ 0, 1 ] to viewZ
  26418. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  26419. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  26420. // -near maps to 0; -far maps to 1
  26421. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  26422. // maps perspective depth in [ 0, 1 ] to viewZ
  26423. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  26424. const perspectiveDepthToLogarithmicDepth = ( perspectiveW, near, far ) => {
  26425. // The final logarithmic depth formula used here is adapted from one described in an
  26426. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  26427. // which was an improvement upon an earlier formula one described in an
  26428. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  26429. // Ulrich's formula is the following:
  26430. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  26431. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  26432. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  26433. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  26434. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  26435. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  26436. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  26437. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  26438. // be used, and ultimately Ulrich's "near plane" version was chosen.
  26439. // Outerra eventually made another improvement to their original "C-constant" variant,
  26440. // but it still does not incorporate the camera near plane (for this version,
  26441. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  26442. // Here we make 4 changes to Ulrich's formula:
  26443. // 1. Clamp the camera near plane so we don't divide by 0.
  26444. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  26445. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  26446. // 4. Add 1 to each division by cameraNear to ensure the depth curve is shifted to the left as cameraNear increases.
  26447. // For visual representation of this depth curve, see https://www.desmos.com/calculator/lz5rqfysih
  26448. near = near.max( 1e-6 ).toVar();
  26449. const numerator = log2( perspectiveW.div( near ).add( 1 ) );
  26450. const denominator = log2( far.div( near ).add( 1 ) );
  26451. return numerator.div( denominator );
  26452. };
  26453. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  26454. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26455. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  26456. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  26457. depth.assign = ( value ) => depthBase( value );
  26458. class ClippingNode extends Node {
  26459. static get type() {
  26460. return 'ClippingNode';
  26461. }
  26462. constructor( scope = ClippingNode.DEFAULT ) {
  26463. super();
  26464. this.scope = scope;
  26465. }
  26466. setup( builder ) {
  26467. super.setup( builder );
  26468. const clippingContext = builder.clippingContext;
  26469. const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext;
  26470. const numClippingPlanes = globalClippingCount + localClippingCount;
  26471. const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes;
  26472. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  26473. return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26474. } else {
  26475. return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26476. }
  26477. }
  26478. setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26479. return Fn( () => {
  26480. const clippingPlanes = uniformArray( planes );
  26481. const distanceToPlane = property( 'float', 'distanceToPlane' );
  26482. const distanceGradient = property( 'float', 'distanceToGradient' );
  26483. const clipOpacity = property( 'float', 'clipOpacity' );
  26484. clipOpacity.assign( 1 );
  26485. let plane;
  26486. Loop( numUnionClippingPlanes, ( { i } ) => {
  26487. plane = clippingPlanes.element( i );
  26488. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26489. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26490. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  26491. clipOpacity.equal( 0.0 ).discard();
  26492. } );
  26493. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26494. const unionClipOpacity = property( 'float', 'unionclipOpacity' );
  26495. unionClipOpacity.assign( 1 );
  26496. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26497. plane = clippingPlanes.element( i );
  26498. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26499. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26500. unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  26501. } );
  26502. clipOpacity.mulAssign( unionClipOpacity.oneMinus() );
  26503. }
  26504. diffuseColor.a.mulAssign( clipOpacity );
  26505. diffuseColor.a.equal( 0.0 ).discard();
  26506. } )();
  26507. }
  26508. setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26509. return Fn( () => {
  26510. const clippingPlanes = uniformArray( planes );
  26511. let plane;
  26512. Loop( numUnionClippingPlanes, ( { i } ) => {
  26513. plane = clippingPlanes.element( i );
  26514. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  26515. } );
  26516. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26517. const clipped = property( 'bool', 'clipped' );
  26518. clipped.assign( true );
  26519. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26520. plane = clippingPlanes.element( i );
  26521. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  26522. } );
  26523. clipped.discard();
  26524. }
  26525. } )();
  26526. }
  26527. }
  26528. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  26529. ClippingNode.DEFAULT = 'default';
  26530. const clipping = () => nodeObject( new ClippingNode() );
  26531. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  26532. /**
  26533. * See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  26534. */
  26535. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  26536. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  26537. return fract( mul( 1.0e4, sin( mul( 17.0, value.x ).add( mul( 0.1, value.y ) ) ) ).mul( add( 0.1, abs( sin( mul( 13.0, value.y ).add( value.x ) ) ) ) ) );
  26538. } );
  26539. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  26540. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  26541. } );
  26542. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  26543. // Find the discretized derivatives of our coordinates
  26544. const maxDeriv = max$1(
  26545. length( dFdx( position.xyz ) ),
  26546. length( dFdy( position.xyz ) )
  26547. ).toVar( 'maxDeriv' );
  26548. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  26549. // Find two nearest log-discretized noise scales
  26550. const pixScales = vec2(
  26551. exp2( floor( log2( pixScale ) ) ),
  26552. exp2( ceil( log2( pixScale ) ) )
  26553. ).toVar( 'pixScales' );
  26554. // Compute alpha thresholds at our two noise scales
  26555. const alpha = vec2(
  26556. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  26557. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  26558. ).toVar( 'alpha' );
  26559. // Factor to interpolate lerp with
  26560. const lerpFactor = fract( log2( pixScale ) ).toVar( 'lerpFactor' );
  26561. // Interpolate alpha threshold from noise at two scales
  26562. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) ).toVar( 'x' );
  26563. // Pass into CDF to compute uniformly distrib threshold
  26564. const a = min$1( lerpFactor, lerpFactor.oneMinus() ).toVar( 'a' );
  26565. const cases = vec3(
  26566. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  26567. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  26568. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) ).toVar( 'cases' );
  26569. // Find our final, uniformly distributed alpha threshold (ατ)
  26570. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  26571. // Avoids ατ == 0. Could also do ατ =1-ατ
  26572. return clamp( threshold, 1.0e-6, 1.0 );
  26573. } );
  26574. class NodeMaterial extends Material {
  26575. static get type() {
  26576. return 'NodeMaterial';
  26577. }
  26578. constructor() {
  26579. super();
  26580. this.isNodeMaterial = true;
  26581. this.type = this.constructor.type;
  26582. this.forceSinglePass = false;
  26583. this.fog = true;
  26584. this.lights = false;
  26585. this.lightsNode = null;
  26586. this.envNode = null;
  26587. this.aoNode = null;
  26588. this.colorNode = null;
  26589. this.normalNode = null;
  26590. this.opacityNode = null;
  26591. this.backdropNode = null;
  26592. this.backdropAlphaNode = null;
  26593. this.alphaTestNode = null;
  26594. this.positionNode = null;
  26595. this.geometryNode = null;
  26596. this.depthNode = null;
  26597. this.shadowNode = null;
  26598. this.shadowPositionNode = null;
  26599. this.outputNode = null;
  26600. this.mrtNode = null;
  26601. this.fragmentNode = null;
  26602. this.vertexNode = null;
  26603. }
  26604. customProgramCacheKey() {
  26605. return this.type + getCacheKey$1( this );
  26606. }
  26607. build( builder ) {
  26608. this.setup( builder );
  26609. }
  26610. setupObserver( builder ) {
  26611. return new NodeMaterialObserver( builder );
  26612. }
  26613. setup( builder ) {
  26614. builder.context.setupNormal = () => this.setupNormal( builder );
  26615. // < VERTEX STAGE >
  26616. builder.addStack();
  26617. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  26618. if ( this.geometryNode !== null ) {
  26619. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  26620. }
  26621. builder.addFlow( 'vertex', builder.removeStack() );
  26622. // < FRAGMENT STAGE >
  26623. builder.addStack();
  26624. let resultNode;
  26625. const clippingNode = this.setupClipping( builder );
  26626. if ( this.depthWrite === true ) this.setupDepth( builder );
  26627. if ( this.fragmentNode === null ) {
  26628. this.setupDiffuseColor( builder );
  26629. this.setupVariants( builder );
  26630. const outgoingLightNode = this.setupLighting( builder );
  26631. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  26632. // force unsigned floats - useful for RenderTargets
  26633. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  26634. resultNode = this.setupOutput( builder, basicOutput );
  26635. // OUTPUT NODE
  26636. output.assign( resultNode );
  26637. //
  26638. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26639. // MRT
  26640. const renderTarget = builder.renderer.getRenderTarget();
  26641. if ( renderTarget !== null ) {
  26642. const mrt = builder.renderer.getMRT();
  26643. const materialMRT = this.mrtNode;
  26644. if ( mrt !== null ) {
  26645. resultNode = mrt;
  26646. if ( materialMRT !== null ) {
  26647. resultNode = mrt.merge( materialMRT );
  26648. }
  26649. } else if ( materialMRT !== null ) {
  26650. resultNode = materialMRT;
  26651. }
  26652. }
  26653. } else {
  26654. let fragmentNode = this.fragmentNode;
  26655. if ( fragmentNode.isOutputStructNode !== true ) {
  26656. fragmentNode = vec4( fragmentNode );
  26657. }
  26658. resultNode = this.setupOutput( builder, fragmentNode );
  26659. }
  26660. builder.stack.outputNode = resultNode;
  26661. builder.addFlow( 'fragment', builder.removeStack() );
  26662. // < MONITOR >
  26663. builder.monitor = this.setupObserver( builder );
  26664. }
  26665. setupClipping( builder ) {
  26666. if ( builder.clippingContext === null ) return null;
  26667. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  26668. let result = null;
  26669. if ( globalClippingCount || localClippingCount ) {
  26670. const samples = builder.renderer.samples;
  26671. if ( this.alphaToCoverage && samples > 1 ) {
  26672. // to be added to flow when the color/alpha value has been determined
  26673. result = clippingAlpha();
  26674. } else {
  26675. builder.stack.add( clipping() );
  26676. }
  26677. }
  26678. return result;
  26679. }
  26680. setupDepth( builder ) {
  26681. const { renderer, camera } = builder;
  26682. // Depth
  26683. let depthNode = this.depthNode;
  26684. if ( depthNode === null ) {
  26685. const mrt = renderer.getMRT();
  26686. if ( mrt && mrt.has( 'depth' ) ) {
  26687. depthNode = mrt.get( 'depth' );
  26688. } else if ( renderer.logarithmicDepthBuffer === true ) {
  26689. if ( camera.isPerspectiveCamera ) {
  26690. depthNode = perspectiveDepthToLogarithmicDepth( modelViewProjection().w, cameraNear, cameraFar );
  26691. } else {
  26692. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26693. }
  26694. }
  26695. }
  26696. if ( depthNode !== null ) {
  26697. depth.assign( depthNode ).append();
  26698. }
  26699. }
  26700. setupPosition( builder ) {
  26701. const { object } = builder;
  26702. const geometry = object.geometry;
  26703. builder.addStack();
  26704. // Vertex
  26705. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  26706. morphReference( object ).append();
  26707. }
  26708. if ( object.isSkinnedMesh === true ) {
  26709. skinningReference( object ).append();
  26710. }
  26711. if ( this.displacementMap ) {
  26712. const displacementMap = materialReference( 'displacementMap', 'texture' );
  26713. const displacementScale = materialReference( 'displacementScale', 'float' );
  26714. const displacementBias = materialReference( 'displacementBias', 'float' );
  26715. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  26716. }
  26717. if ( object.isBatchedMesh ) {
  26718. batch( object ).append();
  26719. }
  26720. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  26721. instance( object ).append();
  26722. }
  26723. if ( this.positionNode !== null ) {
  26724. positionLocal.assign( this.positionNode );
  26725. }
  26726. const mvp = modelViewProjection();
  26727. builder.context.vertex = builder.removeStack();
  26728. builder.context.mvp = mvp;
  26729. return mvp;
  26730. }
  26731. setupDiffuseColor( { object, geometry } ) {
  26732. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  26733. // VERTEX COLORS
  26734. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  26735. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  26736. }
  26737. // Instanced colors
  26738. if ( object.instanceColor ) {
  26739. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  26740. colorNode = instanceColor.mul( colorNode );
  26741. }
  26742. if ( object.isBatchedMesh && object._colorsTexture ) {
  26743. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  26744. colorNode = batchColor.mul( colorNode );
  26745. }
  26746. // COLOR
  26747. diffuseColor.assign( colorNode );
  26748. // OPACITY
  26749. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  26750. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  26751. // ALPHA TEST
  26752. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  26753. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  26754. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  26755. }
  26756. // ALPHA HASH
  26757. if ( this.alphaHash === true ) {
  26758. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  26759. }
  26760. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  26761. diffuseColor.a.assign( 1.0 );
  26762. }
  26763. }
  26764. setupVariants( /*builder*/ ) {
  26765. // Interface function.
  26766. }
  26767. setupOutgoingLight() {
  26768. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  26769. }
  26770. setupNormal() {
  26771. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  26772. }
  26773. setupEnvironment( /*builder*/ ) {
  26774. let node = null;
  26775. if ( this.envNode ) {
  26776. node = this.envNode;
  26777. } else if ( this.envMap ) {
  26778. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  26779. }
  26780. return node;
  26781. }
  26782. setupLightMap( builder ) {
  26783. let node = null;
  26784. if ( builder.material.lightMap ) {
  26785. node = new IrradianceNode( materialLightMap );
  26786. }
  26787. return node;
  26788. }
  26789. setupLights( builder ) {
  26790. const materialLightsNode = [];
  26791. //
  26792. const envNode = this.setupEnvironment( builder );
  26793. if ( envNode && envNode.isLightingNode ) {
  26794. materialLightsNode.push( envNode );
  26795. }
  26796. const lightMapNode = this.setupLightMap( builder );
  26797. if ( lightMapNode && lightMapNode.isLightingNode ) {
  26798. materialLightsNode.push( lightMapNode );
  26799. }
  26800. if ( this.aoNode !== null || builder.material.aoMap ) {
  26801. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  26802. materialLightsNode.push( new AONode( aoNode ) );
  26803. }
  26804. let lightsN = this.lightsNode || builder.lightsNode;
  26805. if ( materialLightsNode.length > 0 ) {
  26806. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  26807. }
  26808. return lightsN;
  26809. }
  26810. setupLightingModel( /*builder*/ ) {
  26811. // Interface function.
  26812. }
  26813. setupLighting( builder ) {
  26814. const { material } = builder;
  26815. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  26816. // OUTGOING LIGHT
  26817. const lights = this.lights === true || this.lightsNode !== null;
  26818. const lightsNode = lights ? this.setupLights( builder ) : null;
  26819. let outgoingLightNode = this.setupOutgoingLight( builder );
  26820. if ( lightsNode && lightsNode.getScope().hasLights ) {
  26821. const lightingModel = this.setupLightingModel( builder );
  26822. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  26823. } else if ( backdropNode !== null ) {
  26824. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  26825. }
  26826. // EMISSIVE
  26827. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  26828. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  26829. outgoingLightNode = outgoingLightNode.add( emissive );
  26830. }
  26831. return outgoingLightNode;
  26832. }
  26833. setupOutput( builder, outputNode ) {
  26834. // FOG
  26835. if ( this.fog === true ) {
  26836. const fogNode = builder.fogNode;
  26837. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  26838. }
  26839. return outputNode;
  26840. }
  26841. setDefaultValues( material ) {
  26842. // This approach is to reuse the native refreshUniforms*
  26843. // and turn available the use of features like transmission and environment in core
  26844. for ( const property in material ) {
  26845. const value = material[ property ];
  26846. if ( this[ property ] === undefined ) {
  26847. this[ property ] = value;
  26848. if ( value && value.clone ) this[ property ] = value.clone();
  26849. }
  26850. }
  26851. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  26852. for ( const key in descriptors ) {
  26853. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  26854. descriptors[ key ].get !== undefined ) {
  26855. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  26856. }
  26857. }
  26858. }
  26859. toJSON( meta ) {
  26860. const isRoot = ( meta === undefined || typeof meta === 'string' );
  26861. if ( isRoot ) {
  26862. meta = {
  26863. textures: {},
  26864. images: {},
  26865. nodes: {}
  26866. };
  26867. }
  26868. const data = Material.prototype.toJSON.call( this, meta );
  26869. const nodeChildren = getNodeChildren( this );
  26870. data.inputNodes = {};
  26871. for ( const { property, childNode } of nodeChildren ) {
  26872. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  26873. }
  26874. // TODO: Copied from Object3D.toJSON
  26875. function extractFromCache( cache ) {
  26876. const values = [];
  26877. for ( const key in cache ) {
  26878. const data = cache[ key ];
  26879. delete data.metadata;
  26880. values.push( data );
  26881. }
  26882. return values;
  26883. }
  26884. if ( isRoot ) {
  26885. const textures = extractFromCache( meta.textures );
  26886. const images = extractFromCache( meta.images );
  26887. const nodes = extractFromCache( meta.nodes );
  26888. if ( textures.length > 0 ) data.textures = textures;
  26889. if ( images.length > 0 ) data.images = images;
  26890. if ( nodes.length > 0 ) data.nodes = nodes;
  26891. }
  26892. return data;
  26893. }
  26894. copy( source ) {
  26895. this.lightsNode = source.lightsNode;
  26896. this.envNode = source.envNode;
  26897. this.colorNode = source.colorNode;
  26898. this.normalNode = source.normalNode;
  26899. this.opacityNode = source.opacityNode;
  26900. this.backdropNode = source.backdropNode;
  26901. this.backdropAlphaNode = source.backdropAlphaNode;
  26902. this.alphaTestNode = source.alphaTestNode;
  26903. this.positionNode = source.positionNode;
  26904. this.geometryNode = source.geometryNode;
  26905. this.depthNode = source.depthNode;
  26906. this.shadowNode = source.shadowNode;
  26907. this.shadowPositionNode = source.shadowPositionNode;
  26908. this.outputNode = source.outputNode;
  26909. this.mrtNode = source.mrtNode;
  26910. this.fragmentNode = source.fragmentNode;
  26911. this.vertexNode = source.vertexNode;
  26912. return super.copy( source );
  26913. }
  26914. }
  26915. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  26916. class InstancedPointsNodeMaterial extends NodeMaterial {
  26917. static get type() {
  26918. return 'InstancedPointsNodeMaterial';
  26919. }
  26920. constructor( params = {} ) {
  26921. super();
  26922. this.lights = false;
  26923. this.useAlphaToCoverage = true;
  26924. this.useColor = params.vertexColors;
  26925. this.pointWidth = 1;
  26926. this.pointColorNode = null;
  26927. this.pointWidthNode = null;
  26928. this.setDefaultValues( _defaultValues$e );
  26929. this.setValues( params );
  26930. }
  26931. setup( builder ) {
  26932. this.setupShaders( builder );
  26933. super.setup( builder );
  26934. }
  26935. setupShaders( { renderer } ) {
  26936. const useAlphaToCoverage = this.alphaToCoverage;
  26937. const useColor = this.useColor;
  26938. this.vertexNode = Fn( () => {
  26939. const instancePosition = attribute( 'instancePosition' ).xyz;
  26940. // camera space
  26941. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  26942. const aspect = viewport.z.div( viewport.w );
  26943. // clip space
  26944. const clipPos = cameraProjectionMatrix.mul( mvPos );
  26945. // offset in ndc space
  26946. const offset = positionGeometry.xy.toVar();
  26947. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  26948. offset.assign( offset.div( viewport.z ) );
  26949. offset.y.assign( offset.y.mul( aspect ) );
  26950. // back to clip space
  26951. offset.assign( offset.mul( clipPos.w ) );
  26952. //clipPos.xy += offset;
  26953. clipPos.addAssign( vec4( offset, 0, 0 ) );
  26954. return clipPos;
  26955. } )();
  26956. this.fragmentNode = Fn( () => {
  26957. const alpha = float( 1 ).toVar();
  26958. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  26959. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  26960. const dlen = float( len2.fwidth() ).toVar();
  26961. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26962. } else {
  26963. len2.greaterThan( 1.0 ).discard();
  26964. }
  26965. let pointColorNode;
  26966. if ( this.pointColorNode ) {
  26967. pointColorNode = this.pointColorNode;
  26968. } else {
  26969. if ( useColor ) {
  26970. const instanceColor = attribute( 'instanceColor' );
  26971. pointColorNode = instanceColor.mul( materialColor );
  26972. } else {
  26973. pointColorNode = materialColor;
  26974. }
  26975. }
  26976. alpha.mulAssign( materialOpacity );
  26977. return vec4( pointColorNode, alpha );
  26978. } )();
  26979. }
  26980. get alphaToCoverage() {
  26981. return this.useAlphaToCoverage;
  26982. }
  26983. set alphaToCoverage( value ) {
  26984. if ( this.useAlphaToCoverage !== value ) {
  26985. this.useAlphaToCoverage = value;
  26986. this.needsUpdate = true;
  26987. }
  26988. }
  26989. }
  26990. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  26991. class LineBasicNodeMaterial extends NodeMaterial {
  26992. static get type() {
  26993. return 'LineBasicNodeMaterial';
  26994. }
  26995. constructor( parameters ) {
  26996. super();
  26997. this.isLineBasicNodeMaterial = true;
  26998. this.lights = false;
  26999. this.setDefaultValues( _defaultValues$d );
  27000. this.setValues( parameters );
  27001. }
  27002. }
  27003. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  27004. class LineDashedNodeMaterial extends NodeMaterial {
  27005. static get type() {
  27006. return 'LineDashedNodeMaterial';
  27007. }
  27008. constructor( parameters ) {
  27009. super();
  27010. this.isLineDashedNodeMaterial = true;
  27011. this.lights = false;
  27012. this.setDefaultValues( _defaultValues$c );
  27013. this.offsetNode = null;
  27014. this.dashScaleNode = null;
  27015. this.dashSizeNode = null;
  27016. this.gapSizeNode = null;
  27017. this.setValues( parameters );
  27018. }
  27019. setupVariants() {
  27020. const offsetNode = this.offsetNode;
  27021. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  27022. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  27023. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  27024. dashSize.assign( dashSizeNode );
  27025. gapSize.assign( gapSizeNode );
  27026. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  27027. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  27028. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  27029. }
  27030. }
  27031. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  27032. class Line2NodeMaterial extends NodeMaterial {
  27033. static get type() {
  27034. return 'Line2NodeMaterial';
  27035. }
  27036. constructor( params = {} ) {
  27037. super();
  27038. this.lights = false;
  27039. this.setDefaultValues( _defaultValues$b );
  27040. this.useAlphaToCoverage = true;
  27041. this.useColor = params.vertexColors;
  27042. this.useDash = params.dashed;
  27043. this.useWorldUnits = false;
  27044. this.dashOffset = 0;
  27045. this.lineWidth = 1;
  27046. this.lineColorNode = null;
  27047. this.offsetNode = null;
  27048. this.dashScaleNode = null;
  27049. this.dashSizeNode = null;
  27050. this.gapSizeNode = null;
  27051. this.setValues( params );
  27052. }
  27053. setup( builder ) {
  27054. this.setupShaders( builder );
  27055. super.setup( builder );
  27056. }
  27057. setupShaders( { renderer } ) {
  27058. const useAlphaToCoverage = this.alphaToCoverage;
  27059. const useColor = this.useColor;
  27060. const useDash = this.dashed;
  27061. const useWorldUnits = this.worldUnits;
  27062. const trimSegment = Fn( ( { start, end } ) => {
  27063. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  27064. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  27065. const nearEstimate = b.mul( - 0.5 ).div( a );
  27066. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  27067. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  27068. } ).setLayout( {
  27069. name: 'trimSegment',
  27070. type: 'vec4',
  27071. inputs: [
  27072. { name: 'start', type: 'vec4' },
  27073. { name: 'end', type: 'vec4' }
  27074. ]
  27075. } );
  27076. this.vertexNode = Fn( () => {
  27077. const instanceStart = attribute( 'instanceStart' );
  27078. const instanceEnd = attribute( 'instanceEnd' );
  27079. // camera space
  27080. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  27081. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  27082. if ( useWorldUnits ) {
  27083. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  27084. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  27085. }
  27086. const aspect = viewport.z.div( viewport.w );
  27087. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  27088. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  27089. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  27090. // perhaps there is a more elegant solution -- WestLangley
  27091. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  27092. If( perspective, () => {
  27093. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  27094. end.assign( trimSegment( { start: start, end: end } ) );
  27095. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  27096. start.assign( trimSegment( { start: end, end: start } ) );
  27097. } );
  27098. } );
  27099. // clip space
  27100. const clipStart = cameraProjectionMatrix.mul( start );
  27101. const clipEnd = cameraProjectionMatrix.mul( end );
  27102. // ndc space
  27103. const ndcStart = clipStart.xyz.div( clipStart.w );
  27104. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  27105. // direction
  27106. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  27107. // account for clip-space aspect ratio
  27108. dir.x.assign( dir.x.mul( aspect ) );
  27109. dir.assign( dir.normalize() );
  27110. const clip = vec4().toVar();
  27111. if ( useWorldUnits ) {
  27112. // get the offset direction as perpendicular to the view vector
  27113. const worldDir = end.xyz.sub( start.xyz ).normalize();
  27114. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  27115. const worldUp = worldDir.cross( tmpFwd ).normalize();
  27116. const worldFwd = worldDir.cross( worldUp );
  27117. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  27118. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  27119. // height offset
  27120. const hw = materialLineWidth.mul( 0.5 );
  27121. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  27122. // don't extend the line if we're rendering dashes because we
  27123. // won't be rendering the endcaps
  27124. if ( ! useDash ) {
  27125. // cap extension
  27126. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  27127. // add width to the box
  27128. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  27129. // endcaps
  27130. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  27131. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  27132. } );
  27133. }
  27134. // project the worldpos
  27135. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  27136. // shift the depth of the projected points so the line
  27137. // segments overlap neatly
  27138. const clipPose = vec3().toVar();
  27139. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  27140. clip.z.assign( clipPose.z.mul( clip.w ) );
  27141. } else {
  27142. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  27143. // undo aspect ratio adjustment
  27144. dir.x.assign( dir.x.div( aspect ) );
  27145. offset.x.assign( offset.x.div( aspect ) );
  27146. // sign flip
  27147. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  27148. // endcaps
  27149. If( positionGeometry.y.lessThan( 0.0 ), () => {
  27150. offset.assign( offset.sub( dir ) );
  27151. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  27152. offset.assign( offset.add( dir ) );
  27153. } );
  27154. // adjust for linewidth
  27155. offset.assign( offset.mul( materialLineWidth ) );
  27156. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  27157. offset.assign( offset.div( viewport.w ) );
  27158. // select end
  27159. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  27160. // back to clip space
  27161. offset.assign( offset.mul( clip.w ) );
  27162. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  27163. }
  27164. return clip;
  27165. } )();
  27166. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  27167. const p13 = p1.sub( p3 );
  27168. const p43 = p4.sub( p3 );
  27169. const p21 = p2.sub( p1 );
  27170. const d1343 = p13.dot( p43 );
  27171. const d4321 = p43.dot( p21 );
  27172. const d1321 = p13.dot( p21 );
  27173. const d4343 = p43.dot( p43 );
  27174. const d2121 = p21.dot( p21 );
  27175. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  27176. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  27177. const mua = numer.div( denom ).clamp();
  27178. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  27179. return vec2( mua, mub );
  27180. } );
  27181. this.fragmentNode = Fn( () => {
  27182. const vUv = uv();
  27183. if ( useDash ) {
  27184. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  27185. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  27186. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  27187. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  27188. dashSize.assign( dashSizeNode );
  27189. gapSize.assign( gapSizeNode );
  27190. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  27191. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  27192. const lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  27193. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  27194. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  27195. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  27196. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  27197. }
  27198. const alpha = float( 1 ).toVar( 'alpha' );
  27199. if ( useWorldUnits ) {
  27200. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  27201. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  27202. // Find the closest points on the view ray and the line segment
  27203. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  27204. const lineDir = worldEnd.sub( worldStart );
  27205. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  27206. const p1 = worldStart.add( lineDir.mul( params.x ) );
  27207. const p2 = rayEnd.mul( params.y );
  27208. const delta = p1.sub( p2 );
  27209. const len = delta.length();
  27210. const norm = len.div( materialLineWidth );
  27211. if ( ! useDash ) {
  27212. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  27213. const dnorm = norm.fwidth();
  27214. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  27215. } else {
  27216. norm.greaterThan( 0.5 ).discard();
  27217. }
  27218. }
  27219. } else {
  27220. // round endcaps
  27221. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  27222. const a = vUv.x;
  27223. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  27224. const len2 = a.mul( a ).add( b.mul( b ) );
  27225. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  27226. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  27227. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  27228. } );
  27229. } else {
  27230. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  27231. const a = vUv.x;
  27232. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  27233. const len2 = a.mul( a ).add( b.mul( b ) );
  27234. len2.greaterThan( 1.0 ).discard();
  27235. } );
  27236. }
  27237. }
  27238. let lineColorNode;
  27239. if ( this.lineColorNode ) {
  27240. lineColorNode = this.lineColorNode;
  27241. } else {
  27242. if ( useColor ) {
  27243. const instanceColorStart = attribute( 'instanceColorStart' );
  27244. const instanceColorEnd = attribute( 'instanceColorEnd' );
  27245. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  27246. lineColorNode = instanceColor.mul( materialColor );
  27247. } else {
  27248. lineColorNode = materialColor;
  27249. }
  27250. }
  27251. return vec4( lineColorNode, alpha );
  27252. } )();
  27253. }
  27254. get worldUnits() {
  27255. return this.useWorldUnits;
  27256. }
  27257. set worldUnits( value ) {
  27258. if ( this.useWorldUnits !== value ) {
  27259. this.useWorldUnits = value;
  27260. this.needsUpdate = true;
  27261. }
  27262. }
  27263. get dashed() {
  27264. return this.useDash;
  27265. }
  27266. set dashed( value ) {
  27267. if ( this.useDash !== value ) {
  27268. this.useDash = value;
  27269. this.needsUpdate = true;
  27270. }
  27271. }
  27272. get alphaToCoverage() {
  27273. return this.useAlphaToCoverage;
  27274. }
  27275. set alphaToCoverage( value ) {
  27276. if ( this.useAlphaToCoverage !== value ) {
  27277. this.useAlphaToCoverage = value;
  27278. this.needsUpdate = true;
  27279. }
  27280. }
  27281. }
  27282. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  27283. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  27284. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  27285. class MeshNormalNodeMaterial extends NodeMaterial {
  27286. static get type() {
  27287. return 'MeshNormalNodeMaterial';
  27288. }
  27289. constructor( parameters ) {
  27290. super();
  27291. this.lights = false;
  27292. this.isMeshNormalNodeMaterial = true;
  27293. this.setDefaultValues( _defaultValues$a );
  27294. this.setValues( parameters );
  27295. }
  27296. setupDiffuseColor() {
  27297. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  27298. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  27299. }
  27300. }
  27301. class EquirectUVNode extends TempNode {
  27302. static get type() {
  27303. return 'EquirectUVNode';
  27304. }
  27305. constructor( dirNode = positionWorldDirection ) {
  27306. super( 'vec2' );
  27307. this.dirNode = dirNode;
  27308. }
  27309. setup() {
  27310. const dir = this.dirNode;
  27311. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  27312. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  27313. return vec2( u, v );
  27314. }
  27315. }
  27316. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  27317. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  27318. class CubeRenderTarget extends WebGLCubeRenderTarget {
  27319. constructor( size = 1, options = {} ) {
  27320. super( size, options );
  27321. this.isCubeRenderTarget = true;
  27322. }
  27323. fromEquirectangularTexture( renderer, texture$1 ) {
  27324. const currentMinFilter = texture$1.minFilter;
  27325. const currentGenerateMipmaps = texture$1.generateMipmaps;
  27326. texture$1.generateMipmaps = true;
  27327. this.texture.type = texture$1.type;
  27328. this.texture.colorSpace = texture$1.colorSpace;
  27329. this.texture.generateMipmaps = texture$1.generateMipmaps;
  27330. this.texture.minFilter = texture$1.minFilter;
  27331. this.texture.magFilter = texture$1.magFilter;
  27332. const geometry = new BoxGeometry( 5, 5, 5 );
  27333. const uvNode = equirectUV( positionWorldDirection );
  27334. const material = new NodeMaterial();
  27335. material.colorNode = texture( texture$1, uvNode, 0 );
  27336. material.side = BackSide;
  27337. material.blending = NoBlending;
  27338. const mesh = new Mesh( geometry, material );
  27339. const scene = new Scene();
  27340. scene.add( mesh );
  27341. // Avoid blurred poles
  27342. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  27343. const camera = new CubeCamera( 1, 10, this );
  27344. const currentMRT = renderer.getMRT();
  27345. renderer.setMRT( null );
  27346. camera.update( renderer, scene );
  27347. renderer.setMRT( currentMRT );
  27348. texture$1.minFilter = currentMinFilter;
  27349. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  27350. mesh.geometry.dispose();
  27351. mesh.material.dispose();
  27352. return this;
  27353. }
  27354. }
  27355. const _cache$1 = new WeakMap();
  27356. class CubeMapNode extends TempNode {
  27357. static get type() {
  27358. return 'CubeMapNode';
  27359. }
  27360. constructor( envNode ) {
  27361. super( 'vec3' );
  27362. this.envNode = envNode;
  27363. this._cubeTexture = null;
  27364. this._cubeTextureNode = cubeTexture();
  27365. const defaultTexture = new CubeTexture();
  27366. defaultTexture.isRenderTargetTexture = true;
  27367. this._defaultTexture = defaultTexture;
  27368. this.updateBeforeType = NodeUpdateType.RENDER;
  27369. }
  27370. updateBefore( frame ) {
  27371. const { renderer, material } = frame;
  27372. const envNode = this.envNode;
  27373. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  27374. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  27375. if ( texture && texture.isTexture ) {
  27376. const mapping = texture.mapping;
  27377. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  27378. // check for converted cubemap map
  27379. if ( _cache$1.has( texture ) ) {
  27380. const cubeMap = _cache$1.get( texture );
  27381. mapTextureMapping( cubeMap, texture.mapping );
  27382. this._cubeTexture = cubeMap;
  27383. } else {
  27384. // create cube map from equirectangular map
  27385. const image = texture.image;
  27386. if ( isEquirectangularMapReady$1( image ) ) {
  27387. const renderTarget = new CubeRenderTarget( image.height );
  27388. renderTarget.fromEquirectangularTexture( renderer, texture );
  27389. mapTextureMapping( renderTarget.texture, texture.mapping );
  27390. this._cubeTexture = renderTarget.texture;
  27391. _cache$1.set( texture, renderTarget.texture );
  27392. texture.addEventListener( 'dispose', onTextureDispose );
  27393. } else {
  27394. // default cube texture as fallback when equirectangular texture is not yet loaded
  27395. this._cubeTexture = this._defaultTexture;
  27396. }
  27397. }
  27398. //
  27399. this._cubeTextureNode.value = this._cubeTexture;
  27400. } else {
  27401. // envNode already refers to a cube map
  27402. this._cubeTextureNode = this.envNode;
  27403. }
  27404. }
  27405. }
  27406. }
  27407. setup( builder ) {
  27408. this.updateBefore( builder );
  27409. return this._cubeTextureNode;
  27410. }
  27411. }
  27412. function isEquirectangularMapReady$1( image ) {
  27413. if ( image === null || image === undefined ) return false;
  27414. return image.height > 0;
  27415. }
  27416. function onTextureDispose( event ) {
  27417. const texture = event.target;
  27418. texture.removeEventListener( 'dispose', onTextureDispose );
  27419. const renderTarget = _cache$1.get( texture );
  27420. if ( renderTarget !== undefined ) {
  27421. _cache$1.delete( texture );
  27422. renderTarget.dispose();
  27423. }
  27424. }
  27425. function mapTextureMapping( texture, mapping ) {
  27426. if ( mapping === EquirectangularReflectionMapping ) {
  27427. texture.mapping = CubeReflectionMapping;
  27428. } else if ( mapping === EquirectangularRefractionMapping ) {
  27429. texture.mapping = CubeRefractionMapping;
  27430. }
  27431. }
  27432. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  27433. class BasicEnvironmentNode extends LightingNode {
  27434. static get type() {
  27435. return 'BasicEnvironmentNode';
  27436. }
  27437. constructor( envNode = null ) {
  27438. super();
  27439. this.envNode = envNode;
  27440. }
  27441. setup( builder ) {
  27442. // environment property is used in the finish() method of BasicLightingModel
  27443. builder.context.environment = cubeMapNode( this.envNode );
  27444. }
  27445. }
  27446. class BasicLightMapNode extends LightingNode {
  27447. static get type() {
  27448. return 'BasicLightMapNode';
  27449. }
  27450. constructor( lightMapNode = null ) {
  27451. super();
  27452. this.lightMapNode = lightMapNode;
  27453. }
  27454. setup( builder ) {
  27455. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  27456. const RECIPROCAL_PI = float( 1 / Math.PI );
  27457. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  27458. }
  27459. }
  27460. class LightingModel {
  27461. start( /*input, stack, builder*/ ) { }
  27462. finish( /*input, stack, builder*/ ) { }
  27463. direct( /*input, stack, builder*/ ) { }
  27464. directRectArea( /*input, stack, builder*/ ) {}
  27465. indirect( /*input, stack, builder*/ ) { }
  27466. ambientOcclusion( /*input, stack, builder*/ ) { }
  27467. }
  27468. class BasicLightingModel extends LightingModel {
  27469. constructor() {
  27470. super();
  27471. }
  27472. indirect( context, stack, builder ) {
  27473. const ambientOcclusion = context.ambientOcclusion;
  27474. const reflectedLight = context.reflectedLight;
  27475. const irradianceLightMap = builder.context.irradianceLightMap;
  27476. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  27477. // accumulation (baked indirect lighting only)
  27478. if ( irradianceLightMap ) {
  27479. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  27480. } else {
  27481. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  27482. }
  27483. // modulation
  27484. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27485. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  27486. }
  27487. finish( context, stack, builder ) {
  27488. const material = builder.material;
  27489. const outgoingLight = context.outgoingLight;
  27490. const envNode = builder.context.environment;
  27491. if ( envNode ) {
  27492. switch ( material.combine ) {
  27493. case MultiplyOperation:
  27494. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  27495. break;
  27496. case MixOperation:
  27497. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  27498. break;
  27499. case AddOperation:
  27500. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  27501. break;
  27502. default:
  27503. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  27504. break;
  27505. }
  27506. }
  27507. }
  27508. }
  27509. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  27510. class MeshBasicNodeMaterial extends NodeMaterial {
  27511. static get type() {
  27512. return 'MeshBasicNodeMaterial';
  27513. }
  27514. constructor( parameters ) {
  27515. super();
  27516. this.isMeshBasicNodeMaterial = true;
  27517. this.lights = true;
  27518. this.setDefaultValues( _defaultValues$9 );
  27519. this.setValues( parameters );
  27520. }
  27521. setupNormal() {
  27522. return normalView; // see #28839
  27523. }
  27524. setupEnvironment( builder ) {
  27525. const envNode = super.setupEnvironment( builder );
  27526. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27527. }
  27528. setupLightMap( builder ) {
  27529. let node = null;
  27530. if ( builder.material.lightMap ) {
  27531. node = new BasicLightMapNode( materialLightMap );
  27532. }
  27533. return node;
  27534. }
  27535. setupOutgoingLight() {
  27536. return diffuseColor.rgb;
  27537. }
  27538. setupLightingModel() {
  27539. return new BasicLightingModel();
  27540. }
  27541. }
  27542. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  27543. // Original approximation by Christophe Schlick '94
  27544. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  27545. // Optimized variant (presented by Epic at SIGGRAPH '13)
  27546. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  27547. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  27548. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  27549. } ); // validated
  27550. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  27551. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  27552. } ); // validated
  27553. const G_BlinnPhong_Implicit = () => float( 0.25 );
  27554. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  27555. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  27556. } );
  27557. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27558. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27559. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27560. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27561. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  27562. const G = G_BlinnPhong_Implicit();
  27563. const D = D_BlinnPhong( { dotNH } );
  27564. return F.mul( G ).mul( D );
  27565. } );
  27566. class PhongLightingModel extends BasicLightingModel {
  27567. constructor( specular = true ) {
  27568. super();
  27569. this.specular = specular;
  27570. }
  27571. direct( { lightDirection, lightColor, reflectedLight } ) {
  27572. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27573. const irradiance = dotNL.mul( lightColor );
  27574. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  27575. if ( this.specular === true ) {
  27576. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  27577. }
  27578. }
  27579. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  27580. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  27581. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27582. }
  27583. }
  27584. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  27585. class MeshLambertNodeMaterial extends NodeMaterial {
  27586. static get type() {
  27587. return 'MeshLambertNodeMaterial';
  27588. }
  27589. constructor( parameters ) {
  27590. super();
  27591. this.isMeshLambertNodeMaterial = true;
  27592. this.lights = true;
  27593. this.setDefaultValues( _defaultValues$8 );
  27594. this.setValues( parameters );
  27595. }
  27596. setupEnvironment( builder ) {
  27597. const envNode = super.setupEnvironment( builder );
  27598. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27599. }
  27600. setupLightingModel( /*builder*/ ) {
  27601. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  27602. }
  27603. }
  27604. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  27605. class MeshPhongNodeMaterial extends NodeMaterial {
  27606. static get type() {
  27607. return 'MeshPhongNodeMaterial';
  27608. }
  27609. constructor( parameters ) {
  27610. super();
  27611. this.isMeshPhongNodeMaterial = true;
  27612. this.lights = true;
  27613. this.shininessNode = null;
  27614. this.specularNode = null;
  27615. this.setDefaultValues( _defaultValues$7 );
  27616. this.setValues( parameters );
  27617. }
  27618. setupEnvironment( builder ) {
  27619. const envNode = super.setupEnvironment( builder );
  27620. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27621. }
  27622. setupLightingModel( /*builder*/ ) {
  27623. return new PhongLightingModel();
  27624. }
  27625. setupVariants() {
  27626. // SHININESS
  27627. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  27628. shininess.assign( shininessNode );
  27629. // SPECULAR COLOR
  27630. const specularNode = this.specularNode || materialSpecular;
  27631. specularColor.assign( specularNode );
  27632. }
  27633. copy( source ) {
  27634. this.shininessNode = source.shininessNode;
  27635. this.specularNode = source.specularNode;
  27636. return super.copy( source );
  27637. }
  27638. }
  27639. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  27640. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  27641. return float( 0 );
  27642. }
  27643. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  27644. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  27645. return geometryRoughness;
  27646. } );
  27647. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  27648. const { roughness } = inputs;
  27649. const geometryRoughness = getGeometryRoughness();
  27650. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  27651. roughnessFactor = roughnessFactor.add( geometryRoughness );
  27652. roughnessFactor = roughnessFactor.min( 1.0 );
  27653. return roughnessFactor;
  27654. } );
  27655. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  27656. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27657. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  27658. const a2 = alpha.pow2();
  27659. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  27660. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  27661. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  27662. } ).setLayout( {
  27663. name: 'V_GGX_SmithCorrelated',
  27664. type: 'float',
  27665. inputs: [
  27666. { name: 'alpha', type: 'float' },
  27667. { name: 'dotNL', type: 'float' },
  27668. { name: 'dotNV', type: 'float' }
  27669. ]
  27670. } ); // validated
  27671. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27672. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  27673. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  27674. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  27675. const v = div( 0.5, gv.add( gl ) );
  27676. return v.saturate();
  27677. } ).setLayout( {
  27678. name: 'V_GGX_SmithCorrelated_Anisotropic',
  27679. type: 'float',
  27680. inputs: [
  27681. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27682. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27683. { name: 'dotTV', type: 'float', qualifier: 'in' },
  27684. { name: 'dotBV', type: 'float', qualifier: 'in' },
  27685. { name: 'dotTL', type: 'float', qualifier: 'in' },
  27686. { name: 'dotBL', type: 'float', qualifier: 'in' },
  27687. { name: 'dotNV', type: 'float', qualifier: 'in' },
  27688. { name: 'dotNL', type: 'float', qualifier: 'in' }
  27689. ]
  27690. } );
  27691. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  27692. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  27693. // alpha is "roughness squared" in Disney’s reparameterization
  27694. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  27695. const a2 = alpha.pow2();
  27696. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  27697. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  27698. } ).setLayout( {
  27699. name: 'D_GGX',
  27700. type: 'float',
  27701. inputs: [
  27702. { name: 'alpha', type: 'float' },
  27703. { name: 'dotNH', type: 'float' }
  27704. ]
  27705. } ); // validated
  27706. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  27707. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27708. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  27709. const a2 = alphaT.mul( alphaB );
  27710. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  27711. const v2 = v.dot( v );
  27712. const w2 = a2.div( v2 );
  27713. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  27714. } ).setLayout( {
  27715. name: 'D_GGX_Anisotropic',
  27716. type: 'float',
  27717. inputs: [
  27718. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27719. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27720. { name: 'dotNH', type: 'float', qualifier: 'in' },
  27721. { name: 'dotTH', type: 'float', qualifier: 'in' },
  27722. { name: 'dotBH', type: 'float', qualifier: 'in' }
  27723. ]
  27724. } );
  27725. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  27726. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  27727. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  27728. const normalView = inputs.normalView || transformedNormalView;
  27729. const alpha = roughness.pow2(); // UE4's roughness
  27730. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27731. const dotNL = normalView.dot( lightDirection ).clamp();
  27732. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  27733. const dotNH = normalView.dot( halfDir ).clamp();
  27734. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27735. let F = F_Schlick( { f0, f90, dotVH } );
  27736. let V, D;
  27737. if ( defined( USE_IRIDESCENCE ) ) {
  27738. F = iridescence.mix( F, f );
  27739. }
  27740. if ( defined( USE_ANISOTROPY ) ) {
  27741. const dotTL = anisotropyT.dot( lightDirection );
  27742. const dotTV = anisotropyT.dot( positionViewDirection );
  27743. const dotTH = anisotropyT.dot( halfDir );
  27744. const dotBL = anisotropyB.dot( lightDirection );
  27745. const dotBV = anisotropyB.dot( positionViewDirection );
  27746. const dotBH = anisotropyB.dot( halfDir );
  27747. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  27748. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  27749. } else {
  27750. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  27751. D = D_GGX( { alpha, dotNH } );
  27752. }
  27753. return F.mul( V ).mul( D );
  27754. } ); // validated
  27755. // Analytical approximation of the DFG LUT, one half of the
  27756. // split-sum approximation used in indirect specular lighting.
  27757. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  27758. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  27759. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  27760. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  27761. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  27762. const r = roughness.mul( c0 ).add( c1 );
  27763. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  27764. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  27765. return fab;
  27766. } ).setLayout( {
  27767. name: 'DFGApprox',
  27768. type: 'vec2',
  27769. inputs: [
  27770. { name: 'roughness', type: 'float' },
  27771. { name: 'dotNV', type: 'vec3' }
  27772. ]
  27773. } );
  27774. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  27775. const { dotNV, specularColor, specularF90, roughness } = inputs;
  27776. const fab = DFGApprox( { dotNV, roughness } );
  27777. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  27778. } );
  27779. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  27780. const x = dotVH.oneMinus().saturate();
  27781. const x2 = x.mul( x );
  27782. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  27783. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  27784. } ).setLayout( {
  27785. name: 'Schlick_to_F0',
  27786. type: 'vec3',
  27787. inputs: [
  27788. { name: 'f', type: 'vec3' },
  27789. { name: 'f90', type: 'float' },
  27790. { name: 'dotVH', type: 'float' }
  27791. ]
  27792. } );
  27793. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27794. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  27795. const alpha = roughness.pow2();
  27796. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  27797. const invAlpha = float( 1.0 ).div( alpha );
  27798. const cos2h = dotNH.pow2();
  27799. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  27800. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  27801. } ).setLayout( {
  27802. name: 'D_Charlie',
  27803. type: 'float',
  27804. inputs: [
  27805. { name: 'roughness', type: 'float' },
  27806. { name: 'dotNH', type: 'float' }
  27807. ]
  27808. } );
  27809. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27810. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  27811. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  27812. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  27813. } ).setLayout( {
  27814. name: 'V_Neubelt',
  27815. type: 'float',
  27816. inputs: [
  27817. { name: 'dotNV', type: 'float' },
  27818. { name: 'dotNL', type: 'float' }
  27819. ]
  27820. } );
  27821. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27822. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27823. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27824. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  27825. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27826. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  27827. const V = V_Neubelt( { dotNV, dotNL } );
  27828. return sheen.mul( D ).mul( V );
  27829. } );
  27830. // Rect Area Light
  27831. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  27832. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  27833. // code: https://github.com/selfshadow/ltc_code/
  27834. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  27835. const LUT_SIZE = 64.0;
  27836. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  27837. const LUT_BIAS = 0.5 / LUT_SIZE;
  27838. const dotNV = N.dot( V ).saturate();
  27839. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  27840. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  27841. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  27842. return uv;
  27843. } ).setLayout( {
  27844. name: 'LTC_Uv',
  27845. type: 'vec2',
  27846. inputs: [
  27847. { name: 'N', type: 'vec3' },
  27848. { name: 'V', type: 'vec3' },
  27849. { name: 'roughness', type: 'float' }
  27850. ]
  27851. } );
  27852. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  27853. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  27854. // An approximation of the form factor of a horizon-clipped rectangle.
  27855. const l = f.length();
  27856. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  27857. } ).setLayout( {
  27858. name: 'LTC_ClippedSphereFormFactor',
  27859. type: 'float',
  27860. inputs: [
  27861. { name: 'f', type: 'vec3' }
  27862. ]
  27863. } );
  27864. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  27865. const x = v1.dot( v2 );
  27866. const y = x.abs().toVar();
  27867. // rational polynomial approximation to theta / sin( theta ) / 2PI
  27868. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  27869. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  27870. const v = a.div( b );
  27871. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  27872. return v1.cross( v2 ).mul( theta_sintheta );
  27873. } ).setLayout( {
  27874. name: 'LTC_EdgeVectorFormFactor',
  27875. type: 'vec3',
  27876. inputs: [
  27877. { name: 'v1', type: 'vec3' },
  27878. { name: 'v2', type: 'vec3' }
  27879. ]
  27880. } );
  27881. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  27882. // bail if point is on back side of plane of light
  27883. // assumes ccw winding order of light vertices
  27884. const v1 = p1.sub( p0 ).toVar();
  27885. const v2 = p3.sub( p0 ).toVar();
  27886. const lightNormal = v1.cross( v2 );
  27887. const result = vec3().toVar();
  27888. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  27889. // construct orthonormal basis around N
  27890. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  27891. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  27892. // compute transform
  27893. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  27894. // transform rect
  27895. // & project rect onto sphere
  27896. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  27897. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  27898. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  27899. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  27900. // calculate vector form factor
  27901. const vectorFormFactor = vec3( 0 ).toVar();
  27902. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  27903. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  27904. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  27905. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  27906. // adjust for horizon clipping
  27907. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  27908. } );
  27909. return result;
  27910. } ).setLayout( {
  27911. name: 'LTC_Evaluate',
  27912. type: 'vec3',
  27913. inputs: [
  27914. { name: 'N', type: 'vec3' },
  27915. { name: 'V', type: 'vec3' },
  27916. { name: 'P', type: 'vec3' },
  27917. { name: 'mInv', type: 'mat3' },
  27918. { name: 'p0', type: 'vec3' },
  27919. { name: 'p1', type: 'vec3' },
  27920. { name: 'p2', type: 'vec3' },
  27921. { name: 'p3', type: 'vec3' }
  27922. ]
  27923. } );
  27924. // Mipped Bicubic Texture Filtering by N8
  27925. // https://www.shadertoy.com/view/Dl2SDW
  27926. const bC = 1.0 / 6.0;
  27927. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  27928. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  27929. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  27930. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  27931. const g0 = ( a ) => w0( a ).add( w1( a ) );
  27932. const g1 = ( a ) => w2( a ).add( w3( a ) );
  27933. // h0 and h1 are the two offset functions
  27934. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  27935. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  27936. const bicubic = ( textureNode, texelSize, lod ) => {
  27937. const uv = textureNode.uvNode;
  27938. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  27939. const iuv = floor( uvScaled );
  27940. const fuv = fract( uvScaled );
  27941. const g0x = g0( fuv.x );
  27942. const g1x = g1( fuv.x );
  27943. const h0x = h0( fuv.x );
  27944. const h1x = h1( fuv.x );
  27945. const h0y = h0( fuv.y );
  27946. const h1y = h1( fuv.y );
  27947. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27948. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27949. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27950. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27951. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  27952. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  27953. return a.add( b );
  27954. };
  27955. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  27956. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  27957. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  27958. const fLodSizeInv = div( 1.0, fLodSize );
  27959. const cLodSizeInv = div( 1.0, cLodSize );
  27960. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  27961. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  27962. return fract( lodNode ).mix( fSample, cSample );
  27963. } );
  27964. //
  27965. // Transmission
  27966. //
  27967. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  27968. // Direction of refracted light.
  27969. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  27970. // Compute rotation-independant scaling of the model matrix.
  27971. const modelScale = vec3(
  27972. length( modelMatrix[ 0 ].xyz ),
  27973. length( modelMatrix[ 1 ].xyz ),
  27974. length( modelMatrix[ 2 ].xyz )
  27975. );
  27976. // The thickness is specified in local space.
  27977. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  27978. } ).setLayout( {
  27979. name: 'getVolumeTransmissionRay',
  27980. type: 'vec3',
  27981. inputs: [
  27982. { name: 'n', type: 'vec3' },
  27983. { name: 'v', type: 'vec3' },
  27984. { name: 'thickness', type: 'float' },
  27985. { name: 'ior', type: 'float' },
  27986. { name: 'modelMatrix', type: 'mat4' }
  27987. ]
  27988. } );
  27989. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  27990. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  27991. // an IOR of 1.5 results in the default amount of microfacet refraction.
  27992. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  27993. } ).setLayout( {
  27994. name: 'applyIorToRoughness',
  27995. type: 'float',
  27996. inputs: [
  27997. { name: 'roughness', type: 'float' },
  27998. { name: 'ior', type: 'float' }
  27999. ]
  28000. } );
  28001. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  28002. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  28003. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  28004. const vTexture = material.side == BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  28005. const transmissionSample = vTexture.uv( fragCoord );
  28006. //const transmissionSample = viewportMipTexture( fragCoord );
  28007. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  28008. return textureBicubic( transmissionSample, lod );
  28009. } );
  28010. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  28011. If( attenuationDistance.notEqual( 0 ), () => {
  28012. // Compute light attenuation using Beer's law.
  28013. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  28014. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  28015. return transmittance;
  28016. } );
  28017. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  28018. return vec3( 1.0 );
  28019. } ).setLayout( {
  28020. name: 'volumeAttenuation',
  28021. type: 'vec3',
  28022. inputs: [
  28023. { name: 'transmissionDistance', type: 'float' },
  28024. { name: 'attenuationColor', type: 'vec3' },
  28025. { name: 'attenuationDistance', type: 'float' }
  28026. ]
  28027. } );
  28028. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  28029. let transmittedLight, transmittance;
  28030. if ( dispersion ) {
  28031. transmittedLight = vec4().toVar();
  28032. transmittance = vec3().toVar();
  28033. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  28034. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  28035. Loop( { start: 0, end: 3 }, ( { i } ) => {
  28036. const ior = iors.element( i );
  28037. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  28038. const refractedRayExit = position.add( transmissionRay );
  28039. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  28040. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  28041. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  28042. refractionCoords.addAssign( 1.0 );
  28043. refractionCoords.divAssign( 2.0 );
  28044. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  28045. // Sample framebuffer to get pixel the refracted ray hits.
  28046. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  28047. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  28048. transmittedLight.a.addAssign( transmissionSample.a );
  28049. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  28050. } );
  28051. transmittedLight.a.divAssign( 3.0 );
  28052. } else {
  28053. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  28054. const refractedRayExit = position.add( transmissionRay );
  28055. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  28056. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  28057. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  28058. refractionCoords.addAssign( 1.0 );
  28059. refractionCoords.divAssign( 2.0 );
  28060. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  28061. // Sample framebuffer to get pixel the refracted ray hits.
  28062. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  28063. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  28064. }
  28065. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  28066. const dotNV = n.dot( v ).clamp();
  28067. // Get the specular component.
  28068. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  28069. dotNV,
  28070. specularColor,
  28071. specularF90,
  28072. roughness
  28073. } ) );
  28074. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  28075. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  28076. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  28077. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  28078. } );
  28079. //
  28080. // Iridescence
  28081. //
  28082. // XYZ to linear-sRGB color space
  28083. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  28084. 3.2404542, - 0.9692660, 0.0556434,
  28085. - 1.5371385, 1.8760108, - 0.2040259,
  28086. - 0.4985314, 0.0415560, 1.0572252
  28087. );
  28088. // Assume air interface for top
  28089. // Note: We don't handle the case fresnel0 == 1
  28090. const Fresnel0ToIor = ( fresnel0 ) => {
  28091. const sqrtF0 = fresnel0.sqrt();
  28092. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  28093. };
  28094. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  28095. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  28096. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  28097. };
  28098. // Fresnel equations for dielectric/dielectric interfaces.
  28099. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  28100. // Evaluation XYZ sensitivity curves in Fourier space
  28101. const evalSensitivity = ( OPD, shift ) => {
  28102. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  28103. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  28104. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  28105. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  28106. 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() );
  28107. 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() );
  28108. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  28109. const rgb = XYZ_TO_REC709.mul( xyz );
  28110. return rgb;
  28111. };
  28112. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  28113. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  28114. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  28115. // Evaluate the cosTheta on the base layer (Snell law)
  28116. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  28117. // Handle TIR:
  28118. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  28119. If( cosTheta2Sq.lessThan( 0 ), () => {
  28120. return vec3( 1.0 );
  28121. } );
  28122. const cosTheta2 = cosTheta2Sq.sqrt();
  28123. // First interface
  28124. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  28125. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  28126. //const R21 = R12;
  28127. const T121 = R12.oneMinus();
  28128. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  28129. const phi21 = float( Math.PI ).sub( phi12 );
  28130. // Second interface
  28131. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  28132. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  28133. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  28134. const phi23 = vec3(
  28135. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  28136. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  28137. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  28138. );
  28139. // Phase shift
  28140. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  28141. const phi = vec3( phi21 ).add( phi23 );
  28142. // Compound terms
  28143. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  28144. const r123 = R123.sqrt();
  28145. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  28146. // Reflectance term for m = 0 (DC term amplitude)
  28147. const C0 = R12.add( Rs );
  28148. const I = C0.toVar();
  28149. // Reflectance term for m > 0 (pairs of diracs)
  28150. const Cm = Rs.sub( T121 ).toVar();
  28151. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  28152. Cm.mulAssign( r123 );
  28153. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  28154. I.addAssign( Cm.mul( Sm ) );
  28155. } );
  28156. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  28157. return I.max( vec3( 0.0 ) );
  28158. } ).setLayout( {
  28159. name: 'evalIridescence',
  28160. type: 'vec3',
  28161. inputs: [
  28162. { name: 'outsideIOR', type: 'float' },
  28163. { name: 'eta2', type: 'float' },
  28164. { name: 'cosTheta1', type: 'float' },
  28165. { name: 'thinFilmThickness', type: 'float' },
  28166. { name: 'baseF0', type: 'vec3' }
  28167. ]
  28168. } );
  28169. //
  28170. // Sheen
  28171. //
  28172. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  28173. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  28174. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  28175. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  28176. const dotNV = normal.dot( viewDir ).saturate();
  28177. const r2 = roughness.pow2();
  28178. const a = select(
  28179. roughness.lessThan( 0.25 ),
  28180. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  28181. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  28182. );
  28183. const b = select(
  28184. roughness.lessThan( 0.25 ),
  28185. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  28186. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  28187. );
  28188. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  28189. return DG.mul( 1.0 / Math.PI ).saturate();
  28190. } );
  28191. const clearcoatF0 = vec3( 0.04 );
  28192. const clearcoatF90 = float( 1 );
  28193. //
  28194. class PhysicalLightingModel extends LightingModel {
  28195. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  28196. super();
  28197. this.clearcoat = clearcoat;
  28198. this.sheen = sheen;
  28199. this.iridescence = iridescence;
  28200. this.anisotropy = anisotropy;
  28201. this.transmission = transmission;
  28202. this.dispersion = dispersion;
  28203. this.clearcoatRadiance = null;
  28204. this.clearcoatSpecularDirect = null;
  28205. this.clearcoatSpecularIndirect = null;
  28206. this.sheenSpecularDirect = null;
  28207. this.sheenSpecularIndirect = null;
  28208. this.iridescenceFresnel = null;
  28209. this.iridescenceF0 = null;
  28210. }
  28211. start( context ) {
  28212. if ( this.clearcoat === true ) {
  28213. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  28214. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  28215. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  28216. }
  28217. if ( this.sheen === true ) {
  28218. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  28219. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  28220. }
  28221. if ( this.iridescence === true ) {
  28222. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  28223. this.iridescenceFresnel = evalIridescence( {
  28224. outsideIOR: float( 1.0 ),
  28225. eta2: iridescenceIOR,
  28226. cosTheta1: dotNVi,
  28227. thinFilmThickness: iridescenceThickness,
  28228. baseF0: specularColor
  28229. } );
  28230. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  28231. }
  28232. if ( this.transmission === true ) {
  28233. const position = positionWorld;
  28234. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  28235. const n = transformedNormalWorld;
  28236. context.backdrop = getIBLVolumeRefraction(
  28237. n,
  28238. v,
  28239. roughness,
  28240. diffuseColor,
  28241. specularColor,
  28242. specularF90, // specularF90
  28243. position, // positionWorld
  28244. modelWorldMatrix, // modelMatrix
  28245. cameraViewMatrix, // viewMatrix
  28246. cameraProjectionMatrix, // projMatrix
  28247. ior,
  28248. thickness,
  28249. attenuationColor,
  28250. attenuationDistance,
  28251. this.dispersion ? dispersion : null
  28252. );
  28253. context.backdropAlpha = transmission;
  28254. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  28255. }
  28256. }
  28257. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  28258. // Approximates multiscattering in order to preserve energy.
  28259. // http://www.jcgt.org/published/0008/01/03/
  28260. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  28261. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  28262. const fab = DFGApprox( { roughness, dotNV } );
  28263. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  28264. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  28265. const Ess = fab.x.add( fab.y );
  28266. const Ems = Ess.oneMinus();
  28267. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  28268. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  28269. singleScatter.addAssign( FssEss );
  28270. multiScatter.addAssign( Fms.mul( Ems ) );
  28271. }
  28272. direct( { lightDirection, lightColor, reflectedLight } ) {
  28273. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  28274. const irradiance = dotNL.mul( lightColor );
  28275. if ( this.sheen === true ) {
  28276. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  28277. }
  28278. if ( this.clearcoat === true ) {
  28279. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  28280. const ccIrradiance = dotNLcc.mul( lightColor );
  28281. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  28282. }
  28283. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  28284. 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 } ) ) );
  28285. }
  28286. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  28287. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  28288. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  28289. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  28290. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  28291. const N = transformedNormalView;
  28292. const V = positionViewDirection;
  28293. const P = positionView.toVar();
  28294. const uv = LTC_Uv( { N, V, roughness } );
  28295. const t1 = ltc_1.uv( uv ).toVar();
  28296. const t2 = ltc_2.uv( uv ).toVar();
  28297. const mInv = mat3(
  28298. vec3( t1.x, 0, t1.y ),
  28299. vec3( 0, 1, 0 ),
  28300. vec3( t1.z, 0, t1.w )
  28301. ).toVar();
  28302. // LTC Fresnel Approximation by Stephen Hill
  28303. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  28304. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  28305. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  28306. 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 } ) ) );
  28307. }
  28308. indirect( context, stack, builder ) {
  28309. this.indirectDiffuse( context, stack, builder );
  28310. this.indirectSpecular( context, stack, builder );
  28311. this.ambientOcclusion( context, stack, builder );
  28312. }
  28313. indirectDiffuse( { irradiance, reflectedLight } ) {
  28314. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  28315. }
  28316. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  28317. if ( this.sheen === true ) {
  28318. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  28319. sheen,
  28320. IBLSheenBRDF( {
  28321. normal: transformedNormalView,
  28322. viewDir: positionViewDirection,
  28323. roughness: sheenRoughness
  28324. } )
  28325. ) );
  28326. }
  28327. if ( this.clearcoat === true ) {
  28328. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  28329. const clearcoatEnv = EnvironmentBRDF( {
  28330. dotNV: dotNVcc,
  28331. specularColor: clearcoatF0,
  28332. specularF90: clearcoatF90,
  28333. roughness: clearcoatRoughness
  28334. } );
  28335. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  28336. }
  28337. // Both indirect specular and indirect diffuse light accumulate here
  28338. const singleScattering = vec3().toVar( 'singleScattering' );
  28339. const multiScattering = vec3().toVar( 'multiScattering' );
  28340. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  28341. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  28342. const totalScattering = singleScattering.add( multiScattering );
  28343. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  28344. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  28345. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  28346. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  28347. }
  28348. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  28349. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  28350. const aoNV = dotNV.add( ambientOcclusion );
  28351. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  28352. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  28353. if ( this.clearcoat === true ) {
  28354. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  28355. }
  28356. if ( this.sheen === true ) {
  28357. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  28358. }
  28359. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  28360. reflectedLight.indirectSpecular.mulAssign( aoNode );
  28361. }
  28362. finish( context ) {
  28363. const { outgoingLight } = context;
  28364. if ( this.clearcoat === true ) {
  28365. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  28366. const Fcc = F_Schlick( {
  28367. dotVH: dotNVcc,
  28368. f0: clearcoatF0,
  28369. f90: clearcoatF90
  28370. } );
  28371. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  28372. outgoingLight.assign( clearcoatLight );
  28373. }
  28374. if ( this.sheen === true ) {
  28375. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  28376. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  28377. outgoingLight.assign( sheenLight );
  28378. }
  28379. }
  28380. }
  28381. // These defines must match with PMREMGenerator
  28382. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  28383. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  28384. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  28385. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  28386. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  28387. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  28388. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  28389. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  28390. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  28391. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  28392. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  28393. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  28394. // These shader functions convert between the UV coordinates of a single face of
  28395. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  28396. // sampling a textureCube (not generally normalized ).
  28397. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  28398. const absDirection = vec3( abs( direction ) ).toVar();
  28399. const face = float( - 1.0 ).toVar();
  28400. If( absDirection.x.greaterThan( absDirection.z ), () => {
  28401. If( absDirection.x.greaterThan( absDirection.y ), () => {
  28402. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  28403. } ).Else( () => {
  28404. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28405. } );
  28406. } ).Else( () => {
  28407. If( absDirection.z.greaterThan( absDirection.y ), () => {
  28408. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  28409. } ).Else( () => {
  28410. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28411. } );
  28412. } );
  28413. return face;
  28414. } ).setLayout( {
  28415. name: 'getFace',
  28416. type: 'float',
  28417. inputs: [
  28418. { name: 'direction', type: 'vec3' }
  28419. ]
  28420. } );
  28421. // RH coordinate system; PMREM face-indexing convention
  28422. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  28423. const uv = vec2().toVar();
  28424. If( face.equal( 0.0 ), () => {
  28425. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  28426. } ).ElseIf( face.equal( 1.0 ), () => {
  28427. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  28428. } ).ElseIf( face.equal( 2.0 ), () => {
  28429. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  28430. } ).ElseIf( face.equal( 3.0 ), () => {
  28431. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  28432. } ).ElseIf( face.equal( 4.0 ), () => {
  28433. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  28434. } ).Else( () => {
  28435. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  28436. } );
  28437. return mul( 0.5, uv.add( 1.0 ) );
  28438. } ).setLayout( {
  28439. name: 'getUV',
  28440. type: 'vec2',
  28441. inputs: [
  28442. { name: 'direction', type: 'vec3' },
  28443. { name: 'face', type: 'float' }
  28444. ]
  28445. } );
  28446. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  28447. const mip = float( 0.0 ).toVar();
  28448. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  28449. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  28450. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  28451. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  28452. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  28453. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  28454. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  28455. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  28456. } ).Else( () => {
  28457. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  28458. } );
  28459. return mip;
  28460. } ).setLayout( {
  28461. name: 'roughnessToMip',
  28462. type: 'float',
  28463. inputs: [
  28464. { name: 'roughness', type: 'float' }
  28465. ]
  28466. } );
  28467. // RH coordinate system; PMREM face-indexing convention
  28468. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  28469. const uv = uv_immutable.toVar();
  28470. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  28471. const direction = vec3( uv, 1.0 ).toVar();
  28472. If( face.equal( 0.0 ), () => {
  28473. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  28474. } ).ElseIf( face.equal( 1.0 ), () => {
  28475. direction.assign( direction.xzy );
  28476. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  28477. } ).ElseIf( face.equal( 2.0 ), () => {
  28478. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  28479. } ).ElseIf( face.equal( 3.0 ), () => {
  28480. direction.assign( direction.zyx );
  28481. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  28482. } ).ElseIf( face.equal( 4.0 ), () => {
  28483. direction.assign( direction.xzy );
  28484. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  28485. } ).ElseIf( face.equal( 5.0 ), () => {
  28486. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  28487. } );
  28488. return direction;
  28489. } ).setLayout( {
  28490. name: 'getDirection',
  28491. type: 'vec3',
  28492. inputs: [
  28493. { name: 'uv', type: 'vec2' },
  28494. { name: 'face', type: 'float' }
  28495. ]
  28496. } );
  28497. //
  28498. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28499. const roughness = float( roughness_immutable );
  28500. const sampleDir = vec3( sampleDir_immutable );
  28501. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  28502. const mipF = fract( mip );
  28503. const mipInt = floor( mip );
  28504. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28505. If( mipF.notEqual( 0.0 ), () => {
  28506. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28507. color0.assign( mix( color0, color1, mipF ) );
  28508. } );
  28509. return color0;
  28510. } );
  28511. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28512. const mipInt = float( mipInt_immutable ).toVar();
  28513. const direction = vec3( direction_immutable );
  28514. const face = float( getFace( direction ) ).toVar();
  28515. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  28516. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  28517. const faceSize = float( exp2( mipInt ) ).toVar();
  28518. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  28519. If( face.greaterThan( 2.0 ), () => {
  28520. uv.y.addAssign( faceSize );
  28521. face.subAssign( 3.0 );
  28522. } );
  28523. uv.x.addAssign( face.mul( faceSize ) );
  28524. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  28525. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  28526. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  28527. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  28528. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  28529. } );
  28530. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28531. const cosTheta = cos( theta );
  28532. // Rodrigues' axis-angle rotation
  28533. const sampleDirection = outputDirection.mul( cosTheta )
  28534. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  28535. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  28536. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  28537. } );
  28538. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28539. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  28540. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  28541. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  28542. } );
  28543. axis.assign( normalize( axis ) );
  28544. const gl_FragColor = vec3().toVar();
  28545. 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 } ) ) );
  28546. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  28547. If( i.greaterThanEqual( samples ), () => {
  28548. Break();
  28549. } );
  28550. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  28551. 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 } ) ) );
  28552. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  28553. } );
  28554. return vec4( gl_FragColor, 1 );
  28555. } );
  28556. let _generator = null;
  28557. const _cache = new WeakMap();
  28558. function _generateCubeUVSize( imageHeight ) {
  28559. const maxMip = Math.log2( imageHeight ) - 2;
  28560. const texelHeight = 1.0 / imageHeight;
  28561. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  28562. return { texelWidth, texelHeight, maxMip };
  28563. }
  28564. function _getPMREMFromTexture( texture ) {
  28565. let cacheTexture = _cache.get( texture );
  28566. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  28567. if ( pmremVersion !== texture.pmremVersion ) {
  28568. const image = texture.image;
  28569. if ( texture.isCubeTexture ) {
  28570. if ( isCubeMapReady( image ) ) {
  28571. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  28572. } else {
  28573. return null;
  28574. }
  28575. } else {
  28576. if ( isEquirectangularMapReady( image ) ) {
  28577. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  28578. } else {
  28579. return null;
  28580. }
  28581. }
  28582. cacheTexture.pmremVersion = texture.pmremVersion;
  28583. _cache.set( texture, cacheTexture );
  28584. }
  28585. return cacheTexture.texture;
  28586. }
  28587. class PMREMNode extends TempNode {
  28588. static get type() {
  28589. return 'PMREMNode';
  28590. }
  28591. constructor( value, uvNode = null, levelNode = null ) {
  28592. super( 'vec3' );
  28593. this._value = value;
  28594. this._pmrem = null;
  28595. this.uvNode = uvNode;
  28596. this.levelNode = levelNode;
  28597. this._generator = null;
  28598. const defaultTexture = new Texture();
  28599. defaultTexture.isRenderTargetTexture = true;
  28600. this._texture = texture( defaultTexture );
  28601. this._width = uniform( 0 );
  28602. this._height = uniform( 0 );
  28603. this._maxMip = uniform( 0 );
  28604. this.updateBeforeType = NodeUpdateType.RENDER;
  28605. }
  28606. set value( value ) {
  28607. this._value = value;
  28608. this._pmrem = null;
  28609. }
  28610. get value() {
  28611. return this._value;
  28612. }
  28613. updateFromTexture( texture ) {
  28614. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  28615. this._texture.value = texture;
  28616. this._width.value = cubeUVSize.texelWidth;
  28617. this._height.value = cubeUVSize.texelHeight;
  28618. this._maxMip.value = cubeUVSize.maxMip;
  28619. }
  28620. updateBefore() {
  28621. let pmrem = this._pmrem;
  28622. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  28623. const texture = this._value;
  28624. if ( pmremVersion !== texture.pmremVersion ) {
  28625. if ( texture.isPMREMTexture === true ) {
  28626. pmrem = texture;
  28627. } else {
  28628. pmrem = _getPMREMFromTexture( texture );
  28629. }
  28630. if ( pmrem !== null ) {
  28631. this._pmrem = pmrem;
  28632. this.updateFromTexture( pmrem );
  28633. }
  28634. }
  28635. }
  28636. setup( builder ) {
  28637. if ( _generator === null ) {
  28638. _generator = builder.createPMREMGenerator();
  28639. }
  28640. //
  28641. this.updateBefore( builder );
  28642. //
  28643. let uvNode = this.uvNode;
  28644. if ( uvNode === null && builder.context.getUV ) {
  28645. uvNode = builder.context.getUV( this );
  28646. }
  28647. //
  28648. const texture = this.value;
  28649. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  28650. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  28651. }
  28652. //
  28653. let levelNode = this.levelNode;
  28654. if ( levelNode === null && builder.context.getTextureLevel ) {
  28655. levelNode = builder.context.getTextureLevel( this );
  28656. }
  28657. //
  28658. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  28659. }
  28660. }
  28661. function isCubeMapReady( image ) {
  28662. if ( image === null || image === undefined ) return false;
  28663. let count = 0;
  28664. const length = 6;
  28665. for ( let i = 0; i < length; i ++ ) {
  28666. if ( image[ i ] !== undefined ) count ++;
  28667. }
  28668. return count === length;
  28669. }
  28670. function isEquirectangularMapReady( image ) {
  28671. if ( image === null || image === undefined ) return false;
  28672. return image.height > 0;
  28673. }
  28674. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  28675. const _envNodeCache = new WeakMap();
  28676. class EnvironmentNode extends LightingNode {
  28677. static get type() {
  28678. return 'EnvironmentNode';
  28679. }
  28680. constructor( envNode = null ) {
  28681. super();
  28682. this.envNode = envNode;
  28683. }
  28684. setup( builder ) {
  28685. const { material } = builder;
  28686. let envNode = this.envNode;
  28687. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  28688. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  28689. let cacheEnvNode = _envNodeCache.get( value );
  28690. if ( cacheEnvNode === undefined ) {
  28691. cacheEnvNode = pmremTexture( value );
  28692. _envNodeCache.set( value, cacheEnvNode );
  28693. }
  28694. envNode = cacheEnvNode;
  28695. }
  28696. //
  28697. const envMap = material.envMap;
  28698. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  28699. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  28700. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  28701. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  28702. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  28703. const isolateRadiance = cache( radiance );
  28704. const isolateIrradiance = cache( irradiance );
  28705. //
  28706. builder.context.radiance.addAssign( isolateRadiance );
  28707. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  28708. //
  28709. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  28710. if ( clearcoatRadiance ) {
  28711. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  28712. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  28713. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  28714. }
  28715. }
  28716. }
  28717. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  28718. let reflectVec = null;
  28719. return {
  28720. getUV: () => {
  28721. if ( reflectVec === null ) {
  28722. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  28723. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  28724. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  28725. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  28726. }
  28727. return reflectVec;
  28728. },
  28729. getTextureLevel: () => {
  28730. return roughnessNode;
  28731. }
  28732. };
  28733. };
  28734. const createIrradianceContext = ( normalWorldNode ) => {
  28735. return {
  28736. getUV: () => {
  28737. return normalWorldNode;
  28738. },
  28739. getTextureLevel: () => {
  28740. return float( 1.0 );
  28741. }
  28742. };
  28743. };
  28744. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  28745. class MeshStandardNodeMaterial extends NodeMaterial {
  28746. static get type() {
  28747. return 'MeshStandardNodeMaterial';
  28748. }
  28749. constructor( parameters ) {
  28750. super();
  28751. this.isMeshStandardNodeMaterial = true;
  28752. this.lights = true;
  28753. this.emissiveNode = null;
  28754. this.metalnessNode = null;
  28755. this.roughnessNode = null;
  28756. this.setDefaultValues( _defaultValues$6 );
  28757. this.setValues( parameters );
  28758. }
  28759. setupEnvironment( builder ) {
  28760. let envNode = super.setupEnvironment( builder );
  28761. if ( envNode === null && builder.environmentNode ) {
  28762. envNode = builder.environmentNode;
  28763. }
  28764. return envNode ? new EnvironmentNode( envNode ) : null;
  28765. }
  28766. setupLightingModel( /*builder*/ ) {
  28767. return new PhysicalLightingModel();
  28768. }
  28769. setupSpecular() {
  28770. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  28771. specularColor.assign( specularColorNode );
  28772. specularF90.assign( 1.0 );
  28773. }
  28774. setupVariants() {
  28775. // METALNESS
  28776. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  28777. metalness.assign( metalnessNode );
  28778. // ROUGHNESS
  28779. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  28780. roughnessNode = getRoughness( { roughness: roughnessNode } );
  28781. roughness.assign( roughnessNode );
  28782. // SPECULAR COLOR
  28783. this.setupSpecular();
  28784. // DIFFUSE COLOR
  28785. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  28786. }
  28787. copy( source ) {
  28788. this.emissiveNode = source.emissiveNode;
  28789. this.metalnessNode = source.metalnessNode;
  28790. this.roughnessNode = source.roughnessNode;
  28791. return super.copy( source );
  28792. }
  28793. }
  28794. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  28795. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  28796. static get type() {
  28797. return 'MeshPhysicalNodeMaterial';
  28798. }
  28799. constructor( parameters ) {
  28800. super();
  28801. this.isMeshPhysicalNodeMaterial = true;
  28802. this.clearcoatNode = null;
  28803. this.clearcoatRoughnessNode = null;
  28804. this.clearcoatNormalNode = null;
  28805. this.sheenNode = null;
  28806. this.sheenRoughnessNode = null;
  28807. this.iridescenceNode = null;
  28808. this.iridescenceIORNode = null;
  28809. this.iridescenceThicknessNode = null;
  28810. this.specularIntensityNode = null;
  28811. this.specularColorNode = null;
  28812. this.iorNode = null;
  28813. this.transmissionNode = null;
  28814. this.thicknessNode = null;
  28815. this.attenuationDistanceNode = null;
  28816. this.attenuationColorNode = null;
  28817. this.dispersionNode = null;
  28818. this.anisotropyNode = null;
  28819. this.setDefaultValues( _defaultValues$5 );
  28820. this.setValues( parameters );
  28821. }
  28822. get useClearcoat() {
  28823. return this.clearcoat > 0 || this.clearcoatNode !== null;
  28824. }
  28825. get useIridescence() {
  28826. return this.iridescence > 0 || this.iridescenceNode !== null;
  28827. }
  28828. get useSheen() {
  28829. return this.sheen > 0 || this.sheenNode !== null;
  28830. }
  28831. get useAnisotropy() {
  28832. return this.anisotropy > 0 || this.anisotropyNode !== null;
  28833. }
  28834. get useTransmission() {
  28835. return this.transmission > 0 || this.transmissionNode !== null;
  28836. }
  28837. get useDispersion() {
  28838. return this.dispersion > 0 || this.dispersionNode !== null;
  28839. }
  28840. setupSpecular() {
  28841. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  28842. ior.assign( iorNode );
  28843. 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 ) );
  28844. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  28845. }
  28846. setupLightingModel( /*builder*/ ) {
  28847. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  28848. }
  28849. setupVariants( builder ) {
  28850. super.setupVariants( builder );
  28851. // CLEARCOAT
  28852. if ( this.useClearcoat ) {
  28853. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  28854. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  28855. clearcoat.assign( clearcoatNode );
  28856. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  28857. }
  28858. // SHEEN
  28859. if ( this.useSheen ) {
  28860. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  28861. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  28862. sheen.assign( sheenNode );
  28863. sheenRoughness.assign( sheenRoughnessNode );
  28864. }
  28865. // IRIDESCENCE
  28866. if ( this.useIridescence ) {
  28867. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  28868. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  28869. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  28870. iridescence.assign( iridescenceNode );
  28871. iridescenceIOR.assign( iridescenceIORNode );
  28872. iridescenceThickness.assign( iridescenceThicknessNode );
  28873. }
  28874. // ANISOTROPY
  28875. if ( this.useAnisotropy ) {
  28876. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  28877. anisotropy.assign( anisotropyV.length() );
  28878. If( anisotropy.equal( 0.0 ), () => {
  28879. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  28880. } ).Else( () => {
  28881. anisotropyV.divAssign( vec2( anisotropy ) );
  28882. anisotropy.assign( anisotropy.saturate() );
  28883. } );
  28884. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  28885. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  28886. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  28887. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  28888. }
  28889. // TRANSMISSION
  28890. if ( this.useTransmission ) {
  28891. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  28892. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  28893. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  28894. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  28895. transmission.assign( transmissionNode );
  28896. thickness.assign( thicknessNode );
  28897. attenuationDistance.assign( attenuationDistanceNode );
  28898. attenuationColor.assign( attenuationColorNode );
  28899. if ( this.useDispersion ) {
  28900. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  28901. dispersion.assign( dispersionNode );
  28902. }
  28903. }
  28904. }
  28905. setupClearcoatNormal() {
  28906. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  28907. }
  28908. setup( builder ) {
  28909. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  28910. super.setup( builder );
  28911. }
  28912. copy( source ) {
  28913. this.clearcoatNode = source.clearcoatNode;
  28914. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  28915. this.clearcoatNormalNode = source.clearcoatNormalNode;
  28916. this.sheenNode = source.sheenNode;
  28917. this.sheenRoughnessNode = source.sheenRoughnessNode;
  28918. this.iridescenceNode = source.iridescenceNode;
  28919. this.iridescenceIORNode = source.iridescenceIORNode;
  28920. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  28921. this.specularIntensityNode = source.specularIntensityNode;
  28922. this.specularColorNode = source.specularColorNode;
  28923. this.transmissionNode = source.transmissionNode;
  28924. this.thicknessNode = source.thicknessNode;
  28925. this.attenuationDistanceNode = source.attenuationDistanceNode;
  28926. this.attenuationColorNode = source.attenuationColorNode;
  28927. this.dispersionNode = source.dispersionNode;
  28928. this.anisotropyNode = source.anisotropyNode;
  28929. return super.copy( source );
  28930. }
  28931. }
  28932. class SSSLightingModel extends PhysicalLightingModel {
  28933. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  28934. super( useClearcoat, useSheen, useIridescence );
  28935. this.useSSS = useSSS;
  28936. }
  28937. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28938. if ( this.useSSS === true ) {
  28939. const material = builder.material;
  28940. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  28941. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  28942. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  28943. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  28944. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  28945. }
  28946. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  28947. }
  28948. }
  28949. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  28950. static get type() {
  28951. return 'MeshSSSNodeMaterial';
  28952. }
  28953. constructor( parameters ) {
  28954. super( parameters );
  28955. this.thicknessColorNode = null;
  28956. this.thicknessDistortionNode = float( 0.1 );
  28957. this.thicknessAmbientNode = float( 0.0 );
  28958. this.thicknessAttenuationNode = float( .1 );
  28959. this.thicknessPowerNode = float( 2.0 );
  28960. this.thicknessScaleNode = float( 10.0 );
  28961. }
  28962. get useSSS() {
  28963. return this.thicknessColorNode !== null;
  28964. }
  28965. setupLightingModel( /*builder*/ ) {
  28966. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  28967. }
  28968. copy( source ) {
  28969. this.thicknessColorNode = source.thicknessColorNode;
  28970. this.thicknessDistortionNode = source.thicknessDistortionNode;
  28971. this.thicknessAmbientNode = source.thicknessAmbientNode;
  28972. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  28973. this.thicknessPowerNode = source.thicknessPowerNode;
  28974. this.thicknessScaleNode = source.thicknessScaleNode;
  28975. return super.copy( source );
  28976. }
  28977. }
  28978. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  28979. // dotNL will be from -1.0 to 1.0
  28980. const dotNL = normal.dot( lightDirection );
  28981. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  28982. if ( builder.material.gradientMap ) {
  28983. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  28984. return vec3( gradientMap.r );
  28985. } else {
  28986. const fw = coord.fwidth().mul( 0.5 );
  28987. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  28988. }
  28989. } );
  28990. class ToonLightingModel extends LightingModel {
  28991. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28992. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  28993. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  28994. }
  28995. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  28996. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  28997. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  28998. }
  28999. }
  29000. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  29001. class MeshToonNodeMaterial extends NodeMaterial {
  29002. static get type() {
  29003. return 'MeshToonNodeMaterial';
  29004. }
  29005. constructor( parameters ) {
  29006. super();
  29007. this.isMeshToonNodeMaterial = true;
  29008. this.lights = true;
  29009. this.setDefaultValues( _defaultValues$4 );
  29010. this.setValues( parameters );
  29011. }
  29012. setupLightingModel( /*builder*/ ) {
  29013. return new ToonLightingModel();
  29014. }
  29015. }
  29016. class MatcapUVNode extends TempNode {
  29017. static get type() {
  29018. return 'MatcapUVNode';
  29019. }
  29020. constructor() {
  29021. super( 'vec2' );
  29022. }
  29023. setup() {
  29024. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  29025. const y = positionViewDirection.cross( x );
  29026. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  29027. }
  29028. }
  29029. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  29030. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  29031. class MeshMatcapNodeMaterial extends NodeMaterial {
  29032. static get type() {
  29033. return 'MeshMatcapNodeMaterial';
  29034. }
  29035. constructor( parameters ) {
  29036. super();
  29037. this.lights = false;
  29038. this.isMeshMatcapNodeMaterial = true;
  29039. this.setDefaultValues( _defaultValues$3 );
  29040. this.setValues( parameters );
  29041. }
  29042. setupVariants( builder ) {
  29043. const uv = matcapUV;
  29044. let matcapColor;
  29045. if ( builder.material.matcap ) {
  29046. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  29047. } else {
  29048. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  29049. }
  29050. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  29051. }
  29052. }
  29053. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  29054. class PointsNodeMaterial extends NodeMaterial {
  29055. static get type() {
  29056. return 'PointsNodeMaterial';
  29057. }
  29058. constructor( parameters ) {
  29059. super();
  29060. this.isPointsNodeMaterial = true;
  29061. this.lights = false;
  29062. this.transparent = true;
  29063. this.sizeNode = null;
  29064. this.setDefaultValues( _defaultValues$2 );
  29065. this.setValues( parameters );
  29066. }
  29067. copy( source ) {
  29068. this.sizeNode = source.sizeNode;
  29069. return super.copy( source );
  29070. }
  29071. }
  29072. class RotateNode extends TempNode {
  29073. static get type() {
  29074. return 'RotateNode';
  29075. }
  29076. constructor( positionNode, rotationNode ) {
  29077. super();
  29078. this.positionNode = positionNode;
  29079. this.rotationNode = rotationNode;
  29080. }
  29081. getNodeType( builder ) {
  29082. return this.positionNode.getNodeType( builder );
  29083. }
  29084. setup( builder ) {
  29085. const { rotationNode, positionNode } = this;
  29086. const nodeType = this.getNodeType( builder );
  29087. if ( nodeType === 'vec2' ) {
  29088. const cosAngle = rotationNode.cos();
  29089. const sinAngle = rotationNode.sin();
  29090. const rotationMatrix = mat2(
  29091. cosAngle, sinAngle,
  29092. sinAngle.negate(), cosAngle
  29093. );
  29094. return rotationMatrix.mul( positionNode );
  29095. } else {
  29096. const rotation = rotationNode;
  29097. 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 ) );
  29098. 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 ) );
  29099. 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 ) );
  29100. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  29101. }
  29102. }
  29103. }
  29104. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  29105. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  29106. class SpriteNodeMaterial extends NodeMaterial {
  29107. static get type() {
  29108. return 'SpriteNodeMaterial';
  29109. }
  29110. constructor( parameters ) {
  29111. super();
  29112. this.isSpriteNodeMaterial = true;
  29113. this.lights = false;
  29114. this._useSizeAttenuation = true;
  29115. this.positionNode = null;
  29116. this.rotationNode = null;
  29117. this.scaleNode = null;
  29118. this.setDefaultValues( _defaultValues$1 );
  29119. this.setValues( parameters );
  29120. }
  29121. setupPosition( { object, camera, context } ) {
  29122. const sizeAttenuation = this.sizeAttenuation;
  29123. // < VERTEX STAGE >
  29124. const { positionNode, rotationNode, scaleNode } = this;
  29125. const vertex = positionLocal;
  29126. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  29127. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  29128. if ( scaleNode !== null ) {
  29129. scale = scale.mul( scaleNode );
  29130. }
  29131. if ( ! sizeAttenuation ) {
  29132. if ( camera.isPerspectiveCamera ) {
  29133. scale = scale.mul( mvPosition.z.negate() );
  29134. } else {
  29135. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  29136. scale = scale.mul( orthoScale.mul( 2 ) );
  29137. }
  29138. }
  29139. let alignedPosition = vertex.xy;
  29140. if ( object.center && object.center.isVector2 === true ) {
  29141. const center = reference$1( 'center', 'vec2' );
  29142. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  29143. }
  29144. alignedPosition = alignedPosition.mul( scale );
  29145. const rotation = float( rotationNode || materialRotation );
  29146. const rotatedPosition = rotate( alignedPosition, rotation );
  29147. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  29148. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  29149. context.vertex = vertex;
  29150. return modelViewProjection;
  29151. }
  29152. copy( source ) {
  29153. this.positionNode = source.positionNode;
  29154. this.rotationNode = source.rotationNode;
  29155. this.scaleNode = source.scaleNode;
  29156. return super.copy( source );
  29157. }
  29158. get sizeAttenuation() {
  29159. return this._useSizeAttenuation;
  29160. }
  29161. set sizeAttenuation( value ) {
  29162. if ( this._useSizeAttenuation !== value ) {
  29163. this._useSizeAttenuation = value;
  29164. this.needsUpdate = true;
  29165. }
  29166. }
  29167. }
  29168. class ShadowMaskModel extends LightingModel {
  29169. constructor() {
  29170. super();
  29171. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  29172. }
  29173. direct( { shadowMask } ) {
  29174. this.shadowNode.mulAssign( shadowMask );
  29175. }
  29176. finish( context ) {
  29177. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  29178. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  29179. }
  29180. }
  29181. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  29182. class ShadowNodeMaterial extends NodeMaterial {
  29183. static get type() {
  29184. return 'ShadowNodeMaterial';
  29185. }
  29186. constructor( parameters ) {
  29187. super();
  29188. this.isShadowNodeMaterial = true;
  29189. this.lights = true;
  29190. this.setDefaultValues( _defaultValues );
  29191. this.setValues( parameters );
  29192. }
  29193. setupLightingModel( /*builder*/ ) {
  29194. return new ShadowMaskModel();
  29195. }
  29196. }
  29197. const normal = Fn( ( { texture, uv } ) => {
  29198. const epsilon = 0.0001;
  29199. const ret = vec3().toVar();
  29200. If( uv.x.lessThan( epsilon ), () => {
  29201. ret.assign( vec3( 1, 0, 0 ) );
  29202. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  29203. ret.assign( vec3( 0, 1, 0 ) );
  29204. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  29205. ret.assign( vec3( 0, 0, 1 ) );
  29206. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  29207. ret.assign( vec3( - 1, 0, 0 ) );
  29208. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  29209. ret.assign( vec3( 0, - 1, 0 ) );
  29210. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  29211. ret.assign( vec3( 0, 0, - 1 ) );
  29212. } ).Else( () => {
  29213. const step = 0.01;
  29214. 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 );
  29215. 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 );
  29216. 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 );
  29217. ret.assign( vec3( x, y, z ) );
  29218. } );
  29219. return ret.normalize();
  29220. } );
  29221. class Texture3DNode extends TextureNode {
  29222. static get type() {
  29223. return 'Texture3DNode';
  29224. }
  29225. constructor( value, uvNode = null, levelNode = null ) {
  29226. super( value, uvNode, levelNode );
  29227. this.isTexture3DNode = true;
  29228. }
  29229. getInputType( /*builder*/ ) {
  29230. return 'texture3D';
  29231. }
  29232. getDefaultUV() {
  29233. return vec3( 0.5, 0.5, 0.5 );
  29234. }
  29235. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  29236. setupUV( builder, uvNode ) {
  29237. return uvNode;
  29238. }
  29239. generateUV( builder, uvNode ) {
  29240. return uvNode.build( builder, 'vec3' );
  29241. }
  29242. normal( uvNode ) {
  29243. return normal( { texture: this, uv: uvNode } );
  29244. }
  29245. }
  29246. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  29247. class VolumeNodeMaterial extends NodeMaterial {
  29248. static get type() {
  29249. return 'VolumeNodeMaterial';
  29250. }
  29251. constructor( params = {} ) {
  29252. super();
  29253. this.lights = false;
  29254. this.isVolumeNodeMaterial = true;
  29255. this.testNode = null;
  29256. this.setValues( params );
  29257. }
  29258. setup( builder ) {
  29259. const map = texture3D( this.map, null, 0 );
  29260. const hitBox = Fn( ( { orig, dir } ) => {
  29261. const box_min = vec3( - 0.5 );
  29262. const box_max = vec3( 0.5 );
  29263. const inv_dir = dir.reciprocal();
  29264. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  29265. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  29266. const tmin = min$1( tmin_tmp, tmax_tmp );
  29267. const tmax = max$1( tmin_tmp, tmax_tmp );
  29268. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  29269. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  29270. return vec2( t0, t1 );
  29271. } );
  29272. this.fragmentNode = Fn( () => {
  29273. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  29274. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  29275. const rayDir = vDirection.normalize();
  29276. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  29277. bounds.x.greaterThan( bounds.y ).discard();
  29278. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  29279. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  29280. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  29281. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  29282. delta.divAssign( materialReference( 'steps', 'float' ) );
  29283. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  29284. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  29285. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  29286. if ( this.testNode !== null ) {
  29287. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  29288. } else {
  29289. // default to show surface of mesh
  29290. ac.a.assign( 1 );
  29291. Break();
  29292. }
  29293. p.addAssign( rayDir.mul( delta ) );
  29294. } );
  29295. ac.a.equal( 0 ).discard();
  29296. return vec4( ac );
  29297. } )();
  29298. super.setup( builder );
  29299. }
  29300. }
  29301. class Animation {
  29302. constructor( nodes, info ) {
  29303. this.nodes = nodes;
  29304. this.info = info;
  29305. this.animationLoop = null;
  29306. this.requestId = null;
  29307. this._init();
  29308. }
  29309. _init() {
  29310. const update = ( time, frame ) => {
  29311. this.requestId = self.requestAnimationFrame( update );
  29312. if ( this.info.autoReset === true ) this.info.reset();
  29313. this.nodes.nodeFrame.update();
  29314. this.info.frame = this.nodes.nodeFrame.frameId;
  29315. if ( this.animationLoop !== null ) this.animationLoop( time, frame );
  29316. };
  29317. update();
  29318. }
  29319. dispose() {
  29320. self.cancelAnimationFrame( this.requestId );
  29321. this.requestId = null;
  29322. }
  29323. setAnimationLoop( callback ) {
  29324. this.animationLoop = callback;
  29325. }
  29326. }
  29327. class ChainMap {
  29328. constructor() {
  29329. this.weakMap = new WeakMap();
  29330. }
  29331. get( keys ) {
  29332. let map = this.weakMap;
  29333. for ( let i = 0; i < keys.length; i ++ ) {
  29334. map = map.get( keys[ i ] );
  29335. if ( map === undefined ) return undefined;
  29336. }
  29337. return map.get( keys[ keys.length - 1 ] );
  29338. }
  29339. set( keys, value ) {
  29340. let map = this.weakMap;
  29341. for ( let i = 0; i < keys.length; i ++ ) {
  29342. const key = keys[ i ];
  29343. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  29344. map = map.get( key );
  29345. }
  29346. return map.set( keys[ keys.length - 1 ], value );
  29347. }
  29348. delete( keys ) {
  29349. let map = this.weakMap;
  29350. for ( let i = 0; i < keys.length; i ++ ) {
  29351. map = map.get( keys[ i ] );
  29352. if ( map === undefined ) return false;
  29353. }
  29354. return map.delete( keys[ keys.length - 1 ] );
  29355. }
  29356. }
  29357. const _plane = /*@__PURE__*/ new Plane();
  29358. class ClippingContext {
  29359. constructor() {
  29360. this.version = 0;
  29361. this.globalClippingCount = 0;
  29362. this.localClippingCount = 0;
  29363. this.localClippingEnabled = false;
  29364. this.localClipIntersection = false;
  29365. this.planes = [];
  29366. this.parentVersion = 0;
  29367. this.viewNormalMatrix = new Matrix3();
  29368. this.cacheKey = 0;
  29369. }
  29370. projectPlanes( source, offset ) {
  29371. const l = source.length;
  29372. const planes = this.planes;
  29373. for ( let i = 0; i < l; i ++ ) {
  29374. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  29375. const v = planes[ offset + i ];
  29376. const normal = _plane.normal;
  29377. v.x = - normal.x;
  29378. v.y = - normal.y;
  29379. v.z = - normal.z;
  29380. v.w = _plane.constant;
  29381. }
  29382. }
  29383. updateGlobal( renderer, camera ) {
  29384. const rendererClippingPlanes = renderer.clippingPlanes;
  29385. this.viewMatrix = camera.matrixWorldInverse;
  29386. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  29387. let update = false;
  29388. if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) {
  29389. const l = rendererClippingPlanes.length;
  29390. if ( l !== this.globalClippingCount ) {
  29391. const planes = [];
  29392. for ( let i = 0; i < l; i ++ ) {
  29393. planes.push( new Vector4() );
  29394. }
  29395. this.globalClippingCount = l;
  29396. this.planes = planes;
  29397. update = true;
  29398. }
  29399. this.projectPlanes( rendererClippingPlanes, 0 );
  29400. } else if ( this.globalClippingCount !== 0 ) {
  29401. this.globalClippingCount = 0;
  29402. this.planes = [];
  29403. update = true;
  29404. }
  29405. if ( renderer.localClippingEnabled !== this.localClippingEnabled ) {
  29406. this.localClippingEnabled = renderer.localClippingEnabled;
  29407. update = true;
  29408. }
  29409. if ( update ) {
  29410. this.version ++;
  29411. this.cacheKey = hash$1( this.globalClippingCount, this.localClippingEnabled === true ? 1 : 0 );
  29412. }
  29413. }
  29414. update( parent, material ) {
  29415. let update = false;
  29416. if ( this !== parent && parent.version !== this.parentVersion ) {
  29417. this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount;
  29418. this.localClippingEnabled = parent.localClippingEnabled;
  29419. this.planes = Array.from( parent.planes );
  29420. this.parentVersion = parent.version;
  29421. this.viewMatrix = parent.viewMatrix;
  29422. this.viewNormalMatrix = parent.viewNormalMatrix;
  29423. update = true;
  29424. }
  29425. if ( this.localClippingEnabled ) {
  29426. const localClippingPlanes = material.clippingPlanes;
  29427. if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) {
  29428. const l = localClippingPlanes.length;
  29429. const planes = this.planes;
  29430. const offset = this.globalClippingCount;
  29431. if ( update || l !== this.localClippingCount ) {
  29432. planes.length = offset + l;
  29433. for ( let i = 0; i < l; i ++ ) {
  29434. planes[ offset + i ] = new Vector4();
  29435. }
  29436. this.localClippingCount = l;
  29437. update = true;
  29438. }
  29439. this.projectPlanes( localClippingPlanes, offset );
  29440. } else if ( this.localClippingCount !== 0 ) {
  29441. this.localClippingCount = 0;
  29442. update = true;
  29443. }
  29444. if ( this.localClipIntersection !== material.clipIntersection ) {
  29445. this.localClipIntersection = material.clipIntersection;
  29446. update = true;
  29447. }
  29448. }
  29449. if ( update ) {
  29450. this.version += parent.version;
  29451. this.cacheKey = hash$1( parent.cacheKey, this.localClippingCount, this.localClipIntersection === true ? 1 : 0 );
  29452. }
  29453. }
  29454. }
  29455. let _id$7 = 0;
  29456. function getKeys( obj ) {
  29457. const keys = Object.keys( obj );
  29458. let proto = Object.getPrototypeOf( obj );
  29459. while ( proto ) {
  29460. const descriptors = Object.getOwnPropertyDescriptors( proto );
  29461. for ( const key in descriptors ) {
  29462. if ( descriptors[ key ] !== undefined ) {
  29463. const descriptor = descriptors[ key ];
  29464. if ( descriptor && typeof descriptor.get === 'function' ) {
  29465. keys.push( key );
  29466. }
  29467. }
  29468. }
  29469. proto = Object.getPrototypeOf( proto );
  29470. }
  29471. return keys;
  29472. }
  29473. class RenderObject {
  29474. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext ) {
  29475. this._nodes = nodes;
  29476. this._geometries = geometries;
  29477. this.id = _id$7 ++;
  29478. this.renderer = renderer;
  29479. this.object = object;
  29480. this.material = material;
  29481. this.scene = scene;
  29482. this.camera = camera;
  29483. this.lightsNode = lightsNode;
  29484. this.context = renderContext;
  29485. this.geometry = object.geometry;
  29486. this.version = material.version;
  29487. this.drawRange = null;
  29488. this.attributes = null;
  29489. this.pipeline = null;
  29490. this.vertexBuffers = null;
  29491. this.drawParams = null;
  29492. this.bundle = null;
  29493. this.updateClipping( renderContext.clippingContext );
  29494. this.clippingContextVersion = this.clippingContext.version;
  29495. this.initialNodesCacheKey = this.getDynamicCacheKey();
  29496. this.initialCacheKey = this.getCacheKey();
  29497. this._nodeBuilderState = null;
  29498. this._bindings = null;
  29499. this._monitor = null;
  29500. this.onDispose = null;
  29501. this.isRenderObject = true;
  29502. this.onMaterialDispose = () => {
  29503. this.dispose();
  29504. };
  29505. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  29506. }
  29507. updateClipping( parent ) {
  29508. const material = this.material;
  29509. let clippingContext = this.clippingContext;
  29510. if ( Array.isArray( material.clippingPlanes ) ) {
  29511. if ( clippingContext === parent || ! clippingContext ) {
  29512. clippingContext = new ClippingContext();
  29513. this.clippingContext = clippingContext;
  29514. }
  29515. clippingContext.update( parent, material );
  29516. } else if ( this.clippingContext !== parent ) {
  29517. this.clippingContext = parent;
  29518. }
  29519. }
  29520. get clippingNeedsUpdate() {
  29521. if ( this.clippingContext.version === this.clippingContextVersion ) return false;
  29522. this.clippingContextVersion = this.clippingContext.version;
  29523. return true;
  29524. }
  29525. getNodeBuilderState() {
  29526. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  29527. }
  29528. getMonitor() {
  29529. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  29530. }
  29531. getBindings() {
  29532. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  29533. }
  29534. getIndex() {
  29535. return this._geometries.getIndex( this );
  29536. }
  29537. getIndirect() {
  29538. return this._geometries.getIndirect( this );
  29539. }
  29540. getChainArray() {
  29541. return [ this.object, this.material, this.context, this.lightsNode ];
  29542. }
  29543. getAttributes() {
  29544. if ( this.attributes !== null ) return this.attributes;
  29545. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  29546. const geometry = this.geometry;
  29547. const attributes = [];
  29548. const vertexBuffers = new Set();
  29549. for ( const nodeAttribute of nodeAttributes ) {
  29550. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  29551. if ( attribute === undefined ) continue;
  29552. attributes.push( attribute );
  29553. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  29554. vertexBuffers.add( bufferAttribute );
  29555. }
  29556. this.attributes = attributes;
  29557. this.vertexBuffers = Array.from( vertexBuffers.values() );
  29558. return attributes;
  29559. }
  29560. getVertexBuffers() {
  29561. if ( this.vertexBuffers === null ) this.getAttributes();
  29562. return this.vertexBuffers;
  29563. }
  29564. getDrawParameters() {
  29565. const { object, material, geometry, group, drawRange } = this;
  29566. const drawParams = this.drawParams || ( this.drawParams = {
  29567. vertexCount: 0,
  29568. firstVertex: 0,
  29569. instanceCount: 0,
  29570. firstInstance: 0
  29571. } );
  29572. const index = this.getIndex();
  29573. const hasIndex = ( index !== null );
  29574. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  29575. if ( instanceCount === 0 ) return null;
  29576. drawParams.instanceCount = instanceCount;
  29577. if ( object.isBatchedMesh === true ) return drawParams;
  29578. let rangeFactor = 1;
  29579. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  29580. rangeFactor = 2;
  29581. }
  29582. let firstVertex = drawRange.start * rangeFactor;
  29583. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  29584. if ( group !== null ) {
  29585. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  29586. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  29587. }
  29588. const position = geometry.attributes.position;
  29589. let itemCount = Infinity;
  29590. if ( hasIndex ) {
  29591. itemCount = index.count;
  29592. } else if ( position !== undefined && position !== null ) {
  29593. itemCount = position.count;
  29594. }
  29595. firstVertex = Math.max( firstVertex, 0 );
  29596. lastVertex = Math.min( lastVertex, itemCount );
  29597. const count = lastVertex - firstVertex;
  29598. if ( count < 0 || count === Infinity ) return null;
  29599. drawParams.vertexCount = count;
  29600. drawParams.firstVertex = firstVertex;
  29601. return drawParams;
  29602. }
  29603. getGeometryCacheKey() {
  29604. const { geometry } = this;
  29605. let cacheKey = '';
  29606. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  29607. const attribute = geometry.attributes[ name ];
  29608. cacheKey += name + ',';
  29609. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  29610. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  29611. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  29612. if ( attribute.normalized ) cacheKey += 'n,';
  29613. }
  29614. if ( geometry.index ) {
  29615. cacheKey += 'index,';
  29616. }
  29617. return cacheKey;
  29618. }
  29619. getMaterialCacheKey() {
  29620. const { object, material } = this;
  29621. let cacheKey = material.customProgramCacheKey();
  29622. for ( const property of getKeys( material ) ) {
  29623. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  29624. const value = material[ property ];
  29625. let valueKey;
  29626. if ( value !== null ) {
  29627. // some material values require a formatting
  29628. const type = typeof value;
  29629. if ( type === 'number' ) {
  29630. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  29631. } else if ( type === 'object' ) {
  29632. valueKey = '{';
  29633. if ( value.isTexture ) {
  29634. valueKey += value.mapping;
  29635. }
  29636. valueKey += '}';
  29637. } else {
  29638. valueKey = String( value );
  29639. }
  29640. } else {
  29641. valueKey = String( value );
  29642. }
  29643. cacheKey += /*property + ':' +*/ valueKey + ',';
  29644. }
  29645. cacheKey += this.clippingContext.cacheKey + ',';
  29646. if ( object.geometry ) {
  29647. cacheKey += this.getGeometryCacheKey();
  29648. }
  29649. if ( object.skeleton ) {
  29650. cacheKey += object.skeleton.bones.length + ',';
  29651. }
  29652. if ( object.morphTargetInfluences ) {
  29653. cacheKey += object.morphTargetInfluences.length + ',';
  29654. }
  29655. if ( object.isBatchedMesh ) {
  29656. cacheKey += object._matricesTexture.uuid + ',';
  29657. if ( object._colorsTexture !== null ) {
  29658. cacheKey += object._colorsTexture.uuid + ',';
  29659. }
  29660. }
  29661. if ( object.count > 1 ) {
  29662. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  29663. cacheKey += object.uuid + ',';
  29664. }
  29665. return hashString( cacheKey );
  29666. }
  29667. get needsUpdate() {
  29668. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  29669. }
  29670. getDynamicCacheKey() {
  29671. // Environment Nodes Cache Key
  29672. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  29673. if ( this.object.receiveShadow ) {
  29674. cacheKey += 1;
  29675. }
  29676. return cacheKey;
  29677. }
  29678. getCacheKey() {
  29679. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  29680. }
  29681. dispose() {
  29682. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  29683. this.onDispose();
  29684. }
  29685. }
  29686. const chainArray = [];
  29687. class RenderObjects {
  29688. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  29689. this.renderer = renderer;
  29690. this.nodes = nodes;
  29691. this.geometries = geometries;
  29692. this.pipelines = pipelines;
  29693. this.bindings = bindings;
  29694. this.info = info;
  29695. this.chainMaps = {};
  29696. }
  29697. get( object, material, scene, camera, lightsNode, renderContext, passId ) {
  29698. const chainMap = this.getChainMap( passId );
  29699. // reuse chainArray
  29700. chainArray[ 0 ] = object;
  29701. chainArray[ 1 ] = material;
  29702. chainArray[ 2 ] = renderContext;
  29703. chainArray[ 3 ] = lightsNode;
  29704. let renderObject = chainMap.get( chainArray );
  29705. if ( renderObject === undefined ) {
  29706. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, passId );
  29707. chainMap.set( chainArray, renderObject );
  29708. } else {
  29709. renderObject.updateClipping( renderContext.clippingContext );
  29710. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  29711. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  29712. renderObject.dispose();
  29713. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, passId );
  29714. } else {
  29715. renderObject.version = material.version;
  29716. }
  29717. }
  29718. }
  29719. return renderObject;
  29720. }
  29721. getChainMap( passId = 'default' ) {
  29722. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  29723. }
  29724. dispose() {
  29725. this.chainMaps = {};
  29726. }
  29727. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, passId ) {
  29728. const chainMap = this.getChainMap( passId );
  29729. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext );
  29730. renderObject.onDispose = () => {
  29731. this.pipelines.delete( renderObject );
  29732. this.bindings.delete( renderObject );
  29733. this.nodes.delete( renderObject );
  29734. chainMap.delete( renderObject.getChainArray() );
  29735. };
  29736. return renderObject;
  29737. }
  29738. }
  29739. class DataMap {
  29740. constructor() {
  29741. this.data = new WeakMap();
  29742. }
  29743. get( object ) {
  29744. let map = this.data.get( object );
  29745. if ( map === undefined ) {
  29746. map = {};
  29747. this.data.set( object, map );
  29748. }
  29749. return map;
  29750. }
  29751. delete( object ) {
  29752. let map;
  29753. if ( this.data.has( object ) ) {
  29754. map = this.data.get( object );
  29755. this.data.delete( object );
  29756. }
  29757. return map;
  29758. }
  29759. has( object ) {
  29760. return this.data.has( object );
  29761. }
  29762. dispose() {
  29763. this.data = new WeakMap();
  29764. }
  29765. }
  29766. const AttributeType = {
  29767. VERTEX: 1,
  29768. INDEX: 2,
  29769. STORAGE: 3,
  29770. INDIRECT: 4
  29771. };
  29772. // size of a chunk in bytes (STD140 layout)
  29773. const GPU_CHUNK_BYTES = 16;
  29774. // @TODO: Move to src/constants.js
  29775. const BlendColorFactor = 211;
  29776. const OneMinusBlendColorFactor = 212;
  29777. class Attributes extends DataMap {
  29778. constructor( backend ) {
  29779. super();
  29780. this.backend = backend;
  29781. }
  29782. delete( attribute ) {
  29783. const attributeData = super.delete( attribute );
  29784. if ( attributeData !== undefined ) {
  29785. this.backend.destroyAttribute( attribute );
  29786. }
  29787. return attributeData;
  29788. }
  29789. update( attribute, type ) {
  29790. const data = this.get( attribute );
  29791. if ( data.version === undefined ) {
  29792. if ( type === AttributeType.VERTEX ) {
  29793. this.backend.createAttribute( attribute );
  29794. } else if ( type === AttributeType.INDEX ) {
  29795. this.backend.createIndexAttribute( attribute );
  29796. } else if ( type === AttributeType.STORAGE ) {
  29797. this.backend.createStorageAttribute( attribute );
  29798. } else if ( type === AttributeType.INDIRECT ) {
  29799. this.backend.createIndirectStorageAttribute( attribute );
  29800. }
  29801. data.version = this._getBufferAttribute( attribute ).version;
  29802. } else {
  29803. const bufferAttribute = this._getBufferAttribute( attribute );
  29804. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  29805. this.backend.updateAttribute( attribute );
  29806. data.version = bufferAttribute.version;
  29807. }
  29808. }
  29809. }
  29810. _getBufferAttribute( attribute ) {
  29811. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  29812. return attribute;
  29813. }
  29814. }
  29815. function arrayNeedsUint32( array ) {
  29816. // assumes larger values usually on last
  29817. for ( let i = array.length - 1; i >= 0; -- i ) {
  29818. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  29819. }
  29820. return false;
  29821. }
  29822. function getWireframeVersion( geometry ) {
  29823. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  29824. }
  29825. function getWireframeIndex( geometry ) {
  29826. const indices = [];
  29827. const geometryIndex = geometry.index;
  29828. const geometryPosition = geometry.attributes.position;
  29829. if ( geometryIndex !== null ) {
  29830. const array = geometryIndex.array;
  29831. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  29832. const a = array[ i + 0 ];
  29833. const b = array[ i + 1 ];
  29834. const c = array[ i + 2 ];
  29835. indices.push( a, b, b, c, c, a );
  29836. }
  29837. } else {
  29838. const array = geometryPosition.array;
  29839. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  29840. const a = i + 0;
  29841. const b = i + 1;
  29842. const c = i + 2;
  29843. indices.push( a, b, b, c, c, a );
  29844. }
  29845. }
  29846. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  29847. attribute.version = getWireframeVersion( geometry );
  29848. return attribute;
  29849. }
  29850. class Geometries extends DataMap {
  29851. constructor( attributes, info ) {
  29852. super();
  29853. this.attributes = attributes;
  29854. this.info = info;
  29855. this.wireframes = new WeakMap();
  29856. this.attributeCall = new WeakMap();
  29857. }
  29858. has( renderObject ) {
  29859. const geometry = renderObject.geometry;
  29860. return super.has( geometry ) && this.get( geometry ).initialized === true;
  29861. }
  29862. updateForRender( renderObject ) {
  29863. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  29864. this.updateAttributes( renderObject );
  29865. }
  29866. initGeometry( renderObject ) {
  29867. const geometry = renderObject.geometry;
  29868. const geometryData = this.get( geometry );
  29869. geometryData.initialized = true;
  29870. this.info.memory.geometries ++;
  29871. const onDispose = () => {
  29872. this.info.memory.geometries --;
  29873. const index = geometry.index;
  29874. const geometryAttributes = renderObject.getAttributes();
  29875. if ( index !== null ) {
  29876. this.attributes.delete( index );
  29877. }
  29878. for ( const geometryAttribute of geometryAttributes ) {
  29879. this.attributes.delete( geometryAttribute );
  29880. }
  29881. const wireframeAttribute = this.wireframes.get( geometry );
  29882. if ( wireframeAttribute !== undefined ) {
  29883. this.attributes.delete( wireframeAttribute );
  29884. }
  29885. geometry.removeEventListener( 'dispose', onDispose );
  29886. };
  29887. geometry.addEventListener( 'dispose', onDispose );
  29888. }
  29889. updateAttributes( renderObject ) {
  29890. // attributes
  29891. const attributes = renderObject.getAttributes();
  29892. for ( const attribute of attributes ) {
  29893. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  29894. this.updateAttribute( attribute, AttributeType.STORAGE );
  29895. } else {
  29896. this.updateAttribute( attribute, AttributeType.VERTEX );
  29897. }
  29898. }
  29899. // indexes
  29900. const index = this.getIndex( renderObject );
  29901. if ( index !== null ) {
  29902. this.updateAttribute( index, AttributeType.INDEX );
  29903. }
  29904. // indirect
  29905. const indirect = renderObject.geometry.indirect;
  29906. if ( indirect !== null ) {
  29907. this.updateAttribute( indirect, AttributeType.INDIRECT );
  29908. }
  29909. }
  29910. updateAttribute( attribute, type ) {
  29911. const callId = this.info.render.calls;
  29912. if ( ! attribute.isInterleavedBufferAttribute ) {
  29913. if ( this.attributeCall.get( attribute ) !== callId ) {
  29914. this.attributes.update( attribute, type );
  29915. this.attributeCall.set( attribute, callId );
  29916. }
  29917. } else {
  29918. if ( this.attributeCall.get( attribute ) === undefined ) {
  29919. this.attributes.update( attribute, type );
  29920. this.attributeCall.set( attribute, callId );
  29921. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  29922. this.attributes.update( attribute, type );
  29923. this.attributeCall.set( attribute.data, callId );
  29924. this.attributeCall.set( attribute, callId );
  29925. }
  29926. }
  29927. }
  29928. getIndirect( renderObject ) {
  29929. return renderObject.geometry.indirect;
  29930. }
  29931. getIndex( renderObject ) {
  29932. const { geometry, material } = renderObject;
  29933. let index = geometry.index;
  29934. if ( material.wireframe === true ) {
  29935. const wireframes = this.wireframes;
  29936. let wireframeAttribute = wireframes.get( geometry );
  29937. if ( wireframeAttribute === undefined ) {
  29938. wireframeAttribute = getWireframeIndex( geometry );
  29939. wireframes.set( geometry, wireframeAttribute );
  29940. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  29941. this.attributes.delete( wireframeAttribute );
  29942. wireframeAttribute = getWireframeIndex( geometry );
  29943. wireframes.set( geometry, wireframeAttribute );
  29944. }
  29945. index = wireframeAttribute;
  29946. }
  29947. return index;
  29948. }
  29949. }
  29950. class Info {
  29951. constructor() {
  29952. this.autoReset = true;
  29953. this.frame = 0;
  29954. this.calls = 0;
  29955. this.render = {
  29956. calls: 0,
  29957. frameCalls: 0,
  29958. drawCalls: 0,
  29959. triangles: 0,
  29960. points: 0,
  29961. lines: 0,
  29962. timestamp: 0,
  29963. previousFrameCalls: 0,
  29964. timestampCalls: 0
  29965. };
  29966. this.compute = {
  29967. calls: 0,
  29968. frameCalls: 0,
  29969. timestamp: 0,
  29970. previousFrameCalls: 0,
  29971. timestampCalls: 0
  29972. };
  29973. this.memory = {
  29974. geometries: 0,
  29975. textures: 0
  29976. };
  29977. }
  29978. update( object, count, instanceCount ) {
  29979. this.render.drawCalls ++;
  29980. if ( object.isMesh || object.isSprite ) {
  29981. this.render.triangles += instanceCount * ( count / 3 );
  29982. } else if ( object.isPoints ) {
  29983. this.render.points += instanceCount * count;
  29984. } else if ( object.isLineSegments ) {
  29985. this.render.lines += instanceCount * ( count / 2 );
  29986. } else if ( object.isLine ) {
  29987. this.render.lines += instanceCount * ( count - 1 );
  29988. } else {
  29989. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  29990. }
  29991. }
  29992. updateTimestamp( type, time ) {
  29993. if ( this[ type ].timestampCalls === 0 ) {
  29994. this[ type ].timestamp = 0;
  29995. }
  29996. this[ type ].timestamp += time;
  29997. this[ type ].timestampCalls ++;
  29998. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  29999. this[ type ].timestampCalls = 0;
  30000. }
  30001. }
  30002. reset() {
  30003. const previousRenderFrameCalls = this.render.frameCalls;
  30004. this.render.previousFrameCalls = previousRenderFrameCalls;
  30005. const previousComputeFrameCalls = this.compute.frameCalls;
  30006. this.compute.previousFrameCalls = previousComputeFrameCalls;
  30007. this.render.drawCalls = 0;
  30008. this.render.frameCalls = 0;
  30009. this.compute.frameCalls = 0;
  30010. this.render.triangles = 0;
  30011. this.render.points = 0;
  30012. this.render.lines = 0;
  30013. }
  30014. dispose() {
  30015. this.reset();
  30016. this.calls = 0;
  30017. this.render.calls = 0;
  30018. this.compute.calls = 0;
  30019. this.render.timestamp = 0;
  30020. this.compute.timestamp = 0;
  30021. this.memory.geometries = 0;
  30022. this.memory.textures = 0;
  30023. }
  30024. }
  30025. class Pipeline {
  30026. constructor( cacheKey ) {
  30027. this.cacheKey = cacheKey;
  30028. this.usedTimes = 0;
  30029. }
  30030. }
  30031. class RenderPipeline extends Pipeline {
  30032. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  30033. super( cacheKey );
  30034. this.vertexProgram = vertexProgram;
  30035. this.fragmentProgram = fragmentProgram;
  30036. }
  30037. }
  30038. class ComputePipeline extends Pipeline {
  30039. constructor( cacheKey, computeProgram ) {
  30040. super( cacheKey );
  30041. this.computeProgram = computeProgram;
  30042. this.isComputePipeline = true;
  30043. }
  30044. }
  30045. let _id$6 = 0;
  30046. class ProgrammableStage {
  30047. constructor( code, type, transforms = null, attributes = null ) {
  30048. this.id = _id$6 ++;
  30049. this.code = code;
  30050. this.stage = type;
  30051. this.transforms = transforms;
  30052. this.attributes = attributes;
  30053. this.usedTimes = 0;
  30054. }
  30055. }
  30056. class Pipelines extends DataMap {
  30057. constructor( backend, nodes ) {
  30058. super();
  30059. this.backend = backend;
  30060. this.nodes = nodes;
  30061. this.bindings = null; // set by the bindings
  30062. this.caches = new Map();
  30063. this.programs = {
  30064. vertex: new Map(),
  30065. fragment: new Map(),
  30066. compute: new Map()
  30067. };
  30068. }
  30069. getForCompute( computeNode, bindings ) {
  30070. const { backend } = this;
  30071. const data = this.get( computeNode );
  30072. if ( this._needsComputeUpdate( computeNode ) ) {
  30073. const previousPipeline = data.pipeline;
  30074. if ( previousPipeline ) {
  30075. previousPipeline.usedTimes --;
  30076. previousPipeline.computeProgram.usedTimes --;
  30077. }
  30078. // get shader
  30079. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  30080. // programmable stage
  30081. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  30082. if ( stageCompute === undefined ) {
  30083. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  30084. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  30085. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  30086. backend.createProgram( stageCompute );
  30087. }
  30088. // determine compute pipeline
  30089. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  30090. let pipeline = this.caches.get( cacheKey );
  30091. if ( pipeline === undefined ) {
  30092. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  30093. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  30094. }
  30095. // keep track of all used times
  30096. pipeline.usedTimes ++;
  30097. stageCompute.usedTimes ++;
  30098. //
  30099. data.version = computeNode.version;
  30100. data.pipeline = pipeline;
  30101. }
  30102. return data.pipeline;
  30103. }
  30104. getForRender( renderObject, promises = null ) {
  30105. const { backend } = this;
  30106. const data = this.get( renderObject );
  30107. if ( this._needsRenderUpdate( renderObject ) ) {
  30108. const previousPipeline = data.pipeline;
  30109. if ( previousPipeline ) {
  30110. previousPipeline.usedTimes --;
  30111. previousPipeline.vertexProgram.usedTimes --;
  30112. previousPipeline.fragmentProgram.usedTimes --;
  30113. }
  30114. // get shader
  30115. const nodeBuilderState = renderObject.getNodeBuilderState();
  30116. // programmable stages
  30117. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  30118. if ( stageVertex === undefined ) {
  30119. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  30120. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  30121. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  30122. backend.createProgram( stageVertex );
  30123. }
  30124. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  30125. if ( stageFragment === undefined ) {
  30126. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  30127. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  30128. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  30129. backend.createProgram( stageFragment );
  30130. }
  30131. // determine render pipeline
  30132. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  30133. let pipeline = this.caches.get( cacheKey );
  30134. if ( pipeline === undefined ) {
  30135. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  30136. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  30137. } else {
  30138. renderObject.pipeline = pipeline;
  30139. }
  30140. // keep track of all used times
  30141. pipeline.usedTimes ++;
  30142. stageVertex.usedTimes ++;
  30143. stageFragment.usedTimes ++;
  30144. //
  30145. data.pipeline = pipeline;
  30146. }
  30147. return data.pipeline;
  30148. }
  30149. delete( object ) {
  30150. const pipeline = this.get( object ).pipeline;
  30151. if ( pipeline ) {
  30152. // pipeline
  30153. pipeline.usedTimes --;
  30154. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  30155. // programs
  30156. if ( pipeline.isComputePipeline ) {
  30157. pipeline.computeProgram.usedTimes --;
  30158. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  30159. } else {
  30160. pipeline.fragmentProgram.usedTimes --;
  30161. pipeline.vertexProgram.usedTimes --;
  30162. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  30163. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  30164. }
  30165. }
  30166. return super.delete( object );
  30167. }
  30168. dispose() {
  30169. super.dispose();
  30170. this.caches = new Map();
  30171. this.programs = {
  30172. vertex: new Map(),
  30173. fragment: new Map(),
  30174. compute: new Map()
  30175. };
  30176. }
  30177. updateForRender( renderObject ) {
  30178. this.getForRender( renderObject );
  30179. }
  30180. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  30181. // check for existing pipeline
  30182. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  30183. let pipeline = this.caches.get( cacheKey );
  30184. if ( pipeline === undefined ) {
  30185. pipeline = new ComputePipeline( cacheKey, stageCompute );
  30186. this.caches.set( cacheKey, pipeline );
  30187. this.backend.createComputePipeline( pipeline, bindings );
  30188. }
  30189. return pipeline;
  30190. }
  30191. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  30192. // check for existing pipeline
  30193. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  30194. let pipeline = this.caches.get( cacheKey );
  30195. if ( pipeline === undefined ) {
  30196. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  30197. this.caches.set( cacheKey, pipeline );
  30198. renderObject.pipeline = pipeline;
  30199. this.backend.createRenderPipeline( renderObject, promises );
  30200. }
  30201. return pipeline;
  30202. }
  30203. _getComputeCacheKey( computeNode, stageCompute ) {
  30204. return computeNode.id + ',' + stageCompute.id;
  30205. }
  30206. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  30207. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  30208. }
  30209. _releasePipeline( pipeline ) {
  30210. this.caches.delete( pipeline.cacheKey );
  30211. }
  30212. _releaseProgram( program ) {
  30213. const code = program.code;
  30214. const stage = program.stage;
  30215. this.programs[ stage ].delete( code );
  30216. }
  30217. _needsComputeUpdate( computeNode ) {
  30218. const data = this.get( computeNode );
  30219. return data.pipeline === undefined || data.version !== computeNode.version;
  30220. }
  30221. _needsRenderUpdate( renderObject ) {
  30222. const data = this.get( renderObject );
  30223. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  30224. }
  30225. }
  30226. class Bindings extends DataMap {
  30227. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  30228. super();
  30229. this.backend = backend;
  30230. this.textures = textures;
  30231. this.pipelines = pipelines;
  30232. this.attributes = attributes;
  30233. this.nodes = nodes;
  30234. this.info = info;
  30235. this.pipelines.bindings = this; // assign bindings to pipelines
  30236. }
  30237. getForRender( renderObject ) {
  30238. const bindings = renderObject.getBindings();
  30239. for ( const bindGroup of bindings ) {
  30240. const groupData = this.get( bindGroup );
  30241. if ( groupData.bindGroup === undefined ) {
  30242. // each object defines an array of bindings (ubos, textures, samplers etc.)
  30243. this._init( bindGroup );
  30244. this.backend.createBindings( bindGroup, bindings );
  30245. groupData.bindGroup = bindGroup;
  30246. }
  30247. }
  30248. return bindings;
  30249. }
  30250. getForCompute( computeNode ) {
  30251. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  30252. for ( const bindGroup of bindings ) {
  30253. const groupData = this.get( bindGroup );
  30254. if ( groupData.bindGroup === undefined ) {
  30255. this._init( bindGroup );
  30256. this.backend.createBindings( bindGroup, bindings );
  30257. groupData.bindGroup = bindGroup;
  30258. }
  30259. }
  30260. return bindings;
  30261. }
  30262. updateForCompute( computeNode ) {
  30263. this._updateBindings( this.getForCompute( computeNode ) );
  30264. }
  30265. updateForRender( renderObject ) {
  30266. this._updateBindings( this.getForRender( renderObject ) );
  30267. }
  30268. _updateBindings( bindings ) {
  30269. for ( const bindGroup of bindings ) {
  30270. this._update( bindGroup, bindings );
  30271. }
  30272. }
  30273. _init( bindGroup ) {
  30274. for ( const binding of bindGroup.bindings ) {
  30275. if ( binding.isSampledTexture ) {
  30276. this.textures.updateTexture( binding.texture );
  30277. } else if ( binding.isStorageBuffer ) {
  30278. const attribute = binding.attribute;
  30279. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  30280. this.attributes.update( attribute, attributeType );
  30281. }
  30282. }
  30283. }
  30284. _update( bindGroup, bindings ) {
  30285. const { backend } = this;
  30286. let needsBindingsUpdate = false;
  30287. // iterate over all bindings and check if buffer updates or a new binding group is required
  30288. for ( const binding of bindGroup.bindings ) {
  30289. if ( binding.isNodeUniformsGroup ) {
  30290. const updated = this.nodes.updateGroup( binding );
  30291. if ( ! updated ) continue;
  30292. }
  30293. if ( binding.isUniformBuffer ) {
  30294. const updated = binding.update();
  30295. if ( updated ) {
  30296. backend.updateBinding( binding );
  30297. }
  30298. } else if ( binding.isSampler ) {
  30299. binding.update();
  30300. } else if ( binding.isSampledTexture ) {
  30301. if ( binding.needsBindingsUpdate( this.textures.get( binding.texture ).generation ) ) needsBindingsUpdate = true;
  30302. const updated = binding.update();
  30303. const texture = binding.texture;
  30304. if ( updated ) {
  30305. this.textures.updateTexture( texture );
  30306. }
  30307. const textureData = backend.get( texture );
  30308. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  30309. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  30310. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  30311. this.textures.updateTexture( texture );
  30312. needsBindingsUpdate = true;
  30313. }
  30314. if ( texture.isStorageTexture === true ) {
  30315. const textureData = this.get( texture );
  30316. if ( binding.store === true ) {
  30317. textureData.needsMipmap = true;
  30318. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  30319. this.backend.generateMipmaps( texture );
  30320. textureData.needsMipmap = false;
  30321. }
  30322. }
  30323. }
  30324. }
  30325. if ( needsBindingsUpdate === true ) {
  30326. this.backend.updateBindings( bindGroup, bindings );
  30327. }
  30328. }
  30329. }
  30330. function painterSortStable( a, b ) {
  30331. if ( a.groupOrder !== b.groupOrder ) {
  30332. return a.groupOrder - b.groupOrder;
  30333. } else if ( a.renderOrder !== b.renderOrder ) {
  30334. return a.renderOrder - b.renderOrder;
  30335. } else if ( a.material.id !== b.material.id ) {
  30336. return a.material.id - b.material.id;
  30337. } else if ( a.z !== b.z ) {
  30338. return a.z - b.z;
  30339. } else {
  30340. return a.id - b.id;
  30341. }
  30342. }
  30343. function reversePainterSortStable( a, b ) {
  30344. if ( a.groupOrder !== b.groupOrder ) {
  30345. return a.groupOrder - b.groupOrder;
  30346. } else if ( a.renderOrder !== b.renderOrder ) {
  30347. return a.renderOrder - b.renderOrder;
  30348. } else if ( a.z !== b.z ) {
  30349. return b.z - a.z;
  30350. } else {
  30351. return a.id - b.id;
  30352. }
  30353. }
  30354. function needsDoublePass( material ) {
  30355. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  30356. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  30357. }
  30358. class RenderList {
  30359. constructor( lighting, scene, camera ) {
  30360. this.renderItems = [];
  30361. this.renderItemsIndex = 0;
  30362. this.opaque = [];
  30363. this.transparentDoublePass = [];
  30364. this.transparent = [];
  30365. this.bundles = [];
  30366. this.lightsNode = lighting.getNode( scene, camera );
  30367. this.lightsArray = [];
  30368. this.scene = scene;
  30369. this.camera = camera;
  30370. this.occlusionQueryCount = 0;
  30371. }
  30372. begin() {
  30373. this.renderItemsIndex = 0;
  30374. this.opaque.length = 0;
  30375. this.transparentDoublePass.length = 0;
  30376. this.transparent.length = 0;
  30377. this.bundles.length = 0;
  30378. this.lightsArray.length = 0;
  30379. this.occlusionQueryCount = 0;
  30380. return this;
  30381. }
  30382. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  30383. let renderItem = this.renderItems[ this.renderItemsIndex ];
  30384. if ( renderItem === undefined ) {
  30385. renderItem = {
  30386. id: object.id,
  30387. object: object,
  30388. geometry: geometry,
  30389. material: material,
  30390. groupOrder: groupOrder,
  30391. renderOrder: object.renderOrder,
  30392. z: z,
  30393. group: group
  30394. };
  30395. this.renderItems[ this.renderItemsIndex ] = renderItem;
  30396. } else {
  30397. renderItem.id = object.id;
  30398. renderItem.object = object;
  30399. renderItem.geometry = geometry;
  30400. renderItem.material = material;
  30401. renderItem.groupOrder = groupOrder;
  30402. renderItem.renderOrder = object.renderOrder;
  30403. renderItem.z = z;
  30404. renderItem.group = group;
  30405. }
  30406. this.renderItemsIndex ++;
  30407. return renderItem;
  30408. }
  30409. push( object, geometry, material, groupOrder, z, group ) {
  30410. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  30411. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  30412. if ( material.transparent === true || material.transmission > 0 ) {
  30413. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  30414. this.transparent.push( renderItem );
  30415. } else {
  30416. this.opaque.push( renderItem );
  30417. }
  30418. }
  30419. unshift( object, geometry, material, groupOrder, z, group ) {
  30420. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  30421. if ( material.transparent === true || material.transmission > 0 ) {
  30422. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  30423. this.transparent.unshift( renderItem );
  30424. } else {
  30425. this.opaque.unshift( renderItem );
  30426. }
  30427. }
  30428. pushBundle( group ) {
  30429. this.bundles.push( group );
  30430. }
  30431. pushLight( light ) {
  30432. this.lightsArray.push( light );
  30433. }
  30434. sort( customOpaqueSort, customTransparentSort ) {
  30435. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  30436. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  30437. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  30438. }
  30439. finish() {
  30440. // update lights
  30441. this.lightsNode.setLights( this.lightsArray );
  30442. // Clear references from inactive renderItems in the list
  30443. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  30444. const renderItem = this.renderItems[ i ];
  30445. if ( renderItem.id === null ) break;
  30446. renderItem.id = null;
  30447. renderItem.object = null;
  30448. renderItem.geometry = null;
  30449. renderItem.material = null;
  30450. renderItem.groupOrder = null;
  30451. renderItem.renderOrder = null;
  30452. renderItem.z = null;
  30453. renderItem.group = null;
  30454. }
  30455. }
  30456. }
  30457. class RenderLists {
  30458. constructor( lighting ) {
  30459. this.lighting = lighting;
  30460. this.lists = new ChainMap();
  30461. }
  30462. get( scene, camera ) {
  30463. const lists = this.lists;
  30464. const keys = [ scene, camera ];
  30465. let list = lists.get( keys );
  30466. if ( list === undefined ) {
  30467. list = new RenderList( this.lighting, scene, camera );
  30468. lists.set( keys, list );
  30469. }
  30470. return list;
  30471. }
  30472. dispose() {
  30473. this.lists = new ChainMap();
  30474. }
  30475. }
  30476. let id$1 = 0;
  30477. class RenderContext {
  30478. constructor() {
  30479. this.id = id$1 ++;
  30480. this.color = true;
  30481. this.clearColor = true;
  30482. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  30483. this.depth = true;
  30484. this.clearDepth = true;
  30485. this.clearDepthValue = 1;
  30486. this.stencil = false;
  30487. this.clearStencil = true;
  30488. this.clearStencilValue = 1;
  30489. this.viewport = false;
  30490. this.viewportValue = new Vector4();
  30491. this.scissor = false;
  30492. this.scissorValue = new Vector4();
  30493. this.textures = null;
  30494. this.depthTexture = null;
  30495. this.activeCubeFace = 0;
  30496. this.sampleCount = 1;
  30497. this.width = 0;
  30498. this.height = 0;
  30499. this.isRenderContext = true;
  30500. }
  30501. getCacheKey() {
  30502. return getCacheKey( this );
  30503. }
  30504. }
  30505. function getCacheKey( renderContext ) {
  30506. const { textures, activeCubeFace } = renderContext;
  30507. const values = [ activeCubeFace ];
  30508. for ( const texture of textures ) {
  30509. values.push( texture.id );
  30510. }
  30511. return hashArray( values );
  30512. }
  30513. class RenderContexts {
  30514. constructor() {
  30515. this.chainMaps = {};
  30516. }
  30517. get( scene, camera, renderTarget = null ) {
  30518. const chainKey = [ scene, camera ];
  30519. let attachmentState;
  30520. if ( renderTarget === null ) {
  30521. attachmentState = 'default';
  30522. } else {
  30523. const format = renderTarget.texture.format;
  30524. const count = renderTarget.textures.length;
  30525. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  30526. }
  30527. const chainMap = this.getChainMap( attachmentState );
  30528. let renderState = chainMap.get( chainKey );
  30529. if ( renderState === undefined ) {
  30530. renderState = new RenderContext();
  30531. chainMap.set( chainKey, renderState );
  30532. }
  30533. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  30534. return renderState;
  30535. }
  30536. getChainMap( attachmentState ) {
  30537. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  30538. }
  30539. dispose() {
  30540. this.chainMaps = {};
  30541. }
  30542. }
  30543. const _size$3 = /*@__PURE__*/ new Vector3();
  30544. class Textures extends DataMap {
  30545. constructor( renderer, backend, info ) {
  30546. super();
  30547. this.renderer = renderer;
  30548. this.backend = backend;
  30549. this.info = info;
  30550. }
  30551. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  30552. const renderTargetData = this.get( renderTarget );
  30553. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  30554. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  30555. const textures = renderTarget.textures;
  30556. const size = this.getSize( textures[ 0 ] );
  30557. const mipWidth = size.width >> activeMipmapLevel;
  30558. const mipHeight = size.height >> activeMipmapLevel;
  30559. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  30560. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  30561. let textureNeedsUpdate = false;
  30562. if ( depthTexture === undefined && useDepthTexture ) {
  30563. depthTexture = new DepthTexture();
  30564. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  30565. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  30566. depthTexture.image.width = mipWidth;
  30567. depthTexture.image.height = mipHeight;
  30568. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  30569. }
  30570. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  30571. textureNeedsUpdate = true;
  30572. if ( depthTexture ) {
  30573. depthTexture.needsUpdate = true;
  30574. depthTexture.image.width = mipWidth;
  30575. depthTexture.image.height = mipHeight;
  30576. }
  30577. }
  30578. renderTargetData.width = size.width;
  30579. renderTargetData.height = size.height;
  30580. renderTargetData.textures = textures;
  30581. renderTargetData.depthTexture = depthTexture || null;
  30582. renderTargetData.depth = renderTarget.depthBuffer;
  30583. renderTargetData.stencil = renderTarget.stencilBuffer;
  30584. renderTargetData.renderTarget = renderTarget;
  30585. if ( renderTargetData.sampleCount !== sampleCount ) {
  30586. textureNeedsUpdate = true;
  30587. if ( depthTexture ) {
  30588. depthTexture.needsUpdate = true;
  30589. }
  30590. renderTargetData.sampleCount = sampleCount;
  30591. }
  30592. //
  30593. const options = { sampleCount };
  30594. for ( let i = 0; i < textures.length; i ++ ) {
  30595. const texture = textures[ i ];
  30596. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  30597. this.updateTexture( texture, options );
  30598. }
  30599. if ( depthTexture ) {
  30600. this.updateTexture( depthTexture, options );
  30601. }
  30602. // dispose handler
  30603. if ( renderTargetData.initialized !== true ) {
  30604. renderTargetData.initialized = true;
  30605. // dispose
  30606. const onDispose = () => {
  30607. renderTarget.removeEventListener( 'dispose', onDispose );
  30608. for ( let i = 0; i < textures.length; i ++ ) {
  30609. this._destroyTexture( textures[ i ] );
  30610. }
  30611. if ( depthTexture ) {
  30612. this._destroyTexture( depthTexture );
  30613. }
  30614. this.delete( renderTarget );
  30615. };
  30616. renderTarget.addEventListener( 'dispose', onDispose );
  30617. }
  30618. }
  30619. updateTexture( texture, options = {} ) {
  30620. const textureData = this.get( texture );
  30621. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  30622. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  30623. const backend = this.backend;
  30624. if ( isRenderTarget && textureData.initialized === true ) {
  30625. // it's an update
  30626. backend.destroySampler( texture );
  30627. backend.destroyTexture( texture );
  30628. }
  30629. //
  30630. if ( texture.isFramebufferTexture ) {
  30631. const renderTarget = this.renderer.getRenderTarget();
  30632. if ( renderTarget ) {
  30633. texture.type = renderTarget.texture.type;
  30634. } else {
  30635. texture.type = UnsignedByteType;
  30636. }
  30637. }
  30638. //
  30639. const { width, height, depth } = this.getSize( texture );
  30640. options.width = width;
  30641. options.height = height;
  30642. options.depth = depth;
  30643. options.needsMipmaps = this.needsMipmaps( texture );
  30644. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  30645. //
  30646. if ( isRenderTarget || texture.isStorageTexture === true ) {
  30647. backend.createSampler( texture );
  30648. backend.createTexture( texture, options );
  30649. textureData.generation = texture.version;
  30650. } else {
  30651. const needsCreate = textureData.initialized !== true;
  30652. if ( needsCreate ) backend.createSampler( texture );
  30653. if ( texture.version > 0 ) {
  30654. const image = texture.image;
  30655. if ( image === undefined ) {
  30656. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  30657. } else if ( image.complete === false ) {
  30658. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  30659. } else {
  30660. if ( texture.images ) {
  30661. const images = [];
  30662. for ( const image of texture.images ) {
  30663. images.push( image );
  30664. }
  30665. options.images = images;
  30666. } else {
  30667. options.image = image;
  30668. }
  30669. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  30670. backend.createTexture( texture, options );
  30671. textureData.isDefaultTexture = false;
  30672. textureData.generation = texture.version;
  30673. }
  30674. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  30675. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  30676. }
  30677. } else {
  30678. // async update
  30679. backend.createDefaultTexture( texture );
  30680. textureData.isDefaultTexture = true;
  30681. textureData.generation = texture.version;
  30682. }
  30683. }
  30684. // dispose handler
  30685. if ( textureData.initialized !== true ) {
  30686. textureData.initialized = true;
  30687. textureData.generation = texture.version;
  30688. //
  30689. this.info.memory.textures ++;
  30690. // dispose
  30691. const onDispose = () => {
  30692. texture.removeEventListener( 'dispose', onDispose );
  30693. this._destroyTexture( texture );
  30694. this.info.memory.textures --;
  30695. };
  30696. texture.addEventListener( 'dispose', onDispose );
  30697. }
  30698. //
  30699. textureData.version = texture.version;
  30700. }
  30701. getSize( texture, target = _size$3 ) {
  30702. let image = texture.images ? texture.images[ 0 ] : texture.image;
  30703. if ( image ) {
  30704. if ( image.image !== undefined ) image = image.image;
  30705. target.width = image.width;
  30706. target.height = image.height;
  30707. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  30708. } else {
  30709. target.width = target.height = target.depth = 1;
  30710. }
  30711. return target;
  30712. }
  30713. getMipLevels( texture, width, height ) {
  30714. let mipLevelCount;
  30715. if ( texture.isCompressedTexture ) {
  30716. mipLevelCount = texture.mipmaps.length;
  30717. } else {
  30718. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  30719. }
  30720. return mipLevelCount;
  30721. }
  30722. needsMipmaps( texture ) {
  30723. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  30724. }
  30725. isEnvironmentTexture( texture ) {
  30726. const mapping = texture.mapping;
  30727. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  30728. }
  30729. _destroyTexture( texture ) {
  30730. this.backend.destroySampler( texture );
  30731. this.backend.destroyTexture( texture );
  30732. this.delete( texture );
  30733. }
  30734. }
  30735. class Color4 extends Color {
  30736. constructor( r, g, b, a = 1 ) {
  30737. super( r, g, b );
  30738. this.a = a;
  30739. }
  30740. set( r, g, b, a = 1 ) {
  30741. this.a = a;
  30742. return super.set( r, g, b );
  30743. }
  30744. copy( color ) {
  30745. if ( color.a !== undefined ) this.a = color.a;
  30746. return super.copy( color );
  30747. }
  30748. clone() {
  30749. return new this.constructor( this.r, this.g, this.b, this.a );
  30750. }
  30751. }
  30752. class ParameterNode extends PropertyNode {
  30753. static get type() {
  30754. return 'ParameterNode';
  30755. }
  30756. constructor( nodeType, name = null ) {
  30757. super( nodeType, name );
  30758. this.isParameterNode = true;
  30759. }
  30760. getHash() {
  30761. return this.uuid;
  30762. }
  30763. generate() {
  30764. return this.name;
  30765. }
  30766. }
  30767. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  30768. class StackNode extends Node {
  30769. static get type() {
  30770. return 'StackNode';
  30771. }
  30772. constructor( parent = null ) {
  30773. super();
  30774. this.nodes = [];
  30775. this.outputNode = null;
  30776. this.parent = parent;
  30777. this._currentCond = null;
  30778. this.isStackNode = true;
  30779. }
  30780. getNodeType( builder ) {
  30781. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  30782. }
  30783. add( node ) {
  30784. this.nodes.push( node );
  30785. return this;
  30786. }
  30787. If( boolNode, method ) {
  30788. const methodNode = new ShaderNode( method );
  30789. this._currentCond = select( boolNode, methodNode );
  30790. return this.add( this._currentCond );
  30791. }
  30792. ElseIf( boolNode, method ) {
  30793. const methodNode = new ShaderNode( method );
  30794. const ifNode = select( boolNode, methodNode );
  30795. this._currentCond.elseNode = ifNode;
  30796. this._currentCond = ifNode;
  30797. return this;
  30798. }
  30799. Else( method ) {
  30800. this._currentCond.elseNode = new ShaderNode( method );
  30801. return this;
  30802. }
  30803. build( builder, ...params ) {
  30804. const previousStack = getCurrentStack();
  30805. setCurrentStack( this );
  30806. for ( const node of this.nodes ) {
  30807. node.build( builder, 'void' );
  30808. }
  30809. setCurrentStack( previousStack );
  30810. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  30811. }
  30812. //
  30813. else( ...params ) { // @deprecated, r168
  30814. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  30815. return this.Else( ...params );
  30816. }
  30817. elseif( ...params ) { // @deprecated, r168
  30818. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  30819. return this.ElseIf( ...params );
  30820. }
  30821. }
  30822. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  30823. class StructTypeNode extends Node {
  30824. static get type() {
  30825. return 'StructTypeNode';
  30826. }
  30827. constructor( types ) {
  30828. super();
  30829. this.types = types;
  30830. this.isStructTypeNode = true;
  30831. }
  30832. getMemberTypes() {
  30833. return this.types;
  30834. }
  30835. }
  30836. class OutputStructNode extends Node {
  30837. static get type() {
  30838. return 'OutputStructNode';
  30839. }
  30840. constructor( ...members ) {
  30841. super();
  30842. this.members = members;
  30843. this.isOutputStructNode = true;
  30844. }
  30845. setup( builder ) {
  30846. super.setup( builder );
  30847. const members = this.members;
  30848. const types = [];
  30849. for ( let i = 0; i < members.length; i ++ ) {
  30850. types.push( members[ i ].getNodeType( builder ) );
  30851. }
  30852. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  30853. }
  30854. generate( builder, output ) {
  30855. const propertyName = builder.getOutputStructName();
  30856. const members = this.members;
  30857. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  30858. for ( let i = 0; i < members.length; i ++ ) {
  30859. const snippet = members[ i ].build( builder, output );
  30860. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  30861. }
  30862. return propertyName;
  30863. }
  30864. }
  30865. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  30866. function getTextureIndex( textures, name ) {
  30867. for ( let i = 0; i < textures.length; i ++ ) {
  30868. if ( textures[ i ].name === name ) {
  30869. return i;
  30870. }
  30871. }
  30872. return - 1;
  30873. }
  30874. class MRTNode extends OutputStructNode {
  30875. static get type() {
  30876. return 'MRTNode';
  30877. }
  30878. constructor( outputNodes ) {
  30879. super();
  30880. this.outputNodes = outputNodes;
  30881. this.isMRTNode = true;
  30882. }
  30883. has( name ) {
  30884. return this.outputNodes[ name ] !== undefined;
  30885. }
  30886. get( name ) {
  30887. return this.outputNodes[ name ];
  30888. }
  30889. merge( mrtNode ) {
  30890. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  30891. return mrt( outputs );
  30892. }
  30893. setup( builder ) {
  30894. const outputNodes = this.outputNodes;
  30895. const mrt = builder.renderer.getRenderTarget();
  30896. const members = [];
  30897. const textures = mrt.textures;
  30898. for ( const name in outputNodes ) {
  30899. const index = getTextureIndex( textures, name );
  30900. members[ index ] = vec4( outputNodes[ name ] );
  30901. }
  30902. this.members = members;
  30903. return super.setup( builder );
  30904. }
  30905. }
  30906. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  30907. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  30908. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  30909. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  30910. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  30911. const result = word.shiftRight( 22 ).bitXor( word );
  30912. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  30913. } );
  30914. // remapping functions https://iquilezles.org/articles/functions/
  30915. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  30916. 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 ) );
  30917. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  30918. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  30919. // https://github.com/cabbibo/glsl-tri-noise-3d
  30920. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  30921. return x.fract().sub( .5 ).abs();
  30922. } ).setLayout( {
  30923. name: 'tri',
  30924. type: 'float',
  30925. inputs: [
  30926. { name: 'x', type: 'float' }
  30927. ]
  30928. } );
  30929. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  30930. 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. ) ) ) ) );
  30931. } ).setLayout( {
  30932. name: 'tri3',
  30933. type: 'vec3',
  30934. inputs: [
  30935. { name: 'p', type: 'vec3' }
  30936. ]
  30937. } );
  30938. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  30939. const p = vec3( p_immutable ).toVar();
  30940. const z = float( 1.4 ).toVar();
  30941. const rz = float( 0.0 ).toVar();
  30942. const bp = vec3( p ).toVar();
  30943. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  30944. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  30945. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  30946. bp.mulAssign( 1.8 );
  30947. z.mulAssign( 1.5 );
  30948. p.mulAssign( 1.2 );
  30949. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  30950. rz.addAssign( t.div( z ) );
  30951. bp.addAssign( 0.14 );
  30952. } );
  30953. return rz;
  30954. } ).setLayout( {
  30955. name: 'triNoise3D',
  30956. type: 'float',
  30957. inputs: [
  30958. { name: 'p', type: 'vec3' },
  30959. { name: 'spd', type: 'float' },
  30960. { name: 'time', type: 'float' }
  30961. ]
  30962. } );
  30963. class FunctionOverloadingNode extends Node {
  30964. static get type() {
  30965. return 'FunctionOverloadingNode';
  30966. }
  30967. constructor( functionNodes = [], ...parametersNodes ) {
  30968. super();
  30969. this.functionNodes = functionNodes;
  30970. this.parametersNodes = parametersNodes;
  30971. this._candidateFnCall = null;
  30972. this.global = true;
  30973. }
  30974. getNodeType() {
  30975. return this.functionNodes[ 0 ].shaderNode.layout.type;
  30976. }
  30977. setup( builder ) {
  30978. const params = this.parametersNodes;
  30979. let candidateFnCall = this._candidateFnCall;
  30980. if ( candidateFnCall === null ) {
  30981. let candidateFn = null;
  30982. let candidateScore = - 1;
  30983. for ( const functionNode of this.functionNodes ) {
  30984. const shaderNode = functionNode.shaderNode;
  30985. const layout = shaderNode.layout;
  30986. if ( layout === null ) {
  30987. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  30988. }
  30989. const inputs = layout.inputs;
  30990. if ( params.length === inputs.length ) {
  30991. let score = 0;
  30992. for ( let i = 0; i < params.length; i ++ ) {
  30993. const param = params[ i ];
  30994. const input = inputs[ i ];
  30995. if ( param.getNodeType( builder ) === input.type ) {
  30996. score ++;
  30997. } else {
  30998. score = 0;
  30999. }
  31000. }
  31001. if ( score > candidateScore ) {
  31002. candidateFn = functionNode;
  31003. candidateScore = score;
  31004. }
  31005. }
  31006. }
  31007. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  31008. }
  31009. return candidateFnCall;
  31010. }
  31011. }
  31012. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  31013. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  31014. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  31015. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  31016. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  31017. // Deprecated
  31018. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  31019. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  31020. return time.mul( timeScale );
  31021. };
  31022. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  31023. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  31024. return time.mul( timeScale );
  31025. };
  31026. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  31027. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  31028. return deltaTime.mul( timeScale );
  31029. };
  31030. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  31031. const oscSquare = ( t = time ) => t.fract().round();
  31032. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  31033. const oscSawtooth = ( t = time ) => t.fract();
  31034. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  31035. return rotate( uv.sub( center ), rotation ).add( center );
  31036. } );
  31037. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  31038. const delta = uv.sub( center );
  31039. const delta2 = delta.dot( delta );
  31040. const delta4 = delta2.mul( delta2 );
  31041. const deltaOffset = delta4.mul( strength );
  31042. return uv.add( delta.mul( deltaOffset ) );
  31043. } );
  31044. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  31045. let worldMatrix;
  31046. if ( position !== null ) {
  31047. worldMatrix = modelWorldMatrix.toVar();
  31048. worldMatrix[ 3 ][ 0 ] = position.x;
  31049. worldMatrix[ 3 ][ 1 ] = position.y;
  31050. worldMatrix[ 3 ][ 2 ] = position.z;
  31051. } else {
  31052. worldMatrix = modelWorldMatrix;
  31053. }
  31054. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  31055. if ( defined( horizontal ) ) {
  31056. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  31057. modelViewMatrix[ 0 ][ 1 ] = 0;
  31058. modelViewMatrix[ 0 ][ 2 ] = 0;
  31059. }
  31060. if ( defined( vertical ) ) {
  31061. modelViewMatrix[ 1 ][ 0 ] = 0;
  31062. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  31063. modelViewMatrix[ 1 ][ 2 ] = 0;
  31064. }
  31065. modelViewMatrix[ 2 ][ 0 ] = 0;
  31066. modelViewMatrix[ 2 ][ 1 ] = 0;
  31067. modelViewMatrix[ 2 ][ 2 ] = 1;
  31068. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  31069. } );
  31070. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  31071. const depth = linearDepth();
  31072. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  31073. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  31074. return finalUV;
  31075. } );
  31076. class SpriteSheetUVNode extends Node {
  31077. static get type() {
  31078. return 'SpriteSheetUVNode';
  31079. }
  31080. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  31081. super( 'vec2' );
  31082. this.countNode = countNode;
  31083. this.uvNode = uvNode;
  31084. this.frameNode = frameNode;
  31085. }
  31086. setup() {
  31087. const { frameNode, uvNode, countNode } = this;
  31088. const { width, height } = countNode;
  31089. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  31090. const column = frameNum.mod( width );
  31091. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  31092. const scale = countNode.reciprocal();
  31093. const uvFrameOffset = vec2( column, row );
  31094. return uvNode.add( uvFrameOffset ).mul( scale );
  31095. }
  31096. }
  31097. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  31098. class TriplanarTexturesNode extends Node {
  31099. static get type() {
  31100. return 'TriplanarTexturesNode';
  31101. }
  31102. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  31103. super( 'vec4' );
  31104. this.textureXNode = textureXNode;
  31105. this.textureYNode = textureYNode;
  31106. this.textureZNode = textureZNode;
  31107. this.scaleNode = scaleNode;
  31108. this.positionNode = positionNode;
  31109. this.normalNode = normalNode;
  31110. }
  31111. setup() {
  31112. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  31113. // Ref: https://github.com/keijiro/StandardTriplanar
  31114. // Blending factor of triplanar mapping
  31115. let bf = normalNode.abs().normalize();
  31116. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  31117. // Triplanar mapping
  31118. const tx = positionNode.yz.mul( scaleNode );
  31119. const ty = positionNode.zx.mul( scaleNode );
  31120. const tz = positionNode.xy.mul( scaleNode );
  31121. // Base color
  31122. const textureX = textureXNode.value;
  31123. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  31124. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  31125. const cx = texture( textureX, tx ).mul( bf.x );
  31126. const cy = texture( textureY, ty ).mul( bf.y );
  31127. const cz = texture( textureZ, tz ).mul( bf.z );
  31128. return add( cx, cy, cz );
  31129. }
  31130. }
  31131. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  31132. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  31133. const _reflectorPlane = new Plane();
  31134. const _normal = new Vector3();
  31135. const _reflectorWorldPosition = new Vector3();
  31136. const _cameraWorldPosition = new Vector3();
  31137. const _rotationMatrix = new Matrix4();
  31138. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  31139. const clipPlane = new Vector4();
  31140. const _view = new Vector3();
  31141. const _target = new Vector3();
  31142. const _q = new Vector4();
  31143. const _size$2 = new Vector2();
  31144. const _defaultRT = new RenderTarget();
  31145. const _defaultUV = screenUV.flipX();
  31146. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  31147. let _inReflector = false;
  31148. class ReflectorNode extends TextureNode {
  31149. static get type() {
  31150. return 'ReflectorNode';
  31151. }
  31152. constructor( parameters = {} ) {
  31153. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  31154. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  31155. this._depthNode = null;
  31156. this.setUpdateMatrix( false );
  31157. }
  31158. get reflector() {
  31159. return this._reflectorBaseNode;
  31160. }
  31161. get target() {
  31162. return this._reflectorBaseNode.target;
  31163. }
  31164. getDepthNode() {
  31165. if ( this._depthNode === null ) {
  31166. if ( this._reflectorBaseNode.depth !== true ) {
  31167. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  31168. }
  31169. this._depthNode = nodeObject( new ReflectorNode( {
  31170. defaultTexture: _defaultRT.depthTexture,
  31171. reflector: this._reflectorBaseNode
  31172. } ) );
  31173. }
  31174. return this._depthNode;
  31175. }
  31176. setup( builder ) {
  31177. // ignore if used in post-processing
  31178. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  31179. return super.setup( builder );
  31180. }
  31181. clone() {
  31182. const texture = new this.constructor( this.reflectorNode );
  31183. texture._reflectorBaseNode = this._reflectorBaseNode;
  31184. return texture;
  31185. }
  31186. }
  31187. class ReflectorBaseNode extends Node {
  31188. static get type() {
  31189. return 'ReflectorBaseNode';
  31190. }
  31191. constructor( textureNode, parameters = {} ) {
  31192. super();
  31193. const {
  31194. target = new Object3D(),
  31195. resolution = 1,
  31196. generateMipmaps = false,
  31197. bounces = true,
  31198. depth = false
  31199. } = parameters;
  31200. //
  31201. this.textureNode = textureNode;
  31202. this.target = target;
  31203. this.resolution = resolution;
  31204. this.generateMipmaps = generateMipmaps;
  31205. this.bounces = bounces;
  31206. this.depth = depth;
  31207. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  31208. this.virtualCameras = new WeakMap();
  31209. this.renderTargets = new WeakMap();
  31210. }
  31211. _updateResolution( renderTarget, renderer ) {
  31212. const resolution = this.resolution;
  31213. renderer.getDrawingBufferSize( _size$2 );
  31214. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  31215. }
  31216. setup( builder ) {
  31217. this._updateResolution( _defaultRT, builder.renderer );
  31218. return super.setup( builder );
  31219. }
  31220. getVirtualCamera( camera ) {
  31221. let virtualCamera = this.virtualCameras.get( camera );
  31222. if ( virtualCamera === undefined ) {
  31223. virtualCamera = camera.clone();
  31224. this.virtualCameras.set( camera, virtualCamera );
  31225. }
  31226. return virtualCamera;
  31227. }
  31228. getRenderTarget( camera ) {
  31229. let renderTarget = this.renderTargets.get( camera );
  31230. if ( renderTarget === undefined ) {
  31231. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  31232. if ( this.generateMipmaps === true ) {
  31233. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  31234. renderTarget.texture.generateMipmaps = true;
  31235. }
  31236. if ( this.depth === true ) {
  31237. renderTarget.depthTexture = new DepthTexture();
  31238. }
  31239. this.renderTargets.set( camera, renderTarget );
  31240. }
  31241. return renderTarget;
  31242. }
  31243. updateBefore( frame ) {
  31244. if ( this.bounces === false && _inReflector ) return;
  31245. _inReflector = true;
  31246. const { scene, camera, renderer, material } = frame;
  31247. const { target } = this;
  31248. const virtualCamera = this.getVirtualCamera( camera );
  31249. const renderTarget = this.getRenderTarget( virtualCamera );
  31250. renderer.getDrawingBufferSize( _size$2 );
  31251. this._updateResolution( renderTarget, renderer );
  31252. //
  31253. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  31254. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  31255. _rotationMatrix.extractRotation( target.matrixWorld );
  31256. _normal.set( 0, 0, 1 );
  31257. _normal.applyMatrix4( _rotationMatrix );
  31258. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  31259. // Avoid rendering when reflector is facing away
  31260. if ( _view.dot( _normal ) > 0 ) return;
  31261. _view.reflect( _normal ).negate();
  31262. _view.add( _reflectorWorldPosition );
  31263. _rotationMatrix.extractRotation( camera.matrixWorld );
  31264. _lookAtPosition.set( 0, 0, - 1 );
  31265. _lookAtPosition.applyMatrix4( _rotationMatrix );
  31266. _lookAtPosition.add( _cameraWorldPosition );
  31267. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  31268. _target.reflect( _normal ).negate();
  31269. _target.add( _reflectorWorldPosition );
  31270. //
  31271. virtualCamera.coordinateSystem = camera.coordinateSystem;
  31272. virtualCamera.position.copy( _view );
  31273. virtualCamera.up.set( 0, 1, 0 );
  31274. virtualCamera.up.applyMatrix4( _rotationMatrix );
  31275. virtualCamera.up.reflect( _normal );
  31276. virtualCamera.lookAt( _target );
  31277. virtualCamera.near = camera.near;
  31278. virtualCamera.far = camera.far;
  31279. virtualCamera.updateMatrixWorld();
  31280. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  31281. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  31282. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  31283. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  31284. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  31285. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  31286. const projectionMatrix = virtualCamera.projectionMatrix;
  31287. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  31288. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  31289. _q.z = - 1.0;
  31290. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  31291. // Calculate the scaled plane vector
  31292. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  31293. const clipBias = 0;
  31294. // Replacing the third row of the projection matrix
  31295. projectionMatrix.elements[ 2 ] = clipPlane.x;
  31296. projectionMatrix.elements[ 6 ] = clipPlane.y;
  31297. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  31298. projectionMatrix.elements[ 14 ] = clipPlane.w;
  31299. //
  31300. this.textureNode.value = renderTarget.texture;
  31301. if ( this.depth === true ) {
  31302. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  31303. }
  31304. material.visible = false;
  31305. const currentRenderTarget = renderer.getRenderTarget();
  31306. const currentMRT = renderer.getMRT();
  31307. renderer.setMRT( null );
  31308. renderer.setRenderTarget( renderTarget );
  31309. renderer.render( scene, virtualCamera );
  31310. renderer.setMRT( currentMRT );
  31311. renderer.setRenderTarget( currentRenderTarget );
  31312. material.visible = true;
  31313. _inReflector = false;
  31314. }
  31315. }
  31316. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  31317. // Helper for passes that need to fill the viewport with a single quad.
  31318. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  31319. // https://github.com/mrdoob/three.js/pull/21358
  31320. class QuadGeometry extends BufferGeometry {
  31321. constructor( flipY = false ) {
  31322. super();
  31323. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  31324. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  31325. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  31326. }
  31327. }
  31328. const _geometry = /*@__PURE__*/ new QuadGeometry();
  31329. class QuadMesh extends Mesh {
  31330. constructor( material = null ) {
  31331. super( _geometry, material );
  31332. this.camera = _camera;
  31333. this.isQuadMesh = true;
  31334. }
  31335. renderAsync( renderer ) {
  31336. return renderer.renderAsync( this, _camera );
  31337. }
  31338. render( renderer ) {
  31339. renderer.render( this, _camera );
  31340. }
  31341. }
  31342. const _size$1 = /*@__PURE__*/ new Vector2();
  31343. class RTTNode extends TextureNode {
  31344. static get type() {
  31345. return 'RTTNode';
  31346. }
  31347. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  31348. const renderTarget = new RenderTarget( width, height, options );
  31349. super( renderTarget.texture, uv() );
  31350. this.node = node;
  31351. this.width = width;
  31352. this.height = height;
  31353. this.renderTarget = renderTarget;
  31354. this.textureNeedsUpdate = true;
  31355. this.autoUpdate = true;
  31356. this.updateMap = new WeakMap();
  31357. this._rttNode = null;
  31358. this._quadMesh = new QuadMesh( new NodeMaterial() );
  31359. this.updateBeforeType = NodeUpdateType.RENDER;
  31360. }
  31361. get autoSize() {
  31362. return this.width === null;
  31363. }
  31364. setup( builder ) {
  31365. this._rttNode = this.node.context( builder.getSharedContext() );
  31366. this._quadMesh.material.name = 'RTT';
  31367. this._quadMesh.material.needsUpdate = true;
  31368. return super.setup( builder );
  31369. }
  31370. setSize( width, height ) {
  31371. this.width = width;
  31372. this.height = height;
  31373. const effectiveWidth = width * this.pixelRatio;
  31374. const effectiveHeight = height * this.pixelRatio;
  31375. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  31376. this.textureNeedsUpdate = true;
  31377. }
  31378. setPixelRatio( pixelRatio ) {
  31379. this.pixelRatio = pixelRatio;
  31380. this.setSize( this.width, this.height );
  31381. }
  31382. updateBefore( { renderer } ) {
  31383. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  31384. this.textureNeedsUpdate = false;
  31385. //
  31386. if ( this.autoSize === true ) {
  31387. this.pixelRatio = renderer.getPixelRatio();
  31388. const size = renderer.getSize( _size$1 );
  31389. this.setSize( size.width, size.height );
  31390. }
  31391. //
  31392. this._quadMesh.material.fragmentNode = this._rttNode;
  31393. //
  31394. const currentRenderTarget = renderer.getRenderTarget();
  31395. renderer.setRenderTarget( this.renderTarget );
  31396. this._quadMesh.render( renderer );
  31397. renderer.setRenderTarget( currentRenderTarget );
  31398. }
  31399. clone() {
  31400. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  31401. newNode.sampler = this.sampler;
  31402. newNode.referenceNode = this;
  31403. return newNode;
  31404. }
  31405. }
  31406. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  31407. const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params );
  31408. /**
  31409. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  31410. * depth value and the camera's inverse projection matrix.
  31411. *
  31412. * @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates.
  31413. * @param {float} depth - The fragment's depth value.
  31414. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  31415. * @return {vec3} The fragments position in view space.
  31416. */
  31417. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  31418. let clipSpacePosition;
  31419. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  31420. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  31421. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  31422. } else {
  31423. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  31424. }
  31425. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  31426. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  31427. } );
  31428. /**
  31429. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  31430. * and the camera's projection matrix
  31431. *
  31432. * @param {vec3} viewPosition - The fragments position in view space.
  31433. * @param {mat4} projectionMatrix - The camera's projection matrix.
  31434. * @return {vec2} The fragment's screen position expressed as uv coordinates.
  31435. */
  31436. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  31437. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  31438. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  31439. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  31440. } );
  31441. /**
  31442. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  31443. * target is available or if flat surface normals are required.
  31444. *
  31445. * @param {vec2} uv - The texture coordinate.
  31446. * @param {DepthTexture} depthTexture - The depth texture.
  31447. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  31448. * @return {vec3} The computed normal vector.
  31449. */
  31450. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  31451. const size = textureSize( textureLoad( depthTexture ) );
  31452. const p = ivec2( uv.mul( size ) ).toVar();
  31453. const c0 = textureLoad( depthTexture, p ).toVar();
  31454. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  31455. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  31456. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  31457. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  31458. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  31459. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  31460. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  31461. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  31462. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  31463. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  31464. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  31465. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  31466. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  31467. const dpdx = dl.lessThan( dr ).select( ce.sub( getViewPosition( uv.sub( vec2( float( 1 ).div( size.x ), 0 ) ), l1, projectionMatrixInverse ) ), ce.negate().add( getViewPosition( uv.add( vec2( float( 1 ).div( size.x ), 0 ) ), r1, projectionMatrixInverse ) ) );
  31468. const dpdy = db.lessThan( dt ).select( ce.sub( getViewPosition( uv.add( vec2( 0, float( 1 ).div( size.y ) ) ), b1, projectionMatrixInverse ) ), ce.negate().add( getViewPosition( uv.sub( vec2( 0, float( 1 ).div( size.y ) ) ), t1, projectionMatrixInverse ) ) );
  31469. return normalize( cross( dpdx, dpdy ) );
  31470. } );
  31471. class VertexColorNode extends AttributeNode {
  31472. static get type() {
  31473. return 'VertexColorNode';
  31474. }
  31475. constructor( index = 0 ) {
  31476. super( null, 'vec4' );
  31477. this.isVertexColorNode = true;
  31478. this.index = index;
  31479. }
  31480. getAttributeName( /*builder*/ ) {
  31481. const index = this.index;
  31482. return 'color' + ( index > 0 ? index : '' );
  31483. }
  31484. generate( builder ) {
  31485. const attributeName = this.getAttributeName( builder );
  31486. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  31487. let result;
  31488. if ( geometryAttribute === true ) {
  31489. result = super.generate( builder );
  31490. } else {
  31491. // Vertex color fallback should be white
  31492. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  31493. }
  31494. return result;
  31495. }
  31496. serialize( data ) {
  31497. super.serialize( data );
  31498. data.index = this.index;
  31499. }
  31500. deserialize( data ) {
  31501. super.deserialize( data );
  31502. this.index = data.index;
  31503. }
  31504. }
  31505. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  31506. class PointUVNode extends Node {
  31507. static get type() {
  31508. return 'PointUVNode';
  31509. }
  31510. constructor() {
  31511. super( 'vec2' );
  31512. this.isPointUVNode = true;
  31513. }
  31514. generate( /*builder*/ ) {
  31515. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  31516. }
  31517. }
  31518. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  31519. const _e1 = /*@__PURE__*/ new Euler();
  31520. const _m1 = /*@__PURE__*/ new Matrix4();
  31521. class SceneNode extends Node {
  31522. static get type() {
  31523. return 'SceneNode';
  31524. }
  31525. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  31526. super();
  31527. this.scope = scope;
  31528. this.scene = scene;
  31529. }
  31530. setup( builder ) {
  31531. const scope = this.scope;
  31532. const scene = this.scene !== null ? this.scene : builder.scene;
  31533. let output;
  31534. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  31535. output = reference( 'backgroundBlurriness', 'float', scene );
  31536. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  31537. output = reference( 'backgroundIntensity', 'float', scene );
  31538. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  31539. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  31540. const background = scene.background;
  31541. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  31542. _e1.copy( scene.backgroundRotation );
  31543. // accommodate left-handed frame
  31544. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  31545. _m1.makeRotationFromEuler( _e1 );
  31546. } else {
  31547. _m1.identity();
  31548. }
  31549. return _m1;
  31550. } );
  31551. } else {
  31552. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  31553. }
  31554. return output;
  31555. }
  31556. }
  31557. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  31558. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  31559. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  31560. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  31561. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  31562. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  31563. class StorageArrayElementNode extends ArrayElementNode {
  31564. static get type() {
  31565. return 'StorageArrayElementNode';
  31566. }
  31567. constructor( storageBufferNode, indexNode ) {
  31568. super( storageBufferNode, indexNode );
  31569. this.isStorageArrayElementNode = true;
  31570. }
  31571. set storageBufferNode( value ) {
  31572. this.node = value;
  31573. }
  31574. get storageBufferNode() {
  31575. return this.node;
  31576. }
  31577. setup( builder ) {
  31578. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  31579. if ( this.node.bufferObject === true ) {
  31580. builder.setupPBO( this.node );
  31581. }
  31582. }
  31583. return super.setup( builder );
  31584. }
  31585. generate( builder, output ) {
  31586. let snippet;
  31587. const isAssignContext = builder.context.assign;
  31588. //
  31589. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  31590. if ( this.node.bufferObject === true && isAssignContext !== true ) {
  31591. snippet = builder.generatePBO( this );
  31592. } else {
  31593. snippet = this.node.build( builder );
  31594. }
  31595. } else {
  31596. snippet = super.generate( builder );
  31597. }
  31598. if ( isAssignContext !== true ) {
  31599. const type = this.getNodeType( builder );
  31600. snippet = builder.format( snippet, type, output );
  31601. }
  31602. return snippet;
  31603. }
  31604. }
  31605. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  31606. const GPUPrimitiveTopology = {
  31607. PointList: 'point-list',
  31608. LineList: 'line-list',
  31609. LineStrip: 'line-strip',
  31610. TriangleList: 'triangle-list',
  31611. TriangleStrip: 'triangle-strip',
  31612. };
  31613. const GPUCompareFunction = {
  31614. Never: 'never',
  31615. Less: 'less',
  31616. Equal: 'equal',
  31617. LessEqual: 'less-equal',
  31618. Greater: 'greater',
  31619. NotEqual: 'not-equal',
  31620. GreaterEqual: 'greater-equal',
  31621. Always: 'always'
  31622. };
  31623. const GPUStoreOp = {
  31624. Store: 'store',
  31625. Discard: 'discard'
  31626. };
  31627. const GPULoadOp = {
  31628. Load: 'load',
  31629. Clear: 'clear'
  31630. };
  31631. const GPUFrontFace = {
  31632. CCW: 'ccw',
  31633. CW: 'cw'
  31634. };
  31635. const GPUCullMode = {
  31636. None: 'none',
  31637. Front: 'front',
  31638. Back: 'back'
  31639. };
  31640. const GPUIndexFormat = {
  31641. Uint16: 'uint16',
  31642. Uint32: 'uint32'
  31643. };
  31644. const GPUTextureFormat = {
  31645. // 8-bit formats
  31646. R8Unorm: 'r8unorm',
  31647. R8Snorm: 'r8snorm',
  31648. R8Uint: 'r8uint',
  31649. R8Sint: 'r8sint',
  31650. // 16-bit formats
  31651. R16Uint: 'r16uint',
  31652. R16Sint: 'r16sint',
  31653. R16Float: 'r16float',
  31654. RG8Unorm: 'rg8unorm',
  31655. RG8Snorm: 'rg8snorm',
  31656. RG8Uint: 'rg8uint',
  31657. RG8Sint: 'rg8sint',
  31658. // 32-bit formats
  31659. R32Uint: 'r32uint',
  31660. R32Sint: 'r32sint',
  31661. R32Float: 'r32float',
  31662. RG16Uint: 'rg16uint',
  31663. RG16Sint: 'rg16sint',
  31664. RG16Float: 'rg16float',
  31665. RGBA8Unorm: 'rgba8unorm',
  31666. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  31667. RGBA8Snorm: 'rgba8snorm',
  31668. RGBA8Uint: 'rgba8uint',
  31669. RGBA8Sint: 'rgba8sint',
  31670. BGRA8Unorm: 'bgra8unorm',
  31671. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  31672. // Packed 32-bit formats
  31673. RGB9E5UFloat: 'rgb9e5ufloat',
  31674. RGB10A2Unorm: 'rgb10a2unorm',
  31675. RG11B10uFloat: 'rgb10a2unorm',
  31676. // 64-bit formats
  31677. RG32Uint: 'rg32uint',
  31678. RG32Sint: 'rg32sint',
  31679. RG32Float: 'rg32float',
  31680. RGBA16Uint: 'rgba16uint',
  31681. RGBA16Sint: 'rgba16sint',
  31682. RGBA16Float: 'rgba16float',
  31683. // 128-bit formats
  31684. RGBA32Uint: 'rgba32uint',
  31685. RGBA32Sint: 'rgba32sint',
  31686. RGBA32Float: 'rgba32float',
  31687. // Depth and stencil formats
  31688. Stencil8: 'stencil8',
  31689. Depth16Unorm: 'depth16unorm',
  31690. Depth24Plus: 'depth24plus',
  31691. Depth24PlusStencil8: 'depth24plus-stencil8',
  31692. Depth32Float: 'depth32float',
  31693. // 'depth32float-stencil8' extension
  31694. Depth32FloatStencil8: 'depth32float-stencil8',
  31695. // BC compressed formats usable if 'texture-compression-bc' is both
  31696. // supported by the device/user agent and enabled in requestDevice.
  31697. BC1RGBAUnorm: 'bc1-rgba-unorm',
  31698. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  31699. BC2RGBAUnorm: 'bc2-rgba-unorm',
  31700. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  31701. BC3RGBAUnorm: 'bc3-rgba-unorm',
  31702. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  31703. BC4RUnorm: 'bc4-r-unorm',
  31704. BC4RSnorm: 'bc4-r-snorm',
  31705. BC5RGUnorm: 'bc5-rg-unorm',
  31706. BC5RGSnorm: 'bc5-rg-snorm',
  31707. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  31708. BC6HRGBFloat: 'bc6h-rgb-float',
  31709. BC7RGBAUnorm: 'bc7-rgba-unorm',
  31710. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  31711. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  31712. // supported by the device/user agent and enabled in requestDevice.
  31713. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  31714. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  31715. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  31716. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  31717. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  31718. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  31719. EACR11Unorm: 'eac-r11unorm',
  31720. EACR11Snorm: 'eac-r11snorm',
  31721. EACRG11Unorm: 'eac-rg11unorm',
  31722. EACRG11Snorm: 'eac-rg11snorm',
  31723. // ASTC compressed formats usable if 'texture-compression-astc' is both
  31724. // supported by the device/user agent and enabled in requestDevice.
  31725. ASTC4x4Unorm: 'astc-4x4-unorm',
  31726. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  31727. ASTC5x4Unorm: 'astc-5x4-unorm',
  31728. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  31729. ASTC5x5Unorm: 'astc-5x5-unorm',
  31730. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  31731. ASTC6x5Unorm: 'astc-6x5-unorm',
  31732. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  31733. ASTC6x6Unorm: 'astc-6x6-unorm',
  31734. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  31735. ASTC8x5Unorm: 'astc-8x5-unorm',
  31736. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  31737. ASTC8x6Unorm: 'astc-8x6-unorm',
  31738. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  31739. ASTC8x8Unorm: 'astc-8x8-unorm',
  31740. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  31741. ASTC10x5Unorm: 'astc-10x5-unorm',
  31742. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  31743. ASTC10x6Unorm: 'astc-10x6-unorm',
  31744. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  31745. ASTC10x8Unorm: 'astc-10x8-unorm',
  31746. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  31747. ASTC10x10Unorm: 'astc-10x10-unorm',
  31748. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  31749. ASTC12x10Unorm: 'astc-12x10-unorm',
  31750. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  31751. ASTC12x12Unorm: 'astc-12x12-unorm',
  31752. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  31753. };
  31754. const GPUAddressMode = {
  31755. ClampToEdge: 'clamp-to-edge',
  31756. Repeat: 'repeat',
  31757. MirrorRepeat: 'mirror-repeat'
  31758. };
  31759. const GPUFilterMode = {
  31760. Linear: 'linear',
  31761. Nearest: 'nearest'
  31762. };
  31763. const GPUBlendFactor = {
  31764. Zero: 'zero',
  31765. One: 'one',
  31766. Src: 'src',
  31767. OneMinusSrc: 'one-minus-src',
  31768. SrcAlpha: 'src-alpha',
  31769. OneMinusSrcAlpha: 'one-minus-src-alpha',
  31770. Dst: 'dst',
  31771. OneMinusDstColor: 'one-minus-dst',
  31772. DstAlpha: 'dst-alpha',
  31773. OneMinusDstAlpha: 'one-minus-dst-alpha',
  31774. SrcAlphaSaturated: 'src-alpha-saturated',
  31775. Constant: 'constant',
  31776. OneMinusConstant: 'one-minus-constant'
  31777. };
  31778. const GPUBlendOperation = {
  31779. Add: 'add',
  31780. Subtract: 'subtract',
  31781. ReverseSubtract: 'reverse-subtract',
  31782. Min: 'min',
  31783. Max: 'max'
  31784. };
  31785. const GPUColorWriteFlags = {
  31786. None: 0,
  31787. Red: 0x1,
  31788. Green: 0x2,
  31789. Blue: 0x4,
  31790. Alpha: 0x8,
  31791. All: 0xF
  31792. };
  31793. const GPUStencilOperation = {
  31794. Keep: 'keep',
  31795. Zero: 'zero',
  31796. Replace: 'replace',
  31797. Invert: 'invert',
  31798. IncrementClamp: 'increment-clamp',
  31799. DecrementClamp: 'decrement-clamp',
  31800. IncrementWrap: 'increment-wrap',
  31801. DecrementWrap: 'decrement-wrap'
  31802. };
  31803. const GPUBufferBindingType = {
  31804. Uniform: 'uniform',
  31805. Storage: 'storage',
  31806. ReadOnlyStorage: 'read-only-storage'
  31807. };
  31808. const GPUStorageTextureAccess = {
  31809. WriteOnly: 'write-only',
  31810. ReadOnly: 'read-only',
  31811. ReadWrite: 'read-write',
  31812. };
  31813. const GPUTextureSampleType = {
  31814. Float: 'float',
  31815. UnfilterableFloat: 'unfilterable-float',
  31816. Depth: 'depth',
  31817. SInt: 'sint',
  31818. UInt: 'uint'
  31819. };
  31820. const GPUTextureDimension = {
  31821. OneD: '1d',
  31822. TwoD: '2d',
  31823. ThreeD: '3d'
  31824. };
  31825. const GPUTextureViewDimension = {
  31826. OneD: '1d',
  31827. TwoD: '2d',
  31828. TwoDArray: '2d-array',
  31829. Cube: 'cube',
  31830. CubeArray: 'cube-array',
  31831. ThreeD: '3d'
  31832. };
  31833. const GPUTextureAspect = {
  31834. All: 'all',
  31835. StencilOnly: 'stencil-only',
  31836. DepthOnly: 'depth-only'
  31837. };
  31838. const GPUInputStepMode = {
  31839. Vertex: 'vertex',
  31840. Instance: 'instance'
  31841. };
  31842. const GPUFeatureName = {
  31843. DepthClipControl: 'depth-clip-control',
  31844. Depth32FloatStencil8: 'depth32float-stencil8',
  31845. TextureCompressionBC: 'texture-compression-bc',
  31846. TextureCompressionETC2: 'texture-compression-etc2',
  31847. TextureCompressionASTC: 'texture-compression-astc',
  31848. TimestampQuery: 'timestamp-query',
  31849. IndirectFirstInstance: 'indirect-first-instance',
  31850. ShaderF16: 'shader-f16',
  31851. RG11B10UFloat: 'rg11b10ufloat-renderable',
  31852. BGRA8UNormStorage: 'bgra8unorm-storage',
  31853. Float32Filterable: 'float32-filterable',
  31854. ClipDistances: 'clip-distances',
  31855. DualSourceBlending: 'dual-source-blending',
  31856. Subgroups: 'subgroups'
  31857. };
  31858. class StorageBufferNode extends BufferNode {
  31859. static get type() {
  31860. return 'StorageBufferNode';
  31861. }
  31862. constructor( value, bufferType, bufferCount = 0 ) {
  31863. super( value, bufferType, bufferCount );
  31864. this.isStorageBufferNode = true;
  31865. this.access = GPUBufferBindingType.Storage;
  31866. this.isAtomic = false;
  31867. this.bufferObject = false;
  31868. this.bufferCount = bufferCount;
  31869. this._attribute = null;
  31870. this._varying = null;
  31871. this.global = true;
  31872. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  31873. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  31874. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  31875. else value.isStorageBufferAttribute = true;
  31876. }
  31877. }
  31878. getHash( builder ) {
  31879. if ( this.bufferCount === 0 ) {
  31880. let bufferData = builder.globalCache.getData( this.value );
  31881. if ( bufferData === undefined ) {
  31882. bufferData = {
  31883. node: this
  31884. };
  31885. builder.globalCache.setData( this.value, bufferData );
  31886. }
  31887. return bufferData.node.uuid;
  31888. }
  31889. return this.uuid;
  31890. }
  31891. getInputType( /*builder*/ ) {
  31892. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  31893. }
  31894. element( indexNode ) {
  31895. return storageElement( this, indexNode );
  31896. }
  31897. setBufferObject( value ) {
  31898. this.bufferObject = value;
  31899. return this;
  31900. }
  31901. setAccess( value ) {
  31902. this.access = value;
  31903. return this;
  31904. }
  31905. toReadOnly() {
  31906. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  31907. }
  31908. setAtomic( value ) {
  31909. this.isAtomic = value;
  31910. return this;
  31911. }
  31912. toAtomic() {
  31913. return this.setAtomic( true );
  31914. }
  31915. getAttributeData() {
  31916. if ( this._attribute === null ) {
  31917. this._attribute = bufferAttribute( this.value );
  31918. this._varying = varying( this._attribute );
  31919. }
  31920. return {
  31921. attribute: this._attribute,
  31922. varying: this._varying
  31923. };
  31924. }
  31925. getNodeType( builder ) {
  31926. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  31927. return super.getNodeType( builder );
  31928. }
  31929. const { attribute } = this.getAttributeData();
  31930. return attribute.getNodeType( builder );
  31931. }
  31932. generate( builder ) {
  31933. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  31934. return super.generate( builder );
  31935. }
  31936. const { attribute, varying } = this.getAttributeData();
  31937. const output = varying.build( builder );
  31938. builder.registerTransform( output, attribute );
  31939. return output;
  31940. }
  31941. }
  31942. // Read-Write Storage
  31943. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  31944. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  31945. class StorageTextureNode extends TextureNode {
  31946. static get type() {
  31947. return 'StorageTextureNode';
  31948. }
  31949. constructor( value, uvNode, storeNode = null ) {
  31950. super( value, uvNode );
  31951. this.storeNode = storeNode;
  31952. this.isStorageTextureNode = true;
  31953. this.access = GPUStorageTextureAccess.WriteOnly;
  31954. }
  31955. getInputType( /*builder*/ ) {
  31956. return 'storageTexture';
  31957. }
  31958. setup( builder ) {
  31959. super.setup( builder );
  31960. const properties = builder.getNodeProperties( this );
  31961. properties.storeNode = this.storeNode;
  31962. }
  31963. setAccess( value ) {
  31964. this.access = value;
  31965. return this;
  31966. }
  31967. generate( builder, output ) {
  31968. let snippet;
  31969. if ( this.storeNode !== null ) {
  31970. snippet = this.generateStore( builder );
  31971. } else {
  31972. snippet = super.generate( builder, output );
  31973. }
  31974. return snippet;
  31975. }
  31976. toReadOnly() {
  31977. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  31978. }
  31979. toWriteOnly() {
  31980. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  31981. }
  31982. generateStore( builder ) {
  31983. const properties = builder.getNodeProperties( this );
  31984. const { uvNode, storeNode } = properties;
  31985. const textureProperty = super.generate( builder, 'property' );
  31986. const uvSnippet = uvNode.build( builder, 'uvec2' );
  31987. const storeSnippet = storeNode.build( builder, 'vec4' );
  31988. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  31989. builder.addLineFlowCode( snippet, this );
  31990. }
  31991. }
  31992. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  31993. const textureStore = ( value, uvNode, storeNode ) => {
  31994. const node = storageTexture( value, uvNode, storeNode );
  31995. if ( storeNode !== null ) node.append();
  31996. return node;
  31997. };
  31998. class UserDataNode extends ReferenceNode {
  31999. static get type() {
  32000. return 'UserDataNode';
  32001. }
  32002. constructor( property, inputType, userData = null ) {
  32003. super( property, inputType, userData );
  32004. this.userData = userData;
  32005. }
  32006. updateReference( state ) {
  32007. this.reference = this.userData !== null ? this.userData : state.object.userData;
  32008. return this.reference;
  32009. }
  32010. }
  32011. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  32012. const _objectData = new WeakMap();
  32013. class VelocityNode extends TempNode {
  32014. static get type() {
  32015. return 'VelocityNode';
  32016. }
  32017. constructor() {
  32018. super( 'vec2' );
  32019. this.projectionMatrix = null;
  32020. this.updateType = NodeUpdateType.OBJECT;
  32021. this.updateAfterType = NodeUpdateType.OBJECT;
  32022. this.previousModelWorldMatrix = uniform( new Matrix4() );
  32023. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  32024. this.previousCameraViewMatrix = uniform( new Matrix4() );
  32025. }
  32026. setProjectionMatrix( projectionMatrix ) {
  32027. this.projectionMatrix = projectionMatrix;
  32028. }
  32029. update( { frameId, camera, object } ) {
  32030. const previousModelMatrix = getPreviousMatrix( object );
  32031. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  32032. //
  32033. const cameraData = getData( camera );
  32034. if ( cameraData.frameId !== frameId ) {
  32035. cameraData.frameId = frameId;
  32036. if ( cameraData.previousProjectionMatrix === undefined ) {
  32037. cameraData.previousProjectionMatrix = new Matrix4();
  32038. cameraData.previousCameraViewMatrix = new Matrix4();
  32039. cameraData.currentProjectionMatrix = new Matrix4();
  32040. cameraData.currentCameraViewMatrix = new Matrix4();
  32041. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  32042. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  32043. } else {
  32044. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  32045. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  32046. }
  32047. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  32048. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  32049. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  32050. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  32051. }
  32052. }
  32053. updateAfter( { object } ) {
  32054. getPreviousMatrix( object ).copy( object.matrixWorld );
  32055. }
  32056. setup( /*builder*/ ) {
  32057. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  32058. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  32059. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  32060. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  32061. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  32062. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  32063. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  32064. return velocity;
  32065. }
  32066. }
  32067. function getData( object ) {
  32068. let objectData = _objectData.get( object );
  32069. if ( objectData === undefined ) {
  32070. objectData = {};
  32071. _objectData.set( object, objectData );
  32072. }
  32073. return objectData;
  32074. }
  32075. function getPreviousMatrix( object, index = 0 ) {
  32076. const objectData = getData( object );
  32077. let matrix = objectData[ index ];
  32078. if ( matrix === undefined ) {
  32079. objectData[ index ] = matrix = new Matrix4();
  32080. }
  32081. return matrix;
  32082. }
  32083. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  32084. const burn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  32085. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  32086. } ).setLayout( {
  32087. name: 'burnBlend',
  32088. type: 'vec3',
  32089. inputs: [
  32090. { name: 'base', type: 'vec3' },
  32091. { name: 'blend', type: 'vec3' }
  32092. ]
  32093. } );
  32094. const dodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  32095. return min$1( base.div( blend.oneMinus() ), 1.0 );
  32096. } ).setLayout( {
  32097. name: 'dodgeBlend',
  32098. type: 'vec3',
  32099. inputs: [
  32100. { name: 'base', type: 'vec3' },
  32101. { name: 'blend', type: 'vec3' }
  32102. ]
  32103. } );
  32104. const screen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  32105. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  32106. } ).setLayout( {
  32107. name: 'screenBlend',
  32108. type: 'vec3',
  32109. inputs: [
  32110. { name: 'base', type: 'vec3' },
  32111. { name: 'blend', type: 'vec3' }
  32112. ]
  32113. } );
  32114. const overlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  32115. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  32116. } ).setLayout( {
  32117. name: 'overlayBlend',
  32118. type: 'vec3',
  32119. inputs: [
  32120. { name: 'base', type: 'vec3' },
  32121. { name: 'blend', type: 'vec3' }
  32122. ]
  32123. } );
  32124. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  32125. return luminance( color.rgb );
  32126. } );
  32127. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  32128. return adjustment.mix( luminance( color.rgb ), color.rgb );
  32129. } );
  32130. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  32131. const average = add( color.r, color.g, color.b ).div( 3.0 );
  32132. const mx = color.r.max( color.g.max( color.b ) );
  32133. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  32134. return mix( color.rgb, mx, amt );
  32135. } );
  32136. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  32137. const k = vec3( 0.57735, 0.57735, 0.57735 );
  32138. const cosAngle = adjustment.cos();
  32139. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  32140. } );
  32141. const luminance = (
  32142. color,
  32143. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  32144. ) => dot( color, luminanceCoefficients );
  32145. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  32146. /**
  32147. * Color Decision List (CDL) v1.2
  32148. *
  32149. * Compact representation of color grading information, defined by slope, offset, power, and
  32150. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  32151. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  32152. *
  32153. * @param {vec4} color Input (-Infinity < input < +Infinity)
  32154. * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity)
  32155. * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  32156. * @param {number | vec3} power Power (0 < power < +Infinity)
  32157. * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  32158. * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  32159. * @return Output, -Infinity < output < +Infinity
  32160. *
  32161. * References:
  32162. * - ASC CDL v1.2
  32163. * - https://blender.stackexchange.com/a/55239/43930
  32164. * - https://docs.acescentral.com/specifications/acescc/
  32165. */
  32166. const cdl = /*@__PURE__*/ Fn( ( [
  32167. color,
  32168. slope = vec3( 1 ),
  32169. offset = vec3( 0 ),
  32170. power = vec3( 1 ),
  32171. saturation = float( 1 ),
  32172. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  32173. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  32174. ] ) => {
  32175. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  32176. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  32177. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  32178. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  32179. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  32180. const pv = v.pow( power ).toVar();
  32181. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  32182. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  32183. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  32184. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  32185. return vec4( v.rgb, color.a );
  32186. } );
  32187. class PosterizeNode extends TempNode {
  32188. static get type() {
  32189. return 'PosterizeNode';
  32190. }
  32191. constructor( sourceNode, stepsNode ) {
  32192. super();
  32193. this.sourceNode = sourceNode;
  32194. this.stepsNode = stepsNode;
  32195. }
  32196. setup() {
  32197. const { sourceNode, stepsNode } = this;
  32198. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  32199. }
  32200. }
  32201. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  32202. let _sharedFramebuffer = null;
  32203. class ViewportSharedTextureNode extends ViewportTextureNode {
  32204. static get type() {
  32205. return 'ViewportSharedTextureNode';
  32206. }
  32207. constructor( uvNode = screenUV, levelNode = null ) {
  32208. if ( _sharedFramebuffer === null ) {
  32209. _sharedFramebuffer = new FramebufferTexture();
  32210. }
  32211. super( uvNode, levelNode, _sharedFramebuffer );
  32212. }
  32213. updateReference() {
  32214. return this;
  32215. }
  32216. }
  32217. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  32218. const _size = /*@__PURE__*/ new Vector2();
  32219. class PassTextureNode extends TextureNode {
  32220. static get type() {
  32221. return 'PassTextureNode';
  32222. }
  32223. constructor( passNode, texture ) {
  32224. super( texture );
  32225. this.passNode = passNode;
  32226. this.setUpdateMatrix( false );
  32227. }
  32228. setup( builder ) {
  32229. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  32230. return super.setup( builder );
  32231. }
  32232. clone() {
  32233. return new this.constructor( this.passNode, this.value );
  32234. }
  32235. }
  32236. class PassMultipleTextureNode extends PassTextureNode {
  32237. static get type() {
  32238. return 'PassMultipleTextureNode';
  32239. }
  32240. constructor( passNode, textureName, previousTexture = false ) {
  32241. super( passNode, null );
  32242. this.textureName = textureName;
  32243. this.previousTexture = previousTexture;
  32244. }
  32245. updateTexture() {
  32246. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  32247. }
  32248. setup( builder ) {
  32249. this.updateTexture();
  32250. return super.setup( builder );
  32251. }
  32252. clone() {
  32253. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  32254. }
  32255. }
  32256. class PassNode extends TempNode {
  32257. static get type() {
  32258. return 'PassNode';
  32259. }
  32260. constructor( scope, scene, camera, options = {} ) {
  32261. super( 'vec4' );
  32262. this.scope = scope;
  32263. this.scene = scene;
  32264. this.camera = camera;
  32265. this.options = options;
  32266. this._pixelRatio = 1;
  32267. this._width = 1;
  32268. this._height = 1;
  32269. const depthTexture = new DepthTexture();
  32270. depthTexture.isRenderTargetTexture = true;
  32271. //depthTexture.type = FloatType;
  32272. depthTexture.name = 'depth';
  32273. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  32274. renderTarget.texture.name = 'output';
  32275. renderTarget.depthTexture = depthTexture;
  32276. this.renderTarget = renderTarget;
  32277. this.updateBeforeType = NodeUpdateType.FRAME;
  32278. this._textures = {
  32279. output: renderTarget.texture,
  32280. depth: depthTexture
  32281. };
  32282. this._textureNodes = {};
  32283. this._linearDepthNodes = {};
  32284. this._viewZNodes = {};
  32285. this._previousTextures = {};
  32286. this._previousTextureNodes = {};
  32287. this._cameraNear = uniform( 0 );
  32288. this._cameraFar = uniform( 0 );
  32289. this._mrt = null;
  32290. this.isPassNode = true;
  32291. }
  32292. setMRT( mrt ) {
  32293. this._mrt = mrt;
  32294. return this;
  32295. }
  32296. getMRT() {
  32297. return this._mrt;
  32298. }
  32299. isGlobal() {
  32300. return true;
  32301. }
  32302. getTexture( name ) {
  32303. let texture = this._textures[ name ];
  32304. if ( texture === undefined ) {
  32305. const refTexture = this.renderTarget.texture;
  32306. texture = refTexture.clone();
  32307. texture.isRenderTargetTexture = true;
  32308. texture.name = name;
  32309. this._textures[ name ] = texture;
  32310. this.renderTarget.textures.push( texture );
  32311. }
  32312. return texture;
  32313. }
  32314. getPreviousTexture( name ) {
  32315. let texture = this._previousTextures[ name ];
  32316. if ( texture === undefined ) {
  32317. texture = this.getTexture( name ).clone();
  32318. texture.isRenderTargetTexture = true;
  32319. this._previousTextures[ name ] = texture;
  32320. }
  32321. return texture;
  32322. }
  32323. toggleTexture( name ) {
  32324. const prevTexture = this._previousTextures[ name ];
  32325. if ( prevTexture !== undefined ) {
  32326. const texture = this._textures[ name ];
  32327. const index = this.renderTarget.textures.indexOf( texture );
  32328. this.renderTarget.textures[ index ] = prevTexture;
  32329. this._textures[ name ] = prevTexture;
  32330. this._previousTextures[ name ] = texture;
  32331. this._textureNodes[ name ].updateTexture();
  32332. this._previousTextureNodes[ name ].updateTexture();
  32333. }
  32334. }
  32335. getTextureNode( name = 'output' ) {
  32336. let textureNode = this._textureNodes[ name ];
  32337. if ( textureNode === undefined ) {
  32338. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  32339. textureNode.updateTexture();
  32340. this._textureNodes[ name ] = textureNode;
  32341. }
  32342. return textureNode;
  32343. }
  32344. getPreviousTextureNode( name = 'output' ) {
  32345. let textureNode = this._previousTextureNodes[ name ];
  32346. if ( textureNode === undefined ) {
  32347. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  32348. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  32349. textureNode.updateTexture();
  32350. this._previousTextureNodes[ name ] = textureNode;
  32351. }
  32352. return textureNode;
  32353. }
  32354. getViewZNode( name = 'depth' ) {
  32355. let viewZNode = this._viewZNodes[ name ];
  32356. if ( viewZNode === undefined ) {
  32357. const cameraNear = this._cameraNear;
  32358. const cameraFar = this._cameraFar;
  32359. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  32360. }
  32361. return viewZNode;
  32362. }
  32363. getLinearDepthNode( name = 'depth' ) {
  32364. let linearDepthNode = this._linearDepthNodes[ name ];
  32365. if ( linearDepthNode === undefined ) {
  32366. const cameraNear = this._cameraNear;
  32367. const cameraFar = this._cameraFar;
  32368. const viewZNode = this.getViewZNode( name );
  32369. // TODO: just if ( builder.camera.isPerspectiveCamera )
  32370. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  32371. }
  32372. return linearDepthNode;
  32373. }
  32374. setup( { renderer } ) {
  32375. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  32376. // Disable MSAA for WebGL backend for now
  32377. if ( renderer.backend.isWebGLBackend === true ) {
  32378. this.renderTarget.samples = 0;
  32379. }
  32380. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  32381. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  32382. }
  32383. updateBefore( frame ) {
  32384. const { renderer } = frame;
  32385. const { scene, camera } = this;
  32386. this._pixelRatio = renderer.getPixelRatio();
  32387. const size = renderer.getSize( _size );
  32388. this.setSize( size.width, size.height );
  32389. const currentRenderTarget = renderer.getRenderTarget();
  32390. const currentMRT = renderer.getMRT();
  32391. this._cameraNear.value = camera.near;
  32392. this._cameraFar.value = camera.far;
  32393. for ( const name in this._previousTextures ) {
  32394. this.toggleTexture( name );
  32395. }
  32396. renderer.setRenderTarget( this.renderTarget );
  32397. renderer.setMRT( this._mrt );
  32398. renderer.render( scene, camera );
  32399. renderer.setRenderTarget( currentRenderTarget );
  32400. renderer.setMRT( currentMRT );
  32401. }
  32402. setSize( width, height ) {
  32403. this._width = width;
  32404. this._height = height;
  32405. const effectiveWidth = this._width * this._pixelRatio;
  32406. const effectiveHeight = this._height * this._pixelRatio;
  32407. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  32408. }
  32409. setPixelRatio( pixelRatio ) {
  32410. this._pixelRatio = pixelRatio;
  32411. this.setSize( this._width, this._height );
  32412. }
  32413. dispose() {
  32414. this.renderTarget.dispose();
  32415. }
  32416. }
  32417. PassNode.COLOR = 'color';
  32418. PassNode.DEPTH = 'depth';
  32419. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  32420. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  32421. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  32422. class ToonOutlinePassNode extends PassNode {
  32423. static get type() {
  32424. return 'ToonOutlinePassNode';
  32425. }
  32426. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  32427. super( PassNode.COLOR, scene, camera );
  32428. this.colorNode = colorNode;
  32429. this.thicknessNode = thicknessNode;
  32430. this.alphaNode = alphaNode;
  32431. this._materialCache = new WeakMap();
  32432. }
  32433. updateBefore( frame ) {
  32434. const { renderer } = frame;
  32435. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  32436. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode ) => {
  32437. // only render outline for supported materials
  32438. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  32439. if ( material.wireframe === false ) {
  32440. const outlineMaterial = this._getOutlineMaterial( material );
  32441. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode );
  32442. }
  32443. }
  32444. // default
  32445. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode );
  32446. } );
  32447. super.updateBefore( frame );
  32448. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  32449. }
  32450. _createMaterial() {
  32451. const material = new NodeMaterial();
  32452. material.isMeshToonOutlineMaterial = true;
  32453. material.name = 'Toon_Outline';
  32454. material.side = BackSide;
  32455. // vertex node
  32456. const outlineNormal = normalLocal.negate();
  32457. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  32458. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  32459. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  32460. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  32461. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  32462. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  32463. // color node
  32464. material.colorNode = vec4( this.colorNode, this.alphaNode );
  32465. return material;
  32466. }
  32467. _getOutlineMaterial( originalMaterial ) {
  32468. let outlineMaterial = this._materialCache.get( originalMaterial );
  32469. if ( outlineMaterial === undefined ) {
  32470. outlineMaterial = this._createMaterial();
  32471. this._materialCache.set( originalMaterial, outlineMaterial );
  32472. }
  32473. return outlineMaterial;
  32474. }
  32475. }
  32476. const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => nodeObject( new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) ) );
  32477. // exposure only
  32478. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32479. return color.mul( exposure ).clamp();
  32480. } ).setLayout( {
  32481. name: 'linearToneMapping',
  32482. type: 'vec3',
  32483. inputs: [
  32484. { name: 'color', type: 'vec3' },
  32485. { name: 'exposure', type: 'float' }
  32486. ]
  32487. } );
  32488. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  32489. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32490. color = color.mul( exposure );
  32491. return color.div( color.add( 1.0 ) ).clamp();
  32492. } ).setLayout( {
  32493. name: 'reinhardToneMapping',
  32494. type: 'vec3',
  32495. inputs: [
  32496. { name: 'color', type: 'vec3' },
  32497. { name: 'exposure', type: 'float' }
  32498. ]
  32499. } );
  32500. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  32501. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32502. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  32503. color = color.mul( exposure );
  32504. color = color.sub( 0.004 ).max( 0.0 );
  32505. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  32506. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  32507. return a.div( b ).pow( 2.2 );
  32508. } ).setLayout( {
  32509. name: 'cineonToneMapping',
  32510. type: 'vec3',
  32511. inputs: [
  32512. { name: 'color', type: 'vec3' },
  32513. { name: 'exposure', type: 'float' }
  32514. ]
  32515. } );
  32516. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  32517. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  32518. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  32519. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  32520. return a.div( b );
  32521. } );
  32522. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  32523. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32524. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  32525. const ACESInputMat = mat3(
  32526. 0.59719, 0.35458, 0.04823,
  32527. 0.07600, 0.90834, 0.01566,
  32528. 0.02840, 0.13383, 0.83777
  32529. );
  32530. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  32531. const ACESOutputMat = mat3(
  32532. 1.60475, - 0.53108, - 0.07367,
  32533. - 0.10208, 1.10813, - 0.00605,
  32534. - 0.00327, - 0.07276, 1.07602
  32535. );
  32536. color = color.mul( exposure ).div( 0.6 );
  32537. color = ACESInputMat.mul( color );
  32538. // Apply RRT and ODT
  32539. color = RRTAndODTFit( color );
  32540. color = ACESOutputMat.mul( color );
  32541. // Clamp to [0, 1]
  32542. return color.clamp();
  32543. } ).setLayout( {
  32544. name: 'acesFilmicToneMapping',
  32545. type: 'vec3',
  32546. inputs: [
  32547. { name: 'color', type: 'vec3' },
  32548. { name: 'exposure', type: 'float' }
  32549. ]
  32550. } );
  32551. 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 ) );
  32552. 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 ) );
  32553. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32554. const x = vec3( x_immutable ).toVar();
  32555. const x2 = vec3( x.mul( x ) ).toVar();
  32556. const x4 = vec3( x2.mul( x2 ) ).toVar();
  32557. 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 ) ) ) );
  32558. } );
  32559. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32560. const colortone = vec3( color ).toVar();
  32561. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  32562. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  32563. const AgxMinEv = float( - 12.47393 );
  32564. const AgxMaxEv = float( 4.026069 );
  32565. colortone.mulAssign( exposure );
  32566. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  32567. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  32568. colortone.assign( max$1( colortone, 1e-10 ) );
  32569. colortone.assign( log2( colortone ) );
  32570. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  32571. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  32572. colortone.assign( agxDefaultContrastApprox( colortone ) );
  32573. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  32574. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  32575. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  32576. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  32577. return colortone;
  32578. } ).setLayout( {
  32579. name: 'agxToneMapping',
  32580. type: 'vec3',
  32581. inputs: [
  32582. { name: 'color', type: 'vec3' },
  32583. { name: 'exposure', type: 'float' }
  32584. ]
  32585. } );
  32586. // https://modelviewer.dev/examples/tone-mapping
  32587. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32588. const StartCompression = float( 0.8 - 0.04 );
  32589. const Desaturation = float( 0.15 );
  32590. color = color.mul( exposure );
  32591. const x = min$1( color.r, min$1( color.g, color.b ) );
  32592. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  32593. color.subAssign( offset );
  32594. const peak = max$1( color.r, max$1( color.g, color.b ) );
  32595. If( peak.lessThan( StartCompression ), () => {
  32596. return color;
  32597. } );
  32598. const d = sub( 1, StartCompression );
  32599. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  32600. color.mulAssign( newPeak.div( peak ) );
  32601. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  32602. return mix( color, vec3( newPeak ), g );
  32603. } ).setLayout( {
  32604. name: 'neutralToneMapping',
  32605. type: 'vec3',
  32606. inputs: [
  32607. { name: 'color', type: 'vec3' },
  32608. { name: 'exposure', type: 'float' }
  32609. ]
  32610. } );
  32611. class CodeNode extends Node {
  32612. static get type() {
  32613. return 'CodeNode';
  32614. }
  32615. constructor( code = '', includes = [], language = '' ) {
  32616. super( 'code' );
  32617. this.isCodeNode = true;
  32618. this.code = code;
  32619. this.language = language;
  32620. this.includes = includes;
  32621. }
  32622. isGlobal() {
  32623. return true;
  32624. }
  32625. setIncludes( includes ) {
  32626. this.includes = includes;
  32627. return this;
  32628. }
  32629. getIncludes( /*builder*/ ) {
  32630. return this.includes;
  32631. }
  32632. generate( builder ) {
  32633. const includes = this.getIncludes( builder );
  32634. for ( const include of includes ) {
  32635. include.build( builder );
  32636. }
  32637. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  32638. nodeCode.code = this.code;
  32639. return nodeCode.code;
  32640. }
  32641. serialize( data ) {
  32642. super.serialize( data );
  32643. data.code = this.code;
  32644. data.language = this.language;
  32645. }
  32646. deserialize( data ) {
  32647. super.deserialize( data );
  32648. this.code = data.code;
  32649. this.language = data.language;
  32650. }
  32651. }
  32652. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  32653. const js = ( src, includes ) => code( src, includes, 'js' );
  32654. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  32655. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  32656. class FunctionNode extends CodeNode {
  32657. static get type() {
  32658. return 'FunctionNode';
  32659. }
  32660. constructor( code = '', includes = [], language = '' ) {
  32661. super( code, includes, language );
  32662. }
  32663. getNodeType( builder ) {
  32664. return this.getNodeFunction( builder ).type;
  32665. }
  32666. getInputs( builder ) {
  32667. return this.getNodeFunction( builder ).inputs;
  32668. }
  32669. getNodeFunction( builder ) {
  32670. const nodeData = builder.getDataFromNode( this );
  32671. let nodeFunction = nodeData.nodeFunction;
  32672. if ( nodeFunction === undefined ) {
  32673. nodeFunction = builder.parser.parseFunction( this.code );
  32674. nodeData.nodeFunction = nodeFunction;
  32675. }
  32676. return nodeFunction;
  32677. }
  32678. generate( builder, output ) {
  32679. super.generate( builder );
  32680. const nodeFunction = this.getNodeFunction( builder );
  32681. const name = nodeFunction.name;
  32682. const type = nodeFunction.type;
  32683. const nodeCode = builder.getCodeFromNode( this, type );
  32684. if ( name !== '' ) {
  32685. // use a custom property name
  32686. nodeCode.name = name;
  32687. }
  32688. const propertyName = builder.getPropertyName( nodeCode );
  32689. const code = this.getNodeFunction( builder ).getCode( propertyName );
  32690. nodeCode.code = code + '\n';
  32691. if ( output === 'property' ) {
  32692. return propertyName;
  32693. } else {
  32694. return builder.format( `${ propertyName }()`, type, output );
  32695. }
  32696. }
  32697. }
  32698. const nativeFn = ( code, includes = [], language = '' ) => {
  32699. for ( let i = 0; i < includes.length; i ++ ) {
  32700. const include = includes[ i ];
  32701. // TSL Function: glslFn, wgslFn
  32702. if ( typeof include === 'function' ) {
  32703. includes[ i ] = include.functionNode;
  32704. }
  32705. }
  32706. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  32707. const fn = ( ...params ) => functionNode.call( ...params );
  32708. fn.functionNode = functionNode;
  32709. return fn;
  32710. };
  32711. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  32712. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  32713. class ScriptableValueNode extends Node {
  32714. static get type() {
  32715. return 'ScriptableValueNode';
  32716. }
  32717. constructor( value = null ) {
  32718. super();
  32719. this._value = value;
  32720. this._cache = null;
  32721. this.inputType = null;
  32722. this.outpuType = null;
  32723. this.events = new EventDispatcher();
  32724. this.isScriptableValueNode = true;
  32725. }
  32726. get isScriptableOutputNode() {
  32727. return this.outputType !== null;
  32728. }
  32729. set value( val ) {
  32730. if ( this._value === val ) return;
  32731. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  32732. URL.revokeObjectURL( this._cache );
  32733. this._cache = null;
  32734. }
  32735. this._value = val;
  32736. this.events.dispatchEvent( { type: 'change' } );
  32737. this.refresh();
  32738. }
  32739. get value() {
  32740. return this._value;
  32741. }
  32742. refresh() {
  32743. this.events.dispatchEvent( { type: 'refresh' } );
  32744. }
  32745. getValue() {
  32746. const value = this.value;
  32747. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  32748. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  32749. } else if ( value && value.value !== null && value.value !== undefined && (
  32750. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  32751. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  32752. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  32753. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  32754. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  32755. ( this.inputType === 'Color' && value.value.isColor ) ||
  32756. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  32757. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  32758. ) ) {
  32759. return value.value;
  32760. }
  32761. return this._cache || value;
  32762. }
  32763. getNodeType( builder ) {
  32764. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  32765. }
  32766. setup() {
  32767. return this.value && this.value.isNode ? this.value : float();
  32768. }
  32769. serialize( data ) {
  32770. super.serialize( data );
  32771. if ( this.value !== null ) {
  32772. if ( this.inputType === 'ArrayBuffer' ) {
  32773. data.value = arrayBufferToBase64( this.value );
  32774. } else {
  32775. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  32776. }
  32777. } else {
  32778. data.value = null;
  32779. }
  32780. data.inputType = this.inputType;
  32781. data.outputType = this.outputType;
  32782. }
  32783. deserialize( data ) {
  32784. super.deserialize( data );
  32785. let value = null;
  32786. if ( data.value !== null ) {
  32787. if ( data.inputType === 'ArrayBuffer' ) {
  32788. value = base64ToArrayBuffer( data.value );
  32789. } else if ( data.inputType === 'Texture' ) {
  32790. value = data.meta.textures[ data.value ];
  32791. } else {
  32792. value = data.meta.nodes[ data.value ] || null;
  32793. }
  32794. }
  32795. this.value = value;
  32796. this.inputType = data.inputType;
  32797. this.outputType = data.outputType;
  32798. }
  32799. }
  32800. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  32801. class Resources extends Map {
  32802. get( key, callback = null, ...params ) {
  32803. if ( this.has( key ) ) return super.get( key );
  32804. if ( callback !== null ) {
  32805. const value = callback( ...params );
  32806. this.set( key, value );
  32807. return value;
  32808. }
  32809. }
  32810. }
  32811. class Parameters {
  32812. constructor( scriptableNode ) {
  32813. this.scriptableNode = scriptableNode;
  32814. }
  32815. get parameters() {
  32816. return this.scriptableNode.parameters;
  32817. }
  32818. get layout() {
  32819. return this.scriptableNode.getLayout();
  32820. }
  32821. getInputLayout( id ) {
  32822. return this.scriptableNode.getInputLayout( id );
  32823. }
  32824. get( name ) {
  32825. const param = this.parameters[ name ];
  32826. const value = param ? param.getValue() : null;
  32827. return value;
  32828. }
  32829. }
  32830. const ScriptableNodeResources = new Resources();
  32831. class ScriptableNode extends Node {
  32832. static get type() {
  32833. return 'ScriptableNode';
  32834. }
  32835. constructor( codeNode = null, parameters = {} ) {
  32836. super();
  32837. this.codeNode = codeNode;
  32838. this.parameters = parameters;
  32839. this._local = new Resources();
  32840. this._output = scriptableValue();
  32841. this._outputs = {};
  32842. this._source = this.source;
  32843. this._method = null;
  32844. this._object = null;
  32845. this._value = null;
  32846. this._needsOutputUpdate = true;
  32847. this.onRefresh = this.onRefresh.bind( this );
  32848. this.isScriptableNode = true;
  32849. }
  32850. get source() {
  32851. return this.codeNode ? this.codeNode.code : '';
  32852. }
  32853. setLocal( name, value ) {
  32854. return this._local.set( name, value );
  32855. }
  32856. getLocal( name ) {
  32857. return this._local.get( name );
  32858. }
  32859. onRefresh() {
  32860. this._refresh();
  32861. }
  32862. getInputLayout( id ) {
  32863. for ( const element of this.getLayout() ) {
  32864. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  32865. return element;
  32866. }
  32867. }
  32868. }
  32869. getOutputLayout( id ) {
  32870. for ( const element of this.getLayout() ) {
  32871. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  32872. return element;
  32873. }
  32874. }
  32875. }
  32876. setOutput( name, value ) {
  32877. const outputs = this._outputs;
  32878. if ( outputs[ name ] === undefined ) {
  32879. outputs[ name ] = scriptableValue( value );
  32880. } else {
  32881. outputs[ name ].value = value;
  32882. }
  32883. return this;
  32884. }
  32885. getOutput( name ) {
  32886. return this._outputs[ name ];
  32887. }
  32888. getParameter( name ) {
  32889. return this.parameters[ name ];
  32890. }
  32891. setParameter( name, value ) {
  32892. const parameters = this.parameters;
  32893. if ( value && value.isScriptableNode ) {
  32894. this.deleteParameter( name );
  32895. parameters[ name ] = value;
  32896. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  32897. } else if ( value && value.isScriptableValueNode ) {
  32898. this.deleteParameter( name );
  32899. parameters[ name ] = value;
  32900. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  32901. } else if ( parameters[ name ] === undefined ) {
  32902. parameters[ name ] = scriptableValue( value );
  32903. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  32904. } else {
  32905. parameters[ name ].value = value;
  32906. }
  32907. return this;
  32908. }
  32909. getValue() {
  32910. return this.getDefaultOutput().getValue();
  32911. }
  32912. deleteParameter( name ) {
  32913. let valueNode = this.parameters[ name ];
  32914. if ( valueNode ) {
  32915. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  32916. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  32917. }
  32918. return this;
  32919. }
  32920. clearParameters() {
  32921. for ( const name of Object.keys( this.parameters ) ) {
  32922. this.deleteParameter( name );
  32923. }
  32924. this.needsUpdate = true;
  32925. return this;
  32926. }
  32927. call( name, ...params ) {
  32928. const object = this.getObject();
  32929. const method = object[ name ];
  32930. if ( typeof method === 'function' ) {
  32931. return method( ...params );
  32932. }
  32933. }
  32934. async callAsync( name, ...params ) {
  32935. const object = this.getObject();
  32936. const method = object[ name ];
  32937. if ( typeof method === 'function' ) {
  32938. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  32939. }
  32940. }
  32941. getNodeType( builder ) {
  32942. return this.getDefaultOutputNode().getNodeType( builder );
  32943. }
  32944. refresh( output = null ) {
  32945. if ( output !== null ) {
  32946. this.getOutput( output ).refresh();
  32947. } else {
  32948. this._refresh();
  32949. }
  32950. }
  32951. getObject() {
  32952. if ( this.needsUpdate ) this.dispose();
  32953. if ( this._object !== null ) return this._object;
  32954. //
  32955. const refresh = () => this.refresh();
  32956. const setOutput = ( id, value ) => this.setOutput( id, value );
  32957. const parameters = new Parameters( this );
  32958. const THREE = ScriptableNodeResources.get( 'THREE' );
  32959. const TSL = ScriptableNodeResources.get( 'TSL' );
  32960. const method = this.getMethod( this.codeNode );
  32961. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  32962. this._object = method( ...params );
  32963. const layout = this._object.layout;
  32964. if ( layout ) {
  32965. if ( layout.cache === false ) {
  32966. this._local.clear();
  32967. }
  32968. // default output
  32969. this._output.outputType = layout.outputType || null;
  32970. if ( Array.isArray( layout.elements ) ) {
  32971. for ( const element of layout.elements ) {
  32972. const id = element.id || element.name;
  32973. if ( element.inputType ) {
  32974. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  32975. this.getParameter( id ).inputType = element.inputType;
  32976. }
  32977. if ( element.outputType ) {
  32978. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  32979. this.getOutput( id ).outputType = element.outputType;
  32980. }
  32981. }
  32982. }
  32983. }
  32984. return this._object;
  32985. }
  32986. deserialize( data ) {
  32987. super.deserialize( data );
  32988. for ( const name in this.parameters ) {
  32989. let valueNode = this.parameters[ name ];
  32990. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  32991. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  32992. }
  32993. }
  32994. getLayout() {
  32995. return this.getObject().layout;
  32996. }
  32997. getDefaultOutputNode() {
  32998. const output = this.getDefaultOutput().value;
  32999. if ( output && output.isNode ) {
  33000. return output;
  33001. }
  33002. return float();
  33003. }
  33004. getDefaultOutput() {
  33005. return this._exec()._output;
  33006. }
  33007. getMethod() {
  33008. if ( this.needsUpdate ) this.dispose();
  33009. if ( this._method !== null ) return this._method;
  33010. //
  33011. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  33012. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  33013. const properties = interfaceProps.join( ', ' );
  33014. const declarations = 'var ' + properties + '; var output = {};\n';
  33015. const returns = '\nreturn { ...output, ' + properties + ' };';
  33016. const code = declarations + this.codeNode.code + returns;
  33017. //
  33018. this._method = new Function( ...parametersProps, code );
  33019. return this._method;
  33020. }
  33021. dispose() {
  33022. if ( this._method === null ) return;
  33023. if ( this._object && typeof this._object.dispose === 'function' ) {
  33024. this._object.dispose();
  33025. }
  33026. this._method = null;
  33027. this._object = null;
  33028. this._source = null;
  33029. this._value = null;
  33030. this._needsOutputUpdate = true;
  33031. this._output.value = null;
  33032. this._outputs = {};
  33033. }
  33034. setup() {
  33035. return this.getDefaultOutputNode();
  33036. }
  33037. getCacheKey( force ) {
  33038. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  33039. for ( const param in this.parameters ) {
  33040. values.push( this.parameters[ param ].getCacheKey( force ) );
  33041. }
  33042. return hashArray( values );
  33043. }
  33044. set needsUpdate( value ) {
  33045. if ( value === true ) this.dispose();
  33046. }
  33047. get needsUpdate() {
  33048. return this.source !== this._source;
  33049. }
  33050. _exec() {
  33051. if ( this.codeNode === null ) return this;
  33052. if ( this._needsOutputUpdate === true ) {
  33053. this._value = this.call( 'main' );
  33054. this._needsOutputUpdate = false;
  33055. }
  33056. this._output.value = this._value;
  33057. return this;
  33058. }
  33059. _refresh() {
  33060. this.needsUpdate = true;
  33061. this._exec();
  33062. this._output.refresh();
  33063. }
  33064. }
  33065. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  33066. class FogNode extends Node {
  33067. static get type() {
  33068. return 'FogNode';
  33069. }
  33070. constructor( colorNode, factorNode ) {
  33071. super( 'float' );
  33072. this.isFogNode = true;
  33073. this.colorNode = colorNode;
  33074. this.factorNode = factorNode;
  33075. }
  33076. getViewZNode( builder ) {
  33077. let viewZ;
  33078. const getViewZ = builder.context.getViewZ;
  33079. if ( getViewZ !== undefined ) {
  33080. viewZ = getViewZ( this );
  33081. }
  33082. return ( viewZ || positionView.z ).negate();
  33083. }
  33084. setup() {
  33085. return this.factorNode;
  33086. }
  33087. }
  33088. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  33089. class FogRangeNode extends FogNode {
  33090. static get type() {
  33091. return 'FogRangeNode';
  33092. }
  33093. constructor( colorNode, nearNode, farNode ) {
  33094. super( colorNode );
  33095. this.isFogRangeNode = true;
  33096. this.nearNode = nearNode;
  33097. this.farNode = farNode;
  33098. }
  33099. setup( builder ) {
  33100. const viewZ = this.getViewZNode( builder );
  33101. return smoothstep( this.nearNode, this.farNode, viewZ );
  33102. }
  33103. }
  33104. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  33105. class FogExp2Node extends FogNode {
  33106. static get type() {
  33107. return 'FogExp2Node';
  33108. }
  33109. constructor( colorNode, densityNode ) {
  33110. super( colorNode );
  33111. this.isFogExp2Node = true;
  33112. this.densityNode = densityNode;
  33113. }
  33114. setup( builder ) {
  33115. const viewZ = this.getViewZNode( builder );
  33116. const density = this.densityNode;
  33117. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  33118. }
  33119. }
  33120. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  33121. let min = null;
  33122. let max = null;
  33123. class RangeNode extends Node {
  33124. static get type() {
  33125. return 'RangeNode';
  33126. }
  33127. constructor( minNode = float(), maxNode = float() ) {
  33128. super();
  33129. this.minNode = minNode;
  33130. this.maxNode = maxNode;
  33131. }
  33132. getVectorLength( builder ) {
  33133. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  33134. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  33135. return minLength > maxLength ? minLength : maxLength;
  33136. }
  33137. getNodeType( builder ) {
  33138. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  33139. }
  33140. setup( builder ) {
  33141. const object = builder.object;
  33142. let output = null;
  33143. if ( object.count > 1 ) {
  33144. const minValue = this.minNode.value;
  33145. const maxValue = this.maxNode.value;
  33146. const minLength = builder.getTypeLength( getValueType( minValue ) );
  33147. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  33148. min = min || new Vector4();
  33149. max = max || new Vector4();
  33150. min.setScalar( 0 );
  33151. max.setScalar( 0 );
  33152. if ( minLength === 1 ) min.setScalar( minValue );
  33153. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  33154. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  33155. if ( maxLength === 1 ) max.setScalar( maxValue );
  33156. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  33157. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  33158. const stride = 4;
  33159. const length = stride * object.count;
  33160. const array = new Float32Array( length );
  33161. for ( let i = 0; i < length; i ++ ) {
  33162. const index = i % stride;
  33163. const minElementValue = min.getComponent( index );
  33164. const maxElementValue = max.getComponent( index );
  33165. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  33166. }
  33167. const nodeType = this.getNodeType( builder );
  33168. if ( object.count <= 4096 ) {
  33169. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  33170. } else {
  33171. // TODO: Improve anonymous buffer attribute creation removing this part
  33172. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  33173. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  33174. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  33175. }
  33176. } else {
  33177. output = float( 0 );
  33178. }
  33179. return output;
  33180. }
  33181. }
  33182. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  33183. class ComputeBuiltinNode extends Node {
  33184. static get type() {
  33185. return 'ComputeBuiltinNode';
  33186. }
  33187. constructor( builtinName, nodeType ) {
  33188. super( nodeType );
  33189. this._builtinName = builtinName;
  33190. }
  33191. getHash( builder ) {
  33192. return this.getBuiltinName( builder );
  33193. }
  33194. getNodeType( /*builder*/ ) {
  33195. return this.nodeType;
  33196. }
  33197. setBuiltinName( builtinName ) {
  33198. this._builtinName = builtinName;
  33199. return this;
  33200. }
  33201. getBuiltinName( /*builder*/ ) {
  33202. return this._builtinName;
  33203. }
  33204. hasBuiltin( builder ) {
  33205. builder.hasBuiltin( this._builtinName );
  33206. }
  33207. generate( builder, output ) {
  33208. const builtinName = this.getBuiltinName( builder );
  33209. const nodeType = this.getNodeType( builder );
  33210. if ( builder.shaderStage === 'compute' ) {
  33211. return builder.format( builtinName, nodeType, output );
  33212. } else {
  33213. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  33214. return builder.generateConst( nodeType );
  33215. }
  33216. }
  33217. serialize( data ) {
  33218. super.serialize( data );
  33219. data.global = this.global;
  33220. data._builtinName = this._builtinName;
  33221. }
  33222. deserialize( data ) {
  33223. super.deserialize( data );
  33224. this.global = data.global;
  33225. this._builtinName = data._builtinName;
  33226. }
  33227. }
  33228. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  33229. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  33230. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  33231. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  33232. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  33233. class BarrierNode extends Node {
  33234. constructor( scope ) {
  33235. super();
  33236. this.scope = scope;
  33237. }
  33238. generate( builder ) {
  33239. const { scope } = this;
  33240. const { renderer } = builder;
  33241. if ( renderer.backend.isWebGLBackend === true ) {
  33242. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  33243. } else {
  33244. builder.addLineFlowCode( `${scope}Barrier()`, this );
  33245. }
  33246. }
  33247. }
  33248. const barrier = nodeProxy( BarrierNode );
  33249. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  33250. const storageBarrier = () => barrier( 'storage' ).append();
  33251. const textureBarrier = () => barrier( 'texture' ).append();
  33252. class WorkgroupInfoElementNode extends ArrayElementNode {
  33253. constructor( workgroupInfoNode, indexNode ) {
  33254. super( workgroupInfoNode, indexNode );
  33255. this.isWorkgroupInfoElementNode = true;
  33256. }
  33257. generate( builder, output ) {
  33258. let snippet;
  33259. const isAssignContext = builder.context.assign;
  33260. snippet = super.generate( builder );
  33261. if ( isAssignContext !== true ) {
  33262. const type = this.getNodeType( builder );
  33263. snippet = builder.format( snippet, type, output );
  33264. }
  33265. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  33266. return snippet;
  33267. }
  33268. }
  33269. class WorkgroupInfoNode extends Node {
  33270. constructor( scope, bufferType, bufferCount = 0 ) {
  33271. super( bufferType );
  33272. this.bufferType = bufferType;
  33273. this.bufferCount = bufferCount;
  33274. this.isWorkgroupInfoNode = true;
  33275. this.scope = scope;
  33276. }
  33277. label( name ) {
  33278. this.name = name;
  33279. return this;
  33280. }
  33281. getHash() {
  33282. return this.uuid;
  33283. }
  33284. setScope( scope ) {
  33285. this.scope = scope;
  33286. return this;
  33287. }
  33288. getInputType( /*builder*/ ) {
  33289. return `${this.scope}Array`;
  33290. }
  33291. element( indexNode ) {
  33292. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  33293. }
  33294. generate( builder ) {
  33295. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  33296. }
  33297. }
  33298. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  33299. class AtomicFunctionNode extends TempNode {
  33300. static get type() {
  33301. return 'AtomicFunctionNode';
  33302. }
  33303. constructor( method, pointerNode, valueNode, storeNode = null ) {
  33304. super( 'uint' );
  33305. this.method = method;
  33306. this.pointerNode = pointerNode;
  33307. this.valueNode = valueNode;
  33308. this.storeNode = storeNode;
  33309. }
  33310. getInputType( builder ) {
  33311. return this.pointerNode.getNodeType( builder );
  33312. }
  33313. getNodeType( builder ) {
  33314. return this.getInputType( builder );
  33315. }
  33316. generate( builder ) {
  33317. const method = this.method;
  33318. const type = this.getNodeType( builder );
  33319. const inputType = this.getInputType( builder );
  33320. const a = this.pointerNode;
  33321. const b = this.valueNode;
  33322. const params = [];
  33323. params.push( `&${ a.build( builder, inputType ) }` );
  33324. params.push( b.build( builder, inputType ) );
  33325. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  33326. if ( this.storeNode !== null ) {
  33327. const varSnippet = this.storeNode.build( builder, inputType );
  33328. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  33329. } else {
  33330. builder.addLineFlowCode( methodSnippet, this );
  33331. }
  33332. }
  33333. }
  33334. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  33335. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  33336. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  33337. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  33338. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  33339. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  33340. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  33341. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  33342. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  33343. const atomicNode = nodeProxy( AtomicFunctionNode );
  33344. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  33345. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  33346. node.append();
  33347. return node;
  33348. };
  33349. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  33350. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  33351. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  33352. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  33353. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  33354. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  33355. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  33356. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  33357. let uniformsLib;
  33358. function getLightData( light ) {
  33359. uniformsLib = uniformsLib || new WeakMap();
  33360. let uniforms = uniformsLib.get( light );
  33361. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  33362. return uniforms;
  33363. }
  33364. function lightPosition( light ) {
  33365. const data = getLightData( light );
  33366. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  33367. }
  33368. function lightTargetPosition( light ) {
  33369. const data = getLightData( light );
  33370. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  33371. }
  33372. function lightViewPosition( light ) {
  33373. const data = getLightData( light );
  33374. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  33375. self.value = self.value || new Vector3();
  33376. self.value.setFromMatrixPosition( light.matrixWorld );
  33377. self.value.applyMatrix4( camera.matrixWorldInverse );
  33378. } ) );
  33379. }
  33380. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  33381. const sortLights = ( lights ) => {
  33382. return lights.sort( ( a, b ) => a.id - b.id );
  33383. };
  33384. const getLightNodeById = ( id, lightNodes ) => {
  33385. for ( const lightNode of lightNodes ) {
  33386. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  33387. return lightNode;
  33388. }
  33389. }
  33390. return null;
  33391. };
  33392. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  33393. class LightsNode extends Node {
  33394. static get type() {
  33395. return 'LightsNode';
  33396. }
  33397. constructor() {
  33398. super( 'vec3' );
  33399. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  33400. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  33401. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  33402. this._lights = [];
  33403. this._lightNodes = null;
  33404. this._lightNodesHash = null;
  33405. this.global = true;
  33406. }
  33407. getHash( builder ) {
  33408. if ( this._lightNodesHash === null ) {
  33409. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  33410. const hash = [];
  33411. for ( const lightNode of this._lightNodes ) {
  33412. hash.push( lightNode.getSelf().getHash() );
  33413. }
  33414. this._lightNodesHash = 'lights-' + hash.join( ',' );
  33415. }
  33416. return this._lightNodesHash;
  33417. }
  33418. analyze( builder ) {
  33419. const properties = builder.getDataFromNode( this );
  33420. for ( const node of properties.nodes ) {
  33421. node.build( builder );
  33422. }
  33423. }
  33424. setupLightsNode( builder ) {
  33425. const lightNodes = [];
  33426. const previousLightNodes = this._lightNodes;
  33427. const lights = sortLights( this._lights );
  33428. const nodeLibrary = builder.renderer.library;
  33429. for ( const light of lights ) {
  33430. if ( light.isNode ) {
  33431. lightNodes.push( nodeObject( light ) );
  33432. } else {
  33433. let lightNode = null;
  33434. if ( previousLightNodes !== null ) {
  33435. lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node
  33436. }
  33437. if ( lightNode === null ) {
  33438. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  33439. if ( lightNodeClass === null ) {
  33440. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  33441. continue;
  33442. }
  33443. let lightNode = null;
  33444. if ( ! _lightsNodeRef.has( light ) ) {
  33445. lightNode = nodeObject( new lightNodeClass( light ) );
  33446. _lightsNodeRef.set( light, lightNode );
  33447. } else {
  33448. lightNode = _lightsNodeRef.get( light );
  33449. }
  33450. lightNodes.push( lightNode );
  33451. }
  33452. }
  33453. }
  33454. this._lightNodes = lightNodes;
  33455. }
  33456. setupLights( builder, lightNodes ) {
  33457. for ( const lightNode of lightNodes ) {
  33458. lightNode.build( builder );
  33459. }
  33460. }
  33461. setup( builder ) {
  33462. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  33463. const context = builder.context;
  33464. const lightingModel = context.lightingModel;
  33465. let outgoingLightNode = this.outgoingLightNode;
  33466. if ( lightingModel ) {
  33467. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  33468. context.outgoingLight = outgoingLightNode;
  33469. const stack = builder.addStack();
  33470. //
  33471. const properties = builder.getDataFromNode( this );
  33472. properties.nodes = stack.nodes;
  33473. //
  33474. lightingModel.start( context, stack, builder );
  33475. // lights
  33476. this.setupLights( builder, _lightNodes );
  33477. //
  33478. lightingModel.indirect( context, stack, builder );
  33479. //
  33480. const { backdrop, backdropAlpha } = context;
  33481. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  33482. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  33483. if ( backdrop !== null ) {
  33484. if ( backdropAlpha !== null ) {
  33485. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  33486. } else {
  33487. totalDiffuse = vec3( backdrop );
  33488. }
  33489. context.material.transparent = true;
  33490. }
  33491. totalDiffuseNode.assign( totalDiffuse );
  33492. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  33493. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  33494. //
  33495. lightingModel.finish( context, stack, builder );
  33496. //
  33497. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  33498. }
  33499. return outgoingLightNode;
  33500. }
  33501. setLights( lights ) {
  33502. this._lights = lights;
  33503. this._lightNodes = null;
  33504. this._lightNodesHash = null;
  33505. return this;
  33506. }
  33507. getLights() {
  33508. return this._lights;
  33509. }
  33510. get hasLights() {
  33511. return this._lights.length > 0;
  33512. }
  33513. }
  33514. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  33515. const BasicShadowMap = Fn( ( { depthTexture, shadowCoord } ) => {
  33516. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  33517. } );
  33518. const PCFShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  33519. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  33520. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33521. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  33522. const texelSize = vec2( 1 ).div( mapSize );
  33523. const dx0 = texelSize.x.negate().mul( radius );
  33524. const dy0 = texelSize.y.negate().mul( radius );
  33525. const dx1 = texelSize.x.mul( radius );
  33526. const dy1 = texelSize.y.mul( radius );
  33527. const dx2 = dx0.div( 2 );
  33528. const dy2 = dy0.div( 2 );
  33529. const dx3 = dx1.div( 2 );
  33530. const dy3 = dy1.div( 2 );
  33531. return add(
  33532. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  33533. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  33534. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  33535. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  33536. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  33537. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  33538. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  33539. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  33540. depthCompare( shadowCoord.xy, shadowCoord.z ),
  33541. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  33542. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  33543. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  33544. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  33545. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  33546. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  33547. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  33548. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  33549. ).mul( 1 / 17 );
  33550. } );
  33551. const PCFSoftShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  33552. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  33553. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33554. const texelSize = vec2( 1 ).div( mapSize );
  33555. const dx = texelSize.x;
  33556. const dy = texelSize.y;
  33557. const uv = shadowCoord.xy;
  33558. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  33559. uv.subAssign( f.mul( texelSize ) );
  33560. return add(
  33561. depthCompare( uv, shadowCoord.z ),
  33562. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  33563. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  33564. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  33565. mix(
  33566. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  33567. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  33568. f.x
  33569. ),
  33570. mix(
  33571. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  33572. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  33573. f.x
  33574. ),
  33575. mix(
  33576. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  33577. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  33578. f.y
  33579. ),
  33580. mix(
  33581. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  33582. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  33583. f.y
  33584. ),
  33585. mix(
  33586. mix(
  33587. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  33588. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  33589. f.x
  33590. ),
  33591. mix(
  33592. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  33593. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  33594. f.x
  33595. ),
  33596. f.y
  33597. )
  33598. ).mul( 1 / 9 );
  33599. } );
  33600. // VSM
  33601. const VSMShadowMapNode = Fn( ( { depthTexture, shadowCoord } ) => {
  33602. const occlusion = float( 1 ).toVar();
  33603. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  33604. const hardShadow = step( shadowCoord.z, distribution.x );
  33605. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  33606. const distance = shadowCoord.z.sub( distribution.x );
  33607. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  33608. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  33609. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  33610. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  33611. } );
  33612. return occlusion;
  33613. } );
  33614. const VSMPassVertical = Fn( ( { samples, radius, size, shadowPass } ) => {
  33615. const mean = float( 0 ).toVar();
  33616. const squaredMean = float( 0 ).toVar();
  33617. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  33618. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  33619. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  33620. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  33621. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  33622. mean.addAssign( depth );
  33623. squaredMean.addAssign( depth.mul( depth ) );
  33624. } );
  33625. mean.divAssign( samples );
  33626. squaredMean.divAssign( samples );
  33627. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  33628. return vec2( mean, std_dev );
  33629. } );
  33630. const VSMPassHorizontal = Fn( ( { samples, radius, size, shadowPass } ) => {
  33631. const mean = float( 0 ).toVar();
  33632. const squaredMean = float( 0 ).toVar();
  33633. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  33634. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  33635. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  33636. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  33637. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  33638. mean.addAssign( distribution.x );
  33639. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  33640. } );
  33641. mean.divAssign( samples );
  33642. squaredMean.divAssign( samples );
  33643. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  33644. return vec2( mean, std_dev );
  33645. } );
  33646. const _shadowFilterLib = [ BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, VSMShadowMapNode ];
  33647. //
  33648. let _overrideMaterial = null;
  33649. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  33650. class ShadowNode extends Node {
  33651. static get type() {
  33652. return 'ShadowNode';
  33653. }
  33654. constructor( light, shadow = null ) {
  33655. super();
  33656. this.light = light;
  33657. this.shadow = shadow || light.shadow;
  33658. this.shadowMap = null;
  33659. this.vsmShadowMapVertical = null;
  33660. this.vsmShadowMapHorizontal = null;
  33661. this.vsmMaterialVertical = null;
  33662. this.vsmMaterialHorizontal = null;
  33663. this.updateBeforeType = NodeUpdateType.RENDER;
  33664. this._node = null;
  33665. this.isShadowNode = true;
  33666. }
  33667. setupShadow( builder ) {
  33668. const { object, renderer } = builder;
  33669. if ( _overrideMaterial === null ) {
  33670. _overrideMaterial = new NodeMaterial();
  33671. _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  33672. _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  33673. _overrideMaterial.name = 'ShadowMaterial';
  33674. }
  33675. const shadow = this.shadow;
  33676. const shadowMapType = renderer.shadowMap.type;
  33677. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  33678. depthTexture.compareFunction = LessCompare;
  33679. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  33680. shadowMap.depthTexture = depthTexture;
  33681. shadow.camera.updateProjectionMatrix();
  33682. // VSM
  33683. if ( shadowMapType === VSMShadowMap ) {
  33684. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  33685. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  33686. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  33687. const shadowPassVertical = texture( depthTexture );
  33688. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  33689. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  33690. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  33691. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33692. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  33693. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  33694. material.name = 'VSMVertical';
  33695. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  33696. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  33697. material.name = 'VSMHorizontal';
  33698. }
  33699. //
  33700. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  33701. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  33702. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  33703. const position = object.material.shadowPositionNode || positionWorld;
  33704. let shadowCoord = uniform( shadow.matrix ).setGroup( renderGroup ).mul( position.add( transformedNormalWorld.mul( normalBias ) ) );
  33705. let coordZ;
  33706. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  33707. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  33708. coordZ = shadowCoord.z;
  33709. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  33710. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  33711. }
  33712. } else {
  33713. const w = shadowCoord.w;
  33714. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  33715. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  33716. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  33717. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  33718. const cameraNearLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.near );
  33719. const cameraFarLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.far );
  33720. coordZ = perspectiveDepthToLogarithmicDepth( w, cameraNearLocal, cameraFarLocal );
  33721. }
  33722. shadowCoord = vec3(
  33723. shadowCoord.x,
  33724. shadowCoord.y.oneMinus(), // follow webgpu standards
  33725. coordZ.add( bias )
  33726. );
  33727. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  33728. .and( shadowCoord.x.lessThanEqual( 1 ) )
  33729. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  33730. .and( shadowCoord.y.lessThanEqual( 1 ) )
  33731. .and( shadowCoord.z.lessThanEqual( 1 ) );
  33732. //
  33733. const filterFn = shadow.filterNode || _shadowFilterLib[ renderer.shadowMap.type ] || null;
  33734. if ( filterFn === null ) {
  33735. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  33736. }
  33737. const shadowColor = texture( shadowMap.texture, shadowCoord );
  33738. const shadowNode = frustumTest.select( filterFn( { depthTexture: ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture, shadowCoord, shadow } ), float( 1 ) );
  33739. this.shadowMap = shadowMap;
  33740. this.shadow.map = shadowMap;
  33741. return mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) );
  33742. }
  33743. setup( builder ) {
  33744. if ( builder.renderer.shadowMap.enabled === false ) return;
  33745. return this._node !== null ? this._node : ( this._node = this.setupShadow( builder ) );
  33746. }
  33747. updateShadow( frame ) {
  33748. const { shadowMap, light, shadow } = this;
  33749. const { renderer, scene, camera } = frame;
  33750. const shadowType = renderer.shadowMap.type;
  33751. const depthVersion = shadowMap.depthTexture.version;
  33752. this._depthVersionCached = depthVersion;
  33753. const currentOverrideMaterial = scene.overrideMaterial;
  33754. scene.overrideMaterial = _overrideMaterial;
  33755. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  33756. shadow.updateMatrices( light );
  33757. shadow.camera.layers.mask = camera.layers.mask;
  33758. const currentRenderTarget = renderer.getRenderTarget();
  33759. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  33760. renderer.setRenderObjectFunction( ( object, ...params ) => {
  33761. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  33762. renderer.renderObject( object, ...params );
  33763. }
  33764. } );
  33765. renderer.setRenderTarget( shadowMap );
  33766. renderer.render( scene, shadow.camera );
  33767. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  33768. // vsm blur pass
  33769. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  33770. this.vsmPass( renderer );
  33771. }
  33772. renderer.setRenderTarget( currentRenderTarget );
  33773. scene.overrideMaterial = currentOverrideMaterial;
  33774. }
  33775. vsmPass( renderer ) {
  33776. const { shadow } = this;
  33777. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  33778. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  33779. renderer.setRenderTarget( this.vsmShadowMapVertical );
  33780. _quadMesh$1.material = this.vsmMaterialVertical;
  33781. _quadMesh$1.render( renderer );
  33782. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  33783. _quadMesh$1.material = this.vsmMaterialHorizontal;
  33784. _quadMesh$1.render( renderer );
  33785. }
  33786. dispose() {
  33787. this.shadowMap.dispose();
  33788. this.shadowMap = null;
  33789. if ( this.vsmShadowMapVertical !== null ) {
  33790. this.vsmShadowMapVertical.dispose();
  33791. this.vsmShadowMapVertical = null;
  33792. this.vsmMaterialVertical.dispose();
  33793. this.vsmMaterialVertical = null;
  33794. }
  33795. if ( this.vsmShadowMapHorizontal !== null ) {
  33796. this.vsmShadowMapHorizontal.dispose();
  33797. this.vsmShadowMapHorizontal = null;
  33798. this.vsmMaterialHorizontal.dispose();
  33799. this.vsmMaterialHorizontal = null;
  33800. }
  33801. this.updateBeforeType = NodeUpdateType.NONE;
  33802. }
  33803. updateBefore( frame ) {
  33804. const { shadow } = this;
  33805. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  33806. if ( needsUpdate ) {
  33807. this.updateShadow( frame );
  33808. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  33809. shadow.needsUpdate = false;
  33810. }
  33811. }
  33812. }
  33813. }
  33814. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  33815. class AnalyticLightNode extends LightingNode {
  33816. static get type() {
  33817. return 'AnalyticLightNode';
  33818. }
  33819. constructor( light = null ) {
  33820. super();
  33821. this.updateType = NodeUpdateType.FRAME;
  33822. this.light = light;
  33823. this.color = new Color();
  33824. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  33825. this.baseColorNode = null;
  33826. this.shadowNode = null;
  33827. this.shadowColorNode = null;
  33828. this.isAnalyticLightNode = true;
  33829. }
  33830. getCacheKey() {
  33831. return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 );
  33832. }
  33833. getHash() {
  33834. return this.light.uuid;
  33835. }
  33836. setupShadow( builder ) {
  33837. const { renderer } = builder;
  33838. if ( renderer.shadowMap.enabled === false ) return;
  33839. let shadowColorNode = this.shadowColorNode;
  33840. if ( shadowColorNode === null ) {
  33841. const customShadowNode = this.light.shadow.shadowNode;
  33842. let shadowNode;
  33843. if ( customShadowNode !== undefined ) {
  33844. shadowNode = nodeObject( customShadowNode );
  33845. } else {
  33846. shadowNode = shadow( this.light );
  33847. }
  33848. this.shadowNode = shadowNode;
  33849. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  33850. this.baseColorNode = this.colorNode;
  33851. }
  33852. //
  33853. this.colorNode = shadowColorNode;
  33854. }
  33855. setup( builder ) {
  33856. this.colorNode = this.baseColorNode || this.colorNode;
  33857. if ( this.light.castShadow ) {
  33858. if ( builder.object.receiveShadow ) {
  33859. this.setupShadow( builder );
  33860. }
  33861. } else if ( this.shadowNode !== null ) {
  33862. this.shadowNode.dispose();
  33863. }
  33864. }
  33865. update( /*frame*/ ) {
  33866. const { light } = this;
  33867. this.color.copy( light.color ).multiplyScalar( light.intensity );
  33868. }
  33869. }
  33870. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  33871. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  33872. // based upon Frostbite 3 Moving to Physically-based Rendering
  33873. // page 32, equation 26: E[window1]
  33874. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  33875. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  33876. return cutoffDistance.greaterThan( 0 ).select(
  33877. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  33878. distanceFalloff
  33879. );
  33880. } ); // validated
  33881. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  33882. const lightingModel = builder.context.lightingModel;
  33883. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  33884. const lightDirection = lVector.normalize();
  33885. const lightDistance = lVector.length();
  33886. const lightAttenuation = getDistanceAttenuation( {
  33887. lightDistance,
  33888. cutoffDistance,
  33889. decayExponent
  33890. } );
  33891. const lightColor = color.mul( lightAttenuation );
  33892. const reflectedLight = builder.context.reflectedLight;
  33893. lightingModel.direct( {
  33894. lightDirection,
  33895. lightColor,
  33896. reflectedLight
  33897. }, builder.stack, builder );
  33898. } );
  33899. class PointLightNode extends AnalyticLightNode {
  33900. static get type() {
  33901. return 'PointLightNode';
  33902. }
  33903. constructor( light = null ) {
  33904. super( light );
  33905. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  33906. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  33907. }
  33908. update( frame ) {
  33909. const { light } = this;
  33910. super.update( frame );
  33911. this.cutoffDistanceNode.value = light.distance;
  33912. this.decayExponentNode.value = light.decay;
  33913. }
  33914. setup() {
  33915. directPointLight( {
  33916. color: this.colorNode,
  33917. lightViewPosition: lightViewPosition( this.light ),
  33918. cutoffDistance: this.cutoffDistanceNode,
  33919. decayExponent: this.decayExponentNode
  33920. } ).append();
  33921. }
  33922. }
  33923. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  33924. const uv = coord.mul( 2.0 );
  33925. const cx = uv.x.floor();
  33926. const cy = uv.y.floor();
  33927. const result = cx.add( cy ).mod( 2.0 );
  33928. return result.sign();
  33929. } );
  33930. // Three.js Transpiler
  33931. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  33932. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  33933. const f = float( f_immutable ).toVar();
  33934. const t = float( t_immutable ).toVar();
  33935. const b = bool( b_immutable ).toVar();
  33936. return select( b, t, f );
  33937. } ).setLayout( {
  33938. name: 'mx_select',
  33939. type: 'float',
  33940. inputs: [
  33941. { name: 'b', type: 'bool' },
  33942. { name: 't', type: 'float' },
  33943. { name: 'f', type: 'float' }
  33944. ]
  33945. } );
  33946. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  33947. const b = bool( b_immutable ).toVar();
  33948. const val = float( val_immutable ).toVar();
  33949. return select( b, val.negate(), val );
  33950. } ).setLayout( {
  33951. name: 'mx_negate_if',
  33952. type: 'float',
  33953. inputs: [
  33954. { name: 'val', type: 'float' },
  33955. { name: 'b', type: 'bool' }
  33956. ]
  33957. } );
  33958. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  33959. const x = float( x_immutable ).toVar();
  33960. return int( floor( x ) );
  33961. } ).setLayout( {
  33962. name: 'mx_floor',
  33963. type: 'int',
  33964. inputs: [
  33965. { name: 'x', type: 'float' }
  33966. ]
  33967. } );
  33968. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  33969. const x = float( x_immutable ).toVar();
  33970. i.assign( mx_floor( x ) );
  33971. return x.sub( float( i ) );
  33972. } );
  33973. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33974. const t = float( t_immutable ).toVar();
  33975. const s = float( s_immutable ).toVar();
  33976. const v3 = float( v3_immutable ).toVar();
  33977. const v2 = float( v2_immutable ).toVar();
  33978. const v1 = float( v1_immutable ).toVar();
  33979. const v0 = float( v0_immutable ).toVar();
  33980. const s1 = float( sub( 1.0, s ) ).toVar();
  33981. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33982. } ).setLayout( {
  33983. name: 'mx_bilerp_0',
  33984. type: 'float',
  33985. inputs: [
  33986. { name: 'v0', type: 'float' },
  33987. { name: 'v1', type: 'float' },
  33988. { name: 'v2', type: 'float' },
  33989. { name: 'v3', type: 'float' },
  33990. { name: 's', type: 'float' },
  33991. { name: 't', type: 'float' }
  33992. ]
  33993. } );
  33994. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33995. const t = float( t_immutable ).toVar();
  33996. const s = float( s_immutable ).toVar();
  33997. const v3 = vec3( v3_immutable ).toVar();
  33998. const v2 = vec3( v2_immutable ).toVar();
  33999. const v1 = vec3( v1_immutable ).toVar();
  34000. const v0 = vec3( v0_immutable ).toVar();
  34001. const s1 = float( sub( 1.0, s ) ).toVar();
  34002. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  34003. } ).setLayout( {
  34004. name: 'mx_bilerp_1',
  34005. type: 'vec3',
  34006. inputs: [
  34007. { name: 'v0', type: 'vec3' },
  34008. { name: 'v1', type: 'vec3' },
  34009. { name: 'v2', type: 'vec3' },
  34010. { name: 'v3', type: 'vec3' },
  34011. { name: 's', type: 'float' },
  34012. { name: 't', type: 'float' }
  34013. ]
  34014. } );
  34015. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  34016. 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 ] ) => {
  34017. const r = float( r_immutable ).toVar();
  34018. const t = float( t_immutable ).toVar();
  34019. const s = float( s_immutable ).toVar();
  34020. const v7 = float( v7_immutable ).toVar();
  34021. const v6 = float( v6_immutable ).toVar();
  34022. const v5 = float( v5_immutable ).toVar();
  34023. const v4 = float( v4_immutable ).toVar();
  34024. const v3 = float( v3_immutable ).toVar();
  34025. const v2 = float( v2_immutable ).toVar();
  34026. const v1 = float( v1_immutable ).toVar();
  34027. const v0 = float( v0_immutable ).toVar();
  34028. const s1 = float( sub( 1.0, s ) ).toVar();
  34029. const t1 = float( sub( 1.0, t ) ).toVar();
  34030. const r1 = float( sub( 1.0, r ) ).toVar();
  34031. 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 ) ) ) ) ) );
  34032. } ).setLayout( {
  34033. name: 'mx_trilerp_0',
  34034. type: 'float',
  34035. inputs: [
  34036. { name: 'v0', type: 'float' },
  34037. { name: 'v1', type: 'float' },
  34038. { name: 'v2', type: 'float' },
  34039. { name: 'v3', type: 'float' },
  34040. { name: 'v4', type: 'float' },
  34041. { name: 'v5', type: 'float' },
  34042. { name: 'v6', type: 'float' },
  34043. { name: 'v7', type: 'float' },
  34044. { name: 's', type: 'float' },
  34045. { name: 't', type: 'float' },
  34046. { name: 'r', type: 'float' }
  34047. ]
  34048. } );
  34049. 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 ] ) => {
  34050. const r = float( r_immutable ).toVar();
  34051. const t = float( t_immutable ).toVar();
  34052. const s = float( s_immutable ).toVar();
  34053. const v7 = vec3( v7_immutable ).toVar();
  34054. const v6 = vec3( v6_immutable ).toVar();
  34055. const v5 = vec3( v5_immutable ).toVar();
  34056. const v4 = vec3( v4_immutable ).toVar();
  34057. const v3 = vec3( v3_immutable ).toVar();
  34058. const v2 = vec3( v2_immutable ).toVar();
  34059. const v1 = vec3( v1_immutable ).toVar();
  34060. const v0 = vec3( v0_immutable ).toVar();
  34061. const s1 = float( sub( 1.0, s ) ).toVar();
  34062. const t1 = float( sub( 1.0, t ) ).toVar();
  34063. const r1 = float( sub( 1.0, r ) ).toVar();
  34064. 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 ) ) ) ) ) );
  34065. } ).setLayout( {
  34066. name: 'mx_trilerp_1',
  34067. type: 'vec3',
  34068. inputs: [
  34069. { name: 'v0', type: 'vec3' },
  34070. { name: 'v1', type: 'vec3' },
  34071. { name: 'v2', type: 'vec3' },
  34072. { name: 'v3', type: 'vec3' },
  34073. { name: 'v4', type: 'vec3' },
  34074. { name: 'v5', type: 'vec3' },
  34075. { name: 'v6', type: 'vec3' },
  34076. { name: 'v7', type: 'vec3' },
  34077. { name: 's', type: 'float' },
  34078. { name: 't', type: 'float' },
  34079. { name: 'r', type: 'float' }
  34080. ]
  34081. } );
  34082. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  34083. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  34084. const y = float( y_immutable ).toVar();
  34085. const x = float( x_immutable ).toVar();
  34086. const hash = uint( hash_immutable ).toVar();
  34087. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  34088. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  34089. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  34090. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  34091. } ).setLayout( {
  34092. name: 'mx_gradient_float_0',
  34093. type: 'float',
  34094. inputs: [
  34095. { name: 'hash', type: 'uint' },
  34096. { name: 'x', type: 'float' },
  34097. { name: 'y', type: 'float' }
  34098. ]
  34099. } );
  34100. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  34101. const z = float( z_immutable ).toVar();
  34102. const y = float( y_immutable ).toVar();
  34103. const x = float( x_immutable ).toVar();
  34104. const hash = uint( hash_immutable ).toVar();
  34105. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  34106. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  34107. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  34108. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  34109. } ).setLayout( {
  34110. name: 'mx_gradient_float_1',
  34111. type: 'float',
  34112. inputs: [
  34113. { name: 'hash', type: 'uint' },
  34114. { name: 'x', type: 'float' },
  34115. { name: 'y', type: 'float' },
  34116. { name: 'z', type: 'float' }
  34117. ]
  34118. } );
  34119. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  34120. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  34121. const y = float( y_immutable ).toVar();
  34122. const x = float( x_immutable ).toVar();
  34123. const hash = uvec3( hash_immutable ).toVar();
  34124. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  34125. } ).setLayout( {
  34126. name: 'mx_gradient_vec3_0',
  34127. type: 'vec3',
  34128. inputs: [
  34129. { name: 'hash', type: 'uvec3' },
  34130. { name: 'x', type: 'float' },
  34131. { name: 'y', type: 'float' }
  34132. ]
  34133. } );
  34134. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  34135. const z = float( z_immutable ).toVar();
  34136. const y = float( y_immutable ).toVar();
  34137. const x = float( x_immutable ).toVar();
  34138. const hash = uvec3( hash_immutable ).toVar();
  34139. 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 ) );
  34140. } ).setLayout( {
  34141. name: 'mx_gradient_vec3_1',
  34142. type: 'vec3',
  34143. inputs: [
  34144. { name: 'hash', type: 'uvec3' },
  34145. { name: 'x', type: 'float' },
  34146. { name: 'y', type: 'float' },
  34147. { name: 'z', type: 'float' }
  34148. ]
  34149. } );
  34150. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  34151. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34152. const v = float( v_immutable ).toVar();
  34153. return mul( 0.6616, v );
  34154. } ).setLayout( {
  34155. name: 'mx_gradient_scale2d_0',
  34156. type: 'float',
  34157. inputs: [
  34158. { name: 'v', type: 'float' }
  34159. ]
  34160. } );
  34161. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34162. const v = float( v_immutable ).toVar();
  34163. return mul( 0.9820, v );
  34164. } ).setLayout( {
  34165. name: 'mx_gradient_scale3d_0',
  34166. type: 'float',
  34167. inputs: [
  34168. { name: 'v', type: 'float' }
  34169. ]
  34170. } );
  34171. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34172. const v = vec3( v_immutable ).toVar();
  34173. return mul( 0.6616, v );
  34174. } ).setLayout( {
  34175. name: 'mx_gradient_scale2d_1',
  34176. type: 'vec3',
  34177. inputs: [
  34178. { name: 'v', type: 'vec3' }
  34179. ]
  34180. } );
  34181. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  34182. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34183. const v = vec3( v_immutable ).toVar();
  34184. return mul( 0.9820, v );
  34185. } ).setLayout( {
  34186. name: 'mx_gradient_scale3d_1',
  34187. type: 'vec3',
  34188. inputs: [
  34189. { name: 'v', type: 'vec3' }
  34190. ]
  34191. } );
  34192. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  34193. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  34194. const k = int( k_immutable ).toVar();
  34195. const x = uint( x_immutable ).toVar();
  34196. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  34197. } ).setLayout( {
  34198. name: 'mx_rotl32',
  34199. type: 'uint',
  34200. inputs: [
  34201. { name: 'x', type: 'uint' },
  34202. { name: 'k', type: 'int' }
  34203. ]
  34204. } );
  34205. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  34206. a.subAssign( c );
  34207. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  34208. c.addAssign( b );
  34209. b.subAssign( a );
  34210. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  34211. a.addAssign( c );
  34212. c.subAssign( b );
  34213. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  34214. b.addAssign( a );
  34215. a.subAssign( c );
  34216. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  34217. c.addAssign( b );
  34218. b.subAssign( a );
  34219. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  34220. a.addAssign( c );
  34221. c.subAssign( b );
  34222. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  34223. b.addAssign( a );
  34224. } );
  34225. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  34226. const c = uint( c_immutable ).toVar();
  34227. const b = uint( b_immutable ).toVar();
  34228. const a = uint( a_immutable ).toVar();
  34229. c.bitXorAssign( b );
  34230. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  34231. a.bitXorAssign( c );
  34232. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  34233. b.bitXorAssign( a );
  34234. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  34235. c.bitXorAssign( b );
  34236. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  34237. a.bitXorAssign( c );
  34238. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  34239. b.bitXorAssign( a );
  34240. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  34241. c.bitXorAssign( b );
  34242. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  34243. return c;
  34244. } ).setLayout( {
  34245. name: 'mx_bjfinal',
  34246. type: 'uint',
  34247. inputs: [
  34248. { name: 'a', type: 'uint' },
  34249. { name: 'b', type: 'uint' },
  34250. { name: 'c', type: 'uint' }
  34251. ]
  34252. } );
  34253. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  34254. const bits = uint( bits_immutable ).toVar();
  34255. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  34256. } ).setLayout( {
  34257. name: 'mx_bits_to_01',
  34258. type: 'float',
  34259. inputs: [
  34260. { name: 'bits', type: 'uint' }
  34261. ]
  34262. } );
  34263. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  34264. const t = float( t_immutable ).toVar();
  34265. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  34266. } ).setLayout( {
  34267. name: 'mx_fade',
  34268. type: 'float',
  34269. inputs: [
  34270. { name: 't', type: 'float' }
  34271. ]
  34272. } );
  34273. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  34274. const x = int( x_immutable ).toVar();
  34275. const len = uint( uint( 1 ) ).toVar();
  34276. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  34277. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  34278. } ).setLayout( {
  34279. name: 'mx_hash_int_0',
  34280. type: 'uint',
  34281. inputs: [
  34282. { name: 'x', type: 'int' }
  34283. ]
  34284. } );
  34285. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  34286. const y = int( y_immutable ).toVar();
  34287. const x = int( x_immutable ).toVar();
  34288. const len = uint( uint( 2 ) ).toVar();
  34289. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34290. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34291. a.addAssign( uint( x ) );
  34292. b.addAssign( uint( y ) );
  34293. return mx_bjfinal( a, b, c );
  34294. } ).setLayout( {
  34295. name: 'mx_hash_int_1',
  34296. type: 'uint',
  34297. inputs: [
  34298. { name: 'x', type: 'int' },
  34299. { name: 'y', type: 'int' }
  34300. ]
  34301. } );
  34302. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34303. const z = int( z_immutable ).toVar();
  34304. const y = int( y_immutable ).toVar();
  34305. const x = int( x_immutable ).toVar();
  34306. const len = uint( uint( 3 ) ).toVar();
  34307. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34308. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34309. a.addAssign( uint( x ) );
  34310. b.addAssign( uint( y ) );
  34311. c.addAssign( uint( z ) );
  34312. return mx_bjfinal( a, b, c );
  34313. } ).setLayout( {
  34314. name: 'mx_hash_int_2',
  34315. type: 'uint',
  34316. inputs: [
  34317. { name: 'x', type: 'int' },
  34318. { name: 'y', type: 'int' },
  34319. { name: 'z', type: 'int' }
  34320. ]
  34321. } );
  34322. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  34323. const xx = int( xx_immutable ).toVar();
  34324. const z = int( z_immutable ).toVar();
  34325. const y = int( y_immutable ).toVar();
  34326. const x = int( x_immutable ).toVar();
  34327. const len = uint( uint( 4 ) ).toVar();
  34328. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34329. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34330. a.addAssign( uint( x ) );
  34331. b.addAssign( uint( y ) );
  34332. c.addAssign( uint( z ) );
  34333. mx_bjmix( a, b, c );
  34334. a.addAssign( uint( xx ) );
  34335. return mx_bjfinal( a, b, c );
  34336. } ).setLayout( {
  34337. name: 'mx_hash_int_3',
  34338. type: 'uint',
  34339. inputs: [
  34340. { name: 'x', type: 'int' },
  34341. { name: 'y', type: 'int' },
  34342. { name: 'z', type: 'int' },
  34343. { name: 'xx', type: 'int' }
  34344. ]
  34345. } );
  34346. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  34347. const yy = int( yy_immutable ).toVar();
  34348. const xx = int( xx_immutable ).toVar();
  34349. const z = int( z_immutable ).toVar();
  34350. const y = int( y_immutable ).toVar();
  34351. const x = int( x_immutable ).toVar();
  34352. const len = uint( uint( 5 ) ).toVar();
  34353. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34354. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34355. a.addAssign( uint( x ) );
  34356. b.addAssign( uint( y ) );
  34357. c.addAssign( uint( z ) );
  34358. mx_bjmix( a, b, c );
  34359. a.addAssign( uint( xx ) );
  34360. b.addAssign( uint( yy ) );
  34361. return mx_bjfinal( a, b, c );
  34362. } ).setLayout( {
  34363. name: 'mx_hash_int_4',
  34364. type: 'uint',
  34365. inputs: [
  34366. { name: 'x', type: 'int' },
  34367. { name: 'y', type: 'int' },
  34368. { name: 'z', type: 'int' },
  34369. { name: 'xx', type: 'int' },
  34370. { name: 'yy', type: 'int' }
  34371. ]
  34372. } );
  34373. 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 ] );
  34374. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  34375. const y = int( y_immutable ).toVar();
  34376. const x = int( x_immutable ).toVar();
  34377. const h = uint( mx_hash_int( x, y ) ).toVar();
  34378. const result = uvec3().toVar();
  34379. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34380. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34381. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34382. return result;
  34383. } ).setLayout( {
  34384. name: 'mx_hash_vec3_0',
  34385. type: 'uvec3',
  34386. inputs: [
  34387. { name: 'x', type: 'int' },
  34388. { name: 'y', type: 'int' }
  34389. ]
  34390. } );
  34391. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34392. const z = int( z_immutable ).toVar();
  34393. const y = int( y_immutable ).toVar();
  34394. const x = int( x_immutable ).toVar();
  34395. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  34396. const result = uvec3().toVar();
  34397. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34398. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34399. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34400. return result;
  34401. } ).setLayout( {
  34402. name: 'mx_hash_vec3_1',
  34403. type: 'uvec3',
  34404. inputs: [
  34405. { name: 'x', type: 'int' },
  34406. { name: 'y', type: 'int' },
  34407. { name: 'z', type: 'int' }
  34408. ]
  34409. } );
  34410. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  34411. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34412. const p = vec2( p_immutable ).toVar();
  34413. const X = int().toVar(), Y = int().toVar();
  34414. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34415. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34416. const u = float( mx_fade( fx ) ).toVar();
  34417. const v = float( mx_fade( fy ) ).toVar();
  34418. 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();
  34419. return mx_gradient_scale2d( result );
  34420. } ).setLayout( {
  34421. name: 'mx_perlin_noise_float_0',
  34422. type: 'float',
  34423. inputs: [
  34424. { name: 'p', type: 'vec2' }
  34425. ]
  34426. } );
  34427. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34428. const p = vec3( p_immutable ).toVar();
  34429. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34430. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34431. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34432. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34433. const u = float( mx_fade( fx ) ).toVar();
  34434. const v = float( mx_fade( fy ) ).toVar();
  34435. const w = float( mx_fade( fz ) ).toVar();
  34436. 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();
  34437. return mx_gradient_scale3d( result );
  34438. } ).setLayout( {
  34439. name: 'mx_perlin_noise_float_1',
  34440. type: 'float',
  34441. inputs: [
  34442. { name: 'p', type: 'vec3' }
  34443. ]
  34444. } );
  34445. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  34446. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34447. const p = vec2( p_immutable ).toVar();
  34448. const X = int().toVar(), Y = int().toVar();
  34449. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34450. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34451. const u = float( mx_fade( fx ) ).toVar();
  34452. const v = float( mx_fade( fy ) ).toVar();
  34453. 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();
  34454. return mx_gradient_scale2d( result );
  34455. } ).setLayout( {
  34456. name: 'mx_perlin_noise_vec3_0',
  34457. type: 'vec3',
  34458. inputs: [
  34459. { name: 'p', type: 'vec2' }
  34460. ]
  34461. } );
  34462. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34463. const p = vec3( p_immutable ).toVar();
  34464. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34465. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34466. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34467. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34468. const u = float( mx_fade( fx ) ).toVar();
  34469. const v = float( mx_fade( fy ) ).toVar();
  34470. const w = float( mx_fade( fz ) ).toVar();
  34471. 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();
  34472. return mx_gradient_scale3d( result );
  34473. } ).setLayout( {
  34474. name: 'mx_perlin_noise_vec3_1',
  34475. type: 'vec3',
  34476. inputs: [
  34477. { name: 'p', type: 'vec3' }
  34478. ]
  34479. } );
  34480. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  34481. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34482. const p = float( p_immutable ).toVar();
  34483. const ix = int( mx_floor( p ) ).toVar();
  34484. return mx_bits_to_01( mx_hash_int( ix ) );
  34485. } ).setLayout( {
  34486. name: 'mx_cell_noise_float_0',
  34487. type: 'float',
  34488. inputs: [
  34489. { name: 'p', type: 'float' }
  34490. ]
  34491. } );
  34492. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34493. const p = vec2( p_immutable ).toVar();
  34494. const ix = int( mx_floor( p.x ) ).toVar();
  34495. const iy = int( mx_floor( p.y ) ).toVar();
  34496. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  34497. } ).setLayout( {
  34498. name: 'mx_cell_noise_float_1',
  34499. type: 'float',
  34500. inputs: [
  34501. { name: 'p', type: 'vec2' }
  34502. ]
  34503. } );
  34504. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34505. const p = vec3( p_immutable ).toVar();
  34506. const ix = int( mx_floor( p.x ) ).toVar();
  34507. const iy = int( mx_floor( p.y ) ).toVar();
  34508. const iz = int( mx_floor( p.z ) ).toVar();
  34509. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  34510. } ).setLayout( {
  34511. name: 'mx_cell_noise_float_2',
  34512. type: 'float',
  34513. inputs: [
  34514. { name: 'p', type: 'vec3' }
  34515. ]
  34516. } );
  34517. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34518. const p = vec4( p_immutable ).toVar();
  34519. const ix = int( mx_floor( p.x ) ).toVar();
  34520. const iy = int( mx_floor( p.y ) ).toVar();
  34521. const iz = int( mx_floor( p.z ) ).toVar();
  34522. const iw = int( mx_floor( p.w ) ).toVar();
  34523. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  34524. } ).setLayout( {
  34525. name: 'mx_cell_noise_float_3',
  34526. type: 'float',
  34527. inputs: [
  34528. { name: 'p', type: 'vec4' }
  34529. ]
  34530. } );
  34531. 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 ] );
  34532. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34533. const p = float( p_immutable ).toVar();
  34534. const ix = int( mx_floor( p ) ).toVar();
  34535. 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 ) ) ) );
  34536. } ).setLayout( {
  34537. name: 'mx_cell_noise_vec3_0',
  34538. type: 'vec3',
  34539. inputs: [
  34540. { name: 'p', type: 'float' }
  34541. ]
  34542. } );
  34543. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34544. const p = vec2( p_immutable ).toVar();
  34545. const ix = int( mx_floor( p.x ) ).toVar();
  34546. const iy = int( mx_floor( p.y ) ).toVar();
  34547. 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 ) ) ) );
  34548. } ).setLayout( {
  34549. name: 'mx_cell_noise_vec3_1',
  34550. type: 'vec3',
  34551. inputs: [
  34552. { name: 'p', type: 'vec2' }
  34553. ]
  34554. } );
  34555. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34556. const p = vec3( p_immutable ).toVar();
  34557. const ix = int( mx_floor( p.x ) ).toVar();
  34558. const iy = int( mx_floor( p.y ) ).toVar();
  34559. const iz = int( mx_floor( p.z ) ).toVar();
  34560. 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 ) ) ) );
  34561. } ).setLayout( {
  34562. name: 'mx_cell_noise_vec3_2',
  34563. type: 'vec3',
  34564. inputs: [
  34565. { name: 'p', type: 'vec3' }
  34566. ]
  34567. } );
  34568. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34569. const p = vec4( p_immutable ).toVar();
  34570. const ix = int( mx_floor( p.x ) ).toVar();
  34571. const iy = int( mx_floor( p.y ) ).toVar();
  34572. const iz = int( mx_floor( p.z ) ).toVar();
  34573. const iw = int( mx_floor( p.w ) ).toVar();
  34574. 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 ) ) ) );
  34575. } ).setLayout( {
  34576. name: 'mx_cell_noise_vec3_3',
  34577. type: 'vec3',
  34578. inputs: [
  34579. { name: 'p', type: 'vec4' }
  34580. ]
  34581. } );
  34582. 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 ] );
  34583. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34584. const diminish = float( diminish_immutable ).toVar();
  34585. const lacunarity = float( lacunarity_immutable ).toVar();
  34586. const octaves = int( octaves_immutable ).toVar();
  34587. const p = vec3( p_immutable ).toVar();
  34588. const result = float( 0.0 ).toVar();
  34589. const amplitude = float( 1.0 ).toVar();
  34590. Loop( octaves, () => {
  34591. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  34592. amplitude.mulAssign( diminish );
  34593. p.mulAssign( lacunarity );
  34594. } );
  34595. return result;
  34596. } ).setLayout( {
  34597. name: 'mx_fractal_noise_float',
  34598. type: 'float',
  34599. inputs: [
  34600. { name: 'p', type: 'vec3' },
  34601. { name: 'octaves', type: 'int' },
  34602. { name: 'lacunarity', type: 'float' },
  34603. { name: 'diminish', type: 'float' }
  34604. ]
  34605. } );
  34606. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34607. const diminish = float( diminish_immutable ).toVar();
  34608. const lacunarity = float( lacunarity_immutable ).toVar();
  34609. const octaves = int( octaves_immutable ).toVar();
  34610. const p = vec3( p_immutable ).toVar();
  34611. const result = vec3( 0.0 ).toVar();
  34612. const amplitude = float( 1.0 ).toVar();
  34613. Loop( octaves, () => {
  34614. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  34615. amplitude.mulAssign( diminish );
  34616. p.mulAssign( lacunarity );
  34617. } );
  34618. return result;
  34619. } ).setLayout( {
  34620. name: 'mx_fractal_noise_vec3',
  34621. type: 'vec3',
  34622. inputs: [
  34623. { name: 'p', type: 'vec3' },
  34624. { name: 'octaves', type: 'int' },
  34625. { name: 'lacunarity', type: 'float' },
  34626. { name: 'diminish', type: 'float' }
  34627. ]
  34628. } );
  34629. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34630. const diminish = float( diminish_immutable ).toVar();
  34631. const lacunarity = float( lacunarity_immutable ).toVar();
  34632. const octaves = int( octaves_immutable ).toVar();
  34633. const p = vec3( p_immutable ).toVar();
  34634. 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 ) );
  34635. } ).setLayout( {
  34636. name: 'mx_fractal_noise_vec2',
  34637. type: 'vec2',
  34638. inputs: [
  34639. { name: 'p', type: 'vec3' },
  34640. { name: 'octaves', type: 'int' },
  34641. { name: 'lacunarity', type: 'float' },
  34642. { name: 'diminish', type: 'float' }
  34643. ]
  34644. } );
  34645. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34646. const diminish = float( diminish_immutable ).toVar();
  34647. const lacunarity = float( lacunarity_immutable ).toVar();
  34648. const octaves = int( octaves_immutable ).toVar();
  34649. const p = vec3( p_immutable ).toVar();
  34650. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  34651. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  34652. return vec4( c, f );
  34653. } ).setLayout( {
  34654. name: 'mx_fractal_noise_vec4',
  34655. type: 'vec4',
  34656. inputs: [
  34657. { name: 'p', type: 'vec3' },
  34658. { name: 'octaves', type: 'int' },
  34659. { name: 'lacunarity', type: 'float' },
  34660. { name: 'diminish', type: 'float' }
  34661. ]
  34662. } );
  34663. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  34664. const metric = int( metric_immutable ).toVar();
  34665. const jitter = float( jitter_immutable ).toVar();
  34666. const yoff = int( yoff_immutable ).toVar();
  34667. const xoff = int( xoff_immutable ).toVar();
  34668. const y = int( y_immutable ).toVar();
  34669. const x = int( x_immutable ).toVar();
  34670. const p = vec2( p_immutable ).toVar();
  34671. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  34672. const off = vec2( tmp.x, tmp.y ).toVar();
  34673. off.subAssign( 0.5 );
  34674. off.mulAssign( jitter );
  34675. off.addAssign( 0.5 );
  34676. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  34677. const diff = vec2( cellpos.sub( p ) ).toVar();
  34678. If( metric.equal( int( 2 ) ), () => {
  34679. return abs( diff.x ).add( abs( diff.y ) );
  34680. } );
  34681. If( metric.equal( int( 3 ) ), () => {
  34682. return max$1( abs( diff.x ), abs( diff.y ) );
  34683. } );
  34684. return dot( diff, diff );
  34685. } ).setLayout( {
  34686. name: 'mx_worley_distance_0',
  34687. type: 'float',
  34688. inputs: [
  34689. { name: 'p', type: 'vec2' },
  34690. { name: 'x', type: 'int' },
  34691. { name: 'y', type: 'int' },
  34692. { name: 'xoff', type: 'int' },
  34693. { name: 'yoff', type: 'int' },
  34694. { name: 'jitter', type: 'float' },
  34695. { name: 'metric', type: 'int' }
  34696. ]
  34697. } );
  34698. 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 ] ) => {
  34699. const metric = int( metric_immutable ).toVar();
  34700. const jitter = float( jitter_immutable ).toVar();
  34701. const zoff = int( zoff_immutable ).toVar();
  34702. const yoff = int( yoff_immutable ).toVar();
  34703. const xoff = int( xoff_immutable ).toVar();
  34704. const z = int( z_immutable ).toVar();
  34705. const y = int( y_immutable ).toVar();
  34706. const x = int( x_immutable ).toVar();
  34707. const p = vec3( p_immutable ).toVar();
  34708. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  34709. off.subAssign( 0.5 );
  34710. off.mulAssign( jitter );
  34711. off.addAssign( 0.5 );
  34712. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  34713. const diff = vec3( cellpos.sub( p ) ).toVar();
  34714. If( metric.equal( int( 2 ) ), () => {
  34715. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  34716. } );
  34717. If( metric.equal( int( 3 ) ), () => {
  34718. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  34719. } );
  34720. return dot( diff, diff );
  34721. } ).setLayout( {
  34722. name: 'mx_worley_distance_1',
  34723. type: 'float',
  34724. inputs: [
  34725. { name: 'p', type: 'vec3' },
  34726. { name: 'x', type: 'int' },
  34727. { name: 'y', type: 'int' },
  34728. { name: 'z', type: 'int' },
  34729. { name: 'xoff', type: 'int' },
  34730. { name: 'yoff', type: 'int' },
  34731. { name: 'zoff', type: 'int' },
  34732. { name: 'jitter', type: 'float' },
  34733. { name: 'metric', type: 'int' }
  34734. ]
  34735. } );
  34736. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  34737. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34738. const metric = int( metric_immutable ).toVar();
  34739. const jitter = float( jitter_immutable ).toVar();
  34740. const p = vec2( p_immutable ).toVar();
  34741. const X = int().toVar(), Y = int().toVar();
  34742. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34743. const sqdist = float( 1e6 ).toVar();
  34744. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34745. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34746. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34747. sqdist.assign( min$1( sqdist, dist ) );
  34748. } );
  34749. } );
  34750. If( metric.equal( int( 0 ) ), () => {
  34751. sqdist.assign( sqrt( sqdist ) );
  34752. } );
  34753. return sqdist;
  34754. } ).setLayout( {
  34755. name: 'mx_worley_noise_float_0',
  34756. type: 'float',
  34757. inputs: [
  34758. { name: 'p', type: 'vec2' },
  34759. { name: 'jitter', type: 'float' },
  34760. { name: 'metric', type: 'int' }
  34761. ]
  34762. } );
  34763. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34764. const metric = int( metric_immutable ).toVar();
  34765. const jitter = float( jitter_immutable ).toVar();
  34766. const p = vec2( p_immutable ).toVar();
  34767. const X = int().toVar(), Y = int().toVar();
  34768. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34769. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34770. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34771. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34772. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34773. If( dist.lessThan( sqdist.x ), () => {
  34774. sqdist.y.assign( sqdist.x );
  34775. sqdist.x.assign( dist );
  34776. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34777. sqdist.y.assign( dist );
  34778. } );
  34779. } );
  34780. } );
  34781. If( metric.equal( int( 0 ) ), () => {
  34782. sqdist.assign( sqrt( sqdist ) );
  34783. } );
  34784. return sqdist;
  34785. } ).setLayout( {
  34786. name: 'mx_worley_noise_vec2_0',
  34787. type: 'vec2',
  34788. inputs: [
  34789. { name: 'p', type: 'vec2' },
  34790. { name: 'jitter', type: 'float' },
  34791. { name: 'metric', type: 'int' }
  34792. ]
  34793. } );
  34794. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34795. const metric = int( metric_immutable ).toVar();
  34796. const jitter = float( jitter_immutable ).toVar();
  34797. const p = vec2( p_immutable ).toVar();
  34798. const X = int().toVar(), Y = int().toVar();
  34799. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34800. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34801. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34802. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34803. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34804. If( dist.lessThan( sqdist.x ), () => {
  34805. sqdist.z.assign( sqdist.y );
  34806. sqdist.y.assign( sqdist.x );
  34807. sqdist.x.assign( dist );
  34808. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34809. sqdist.z.assign( sqdist.y );
  34810. sqdist.y.assign( dist );
  34811. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  34812. sqdist.z.assign( dist );
  34813. } );
  34814. } );
  34815. } );
  34816. If( metric.equal( int( 0 ) ), () => {
  34817. sqdist.assign( sqrt( sqdist ) );
  34818. } );
  34819. return sqdist;
  34820. } ).setLayout( {
  34821. name: 'mx_worley_noise_vec3_0',
  34822. type: 'vec3',
  34823. inputs: [
  34824. { name: 'p', type: 'vec2' },
  34825. { name: 'jitter', type: 'float' },
  34826. { name: 'metric', type: 'int' }
  34827. ]
  34828. } );
  34829. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34830. const metric = int( metric_immutable ).toVar();
  34831. const jitter = float( jitter_immutable ).toVar();
  34832. const p = vec3( p_immutable ).toVar();
  34833. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34834. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34835. const sqdist = float( 1e6 ).toVar();
  34836. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34837. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34838. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34839. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34840. sqdist.assign( min$1( sqdist, dist ) );
  34841. } );
  34842. } );
  34843. } );
  34844. If( metric.equal( int( 0 ) ), () => {
  34845. sqdist.assign( sqrt( sqdist ) );
  34846. } );
  34847. return sqdist;
  34848. } ).setLayout( {
  34849. name: 'mx_worley_noise_float_1',
  34850. type: 'float',
  34851. inputs: [
  34852. { name: 'p', type: 'vec3' },
  34853. { name: 'jitter', type: 'float' },
  34854. { name: 'metric', type: 'int' }
  34855. ]
  34856. } );
  34857. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  34858. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34859. const metric = int( metric_immutable ).toVar();
  34860. const jitter = float( jitter_immutable ).toVar();
  34861. const p = vec3( p_immutable ).toVar();
  34862. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34863. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34864. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34865. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34866. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34867. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34868. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34869. If( dist.lessThan( sqdist.x ), () => {
  34870. sqdist.y.assign( sqdist.x );
  34871. sqdist.x.assign( dist );
  34872. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34873. sqdist.y.assign( dist );
  34874. } );
  34875. } );
  34876. } );
  34877. } );
  34878. If( metric.equal( int( 0 ) ), () => {
  34879. sqdist.assign( sqrt( sqdist ) );
  34880. } );
  34881. return sqdist;
  34882. } ).setLayout( {
  34883. name: 'mx_worley_noise_vec2_1',
  34884. type: 'vec2',
  34885. inputs: [
  34886. { name: 'p', type: 'vec3' },
  34887. { name: 'jitter', type: 'float' },
  34888. { name: 'metric', type: 'int' }
  34889. ]
  34890. } );
  34891. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  34892. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34893. const metric = int( metric_immutable ).toVar();
  34894. const jitter = float( jitter_immutable ).toVar();
  34895. const p = vec3( p_immutable ).toVar();
  34896. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34897. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34898. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34899. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34900. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34901. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34902. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34903. If( dist.lessThan( sqdist.x ), () => {
  34904. sqdist.z.assign( sqdist.y );
  34905. sqdist.y.assign( sqdist.x );
  34906. sqdist.x.assign( dist );
  34907. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34908. sqdist.z.assign( sqdist.y );
  34909. sqdist.y.assign( dist );
  34910. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  34911. sqdist.z.assign( dist );
  34912. } );
  34913. } );
  34914. } );
  34915. } );
  34916. If( metric.equal( int( 0 ) ), () => {
  34917. sqdist.assign( sqrt( sqdist ) );
  34918. } );
  34919. return sqdist;
  34920. } ).setLayout( {
  34921. name: 'mx_worley_noise_vec3_1',
  34922. type: 'vec3',
  34923. inputs: [
  34924. { name: 'p', type: 'vec3' },
  34925. { name: 'jitter', type: 'float' },
  34926. { name: 'metric', type: 'int' }
  34927. ]
  34928. } );
  34929. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  34930. // Three.js Transpiler
  34931. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  34932. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  34933. const s = hsv.y;
  34934. const v = hsv.z;
  34935. const result = vec3().toVar();
  34936. If( s.lessThan( 0.0001 ), () => {
  34937. result.assign( vec3( v, v, v ) );
  34938. } ).Else( () => {
  34939. let h = hsv.x;
  34940. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  34941. const hi = int( trunc( h ) );
  34942. const f = h.sub( float( hi ) );
  34943. const p = v.mul( s.oneMinus() );
  34944. const q = v.mul( s.mul( f ).oneMinus() );
  34945. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  34946. If( hi.equal( int( 0 ) ), () => {
  34947. result.assign( vec3( v, t, p ) );
  34948. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  34949. result.assign( vec3( q, v, p ) );
  34950. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  34951. result.assign( vec3( p, v, t ) );
  34952. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  34953. result.assign( vec3( p, q, v ) );
  34954. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  34955. result.assign( vec3( t, p, v ) );
  34956. } ).Else( () => {
  34957. result.assign( vec3( v, p, q ) );
  34958. } );
  34959. } );
  34960. return result;
  34961. } ).setLayout( {
  34962. name: 'mx_hsvtorgb',
  34963. type: 'vec3',
  34964. inputs: [
  34965. { name: 'hsv', type: 'vec3' }
  34966. ]
  34967. } );
  34968. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  34969. const c = vec3( c_immutable ).toVar();
  34970. const r = float( c.x ).toVar();
  34971. const g = float( c.y ).toVar();
  34972. const b = float( c.z ).toVar();
  34973. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  34974. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  34975. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  34976. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  34977. v.assign( maxcomp );
  34978. If( maxcomp.greaterThan( 0.0 ), () => {
  34979. s.assign( delta.div( maxcomp ) );
  34980. } ).Else( () => {
  34981. s.assign( 0.0 );
  34982. } );
  34983. If( s.lessThanEqual( 0.0 ), () => {
  34984. h.assign( 0.0 );
  34985. } ).Else( () => {
  34986. If( r.greaterThanEqual( maxcomp ), () => {
  34987. h.assign( g.sub( b ).div( delta ) );
  34988. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  34989. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  34990. } ).Else( () => {
  34991. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  34992. } );
  34993. h.mulAssign( 1.0 / 6.0 );
  34994. If( h.lessThan( 0.0 ), () => {
  34995. h.addAssign( 1.0 );
  34996. } );
  34997. } );
  34998. return vec3( h, s, v );
  34999. } ).setLayout( {
  35000. name: 'mx_rgbtohsv',
  35001. type: 'vec3',
  35002. inputs: [
  35003. { name: 'c', type: 'vec3' }
  35004. ]
  35005. } );
  35006. // Three.js Transpiler
  35007. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  35008. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  35009. const color = vec3( color_immutable ).toVar();
  35010. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  35011. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  35012. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  35013. return mix( linSeg, powSeg, isAbove );
  35014. } ).setLayout( {
  35015. name: 'mx_srgb_texture_to_lin_rec709',
  35016. type: 'vec3',
  35017. inputs: [
  35018. { name: 'color', type: 'vec3' }
  35019. ]
  35020. } );
  35021. const mx_aastep = ( threshold, value ) => {
  35022. threshold = float( threshold );
  35023. value = float( value );
  35024. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  35025. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  35026. };
  35027. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  35028. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  35029. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  35030. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  35031. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  35032. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  35033. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  35034. const mx_safepower = ( in1, in2 = 1 ) => {
  35035. in1 = float( in1 );
  35036. return in1.abs().pow( in2 ).mul( in1.sign() );
  35037. };
  35038. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  35039. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  35040. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  35041. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  35042. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  35043. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  35044. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  35045. return noise_vec4.mul( amplitude ).add( pivot );
  35046. };
  35047. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  35048. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  35049. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  35050. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  35051. 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 );
  35052. 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 );
  35053. 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 );
  35054. 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 );
  35055. // https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html
  35056. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  35057. const nDir = normalize( normal ).toVar( 'nDir' );
  35058. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  35059. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  35060. const rbminmax = vec3().toVar( 'rbminmax' );
  35061. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  35062. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  35063. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  35064. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  35065. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  35066. return boxIntersection.sub( cubePos );
  35067. } );
  35068. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  35069. // normal is assumed to have unit length
  35070. const x = normal.x, y = normal.y, z = normal.z;
  35071. // band 0
  35072. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  35073. // band 1
  35074. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  35075. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  35076. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  35077. // band 2
  35078. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  35079. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  35080. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  35081. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  35082. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  35083. return result;
  35084. } );
  35085. const _clearColor$1 = /*@__PURE__*/ new Color4();
  35086. class Background extends DataMap {
  35087. constructor( renderer, nodes ) {
  35088. super();
  35089. this.renderer = renderer;
  35090. this.nodes = nodes;
  35091. }
  35092. update( scene, renderList, renderContext ) {
  35093. const renderer = this.renderer;
  35094. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  35095. let forceClear = false;
  35096. if ( background === null ) {
  35097. // no background settings, use clear color configuration from the renderer
  35098. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  35099. _clearColor$1.a = renderer._clearColor.a;
  35100. } else if ( background.isColor === true ) {
  35101. // background is an opaque color
  35102. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  35103. _clearColor$1.a = 1;
  35104. forceClear = true;
  35105. } else if ( background.isNode === true ) {
  35106. const sceneData = this.get( scene );
  35107. const backgroundNode = background;
  35108. _clearColor$1.copy( renderer._clearColor );
  35109. let backgroundMesh = sceneData.backgroundMesh;
  35110. if ( backgroundMesh === undefined ) {
  35111. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  35112. // @TODO: Add Texture2D support using node context
  35113. getUV: () => backgroundRotation.mul( normalWorld ),
  35114. getTextureLevel: () => backgroundBlurriness
  35115. } );
  35116. let viewProj = modelViewProjection();
  35117. viewProj = viewProj.setZ( viewProj.w );
  35118. const nodeMaterial = new NodeMaterial();
  35119. nodeMaterial.name = 'Background.material';
  35120. nodeMaterial.side = BackSide;
  35121. nodeMaterial.depthTest = false;
  35122. nodeMaterial.depthWrite = false;
  35123. nodeMaterial.fog = false;
  35124. nodeMaterial.lights = false;
  35125. nodeMaterial.vertexNode = viewProj;
  35126. nodeMaterial.colorNode = backgroundMeshNode;
  35127. sceneData.backgroundMeshNode = backgroundMeshNode;
  35128. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  35129. backgroundMesh.frustumCulled = false;
  35130. backgroundMesh.name = 'Background.mesh';
  35131. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  35132. this.matrixWorld.copyPosition( camera.matrixWorld );
  35133. };
  35134. }
  35135. const backgroundCacheKey = backgroundNode.getCacheKey();
  35136. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  35137. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  35138. sceneData.backgroundMeshNode.needsUpdate = true;
  35139. backgroundMesh.material.needsUpdate = true;
  35140. sceneData.backgroundCacheKey = backgroundCacheKey;
  35141. }
  35142. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  35143. } else {
  35144. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  35145. }
  35146. //
  35147. if ( renderer.autoClear === true || forceClear === true ) {
  35148. const clearColorValue = renderContext.clearColorValue;
  35149. clearColorValue.r = _clearColor$1.r;
  35150. clearColorValue.g = _clearColor$1.g;
  35151. clearColorValue.b = _clearColor$1.b;
  35152. clearColorValue.a = _clearColor$1.a;
  35153. // premultiply alpha
  35154. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  35155. clearColorValue.r *= clearColorValue.a;
  35156. clearColorValue.g *= clearColorValue.a;
  35157. clearColorValue.b *= clearColorValue.a;
  35158. }
  35159. //
  35160. renderContext.depthClearValue = renderer._clearDepth;
  35161. renderContext.stencilClearValue = renderer._clearStencil;
  35162. renderContext.clearColor = renderer.autoClearColor === true;
  35163. renderContext.clearDepth = renderer.autoClearDepth === true;
  35164. renderContext.clearStencil = renderer.autoClearStencil === true;
  35165. } else {
  35166. renderContext.clearColor = false;
  35167. renderContext.clearDepth = false;
  35168. renderContext.clearStencil = false;
  35169. }
  35170. }
  35171. }
  35172. let _id$5 = 0;
  35173. class BindGroup {
  35174. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  35175. this.name = name;
  35176. this.bindings = bindings;
  35177. this.index = index;
  35178. this.bindingsReference = bindingsReference;
  35179. this.id = _id$5 ++;
  35180. }
  35181. }
  35182. class NodeBuilderState {
  35183. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  35184. this.vertexShader = vertexShader;
  35185. this.fragmentShader = fragmentShader;
  35186. this.computeShader = computeShader;
  35187. this.transforms = transforms;
  35188. this.nodeAttributes = nodeAttributes;
  35189. this.bindings = bindings;
  35190. this.updateNodes = updateNodes;
  35191. this.updateBeforeNodes = updateBeforeNodes;
  35192. this.updateAfterNodes = updateAfterNodes;
  35193. this.monitor = monitor;
  35194. this.usedTimes = 0;
  35195. }
  35196. createBindings() {
  35197. const bindings = [];
  35198. for ( const instanceGroup of this.bindings ) {
  35199. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  35200. if ( shared !== true ) {
  35201. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  35202. bindings.push( bindingsGroup );
  35203. for ( const instanceBinding of instanceGroup.bindings ) {
  35204. bindingsGroup.bindings.push( instanceBinding.clone() );
  35205. }
  35206. } else {
  35207. bindings.push( instanceGroup );
  35208. }
  35209. }
  35210. return bindings;
  35211. }
  35212. }
  35213. class NodeAttribute {
  35214. constructor( name, type, node = null ) {
  35215. this.isNodeAttribute = true;
  35216. this.name = name;
  35217. this.type = type;
  35218. this.node = node;
  35219. }
  35220. }
  35221. class NodeUniform {
  35222. constructor( name, type, node ) {
  35223. this.isNodeUniform = true;
  35224. this.name = name;
  35225. this.type = type;
  35226. this.node = node.getSelf();
  35227. }
  35228. get value() {
  35229. return this.node.value;
  35230. }
  35231. set value( val ) {
  35232. this.node.value = val;
  35233. }
  35234. get id() {
  35235. return this.node.id;
  35236. }
  35237. get groupNode() {
  35238. return this.node.groupNode;
  35239. }
  35240. }
  35241. class NodeVar {
  35242. constructor( name, type ) {
  35243. this.isNodeVar = true;
  35244. this.name = name;
  35245. this.type = type;
  35246. }
  35247. }
  35248. class NodeVarying extends NodeVar {
  35249. constructor( name, type ) {
  35250. super( name, type );
  35251. this.needsInterpolation = false;
  35252. this.isNodeVarying = true;
  35253. }
  35254. }
  35255. class NodeCode {
  35256. constructor( name, type, code = '' ) {
  35257. this.name = name;
  35258. this.type = type;
  35259. this.code = code;
  35260. Object.defineProperty( this, 'isNodeCode', { value: true } );
  35261. }
  35262. }
  35263. let id = 0;
  35264. class NodeCache {
  35265. constructor( parent = null ) {
  35266. this.id = id ++;
  35267. this.nodesData = new WeakMap();
  35268. this.parent = parent;
  35269. }
  35270. getData( node ) {
  35271. let data = this.nodesData.get( node );
  35272. if ( data === undefined && this.parent !== null ) {
  35273. data = this.parent.getData( node );
  35274. }
  35275. return data;
  35276. }
  35277. setData( node, data ) {
  35278. this.nodesData.set( node, data );
  35279. }
  35280. }
  35281. class Uniform {
  35282. constructor( name, value ) {
  35283. this.name = name;
  35284. this.value = value;
  35285. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  35286. this.itemSize = 0;
  35287. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  35288. }
  35289. setValue( value ) {
  35290. this.value = value;
  35291. }
  35292. getValue() {
  35293. return this.value;
  35294. }
  35295. }
  35296. class NumberUniform extends Uniform {
  35297. constructor( name, value = 0 ) {
  35298. super( name, value );
  35299. this.isNumberUniform = true;
  35300. this.boundary = 4;
  35301. this.itemSize = 1;
  35302. }
  35303. }
  35304. class Vector2Uniform extends Uniform {
  35305. constructor( name, value = new Vector2() ) {
  35306. super( name, value );
  35307. this.isVector2Uniform = true;
  35308. this.boundary = 8;
  35309. this.itemSize = 2;
  35310. }
  35311. }
  35312. class Vector3Uniform extends Uniform {
  35313. constructor( name, value = new Vector3() ) {
  35314. super( name, value );
  35315. this.isVector3Uniform = true;
  35316. this.boundary = 16;
  35317. this.itemSize = 3;
  35318. }
  35319. }
  35320. class Vector4Uniform extends Uniform {
  35321. constructor( name, value = new Vector4() ) {
  35322. super( name, value );
  35323. this.isVector4Uniform = true;
  35324. this.boundary = 16;
  35325. this.itemSize = 4;
  35326. }
  35327. }
  35328. class ColorUniform extends Uniform {
  35329. constructor( name, value = new Color() ) {
  35330. super( name, value );
  35331. this.isColorUniform = true;
  35332. this.boundary = 16;
  35333. this.itemSize = 3;
  35334. }
  35335. }
  35336. class Matrix3Uniform extends Uniform {
  35337. constructor( name, value = new Matrix3() ) {
  35338. super( name, value );
  35339. this.isMatrix3Uniform = true;
  35340. this.boundary = 48;
  35341. this.itemSize = 12;
  35342. }
  35343. }
  35344. class Matrix4Uniform extends Uniform {
  35345. constructor( name, value = new Matrix4() ) {
  35346. super( name, value );
  35347. this.isMatrix4Uniform = true;
  35348. this.boundary = 64;
  35349. this.itemSize = 16;
  35350. }
  35351. }
  35352. class NumberNodeUniform extends NumberUniform {
  35353. constructor( nodeUniform ) {
  35354. super( nodeUniform.name, nodeUniform.value );
  35355. this.nodeUniform = nodeUniform;
  35356. }
  35357. getValue() {
  35358. return this.nodeUniform.value;
  35359. }
  35360. }
  35361. class Vector2NodeUniform extends Vector2Uniform {
  35362. constructor( nodeUniform ) {
  35363. super( nodeUniform.name, nodeUniform.value );
  35364. this.nodeUniform = nodeUniform;
  35365. }
  35366. getValue() {
  35367. return this.nodeUniform.value;
  35368. }
  35369. }
  35370. class Vector3NodeUniform extends Vector3Uniform {
  35371. constructor( nodeUniform ) {
  35372. super( nodeUniform.name, nodeUniform.value );
  35373. this.nodeUniform = nodeUniform;
  35374. }
  35375. getValue() {
  35376. return this.nodeUniform.value;
  35377. }
  35378. }
  35379. class Vector4NodeUniform extends Vector4Uniform {
  35380. constructor( nodeUniform ) {
  35381. super( nodeUniform.name, nodeUniform.value );
  35382. this.nodeUniform = nodeUniform;
  35383. }
  35384. getValue() {
  35385. return this.nodeUniform.value;
  35386. }
  35387. }
  35388. class ColorNodeUniform extends ColorUniform {
  35389. constructor( nodeUniform ) {
  35390. super( nodeUniform.name, nodeUniform.value );
  35391. this.nodeUniform = nodeUniform;
  35392. }
  35393. getValue() {
  35394. return this.nodeUniform.value;
  35395. }
  35396. }
  35397. class Matrix3NodeUniform extends Matrix3Uniform {
  35398. constructor( nodeUniform ) {
  35399. super( nodeUniform.name, nodeUniform.value );
  35400. this.nodeUniform = nodeUniform;
  35401. }
  35402. getValue() {
  35403. return this.nodeUniform.value;
  35404. }
  35405. }
  35406. class Matrix4NodeUniform extends Matrix4Uniform {
  35407. constructor( nodeUniform ) {
  35408. super( nodeUniform.name, nodeUniform.value );
  35409. this.nodeUniform = nodeUniform;
  35410. }
  35411. getValue() {
  35412. return this.nodeUniform.value;
  35413. }
  35414. }
  35415. const LOD_MIN = 4;
  35416. // The standard deviations (radians) associated with the extra mips. These are
  35417. // chosen to approximate a Trowbridge-Reitz distribution function times the
  35418. // geometric shadowing function. These sigma values squared must match the
  35419. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  35420. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  35421. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  35422. // samples and exit early, but not recompile the shader.
  35423. const MAX_SAMPLES = 20;
  35424. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  35425. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  35426. const _clearColor = /*@__PURE__*/ new Color();
  35427. let _oldTarget = null;
  35428. let _oldActiveCubeFace = 0;
  35429. let _oldActiveMipmapLevel = 0;
  35430. // Golden Ratio
  35431. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  35432. const INV_PHI = 1 / PHI;
  35433. // Vertices of a dodecahedron (except the opposites, which represent the
  35434. // same axis), used as axis directions evenly spread on a sphere.
  35435. const _axisDirections = [
  35436. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  35437. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  35438. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  35439. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  35440. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  35441. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  35442. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  35443. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  35444. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  35445. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  35446. ];
  35447. //
  35448. // WebGPU Face indices
  35449. const _faceLib = [
  35450. 3, 1, 5,
  35451. 0, 4, 2
  35452. ];
  35453. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  35454. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  35455. /**
  35456. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  35457. * (PMREM) from a cubeMap environment texture. This allows different levels of
  35458. * blur to be quickly accessed based on material roughness. It is packed into a
  35459. * special CubeUV format that allows us to perform custom interpolation so that
  35460. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  35461. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  35462. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  35463. * higher roughness levels. In this way we maintain resolution to smoothly
  35464. * interpolate diffuse lighting while limiting sampling computation.
  35465. *
  35466. * Paper: Fast, Accurate Image-Based Lighting
  35467. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  35468. */
  35469. class PMREMGenerator {
  35470. constructor( renderer ) {
  35471. this._renderer = renderer;
  35472. this._pingPongRenderTarget = null;
  35473. this._lodMax = 0;
  35474. this._cubeSize = 0;
  35475. this._lodPlanes = [];
  35476. this._sizeLods = [];
  35477. this._sigmas = [];
  35478. this._lodMeshes = [];
  35479. this._blurMaterial = null;
  35480. this._cubemapMaterial = null;
  35481. this._equirectMaterial = null;
  35482. this._backgroundBox = null;
  35483. }
  35484. /**
  35485. * Generates a PMREM from a supplied Scene, which can be faster than using an
  35486. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  35487. * in radians to be applied to the scene before PMREM generation. Optional near
  35488. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  35489. * is placed at the origin).
  35490. */
  35491. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  35492. _oldTarget = this._renderer.getRenderTarget();
  35493. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  35494. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  35495. this._setSize( 256 );
  35496. const cubeUVRenderTarget = this._allocateTargets();
  35497. cubeUVRenderTarget.depthBuffer = true;
  35498. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  35499. if ( sigma > 0 ) {
  35500. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  35501. }
  35502. this._applyPMREM( cubeUVRenderTarget );
  35503. this._cleanup( cubeUVRenderTarget );
  35504. return cubeUVRenderTarget;
  35505. }
  35506. /**
  35507. * Generates a PMREM from an equirectangular texture, which can be either LDR
  35508. * or HDR. The ideal input image size is 1k (1024 x 512),
  35509. * as this matches best with the 256 x 256 cubemap output.
  35510. */
  35511. fromEquirectangular( equirectangular, renderTarget = null ) {
  35512. return this._fromTexture( equirectangular, renderTarget );
  35513. }
  35514. /**
  35515. * Generates a PMREM from an cubemap texture, which can be either LDR
  35516. * or HDR. The ideal input cube size is 256 x 256,
  35517. * as this matches best with the 256 x 256 cubemap output.
  35518. */
  35519. fromCubemap( cubemap, renderTarget = null ) {
  35520. return this._fromTexture( cubemap, renderTarget );
  35521. }
  35522. /**
  35523. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  35524. * your texture's network fetch for increased concurrency.
  35525. */
  35526. async compileCubemapShader() {
  35527. if ( this._cubemapMaterial === null ) {
  35528. this._cubemapMaterial = _getCubemapMaterial();
  35529. await this._compileMaterial( this._cubemapMaterial );
  35530. }
  35531. }
  35532. /**
  35533. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  35534. * your texture's network fetch for increased concurrency.
  35535. */
  35536. async compileEquirectangularShader() {
  35537. if ( this._equirectMaterial === null ) {
  35538. this._equirectMaterial = _getEquirectMaterial();
  35539. await this._compileMaterial( this._equirectMaterial );
  35540. }
  35541. }
  35542. /**
  35543. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  35544. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  35545. * one of them will cause any others to also become unusable.
  35546. */
  35547. dispose() {
  35548. this._dispose();
  35549. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  35550. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  35551. if ( this._backgroundBox !== null ) {
  35552. this._backgroundBox.geometry.dispose();
  35553. this._backgroundBox.material.dispose();
  35554. }
  35555. }
  35556. // private interface
  35557. _setSize( cubeSize ) {
  35558. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  35559. this._cubeSize = Math.pow( 2, this._lodMax );
  35560. }
  35561. _dispose() {
  35562. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  35563. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  35564. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  35565. this._lodPlanes[ i ].dispose();
  35566. }
  35567. }
  35568. _cleanup( outputTarget ) {
  35569. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  35570. outputTarget.scissorTest = false;
  35571. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  35572. }
  35573. _fromTexture( texture, renderTarget ) {
  35574. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  35575. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  35576. } else { // Equirectangular
  35577. this._setSize( texture.image.width / 4 );
  35578. }
  35579. _oldTarget = this._renderer.getRenderTarget();
  35580. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  35581. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  35582. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  35583. this._textureToCubeUV( texture, cubeUVRenderTarget );
  35584. this._applyPMREM( cubeUVRenderTarget );
  35585. this._cleanup( cubeUVRenderTarget );
  35586. return cubeUVRenderTarget;
  35587. }
  35588. _allocateTargets() {
  35589. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  35590. const height = 4 * this._cubeSize;
  35591. const params = {
  35592. magFilter: LinearFilter,
  35593. minFilter: LinearFilter,
  35594. generateMipmaps: false,
  35595. type: HalfFloatType,
  35596. format: RGBAFormat,
  35597. colorSpace: LinearSRGBColorSpace,
  35598. //depthBuffer: false
  35599. };
  35600. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  35601. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  35602. if ( this._pingPongRenderTarget !== null ) {
  35603. this._dispose();
  35604. }
  35605. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  35606. const { _lodMax } = this;
  35607. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  35608. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  35609. }
  35610. return cubeUVRenderTarget;
  35611. }
  35612. async _compileMaterial( material ) {
  35613. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  35614. await this._renderer.compile( tmpMesh, _flatCamera );
  35615. }
  35616. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  35617. const cubeCamera = _cubeCamera;
  35618. cubeCamera.near = near;
  35619. cubeCamera.far = far;
  35620. // px, py, pz, nx, ny, nz
  35621. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  35622. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  35623. const renderer = this._renderer;
  35624. const originalAutoClear = renderer.autoClear;
  35625. renderer.getClearColor( _clearColor );
  35626. renderer.autoClear = false;
  35627. let backgroundBox = this._backgroundBox;
  35628. if ( backgroundBox === null ) {
  35629. const backgroundMaterial = new MeshBasicMaterial( {
  35630. name: 'PMREM.Background',
  35631. side: BackSide,
  35632. depthWrite: false,
  35633. depthTest: false
  35634. } );
  35635. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  35636. }
  35637. let useSolidColor = false;
  35638. const background = scene.background;
  35639. if ( background ) {
  35640. if ( background.isColor ) {
  35641. backgroundBox.material.color.copy( background );
  35642. scene.background = null;
  35643. useSolidColor = true;
  35644. }
  35645. } else {
  35646. backgroundBox.material.color.copy( _clearColor );
  35647. useSolidColor = true;
  35648. }
  35649. renderer.setRenderTarget( cubeUVRenderTarget );
  35650. renderer.clear();
  35651. if ( useSolidColor ) {
  35652. renderer.render( backgroundBox, cubeCamera );
  35653. }
  35654. for ( let i = 0; i < 6; i ++ ) {
  35655. const col = i % 3;
  35656. if ( col === 0 ) {
  35657. cubeCamera.up.set( 0, upSign[ i ], 0 );
  35658. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  35659. } else if ( col === 1 ) {
  35660. cubeCamera.up.set( 0, 0, upSign[ i ] );
  35661. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  35662. } else {
  35663. cubeCamera.up.set( 0, upSign[ i ], 0 );
  35664. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  35665. }
  35666. const size = this._cubeSize;
  35667. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  35668. renderer.render( scene, cubeCamera );
  35669. }
  35670. renderer.autoClear = originalAutoClear;
  35671. scene.background = background;
  35672. }
  35673. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  35674. const renderer = this._renderer;
  35675. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  35676. if ( isCubeTexture ) {
  35677. if ( this._cubemapMaterial === null ) {
  35678. this._cubemapMaterial = _getCubemapMaterial( texture );
  35679. }
  35680. } else {
  35681. if ( this._equirectMaterial === null ) {
  35682. this._equirectMaterial = _getEquirectMaterial( texture );
  35683. }
  35684. }
  35685. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  35686. material.fragmentNode.value = texture;
  35687. const mesh = this._lodMeshes[ 0 ];
  35688. mesh.material = material;
  35689. const size = this._cubeSize;
  35690. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  35691. renderer.setRenderTarget( cubeUVRenderTarget );
  35692. renderer.render( mesh, _flatCamera );
  35693. }
  35694. _applyPMREM( cubeUVRenderTarget ) {
  35695. const renderer = this._renderer;
  35696. const autoClear = renderer.autoClear;
  35697. renderer.autoClear = false;
  35698. const n = this._lodPlanes.length;
  35699. for ( let i = 1; i < n; i ++ ) {
  35700. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  35701. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  35702. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  35703. }
  35704. renderer.autoClear = autoClear;
  35705. }
  35706. /**
  35707. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  35708. * vertically and horizontally, but this breaks down on a cube. Here we apply
  35709. * the blur latitudinally (around the poles), and then longitudinally (towards
  35710. * the poles) to approximate the orthogonally-separable blur. It is least
  35711. * accurate at the poles, but still does a decent job.
  35712. */
  35713. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  35714. const pingPongRenderTarget = this._pingPongRenderTarget;
  35715. this._halfBlur(
  35716. cubeUVRenderTarget,
  35717. pingPongRenderTarget,
  35718. lodIn,
  35719. lodOut,
  35720. sigma,
  35721. 'latitudinal',
  35722. poleAxis );
  35723. this._halfBlur(
  35724. pingPongRenderTarget,
  35725. cubeUVRenderTarget,
  35726. lodOut,
  35727. lodOut,
  35728. sigma,
  35729. 'longitudinal',
  35730. poleAxis );
  35731. }
  35732. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  35733. const renderer = this._renderer;
  35734. const blurMaterial = this._blurMaterial;
  35735. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  35736. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  35737. }
  35738. // Number of standard deviations at which to cut off the discrete approximation.
  35739. const STANDARD_DEVIATIONS = 3;
  35740. const blurMesh = this._lodMeshes[ lodOut ];
  35741. blurMesh.material = blurMaterial;
  35742. const blurUniforms = blurMaterial.uniforms;
  35743. const pixels = this._sizeLods[ lodIn ] - 1;
  35744. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  35745. const sigmaPixels = sigmaRadians / radiansPerPixel;
  35746. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  35747. if ( samples > MAX_SAMPLES ) {
  35748. console.warn( `sigmaRadians, ${
  35749. sigmaRadians}, is too large and will clip, as it requested ${
  35750. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  35751. }
  35752. const weights = [];
  35753. let sum = 0;
  35754. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  35755. const x = i / sigmaPixels;
  35756. const weight = Math.exp( - x * x / 2 );
  35757. weights.push( weight );
  35758. if ( i === 0 ) {
  35759. sum += weight;
  35760. } else if ( i < samples ) {
  35761. sum += 2 * weight;
  35762. }
  35763. }
  35764. for ( let i = 0; i < weights.length; i ++ ) {
  35765. weights[ i ] = weights[ i ] / sum;
  35766. }
  35767. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  35768. blurUniforms.envMap.value = targetIn.texture;
  35769. blurUniforms.samples.value = samples;
  35770. blurUniforms.weights.array = weights;
  35771. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  35772. if ( poleAxis ) {
  35773. blurUniforms.poleAxis.value = poleAxis;
  35774. }
  35775. const { _lodMax } = this;
  35776. blurUniforms.dTheta.value = radiansPerPixel;
  35777. blurUniforms.mipInt.value = _lodMax - lodIn;
  35778. const outputSize = this._sizeLods[ lodOut ];
  35779. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  35780. const y = 4 * ( this._cubeSize - outputSize );
  35781. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  35782. renderer.setRenderTarget( targetOut );
  35783. renderer.render( blurMesh, _flatCamera );
  35784. }
  35785. }
  35786. function _createPlanes( lodMax ) {
  35787. const lodPlanes = [];
  35788. const sizeLods = [];
  35789. const sigmas = [];
  35790. const lodMeshes = [];
  35791. let lod = lodMax;
  35792. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  35793. for ( let i = 0; i < totalLods; i ++ ) {
  35794. const sizeLod = Math.pow( 2, lod );
  35795. sizeLods.push( sizeLod );
  35796. let sigma = 1.0 / sizeLod;
  35797. if ( i > lodMax - LOD_MIN ) {
  35798. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  35799. } else if ( i === 0 ) {
  35800. sigma = 0;
  35801. }
  35802. sigmas.push( sigma );
  35803. const texelSize = 1.0 / ( sizeLod - 2 );
  35804. const min = - texelSize;
  35805. const max = 1 + texelSize;
  35806. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  35807. const cubeFaces = 6;
  35808. const vertices = 6;
  35809. const positionSize = 3;
  35810. const uvSize = 2;
  35811. const faceIndexSize = 1;
  35812. const position = new Float32Array( positionSize * vertices * cubeFaces );
  35813. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  35814. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  35815. for ( let face = 0; face < cubeFaces; face ++ ) {
  35816. const x = ( face % 3 ) * 2 / 3 - 1;
  35817. const y = face > 2 ? 0 : - 1;
  35818. const coordinates = [
  35819. x, y, 0,
  35820. x + 2 / 3, y, 0,
  35821. x + 2 / 3, y + 1, 0,
  35822. x, y, 0,
  35823. x + 2 / 3, y + 1, 0,
  35824. x, y + 1, 0
  35825. ];
  35826. const faceIdx = _faceLib[ face ];
  35827. position.set( coordinates, positionSize * vertices * faceIdx );
  35828. uv.set( uv1, uvSize * vertices * faceIdx );
  35829. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  35830. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  35831. }
  35832. const planes = new BufferGeometry();
  35833. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  35834. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  35835. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  35836. lodPlanes.push( planes );
  35837. lodMeshes.push( new Mesh( planes, null ) );
  35838. if ( lod > LOD_MIN ) {
  35839. lod --;
  35840. }
  35841. }
  35842. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  35843. }
  35844. function _createRenderTarget( width, height, params ) {
  35845. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  35846. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  35847. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  35848. cubeUVRenderTarget.texture.isPMREMTexture = true;
  35849. cubeUVRenderTarget.scissorTest = true;
  35850. return cubeUVRenderTarget;
  35851. }
  35852. function _setViewport( target, x, y, width, height ) {
  35853. target.viewport.set( x, y, width, height );
  35854. target.scissor.set( x, y, width, height );
  35855. }
  35856. function _getMaterial( type ) {
  35857. const material = new NodeMaterial();
  35858. material.depthTest = false;
  35859. material.depthWrite = false;
  35860. material.blending = NoBlending;
  35861. material.name = `PMREM_${ type }`;
  35862. return material;
  35863. }
  35864. function _getBlurShader( lodMax, width, height ) {
  35865. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  35866. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  35867. const dTheta = uniform( 0 );
  35868. const n = float( MAX_SAMPLES );
  35869. const latitudinal = uniform( 0 ); // false, bool
  35870. const samples = uniform( 1 ); // int
  35871. const envMap = texture( null );
  35872. const mipInt = uniform( 0 ); // int
  35873. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  35874. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  35875. const CUBEUV_MAX_MIP = float( lodMax );
  35876. const materialUniforms = {
  35877. n,
  35878. latitudinal,
  35879. weights,
  35880. poleAxis,
  35881. outputDirection,
  35882. dTheta,
  35883. samples,
  35884. envMap,
  35885. mipInt,
  35886. CUBEUV_TEXEL_WIDTH,
  35887. CUBEUV_TEXEL_HEIGHT,
  35888. CUBEUV_MAX_MIP
  35889. };
  35890. const material = _getMaterial( 'blur' );
  35891. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  35892. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  35893. return material;
  35894. }
  35895. function _getCubemapMaterial( envTexture ) {
  35896. const material = _getMaterial( 'cubemap' );
  35897. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  35898. return material;
  35899. }
  35900. function _getEquirectMaterial( envTexture ) {
  35901. const material = _getMaterial( 'equirect' );
  35902. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  35903. return material;
  35904. }
  35905. const rendererCache = new WeakMap();
  35906. const typeFromLength = new Map( [
  35907. [ 2, 'vec2' ],
  35908. [ 3, 'vec3' ],
  35909. [ 4, 'vec4' ],
  35910. [ 9, 'mat3' ],
  35911. [ 16, 'mat4' ]
  35912. ] );
  35913. const typeFromArray = new Map( [
  35914. [ Int8Array, 'int' ],
  35915. [ Int16Array, 'int' ],
  35916. [ Int32Array, 'int' ],
  35917. [ Uint8Array, 'uint' ],
  35918. [ Uint16Array, 'uint' ],
  35919. [ Uint32Array, 'uint' ],
  35920. [ Float32Array, 'float' ]
  35921. ] );
  35922. const toFloat = ( value ) => {
  35923. if ( /e/g.test( value ) ) {
  35924. return String( value ).replace( /\+/g, '' );
  35925. } else {
  35926. value = Number( value );
  35927. return value + ( value % 1 ? '' : '.0' );
  35928. }
  35929. };
  35930. class NodeBuilder {
  35931. constructor( object, renderer, parser ) {
  35932. this.object = object;
  35933. this.material = ( object && object.material ) || null;
  35934. this.geometry = ( object && object.geometry ) || null;
  35935. this.renderer = renderer;
  35936. this.parser = parser;
  35937. this.scene = null;
  35938. this.camera = null;
  35939. this.nodes = [];
  35940. this.sequentialNodes = [];
  35941. this.updateNodes = [];
  35942. this.updateBeforeNodes = [];
  35943. this.updateAfterNodes = [];
  35944. this.hashNodes = {};
  35945. this.monitor = null;
  35946. this.lightsNode = null;
  35947. this.environmentNode = null;
  35948. this.fogNode = null;
  35949. this.clippingContext = null;
  35950. this.vertexShader = null;
  35951. this.fragmentShader = null;
  35952. this.computeShader = null;
  35953. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  35954. this.flowCode = { vertex: '', fragment: '', compute: '' };
  35955. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  35956. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  35957. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  35958. this.bindingsIndexes = {};
  35959. this.bindGroups = null;
  35960. this.attributes = [];
  35961. this.bufferAttributes = [];
  35962. this.varyings = [];
  35963. this.codes = {};
  35964. this.vars = {};
  35965. this.flow = { code: '' };
  35966. this.chaining = [];
  35967. this.stack = stack();
  35968. this.stacks = [];
  35969. this.tab = '\t';
  35970. this.currentFunctionNode = null;
  35971. this.context = {
  35972. material: this.material
  35973. };
  35974. this.cache = new NodeCache();
  35975. this.globalCache = this.cache;
  35976. this.flowsData = new WeakMap();
  35977. this.shaderStage = null;
  35978. this.buildStage = null;
  35979. this.useComparisonMethod = false;
  35980. }
  35981. getBindGroupsCache() {
  35982. let bindGroupsCache = rendererCache.get( this.renderer );
  35983. if ( bindGroupsCache === undefined ) {
  35984. bindGroupsCache = new ChainMap();
  35985. rendererCache.set( this.renderer, bindGroupsCache );
  35986. }
  35987. return bindGroupsCache;
  35988. }
  35989. createRenderTarget( width, height, options ) {
  35990. return new RenderTarget( width, height, options );
  35991. }
  35992. createCubeRenderTarget( size, options ) {
  35993. return new CubeRenderTarget( size, options );
  35994. }
  35995. createPMREMGenerator() {
  35996. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  35997. return new PMREMGenerator( this.renderer );
  35998. }
  35999. includes( node ) {
  36000. return this.nodes.includes( node );
  36001. }
  36002. _getBindGroup( groupName, bindings ) {
  36003. const bindGroupsCache = this.getBindGroupsCache();
  36004. //
  36005. const bindingsArray = [];
  36006. let sharedGroup = true;
  36007. for ( const binding of bindings ) {
  36008. bindingsArray.push( binding );
  36009. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  36010. }
  36011. //
  36012. let bindGroup;
  36013. if ( sharedGroup ) {
  36014. bindGroup = bindGroupsCache.get( bindingsArray );
  36015. if ( bindGroup === undefined ) {
  36016. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  36017. bindGroupsCache.set( bindingsArray, bindGroup );
  36018. }
  36019. } else {
  36020. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  36021. }
  36022. return bindGroup;
  36023. }
  36024. getBindGroupArray( groupName, shaderStage ) {
  36025. const bindings = this.bindings[ shaderStage ];
  36026. let bindGroup = bindings[ groupName ];
  36027. if ( bindGroup === undefined ) {
  36028. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  36029. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  36030. }
  36031. bindings[ groupName ] = bindGroup = [];
  36032. }
  36033. return bindGroup;
  36034. }
  36035. getBindings() {
  36036. let bindingsGroups = this.bindGroups;
  36037. if ( bindingsGroups === null ) {
  36038. const groups = {};
  36039. const bindings = this.bindings;
  36040. for ( const shaderStage of shaderStages ) {
  36041. for ( const groupName in bindings[ shaderStage ] ) {
  36042. const uniforms = bindings[ shaderStage ][ groupName ];
  36043. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  36044. groupUniforms.push( ...uniforms );
  36045. }
  36046. }
  36047. bindingsGroups = [];
  36048. for ( const groupName in groups ) {
  36049. const group = groups[ groupName ];
  36050. const bindingsGroup = this._getBindGroup( groupName, group );
  36051. bindingsGroups.push( bindingsGroup );
  36052. }
  36053. this.bindGroups = bindingsGroups;
  36054. }
  36055. return bindingsGroups;
  36056. }
  36057. sortBindingGroups() {
  36058. const bindingsGroups = this.getBindings();
  36059. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  36060. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  36061. const bindingGroup = bindingsGroups[ i ];
  36062. this.bindingsIndexes[ bindingGroup.name ].group = i;
  36063. bindingGroup.index = i;
  36064. }
  36065. }
  36066. setHashNode( node, hash ) {
  36067. this.hashNodes[ hash ] = node;
  36068. }
  36069. addNode( node ) {
  36070. if ( this.nodes.includes( node ) === false ) {
  36071. this.nodes.push( node );
  36072. this.setHashNode( node, node.getHash( this ) );
  36073. }
  36074. }
  36075. addSequentialNode( node ) {
  36076. if ( this.sequentialNodes.includes( node ) === false ) {
  36077. this.sequentialNodes.push( node );
  36078. }
  36079. }
  36080. buildUpdateNodes() {
  36081. for ( const node of this.nodes ) {
  36082. const updateType = node.getUpdateType();
  36083. if ( updateType !== NodeUpdateType.NONE ) {
  36084. this.updateNodes.push( node.getSelf() );
  36085. }
  36086. }
  36087. for ( const node of this.sequentialNodes ) {
  36088. const updateBeforeType = node.getUpdateBeforeType();
  36089. const updateAfterType = node.getUpdateAfterType();
  36090. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  36091. this.updateBeforeNodes.push( node.getSelf() );
  36092. }
  36093. if ( updateAfterType !== NodeUpdateType.NONE ) {
  36094. this.updateAfterNodes.push( node.getSelf() );
  36095. }
  36096. }
  36097. }
  36098. get currentNode() {
  36099. return this.chaining[ this.chaining.length - 1 ];
  36100. }
  36101. isFilteredTexture( texture ) {
  36102. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  36103. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  36104. }
  36105. addChain( node ) {
  36106. /*
  36107. if ( this.chaining.indexOf( node ) !== - 1 ) {
  36108. console.warn( 'Recursive node: ', node );
  36109. }
  36110. */
  36111. this.chaining.push( node );
  36112. }
  36113. removeChain( node ) {
  36114. const lastChain = this.chaining.pop();
  36115. if ( lastChain !== node ) {
  36116. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  36117. }
  36118. }
  36119. getMethod( method ) {
  36120. return method;
  36121. }
  36122. getNodeFromHash( hash ) {
  36123. return this.hashNodes[ hash ];
  36124. }
  36125. addFlow( shaderStage, node ) {
  36126. this.flowNodes[ shaderStage ].push( node );
  36127. return node;
  36128. }
  36129. setContext( context ) {
  36130. this.context = context;
  36131. }
  36132. getContext() {
  36133. return this.context;
  36134. }
  36135. getSharedContext() {
  36136. ({ ...this.context });
  36137. return this.context;
  36138. }
  36139. setCache( cache ) {
  36140. this.cache = cache;
  36141. }
  36142. getCache() {
  36143. return this.cache;
  36144. }
  36145. getCacheFromNode( node, parent = true ) {
  36146. const data = this.getDataFromNode( node );
  36147. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  36148. return data.cache;
  36149. }
  36150. isAvailable( /*name*/ ) {
  36151. return false;
  36152. }
  36153. getVertexIndex() {
  36154. console.warn( 'Abstract function.' );
  36155. }
  36156. getInstanceIndex() {
  36157. console.warn( 'Abstract function.' );
  36158. }
  36159. getDrawIndex() {
  36160. console.warn( 'Abstract function.' );
  36161. }
  36162. getFrontFacing() {
  36163. console.warn( 'Abstract function.' );
  36164. }
  36165. getFragCoord() {
  36166. console.warn( 'Abstract function.' );
  36167. }
  36168. isFlipY() {
  36169. return false;
  36170. }
  36171. increaseUsage( node ) {
  36172. const nodeData = this.getDataFromNode( node );
  36173. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  36174. return nodeData.usageCount;
  36175. }
  36176. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  36177. console.warn( 'Abstract function.' );
  36178. }
  36179. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  36180. console.warn( 'Abstract function.' );
  36181. }
  36182. generateConst( type, value = null ) {
  36183. if ( value === null ) {
  36184. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  36185. else if ( type === 'bool' ) value = false;
  36186. else if ( type === 'color' ) value = new Color();
  36187. else if ( type === 'vec2' ) value = new Vector2();
  36188. else if ( type === 'vec3' ) value = new Vector3();
  36189. else if ( type === 'vec4' ) value = new Vector4();
  36190. }
  36191. if ( type === 'float' ) return toFloat( value );
  36192. if ( type === 'int' ) return `${ Math.round( value ) }`;
  36193. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  36194. if ( type === 'bool' ) return value ? 'true' : 'false';
  36195. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  36196. const typeLength = this.getTypeLength( type );
  36197. const componentType = this.getComponentType( type );
  36198. const generateConst = value => this.generateConst( componentType, value );
  36199. if ( typeLength === 2 ) {
  36200. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  36201. } else if ( typeLength === 3 ) {
  36202. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  36203. } else if ( typeLength === 4 ) {
  36204. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  36205. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  36206. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  36207. } else if ( typeLength > 4 ) {
  36208. return `${ this.getType( type ) }()`;
  36209. }
  36210. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  36211. }
  36212. getType( type ) {
  36213. if ( type === 'color' ) return 'vec3';
  36214. return type;
  36215. }
  36216. hasGeometryAttribute( name ) {
  36217. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  36218. }
  36219. getAttribute( name, type ) {
  36220. const attributes = this.attributes;
  36221. // find attribute
  36222. for ( const attribute of attributes ) {
  36223. if ( attribute.name === name ) {
  36224. return attribute;
  36225. }
  36226. }
  36227. // create a new if no exist
  36228. const attribute = new NodeAttribute( name, type );
  36229. attributes.push( attribute );
  36230. return attribute;
  36231. }
  36232. getPropertyName( node/*, shaderStage*/ ) {
  36233. return node.name;
  36234. }
  36235. isVector( type ) {
  36236. return /vec\d/.test( type );
  36237. }
  36238. isMatrix( type ) {
  36239. return /mat\d/.test( type );
  36240. }
  36241. isReference( type ) {
  36242. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  36243. }
  36244. needsToWorkingColorSpace( /*texture*/ ) {
  36245. return false;
  36246. }
  36247. getComponentTypeFromTexture( texture ) {
  36248. const type = texture.type;
  36249. if ( texture.isDataTexture ) {
  36250. if ( type === IntType ) return 'int';
  36251. if ( type === UnsignedIntType ) return 'uint';
  36252. }
  36253. return 'float';
  36254. }
  36255. getElementType( type ) {
  36256. if ( type === 'mat2' ) return 'vec2';
  36257. if ( type === 'mat3' ) return 'vec3';
  36258. if ( type === 'mat4' ) return 'vec4';
  36259. return this.getComponentType( type );
  36260. }
  36261. getComponentType( type ) {
  36262. type = this.getVectorType( type );
  36263. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  36264. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  36265. if ( componentType === null ) return null;
  36266. if ( componentType[ 1 ] === 'b' ) return 'bool';
  36267. if ( componentType[ 1 ] === 'i' ) return 'int';
  36268. if ( componentType[ 1 ] === 'u' ) return 'uint';
  36269. return 'float';
  36270. }
  36271. getVectorType( type ) {
  36272. if ( type === 'color' ) return 'vec3';
  36273. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  36274. return type;
  36275. }
  36276. getTypeFromLength( length, componentType = 'float' ) {
  36277. if ( length === 1 ) return componentType;
  36278. const baseType = typeFromLength.get( length );
  36279. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  36280. return prefix + baseType;
  36281. }
  36282. getTypeFromArray( array ) {
  36283. return typeFromArray.get( array.constructor );
  36284. }
  36285. getTypeFromAttribute( attribute ) {
  36286. let dataAttribute = attribute;
  36287. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  36288. const array = dataAttribute.array;
  36289. const itemSize = attribute.itemSize;
  36290. const normalized = attribute.normalized;
  36291. let arrayType;
  36292. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  36293. arrayType = this.getTypeFromArray( array );
  36294. }
  36295. return this.getTypeFromLength( itemSize, arrayType );
  36296. }
  36297. getTypeLength( type ) {
  36298. const vecType = this.getVectorType( type );
  36299. const vecNum = /vec([2-4])/.exec( vecType );
  36300. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  36301. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  36302. if ( /mat2/.test( type ) === true ) return 4;
  36303. if ( /mat3/.test( type ) === true ) return 9;
  36304. if ( /mat4/.test( type ) === true ) return 16;
  36305. return 0;
  36306. }
  36307. getVectorFromMatrix( type ) {
  36308. return type.replace( 'mat', 'vec' );
  36309. }
  36310. changeComponentType( type, newComponentType ) {
  36311. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  36312. }
  36313. getIntegerType( type ) {
  36314. const componentType = this.getComponentType( type );
  36315. if ( componentType === 'int' || componentType === 'uint' ) return type;
  36316. return this.changeComponentType( type, 'int' );
  36317. }
  36318. addStack() {
  36319. this.stack = stack( this.stack );
  36320. this.stacks.push( getCurrentStack() || this.stack );
  36321. setCurrentStack( this.stack );
  36322. return this.stack;
  36323. }
  36324. removeStack() {
  36325. const lastStack = this.stack;
  36326. this.stack = lastStack.parent;
  36327. setCurrentStack( this.stacks.pop() );
  36328. return lastStack;
  36329. }
  36330. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  36331. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  36332. let nodeData = cache.getData( node );
  36333. if ( nodeData === undefined ) {
  36334. nodeData = {};
  36335. cache.setData( node, nodeData );
  36336. }
  36337. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  36338. return nodeData[ shaderStage ];
  36339. }
  36340. getNodeProperties( node, shaderStage = 'any' ) {
  36341. const nodeData = this.getDataFromNode( node, shaderStage );
  36342. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  36343. }
  36344. getBufferAttributeFromNode( node, type ) {
  36345. const nodeData = this.getDataFromNode( node );
  36346. let bufferAttribute = nodeData.bufferAttribute;
  36347. if ( bufferAttribute === undefined ) {
  36348. const index = this.uniforms.index ++;
  36349. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  36350. this.bufferAttributes.push( bufferAttribute );
  36351. nodeData.bufferAttribute = bufferAttribute;
  36352. }
  36353. return bufferAttribute;
  36354. }
  36355. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  36356. const nodeData = this.getDataFromNode( node, shaderStage );
  36357. if ( nodeData.structType === undefined ) {
  36358. const index = this.structs.index ++;
  36359. node.name = `StructType${ index }`;
  36360. this.structs[ shaderStage ].push( node );
  36361. nodeData.structType = node;
  36362. }
  36363. return node;
  36364. }
  36365. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  36366. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36367. let nodeUniform = nodeData.uniform;
  36368. if ( nodeUniform === undefined ) {
  36369. const index = this.uniforms.index ++;
  36370. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  36371. this.uniforms[ shaderStage ].push( nodeUniform );
  36372. nodeData.uniform = nodeUniform;
  36373. }
  36374. return nodeUniform;
  36375. }
  36376. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  36377. const nodeData = this.getDataFromNode( node, shaderStage );
  36378. let nodeVar = nodeData.variable;
  36379. if ( nodeVar === undefined ) {
  36380. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  36381. if ( name === null ) name = 'nodeVar' + vars.length;
  36382. nodeVar = new NodeVar( name, type );
  36383. vars.push( nodeVar );
  36384. nodeData.variable = nodeVar;
  36385. }
  36386. return nodeVar;
  36387. }
  36388. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  36389. const nodeData = this.getDataFromNode( node, 'any' );
  36390. let nodeVarying = nodeData.varying;
  36391. if ( nodeVarying === undefined ) {
  36392. const varyings = this.varyings;
  36393. const index = varyings.length;
  36394. if ( name === null ) name = 'nodeVarying' + index;
  36395. nodeVarying = new NodeVarying( name, type );
  36396. varyings.push( nodeVarying );
  36397. nodeData.varying = nodeVarying;
  36398. }
  36399. return nodeVarying;
  36400. }
  36401. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  36402. const nodeData = this.getDataFromNode( node );
  36403. let nodeCode = nodeData.code;
  36404. if ( nodeCode === undefined ) {
  36405. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  36406. const index = codes.length;
  36407. nodeCode = new NodeCode( 'nodeCode' + index, type );
  36408. codes.push( nodeCode );
  36409. nodeData.code = nodeCode;
  36410. }
  36411. return nodeCode;
  36412. }
  36413. addFlowCodeHierarchy( node, nodeBlock ) {
  36414. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  36415. let needsFlowCode = true;
  36416. let nodeBlockHierarchy = nodeBlock;
  36417. while ( nodeBlockHierarchy ) {
  36418. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  36419. needsFlowCode = false;
  36420. break;
  36421. }
  36422. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  36423. }
  36424. if ( needsFlowCode ) {
  36425. for ( const flowCode of flowCodes ) {
  36426. this.addLineFlowCode( flowCode );
  36427. }
  36428. }
  36429. }
  36430. addLineFlowCodeBlock( node, code, nodeBlock ) {
  36431. const nodeData = this.getDataFromNode( node );
  36432. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  36433. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  36434. flowCodes.push( code );
  36435. codeBlock.set( nodeBlock, true );
  36436. }
  36437. addLineFlowCode( code, node = null ) {
  36438. if ( code === '' ) return this;
  36439. if ( node !== null && this.context.nodeBlock ) {
  36440. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  36441. }
  36442. code = this.tab + code;
  36443. if ( ! /;\s*$/.test( code ) ) {
  36444. code = code + ';\n';
  36445. }
  36446. this.flow.code += code;
  36447. return this;
  36448. }
  36449. addFlowCode( code ) {
  36450. this.flow.code += code;
  36451. return this;
  36452. }
  36453. addFlowTab() {
  36454. this.tab += '\t';
  36455. return this;
  36456. }
  36457. removeFlowTab() {
  36458. this.tab = this.tab.slice( 0, - 1 );
  36459. return this;
  36460. }
  36461. getFlowData( node/*, shaderStage*/ ) {
  36462. return this.flowsData.get( node );
  36463. }
  36464. flowNode( node ) {
  36465. const output = node.getNodeType( this );
  36466. const flowData = this.flowChildNode( node, output );
  36467. this.flowsData.set( node, flowData );
  36468. return flowData;
  36469. }
  36470. buildFunctionNode( shaderNode ) {
  36471. const fn = new FunctionNode();
  36472. const previous = this.currentFunctionNode;
  36473. this.currentFunctionNode = fn;
  36474. fn.code = this.buildFunctionCode( shaderNode );
  36475. this.currentFunctionNode = previous;
  36476. return fn;
  36477. }
  36478. flowShaderNode( shaderNode ) {
  36479. const layout = shaderNode.layout;
  36480. const inputs = {
  36481. [ Symbol.iterator ]() {
  36482. let index = 0;
  36483. const values = Object.values( this );
  36484. return {
  36485. next: () => ( {
  36486. value: values[ index ],
  36487. done: index ++ >= values.length
  36488. } )
  36489. };
  36490. }
  36491. };
  36492. for ( const input of layout.inputs ) {
  36493. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  36494. }
  36495. //
  36496. shaderNode.layout = null;
  36497. const callNode = shaderNode.call( inputs );
  36498. const flowData = this.flowStagesNode( callNode, layout.type );
  36499. shaderNode.layout = layout;
  36500. return flowData;
  36501. }
  36502. flowStagesNode( node, output = null ) {
  36503. const previousFlow = this.flow;
  36504. const previousVars = this.vars;
  36505. const previousCache = this.cache;
  36506. const previousBuildStage = this.buildStage;
  36507. const previousStack = this.stack;
  36508. const flow = {
  36509. code: ''
  36510. };
  36511. this.flow = flow;
  36512. this.vars = {};
  36513. this.cache = new NodeCache();
  36514. this.stack = stack();
  36515. for ( const buildStage of defaultBuildStages ) {
  36516. this.setBuildStage( buildStage );
  36517. flow.result = node.build( this, output );
  36518. }
  36519. flow.vars = this.getVars( this.shaderStage );
  36520. this.flow = previousFlow;
  36521. this.vars = previousVars;
  36522. this.cache = previousCache;
  36523. this.stack = previousStack;
  36524. this.setBuildStage( previousBuildStage );
  36525. return flow;
  36526. }
  36527. getFunctionOperator() {
  36528. return null;
  36529. }
  36530. flowChildNode( node, output = null ) {
  36531. const previousFlow = this.flow;
  36532. const flow = {
  36533. code: ''
  36534. };
  36535. this.flow = flow;
  36536. flow.result = node.build( this, output );
  36537. this.flow = previousFlow;
  36538. return flow;
  36539. }
  36540. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  36541. const previousShaderStage = this.shaderStage;
  36542. this.setShaderStage( shaderStage );
  36543. const flowData = this.flowChildNode( node, output );
  36544. if ( propertyName !== null ) {
  36545. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  36546. }
  36547. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  36548. this.setShaderStage( previousShaderStage );
  36549. return flowData;
  36550. }
  36551. getAttributesArray() {
  36552. return this.attributes.concat( this.bufferAttributes );
  36553. }
  36554. getAttributes( /*shaderStage*/ ) {
  36555. console.warn( 'Abstract function.' );
  36556. }
  36557. getVaryings( /*shaderStage*/ ) {
  36558. console.warn( 'Abstract function.' );
  36559. }
  36560. getVar( type, name ) {
  36561. return `${ this.getType( type ) } ${ name }`;
  36562. }
  36563. getVars( shaderStage ) {
  36564. let snippet = '';
  36565. const vars = this.vars[ shaderStage ];
  36566. if ( vars !== undefined ) {
  36567. for ( const variable of vars ) {
  36568. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  36569. }
  36570. }
  36571. return snippet;
  36572. }
  36573. getUniforms( /*shaderStage*/ ) {
  36574. console.warn( 'Abstract function.' );
  36575. }
  36576. getCodes( shaderStage ) {
  36577. const codes = this.codes[ shaderStage ];
  36578. let code = '';
  36579. if ( codes !== undefined ) {
  36580. for ( const nodeCode of codes ) {
  36581. code += nodeCode.code + '\n';
  36582. }
  36583. }
  36584. return code;
  36585. }
  36586. getHash() {
  36587. return this.vertexShader + this.fragmentShader + this.computeShader;
  36588. }
  36589. setShaderStage( shaderStage ) {
  36590. this.shaderStage = shaderStage;
  36591. }
  36592. getShaderStage() {
  36593. return this.shaderStage;
  36594. }
  36595. setBuildStage( buildStage ) {
  36596. this.buildStage = buildStage;
  36597. }
  36598. getBuildStage() {
  36599. return this.buildStage;
  36600. }
  36601. buildCode() {
  36602. console.warn( 'Abstract function.' );
  36603. }
  36604. build() {
  36605. const { object, material, renderer } = this;
  36606. if ( material !== null ) {
  36607. let nodeMaterial = renderer.library.fromMaterial( material );
  36608. if ( nodeMaterial === null ) {
  36609. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  36610. nodeMaterial = new NodeMaterial();
  36611. }
  36612. nodeMaterial.build( this );
  36613. } else {
  36614. this.addFlow( 'compute', object );
  36615. }
  36616. // setup() -> stage 1: create possible new nodes and returns an output reference node
  36617. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  36618. // generate() -> stage 3: generate shader
  36619. for ( const buildStage of defaultBuildStages ) {
  36620. this.setBuildStage( buildStage );
  36621. if ( this.context.vertex && this.context.vertex.isNode ) {
  36622. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  36623. }
  36624. for ( const shaderStage of shaderStages ) {
  36625. this.setShaderStage( shaderStage );
  36626. const flowNodes = this.flowNodes[ shaderStage ];
  36627. for ( const node of flowNodes ) {
  36628. if ( buildStage === 'generate' ) {
  36629. this.flowNode( node );
  36630. } else {
  36631. node.build( this );
  36632. }
  36633. }
  36634. }
  36635. }
  36636. this.setBuildStage( null );
  36637. this.setShaderStage( null );
  36638. // stage 4: build code for a specific output
  36639. this.buildCode();
  36640. this.buildUpdateNodes();
  36641. return this;
  36642. }
  36643. getNodeUniform( uniformNode, type ) {
  36644. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  36645. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  36646. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  36647. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  36648. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  36649. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  36650. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  36651. throw new Error( `Uniform "${type}" not declared.` );
  36652. }
  36653. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  36654. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  36655. }
  36656. format( snippet, fromType, toType ) {
  36657. fromType = this.getVectorType( fromType );
  36658. toType = this.getVectorType( toType );
  36659. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  36660. return snippet;
  36661. }
  36662. const fromTypeLength = this.getTypeLength( fromType );
  36663. const toTypeLength = this.getTypeLength( toType );
  36664. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  36665. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  36666. }
  36667. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  36668. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  36669. }
  36670. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  36671. // @TODO: ignore for now
  36672. return snippet;
  36673. }
  36674. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  36675. // @TODO: ignore for now
  36676. return snippet;
  36677. }
  36678. if ( fromTypeLength === toTypeLength ) {
  36679. return `${ this.getType( toType ) }( ${ snippet } )`;
  36680. }
  36681. if ( fromTypeLength > toTypeLength ) {
  36682. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  36683. }
  36684. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  36685. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  36686. }
  36687. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  36688. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  36689. }
  36690. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  36691. // convert a number value to vector type, e.g:
  36692. // vec3( 1u ) -> vec3( float( 1u ) )
  36693. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  36694. }
  36695. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  36696. }
  36697. getSignature() {
  36698. return `// Three.js r${ REVISION } - Node System\n`;
  36699. }
  36700. }
  36701. class NodeFrame {
  36702. constructor() {
  36703. this.time = 0;
  36704. this.deltaTime = 0;
  36705. this.frameId = 0;
  36706. this.renderId = 0;
  36707. this.startTime = null;
  36708. this.updateMap = new WeakMap();
  36709. this.updateBeforeMap = new WeakMap();
  36710. this.updateAfterMap = new WeakMap();
  36711. this.renderer = null;
  36712. this.material = null;
  36713. this.camera = null;
  36714. this.object = null;
  36715. this.scene = null;
  36716. }
  36717. _getMaps( referenceMap, nodeRef ) {
  36718. let maps = referenceMap.get( nodeRef );
  36719. if ( maps === undefined ) {
  36720. maps = {
  36721. renderMap: new WeakMap(),
  36722. frameMap: new WeakMap()
  36723. };
  36724. referenceMap.set( nodeRef, maps );
  36725. }
  36726. return maps;
  36727. }
  36728. updateBeforeNode( node ) {
  36729. const updateType = node.getUpdateBeforeType();
  36730. const reference = node.updateReference( this );
  36731. if ( updateType === NodeUpdateType.FRAME ) {
  36732. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  36733. if ( frameMap.get( reference ) !== this.frameId ) {
  36734. if ( node.updateBefore( this ) !== false ) {
  36735. frameMap.set( reference, this.frameId );
  36736. }
  36737. }
  36738. } else if ( updateType === NodeUpdateType.RENDER ) {
  36739. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  36740. if ( renderMap.get( reference ) !== this.renderId ) {
  36741. if ( node.updateBefore( this ) !== false ) {
  36742. renderMap.set( reference, this.renderId );
  36743. }
  36744. }
  36745. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36746. node.updateBefore( this );
  36747. }
  36748. }
  36749. updateAfterNode( node ) {
  36750. const updateType = node.getUpdateAfterType();
  36751. const reference = node.updateReference( this );
  36752. if ( updateType === NodeUpdateType.FRAME ) {
  36753. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  36754. if ( frameMap.get( reference ) !== this.frameId ) {
  36755. if ( node.updateAfter( this ) !== false ) {
  36756. frameMap.set( reference, this.frameId );
  36757. }
  36758. }
  36759. } else if ( updateType === NodeUpdateType.RENDER ) {
  36760. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  36761. if ( renderMap.get( reference ) !== this.renderId ) {
  36762. if ( node.updateAfter( this ) !== false ) {
  36763. renderMap.set( reference, this.renderId );
  36764. }
  36765. }
  36766. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36767. node.updateAfter( this );
  36768. }
  36769. }
  36770. updateNode( node ) {
  36771. const updateType = node.getUpdateType();
  36772. const reference = node.updateReference( this );
  36773. if ( updateType === NodeUpdateType.FRAME ) {
  36774. const { frameMap } = this._getMaps( this.updateMap, reference );
  36775. if ( frameMap.get( reference ) !== this.frameId ) {
  36776. if ( node.update( this ) !== false ) {
  36777. frameMap.set( reference, this.frameId );
  36778. }
  36779. }
  36780. } else if ( updateType === NodeUpdateType.RENDER ) {
  36781. const { renderMap } = this._getMaps( this.updateMap, reference );
  36782. if ( renderMap.get( reference ) !== this.renderId ) {
  36783. if ( node.update( this ) !== false ) {
  36784. renderMap.set( reference, this.renderId );
  36785. }
  36786. }
  36787. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36788. node.update( this );
  36789. }
  36790. }
  36791. update() {
  36792. this.frameId ++;
  36793. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  36794. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  36795. this.lastTime = performance.now();
  36796. this.time += this.deltaTime;
  36797. }
  36798. }
  36799. class NodeFunctionInput {
  36800. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  36801. this.type = type;
  36802. this.name = name;
  36803. this.count = count;
  36804. this.qualifier = qualifier;
  36805. this.isConst = isConst;
  36806. }
  36807. }
  36808. NodeFunctionInput.isNodeFunctionInput = true;
  36809. class DirectionalLightNode extends AnalyticLightNode {
  36810. static get type() {
  36811. return 'DirectionalLightNode';
  36812. }
  36813. constructor( light = null ) {
  36814. super( light );
  36815. }
  36816. setup( builder ) {
  36817. super.setup( builder );
  36818. const lightingModel = builder.context.lightingModel;
  36819. const lightColor = this.colorNode;
  36820. const lightDirection = lightTargetDirection( this.light );
  36821. const reflectedLight = builder.context.reflectedLight;
  36822. lightingModel.direct( {
  36823. lightDirection,
  36824. lightColor,
  36825. reflectedLight
  36826. }, builder.stack, builder );
  36827. }
  36828. }
  36829. const _matrix41 = /*@__PURE__*/ new Matrix4();
  36830. const _matrix42 = /*@__PURE__*/ new Matrix4();
  36831. let ltcLib = null;
  36832. class RectAreaLightNode extends AnalyticLightNode {
  36833. static get type() {
  36834. return 'RectAreaLightNode';
  36835. }
  36836. constructor( light = null ) {
  36837. super( light );
  36838. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  36839. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  36840. this.updateType = NodeUpdateType.RENDER;
  36841. }
  36842. update( frame ) {
  36843. super.update( frame );
  36844. const { light } = this;
  36845. const viewMatrix = frame.camera.matrixWorldInverse;
  36846. _matrix42.identity();
  36847. _matrix41.copy( light.matrixWorld );
  36848. _matrix41.premultiply( viewMatrix );
  36849. _matrix42.extractRotation( _matrix41 );
  36850. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  36851. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  36852. this.halfWidth.value.applyMatrix4( _matrix42 );
  36853. this.halfHeight.value.applyMatrix4( _matrix42 );
  36854. }
  36855. setup( builder ) {
  36856. super.setup( builder );
  36857. let ltc_1, ltc_2;
  36858. if ( builder.isAvailable( 'float32Filterable' ) ) {
  36859. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  36860. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  36861. } else {
  36862. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  36863. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  36864. }
  36865. const { colorNode, light } = this;
  36866. const lightingModel = builder.context.lightingModel;
  36867. const lightPosition = lightViewPosition( light );
  36868. const reflectedLight = builder.context.reflectedLight;
  36869. lightingModel.directRectArea( {
  36870. lightColor: colorNode,
  36871. lightPosition,
  36872. halfWidth: this.halfWidth,
  36873. halfHeight: this.halfHeight,
  36874. reflectedLight,
  36875. ltc_1,
  36876. ltc_2
  36877. }, builder.stack, builder );
  36878. }
  36879. static setLTC( ltc ) {
  36880. ltcLib = ltc;
  36881. }
  36882. }
  36883. class SpotLightNode extends AnalyticLightNode {
  36884. static get type() {
  36885. return 'SpotLightNode';
  36886. }
  36887. constructor( light = null ) {
  36888. super( light );
  36889. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  36890. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  36891. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  36892. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  36893. }
  36894. update( frame ) {
  36895. super.update( frame );
  36896. const { light } = this;
  36897. this.coneCosNode.value = Math.cos( light.angle );
  36898. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  36899. this.cutoffDistanceNode.value = light.distance;
  36900. this.decayExponentNode.value = light.decay;
  36901. }
  36902. getSpotAttenuation( angleCosine ) {
  36903. const { coneCosNode, penumbraCosNode } = this;
  36904. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  36905. }
  36906. setup( builder ) {
  36907. super.setup( builder );
  36908. const lightingModel = builder.context.lightingModel;
  36909. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  36910. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  36911. const lightDirection = lVector.normalize();
  36912. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  36913. const spotAttenuation = this.getSpotAttenuation( angleCos );
  36914. const lightDistance = lVector.length();
  36915. const lightAttenuation = getDistanceAttenuation( {
  36916. lightDistance,
  36917. cutoffDistance: cutoffDistanceNode,
  36918. decayExponent: decayExponentNode
  36919. } );
  36920. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  36921. const reflectedLight = builder.context.reflectedLight;
  36922. lightingModel.direct( {
  36923. lightDirection,
  36924. lightColor,
  36925. reflectedLight
  36926. }, builder.stack, builder );
  36927. }
  36928. }
  36929. class IESSpotLightNode extends SpotLightNode {
  36930. static get type() {
  36931. return 'IESSpotLightNode';
  36932. }
  36933. getSpotAttenuation( angleCosine ) {
  36934. const iesMap = this.light.iesMap;
  36935. let spotAttenuation = null;
  36936. if ( iesMap && iesMap.isTexture === true ) {
  36937. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  36938. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  36939. } else {
  36940. spotAttenuation = super.getSpotAttenuation( angleCosine );
  36941. }
  36942. return spotAttenuation;
  36943. }
  36944. }
  36945. class AmbientLightNode extends AnalyticLightNode {
  36946. static get type() {
  36947. return 'AmbientLightNode';
  36948. }
  36949. constructor( light = null ) {
  36950. super( light );
  36951. }
  36952. setup( { context } ) {
  36953. context.irradiance.addAssign( this.colorNode );
  36954. }
  36955. }
  36956. class HemisphereLightNode extends AnalyticLightNode {
  36957. static get type() {
  36958. return 'HemisphereLightNode';
  36959. }
  36960. constructor( light = null ) {
  36961. super( light );
  36962. this.lightPositionNode = lightPosition( light );
  36963. this.lightDirectionNode = this.lightPositionNode.normalize();
  36964. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  36965. }
  36966. update( frame ) {
  36967. const { light } = this;
  36968. super.update( frame );
  36969. this.lightPositionNode.object3d = light;
  36970. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  36971. }
  36972. setup( builder ) {
  36973. const { colorNode, groundColorNode, lightDirectionNode } = this;
  36974. const dotNL = normalView.dot( lightDirectionNode );
  36975. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  36976. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  36977. builder.context.irradiance.addAssign( irradiance );
  36978. }
  36979. }
  36980. class LightProbeNode extends AnalyticLightNode {
  36981. static get type() {
  36982. return 'LightProbeNode';
  36983. }
  36984. constructor( light = null ) {
  36985. super( light );
  36986. const array = [];
  36987. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  36988. this.lightProbe = uniformArray( array );
  36989. }
  36990. update( frame ) {
  36991. const { light } = this;
  36992. super.update( frame );
  36993. //
  36994. for ( let i = 0; i < 9; i ++ ) {
  36995. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  36996. }
  36997. }
  36998. setup( builder ) {
  36999. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  37000. builder.context.irradiance.addAssign( irradiance );
  37001. }
  37002. }
  37003. class NodeParser {
  37004. parseFunction( /*source*/ ) {
  37005. console.warn( 'Abstract function.' );
  37006. }
  37007. }
  37008. class NodeFunction {
  37009. constructor( type, inputs, name = '', precision = '' ) {
  37010. this.type = type;
  37011. this.inputs = inputs;
  37012. this.name = name;
  37013. this.precision = precision;
  37014. }
  37015. getCode( /*name = this.name*/ ) {
  37016. console.warn( 'Abstract function.' );
  37017. }
  37018. }
  37019. NodeFunction.isNodeFunction = true;
  37020. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  37021. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  37022. const pragmaMain = '#pragma main';
  37023. const parse$1 = ( source ) => {
  37024. source = source.trim();
  37025. const pragmaMainIndex = source.indexOf( pragmaMain );
  37026. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  37027. const declaration = mainCode.match( declarationRegexp$1 );
  37028. if ( declaration !== null && declaration.length === 5 ) {
  37029. // tokenizer
  37030. const inputsCode = declaration[ 4 ];
  37031. const propsMatches = [];
  37032. let nameMatch = null;
  37033. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  37034. propsMatches.push( nameMatch );
  37035. }
  37036. // parser
  37037. const inputs = [];
  37038. let i = 0;
  37039. while ( i < propsMatches.length ) {
  37040. const isConst = propsMatches[ i ][ 0 ] === 'const';
  37041. if ( isConst === true ) {
  37042. i ++;
  37043. }
  37044. let qualifier = propsMatches[ i ][ 0 ];
  37045. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  37046. i ++;
  37047. } else {
  37048. qualifier = '';
  37049. }
  37050. const type = propsMatches[ i ++ ][ 0 ];
  37051. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  37052. if ( Number.isNaN( count ) === false ) i ++;
  37053. else count = null;
  37054. const name = propsMatches[ i ++ ][ 0 ];
  37055. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  37056. }
  37057. //
  37058. const blockCode = mainCode.substring( declaration[ 0 ].length );
  37059. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  37060. const type = declaration[ 2 ];
  37061. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  37062. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  37063. return {
  37064. type,
  37065. inputs,
  37066. name,
  37067. precision,
  37068. inputsCode,
  37069. blockCode,
  37070. headerCode
  37071. };
  37072. } else {
  37073. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  37074. }
  37075. };
  37076. class GLSLNodeFunction extends NodeFunction {
  37077. constructor( source ) {
  37078. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  37079. super( type, inputs, name, precision );
  37080. this.inputsCode = inputsCode;
  37081. this.blockCode = blockCode;
  37082. this.headerCode = headerCode;
  37083. }
  37084. getCode( name = this.name ) {
  37085. let code;
  37086. const blockCode = this.blockCode;
  37087. if ( blockCode !== '' ) {
  37088. const { type, inputsCode, headerCode, precision } = this;
  37089. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  37090. if ( precision !== '' ) {
  37091. declarationCode = `${ precision } ${ declarationCode }`;
  37092. }
  37093. code = headerCode + declarationCode + blockCode;
  37094. } else {
  37095. // interface function
  37096. code = '';
  37097. }
  37098. return code;
  37099. }
  37100. }
  37101. class GLSLNodeParser extends NodeParser {
  37102. parseFunction( source ) {
  37103. return new GLSLNodeFunction( source );
  37104. }
  37105. }
  37106. const outputNodeMap = new WeakMap();
  37107. class Nodes extends DataMap {
  37108. constructor( renderer, backend ) {
  37109. super();
  37110. this.renderer = renderer;
  37111. this.backend = backend;
  37112. this.nodeFrame = new NodeFrame();
  37113. this.nodeBuilderCache = new Map();
  37114. this.callHashCache = new ChainMap();
  37115. this.groupsData = new ChainMap();
  37116. }
  37117. updateGroup( nodeUniformsGroup ) {
  37118. const groupNode = nodeUniformsGroup.groupNode;
  37119. const name = groupNode.name;
  37120. // objectGroup is every updated
  37121. if ( name === objectGroup.name ) return true;
  37122. // renderGroup is updated once per render/compute call
  37123. if ( name === renderGroup.name ) {
  37124. const uniformsGroupData = this.get( nodeUniformsGroup );
  37125. const renderId = this.nodeFrame.renderId;
  37126. if ( uniformsGroupData.renderId !== renderId ) {
  37127. uniformsGroupData.renderId = renderId;
  37128. return true;
  37129. }
  37130. return false;
  37131. }
  37132. // frameGroup is updated once per frame
  37133. if ( name === frameGroup.name ) {
  37134. const uniformsGroupData = this.get( nodeUniformsGroup );
  37135. const frameId = this.nodeFrame.frameId;
  37136. if ( uniformsGroupData.frameId !== frameId ) {
  37137. uniformsGroupData.frameId = frameId;
  37138. return true;
  37139. }
  37140. return false;
  37141. }
  37142. // other groups are updated just when groupNode.needsUpdate is true
  37143. const groupChain = [ groupNode, nodeUniformsGroup ];
  37144. let groupData = this.groupsData.get( groupChain );
  37145. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  37146. if ( groupData.version !== groupNode.version ) {
  37147. groupData.version = groupNode.version;
  37148. return true;
  37149. }
  37150. return false;
  37151. }
  37152. getForRenderCacheKey( renderObject ) {
  37153. return renderObject.initialCacheKey;
  37154. }
  37155. getForRender( renderObject ) {
  37156. const renderObjectData = this.get( renderObject );
  37157. let nodeBuilderState = renderObjectData.nodeBuilderState;
  37158. if ( nodeBuilderState === undefined ) {
  37159. const { nodeBuilderCache } = this;
  37160. const cacheKey = this.getForRenderCacheKey( renderObject );
  37161. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  37162. if ( nodeBuilderState === undefined ) {
  37163. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  37164. nodeBuilder.scene = renderObject.scene;
  37165. nodeBuilder.material = renderObject.material;
  37166. nodeBuilder.camera = renderObject.camera;
  37167. nodeBuilder.context.material = renderObject.material;
  37168. nodeBuilder.lightsNode = renderObject.lightsNode;
  37169. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  37170. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  37171. nodeBuilder.clippingContext = renderObject.clippingContext;
  37172. nodeBuilder.build();
  37173. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37174. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  37175. }
  37176. nodeBuilderState.usedTimes ++;
  37177. renderObjectData.nodeBuilderState = nodeBuilderState;
  37178. }
  37179. return nodeBuilderState;
  37180. }
  37181. delete( object ) {
  37182. if ( object.isRenderObject ) {
  37183. const nodeBuilderState = this.get( object ).nodeBuilderState;
  37184. nodeBuilderState.usedTimes --;
  37185. if ( nodeBuilderState.usedTimes === 0 ) {
  37186. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  37187. }
  37188. }
  37189. return super.delete( object );
  37190. }
  37191. getForCompute( computeNode ) {
  37192. const computeData = this.get( computeNode );
  37193. let nodeBuilderState = computeData.nodeBuilderState;
  37194. if ( nodeBuilderState === undefined ) {
  37195. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  37196. nodeBuilder.build();
  37197. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37198. computeData.nodeBuilderState = nodeBuilderState;
  37199. }
  37200. return nodeBuilderState;
  37201. }
  37202. _createNodeBuilderState( nodeBuilder ) {
  37203. return new NodeBuilderState(
  37204. nodeBuilder.vertexShader,
  37205. nodeBuilder.fragmentShader,
  37206. nodeBuilder.computeShader,
  37207. nodeBuilder.getAttributesArray(),
  37208. nodeBuilder.getBindings(),
  37209. nodeBuilder.updateNodes,
  37210. nodeBuilder.updateBeforeNodes,
  37211. nodeBuilder.updateAfterNodes,
  37212. nodeBuilder.monitor,
  37213. nodeBuilder.transforms
  37214. );
  37215. }
  37216. getEnvironmentNode( scene ) {
  37217. return scene.environmentNode || this.get( scene ).environmentNode || null;
  37218. }
  37219. getBackgroundNode( scene ) {
  37220. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  37221. }
  37222. getFogNode( scene ) {
  37223. return scene.fogNode || this.get( scene ).fogNode || null;
  37224. }
  37225. getCacheKey( scene, lightsNode ) {
  37226. const chain = [ scene, lightsNode ];
  37227. const callId = this.renderer.info.calls;
  37228. let cacheKeyData = this.callHashCache.get( chain );
  37229. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  37230. const environmentNode = this.getEnvironmentNode( scene );
  37231. const fogNode = this.getFogNode( scene );
  37232. const values = [];
  37233. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  37234. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  37235. if ( fogNode ) values.push( fogNode.getCacheKey() );
  37236. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  37237. cacheKeyData = {
  37238. callId,
  37239. cacheKey: hashArray( values )
  37240. };
  37241. this.callHashCache.set( chain, cacheKeyData );
  37242. }
  37243. return cacheKeyData.cacheKey;
  37244. }
  37245. updateScene( scene ) {
  37246. this.updateEnvironment( scene );
  37247. this.updateFog( scene );
  37248. this.updateBackground( scene );
  37249. }
  37250. get isToneMappingState() {
  37251. return this.renderer.getRenderTarget() ? false : true;
  37252. }
  37253. updateBackground( scene ) {
  37254. const sceneData = this.get( scene );
  37255. const background = scene.background;
  37256. if ( background ) {
  37257. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  37258. if ( sceneData.background !== background || forceUpdate ) {
  37259. let backgroundNode = null;
  37260. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  37261. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  37262. backgroundNode = pmremTexture( background );
  37263. } else {
  37264. let envMap;
  37265. if ( background.isCubeTexture === true ) {
  37266. envMap = cubeTexture( background );
  37267. } else {
  37268. envMap = texture( background );
  37269. }
  37270. backgroundNode = cubeMapNode( envMap );
  37271. }
  37272. } else if ( background.isTexture === true ) {
  37273. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  37274. } else if ( background.isColor !== true ) {
  37275. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  37276. }
  37277. sceneData.backgroundNode = backgroundNode;
  37278. sceneData.background = background;
  37279. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  37280. }
  37281. } else if ( sceneData.backgroundNode ) {
  37282. delete sceneData.backgroundNode;
  37283. delete sceneData.background;
  37284. }
  37285. }
  37286. updateFog( scene ) {
  37287. const sceneData = this.get( scene );
  37288. const fog = scene.fog;
  37289. if ( fog ) {
  37290. if ( sceneData.fog !== fog ) {
  37291. let fogNode = null;
  37292. if ( fog.isFogExp2 ) {
  37293. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  37294. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  37295. fogNode = densityFog( color, density );
  37296. } else if ( fog.isFog ) {
  37297. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  37298. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  37299. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  37300. fogNode = rangeFog( color, near, far );
  37301. } else {
  37302. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  37303. }
  37304. sceneData.fogNode = fogNode;
  37305. sceneData.fog = fog;
  37306. }
  37307. } else {
  37308. delete sceneData.fogNode;
  37309. delete sceneData.fog;
  37310. }
  37311. }
  37312. updateEnvironment( scene ) {
  37313. const sceneData = this.get( scene );
  37314. const environment = scene.environment;
  37315. if ( environment ) {
  37316. if ( sceneData.environment !== environment ) {
  37317. let environmentNode = null;
  37318. if ( environment.isCubeTexture === true ) {
  37319. environmentNode = cubeTexture( environment );
  37320. } else if ( environment.isTexture === true ) {
  37321. environmentNode = texture( environment );
  37322. } else {
  37323. console.error( 'Nodes: Unsupported environment configuration.', environment );
  37324. }
  37325. sceneData.environmentNode = environmentNode;
  37326. sceneData.environment = environment;
  37327. }
  37328. } else if ( sceneData.environmentNode ) {
  37329. delete sceneData.environmentNode;
  37330. delete sceneData.environment;
  37331. }
  37332. }
  37333. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  37334. const nodeFrame = this.nodeFrame;
  37335. nodeFrame.renderer = renderer;
  37336. nodeFrame.scene = scene;
  37337. nodeFrame.object = object;
  37338. nodeFrame.camera = camera;
  37339. nodeFrame.material = material;
  37340. return nodeFrame;
  37341. }
  37342. getNodeFrameForRender( renderObject ) {
  37343. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  37344. }
  37345. getOutputCacheKey() {
  37346. const renderer = this.renderer;
  37347. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  37348. }
  37349. hasOutputChange( outputTarget ) {
  37350. const cacheKey = outputNodeMap.get( outputTarget );
  37351. return cacheKey !== this.getOutputCacheKey();
  37352. }
  37353. getOutputNode( outputTexture ) {
  37354. const renderer = this.renderer;
  37355. const cacheKey = this.getOutputCacheKey();
  37356. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  37357. outputNodeMap.set( outputTexture, cacheKey );
  37358. return output;
  37359. }
  37360. updateBefore( renderObject ) {
  37361. const nodeBuilder = renderObject.getNodeBuilderState();
  37362. for ( const node of nodeBuilder.updateBeforeNodes ) {
  37363. // update frame state for each node
  37364. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  37365. }
  37366. }
  37367. updateAfter( renderObject ) {
  37368. const nodeBuilder = renderObject.getNodeBuilderState();
  37369. for ( const node of nodeBuilder.updateAfterNodes ) {
  37370. // update frame state for each node
  37371. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  37372. }
  37373. }
  37374. updateForCompute( computeNode ) {
  37375. const nodeFrame = this.getNodeFrame();
  37376. const nodeBuilder = this.getForCompute( computeNode );
  37377. for ( const node of nodeBuilder.updateNodes ) {
  37378. nodeFrame.updateNode( node );
  37379. }
  37380. }
  37381. updateForRender( renderObject ) {
  37382. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37383. const nodeBuilder = renderObject.getNodeBuilderState();
  37384. for ( const node of nodeBuilder.updateNodes ) {
  37385. nodeFrame.updateNode( node );
  37386. }
  37387. }
  37388. needsRefresh( renderObject ) {
  37389. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37390. const monitor = renderObject.getMonitor();
  37391. return monitor.needsRefresh( renderObject, nodeFrame );
  37392. }
  37393. dispose() {
  37394. super.dispose();
  37395. this.nodeFrame = new NodeFrame();
  37396. this.nodeBuilderCache = new Map();
  37397. }
  37398. }
  37399. class RenderBundle {
  37400. constructor( scene, camera ) {
  37401. this.scene = scene;
  37402. this.camera = camera;
  37403. }
  37404. clone() {
  37405. return Object.assign( new this.constructor(), this );
  37406. }
  37407. }
  37408. class RenderBundles {
  37409. constructor() {
  37410. this.lists = new ChainMap();
  37411. }
  37412. get( scene, camera ) {
  37413. const lists = this.lists;
  37414. const keys = [ scene, camera ];
  37415. let list = lists.get( keys );
  37416. if ( list === undefined ) {
  37417. list = new RenderBundle( scene, camera );
  37418. lists.set( keys, list );
  37419. }
  37420. return list;
  37421. }
  37422. dispose() {
  37423. this.lists = new ChainMap();
  37424. }
  37425. }
  37426. class NodeLibrary {
  37427. constructor() {
  37428. this.lightNodes = new WeakMap();
  37429. this.materialNodes = new Map();
  37430. this.toneMappingNodes = new Map();
  37431. }
  37432. fromMaterial( material ) {
  37433. if ( material.isNodeMaterial ) return material;
  37434. let nodeMaterial = null;
  37435. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  37436. if ( nodeMaterialClass !== null ) {
  37437. nodeMaterial = new nodeMaterialClass();
  37438. for ( const key in material ) {
  37439. nodeMaterial[ key ] = material[ key ];
  37440. }
  37441. }
  37442. return nodeMaterial;
  37443. }
  37444. addToneMapping( toneMappingNode, toneMapping ) {
  37445. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  37446. }
  37447. getToneMappingFunction( toneMapping ) {
  37448. return this.toneMappingNodes.get( toneMapping ) || null;
  37449. }
  37450. getMaterialNodeClass( materialType ) {
  37451. return this.materialNodes.get( materialType ) || null;
  37452. }
  37453. addMaterial( materialNodeClass, materialClass ) {
  37454. this.addType( materialNodeClass, materialClass.type, this.materialNodes );
  37455. }
  37456. getLightNodeClass( light ) {
  37457. return this.lightNodes.get( light ) || null;
  37458. }
  37459. addLight( lightNodeClass, lightClass ) {
  37460. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  37461. }
  37462. addType( nodeClass, type, library ) {
  37463. if ( library.has( type ) ) {
  37464. console.warn( `Redefinition of node ${ type }` );
  37465. return;
  37466. }
  37467. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37468. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  37469. library.set( type, nodeClass );
  37470. }
  37471. addClass( nodeClass, baseClass, library ) {
  37472. if ( library.has( baseClass ) ) {
  37473. console.warn( `Redefinition of node ${ baseClass.name }` );
  37474. return;
  37475. }
  37476. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37477. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  37478. library.set( baseClass, nodeClass );
  37479. }
  37480. }
  37481. const _defaultLights = /*@__PURE__*/ new LightsNode();
  37482. class Lighting extends ChainMap {
  37483. constructor() {
  37484. super();
  37485. }
  37486. createNode( lights = [] ) {
  37487. return new LightsNode().setLights( lights );
  37488. }
  37489. getNode( scene, camera ) {
  37490. // ignore post-processing
  37491. if ( scene.isQuadMesh ) return _defaultLights;
  37492. // tiled lighting
  37493. const keys = [ scene, camera ];
  37494. let node = this.get( keys );
  37495. if ( node === undefined ) {
  37496. node = this.createNode();
  37497. this.set( keys, node );
  37498. }
  37499. return node;
  37500. }
  37501. }
  37502. const _scene = /*@__PURE__*/ new Scene();
  37503. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  37504. const _screen = /*@__PURE__*/ new Vector4();
  37505. const _frustum = /*@__PURE__*/ new Frustum();
  37506. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  37507. const _vector4 = /*@__PURE__*/ new Vector4();
  37508. class Renderer {
  37509. constructor( backend, parameters = {} ) {
  37510. this.isRenderer = true;
  37511. //
  37512. const {
  37513. logarithmicDepthBuffer = false,
  37514. alpha = true,
  37515. depth = true,
  37516. stencil = false,
  37517. antialias = false,
  37518. samples = 0,
  37519. getFallback = null
  37520. } = parameters;
  37521. // public
  37522. this.domElement = backend.getDomElement();
  37523. this.backend = backend;
  37524. this.samples = samples || ( antialias === true ) ? 4 : 0;
  37525. this.autoClear = true;
  37526. this.autoClearColor = true;
  37527. this.autoClearDepth = true;
  37528. this.autoClearStencil = true;
  37529. this.alpha = alpha;
  37530. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  37531. this.outputColorSpace = SRGBColorSpace;
  37532. this.toneMapping = NoToneMapping;
  37533. this.toneMappingExposure = 1.0;
  37534. this.sortObjects = true;
  37535. this.depth = depth;
  37536. this.stencil = stencil;
  37537. this.clippingPlanes = [];
  37538. this.info = new Info();
  37539. this.nodes = {
  37540. modelViewMatrix: null,
  37541. modelNormalViewMatrix: null
  37542. };
  37543. this.library = new NodeLibrary();
  37544. this.lighting = new Lighting();
  37545. // internals
  37546. this._getFallback = getFallback;
  37547. this._pixelRatio = 1;
  37548. this._width = this.domElement.width;
  37549. this._height = this.domElement.height;
  37550. this._viewport = new Vector4( 0, 0, this._width, this._height );
  37551. this._scissor = new Vector4( 0, 0, this._width, this._height );
  37552. this._scissorTest = false;
  37553. this._attributes = null;
  37554. this._geometries = null;
  37555. this._nodes = null;
  37556. this._animation = null;
  37557. this._bindings = null;
  37558. this._objects = null;
  37559. this._pipelines = null;
  37560. this._bundles = null;
  37561. this._renderLists = null;
  37562. this._renderContexts = null;
  37563. this._textures = null;
  37564. this._background = null;
  37565. this._quad = new QuadMesh( new NodeMaterial() );
  37566. this._quad.material.type = 'Renderer_output';
  37567. this._currentRenderContext = null;
  37568. this._opaqueSort = null;
  37569. this._transparentSort = null;
  37570. this._frameBufferTarget = null;
  37571. const alphaClear = this.alpha === true ? 0 : 1;
  37572. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  37573. this._clearDepth = 1;
  37574. this._clearStencil = 0;
  37575. this._renderTarget = null;
  37576. this._activeCubeFace = 0;
  37577. this._activeMipmapLevel = 0;
  37578. this._mrt = null;
  37579. this._renderObjectFunction = null;
  37580. this._currentRenderObjectFunction = null;
  37581. this._currentRenderBundle = null;
  37582. this._handleObjectFunction = this._renderObjectDirect;
  37583. this._isDeviceLost = false;
  37584. this.onDeviceLost = this._onDeviceLost;
  37585. this._initialized = false;
  37586. this._initPromise = null;
  37587. this._compilationPromises = null;
  37588. this.transparent = true;
  37589. this.opaque = true;
  37590. this.shadowMap = {
  37591. enabled: false,
  37592. type: PCFShadowMap$1
  37593. };
  37594. this.xr = {
  37595. enabled: false
  37596. };
  37597. this.debug = {
  37598. checkShaderErrors: true,
  37599. onShaderError: null,
  37600. getShaderAsync: async ( scene, camera, object ) => {
  37601. await this.compileAsync( scene, camera );
  37602. const renderList = this._renderLists.get( scene, camera );
  37603. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  37604. const material = scene.overrideMaterial || object.material;
  37605. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext );
  37606. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  37607. return { fragmentShader, vertexShader };
  37608. }
  37609. };
  37610. }
  37611. async init() {
  37612. if ( this._initialized ) {
  37613. throw new Error( 'Renderer: Backend has already been initialized.' );
  37614. }
  37615. if ( this._initPromise !== null ) {
  37616. return this._initPromise;
  37617. }
  37618. this._initPromise = new Promise( async ( resolve, reject ) => {
  37619. let backend = this.backend;
  37620. try {
  37621. await backend.init( this );
  37622. } catch ( error ) {
  37623. if ( this._getFallback !== null ) {
  37624. // try the fallback
  37625. try {
  37626. this.backend = backend = this._getFallback( error );
  37627. await backend.init( this );
  37628. } catch ( error ) {
  37629. reject( error );
  37630. return;
  37631. }
  37632. } else {
  37633. reject( error );
  37634. return;
  37635. }
  37636. }
  37637. this._nodes = new Nodes( this, backend );
  37638. this._animation = new Animation( this._nodes, this.info );
  37639. this._attributes = new Attributes( backend );
  37640. this._background = new Background( this, this._nodes );
  37641. this._geometries = new Geometries( this._attributes, this.info );
  37642. this._textures = new Textures( this, backend, this.info );
  37643. this._pipelines = new Pipelines( backend, this._nodes );
  37644. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  37645. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  37646. this._renderLists = new RenderLists( this.lighting );
  37647. this._bundles = new RenderBundles();
  37648. this._renderContexts = new RenderContexts();
  37649. //
  37650. this._initialized = true;
  37651. resolve();
  37652. } );
  37653. return this._initPromise;
  37654. }
  37655. get coordinateSystem() {
  37656. return this.backend.coordinateSystem;
  37657. }
  37658. async compileAsync( scene, camera, targetScene = null ) {
  37659. if ( this._isDeviceLost === true ) return;
  37660. if ( this._initialized === false ) await this.init();
  37661. // preserve render tree
  37662. const nodeFrame = this._nodes.nodeFrame;
  37663. const previousRenderId = nodeFrame.renderId;
  37664. const previousRenderContext = this._currentRenderContext;
  37665. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37666. const previousCompilationPromises = this._compilationPromises;
  37667. //
  37668. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37669. if ( targetScene === null ) targetScene = scene;
  37670. const renderTarget = this._renderTarget;
  37671. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  37672. const activeMipmapLevel = this._activeMipmapLevel;
  37673. const compilationPromises = [];
  37674. this._currentRenderContext = renderContext;
  37675. this._currentRenderObjectFunction = this.renderObject;
  37676. this._handleObjectFunction = this._createObjectPipeline;
  37677. this._compilationPromises = compilationPromises;
  37678. nodeFrame.renderId ++;
  37679. //
  37680. nodeFrame.update();
  37681. //
  37682. renderContext.depth = this.depth;
  37683. renderContext.stencil = this.stencil;
  37684. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37685. renderContext.clippingContext.updateGlobal( this, camera );
  37686. //
  37687. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37688. //
  37689. const renderList = this._renderLists.get( scene, camera );
  37690. renderList.begin();
  37691. this._projectObject( scene, camera, 0, renderList );
  37692. // include lights from target scene
  37693. if ( targetScene !== scene ) {
  37694. targetScene.traverseVisible( function ( object ) {
  37695. if ( object.isLight && object.layers.test( camera.layers ) ) {
  37696. renderList.pushLight( object );
  37697. }
  37698. } );
  37699. }
  37700. renderList.finish();
  37701. //
  37702. if ( renderTarget !== null ) {
  37703. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37704. const renderTargetData = this._textures.get( renderTarget );
  37705. renderContext.textures = renderTargetData.textures;
  37706. renderContext.depthTexture = renderTargetData.depthTexture;
  37707. } else {
  37708. renderContext.textures = null;
  37709. renderContext.depthTexture = null;
  37710. }
  37711. //
  37712. this._nodes.updateScene( sceneRef );
  37713. //
  37714. this._background.update( sceneRef, renderList, renderContext );
  37715. // process render lists
  37716. const opaqueObjects = renderList.opaque;
  37717. const transparentObjects = renderList.transparent;
  37718. const lightsNode = renderList.lightsNode;
  37719. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37720. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, camera, sceneRef, lightsNode );
  37721. // restore render tree
  37722. nodeFrame.renderId = previousRenderId;
  37723. this._currentRenderContext = previousRenderContext;
  37724. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37725. this._compilationPromises = previousCompilationPromises;
  37726. this._handleObjectFunction = this._renderObjectDirect;
  37727. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  37728. await Promise.all( compilationPromises );
  37729. }
  37730. async renderAsync( scene, camera ) {
  37731. if ( this._initialized === false ) await this.init();
  37732. const renderContext = this._renderScene( scene, camera );
  37733. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  37734. }
  37735. async waitForGPU() {
  37736. await this.backend.waitForGPU();
  37737. }
  37738. setMRT( mrt ) {
  37739. this._mrt = mrt;
  37740. return this;
  37741. }
  37742. getMRT() {
  37743. return this._mrt;
  37744. }
  37745. _onDeviceLost( info ) {
  37746. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  37747. if ( info.reason ) {
  37748. errorMessage += `\nReason: ${info.reason}`;
  37749. }
  37750. console.error( errorMessage );
  37751. this._isDeviceLost = true;
  37752. }
  37753. _renderBundle( bundle, sceneRef, lightsNode ) {
  37754. const { bundleGroup, camera, renderList } = bundle;
  37755. const renderContext = this._currentRenderContext;
  37756. //
  37757. const renderBundle = this._bundles.get( bundleGroup, camera );
  37758. const renderBundleData = this.backend.get( renderBundle );
  37759. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  37760. //
  37761. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  37762. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  37763. renderBundleData.renderContexts.add( renderContext );
  37764. if ( renderBundleNeedsUpdate ) {
  37765. this.backend.beginBundle( renderContext );
  37766. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  37767. renderBundleData.renderObjects = [];
  37768. }
  37769. this._currentRenderBundle = renderBundle;
  37770. const opaqueObjects = renderList.opaque;
  37771. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37772. this._currentRenderBundle = null;
  37773. //
  37774. this.backend.finishBundle( renderContext, renderBundle );
  37775. renderBundleData.version = bundleGroup.version;
  37776. } else {
  37777. const { renderObjects } = renderBundleData;
  37778. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  37779. const renderObject = renderObjects[ i ];
  37780. if ( this._nodes.needsRefresh( renderObject ) ) {
  37781. this._nodes.updateBefore( renderObject );
  37782. this._nodes.updateForRender( renderObject );
  37783. this._bindings.updateForRender( renderObject );
  37784. this._nodes.updateAfter( renderObject );
  37785. }
  37786. }
  37787. }
  37788. this.backend.addBundle( renderContext, renderBundle );
  37789. }
  37790. render( scene, camera ) {
  37791. if ( this._initialized === false ) {
  37792. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  37793. return this.renderAsync( scene, camera );
  37794. }
  37795. this._renderScene( scene, camera );
  37796. }
  37797. _getFrameBufferTarget() {
  37798. const { currentToneMapping, currentColorSpace } = this;
  37799. const useToneMapping = currentToneMapping !== NoToneMapping;
  37800. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  37801. if ( useToneMapping === false && useColorSpace === false ) return null;
  37802. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  37803. const { depth, stencil } = this;
  37804. let frameBufferTarget = this._frameBufferTarget;
  37805. if ( frameBufferTarget === null ) {
  37806. frameBufferTarget = new RenderTarget( width, height, {
  37807. depthBuffer: depth,
  37808. stencilBuffer: stencil,
  37809. type: HalfFloatType, // FloatType
  37810. format: RGBAFormat,
  37811. colorSpace: LinearSRGBColorSpace,
  37812. generateMipmaps: false,
  37813. minFilter: LinearFilter,
  37814. magFilter: LinearFilter,
  37815. samples: this.samples
  37816. } );
  37817. frameBufferTarget.isPostProcessingRenderTarget = true;
  37818. this._frameBufferTarget = frameBufferTarget;
  37819. }
  37820. frameBufferTarget.depthBuffer = depth;
  37821. frameBufferTarget.stencilBuffer = stencil;
  37822. frameBufferTarget.setSize( width, height );
  37823. frameBufferTarget.viewport.copy( this._viewport );
  37824. frameBufferTarget.scissor.copy( this._scissor );
  37825. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  37826. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  37827. frameBufferTarget.scissorTest = this._scissorTest;
  37828. return frameBufferTarget;
  37829. }
  37830. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  37831. if ( this._isDeviceLost === true ) return;
  37832. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  37833. // preserve render tree
  37834. const nodeFrame = this._nodes.nodeFrame;
  37835. const previousRenderId = nodeFrame.renderId;
  37836. const previousRenderContext = this._currentRenderContext;
  37837. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37838. //
  37839. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37840. const outputRenderTarget = this._renderTarget;
  37841. const activeCubeFace = this._activeCubeFace;
  37842. const activeMipmapLevel = this._activeMipmapLevel;
  37843. //
  37844. let renderTarget;
  37845. if ( frameBufferTarget !== null ) {
  37846. renderTarget = frameBufferTarget;
  37847. this.setRenderTarget( renderTarget );
  37848. } else {
  37849. renderTarget = outputRenderTarget;
  37850. }
  37851. //
  37852. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  37853. this._currentRenderContext = renderContext;
  37854. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  37855. //
  37856. this.info.calls ++;
  37857. this.info.render.calls ++;
  37858. this.info.render.frameCalls ++;
  37859. nodeFrame.renderId = this.info.calls;
  37860. //
  37861. const coordinateSystem = this.coordinateSystem;
  37862. if ( camera.coordinateSystem !== coordinateSystem ) {
  37863. camera.coordinateSystem = coordinateSystem;
  37864. camera.updateProjectionMatrix();
  37865. }
  37866. //
  37867. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  37868. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  37869. //
  37870. let viewport = this._viewport;
  37871. let scissor = this._scissor;
  37872. let pixelRatio = this._pixelRatio;
  37873. if ( renderTarget !== null ) {
  37874. viewport = renderTarget.viewport;
  37875. scissor = renderTarget.scissor;
  37876. pixelRatio = 1;
  37877. }
  37878. this.getDrawingBufferSize( _drawingBufferSize );
  37879. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  37880. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  37881. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  37882. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  37883. renderContext.viewportValue.width >>= activeMipmapLevel;
  37884. renderContext.viewportValue.height >>= activeMipmapLevel;
  37885. renderContext.viewportValue.minDepth = minDepth;
  37886. renderContext.viewportValue.maxDepth = maxDepth;
  37887. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  37888. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  37889. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  37890. renderContext.scissorValue.width >>= activeMipmapLevel;
  37891. renderContext.scissorValue.height >>= activeMipmapLevel;
  37892. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37893. renderContext.clippingContext.updateGlobal( this, camera );
  37894. //
  37895. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37896. //
  37897. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  37898. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  37899. const renderList = this._renderLists.get( scene, camera );
  37900. renderList.begin();
  37901. this._projectObject( scene, camera, 0, renderList );
  37902. renderList.finish();
  37903. if ( this.sortObjects === true ) {
  37904. renderList.sort( this._opaqueSort, this._transparentSort );
  37905. }
  37906. //
  37907. if ( renderTarget !== null ) {
  37908. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37909. const renderTargetData = this._textures.get( renderTarget );
  37910. renderContext.textures = renderTargetData.textures;
  37911. renderContext.depthTexture = renderTargetData.depthTexture;
  37912. renderContext.width = renderTargetData.width;
  37913. renderContext.height = renderTargetData.height;
  37914. renderContext.renderTarget = renderTarget;
  37915. renderContext.depth = renderTarget.depthBuffer;
  37916. renderContext.stencil = renderTarget.stencilBuffer;
  37917. } else {
  37918. renderContext.textures = null;
  37919. renderContext.depthTexture = null;
  37920. renderContext.width = this.domElement.width;
  37921. renderContext.height = this.domElement.height;
  37922. renderContext.depth = this.depth;
  37923. renderContext.stencil = this.stencil;
  37924. }
  37925. renderContext.width >>= activeMipmapLevel;
  37926. renderContext.height >>= activeMipmapLevel;
  37927. renderContext.activeCubeFace = activeCubeFace;
  37928. renderContext.activeMipmapLevel = activeMipmapLevel;
  37929. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  37930. //
  37931. this._nodes.updateScene( sceneRef );
  37932. //
  37933. this._background.update( sceneRef, renderList, renderContext );
  37934. //
  37935. this.backend.beginRender( renderContext );
  37936. // process render lists
  37937. const {
  37938. bundles,
  37939. lightsNode,
  37940. transparentDoublePass: transparentDoublePassObjects,
  37941. transparent: transparentObjects,
  37942. opaque: opaqueObjects
  37943. } = renderList;
  37944. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  37945. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37946. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37947. // finish render pass
  37948. this.backend.finishRender( renderContext );
  37949. // restore render tree
  37950. nodeFrame.renderId = previousRenderId;
  37951. this._currentRenderContext = previousRenderContext;
  37952. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37953. //
  37954. if ( frameBufferTarget !== null ) {
  37955. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  37956. const quad = this._quad;
  37957. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37958. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37959. quad.material.needsUpdate = true;
  37960. }
  37961. this._renderScene( quad, quad.camera, false );
  37962. }
  37963. //
  37964. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  37965. //
  37966. return renderContext;
  37967. }
  37968. getMaxAnisotropy() {
  37969. return this.backend.getMaxAnisotropy();
  37970. }
  37971. getActiveCubeFace() {
  37972. return this._activeCubeFace;
  37973. }
  37974. getActiveMipmapLevel() {
  37975. return this._activeMipmapLevel;
  37976. }
  37977. async setAnimationLoop( callback ) {
  37978. if ( this._initialized === false ) await this.init();
  37979. this._animation.setAnimationLoop( callback );
  37980. }
  37981. async getArrayBufferAsync( attribute ) {
  37982. return await this.backend.getArrayBufferAsync( attribute );
  37983. }
  37984. getContext() {
  37985. return this.backend.getContext();
  37986. }
  37987. getPixelRatio() {
  37988. return this._pixelRatio;
  37989. }
  37990. getDrawingBufferSize( target ) {
  37991. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  37992. }
  37993. getSize( target ) {
  37994. return target.set( this._width, this._height );
  37995. }
  37996. setPixelRatio( value = 1 ) {
  37997. if ( this._pixelRatio === value ) return;
  37998. this._pixelRatio = value;
  37999. this.setSize( this._width, this._height, false );
  38000. }
  38001. setDrawingBufferSize( width, height, pixelRatio ) {
  38002. this._width = width;
  38003. this._height = height;
  38004. this._pixelRatio = pixelRatio;
  38005. this.domElement.width = Math.floor( width * pixelRatio );
  38006. this.domElement.height = Math.floor( height * pixelRatio );
  38007. this.setViewport( 0, 0, width, height );
  38008. if ( this._initialized ) this.backend.updateSize();
  38009. }
  38010. setSize( width, height, updateStyle = true ) {
  38011. this._width = width;
  38012. this._height = height;
  38013. this.domElement.width = Math.floor( width * this._pixelRatio );
  38014. this.domElement.height = Math.floor( height * this._pixelRatio );
  38015. if ( updateStyle === true ) {
  38016. this.domElement.style.width = width + 'px';
  38017. this.domElement.style.height = height + 'px';
  38018. }
  38019. this.setViewport( 0, 0, width, height );
  38020. if ( this._initialized ) this.backend.updateSize();
  38021. }
  38022. setOpaqueSort( method ) {
  38023. this._opaqueSort = method;
  38024. }
  38025. setTransparentSort( method ) {
  38026. this._transparentSort = method;
  38027. }
  38028. getScissor( target ) {
  38029. const scissor = this._scissor;
  38030. target.x = scissor.x;
  38031. target.y = scissor.y;
  38032. target.width = scissor.width;
  38033. target.height = scissor.height;
  38034. return target;
  38035. }
  38036. setScissor( x, y, width, height ) {
  38037. const scissor = this._scissor;
  38038. if ( x.isVector4 ) {
  38039. scissor.copy( x );
  38040. } else {
  38041. scissor.set( x, y, width, height );
  38042. }
  38043. }
  38044. getScissorTest() {
  38045. return this._scissorTest;
  38046. }
  38047. setScissorTest( boolean ) {
  38048. this._scissorTest = boolean;
  38049. this.backend.setScissorTest( boolean );
  38050. }
  38051. getViewport( target ) {
  38052. return target.copy( this._viewport );
  38053. }
  38054. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  38055. const viewport = this._viewport;
  38056. if ( x.isVector4 ) {
  38057. viewport.copy( x );
  38058. } else {
  38059. viewport.set( x, y, width, height );
  38060. }
  38061. viewport.minDepth = minDepth;
  38062. viewport.maxDepth = maxDepth;
  38063. }
  38064. getClearColor( target ) {
  38065. return target.copy( this._clearColor );
  38066. }
  38067. setClearColor( color, alpha = 1 ) {
  38068. this._clearColor.set( color );
  38069. this._clearColor.a = alpha;
  38070. }
  38071. getClearAlpha() {
  38072. return this._clearColor.a;
  38073. }
  38074. setClearAlpha( alpha ) {
  38075. this._clearColor.a = alpha;
  38076. }
  38077. getClearDepth() {
  38078. return this._clearDepth;
  38079. }
  38080. setClearDepth( depth ) {
  38081. this._clearDepth = depth;
  38082. }
  38083. getClearStencil() {
  38084. return this._clearStencil;
  38085. }
  38086. setClearStencil( stencil ) {
  38087. this._clearStencil = stencil;
  38088. }
  38089. isOccluded( object ) {
  38090. const renderContext = this._currentRenderContext;
  38091. return renderContext && this.backend.isOccluded( renderContext, object );
  38092. }
  38093. clear( color = true, depth = true, stencil = true ) {
  38094. if ( this._initialized === false ) {
  38095. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  38096. return this.clearAsync( color, depth, stencil );
  38097. }
  38098. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38099. let renderTargetData = null;
  38100. if ( renderTarget !== null ) {
  38101. this._textures.updateRenderTarget( renderTarget );
  38102. renderTargetData = this._textures.get( renderTarget );
  38103. }
  38104. this.backend.clear( color, depth, stencil, renderTargetData );
  38105. if ( renderTarget !== null && this._renderTarget === null ) {
  38106. // If a color space transform or tone mapping is required,
  38107. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  38108. const quad = this._quad;
  38109. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  38110. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  38111. quad.material.needsUpdate = true;
  38112. }
  38113. this._renderScene( quad, quad.camera, false );
  38114. }
  38115. }
  38116. clearColor() {
  38117. return this.clear( true, false, false );
  38118. }
  38119. clearDepth() {
  38120. return this.clear( false, true, false );
  38121. }
  38122. clearStencil() {
  38123. return this.clear( false, false, true );
  38124. }
  38125. async clearAsync( color = true, depth = true, stencil = true ) {
  38126. if ( this._initialized === false ) await this.init();
  38127. this.clear( color, depth, stencil );
  38128. }
  38129. clearColorAsync() {
  38130. return this.clearAsync( true, false, false );
  38131. }
  38132. clearDepthAsync() {
  38133. return this.clearAsync( false, true, false );
  38134. }
  38135. clearStencilAsync() {
  38136. return this.clearAsync( false, false, true );
  38137. }
  38138. get currentToneMapping() {
  38139. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  38140. }
  38141. get currentColorSpace() {
  38142. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  38143. }
  38144. dispose() {
  38145. this.info.dispose();
  38146. this.backend.dispose();
  38147. this._animation.dispose();
  38148. this._objects.dispose();
  38149. this._pipelines.dispose();
  38150. this._nodes.dispose();
  38151. this._bindings.dispose();
  38152. this._renderLists.dispose();
  38153. this._renderContexts.dispose();
  38154. this._textures.dispose();
  38155. this.setRenderTarget( null );
  38156. this.setAnimationLoop( null );
  38157. }
  38158. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  38159. this._renderTarget = renderTarget;
  38160. this._activeCubeFace = activeCubeFace;
  38161. this._activeMipmapLevel = activeMipmapLevel;
  38162. }
  38163. getRenderTarget() {
  38164. return this._renderTarget;
  38165. }
  38166. setRenderObjectFunction( renderObjectFunction ) {
  38167. this._renderObjectFunction = renderObjectFunction;
  38168. }
  38169. getRenderObjectFunction() {
  38170. return this._renderObjectFunction;
  38171. }
  38172. compute( computeNodes ) {
  38173. if ( this.isDeviceLost === true ) return;
  38174. if ( this._initialized === false ) {
  38175. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  38176. return this.computeAsync( computeNodes );
  38177. }
  38178. //
  38179. const nodeFrame = this._nodes.nodeFrame;
  38180. const previousRenderId = nodeFrame.renderId;
  38181. //
  38182. this.info.calls ++;
  38183. this.info.compute.calls ++;
  38184. this.info.compute.frameCalls ++;
  38185. nodeFrame.renderId = this.info.calls;
  38186. //
  38187. const backend = this.backend;
  38188. const pipelines = this._pipelines;
  38189. const bindings = this._bindings;
  38190. const nodes = this._nodes;
  38191. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  38192. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  38193. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  38194. }
  38195. backend.beginCompute( computeNodes );
  38196. for ( const computeNode of computeList ) {
  38197. // onInit
  38198. if ( pipelines.has( computeNode ) === false ) {
  38199. const dispose = () => {
  38200. computeNode.removeEventListener( 'dispose', dispose );
  38201. pipelines.delete( computeNode );
  38202. bindings.delete( computeNode );
  38203. nodes.delete( computeNode );
  38204. };
  38205. computeNode.addEventListener( 'dispose', dispose );
  38206. //
  38207. const onInitFn = computeNode.onInitFunction;
  38208. if ( onInitFn !== null ) {
  38209. onInitFn.call( computeNode, { renderer: this } );
  38210. }
  38211. }
  38212. nodes.updateForCompute( computeNode );
  38213. bindings.updateForCompute( computeNode );
  38214. const computeBindings = bindings.getForCompute( computeNode );
  38215. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  38216. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  38217. }
  38218. backend.finishCompute( computeNodes );
  38219. //
  38220. nodeFrame.renderId = previousRenderId;
  38221. }
  38222. async computeAsync( computeNodes ) {
  38223. if ( this._initialized === false ) await this.init();
  38224. this.compute( computeNodes );
  38225. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  38226. }
  38227. async hasFeatureAsync( name ) {
  38228. if ( this._initialized === false ) await this.init();
  38229. return this.backend.hasFeature( name );
  38230. }
  38231. hasFeature( name ) {
  38232. if ( this._initialized === false ) {
  38233. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  38234. return false;
  38235. }
  38236. return this.backend.hasFeature( name );
  38237. }
  38238. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  38239. if ( rectangle !== null ) {
  38240. if ( rectangle.isVector2 ) {
  38241. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  38242. } else if ( rectangle.isVector4 ) {
  38243. rectangle = _vector4.copy( rectangle ).floor();
  38244. } else {
  38245. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  38246. return;
  38247. }
  38248. } else {
  38249. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  38250. }
  38251. //
  38252. let renderContext = this._currentRenderContext;
  38253. let renderTarget;
  38254. if ( renderContext !== null ) {
  38255. renderTarget = renderContext.renderTarget;
  38256. } else {
  38257. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38258. if ( renderTarget !== null ) {
  38259. this._textures.updateRenderTarget( renderTarget );
  38260. renderContext = this._textures.get( renderTarget );
  38261. }
  38262. }
  38263. //
  38264. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  38265. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  38266. }
  38267. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  38268. this._textures.updateTexture( srcTexture );
  38269. this._textures.updateTexture( dstTexture );
  38270. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  38271. }
  38272. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  38273. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  38274. }
  38275. _projectObject( object, camera, groupOrder, renderList ) {
  38276. if ( object.visible === false ) return;
  38277. const visible = object.layers.test( camera.layers );
  38278. if ( visible ) {
  38279. if ( object.isGroup ) {
  38280. groupOrder = object.renderOrder;
  38281. } else if ( object.isLOD ) {
  38282. if ( object.autoUpdate === true ) object.update( camera );
  38283. } else if ( object.isLight ) {
  38284. renderList.pushLight( object );
  38285. } else if ( object.isSprite ) {
  38286. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  38287. if ( this.sortObjects === true ) {
  38288. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  38289. }
  38290. const { geometry, material } = object;
  38291. if ( material.visible ) {
  38292. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  38293. }
  38294. }
  38295. } else if ( object.isLineLoop ) {
  38296. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  38297. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  38298. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  38299. const { geometry, material } = object;
  38300. if ( this.sortObjects === true ) {
  38301. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  38302. _vector4
  38303. .copy( geometry.boundingSphere.center )
  38304. .applyMatrix4( object.matrixWorld )
  38305. .applyMatrix4( _projScreenMatrix );
  38306. }
  38307. if ( Array.isArray( material ) ) {
  38308. const groups = geometry.groups;
  38309. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  38310. const group = groups[ i ];
  38311. const groupMaterial = material[ group.materialIndex ];
  38312. if ( groupMaterial && groupMaterial.visible ) {
  38313. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  38314. }
  38315. }
  38316. } else if ( material.visible ) {
  38317. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  38318. }
  38319. }
  38320. }
  38321. }
  38322. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  38323. const baseRenderList = renderList;
  38324. // replace render list
  38325. renderList = this._renderLists.get( object, camera );
  38326. renderList.begin();
  38327. baseRenderList.pushBundle( {
  38328. bundleGroup: object,
  38329. camera,
  38330. renderList,
  38331. } );
  38332. renderList.finish();
  38333. }
  38334. const children = object.children;
  38335. for ( let i = 0, l = children.length; i < l; i ++ ) {
  38336. this._projectObject( children[ i ], camera, groupOrder, renderList );
  38337. }
  38338. }
  38339. _renderBundles( bundles, sceneRef, lightsNode ) {
  38340. for ( const bundle of bundles ) {
  38341. this._renderBundle( bundle, sceneRef, lightsNode );
  38342. }
  38343. }
  38344. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  38345. if ( doublePassList.length > 0 ) {
  38346. // render back side
  38347. for ( const { material } of doublePassList ) {
  38348. material.side = BackSide;
  38349. }
  38350. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  38351. // render front side
  38352. for ( const { material } of doublePassList ) {
  38353. material.side = FrontSide;
  38354. }
  38355. this._renderObjects( renderList, camera, scene, lightsNode );
  38356. // restore
  38357. for ( const { material } of doublePassList ) {
  38358. material.side = DoubleSide;
  38359. }
  38360. } else {
  38361. this._renderObjects( renderList, camera, scene, lightsNode );
  38362. }
  38363. }
  38364. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  38365. // process renderable objects
  38366. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  38367. const renderItem = renderList[ i ];
  38368. // @TODO: Add support for multiple materials per object. This will require to extract
  38369. // the material from the renderItem object and pass it with its group data to renderObject().
  38370. const { object, geometry, material, group } = renderItem;
  38371. if ( camera.isArrayCamera ) {
  38372. const cameras = camera.cameras;
  38373. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  38374. const camera2 = cameras[ j ];
  38375. if ( object.layers.test( camera2.layers ) ) {
  38376. const vp = camera2.viewport;
  38377. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  38378. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  38379. const viewportValue = this._currentRenderContext.viewportValue;
  38380. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  38381. viewportValue.minDepth = minDepth;
  38382. viewportValue.maxDepth = maxDepth;
  38383. this.backend.updateViewport( this._currentRenderContext );
  38384. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, passId );
  38385. }
  38386. }
  38387. } else {
  38388. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, passId );
  38389. }
  38390. }
  38391. }
  38392. renderObject( object, scene, camera, geometry, material, group, lightsNode, passId = null ) {
  38393. let overridePositionNode;
  38394. let overrideFragmentNode;
  38395. let overrideDepthNode;
  38396. //
  38397. object.onBeforeRender( this, scene, camera, geometry, material, group );
  38398. //
  38399. if ( scene.overrideMaterial !== null ) {
  38400. const overrideMaterial = scene.overrideMaterial;
  38401. if ( material.positionNode && material.positionNode.isNode ) {
  38402. overridePositionNode = overrideMaterial.positionNode;
  38403. overrideMaterial.positionNode = material.positionNode;
  38404. }
  38405. if ( overrideMaterial.isShadowNodeMaterial ) {
  38406. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  38407. if ( material.depthNode && material.depthNode.isNode ) {
  38408. overrideDepthNode = overrideMaterial.depthNode;
  38409. overrideMaterial.depthNode = material.depthNode;
  38410. }
  38411. if ( material.shadowNode && material.shadowNode.isNode ) {
  38412. overrideFragmentNode = overrideMaterial.fragmentNode;
  38413. overrideMaterial.fragmentNode = material.shadowNode;
  38414. }
  38415. if ( this.localClippingEnabled ) {
  38416. if ( material.clipShadows ) {
  38417. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  38418. overrideMaterial.clippingPlanes = material.clippingPlanes;
  38419. overrideMaterial.needsUpdate = true;
  38420. }
  38421. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  38422. overrideMaterial.clipIntersection = material.clipIntersection;
  38423. }
  38424. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  38425. overrideMaterial.clippingPlanes = null;
  38426. overrideMaterial.needsUpdate = true;
  38427. }
  38428. }
  38429. }
  38430. material = overrideMaterial;
  38431. }
  38432. //
  38433. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  38434. material.side = BackSide;
  38435. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  38436. material.side = FrontSide;
  38437. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, passId ); // use default pass id
  38438. material.side = DoubleSide;
  38439. } else {
  38440. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, passId );
  38441. }
  38442. //
  38443. if ( overridePositionNode !== undefined ) {
  38444. scene.overrideMaterial.positionNode = overridePositionNode;
  38445. }
  38446. if ( overrideDepthNode !== undefined ) {
  38447. scene.overrideMaterial.depthNode = overrideDepthNode;
  38448. }
  38449. if ( overrideFragmentNode !== undefined ) {
  38450. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  38451. }
  38452. //
  38453. object.onAfterRender( this, scene, camera, geometry, material, group );
  38454. }
  38455. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  38456. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  38457. renderObject.drawRange = object.geometry.drawRange;
  38458. renderObject.group = group;
  38459. //
  38460. const needsRefresh = this._nodes.needsRefresh( renderObject );
  38461. if ( needsRefresh ) {
  38462. this._nodes.updateBefore( renderObject );
  38463. this._geometries.updateForRender( renderObject );
  38464. this._nodes.updateForRender( renderObject );
  38465. this._bindings.updateForRender( renderObject );
  38466. }
  38467. this._pipelines.updateForRender( renderObject );
  38468. //
  38469. if ( this._currentRenderBundle !== null ) {
  38470. const renderBundleData = this.backend.get( this._currentRenderBundle );
  38471. renderBundleData.renderObjects.push( renderObject );
  38472. renderObject.bundle = this._currentRenderBundle.scene;
  38473. }
  38474. this.backend.draw( renderObject, this.info );
  38475. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  38476. }
  38477. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  38478. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  38479. //
  38480. this._nodes.updateBefore( renderObject );
  38481. this._geometries.updateForRender( renderObject );
  38482. this._nodes.updateForRender( renderObject );
  38483. this._bindings.updateForRender( renderObject );
  38484. this._pipelines.getForRender( renderObject, this._compilationPromises );
  38485. this._nodes.updateAfter( renderObject );
  38486. }
  38487. get compile() {
  38488. return this.compileAsync;
  38489. }
  38490. }
  38491. class Binding {
  38492. constructor( name = '' ) {
  38493. this.name = name;
  38494. this.visibility = 0;
  38495. }
  38496. setVisibility( visibility ) {
  38497. this.visibility |= visibility;
  38498. }
  38499. clone() {
  38500. return Object.assign( new this.constructor(), this );
  38501. }
  38502. }
  38503. function getFloatLength( floatLength ) {
  38504. // ensure chunk size alignment (STD140 layout)
  38505. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  38506. }
  38507. class Buffer extends Binding {
  38508. constructor( name, buffer = null ) {
  38509. super( name );
  38510. this.isBuffer = true;
  38511. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  38512. this._buffer = buffer;
  38513. }
  38514. get byteLength() {
  38515. return getFloatLength( this._buffer.byteLength );
  38516. }
  38517. get buffer() {
  38518. return this._buffer;
  38519. }
  38520. update() {
  38521. return true;
  38522. }
  38523. }
  38524. class UniformBuffer extends Buffer {
  38525. constructor( name, buffer = null ) {
  38526. super( name, buffer );
  38527. this.isUniformBuffer = true;
  38528. }
  38529. }
  38530. let _id$4 = 0;
  38531. class NodeUniformBuffer extends UniformBuffer {
  38532. constructor( nodeUniform, groupNode ) {
  38533. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  38534. this.nodeUniform = nodeUniform;
  38535. this.groupNode = groupNode;
  38536. }
  38537. get buffer() {
  38538. return this.nodeUniform.value;
  38539. }
  38540. }
  38541. class UniformsGroup extends UniformBuffer {
  38542. constructor( name ) {
  38543. super( name );
  38544. this.isUniformsGroup = true;
  38545. this._values = null;
  38546. // the order of uniforms in this array must match the order of uniforms in the shader
  38547. this.uniforms = [];
  38548. }
  38549. addUniform( uniform ) {
  38550. this.uniforms.push( uniform );
  38551. return this;
  38552. }
  38553. removeUniform( uniform ) {
  38554. const index = this.uniforms.indexOf( uniform );
  38555. if ( index !== - 1 ) {
  38556. this.uniforms.splice( index, 1 );
  38557. }
  38558. return this;
  38559. }
  38560. get values() {
  38561. if ( this._values === null ) {
  38562. this._values = Array.from( this.buffer );
  38563. }
  38564. return this._values;
  38565. }
  38566. get buffer() {
  38567. let buffer = this._buffer;
  38568. if ( buffer === null ) {
  38569. const byteLength = this.byteLength;
  38570. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  38571. this._buffer = buffer;
  38572. }
  38573. return buffer;
  38574. }
  38575. get byteLength() {
  38576. let offset = 0; // global buffer offset in bytes
  38577. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  38578. const uniform = this.uniforms[ i ];
  38579. const { boundary, itemSize } = uniform;
  38580. // offset within a single chunk in bytes
  38581. const chunkOffset = offset % GPU_CHUNK_BYTES;
  38582. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  38583. // conformance tests
  38584. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  38585. // check for chunk overflow
  38586. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  38587. } else if ( chunkOffset % boundary !== 0 ) {
  38588. // check for correct alignment
  38589. offset += ( chunkOffset % boundary );
  38590. }
  38591. uniform.offset = ( offset / this.bytesPerElement );
  38592. offset += ( itemSize * this.bytesPerElement );
  38593. }
  38594. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  38595. }
  38596. update() {
  38597. let updated = false;
  38598. for ( const uniform of this.uniforms ) {
  38599. if ( this.updateByType( uniform ) === true ) {
  38600. updated = true;
  38601. }
  38602. }
  38603. return updated;
  38604. }
  38605. updateByType( uniform ) {
  38606. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  38607. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  38608. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  38609. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  38610. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  38611. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  38612. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  38613. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  38614. }
  38615. updateNumber( uniform ) {
  38616. let updated = false;
  38617. const a = this.values;
  38618. const v = uniform.getValue();
  38619. const offset = uniform.offset;
  38620. if ( a[ offset ] !== v ) {
  38621. const b = this.buffer;
  38622. b[ offset ] = a[ offset ] = v;
  38623. updated = true;
  38624. }
  38625. return updated;
  38626. }
  38627. updateVector2( uniform ) {
  38628. let updated = false;
  38629. const a = this.values;
  38630. const v = uniform.getValue();
  38631. const offset = uniform.offset;
  38632. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  38633. const b = this.buffer;
  38634. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38635. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38636. updated = true;
  38637. }
  38638. return updated;
  38639. }
  38640. updateVector3( uniform ) {
  38641. let updated = false;
  38642. const a = this.values;
  38643. const v = uniform.getValue();
  38644. const offset = uniform.offset;
  38645. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  38646. const b = this.buffer;
  38647. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38648. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38649. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38650. updated = true;
  38651. }
  38652. return updated;
  38653. }
  38654. updateVector4( uniform ) {
  38655. let updated = false;
  38656. const a = this.values;
  38657. const v = uniform.getValue();
  38658. const offset = uniform.offset;
  38659. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  38660. const b = this.buffer;
  38661. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38662. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38663. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38664. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  38665. updated = true;
  38666. }
  38667. return updated;
  38668. }
  38669. updateColor( uniform ) {
  38670. let updated = false;
  38671. const a = this.values;
  38672. const c = uniform.getValue();
  38673. const offset = uniform.offset;
  38674. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  38675. const b = this.buffer;
  38676. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  38677. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  38678. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  38679. updated = true;
  38680. }
  38681. return updated;
  38682. }
  38683. updateMatrix3( uniform ) {
  38684. let updated = false;
  38685. const a = this.values;
  38686. const e = uniform.getValue().elements;
  38687. const offset = uniform.offset;
  38688. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  38689. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  38690. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  38691. const b = this.buffer;
  38692. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  38693. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  38694. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  38695. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  38696. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  38697. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  38698. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  38699. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  38700. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  38701. updated = true;
  38702. }
  38703. return updated;
  38704. }
  38705. updateMatrix4( uniform ) {
  38706. let updated = false;
  38707. const a = this.values;
  38708. const e = uniform.getValue().elements;
  38709. const offset = uniform.offset;
  38710. if ( arraysEqual( a, e, offset ) === false ) {
  38711. const b = this.buffer;
  38712. b.set( e, offset );
  38713. setArray( a, e, offset );
  38714. updated = true;
  38715. }
  38716. return updated;
  38717. }
  38718. }
  38719. function setArray( a, b, offset ) {
  38720. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38721. a[ offset + i ] = b[ i ];
  38722. }
  38723. }
  38724. function arraysEqual( a, b, offset ) {
  38725. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38726. if ( a[ offset + i ] !== b[ i ] ) return false;
  38727. }
  38728. return true;
  38729. }
  38730. let _id$3 = 0;
  38731. class NodeUniformsGroup extends UniformsGroup {
  38732. constructor( name, groupNode ) {
  38733. super( name );
  38734. this.id = _id$3 ++;
  38735. this.groupNode = groupNode;
  38736. this.isNodeUniformsGroup = true;
  38737. }
  38738. getNodes() {
  38739. const nodes = [];
  38740. for ( const uniform of this.uniforms ) {
  38741. const node = uniform.nodeUniform.node;
  38742. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  38743. nodes.push( node );
  38744. }
  38745. return nodes;
  38746. }
  38747. }
  38748. let _id$2 = 0;
  38749. class SampledTexture extends Binding {
  38750. constructor( name, texture ) {
  38751. super( name );
  38752. this.id = _id$2 ++;
  38753. this.texture = texture;
  38754. this.version = texture ? texture.version : 0;
  38755. this.store = false;
  38756. this.generation = null;
  38757. this.isSampledTexture = true;
  38758. }
  38759. needsBindingsUpdate( generation ) {
  38760. const { texture } = this;
  38761. if ( generation !== this.generation ) {
  38762. this.generation = generation;
  38763. return true;
  38764. }
  38765. return texture.isVideoTexture;
  38766. }
  38767. update() {
  38768. const { texture, version } = this;
  38769. if ( version !== texture.version ) {
  38770. this.version = texture.version;
  38771. return true;
  38772. }
  38773. return false;
  38774. }
  38775. }
  38776. class NodeSampledTexture extends SampledTexture {
  38777. constructor( name, textureNode, groupNode, access = null ) {
  38778. super( name, textureNode ? textureNode.value : null );
  38779. this.textureNode = textureNode;
  38780. this.groupNode = groupNode;
  38781. this.access = access;
  38782. }
  38783. needsBindingsUpdate( generation ) {
  38784. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  38785. }
  38786. update() {
  38787. const { textureNode } = this;
  38788. if ( this.texture !== textureNode.value ) {
  38789. this.texture = textureNode.value;
  38790. return true;
  38791. }
  38792. return super.update();
  38793. }
  38794. }
  38795. class NodeSampledCubeTexture extends NodeSampledTexture {
  38796. constructor( name, textureNode, groupNode, access ) {
  38797. super( name, textureNode, groupNode, access );
  38798. this.isSampledCubeTexture = true;
  38799. }
  38800. }
  38801. class NodeSampledTexture3D extends NodeSampledTexture {
  38802. constructor( name, textureNode, groupNode, access ) {
  38803. super( name, textureNode, groupNode, access );
  38804. this.isSampledTexture3D = true;
  38805. }
  38806. }
  38807. const glslMethods = {
  38808. atan2: 'atan',
  38809. textureDimensions: 'textureSize',
  38810. equals: 'equal'
  38811. };
  38812. const precisionLib = {
  38813. low: 'lowp',
  38814. medium: 'mediump',
  38815. high: 'highp'
  38816. };
  38817. const supports$1 = {
  38818. swizzleAssign: true,
  38819. storageBuffer: false
  38820. };
  38821. const defaultPrecisions = `
  38822. precision highp float;
  38823. precision highp int;
  38824. precision highp sampler2D;
  38825. precision highp sampler3D;
  38826. precision highp samplerCube;
  38827. precision highp sampler2DArray;
  38828. precision highp usampler2D;
  38829. precision highp usampler3D;
  38830. precision highp usamplerCube;
  38831. precision highp usampler2DArray;
  38832. precision highp isampler2D;
  38833. precision highp isampler3D;
  38834. precision highp isamplerCube;
  38835. precision highp isampler2DArray;
  38836. precision lowp sampler2DShadow;
  38837. `;
  38838. class GLSLNodeBuilder extends NodeBuilder {
  38839. constructor( object, renderer ) {
  38840. super( object, renderer, new GLSLNodeParser() );
  38841. this.uniformGroups = {};
  38842. this.transforms = [];
  38843. this.extensions = {};
  38844. this.useComparisonMethod = true;
  38845. }
  38846. needsColorSpaceToLinearSRGB( texture ) {
  38847. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  38848. }
  38849. getMethod( method ) {
  38850. return glslMethods[ method ] || method;
  38851. }
  38852. getOutputStructName() {
  38853. return '';
  38854. }
  38855. buildFunctionCode( shaderNode ) {
  38856. const layout = shaderNode.layout;
  38857. const flowData = this.flowShaderNode( shaderNode );
  38858. const parameters = [];
  38859. for ( const input of layout.inputs ) {
  38860. parameters.push( this.getType( input.type ) + ' ' + input.name );
  38861. }
  38862. //
  38863. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  38864. ${ flowData.vars }
  38865. ${ flowData.code }
  38866. return ${ flowData.result };
  38867. }`;
  38868. //
  38869. return code;
  38870. }
  38871. setupPBO( storageBufferNode ) {
  38872. const attribute = storageBufferNode.value;
  38873. if ( attribute.pbo === undefined ) {
  38874. const originalArray = attribute.array;
  38875. const numElements = attribute.count * attribute.itemSize;
  38876. const { itemSize } = attribute;
  38877. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  38878. let format = isInteger ? RedIntegerFormat : RedFormat;
  38879. if ( itemSize === 2 ) {
  38880. format = isInteger ? RGIntegerFormat : RGFormat;
  38881. } else if ( itemSize === 3 ) {
  38882. format = isInteger ? RGBIntegerFormat : RGBFormat;
  38883. } else if ( itemSize === 4 ) {
  38884. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  38885. }
  38886. const typeMap = {
  38887. Float32Array: FloatType,
  38888. Uint8Array: UnsignedByteType,
  38889. Uint16Array: UnsignedShortType,
  38890. Uint32Array: UnsignedIntType,
  38891. Int8Array: ByteType,
  38892. Int16Array: ShortType,
  38893. Int32Array: IntType,
  38894. Uint8ClampedArray: UnsignedByteType,
  38895. };
  38896. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  38897. let height = Math.ceil( ( numElements / itemSize ) / width );
  38898. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  38899. const newSize = width * height * itemSize;
  38900. const newArray = new originalArray.constructor( newSize );
  38901. newArray.set( originalArray, 0 );
  38902. attribute.array = newArray;
  38903. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  38904. pboTexture.needsUpdate = true;
  38905. pboTexture.isPBOTexture = true;
  38906. const pbo = new TextureNode( pboTexture, null, null );
  38907. pbo.setPrecision( 'high' );
  38908. attribute.pboNode = pbo;
  38909. attribute.pbo = pbo.value;
  38910. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38911. }
  38912. }
  38913. getPropertyName( node, shaderStage = this.shaderStage ) {
  38914. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  38915. return shaderStage.charAt( 0 ) + '_' + node.name;
  38916. }
  38917. return super.getPropertyName( node, shaderStage );
  38918. }
  38919. generatePBO( storageArrayElementNode ) {
  38920. const { node, indexNode } = storageArrayElementNode;
  38921. const attribute = node.value;
  38922. if ( this.renderer.backend.has( attribute ) ) {
  38923. const attributeData = this.renderer.backend.get( attribute );
  38924. attributeData.pbo = attribute.pbo;
  38925. }
  38926. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38927. const textureName = this.getPropertyName( nodeUniform );
  38928. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  38929. const indexSnippet = indexNode.build( this, 'uint' );
  38930. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  38931. let propertyName = elementNodeData.propertyName;
  38932. if ( propertyName === undefined ) {
  38933. // property element
  38934. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  38935. propertyName = this.getPropertyName( nodeVar );
  38936. // property size
  38937. const bufferNodeData = this.getDataFromNode( node );
  38938. let propertySizeName = bufferNodeData.propertySizeName;
  38939. if ( propertySizeName === undefined ) {
  38940. propertySizeName = propertyName + 'Size';
  38941. this.getVarFromNode( node, propertySizeName, 'uint' );
  38942. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  38943. bufferNodeData.propertySizeName = propertySizeName;
  38944. }
  38945. //
  38946. const { itemSize } = attribute;
  38947. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  38948. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  38949. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  38950. //
  38951. let prefix = 'vec4';
  38952. if ( attribute.pbo.type === UnsignedIntType ) {
  38953. prefix = 'uvec4';
  38954. } else if ( attribute.pbo.type === IntType ) {
  38955. prefix = 'ivec4';
  38956. }
  38957. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  38958. elementNodeData.propertyName = propertyName;
  38959. }
  38960. return propertyName;
  38961. }
  38962. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  38963. if ( depthSnippet ) {
  38964. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  38965. } else {
  38966. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  38967. }
  38968. }
  38969. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  38970. if ( texture.isDepthTexture ) {
  38971. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  38972. } else {
  38973. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  38974. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  38975. }
  38976. }
  38977. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  38978. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  38979. }
  38980. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  38981. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  38982. }
  38983. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  38984. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  38985. }
  38986. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  38987. if ( shaderStage === 'fragment' ) {
  38988. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  38989. } else {
  38990. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  38991. }
  38992. }
  38993. getVars( shaderStage ) {
  38994. const snippets = [];
  38995. const vars = this.vars[ shaderStage ];
  38996. if ( vars !== undefined ) {
  38997. for ( const variable of vars ) {
  38998. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  38999. }
  39000. }
  39001. return snippets.join( '\n\t' );
  39002. }
  39003. getUniforms( shaderStage ) {
  39004. const uniforms = this.uniforms[ shaderStage ];
  39005. const bindingSnippets = [];
  39006. const uniformGroups = {};
  39007. for ( const uniform of uniforms ) {
  39008. let snippet = null;
  39009. let group = false;
  39010. if ( uniform.type === 'texture' ) {
  39011. const texture = uniform.node.value;
  39012. let typePrefix = '';
  39013. if ( texture.isDataTexture === true ) {
  39014. if ( texture.type === UnsignedIntType ) {
  39015. typePrefix = 'u';
  39016. } else if ( texture.type === IntType ) {
  39017. typePrefix = 'i';
  39018. }
  39019. }
  39020. if ( texture.compareFunction ) {
  39021. snippet = `sampler2DShadow ${ uniform.name };`;
  39022. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  39023. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  39024. } else {
  39025. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  39026. }
  39027. } else if ( uniform.type === 'cubeTexture' ) {
  39028. snippet = `samplerCube ${ uniform.name };`;
  39029. } else if ( uniform.type === 'texture3D' ) {
  39030. snippet = `sampler3D ${ uniform.name };`;
  39031. } else if ( uniform.type === 'buffer' ) {
  39032. const bufferNode = uniform.node;
  39033. const bufferType = this.getType( bufferNode.bufferType );
  39034. const bufferCount = bufferNode.bufferCount;
  39035. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  39036. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  39037. } else {
  39038. const vectorType = this.getVectorType( uniform.type );
  39039. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  39040. group = true;
  39041. }
  39042. const precision = uniform.node.precision;
  39043. if ( precision !== null ) {
  39044. snippet = precisionLib[ precision ] + ' ' + snippet;
  39045. }
  39046. if ( group ) {
  39047. snippet = '\t' + snippet;
  39048. const groupName = uniform.groupNode.name;
  39049. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  39050. groupSnippets.push( snippet );
  39051. } else {
  39052. snippet = 'uniform ' + snippet;
  39053. bindingSnippets.push( snippet );
  39054. }
  39055. }
  39056. let output = '';
  39057. for ( const name in uniformGroups ) {
  39058. const groupSnippets = uniformGroups[ name ];
  39059. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  39060. }
  39061. output += bindingSnippets.join( '\n' );
  39062. return output;
  39063. }
  39064. getTypeFromAttribute( attribute ) {
  39065. let nodeType = super.getTypeFromAttribute( attribute );
  39066. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  39067. let dataAttribute = attribute;
  39068. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  39069. const array = dataAttribute.array;
  39070. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  39071. nodeType = nodeType.slice( 1 );
  39072. }
  39073. }
  39074. return nodeType;
  39075. }
  39076. getAttributes( shaderStage ) {
  39077. let snippet = '';
  39078. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  39079. const attributes = this.getAttributesArray();
  39080. let location = 0;
  39081. for ( const attribute of attributes ) {
  39082. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  39083. }
  39084. }
  39085. return snippet;
  39086. }
  39087. getStructMembers( struct ) {
  39088. const snippets = [];
  39089. const members = struct.getMemberTypes();
  39090. for ( let i = 0; i < members.length; i ++ ) {
  39091. const member = members[ i ];
  39092. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  39093. }
  39094. return snippets.join( '\n' );
  39095. }
  39096. getStructs( shaderStage ) {
  39097. const snippets = [];
  39098. const structs = this.structs[ shaderStage ];
  39099. if ( structs.length === 0 ) {
  39100. return 'layout( location = 0 ) out vec4 fragColor;\n';
  39101. }
  39102. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  39103. const struct = structs[ index ];
  39104. let snippet = '\n';
  39105. snippet += this.getStructMembers( struct );
  39106. snippet += '\n';
  39107. snippets.push( snippet );
  39108. }
  39109. return snippets.join( '\n\n' );
  39110. }
  39111. getVaryings( shaderStage ) {
  39112. let snippet = '';
  39113. const varyings = this.varyings;
  39114. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  39115. for ( const varying of varyings ) {
  39116. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  39117. const type = varying.type;
  39118. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  39119. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  39120. }
  39121. } else if ( shaderStage === 'fragment' ) {
  39122. for ( const varying of varyings ) {
  39123. if ( varying.needsInterpolation ) {
  39124. const type = varying.type;
  39125. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  39126. snippet += `${flat}in ${type} ${varying.name};\n`;
  39127. }
  39128. }
  39129. }
  39130. return snippet;
  39131. }
  39132. getVertexIndex() {
  39133. return 'uint( gl_VertexID )';
  39134. }
  39135. getInstanceIndex() {
  39136. return 'uint( gl_InstanceID )';
  39137. }
  39138. getInvocationLocalIndex() {
  39139. const workgroupSize = this.object.workgroupSize;
  39140. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  39141. return `uint( gl_InstanceID ) % ${size}u`;
  39142. }
  39143. getDrawIndex() {
  39144. const extensions = this.renderer.backend.extensions;
  39145. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  39146. return 'uint( gl_DrawID )';
  39147. }
  39148. return null;
  39149. }
  39150. getFrontFacing() {
  39151. return 'gl_FrontFacing';
  39152. }
  39153. getFragCoord() {
  39154. return 'gl_FragCoord.xy';
  39155. }
  39156. getFragDepth() {
  39157. return 'gl_FragDepth';
  39158. }
  39159. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  39160. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  39161. if ( map.has( name ) === false ) {
  39162. map.set( name, {
  39163. name,
  39164. behavior
  39165. } );
  39166. }
  39167. }
  39168. getExtensions( shaderStage ) {
  39169. const snippets = [];
  39170. if ( shaderStage === 'vertex' ) {
  39171. const ext = this.renderer.backend.extensions;
  39172. const isBatchedMesh = this.object.isBatchedMesh;
  39173. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  39174. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  39175. }
  39176. }
  39177. const extensions = this.extensions[ shaderStage ];
  39178. if ( extensions !== undefined ) {
  39179. for ( const { name, behavior } of extensions.values() ) {
  39180. snippets.push( `#extension ${name} : ${behavior}` );
  39181. }
  39182. }
  39183. return snippets.join( '\n' );
  39184. }
  39185. isAvailable( name ) {
  39186. let result = supports$1[ name ];
  39187. if ( result === undefined ) {
  39188. if ( name === 'float32Filterable' ) {
  39189. const extensions = this.renderer.backend.extensions;
  39190. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  39191. extensions.get( 'OES_texture_float_linear' );
  39192. result = true;
  39193. } else {
  39194. result = false;
  39195. }
  39196. }
  39197. supports$1[ name ] = result;
  39198. }
  39199. return result;
  39200. }
  39201. isFlipY() {
  39202. return true;
  39203. }
  39204. registerTransform( varyingName, attributeNode ) {
  39205. this.transforms.push( { varyingName, attributeNode } );
  39206. }
  39207. getTransforms( /* shaderStage */ ) {
  39208. const transforms = this.transforms;
  39209. let snippet = '';
  39210. for ( let i = 0; i < transforms.length; i ++ ) {
  39211. const transform = transforms[ i ];
  39212. const attributeName = this.getPropertyName( transform.attributeNode );
  39213. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  39214. }
  39215. return snippet;
  39216. }
  39217. _getGLSLUniformStruct( name, vars ) {
  39218. return `
  39219. layout( std140 ) uniform ${name} {
  39220. ${vars}
  39221. };`;
  39222. }
  39223. _getGLSLVertexCode( shaderData ) {
  39224. return `#version 300 es
  39225. ${ this.getSignature() }
  39226. // extensions
  39227. ${shaderData.extensions}
  39228. // precision
  39229. ${ defaultPrecisions }
  39230. // uniforms
  39231. ${shaderData.uniforms}
  39232. // varyings
  39233. ${shaderData.varyings}
  39234. // attributes
  39235. ${shaderData.attributes}
  39236. // codes
  39237. ${shaderData.codes}
  39238. void main() {
  39239. // vars
  39240. ${shaderData.vars}
  39241. // transforms
  39242. ${shaderData.transforms}
  39243. // flow
  39244. ${shaderData.flow}
  39245. gl_PointSize = 1.0;
  39246. }
  39247. `;
  39248. }
  39249. _getGLSLFragmentCode( shaderData ) {
  39250. return `#version 300 es
  39251. ${ this.getSignature() }
  39252. // precision
  39253. ${ defaultPrecisions }
  39254. // uniforms
  39255. ${shaderData.uniforms}
  39256. // varyings
  39257. ${shaderData.varyings}
  39258. // codes
  39259. ${shaderData.codes}
  39260. ${shaderData.structs}
  39261. void main() {
  39262. // vars
  39263. ${shaderData.vars}
  39264. // flow
  39265. ${shaderData.flow}
  39266. }
  39267. `;
  39268. }
  39269. buildCode() {
  39270. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  39271. this.sortBindingGroups();
  39272. for ( const shaderStage in shadersData ) {
  39273. let flow = '// code\n\n';
  39274. flow += this.flowCode[ shaderStage ];
  39275. const flowNodes = this.flowNodes[ shaderStage ];
  39276. const mainNode = flowNodes[ flowNodes.length - 1 ];
  39277. for ( const node of flowNodes ) {
  39278. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  39279. const slotName = node.name;
  39280. if ( slotName ) {
  39281. if ( flow.length > 0 ) flow += '\n';
  39282. flow += `\t// flow -> ${ slotName }\n\t`;
  39283. }
  39284. flow += `${ flowSlotData.code }\n\t`;
  39285. if ( node === mainNode && shaderStage !== 'compute' ) {
  39286. flow += '// result\n\t';
  39287. if ( shaderStage === 'vertex' ) {
  39288. flow += 'gl_Position = ';
  39289. flow += `${ flowSlotData.result };`;
  39290. } else if ( shaderStage === 'fragment' ) {
  39291. if ( ! node.outputNode.isOutputStructNode ) {
  39292. flow += 'fragColor = ';
  39293. flow += `${ flowSlotData.result };`;
  39294. }
  39295. }
  39296. }
  39297. }
  39298. const stageData = shadersData[ shaderStage ];
  39299. stageData.extensions = this.getExtensions( shaderStage );
  39300. stageData.uniforms = this.getUniforms( shaderStage );
  39301. stageData.attributes = this.getAttributes( shaderStage );
  39302. stageData.varyings = this.getVaryings( shaderStage );
  39303. stageData.vars = this.getVars( shaderStage );
  39304. stageData.structs = this.getStructs( shaderStage );
  39305. stageData.codes = this.getCodes( shaderStage );
  39306. stageData.transforms = this.getTransforms( shaderStage );
  39307. stageData.flow = flow;
  39308. }
  39309. if ( this.material !== null ) {
  39310. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  39311. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  39312. } else {
  39313. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  39314. }
  39315. }
  39316. getUniformFromNode( node, type, shaderStage, name = null ) {
  39317. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  39318. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  39319. let uniformGPU = nodeData.uniformGPU;
  39320. if ( uniformGPU === undefined ) {
  39321. const group = node.groupNode;
  39322. const groupName = group.name;
  39323. const bindings = this.getBindGroupArray( groupName, shaderStage );
  39324. if ( type === 'texture' ) {
  39325. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  39326. bindings.push( uniformGPU );
  39327. } else if ( type === 'cubeTexture' ) {
  39328. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  39329. bindings.push( uniformGPU );
  39330. } else if ( type === 'texture3D' ) {
  39331. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  39332. bindings.push( uniformGPU );
  39333. } else if ( type === 'buffer' ) {
  39334. node.name = `NodeBuffer_${ node.id }`;
  39335. uniformNode.name = `buffer${ node.id }`;
  39336. const buffer = new NodeUniformBuffer( node, group );
  39337. buffer.name = node.name;
  39338. bindings.push( buffer );
  39339. uniformGPU = buffer;
  39340. } else {
  39341. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  39342. let uniformsGroup = uniformsStage[ groupName ];
  39343. if ( uniformsGroup === undefined ) {
  39344. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  39345. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  39346. uniformsStage[ groupName ] = uniformsGroup;
  39347. bindings.push( uniformsGroup );
  39348. }
  39349. uniformGPU = this.getNodeUniform( uniformNode, type );
  39350. uniformsGroup.addUniform( uniformGPU );
  39351. }
  39352. nodeData.uniformGPU = uniformGPU;
  39353. }
  39354. return uniformNode;
  39355. }
  39356. }
  39357. let vector2 = null;
  39358. let vector4 = null;
  39359. let color4 = null;
  39360. class Backend {
  39361. constructor( parameters = {} ) {
  39362. this.parameters = Object.assign( {}, parameters );
  39363. this.data = new WeakMap();
  39364. this.renderer = null;
  39365. this.domElement = null;
  39366. }
  39367. async init( renderer ) {
  39368. this.renderer = renderer;
  39369. }
  39370. // render context
  39371. begin( /*renderContext*/ ) { }
  39372. finish( /*renderContext*/ ) { }
  39373. // render object
  39374. draw( /*renderObject, info*/ ) { }
  39375. // program
  39376. createProgram( /*program*/ ) { }
  39377. destroyProgram( /*program*/ ) { }
  39378. // bindings
  39379. createBindings( /*bingGroup, bindings*/ ) { }
  39380. updateBindings( /*bingGroup, bindings*/ ) { }
  39381. // pipeline
  39382. createRenderPipeline( /*renderObject*/ ) { }
  39383. createComputePipeline( /*computeNode, pipeline*/ ) { }
  39384. destroyPipeline( /*pipeline*/ ) { }
  39385. // cache key
  39386. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  39387. getRenderCacheKey( /*renderObject*/ ) { } // return String
  39388. // node builder
  39389. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  39390. // textures
  39391. createSampler( /*texture*/ ) { }
  39392. createDefaultTexture( /*texture*/ ) { }
  39393. createTexture( /*texture*/ ) { }
  39394. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  39395. // attributes
  39396. createAttribute( /*attribute*/ ) { }
  39397. createIndexAttribute( /*attribute*/ ) { }
  39398. updateAttribute( /*attribute*/ ) { }
  39399. destroyAttribute( /*attribute*/ ) { }
  39400. // canvas
  39401. getContext() { }
  39402. updateSize() { }
  39403. // utils
  39404. resolveTimestampAsync( /*renderContext, type*/ ) { }
  39405. hasFeatureAsync( /*name*/ ) { } // return Boolean
  39406. hasFeature( /*name*/ ) { } // return Boolean
  39407. getInstanceCount( renderObject ) {
  39408. const { object, geometry } = renderObject;
  39409. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  39410. }
  39411. getDrawingBufferSize() {
  39412. vector2 = vector2 || new Vector2();
  39413. return this.renderer.getDrawingBufferSize( vector2 );
  39414. }
  39415. getScissor() {
  39416. vector4 = vector4 || new Vector4();
  39417. return this.renderer.getScissor( vector4 );
  39418. }
  39419. setScissorTest( /*boolean*/ ) { }
  39420. getClearColor() {
  39421. const renderer = this.renderer;
  39422. color4 = color4 || new Color4();
  39423. renderer.getClearColor( color4 );
  39424. color4.getRGB( color4, this.renderer.currentColorSpace );
  39425. return color4;
  39426. }
  39427. getDomElement() {
  39428. let domElement = this.domElement;
  39429. if ( domElement === null ) {
  39430. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  39431. // OffscreenCanvas does not have setAttribute, see #22811
  39432. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  39433. this.domElement = domElement;
  39434. }
  39435. return domElement;
  39436. }
  39437. // resource properties
  39438. set( object, value ) {
  39439. this.data.set( object, value );
  39440. }
  39441. get( object ) {
  39442. let map = this.data.get( object );
  39443. if ( map === undefined ) {
  39444. map = {};
  39445. this.data.set( object, map );
  39446. }
  39447. return map;
  39448. }
  39449. has( object ) {
  39450. return this.data.has( object );
  39451. }
  39452. delete( object ) {
  39453. this.data.delete( object );
  39454. }
  39455. dispose() { }
  39456. }
  39457. let _id$1 = 0;
  39458. class DualAttributeData {
  39459. constructor( attributeData, dualBuffer ) {
  39460. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  39461. this.type = attributeData.type;
  39462. this.bufferType = attributeData.bufferType;
  39463. this.pbo = attributeData.pbo;
  39464. this.byteLength = attributeData.byteLength;
  39465. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  39466. this.version = attributeData.version;
  39467. this.isInteger = attributeData.isInteger;
  39468. this.activeBufferIndex = 0;
  39469. this.baseId = attributeData.id;
  39470. }
  39471. get id() {
  39472. return `${ this.baseId }|${ this.activeBufferIndex }`;
  39473. }
  39474. get bufferGPU() {
  39475. return this.buffers[ this.activeBufferIndex ];
  39476. }
  39477. get transformBuffer() {
  39478. return this.buffers[ this.activeBufferIndex ^ 1 ];
  39479. }
  39480. switchBuffers() {
  39481. this.activeBufferIndex ^= 1;
  39482. }
  39483. }
  39484. class WebGLAttributeUtils {
  39485. constructor( backend ) {
  39486. this.backend = backend;
  39487. }
  39488. createAttribute( attribute, bufferType ) {
  39489. const backend = this.backend;
  39490. const { gl } = backend;
  39491. const array = attribute.array;
  39492. const usage = attribute.usage || gl.STATIC_DRAW;
  39493. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39494. const bufferData = backend.get( bufferAttribute );
  39495. let bufferGPU = bufferData.bufferGPU;
  39496. if ( bufferGPU === undefined ) {
  39497. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  39498. bufferData.bufferGPU = bufferGPU;
  39499. bufferData.bufferType = bufferType;
  39500. bufferData.version = bufferAttribute.version;
  39501. }
  39502. //attribute.onUploadCallback();
  39503. let type;
  39504. if ( array instanceof Float32Array ) {
  39505. type = gl.FLOAT;
  39506. } else if ( array instanceof Uint16Array ) {
  39507. if ( attribute.isFloat16BufferAttribute ) {
  39508. type = gl.HALF_FLOAT;
  39509. } else {
  39510. type = gl.UNSIGNED_SHORT;
  39511. }
  39512. } else if ( array instanceof Int16Array ) {
  39513. type = gl.SHORT;
  39514. } else if ( array instanceof Uint32Array ) {
  39515. type = gl.UNSIGNED_INT;
  39516. } else if ( array instanceof Int32Array ) {
  39517. type = gl.INT;
  39518. } else if ( array instanceof Int8Array ) {
  39519. type = gl.BYTE;
  39520. } else if ( array instanceof Uint8Array ) {
  39521. type = gl.UNSIGNED_BYTE;
  39522. } else if ( array instanceof Uint8ClampedArray ) {
  39523. type = gl.UNSIGNED_BYTE;
  39524. } else {
  39525. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  39526. }
  39527. let attributeData = {
  39528. bufferGPU,
  39529. bufferType,
  39530. type,
  39531. byteLength: array.byteLength,
  39532. bytesPerElement: array.BYTES_PER_ELEMENT,
  39533. version: attribute.version,
  39534. pbo: attribute.pbo,
  39535. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  39536. id: _id$1 ++
  39537. };
  39538. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  39539. // create buffer for tranform feedback use
  39540. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  39541. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  39542. }
  39543. backend.set( attribute, attributeData );
  39544. }
  39545. updateAttribute( attribute ) {
  39546. const backend = this.backend;
  39547. const { gl } = backend;
  39548. const array = attribute.array;
  39549. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39550. const bufferData = backend.get( bufferAttribute );
  39551. const bufferType = bufferData.bufferType;
  39552. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  39553. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  39554. if ( updateRanges.length === 0 ) {
  39555. // Not using update ranges
  39556. gl.bufferSubData( bufferType, 0, array );
  39557. } else {
  39558. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  39559. const range = updateRanges[ i ];
  39560. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  39561. array, range.start, range.count );
  39562. }
  39563. bufferAttribute.clearUpdateRanges();
  39564. }
  39565. gl.bindBuffer( bufferType, null );
  39566. bufferData.version = bufferAttribute.version;
  39567. }
  39568. destroyAttribute( attribute ) {
  39569. const backend = this.backend;
  39570. const { gl } = backend;
  39571. if ( attribute.isInterleavedBufferAttribute ) {
  39572. backend.delete( attribute.data );
  39573. }
  39574. const attributeData = backend.get( attribute );
  39575. gl.deleteBuffer( attributeData.bufferGPU );
  39576. backend.delete( attribute );
  39577. }
  39578. async getArrayBufferAsync( attribute ) {
  39579. const backend = this.backend;
  39580. const { gl } = backend;
  39581. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39582. const { bufferGPU } = backend.get( bufferAttribute );
  39583. const array = attribute.array;
  39584. const byteLength = array.byteLength;
  39585. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  39586. const writeBuffer = gl.createBuffer();
  39587. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39588. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  39589. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  39590. await backend.utils._clientWaitAsync();
  39591. const dstBuffer = new attribute.array.constructor( array.length );
  39592. // Ensure the buffer is bound before reading
  39593. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39594. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  39595. gl.deleteBuffer( writeBuffer );
  39596. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  39597. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  39598. return dstBuffer.buffer;
  39599. }
  39600. _createBuffer( gl, bufferType, array, usage ) {
  39601. const bufferGPU = gl.createBuffer();
  39602. gl.bindBuffer( bufferType, bufferGPU );
  39603. gl.bufferData( bufferType, array, usage );
  39604. gl.bindBuffer( bufferType, null );
  39605. return bufferGPU;
  39606. }
  39607. }
  39608. let initialized$1 = false, equationToGL, factorToGL;
  39609. class WebGLState {
  39610. constructor( backend ) {
  39611. this.backend = backend;
  39612. this.gl = this.backend.gl;
  39613. this.enabled = {};
  39614. this.currentFlipSided = null;
  39615. this.currentCullFace = null;
  39616. this.currentProgram = null;
  39617. this.currentBlendingEnabled = false;
  39618. this.currentBlending = null;
  39619. this.currentBlendSrc = null;
  39620. this.currentBlendDst = null;
  39621. this.currentBlendSrcAlpha = null;
  39622. this.currentBlendDstAlpha = null;
  39623. this.currentPremultipledAlpha = null;
  39624. this.currentPolygonOffsetFactor = null;
  39625. this.currentPolygonOffsetUnits = null;
  39626. this.currentColorMask = null;
  39627. this.currentDepthFunc = null;
  39628. this.currentDepthMask = null;
  39629. this.currentStencilFunc = null;
  39630. this.currentStencilRef = null;
  39631. this.currentStencilFuncMask = null;
  39632. this.currentStencilFail = null;
  39633. this.currentStencilZFail = null;
  39634. this.currentStencilZPass = null;
  39635. this.currentStencilMask = null;
  39636. this.currentLineWidth = null;
  39637. this.currentBoundFramebuffers = {};
  39638. this.currentDrawbuffers = new WeakMap();
  39639. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  39640. this.currentTextureSlot = null;
  39641. this.currentBoundTextures = {};
  39642. this.currentBoundBufferBases = {};
  39643. if ( initialized$1 === false ) {
  39644. this._init( this.gl );
  39645. initialized$1 = true;
  39646. }
  39647. }
  39648. _init( gl ) {
  39649. // Store only WebGL constants here.
  39650. equationToGL = {
  39651. [ AddEquation ]: gl.FUNC_ADD,
  39652. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  39653. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  39654. };
  39655. factorToGL = {
  39656. [ ZeroFactor ]: gl.ZERO,
  39657. [ OneFactor ]: gl.ONE,
  39658. [ SrcColorFactor ]: gl.SRC_COLOR,
  39659. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  39660. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  39661. [ DstColorFactor ]: gl.DST_COLOR,
  39662. [ DstAlphaFactor ]: gl.DST_ALPHA,
  39663. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  39664. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  39665. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  39666. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  39667. };
  39668. }
  39669. enable( id ) {
  39670. const { enabled } = this;
  39671. if ( enabled[ id ] !== true ) {
  39672. this.gl.enable( id );
  39673. enabled[ id ] = true;
  39674. }
  39675. }
  39676. disable( id ) {
  39677. const { enabled } = this;
  39678. if ( enabled[ id ] !== false ) {
  39679. this.gl.disable( id );
  39680. enabled[ id ] = false;
  39681. }
  39682. }
  39683. setFlipSided( flipSided ) {
  39684. if ( this.currentFlipSided !== flipSided ) {
  39685. const { gl } = this;
  39686. if ( flipSided ) {
  39687. gl.frontFace( gl.CW );
  39688. } else {
  39689. gl.frontFace( gl.CCW );
  39690. }
  39691. this.currentFlipSided = flipSided;
  39692. }
  39693. }
  39694. setCullFace( cullFace ) {
  39695. const { gl } = this;
  39696. if ( cullFace !== CullFaceNone ) {
  39697. this.enable( gl.CULL_FACE );
  39698. if ( cullFace !== this.currentCullFace ) {
  39699. if ( cullFace === CullFaceBack ) {
  39700. gl.cullFace( gl.BACK );
  39701. } else if ( cullFace === CullFaceFront ) {
  39702. gl.cullFace( gl.FRONT );
  39703. } else {
  39704. gl.cullFace( gl.FRONT_AND_BACK );
  39705. }
  39706. }
  39707. } else {
  39708. this.disable( gl.CULL_FACE );
  39709. }
  39710. this.currentCullFace = cullFace;
  39711. }
  39712. setLineWidth( width ) {
  39713. const { currentLineWidth, gl } = this;
  39714. if ( width !== currentLineWidth ) {
  39715. gl.lineWidth( width );
  39716. this.currentLineWidth = width;
  39717. }
  39718. }
  39719. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  39720. const { gl } = this;
  39721. if ( blending === NoBlending ) {
  39722. if ( this.currentBlendingEnabled === true ) {
  39723. this.disable( gl.BLEND );
  39724. this.currentBlendingEnabled = false;
  39725. }
  39726. return;
  39727. }
  39728. if ( this.currentBlendingEnabled === false ) {
  39729. this.enable( gl.BLEND );
  39730. this.currentBlendingEnabled = true;
  39731. }
  39732. if ( blending !== CustomBlending ) {
  39733. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  39734. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  39735. gl.blendEquation( gl.FUNC_ADD );
  39736. this.currentBlendEquation = AddEquation;
  39737. this.currentBlendEquationAlpha = AddEquation;
  39738. }
  39739. if ( premultipliedAlpha ) {
  39740. switch ( blending ) {
  39741. case NormalBlending:
  39742. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39743. break;
  39744. case AdditiveBlending:
  39745. gl.blendFunc( gl.ONE, gl.ONE );
  39746. break;
  39747. case SubtractiveBlending:
  39748. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39749. break;
  39750. case MultiplyBlending:
  39751. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  39752. break;
  39753. default:
  39754. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39755. break;
  39756. }
  39757. } else {
  39758. switch ( blending ) {
  39759. case NormalBlending:
  39760. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39761. break;
  39762. case AdditiveBlending:
  39763. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  39764. break;
  39765. case SubtractiveBlending:
  39766. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39767. break;
  39768. case MultiplyBlending:
  39769. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  39770. break;
  39771. default:
  39772. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39773. break;
  39774. }
  39775. }
  39776. this.currentBlendSrc = null;
  39777. this.currentBlendDst = null;
  39778. this.currentBlendSrcAlpha = null;
  39779. this.currentBlendDstAlpha = null;
  39780. this.currentBlending = blending;
  39781. this.currentPremultipledAlpha = premultipliedAlpha;
  39782. }
  39783. return;
  39784. }
  39785. // custom blending
  39786. blendEquationAlpha = blendEquationAlpha || blendEquation;
  39787. blendSrcAlpha = blendSrcAlpha || blendSrc;
  39788. blendDstAlpha = blendDstAlpha || blendDst;
  39789. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  39790. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  39791. this.currentBlendEquation = blendEquation;
  39792. this.currentBlendEquationAlpha = blendEquationAlpha;
  39793. }
  39794. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  39795. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  39796. this.currentBlendSrc = blendSrc;
  39797. this.currentBlendDst = blendDst;
  39798. this.currentBlendSrcAlpha = blendSrcAlpha;
  39799. this.currentBlendDstAlpha = blendDstAlpha;
  39800. }
  39801. this.currentBlending = blending;
  39802. this.currentPremultipledAlpha = false;
  39803. }
  39804. setColorMask( colorMask ) {
  39805. if ( this.currentColorMask !== colorMask ) {
  39806. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  39807. this.currentColorMask = colorMask;
  39808. }
  39809. }
  39810. setDepthTest( depthTest ) {
  39811. const { gl } = this;
  39812. if ( depthTest ) {
  39813. this.enable( gl.DEPTH_TEST );
  39814. } else {
  39815. this.disable( gl.DEPTH_TEST );
  39816. }
  39817. }
  39818. setDepthMask( depthMask ) {
  39819. if ( this.currentDepthMask !== depthMask ) {
  39820. this.gl.depthMask( depthMask );
  39821. this.currentDepthMask = depthMask;
  39822. }
  39823. }
  39824. setDepthFunc( depthFunc ) {
  39825. if ( this.currentDepthFunc !== depthFunc ) {
  39826. const { gl } = this;
  39827. switch ( depthFunc ) {
  39828. case NeverDepth:
  39829. gl.depthFunc( gl.NEVER );
  39830. break;
  39831. case AlwaysDepth:
  39832. gl.depthFunc( gl.ALWAYS );
  39833. break;
  39834. case LessDepth:
  39835. gl.depthFunc( gl.LESS );
  39836. break;
  39837. case LessEqualDepth:
  39838. gl.depthFunc( gl.LEQUAL );
  39839. break;
  39840. case EqualDepth:
  39841. gl.depthFunc( gl.EQUAL );
  39842. break;
  39843. case GreaterEqualDepth:
  39844. gl.depthFunc( gl.GEQUAL );
  39845. break;
  39846. case GreaterDepth:
  39847. gl.depthFunc( gl.GREATER );
  39848. break;
  39849. case NotEqualDepth:
  39850. gl.depthFunc( gl.NOTEQUAL );
  39851. break;
  39852. default:
  39853. gl.depthFunc( gl.LEQUAL );
  39854. }
  39855. this.currentDepthFunc = depthFunc;
  39856. }
  39857. }
  39858. setStencilTest( stencilTest ) {
  39859. const { gl } = this;
  39860. if ( stencilTest ) {
  39861. this.enable( gl.STENCIL_TEST );
  39862. } else {
  39863. this.disable( gl.STENCIL_TEST );
  39864. }
  39865. }
  39866. setStencilMask( stencilMask ) {
  39867. if ( this.currentStencilMask !== stencilMask ) {
  39868. this.gl.stencilMask( stencilMask );
  39869. this.currentStencilMask = stencilMask;
  39870. }
  39871. }
  39872. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  39873. if ( this.currentStencilFunc !== stencilFunc ||
  39874. this.currentStencilRef !== stencilRef ||
  39875. this.currentStencilFuncMask !== stencilMask ) {
  39876. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  39877. this.currentStencilFunc = stencilFunc;
  39878. this.currentStencilRef = stencilRef;
  39879. this.currentStencilFuncMask = stencilMask;
  39880. }
  39881. }
  39882. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  39883. if ( this.currentStencilFail !== stencilFail ||
  39884. this.currentStencilZFail !== stencilZFail ||
  39885. this.currentStencilZPass !== stencilZPass ) {
  39886. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  39887. this.currentStencilFail = stencilFail;
  39888. this.currentStencilZFail = stencilZFail;
  39889. this.currentStencilZPass = stencilZPass;
  39890. }
  39891. }
  39892. setMaterial( material, frontFaceCW ) {
  39893. const { gl } = this;
  39894. material.side === DoubleSide
  39895. ? this.disable( gl.CULL_FACE )
  39896. : this.enable( gl.CULL_FACE );
  39897. let flipSided = ( material.side === BackSide );
  39898. if ( frontFaceCW ) flipSided = ! flipSided;
  39899. this.setFlipSided( flipSided );
  39900. ( material.blending === NormalBlending && material.transparent === false )
  39901. ? this.setBlending( NoBlending )
  39902. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  39903. this.setDepthFunc( material.depthFunc );
  39904. this.setDepthTest( material.depthTest );
  39905. this.setDepthMask( material.depthWrite );
  39906. this.setColorMask( material.colorWrite );
  39907. const stencilWrite = material.stencilWrite;
  39908. this.setStencilTest( stencilWrite );
  39909. if ( stencilWrite ) {
  39910. this.setStencilMask( material.stencilWriteMask );
  39911. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  39912. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  39913. }
  39914. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  39915. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  39916. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  39917. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39918. }
  39919. setPolygonOffset( polygonOffset, factor, units ) {
  39920. const { gl } = this;
  39921. if ( polygonOffset ) {
  39922. this.enable( gl.POLYGON_OFFSET_FILL );
  39923. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  39924. gl.polygonOffset( factor, units );
  39925. this.currentPolygonOffsetFactor = factor;
  39926. this.currentPolygonOffsetUnits = units;
  39927. }
  39928. } else {
  39929. this.disable( gl.POLYGON_OFFSET_FILL );
  39930. }
  39931. }
  39932. useProgram( program ) {
  39933. if ( this.currentProgram !== program ) {
  39934. this.gl.useProgram( program );
  39935. this.currentProgram = program;
  39936. return true;
  39937. }
  39938. return false;
  39939. }
  39940. // framebuffer
  39941. bindFramebuffer( target, framebuffer ) {
  39942. const { gl, currentBoundFramebuffers } = this;
  39943. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  39944. gl.bindFramebuffer( target, framebuffer );
  39945. currentBoundFramebuffers[ target ] = framebuffer;
  39946. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  39947. if ( target === gl.DRAW_FRAMEBUFFER ) {
  39948. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  39949. }
  39950. if ( target === gl.FRAMEBUFFER ) {
  39951. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  39952. }
  39953. return true;
  39954. }
  39955. return false;
  39956. }
  39957. drawBuffers( renderContext, framebuffer ) {
  39958. const { gl } = this;
  39959. let drawBuffers = [];
  39960. let needsUpdate = false;
  39961. if ( renderContext.textures !== null ) {
  39962. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  39963. if ( drawBuffers === undefined ) {
  39964. drawBuffers = [];
  39965. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  39966. }
  39967. const textures = renderContext.textures;
  39968. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  39969. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39970. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  39971. }
  39972. drawBuffers.length = textures.length;
  39973. needsUpdate = true;
  39974. }
  39975. } else {
  39976. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  39977. drawBuffers[ 0 ] = gl.BACK;
  39978. needsUpdate = true;
  39979. }
  39980. }
  39981. if ( needsUpdate ) {
  39982. gl.drawBuffers( drawBuffers );
  39983. }
  39984. }
  39985. // texture
  39986. activeTexture( webglSlot ) {
  39987. const { gl, currentTextureSlot, maxTextures } = this;
  39988. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39989. if ( currentTextureSlot !== webglSlot ) {
  39990. gl.activeTexture( webglSlot );
  39991. this.currentTextureSlot = webglSlot;
  39992. }
  39993. }
  39994. bindTexture( webglType, webglTexture, webglSlot ) {
  39995. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  39996. if ( webglSlot === undefined ) {
  39997. if ( currentTextureSlot === null ) {
  39998. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39999. } else {
  40000. webglSlot = currentTextureSlot;
  40001. }
  40002. }
  40003. let boundTexture = currentBoundTextures[ webglSlot ];
  40004. if ( boundTexture === undefined ) {
  40005. boundTexture = { type: undefined, texture: undefined };
  40006. currentBoundTextures[ webglSlot ] = boundTexture;
  40007. }
  40008. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  40009. if ( currentTextureSlot !== webglSlot ) {
  40010. gl.activeTexture( webglSlot );
  40011. this.currentTextureSlot = webglSlot;
  40012. }
  40013. gl.bindTexture( webglType, webglTexture );
  40014. boundTexture.type = webglType;
  40015. boundTexture.texture = webglTexture;
  40016. }
  40017. }
  40018. bindBufferBase( target, index, buffer ) {
  40019. const { gl } = this;
  40020. const key = `${target}-${index}`;
  40021. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  40022. gl.bindBufferBase( target, index, buffer );
  40023. this.currentBoundBufferBases[ key ] = buffer;
  40024. return true;
  40025. }
  40026. return false;
  40027. }
  40028. unbindTexture() {
  40029. const { gl, currentTextureSlot, currentBoundTextures } = this;
  40030. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  40031. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  40032. gl.bindTexture( boundTexture.type, null );
  40033. boundTexture.type = undefined;
  40034. boundTexture.texture = undefined;
  40035. }
  40036. }
  40037. }
  40038. class WebGLUtils {
  40039. constructor( backend ) {
  40040. this.backend = backend;
  40041. this.gl = this.backend.gl;
  40042. this.extensions = backend.extensions;
  40043. }
  40044. convert( p, colorSpace = NoColorSpace ) {
  40045. const { gl, extensions } = this;
  40046. let extension;
  40047. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  40048. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  40049. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  40050. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  40051. if ( p === ByteType ) return gl.BYTE;
  40052. if ( p === ShortType ) return gl.SHORT;
  40053. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  40054. if ( p === IntType ) return gl.INT;
  40055. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  40056. if ( p === FloatType ) return gl.FLOAT;
  40057. if ( p === HalfFloatType ) {
  40058. return gl.HALF_FLOAT;
  40059. }
  40060. if ( p === AlphaFormat ) return gl.ALPHA;
  40061. if ( p === RGBFormat ) return gl.RGB;
  40062. if ( p === RGBAFormat ) return gl.RGBA;
  40063. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  40064. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  40065. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  40066. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  40067. // WebGL2 formats.
  40068. if ( p === RedFormat ) return gl.RED;
  40069. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  40070. if ( p === RGFormat ) return gl.RG;
  40071. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  40072. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  40073. // S3TC
  40074. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  40075. if ( colorSpace === SRGBColorSpace ) {
  40076. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  40077. if ( extension !== null ) {
  40078. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  40079. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  40080. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  40081. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  40082. } else {
  40083. return null;
  40084. }
  40085. } else {
  40086. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  40087. if ( extension !== null ) {
  40088. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  40089. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40090. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40091. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40092. } else {
  40093. return null;
  40094. }
  40095. }
  40096. }
  40097. // PVRTC
  40098. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  40099. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  40100. if ( extension !== null ) {
  40101. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  40102. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  40103. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  40104. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  40105. } else {
  40106. return null;
  40107. }
  40108. }
  40109. // ETC
  40110. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  40111. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  40112. if ( extension !== null ) {
  40113. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  40114. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  40115. } else {
  40116. return null;
  40117. }
  40118. }
  40119. // ASTC
  40120. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  40121. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  40122. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  40123. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  40124. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  40125. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  40126. if ( extension !== null ) {
  40127. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  40128. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  40129. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  40130. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  40131. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  40132. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  40133. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  40134. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  40135. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  40136. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  40137. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  40138. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  40139. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  40140. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  40141. } else {
  40142. return null;
  40143. }
  40144. }
  40145. // BPTC
  40146. if ( p === RGBA_BPTC_Format ) {
  40147. extension = extensions.get( 'EXT_texture_compression_bptc' );
  40148. if ( extension !== null ) {
  40149. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  40150. } else {
  40151. return null;
  40152. }
  40153. }
  40154. // RGTC
  40155. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  40156. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  40157. if ( extension !== null ) {
  40158. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  40159. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  40160. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  40161. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  40162. } else {
  40163. return null;
  40164. }
  40165. }
  40166. //
  40167. if ( p === UnsignedInt248Type ) {
  40168. return gl.UNSIGNED_INT_24_8;
  40169. }
  40170. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  40171. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  40172. }
  40173. _clientWaitAsync() {
  40174. const { gl } = this;
  40175. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  40176. gl.flush();
  40177. return new Promise( ( resolve, reject ) => {
  40178. function test() {
  40179. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  40180. if ( res === gl.WAIT_FAILED ) {
  40181. gl.deleteSync( sync );
  40182. reject();
  40183. return;
  40184. }
  40185. if ( res === gl.TIMEOUT_EXPIRED ) {
  40186. requestAnimationFrame( test );
  40187. return;
  40188. }
  40189. gl.deleteSync( sync );
  40190. resolve();
  40191. }
  40192. test();
  40193. } );
  40194. }
  40195. }
  40196. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  40197. class WebGLTextureUtils {
  40198. constructor( backend ) {
  40199. this.backend = backend;
  40200. this.gl = backend.gl;
  40201. this.extensions = backend.extensions;
  40202. this.defaultTextures = {};
  40203. if ( initialized === false ) {
  40204. this._init( this.gl );
  40205. initialized = true;
  40206. }
  40207. }
  40208. _init( gl ) {
  40209. // Store only WebGL constants here.
  40210. wrappingToGL = {
  40211. [ RepeatWrapping ]: gl.REPEAT,
  40212. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  40213. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  40214. };
  40215. filterToGL = {
  40216. [ NearestFilter ]: gl.NEAREST,
  40217. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  40218. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  40219. [ LinearFilter ]: gl.LINEAR,
  40220. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  40221. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  40222. };
  40223. compareToGL = {
  40224. [ NeverCompare ]: gl.NEVER,
  40225. [ AlwaysCompare ]: gl.ALWAYS,
  40226. [ LessCompare ]: gl.LESS,
  40227. [ LessEqualCompare ]: gl.LEQUAL,
  40228. [ EqualCompare ]: gl.EQUAL,
  40229. [ GreaterEqualCompare ]: gl.GEQUAL,
  40230. [ GreaterCompare ]: gl.GREATER,
  40231. [ NotEqualCompare ]: gl.NOTEQUAL
  40232. };
  40233. }
  40234. filterFallback( f ) {
  40235. const { gl } = this;
  40236. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  40237. return gl.NEAREST;
  40238. }
  40239. return gl.LINEAR;
  40240. }
  40241. getGLTextureType( texture ) {
  40242. const { gl } = this;
  40243. let glTextureType;
  40244. if ( texture.isCubeTexture === true ) {
  40245. glTextureType = gl.TEXTURE_CUBE_MAP;
  40246. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  40247. glTextureType = gl.TEXTURE_2D_ARRAY;
  40248. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  40249. glTextureType = gl.TEXTURE_3D;
  40250. } else {
  40251. glTextureType = gl.TEXTURE_2D;
  40252. }
  40253. return glTextureType;
  40254. }
  40255. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  40256. const { gl, extensions } = this;
  40257. if ( internalFormatName !== null ) {
  40258. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  40259. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  40260. }
  40261. let internalFormat = glFormat;
  40262. if ( glFormat === gl.RED ) {
  40263. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  40264. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  40265. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  40266. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  40267. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40268. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40269. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40270. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40271. }
  40272. if ( glFormat === gl.RED_INTEGER ) {
  40273. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  40274. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  40275. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40276. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40277. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40278. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40279. }
  40280. if ( glFormat === gl.RG ) {
  40281. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  40282. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  40283. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  40284. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  40285. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40286. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40287. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40288. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40289. }
  40290. if ( glFormat === gl.RG_INTEGER ) {
  40291. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  40292. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  40293. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40294. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40295. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40296. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40297. }
  40298. if ( glFormat === gl.RGB ) {
  40299. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  40300. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  40301. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  40302. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  40303. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40304. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40305. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40306. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40307. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  40308. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  40309. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40310. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  40311. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  40312. }
  40313. if ( glFormat === gl.RGB_INTEGER ) {
  40314. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  40315. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  40316. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40317. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40318. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40319. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40320. }
  40321. if ( glFormat === gl.RGBA ) {
  40322. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  40323. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  40324. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  40325. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  40326. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40327. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40328. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40329. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40330. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  40331. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  40332. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40333. }
  40334. if ( glFormat === gl.RGBA_INTEGER ) {
  40335. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  40336. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  40337. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40338. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40339. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40340. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40341. }
  40342. if ( glFormat === gl.DEPTH_COMPONENT ) {
  40343. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  40344. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  40345. }
  40346. if ( glFormat === gl.DEPTH_STENCIL ) {
  40347. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  40348. }
  40349. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  40350. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  40351. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  40352. extensions.get( 'EXT_color_buffer_float' );
  40353. }
  40354. return internalFormat;
  40355. }
  40356. setTextureParameters( textureType, texture ) {
  40357. const { gl, extensions, backend } = this;
  40358. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  40359. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  40360. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  40361. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  40362. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  40363. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  40364. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  40365. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  40366. }
  40367. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  40368. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  40369. // follow WebGPU backend mapping for texture filtering
  40370. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  40371. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  40372. if ( texture.compareFunction ) {
  40373. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  40374. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  40375. }
  40376. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40377. if ( texture.magFilter === NearestFilter ) return;
  40378. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  40379. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  40380. if ( texture.anisotropy > 1 ) {
  40381. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40382. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  40383. }
  40384. }
  40385. }
  40386. createDefaultTexture( texture ) {
  40387. const { gl, backend, defaultTextures } = this;
  40388. const glTextureType = this.getGLTextureType( texture );
  40389. let textureGPU = defaultTextures[ glTextureType ];
  40390. if ( textureGPU === undefined ) {
  40391. textureGPU = gl.createTexture();
  40392. backend.state.bindTexture( glTextureType, textureGPU );
  40393. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  40394. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  40395. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  40396. defaultTextures[ glTextureType ] = textureGPU;
  40397. }
  40398. backend.set( texture, {
  40399. textureGPU,
  40400. glTextureType,
  40401. isDefault: true
  40402. } );
  40403. }
  40404. createTexture( texture, options ) {
  40405. const { gl, backend } = this;
  40406. const { levels, width, height, depth } = options;
  40407. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  40408. const glType = backend.utils.convert( texture.type );
  40409. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  40410. const textureGPU = gl.createTexture();
  40411. const glTextureType = this.getGLTextureType( texture );
  40412. backend.state.bindTexture( glTextureType, textureGPU );
  40413. this.setTextureParameters( glTextureType, texture );
  40414. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  40415. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  40416. } else if ( texture.isData3DTexture ) {
  40417. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  40418. } else if ( ! texture.isVideoTexture ) {
  40419. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  40420. }
  40421. backend.set( texture, {
  40422. textureGPU,
  40423. glTextureType,
  40424. glFormat,
  40425. glType,
  40426. glInternalFormat
  40427. } );
  40428. }
  40429. copyBufferToTexture( buffer, texture ) {
  40430. const { gl, backend } = this;
  40431. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  40432. const { width, height } = texture.source.data;
  40433. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  40434. backend.state.bindTexture( glTextureType, textureGPU );
  40435. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  40436. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  40437. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  40438. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  40439. backend.state.unbindTexture();
  40440. // debug
  40441. // const framebuffer = gl.createFramebuffer();
  40442. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  40443. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  40444. // const readout = new Float32Array( width * height * 4 );
  40445. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  40446. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  40447. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  40448. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  40449. // console.log( readout );
  40450. }
  40451. updateTexture( texture, options ) {
  40452. const { gl } = this;
  40453. const { width, height } = options;
  40454. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  40455. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  40456. return;
  40457. const getImage = ( source ) => {
  40458. if ( source.isDataTexture ) {
  40459. return source.image.data;
  40460. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  40461. return source;
  40462. }
  40463. return source.data;
  40464. };
  40465. this.backend.state.bindTexture( glTextureType, textureGPU );
  40466. this.setTextureParameters( glTextureType, texture );
  40467. if ( texture.isCompressedTexture ) {
  40468. const mipmaps = texture.mipmaps;
  40469. const image = options.image;
  40470. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40471. const mipmap = mipmaps[ i ];
  40472. if ( texture.isCompressedArrayTexture ) {
  40473. if ( texture.format !== gl.RGBA ) {
  40474. if ( glFormat !== null ) {
  40475. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  40476. } else {
  40477. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  40478. }
  40479. } else {
  40480. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  40481. }
  40482. } else {
  40483. if ( glFormat !== null ) {
  40484. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  40485. } else {
  40486. console.warn( 'Unsupported compressed texture format' );
  40487. }
  40488. }
  40489. }
  40490. } else if ( texture.isCubeTexture ) {
  40491. const images = options.images;
  40492. for ( let i = 0; i < 6; i ++ ) {
  40493. const image = getImage( images[ i ] );
  40494. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  40495. }
  40496. } else if ( texture.isDataArrayTexture ) {
  40497. const image = options.image;
  40498. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40499. } else if ( texture.isData3DTexture ) {
  40500. const image = options.image;
  40501. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40502. } else if ( texture.isVideoTexture ) {
  40503. texture.update();
  40504. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  40505. } else {
  40506. const image = getImage( options.image );
  40507. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  40508. }
  40509. }
  40510. generateMipmaps( texture ) {
  40511. const { gl, backend } = this;
  40512. const { textureGPU, glTextureType } = backend.get( texture );
  40513. backend.state.bindTexture( glTextureType, textureGPU );
  40514. gl.generateMipmap( glTextureType );
  40515. }
  40516. deallocateRenderBuffers( renderTarget ) {
  40517. const { gl, backend } = this;
  40518. // remove framebuffer reference
  40519. if ( renderTarget ) {
  40520. const renderContextData = backend.get( renderTarget );
  40521. renderContextData.renderBufferStorageSetup = undefined;
  40522. if ( renderContextData.framebuffers ) {
  40523. for ( const cacheKey in renderContextData.framebuffers ) {
  40524. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  40525. }
  40526. delete renderContextData.framebuffers;
  40527. }
  40528. if ( renderContextData.depthRenderbuffer ) {
  40529. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  40530. delete renderContextData.depthRenderbuffer;
  40531. }
  40532. if ( renderContextData.stencilRenderbuffer ) {
  40533. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  40534. delete renderContextData.stencilRenderbuffer;
  40535. }
  40536. if ( renderContextData.msaaFrameBuffer ) {
  40537. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  40538. delete renderContextData.msaaFrameBuffer;
  40539. }
  40540. if ( renderContextData.msaaRenderbuffers ) {
  40541. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  40542. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  40543. }
  40544. delete renderContextData.msaaRenderbuffers;
  40545. }
  40546. }
  40547. }
  40548. destroyTexture( texture ) {
  40549. const { gl, backend } = this;
  40550. const { textureGPU, renderTarget } = backend.get( texture );
  40551. this.deallocateRenderBuffers( renderTarget );
  40552. gl.deleteTexture( textureGPU );
  40553. backend.delete( texture );
  40554. }
  40555. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  40556. const { gl, backend } = this;
  40557. const { state } = this.backend;
  40558. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  40559. let width, height, minX, minY;
  40560. let dstX, dstY;
  40561. if ( srcRegion !== null ) {
  40562. width = srcRegion.max.x - srcRegion.min.x;
  40563. height = srcRegion.max.y - srcRegion.min.y;
  40564. minX = srcRegion.min.x;
  40565. minY = srcRegion.min.y;
  40566. } else {
  40567. width = srcTexture.image.width;
  40568. height = srcTexture.image.height;
  40569. minX = 0;
  40570. minY = 0;
  40571. }
  40572. if ( dstPosition !== null ) {
  40573. dstX = dstPosition.x;
  40574. dstY = dstPosition.y;
  40575. } else {
  40576. dstX = 0;
  40577. dstY = 0;
  40578. }
  40579. state.bindTexture( glTextureType, dstTextureGPU );
  40580. // As another texture upload may have changed pixelStorei
  40581. // parameters, make sure they are correct for the dstTexture
  40582. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40583. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  40584. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  40585. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40586. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  40587. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  40588. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  40589. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  40590. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  40591. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  40592. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  40593. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  40594. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  40595. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  40596. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  40597. const srcTextureData = backend.get( srcTexture );
  40598. const dstTextureData = backend.get( dstTexture );
  40599. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  40600. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  40601. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  40602. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  40603. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  40604. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  40605. let mask = gl.COLOR_BUFFER_BIT;
  40606. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  40607. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  40608. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  40609. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  40610. } else {
  40611. if ( srcTexture.isDataTexture ) {
  40612. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  40613. } else {
  40614. if ( srcTexture.isCompressedTexture ) {
  40615. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  40616. } else {
  40617. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  40618. }
  40619. }
  40620. }
  40621. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  40622. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  40623. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  40624. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  40625. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  40626. // Generate mipmaps only when copying level 0
  40627. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  40628. state.unbindTexture();
  40629. }
  40630. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  40631. const { gl } = this;
  40632. const { state } = this.backend;
  40633. const { textureGPU } = this.backend.get( texture );
  40634. const { x, y, z: width, w: height } = rectangle;
  40635. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  40636. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  40637. if ( requireDrawFrameBuffer ) {
  40638. const partial = ( x !== 0 || y !== 0 );
  40639. let mask;
  40640. let attachment;
  40641. if ( texture.isDepthTexture === true ) {
  40642. mask = gl.DEPTH_BUFFER_BIT;
  40643. attachment = gl.DEPTH_ATTACHMENT;
  40644. if ( renderContext.stencil ) {
  40645. mask |= gl.STENCIL_BUFFER_BIT;
  40646. }
  40647. } else {
  40648. mask = gl.COLOR_BUFFER_BIT;
  40649. attachment = gl.COLOR_ATTACHMENT0;
  40650. }
  40651. if ( partial ) {
  40652. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  40653. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40654. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40655. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40656. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40657. const flippedY = srcHeight - y - height;
  40658. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  40659. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40660. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40661. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  40662. state.unbindTexture();
  40663. } else {
  40664. const fb = gl.createFramebuffer();
  40665. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40666. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  40667. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  40668. gl.deleteFramebuffer( fb );
  40669. }
  40670. } else {
  40671. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40672. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  40673. state.unbindTexture();
  40674. }
  40675. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  40676. this.backend._setFramebuffer( renderContext );
  40677. }
  40678. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  40679. setupRenderBufferStorage( renderbuffer, renderContext ) {
  40680. const { gl } = this;
  40681. const renderTarget = renderContext.renderTarget;
  40682. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  40683. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  40684. if ( depthBuffer && ! stencilBuffer ) {
  40685. let glInternalFormat = gl.DEPTH_COMPONENT24;
  40686. if ( samples > 0 ) {
  40687. if ( depthTexture && depthTexture.isDepthTexture ) {
  40688. if ( depthTexture.type === gl.FLOAT ) {
  40689. glInternalFormat = gl.DEPTH_COMPONENT32F;
  40690. }
  40691. }
  40692. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  40693. } else {
  40694. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  40695. }
  40696. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40697. } else if ( depthBuffer && stencilBuffer ) {
  40698. if ( samples > 0 ) {
  40699. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  40700. } else {
  40701. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  40702. }
  40703. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40704. }
  40705. }
  40706. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40707. const { backend, gl } = this;
  40708. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  40709. const fb = gl.createFramebuffer();
  40710. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40711. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  40712. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  40713. const typedArrayType = this._getTypedArrayType( glType );
  40714. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  40715. const elementCount = width * height;
  40716. const byteLength = elementCount * bytesPerTexel;
  40717. const buffer = gl.createBuffer();
  40718. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40719. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  40720. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  40721. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40722. await backend.utils._clientWaitAsync();
  40723. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  40724. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40725. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  40726. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40727. gl.deleteFramebuffer( fb );
  40728. return dstBuffer;
  40729. }
  40730. _getTypedArrayType( glType ) {
  40731. const { gl } = this;
  40732. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  40733. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  40734. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  40735. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  40736. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  40737. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  40738. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  40739. if ( glType === gl.FLOAT ) return Float32Array;
  40740. throw new Error( `Unsupported WebGL type: ${glType}` );
  40741. }
  40742. _getBytesPerTexel( glType, glFormat ) {
  40743. const { gl } = this;
  40744. let bytesPerComponent = 0;
  40745. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  40746. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  40747. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  40748. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  40749. glType === gl.UNSIGNED_SHORT ||
  40750. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  40751. if ( glType === gl.UNSIGNED_INT ||
  40752. glType === gl.FLOAT ) bytesPerComponent = 4;
  40753. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  40754. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  40755. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  40756. }
  40757. }
  40758. class WebGLExtensions {
  40759. constructor( backend ) {
  40760. this.backend = backend;
  40761. this.gl = this.backend.gl;
  40762. this.availableExtensions = this.gl.getSupportedExtensions();
  40763. this.extensions = {};
  40764. }
  40765. get( name ) {
  40766. let extension = this.extensions[ name ];
  40767. if ( extension === undefined ) {
  40768. extension = this.gl.getExtension( name );
  40769. this.extensions[ name ] = extension;
  40770. }
  40771. return extension;
  40772. }
  40773. has( name ) {
  40774. return this.availableExtensions.includes( name );
  40775. }
  40776. }
  40777. class WebGLCapabilities {
  40778. constructor( backend ) {
  40779. this.backend = backend;
  40780. this.maxAnisotropy = null;
  40781. }
  40782. getMaxAnisotropy() {
  40783. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  40784. const gl = this.backend.gl;
  40785. const extensions = this.backend.extensions;
  40786. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40787. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40788. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  40789. } else {
  40790. this.maxAnisotropy = 0;
  40791. }
  40792. return this.maxAnisotropy;
  40793. }
  40794. }
  40795. const GLFeatureName = {
  40796. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  40797. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  40798. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  40799. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  40800. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40801. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40802. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  40803. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  40804. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  40805. };
  40806. class WebGLBufferRenderer {
  40807. constructor( backend ) {
  40808. this.gl = backend.gl;
  40809. this.extensions = backend.extensions;
  40810. this.info = backend.renderer.info;
  40811. this.mode = null;
  40812. this.index = 0;
  40813. this.type = null;
  40814. this.object = null;
  40815. }
  40816. render( start, count ) {
  40817. const { gl, mode, object, type, info, index } = this;
  40818. if ( index !== 0 ) {
  40819. gl.drawElements( mode, count, type, start );
  40820. } else {
  40821. gl.drawArrays( mode, start, count );
  40822. }
  40823. info.update( object, count, mode, 1 );
  40824. }
  40825. renderInstances( start, count, primcount ) {
  40826. const { gl, mode, type, index, object, info } = this;
  40827. if ( primcount === 0 ) return;
  40828. if ( index !== 0 ) {
  40829. gl.drawElementsInstanced( mode, count, type, start, primcount );
  40830. } else {
  40831. gl.drawArraysInstanced( mode, start, count, primcount );
  40832. }
  40833. info.update( object, count, mode, primcount );
  40834. }
  40835. renderMultiDraw( starts, counts, drawCount ) {
  40836. const { extensions, mode, object, info } = this;
  40837. if ( drawCount === 0 ) return;
  40838. const extension = extensions.get( 'WEBGL_multi_draw' );
  40839. if ( extension === null ) {
  40840. for ( let i = 0; i < drawCount; i ++ ) {
  40841. this.render( starts[ i ], counts[ i ] );
  40842. }
  40843. } else {
  40844. if ( this.index !== 0 ) {
  40845. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  40846. } else {
  40847. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  40848. }
  40849. let elementCount = 0;
  40850. for ( let i = 0; i < drawCount; i ++ ) {
  40851. elementCount += counts[ i ];
  40852. }
  40853. info.update( object, elementCount, mode, 1 );
  40854. }
  40855. }
  40856. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  40857. const { extensions, mode, object, info } = this;
  40858. if ( drawCount === 0 ) return;
  40859. const extension = extensions.get( 'WEBGL_multi_draw' );
  40860. if ( extension === null ) {
  40861. for ( let i = 0; i < drawCount; i ++ ) {
  40862. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  40863. }
  40864. } else {
  40865. if ( this.index !== 0 ) {
  40866. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  40867. } else {
  40868. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  40869. }
  40870. let elementCount = 0;
  40871. for ( let i = 0; i < drawCount; i ++ ) {
  40872. elementCount += counts[ i ] * primcount[ i ];
  40873. }
  40874. info.update( object, elementCount, mode, 1 );
  40875. }
  40876. }
  40877. //
  40878. }
  40879. //
  40880. class WebGLBackend extends Backend {
  40881. constructor( parameters = {} ) {
  40882. super( parameters );
  40883. this.isWebGLBackend = true;
  40884. }
  40885. init( renderer ) {
  40886. super.init( renderer );
  40887. //
  40888. const parameters = this.parameters;
  40889. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  40890. function onContextLost( event ) {
  40891. event.preventDefault();
  40892. const contextLossInfo = {
  40893. api: 'WebGL',
  40894. message: event.statusMessage || 'Unknown reason',
  40895. reason: null,
  40896. originalEvent: event
  40897. };
  40898. renderer.onDeviceLost( contextLossInfo );
  40899. }
  40900. this._onContextLost = onContextLost;
  40901. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  40902. this.gl = glContext;
  40903. this.extensions = new WebGLExtensions( this );
  40904. this.capabilities = new WebGLCapabilities( this );
  40905. this.attributeUtils = new WebGLAttributeUtils( this );
  40906. this.textureUtils = new WebGLTextureUtils( this );
  40907. this.bufferRenderer = new WebGLBufferRenderer( this );
  40908. this.state = new WebGLState( this );
  40909. this.utils = new WebGLUtils( this );
  40910. this.vaoCache = {};
  40911. this.transformFeedbackCache = {};
  40912. this.discard = false;
  40913. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40914. this.extensions.get( 'EXT_color_buffer_float' );
  40915. this.extensions.get( 'WEBGL_clip_cull_distance' );
  40916. this.extensions.get( 'OES_texture_float_linear' );
  40917. this.extensions.get( 'EXT_color_buffer_half_float' );
  40918. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  40919. this.extensions.get( 'WEBGL_render_shared_exponent' );
  40920. this.extensions.get( 'WEBGL_multi_draw' );
  40921. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  40922. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  40923. this._knownBindings = new WeakSet();
  40924. this._currentContext = null;
  40925. }
  40926. get coordinateSystem() {
  40927. return WebGLCoordinateSystem;
  40928. }
  40929. async getArrayBufferAsync( attribute ) {
  40930. return await this.attributeUtils.getArrayBufferAsync( attribute );
  40931. }
  40932. async waitForGPU() {
  40933. await this.utils._clientWaitAsync();
  40934. }
  40935. initTimestampQuery( renderContext ) {
  40936. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40937. const renderContextData = this.get( renderContext );
  40938. if ( this.queryRunning ) {
  40939. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  40940. renderContextData.queryQueue.push( renderContext );
  40941. return;
  40942. }
  40943. if ( renderContextData.activeQuery ) {
  40944. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40945. renderContextData.activeQuery = null;
  40946. }
  40947. renderContextData.activeQuery = this.gl.createQuery();
  40948. if ( renderContextData.activeQuery !== null ) {
  40949. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  40950. this.queryRunning = true;
  40951. }
  40952. }
  40953. // timestamp utils
  40954. prepareTimestampBuffer( renderContext ) {
  40955. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40956. const renderContextData = this.get( renderContext );
  40957. if ( renderContextData.activeQuery ) {
  40958. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40959. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40960. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  40961. renderContextData.activeQuery = null;
  40962. this.queryRunning = false;
  40963. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  40964. const nextRenderContext = renderContextData.queryQueue.shift();
  40965. this.initTimestampQuery( nextRenderContext );
  40966. }
  40967. }
  40968. }
  40969. async resolveTimestampAsync( renderContext, type = 'render' ) {
  40970. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40971. const renderContextData = this.get( renderContext );
  40972. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40973. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  40974. const queryInfo = renderContextData.gpuQueries[ i ];
  40975. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  40976. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  40977. if ( available && ! disjoint ) {
  40978. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  40979. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  40980. this.gl.deleteQuery( queryInfo.query );
  40981. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  40982. i --;
  40983. this.renderer.info.updateTimestamp( type, duration );
  40984. }
  40985. }
  40986. }
  40987. getContext() {
  40988. return this.gl;
  40989. }
  40990. beginRender( renderContext ) {
  40991. const { gl } = this;
  40992. const renderContextData = this.get( renderContext );
  40993. //
  40994. //
  40995. this.initTimestampQuery( renderContext );
  40996. renderContextData.previousContext = this._currentContext;
  40997. this._currentContext = renderContext;
  40998. this._setFramebuffer( renderContext );
  40999. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  41000. //
  41001. if ( renderContext.viewport ) {
  41002. this.updateViewport( renderContext );
  41003. } else {
  41004. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41005. }
  41006. if ( renderContext.scissor ) {
  41007. const { x, y, width, height } = renderContext.scissorValue;
  41008. gl.scissor( x, renderContext.height - height - y, width, height );
  41009. }
  41010. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41011. if ( occlusionQueryCount > 0 ) {
  41012. // Get a reference to the array of objects with queries. The renderContextData property
  41013. // can be changed by another render pass before the async reading of all previous queries complete
  41014. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  41015. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  41016. renderContextData.lastOcclusionObject = null;
  41017. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  41018. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  41019. renderContextData.occlusionQueryIndex = 0;
  41020. }
  41021. }
  41022. finishRender( renderContext ) {
  41023. const { gl, state } = this;
  41024. const renderContextData = this.get( renderContext );
  41025. const previousContext = renderContextData.previousContext;
  41026. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41027. if ( occlusionQueryCount > 0 ) {
  41028. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  41029. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41030. }
  41031. this.resolveOccludedAsync( renderContext );
  41032. }
  41033. const textures = renderContext.textures;
  41034. if ( textures !== null ) {
  41035. for ( let i = 0; i < textures.length; i ++ ) {
  41036. const texture = textures[ i ];
  41037. if ( texture.generateMipmaps ) {
  41038. this.generateMipmaps( texture );
  41039. }
  41040. }
  41041. }
  41042. this._currentContext = previousContext;
  41043. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  41044. const renderTargetContextData = this.get( renderContext.renderTarget );
  41045. const { samples } = renderContext.renderTarget;
  41046. if ( samples > 0 ) {
  41047. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  41048. const mask = gl.COLOR_BUFFER_BIT;
  41049. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41050. const textures = renderContext.textures;
  41051. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  41052. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41053. for ( let i = 0; i < textures.length; i ++ ) {
  41054. // TODO Add support for MRT
  41055. if ( renderContext.scissor ) {
  41056. const { x, y, width, height } = renderContext.scissorValue;
  41057. const viewY = renderContext.height - height - y;
  41058. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  41059. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  41060. } else {
  41061. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  41062. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  41063. }
  41064. }
  41065. }
  41066. }
  41067. if ( previousContext !== null ) {
  41068. this._setFramebuffer( previousContext );
  41069. if ( previousContext.viewport ) {
  41070. this.updateViewport( previousContext );
  41071. } else {
  41072. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41073. }
  41074. }
  41075. this.prepareTimestampBuffer( renderContext );
  41076. }
  41077. resolveOccludedAsync( renderContext ) {
  41078. const renderContextData = this.get( renderContext );
  41079. // handle occlusion query results
  41080. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  41081. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  41082. const occluded = new WeakSet();
  41083. const { gl } = this;
  41084. renderContextData.currentOcclusionQueryObjects = null;
  41085. renderContextData.currentOcclusionQueries = null;
  41086. const check = () => {
  41087. let completed = 0;
  41088. // check all queries and requeue as appropriate
  41089. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  41090. const query = currentOcclusionQueries[ i ];
  41091. if ( query === null ) continue;
  41092. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  41093. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  41094. currentOcclusionQueries[ i ] = null;
  41095. gl.deleteQuery( query );
  41096. completed ++;
  41097. }
  41098. }
  41099. if ( completed < currentOcclusionQueries.length ) {
  41100. requestAnimationFrame( check );
  41101. } else {
  41102. renderContextData.occluded = occluded;
  41103. }
  41104. };
  41105. check();
  41106. }
  41107. }
  41108. isOccluded( renderContext, object ) {
  41109. const renderContextData = this.get( renderContext );
  41110. return renderContextData.occluded && renderContextData.occluded.has( object );
  41111. }
  41112. updateViewport( renderContext ) {
  41113. const gl = this.gl;
  41114. const { x, y, width, height } = renderContext.viewportValue;
  41115. gl.viewport( x, renderContext.height - height - y, width, height );
  41116. }
  41117. setScissorTest( boolean ) {
  41118. const gl = this.gl;
  41119. if ( boolean ) {
  41120. gl.enable( gl.SCISSOR_TEST );
  41121. } else {
  41122. gl.disable( gl.SCISSOR_TEST );
  41123. }
  41124. }
  41125. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  41126. const { gl } = this;
  41127. if ( descriptor === null ) {
  41128. const clearColor = this.getClearColor();
  41129. // premultiply alpha
  41130. clearColor.r *= clearColor.a;
  41131. clearColor.g *= clearColor.a;
  41132. clearColor.b *= clearColor.a;
  41133. descriptor = {
  41134. textures: null,
  41135. clearColorValue: clearColor
  41136. };
  41137. }
  41138. //
  41139. let clear = 0;
  41140. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  41141. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  41142. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  41143. if ( clear !== 0 ) {
  41144. let clearColor;
  41145. if ( descriptor.clearColorValue ) {
  41146. clearColor = descriptor.clearColorValue;
  41147. } else {
  41148. clearColor = this.getClearColor();
  41149. // premultiply alpha
  41150. clearColor.r *= clearColor.a;
  41151. clearColor.g *= clearColor.a;
  41152. clearColor.b *= clearColor.a;
  41153. }
  41154. if ( depth ) this.state.setDepthMask( true );
  41155. if ( descriptor.textures === null ) {
  41156. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  41157. gl.clear( clear );
  41158. } else {
  41159. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  41160. if ( color ) {
  41161. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  41162. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  41163. }
  41164. }
  41165. if ( depth && stencil ) {
  41166. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  41167. } else if ( depth ) {
  41168. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  41169. } else if ( stencil ) {
  41170. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  41171. }
  41172. }
  41173. }
  41174. }
  41175. beginCompute( computeGroup ) {
  41176. const { state, gl } = this;
  41177. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  41178. this.initTimestampQuery( computeGroup );
  41179. }
  41180. compute( computeGroup, computeNode, bindings, pipeline ) {
  41181. const { state, gl } = this;
  41182. if ( ! this.discard ) {
  41183. // required here to handle async behaviour of render.compute()
  41184. gl.enable( gl.RASTERIZER_DISCARD );
  41185. this.discard = true;
  41186. }
  41187. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  41188. const vaoKey = this._getVaoKey( null, attributes );
  41189. const vaoGPU = this.vaoCache[ vaoKey ];
  41190. if ( vaoGPU === undefined ) {
  41191. this._createVao( null, attributes );
  41192. } else {
  41193. gl.bindVertexArray( vaoGPU );
  41194. }
  41195. state.useProgram( programGPU );
  41196. this._bindUniforms( bindings );
  41197. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  41198. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41199. gl.beginTransformFeedback( gl.POINTS );
  41200. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  41201. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  41202. } else {
  41203. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  41204. }
  41205. gl.endTransformFeedback();
  41206. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41207. // switch active buffers
  41208. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41209. const dualAttributeData = transformBuffers[ i ];
  41210. if ( dualAttributeData.pbo ) {
  41211. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  41212. }
  41213. dualAttributeData.switchBuffers();
  41214. }
  41215. }
  41216. finishCompute( computeGroup ) {
  41217. const gl = this.gl;
  41218. this.discard = false;
  41219. gl.disable( gl.RASTERIZER_DISCARD );
  41220. this.prepareTimestampBuffer( computeGroup );
  41221. if ( this._currentContext ) {
  41222. this._setFramebuffer( this._currentContext );
  41223. }
  41224. }
  41225. draw( renderObject/*, info*/ ) {
  41226. const { object, pipeline, material, context } = renderObject;
  41227. const { programGPU } = this.get( pipeline );
  41228. const { gl, state } = this;
  41229. const contextData = this.get( context );
  41230. const drawParams = renderObject.getDrawParameters();
  41231. if ( drawParams === null ) return;
  41232. //
  41233. this._bindUniforms( renderObject.getBindings() );
  41234. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  41235. state.setMaterial( material, frontFaceCW );
  41236. state.useProgram( programGPU );
  41237. //
  41238. let vaoGPU = renderObject.staticVao;
  41239. if ( vaoGPU === undefined ) {
  41240. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  41241. vaoGPU = this.vaoCache[ vaoKey ];
  41242. if ( vaoGPU === undefined ) {
  41243. let staticVao;
  41244. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  41245. if ( staticVao ) renderObject.staticVao = vaoGPU;
  41246. }
  41247. }
  41248. gl.bindVertexArray( vaoGPU );
  41249. //
  41250. const index = renderObject.getIndex();
  41251. //
  41252. const lastObject = contextData.lastOcclusionObject;
  41253. if ( lastObject !== object && lastObject !== undefined ) {
  41254. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  41255. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41256. contextData.occlusionQueryIndex ++;
  41257. }
  41258. if ( object.occlusionTest === true ) {
  41259. const query = gl.createQuery();
  41260. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  41261. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  41262. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  41263. }
  41264. contextData.lastOcclusionObject = object;
  41265. }
  41266. //
  41267. const renderer = this.bufferRenderer;
  41268. if ( object.isPoints ) renderer.mode = gl.POINTS;
  41269. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  41270. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  41271. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  41272. else {
  41273. if ( material.wireframe === true ) {
  41274. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  41275. renderer.mode = gl.LINES;
  41276. } else {
  41277. renderer.mode = gl.TRIANGLES;
  41278. }
  41279. }
  41280. //
  41281. const { vertexCount, instanceCount } = drawParams;
  41282. let { firstVertex } = drawParams;
  41283. renderer.object = object;
  41284. if ( index !== null ) {
  41285. firstVertex *= index.array.BYTES_PER_ELEMENT;
  41286. const indexData = this.get( index );
  41287. renderer.index = index.count;
  41288. renderer.type = indexData.type;
  41289. } else {
  41290. renderer.index = 0;
  41291. }
  41292. if ( object.isBatchedMesh ) {
  41293. if ( object._multiDrawInstances !== null ) {
  41294. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  41295. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  41296. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  41297. } else {
  41298. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  41299. }
  41300. } else if ( instanceCount > 1 ) {
  41301. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  41302. } else {
  41303. renderer.render( firstVertex, vertexCount );
  41304. }
  41305. //
  41306. gl.bindVertexArray( null );
  41307. }
  41308. needsRenderUpdate( /*renderObject*/ ) {
  41309. return false;
  41310. }
  41311. getRenderCacheKey( /*renderObject*/ ) {
  41312. return '';
  41313. }
  41314. // textures
  41315. createDefaultTexture( texture ) {
  41316. this.textureUtils.createDefaultTexture( texture );
  41317. }
  41318. createTexture( texture, options ) {
  41319. this.textureUtils.createTexture( texture, options );
  41320. }
  41321. updateTexture( texture, options ) {
  41322. this.textureUtils.updateTexture( texture, options );
  41323. }
  41324. generateMipmaps( texture ) {
  41325. this.textureUtils.generateMipmaps( texture );
  41326. }
  41327. destroyTexture( texture ) {
  41328. this.textureUtils.destroyTexture( texture );
  41329. }
  41330. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41331. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  41332. }
  41333. createSampler( /*texture*/ ) {
  41334. //console.warn( 'Abstract class.' );
  41335. }
  41336. destroySampler() {}
  41337. // node builder
  41338. createNodeBuilder( object, renderer ) {
  41339. return new GLSLNodeBuilder( object, renderer );
  41340. }
  41341. // program
  41342. createProgram( program ) {
  41343. const gl = this.gl;
  41344. const { stage, code } = program;
  41345. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  41346. gl.shaderSource( shader, code );
  41347. gl.compileShader( shader );
  41348. this.set( program, {
  41349. shaderGPU: shader
  41350. } );
  41351. }
  41352. destroyProgram( /*program*/ ) {
  41353. console.warn( 'Abstract class.' );
  41354. }
  41355. createRenderPipeline( renderObject, promises ) {
  41356. const gl = this.gl;
  41357. const pipeline = renderObject.pipeline;
  41358. // Program
  41359. const { fragmentProgram, vertexProgram } = pipeline;
  41360. const programGPU = gl.createProgram();
  41361. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41362. const vertexShader = this.get( vertexProgram ).shaderGPU;
  41363. gl.attachShader( programGPU, fragmentShader );
  41364. gl.attachShader( programGPU, vertexShader );
  41365. gl.linkProgram( programGPU );
  41366. this.set( pipeline, {
  41367. programGPU,
  41368. fragmentShader,
  41369. vertexShader
  41370. } );
  41371. if ( promises !== null && this.parallel ) {
  41372. const p = new Promise( ( resolve /*, reject*/ ) => {
  41373. const parallel = this.parallel;
  41374. const checkStatus = () => {
  41375. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  41376. this._completeCompile( renderObject, pipeline );
  41377. resolve();
  41378. } else {
  41379. requestAnimationFrame( checkStatus );
  41380. }
  41381. };
  41382. checkStatus();
  41383. } );
  41384. promises.push( p );
  41385. return;
  41386. }
  41387. this._completeCompile( renderObject, pipeline );
  41388. }
  41389. _handleSource( string, errorLine ) {
  41390. const lines = string.split( '\n' );
  41391. const lines2 = [];
  41392. const from = Math.max( errorLine - 6, 0 );
  41393. const to = Math.min( errorLine + 6, lines.length );
  41394. for ( let i = from; i < to; i ++ ) {
  41395. const line = i + 1;
  41396. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  41397. }
  41398. return lines2.join( '\n' );
  41399. }
  41400. _getShaderErrors( gl, shader, type ) {
  41401. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  41402. const errors = gl.getShaderInfoLog( shader ).trim();
  41403. if ( status && errors === '' ) return '';
  41404. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  41405. if ( errorMatches ) {
  41406. const errorLine = parseInt( errorMatches[ 1 ] );
  41407. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  41408. } else {
  41409. return errors;
  41410. }
  41411. }
  41412. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  41413. if ( this.renderer.debug.checkShaderErrors ) {
  41414. const gl = this.gl;
  41415. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  41416. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41417. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  41418. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  41419. } else {
  41420. // default error reporting
  41421. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  41422. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  41423. console.error(
  41424. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  41425. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  41426. 'Program Info Log: ' + programLog + '\n' +
  41427. vertexErrors + '\n' +
  41428. fragmentErrors
  41429. );
  41430. }
  41431. } else if ( programLog !== '' ) {
  41432. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  41433. }
  41434. }
  41435. }
  41436. _completeCompile( renderObject, pipeline ) {
  41437. const { state, gl } = this;
  41438. const pipelineData = this.get( pipeline );
  41439. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  41440. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41441. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41442. }
  41443. state.useProgram( programGPU );
  41444. // Bindings
  41445. const bindings = renderObject.getBindings();
  41446. this._setupBindings( bindings, programGPU );
  41447. //
  41448. this.set( pipeline, {
  41449. programGPU
  41450. } );
  41451. }
  41452. createComputePipeline( computePipeline, bindings ) {
  41453. const { state, gl } = this;
  41454. // Program
  41455. const fragmentProgram = {
  41456. stage: 'fragment',
  41457. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  41458. };
  41459. this.createProgram( fragmentProgram );
  41460. const { computeProgram } = computePipeline;
  41461. const programGPU = gl.createProgram();
  41462. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41463. const vertexShader = this.get( computeProgram ).shaderGPU;
  41464. const transforms = computeProgram.transforms;
  41465. const transformVaryingNames = [];
  41466. const transformAttributeNodes = [];
  41467. for ( let i = 0; i < transforms.length; i ++ ) {
  41468. const transform = transforms[ i ];
  41469. transformVaryingNames.push( transform.varyingName );
  41470. transformAttributeNodes.push( transform.attributeNode );
  41471. }
  41472. gl.attachShader( programGPU, fragmentShader );
  41473. gl.attachShader( programGPU, vertexShader );
  41474. gl.transformFeedbackVaryings(
  41475. programGPU,
  41476. transformVaryingNames,
  41477. gl.SEPARATE_ATTRIBS
  41478. );
  41479. gl.linkProgram( programGPU );
  41480. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41481. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41482. }
  41483. state.useProgram( programGPU );
  41484. // Bindings
  41485. this._setupBindings( bindings, programGPU );
  41486. const attributeNodes = computeProgram.attributes;
  41487. const attributes = [];
  41488. const transformBuffers = [];
  41489. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  41490. const attribute = attributeNodes[ i ].node.attribute;
  41491. attributes.push( attribute );
  41492. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41493. }
  41494. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  41495. const attribute = transformAttributeNodes[ i ].attribute;
  41496. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41497. const attributeData = this.get( attribute );
  41498. transformBuffers.push( attributeData );
  41499. }
  41500. //
  41501. this.set( computePipeline, {
  41502. programGPU,
  41503. transformBuffers,
  41504. attributes
  41505. } );
  41506. }
  41507. createBindings( bindGroup, bindings ) {
  41508. if ( this._knownBindings.has( bindings ) === false ) {
  41509. this._knownBindings.add( bindings );
  41510. let uniformBuffers = 0;
  41511. let textures = 0;
  41512. for ( const bindGroup of bindings ) {
  41513. this.set( bindGroup, {
  41514. textures: textures,
  41515. uniformBuffers: uniformBuffers
  41516. } );
  41517. for ( const binding of bindGroup.bindings ) {
  41518. if ( binding.isUniformBuffer ) uniformBuffers ++;
  41519. if ( binding.isSampledTexture ) textures ++;
  41520. }
  41521. }
  41522. }
  41523. this.updateBindings( bindGroup, bindings );
  41524. }
  41525. updateBindings( bindGroup /*, bindings*/ ) {
  41526. const { gl } = this;
  41527. const bindGroupData = this.get( bindGroup );
  41528. let i = bindGroupData.uniformBuffers;
  41529. let t = bindGroupData.textures;
  41530. for ( const binding of bindGroup.bindings ) {
  41531. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41532. const data = binding.buffer;
  41533. const bufferGPU = gl.createBuffer();
  41534. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41535. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41536. this.set( binding, {
  41537. index: i ++,
  41538. bufferGPU
  41539. } );
  41540. } else if ( binding.isSampledTexture ) {
  41541. const { textureGPU, glTextureType } = this.get( binding.texture );
  41542. this.set( binding, {
  41543. index: t ++,
  41544. textureGPU,
  41545. glTextureType
  41546. } );
  41547. }
  41548. }
  41549. }
  41550. updateBinding( binding ) {
  41551. const gl = this.gl;
  41552. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41553. const bindingData = this.get( binding );
  41554. const bufferGPU = bindingData.bufferGPU;
  41555. const data = binding.buffer;
  41556. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41557. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41558. }
  41559. }
  41560. // attributes
  41561. createIndexAttribute( attribute ) {
  41562. const gl = this.gl;
  41563. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  41564. }
  41565. createAttribute( attribute ) {
  41566. if ( this.has( attribute ) ) return;
  41567. const gl = this.gl;
  41568. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41569. }
  41570. createStorageAttribute( attribute ) {
  41571. if ( this.has( attribute ) ) return;
  41572. const gl = this.gl;
  41573. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41574. }
  41575. updateAttribute( attribute ) {
  41576. this.attributeUtils.updateAttribute( attribute );
  41577. }
  41578. destroyAttribute( attribute ) {
  41579. this.attributeUtils.destroyAttribute( attribute );
  41580. }
  41581. updateSize() {
  41582. //console.warn( 'Abstract class.' );
  41583. }
  41584. hasFeature( name ) {
  41585. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  41586. const extensions = this.extensions;
  41587. for ( let i = 0; i < keysMatching.length; i ++ ) {
  41588. if ( extensions.has( keysMatching[ i ] ) ) return true;
  41589. }
  41590. return false;
  41591. }
  41592. getMaxAnisotropy() {
  41593. return this.capabilities.getMaxAnisotropy();
  41594. }
  41595. copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ) {
  41596. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  41597. }
  41598. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  41599. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  41600. }
  41601. _setFramebuffer( descriptor ) {
  41602. const { gl, state } = this;
  41603. let currentFrameBuffer = null;
  41604. if ( descriptor.textures !== null ) {
  41605. const renderTarget = descriptor.renderTarget;
  41606. const renderTargetContextData = this.get( renderTarget );
  41607. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  41608. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  41609. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  41610. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  41611. const cacheKey = getCacheKey( descriptor );
  41612. let fb;
  41613. if ( isCube ) {
  41614. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  41615. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  41616. } else {
  41617. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  41618. fb = renderTargetContextData.framebuffers[ cacheKey ];
  41619. }
  41620. if ( fb === undefined ) {
  41621. fb = gl.createFramebuffer();
  41622. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  41623. const textures = descriptor.textures;
  41624. if ( isCube ) {
  41625. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  41626. const { textureGPU } = this.get( textures[ 0 ] );
  41627. const cubeFace = this.renderer._activeCubeFace;
  41628. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  41629. } else {
  41630. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  41631. for ( let i = 0; i < textures.length; i ++ ) {
  41632. const texture = textures[ i ];
  41633. const textureData = this.get( texture );
  41634. textureData.renderTarget = descriptor.renderTarget;
  41635. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41636. const attachment = gl.COLOR_ATTACHMENT0 + i;
  41637. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41638. }
  41639. state.drawBuffers( descriptor, fb );
  41640. }
  41641. if ( descriptor.depthTexture !== null ) {
  41642. const textureData = this.get( descriptor.depthTexture );
  41643. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41644. textureData.renderTarget = descriptor.renderTarget;
  41645. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41646. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41647. }
  41648. }
  41649. if ( samples > 0 ) {
  41650. if ( msaaFb === undefined ) {
  41651. const invalidationArray = [];
  41652. msaaFb = gl.createFramebuffer();
  41653. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  41654. const msaaRenderbuffers = [];
  41655. const textures = descriptor.textures;
  41656. for ( let i = 0; i < textures.length; i ++ ) {
  41657. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  41658. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41659. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  41660. if ( depthBuffer ) {
  41661. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41662. invalidationArray.push( depthStyle );
  41663. }
  41664. const texture = descriptor.textures[ i ];
  41665. const textureData = this.get( texture );
  41666. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  41667. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41668. }
  41669. renderTargetContextData.msaaFrameBuffer = msaaFb;
  41670. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  41671. if ( depthRenderbuffer === undefined ) {
  41672. depthRenderbuffer = gl.createRenderbuffer();
  41673. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  41674. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  41675. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41676. invalidationArray.push( depthStyle );
  41677. }
  41678. renderTargetContextData.invalidationArray = invalidationArray;
  41679. }
  41680. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41681. } else {
  41682. currentFrameBuffer = fb;
  41683. }
  41684. }
  41685. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  41686. }
  41687. _getVaoKey( index, attributes ) {
  41688. let key = [];
  41689. if ( index !== null ) {
  41690. const indexData = this.get( index );
  41691. key += ':' + indexData.id;
  41692. }
  41693. for ( let i = 0; i < attributes.length; i ++ ) {
  41694. const attributeData = this.get( attributes[ i ] );
  41695. key += ':' + attributeData.id;
  41696. }
  41697. return key;
  41698. }
  41699. _createVao( index, attributes ) {
  41700. const { gl } = this;
  41701. const vaoGPU = gl.createVertexArray();
  41702. let key = '';
  41703. let staticVao = true;
  41704. gl.bindVertexArray( vaoGPU );
  41705. if ( index !== null ) {
  41706. const indexData = this.get( index );
  41707. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  41708. key += ':' + indexData.id;
  41709. }
  41710. for ( let i = 0; i < attributes.length; i ++ ) {
  41711. const attribute = attributes[ i ];
  41712. const attributeData = this.get( attribute );
  41713. key += ':' + attributeData.id;
  41714. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  41715. gl.enableVertexAttribArray( i );
  41716. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  41717. let stride, offset;
  41718. if ( attribute.isInterleavedBufferAttribute === true ) {
  41719. stride = attribute.data.stride * attributeData.bytesPerElement;
  41720. offset = attribute.offset * attributeData.bytesPerElement;
  41721. } else {
  41722. stride = 0;
  41723. offset = 0;
  41724. }
  41725. if ( attributeData.isInteger ) {
  41726. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  41727. } else {
  41728. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  41729. }
  41730. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  41731. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  41732. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  41733. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  41734. }
  41735. }
  41736. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  41737. this.vaoCache[ key ] = vaoGPU;
  41738. return { vaoGPU, staticVao };
  41739. }
  41740. _getTransformFeedback( transformBuffers ) {
  41741. let key = '';
  41742. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41743. key += ':' + transformBuffers[ i ].id;
  41744. }
  41745. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  41746. if ( transformFeedbackGPU !== undefined ) {
  41747. return transformFeedbackGPU;
  41748. }
  41749. const { gl } = this;
  41750. transformFeedbackGPU = gl.createTransformFeedback();
  41751. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41752. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41753. const attributeData = transformBuffers[ i ];
  41754. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  41755. }
  41756. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41757. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  41758. return transformFeedbackGPU;
  41759. }
  41760. _setupBindings( bindings, programGPU ) {
  41761. const gl = this.gl;
  41762. for ( const bindGroup of bindings ) {
  41763. for ( const binding of bindGroup.bindings ) {
  41764. const bindingData = this.get( binding );
  41765. const index = bindingData.index;
  41766. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41767. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  41768. gl.uniformBlockBinding( programGPU, location, index );
  41769. } else if ( binding.isSampledTexture ) {
  41770. const location = gl.getUniformLocation( programGPU, binding.name );
  41771. gl.uniform1i( location, index );
  41772. }
  41773. }
  41774. }
  41775. }
  41776. _bindUniforms( bindings ) {
  41777. const { gl, state } = this;
  41778. for ( const bindGroup of bindings ) {
  41779. for ( const binding of bindGroup.bindings ) {
  41780. const bindingData = this.get( binding );
  41781. const index = bindingData.index;
  41782. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41783. // TODO USE bindBufferRange to group multiple uniform buffers
  41784. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  41785. } else if ( binding.isSampledTexture ) {
  41786. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  41787. }
  41788. }
  41789. }
  41790. }
  41791. dispose() {
  41792. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  41793. }
  41794. }
  41795. class Sampler extends Binding {
  41796. constructor( name, texture ) {
  41797. super( name );
  41798. this.texture = texture;
  41799. this.version = texture ? texture.version : 0;
  41800. this.isSampler = true;
  41801. }
  41802. }
  41803. class NodeSampler extends Sampler {
  41804. constructor( name, textureNode, groupNode ) {
  41805. super( name, textureNode ? textureNode.value : null );
  41806. this.textureNode = textureNode;
  41807. this.groupNode = groupNode;
  41808. }
  41809. update() {
  41810. this.texture = this.textureNode.value;
  41811. }
  41812. }
  41813. class StorageBuffer extends Buffer {
  41814. constructor( name, attribute ) {
  41815. super( name, attribute ? attribute.array : null );
  41816. this.attribute = attribute;
  41817. this.isStorageBuffer = true;
  41818. }
  41819. }
  41820. let _id = 0;
  41821. class NodeStorageBuffer extends StorageBuffer {
  41822. constructor( nodeUniform, groupNode ) {
  41823. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  41824. this.nodeUniform = nodeUniform;
  41825. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  41826. this.groupNode = groupNode;
  41827. }
  41828. get buffer() {
  41829. return this.nodeUniform.value;
  41830. }
  41831. }
  41832. class WebGPUTexturePassUtils extends DataMap {
  41833. constructor( device ) {
  41834. super();
  41835. this.device = device;
  41836. const mipmapVertexSource = `
  41837. struct VarysStruct {
  41838. @builtin( position ) Position: vec4<f32>,
  41839. @location( 0 ) vTex : vec2<f32>
  41840. };
  41841. @vertex
  41842. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  41843. var Varys : VarysStruct;
  41844. var pos = array< vec2<f32>, 4 >(
  41845. vec2<f32>( -1.0, 1.0 ),
  41846. vec2<f32>( 1.0, 1.0 ),
  41847. vec2<f32>( -1.0, -1.0 ),
  41848. vec2<f32>( 1.0, -1.0 )
  41849. );
  41850. var tex = array< vec2<f32>, 4 >(
  41851. vec2<f32>( 0.0, 0.0 ),
  41852. vec2<f32>( 1.0, 0.0 ),
  41853. vec2<f32>( 0.0, 1.0 ),
  41854. vec2<f32>( 1.0, 1.0 )
  41855. );
  41856. Varys.vTex = tex[ vertexIndex ];
  41857. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  41858. return Varys;
  41859. }
  41860. `;
  41861. const mipmapFragmentSource = `
  41862. @group( 0 ) @binding( 0 )
  41863. var imgSampler : sampler;
  41864. @group( 0 ) @binding( 1 )
  41865. var img : texture_2d<f32>;
  41866. @fragment
  41867. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41868. return textureSample( img, imgSampler, vTex );
  41869. }
  41870. `;
  41871. const flipYFragmentSource = `
  41872. @group( 0 ) @binding( 0 )
  41873. var imgSampler : sampler;
  41874. @group( 0 ) @binding( 1 )
  41875. var img : texture_2d<f32>;
  41876. @fragment
  41877. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41878. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  41879. }
  41880. `;
  41881. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  41882. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  41883. // We'll need a new pipeline for every texture format used.
  41884. this.transferPipelines = {};
  41885. this.flipYPipelines = {};
  41886. this.mipmapVertexShaderModule = device.createShaderModule( {
  41887. label: 'mipmapVertex',
  41888. code: mipmapVertexSource
  41889. } );
  41890. this.mipmapFragmentShaderModule = device.createShaderModule( {
  41891. label: 'mipmapFragment',
  41892. code: mipmapFragmentSource
  41893. } );
  41894. this.flipYFragmentShaderModule = device.createShaderModule( {
  41895. label: 'flipYFragment',
  41896. code: flipYFragmentSource
  41897. } );
  41898. }
  41899. getTransferPipeline( format ) {
  41900. let pipeline = this.transferPipelines[ format ];
  41901. if ( pipeline === undefined ) {
  41902. pipeline = this.device.createRenderPipeline( {
  41903. label: `mipmap-${ format }`,
  41904. vertex: {
  41905. module: this.mipmapVertexShaderModule,
  41906. entryPoint: 'main'
  41907. },
  41908. fragment: {
  41909. module: this.mipmapFragmentShaderModule,
  41910. entryPoint: 'main',
  41911. targets: [ { format } ]
  41912. },
  41913. primitive: {
  41914. topology: GPUPrimitiveTopology.TriangleStrip,
  41915. stripIndexFormat: GPUIndexFormat.Uint32
  41916. },
  41917. layout: 'auto'
  41918. } );
  41919. this.transferPipelines[ format ] = pipeline;
  41920. }
  41921. return pipeline;
  41922. }
  41923. getFlipYPipeline( format ) {
  41924. let pipeline = this.flipYPipelines[ format ];
  41925. if ( pipeline === undefined ) {
  41926. pipeline = this.device.createRenderPipeline( {
  41927. label: `flipY-${ format }`,
  41928. vertex: {
  41929. module: this.mipmapVertexShaderModule,
  41930. entryPoint: 'main'
  41931. },
  41932. fragment: {
  41933. module: this.flipYFragmentShaderModule,
  41934. entryPoint: 'main',
  41935. targets: [ { format } ]
  41936. },
  41937. primitive: {
  41938. topology: GPUPrimitiveTopology.TriangleStrip,
  41939. stripIndexFormat: GPUIndexFormat.Uint32
  41940. },
  41941. layout: 'auto'
  41942. } );
  41943. this.flipYPipelines[ format ] = pipeline;
  41944. }
  41945. return pipeline;
  41946. }
  41947. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41948. const format = textureGPUDescriptor.format;
  41949. const { width, height } = textureGPUDescriptor.size;
  41950. const transferPipeline = this.getTransferPipeline( format );
  41951. const flipYPipeline = this.getFlipYPipeline( format );
  41952. const tempTexture = this.device.createTexture( {
  41953. size: { width, height, depthOrArrayLayers: 1 },
  41954. format,
  41955. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  41956. } );
  41957. const srcView = textureGPU.createView( {
  41958. baseMipLevel: 0,
  41959. mipLevelCount: 1,
  41960. dimension: GPUTextureViewDimension.TwoD,
  41961. baseArrayLayer
  41962. } );
  41963. const dstView = tempTexture.createView( {
  41964. baseMipLevel: 0,
  41965. mipLevelCount: 1,
  41966. dimension: GPUTextureViewDimension.TwoD,
  41967. baseArrayLayer: 0
  41968. } );
  41969. const commandEncoder = this.device.createCommandEncoder( {} );
  41970. const pass = ( pipeline, sourceView, destinationView ) => {
  41971. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41972. const bindGroup = this.device.createBindGroup( {
  41973. layout: bindGroupLayout,
  41974. entries: [ {
  41975. binding: 0,
  41976. resource: this.flipYSampler
  41977. }, {
  41978. binding: 1,
  41979. resource: sourceView
  41980. } ]
  41981. } );
  41982. const passEncoder = commandEncoder.beginRenderPass( {
  41983. colorAttachments: [ {
  41984. view: destinationView,
  41985. loadOp: GPULoadOp.Clear,
  41986. storeOp: GPUStoreOp.Store,
  41987. clearValue: [ 0, 0, 0, 0 ]
  41988. } ]
  41989. } );
  41990. passEncoder.setPipeline( pipeline );
  41991. passEncoder.setBindGroup( 0, bindGroup );
  41992. passEncoder.draw( 4, 1, 0, 0 );
  41993. passEncoder.end();
  41994. };
  41995. pass( transferPipeline, srcView, dstView );
  41996. pass( flipYPipeline, dstView, srcView );
  41997. this.device.queue.submit( [ commandEncoder.finish() ] );
  41998. tempTexture.destroy();
  41999. }
  42000. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42001. const textureData = this.get( textureGPU );
  42002. if ( textureData.useCount === undefined ) {
  42003. textureData.useCount = 0;
  42004. textureData.layers = [];
  42005. }
  42006. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  42007. const commandEncoder = this.device.createCommandEncoder( {} );
  42008. this._mipmapRunBundles( commandEncoder, passes );
  42009. this.device.queue.submit( [ commandEncoder.finish() ] );
  42010. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  42011. textureData.useCount ++;
  42012. }
  42013. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  42014. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  42015. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42016. let srcView = textureGPU.createView( {
  42017. baseMipLevel: 0,
  42018. mipLevelCount: 1,
  42019. dimension: GPUTextureViewDimension.TwoD,
  42020. baseArrayLayer
  42021. } );
  42022. const passes = [];
  42023. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  42024. const bindGroup = this.device.createBindGroup( {
  42025. layout: bindGroupLayout,
  42026. entries: [ {
  42027. binding: 0,
  42028. resource: this.mipmapSampler
  42029. }, {
  42030. binding: 1,
  42031. resource: srcView
  42032. } ]
  42033. } );
  42034. const dstView = textureGPU.createView( {
  42035. baseMipLevel: i,
  42036. mipLevelCount: 1,
  42037. dimension: GPUTextureViewDimension.TwoD,
  42038. baseArrayLayer
  42039. } );
  42040. const passDescriptor = {
  42041. colorAttachments: [ {
  42042. view: dstView,
  42043. loadOp: GPULoadOp.Clear,
  42044. storeOp: GPUStoreOp.Store,
  42045. clearValue: [ 0, 0, 0, 0 ]
  42046. } ]
  42047. };
  42048. const passEncoder = this.device.createRenderBundleEncoder( {
  42049. colorFormats: [ textureGPUDescriptor.format ]
  42050. } );
  42051. passEncoder.setPipeline( pipeline );
  42052. passEncoder.setBindGroup( 0, bindGroup );
  42053. passEncoder.draw( 4, 1, 0, 0 );
  42054. passes.push( {
  42055. renderBundles: [ passEncoder.finish() ],
  42056. passDescriptor
  42057. } );
  42058. srcView = dstView;
  42059. }
  42060. return passes;
  42061. }
  42062. _mipmapRunBundles( commandEncoder, passes ) {
  42063. const levels = passes.length;
  42064. for ( let i = 0; i < levels; i ++ ) {
  42065. const pass = passes[ i ];
  42066. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  42067. passEncoder.executeBundles( pass.renderBundles );
  42068. passEncoder.end();
  42069. }
  42070. }
  42071. }
  42072. const _compareToWebGPU = {
  42073. [ NeverCompare ]: 'never',
  42074. [ LessCompare ]: 'less',
  42075. [ EqualCompare ]: 'equal',
  42076. [ LessEqualCompare ]: 'less-equal',
  42077. [ GreaterCompare ]: 'greater',
  42078. [ GreaterEqualCompare ]: 'greater-equal',
  42079. [ AlwaysCompare ]: 'always',
  42080. [ NotEqualCompare ]: 'not-equal'
  42081. };
  42082. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  42083. class WebGPUTextureUtils {
  42084. constructor( backend ) {
  42085. this.backend = backend;
  42086. this._passUtils = null;
  42087. this.defaultTexture = {};
  42088. this.defaultCubeTexture = {};
  42089. this.defaultVideoFrame = null;
  42090. this.colorBuffer = null;
  42091. this.depthTexture = new DepthTexture();
  42092. this.depthTexture.name = 'depthBuffer';
  42093. }
  42094. createSampler( texture ) {
  42095. const backend = this.backend;
  42096. const device = backend.device;
  42097. const textureGPU = backend.get( texture );
  42098. const samplerDescriptorGPU = {
  42099. addressModeU: this._convertAddressMode( texture.wrapS ),
  42100. addressModeV: this._convertAddressMode( texture.wrapT ),
  42101. addressModeW: this._convertAddressMode( texture.wrapR ),
  42102. magFilter: this._convertFilterMode( texture.magFilter ),
  42103. minFilter: this._convertFilterMode( texture.minFilter ),
  42104. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  42105. maxAnisotropy: 1
  42106. };
  42107. // anisotropy can only be used when all filter modes are set to linear.
  42108. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  42109. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  42110. }
  42111. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  42112. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  42113. }
  42114. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  42115. }
  42116. createDefaultTexture( texture ) {
  42117. let textureGPU;
  42118. const format = getFormat( texture );
  42119. if ( texture.isCubeTexture ) {
  42120. textureGPU = this._getDefaultCubeTextureGPU( format );
  42121. } else if ( texture.isVideoTexture ) {
  42122. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  42123. } else {
  42124. textureGPU = this._getDefaultTextureGPU( format );
  42125. }
  42126. this.backend.get( texture ).texture = textureGPU;
  42127. }
  42128. createTexture( texture, options = {} ) {
  42129. const backend = this.backend;
  42130. const textureData = backend.get( texture );
  42131. if ( textureData.initialized ) {
  42132. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  42133. }
  42134. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  42135. if ( options.levels === undefined ) options.levels = 1;
  42136. if ( options.depth === undefined ) options.depth = 1;
  42137. const { width, height, depth, levels } = options;
  42138. if ( texture.isFramebufferTexture ) {
  42139. if ( options.renderTarget ) {
  42140. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  42141. } else {
  42142. options.format = this.backend.utils.getPreferredCanvasFormat();
  42143. }
  42144. }
  42145. const dimension = this._getDimension( texture );
  42146. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  42147. textureData.format = format;
  42148. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  42149. sampleCount = backend.utils.getSampleCount( sampleCount );
  42150. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  42151. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  42152. if ( texture.isStorageTexture === true ) {
  42153. usage |= GPUTextureUsage.STORAGE_BINDING;
  42154. }
  42155. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  42156. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  42157. }
  42158. const textureDescriptorGPU = {
  42159. label: texture.name,
  42160. size: {
  42161. width: width,
  42162. height: height,
  42163. depthOrArrayLayers: depth,
  42164. },
  42165. mipLevelCount: levels,
  42166. sampleCount: primarySampleCount,
  42167. dimension: dimension,
  42168. format: format,
  42169. usage: usage
  42170. };
  42171. // texture creation
  42172. if ( texture.isVideoTexture ) {
  42173. const video = texture.source.data;
  42174. const videoFrame = new VideoFrame( video );
  42175. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  42176. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  42177. videoFrame.close();
  42178. textureData.externalTexture = video;
  42179. } else {
  42180. if ( format === undefined ) {
  42181. console.warn( 'WebGPURenderer: Texture format not supported.' );
  42182. return this.createDefaultTexture( texture );
  42183. }
  42184. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  42185. }
  42186. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  42187. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  42188. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  42189. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  42190. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  42191. }
  42192. textureData.initialized = true;
  42193. textureData.textureDescriptorGPU = textureDescriptorGPU;
  42194. }
  42195. destroyTexture( texture ) {
  42196. const backend = this.backend;
  42197. const textureData = backend.get( texture );
  42198. textureData.texture.destroy();
  42199. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  42200. backend.delete( texture );
  42201. }
  42202. destroySampler( texture ) {
  42203. const backend = this.backend;
  42204. const textureData = backend.get( texture );
  42205. delete textureData.sampler;
  42206. }
  42207. generateMipmaps( texture ) {
  42208. const textureData = this.backend.get( texture );
  42209. if ( texture.isCubeTexture ) {
  42210. for ( let i = 0; i < 6; i ++ ) {
  42211. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42212. }
  42213. } else {
  42214. const depth = texture.image.depth || 1;
  42215. for ( let i = 0; i < depth; i ++ ) {
  42216. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42217. }
  42218. }
  42219. }
  42220. getColorBuffer() {
  42221. if ( this.colorBuffer ) this.colorBuffer.destroy();
  42222. const backend = this.backend;
  42223. const { width, height } = backend.getDrawingBufferSize();
  42224. this.colorBuffer = backend.device.createTexture( {
  42225. label: 'colorBuffer',
  42226. size: {
  42227. width: width,
  42228. height: height,
  42229. depthOrArrayLayers: 1
  42230. },
  42231. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  42232. format: backend.utils.getPreferredCanvasFormat(),
  42233. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  42234. } );
  42235. return this.colorBuffer;
  42236. }
  42237. getDepthBuffer( depth = true, stencil = false ) {
  42238. const backend = this.backend;
  42239. const { width, height } = backend.getDrawingBufferSize();
  42240. const depthTexture = this.depthTexture;
  42241. const depthTextureGPU = backend.get( depthTexture ).texture;
  42242. let format, type;
  42243. if ( stencil ) {
  42244. format = DepthStencilFormat;
  42245. type = UnsignedInt248Type;
  42246. } else if ( depth ) {
  42247. format = DepthFormat;
  42248. type = UnsignedIntType;
  42249. }
  42250. if ( depthTextureGPU !== undefined ) {
  42251. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  42252. return depthTextureGPU;
  42253. }
  42254. this.destroyTexture( depthTexture );
  42255. }
  42256. depthTexture.name = 'depthBuffer';
  42257. depthTexture.format = format;
  42258. depthTexture.type = type;
  42259. depthTexture.image.width = width;
  42260. depthTexture.image.height = height;
  42261. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  42262. return backend.get( depthTexture ).texture;
  42263. }
  42264. updateTexture( texture, options ) {
  42265. const textureData = this.backend.get( texture );
  42266. const { textureDescriptorGPU } = textureData;
  42267. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  42268. return;
  42269. // transfer texture data
  42270. if ( texture.isDataTexture ) {
  42271. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42272. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  42273. for ( let i = 0; i < options.image.depth; i ++ ) {
  42274. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  42275. }
  42276. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  42277. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  42278. } else if ( texture.isCubeTexture ) {
  42279. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  42280. } else if ( texture.isVideoTexture ) {
  42281. const video = texture.source.data;
  42282. textureData.externalTexture = video;
  42283. } else {
  42284. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42285. }
  42286. //
  42287. textureData.version = texture.version;
  42288. if ( texture.onUpdate ) texture.onUpdate( texture );
  42289. }
  42290. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42291. const device = this.backend.device;
  42292. const textureData = this.backend.get( texture );
  42293. const textureGPU = textureData.texture;
  42294. const format = textureData.textureDescriptorGPU.format;
  42295. const bytesPerTexel = this._getBytesPerTexel( format );
  42296. let bytesPerRow = width * bytesPerTexel;
  42297. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  42298. const readBuffer = device.createBuffer(
  42299. {
  42300. size: width * height * bytesPerTexel,
  42301. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  42302. }
  42303. );
  42304. const encoder = device.createCommandEncoder();
  42305. encoder.copyTextureToBuffer(
  42306. {
  42307. texture: textureGPU,
  42308. origin: { x, y, z: faceIndex },
  42309. },
  42310. {
  42311. buffer: readBuffer,
  42312. bytesPerRow: bytesPerRow
  42313. },
  42314. {
  42315. width: width,
  42316. height: height
  42317. }
  42318. );
  42319. const typedArrayType = this._getTypedArrayType( format );
  42320. device.queue.submit( [ encoder.finish() ] );
  42321. await readBuffer.mapAsync( GPUMapMode.READ );
  42322. const buffer = readBuffer.getMappedRange();
  42323. return new typedArrayType( buffer );
  42324. }
  42325. _isEnvironmentTexture( texture ) {
  42326. const mapping = texture.mapping;
  42327. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  42328. }
  42329. _getDefaultTextureGPU( format ) {
  42330. let defaultTexture = this.defaultTexture[ format ];
  42331. if ( defaultTexture === undefined ) {
  42332. const texture = new Texture();
  42333. texture.minFilter = NearestFilter;
  42334. texture.magFilter = NearestFilter;
  42335. this.createTexture( texture, { width: 1, height: 1, format } );
  42336. this.defaultTexture[ format ] = defaultTexture = texture;
  42337. }
  42338. return this.backend.get( defaultTexture ).texture;
  42339. }
  42340. _getDefaultCubeTextureGPU( format ) {
  42341. let defaultCubeTexture = this.defaultTexture[ format ];
  42342. if ( defaultCubeTexture === undefined ) {
  42343. const texture = new CubeTexture();
  42344. texture.minFilter = NearestFilter;
  42345. texture.magFilter = NearestFilter;
  42346. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  42347. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  42348. }
  42349. return this.backend.get( defaultCubeTexture ).texture;
  42350. }
  42351. _getDefaultVideoFrame() {
  42352. let defaultVideoFrame = this.defaultVideoFrame;
  42353. if ( defaultVideoFrame === null ) {
  42354. const init = {
  42355. timestamp: 0,
  42356. codedWidth: 1,
  42357. codedHeight: 1,
  42358. format: 'RGBA',
  42359. };
  42360. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  42361. }
  42362. return defaultVideoFrame;
  42363. }
  42364. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  42365. for ( let i = 0; i < 6; i ++ ) {
  42366. const image = images[ i ];
  42367. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  42368. if ( image.isDataTexture ) {
  42369. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42370. } else {
  42371. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42372. }
  42373. }
  42374. }
  42375. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  42376. const device = this.backend.device;
  42377. device.queue.copyExternalImageToTexture(
  42378. {
  42379. source: image
  42380. }, {
  42381. texture: textureGPU,
  42382. mipLevel: 0,
  42383. origin: { x: 0, y: 0, z: originDepth }
  42384. }, {
  42385. width: image.width,
  42386. height: image.height,
  42387. depthOrArrayLayers: 1
  42388. }
  42389. );
  42390. if ( flipY === true ) {
  42391. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42392. }
  42393. }
  42394. _getPassUtils() {
  42395. let passUtils = this._passUtils;
  42396. if ( passUtils === null ) {
  42397. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  42398. }
  42399. return passUtils;
  42400. }
  42401. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  42402. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  42403. }
  42404. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  42405. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  42406. }
  42407. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  42408. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42409. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  42410. const device = this.backend.device;
  42411. const data = image.data;
  42412. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  42413. const bytesPerRow = image.width * bytesPerTexel;
  42414. device.queue.writeTexture(
  42415. {
  42416. texture: textureGPU,
  42417. mipLevel: 0,
  42418. origin: { x: 0, y: 0, z: originDepth }
  42419. },
  42420. data,
  42421. {
  42422. offset: image.width * image.height * bytesPerTexel * depth,
  42423. bytesPerRow
  42424. },
  42425. {
  42426. width: image.width,
  42427. height: image.height,
  42428. depthOrArrayLayers: 1
  42429. } );
  42430. if ( flipY === true ) {
  42431. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42432. }
  42433. }
  42434. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  42435. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42436. const device = this.backend.device;
  42437. const blockData = this._getBlockData( textureDescriptorGPU.format );
  42438. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  42439. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42440. const mipmap = mipmaps[ i ];
  42441. const width = mipmap.width;
  42442. const height = mipmap.height;
  42443. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  42444. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  42445. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  42446. for ( let j = 0; j < depth; j ++ ) {
  42447. device.queue.writeTexture(
  42448. {
  42449. texture: textureGPU,
  42450. mipLevel: i,
  42451. origin: { x: 0, y: 0, z: j }
  42452. },
  42453. mipmap.data,
  42454. {
  42455. offset: j * bytesPerImage,
  42456. bytesPerRow,
  42457. rowsPerImage: Math.ceil( height / blockData.height )
  42458. },
  42459. {
  42460. width: Math.ceil( width / blockData.width ) * blockData.width,
  42461. height: Math.ceil( height / blockData.height ) * blockData.height,
  42462. depthOrArrayLayers: 1
  42463. }
  42464. );
  42465. }
  42466. }
  42467. }
  42468. _getBlockData( format ) {
  42469. // this method is only relevant for compressed texture formats
  42470. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  42471. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  42472. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  42473. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  42474. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  42475. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  42476. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  42477. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42478. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42479. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42480. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  42481. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  42482. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  42483. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  42484. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42485. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  42486. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  42487. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  42488. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  42489. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  42490. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  42491. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  42492. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  42493. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  42494. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  42495. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  42496. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  42497. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  42498. }
  42499. _convertAddressMode( value ) {
  42500. let addressMode = GPUAddressMode.ClampToEdge;
  42501. if ( value === RepeatWrapping ) {
  42502. addressMode = GPUAddressMode.Repeat;
  42503. } else if ( value === MirroredRepeatWrapping ) {
  42504. addressMode = GPUAddressMode.MirrorRepeat;
  42505. }
  42506. return addressMode;
  42507. }
  42508. _convertFilterMode( value ) {
  42509. let filterMode = GPUFilterMode.Linear;
  42510. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  42511. filterMode = GPUFilterMode.Nearest;
  42512. }
  42513. return filterMode;
  42514. }
  42515. _getBytesPerTexel( format ) {
  42516. // 8-bit formats
  42517. if ( format === GPUTextureFormat.R8Unorm ||
  42518. format === GPUTextureFormat.R8Snorm ||
  42519. format === GPUTextureFormat.R8Uint ||
  42520. format === GPUTextureFormat.R8Sint ) return 1;
  42521. // 16-bit formats
  42522. if ( format === GPUTextureFormat.R16Uint ||
  42523. format === GPUTextureFormat.R16Sint ||
  42524. format === GPUTextureFormat.R16Float ||
  42525. format === GPUTextureFormat.RG8Unorm ||
  42526. format === GPUTextureFormat.RG8Snorm ||
  42527. format === GPUTextureFormat.RG8Uint ||
  42528. format === GPUTextureFormat.RG8Sint ) return 2;
  42529. // 32-bit formats
  42530. if ( format === GPUTextureFormat.R32Uint ||
  42531. format === GPUTextureFormat.R32Sint ||
  42532. format === GPUTextureFormat.R32Float ||
  42533. format === GPUTextureFormat.RG16Uint ||
  42534. format === GPUTextureFormat.RG16Sint ||
  42535. format === GPUTextureFormat.RG16Float ||
  42536. format === GPUTextureFormat.RGBA8Unorm ||
  42537. format === GPUTextureFormat.RGBA8UnormSRGB ||
  42538. format === GPUTextureFormat.RGBA8Snorm ||
  42539. format === GPUTextureFormat.RGBA8Uint ||
  42540. format === GPUTextureFormat.RGBA8Sint ||
  42541. format === GPUTextureFormat.BGRA8Unorm ||
  42542. format === GPUTextureFormat.BGRA8UnormSRGB ||
  42543. // Packed 32-bit formats
  42544. format === GPUTextureFormat.RGB9E5UFloat ||
  42545. format === GPUTextureFormat.RGB10A2Unorm ||
  42546. format === GPUTextureFormat.RG11B10UFloat ||
  42547. format === GPUTextureFormat.Depth32Float ||
  42548. format === GPUTextureFormat.Depth24Plus ||
  42549. format === GPUTextureFormat.Depth24PlusStencil8 ||
  42550. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  42551. // 64-bit formats
  42552. if ( format === GPUTextureFormat.RG32Uint ||
  42553. format === GPUTextureFormat.RG32Sint ||
  42554. format === GPUTextureFormat.RG32Float ||
  42555. format === GPUTextureFormat.RGBA16Uint ||
  42556. format === GPUTextureFormat.RGBA16Sint ||
  42557. format === GPUTextureFormat.RGBA16Float ) return 8;
  42558. // 128-bit formats
  42559. if ( format === GPUTextureFormat.RGBA32Uint ||
  42560. format === GPUTextureFormat.RGBA32Sint ||
  42561. format === GPUTextureFormat.RGBA32Float ) return 16;
  42562. }
  42563. _getTypedArrayType( format ) {
  42564. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  42565. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  42566. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  42567. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  42568. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  42569. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  42570. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  42571. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  42572. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  42573. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  42574. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  42575. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  42576. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  42577. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  42578. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  42579. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  42580. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  42581. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  42582. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  42583. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  42584. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  42585. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  42586. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  42587. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  42588. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  42589. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  42590. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  42591. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  42592. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  42593. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  42594. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  42595. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  42596. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  42597. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  42598. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  42599. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  42600. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  42601. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  42602. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  42603. }
  42604. _getDimension( texture ) {
  42605. let dimension;
  42606. if ( texture.isData3DTexture ) {
  42607. dimension = GPUTextureDimension.ThreeD;
  42608. } else {
  42609. dimension = GPUTextureDimension.TwoD;
  42610. }
  42611. return dimension;
  42612. }
  42613. }
  42614. function getFormat( texture, device = null ) {
  42615. const format = texture.format;
  42616. const type = texture.type;
  42617. const colorSpace = texture.colorSpace;
  42618. let formatGPU;
  42619. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  42620. switch ( format ) {
  42621. case RGBA_S3TC_DXT1_Format:
  42622. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  42623. break;
  42624. case RGBA_S3TC_DXT3_Format:
  42625. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  42626. break;
  42627. case RGBA_S3TC_DXT5_Format:
  42628. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  42629. break;
  42630. case RGB_ETC2_Format:
  42631. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  42632. break;
  42633. case RGBA_ETC2_EAC_Format:
  42634. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  42635. break;
  42636. case RGBA_ASTC_4x4_Format:
  42637. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  42638. break;
  42639. case RGBA_ASTC_5x4_Format:
  42640. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  42641. break;
  42642. case RGBA_ASTC_5x5_Format:
  42643. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  42644. break;
  42645. case RGBA_ASTC_6x5_Format:
  42646. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  42647. break;
  42648. case RGBA_ASTC_6x6_Format:
  42649. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  42650. break;
  42651. case RGBA_ASTC_8x5_Format:
  42652. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  42653. break;
  42654. case RGBA_ASTC_8x6_Format:
  42655. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  42656. break;
  42657. case RGBA_ASTC_8x8_Format:
  42658. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  42659. break;
  42660. case RGBA_ASTC_10x5_Format:
  42661. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  42662. break;
  42663. case RGBA_ASTC_10x6_Format:
  42664. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  42665. break;
  42666. case RGBA_ASTC_10x8_Format:
  42667. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  42668. break;
  42669. case RGBA_ASTC_10x10_Format:
  42670. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  42671. break;
  42672. case RGBA_ASTC_12x10_Format:
  42673. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  42674. break;
  42675. case RGBA_ASTC_12x12_Format:
  42676. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  42677. break;
  42678. default:
  42679. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42680. }
  42681. } else {
  42682. switch ( format ) {
  42683. case RGBAFormat:
  42684. switch ( type ) {
  42685. case ByteType:
  42686. formatGPU = GPUTextureFormat.RGBA8Snorm;
  42687. break;
  42688. case ShortType:
  42689. formatGPU = GPUTextureFormat.RGBA16Sint;
  42690. break;
  42691. case UnsignedShortType:
  42692. formatGPU = GPUTextureFormat.RGBA16Uint;
  42693. break;
  42694. case UnsignedIntType:
  42695. formatGPU = GPUTextureFormat.RGBA32Uint;
  42696. break;
  42697. case IntType:
  42698. formatGPU = GPUTextureFormat.RGBA32Sint;
  42699. break;
  42700. case UnsignedByteType:
  42701. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  42702. break;
  42703. case HalfFloatType:
  42704. formatGPU = GPUTextureFormat.RGBA16Float;
  42705. break;
  42706. case FloatType:
  42707. formatGPU = GPUTextureFormat.RGBA32Float;
  42708. break;
  42709. default:
  42710. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  42711. }
  42712. break;
  42713. case RGBFormat:
  42714. switch ( type ) {
  42715. case UnsignedInt5999Type:
  42716. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  42717. break;
  42718. default:
  42719. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  42720. }
  42721. break;
  42722. case RedFormat:
  42723. switch ( type ) {
  42724. case ByteType:
  42725. formatGPU = GPUTextureFormat.R8Snorm;
  42726. break;
  42727. case ShortType:
  42728. formatGPU = GPUTextureFormat.R16Sint;
  42729. break;
  42730. case UnsignedShortType:
  42731. formatGPU = GPUTextureFormat.R16Uint;
  42732. break;
  42733. case UnsignedIntType:
  42734. formatGPU = GPUTextureFormat.R32Uint;
  42735. break;
  42736. case IntType:
  42737. formatGPU = GPUTextureFormat.R32Sint;
  42738. break;
  42739. case UnsignedByteType:
  42740. formatGPU = GPUTextureFormat.R8Unorm;
  42741. break;
  42742. case HalfFloatType:
  42743. formatGPU = GPUTextureFormat.R16Float;
  42744. break;
  42745. case FloatType:
  42746. formatGPU = GPUTextureFormat.R32Float;
  42747. break;
  42748. default:
  42749. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  42750. }
  42751. break;
  42752. case RGFormat:
  42753. switch ( type ) {
  42754. case ByteType:
  42755. formatGPU = GPUTextureFormat.RG8Snorm;
  42756. break;
  42757. case ShortType:
  42758. formatGPU = GPUTextureFormat.RG16Sint;
  42759. break;
  42760. case UnsignedShortType:
  42761. formatGPU = GPUTextureFormat.RG16Uint;
  42762. break;
  42763. case UnsignedIntType:
  42764. formatGPU = GPUTextureFormat.RG32Uint;
  42765. break;
  42766. case IntType:
  42767. formatGPU = GPUTextureFormat.RG32Sint;
  42768. break;
  42769. case UnsignedByteType:
  42770. formatGPU = GPUTextureFormat.RG8Unorm;
  42771. break;
  42772. case HalfFloatType:
  42773. formatGPU = GPUTextureFormat.RG16Float;
  42774. break;
  42775. case FloatType:
  42776. formatGPU = GPUTextureFormat.RG32Float;
  42777. break;
  42778. default:
  42779. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  42780. }
  42781. break;
  42782. case DepthFormat:
  42783. switch ( type ) {
  42784. case UnsignedShortType:
  42785. formatGPU = GPUTextureFormat.Depth16Unorm;
  42786. break;
  42787. case UnsignedIntType:
  42788. formatGPU = GPUTextureFormat.Depth24Plus;
  42789. break;
  42790. case FloatType:
  42791. formatGPU = GPUTextureFormat.Depth32Float;
  42792. break;
  42793. default:
  42794. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  42795. }
  42796. break;
  42797. case DepthStencilFormat:
  42798. switch ( type ) {
  42799. case UnsignedInt248Type:
  42800. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  42801. break;
  42802. case FloatType:
  42803. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  42804. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  42805. }
  42806. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  42807. break;
  42808. default:
  42809. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  42810. }
  42811. break;
  42812. case RedIntegerFormat:
  42813. switch ( type ) {
  42814. case IntType:
  42815. formatGPU = GPUTextureFormat.R32Sint;
  42816. break;
  42817. case UnsignedIntType:
  42818. formatGPU = GPUTextureFormat.R32Uint;
  42819. break;
  42820. default:
  42821. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  42822. }
  42823. break;
  42824. case RGIntegerFormat:
  42825. switch ( type ) {
  42826. case IntType:
  42827. formatGPU = GPUTextureFormat.RG32Sint;
  42828. break;
  42829. case UnsignedIntType:
  42830. formatGPU = GPUTextureFormat.RG32Uint;
  42831. break;
  42832. default:
  42833. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  42834. }
  42835. break;
  42836. case RGBAIntegerFormat:
  42837. switch ( type ) {
  42838. case IntType:
  42839. formatGPU = GPUTextureFormat.RGBA32Sint;
  42840. break;
  42841. case UnsignedIntType:
  42842. formatGPU = GPUTextureFormat.RGBA32Uint;
  42843. break;
  42844. default:
  42845. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  42846. }
  42847. break;
  42848. default:
  42849. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42850. }
  42851. }
  42852. return formatGPU;
  42853. }
  42854. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  42855. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  42856. const wgslTypeLib$1 = {
  42857. 'f32': 'float',
  42858. 'i32': 'int',
  42859. 'u32': 'uint',
  42860. 'bool': 'bool',
  42861. 'vec2<f32>': 'vec2',
  42862. 'vec2<i32>': 'ivec2',
  42863. 'vec2<u32>': 'uvec2',
  42864. 'vec2<bool>': 'bvec2',
  42865. 'vec2f': 'vec2',
  42866. 'vec2i': 'ivec2',
  42867. 'vec2u': 'uvec2',
  42868. 'vec2b': 'bvec2',
  42869. 'vec3<f32>': 'vec3',
  42870. 'vec3<i32>': 'ivec3',
  42871. 'vec3<u32>': 'uvec3',
  42872. 'vec3<bool>': 'bvec3',
  42873. 'vec3f': 'vec3',
  42874. 'vec3i': 'ivec3',
  42875. 'vec3u': 'uvec3',
  42876. 'vec3b': 'bvec3',
  42877. 'vec4<f32>': 'vec4',
  42878. 'vec4<i32>': 'ivec4',
  42879. 'vec4<u32>': 'uvec4',
  42880. 'vec4<bool>': 'bvec4',
  42881. 'vec4f': 'vec4',
  42882. 'vec4i': 'ivec4',
  42883. 'vec4u': 'uvec4',
  42884. 'vec4b': 'bvec4',
  42885. 'mat2x2<f32>': 'mat2',
  42886. 'mat2x2f': 'mat2',
  42887. 'mat3x3<f32>': 'mat3',
  42888. 'mat3x3f': 'mat3',
  42889. 'mat4x4<f32>': 'mat4',
  42890. 'mat4x4f': 'mat4',
  42891. 'sampler': 'sampler',
  42892. 'texture_1d': 'texture',
  42893. 'texture_2d': 'texture',
  42894. 'texture_2d_array': 'texture',
  42895. 'texture_multisampled_2d': 'cubeTexture',
  42896. 'texture_depth_2d': 'depthTexture',
  42897. 'texture_3d': 'texture3D',
  42898. 'texture_cube': 'cubeTexture',
  42899. 'texture_cube_array': 'cubeTexture',
  42900. 'texture_storage_1d': 'storageTexture',
  42901. 'texture_storage_2d': 'storageTexture',
  42902. 'texture_storage_2d_array': 'storageTexture',
  42903. 'texture_storage_3d': 'storageTexture'
  42904. };
  42905. const parse = ( source ) => {
  42906. source = source.trim();
  42907. const declaration = source.match( declarationRegexp );
  42908. if ( declaration !== null && declaration.length === 4 ) {
  42909. const inputsCode = declaration[ 2 ];
  42910. const propsMatches = [];
  42911. let match = null;
  42912. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  42913. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  42914. }
  42915. // Process matches to correctly pair names and types
  42916. const inputs = [];
  42917. for ( let i = 0; i < propsMatches.length; i ++ ) {
  42918. const { name, type } = propsMatches[ i ];
  42919. let resolvedType = type;
  42920. if ( resolvedType.startsWith( 'ptr' ) ) {
  42921. resolvedType = 'pointer';
  42922. } else {
  42923. if ( resolvedType.startsWith( 'texture' ) ) {
  42924. resolvedType = type.split( '<' )[ 0 ];
  42925. }
  42926. resolvedType = wgslTypeLib$1[ resolvedType ];
  42927. }
  42928. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  42929. }
  42930. const blockCode = source.substring( declaration[ 0 ].length );
  42931. const outputType = declaration[ 3 ] || 'void';
  42932. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  42933. const type = wgslTypeLib$1[ outputType ] || outputType;
  42934. return {
  42935. type,
  42936. inputs,
  42937. name,
  42938. inputsCode,
  42939. blockCode,
  42940. outputType
  42941. };
  42942. } else {
  42943. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  42944. }
  42945. };
  42946. class WGSLNodeFunction extends NodeFunction {
  42947. constructor( source ) {
  42948. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  42949. super( type, inputs, name );
  42950. this.inputsCode = inputsCode;
  42951. this.blockCode = blockCode;
  42952. this.outputType = outputType;
  42953. }
  42954. getCode( name = this.name ) {
  42955. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  42956. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  42957. }
  42958. }
  42959. class WGSLNodeParser extends NodeParser {
  42960. parseFunction( source ) {
  42961. return new WGSLNodeFunction( source );
  42962. }
  42963. }
  42964. // GPUShaderStage is not defined in browsers not supporting WebGPU
  42965. const GPUShaderStage = self.GPUShaderStage;
  42966. const gpuShaderStageLib = {
  42967. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  42968. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  42969. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  42970. };
  42971. const supports = {
  42972. instance: true,
  42973. swizzleAssign: false,
  42974. storageBuffer: true
  42975. };
  42976. const wgslFnOpLib = {
  42977. '^^': 'tsl_xor'
  42978. };
  42979. const wgslTypeLib = {
  42980. float: 'f32',
  42981. int: 'i32',
  42982. uint: 'u32',
  42983. bool: 'bool',
  42984. color: 'vec3<f32>',
  42985. vec2: 'vec2<f32>',
  42986. ivec2: 'vec2<i32>',
  42987. uvec2: 'vec2<u32>',
  42988. bvec2: 'vec2<bool>',
  42989. vec3: 'vec3<f32>',
  42990. ivec3: 'vec3<i32>',
  42991. uvec3: 'vec3<u32>',
  42992. bvec3: 'vec3<bool>',
  42993. vec4: 'vec4<f32>',
  42994. ivec4: 'vec4<i32>',
  42995. uvec4: 'vec4<u32>',
  42996. bvec4: 'vec4<bool>',
  42997. mat2: 'mat2x2<f32>',
  42998. mat3: 'mat3x3<f32>',
  42999. mat4: 'mat4x4<f32>'
  43000. };
  43001. const wgslPolyfill = {
  43002. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  43003. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  43004. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  43005. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  43006. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  43007. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  43008. 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 ); }' ),
  43009. 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 ); }' ),
  43010. 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 ); }' ),
  43011. repeatWrapping: new CodeNode( /* wgsl */`
  43012. fn tsl_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  43013. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  43014. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  43015. }
  43016. ` ),
  43017. biquadraticTexture: new CodeNode( /* wgsl */`
  43018. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  43019. let iRes = vec2i( textureDimensions( map, level ) );
  43020. let res = vec2f( iRes );
  43021. let uvScaled = coord * res;
  43022. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  43023. // https://www.shadertoy.com/view/WtyXRy
  43024. let uv = uvWrapping - 0.5;
  43025. let iuv = floor( uv );
  43026. let f = fract( uv );
  43027. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  43028. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  43029. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  43030. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  43031. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  43032. }
  43033. ` )
  43034. };
  43035. const wgslMethods = {
  43036. dFdx: 'dpdx',
  43037. dFdy: '- dpdy',
  43038. mod_float: 'tsl_mod_float',
  43039. mod_vec2: 'tsl_mod_vec2',
  43040. mod_vec3: 'tsl_mod_vec3',
  43041. mod_vec4: 'tsl_mod_vec4',
  43042. equals_bool: 'tsl_equals_bool',
  43043. equals_bvec2: 'tsl_equals_bvec2',
  43044. equals_bvec3: 'tsl_equals_bvec3',
  43045. equals_bvec4: 'tsl_equals_bvec4',
  43046. inversesqrt: 'inverseSqrt',
  43047. bitcast: 'bitcast<f32>'
  43048. };
  43049. // WebGPU issue: does not support pow() with negative base on Windows
  43050. if ( /Windows/g.test( navigator.userAgent ) ) {
  43051. 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 ); }' );
  43052. 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 ] );
  43053. 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 ] );
  43054. 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 ] );
  43055. wgslMethods.pow_float = 'tsl_pow_float';
  43056. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  43057. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  43058. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  43059. }
  43060. //
  43061. let diagnostics = '';
  43062. if ( /Firefox|Deno/g.test( navigator.userAgent ) !== true ) {
  43063. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  43064. }
  43065. //
  43066. class WGSLNodeBuilder extends NodeBuilder {
  43067. constructor( object, renderer ) {
  43068. super( object, renderer, new WGSLNodeParser() );
  43069. this.uniformGroups = {};
  43070. this.builtins = {};
  43071. this.directives = {};
  43072. this.scopedArrays = new Map();
  43073. }
  43074. needsToWorkingColorSpace( texture ) {
  43075. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  43076. }
  43077. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43078. if ( shaderStage === 'fragment' ) {
  43079. if ( depthSnippet ) {
  43080. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  43081. } else {
  43082. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  43083. }
  43084. } else if ( this.isFilteredTexture( texture ) ) {
  43085. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  43086. } else {
  43087. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  43088. }
  43089. }
  43090. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  43091. if ( shaderStage === 'fragment' ) {
  43092. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  43093. } else {
  43094. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  43095. }
  43096. }
  43097. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43098. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  43099. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  43100. } else if ( this.isFilteredTexture( texture ) ) {
  43101. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  43102. } else {
  43103. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  43104. }
  43105. }
  43106. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  43107. this._include( 'biquadraticTexture' );
  43108. return `tsl_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  43109. }
  43110. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  43111. this._include( 'repeatWrapping' );
  43112. const dimension = texture.isMultisampleRenderTargetTexture === true ? `textureDimensions( ${ textureProperty } )` : `textureDimensions( ${ textureProperty }, 0 )`;
  43113. return `textureLoad( ${ textureProperty }, tsl_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  43114. }
  43115. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  43116. if ( depthSnippet ) {
  43117. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  43118. } else {
  43119. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  43120. }
  43121. }
  43122. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  43123. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  43124. }
  43125. isUnfilterable( texture ) {
  43126. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) || texture.isMultisampleRenderTargetTexture === true;
  43127. }
  43128. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43129. let snippet = null;
  43130. if ( texture.isVideoTexture === true ) {
  43131. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  43132. } else if ( this.isUnfilterable( texture ) ) {
  43133. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  43134. } else {
  43135. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  43136. }
  43137. return snippet;
  43138. }
  43139. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43140. if ( shaderStage === 'fragment' ) {
  43141. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  43142. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  43143. } else {
  43144. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  43145. }
  43146. }
  43147. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43148. if ( shaderStage === 'fragment' ) {
  43149. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  43150. } else {
  43151. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  43152. }
  43153. }
  43154. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43155. let snippet = null;
  43156. if ( texture.isVideoTexture === true ) {
  43157. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  43158. } else {
  43159. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  43160. }
  43161. return snippet;
  43162. }
  43163. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43164. if ( shaderStage === 'fragment' ) {
  43165. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  43166. } else {
  43167. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  43168. }
  43169. }
  43170. getPropertyName( node, shaderStage = this.shaderStage ) {
  43171. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  43172. if ( shaderStage === 'vertex' ) {
  43173. return `varyings.${ node.name }`;
  43174. }
  43175. } else if ( node.isNodeUniform === true ) {
  43176. const name = node.name;
  43177. const type = node.type;
  43178. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  43179. return name;
  43180. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  43181. return `NodeBuffer_${ node.id }.${name}`;
  43182. } else {
  43183. return node.groupNode.name + '.' + name;
  43184. }
  43185. }
  43186. return super.getPropertyName( node );
  43187. }
  43188. getOutputStructName() {
  43189. return 'output';
  43190. }
  43191. _getUniformGroupCount( shaderStage ) {
  43192. return Object.keys( this.uniforms[ shaderStage ] ).length;
  43193. }
  43194. getFunctionOperator( op ) {
  43195. const fnOp = wgslFnOpLib[ op ];
  43196. if ( fnOp !== undefined ) {
  43197. this._include( fnOp );
  43198. return fnOp;
  43199. }
  43200. return null;
  43201. }
  43202. getStorageAccess( node ) {
  43203. if ( node.isStorageTextureNode ) {
  43204. switch ( node.access ) {
  43205. case GPUStorageTextureAccess.ReadOnly:
  43206. return 'read';
  43207. case GPUStorageTextureAccess.WriteOnly:
  43208. return 'write';
  43209. default:
  43210. return 'read_write';
  43211. }
  43212. } else {
  43213. switch ( node.access ) {
  43214. case GPUBufferBindingType.Storage:
  43215. return 'read_write';
  43216. case GPUBufferBindingType.ReadOnlyStorage:
  43217. return 'read';
  43218. default:
  43219. return 'write';
  43220. }
  43221. }
  43222. }
  43223. getUniformFromNode( node, type, shaderStage, name = null ) {
  43224. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  43225. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  43226. if ( nodeData.uniformGPU === undefined ) {
  43227. let uniformGPU;
  43228. const group = node.groupNode;
  43229. const groupName = group.name;
  43230. const bindings = this.getBindGroupArray( groupName, shaderStage );
  43231. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  43232. let texture = null;
  43233. if ( type === 'texture' || type === 'storageTexture' ) {
  43234. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  43235. } else if ( type === 'cubeTexture' ) {
  43236. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  43237. } else if ( type === 'texture3D' ) {
  43238. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  43239. }
  43240. texture.store = node.isStorageTextureNode === true;
  43241. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43242. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  43243. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  43244. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43245. bindings.push( sampler, texture );
  43246. uniformGPU = [ sampler, texture ];
  43247. } else {
  43248. bindings.push( texture );
  43249. uniformGPU = [ texture ];
  43250. }
  43251. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  43252. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  43253. const buffer = new bufferClass( node, group );
  43254. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43255. bindings.push( buffer );
  43256. uniformGPU = buffer;
  43257. } else {
  43258. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  43259. let uniformsGroup = uniformsStage[ groupName ];
  43260. if ( uniformsGroup === undefined ) {
  43261. uniformsGroup = new NodeUniformsGroup( groupName, group );
  43262. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43263. uniformsStage[ groupName ] = uniformsGroup;
  43264. bindings.push( uniformsGroup );
  43265. }
  43266. uniformGPU = this.getNodeUniform( uniformNode, type );
  43267. uniformsGroup.addUniform( uniformGPU );
  43268. }
  43269. nodeData.uniformGPU = uniformGPU;
  43270. }
  43271. return uniformNode;
  43272. }
  43273. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  43274. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  43275. if ( map.has( name ) === false ) {
  43276. map.set( name, {
  43277. name,
  43278. property,
  43279. type
  43280. } );
  43281. }
  43282. return property;
  43283. }
  43284. hasBuiltin( name, shaderStage = this.shaderStage ) {
  43285. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  43286. }
  43287. getVertexIndex() {
  43288. if ( this.shaderStage === 'vertex' ) {
  43289. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  43290. }
  43291. return 'vertexIndex';
  43292. }
  43293. buildFunctionCode( shaderNode ) {
  43294. const layout = shaderNode.layout;
  43295. const flowData = this.flowShaderNode( shaderNode );
  43296. const parameters = [];
  43297. for ( const input of layout.inputs ) {
  43298. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  43299. }
  43300. //
  43301. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  43302. ${ flowData.vars }
  43303. ${ flowData.code }
  43304. `;
  43305. if ( flowData.result ) {
  43306. code += `\treturn ${ flowData.result };\n`;
  43307. }
  43308. code += '\n}\n';
  43309. //
  43310. return code;
  43311. }
  43312. getInstanceIndex() {
  43313. if ( this.shaderStage === 'vertex' ) {
  43314. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  43315. }
  43316. return 'instanceIndex';
  43317. }
  43318. getInvocationLocalIndex() {
  43319. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  43320. }
  43321. getSubgroupSize() {
  43322. this.enableSubGroups();
  43323. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  43324. }
  43325. getInvocationSubgroupIndex() {
  43326. this.enableSubGroups();
  43327. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  43328. }
  43329. getSubgroupIndex() {
  43330. this.enableSubGroups();
  43331. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  43332. }
  43333. getDrawIndex() {
  43334. return null;
  43335. }
  43336. getFrontFacing() {
  43337. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  43338. }
  43339. getFragCoord() {
  43340. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  43341. }
  43342. getFragDepth() {
  43343. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  43344. }
  43345. isFlipY() {
  43346. return false;
  43347. }
  43348. enableDirective( name, shaderStage = this.shaderStage ) {
  43349. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  43350. stage.add( name );
  43351. }
  43352. getDirectives( shaderStage ) {
  43353. const snippets = [];
  43354. const directives = this.directives[ shaderStage ];
  43355. if ( directives !== undefined ) {
  43356. for ( const directive of directives ) {
  43357. snippets.push( `enable ${directive};` );
  43358. }
  43359. }
  43360. return snippets.join( '\n' );
  43361. }
  43362. enableSubGroups() {
  43363. this.enableDirective( 'subgroups' );
  43364. }
  43365. enableSubgroupsF16() {
  43366. this.enableDirective( 'subgroups-f16' );
  43367. }
  43368. enableClipDistances() {
  43369. this.enableDirective( 'clip_distances' );
  43370. }
  43371. enableShaderF16() {
  43372. this.enableDirective( 'f16' );
  43373. }
  43374. enableDualSourceBlending() {
  43375. this.enableDirective( 'dual_source_blending' );
  43376. }
  43377. getBuiltins( shaderStage ) {
  43378. const snippets = [];
  43379. const builtins = this.builtins[ shaderStage ];
  43380. if ( builtins !== undefined ) {
  43381. for ( const { name, property, type } of builtins.values() ) {
  43382. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  43383. }
  43384. }
  43385. return snippets.join( ',\n\t' );
  43386. }
  43387. getScopedArray( name, scope, bufferType, bufferCount ) {
  43388. if ( this.scopedArrays.has( name ) === false ) {
  43389. this.scopedArrays.set( name, {
  43390. name,
  43391. scope,
  43392. bufferType,
  43393. bufferCount
  43394. } );
  43395. }
  43396. return name;
  43397. }
  43398. getScopedArrays( shaderStage ) {
  43399. if ( shaderStage !== 'compute' ) {
  43400. return;
  43401. }
  43402. const snippets = [];
  43403. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  43404. const type = this.getType( bufferType );
  43405. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  43406. }
  43407. return snippets.join( '\n' );
  43408. }
  43409. getAttributes( shaderStage ) {
  43410. const snippets = [];
  43411. if ( shaderStage === 'compute' ) {
  43412. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  43413. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  43414. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  43415. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  43416. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  43417. this.enableDirective( 'subgroups', shaderStage );
  43418. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  43419. }
  43420. }
  43421. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43422. const builtins = this.getBuiltins( 'attribute' );
  43423. if ( builtins ) snippets.push( builtins );
  43424. const attributes = this.getAttributesArray();
  43425. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  43426. const attribute = attributes[ index ];
  43427. const name = attribute.name;
  43428. const type = this.getType( attribute.type );
  43429. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  43430. }
  43431. }
  43432. return snippets.join( ',\n\t' );
  43433. }
  43434. getStructMembers( struct ) {
  43435. const snippets = [];
  43436. const members = struct.getMemberTypes();
  43437. for ( let i = 0; i < members.length; i ++ ) {
  43438. const member = members[ i ];
  43439. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  43440. }
  43441. const builtins = this.getBuiltins( 'output' );
  43442. if ( builtins ) snippets.push( '\t' + builtins );
  43443. return snippets.join( ',\n' );
  43444. }
  43445. getStructs( shaderStage ) {
  43446. const snippets = [];
  43447. const structs = this.structs[ shaderStage ];
  43448. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  43449. const struct = structs[ index ];
  43450. const name = struct.name;
  43451. let snippet = `\struct ${ name } {\n`;
  43452. snippet += this.getStructMembers( struct );
  43453. snippet += '\n}';
  43454. snippets.push( snippet );
  43455. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  43456. }
  43457. return snippets.join( '\n\n' );
  43458. }
  43459. getVar( type, name ) {
  43460. return `var ${ name } : ${ this.getType( type ) }`;
  43461. }
  43462. getVars( shaderStage ) {
  43463. const snippets = [];
  43464. const vars = this.vars[ shaderStage ];
  43465. if ( vars !== undefined ) {
  43466. for ( const variable of vars ) {
  43467. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  43468. }
  43469. }
  43470. return `\n${ snippets.join( '\n' ) }\n`;
  43471. }
  43472. getVaryings( shaderStage ) {
  43473. const snippets = [];
  43474. if ( shaderStage === 'vertex' ) {
  43475. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  43476. }
  43477. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  43478. const varyings = this.varyings;
  43479. const vars = this.vars[ shaderStage ];
  43480. for ( let index = 0; index < varyings.length; index ++ ) {
  43481. const varying = varyings[ index ];
  43482. if ( varying.needsInterpolation ) {
  43483. let attributesSnippet = `@location( ${index} )`;
  43484. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  43485. attributesSnippet += ' @interpolate( flat )';
  43486. }
  43487. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  43488. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  43489. vars.push( varying );
  43490. }
  43491. }
  43492. }
  43493. const builtins = this.getBuiltins( shaderStage );
  43494. if ( builtins ) snippets.push( builtins );
  43495. const code = snippets.join( ',\n\t' );
  43496. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  43497. }
  43498. getUniforms( shaderStage ) {
  43499. const uniforms = this.uniforms[ shaderStage ];
  43500. const bindingSnippets = [];
  43501. const bufferSnippets = [];
  43502. const structSnippets = [];
  43503. const uniformGroups = {};
  43504. for ( const uniform of uniforms ) {
  43505. const groupName = uniform.groupNode.name;
  43506. const uniformIndexes = this.bindingsIndexes[ groupName ];
  43507. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  43508. const texture = uniform.node.value;
  43509. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  43510. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  43511. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  43512. } else {
  43513. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  43514. }
  43515. }
  43516. let textureType;
  43517. let multisampled = '';
  43518. if ( texture.isMultisampleRenderTargetTexture === true ) {
  43519. multisampled = '_multisampled';
  43520. }
  43521. if ( texture.isCubeTexture === true ) {
  43522. textureType = 'texture_cube<f32>';
  43523. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43524. textureType = 'texture_2d_array<f32>';
  43525. } else if ( texture.isDepthTexture === true ) {
  43526. textureType = `texture_depth${multisampled}_2d`;
  43527. } else if ( texture.isVideoTexture === true ) {
  43528. textureType = 'texture_external';
  43529. } else if ( texture.isData3DTexture === true ) {
  43530. textureType = 'texture_3d<f32>';
  43531. } else if ( uniform.node.isStorageTextureNode === true ) {
  43532. const format = getFormat( texture );
  43533. const access = this.getStorageAccess( uniform.node );
  43534. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  43535. } else {
  43536. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  43537. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  43538. }
  43539. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  43540. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  43541. const bufferNode = uniform.node;
  43542. const bufferType = this.getType( bufferNode.bufferType );
  43543. const bufferCount = bufferNode.bufferCount;
  43544. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  43545. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  43546. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  43547. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  43548. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  43549. } else {
  43550. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  43551. const groupName = uniform.groupNode.name;
  43552. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  43553. index: uniformIndexes.binding ++,
  43554. id: uniformIndexes.group,
  43555. snippets: []
  43556. } );
  43557. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  43558. }
  43559. }
  43560. for ( const name in uniformGroups ) {
  43561. const group = uniformGroups[ name ];
  43562. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  43563. }
  43564. let code = bindingSnippets.join( '\n' );
  43565. code += bufferSnippets.join( '\n' );
  43566. code += structSnippets.join( '\n' );
  43567. return code;
  43568. }
  43569. buildCode() {
  43570. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  43571. this.sortBindingGroups();
  43572. for ( const shaderStage in shadersData ) {
  43573. const stageData = shadersData[ shaderStage ];
  43574. stageData.uniforms = this.getUniforms( shaderStage );
  43575. stageData.attributes = this.getAttributes( shaderStage );
  43576. stageData.varyings = this.getVaryings( shaderStage );
  43577. stageData.structs = this.getStructs( shaderStage );
  43578. stageData.vars = this.getVars( shaderStage );
  43579. stageData.codes = this.getCodes( shaderStage );
  43580. stageData.directives = this.getDirectives( shaderStage );
  43581. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  43582. //
  43583. let flow = '// code\n\n';
  43584. flow += this.flowCode[ shaderStage ];
  43585. const flowNodes = this.flowNodes[ shaderStage ];
  43586. const mainNode = flowNodes[ flowNodes.length - 1 ];
  43587. const outputNode = mainNode.outputNode;
  43588. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  43589. for ( const node of flowNodes ) {
  43590. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  43591. const slotName = node.name;
  43592. if ( slotName ) {
  43593. if ( flow.length > 0 ) flow += '\n';
  43594. flow += `\t// flow -> ${ slotName }\n\t`;
  43595. }
  43596. flow += `${ flowSlotData.code }\n\t`;
  43597. if ( node === mainNode && shaderStage !== 'compute' ) {
  43598. flow += '// result\n\n\t';
  43599. if ( shaderStage === 'vertex' ) {
  43600. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  43601. } else if ( shaderStage === 'fragment' ) {
  43602. if ( isOutputStruct ) {
  43603. stageData.returnType = outputNode.nodeType;
  43604. flow += `return ${ flowSlotData.result };`;
  43605. } else {
  43606. let structSnippet = '\t@location(0) color: vec4<f32>';
  43607. const builtins = this.getBuiltins( 'output' );
  43608. if ( builtins ) structSnippet += ',\n\t' + builtins;
  43609. stageData.returnType = 'OutputStruct';
  43610. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  43611. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  43612. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  43613. }
  43614. }
  43615. }
  43616. }
  43617. stageData.flow = flow;
  43618. }
  43619. if ( this.material !== null ) {
  43620. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  43621. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  43622. } else {
  43623. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  43624. }
  43625. }
  43626. getMethod( method, output = null ) {
  43627. let wgslMethod;
  43628. if ( output !== null ) {
  43629. wgslMethod = this._getWGSLMethod( method + '_' + output );
  43630. }
  43631. if ( wgslMethod === undefined ) {
  43632. wgslMethod = this._getWGSLMethod( method );
  43633. }
  43634. return wgslMethod || method;
  43635. }
  43636. getType( type ) {
  43637. return wgslTypeLib[ type ] || type;
  43638. }
  43639. isAvailable( name ) {
  43640. let result = supports[ name ];
  43641. if ( result === undefined ) {
  43642. if ( name === 'float32Filterable' ) {
  43643. result = this.renderer.hasFeature( 'float32-filterable' );
  43644. }
  43645. supports[ name ] = result;
  43646. }
  43647. return result;
  43648. }
  43649. _getWGSLMethod( method ) {
  43650. if ( wgslPolyfill[ method ] !== undefined ) {
  43651. this._include( method );
  43652. }
  43653. return wgslMethods[ method ];
  43654. }
  43655. _include( name ) {
  43656. const codeNode = wgslPolyfill[ name ];
  43657. codeNode.build( this );
  43658. if ( this.currentFunctionNode !== null ) {
  43659. this.currentFunctionNode.includes.push( codeNode );
  43660. }
  43661. return codeNode;
  43662. }
  43663. _getWGSLVertexCode( shaderData ) {
  43664. return `${ this.getSignature() }
  43665. // directives
  43666. ${shaderData.directives}
  43667. // uniforms
  43668. ${shaderData.uniforms}
  43669. // varyings
  43670. ${shaderData.varyings}
  43671. var<private> varyings : VaryingsStruct;
  43672. // codes
  43673. ${shaderData.codes}
  43674. @vertex
  43675. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  43676. // vars
  43677. ${shaderData.vars}
  43678. // flow
  43679. ${shaderData.flow}
  43680. return varyings;
  43681. }
  43682. `;
  43683. }
  43684. _getWGSLFragmentCode( shaderData ) {
  43685. return `${ this.getSignature() }
  43686. // global
  43687. ${ diagnostics }
  43688. // uniforms
  43689. ${shaderData.uniforms}
  43690. // structs
  43691. ${shaderData.structs}
  43692. // codes
  43693. ${shaderData.codes}
  43694. @fragment
  43695. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  43696. // vars
  43697. ${shaderData.vars}
  43698. // flow
  43699. ${shaderData.flow}
  43700. }
  43701. `;
  43702. }
  43703. _getWGSLComputeCode( shaderData, workgroupSize ) {
  43704. return `${ this.getSignature() }
  43705. // directives
  43706. ${shaderData.directives}
  43707. // system
  43708. var<private> instanceIndex : u32;
  43709. // locals
  43710. ${shaderData.scopedArrays}
  43711. // uniforms
  43712. ${shaderData.uniforms}
  43713. // codes
  43714. ${shaderData.codes}
  43715. @compute @workgroup_size( ${workgroupSize} )
  43716. fn main( ${shaderData.attributes} ) {
  43717. // system
  43718. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  43719. // vars
  43720. ${shaderData.vars}
  43721. // flow
  43722. ${shaderData.flow}
  43723. }
  43724. `;
  43725. }
  43726. _getWGSLStruct( name, vars ) {
  43727. return `
  43728. struct ${name} {
  43729. ${vars}
  43730. };`;
  43731. }
  43732. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  43733. const structName = name + 'Struct';
  43734. const structSnippet = this._getWGSLStruct( structName, vars );
  43735. return `${structSnippet}
  43736. @binding( ${binding} ) @group( ${group} )
  43737. var<${access}> ${name} : ${structName};`;
  43738. }
  43739. }
  43740. class WebGPUUtils {
  43741. constructor( backend ) {
  43742. this.backend = backend;
  43743. }
  43744. getCurrentDepthStencilFormat( renderContext ) {
  43745. let format;
  43746. if ( renderContext.depthTexture !== null ) {
  43747. format = this.getTextureFormatGPU( renderContext.depthTexture );
  43748. } else if ( renderContext.depth && renderContext.stencil ) {
  43749. format = GPUTextureFormat.Depth24PlusStencil8;
  43750. } else if ( renderContext.depth ) {
  43751. format = GPUTextureFormat.Depth24Plus;
  43752. }
  43753. return format;
  43754. }
  43755. getTextureFormatGPU( texture ) {
  43756. return this.backend.get( texture ).format;
  43757. }
  43758. getCurrentColorFormat( renderContext ) {
  43759. let format;
  43760. if ( renderContext.textures !== null ) {
  43761. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  43762. } else {
  43763. format = this.getPreferredCanvasFormat(); // default context format
  43764. }
  43765. return format;
  43766. }
  43767. getCurrentColorSpace( renderContext ) {
  43768. if ( renderContext.textures !== null ) {
  43769. return renderContext.textures[ 0 ].colorSpace;
  43770. }
  43771. return this.backend.renderer.outputColorSpace;
  43772. }
  43773. getPrimitiveTopology( object, material ) {
  43774. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  43775. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  43776. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  43777. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  43778. }
  43779. getSampleCount( sampleCount ) {
  43780. let count = 1;
  43781. if ( sampleCount > 1 ) {
  43782. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  43783. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  43784. if ( count === 2 ) {
  43785. count = 4;
  43786. }
  43787. }
  43788. return count;
  43789. }
  43790. getSampleCountRenderContext( renderContext ) {
  43791. if ( renderContext.textures !== null ) {
  43792. return this.getSampleCount( renderContext.sampleCount );
  43793. }
  43794. return this.getSampleCount( this.backend.renderer.samples );
  43795. }
  43796. getPreferredCanvasFormat() {
  43797. // TODO: Remove this check when Quest 34.5 is out
  43798. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  43799. if ( navigator.userAgent.includes( 'Quest' ) ) {
  43800. return GPUTextureFormat.BGRA8Unorm;
  43801. } else {
  43802. return navigator.gpu.getPreferredCanvasFormat();
  43803. }
  43804. }
  43805. }
  43806. const typedArraysToVertexFormatPrefix = new Map( [
  43807. [ Int8Array, [ 'sint8', 'snorm8' ]],
  43808. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  43809. [ Int16Array, [ 'sint16', 'snorm16' ]],
  43810. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  43811. [ Int32Array, [ 'sint32', 'snorm32' ]],
  43812. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  43813. [ Float32Array, [ 'float32', ]],
  43814. ] );
  43815. const typedAttributeToVertexFormatPrefix = new Map( [
  43816. [ Float16BufferAttribute, [ 'float16', ]],
  43817. ] );
  43818. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  43819. [ Int32Array, 'sint32' ],
  43820. [ Int16Array, 'sint32' ], // patch for INT16
  43821. [ Uint32Array, 'uint32' ],
  43822. [ Uint16Array, 'uint32' ], // patch for UINT16
  43823. [ Float32Array, 'float32' ]
  43824. ] );
  43825. class WebGPUAttributeUtils {
  43826. constructor( backend ) {
  43827. this.backend = backend;
  43828. }
  43829. createAttribute( attribute, usage ) {
  43830. const bufferAttribute = this._getBufferAttribute( attribute );
  43831. const backend = this.backend;
  43832. const bufferData = backend.get( bufferAttribute );
  43833. let buffer = bufferData.buffer;
  43834. if ( buffer === undefined ) {
  43835. const device = backend.device;
  43836. let array = bufferAttribute.array;
  43837. // patch for INT16 and UINT16
  43838. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  43839. const tempArray = new Uint32Array( array.length );
  43840. for ( let i = 0; i < array.length; i ++ ) {
  43841. tempArray[ i ] = array[ i ];
  43842. }
  43843. array = tempArray;
  43844. }
  43845. bufferAttribute.array = array;
  43846. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  43847. array = new array.constructor( bufferAttribute.count * 4 );
  43848. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  43849. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  43850. }
  43851. // Update BufferAttribute
  43852. bufferAttribute.itemSize = 4;
  43853. bufferAttribute.array = array;
  43854. }
  43855. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  43856. buffer = device.createBuffer( {
  43857. label: bufferAttribute.name,
  43858. size: size,
  43859. usage: usage,
  43860. mappedAtCreation: true
  43861. } );
  43862. new array.constructor( buffer.getMappedRange() ).set( array );
  43863. buffer.unmap();
  43864. bufferData.buffer = buffer;
  43865. }
  43866. }
  43867. updateAttribute( attribute ) {
  43868. const bufferAttribute = this._getBufferAttribute( attribute );
  43869. const backend = this.backend;
  43870. const device = backend.device;
  43871. const buffer = backend.get( bufferAttribute ).buffer;
  43872. const array = bufferAttribute.array;
  43873. const updateRanges = bufferAttribute.updateRanges;
  43874. if ( updateRanges.length === 0 ) {
  43875. // Not using update ranges
  43876. device.queue.writeBuffer(
  43877. buffer,
  43878. 0,
  43879. array,
  43880. 0
  43881. );
  43882. } else {
  43883. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  43884. const range = updateRanges[ i ];
  43885. device.queue.writeBuffer(
  43886. buffer,
  43887. 0,
  43888. array,
  43889. range.start * array.BYTES_PER_ELEMENT,
  43890. range.count * array.BYTES_PER_ELEMENT
  43891. );
  43892. }
  43893. bufferAttribute.clearUpdateRanges();
  43894. }
  43895. }
  43896. createShaderVertexBuffers( renderObject ) {
  43897. const attributes = renderObject.getAttributes();
  43898. const vertexBuffers = new Map();
  43899. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  43900. const geometryAttribute = attributes[ slot ];
  43901. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  43902. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  43903. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  43904. if ( vertexBufferLayout === undefined ) {
  43905. let arrayStride, stepMode;
  43906. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  43907. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  43908. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43909. } else {
  43910. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  43911. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43912. }
  43913. // patch for INT16 and UINT16
  43914. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  43915. arrayStride = 4;
  43916. }
  43917. vertexBufferLayout = {
  43918. arrayStride,
  43919. attributes: [],
  43920. stepMode
  43921. };
  43922. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  43923. }
  43924. const format = this._getVertexFormat( geometryAttribute );
  43925. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  43926. vertexBufferLayout.attributes.push( {
  43927. shaderLocation: slot,
  43928. offset,
  43929. format
  43930. } );
  43931. }
  43932. return Array.from( vertexBuffers.values() );
  43933. }
  43934. destroyAttribute( attribute ) {
  43935. const backend = this.backend;
  43936. const data = backend.get( this._getBufferAttribute( attribute ) );
  43937. data.buffer.destroy();
  43938. backend.delete( attribute );
  43939. }
  43940. async getArrayBufferAsync( attribute ) {
  43941. const backend = this.backend;
  43942. const device = backend.device;
  43943. const data = backend.get( this._getBufferAttribute( attribute ) );
  43944. const bufferGPU = data.buffer;
  43945. const size = bufferGPU.size;
  43946. const readBufferGPU = device.createBuffer( {
  43947. label: attribute.name,
  43948. size,
  43949. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43950. } );
  43951. const cmdEncoder = device.createCommandEncoder( {} );
  43952. cmdEncoder.copyBufferToBuffer(
  43953. bufferGPU,
  43954. 0,
  43955. readBufferGPU,
  43956. 0,
  43957. size
  43958. );
  43959. readBufferGPU.unmap();
  43960. const gpuCommands = cmdEncoder.finish();
  43961. device.queue.submit( [ gpuCommands ] );
  43962. await readBufferGPU.mapAsync( GPUMapMode.READ );
  43963. const arrayBuffer = readBufferGPU.getMappedRange();
  43964. return arrayBuffer;
  43965. }
  43966. _getVertexFormat( geometryAttribute ) {
  43967. const { itemSize, normalized } = geometryAttribute;
  43968. const ArrayType = geometryAttribute.array.constructor;
  43969. const AttributeType = geometryAttribute.constructor;
  43970. let format;
  43971. if ( itemSize == 1 ) {
  43972. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  43973. } else {
  43974. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  43975. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  43976. if ( prefix ) {
  43977. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  43978. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  43979. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  43980. if ( paddedItemSize % 1 ) {
  43981. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  43982. }
  43983. format = `${prefix}x${paddedItemSize}`;
  43984. }
  43985. }
  43986. if ( ! format ) {
  43987. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  43988. }
  43989. return format;
  43990. }
  43991. _getBufferAttribute( attribute ) {
  43992. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43993. return attribute;
  43994. }
  43995. }
  43996. class WebGPUBindingUtils {
  43997. constructor( backend ) {
  43998. this.backend = backend;
  43999. this.bindGroupLayoutCache = new WeakMap();
  44000. }
  44001. createBindingsLayout( bindGroup ) {
  44002. const backend = this.backend;
  44003. const device = backend.device;
  44004. const entries = [];
  44005. let index = 0;
  44006. for ( const binding of bindGroup.bindings ) {
  44007. const bindingGPU = {
  44008. binding: index ++,
  44009. visibility: binding.visibility
  44010. };
  44011. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  44012. const buffer = {}; // GPUBufferBindingLayout
  44013. if ( binding.isStorageBuffer ) {
  44014. buffer.type = binding.access;
  44015. }
  44016. bindingGPU.buffer = buffer;
  44017. } else if ( binding.isSampler ) {
  44018. const sampler = {}; // GPUSamplerBindingLayout
  44019. if ( binding.texture.isDepthTexture ) {
  44020. if ( binding.texture.compareFunction !== null ) {
  44021. sampler.type = 'comparison';
  44022. }
  44023. }
  44024. bindingGPU.sampler = sampler;
  44025. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  44026. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  44027. } else if ( binding.isSampledTexture && binding.store ) {
  44028. const format = this.backend.get( binding.texture ).texture.format;
  44029. const access = binding.access;
  44030. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  44031. } else if ( binding.isSampledTexture ) {
  44032. const texture = {}; // GPUTextureBindingLayout
  44033. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  44034. texture.multisampled = true;
  44035. }
  44036. if ( binding.texture.isDepthTexture ) {
  44037. texture.sampleType = GPUTextureSampleType.Depth;
  44038. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  44039. const type = binding.texture.type;
  44040. if ( type === IntType ) {
  44041. texture.sampleType = GPUTextureSampleType.SInt;
  44042. } else if ( type === UnsignedIntType ) {
  44043. texture.sampleType = GPUTextureSampleType.UInt;
  44044. } else if ( type === FloatType ) {
  44045. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  44046. texture.sampleType = GPUTextureSampleType.Float;
  44047. } else {
  44048. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  44049. }
  44050. }
  44051. }
  44052. if ( binding.isSampledCubeTexture ) {
  44053. texture.viewDimension = GPUTextureViewDimension.Cube;
  44054. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  44055. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  44056. } else if ( binding.isSampledTexture3D ) {
  44057. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  44058. }
  44059. bindingGPU.texture = texture;
  44060. } else {
  44061. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  44062. }
  44063. entries.push( bindingGPU );
  44064. }
  44065. return device.createBindGroupLayout( { entries } );
  44066. }
  44067. createBindings( bindGroup ) {
  44068. const { backend, bindGroupLayoutCache } = this;
  44069. const bindingsData = backend.get( bindGroup );
  44070. // setup (static) binding layout and (dynamic) binding group
  44071. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  44072. if ( bindLayoutGPU === undefined ) {
  44073. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  44074. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  44075. }
  44076. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  44077. bindingsData.layout = bindLayoutGPU;
  44078. bindingsData.group = bindGroupGPU;
  44079. }
  44080. updateBinding( binding ) {
  44081. const backend = this.backend;
  44082. const device = backend.device;
  44083. const buffer = binding.buffer;
  44084. const bufferGPU = backend.get( binding ).buffer;
  44085. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  44086. }
  44087. createBindGroup( bindGroup, layoutGPU ) {
  44088. const backend = this.backend;
  44089. const device = backend.device;
  44090. let bindingPoint = 0;
  44091. const entriesGPU = [];
  44092. for ( const binding of bindGroup.bindings ) {
  44093. if ( binding.isUniformBuffer ) {
  44094. const bindingData = backend.get( binding );
  44095. if ( bindingData.buffer === undefined ) {
  44096. const byteLength = binding.byteLength;
  44097. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  44098. const bufferGPU = device.createBuffer( {
  44099. label: 'bindingBuffer_' + binding.name,
  44100. size: byteLength,
  44101. usage: usage
  44102. } );
  44103. bindingData.buffer = bufferGPU;
  44104. }
  44105. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  44106. } else if ( binding.isStorageBuffer ) {
  44107. const bindingData = backend.get( binding );
  44108. if ( bindingData.buffer === undefined ) {
  44109. const attribute = binding.attribute;
  44110. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  44111. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  44112. bindingData.buffer = backend.get( attribute ).buffer;
  44113. }
  44114. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  44115. } else if ( binding.isSampler ) {
  44116. const textureGPU = backend.get( binding.texture );
  44117. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  44118. } else if ( binding.isSampledTexture ) {
  44119. const textureData = backend.get( binding.texture );
  44120. let resourceGPU;
  44121. if ( textureData.externalTexture !== undefined ) {
  44122. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  44123. } else {
  44124. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  44125. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  44126. resourceGPU = textureData[ propertyName ];
  44127. if ( resourceGPU === undefined ) {
  44128. const aspectGPU = GPUTextureAspect.All;
  44129. let dimensionViewGPU;
  44130. if ( binding.isSampledCubeTexture ) {
  44131. dimensionViewGPU = GPUTextureViewDimension.Cube;
  44132. } else if ( binding.isSampledTexture3D ) {
  44133. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  44134. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  44135. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  44136. } else {
  44137. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  44138. }
  44139. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  44140. }
  44141. }
  44142. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  44143. }
  44144. bindingPoint ++;
  44145. }
  44146. return device.createBindGroup( {
  44147. label: 'bindGroup_' + bindGroup.name,
  44148. layout: layoutGPU,
  44149. entries: entriesGPU
  44150. } );
  44151. }
  44152. }
  44153. class WebGPUPipelineUtils {
  44154. constructor( backend ) {
  44155. this.backend = backend;
  44156. }
  44157. _getSampleCount( renderObjectContext ) {
  44158. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  44159. }
  44160. createRenderPipeline( renderObject, promises ) {
  44161. const { object, material, geometry, pipeline } = renderObject;
  44162. const { vertexProgram, fragmentProgram } = pipeline;
  44163. const backend = this.backend;
  44164. const device = backend.device;
  44165. const utils = backend.utils;
  44166. const pipelineData = backend.get( pipeline );
  44167. // bind group layouts
  44168. const bindGroupLayouts = [];
  44169. for ( const bindGroup of renderObject.getBindings() ) {
  44170. const bindingsData = backend.get( bindGroup );
  44171. bindGroupLayouts.push( bindingsData.layout );
  44172. }
  44173. // vertex buffers
  44174. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  44175. // blending
  44176. let blending;
  44177. if ( material.transparent === true && material.blending !== NoBlending ) {
  44178. blending = this._getBlending( material );
  44179. }
  44180. // stencil
  44181. let stencilFront = {};
  44182. if ( material.stencilWrite === true ) {
  44183. stencilFront = {
  44184. compare: this._getStencilCompare( material ),
  44185. failOp: this._getStencilOperation( material.stencilFail ),
  44186. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  44187. passOp: this._getStencilOperation( material.stencilZPass )
  44188. };
  44189. }
  44190. const colorWriteMask = this._getColorWriteMask( material );
  44191. const targets = [];
  44192. if ( renderObject.context.textures !== null ) {
  44193. const textures = renderObject.context.textures;
  44194. for ( let i = 0; i < textures.length; i ++ ) {
  44195. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  44196. targets.push( {
  44197. format: colorFormat,
  44198. blend: blending,
  44199. writeMask: colorWriteMask
  44200. } );
  44201. }
  44202. } else {
  44203. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  44204. targets.push( {
  44205. format: colorFormat,
  44206. blend: blending,
  44207. writeMask: colorWriteMask
  44208. } );
  44209. }
  44210. const vertexModule = backend.get( vertexProgram ).module;
  44211. const fragmentModule = backend.get( fragmentProgram ).module;
  44212. const primitiveState = this._getPrimitiveState( object, geometry, material );
  44213. const depthCompare = this._getDepthCompare( material );
  44214. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  44215. const sampleCount = this._getSampleCount( renderObject.context );
  44216. const pipelineDescriptor = {
  44217. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  44218. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  44219. fragment: Object.assign( {}, fragmentModule, { targets } ),
  44220. primitive: primitiveState,
  44221. multisample: {
  44222. count: sampleCount,
  44223. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  44224. },
  44225. layout: device.createPipelineLayout( {
  44226. bindGroupLayouts
  44227. } )
  44228. };
  44229. const depthStencil = {};
  44230. const renderDepth = renderObject.context.depth;
  44231. const renderStencil = renderObject.context.stencil;
  44232. if ( renderDepth === true || renderStencil === true ) {
  44233. if ( renderDepth === true ) {
  44234. depthStencil.format = depthStencilFormat;
  44235. depthStencil.depthWriteEnabled = material.depthWrite;
  44236. depthStencil.depthCompare = depthCompare;
  44237. }
  44238. if ( renderStencil === true ) {
  44239. depthStencil.stencilFront = stencilFront;
  44240. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  44241. depthStencil.stencilReadMask = material.stencilFuncMask;
  44242. depthStencil.stencilWriteMask = material.stencilWriteMask;
  44243. }
  44244. pipelineDescriptor.depthStencil = depthStencil;
  44245. }
  44246. if ( promises === null ) {
  44247. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  44248. } else {
  44249. const p = new Promise( ( resolve /*, reject*/ ) => {
  44250. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  44251. pipelineData.pipeline = pipeline;
  44252. resolve();
  44253. } );
  44254. } );
  44255. promises.push( p );
  44256. }
  44257. }
  44258. createBundleEncoder( renderContext ) {
  44259. const backend = this.backend;
  44260. const { utils, device } = backend;
  44261. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  44262. const colorFormat = utils.getCurrentColorFormat( renderContext );
  44263. const sampleCount = this._getSampleCount( renderContext );
  44264. const descriptor = {
  44265. label: 'renderBundleEncoder',
  44266. colorFormats: [ colorFormat ],
  44267. depthStencilFormat,
  44268. sampleCount
  44269. };
  44270. return device.createRenderBundleEncoder( descriptor );
  44271. }
  44272. createComputePipeline( pipeline, bindings ) {
  44273. const backend = this.backend;
  44274. const device = backend.device;
  44275. const computeProgram = backend.get( pipeline.computeProgram ).module;
  44276. const pipelineGPU = backend.get( pipeline );
  44277. // bind group layouts
  44278. const bindGroupLayouts = [];
  44279. for ( const bindingsGroup of bindings ) {
  44280. const bindingsData = backend.get( bindingsGroup );
  44281. bindGroupLayouts.push( bindingsData.layout );
  44282. }
  44283. pipelineGPU.pipeline = device.createComputePipeline( {
  44284. compute: computeProgram,
  44285. layout: device.createPipelineLayout( {
  44286. bindGroupLayouts
  44287. } )
  44288. } );
  44289. }
  44290. _getBlending( material ) {
  44291. let color, alpha;
  44292. const blending = material.blending;
  44293. const blendSrc = material.blendSrc;
  44294. const blendDst = material.blendDst;
  44295. const blendEquation = material.blendEquation;
  44296. if ( blending === CustomBlending ) {
  44297. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  44298. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  44299. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  44300. color = {
  44301. srcFactor: this._getBlendFactor( blendSrc ),
  44302. dstFactor: this._getBlendFactor( blendDst ),
  44303. operation: this._getBlendOperation( blendEquation )
  44304. };
  44305. alpha = {
  44306. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  44307. dstFactor: this._getBlendFactor( blendDstAlpha ),
  44308. operation: this._getBlendOperation( blendEquationAlpha )
  44309. };
  44310. } else {
  44311. const premultipliedAlpha = material.premultipliedAlpha;
  44312. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  44313. color = {
  44314. srcFactor: srcRGB,
  44315. dstFactor: dstRGB,
  44316. operation: GPUBlendOperation.Add
  44317. };
  44318. alpha = {
  44319. srcFactor: srcAlpha,
  44320. dstFactor: dstAlpha,
  44321. operation: GPUBlendOperation.Add
  44322. };
  44323. };
  44324. if ( premultipliedAlpha ) {
  44325. switch ( blending ) {
  44326. case NormalBlending:
  44327. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44328. break;
  44329. case AdditiveBlending:
  44330. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  44331. break;
  44332. case SubtractiveBlending:
  44333. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44334. break;
  44335. case MultiplyBlending:
  44336. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  44337. break;
  44338. }
  44339. } else {
  44340. switch ( blending ) {
  44341. case NormalBlending:
  44342. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44343. break;
  44344. case AdditiveBlending:
  44345. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  44346. break;
  44347. case SubtractiveBlending:
  44348. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44349. break;
  44350. case MultiplyBlending:
  44351. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  44352. break;
  44353. }
  44354. }
  44355. }
  44356. if ( color !== undefined && alpha !== undefined ) {
  44357. return { color, alpha };
  44358. } else {
  44359. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  44360. }
  44361. }
  44362. _getBlendFactor( blend ) {
  44363. let blendFactor;
  44364. switch ( blend ) {
  44365. case ZeroFactor:
  44366. blendFactor = GPUBlendFactor.Zero;
  44367. break;
  44368. case OneFactor:
  44369. blendFactor = GPUBlendFactor.One;
  44370. break;
  44371. case SrcColorFactor:
  44372. blendFactor = GPUBlendFactor.Src;
  44373. break;
  44374. case OneMinusSrcColorFactor:
  44375. blendFactor = GPUBlendFactor.OneMinusSrc;
  44376. break;
  44377. case SrcAlphaFactor:
  44378. blendFactor = GPUBlendFactor.SrcAlpha;
  44379. break;
  44380. case OneMinusSrcAlphaFactor:
  44381. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  44382. break;
  44383. case DstColorFactor:
  44384. blendFactor = GPUBlendFactor.Dst;
  44385. break;
  44386. case OneMinusDstColorFactor:
  44387. blendFactor = GPUBlendFactor.OneMinusDstColor;
  44388. break;
  44389. case DstAlphaFactor:
  44390. blendFactor = GPUBlendFactor.DstAlpha;
  44391. break;
  44392. case OneMinusDstAlphaFactor:
  44393. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  44394. break;
  44395. case SrcAlphaSaturateFactor:
  44396. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  44397. break;
  44398. case BlendColorFactor:
  44399. blendFactor = GPUBlendFactor.Constant;
  44400. break;
  44401. case OneMinusBlendColorFactor:
  44402. blendFactor = GPUBlendFactor.OneMinusConstant;
  44403. break;
  44404. default:
  44405. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  44406. }
  44407. return blendFactor;
  44408. }
  44409. _getStencilCompare( material ) {
  44410. let stencilCompare;
  44411. const stencilFunc = material.stencilFunc;
  44412. switch ( stencilFunc ) {
  44413. case NeverStencilFunc:
  44414. stencilCompare = GPUCompareFunction.Never;
  44415. break;
  44416. case AlwaysStencilFunc:
  44417. stencilCompare = GPUCompareFunction.Always;
  44418. break;
  44419. case LessStencilFunc:
  44420. stencilCompare = GPUCompareFunction.Less;
  44421. break;
  44422. case LessEqualStencilFunc:
  44423. stencilCompare = GPUCompareFunction.LessEqual;
  44424. break;
  44425. case EqualStencilFunc:
  44426. stencilCompare = GPUCompareFunction.Equal;
  44427. break;
  44428. case GreaterEqualStencilFunc:
  44429. stencilCompare = GPUCompareFunction.GreaterEqual;
  44430. break;
  44431. case GreaterStencilFunc:
  44432. stencilCompare = GPUCompareFunction.Greater;
  44433. break;
  44434. case NotEqualStencilFunc:
  44435. stencilCompare = GPUCompareFunction.NotEqual;
  44436. break;
  44437. default:
  44438. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  44439. }
  44440. return stencilCompare;
  44441. }
  44442. _getStencilOperation( op ) {
  44443. let stencilOperation;
  44444. switch ( op ) {
  44445. case KeepStencilOp:
  44446. stencilOperation = GPUStencilOperation.Keep;
  44447. break;
  44448. case ZeroStencilOp:
  44449. stencilOperation = GPUStencilOperation.Zero;
  44450. break;
  44451. case ReplaceStencilOp:
  44452. stencilOperation = GPUStencilOperation.Replace;
  44453. break;
  44454. case InvertStencilOp:
  44455. stencilOperation = GPUStencilOperation.Invert;
  44456. break;
  44457. case IncrementStencilOp:
  44458. stencilOperation = GPUStencilOperation.IncrementClamp;
  44459. break;
  44460. case DecrementStencilOp:
  44461. stencilOperation = GPUStencilOperation.DecrementClamp;
  44462. break;
  44463. case IncrementWrapStencilOp:
  44464. stencilOperation = GPUStencilOperation.IncrementWrap;
  44465. break;
  44466. case DecrementWrapStencilOp:
  44467. stencilOperation = GPUStencilOperation.DecrementWrap;
  44468. break;
  44469. default:
  44470. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  44471. }
  44472. return stencilOperation;
  44473. }
  44474. _getBlendOperation( blendEquation ) {
  44475. let blendOperation;
  44476. switch ( blendEquation ) {
  44477. case AddEquation:
  44478. blendOperation = GPUBlendOperation.Add;
  44479. break;
  44480. case SubtractEquation:
  44481. blendOperation = GPUBlendOperation.Subtract;
  44482. break;
  44483. case ReverseSubtractEquation:
  44484. blendOperation = GPUBlendOperation.ReverseSubtract;
  44485. break;
  44486. case MinEquation:
  44487. blendOperation = GPUBlendOperation.Min;
  44488. break;
  44489. case MaxEquation:
  44490. blendOperation = GPUBlendOperation.Max;
  44491. break;
  44492. default:
  44493. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  44494. }
  44495. return blendOperation;
  44496. }
  44497. _getPrimitiveState( object, geometry, material ) {
  44498. const descriptor = {};
  44499. const utils = this.backend.utils;
  44500. descriptor.topology = utils.getPrimitiveTopology( object, material );
  44501. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  44502. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  44503. }
  44504. switch ( material.side ) {
  44505. case FrontSide:
  44506. descriptor.frontFace = GPUFrontFace.CCW;
  44507. descriptor.cullMode = GPUCullMode.Back;
  44508. break;
  44509. case BackSide:
  44510. descriptor.frontFace = GPUFrontFace.CCW;
  44511. descriptor.cullMode = GPUCullMode.Front;
  44512. break;
  44513. case DoubleSide:
  44514. descriptor.frontFace = GPUFrontFace.CCW;
  44515. descriptor.cullMode = GPUCullMode.None;
  44516. break;
  44517. default:
  44518. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  44519. break;
  44520. }
  44521. return descriptor;
  44522. }
  44523. _getColorWriteMask( material ) {
  44524. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  44525. }
  44526. _getDepthCompare( material ) {
  44527. let depthCompare;
  44528. if ( material.depthTest === false ) {
  44529. depthCompare = GPUCompareFunction.Always;
  44530. } else {
  44531. const depthFunc = material.depthFunc;
  44532. switch ( depthFunc ) {
  44533. case NeverDepth:
  44534. depthCompare = GPUCompareFunction.Never;
  44535. break;
  44536. case AlwaysDepth:
  44537. depthCompare = GPUCompareFunction.Always;
  44538. break;
  44539. case LessDepth:
  44540. depthCompare = GPUCompareFunction.Less;
  44541. break;
  44542. case LessEqualDepth:
  44543. depthCompare = GPUCompareFunction.LessEqual;
  44544. break;
  44545. case EqualDepth:
  44546. depthCompare = GPUCompareFunction.Equal;
  44547. break;
  44548. case GreaterEqualDepth:
  44549. depthCompare = GPUCompareFunction.GreaterEqual;
  44550. break;
  44551. case GreaterDepth:
  44552. depthCompare = GPUCompareFunction.Greater;
  44553. break;
  44554. case NotEqualDepth:
  44555. depthCompare = GPUCompareFunction.NotEqual;
  44556. break;
  44557. default:
  44558. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  44559. }
  44560. }
  44561. return depthCompare;
  44562. }
  44563. }
  44564. /*// debugger tools
  44565. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  44566. //*/
  44567. //
  44568. class WebGPUBackend extends Backend {
  44569. constructor( parameters = {} ) {
  44570. super( parameters );
  44571. this.isWebGPUBackend = true;
  44572. // some parameters require default values other than "undefined"
  44573. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  44574. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  44575. this.trackTimestamp = ( parameters.trackTimestamp === true );
  44576. this.device = null;
  44577. this.context = null;
  44578. this.colorBuffer = null;
  44579. this.defaultRenderPassdescriptor = null;
  44580. this.utils = new WebGPUUtils( this );
  44581. this.attributeUtils = new WebGPUAttributeUtils( this );
  44582. this.bindingUtils = new WebGPUBindingUtils( this );
  44583. this.pipelineUtils = new WebGPUPipelineUtils( this );
  44584. this.textureUtils = new WebGPUTextureUtils( this );
  44585. this.occludedResolveCache = new Map();
  44586. }
  44587. async init( renderer ) {
  44588. await super.init( renderer );
  44589. //
  44590. const parameters = this.parameters;
  44591. // create the device if it is not passed with parameters
  44592. let device;
  44593. if ( parameters.device === undefined ) {
  44594. const adapterOptions = {
  44595. powerPreference: parameters.powerPreference
  44596. };
  44597. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  44598. if ( adapter === null ) {
  44599. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  44600. }
  44601. // feature support
  44602. const features = Object.values( GPUFeatureName );
  44603. const supportedFeatures = [];
  44604. for ( const name of features ) {
  44605. if ( adapter.features.has( name ) ) {
  44606. supportedFeatures.push( name );
  44607. }
  44608. }
  44609. const deviceDescriptor = {
  44610. requiredFeatures: supportedFeatures,
  44611. requiredLimits: parameters.requiredLimits
  44612. };
  44613. device = await adapter.requestDevice( deviceDescriptor );
  44614. } else {
  44615. device = parameters.device;
  44616. }
  44617. device.lost.then( ( info ) => {
  44618. const deviceLossInfo = {
  44619. api: 'WebGPU',
  44620. message: info.message || 'Unknown reason',
  44621. reason: info.reason || null,
  44622. originalEvent: info
  44623. };
  44624. renderer.onDeviceLost( deviceLossInfo );
  44625. } );
  44626. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  44627. this.device = device;
  44628. this.context = context;
  44629. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  44630. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  44631. this.context.configure( {
  44632. device: this.device,
  44633. format: this.utils.getPreferredCanvasFormat(),
  44634. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  44635. alphaMode: alphaMode
  44636. } );
  44637. this.updateSize();
  44638. }
  44639. get coordinateSystem() {
  44640. return WebGPUCoordinateSystem;
  44641. }
  44642. async getArrayBufferAsync( attribute ) {
  44643. return await this.attributeUtils.getArrayBufferAsync( attribute );
  44644. }
  44645. getContext() {
  44646. return this.context;
  44647. }
  44648. _getDefaultRenderPassDescriptor() {
  44649. let descriptor = this.defaultRenderPassdescriptor;
  44650. if ( descriptor === null ) {
  44651. const renderer = this.renderer;
  44652. descriptor = {
  44653. colorAttachments: [ {
  44654. view: null
  44655. } ],
  44656. };
  44657. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  44658. descriptor.depthStencilAttachment = {
  44659. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  44660. };
  44661. }
  44662. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44663. if ( this.renderer.samples > 0 ) {
  44664. colorAttachment.view = this.colorBuffer.createView();
  44665. } else {
  44666. colorAttachment.resolveTarget = undefined;
  44667. }
  44668. this.defaultRenderPassdescriptor = descriptor;
  44669. }
  44670. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44671. if ( this.renderer.samples > 0 ) {
  44672. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  44673. } else {
  44674. colorAttachment.view = this.context.getCurrentTexture().createView();
  44675. }
  44676. return descriptor;
  44677. }
  44678. _getRenderPassDescriptor( renderContext ) {
  44679. const renderTarget = renderContext.renderTarget;
  44680. const renderTargetData = this.get( renderTarget );
  44681. let descriptors = renderTargetData.descriptors;
  44682. if ( descriptors === undefined ||
  44683. renderTargetData.width !== renderTarget.width ||
  44684. renderTargetData.height !== renderTarget.height ||
  44685. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  44686. renderTargetData.samples !== renderTarget.samples
  44687. ) {
  44688. descriptors = {};
  44689. renderTargetData.descriptors = descriptors;
  44690. // dispose
  44691. const onDispose = () => {
  44692. renderTarget.removeEventListener( 'dispose', onDispose );
  44693. this.delete( renderTarget );
  44694. };
  44695. renderTarget.addEventListener( 'dispose', onDispose );
  44696. }
  44697. const cacheKey = renderContext.getCacheKey();
  44698. let descriptor = descriptors[ cacheKey ];
  44699. if ( descriptor === undefined ) {
  44700. const textures = renderContext.textures;
  44701. const colorAttachments = [];
  44702. for ( let i = 0; i < textures.length; i ++ ) {
  44703. const textureData = this.get( textures[ i ] );
  44704. const textureView = textureData.texture.createView( {
  44705. baseMipLevel: renderContext.activeMipmapLevel,
  44706. mipLevelCount: 1,
  44707. baseArrayLayer: renderContext.activeCubeFace,
  44708. dimension: GPUTextureViewDimension.TwoD
  44709. } );
  44710. let view, resolveTarget;
  44711. if ( textureData.msaaTexture !== undefined ) {
  44712. view = textureData.msaaTexture.createView();
  44713. resolveTarget = textureView;
  44714. } else {
  44715. view = textureView;
  44716. resolveTarget = undefined;
  44717. }
  44718. colorAttachments.push( {
  44719. view,
  44720. resolveTarget,
  44721. loadOp: GPULoadOp.Load,
  44722. storeOp: GPUStoreOp.Store
  44723. } );
  44724. }
  44725. descriptor = {
  44726. colorAttachments,
  44727. };
  44728. if ( renderContext.depth ) {
  44729. const depthTextureData = this.get( renderContext.depthTexture );
  44730. const depthStencilAttachment = {
  44731. view: depthTextureData.texture.createView()
  44732. };
  44733. descriptor.depthStencilAttachment = depthStencilAttachment;
  44734. }
  44735. descriptors[ cacheKey ] = descriptor;
  44736. renderTargetData.width = renderTarget.width;
  44737. renderTargetData.height = renderTarget.height;
  44738. renderTargetData.samples = renderTarget.samples;
  44739. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  44740. }
  44741. return descriptor;
  44742. }
  44743. beginRender( renderContext ) {
  44744. const renderContextData = this.get( renderContext );
  44745. const device = this.device;
  44746. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44747. let occlusionQuerySet;
  44748. if ( occlusionQueryCount > 0 ) {
  44749. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  44750. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  44751. // Get a reference to the array of objects with queries. The renderContextData property
  44752. // can be changed by another render pass before the buffer.mapAsyc() completes.
  44753. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  44754. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  44755. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  44756. //
  44757. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  44758. renderContextData.occlusionQuerySet = occlusionQuerySet;
  44759. renderContextData.occlusionQueryIndex = 0;
  44760. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  44761. renderContextData.lastOcclusionObject = null;
  44762. }
  44763. let descriptor;
  44764. if ( renderContext.textures === null ) {
  44765. descriptor = this._getDefaultRenderPassDescriptor();
  44766. } else {
  44767. descriptor = this._getRenderPassDescriptor( renderContext );
  44768. }
  44769. this.initTimestampQuery( renderContext, descriptor );
  44770. descriptor.occlusionQuerySet = occlusionQuerySet;
  44771. const depthStencilAttachment = descriptor.depthStencilAttachment;
  44772. if ( renderContext.textures !== null ) {
  44773. const colorAttachments = descriptor.colorAttachments;
  44774. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  44775. const colorAttachment = colorAttachments[ i ];
  44776. if ( renderContext.clearColor ) {
  44777. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  44778. colorAttachment.loadOp = GPULoadOp.Clear;
  44779. colorAttachment.storeOp = GPUStoreOp.Store;
  44780. } else {
  44781. colorAttachment.loadOp = GPULoadOp.Load;
  44782. colorAttachment.storeOp = GPUStoreOp.Store;
  44783. }
  44784. }
  44785. } else {
  44786. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44787. if ( renderContext.clearColor ) {
  44788. colorAttachment.clearValue = renderContext.clearColorValue;
  44789. colorAttachment.loadOp = GPULoadOp.Clear;
  44790. colorAttachment.storeOp = GPUStoreOp.Store;
  44791. } else {
  44792. colorAttachment.loadOp = GPULoadOp.Load;
  44793. colorAttachment.storeOp = GPUStoreOp.Store;
  44794. }
  44795. }
  44796. //
  44797. if ( renderContext.depth ) {
  44798. if ( renderContext.clearDepth ) {
  44799. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  44800. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  44801. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44802. } else {
  44803. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44804. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44805. }
  44806. }
  44807. if ( renderContext.stencil ) {
  44808. if ( renderContext.clearStencil ) {
  44809. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  44810. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  44811. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44812. } else {
  44813. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44814. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44815. }
  44816. }
  44817. //
  44818. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  44819. const currentPass = encoder.beginRenderPass( descriptor );
  44820. //
  44821. renderContextData.descriptor = descriptor;
  44822. renderContextData.encoder = encoder;
  44823. renderContextData.currentPass = currentPass;
  44824. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  44825. renderContextData.renderBundles = [];
  44826. //
  44827. if ( renderContext.viewport ) {
  44828. this.updateViewport( renderContext );
  44829. }
  44830. if ( renderContext.scissor ) {
  44831. const { x, y, width, height } = renderContext.scissorValue;
  44832. currentPass.setScissorRect( x, y, width, height );
  44833. }
  44834. }
  44835. finishRender( renderContext ) {
  44836. const renderContextData = this.get( renderContext );
  44837. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44838. if ( renderContextData.renderBundles.length > 0 ) {
  44839. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  44840. }
  44841. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  44842. renderContextData.currentPass.endOcclusionQuery();
  44843. }
  44844. renderContextData.currentPass.end();
  44845. if ( occlusionQueryCount > 0 ) {
  44846. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  44847. //
  44848. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  44849. if ( queryResolveBuffer === undefined ) {
  44850. queryResolveBuffer = this.device.createBuffer(
  44851. {
  44852. size: bufferSize,
  44853. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  44854. }
  44855. );
  44856. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  44857. }
  44858. //
  44859. const readBuffer = this.device.createBuffer(
  44860. {
  44861. size: bufferSize,
  44862. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  44863. }
  44864. );
  44865. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  44866. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  44867. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  44868. renderContextData.occlusionQueryBuffer = readBuffer;
  44869. //
  44870. this.resolveOccludedAsync( renderContext );
  44871. }
  44872. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  44873. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  44874. //
  44875. if ( renderContext.textures !== null ) {
  44876. const textures = renderContext.textures;
  44877. for ( let i = 0; i < textures.length; i ++ ) {
  44878. const texture = textures[ i ];
  44879. if ( texture.generateMipmaps === true ) {
  44880. this.textureUtils.generateMipmaps( texture );
  44881. }
  44882. }
  44883. }
  44884. }
  44885. isOccluded( renderContext, object ) {
  44886. const renderContextData = this.get( renderContext );
  44887. return renderContextData.occluded && renderContextData.occluded.has( object );
  44888. }
  44889. async resolveOccludedAsync( renderContext ) {
  44890. const renderContextData = this.get( renderContext );
  44891. // handle occlusion query results
  44892. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  44893. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  44894. const occluded = new WeakSet();
  44895. renderContextData.currentOcclusionQueryObjects = null;
  44896. renderContextData.currentOcclusionQueryBuffer = null;
  44897. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  44898. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  44899. const results = new BigUint64Array( buffer );
  44900. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  44901. if ( results[ i ] !== BigInt( 0 ) ) {
  44902. occluded.add( currentOcclusionQueryObjects[ i ] );
  44903. }
  44904. }
  44905. currentOcclusionQueryBuffer.destroy();
  44906. renderContextData.occluded = occluded;
  44907. }
  44908. }
  44909. updateViewport( renderContext ) {
  44910. const { currentPass } = this.get( renderContext );
  44911. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  44912. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  44913. }
  44914. clear( color, depth, stencil, renderTargetData = null ) {
  44915. const device = this.device;
  44916. const renderer = this.renderer;
  44917. let colorAttachments = [];
  44918. let depthStencilAttachment;
  44919. let clearValue;
  44920. let supportsDepth;
  44921. let supportsStencil;
  44922. if ( color ) {
  44923. const clearColor = this.getClearColor();
  44924. if ( this.renderer.alpha === true ) {
  44925. // premultiply alpha
  44926. const a = clearColor.a;
  44927. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  44928. } else {
  44929. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  44930. }
  44931. }
  44932. if ( renderTargetData === null ) {
  44933. supportsDepth = renderer.depth;
  44934. supportsStencil = renderer.stencil;
  44935. const descriptor = this._getDefaultRenderPassDescriptor();
  44936. if ( color ) {
  44937. colorAttachments = descriptor.colorAttachments;
  44938. const colorAttachment = colorAttachments[ 0 ];
  44939. colorAttachment.clearValue = clearValue;
  44940. colorAttachment.loadOp = GPULoadOp.Clear;
  44941. colorAttachment.storeOp = GPUStoreOp.Store;
  44942. }
  44943. if ( supportsDepth || supportsStencil ) {
  44944. depthStencilAttachment = descriptor.depthStencilAttachment;
  44945. }
  44946. } else {
  44947. supportsDepth = renderTargetData.depth;
  44948. supportsStencil = renderTargetData.stencil;
  44949. if ( color ) {
  44950. for ( const texture of renderTargetData.textures ) {
  44951. const textureData = this.get( texture );
  44952. const textureView = textureData.texture.createView();
  44953. let view, resolveTarget;
  44954. if ( textureData.msaaTexture !== undefined ) {
  44955. view = textureData.msaaTexture.createView();
  44956. resolveTarget = textureView;
  44957. } else {
  44958. view = textureView;
  44959. resolveTarget = undefined;
  44960. }
  44961. colorAttachments.push( {
  44962. view,
  44963. resolveTarget,
  44964. clearValue,
  44965. loadOp: GPULoadOp.Clear,
  44966. storeOp: GPUStoreOp.Store
  44967. } );
  44968. }
  44969. }
  44970. if ( supportsDepth || supportsStencil ) {
  44971. const depthTextureData = this.get( renderTargetData.depthTexture );
  44972. depthStencilAttachment = {
  44973. view: depthTextureData.texture.createView()
  44974. };
  44975. }
  44976. }
  44977. //
  44978. if ( supportsDepth ) {
  44979. if ( depth ) {
  44980. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  44981. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  44982. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44983. } else {
  44984. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44985. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44986. }
  44987. }
  44988. //
  44989. if ( supportsStencil ) {
  44990. if ( stencil ) {
  44991. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  44992. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  44993. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44994. } else {
  44995. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44996. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44997. }
  44998. }
  44999. //
  45000. const encoder = device.createCommandEncoder( {} );
  45001. const currentPass = encoder.beginRenderPass( {
  45002. colorAttachments,
  45003. depthStencilAttachment
  45004. } );
  45005. currentPass.end();
  45006. device.queue.submit( [ encoder.finish() ] );
  45007. }
  45008. // compute
  45009. beginCompute( computeGroup ) {
  45010. const groupGPU = this.get( computeGroup );
  45011. const descriptor = {};
  45012. this.initTimestampQuery( computeGroup, descriptor );
  45013. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  45014. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  45015. }
  45016. compute( computeGroup, computeNode, bindings, pipeline ) {
  45017. const { passEncoderGPU } = this.get( computeGroup );
  45018. // pipeline
  45019. const pipelineGPU = this.get( pipeline ).pipeline;
  45020. passEncoderGPU.setPipeline( pipelineGPU );
  45021. // bind groups
  45022. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  45023. const bindGroup = bindings[ i ];
  45024. const bindingsData = this.get( bindGroup );
  45025. passEncoderGPU.setBindGroup( i, bindingsData.group );
  45026. }
  45027. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  45028. const computeNodeData = this.get( computeNode );
  45029. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  45030. const { dispatchSize } = computeNodeData;
  45031. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  45032. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  45033. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  45034. } else {
  45035. dispatchSize.x = computeNode.dispatchCount;
  45036. }
  45037. passEncoderGPU.dispatchWorkgroups(
  45038. dispatchSize.x,
  45039. dispatchSize.y,
  45040. dispatchSize.z
  45041. );
  45042. }
  45043. finishCompute( computeGroup ) {
  45044. const groupData = this.get( computeGroup );
  45045. groupData.passEncoderGPU.end();
  45046. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  45047. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  45048. }
  45049. async waitForGPU() {
  45050. await this.device.queue.onSubmittedWorkDone();
  45051. }
  45052. // render object
  45053. draw( renderObject, info ) {
  45054. const { object, context, pipeline } = renderObject;
  45055. const bindings = renderObject.getBindings();
  45056. const renderContextData = this.get( context );
  45057. const pipelineGPU = this.get( pipeline ).pipeline;
  45058. const currentSets = renderContextData.currentSets;
  45059. const passEncoderGPU = renderContextData.currentPass;
  45060. const drawParams = renderObject.getDrawParameters();
  45061. if ( drawParams === null ) return;
  45062. // pipeline
  45063. if ( currentSets.pipeline !== pipelineGPU ) {
  45064. passEncoderGPU.setPipeline( pipelineGPU );
  45065. currentSets.pipeline = pipelineGPU;
  45066. }
  45067. // bind groups
  45068. const currentBindingGroups = currentSets.bindingGroups;
  45069. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  45070. const bindGroup = bindings[ i ];
  45071. const bindingsData = this.get( bindGroup );
  45072. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  45073. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  45074. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  45075. }
  45076. }
  45077. // attributes
  45078. const index = renderObject.getIndex();
  45079. const hasIndex = ( index !== null );
  45080. // index
  45081. if ( hasIndex === true ) {
  45082. if ( currentSets.index !== index ) {
  45083. const buffer = this.get( index ).buffer;
  45084. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  45085. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  45086. currentSets.index = index;
  45087. }
  45088. }
  45089. // vertex buffers
  45090. const vertexBuffers = renderObject.getVertexBuffers();
  45091. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  45092. const vertexBuffer = vertexBuffers[ i ];
  45093. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  45094. const buffer = this.get( vertexBuffer ).buffer;
  45095. passEncoderGPU.setVertexBuffer( i, buffer );
  45096. currentSets.attributes[ i ] = vertexBuffer;
  45097. }
  45098. }
  45099. // occlusion queries - handle multiple consecutive draw calls for an object
  45100. if ( renderContextData.occlusionQuerySet !== undefined ) {
  45101. const lastObject = renderContextData.lastOcclusionObject;
  45102. if ( lastObject !== object ) {
  45103. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  45104. passEncoderGPU.endOcclusionQuery();
  45105. renderContextData.occlusionQueryIndex ++;
  45106. }
  45107. if ( object.occlusionTest === true ) {
  45108. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  45109. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  45110. }
  45111. renderContextData.lastOcclusionObject = object;
  45112. }
  45113. }
  45114. // draw
  45115. if ( object.isBatchedMesh === true ) {
  45116. const starts = object._multiDrawStarts;
  45117. const counts = object._multiDrawCounts;
  45118. const drawCount = object._multiDrawCount;
  45119. const drawInstances = object._multiDrawInstances;
  45120. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  45121. for ( let i = 0; i < drawCount; i ++ ) {
  45122. const count = drawInstances ? drawInstances[ i ] : 1;
  45123. const firstInstance = count > 1 ? 0 : i;
  45124. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  45125. }
  45126. } else if ( hasIndex === true ) {
  45127. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  45128. const indirect = renderObject.getIndirect();
  45129. if ( indirect !== null ) {
  45130. const buffer = this.get( indirect ).buffer;
  45131. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  45132. } else {
  45133. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  45134. }
  45135. info.update( object, indexCount, instanceCount );
  45136. } else {
  45137. const { vertexCount, instanceCount, firstVertex } = drawParams;
  45138. const indirect = renderObject.getIndirect();
  45139. if ( indirect !== null ) {
  45140. const buffer = this.get( indirect ).buffer;
  45141. passEncoderGPU.drawIndirect( buffer, 0 );
  45142. } else {
  45143. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  45144. }
  45145. info.update( object, vertexCount, instanceCount );
  45146. }
  45147. }
  45148. // cache key
  45149. needsRenderUpdate( renderObject ) {
  45150. const data = this.get( renderObject );
  45151. const { object, material } = renderObject;
  45152. const utils = this.utils;
  45153. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  45154. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  45155. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  45156. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  45157. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  45158. let needsUpdate = false;
  45159. if ( data.material !== material || data.materialVersion !== material.version ||
  45160. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  45161. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  45162. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  45163. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  45164. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  45165. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  45166. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  45167. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  45168. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  45169. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  45170. data.primitiveTopology !== primitiveTopology ||
  45171. data.clippingContextCacheKey !== renderObject.clippingContext.cacheKey
  45172. ) {
  45173. data.material = material; data.materialVersion = material.version;
  45174. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  45175. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  45176. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  45177. data.colorWrite = material.colorWrite;
  45178. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  45179. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  45180. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  45181. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  45182. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  45183. data.sampleCount = sampleCount;
  45184. data.colorSpace = colorSpace;
  45185. data.colorFormat = colorFormat;
  45186. data.depthStencilFormat = depthStencilFormat;
  45187. data.primitiveTopology = primitiveTopology;
  45188. data.clippingContextCacheKey = renderObject.clippingContext.cacheKey;
  45189. needsUpdate = true;
  45190. }
  45191. return needsUpdate;
  45192. }
  45193. getRenderCacheKey( renderObject ) {
  45194. const { object, material } = renderObject;
  45195. const utils = this.utils;
  45196. const renderContext = renderObject.context;
  45197. return [
  45198. material.transparent, material.blending, material.premultipliedAlpha,
  45199. material.blendSrc, material.blendDst, material.blendEquation,
  45200. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  45201. material.colorWrite,
  45202. material.depthWrite, material.depthTest, material.depthFunc,
  45203. material.stencilWrite, material.stencilFunc,
  45204. material.stencilFail, material.stencilZFail, material.stencilZPass,
  45205. material.stencilFuncMask, material.stencilWriteMask,
  45206. material.side,
  45207. utils.getSampleCountRenderContext( renderContext ),
  45208. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  45209. utils.getPrimitiveTopology( object, material ),
  45210. renderObject.getGeometryCacheKey(),
  45211. renderObject.clippingContext.cacheKey
  45212. ].join();
  45213. }
  45214. // textures
  45215. createSampler( texture ) {
  45216. this.textureUtils.createSampler( texture );
  45217. }
  45218. destroySampler( texture ) {
  45219. this.textureUtils.destroySampler( texture );
  45220. }
  45221. createDefaultTexture( texture ) {
  45222. this.textureUtils.createDefaultTexture( texture );
  45223. }
  45224. createTexture( texture, options ) {
  45225. this.textureUtils.createTexture( texture, options );
  45226. }
  45227. updateTexture( texture, options ) {
  45228. this.textureUtils.updateTexture( texture, options );
  45229. }
  45230. generateMipmaps( texture ) {
  45231. this.textureUtils.generateMipmaps( texture );
  45232. }
  45233. destroyTexture( texture ) {
  45234. this.textureUtils.destroyTexture( texture );
  45235. }
  45236. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  45237. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  45238. }
  45239. initTimestampQuery( renderContext, descriptor ) {
  45240. if ( ! this.trackTimestamp ) return;
  45241. const renderContextData = this.get( renderContext );
  45242. if ( ! renderContextData.timeStampQuerySet ) {
  45243. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  45244. // beginning and one for the end of compute pass execution.
  45245. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  45246. const timestampWrites = {
  45247. querySet: timeStampQuerySet,
  45248. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  45249. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  45250. };
  45251. Object.assign( descriptor, {
  45252. timestampWrites,
  45253. } );
  45254. renderContextData.timeStampQuerySet = timeStampQuerySet;
  45255. }
  45256. }
  45257. // timestamp utils
  45258. prepareTimestampBuffer( renderContext, encoder ) {
  45259. if ( ! this.trackTimestamp ) return;
  45260. const renderContextData = this.get( renderContext );
  45261. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  45262. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  45263. renderContextData.currentTimestampQueryBuffers = {
  45264. resolveBuffer: this.device.createBuffer( {
  45265. label: 'timestamp resolve buffer',
  45266. size: size,
  45267. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  45268. } ),
  45269. resultBuffer: this.device.createBuffer( {
  45270. label: 'timestamp result buffer',
  45271. size: size,
  45272. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  45273. } ),
  45274. isMappingPending: false,
  45275. };
  45276. }
  45277. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  45278. if ( isMappingPending === true ) return;
  45279. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  45280. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  45281. }
  45282. async resolveTimestampAsync( renderContext, type = 'render' ) {
  45283. if ( ! this.trackTimestamp ) return;
  45284. const renderContextData = this.get( renderContext );
  45285. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  45286. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  45287. if ( isMappingPending === true ) return;
  45288. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  45289. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  45290. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  45291. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  45292. this.renderer.info.updateTimestamp( type, duration );
  45293. resultBuffer.unmap();
  45294. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  45295. } );
  45296. }
  45297. // node builder
  45298. createNodeBuilder( object, renderer ) {
  45299. return new WGSLNodeBuilder( object, renderer );
  45300. }
  45301. // program
  45302. createProgram( program ) {
  45303. const programGPU = this.get( program );
  45304. programGPU.module = {
  45305. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  45306. entryPoint: 'main'
  45307. };
  45308. }
  45309. destroyProgram( program ) {
  45310. this.delete( program );
  45311. }
  45312. // pipelines
  45313. createRenderPipeline( renderObject, promises ) {
  45314. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  45315. }
  45316. createComputePipeline( computePipeline, bindings ) {
  45317. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  45318. }
  45319. beginBundle( renderContext ) {
  45320. const renderContextData = this.get( renderContext );
  45321. renderContextData._currentPass = renderContextData.currentPass;
  45322. renderContextData._currentSets = renderContextData.currentSets;
  45323. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45324. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  45325. }
  45326. finishBundle( renderContext, bundle ) {
  45327. const renderContextData = this.get( renderContext );
  45328. const bundleEncoder = renderContextData.currentPass;
  45329. const bundleGPU = bundleEncoder.finish();
  45330. this.get( bundle ).bundleGPU = bundleGPU;
  45331. // restore render pass state
  45332. renderContextData.currentSets = renderContextData._currentSets;
  45333. renderContextData.currentPass = renderContextData._currentPass;
  45334. }
  45335. addBundle( renderContext, bundle ) {
  45336. const renderContextData = this.get( renderContext );
  45337. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  45338. }
  45339. // bindings
  45340. createBindings( bindGroup ) {
  45341. this.bindingUtils.createBindings( bindGroup );
  45342. }
  45343. updateBindings( bindGroup ) {
  45344. this.bindingUtils.createBindings( bindGroup );
  45345. }
  45346. updateBinding( binding ) {
  45347. this.bindingUtils.updateBinding( binding );
  45348. }
  45349. // attributes
  45350. createIndexAttribute( attribute ) {
  45351. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45352. }
  45353. createAttribute( attribute ) {
  45354. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45355. }
  45356. createStorageAttribute( attribute ) {
  45357. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45358. }
  45359. createIndirectStorageAttribute( attribute ) {
  45360. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45361. }
  45362. updateAttribute( attribute ) {
  45363. this.attributeUtils.updateAttribute( attribute );
  45364. }
  45365. destroyAttribute( attribute ) {
  45366. this.attributeUtils.destroyAttribute( attribute );
  45367. }
  45368. // canvas
  45369. updateSize() {
  45370. this.colorBuffer = this.textureUtils.getColorBuffer();
  45371. this.defaultRenderPassdescriptor = null;
  45372. }
  45373. // utils public
  45374. getMaxAnisotropy() {
  45375. return 16;
  45376. }
  45377. hasFeature( name ) {
  45378. return this.device.features.has( name );
  45379. }
  45380. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  45381. let dstX = 0;
  45382. let dstY = 0;
  45383. let dstLayer = 0;
  45384. let srcX = 0;
  45385. let srcY = 0;
  45386. let srcLayer = 0;
  45387. let srcWidth = srcTexture.image.width;
  45388. let srcHeight = srcTexture.image.height;
  45389. if ( srcRegion !== null ) {
  45390. srcX = srcRegion.x;
  45391. srcY = srcRegion.y;
  45392. srcLayer = srcRegion.z || 0;
  45393. srcWidth = srcRegion.width;
  45394. srcHeight = srcRegion.height;
  45395. }
  45396. if ( dstPosition !== null ) {
  45397. dstX = dstPosition.x;
  45398. dstY = dstPosition.y;
  45399. dstLayer = dstPosition.z || 0;
  45400. }
  45401. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  45402. const sourceGPU = this.get( srcTexture ).texture;
  45403. const destinationGPU = this.get( dstTexture ).texture;
  45404. encoder.copyTextureToTexture(
  45405. {
  45406. texture: sourceGPU,
  45407. mipLevel: level,
  45408. origin: { x: srcX, y: srcY, z: srcLayer }
  45409. },
  45410. {
  45411. texture: destinationGPU,
  45412. mipLevel: level,
  45413. origin: { x: dstX, y: dstY, z: dstLayer }
  45414. },
  45415. [
  45416. srcWidth,
  45417. srcHeight,
  45418. 1
  45419. ]
  45420. );
  45421. this.device.queue.submit( [ encoder.finish() ] );
  45422. }
  45423. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  45424. const renderContextData = this.get( renderContext );
  45425. let sourceGPU = null;
  45426. if ( renderContext.renderTarget ) {
  45427. if ( texture.isDepthTexture ) {
  45428. sourceGPU = this.get( renderContext.depthTexture ).texture;
  45429. } else {
  45430. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  45431. }
  45432. } else {
  45433. if ( texture.isDepthTexture ) {
  45434. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  45435. } else {
  45436. sourceGPU = this.context.getCurrentTexture();
  45437. }
  45438. }
  45439. const destinationGPU = this.get( texture ).texture;
  45440. if ( sourceGPU.format !== destinationGPU.format ) {
  45441. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  45442. return;
  45443. }
  45444. let encoder;
  45445. if ( renderContextData.currentPass ) {
  45446. renderContextData.currentPass.end();
  45447. encoder = renderContextData.encoder;
  45448. } else {
  45449. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  45450. }
  45451. encoder.copyTextureToTexture(
  45452. {
  45453. texture: sourceGPU,
  45454. origin: { x: rectangle.x, y: rectangle.y, z: 0 }
  45455. },
  45456. {
  45457. texture: destinationGPU
  45458. },
  45459. [
  45460. rectangle.z,
  45461. rectangle.w
  45462. ]
  45463. );
  45464. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  45465. if ( renderContextData.currentPass ) {
  45466. const { descriptor } = renderContextData;
  45467. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  45468. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  45469. }
  45470. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45471. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45472. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  45473. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45474. } else {
  45475. this.device.queue.submit( [ encoder.finish() ] );
  45476. }
  45477. }
  45478. }
  45479. class IESSpotLight extends SpotLight {
  45480. constructor( color, intensity, distance, angle, penumbra, decay ) {
  45481. super( color, intensity, distance, angle, penumbra, decay );
  45482. this.iesMap = null;
  45483. }
  45484. copy( source, recursive ) {
  45485. super.copy( source, recursive );
  45486. this.iesMap = source.iesMap;
  45487. return this;
  45488. }
  45489. }
  45490. class StandardNodeLibrary extends NodeLibrary {
  45491. constructor() {
  45492. super();
  45493. this.addMaterial( MeshPhongNodeMaterial, MeshPhongMaterial );
  45494. this.addMaterial( MeshStandardNodeMaterial, MeshStandardMaterial );
  45495. this.addMaterial( MeshPhysicalNodeMaterial, MeshPhysicalMaterial );
  45496. this.addMaterial( MeshToonNodeMaterial, MeshToonMaterial );
  45497. this.addMaterial( MeshBasicNodeMaterial, MeshBasicMaterial );
  45498. this.addMaterial( MeshLambertNodeMaterial, MeshLambertMaterial );
  45499. this.addMaterial( MeshNormalNodeMaterial, MeshNormalMaterial );
  45500. this.addMaterial( MeshMatcapNodeMaterial, MeshMatcapMaterial );
  45501. this.addMaterial( LineBasicNodeMaterial, LineBasicMaterial );
  45502. this.addMaterial( LineDashedNodeMaterial, LineDashedMaterial );
  45503. this.addMaterial( PointsNodeMaterial, PointsMaterial );
  45504. this.addMaterial( SpriteNodeMaterial, SpriteMaterial );
  45505. this.addMaterial( ShadowNodeMaterial, ShadowMaterial );
  45506. this.addLight( PointLightNode, PointLight );
  45507. this.addLight( DirectionalLightNode, DirectionalLight );
  45508. this.addLight( RectAreaLightNode, RectAreaLight );
  45509. this.addLight( SpotLightNode, SpotLight );
  45510. this.addLight( AmbientLightNode, AmbientLight );
  45511. this.addLight( HemisphereLightNode, HemisphereLight );
  45512. this.addLight( LightProbeNode, LightProbe );
  45513. this.addLight( IESSpotLightNode, IESSpotLight );
  45514. this.addToneMapping( linearToneMapping, LinearToneMapping );
  45515. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  45516. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  45517. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  45518. this.addToneMapping( agxToneMapping, AgXToneMapping );
  45519. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  45520. }
  45521. }
  45522. /*
  45523. const debugHandler = {
  45524. get: function ( target, name ) {
  45525. // Add |update
  45526. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  45527. return target[ name ];
  45528. }
  45529. };
  45530. */
  45531. class WebGPURenderer extends Renderer {
  45532. constructor( parameters = {} ) {
  45533. let BackendClass;
  45534. if ( parameters.forceWebGL ) {
  45535. BackendClass = WebGLBackend;
  45536. } else {
  45537. BackendClass = WebGPUBackend;
  45538. parameters.getFallback = () => {
  45539. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  45540. return new WebGLBackend( parameters );
  45541. };
  45542. }
  45543. const backend = new BackendClass( parameters );
  45544. //super( new Proxy( backend, debugHandler ) );
  45545. super( backend, parameters );
  45546. this.library = new StandardNodeLibrary();
  45547. this.isWebGPURenderer = true;
  45548. }
  45549. }
  45550. class BundleGroup extends Group {
  45551. constructor() {
  45552. super();
  45553. this.isBundleGroup = true;
  45554. this.type = 'BundleGroup';
  45555. this.static = true;
  45556. this.version = 0;
  45557. }
  45558. set needsUpdate( value ) {
  45559. if ( value === true ) this.version ++;
  45560. }
  45561. }
  45562. const _material = /*@__PURE__*/ new NodeMaterial();
  45563. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  45564. class PostProcessing {
  45565. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  45566. this.renderer = renderer;
  45567. this.outputNode = outputNode;
  45568. this.outputColorTransform = true;
  45569. this.needsUpdate = true;
  45570. _material.name = 'PostProcessing';
  45571. }
  45572. render() {
  45573. this.update();
  45574. const renderer = this.renderer;
  45575. const toneMapping = renderer.toneMapping;
  45576. const outputColorSpace = renderer.outputColorSpace;
  45577. renderer.toneMapping = NoToneMapping;
  45578. renderer.outputColorSpace = LinearSRGBColorSpace;
  45579. //
  45580. _quadMesh.render( renderer );
  45581. //
  45582. renderer.toneMapping = toneMapping;
  45583. renderer.outputColorSpace = outputColorSpace;
  45584. }
  45585. update() {
  45586. if ( this.needsUpdate === true ) {
  45587. const renderer = this.renderer;
  45588. const toneMapping = renderer.toneMapping;
  45589. const outputColorSpace = renderer.outputColorSpace;
  45590. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  45591. _quadMesh.material.needsUpdate = true;
  45592. this.needsUpdate = false;
  45593. }
  45594. }
  45595. async renderAsync() {
  45596. this.update();
  45597. const renderer = this.renderer;
  45598. const toneMapping = renderer.toneMapping;
  45599. const outputColorSpace = renderer.outputColorSpace;
  45600. renderer.toneMapping = NoToneMapping;
  45601. renderer.outputColorSpace = LinearSRGBColorSpace;
  45602. //
  45603. await _quadMesh.renderAsync( renderer );
  45604. //
  45605. renderer.toneMapping = toneMapping;
  45606. renderer.outputColorSpace = outputColorSpace;
  45607. }
  45608. }
  45609. // renderer state
  45610. function saveRendererState( renderer, state = {} ) {
  45611. state.toneMapping = renderer.toneMapping;
  45612. state.toneMappingExposure = renderer.toneMappingExposure;
  45613. state.outputColorSpace = renderer.outputColorSpace;
  45614. state.renderTarget = renderer.getRenderTarget();
  45615. state.activeCubeFace = renderer.getActiveCubeFace();
  45616. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  45617. state.renderObjectFunction = renderer.getRenderObjectFunction();
  45618. state.pixelRatio = renderer.getPixelRatio();
  45619. state.mrt = renderer.getMRT();
  45620. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  45621. state.clearAlpha = renderer.getClearAlpha();
  45622. state.autoClear = renderer.autoClear;
  45623. state.scissorTest = renderer.getScissorTest();
  45624. return state;
  45625. }
  45626. function resetRendererState( renderer, state ) {
  45627. state = saveRendererState( renderer, state );
  45628. renderer.setMRT( null );
  45629. renderer.setRenderObjectFunction( null );
  45630. renderer.setClearColor( 0x000000, 1 );
  45631. renderer.autoClear = true;
  45632. return state;
  45633. }
  45634. function restoreRendererState( renderer, state ) {
  45635. renderer.toneMapping = state.toneMapping;
  45636. renderer.toneMappingExposure = state.toneMappingExposure;
  45637. renderer.outputColorSpace = state.outputColorSpace;
  45638. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  45639. renderer.setRenderObjectFunction( state.renderObjectFunction );
  45640. renderer.setPixelRatio( state.pixelRatio );
  45641. renderer.setMRT( state.mrt );
  45642. renderer.setClearColor( state.clearColor, state.clearAlpha );
  45643. renderer.autoClear = state.autoClear;
  45644. renderer.setScissorTest( state.scissorTest );
  45645. }
  45646. // renderer and scene state
  45647. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  45648. state = saveRendererState( renderer, state );
  45649. state.background = scene.background;
  45650. state.backgroundNode = scene.backgroundNode;
  45651. state.overrideMaterial = scene.overrideMaterial;
  45652. return state;
  45653. }
  45654. function resetRendererAndSceneState( renderer, scene, state ) {
  45655. state = saveRendererAndSceneState( renderer, scene, state );
  45656. scene.background = null;
  45657. scene.backgroundNode = null;
  45658. scene.overrideMaterial = null;
  45659. return state;
  45660. }
  45661. function restoreRendererAndSceneState( renderer, scene, state ) {
  45662. restoreRendererState( renderer, state );
  45663. scene.background = state.background;
  45664. scene.backgroundNode = state.backgroundNode;
  45665. scene.overrideMaterial = state.overrideMaterial;
  45666. }
  45667. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  45668. __proto__: null,
  45669. resetRendererAndSceneState: resetRendererAndSceneState,
  45670. resetRendererState: resetRendererState,
  45671. restoreRendererAndSceneState: restoreRendererAndSceneState,
  45672. restoreRendererState: restoreRendererState,
  45673. saveRendererAndSceneState: saveRendererAndSceneState,
  45674. saveRendererState: saveRendererState
  45675. });
  45676. class StorageTexture extends Texture {
  45677. constructor( width = 1, height = 1 ) {
  45678. super();
  45679. this.image = { width, height };
  45680. this.magFilter = LinearFilter;
  45681. this.minFilter = LinearFilter;
  45682. this.isStorageTexture = true;
  45683. }
  45684. }
  45685. class StorageBufferAttribute extends BufferAttribute {
  45686. constructor( array, itemSize, typeClass = Float32Array ) {
  45687. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  45688. super( array, itemSize );
  45689. this.isStorageBufferAttribute = true;
  45690. }
  45691. }
  45692. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  45693. constructor( array, itemSize, typeClass = Float32Array ) {
  45694. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  45695. super( array, itemSize );
  45696. this.isStorageInstancedBufferAttribute = true;
  45697. }
  45698. }
  45699. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  45700. constructor( array, itemSize ) {
  45701. super( array, itemSize, Uint32Array );
  45702. this.isIndirectStorageBufferAttribute = true;
  45703. }
  45704. }
  45705. class NodeLoader extends Loader {
  45706. constructor( manager ) {
  45707. super( manager );
  45708. this.textures = {};
  45709. this.nodes = {};
  45710. }
  45711. load( url, onLoad, onProgress, onError ) {
  45712. const loader = new FileLoader( this.manager );
  45713. loader.setPath( this.path );
  45714. loader.setRequestHeader( this.requestHeader );
  45715. loader.setWithCredentials( this.withCredentials );
  45716. loader.load( url, ( text ) => {
  45717. try {
  45718. onLoad( this.parse( JSON.parse( text ) ) );
  45719. } catch ( e ) {
  45720. if ( onError ) {
  45721. onError( e );
  45722. } else {
  45723. console.error( e );
  45724. }
  45725. this.manager.itemError( url );
  45726. }
  45727. }, onProgress, onError );
  45728. }
  45729. parseNodes( json ) {
  45730. const nodes = {};
  45731. if ( json !== undefined ) {
  45732. for ( const nodeJSON of json ) {
  45733. const { uuid, type } = nodeJSON;
  45734. nodes[ uuid ] = this.createNodeFromType( type );
  45735. nodes[ uuid ].uuid = uuid;
  45736. }
  45737. const meta = { nodes, textures: this.textures };
  45738. for ( const nodeJSON of json ) {
  45739. nodeJSON.meta = meta;
  45740. const node = nodes[ nodeJSON.uuid ];
  45741. node.deserialize( nodeJSON );
  45742. delete nodeJSON.meta;
  45743. }
  45744. }
  45745. return nodes;
  45746. }
  45747. parse( json ) {
  45748. const node = this.createNodeFromType( json.type );
  45749. node.uuid = json.uuid;
  45750. const nodes = this.parseNodes( json.nodes );
  45751. const meta = { nodes, textures: this.textures };
  45752. json.meta = meta;
  45753. node.deserialize( json );
  45754. delete json.meta;
  45755. return node;
  45756. }
  45757. setTextures( value ) {
  45758. this.textures = value;
  45759. return this;
  45760. }
  45761. setNodes( value ) {
  45762. this.nodes = value;
  45763. return this;
  45764. }
  45765. createNodeFromType( type ) {
  45766. if ( this.nodes[ type ] === undefined ) {
  45767. console.error( 'THREE.NodeLoader: Node type not found:', type );
  45768. return float();
  45769. }
  45770. return nodeObject( new this.nodes[ type ]() );
  45771. }
  45772. }
  45773. class NodeMaterialLoader extends MaterialLoader {
  45774. constructor( manager ) {
  45775. super( manager );
  45776. this.nodes = {};
  45777. this.nodeMaterials = {};
  45778. }
  45779. parse( json ) {
  45780. const material = super.parse( json );
  45781. const nodes = this.nodes;
  45782. const inputNodes = json.inputNodes;
  45783. for ( const property in inputNodes ) {
  45784. const uuid = inputNodes[ property ];
  45785. material[ property ] = nodes[ uuid ];
  45786. }
  45787. return material;
  45788. }
  45789. setNodes( value ) {
  45790. this.nodes = value;
  45791. return this;
  45792. }
  45793. setNodeMaterials( value ) {
  45794. this.nodeMaterials = value;
  45795. return this;
  45796. }
  45797. createMaterialFromType( type ) {
  45798. const materialClass = this.nodeMaterials[ type ];
  45799. if ( materialClass !== undefined ) {
  45800. return new materialClass();
  45801. }
  45802. return super.createMaterialFromType( type );
  45803. }
  45804. }
  45805. class NodeObjectLoader extends ObjectLoader {
  45806. constructor( manager ) {
  45807. super( manager );
  45808. this.nodes = {};
  45809. this.nodeMaterials = {};
  45810. this._nodesJSON = null;
  45811. }
  45812. setNodes( value ) {
  45813. this.nodes = value;
  45814. return this;
  45815. }
  45816. setNodeMaterials( value ) {
  45817. this.nodeMaterials = value;
  45818. return this;
  45819. }
  45820. parse( json, onLoad ) {
  45821. this._nodesJSON = json.nodes;
  45822. const data = super.parse( json, onLoad );
  45823. this._nodesJSON = null; // dispose
  45824. return data;
  45825. }
  45826. parseNodes( json, textures ) {
  45827. if ( json !== undefined ) {
  45828. const loader = new NodeLoader();
  45829. loader.setNodes( this.nodes );
  45830. loader.setTextures( textures );
  45831. return loader.parseNodes( json );
  45832. }
  45833. return {};
  45834. }
  45835. parseMaterials( json, textures ) {
  45836. const materials = {};
  45837. if ( json !== undefined ) {
  45838. const nodes = this.parseNodes( this._nodesJSON, textures );
  45839. const loader = new NodeMaterialLoader();
  45840. loader.setTextures( textures );
  45841. loader.setNodes( nodes );
  45842. loader.setNodeMaterials( this.nodeMaterials );
  45843. for ( let i = 0, l = json.length; i < l; i ++ ) {
  45844. const data = json[ i ];
  45845. materials[ data.uuid ] = loader.parse( data );
  45846. }
  45847. }
  45848. return materials;
  45849. }
  45850. }
  45851. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  45852. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  45853. revision: REVISION,
  45854. } } ) );
  45855. }
  45856. if ( typeof window !== 'undefined' ) {
  45857. if ( window.__THREE__ ) {
  45858. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  45859. } else {
  45860. window.__THREE__ = REVISION;
  45861. }
  45862. }
  45863. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, 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, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferGeometryLoader, BufferNode, BumpMapNode, BundleGroup, 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, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DirectionalLightNode, Discard, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EPSILON, EdgesGeometry, EllipseCurve, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, ExtrudeGeometry, F_Schlick, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fn, Fog, FogExp2, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLBufferAttribute, GLSL1, GLSL3, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightNode, IESSpotLight, IESSpotLightNode, INFINITY, IcosahedronGeometry, If, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, 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, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line, Line2NodeMaterial, Line3, LineBasicMaterial, LineBasicNodeMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineDashedNodeMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, Loop, LoopNode, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, 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, OutputStructNode, PCFShadowMap$1 as PCFShadowMap, PCFSoftShadowMap$1 as PCFSoftShadowMap, PI, PI2, PMREMGenerator, PMREMNode, ParameterNode, PassNode, Path, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, PointLightNode, PointUVNode, Points, PointsMaterial, PointsNodeMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PostProcessing, PostProcessingUtils, 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, 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, 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, Scene, SceneNode, Schlick_to_F0, ScreenNode, ScriptableNode, ScriptableNodeResources, ScriptableValueNode, SetNode, ShaderMaterial, ShaderNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SkinningNode, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SplitNode, SpotLight, SpotLightHelper, SpotLightNode, Sprite, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TBNViewMatrix, TOUCH, TangentSpaceNormalMap, TempNode, TetrahedronGeometry, Texture, Texture3DNode, TextureLoader, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TorusGeometry, TorusKnotGeometry, 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, agxToneMapping, all, alphaT, and, anisotropy, anisotropyB, anisotropyT, any, append, arrayBuffer, asin, assign, atan, atan2, atomicAdd, atomicAnd, atomicFunc, atomicMax, atomicMin, atomicOr, atomicStore, atomicSub, atomicXor, attenuationColor, attenuationDistance, attribute, backgroundBlurriness, backgroundIntensity, backgroundRotation, batch, billboarding, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, blur, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, cdl, ceil, checker, cineonToneMapping, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToWorking, colorToDirection, compute, cond, context, convert, convertColorSpace, convertToTexture, cos, createCanvasElement, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, deltaTime, densityFog, depth, depthPass, difference, diffuseColor, directPointLight, directionToColor, dispersion, distance, div, dodge, dot, drawIndex, dynamicBufferAttribute, element, emissive, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gain, gapSize, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getNormalFromDepth, getParallaxCorrectNormal, getRoughness, getScreenPosition, getShIrradianceAt, getTextureIndex, getViewPosition, glsl, glslFn, grayscale, greaterThan, greaterThanEqual, hash, highPrecisionModelNormalViewMatrix, highPrecisionModelViewMatrix, hue, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, invocationLocalIndex, invocationSubgroupIndex, ior, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightPosition, lightTargetDirection, lightTargetPosition, lightViewPosition, lightingContext, lights, linearDepth, linearToneMapping, localId, log, log2, loop, luminance, 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, 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, numWorkgroups, objectDirection, objectGroup, objectPosition, objectScale, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, passTexture, pcurve, perspectiveDepthToLogarithmicDepth, perspectiveDepthToViewZ, 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, rotate, rotateUV, roughness, round, rtt, sRGBTransferEOTF, sRGBTransferOETF, sampler, saturate, saturation, screen, screenCoordinate, screenSize, screenUV, scriptable, scriptableValue, select, setCurrentStack, shaderStages, shadow, sharedUniformGroup, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, smoothstepElement, specularColor, specularF90, spherizeUV, split, spritesheetUV, sqrt, stack, step, storage, storageBarrier, storageObject, storageTexture, string, sub, subgroupIndex, subgroupSize, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBarrier, textureBicubic, textureCubeUV, textureLoad, textureSize, textureStore, thickness, threshold, time, timerDelta, timerGlobal, timerLocal, toOutputColorSpace, toWorkingColorSpace, toneMapping, toneMappingExposure, toonOutlinePass, transformDirection, transformNormal, transformNormalToView, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, 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, workgroupId, workingToColorSpace, xor };
粤ICP备19079148号