three-loader-3dtiles.esm.js 500 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367
  1. import { CanvasTexture, LinearFilter, RepeatWrapping, Frustum, Matrix4 as Matrix4$1, Group, PlaneGeometry, Vector3 as Vector3$1, MeshBasicMaterial, DoubleSide, Mesh, ArrowHelper, Color, BoxGeometry, EdgesGeometry, LineSegments, LineBasicMaterial, Vector2 as Vector2$1, ShaderMaterial, Euler, BufferGeometry, Float32BufferAttribute, Uint8BufferAttribute, BufferAttribute, Points } from 'three';
  2. import { GLTFLoader as GLTFLoader$1 } from 'three/examples/jsm/loaders/GLTFLoader.js';
  3. import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
  4. import { KTX2Loader } from 'three/examples/jsm/loaders/KTX2Loader.js';
  5. function _mergeNamespaces(n, m) {
  6. m.forEach(function (e) {
  7. e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
  8. if (k !== 'default' && !(k in n)) {
  9. var d = Object.getOwnPropertyDescriptor(e, k);
  10. Object.defineProperty(n, k, d.get ? d : {
  11. enumerable: true,
  12. get: function () { return e[k]; }
  13. });
  14. }
  15. });
  16. });
  17. return Object.freeze(n);
  18. }
  19. /******************************************************************************
  20. Copyright (c) Microsoft Corporation.
  21. Permission to use, copy, modify, and/or distribute this software for any
  22. purpose with or without fee is hereby granted.
  23. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  24. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  25. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  26. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  27. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  28. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  29. PERFORMANCE OF THIS SOFTWARE.
  30. ***************************************************************************** */
  31. function __awaiter(thisArg, _arguments, P, generator) {
  32. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  33. return new (P || (P = Promise))(function (resolve, reject) {
  34. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  35. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  36. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  37. step((generator = generator.apply(thisArg, _arguments || [])).next());
  38. });
  39. }
  40. function assert$7(condition, message) {
  41. if (!condition) {
  42. throw new Error(message || 'loader assertion failed.');
  43. }
  44. }
  45. const isBrowser$2 = Boolean(typeof process !== 'object' || String(process) !== '[object process]' || process.browser);
  46. const matches$1 = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  47. matches$1 && parseFloat(matches$1[1]) || 0;
  48. const VERSION$8 = "3.2.5" ;
  49. function assert$6(condition, message) {
  50. if (!condition) {
  51. throw new Error(message || 'loaders.gl assertion failed.');
  52. }
  53. }
  54. const globals$1 = {
  55. self: typeof self !== 'undefined' && self,
  56. window: typeof window !== 'undefined' && window,
  57. global: typeof global !== 'undefined' && global,
  58. document: typeof document !== 'undefined' && document
  59. };
  60. const global_ = globals$1.global || globals$1.self || globals$1.window || {};
  61. const isBrowser$1 = typeof process !== 'object' || String(process) !== '[object process]' || process.browser;
  62. const isWorker = typeof importScripts === 'function';
  63. const isMobile = typeof window !== 'undefined' && typeof window.orientation !== 'undefined';
  64. const matches = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  65. matches && parseFloat(matches[1]) || 0;
  66. function _defineProperty(obj, key, value) {
  67. if (key in obj) {
  68. Object.defineProperty(obj, key, {
  69. value: value,
  70. enumerable: true,
  71. configurable: true,
  72. writable: true
  73. });
  74. } else {
  75. obj[key] = value;
  76. }
  77. return obj;
  78. }
  79. class WorkerJob {
  80. constructor(jobName, workerThread) {
  81. _defineProperty(this, "name", void 0);
  82. _defineProperty(this, "workerThread", void 0);
  83. _defineProperty(this, "isRunning", true);
  84. _defineProperty(this, "result", void 0);
  85. _defineProperty(this, "_resolve", () => {});
  86. _defineProperty(this, "_reject", () => {});
  87. this.name = jobName;
  88. this.workerThread = workerThread;
  89. this.result = new Promise((resolve, reject) => {
  90. this._resolve = resolve;
  91. this._reject = reject;
  92. });
  93. }
  94. postMessage(type, payload) {
  95. this.workerThread.postMessage({
  96. source: 'loaders.gl',
  97. type,
  98. payload
  99. });
  100. }
  101. done(value) {
  102. assert$6(this.isRunning);
  103. this.isRunning = false;
  104. this._resolve(value);
  105. }
  106. error(error) {
  107. assert$6(this.isRunning);
  108. this.isRunning = false;
  109. this._reject(error);
  110. }
  111. }
  112. class Worker$1 {}
  113. const workerURLCache = new Map();
  114. function getLoadableWorkerURL(props) {
  115. assert$6(props.source && !props.url || !props.source && props.url);
  116. let workerURL = workerURLCache.get(props.source || props.url);
  117. if (!workerURL) {
  118. if (props.url) {
  119. workerURL = getLoadableWorkerURLFromURL(props.url);
  120. workerURLCache.set(props.url, workerURL);
  121. }
  122. if (props.source) {
  123. workerURL = getLoadableWorkerURLFromSource(props.source);
  124. workerURLCache.set(props.source, workerURL);
  125. }
  126. }
  127. assert$6(workerURL);
  128. return workerURL;
  129. }
  130. function getLoadableWorkerURLFromURL(url) {
  131. if (!url.startsWith('http')) {
  132. return url;
  133. }
  134. const workerSource = buildScriptSource(url);
  135. return getLoadableWorkerURLFromSource(workerSource);
  136. }
  137. function getLoadableWorkerURLFromSource(workerSource) {
  138. const blob = new Blob([workerSource], {
  139. type: 'application/javascript'
  140. });
  141. return URL.createObjectURL(blob);
  142. }
  143. function buildScriptSource(workerUrl) {
  144. return "try {\n importScripts('".concat(workerUrl, "');\n} catch (error) {\n console.error(error);\n throw error;\n}");
  145. }
  146. function getTransferList(object, recursive = true, transfers) {
  147. const transfersSet = transfers || new Set();
  148. if (!object) ; else if (isTransferable(object)) {
  149. transfersSet.add(object);
  150. } else if (isTransferable(object.buffer)) {
  151. transfersSet.add(object.buffer);
  152. } else if (ArrayBuffer.isView(object)) ; else if (recursive && typeof object === 'object') {
  153. for (const key in object) {
  154. getTransferList(object[key], recursive, transfersSet);
  155. }
  156. }
  157. return transfers === undefined ? Array.from(transfersSet) : [];
  158. }
  159. function isTransferable(object) {
  160. if (!object) {
  161. return false;
  162. }
  163. if (object instanceof ArrayBuffer) {
  164. return true;
  165. }
  166. if (typeof MessagePort !== 'undefined' && object instanceof MessagePort) {
  167. return true;
  168. }
  169. if (typeof ImageBitmap !== 'undefined' && object instanceof ImageBitmap) {
  170. return true;
  171. }
  172. if (typeof OffscreenCanvas !== 'undefined' && object instanceof OffscreenCanvas) {
  173. return true;
  174. }
  175. return false;
  176. }
  177. const NOOP = () => {};
  178. class WorkerThread {
  179. static isSupported() {
  180. return typeof Worker !== 'undefined' && isBrowser$1 || typeof Worker$1 !== undefined;
  181. }
  182. constructor(props) {
  183. _defineProperty(this, "name", void 0);
  184. _defineProperty(this, "source", void 0);
  185. _defineProperty(this, "url", void 0);
  186. _defineProperty(this, "terminated", false);
  187. _defineProperty(this, "worker", void 0);
  188. _defineProperty(this, "onMessage", void 0);
  189. _defineProperty(this, "onError", void 0);
  190. _defineProperty(this, "_loadableURL", '');
  191. const {
  192. name,
  193. source,
  194. url
  195. } = props;
  196. assert$6(source || url);
  197. this.name = name;
  198. this.source = source;
  199. this.url = url;
  200. this.onMessage = NOOP;
  201. this.onError = error => console.log(error);
  202. this.worker = isBrowser$1 ? this._createBrowserWorker() : this._createNodeWorker();
  203. }
  204. destroy() {
  205. this.onMessage = NOOP;
  206. this.onError = NOOP;
  207. this.worker.terminate();
  208. this.terminated = true;
  209. }
  210. get isRunning() {
  211. return Boolean(this.onMessage);
  212. }
  213. postMessage(data, transferList) {
  214. transferList = transferList || getTransferList(data);
  215. this.worker.postMessage(data, transferList);
  216. }
  217. _getErrorFromErrorEvent(event) {
  218. let message = 'Failed to load ';
  219. message += "worker ".concat(this.name, " from ").concat(this.url, ". ");
  220. if (event.message) {
  221. message += "".concat(event.message, " in ");
  222. }
  223. if (event.lineno) {
  224. message += ":".concat(event.lineno, ":").concat(event.colno);
  225. }
  226. return new Error(message);
  227. }
  228. _createBrowserWorker() {
  229. this._loadableURL = getLoadableWorkerURL({
  230. source: this.source,
  231. url: this.url
  232. });
  233. const worker = new Worker(this._loadableURL, {
  234. name: this.name
  235. });
  236. worker.onmessage = event => {
  237. if (!event.data) {
  238. this.onError(new Error('No data received'));
  239. } else {
  240. this.onMessage(event.data);
  241. }
  242. };
  243. worker.onerror = error => {
  244. this.onError(this._getErrorFromErrorEvent(error));
  245. this.terminated = true;
  246. };
  247. worker.onmessageerror = event => console.error(event);
  248. return worker;
  249. }
  250. _createNodeWorker() {
  251. let worker;
  252. if (this.url) {
  253. const absolute = this.url.includes(':/') || this.url.startsWith('/');
  254. const url = absolute ? this.url : "./".concat(this.url);
  255. worker = new Worker$1(url, {
  256. eval: false
  257. });
  258. } else if (this.source) {
  259. worker = new Worker$1(this.source, {
  260. eval: true
  261. });
  262. } else {
  263. throw new Error('no worker');
  264. }
  265. worker.on('message', data => {
  266. this.onMessage(data);
  267. });
  268. worker.on('error', error => {
  269. this.onError(error);
  270. });
  271. worker.on('exit', code => {});
  272. return worker;
  273. }
  274. }
  275. class WorkerPool {
  276. static isSupported() {
  277. return WorkerThread.isSupported();
  278. }
  279. constructor(props) {
  280. _defineProperty(this, "name", 'unnamed');
  281. _defineProperty(this, "source", void 0);
  282. _defineProperty(this, "url", void 0);
  283. _defineProperty(this, "maxConcurrency", 1);
  284. _defineProperty(this, "maxMobileConcurrency", 1);
  285. _defineProperty(this, "onDebug", () => {});
  286. _defineProperty(this, "reuseWorkers", true);
  287. _defineProperty(this, "props", {});
  288. _defineProperty(this, "jobQueue", []);
  289. _defineProperty(this, "idleQueue", []);
  290. _defineProperty(this, "count", 0);
  291. _defineProperty(this, "isDestroyed", false);
  292. this.source = props.source;
  293. this.url = props.url;
  294. this.setProps(props);
  295. }
  296. destroy() {
  297. this.idleQueue.forEach(worker => worker.destroy());
  298. this.isDestroyed = true;
  299. }
  300. setProps(props) {
  301. this.props = { ...this.props,
  302. ...props
  303. };
  304. if (props.name !== undefined) {
  305. this.name = props.name;
  306. }
  307. if (props.maxConcurrency !== undefined) {
  308. this.maxConcurrency = props.maxConcurrency;
  309. }
  310. if (props.maxMobileConcurrency !== undefined) {
  311. this.maxMobileConcurrency = props.maxMobileConcurrency;
  312. }
  313. if (props.reuseWorkers !== undefined) {
  314. this.reuseWorkers = props.reuseWorkers;
  315. }
  316. if (props.onDebug !== undefined) {
  317. this.onDebug = props.onDebug;
  318. }
  319. }
  320. async startJob(name, onMessage = (job, type, data) => job.done(data), onError = (job, error) => job.error(error)) {
  321. const startPromise = new Promise(onStart => {
  322. this.jobQueue.push({
  323. name,
  324. onMessage,
  325. onError,
  326. onStart
  327. });
  328. return this;
  329. });
  330. this._startQueuedJob();
  331. return await startPromise;
  332. }
  333. async _startQueuedJob() {
  334. if (!this.jobQueue.length) {
  335. return;
  336. }
  337. const workerThread = this._getAvailableWorker();
  338. if (!workerThread) {
  339. return;
  340. }
  341. const queuedJob = this.jobQueue.shift();
  342. if (queuedJob) {
  343. this.onDebug({
  344. message: 'Starting job',
  345. name: queuedJob.name,
  346. workerThread,
  347. backlog: this.jobQueue.length
  348. });
  349. const job = new WorkerJob(queuedJob.name, workerThread);
  350. workerThread.onMessage = data => queuedJob.onMessage(job, data.type, data.payload);
  351. workerThread.onError = error => queuedJob.onError(job, error);
  352. queuedJob.onStart(job);
  353. try {
  354. await job.result;
  355. } finally {
  356. this.returnWorkerToQueue(workerThread);
  357. }
  358. }
  359. }
  360. returnWorkerToQueue(worker) {
  361. const shouldDestroyWorker = this.isDestroyed || !this.reuseWorkers || this.count > this._getMaxConcurrency();
  362. if (shouldDestroyWorker) {
  363. worker.destroy();
  364. this.count--;
  365. } else {
  366. this.idleQueue.push(worker);
  367. }
  368. if (!this.isDestroyed) {
  369. this._startQueuedJob();
  370. }
  371. }
  372. _getAvailableWorker() {
  373. if (this.idleQueue.length > 0) {
  374. return this.idleQueue.shift() || null;
  375. }
  376. if (this.count < this._getMaxConcurrency()) {
  377. this.count++;
  378. const name = "".concat(this.name.toLowerCase(), " (#").concat(this.count, " of ").concat(this.maxConcurrency, ")");
  379. return new WorkerThread({
  380. name,
  381. source: this.source,
  382. url: this.url
  383. });
  384. }
  385. return null;
  386. }
  387. _getMaxConcurrency() {
  388. return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
  389. }
  390. }
  391. const DEFAULT_PROPS$3 = {
  392. maxConcurrency: 3,
  393. maxMobileConcurrency: 1,
  394. reuseWorkers: true,
  395. onDebug: () => {}
  396. };
  397. class WorkerFarm {
  398. static isSupported() {
  399. return WorkerThread.isSupported();
  400. }
  401. static getWorkerFarm(props = {}) {
  402. WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});
  403. WorkerFarm._workerFarm.setProps(props);
  404. return WorkerFarm._workerFarm;
  405. }
  406. constructor(props) {
  407. _defineProperty(this, "props", void 0);
  408. _defineProperty(this, "workerPools", new Map());
  409. this.props = { ...DEFAULT_PROPS$3
  410. };
  411. this.setProps(props);
  412. this.workerPools = new Map();
  413. }
  414. destroy() {
  415. for (const workerPool of this.workerPools.values()) {
  416. workerPool.destroy();
  417. }
  418. this.workerPools = new Map();
  419. }
  420. setProps(props) {
  421. this.props = { ...this.props,
  422. ...props
  423. };
  424. for (const workerPool of this.workerPools.values()) {
  425. workerPool.setProps(this._getWorkerPoolProps());
  426. }
  427. }
  428. getWorkerPool(options) {
  429. const {
  430. name,
  431. source,
  432. url
  433. } = options;
  434. let workerPool = this.workerPools.get(name);
  435. if (!workerPool) {
  436. workerPool = new WorkerPool({
  437. name,
  438. source,
  439. url
  440. });
  441. workerPool.setProps(this._getWorkerPoolProps());
  442. this.workerPools.set(name, workerPool);
  443. }
  444. return workerPool;
  445. }
  446. _getWorkerPoolProps() {
  447. return {
  448. maxConcurrency: this.props.maxConcurrency,
  449. maxMobileConcurrency: this.props.maxMobileConcurrency,
  450. reuseWorkers: this.props.reuseWorkers,
  451. onDebug: this.props.onDebug
  452. };
  453. }
  454. }
  455. _defineProperty(WorkerFarm, "_workerFarm", void 0);
  456. const NPM_TAG = 'latest';
  457. function getWorkerURL(worker, options = {}) {
  458. const workerOptions = options[worker.id] || {};
  459. const workerFile = "".concat(worker.id, "-worker.js");
  460. let url = workerOptions.workerUrl;
  461. if (!url && worker.id === 'compression') {
  462. url = options.workerUrl;
  463. }
  464. if (options._workerType === 'test') {
  465. url = "modules/".concat(worker.module, "/dist/").concat(workerFile);
  466. }
  467. if (!url) {
  468. let version = worker.version;
  469. if (version === 'latest') {
  470. version = NPM_TAG;
  471. }
  472. const versionTag = version ? "@".concat(version) : '';
  473. url = "https://unpkg.com/@loaders.gl/".concat(worker.module).concat(versionTag, "/dist/").concat(workerFile);
  474. }
  475. assert$6(url);
  476. return url;
  477. }
  478. function validateWorkerVersion(worker, coreVersion = VERSION$8) {
  479. assert$6(worker, 'no worker provided');
  480. const workerVersion = worker.version;
  481. if (!coreVersion || !workerVersion) {
  482. return false;
  483. }
  484. return true;
  485. }
  486. var ChildProcessProxy = {};
  487. var node = /*#__PURE__*/_mergeNamespaces({
  488. __proto__: null,
  489. 'default': ChildProcessProxy
  490. }, [ChildProcessProxy]);
  491. const VERSION$7 = "3.2.5" ;
  492. const loadLibraryPromises = {};
  493. async function loadLibrary(libraryUrl, moduleName = null, options = {}) {
  494. if (moduleName) {
  495. libraryUrl = getLibraryUrl(libraryUrl, moduleName, options);
  496. }
  497. loadLibraryPromises[libraryUrl] = loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
  498. return await loadLibraryPromises[libraryUrl];
  499. }
  500. function getLibraryUrl(library, moduleName, options) {
  501. if (library.startsWith('http')) {
  502. return library;
  503. }
  504. const modules = options.modules || {};
  505. if (modules[library]) {
  506. return modules[library];
  507. }
  508. if (!isBrowser$1) {
  509. return "modules/".concat(moduleName, "/dist/libs/").concat(library);
  510. }
  511. if (options.CDN) {
  512. assert$6(options.CDN.startsWith('http'));
  513. return "".concat(options.CDN, "/").concat(moduleName, "@").concat(VERSION$7, "/dist/libs/").concat(library);
  514. }
  515. if (isWorker) {
  516. return "../src/libs/".concat(library);
  517. }
  518. return "modules/".concat(moduleName, "/src/libs/").concat(library);
  519. }
  520. async function loadLibraryFromFile(libraryUrl) {
  521. if (libraryUrl.endsWith('wasm')) {
  522. const response = await fetch(libraryUrl);
  523. return await response.arrayBuffer();
  524. }
  525. if (!isBrowser$1) {
  526. try {
  527. return node && ChildProcessProxy.requireFromFile && (await ChildProcessProxy.requireFromFile(libraryUrl));
  528. } catch {
  529. return null;
  530. }
  531. }
  532. if (isWorker) {
  533. return importScripts(libraryUrl);
  534. }
  535. const response = await fetch(libraryUrl);
  536. const scriptSource = await response.text();
  537. return loadLibraryFromString(scriptSource, libraryUrl);
  538. }
  539. function loadLibraryFromString(scriptSource, id) {
  540. if (!isBrowser$1) {
  541. return ChildProcessProxy.requireFromString && ChildProcessProxy.requireFromString(scriptSource, id);
  542. }
  543. if (isWorker) {
  544. eval.call(global_, scriptSource);
  545. return null;
  546. }
  547. const script = document.createElement('script');
  548. script.id = id;
  549. try {
  550. script.appendChild(document.createTextNode(scriptSource));
  551. } catch (e) {
  552. script.text = scriptSource;
  553. }
  554. document.body.appendChild(script);
  555. return null;
  556. }
  557. function canParseWithWorker(loader, options) {
  558. if (!WorkerFarm.isSupported()) {
  559. return false;
  560. }
  561. if (!isBrowser$1 && !(options !== null && options !== void 0 && options._nodeWorkers)) {
  562. return false;
  563. }
  564. return loader.worker && (options === null || options === void 0 ? void 0 : options.worker);
  565. }
  566. async function parseWithWorker(loader, data, options, context, parseOnMainThread) {
  567. const name = loader.id;
  568. const url = getWorkerURL(loader, options);
  569. const workerFarm = WorkerFarm.getWorkerFarm(options);
  570. const workerPool = workerFarm.getWorkerPool({
  571. name,
  572. url
  573. });
  574. options = JSON.parse(JSON.stringify(options));
  575. context = JSON.parse(JSON.stringify(context || {}));
  576. const job = await workerPool.startJob('process-on-worker', onMessage.bind(null, parseOnMainThread));
  577. job.postMessage('process', {
  578. input: data,
  579. options,
  580. context
  581. });
  582. const result = await job.result;
  583. return await result.result;
  584. }
  585. async function onMessage(parseOnMainThread, job, type, payload) {
  586. switch (type) {
  587. case 'done':
  588. job.done(payload);
  589. break;
  590. case 'error':
  591. job.error(new Error(payload.error));
  592. break;
  593. case 'process':
  594. const {
  595. id,
  596. input,
  597. options
  598. } = payload;
  599. try {
  600. const result = await parseOnMainThread(input, options);
  601. job.postMessage('done', {
  602. id,
  603. result
  604. });
  605. } catch (error) {
  606. const message = error instanceof Error ? error.message : 'unknown error';
  607. job.postMessage('error', {
  608. id,
  609. error: message
  610. });
  611. }
  612. break;
  613. default:
  614. console.warn("parse-with-worker unknown message ".concat(type));
  615. }
  616. }
  617. function getFirstCharacters$1(data, length = 5) {
  618. if (typeof data === 'string') {
  619. return data.slice(0, length);
  620. } else if (ArrayBuffer.isView(data)) {
  621. return getMagicString$3(data.buffer, data.byteOffset, length);
  622. } else if (data instanceof ArrayBuffer) {
  623. const byteOffset = 0;
  624. return getMagicString$3(data, byteOffset, length);
  625. }
  626. return '';
  627. }
  628. function getMagicString$3(arrayBuffer, byteOffset, length) {
  629. if (arrayBuffer.byteLength <= byteOffset + length) {
  630. return '';
  631. }
  632. const dataView = new DataView(arrayBuffer);
  633. let magic = '';
  634. for (let i = 0; i < length; i++) {
  635. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  636. }
  637. return magic;
  638. }
  639. function parseJSON(string) {
  640. try {
  641. return JSON.parse(string);
  642. } catch (_) {
  643. throw new Error("Failed to parse JSON from data starting with \"".concat(getFirstCharacters$1(string), "\""));
  644. }
  645. }
  646. function isBuffer$1(value) {
  647. return value && typeof value === 'object' && value.isBuffer;
  648. }
  649. function bufferToArrayBuffer(buffer) {
  650. if (isBuffer$1(buffer)) {
  651. const typedArray = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.length);
  652. return typedArray.slice().buffer;
  653. }
  654. return buffer;
  655. }
  656. function toArrayBuffer(data) {
  657. if (isBuffer$1(data)) {
  658. return bufferToArrayBuffer(data);
  659. }
  660. if (data instanceof ArrayBuffer) {
  661. return data;
  662. }
  663. if (ArrayBuffer.isView(data)) {
  664. if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
  665. return data.buffer;
  666. }
  667. return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
  668. }
  669. if (typeof data === 'string') {
  670. const text = data;
  671. const uint8Array = new TextEncoder().encode(text);
  672. return uint8Array.buffer;
  673. }
  674. if (data && typeof data === 'object' && data._toArrayBuffer) {
  675. return data._toArrayBuffer();
  676. }
  677. throw new Error('toArrayBuffer');
  678. }
  679. function compareArrayBuffers(arrayBuffer1, arrayBuffer2, byteLength) {
  680. byteLength = byteLength || arrayBuffer1.byteLength;
  681. if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {
  682. return false;
  683. }
  684. const array1 = new Uint8Array(arrayBuffer1);
  685. const array2 = new Uint8Array(arrayBuffer2);
  686. for (let i = 0; i < array1.length; ++i) {
  687. if (array1[i] !== array2[i]) {
  688. return false;
  689. }
  690. }
  691. return true;
  692. }
  693. function concatenateArrayBuffers(...sources) {
  694. const sourceArrays = sources.map(source2 => source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2);
  695. const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);
  696. const result = new Uint8Array(byteLength);
  697. let offset = 0;
  698. for (const sourceArray of sourceArrays) {
  699. result.set(sourceArray, offset);
  700. offset += sourceArray.byteLength;
  701. }
  702. return result.buffer;
  703. }
  704. function sliceArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  705. const subArray = byteLength !== undefined ? new Uint8Array(arrayBuffer).subarray(byteOffset, byteOffset + byteLength) : new Uint8Array(arrayBuffer).subarray(byteOffset);
  706. const arrayCopy = new Uint8Array(subArray);
  707. return arrayCopy.buffer;
  708. }
  709. function padToNBytes(byteLength, padding) {
  710. assert$7(byteLength >= 0);
  711. assert$7(padding > 0);
  712. return byteLength + (padding - 1) & ~(padding - 1);
  713. }
  714. function copyToArray(source, target, targetOffset) {
  715. let sourceArray;
  716. if (source instanceof ArrayBuffer) {
  717. sourceArray = new Uint8Array(source);
  718. } else {
  719. const srcByteOffset = source.byteOffset;
  720. const srcByteLength = source.byteLength;
  721. sourceArray = new Uint8Array(source.buffer || source.arrayBuffer, srcByteOffset, srcByteLength);
  722. }
  723. target.set(sourceArray, targetOffset);
  724. return targetOffset + padToNBytes(sourceArray.byteLength, 4);
  725. }
  726. async function concatenateArrayBuffersAsync(asyncIterator) {
  727. const arrayBuffers = [];
  728. for await (const chunk of asyncIterator) {
  729. arrayBuffers.push(chunk);
  730. }
  731. return concatenateArrayBuffers(...arrayBuffers);
  732. }
  733. function getHiResTimestamp$1() {
  734. let timestamp;
  735. if (typeof window !== 'undefined' && window.performance) {
  736. timestamp = window.performance.now();
  737. } else if (typeof process !== 'undefined' && process.hrtime) {
  738. const timeParts = process.hrtime();
  739. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  740. } else {
  741. timestamp = Date.now();
  742. }
  743. return timestamp;
  744. }
  745. class Stat {
  746. constructor(name, type) {
  747. _defineProperty(this, "name", void 0);
  748. _defineProperty(this, "type", void 0);
  749. _defineProperty(this, "sampleSize", 1);
  750. _defineProperty(this, "time", void 0);
  751. _defineProperty(this, "count", void 0);
  752. _defineProperty(this, "samples", void 0);
  753. _defineProperty(this, "lastTiming", void 0);
  754. _defineProperty(this, "lastSampleTime", void 0);
  755. _defineProperty(this, "lastSampleCount", void 0);
  756. _defineProperty(this, "_count", 0);
  757. _defineProperty(this, "_time", 0);
  758. _defineProperty(this, "_samples", 0);
  759. _defineProperty(this, "_startTime", 0);
  760. _defineProperty(this, "_timerPending", false);
  761. this.name = name;
  762. this.type = type;
  763. this.reset();
  764. }
  765. setSampleSize(samples) {
  766. this.sampleSize = samples;
  767. return this;
  768. }
  769. incrementCount() {
  770. this.addCount(1);
  771. return this;
  772. }
  773. decrementCount() {
  774. this.subtractCount(1);
  775. return this;
  776. }
  777. addCount(value) {
  778. this._count += value;
  779. this._samples++;
  780. this._checkSampling();
  781. return this;
  782. }
  783. subtractCount(value) {
  784. this._count -= value;
  785. this._samples++;
  786. this._checkSampling();
  787. return this;
  788. }
  789. addTime(time) {
  790. this._time += time;
  791. this.lastTiming = time;
  792. this._samples++;
  793. this._checkSampling();
  794. return this;
  795. }
  796. timeStart() {
  797. this._startTime = getHiResTimestamp$1();
  798. this._timerPending = true;
  799. return this;
  800. }
  801. timeEnd() {
  802. if (!this._timerPending) {
  803. return this;
  804. }
  805. this.addTime(getHiResTimestamp$1() - this._startTime);
  806. this._timerPending = false;
  807. this._checkSampling();
  808. return this;
  809. }
  810. getSampleAverageCount() {
  811. return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;
  812. }
  813. getSampleAverageTime() {
  814. return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;
  815. }
  816. getSampleHz() {
  817. return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1000) : 0;
  818. }
  819. getAverageCount() {
  820. return this.samples > 0 ? this.count / this.samples : 0;
  821. }
  822. getAverageTime() {
  823. return this.samples > 0 ? this.time / this.samples : 0;
  824. }
  825. getHz() {
  826. return this.time > 0 ? this.samples / (this.time / 1000) : 0;
  827. }
  828. reset() {
  829. this.time = 0;
  830. this.count = 0;
  831. this.samples = 0;
  832. this.lastTiming = 0;
  833. this.lastSampleTime = 0;
  834. this.lastSampleCount = 0;
  835. this._count = 0;
  836. this._time = 0;
  837. this._samples = 0;
  838. this._startTime = 0;
  839. this._timerPending = false;
  840. return this;
  841. }
  842. _checkSampling() {
  843. if (this._samples === this.sampleSize) {
  844. this.lastSampleTime = this._time;
  845. this.lastSampleCount = this._count;
  846. this.count += this._count;
  847. this.time += this._time;
  848. this.samples += this._samples;
  849. this._time = 0;
  850. this._count = 0;
  851. this._samples = 0;
  852. }
  853. }
  854. }
  855. class Stats {
  856. constructor(options) {
  857. _defineProperty(this, "id", void 0);
  858. _defineProperty(this, "stats", {});
  859. this.id = options.id;
  860. this.stats = {};
  861. this._initializeStats(options.stats);
  862. Object.seal(this);
  863. }
  864. get(name) {
  865. let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'count';
  866. return this._getOrCreate({
  867. name,
  868. type
  869. });
  870. }
  871. get size() {
  872. return Object.keys(this.stats).length;
  873. }
  874. reset() {
  875. for (const key in this.stats) {
  876. this.stats[key].reset();
  877. }
  878. return this;
  879. }
  880. forEach(fn) {
  881. for (const key in this.stats) {
  882. fn(this.stats[key]);
  883. }
  884. }
  885. getTable() {
  886. const table = {};
  887. this.forEach(stat => {
  888. table[stat.name] = {
  889. time: stat.time || 0,
  890. count: stat.count || 0,
  891. average: stat.getAverageTime() || 0,
  892. hz: stat.getHz() || 0
  893. };
  894. });
  895. return table;
  896. }
  897. _initializeStats() {
  898. let stats = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  899. stats.forEach(stat => this._getOrCreate(stat));
  900. }
  901. _getOrCreate(stat) {
  902. if (!stat || !stat.name) {
  903. return null;
  904. }
  905. const {
  906. name,
  907. type
  908. } = stat;
  909. if (!this.stats[name]) {
  910. if (stat instanceof Stat) {
  911. this.stats[name] = stat;
  912. } else {
  913. this.stats[name] = new Stat(name, type);
  914. }
  915. }
  916. return this.stats[name];
  917. }
  918. }
  919. const STAT_QUEUED_REQUESTS = 'Queued Requests';
  920. const STAT_ACTIVE_REQUESTS = 'Active Requests';
  921. const STAT_CANCELLED_REQUESTS = 'Cancelled Requests';
  922. const STAT_QUEUED_REQUESTS_EVER = 'Queued Requests Ever';
  923. const STAT_ACTIVE_REQUESTS_EVER = 'Active Requests Ever';
  924. const DEFAULT_PROPS$2 = {
  925. id: 'request-scheduler',
  926. throttleRequests: true,
  927. maxRequests: 6
  928. };
  929. class RequestScheduler {
  930. constructor(props = {}) {
  931. _defineProperty(this, "props", void 0);
  932. _defineProperty(this, "stats", void 0);
  933. _defineProperty(this, "activeRequestCount", 0);
  934. _defineProperty(this, "requestQueue", []);
  935. _defineProperty(this, "requestMap", new Map());
  936. _defineProperty(this, "deferredUpdate", null);
  937. this.props = { ...DEFAULT_PROPS$2,
  938. ...props
  939. };
  940. this.stats = new Stats({
  941. id: this.props.id
  942. });
  943. this.stats.get(STAT_QUEUED_REQUESTS);
  944. this.stats.get(STAT_ACTIVE_REQUESTS);
  945. this.stats.get(STAT_CANCELLED_REQUESTS);
  946. this.stats.get(STAT_QUEUED_REQUESTS_EVER);
  947. this.stats.get(STAT_ACTIVE_REQUESTS_EVER);
  948. }
  949. scheduleRequest(handle, getPriority = () => 0) {
  950. if (!this.props.throttleRequests) {
  951. return Promise.resolve({
  952. done: () => {}
  953. });
  954. }
  955. if (this.requestMap.has(handle)) {
  956. return this.requestMap.get(handle);
  957. }
  958. const request = {
  959. handle,
  960. priority: 0,
  961. getPriority
  962. };
  963. const promise = new Promise(resolve => {
  964. request.resolve = resolve;
  965. return request;
  966. });
  967. this.requestQueue.push(request);
  968. this.requestMap.set(handle, promise);
  969. this._issueNewRequests();
  970. return promise;
  971. }
  972. _issueRequest(request) {
  973. const {
  974. handle,
  975. resolve
  976. } = request;
  977. let isDone = false;
  978. const done = () => {
  979. if (!isDone) {
  980. isDone = true;
  981. this.requestMap.delete(handle);
  982. this.activeRequestCount--;
  983. this._issueNewRequests();
  984. }
  985. };
  986. this.activeRequestCount++;
  987. return resolve ? resolve({
  988. done
  989. }) : Promise.resolve({
  990. done
  991. });
  992. }
  993. _issueNewRequests() {
  994. if (!this.deferredUpdate) {
  995. this.deferredUpdate = setTimeout(() => this._issueNewRequestsAsync(), 0);
  996. }
  997. }
  998. _issueNewRequestsAsync() {
  999. this.deferredUpdate = null;
  1000. const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);
  1001. if (freeSlots === 0) {
  1002. return;
  1003. }
  1004. this._updateAllRequests();
  1005. for (let i = 0; i < freeSlots; ++i) {
  1006. const request = this.requestQueue.shift();
  1007. if (request) {
  1008. this._issueRequest(request);
  1009. }
  1010. }
  1011. }
  1012. _updateAllRequests() {
  1013. const requestQueue = this.requestQueue;
  1014. for (let i = 0; i < requestQueue.length; ++i) {
  1015. const request = requestQueue[i];
  1016. if (!this._updateRequest(request)) {
  1017. requestQueue.splice(i, 1);
  1018. this.requestMap.delete(request.handle);
  1019. i--;
  1020. }
  1021. }
  1022. requestQueue.sort((a, b) => a.priority - b.priority);
  1023. }
  1024. _updateRequest(request) {
  1025. request.priority = request.getPriority(request.handle);
  1026. if (request.priority < 0) {
  1027. request.resolve(null);
  1028. return false;
  1029. }
  1030. return true;
  1031. }
  1032. }
  1033. let pathPrefix = '';
  1034. const fileAliases = {};
  1035. function resolvePath(filename) {
  1036. for (const alias in fileAliases) {
  1037. if (filename.startsWith(alias)) {
  1038. const replacement = fileAliases[alias];
  1039. filename = filename.replace(alias, replacement);
  1040. }
  1041. }
  1042. if (!filename.startsWith('http://') && !filename.startsWith('https://')) {
  1043. filename = "".concat(pathPrefix).concat(filename);
  1044. }
  1045. return filename;
  1046. }
  1047. function filename(url) {
  1048. const slashIndex = url && url.lastIndexOf('/');
  1049. return slashIndex >= 0 ? url.substr(slashIndex + 1) : '';
  1050. }
  1051. function dirname(url) {
  1052. const slashIndex = url && url.lastIndexOf('/');
  1053. return slashIndex >= 0 ? url.substr(0, slashIndex) : '';
  1054. }
  1055. const isBoolean = x => typeof x === 'boolean';
  1056. const isFunction = x => typeof x === 'function';
  1057. const isObject = x => x !== null && typeof x === 'object';
  1058. const isPureObject = x => isObject(x) && x.constructor === {}.constructor;
  1059. const isIterable = x => x && typeof x[Symbol.iterator] === 'function';
  1060. const isAsyncIterable = x => x && typeof x[Symbol.asyncIterator] === 'function';
  1061. const isResponse = x => typeof Response !== 'undefined' && x instanceof Response || x && x.arrayBuffer && x.text && x.json;
  1062. const isBlob = x => typeof Blob !== 'undefined' && x instanceof Blob;
  1063. const isBuffer = x => x && typeof x === 'object' && x.isBuffer;
  1064. const isReadableDOMStream = x => typeof ReadableStream !== 'undefined' && x instanceof ReadableStream || isObject(x) && isFunction(x.tee) && isFunction(x.cancel) && isFunction(x.getReader);
  1065. const isReadableNodeStream = x => isObject(x) && isFunction(x.read) && isFunction(x.pipe) && isBoolean(x.readable);
  1066. const isReadableStream = x => isReadableDOMStream(x) || isReadableNodeStream(x);
  1067. const DATA_URL_PATTERN = /^data:([-\w.]+\/[-\w.+]+)(;|,)/;
  1068. const MIME_TYPE_PATTERN = /^([-\w.]+\/[-\w.+]+)/;
  1069. function parseMIMEType(mimeString) {
  1070. const matches = MIME_TYPE_PATTERN.exec(mimeString);
  1071. if (matches) {
  1072. return matches[1];
  1073. }
  1074. return mimeString;
  1075. }
  1076. function parseMIMETypeFromURL(url) {
  1077. const matches = DATA_URL_PATTERN.exec(url);
  1078. if (matches) {
  1079. return matches[1];
  1080. }
  1081. return '';
  1082. }
  1083. const QUERY_STRING_PATTERN = /\?.*/;
  1084. function getResourceUrlAndType(resource) {
  1085. if (isResponse(resource)) {
  1086. const url = stripQueryString(resource.url || '');
  1087. const contentTypeHeader = resource.headers.get('content-type') || '';
  1088. return {
  1089. url,
  1090. type: parseMIMEType(contentTypeHeader) || parseMIMETypeFromURL(url)
  1091. };
  1092. }
  1093. if (isBlob(resource)) {
  1094. return {
  1095. url: stripQueryString(resource.name || ''),
  1096. type: resource.type || ''
  1097. };
  1098. }
  1099. if (typeof resource === 'string') {
  1100. return {
  1101. url: stripQueryString(resource),
  1102. type: parseMIMETypeFromURL(resource)
  1103. };
  1104. }
  1105. return {
  1106. url: '',
  1107. type: ''
  1108. };
  1109. }
  1110. function getResourceContentLength(resource) {
  1111. if (isResponse(resource)) {
  1112. return resource.headers['content-length'] || -1;
  1113. }
  1114. if (isBlob(resource)) {
  1115. return resource.size;
  1116. }
  1117. if (typeof resource === 'string') {
  1118. return resource.length;
  1119. }
  1120. if (resource instanceof ArrayBuffer) {
  1121. return resource.byteLength;
  1122. }
  1123. if (ArrayBuffer.isView(resource)) {
  1124. return resource.byteLength;
  1125. }
  1126. return -1;
  1127. }
  1128. function stripQueryString(url) {
  1129. return url.replace(QUERY_STRING_PATTERN, '');
  1130. }
  1131. async function makeResponse(resource) {
  1132. if (isResponse(resource)) {
  1133. return resource;
  1134. }
  1135. const headers = {};
  1136. const contentLength = getResourceContentLength(resource);
  1137. if (contentLength >= 0) {
  1138. headers['content-length'] = String(contentLength);
  1139. }
  1140. const {
  1141. url,
  1142. type
  1143. } = getResourceUrlAndType(resource);
  1144. if (type) {
  1145. headers['content-type'] = type;
  1146. }
  1147. const initialDataUrl = await getInitialDataUrl(resource);
  1148. if (initialDataUrl) {
  1149. headers['x-first-bytes'] = initialDataUrl;
  1150. }
  1151. if (typeof resource === 'string') {
  1152. resource = new TextEncoder().encode(resource);
  1153. }
  1154. const response = new Response(resource, {
  1155. headers
  1156. });
  1157. Object.defineProperty(response, 'url', {
  1158. value: url
  1159. });
  1160. return response;
  1161. }
  1162. async function checkResponse(response) {
  1163. if (!response.ok) {
  1164. const message = await getResponseError(response);
  1165. throw new Error(message);
  1166. }
  1167. }
  1168. async function getResponseError(response) {
  1169. let message = "Failed to fetch resource ".concat(response.url, " (").concat(response.status, "): ");
  1170. try {
  1171. const contentType = response.headers.get('Content-Type');
  1172. let text = response.statusText;
  1173. if (contentType.includes('application/json')) {
  1174. text += " ".concat(await response.text());
  1175. }
  1176. message += text;
  1177. message = message.length > 60 ? "".concat(message.slice(0, 60), "...") : message;
  1178. } catch (error) {}
  1179. return message;
  1180. }
  1181. async function getInitialDataUrl(resource) {
  1182. const INITIAL_DATA_LENGTH = 5;
  1183. if (typeof resource === 'string') {
  1184. return "data:,".concat(resource.slice(0, INITIAL_DATA_LENGTH));
  1185. }
  1186. if (resource instanceof Blob) {
  1187. const blobSlice = resource.slice(0, 5);
  1188. return await new Promise(resolve => {
  1189. const reader = new FileReader();
  1190. reader.onload = event => {
  1191. var _event$target;
  1192. return resolve(event === null || event === void 0 ? void 0 : (_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.result);
  1193. };
  1194. reader.readAsDataURL(blobSlice);
  1195. });
  1196. }
  1197. if (resource instanceof ArrayBuffer) {
  1198. const slice = resource.slice(0, INITIAL_DATA_LENGTH);
  1199. const base64 = arrayBufferToBase64(slice);
  1200. return "data:base64,".concat(base64);
  1201. }
  1202. return null;
  1203. }
  1204. function arrayBufferToBase64(buffer) {
  1205. let binary = '';
  1206. const bytes = new Uint8Array(buffer);
  1207. for (let i = 0; i < bytes.byteLength; i++) {
  1208. binary += String.fromCharCode(bytes[i]);
  1209. }
  1210. return btoa(binary);
  1211. }
  1212. async function fetchFile(url, options) {
  1213. if (typeof url === 'string') {
  1214. url = resolvePath(url);
  1215. let fetchOptions = options;
  1216. if (options !== null && options !== void 0 && options.fetch && typeof (options === null || options === void 0 ? void 0 : options.fetch) !== 'function') {
  1217. fetchOptions = options.fetch;
  1218. }
  1219. return await fetch(url, fetchOptions);
  1220. }
  1221. return await makeResponse(url);
  1222. }
  1223. function isElectron(mockUserAgent) {
  1224. if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {
  1225. return true;
  1226. }
  1227. if (typeof process !== 'undefined' && typeof process.versions === 'object' && Boolean(process.versions.electron)) {
  1228. return true;
  1229. }
  1230. const realUserAgent = typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent;
  1231. const userAgent = mockUserAgent || realUserAgent;
  1232. if (userAgent && userAgent.indexOf('Electron') >= 0) {
  1233. return true;
  1234. }
  1235. return false;
  1236. }
  1237. function isBrowser() {
  1238. const isNode = typeof process === 'object' && String(process) === '[object process]' && !process.browser;
  1239. return !isNode || isElectron();
  1240. }
  1241. const globals = {
  1242. self: typeof self !== 'undefined' && self,
  1243. window: typeof window !== 'undefined' && window,
  1244. global: typeof global !== 'undefined' && global,
  1245. document: typeof document !== 'undefined' && document,
  1246. process: typeof process === 'object' && process
  1247. };
  1248. const window_ = globals.window || globals.self || globals.global;
  1249. const process_ = globals.process || {};
  1250. const VERSION$6 = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'untranspiled source';
  1251. isBrowser();
  1252. function getStorage(type) {
  1253. try {
  1254. const storage = window[type];
  1255. const x = '__storage_test__';
  1256. storage.setItem(x, x);
  1257. storage.removeItem(x);
  1258. return storage;
  1259. } catch (e) {
  1260. return null;
  1261. }
  1262. }
  1263. class LocalStorage {
  1264. constructor(id) {
  1265. let defaultSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1266. let type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'sessionStorage';
  1267. _defineProperty(this, "storage", void 0);
  1268. _defineProperty(this, "id", void 0);
  1269. _defineProperty(this, "config", {});
  1270. this.storage = getStorage(type);
  1271. this.id = id;
  1272. this.config = {};
  1273. Object.assign(this.config, defaultSettings);
  1274. this._loadConfiguration();
  1275. }
  1276. getConfiguration() {
  1277. return this.config;
  1278. }
  1279. setConfiguration(configuration) {
  1280. this.config = {};
  1281. return this.updateConfiguration(configuration);
  1282. }
  1283. updateConfiguration(configuration) {
  1284. Object.assign(this.config, configuration);
  1285. if (this.storage) {
  1286. const serialized = JSON.stringify(this.config);
  1287. this.storage.setItem(this.id, serialized);
  1288. }
  1289. return this;
  1290. }
  1291. _loadConfiguration() {
  1292. let configuration = {};
  1293. if (this.storage) {
  1294. const serializedConfiguration = this.storage.getItem(this.id);
  1295. configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {};
  1296. }
  1297. Object.assign(this.config, configuration);
  1298. return this;
  1299. }
  1300. }
  1301. function formatTime(ms) {
  1302. let formatted;
  1303. if (ms < 10) {
  1304. formatted = "".concat(ms.toFixed(2), "ms");
  1305. } else if (ms < 100) {
  1306. formatted = "".concat(ms.toFixed(1), "ms");
  1307. } else if (ms < 1000) {
  1308. formatted = "".concat(ms.toFixed(0), "ms");
  1309. } else {
  1310. formatted = "".concat((ms / 1000).toFixed(2), "s");
  1311. }
  1312. return formatted;
  1313. }
  1314. function leftPad(string) {
  1315. let length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 8;
  1316. const padLength = Math.max(length - string.length, 0);
  1317. return "".concat(' '.repeat(padLength)).concat(string);
  1318. }
  1319. function formatImage(image, message, scale) {
  1320. let maxWidth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 600;
  1321. const imageUrl = image.src.replace(/\(/g, '%28').replace(/\)/g, '%29');
  1322. if (image.width > maxWidth) {
  1323. scale = Math.min(scale, maxWidth / image.width);
  1324. }
  1325. const width = image.width * scale;
  1326. const height = image.height * scale;
  1327. const style = ['font-size:1px;', "padding:".concat(Math.floor(height / 2), "px ").concat(Math.floor(width / 2), "px;"), "line-height:".concat(height, "px;"), "background:url(".concat(imageUrl, ");"), "background-size:".concat(width, "px ").concat(height, "px;"), 'color:transparent;'].join('');
  1328. return ["".concat(message, " %c+"), style];
  1329. }
  1330. let COLOR;
  1331. (function (COLOR) {
  1332. COLOR[COLOR["BLACK"] = 30] = "BLACK";
  1333. COLOR[COLOR["RED"] = 31] = "RED";
  1334. COLOR[COLOR["GREEN"] = 32] = "GREEN";
  1335. COLOR[COLOR["YELLOW"] = 33] = "YELLOW";
  1336. COLOR[COLOR["BLUE"] = 34] = "BLUE";
  1337. COLOR[COLOR["MAGENTA"] = 35] = "MAGENTA";
  1338. COLOR[COLOR["CYAN"] = 36] = "CYAN";
  1339. COLOR[COLOR["WHITE"] = 37] = "WHITE";
  1340. COLOR[COLOR["BRIGHT_BLACK"] = 90] = "BRIGHT_BLACK";
  1341. COLOR[COLOR["BRIGHT_RED"] = 91] = "BRIGHT_RED";
  1342. COLOR[COLOR["BRIGHT_GREEN"] = 92] = "BRIGHT_GREEN";
  1343. COLOR[COLOR["BRIGHT_YELLOW"] = 93] = "BRIGHT_YELLOW";
  1344. COLOR[COLOR["BRIGHT_BLUE"] = 94] = "BRIGHT_BLUE";
  1345. COLOR[COLOR["BRIGHT_MAGENTA"] = 95] = "BRIGHT_MAGENTA";
  1346. COLOR[COLOR["BRIGHT_CYAN"] = 96] = "BRIGHT_CYAN";
  1347. COLOR[COLOR["BRIGHT_WHITE"] = 97] = "BRIGHT_WHITE";
  1348. })(COLOR || (COLOR = {}));
  1349. function getColor(color) {
  1350. return typeof color === 'string' ? COLOR[color.toUpperCase()] || COLOR.WHITE : color;
  1351. }
  1352. function addColor(string, color, background) {
  1353. if (!isBrowser && typeof string === 'string') {
  1354. if (color) {
  1355. color = getColor(color);
  1356. string = "\x1B[".concat(color, "m").concat(string, "\x1B[39m");
  1357. }
  1358. if (background) {
  1359. color = getColor(background);
  1360. string = "\x1B[".concat(background + 10, "m").concat(string, "\x1B[49m");
  1361. }
  1362. }
  1363. return string;
  1364. }
  1365. function autobind(obj) {
  1366. let predefined = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ['constructor'];
  1367. const proto = Object.getPrototypeOf(obj);
  1368. const propNames = Object.getOwnPropertyNames(proto);
  1369. for (const key of propNames) {
  1370. if (typeof obj[key] === 'function') {
  1371. if (!predefined.find(name => key === name)) {
  1372. obj[key] = obj[key].bind(obj);
  1373. }
  1374. }
  1375. }
  1376. }
  1377. function assert$5(condition, message) {
  1378. if (!condition) {
  1379. throw new Error(message || 'Assertion failed');
  1380. }
  1381. }
  1382. function getHiResTimestamp() {
  1383. let timestamp;
  1384. if (isBrowser && 'performance' in window_) {
  1385. var _window$performance, _window$performance$n;
  1386. timestamp = window_ === null || window_ === void 0 ? void 0 : (_window$performance = window_.performance) === null || _window$performance === void 0 ? void 0 : (_window$performance$n = _window$performance.now) === null || _window$performance$n === void 0 ? void 0 : _window$performance$n.call(_window$performance);
  1387. } else if ('hrtime' in process_) {
  1388. var _process$hrtime;
  1389. const timeParts = process_ === null || process_ === void 0 ? void 0 : (_process$hrtime = process_.hrtime) === null || _process$hrtime === void 0 ? void 0 : _process$hrtime.call(process_);
  1390. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  1391. } else {
  1392. timestamp = Date.now();
  1393. }
  1394. return timestamp;
  1395. }
  1396. const originalConsole = {
  1397. debug: isBrowser ? console.debug || console.log : console.log,
  1398. log: console.log,
  1399. info: console.info,
  1400. warn: console.warn,
  1401. error: console.error
  1402. };
  1403. const DEFAULT_SETTINGS = {
  1404. enabled: true,
  1405. level: 0
  1406. };
  1407. function noop() {}
  1408. const cache = {};
  1409. const ONCE = {
  1410. once: true
  1411. };
  1412. class Log {
  1413. constructor() {
  1414. let {
  1415. id
  1416. } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
  1417. id: ''
  1418. };
  1419. _defineProperty(this, "id", void 0);
  1420. _defineProperty(this, "VERSION", VERSION$6);
  1421. _defineProperty(this, "_startTs", getHiResTimestamp());
  1422. _defineProperty(this, "_deltaTs", getHiResTimestamp());
  1423. _defineProperty(this, "_storage", void 0);
  1424. _defineProperty(this, "userData", {});
  1425. _defineProperty(this, "LOG_THROTTLE_TIMEOUT", 0);
  1426. this.id = id;
  1427. this._storage = new LocalStorage("__probe-".concat(this.id, "__"), DEFAULT_SETTINGS);
  1428. this.userData = {};
  1429. this.timeStamp("".concat(this.id, " started"));
  1430. autobind(this);
  1431. Object.seal(this);
  1432. }
  1433. set level(newLevel) {
  1434. this.setLevel(newLevel);
  1435. }
  1436. get level() {
  1437. return this.getLevel();
  1438. }
  1439. isEnabled() {
  1440. return this._storage.config.enabled;
  1441. }
  1442. getLevel() {
  1443. return this._storage.config.level;
  1444. }
  1445. getTotal() {
  1446. return Number((getHiResTimestamp() - this._startTs).toPrecision(10));
  1447. }
  1448. getDelta() {
  1449. return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10));
  1450. }
  1451. set priority(newPriority) {
  1452. this.level = newPriority;
  1453. }
  1454. get priority() {
  1455. return this.level;
  1456. }
  1457. getPriority() {
  1458. return this.level;
  1459. }
  1460. enable() {
  1461. let enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  1462. this._storage.updateConfiguration({
  1463. enabled
  1464. });
  1465. return this;
  1466. }
  1467. setLevel(level) {
  1468. this._storage.updateConfiguration({
  1469. level
  1470. });
  1471. return this;
  1472. }
  1473. get(setting) {
  1474. return this._storage.config[setting];
  1475. }
  1476. set(setting, value) {
  1477. this._storage.updateConfiguration({
  1478. [setting]: value
  1479. });
  1480. }
  1481. settings() {
  1482. if (console.table) {
  1483. console.table(this._storage.config);
  1484. } else {
  1485. console.log(this._storage.config);
  1486. }
  1487. }
  1488. assert(condition, message) {
  1489. assert$5(condition, message);
  1490. }
  1491. warn(message) {
  1492. return this._getLogFunction(0, message, originalConsole.warn, arguments, ONCE);
  1493. }
  1494. error(message) {
  1495. return this._getLogFunction(0, message, originalConsole.error, arguments);
  1496. }
  1497. deprecated(oldUsage, newUsage) {
  1498. return this.warn("`".concat(oldUsage, "` is deprecated and will be removed in a later version. Use `").concat(newUsage, "` instead"));
  1499. }
  1500. removed(oldUsage, newUsage) {
  1501. return this.error("`".concat(oldUsage, "` has been removed. Use `").concat(newUsage, "` instead"));
  1502. }
  1503. probe(logLevel, message) {
  1504. return this._getLogFunction(logLevel, message, originalConsole.log, arguments, {
  1505. time: true,
  1506. once: true
  1507. });
  1508. }
  1509. log(logLevel, message) {
  1510. return this._getLogFunction(logLevel, message, originalConsole.debug, arguments);
  1511. }
  1512. info(logLevel, message) {
  1513. return this._getLogFunction(logLevel, message, console.info, arguments);
  1514. }
  1515. once(logLevel, message) {
  1516. for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  1517. args[_key - 2] = arguments[_key];
  1518. }
  1519. return this._getLogFunction(logLevel, message, originalConsole.debug || originalConsole.info, arguments, ONCE);
  1520. }
  1521. table(logLevel, table, columns) {
  1522. if (table) {
  1523. return this._getLogFunction(logLevel, table, console.table || noop, columns && [columns], {
  1524. tag: getTableHeader(table)
  1525. });
  1526. }
  1527. return noop;
  1528. }
  1529. image(_ref) {
  1530. let {
  1531. logLevel,
  1532. priority,
  1533. image,
  1534. message = '',
  1535. scale = 1
  1536. } = _ref;
  1537. if (!this._shouldLog(logLevel || priority)) {
  1538. return noop;
  1539. }
  1540. return isBrowser ? logImageInBrowser({
  1541. image,
  1542. message,
  1543. scale
  1544. }) : logImageInNode({
  1545. image,
  1546. message,
  1547. scale
  1548. });
  1549. }
  1550. time(logLevel, message) {
  1551. return this._getLogFunction(logLevel, message, console.time ? console.time : console.info);
  1552. }
  1553. timeEnd(logLevel, message) {
  1554. return this._getLogFunction(logLevel, message, console.timeEnd ? console.timeEnd : console.info);
  1555. }
  1556. timeStamp(logLevel, message) {
  1557. return this._getLogFunction(logLevel, message, console.timeStamp || noop);
  1558. }
  1559. group(logLevel, message) {
  1560. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
  1561. collapsed: false
  1562. };
  1563. const options = normalizeArguments({
  1564. logLevel,
  1565. message,
  1566. opts
  1567. });
  1568. const {
  1569. collapsed
  1570. } = opts;
  1571. options.method = (collapsed ? console.groupCollapsed : console.group) || console.info;
  1572. return this._getLogFunction(options);
  1573. }
  1574. groupCollapsed(logLevel, message) {
  1575. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  1576. return this.group(logLevel, message, Object.assign({}, opts, {
  1577. collapsed: true
  1578. }));
  1579. }
  1580. groupEnd(logLevel) {
  1581. return this._getLogFunction(logLevel, '', console.groupEnd || noop);
  1582. }
  1583. withGroup(logLevel, message, func) {
  1584. this.group(logLevel, message)();
  1585. try {
  1586. func();
  1587. } finally {
  1588. this.groupEnd(logLevel)();
  1589. }
  1590. }
  1591. trace() {
  1592. if (console.trace) {
  1593. console.trace();
  1594. }
  1595. }
  1596. _shouldLog(logLevel) {
  1597. return this.isEnabled() && this.getLevel() >= normalizeLogLevel(logLevel);
  1598. }
  1599. _getLogFunction(logLevel, message, method, args, opts) {
  1600. if (this._shouldLog(logLevel)) {
  1601. opts = normalizeArguments({
  1602. logLevel,
  1603. message,
  1604. args,
  1605. opts
  1606. });
  1607. method = method || opts.method;
  1608. assert$5(method);
  1609. opts.total = this.getTotal();
  1610. opts.delta = this.getDelta();
  1611. this._deltaTs = getHiResTimestamp();
  1612. const tag = opts.tag || opts.message;
  1613. if (opts.once) {
  1614. if (!cache[tag]) {
  1615. cache[tag] = getHiResTimestamp();
  1616. } else {
  1617. return noop;
  1618. }
  1619. }
  1620. message = decorateMessage(this.id, opts.message, opts);
  1621. return method.bind(console, message, ...opts.args);
  1622. }
  1623. return noop;
  1624. }
  1625. }
  1626. _defineProperty(Log, "VERSION", VERSION$6);
  1627. function normalizeLogLevel(logLevel) {
  1628. if (!logLevel) {
  1629. return 0;
  1630. }
  1631. let resolvedLevel;
  1632. switch (typeof logLevel) {
  1633. case 'number':
  1634. resolvedLevel = logLevel;
  1635. break;
  1636. case 'object':
  1637. resolvedLevel = logLevel.logLevel || logLevel.priority || 0;
  1638. break;
  1639. default:
  1640. return 0;
  1641. }
  1642. assert$5(Number.isFinite(resolvedLevel) && resolvedLevel >= 0);
  1643. return resolvedLevel;
  1644. }
  1645. function normalizeArguments(opts) {
  1646. const {
  1647. logLevel,
  1648. message
  1649. } = opts;
  1650. opts.logLevel = normalizeLogLevel(logLevel);
  1651. const args = opts.args ? Array.from(opts.args) : [];
  1652. while (args.length && args.shift() !== message) {}
  1653. switch (typeof logLevel) {
  1654. case 'string':
  1655. case 'function':
  1656. if (message !== undefined) {
  1657. args.unshift(message);
  1658. }
  1659. opts.message = logLevel;
  1660. break;
  1661. case 'object':
  1662. Object.assign(opts, logLevel);
  1663. break;
  1664. }
  1665. if (typeof opts.message === 'function') {
  1666. opts.message = opts.message();
  1667. }
  1668. const messageType = typeof opts.message;
  1669. assert$5(messageType === 'string' || messageType === 'object');
  1670. return Object.assign(opts, {
  1671. args
  1672. }, opts.opts);
  1673. }
  1674. function decorateMessage(id, message, opts) {
  1675. if (typeof message === 'string') {
  1676. const time = opts.time ? leftPad(formatTime(opts.total)) : '';
  1677. message = opts.time ? "".concat(id, ": ").concat(time, " ").concat(message) : "".concat(id, ": ").concat(message);
  1678. message = addColor(message, opts.color, opts.background);
  1679. }
  1680. return message;
  1681. }
  1682. function logImageInNode(_ref2) {
  1683. let {
  1684. image,
  1685. message = '',
  1686. scale = 1
  1687. } = _ref2;
  1688. let asciify = null;
  1689. try {
  1690. asciify = module.require('asciify-image');
  1691. } catch (error) {}
  1692. if (asciify) {
  1693. return () => asciify(image, {
  1694. fit: 'box',
  1695. width: "".concat(Math.round(80 * scale), "%")
  1696. }).then(data => console.log(data));
  1697. }
  1698. return noop;
  1699. }
  1700. function logImageInBrowser(_ref3) {
  1701. let {
  1702. image,
  1703. message = '',
  1704. scale = 1
  1705. } = _ref3;
  1706. if (typeof image === 'string') {
  1707. const img = new Image();
  1708. img.onload = () => {
  1709. const args = formatImage(img, message, scale);
  1710. console.log(...args);
  1711. };
  1712. img.src = image;
  1713. return noop;
  1714. }
  1715. const element = image.nodeName || '';
  1716. if (element.toLowerCase() === 'img') {
  1717. console.log(...formatImage(image, message, scale));
  1718. return noop;
  1719. }
  1720. if (element.toLowerCase() === 'canvas') {
  1721. const img = new Image();
  1722. img.onload = () => console.log(...formatImage(img, message, scale));
  1723. img.src = image.toDataURL();
  1724. return noop;
  1725. }
  1726. return noop;
  1727. }
  1728. function getTableHeader(table) {
  1729. for (const key in table) {
  1730. for (const title in table[key]) {
  1731. return title || 'untitled';
  1732. }
  1733. }
  1734. return 'empty';
  1735. }
  1736. const probeLog = new Log({
  1737. id: 'loaders.gl'
  1738. });
  1739. class NullLog {
  1740. log() {
  1741. return () => {};
  1742. }
  1743. info() {
  1744. return () => {};
  1745. }
  1746. warn() {
  1747. return () => {};
  1748. }
  1749. error() {
  1750. return () => {};
  1751. }
  1752. }
  1753. class ConsoleLog {
  1754. constructor() {
  1755. _defineProperty(this, "console", void 0);
  1756. this.console = console;
  1757. }
  1758. log(...args) {
  1759. return this.console.log.bind(this.console, ...args);
  1760. }
  1761. info(...args) {
  1762. return this.console.info.bind(this.console, ...args);
  1763. }
  1764. warn(...args) {
  1765. return this.console.warn.bind(this.console, ...args);
  1766. }
  1767. error(...args) {
  1768. return this.console.error.bind(this.console, ...args);
  1769. }
  1770. }
  1771. const DEFAULT_LOADER_OPTIONS = {
  1772. fetch: null,
  1773. mimeType: undefined,
  1774. nothrow: false,
  1775. log: new ConsoleLog(),
  1776. CDN: 'https://unpkg.com/@loaders.gl',
  1777. worker: true,
  1778. maxConcurrency: 3,
  1779. maxMobileConcurrency: 1,
  1780. reuseWorkers: isBrowser$2,
  1781. _nodeWorkers: false,
  1782. _workerType: '',
  1783. limit: 0,
  1784. _limitMB: 0,
  1785. batchSize: 'auto',
  1786. batchDebounceMs: 0,
  1787. metadata: false,
  1788. transforms: []
  1789. };
  1790. const REMOVED_LOADER_OPTIONS = {
  1791. throws: 'nothrow',
  1792. dataType: '(no longer used)',
  1793. uri: 'baseUri',
  1794. method: 'fetch.method',
  1795. headers: 'fetch.headers',
  1796. body: 'fetch.body',
  1797. mode: 'fetch.mode',
  1798. credentials: 'fetch.credentials',
  1799. cache: 'fetch.cache',
  1800. redirect: 'fetch.redirect',
  1801. referrer: 'fetch.referrer',
  1802. referrerPolicy: 'fetch.referrerPolicy',
  1803. integrity: 'fetch.integrity',
  1804. keepalive: 'fetch.keepalive',
  1805. signal: 'fetch.signal'
  1806. };
  1807. function getGlobalLoaderState() {
  1808. globalThis.loaders = globalThis.loaders || {};
  1809. const {
  1810. loaders
  1811. } = globalThis;
  1812. loaders._state = loaders._state || {};
  1813. return loaders._state;
  1814. }
  1815. const getGlobalLoaderOptions = () => {
  1816. const state = getGlobalLoaderState();
  1817. state.globalOptions = state.globalOptions || { ...DEFAULT_LOADER_OPTIONS
  1818. };
  1819. return state.globalOptions;
  1820. };
  1821. function normalizeOptions(options, loader, loaders, url) {
  1822. loaders = loaders || [];
  1823. loaders = Array.isArray(loaders) ? loaders : [loaders];
  1824. validateOptions(options, loaders);
  1825. return normalizeOptionsInternal(loader, options, url);
  1826. }
  1827. function getFetchFunction(options, context) {
  1828. const globalOptions = getGlobalLoaderOptions();
  1829. const fetchOptions = options || globalOptions;
  1830. if (typeof fetchOptions.fetch === 'function') {
  1831. return fetchOptions.fetch;
  1832. }
  1833. if (isObject(fetchOptions.fetch)) {
  1834. return url => fetchFile(url, fetchOptions);
  1835. }
  1836. if (context !== null && context !== void 0 && context.fetch) {
  1837. return context === null || context === void 0 ? void 0 : context.fetch;
  1838. }
  1839. return fetchFile;
  1840. }
  1841. function validateOptions(options, loaders) {
  1842. validateOptionsObject(options, null, DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS, loaders);
  1843. for (const loader of loaders) {
  1844. const idOptions = options && options[loader.id] || {};
  1845. const loaderOptions = loader.options && loader.options[loader.id] || {};
  1846. const deprecatedOptions = loader.deprecatedOptions && loader.deprecatedOptions[loader.id] || {};
  1847. validateOptionsObject(idOptions, loader.id, loaderOptions, deprecatedOptions, loaders);
  1848. }
  1849. }
  1850. function validateOptionsObject(options, id, defaultOptions, deprecatedOptions, loaders) {
  1851. const loaderName = id || 'Top level';
  1852. const prefix = id ? "".concat(id, ".") : '';
  1853. for (const key in options) {
  1854. const isSubOptions = !id && isObject(options[key]);
  1855. const isBaseUriOption = key === 'baseUri' && !id;
  1856. const isWorkerUrlOption = key === 'workerUrl' && id;
  1857. if (!(key in defaultOptions) && !isBaseUriOption && !isWorkerUrlOption) {
  1858. if (key in deprecatedOptions) {
  1859. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' no longer supported, use '").concat(deprecatedOptions[key], "'"))();
  1860. } else if (!isSubOptions) {
  1861. const suggestion = findSimilarOption(key, loaders);
  1862. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' not recognized. ").concat(suggestion))();
  1863. }
  1864. }
  1865. }
  1866. }
  1867. function findSimilarOption(optionKey, loaders) {
  1868. const lowerCaseOptionKey = optionKey.toLowerCase();
  1869. let bestSuggestion = '';
  1870. for (const loader of loaders) {
  1871. for (const key in loader.options) {
  1872. if (optionKey === key) {
  1873. return "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1874. }
  1875. const lowerCaseKey = key.toLowerCase();
  1876. const isPartialMatch = lowerCaseOptionKey.startsWith(lowerCaseKey) || lowerCaseKey.startsWith(lowerCaseOptionKey);
  1877. if (isPartialMatch) {
  1878. bestSuggestion = bestSuggestion || "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1879. }
  1880. }
  1881. }
  1882. return bestSuggestion;
  1883. }
  1884. function normalizeOptionsInternal(loader, options, url) {
  1885. const loaderDefaultOptions = loader.options || {};
  1886. const mergedOptions = { ...loaderDefaultOptions
  1887. };
  1888. addUrlOptions(mergedOptions, url);
  1889. if (mergedOptions.log === null) {
  1890. mergedOptions.log = new NullLog();
  1891. }
  1892. mergeNestedFields(mergedOptions, getGlobalLoaderOptions());
  1893. mergeNestedFields(mergedOptions, options);
  1894. return mergedOptions;
  1895. }
  1896. function mergeNestedFields(mergedOptions, options) {
  1897. for (const key in options) {
  1898. if (key in options) {
  1899. const value = options[key];
  1900. if (isPureObject(value) && isPureObject(mergedOptions[key])) {
  1901. mergedOptions[key] = { ...mergedOptions[key],
  1902. ...options[key]
  1903. };
  1904. } else {
  1905. mergedOptions[key] = options[key];
  1906. }
  1907. }
  1908. }
  1909. }
  1910. function addUrlOptions(options, url) {
  1911. if (url && !('baseUri' in options)) {
  1912. options.baseUri = url;
  1913. }
  1914. }
  1915. function isLoaderObject(loader) {
  1916. var _loader;
  1917. if (!loader) {
  1918. return false;
  1919. }
  1920. if (Array.isArray(loader)) {
  1921. loader = loader[0];
  1922. }
  1923. const hasExtensions = Array.isArray((_loader = loader) === null || _loader === void 0 ? void 0 : _loader.extensions);
  1924. return hasExtensions;
  1925. }
  1926. function normalizeLoader(loader) {
  1927. var _loader2, _loader3;
  1928. assert$7(loader, 'null loader');
  1929. assert$7(isLoaderObject(loader), 'invalid loader');
  1930. let options;
  1931. if (Array.isArray(loader)) {
  1932. options = loader[1];
  1933. loader = loader[0];
  1934. loader = { ...loader,
  1935. options: { ...loader.options,
  1936. ...options
  1937. }
  1938. };
  1939. }
  1940. if ((_loader2 = loader) !== null && _loader2 !== void 0 && _loader2.parseTextSync || (_loader3 = loader) !== null && _loader3 !== void 0 && _loader3.parseText) {
  1941. loader.text = true;
  1942. }
  1943. if (!loader.text) {
  1944. loader.binary = true;
  1945. }
  1946. return loader;
  1947. }
  1948. const getGlobalLoaderRegistry = () => {
  1949. const state = getGlobalLoaderState();
  1950. state.loaderRegistry = state.loaderRegistry || [];
  1951. return state.loaderRegistry;
  1952. };
  1953. function getRegisteredLoaders() {
  1954. return getGlobalLoaderRegistry();
  1955. }
  1956. const log = new Log({
  1957. id: 'loaders.gl'
  1958. });
  1959. const EXT_PATTERN = /\.([^.]+)$/;
  1960. async function selectLoader(data, loaders = [], options, context) {
  1961. if (!validHTTPResponse(data)) {
  1962. return null;
  1963. }
  1964. let loader = selectLoaderSync(data, loaders, { ...options,
  1965. nothrow: true
  1966. }, context);
  1967. if (loader) {
  1968. return loader;
  1969. }
  1970. if (isBlob(data)) {
  1971. data = await data.slice(0, 10).arrayBuffer();
  1972. loader = selectLoaderSync(data, loaders, options, context);
  1973. }
  1974. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1975. throw new Error(getNoValidLoaderMessage(data));
  1976. }
  1977. return loader;
  1978. }
  1979. function selectLoaderSync(data, loaders = [], options, context) {
  1980. if (!validHTTPResponse(data)) {
  1981. return null;
  1982. }
  1983. if (loaders && !Array.isArray(loaders)) {
  1984. return normalizeLoader(loaders);
  1985. }
  1986. let candidateLoaders = [];
  1987. if (loaders) {
  1988. candidateLoaders = candidateLoaders.concat(loaders);
  1989. }
  1990. if (!(options !== null && options !== void 0 && options.ignoreRegisteredLoaders)) {
  1991. candidateLoaders.push(...getRegisteredLoaders());
  1992. }
  1993. normalizeLoaders(candidateLoaders);
  1994. const loader = selectLoaderInternal(data, candidateLoaders, options, context);
  1995. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1996. throw new Error(getNoValidLoaderMessage(data));
  1997. }
  1998. return loader;
  1999. }
  2000. function selectLoaderInternal(data, loaders, options, context) {
  2001. const {
  2002. url,
  2003. type
  2004. } = getResourceUrlAndType(data);
  2005. const testUrl = url || (context === null || context === void 0 ? void 0 : context.url);
  2006. let loader = null;
  2007. let reason = '';
  2008. if (options !== null && options !== void 0 && options.mimeType) {
  2009. loader = findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.mimeType);
  2010. reason = "match forced by supplied MIME type ".concat(options === null || options === void 0 ? void 0 : options.mimeType);
  2011. }
  2012. loader = loader || findLoaderByUrl(loaders, testUrl);
  2013. reason = reason || (loader ? "matched url ".concat(testUrl) : '');
  2014. loader = loader || findLoaderByMIMEType(loaders, type);
  2015. reason = reason || (loader ? "matched MIME type ".concat(type) : '');
  2016. loader = loader || findLoaderByInitialBytes(loaders, data);
  2017. reason = reason || (loader ? "matched initial data ".concat(getFirstCharacters(data)) : '');
  2018. loader = loader || findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.fallbackMimeType);
  2019. reason = reason || (loader ? "matched fallback MIME type ".concat(type) : '');
  2020. if (reason) {
  2021. var _loader;
  2022. log.log(1, "selectLoader selected ".concat((_loader = loader) === null || _loader === void 0 ? void 0 : _loader.name, ": ").concat(reason, "."));
  2023. }
  2024. return loader;
  2025. }
  2026. function validHTTPResponse(data) {
  2027. if (data instanceof Response) {
  2028. if (data.status === 204) {
  2029. return false;
  2030. }
  2031. }
  2032. return true;
  2033. }
  2034. function getNoValidLoaderMessage(data) {
  2035. const {
  2036. url,
  2037. type
  2038. } = getResourceUrlAndType(data);
  2039. let message = 'No valid loader found (';
  2040. message += url ? "".concat(filename(url), ", ") : 'no url provided, ';
  2041. message += "MIME type: ".concat(type ? "\"".concat(type, "\"") : 'not provided', ", ");
  2042. const firstCharacters = data ? getFirstCharacters(data) : '';
  2043. message += firstCharacters ? " first bytes: \"".concat(firstCharacters, "\"") : 'first bytes: not available';
  2044. message += ')';
  2045. return message;
  2046. }
  2047. function normalizeLoaders(loaders) {
  2048. for (const loader of loaders) {
  2049. normalizeLoader(loader);
  2050. }
  2051. }
  2052. function findLoaderByUrl(loaders, url) {
  2053. const match = url && EXT_PATTERN.exec(url);
  2054. const extension = match && match[1];
  2055. return extension ? findLoaderByExtension(loaders, extension) : null;
  2056. }
  2057. function findLoaderByExtension(loaders, extension) {
  2058. extension = extension.toLowerCase();
  2059. for (const loader of loaders) {
  2060. for (const loaderExtension of loader.extensions) {
  2061. if (loaderExtension.toLowerCase() === extension) {
  2062. return loader;
  2063. }
  2064. }
  2065. }
  2066. return null;
  2067. }
  2068. function findLoaderByMIMEType(loaders, mimeType) {
  2069. for (const loader of loaders) {
  2070. if (loader.mimeTypes && loader.mimeTypes.includes(mimeType)) {
  2071. return loader;
  2072. }
  2073. if (mimeType === "application/x.".concat(loader.id)) {
  2074. return loader;
  2075. }
  2076. }
  2077. return null;
  2078. }
  2079. function findLoaderByInitialBytes(loaders, data) {
  2080. if (!data) {
  2081. return null;
  2082. }
  2083. for (const loader of loaders) {
  2084. if (typeof data === 'string') {
  2085. if (testDataAgainstText(data, loader)) {
  2086. return loader;
  2087. }
  2088. } else if (ArrayBuffer.isView(data)) {
  2089. if (testDataAgainstBinary(data.buffer, data.byteOffset, loader)) {
  2090. return loader;
  2091. }
  2092. } else if (data instanceof ArrayBuffer) {
  2093. const byteOffset = 0;
  2094. if (testDataAgainstBinary(data, byteOffset, loader)) {
  2095. return loader;
  2096. }
  2097. }
  2098. }
  2099. return null;
  2100. }
  2101. function testDataAgainstText(data, loader) {
  2102. if (loader.testText) {
  2103. return loader.testText(data);
  2104. }
  2105. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2106. return tests.some(test => data.startsWith(test));
  2107. }
  2108. function testDataAgainstBinary(data, byteOffset, loader) {
  2109. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2110. return tests.some(test => testBinary(data, byteOffset, loader, test));
  2111. }
  2112. function testBinary(data, byteOffset, loader, test) {
  2113. if (test instanceof ArrayBuffer) {
  2114. return compareArrayBuffers(test, data, test.byteLength);
  2115. }
  2116. switch (typeof test) {
  2117. case 'function':
  2118. return test(data, loader);
  2119. case 'string':
  2120. const magic = getMagicString$2(data, byteOffset, test.length);
  2121. return test === magic;
  2122. default:
  2123. return false;
  2124. }
  2125. }
  2126. function getFirstCharacters(data, length = 5) {
  2127. if (typeof data === 'string') {
  2128. return data.slice(0, length);
  2129. } else if (ArrayBuffer.isView(data)) {
  2130. return getMagicString$2(data.buffer, data.byteOffset, length);
  2131. } else if (data instanceof ArrayBuffer) {
  2132. const byteOffset = 0;
  2133. return getMagicString$2(data, byteOffset, length);
  2134. }
  2135. return '';
  2136. }
  2137. function getMagicString$2(arrayBuffer, byteOffset, length) {
  2138. if (arrayBuffer.byteLength < byteOffset + length) {
  2139. return '';
  2140. }
  2141. const dataView = new DataView(arrayBuffer);
  2142. let magic = '';
  2143. for (let i = 0; i < length; i++) {
  2144. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  2145. }
  2146. return magic;
  2147. }
  2148. const DEFAULT_CHUNK_SIZE$2 = 256 * 1024;
  2149. function* makeStringIterator(string, options) {
  2150. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE$2;
  2151. let offset = 0;
  2152. const textEncoder = new TextEncoder();
  2153. while (offset < string.length) {
  2154. const chunkLength = Math.min(string.length - offset, chunkSize);
  2155. const chunk = string.slice(offset, offset + chunkLength);
  2156. offset += chunkLength;
  2157. yield textEncoder.encode(chunk);
  2158. }
  2159. }
  2160. const DEFAULT_CHUNK_SIZE$1 = 256 * 1024;
  2161. function* makeArrayBufferIterator(arrayBuffer, options = {}) {
  2162. const {
  2163. chunkSize = DEFAULT_CHUNK_SIZE$1
  2164. } = options;
  2165. let byteOffset = 0;
  2166. while (byteOffset < arrayBuffer.byteLength) {
  2167. const chunkByteLength = Math.min(arrayBuffer.byteLength - byteOffset, chunkSize);
  2168. const chunk = new ArrayBuffer(chunkByteLength);
  2169. const sourceArray = new Uint8Array(arrayBuffer, byteOffset, chunkByteLength);
  2170. const chunkArray = new Uint8Array(chunk);
  2171. chunkArray.set(sourceArray);
  2172. byteOffset += chunkByteLength;
  2173. yield chunk;
  2174. }
  2175. }
  2176. const DEFAULT_CHUNK_SIZE = 1024 * 1024;
  2177. async function* makeBlobIterator(blob, options) {
  2178. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE;
  2179. let offset = 0;
  2180. while (offset < blob.size) {
  2181. const end = offset + chunkSize;
  2182. const chunk = await blob.slice(offset, end).arrayBuffer();
  2183. offset = end;
  2184. yield chunk;
  2185. }
  2186. }
  2187. function makeStreamIterator(stream, options) {
  2188. return isBrowser$2 ? makeBrowserStreamIterator(stream, options) : makeNodeStreamIterator(stream);
  2189. }
  2190. async function* makeBrowserStreamIterator(stream, options) {
  2191. const reader = stream.getReader();
  2192. let nextBatchPromise;
  2193. try {
  2194. while (true) {
  2195. const currentBatchPromise = nextBatchPromise || reader.read();
  2196. if (options !== null && options !== void 0 && options._streamReadAhead) {
  2197. nextBatchPromise = reader.read();
  2198. }
  2199. const {
  2200. done,
  2201. value
  2202. } = await currentBatchPromise;
  2203. if (done) {
  2204. return;
  2205. }
  2206. yield toArrayBuffer(value);
  2207. }
  2208. } catch (error) {
  2209. reader.releaseLock();
  2210. }
  2211. }
  2212. async function* makeNodeStreamIterator(stream, options) {
  2213. for await (const chunk of stream) {
  2214. yield toArrayBuffer(chunk);
  2215. }
  2216. }
  2217. function makeIterator(data, options) {
  2218. if (typeof data === 'string') {
  2219. return makeStringIterator(data, options);
  2220. }
  2221. if (data instanceof ArrayBuffer) {
  2222. return makeArrayBufferIterator(data, options);
  2223. }
  2224. if (isBlob(data)) {
  2225. return makeBlobIterator(data, options);
  2226. }
  2227. if (isReadableStream(data)) {
  2228. return makeStreamIterator(data, options);
  2229. }
  2230. if (isResponse(data)) {
  2231. const response = data;
  2232. return makeStreamIterator(response.body, options);
  2233. }
  2234. throw new Error('makeIterator');
  2235. }
  2236. const ERR_DATA = 'Cannot convert supplied data type';
  2237. function getArrayBufferOrStringFromDataSync(data, loader, options) {
  2238. if (loader.text && typeof data === 'string') {
  2239. return data;
  2240. }
  2241. if (isBuffer(data)) {
  2242. data = data.buffer;
  2243. }
  2244. if (data instanceof ArrayBuffer) {
  2245. const arrayBuffer = data;
  2246. if (loader.text && !loader.binary) {
  2247. const textDecoder = new TextDecoder('utf8');
  2248. return textDecoder.decode(arrayBuffer);
  2249. }
  2250. return arrayBuffer;
  2251. }
  2252. if (ArrayBuffer.isView(data)) {
  2253. if (loader.text && !loader.binary) {
  2254. const textDecoder = new TextDecoder('utf8');
  2255. return textDecoder.decode(data);
  2256. }
  2257. let arrayBuffer = data.buffer;
  2258. const byteLength = data.byteLength || data.length;
  2259. if (data.byteOffset !== 0 || byteLength !== arrayBuffer.byteLength) {
  2260. arrayBuffer = arrayBuffer.slice(data.byteOffset, data.byteOffset + byteLength);
  2261. }
  2262. return arrayBuffer;
  2263. }
  2264. throw new Error(ERR_DATA);
  2265. }
  2266. async function getArrayBufferOrStringFromData(data, loader, options) {
  2267. const isArrayBuffer = data instanceof ArrayBuffer || ArrayBuffer.isView(data);
  2268. if (typeof data === 'string' || isArrayBuffer) {
  2269. return getArrayBufferOrStringFromDataSync(data, loader);
  2270. }
  2271. if (isBlob(data)) {
  2272. data = await makeResponse(data);
  2273. }
  2274. if (isResponse(data)) {
  2275. const response = data;
  2276. await checkResponse(response);
  2277. return loader.binary ? await response.arrayBuffer() : await response.text();
  2278. }
  2279. if (isReadableStream(data)) {
  2280. data = makeIterator(data, options);
  2281. }
  2282. if (isIterable(data) || isAsyncIterable(data)) {
  2283. return concatenateArrayBuffersAsync(data);
  2284. }
  2285. throw new Error(ERR_DATA);
  2286. }
  2287. function getLoaderContext(context, options, previousContext = null) {
  2288. if (previousContext) {
  2289. return previousContext;
  2290. }
  2291. const resolvedContext = {
  2292. fetch: getFetchFunction(options, context),
  2293. ...context
  2294. };
  2295. if (!Array.isArray(resolvedContext.loaders)) {
  2296. resolvedContext.loaders = null;
  2297. }
  2298. return resolvedContext;
  2299. }
  2300. function getLoadersFromContext(loaders, context) {
  2301. if (!context && loaders && !Array.isArray(loaders)) {
  2302. return loaders;
  2303. }
  2304. let candidateLoaders;
  2305. if (loaders) {
  2306. candidateLoaders = Array.isArray(loaders) ? loaders : [loaders];
  2307. }
  2308. if (context && context.loaders) {
  2309. const contextLoaders = Array.isArray(context.loaders) ? context.loaders : [context.loaders];
  2310. candidateLoaders = candidateLoaders ? [...candidateLoaders, ...contextLoaders] : contextLoaders;
  2311. }
  2312. return candidateLoaders && candidateLoaders.length ? candidateLoaders : null;
  2313. }
  2314. async function parse$3(data, loaders, options, context) {
  2315. assert$6(!context || typeof context === 'object');
  2316. if (loaders && !Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2317. context = undefined;
  2318. options = loaders;
  2319. loaders = undefined;
  2320. }
  2321. data = await data;
  2322. options = options || {};
  2323. const {
  2324. url
  2325. } = getResourceUrlAndType(data);
  2326. const typedLoaders = loaders;
  2327. const candidateLoaders = getLoadersFromContext(typedLoaders, context);
  2328. const loader = await selectLoader(data, candidateLoaders, options);
  2329. if (!loader) {
  2330. return null;
  2331. }
  2332. options = normalizeOptions(options, loader, candidateLoaders, url);
  2333. context = getLoaderContext({
  2334. url,
  2335. parse: parse$3,
  2336. loaders: candidateLoaders
  2337. }, options, context);
  2338. return await parseWithLoader(loader, data, options, context);
  2339. }
  2340. async function parseWithLoader(loader, data, options, context) {
  2341. validateWorkerVersion(loader);
  2342. if (isResponse(data)) {
  2343. const response = data;
  2344. const {
  2345. ok,
  2346. redirected,
  2347. status,
  2348. statusText,
  2349. type,
  2350. url
  2351. } = response;
  2352. const headers = Object.fromEntries(response.headers.entries());
  2353. context.response = {
  2354. headers,
  2355. ok,
  2356. redirected,
  2357. status,
  2358. statusText,
  2359. type,
  2360. url
  2361. };
  2362. }
  2363. data = await getArrayBufferOrStringFromData(data, loader, options);
  2364. if (loader.parseTextSync && typeof data === 'string') {
  2365. options.dataType = 'text';
  2366. return loader.parseTextSync(data, options, context, loader);
  2367. }
  2368. if (canParseWithWorker(loader, options)) {
  2369. return await parseWithWorker(loader, data, options, context, parse$3);
  2370. }
  2371. if (loader.parseText && typeof data === 'string') {
  2372. return await loader.parseText(data, options, context, loader);
  2373. }
  2374. if (loader.parse) {
  2375. return await loader.parse(data, options, context, loader);
  2376. }
  2377. assert$6(!loader.parseSync);
  2378. throw new Error("".concat(loader.id, " loader - no parser found and worker is disabled"));
  2379. }
  2380. async function load(url, loaders, options, context) {
  2381. if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2382. options = loaders;
  2383. loaders = undefined;
  2384. }
  2385. const fetch = getFetchFunction(options);
  2386. let data = url;
  2387. if (typeof url === 'string') {
  2388. data = await fetch(url);
  2389. }
  2390. if (isBlob(url)) {
  2391. data = await fetch(url);
  2392. }
  2393. return await parse$3(data, loaders, options);
  2394. }
  2395. function assert$4(condition, message) {
  2396. if (!condition) {
  2397. throw new Error("math.gl assertion ".concat(message));
  2398. }
  2399. }
  2400. const RADIANS_TO_DEGREES = 1 / Math.PI * 180;
  2401. const DEGREES_TO_RADIANS = 1 / 180 * Math.PI;
  2402. const config = {
  2403. EPSILON: 1e-12,
  2404. debug: false,
  2405. precision: 4,
  2406. printTypes: false,
  2407. printDegrees: false,
  2408. printRowMajor: true
  2409. };
  2410. function formatValue(value, {
  2411. precision = config.precision
  2412. } = {}) {
  2413. value = round(value);
  2414. return "".concat(parseFloat(value.toPrecision(precision)));
  2415. }
  2416. function isArray(value) {
  2417. return Array.isArray(value) || ArrayBuffer.isView(value) && !(value instanceof DataView);
  2418. }
  2419. function toRadians(degrees) {
  2420. return radians(degrees);
  2421. }
  2422. function toDegrees(radians) {
  2423. return degrees(radians);
  2424. }
  2425. function radians(degrees, result) {
  2426. return map(degrees, degrees => degrees * DEGREES_TO_RADIANS, result);
  2427. }
  2428. function degrees(radians, result) {
  2429. return map(radians, radians => radians * RADIANS_TO_DEGREES, result);
  2430. }
  2431. function clamp(value, min, max) {
  2432. return map(value, value => Math.max(min, Math.min(max, value)));
  2433. }
  2434. function equals(a, b, epsilon) {
  2435. const oldEpsilon = config.EPSILON;
  2436. if (epsilon) {
  2437. config.EPSILON = epsilon;
  2438. }
  2439. try {
  2440. if (a === b) {
  2441. return true;
  2442. }
  2443. if (isArray(a) && isArray(b)) {
  2444. if (a.length !== b.length) {
  2445. return false;
  2446. }
  2447. for (let i = 0; i < a.length; ++i) {
  2448. if (!equals(a[i], b[i])) {
  2449. return false;
  2450. }
  2451. }
  2452. return true;
  2453. }
  2454. if (a && a.equals) {
  2455. return a.equals(b);
  2456. }
  2457. if (b && b.equals) {
  2458. return b.equals(a);
  2459. }
  2460. if (typeof a === 'number' && typeof b === 'number') {
  2461. return Math.abs(a - b) <= config.EPSILON * Math.max(1, Math.abs(a), Math.abs(b));
  2462. }
  2463. return false;
  2464. } finally {
  2465. config.EPSILON = oldEpsilon;
  2466. }
  2467. }
  2468. function round(value) {
  2469. return Math.round(value / config.EPSILON) * config.EPSILON;
  2470. }
  2471. function duplicateArray(array) {
  2472. return array.clone ? array.clone() : new Array(array.length);
  2473. }
  2474. function map(value, func, result) {
  2475. if (isArray(value)) {
  2476. const array = value;
  2477. result = result || duplicateArray(array);
  2478. for (let i = 0; i < result.length && i < array.length; ++i) {
  2479. result[i] = func(value[i], i, result);
  2480. }
  2481. return result;
  2482. }
  2483. return func(value);
  2484. }
  2485. function _extendableBuiltin(cls) {
  2486. function ExtendableBuiltin() {
  2487. var instance = Reflect.construct(cls, Array.from(arguments));
  2488. Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
  2489. return instance;
  2490. }
  2491. ExtendableBuiltin.prototype = Object.create(cls.prototype, {
  2492. constructor: {
  2493. value: cls,
  2494. enumerable: false,
  2495. writable: true,
  2496. configurable: true
  2497. }
  2498. });
  2499. if (Object.setPrototypeOf) {
  2500. Object.setPrototypeOf(ExtendableBuiltin, cls);
  2501. } else {
  2502. ExtendableBuiltin.__proto__ = cls;
  2503. }
  2504. return ExtendableBuiltin;
  2505. }
  2506. class MathArray extends _extendableBuiltin(Array) {
  2507. clone() {
  2508. return new this.constructor().copy(this);
  2509. }
  2510. fromArray(array, offset = 0) {
  2511. for (let i = 0; i < this.ELEMENTS; ++i) {
  2512. this[i] = array[i + offset];
  2513. }
  2514. return this.check();
  2515. }
  2516. toArray(targetArray = [], offset = 0) {
  2517. for (let i = 0; i < this.ELEMENTS; ++i) {
  2518. targetArray[offset + i] = this[i];
  2519. }
  2520. return targetArray;
  2521. }
  2522. from(arrayOrObject) {
  2523. return Array.isArray(arrayOrObject) ? this.copy(arrayOrObject) : this.fromObject(arrayOrObject);
  2524. }
  2525. to(arrayOrObject) {
  2526. if (arrayOrObject === this) {
  2527. return this;
  2528. }
  2529. return isArray(arrayOrObject) ? this.toArray(arrayOrObject) : this.toObject(arrayOrObject);
  2530. }
  2531. toTarget(target) {
  2532. return target ? this.to(target) : this;
  2533. }
  2534. toFloat32Array() {
  2535. return new Float32Array(this);
  2536. }
  2537. toString() {
  2538. return this.formatString(config);
  2539. }
  2540. formatString(opts) {
  2541. let string = '';
  2542. for (let i = 0; i < this.ELEMENTS; ++i) {
  2543. string += (i > 0 ? ', ' : '') + formatValue(this[i], opts);
  2544. }
  2545. return "".concat(opts.printTypes ? this.constructor.name : '', "[").concat(string, "]");
  2546. }
  2547. equals(array) {
  2548. if (!array || this.length !== array.length) {
  2549. return false;
  2550. }
  2551. for (let i = 0; i < this.ELEMENTS; ++i) {
  2552. if (!equals(this[i], array[i])) {
  2553. return false;
  2554. }
  2555. }
  2556. return true;
  2557. }
  2558. exactEquals(array) {
  2559. if (!array || this.length !== array.length) {
  2560. return false;
  2561. }
  2562. for (let i = 0; i < this.ELEMENTS; ++i) {
  2563. if (this[i] !== array[i]) {
  2564. return false;
  2565. }
  2566. }
  2567. return true;
  2568. }
  2569. negate() {
  2570. for (let i = 0; i < this.ELEMENTS; ++i) {
  2571. this[i] = -this[i];
  2572. }
  2573. return this.check();
  2574. }
  2575. lerp(a, b, t) {
  2576. if (t === undefined) {
  2577. return this.lerp(this, a, b);
  2578. }
  2579. for (let i = 0; i < this.ELEMENTS; ++i) {
  2580. const ai = a[i];
  2581. this[i] = ai + t * (b[i] - ai);
  2582. }
  2583. return this.check();
  2584. }
  2585. min(vector) {
  2586. for (let i = 0; i < this.ELEMENTS; ++i) {
  2587. this[i] = Math.min(vector[i], this[i]);
  2588. }
  2589. return this.check();
  2590. }
  2591. max(vector) {
  2592. for (let i = 0; i < this.ELEMENTS; ++i) {
  2593. this[i] = Math.max(vector[i], this[i]);
  2594. }
  2595. return this.check();
  2596. }
  2597. clamp(minVector, maxVector) {
  2598. for (let i = 0; i < this.ELEMENTS; ++i) {
  2599. this[i] = Math.min(Math.max(this[i], minVector[i]), maxVector[i]);
  2600. }
  2601. return this.check();
  2602. }
  2603. add(...vectors) {
  2604. for (const vector of vectors) {
  2605. for (let i = 0; i < this.ELEMENTS; ++i) {
  2606. this[i] += vector[i];
  2607. }
  2608. }
  2609. return this.check();
  2610. }
  2611. subtract(...vectors) {
  2612. for (const vector of vectors) {
  2613. for (let i = 0; i < this.ELEMENTS; ++i) {
  2614. this[i] -= vector[i];
  2615. }
  2616. }
  2617. return this.check();
  2618. }
  2619. scale(scale) {
  2620. if (typeof scale === 'number') {
  2621. for (let i = 0; i < this.ELEMENTS; ++i) {
  2622. this[i] *= scale;
  2623. }
  2624. } else {
  2625. for (let i = 0; i < this.ELEMENTS && i < scale.length; ++i) {
  2626. this[i] *= scale[i];
  2627. }
  2628. }
  2629. return this.check();
  2630. }
  2631. multiplyByScalar(scalar) {
  2632. for (let i = 0; i < this.ELEMENTS; ++i) {
  2633. this[i] *= scalar;
  2634. }
  2635. return this.check();
  2636. }
  2637. check() {
  2638. if (config.debug && !this.validate()) {
  2639. throw new Error("math.gl: ".concat(this.constructor.name, " some fields set to invalid numbers'"));
  2640. }
  2641. return this;
  2642. }
  2643. validate() {
  2644. let valid = this.length === this.ELEMENTS;
  2645. for (let i = 0; i < this.ELEMENTS; ++i) {
  2646. valid = valid && Number.isFinite(this[i]);
  2647. }
  2648. return valid;
  2649. }
  2650. sub(a) {
  2651. return this.subtract(a);
  2652. }
  2653. setScalar(a) {
  2654. for (let i = 0; i < this.ELEMENTS; ++i) {
  2655. this[i] = a;
  2656. }
  2657. return this.check();
  2658. }
  2659. addScalar(a) {
  2660. for (let i = 0; i < this.ELEMENTS; ++i) {
  2661. this[i] += a;
  2662. }
  2663. return this.check();
  2664. }
  2665. subScalar(a) {
  2666. return this.addScalar(-a);
  2667. }
  2668. multiplyScalar(scalar) {
  2669. for (let i = 0; i < this.ELEMENTS; ++i) {
  2670. this[i] *= scalar;
  2671. }
  2672. return this.check();
  2673. }
  2674. divideScalar(a) {
  2675. return this.multiplyByScalar(1 / a);
  2676. }
  2677. clampScalar(min, max) {
  2678. for (let i = 0; i < this.ELEMENTS; ++i) {
  2679. this[i] = Math.min(Math.max(this[i], min), max);
  2680. }
  2681. return this.check();
  2682. }
  2683. get elements() {
  2684. return this;
  2685. }
  2686. }
  2687. function validateVector(v, length) {
  2688. if (v.length !== length) {
  2689. return false;
  2690. }
  2691. for (let i = 0; i < v.length; ++i) {
  2692. if (!Number.isFinite(v[i])) {
  2693. return false;
  2694. }
  2695. }
  2696. return true;
  2697. }
  2698. function checkNumber(value) {
  2699. if (!Number.isFinite(value)) {
  2700. throw new Error("Invalid number ".concat(value));
  2701. }
  2702. return value;
  2703. }
  2704. function checkVector(v, length, callerName = '') {
  2705. if (config.debug && !validateVector(v, length)) {
  2706. throw new Error("math.gl: ".concat(callerName, " some fields set to invalid numbers'"));
  2707. }
  2708. return v;
  2709. }
  2710. class Vector extends MathArray {
  2711. get x() {
  2712. return this[0];
  2713. }
  2714. set x(value) {
  2715. this[0] = checkNumber(value);
  2716. }
  2717. get y() {
  2718. return this[1];
  2719. }
  2720. set y(value) {
  2721. this[1] = checkNumber(value);
  2722. }
  2723. len() {
  2724. return Math.sqrt(this.lengthSquared());
  2725. }
  2726. magnitude() {
  2727. return this.len();
  2728. }
  2729. lengthSquared() {
  2730. let length = 0;
  2731. for (let i = 0; i < this.ELEMENTS; ++i) {
  2732. length += this[i] * this[i];
  2733. }
  2734. return length;
  2735. }
  2736. magnitudeSquared() {
  2737. return this.lengthSquared();
  2738. }
  2739. distance(mathArray) {
  2740. return Math.sqrt(this.distanceSquared(mathArray));
  2741. }
  2742. distanceSquared(mathArray) {
  2743. let length = 0;
  2744. for (let i = 0; i < this.ELEMENTS; ++i) {
  2745. const dist = this[i] - mathArray[i];
  2746. length += dist * dist;
  2747. }
  2748. return checkNumber(length);
  2749. }
  2750. dot(mathArray) {
  2751. let product = 0;
  2752. for (let i = 0; i < this.ELEMENTS; ++i) {
  2753. product += this[i] * mathArray[i];
  2754. }
  2755. return checkNumber(product);
  2756. }
  2757. normalize() {
  2758. const length = this.magnitude();
  2759. if (length !== 0) {
  2760. for (let i = 0; i < this.ELEMENTS; ++i) {
  2761. this[i] /= length;
  2762. }
  2763. }
  2764. return this.check();
  2765. }
  2766. multiply(...vectors) {
  2767. for (const vector of vectors) {
  2768. for (let i = 0; i < this.ELEMENTS; ++i) {
  2769. this[i] *= vector[i];
  2770. }
  2771. }
  2772. return this.check();
  2773. }
  2774. divide(...vectors) {
  2775. for (const vector of vectors) {
  2776. for (let i = 0; i < this.ELEMENTS; ++i) {
  2777. this[i] /= vector[i];
  2778. }
  2779. }
  2780. return this.check();
  2781. }
  2782. lengthSq() {
  2783. return this.lengthSquared();
  2784. }
  2785. distanceTo(vector) {
  2786. return this.distance(vector);
  2787. }
  2788. distanceToSquared(vector) {
  2789. return this.distanceSquared(vector);
  2790. }
  2791. getComponent(i) {
  2792. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2793. return checkNumber(this[i]);
  2794. }
  2795. setComponent(i, value) {
  2796. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2797. this[i] = value;
  2798. return this.check();
  2799. }
  2800. addVectors(a, b) {
  2801. return this.copy(a).add(b);
  2802. }
  2803. subVectors(a, b) {
  2804. return this.copy(a).subtract(b);
  2805. }
  2806. multiplyVectors(a, b) {
  2807. return this.copy(a).multiply(b);
  2808. }
  2809. addScaledVector(a, b) {
  2810. return this.add(new this.constructor(a).multiplyScalar(b));
  2811. }
  2812. }
  2813. /**
  2814. * Common utilities
  2815. * @module glMatrix
  2816. */
  2817. // Configuration Constants
  2818. var EPSILON = 0.000001;
  2819. var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  2820. if (!Math.hypot) Math.hypot = function () {
  2821. var y = 0,
  2822. i = arguments.length;
  2823. while (i--) {
  2824. y += arguments[i] * arguments[i];
  2825. }
  2826. return Math.sqrt(y);
  2827. };
  2828. /**
  2829. * 2 Dimensional Vector
  2830. * @module vec2
  2831. */
  2832. /**
  2833. * Creates a new, empty vec2
  2834. *
  2835. * @returns {vec2} a new 2D vector
  2836. */
  2837. function create$4() {
  2838. var out = new ARRAY_TYPE(2);
  2839. if (ARRAY_TYPE != Float32Array) {
  2840. out[0] = 0;
  2841. out[1] = 0;
  2842. }
  2843. return out;
  2844. }
  2845. /**
  2846. * Transforms the vec2 with a mat2
  2847. *
  2848. * @param {vec2} out the receiving vector
  2849. * @param {ReadonlyVec2} a the vector to transform
  2850. * @param {ReadonlyMat2} m matrix to transform with
  2851. * @returns {vec2} out
  2852. */
  2853. function transformMat2(out, a, m) {
  2854. var x = a[0],
  2855. y = a[1];
  2856. out[0] = m[0] * x + m[2] * y;
  2857. out[1] = m[1] * x + m[3] * y;
  2858. return out;
  2859. }
  2860. /**
  2861. * Transforms the vec2 with a mat2d
  2862. *
  2863. * @param {vec2} out the receiving vector
  2864. * @param {ReadonlyVec2} a the vector to transform
  2865. * @param {ReadonlyMat2d} m matrix to transform with
  2866. * @returns {vec2} out
  2867. */
  2868. function transformMat2d(out, a, m) {
  2869. var x = a[0],
  2870. y = a[1];
  2871. out[0] = m[0] * x + m[2] * y + m[4];
  2872. out[1] = m[1] * x + m[3] * y + m[5];
  2873. return out;
  2874. }
  2875. /**
  2876. * Transforms the vec2 with a mat3
  2877. * 3rd vector component is implicitly '1'
  2878. *
  2879. * @param {vec2} out the receiving vector
  2880. * @param {ReadonlyVec2} a the vector to transform
  2881. * @param {ReadonlyMat3} m matrix to transform with
  2882. * @returns {vec2} out
  2883. */
  2884. function transformMat3$1(out, a, m) {
  2885. var x = a[0],
  2886. y = a[1];
  2887. out[0] = m[0] * x + m[3] * y + m[6];
  2888. out[1] = m[1] * x + m[4] * y + m[7];
  2889. return out;
  2890. }
  2891. /**
  2892. * Transforms the vec2 with a mat4
  2893. * 3rd vector component is implicitly '0'
  2894. * 4th vector component is implicitly '1'
  2895. *
  2896. * @param {vec2} out the receiving vector
  2897. * @param {ReadonlyVec2} a the vector to transform
  2898. * @param {ReadonlyMat4} m matrix to transform with
  2899. * @returns {vec2} out
  2900. */
  2901. function transformMat4$2(out, a, m) {
  2902. var x = a[0];
  2903. var y = a[1];
  2904. out[0] = m[0] * x + m[4] * y + m[12];
  2905. out[1] = m[1] * x + m[5] * y + m[13];
  2906. return out;
  2907. }
  2908. /**
  2909. * Perform some operation over an array of vec2s.
  2910. *
  2911. * @param {Array} a the array of vectors to iterate over
  2912. * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
  2913. * @param {Number} offset Number of elements to skip at the beginning of the array
  2914. * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
  2915. * @param {Function} fn Function to call for each vector in the array
  2916. * @param {Object} [arg] additional argument to pass to fn
  2917. * @returns {Array} a
  2918. * @function
  2919. */
  2920. (function () {
  2921. var vec = create$4();
  2922. return function (a, stride, offset, count, fn, arg) {
  2923. var i, l;
  2924. if (!stride) {
  2925. stride = 2;
  2926. }
  2927. if (!offset) {
  2928. offset = 0;
  2929. }
  2930. if (count) {
  2931. l = Math.min(count * stride + offset, a.length);
  2932. } else {
  2933. l = a.length;
  2934. }
  2935. for (i = offset; i < l; i += stride) {
  2936. vec[0] = a[i];
  2937. vec[1] = a[i + 1];
  2938. fn(vec, vec, arg);
  2939. a[i] = vec[0];
  2940. a[i + 1] = vec[1];
  2941. }
  2942. return a;
  2943. };
  2944. })();
  2945. function vec2_transformMat4AsVector(out, a, m) {
  2946. const x = a[0];
  2947. const y = a[1];
  2948. const w = m[3] * x + m[7] * y || 1.0;
  2949. out[0] = (m[0] * x + m[4] * y) / w;
  2950. out[1] = (m[1] * x + m[5] * y) / w;
  2951. return out;
  2952. }
  2953. function vec3_transformMat4AsVector(out, a, m) {
  2954. const x = a[0];
  2955. const y = a[1];
  2956. const z = a[2];
  2957. const w = m[3] * x + m[7] * y + m[11] * z || 1.0;
  2958. out[0] = (m[0] * x + m[4] * y + m[8] * z) / w;
  2959. out[1] = (m[1] * x + m[5] * y + m[9] * z) / w;
  2960. out[2] = (m[2] * x + m[6] * y + m[10] * z) / w;
  2961. return out;
  2962. }
  2963. function vec3_transformMat2(out, a, m) {
  2964. const x = a[0];
  2965. const y = a[1];
  2966. out[0] = m[0] * x + m[2] * y;
  2967. out[1] = m[1] * x + m[3] * y;
  2968. out[2] = a[2];
  2969. return out;
  2970. }
  2971. function vec4_transformMat2(out, a, m) {
  2972. const x = a[0];
  2973. const y = a[1];
  2974. out[0] = m[0] * x + m[2] * y;
  2975. out[1] = m[1] * x + m[3] * y;
  2976. out[2] = a[2];
  2977. out[3] = a[3];
  2978. return out;
  2979. }
  2980. function vec4_transformMat3(out, a, m) {
  2981. const x = a[0];
  2982. const y = a[1];
  2983. const z = a[2];
  2984. out[0] = m[0] * x + m[3] * y + m[6] * z;
  2985. out[1] = m[1] * x + m[4] * y + m[7] * z;
  2986. out[2] = m[2] * x + m[5] * y + m[8] * z;
  2987. out[3] = a[3];
  2988. return out;
  2989. }
  2990. class Vector2 extends Vector {
  2991. constructor(x = 0, y = 0) {
  2992. super(2);
  2993. if (isArray(x) && arguments.length === 1) {
  2994. this.copy(x);
  2995. } else {
  2996. if (config.debug) {
  2997. checkNumber(x);
  2998. checkNumber(y);
  2999. }
  3000. this[0] = x;
  3001. this[1] = y;
  3002. }
  3003. }
  3004. set(x, y) {
  3005. this[0] = x;
  3006. this[1] = y;
  3007. return this.check();
  3008. }
  3009. copy(array) {
  3010. this[0] = array[0];
  3011. this[1] = array[1];
  3012. return this.check();
  3013. }
  3014. fromObject(object) {
  3015. if (config.debug) {
  3016. checkNumber(object.x);
  3017. checkNumber(object.y);
  3018. }
  3019. this[0] = object.x;
  3020. this[1] = object.y;
  3021. return this.check();
  3022. }
  3023. toObject(object) {
  3024. object.x = this[0];
  3025. object.y = this[1];
  3026. return object;
  3027. }
  3028. get ELEMENTS() {
  3029. return 2;
  3030. }
  3031. horizontalAngle() {
  3032. return Math.atan2(this.y, this.x);
  3033. }
  3034. verticalAngle() {
  3035. return Math.atan2(this.x, this.y);
  3036. }
  3037. transform(matrix4) {
  3038. return this.transformAsPoint(matrix4);
  3039. }
  3040. transformAsPoint(matrix4) {
  3041. transformMat4$2(this, this, matrix4);
  3042. return this.check();
  3043. }
  3044. transformAsVector(matrix4) {
  3045. vec2_transformMat4AsVector(this, this, matrix4);
  3046. return this.check();
  3047. }
  3048. transformByMatrix3(matrix3) {
  3049. transformMat3$1(this, this, matrix3);
  3050. return this.check();
  3051. }
  3052. transformByMatrix2x3(matrix2x3) {
  3053. transformMat2d(this, this, matrix2x3);
  3054. return this.check();
  3055. }
  3056. transformByMatrix2(matrix2) {
  3057. transformMat2(this, this, matrix2);
  3058. return this.check();
  3059. }
  3060. }
  3061. /**
  3062. * 3 Dimensional Vector
  3063. * @module vec3
  3064. */
  3065. /**
  3066. * Creates a new, empty vec3
  3067. *
  3068. * @returns {vec3} a new 3D vector
  3069. */
  3070. function create$3() {
  3071. var out = new ARRAY_TYPE(3);
  3072. if (ARRAY_TYPE != Float32Array) {
  3073. out[0] = 0;
  3074. out[1] = 0;
  3075. out[2] = 0;
  3076. }
  3077. return out;
  3078. }
  3079. /**
  3080. * Calculates the length of a vec3
  3081. *
  3082. * @param {ReadonlyVec3} a vector to calculate length of
  3083. * @returns {Number} length of a
  3084. */
  3085. function length$2(a) {
  3086. var x = a[0];
  3087. var y = a[1];
  3088. var z = a[2];
  3089. return Math.hypot(x, y, z);
  3090. }
  3091. /**
  3092. * Creates a new vec3 initialized with the given values
  3093. *
  3094. * @param {Number} x X component
  3095. * @param {Number} y Y component
  3096. * @param {Number} z Z component
  3097. * @returns {vec3} a new 3D vector
  3098. */
  3099. function fromValues(x, y, z) {
  3100. var out = new ARRAY_TYPE(3);
  3101. out[0] = x;
  3102. out[1] = y;
  3103. out[2] = z;
  3104. return out;
  3105. }
  3106. /**
  3107. * Normalize a vec3
  3108. *
  3109. * @param {vec3} out the receiving vector
  3110. * @param {ReadonlyVec3} a vector to normalize
  3111. * @returns {vec3} out
  3112. */
  3113. function normalize$2(out, a) {
  3114. var x = a[0];
  3115. var y = a[1];
  3116. var z = a[2];
  3117. var len = x * x + y * y + z * z;
  3118. if (len > 0) {
  3119. //TODO: evaluate use of glm_invsqrt here?
  3120. len = 1 / Math.sqrt(len);
  3121. }
  3122. out[0] = a[0] * len;
  3123. out[1] = a[1] * len;
  3124. out[2] = a[2] * len;
  3125. return out;
  3126. }
  3127. /**
  3128. * Calculates the dot product of two vec3's
  3129. *
  3130. * @param {ReadonlyVec3} a the first operand
  3131. * @param {ReadonlyVec3} b the second operand
  3132. * @returns {Number} dot product of a and b
  3133. */
  3134. function dot$2(a, b) {
  3135. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  3136. }
  3137. /**
  3138. * Computes the cross product of two vec3's
  3139. *
  3140. * @param {vec3} out the receiving vector
  3141. * @param {ReadonlyVec3} a the first operand
  3142. * @param {ReadonlyVec3} b the second operand
  3143. * @returns {vec3} out
  3144. */
  3145. function cross(out, a, b) {
  3146. var ax = a[0],
  3147. ay = a[1],
  3148. az = a[2];
  3149. var bx = b[0],
  3150. by = b[1],
  3151. bz = b[2];
  3152. out[0] = ay * bz - az * by;
  3153. out[1] = az * bx - ax * bz;
  3154. out[2] = ax * by - ay * bx;
  3155. return out;
  3156. }
  3157. /**
  3158. * Transforms the vec3 with a mat4.
  3159. * 4th vector component is implicitly '1'
  3160. *
  3161. * @param {vec3} out the receiving vector
  3162. * @param {ReadonlyVec3} a the vector to transform
  3163. * @param {ReadonlyMat4} m matrix to transform with
  3164. * @returns {vec3} out
  3165. */
  3166. function transformMat4$1(out, a, m) {
  3167. var x = a[0],
  3168. y = a[1],
  3169. z = a[2];
  3170. var w = m[3] * x + m[7] * y + m[11] * z + m[15];
  3171. w = w || 1.0;
  3172. out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
  3173. out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
  3174. out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
  3175. return out;
  3176. }
  3177. /**
  3178. * Transforms the vec3 with a mat3.
  3179. *
  3180. * @param {vec3} out the receiving vector
  3181. * @param {ReadonlyVec3} a the vector to transform
  3182. * @param {ReadonlyMat3} m the 3x3 matrix to transform with
  3183. * @returns {vec3} out
  3184. */
  3185. function transformMat3(out, a, m) {
  3186. var x = a[0],
  3187. y = a[1],
  3188. z = a[2];
  3189. out[0] = x * m[0] + y * m[3] + z * m[6];
  3190. out[1] = x * m[1] + y * m[4] + z * m[7];
  3191. out[2] = x * m[2] + y * m[5] + z * m[8];
  3192. return out;
  3193. }
  3194. /**
  3195. * Transforms the vec3 with a quat
  3196. * Can also be used for dual quaternions. (Multiply it with the real part)
  3197. *
  3198. * @param {vec3} out the receiving vector
  3199. * @param {ReadonlyVec3} a the vector to transform
  3200. * @param {ReadonlyQuat} q quaternion to transform with
  3201. * @returns {vec3} out
  3202. */
  3203. function transformQuat$1(out, a, q) {
  3204. // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed
  3205. var qx = q[0],
  3206. qy = q[1],
  3207. qz = q[2],
  3208. qw = q[3];
  3209. var x = a[0],
  3210. y = a[1],
  3211. z = a[2]; // var qvec = [qx, qy, qz];
  3212. // var uv = vec3.cross([], qvec, a);
  3213. var uvx = qy * z - qz * y,
  3214. uvy = qz * x - qx * z,
  3215. uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);
  3216. var uuvx = qy * uvz - qz * uvy,
  3217. uuvy = qz * uvx - qx * uvz,
  3218. uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);
  3219. var w2 = qw * 2;
  3220. uvx *= w2;
  3221. uvy *= w2;
  3222. uvz *= w2; // vec3.scale(uuv, uuv, 2);
  3223. uuvx *= 2;
  3224. uuvy *= 2;
  3225. uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));
  3226. out[0] = x + uvx + uuvx;
  3227. out[1] = y + uvy + uuvy;
  3228. out[2] = z + uvz + uuvz;
  3229. return out;
  3230. }
  3231. /**
  3232. * Rotate a 3D vector around the x-axis
  3233. * @param {vec3} out The receiving vec3
  3234. * @param {ReadonlyVec3} a The vec3 point to rotate
  3235. * @param {ReadonlyVec3} b The origin of the rotation
  3236. * @param {Number} rad The angle of rotation in radians
  3237. * @returns {vec3} out
  3238. */
  3239. function rotateX$2(out, a, b, rad) {
  3240. var p = [],
  3241. r = []; //Translate point to the origin
  3242. p[0] = a[0] - b[0];
  3243. p[1] = a[1] - b[1];
  3244. p[2] = a[2] - b[2]; //perform rotation
  3245. r[0] = p[0];
  3246. r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);
  3247. r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position
  3248. out[0] = r[0] + b[0];
  3249. out[1] = r[1] + b[1];
  3250. out[2] = r[2] + b[2];
  3251. return out;
  3252. }
  3253. /**
  3254. * Rotate a 3D vector around the y-axis
  3255. * @param {vec3} out The receiving vec3
  3256. * @param {ReadonlyVec3} a The vec3 point to rotate
  3257. * @param {ReadonlyVec3} b The origin of the rotation
  3258. * @param {Number} rad The angle of rotation in radians
  3259. * @returns {vec3} out
  3260. */
  3261. function rotateY$2(out, a, b, rad) {
  3262. var p = [],
  3263. r = []; //Translate point to the origin
  3264. p[0] = a[0] - b[0];
  3265. p[1] = a[1] - b[1];
  3266. p[2] = a[2] - b[2]; //perform rotation
  3267. r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);
  3268. r[1] = p[1];
  3269. r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position
  3270. out[0] = r[0] + b[0];
  3271. out[1] = r[1] + b[1];
  3272. out[2] = r[2] + b[2];
  3273. return out;
  3274. }
  3275. /**
  3276. * Rotate a 3D vector around the z-axis
  3277. * @param {vec3} out The receiving vec3
  3278. * @param {ReadonlyVec3} a The vec3 point to rotate
  3279. * @param {ReadonlyVec3} b The origin of the rotation
  3280. * @param {Number} rad The angle of rotation in radians
  3281. * @returns {vec3} out
  3282. */
  3283. function rotateZ$2(out, a, b, rad) {
  3284. var p = [],
  3285. r = []; //Translate point to the origin
  3286. p[0] = a[0] - b[0];
  3287. p[1] = a[1] - b[1];
  3288. p[2] = a[2] - b[2]; //perform rotation
  3289. r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);
  3290. r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);
  3291. r[2] = p[2]; //translate to correct position
  3292. out[0] = r[0] + b[0];
  3293. out[1] = r[1] + b[1];
  3294. out[2] = r[2] + b[2];
  3295. return out;
  3296. }
  3297. /**
  3298. * Get the angle between two 3D vectors
  3299. * @param {ReadonlyVec3} a The first operand
  3300. * @param {ReadonlyVec3} b The second operand
  3301. * @returns {Number} The angle in radians
  3302. */
  3303. function angle(a, b) {
  3304. var ax = a[0],
  3305. ay = a[1],
  3306. az = a[2],
  3307. bx = b[0],
  3308. by = b[1],
  3309. bz = b[2],
  3310. mag1 = Math.sqrt(ax * ax + ay * ay + az * az),
  3311. mag2 = Math.sqrt(bx * bx + by * by + bz * bz),
  3312. mag = mag1 * mag2,
  3313. cosine = mag && dot$2(a, b) / mag;
  3314. return Math.acos(Math.min(Math.max(cosine, -1), 1));
  3315. }
  3316. /**
  3317. * Alias for {@link vec3.length}
  3318. * @function
  3319. */
  3320. var len = length$2;
  3321. /**
  3322. * Perform some operation over an array of vec3s.
  3323. *
  3324. * @param {Array} a the array of vectors to iterate over
  3325. * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
  3326. * @param {Number} offset Number of elements to skip at the beginning of the array
  3327. * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
  3328. * @param {Function} fn Function to call for each vector in the array
  3329. * @param {Object} [arg] additional argument to pass to fn
  3330. * @returns {Array} a
  3331. * @function
  3332. */
  3333. (function () {
  3334. var vec = create$3();
  3335. return function (a, stride, offset, count, fn, arg) {
  3336. var i, l;
  3337. if (!stride) {
  3338. stride = 3;
  3339. }
  3340. if (!offset) {
  3341. offset = 0;
  3342. }
  3343. if (count) {
  3344. l = Math.min(count * stride + offset, a.length);
  3345. } else {
  3346. l = a.length;
  3347. }
  3348. for (i = offset; i < l; i += stride) {
  3349. vec[0] = a[i];
  3350. vec[1] = a[i + 1];
  3351. vec[2] = a[i + 2];
  3352. fn(vec, vec, arg);
  3353. a[i] = vec[0];
  3354. a[i + 1] = vec[1];
  3355. a[i + 2] = vec[2];
  3356. }
  3357. return a;
  3358. };
  3359. })();
  3360. const ORIGIN = [0, 0, 0];
  3361. let ZERO$2;
  3362. class Vector3 extends Vector {
  3363. static get ZERO() {
  3364. if (!ZERO$2) {
  3365. ZERO$2 = new Vector3(0, 0, 0);
  3366. Object.freeze(ZERO$2);
  3367. }
  3368. return ZERO$2;
  3369. }
  3370. constructor(x = 0, y = 0, z = 0) {
  3371. super(-0, -0, -0);
  3372. if (arguments.length === 1 && isArray(x)) {
  3373. this.copy(x);
  3374. } else {
  3375. if (config.debug) {
  3376. checkNumber(x);
  3377. checkNumber(y);
  3378. checkNumber(z);
  3379. }
  3380. this[0] = x;
  3381. this[1] = y;
  3382. this[2] = z;
  3383. }
  3384. }
  3385. set(x, y, z) {
  3386. this[0] = x;
  3387. this[1] = y;
  3388. this[2] = z;
  3389. return this.check();
  3390. }
  3391. copy(array) {
  3392. this[0] = array[0];
  3393. this[1] = array[1];
  3394. this[2] = array[2];
  3395. return this.check();
  3396. }
  3397. fromObject(object) {
  3398. if (config.debug) {
  3399. checkNumber(object.x);
  3400. checkNumber(object.y);
  3401. checkNumber(object.z);
  3402. }
  3403. this[0] = object.x;
  3404. this[1] = object.y;
  3405. this[2] = object.z;
  3406. return this.check();
  3407. }
  3408. toObject(object) {
  3409. object.x = this[0];
  3410. object.y = this[1];
  3411. object.z = this[2];
  3412. return object;
  3413. }
  3414. get ELEMENTS() {
  3415. return 3;
  3416. }
  3417. get z() {
  3418. return this[2];
  3419. }
  3420. set z(value) {
  3421. this[2] = checkNumber(value);
  3422. }
  3423. angle(vector) {
  3424. return angle(this, vector);
  3425. }
  3426. cross(vector) {
  3427. cross(this, this, vector);
  3428. return this.check();
  3429. }
  3430. rotateX({
  3431. radians,
  3432. origin = ORIGIN
  3433. }) {
  3434. rotateX$2(this, this, origin, radians);
  3435. return this.check();
  3436. }
  3437. rotateY({
  3438. radians,
  3439. origin = ORIGIN
  3440. }) {
  3441. rotateY$2(this, this, origin, radians);
  3442. return this.check();
  3443. }
  3444. rotateZ({
  3445. radians,
  3446. origin = ORIGIN
  3447. }) {
  3448. rotateZ$2(this, this, origin, radians);
  3449. return this.check();
  3450. }
  3451. transform(matrix4) {
  3452. return this.transformAsPoint(matrix4);
  3453. }
  3454. transformAsPoint(matrix4) {
  3455. transformMat4$1(this, this, matrix4);
  3456. return this.check();
  3457. }
  3458. transformAsVector(matrix4) {
  3459. vec3_transformMat4AsVector(this, this, matrix4);
  3460. return this.check();
  3461. }
  3462. transformByMatrix3(matrix3) {
  3463. transformMat3(this, this, matrix3);
  3464. return this.check();
  3465. }
  3466. transformByMatrix2(matrix2) {
  3467. vec3_transformMat2(this, this, matrix2);
  3468. return this.check();
  3469. }
  3470. transformByQuaternion(quaternion) {
  3471. transformQuat$1(this, this, quaternion);
  3472. return this.check();
  3473. }
  3474. }
  3475. let ZERO$1;
  3476. class Vector4 extends Vector {
  3477. static get ZERO() {
  3478. if (!ZERO$1) {
  3479. ZERO$1 = new Vector4(0, 0, 0, 0);
  3480. Object.freeze(ZERO$1);
  3481. }
  3482. return ZERO$1;
  3483. }
  3484. constructor(x = 0, y = 0, z = 0, w = 0) {
  3485. super(-0, -0, -0, -0);
  3486. if (isArray(x) && arguments.length === 1) {
  3487. this.copy(x);
  3488. } else {
  3489. if (config.debug) {
  3490. checkNumber(x);
  3491. checkNumber(y);
  3492. checkNumber(z);
  3493. checkNumber(w);
  3494. }
  3495. this[0] = x;
  3496. this[1] = y;
  3497. this[2] = z;
  3498. this[3] = w;
  3499. }
  3500. }
  3501. set(x, y, z, w) {
  3502. this[0] = x;
  3503. this[1] = y;
  3504. this[2] = z;
  3505. this[3] = w;
  3506. return this.check();
  3507. }
  3508. copy(array) {
  3509. this[0] = array[0];
  3510. this[1] = array[1];
  3511. this[2] = array[2];
  3512. this[3] = array[3];
  3513. return this.check();
  3514. }
  3515. fromObject(object) {
  3516. if (config.debug) {
  3517. checkNumber(object.x);
  3518. checkNumber(object.y);
  3519. checkNumber(object.z);
  3520. checkNumber(object.w);
  3521. }
  3522. this[0] = object.x;
  3523. this[1] = object.y;
  3524. this[2] = object.z;
  3525. this[3] = object.w;
  3526. return this;
  3527. }
  3528. toObject(object) {
  3529. object.x = this[0];
  3530. object.y = this[1];
  3531. object.z = this[2];
  3532. object.w = this[3];
  3533. return object;
  3534. }
  3535. get ELEMENTS() {
  3536. return 4;
  3537. }
  3538. get z() {
  3539. return this[2];
  3540. }
  3541. set z(value) {
  3542. this[2] = checkNumber(value);
  3543. }
  3544. get w() {
  3545. return this[3];
  3546. }
  3547. set w(value) {
  3548. this[3] = checkNumber(value);
  3549. }
  3550. transform(matrix4) {
  3551. transformMat4$1(this, this, matrix4);
  3552. return this.check();
  3553. }
  3554. transformByMatrix3(matrix3) {
  3555. vec4_transformMat3(this, this, matrix3);
  3556. return this.check();
  3557. }
  3558. transformByMatrix2(matrix2) {
  3559. vec4_transformMat2(this, this, matrix2);
  3560. return this.check();
  3561. }
  3562. transformByQuaternion(quaternion) {
  3563. transformQuat$1(this, this, quaternion);
  3564. return this.check();
  3565. }
  3566. applyMatrix4(m) {
  3567. m.transform(this, this);
  3568. return this;
  3569. }
  3570. }
  3571. class Matrix extends MathArray {
  3572. toString() {
  3573. let string = '[';
  3574. if (config.printRowMajor) {
  3575. string += 'row-major:';
  3576. for (let row = 0; row < this.RANK; ++row) {
  3577. for (let col = 0; col < this.RANK; ++col) {
  3578. string += " ".concat(this[col * this.RANK + row]);
  3579. }
  3580. }
  3581. } else {
  3582. string += 'column-major:';
  3583. for (let i = 0; i < this.ELEMENTS; ++i) {
  3584. string += " ".concat(this[i]);
  3585. }
  3586. }
  3587. string += ']';
  3588. return string;
  3589. }
  3590. getElementIndex(row, col) {
  3591. return col * this.RANK + row;
  3592. }
  3593. getElement(row, col) {
  3594. return this[col * this.RANK + row];
  3595. }
  3596. setElement(row, col, value) {
  3597. this[col * this.RANK + row] = checkNumber(value);
  3598. return this;
  3599. }
  3600. getColumn(columnIndex, result = new Array(this.RANK).fill(-0)) {
  3601. const firstIndex = columnIndex * this.RANK;
  3602. for (let i = 0; i < this.RANK; ++i) {
  3603. result[i] = this[firstIndex + i];
  3604. }
  3605. return result;
  3606. }
  3607. setColumn(columnIndex, columnVector) {
  3608. const firstIndex = columnIndex * this.RANK;
  3609. for (let i = 0; i < this.RANK; ++i) {
  3610. this[firstIndex + i] = columnVector[i];
  3611. }
  3612. return this;
  3613. }
  3614. }
  3615. /**
  3616. * 3x3 Matrix
  3617. * @module mat3
  3618. */
  3619. /**
  3620. * Creates a new identity mat3
  3621. *
  3622. * @returns {mat3} a new 3x3 matrix
  3623. */
  3624. function create$2() {
  3625. var out = new ARRAY_TYPE(9);
  3626. if (ARRAY_TYPE != Float32Array) {
  3627. out[1] = 0;
  3628. out[2] = 0;
  3629. out[3] = 0;
  3630. out[5] = 0;
  3631. out[6] = 0;
  3632. out[7] = 0;
  3633. }
  3634. out[0] = 1;
  3635. out[4] = 1;
  3636. out[8] = 1;
  3637. return out;
  3638. }
  3639. /**
  3640. * Transpose the values of a mat3
  3641. *
  3642. * @param {mat3} out the receiving matrix
  3643. * @param {ReadonlyMat3} a the source matrix
  3644. * @returns {mat3} out
  3645. */
  3646. function transpose$1(out, a) {
  3647. // If we are transposing ourselves we can skip a few steps but have to cache some values
  3648. if (out === a) {
  3649. var a01 = a[1],
  3650. a02 = a[2],
  3651. a12 = a[5];
  3652. out[1] = a[3];
  3653. out[2] = a[6];
  3654. out[3] = a01;
  3655. out[5] = a[7];
  3656. out[6] = a02;
  3657. out[7] = a12;
  3658. } else {
  3659. out[0] = a[0];
  3660. out[1] = a[3];
  3661. out[2] = a[6];
  3662. out[3] = a[1];
  3663. out[4] = a[4];
  3664. out[5] = a[7];
  3665. out[6] = a[2];
  3666. out[7] = a[5];
  3667. out[8] = a[8];
  3668. }
  3669. return out;
  3670. }
  3671. /**
  3672. * Inverts a mat3
  3673. *
  3674. * @param {mat3} out the receiving matrix
  3675. * @param {ReadonlyMat3} a the source matrix
  3676. * @returns {mat3} out
  3677. */
  3678. function invert$2(out, a) {
  3679. var a00 = a[0],
  3680. a01 = a[1],
  3681. a02 = a[2];
  3682. var a10 = a[3],
  3683. a11 = a[4],
  3684. a12 = a[5];
  3685. var a20 = a[6],
  3686. a21 = a[7],
  3687. a22 = a[8];
  3688. var b01 = a22 * a11 - a12 * a21;
  3689. var b11 = -a22 * a10 + a12 * a20;
  3690. var b21 = a21 * a10 - a11 * a20; // Calculate the determinant
  3691. var det = a00 * b01 + a01 * b11 + a02 * b21;
  3692. if (!det) {
  3693. return null;
  3694. }
  3695. det = 1.0 / det;
  3696. out[0] = b01 * det;
  3697. out[1] = (-a22 * a01 + a02 * a21) * det;
  3698. out[2] = (a12 * a01 - a02 * a11) * det;
  3699. out[3] = b11 * det;
  3700. out[4] = (a22 * a00 - a02 * a20) * det;
  3701. out[5] = (-a12 * a00 + a02 * a10) * det;
  3702. out[6] = b21 * det;
  3703. out[7] = (-a21 * a00 + a01 * a20) * det;
  3704. out[8] = (a11 * a00 - a01 * a10) * det;
  3705. return out;
  3706. }
  3707. /**
  3708. * Calculates the determinant of a mat3
  3709. *
  3710. * @param {ReadonlyMat3} a the source matrix
  3711. * @returns {Number} determinant of a
  3712. */
  3713. function determinant$1(a) {
  3714. var a00 = a[0],
  3715. a01 = a[1],
  3716. a02 = a[2];
  3717. var a10 = a[3],
  3718. a11 = a[4],
  3719. a12 = a[5];
  3720. var a20 = a[6],
  3721. a21 = a[7],
  3722. a22 = a[8];
  3723. return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
  3724. }
  3725. /**
  3726. * Multiplies two mat3's
  3727. *
  3728. * @param {mat3} out the receiving matrix
  3729. * @param {ReadonlyMat3} a the first operand
  3730. * @param {ReadonlyMat3} b the second operand
  3731. * @returns {mat3} out
  3732. */
  3733. function multiply$2(out, a, b) {
  3734. var a00 = a[0],
  3735. a01 = a[1],
  3736. a02 = a[2];
  3737. var a10 = a[3],
  3738. a11 = a[4],
  3739. a12 = a[5];
  3740. var a20 = a[6],
  3741. a21 = a[7],
  3742. a22 = a[8];
  3743. var b00 = b[0],
  3744. b01 = b[1],
  3745. b02 = b[2];
  3746. var b10 = b[3],
  3747. b11 = b[4],
  3748. b12 = b[5];
  3749. var b20 = b[6],
  3750. b21 = b[7],
  3751. b22 = b[8];
  3752. out[0] = b00 * a00 + b01 * a10 + b02 * a20;
  3753. out[1] = b00 * a01 + b01 * a11 + b02 * a21;
  3754. out[2] = b00 * a02 + b01 * a12 + b02 * a22;
  3755. out[3] = b10 * a00 + b11 * a10 + b12 * a20;
  3756. out[4] = b10 * a01 + b11 * a11 + b12 * a21;
  3757. out[5] = b10 * a02 + b11 * a12 + b12 * a22;
  3758. out[6] = b20 * a00 + b21 * a10 + b22 * a20;
  3759. out[7] = b20 * a01 + b21 * a11 + b22 * a21;
  3760. out[8] = b20 * a02 + b21 * a12 + b22 * a22;
  3761. return out;
  3762. }
  3763. /**
  3764. * Translate a mat3 by the given vector
  3765. *
  3766. * @param {mat3} out the receiving matrix
  3767. * @param {ReadonlyMat3} a the matrix to translate
  3768. * @param {ReadonlyVec2} v vector to translate by
  3769. * @returns {mat3} out
  3770. */
  3771. function translate$1(out, a, v) {
  3772. var a00 = a[0],
  3773. a01 = a[1],
  3774. a02 = a[2],
  3775. a10 = a[3],
  3776. a11 = a[4],
  3777. a12 = a[5],
  3778. a20 = a[6],
  3779. a21 = a[7],
  3780. a22 = a[8],
  3781. x = v[0],
  3782. y = v[1];
  3783. out[0] = a00;
  3784. out[1] = a01;
  3785. out[2] = a02;
  3786. out[3] = a10;
  3787. out[4] = a11;
  3788. out[5] = a12;
  3789. out[6] = x * a00 + y * a10 + a20;
  3790. out[7] = x * a01 + y * a11 + a21;
  3791. out[8] = x * a02 + y * a12 + a22;
  3792. return out;
  3793. }
  3794. /**
  3795. * Rotates a mat3 by the given angle
  3796. *
  3797. * @param {mat3} out the receiving matrix
  3798. * @param {ReadonlyMat3} a the matrix to rotate
  3799. * @param {Number} rad the angle to rotate the matrix by
  3800. * @returns {mat3} out
  3801. */
  3802. function rotate$1(out, a, rad) {
  3803. var a00 = a[0],
  3804. a01 = a[1],
  3805. a02 = a[2],
  3806. a10 = a[3],
  3807. a11 = a[4],
  3808. a12 = a[5],
  3809. a20 = a[6],
  3810. a21 = a[7],
  3811. a22 = a[8],
  3812. s = Math.sin(rad),
  3813. c = Math.cos(rad);
  3814. out[0] = c * a00 + s * a10;
  3815. out[1] = c * a01 + s * a11;
  3816. out[2] = c * a02 + s * a12;
  3817. out[3] = c * a10 - s * a00;
  3818. out[4] = c * a11 - s * a01;
  3819. out[5] = c * a12 - s * a02;
  3820. out[6] = a20;
  3821. out[7] = a21;
  3822. out[8] = a22;
  3823. return out;
  3824. }
  3825. /**
  3826. * Scales the mat3 by the dimensions in the given vec2
  3827. *
  3828. * @param {mat3} out the receiving matrix
  3829. * @param {ReadonlyMat3} a the matrix to rotate
  3830. * @param {ReadonlyVec2} v the vec2 to scale the matrix by
  3831. * @returns {mat3} out
  3832. **/
  3833. function scale$3(out, a, v) {
  3834. var x = v[0],
  3835. y = v[1];
  3836. out[0] = x * a[0];
  3837. out[1] = x * a[1];
  3838. out[2] = x * a[2];
  3839. out[3] = y * a[3];
  3840. out[4] = y * a[4];
  3841. out[5] = y * a[5];
  3842. out[6] = a[6];
  3843. out[7] = a[7];
  3844. out[8] = a[8];
  3845. return out;
  3846. }
  3847. /**
  3848. * Calculates a 3x3 matrix from the given quaternion
  3849. *
  3850. * @param {mat3} out mat3 receiving operation result
  3851. * @param {ReadonlyQuat} q Quaternion to create matrix from
  3852. *
  3853. * @returns {mat3} out
  3854. */
  3855. function fromQuat$1(out, q) {
  3856. var x = q[0],
  3857. y = q[1],
  3858. z = q[2],
  3859. w = q[3];
  3860. var x2 = x + x;
  3861. var y2 = y + y;
  3862. var z2 = z + z;
  3863. var xx = x * x2;
  3864. var yx = y * x2;
  3865. var yy = y * y2;
  3866. var zx = z * x2;
  3867. var zy = z * y2;
  3868. var zz = z * z2;
  3869. var wx = w * x2;
  3870. var wy = w * y2;
  3871. var wz = w * z2;
  3872. out[0] = 1 - yy - zz;
  3873. out[3] = yx - wz;
  3874. out[6] = zx + wy;
  3875. out[1] = yx + wz;
  3876. out[4] = 1 - xx - zz;
  3877. out[7] = zy - wx;
  3878. out[2] = zx - wy;
  3879. out[5] = zy + wx;
  3880. out[8] = 1 - xx - yy;
  3881. return out;
  3882. }
  3883. var INDICES$1;
  3884. (function (INDICES) {
  3885. INDICES[INDICES["COL0ROW0"] = 0] = "COL0ROW0";
  3886. INDICES[INDICES["COL0ROW1"] = 1] = "COL0ROW1";
  3887. INDICES[INDICES["COL0ROW2"] = 2] = "COL0ROW2";
  3888. INDICES[INDICES["COL1ROW0"] = 3] = "COL1ROW0";
  3889. INDICES[INDICES["COL1ROW1"] = 4] = "COL1ROW1";
  3890. INDICES[INDICES["COL1ROW2"] = 5] = "COL1ROW2";
  3891. INDICES[INDICES["COL2ROW0"] = 6] = "COL2ROW0";
  3892. INDICES[INDICES["COL2ROW1"] = 7] = "COL2ROW1";
  3893. INDICES[INDICES["COL2ROW2"] = 8] = "COL2ROW2";
  3894. })(INDICES$1 || (INDICES$1 = {}));
  3895. const IDENTITY_MATRIX$1 = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1]);
  3896. class Matrix3 extends Matrix {
  3897. static get IDENTITY() {
  3898. return getIdentityMatrix$1();
  3899. }
  3900. static get ZERO() {
  3901. return getZeroMatrix$1();
  3902. }
  3903. get ELEMENTS() {
  3904. return 9;
  3905. }
  3906. get RANK() {
  3907. return 3;
  3908. }
  3909. get INDICES() {
  3910. return INDICES$1;
  3911. }
  3912. constructor(array, ...args) {
  3913. super(-0, -0, -0, -0, -0, -0, -0, -0, -0);
  3914. if (arguments.length === 1 && Array.isArray(array)) {
  3915. this.copy(array);
  3916. } else if (args.length > 0) {
  3917. this.copy([array, ...args]);
  3918. } else {
  3919. this.identity();
  3920. }
  3921. }
  3922. copy(array) {
  3923. this[0] = array[0];
  3924. this[1] = array[1];
  3925. this[2] = array[2];
  3926. this[3] = array[3];
  3927. this[4] = array[4];
  3928. this[5] = array[5];
  3929. this[6] = array[6];
  3930. this[7] = array[7];
  3931. this[8] = array[8];
  3932. return this.check();
  3933. }
  3934. identity() {
  3935. return this.copy(IDENTITY_MATRIX$1);
  3936. }
  3937. fromObject(object) {
  3938. return this.check();
  3939. }
  3940. fromQuaternion(q) {
  3941. fromQuat$1(this, q);
  3942. return this.check();
  3943. }
  3944. set(m00, m10, m20, m01, m11, m21, m02, m12, m22) {
  3945. this[0] = m00;
  3946. this[1] = m10;
  3947. this[2] = m20;
  3948. this[3] = m01;
  3949. this[4] = m11;
  3950. this[5] = m21;
  3951. this[6] = m02;
  3952. this[7] = m12;
  3953. this[8] = m22;
  3954. return this.check();
  3955. }
  3956. setRowMajor(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
  3957. this[0] = m00;
  3958. this[1] = m10;
  3959. this[2] = m20;
  3960. this[3] = m01;
  3961. this[4] = m11;
  3962. this[5] = m21;
  3963. this[6] = m02;
  3964. this[7] = m12;
  3965. this[8] = m22;
  3966. return this.check();
  3967. }
  3968. determinant() {
  3969. return determinant$1(this);
  3970. }
  3971. transpose() {
  3972. transpose$1(this, this);
  3973. return this.check();
  3974. }
  3975. invert() {
  3976. invert$2(this, this);
  3977. return this.check();
  3978. }
  3979. multiplyLeft(a) {
  3980. multiply$2(this, a, this);
  3981. return this.check();
  3982. }
  3983. multiplyRight(a) {
  3984. multiply$2(this, this, a);
  3985. return this.check();
  3986. }
  3987. rotate(radians) {
  3988. rotate$1(this, this, radians);
  3989. return this.check();
  3990. }
  3991. scale(factor) {
  3992. if (Array.isArray(factor)) {
  3993. scale$3(this, this, factor);
  3994. } else {
  3995. scale$3(this, this, [factor, factor]);
  3996. }
  3997. return this.check();
  3998. }
  3999. translate(vec) {
  4000. translate$1(this, this, vec);
  4001. return this.check();
  4002. }
  4003. transform(vector, result) {
  4004. let out;
  4005. switch (vector.length) {
  4006. case 2:
  4007. out = transformMat3$1(result || [-0, -0], vector, this);
  4008. break;
  4009. case 3:
  4010. out = transformMat3(result || [-0, -0, -0], vector, this);
  4011. break;
  4012. case 4:
  4013. out = vec4_transformMat3(result || [-0, -0, -0, -0], vector, this);
  4014. break;
  4015. default:
  4016. throw new Error('Illegal vector');
  4017. }
  4018. checkVector(out, vector.length);
  4019. return out;
  4020. }
  4021. transformVector(vector, result) {
  4022. return this.transform(vector, result);
  4023. }
  4024. transformVector2(vector, result) {
  4025. return this.transform(vector, result);
  4026. }
  4027. transformVector3(vector, result) {
  4028. return this.transform(vector, result);
  4029. }
  4030. }
  4031. let ZERO_MATRIX3;
  4032. let IDENTITY_MATRIX3;
  4033. function getZeroMatrix$1() {
  4034. if (!ZERO_MATRIX3) {
  4035. ZERO_MATRIX3 = new Matrix3([0, 0, 0, 0, 0, 0, 0, 0, 0]);
  4036. Object.freeze(ZERO_MATRIX3);
  4037. }
  4038. return ZERO_MATRIX3;
  4039. }
  4040. function getIdentityMatrix$1() {
  4041. if (!IDENTITY_MATRIX3) {
  4042. IDENTITY_MATRIX3 = new Matrix3();
  4043. Object.freeze(IDENTITY_MATRIX3);
  4044. }
  4045. return IDENTITY_MATRIX3;
  4046. }
  4047. /**
  4048. * Set a mat4 to the identity matrix
  4049. *
  4050. * @param {mat4} out the receiving matrix
  4051. * @returns {mat4} out
  4052. */
  4053. function identity$2(out) {
  4054. out[0] = 1;
  4055. out[1] = 0;
  4056. out[2] = 0;
  4057. out[3] = 0;
  4058. out[4] = 0;
  4059. out[5] = 1;
  4060. out[6] = 0;
  4061. out[7] = 0;
  4062. out[8] = 0;
  4063. out[9] = 0;
  4064. out[10] = 1;
  4065. out[11] = 0;
  4066. out[12] = 0;
  4067. out[13] = 0;
  4068. out[14] = 0;
  4069. out[15] = 1;
  4070. return out;
  4071. }
  4072. /**
  4073. * Transpose the values of a mat4
  4074. *
  4075. * @param {mat4} out the receiving matrix
  4076. * @param {ReadonlyMat4} a the source matrix
  4077. * @returns {mat4} out
  4078. */
  4079. function transpose(out, a) {
  4080. // If we are transposing ourselves we can skip a few steps but have to cache some values
  4081. if (out === a) {
  4082. var a01 = a[1],
  4083. a02 = a[2],
  4084. a03 = a[3];
  4085. var a12 = a[6],
  4086. a13 = a[7];
  4087. var a23 = a[11];
  4088. out[1] = a[4];
  4089. out[2] = a[8];
  4090. out[3] = a[12];
  4091. out[4] = a01;
  4092. out[6] = a[9];
  4093. out[7] = a[13];
  4094. out[8] = a02;
  4095. out[9] = a12;
  4096. out[11] = a[14];
  4097. out[12] = a03;
  4098. out[13] = a13;
  4099. out[14] = a23;
  4100. } else {
  4101. out[0] = a[0];
  4102. out[1] = a[4];
  4103. out[2] = a[8];
  4104. out[3] = a[12];
  4105. out[4] = a[1];
  4106. out[5] = a[5];
  4107. out[6] = a[9];
  4108. out[7] = a[13];
  4109. out[8] = a[2];
  4110. out[9] = a[6];
  4111. out[10] = a[10];
  4112. out[11] = a[14];
  4113. out[12] = a[3];
  4114. out[13] = a[7];
  4115. out[14] = a[11];
  4116. out[15] = a[15];
  4117. }
  4118. return out;
  4119. }
  4120. /**
  4121. * Inverts a mat4
  4122. *
  4123. * @param {mat4} out the receiving matrix
  4124. * @param {ReadonlyMat4} a the source matrix
  4125. * @returns {mat4} out
  4126. */
  4127. function invert$1(out, a) {
  4128. var a00 = a[0],
  4129. a01 = a[1],
  4130. a02 = a[2],
  4131. a03 = a[3];
  4132. var a10 = a[4],
  4133. a11 = a[5],
  4134. a12 = a[6],
  4135. a13 = a[7];
  4136. var a20 = a[8],
  4137. a21 = a[9],
  4138. a22 = a[10],
  4139. a23 = a[11];
  4140. var a30 = a[12],
  4141. a31 = a[13],
  4142. a32 = a[14],
  4143. a33 = a[15];
  4144. var b00 = a00 * a11 - a01 * a10;
  4145. var b01 = a00 * a12 - a02 * a10;
  4146. var b02 = a00 * a13 - a03 * a10;
  4147. var b03 = a01 * a12 - a02 * a11;
  4148. var b04 = a01 * a13 - a03 * a11;
  4149. var b05 = a02 * a13 - a03 * a12;
  4150. var b06 = a20 * a31 - a21 * a30;
  4151. var b07 = a20 * a32 - a22 * a30;
  4152. var b08 = a20 * a33 - a23 * a30;
  4153. var b09 = a21 * a32 - a22 * a31;
  4154. var b10 = a21 * a33 - a23 * a31;
  4155. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  4156. var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  4157. if (!det) {
  4158. return null;
  4159. }
  4160. det = 1.0 / det;
  4161. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  4162. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  4163. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  4164. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  4165. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  4166. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  4167. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  4168. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  4169. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  4170. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  4171. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  4172. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  4173. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  4174. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  4175. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  4176. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  4177. return out;
  4178. }
  4179. /**
  4180. * Calculates the determinant of a mat4
  4181. *
  4182. * @param {ReadonlyMat4} a the source matrix
  4183. * @returns {Number} determinant of a
  4184. */
  4185. function determinant(a) {
  4186. var a00 = a[0],
  4187. a01 = a[1],
  4188. a02 = a[2],
  4189. a03 = a[3];
  4190. var a10 = a[4],
  4191. a11 = a[5],
  4192. a12 = a[6],
  4193. a13 = a[7];
  4194. var a20 = a[8],
  4195. a21 = a[9],
  4196. a22 = a[10],
  4197. a23 = a[11];
  4198. var a30 = a[12],
  4199. a31 = a[13],
  4200. a32 = a[14],
  4201. a33 = a[15];
  4202. var b00 = a00 * a11 - a01 * a10;
  4203. var b01 = a00 * a12 - a02 * a10;
  4204. var b02 = a00 * a13 - a03 * a10;
  4205. var b03 = a01 * a12 - a02 * a11;
  4206. var b04 = a01 * a13 - a03 * a11;
  4207. var b05 = a02 * a13 - a03 * a12;
  4208. var b06 = a20 * a31 - a21 * a30;
  4209. var b07 = a20 * a32 - a22 * a30;
  4210. var b08 = a20 * a33 - a23 * a30;
  4211. var b09 = a21 * a32 - a22 * a31;
  4212. var b10 = a21 * a33 - a23 * a31;
  4213. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  4214. return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  4215. }
  4216. /**
  4217. * Multiplies two mat4s
  4218. *
  4219. * @param {mat4} out the receiving matrix
  4220. * @param {ReadonlyMat4} a the first operand
  4221. * @param {ReadonlyMat4} b the second operand
  4222. * @returns {mat4} out
  4223. */
  4224. function multiply$1(out, a, b) {
  4225. var a00 = a[0],
  4226. a01 = a[1],
  4227. a02 = a[2],
  4228. a03 = a[3];
  4229. var a10 = a[4],
  4230. a11 = a[5],
  4231. a12 = a[6],
  4232. a13 = a[7];
  4233. var a20 = a[8],
  4234. a21 = a[9],
  4235. a22 = a[10],
  4236. a23 = a[11];
  4237. var a30 = a[12],
  4238. a31 = a[13],
  4239. a32 = a[14],
  4240. a33 = a[15]; // Cache only the current line of the second matrix
  4241. var b0 = b[0],
  4242. b1 = b[1],
  4243. b2 = b[2],
  4244. b3 = b[3];
  4245. out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4246. out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4247. out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4248. out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4249. b0 = b[4];
  4250. b1 = b[5];
  4251. b2 = b[6];
  4252. b3 = b[7];
  4253. out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4254. out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4255. out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4256. out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4257. b0 = b[8];
  4258. b1 = b[9];
  4259. b2 = b[10];
  4260. b3 = b[11];
  4261. out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4262. out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4263. out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4264. out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4265. b0 = b[12];
  4266. b1 = b[13];
  4267. b2 = b[14];
  4268. b3 = b[15];
  4269. out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4270. out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4271. out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4272. out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4273. return out;
  4274. }
  4275. /**
  4276. * Translate a mat4 by the given vector
  4277. *
  4278. * @param {mat4} out the receiving matrix
  4279. * @param {ReadonlyMat4} a the matrix to translate
  4280. * @param {ReadonlyVec3} v vector to translate by
  4281. * @returns {mat4} out
  4282. */
  4283. function translate(out, a, v) {
  4284. var x = v[0],
  4285. y = v[1],
  4286. z = v[2];
  4287. var a00, a01, a02, a03;
  4288. var a10, a11, a12, a13;
  4289. var a20, a21, a22, a23;
  4290. if (a === out) {
  4291. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  4292. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  4293. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  4294. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  4295. } else {
  4296. a00 = a[0];
  4297. a01 = a[1];
  4298. a02 = a[2];
  4299. a03 = a[3];
  4300. a10 = a[4];
  4301. a11 = a[5];
  4302. a12 = a[6];
  4303. a13 = a[7];
  4304. a20 = a[8];
  4305. a21 = a[9];
  4306. a22 = a[10];
  4307. a23 = a[11];
  4308. out[0] = a00;
  4309. out[1] = a01;
  4310. out[2] = a02;
  4311. out[3] = a03;
  4312. out[4] = a10;
  4313. out[5] = a11;
  4314. out[6] = a12;
  4315. out[7] = a13;
  4316. out[8] = a20;
  4317. out[9] = a21;
  4318. out[10] = a22;
  4319. out[11] = a23;
  4320. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  4321. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  4322. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  4323. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  4324. }
  4325. return out;
  4326. }
  4327. /**
  4328. * Scales the mat4 by the dimensions in the given vec3 not using vectorization
  4329. *
  4330. * @param {mat4} out the receiving matrix
  4331. * @param {ReadonlyMat4} a the matrix to scale
  4332. * @param {ReadonlyVec3} v the vec3 to scale the matrix by
  4333. * @returns {mat4} out
  4334. **/
  4335. function scale$2(out, a, v) {
  4336. var x = v[0],
  4337. y = v[1],
  4338. z = v[2];
  4339. out[0] = a[0] * x;
  4340. out[1] = a[1] * x;
  4341. out[2] = a[2] * x;
  4342. out[3] = a[3] * x;
  4343. out[4] = a[4] * y;
  4344. out[5] = a[5] * y;
  4345. out[6] = a[6] * y;
  4346. out[7] = a[7] * y;
  4347. out[8] = a[8] * z;
  4348. out[9] = a[9] * z;
  4349. out[10] = a[10] * z;
  4350. out[11] = a[11] * z;
  4351. out[12] = a[12];
  4352. out[13] = a[13];
  4353. out[14] = a[14];
  4354. out[15] = a[15];
  4355. return out;
  4356. }
  4357. /**
  4358. * Rotates a mat4 by the given angle around the given axis
  4359. *
  4360. * @param {mat4} out the receiving matrix
  4361. * @param {ReadonlyMat4} a the matrix to rotate
  4362. * @param {Number} rad the angle to rotate the matrix by
  4363. * @param {ReadonlyVec3} axis the axis to rotate around
  4364. * @returns {mat4} out
  4365. */
  4366. function rotate(out, a, rad, axis) {
  4367. var x = axis[0],
  4368. y = axis[1],
  4369. z = axis[2];
  4370. var len = Math.hypot(x, y, z);
  4371. var s, c, t;
  4372. var a00, a01, a02, a03;
  4373. var a10, a11, a12, a13;
  4374. var a20, a21, a22, a23;
  4375. var b00, b01, b02;
  4376. var b10, b11, b12;
  4377. var b20, b21, b22;
  4378. if (len < EPSILON) {
  4379. return null;
  4380. }
  4381. len = 1 / len;
  4382. x *= len;
  4383. y *= len;
  4384. z *= len;
  4385. s = Math.sin(rad);
  4386. c = Math.cos(rad);
  4387. t = 1 - c;
  4388. a00 = a[0];
  4389. a01 = a[1];
  4390. a02 = a[2];
  4391. a03 = a[3];
  4392. a10 = a[4];
  4393. a11 = a[5];
  4394. a12 = a[6];
  4395. a13 = a[7];
  4396. a20 = a[8];
  4397. a21 = a[9];
  4398. a22 = a[10];
  4399. a23 = a[11]; // Construct the elements of the rotation matrix
  4400. b00 = x * x * t + c;
  4401. b01 = y * x * t + z * s;
  4402. b02 = z * x * t - y * s;
  4403. b10 = x * y * t - z * s;
  4404. b11 = y * y * t + c;
  4405. b12 = z * y * t + x * s;
  4406. b20 = x * z * t + y * s;
  4407. b21 = y * z * t - x * s;
  4408. b22 = z * z * t + c; // Perform rotation-specific matrix multiplication
  4409. out[0] = a00 * b00 + a10 * b01 + a20 * b02;
  4410. out[1] = a01 * b00 + a11 * b01 + a21 * b02;
  4411. out[2] = a02 * b00 + a12 * b01 + a22 * b02;
  4412. out[3] = a03 * b00 + a13 * b01 + a23 * b02;
  4413. out[4] = a00 * b10 + a10 * b11 + a20 * b12;
  4414. out[5] = a01 * b10 + a11 * b11 + a21 * b12;
  4415. out[6] = a02 * b10 + a12 * b11 + a22 * b12;
  4416. out[7] = a03 * b10 + a13 * b11 + a23 * b12;
  4417. out[8] = a00 * b20 + a10 * b21 + a20 * b22;
  4418. out[9] = a01 * b20 + a11 * b21 + a21 * b22;
  4419. out[10] = a02 * b20 + a12 * b21 + a22 * b22;
  4420. out[11] = a03 * b20 + a13 * b21 + a23 * b22;
  4421. if (a !== out) {
  4422. // If the source and destination differ, copy the unchanged last row
  4423. out[12] = a[12];
  4424. out[13] = a[13];
  4425. out[14] = a[14];
  4426. out[15] = a[15];
  4427. }
  4428. return out;
  4429. }
  4430. /**
  4431. * Rotates a matrix by the given angle around the X axis
  4432. *
  4433. * @param {mat4} out the receiving matrix
  4434. * @param {ReadonlyMat4} a the matrix to rotate
  4435. * @param {Number} rad the angle to rotate the matrix by
  4436. * @returns {mat4} out
  4437. */
  4438. function rotateX$1(out, a, rad) {
  4439. var s = Math.sin(rad);
  4440. var c = Math.cos(rad);
  4441. var a10 = a[4];
  4442. var a11 = a[5];
  4443. var a12 = a[6];
  4444. var a13 = a[7];
  4445. var a20 = a[8];
  4446. var a21 = a[9];
  4447. var a22 = a[10];
  4448. var a23 = a[11];
  4449. if (a !== out) {
  4450. // If the source and destination differ, copy the unchanged rows
  4451. out[0] = a[0];
  4452. out[1] = a[1];
  4453. out[2] = a[2];
  4454. out[3] = a[3];
  4455. out[12] = a[12];
  4456. out[13] = a[13];
  4457. out[14] = a[14];
  4458. out[15] = a[15];
  4459. } // Perform axis-specific matrix multiplication
  4460. out[4] = a10 * c + a20 * s;
  4461. out[5] = a11 * c + a21 * s;
  4462. out[6] = a12 * c + a22 * s;
  4463. out[7] = a13 * c + a23 * s;
  4464. out[8] = a20 * c - a10 * s;
  4465. out[9] = a21 * c - a11 * s;
  4466. out[10] = a22 * c - a12 * s;
  4467. out[11] = a23 * c - a13 * s;
  4468. return out;
  4469. }
  4470. /**
  4471. * Rotates a matrix by the given angle around the Y axis
  4472. *
  4473. * @param {mat4} out the receiving matrix
  4474. * @param {ReadonlyMat4} a the matrix to rotate
  4475. * @param {Number} rad the angle to rotate the matrix by
  4476. * @returns {mat4} out
  4477. */
  4478. function rotateY$1(out, a, rad) {
  4479. var s = Math.sin(rad);
  4480. var c = Math.cos(rad);
  4481. var a00 = a[0];
  4482. var a01 = a[1];
  4483. var a02 = a[2];
  4484. var a03 = a[3];
  4485. var a20 = a[8];
  4486. var a21 = a[9];
  4487. var a22 = a[10];
  4488. var a23 = a[11];
  4489. if (a !== out) {
  4490. // If the source and destination differ, copy the unchanged rows
  4491. out[4] = a[4];
  4492. out[5] = a[5];
  4493. out[6] = a[6];
  4494. out[7] = a[7];
  4495. out[12] = a[12];
  4496. out[13] = a[13];
  4497. out[14] = a[14];
  4498. out[15] = a[15];
  4499. } // Perform axis-specific matrix multiplication
  4500. out[0] = a00 * c - a20 * s;
  4501. out[1] = a01 * c - a21 * s;
  4502. out[2] = a02 * c - a22 * s;
  4503. out[3] = a03 * c - a23 * s;
  4504. out[8] = a00 * s + a20 * c;
  4505. out[9] = a01 * s + a21 * c;
  4506. out[10] = a02 * s + a22 * c;
  4507. out[11] = a03 * s + a23 * c;
  4508. return out;
  4509. }
  4510. /**
  4511. * Rotates a matrix by the given angle around the Z axis
  4512. *
  4513. * @param {mat4} out the receiving matrix
  4514. * @param {ReadonlyMat4} a the matrix to rotate
  4515. * @param {Number} rad the angle to rotate the matrix by
  4516. * @returns {mat4} out
  4517. */
  4518. function rotateZ$1(out, a, rad) {
  4519. var s = Math.sin(rad);
  4520. var c = Math.cos(rad);
  4521. var a00 = a[0];
  4522. var a01 = a[1];
  4523. var a02 = a[2];
  4524. var a03 = a[3];
  4525. var a10 = a[4];
  4526. var a11 = a[5];
  4527. var a12 = a[6];
  4528. var a13 = a[7];
  4529. if (a !== out) {
  4530. // If the source and destination differ, copy the unchanged last row
  4531. out[8] = a[8];
  4532. out[9] = a[9];
  4533. out[10] = a[10];
  4534. out[11] = a[11];
  4535. out[12] = a[12];
  4536. out[13] = a[13];
  4537. out[14] = a[14];
  4538. out[15] = a[15];
  4539. } // Perform axis-specific matrix multiplication
  4540. out[0] = a00 * c + a10 * s;
  4541. out[1] = a01 * c + a11 * s;
  4542. out[2] = a02 * c + a12 * s;
  4543. out[3] = a03 * c + a13 * s;
  4544. out[4] = a10 * c - a00 * s;
  4545. out[5] = a11 * c - a01 * s;
  4546. out[6] = a12 * c - a02 * s;
  4547. out[7] = a13 * c - a03 * s;
  4548. return out;
  4549. }
  4550. /**
  4551. * Returns the scaling factor component of a transformation
  4552. * matrix. If a matrix is built with fromRotationTranslationScale
  4553. * with a normalized Quaternion paramter, the returned vector will be
  4554. * the same as the scaling vector
  4555. * originally supplied.
  4556. * @param {vec3} out Vector to receive scaling factor component
  4557. * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
  4558. * @return {vec3} out
  4559. */
  4560. function getScaling(out, mat) {
  4561. var m11 = mat[0];
  4562. var m12 = mat[1];
  4563. var m13 = mat[2];
  4564. var m21 = mat[4];
  4565. var m22 = mat[5];
  4566. var m23 = mat[6];
  4567. var m31 = mat[8];
  4568. var m32 = mat[9];
  4569. var m33 = mat[10];
  4570. out[0] = Math.hypot(m11, m12, m13);
  4571. out[1] = Math.hypot(m21, m22, m23);
  4572. out[2] = Math.hypot(m31, m32, m33);
  4573. return out;
  4574. }
  4575. /**
  4576. * Calculates a 4x4 matrix from the given quaternion
  4577. *
  4578. * @param {mat4} out mat4 receiving operation result
  4579. * @param {ReadonlyQuat} q Quaternion to create matrix from
  4580. *
  4581. * @returns {mat4} out
  4582. */
  4583. function fromQuat(out, q) {
  4584. var x = q[0],
  4585. y = q[1],
  4586. z = q[2],
  4587. w = q[3];
  4588. var x2 = x + x;
  4589. var y2 = y + y;
  4590. var z2 = z + z;
  4591. var xx = x * x2;
  4592. var yx = y * x2;
  4593. var yy = y * y2;
  4594. var zx = z * x2;
  4595. var zy = z * y2;
  4596. var zz = z * z2;
  4597. var wx = w * x2;
  4598. var wy = w * y2;
  4599. var wz = w * z2;
  4600. out[0] = 1 - yy - zz;
  4601. out[1] = yx + wz;
  4602. out[2] = zx - wy;
  4603. out[3] = 0;
  4604. out[4] = yx - wz;
  4605. out[5] = 1 - xx - zz;
  4606. out[6] = zy + wx;
  4607. out[7] = 0;
  4608. out[8] = zx + wy;
  4609. out[9] = zy - wx;
  4610. out[10] = 1 - xx - yy;
  4611. out[11] = 0;
  4612. out[12] = 0;
  4613. out[13] = 0;
  4614. out[14] = 0;
  4615. out[15] = 1;
  4616. return out;
  4617. }
  4618. /**
  4619. * Generates a frustum matrix with the given bounds
  4620. *
  4621. * @param {mat4} out mat4 frustum matrix will be written into
  4622. * @param {Number} left Left bound of the frustum
  4623. * @param {Number} right Right bound of the frustum
  4624. * @param {Number} bottom Bottom bound of the frustum
  4625. * @param {Number} top Top bound of the frustum
  4626. * @param {Number} near Near bound of the frustum
  4627. * @param {Number} far Far bound of the frustum
  4628. * @returns {mat4} out
  4629. */
  4630. function frustum(out, left, right, bottom, top, near, far) {
  4631. var rl = 1 / (right - left);
  4632. var tb = 1 / (top - bottom);
  4633. var nf = 1 / (near - far);
  4634. out[0] = near * 2 * rl;
  4635. out[1] = 0;
  4636. out[2] = 0;
  4637. out[3] = 0;
  4638. out[4] = 0;
  4639. out[5] = near * 2 * tb;
  4640. out[6] = 0;
  4641. out[7] = 0;
  4642. out[8] = (right + left) * rl;
  4643. out[9] = (top + bottom) * tb;
  4644. out[10] = (far + near) * nf;
  4645. out[11] = -1;
  4646. out[12] = 0;
  4647. out[13] = 0;
  4648. out[14] = far * near * 2 * nf;
  4649. out[15] = 0;
  4650. return out;
  4651. }
  4652. /**
  4653. * Generates a perspective projection matrix with the given bounds.
  4654. * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],
  4655. * which matches WebGL/OpenGL's clip volume.
  4656. * Passing null/undefined/no value for far will generate infinite projection matrix.
  4657. *
  4658. * @param {mat4} out mat4 frustum matrix will be written into
  4659. * @param {number} fovy Vertical field of view in radians
  4660. * @param {number} aspect Aspect ratio. typically viewport width/height
  4661. * @param {number} near Near bound of the frustum
  4662. * @param {number} far Far bound of the frustum, can be null or Infinity
  4663. * @returns {mat4} out
  4664. */
  4665. function perspectiveNO(out, fovy, aspect, near, far) {
  4666. var f = 1.0 / Math.tan(fovy / 2),
  4667. nf;
  4668. out[0] = f / aspect;
  4669. out[1] = 0;
  4670. out[2] = 0;
  4671. out[3] = 0;
  4672. out[4] = 0;
  4673. out[5] = f;
  4674. out[6] = 0;
  4675. out[7] = 0;
  4676. out[8] = 0;
  4677. out[9] = 0;
  4678. out[11] = -1;
  4679. out[12] = 0;
  4680. out[13] = 0;
  4681. out[15] = 0;
  4682. if (far != null && far !== Infinity) {
  4683. nf = 1 / (near - far);
  4684. out[10] = (far + near) * nf;
  4685. out[14] = 2 * far * near * nf;
  4686. } else {
  4687. out[10] = -1;
  4688. out[14] = -2 * near;
  4689. }
  4690. return out;
  4691. }
  4692. /**
  4693. * Alias for {@link mat4.perspectiveNO}
  4694. * @function
  4695. */
  4696. var perspective = perspectiveNO;
  4697. /**
  4698. * Generates a orthogonal projection matrix with the given bounds.
  4699. * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],
  4700. * which matches WebGL/OpenGL's clip volume.
  4701. *
  4702. * @param {mat4} out mat4 frustum matrix will be written into
  4703. * @param {number} left Left bound of the frustum
  4704. * @param {number} right Right bound of the frustum
  4705. * @param {number} bottom Bottom bound of the frustum
  4706. * @param {number} top Top bound of the frustum
  4707. * @param {number} near Near bound of the frustum
  4708. * @param {number} far Far bound of the frustum
  4709. * @returns {mat4} out
  4710. */
  4711. function orthoNO(out, left, right, bottom, top, near, far) {
  4712. var lr = 1 / (left - right);
  4713. var bt = 1 / (bottom - top);
  4714. var nf = 1 / (near - far);
  4715. out[0] = -2 * lr;
  4716. out[1] = 0;
  4717. out[2] = 0;
  4718. out[3] = 0;
  4719. out[4] = 0;
  4720. out[5] = -2 * bt;
  4721. out[6] = 0;
  4722. out[7] = 0;
  4723. out[8] = 0;
  4724. out[9] = 0;
  4725. out[10] = 2 * nf;
  4726. out[11] = 0;
  4727. out[12] = (left + right) * lr;
  4728. out[13] = (top + bottom) * bt;
  4729. out[14] = (far + near) * nf;
  4730. out[15] = 1;
  4731. return out;
  4732. }
  4733. /**
  4734. * Alias for {@link mat4.orthoNO}
  4735. * @function
  4736. */
  4737. var ortho = orthoNO;
  4738. /**
  4739. * Generates a look-at matrix with the given eye position, focal point, and up axis.
  4740. * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
  4741. *
  4742. * @param {mat4} out mat4 frustum matrix will be written into
  4743. * @param {ReadonlyVec3} eye Position of the viewer
  4744. * @param {ReadonlyVec3} center Point the viewer is looking at
  4745. * @param {ReadonlyVec3} up vec3 pointing up
  4746. * @returns {mat4} out
  4747. */
  4748. function lookAt(out, eye, center, up) {
  4749. var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
  4750. var eyex = eye[0];
  4751. var eyey = eye[1];
  4752. var eyez = eye[2];
  4753. var upx = up[0];
  4754. var upy = up[1];
  4755. var upz = up[2];
  4756. var centerx = center[0];
  4757. var centery = center[1];
  4758. var centerz = center[2];
  4759. if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) {
  4760. return identity$2(out);
  4761. }
  4762. z0 = eyex - centerx;
  4763. z1 = eyey - centery;
  4764. z2 = eyez - centerz;
  4765. len = 1 / Math.hypot(z0, z1, z2);
  4766. z0 *= len;
  4767. z1 *= len;
  4768. z2 *= len;
  4769. x0 = upy * z2 - upz * z1;
  4770. x1 = upz * z0 - upx * z2;
  4771. x2 = upx * z1 - upy * z0;
  4772. len = Math.hypot(x0, x1, x2);
  4773. if (!len) {
  4774. x0 = 0;
  4775. x1 = 0;
  4776. x2 = 0;
  4777. } else {
  4778. len = 1 / len;
  4779. x0 *= len;
  4780. x1 *= len;
  4781. x2 *= len;
  4782. }
  4783. y0 = z1 * x2 - z2 * x1;
  4784. y1 = z2 * x0 - z0 * x2;
  4785. y2 = z0 * x1 - z1 * x0;
  4786. len = Math.hypot(y0, y1, y2);
  4787. if (!len) {
  4788. y0 = 0;
  4789. y1 = 0;
  4790. y2 = 0;
  4791. } else {
  4792. len = 1 / len;
  4793. y0 *= len;
  4794. y1 *= len;
  4795. y2 *= len;
  4796. }
  4797. out[0] = x0;
  4798. out[1] = y0;
  4799. out[2] = z0;
  4800. out[3] = 0;
  4801. out[4] = x1;
  4802. out[5] = y1;
  4803. out[6] = z1;
  4804. out[7] = 0;
  4805. out[8] = x2;
  4806. out[9] = y2;
  4807. out[10] = z2;
  4808. out[11] = 0;
  4809. out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
  4810. out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
  4811. out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
  4812. out[15] = 1;
  4813. return out;
  4814. }
  4815. /**
  4816. * 4 Dimensional Vector
  4817. * @module vec4
  4818. */
  4819. /**
  4820. * Creates a new, empty vec4
  4821. *
  4822. * @returns {vec4} a new 4D vector
  4823. */
  4824. function create$1() {
  4825. var out = new ARRAY_TYPE(4);
  4826. if (ARRAY_TYPE != Float32Array) {
  4827. out[0] = 0;
  4828. out[1] = 0;
  4829. out[2] = 0;
  4830. out[3] = 0;
  4831. }
  4832. return out;
  4833. }
  4834. /**
  4835. * Adds two vec4's
  4836. *
  4837. * @param {vec4} out the receiving vector
  4838. * @param {ReadonlyVec4} a the first operand
  4839. * @param {ReadonlyVec4} b the second operand
  4840. * @returns {vec4} out
  4841. */
  4842. function add$1(out, a, b) {
  4843. out[0] = a[0] + b[0];
  4844. out[1] = a[1] + b[1];
  4845. out[2] = a[2] + b[2];
  4846. out[3] = a[3] + b[3];
  4847. return out;
  4848. }
  4849. /**
  4850. * Scales a vec4 by a scalar number
  4851. *
  4852. * @param {vec4} out the receiving vector
  4853. * @param {ReadonlyVec4} a the vector to scale
  4854. * @param {Number} b amount to scale the vector by
  4855. * @returns {vec4} out
  4856. */
  4857. function scale$1(out, a, b) {
  4858. out[0] = a[0] * b;
  4859. out[1] = a[1] * b;
  4860. out[2] = a[2] * b;
  4861. out[3] = a[3] * b;
  4862. return out;
  4863. }
  4864. /**
  4865. * Calculates the length of a vec4
  4866. *
  4867. * @param {ReadonlyVec4} a vector to calculate length of
  4868. * @returns {Number} length of a
  4869. */
  4870. function length$1(a) {
  4871. var x = a[0];
  4872. var y = a[1];
  4873. var z = a[2];
  4874. var w = a[3];
  4875. return Math.hypot(x, y, z, w);
  4876. }
  4877. /**
  4878. * Calculates the squared length of a vec4
  4879. *
  4880. * @param {ReadonlyVec4} a vector to calculate squared length of
  4881. * @returns {Number} squared length of a
  4882. */
  4883. function squaredLength$1(a) {
  4884. var x = a[0];
  4885. var y = a[1];
  4886. var z = a[2];
  4887. var w = a[3];
  4888. return x * x + y * y + z * z + w * w;
  4889. }
  4890. /**
  4891. * Normalize a vec4
  4892. *
  4893. * @param {vec4} out the receiving vector
  4894. * @param {ReadonlyVec4} a vector to normalize
  4895. * @returns {vec4} out
  4896. */
  4897. function normalize$1(out, a) {
  4898. var x = a[0];
  4899. var y = a[1];
  4900. var z = a[2];
  4901. var w = a[3];
  4902. var len = x * x + y * y + z * z + w * w;
  4903. if (len > 0) {
  4904. len = 1 / Math.sqrt(len);
  4905. }
  4906. out[0] = x * len;
  4907. out[1] = y * len;
  4908. out[2] = z * len;
  4909. out[3] = w * len;
  4910. return out;
  4911. }
  4912. /**
  4913. * Calculates the dot product of two vec4's
  4914. *
  4915. * @param {ReadonlyVec4} a the first operand
  4916. * @param {ReadonlyVec4} b the second operand
  4917. * @returns {Number} dot product of a and b
  4918. */
  4919. function dot$1(a, b) {
  4920. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
  4921. }
  4922. /**
  4923. * Performs a linear interpolation between two vec4's
  4924. *
  4925. * @param {vec4} out the receiving vector
  4926. * @param {ReadonlyVec4} a the first operand
  4927. * @param {ReadonlyVec4} b the second operand
  4928. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  4929. * @returns {vec4} out
  4930. */
  4931. function lerp$1(out, a, b, t) {
  4932. var ax = a[0];
  4933. var ay = a[1];
  4934. var az = a[2];
  4935. var aw = a[3];
  4936. out[0] = ax + t * (b[0] - ax);
  4937. out[1] = ay + t * (b[1] - ay);
  4938. out[2] = az + t * (b[2] - az);
  4939. out[3] = aw + t * (b[3] - aw);
  4940. return out;
  4941. }
  4942. /**
  4943. * Transforms the vec4 with a mat4.
  4944. *
  4945. * @param {vec4} out the receiving vector
  4946. * @param {ReadonlyVec4} a the vector to transform
  4947. * @param {ReadonlyMat4} m matrix to transform with
  4948. * @returns {vec4} out
  4949. */
  4950. function transformMat4(out, a, m) {
  4951. var x = a[0],
  4952. y = a[1],
  4953. z = a[2],
  4954. w = a[3];
  4955. out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
  4956. out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
  4957. out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
  4958. out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
  4959. return out;
  4960. }
  4961. /**
  4962. * Transforms the vec4 with a quat
  4963. *
  4964. * @param {vec4} out the receiving vector
  4965. * @param {ReadonlyVec4} a the vector to transform
  4966. * @param {ReadonlyQuat} q quaternion to transform with
  4967. * @returns {vec4} out
  4968. */
  4969. function transformQuat(out, a, q) {
  4970. var x = a[0],
  4971. y = a[1],
  4972. z = a[2];
  4973. var qx = q[0],
  4974. qy = q[1],
  4975. qz = q[2],
  4976. qw = q[3]; // calculate quat * vec
  4977. var ix = qw * x + qy * z - qz * y;
  4978. var iy = qw * y + qz * x - qx * z;
  4979. var iz = qw * z + qx * y - qy * x;
  4980. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  4981. out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  4982. out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  4983. out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  4984. out[3] = a[3];
  4985. return out;
  4986. }
  4987. /**
  4988. * Perform some operation over an array of vec4s.
  4989. *
  4990. * @param {Array} a the array of vectors to iterate over
  4991. * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
  4992. * @param {Number} offset Number of elements to skip at the beginning of the array
  4993. * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
  4994. * @param {Function} fn Function to call for each vector in the array
  4995. * @param {Object} [arg] additional argument to pass to fn
  4996. * @returns {Array} a
  4997. * @function
  4998. */
  4999. (function () {
  5000. var vec = create$1();
  5001. return function (a, stride, offset, count, fn, arg) {
  5002. var i, l;
  5003. if (!stride) {
  5004. stride = 4;
  5005. }
  5006. if (!offset) {
  5007. offset = 0;
  5008. }
  5009. if (count) {
  5010. l = Math.min(count * stride + offset, a.length);
  5011. } else {
  5012. l = a.length;
  5013. }
  5014. for (i = offset; i < l; i += stride) {
  5015. vec[0] = a[i];
  5016. vec[1] = a[i + 1];
  5017. vec[2] = a[i + 2];
  5018. vec[3] = a[i + 3];
  5019. fn(vec, vec, arg);
  5020. a[i] = vec[0];
  5021. a[i + 1] = vec[1];
  5022. a[i + 2] = vec[2];
  5023. a[i + 3] = vec[3];
  5024. }
  5025. return a;
  5026. };
  5027. })();
  5028. var INDICES;
  5029. (function (INDICES) {
  5030. INDICES[INDICES["COL0ROW0"] = 0] = "COL0ROW0";
  5031. INDICES[INDICES["COL0ROW1"] = 1] = "COL0ROW1";
  5032. INDICES[INDICES["COL0ROW2"] = 2] = "COL0ROW2";
  5033. INDICES[INDICES["COL0ROW3"] = 3] = "COL0ROW3";
  5034. INDICES[INDICES["COL1ROW0"] = 4] = "COL1ROW0";
  5035. INDICES[INDICES["COL1ROW1"] = 5] = "COL1ROW1";
  5036. INDICES[INDICES["COL1ROW2"] = 6] = "COL1ROW2";
  5037. INDICES[INDICES["COL1ROW3"] = 7] = "COL1ROW3";
  5038. INDICES[INDICES["COL2ROW0"] = 8] = "COL2ROW0";
  5039. INDICES[INDICES["COL2ROW1"] = 9] = "COL2ROW1";
  5040. INDICES[INDICES["COL2ROW2"] = 10] = "COL2ROW2";
  5041. INDICES[INDICES["COL2ROW3"] = 11] = "COL2ROW3";
  5042. INDICES[INDICES["COL3ROW0"] = 12] = "COL3ROW0";
  5043. INDICES[INDICES["COL3ROW1"] = 13] = "COL3ROW1";
  5044. INDICES[INDICES["COL3ROW2"] = 14] = "COL3ROW2";
  5045. INDICES[INDICES["COL3ROW3"] = 15] = "COL3ROW3";
  5046. })(INDICES || (INDICES = {}));
  5047. const DEFAULT_FOVY = 45 * Math.PI / 180;
  5048. const DEFAULT_ASPECT = 1;
  5049. const DEFAULT_NEAR = 0.1;
  5050. const DEFAULT_FAR = 500;
  5051. const IDENTITY_MATRIX = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
  5052. class Matrix4 extends Matrix {
  5053. static get IDENTITY() {
  5054. return getIdentityMatrix();
  5055. }
  5056. static get ZERO() {
  5057. return getZeroMatrix();
  5058. }
  5059. get ELEMENTS() {
  5060. return 16;
  5061. }
  5062. get RANK() {
  5063. return 4;
  5064. }
  5065. get INDICES() {
  5066. return INDICES;
  5067. }
  5068. constructor(array) {
  5069. super(-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0);
  5070. if (arguments.length === 1 && Array.isArray(array)) {
  5071. this.copy(array);
  5072. } else {
  5073. this.identity();
  5074. }
  5075. }
  5076. copy(array) {
  5077. this[0] = array[0];
  5078. this[1] = array[1];
  5079. this[2] = array[2];
  5080. this[3] = array[3];
  5081. this[4] = array[4];
  5082. this[5] = array[5];
  5083. this[6] = array[6];
  5084. this[7] = array[7];
  5085. this[8] = array[8];
  5086. this[9] = array[9];
  5087. this[10] = array[10];
  5088. this[11] = array[11];
  5089. this[12] = array[12];
  5090. this[13] = array[13];
  5091. this[14] = array[14];
  5092. this[15] = array[15];
  5093. return this.check();
  5094. }
  5095. set(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33) {
  5096. this[0] = m00;
  5097. this[1] = m10;
  5098. this[2] = m20;
  5099. this[3] = m30;
  5100. this[4] = m01;
  5101. this[5] = m11;
  5102. this[6] = m21;
  5103. this[7] = m31;
  5104. this[8] = m02;
  5105. this[9] = m12;
  5106. this[10] = m22;
  5107. this[11] = m32;
  5108. this[12] = m03;
  5109. this[13] = m13;
  5110. this[14] = m23;
  5111. this[15] = m33;
  5112. return this.check();
  5113. }
  5114. setRowMajor(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
  5115. this[0] = m00;
  5116. this[1] = m10;
  5117. this[2] = m20;
  5118. this[3] = m30;
  5119. this[4] = m01;
  5120. this[5] = m11;
  5121. this[6] = m21;
  5122. this[7] = m31;
  5123. this[8] = m02;
  5124. this[9] = m12;
  5125. this[10] = m22;
  5126. this[11] = m32;
  5127. this[12] = m03;
  5128. this[13] = m13;
  5129. this[14] = m23;
  5130. this[15] = m33;
  5131. return this.check();
  5132. }
  5133. toRowMajor(result) {
  5134. result[0] = this[0];
  5135. result[1] = this[4];
  5136. result[2] = this[8];
  5137. result[3] = this[12];
  5138. result[4] = this[1];
  5139. result[5] = this[5];
  5140. result[6] = this[9];
  5141. result[7] = this[13];
  5142. result[8] = this[2];
  5143. result[9] = this[6];
  5144. result[10] = this[10];
  5145. result[11] = this[14];
  5146. result[12] = this[3];
  5147. result[13] = this[7];
  5148. result[14] = this[11];
  5149. result[15] = this[15];
  5150. return result;
  5151. }
  5152. identity() {
  5153. return this.copy(IDENTITY_MATRIX);
  5154. }
  5155. fromObject(object) {
  5156. return this.check();
  5157. }
  5158. fromQuaternion(quaternion) {
  5159. fromQuat(this, quaternion);
  5160. return this.check();
  5161. }
  5162. frustum(view) {
  5163. const {
  5164. left,
  5165. right,
  5166. bottom,
  5167. top,
  5168. near = DEFAULT_NEAR,
  5169. far = DEFAULT_FAR
  5170. } = view;
  5171. if (far === Infinity) {
  5172. computeInfinitePerspectiveOffCenter(this, left, right, bottom, top, near);
  5173. } else {
  5174. frustum(this, left, right, bottom, top, near, far);
  5175. }
  5176. return this.check();
  5177. }
  5178. lookAt(view) {
  5179. const {
  5180. eye,
  5181. center = [0, 0, 0],
  5182. up = [0, 1, 0]
  5183. } = view;
  5184. lookAt(this, eye, center, up);
  5185. return this.check();
  5186. }
  5187. ortho(view) {
  5188. const {
  5189. left,
  5190. right,
  5191. bottom,
  5192. top,
  5193. near = DEFAULT_NEAR,
  5194. far = DEFAULT_FAR
  5195. } = view;
  5196. ortho(this, left, right, bottom, top, near, far);
  5197. return this.check();
  5198. }
  5199. orthographic(view) {
  5200. const {
  5201. fovy = DEFAULT_FOVY,
  5202. aspect = DEFAULT_ASPECT,
  5203. focalDistance = 1,
  5204. near = DEFAULT_NEAR,
  5205. far = DEFAULT_FAR
  5206. } = view;
  5207. checkRadians(fovy);
  5208. const halfY = fovy / 2;
  5209. const top = focalDistance * Math.tan(halfY);
  5210. const right = top * aspect;
  5211. return this.ortho({
  5212. left: -right,
  5213. right,
  5214. bottom: -top,
  5215. top,
  5216. near,
  5217. far
  5218. });
  5219. }
  5220. perspective(view) {
  5221. const {
  5222. fovy = 45 * Math.PI / 180,
  5223. aspect = 1,
  5224. near = 0.1,
  5225. far = 500
  5226. } = view;
  5227. checkRadians(fovy);
  5228. perspective(this, fovy, aspect, near, far);
  5229. return this.check();
  5230. }
  5231. determinant() {
  5232. return determinant(this);
  5233. }
  5234. getScale(result = [-0, -0, -0]) {
  5235. result[0] = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);
  5236. result[1] = Math.sqrt(this[4] * this[4] + this[5] * this[5] + this[6] * this[6]);
  5237. result[2] = Math.sqrt(this[8] * this[8] + this[9] * this[9] + this[10] * this[10]);
  5238. return result;
  5239. }
  5240. getTranslation(result = [-0, -0, -0]) {
  5241. result[0] = this[12];
  5242. result[1] = this[13];
  5243. result[2] = this[14];
  5244. return result;
  5245. }
  5246. getRotation(result, scaleResult) {
  5247. result = result || [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0];
  5248. scaleResult = scaleResult || [-0, -0, -0];
  5249. const scale = this.getScale(scaleResult);
  5250. const inverseScale0 = 1 / scale[0];
  5251. const inverseScale1 = 1 / scale[1];
  5252. const inverseScale2 = 1 / scale[2];
  5253. result[0] = this[0] * inverseScale0;
  5254. result[1] = this[1] * inverseScale1;
  5255. result[2] = this[2] * inverseScale2;
  5256. result[3] = 0;
  5257. result[4] = this[4] * inverseScale0;
  5258. result[5] = this[5] * inverseScale1;
  5259. result[6] = this[6] * inverseScale2;
  5260. result[7] = 0;
  5261. result[8] = this[8] * inverseScale0;
  5262. result[9] = this[9] * inverseScale1;
  5263. result[10] = this[10] * inverseScale2;
  5264. result[11] = 0;
  5265. result[12] = 0;
  5266. result[13] = 0;
  5267. result[14] = 0;
  5268. result[15] = 1;
  5269. return result;
  5270. }
  5271. getRotationMatrix3(result, scaleResult) {
  5272. result = result || [-0, -0, -0, -0, -0, -0, -0, -0, -0];
  5273. scaleResult = scaleResult || [-0, -0, -0];
  5274. const scale = this.getScale(scaleResult);
  5275. const inverseScale0 = 1 / scale[0];
  5276. const inverseScale1 = 1 / scale[1];
  5277. const inverseScale2 = 1 / scale[2];
  5278. result[0] = this[0] * inverseScale0;
  5279. result[1] = this[1] * inverseScale1;
  5280. result[2] = this[2] * inverseScale2;
  5281. result[3] = this[4] * inverseScale0;
  5282. result[4] = this[5] * inverseScale1;
  5283. result[5] = this[6] * inverseScale2;
  5284. result[6] = this[8] * inverseScale0;
  5285. result[7] = this[9] * inverseScale1;
  5286. result[8] = this[10] * inverseScale2;
  5287. return result;
  5288. }
  5289. transpose() {
  5290. transpose(this, this);
  5291. return this.check();
  5292. }
  5293. invert() {
  5294. invert$1(this, this);
  5295. return this.check();
  5296. }
  5297. multiplyLeft(a) {
  5298. multiply$1(this, a, this);
  5299. return this.check();
  5300. }
  5301. multiplyRight(a) {
  5302. multiply$1(this, this, a);
  5303. return this.check();
  5304. }
  5305. rotateX(radians) {
  5306. rotateX$1(this, this, radians);
  5307. return this.check();
  5308. }
  5309. rotateY(radians) {
  5310. rotateY$1(this, this, radians);
  5311. return this.check();
  5312. }
  5313. rotateZ(radians) {
  5314. rotateZ$1(this, this, radians);
  5315. return this.check();
  5316. }
  5317. rotateXYZ(angleXYZ) {
  5318. return this.rotateX(angleXYZ[0]).rotateY(angleXYZ[1]).rotateZ(angleXYZ[2]);
  5319. }
  5320. rotateAxis(radians, axis) {
  5321. rotate(this, this, radians, axis);
  5322. return this.check();
  5323. }
  5324. scale(factor) {
  5325. scale$2(this, this, Array.isArray(factor) ? factor : [factor, factor, factor]);
  5326. return this.check();
  5327. }
  5328. translate(vector) {
  5329. translate(this, this, vector);
  5330. return this.check();
  5331. }
  5332. transform(vector, result) {
  5333. if (vector.length === 4) {
  5334. result = transformMat4(result || [-0, -0, -0, -0], vector, this);
  5335. checkVector(result, 4);
  5336. return result;
  5337. }
  5338. return this.transformAsPoint(vector, result);
  5339. }
  5340. transformAsPoint(vector, result) {
  5341. const {
  5342. length
  5343. } = vector;
  5344. let out;
  5345. switch (length) {
  5346. case 2:
  5347. out = transformMat4$2(result || [-0, -0], vector, this);
  5348. break;
  5349. case 3:
  5350. out = transformMat4$1(result || [-0, -0, -0], vector, this);
  5351. break;
  5352. default:
  5353. throw new Error('Illegal vector');
  5354. }
  5355. checkVector(out, vector.length);
  5356. return out;
  5357. }
  5358. transformAsVector(vector, result) {
  5359. let out;
  5360. switch (vector.length) {
  5361. case 2:
  5362. out = vec2_transformMat4AsVector(result || [-0, -0], vector, this);
  5363. break;
  5364. case 3:
  5365. out = vec3_transformMat4AsVector(result || [-0, -0, -0], vector, this);
  5366. break;
  5367. default:
  5368. throw new Error('Illegal vector');
  5369. }
  5370. checkVector(out, vector.length);
  5371. return out;
  5372. }
  5373. transformPoint(vector, result) {
  5374. return this.transformAsPoint(vector, result);
  5375. }
  5376. transformVector(vector, result) {
  5377. return this.transformAsPoint(vector, result);
  5378. }
  5379. transformDirection(vector, result) {
  5380. return this.transformAsVector(vector, result);
  5381. }
  5382. makeRotationX(radians) {
  5383. return this.identity().rotateX(radians);
  5384. }
  5385. makeTranslation(x, y, z) {
  5386. return this.identity().translate([x, y, z]);
  5387. }
  5388. }
  5389. let ZERO;
  5390. let IDENTITY;
  5391. function getZeroMatrix() {
  5392. if (!ZERO) {
  5393. ZERO = new Matrix4([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  5394. Object.freeze(ZERO);
  5395. }
  5396. return ZERO;
  5397. }
  5398. function getIdentityMatrix() {
  5399. if (!IDENTITY) {
  5400. IDENTITY = new Matrix4();
  5401. Object.freeze(IDENTITY);
  5402. }
  5403. return IDENTITY;
  5404. }
  5405. function checkRadians(possiblyDegrees) {
  5406. if (possiblyDegrees > Math.PI * 2) {
  5407. throw Error('expected radians');
  5408. }
  5409. }
  5410. function computeInfinitePerspectiveOffCenter(result, left, right, bottom, top, near) {
  5411. const column0Row0 = 2 * near / (right - left);
  5412. const column1Row1 = 2 * near / (top - bottom);
  5413. const column2Row0 = (right + left) / (right - left);
  5414. const column2Row1 = (top + bottom) / (top - bottom);
  5415. const column2Row2 = -1;
  5416. const column2Row3 = -1;
  5417. const column3Row2 = -2 * near;
  5418. result[0] = column0Row0;
  5419. result[1] = 0;
  5420. result[2] = 0;
  5421. result[3] = 0;
  5422. result[4] = 0;
  5423. result[5] = column1Row1;
  5424. result[6] = 0;
  5425. result[7] = 0;
  5426. result[8] = column2Row0;
  5427. result[9] = column2Row1;
  5428. result[10] = column2Row2;
  5429. result[11] = column2Row3;
  5430. result[12] = 0;
  5431. result[13] = 0;
  5432. result[14] = column3Row2;
  5433. result[15] = 0;
  5434. return result;
  5435. }
  5436. /**
  5437. * Quaternion
  5438. * @module quat
  5439. */
  5440. /**
  5441. * Creates a new identity quat
  5442. *
  5443. * @returns {quat} a new quaternion
  5444. */
  5445. function create() {
  5446. var out = new ARRAY_TYPE(4);
  5447. if (ARRAY_TYPE != Float32Array) {
  5448. out[0] = 0;
  5449. out[1] = 0;
  5450. out[2] = 0;
  5451. }
  5452. out[3] = 1;
  5453. return out;
  5454. }
  5455. /**
  5456. * Set a quat to the identity quaternion
  5457. *
  5458. * @param {quat} out the receiving quaternion
  5459. * @returns {quat} out
  5460. */
  5461. function identity$1(out) {
  5462. out[0] = 0;
  5463. out[1] = 0;
  5464. out[2] = 0;
  5465. out[3] = 1;
  5466. return out;
  5467. }
  5468. /**
  5469. * Sets a quat from the given angle and rotation axis,
  5470. * then returns it.
  5471. *
  5472. * @param {quat} out the receiving quaternion
  5473. * @param {ReadonlyVec3} axis the axis around which to rotate
  5474. * @param {Number} rad the angle in radians
  5475. * @returns {quat} out
  5476. **/
  5477. function setAxisAngle(out, axis, rad) {
  5478. rad = rad * 0.5;
  5479. var s = Math.sin(rad);
  5480. out[0] = s * axis[0];
  5481. out[1] = s * axis[1];
  5482. out[2] = s * axis[2];
  5483. out[3] = Math.cos(rad);
  5484. return out;
  5485. }
  5486. /**
  5487. * Multiplies two quat's
  5488. *
  5489. * @param {quat} out the receiving quaternion
  5490. * @param {ReadonlyQuat} a the first operand
  5491. * @param {ReadonlyQuat} b the second operand
  5492. * @returns {quat} out
  5493. */
  5494. function multiply(out, a, b) {
  5495. var ax = a[0],
  5496. ay = a[1],
  5497. az = a[2],
  5498. aw = a[3];
  5499. var bx = b[0],
  5500. by = b[1],
  5501. bz = b[2],
  5502. bw = b[3];
  5503. out[0] = ax * bw + aw * bx + ay * bz - az * by;
  5504. out[1] = ay * bw + aw * by + az * bx - ax * bz;
  5505. out[2] = az * bw + aw * bz + ax * by - ay * bx;
  5506. out[3] = aw * bw - ax * bx - ay * by - az * bz;
  5507. return out;
  5508. }
  5509. /**
  5510. * Rotates a quaternion by the given angle about the X axis
  5511. *
  5512. * @param {quat} out quat receiving operation result
  5513. * @param {ReadonlyQuat} a quat to rotate
  5514. * @param {number} rad angle (in radians) to rotate
  5515. * @returns {quat} out
  5516. */
  5517. function rotateX(out, a, rad) {
  5518. rad *= 0.5;
  5519. var ax = a[0],
  5520. ay = a[1],
  5521. az = a[2],
  5522. aw = a[3];
  5523. var bx = Math.sin(rad),
  5524. bw = Math.cos(rad);
  5525. out[0] = ax * bw + aw * bx;
  5526. out[1] = ay * bw + az * bx;
  5527. out[2] = az * bw - ay * bx;
  5528. out[3] = aw * bw - ax * bx;
  5529. return out;
  5530. }
  5531. /**
  5532. * Rotates a quaternion by the given angle about the Y axis
  5533. *
  5534. * @param {quat} out quat receiving operation result
  5535. * @param {ReadonlyQuat} a quat to rotate
  5536. * @param {number} rad angle (in radians) to rotate
  5537. * @returns {quat} out
  5538. */
  5539. function rotateY(out, a, rad) {
  5540. rad *= 0.5;
  5541. var ax = a[0],
  5542. ay = a[1],
  5543. az = a[2],
  5544. aw = a[3];
  5545. var by = Math.sin(rad),
  5546. bw = Math.cos(rad);
  5547. out[0] = ax * bw - az * by;
  5548. out[1] = ay * bw + aw * by;
  5549. out[2] = az * bw + ax * by;
  5550. out[3] = aw * bw - ay * by;
  5551. return out;
  5552. }
  5553. /**
  5554. * Rotates a quaternion by the given angle about the Z axis
  5555. *
  5556. * @param {quat} out quat receiving operation result
  5557. * @param {ReadonlyQuat} a quat to rotate
  5558. * @param {number} rad angle (in radians) to rotate
  5559. * @returns {quat} out
  5560. */
  5561. function rotateZ(out, a, rad) {
  5562. rad *= 0.5;
  5563. var ax = a[0],
  5564. ay = a[1],
  5565. az = a[2],
  5566. aw = a[3];
  5567. var bz = Math.sin(rad),
  5568. bw = Math.cos(rad);
  5569. out[0] = ax * bw + ay * bz;
  5570. out[1] = ay * bw - ax * bz;
  5571. out[2] = az * bw + aw * bz;
  5572. out[3] = aw * bw - az * bz;
  5573. return out;
  5574. }
  5575. /**
  5576. * Calculates the W component of a quat from the X, Y, and Z components.
  5577. * Assumes that quaternion is 1 unit in length.
  5578. * Any existing W component will be ignored.
  5579. *
  5580. * @param {quat} out the receiving quaternion
  5581. * @param {ReadonlyQuat} a quat to calculate W component of
  5582. * @returns {quat} out
  5583. */
  5584. function calculateW(out, a) {
  5585. var x = a[0],
  5586. y = a[1],
  5587. z = a[2];
  5588. out[0] = x;
  5589. out[1] = y;
  5590. out[2] = z;
  5591. out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
  5592. return out;
  5593. }
  5594. /**
  5595. * Performs a spherical linear interpolation between two quat
  5596. *
  5597. * @param {quat} out the receiving quaternion
  5598. * @param {ReadonlyQuat} a the first operand
  5599. * @param {ReadonlyQuat} b the second operand
  5600. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5601. * @returns {quat} out
  5602. */
  5603. function slerp(out, a, b, t) {
  5604. // benchmarks:
  5605. // http://jsperf.com/quaternion-slerp-implementations
  5606. var ax = a[0],
  5607. ay = a[1],
  5608. az = a[2],
  5609. aw = a[3];
  5610. var bx = b[0],
  5611. by = b[1],
  5612. bz = b[2],
  5613. bw = b[3];
  5614. var omega, cosom, sinom, scale0, scale1; // calc cosine
  5615. cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)
  5616. if (cosom < 0.0) {
  5617. cosom = -cosom;
  5618. bx = -bx;
  5619. by = -by;
  5620. bz = -bz;
  5621. bw = -bw;
  5622. } // calculate coefficients
  5623. if (1.0 - cosom > EPSILON) {
  5624. // standard case (slerp)
  5625. omega = Math.acos(cosom);
  5626. sinom = Math.sin(omega);
  5627. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  5628. scale1 = Math.sin(t * omega) / sinom;
  5629. } else {
  5630. // "from" and "to" quaternions are very close
  5631. // ... so we can do a linear interpolation
  5632. scale0 = 1.0 - t;
  5633. scale1 = t;
  5634. } // calculate final values
  5635. out[0] = scale0 * ax + scale1 * bx;
  5636. out[1] = scale0 * ay + scale1 * by;
  5637. out[2] = scale0 * az + scale1 * bz;
  5638. out[3] = scale0 * aw + scale1 * bw;
  5639. return out;
  5640. }
  5641. /**
  5642. * Calculates the inverse of a quat
  5643. *
  5644. * @param {quat} out the receiving quaternion
  5645. * @param {ReadonlyQuat} a quat to calculate inverse of
  5646. * @returns {quat} out
  5647. */
  5648. function invert(out, a) {
  5649. var a0 = a[0],
  5650. a1 = a[1],
  5651. a2 = a[2],
  5652. a3 = a[3];
  5653. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  5654. var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
  5655. out[0] = -a0 * invDot;
  5656. out[1] = -a1 * invDot;
  5657. out[2] = -a2 * invDot;
  5658. out[3] = a3 * invDot;
  5659. return out;
  5660. }
  5661. /**
  5662. * Calculates the conjugate of a quat
  5663. * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
  5664. *
  5665. * @param {quat} out the receiving quaternion
  5666. * @param {ReadonlyQuat} a quat to calculate conjugate of
  5667. * @returns {quat} out
  5668. */
  5669. function conjugate(out, a) {
  5670. out[0] = -a[0];
  5671. out[1] = -a[1];
  5672. out[2] = -a[2];
  5673. out[3] = a[3];
  5674. return out;
  5675. }
  5676. /**
  5677. * Creates a quaternion from the given 3x3 rotation matrix.
  5678. *
  5679. * NOTE: The resultant quaternion is not normalized, so you should be sure
  5680. * to renormalize the quaternion yourself where necessary.
  5681. *
  5682. * @param {quat} out the receiving quaternion
  5683. * @param {ReadonlyMat3} m rotation matrix
  5684. * @returns {quat} out
  5685. * @function
  5686. */
  5687. function fromMat3(out, m) {
  5688. // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  5689. // article "Quaternion Calculus and Fast Animation".
  5690. var fTrace = m[0] + m[4] + m[8];
  5691. var fRoot;
  5692. if (fTrace > 0.0) {
  5693. // |w| > 1/2, may as well choose w > 1/2
  5694. fRoot = Math.sqrt(fTrace + 1.0); // 2w
  5695. out[3] = 0.5 * fRoot;
  5696. fRoot = 0.5 / fRoot; // 1/(4w)
  5697. out[0] = (m[5] - m[7]) * fRoot;
  5698. out[1] = (m[6] - m[2]) * fRoot;
  5699. out[2] = (m[1] - m[3]) * fRoot;
  5700. } else {
  5701. // |w| <= 1/2
  5702. var i = 0;
  5703. if (m[4] > m[0]) i = 1;
  5704. if (m[8] > m[i * 3 + i]) i = 2;
  5705. var j = (i + 1) % 3;
  5706. var k = (i + 2) % 3;
  5707. fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);
  5708. out[i] = 0.5 * fRoot;
  5709. fRoot = 0.5 / fRoot;
  5710. out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
  5711. out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
  5712. out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
  5713. }
  5714. return out;
  5715. }
  5716. /**
  5717. * Adds two quat's
  5718. *
  5719. * @param {quat} out the receiving quaternion
  5720. * @param {ReadonlyQuat} a the first operand
  5721. * @param {ReadonlyQuat} b the second operand
  5722. * @returns {quat} out
  5723. * @function
  5724. */
  5725. var add = add$1;
  5726. /**
  5727. * Scales a quat by a scalar number
  5728. *
  5729. * @param {quat} out the receiving vector
  5730. * @param {ReadonlyQuat} a the vector to scale
  5731. * @param {Number} b amount to scale the vector by
  5732. * @returns {quat} out
  5733. * @function
  5734. */
  5735. var scale = scale$1;
  5736. /**
  5737. * Calculates the dot product of two quat's
  5738. *
  5739. * @param {ReadonlyQuat} a the first operand
  5740. * @param {ReadonlyQuat} b the second operand
  5741. * @returns {Number} dot product of a and b
  5742. * @function
  5743. */
  5744. var dot = dot$1;
  5745. /**
  5746. * Performs a linear interpolation between two quat's
  5747. *
  5748. * @param {quat} out the receiving quaternion
  5749. * @param {ReadonlyQuat} a the first operand
  5750. * @param {ReadonlyQuat} b the second operand
  5751. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5752. * @returns {quat} out
  5753. * @function
  5754. */
  5755. var lerp = lerp$1;
  5756. /**
  5757. * Calculates the length of a quat
  5758. *
  5759. * @param {ReadonlyQuat} a vector to calculate length of
  5760. * @returns {Number} length of a
  5761. */
  5762. var length = length$1;
  5763. /**
  5764. * Calculates the squared length of a quat
  5765. *
  5766. * @param {ReadonlyQuat} a vector to calculate squared length of
  5767. * @returns {Number} squared length of a
  5768. * @function
  5769. */
  5770. var squaredLength = squaredLength$1;
  5771. /**
  5772. * Normalize a quat
  5773. *
  5774. * @param {quat} out the receiving quaternion
  5775. * @param {ReadonlyQuat} a quaternion to normalize
  5776. * @returns {quat} out
  5777. * @function
  5778. */
  5779. var normalize = normalize$1;
  5780. /**
  5781. * Sets a quaternion to represent the shortest rotation from one
  5782. * vector to another.
  5783. *
  5784. * Both vectors are assumed to be unit length.
  5785. *
  5786. * @param {quat} out the receiving quaternion.
  5787. * @param {ReadonlyVec3} a the initial vector
  5788. * @param {ReadonlyVec3} b the destination vector
  5789. * @returns {quat} out
  5790. */
  5791. var rotationTo = function () {
  5792. var tmpvec3 = create$3();
  5793. var xUnitVec3 = fromValues(1, 0, 0);
  5794. var yUnitVec3 = fromValues(0, 1, 0);
  5795. return function (out, a, b) {
  5796. var dot = dot$2(a, b);
  5797. if (dot < -0.999999) {
  5798. cross(tmpvec3, xUnitVec3, a);
  5799. if (len(tmpvec3) < 0.000001) cross(tmpvec3, yUnitVec3, a);
  5800. normalize$2(tmpvec3, tmpvec3);
  5801. setAxisAngle(out, tmpvec3, Math.PI);
  5802. return out;
  5803. } else if (dot > 0.999999) {
  5804. out[0] = 0;
  5805. out[1] = 0;
  5806. out[2] = 0;
  5807. out[3] = 1;
  5808. return out;
  5809. } else {
  5810. cross(tmpvec3, a, b);
  5811. out[0] = tmpvec3[0];
  5812. out[1] = tmpvec3[1];
  5813. out[2] = tmpvec3[2];
  5814. out[3] = 1 + dot;
  5815. return normalize(out, out);
  5816. }
  5817. };
  5818. }();
  5819. /**
  5820. * Performs a spherical linear interpolation with two control points
  5821. *
  5822. * @param {quat} out the receiving quaternion
  5823. * @param {ReadonlyQuat} a the first operand
  5824. * @param {ReadonlyQuat} b the second operand
  5825. * @param {ReadonlyQuat} c the third operand
  5826. * @param {ReadonlyQuat} d the fourth operand
  5827. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5828. * @returns {quat} out
  5829. */
  5830. (function () {
  5831. var temp1 = create();
  5832. var temp2 = create();
  5833. return function (out, a, b, c, d, t) {
  5834. slerp(temp1, a, d, t);
  5835. slerp(temp2, b, c, t);
  5836. slerp(out, temp1, temp2, 2 * t * (1 - t));
  5837. return out;
  5838. };
  5839. })();
  5840. /**
  5841. * Sets the specified quaternion with values corresponding to the given
  5842. * axes. Each axis is a vec3 and is expected to be unit length and
  5843. * perpendicular to all other specified axes.
  5844. *
  5845. * @param {ReadonlyVec3} view the vector representing the viewing direction
  5846. * @param {ReadonlyVec3} right the vector representing the local "right" direction
  5847. * @param {ReadonlyVec3} up the vector representing the local "up" direction
  5848. * @returns {quat} out
  5849. */
  5850. (function () {
  5851. var matr = create$2();
  5852. return function (out, view, right, up) {
  5853. matr[0] = right[0];
  5854. matr[3] = right[1];
  5855. matr[6] = right[2];
  5856. matr[1] = up[0];
  5857. matr[4] = up[1];
  5858. matr[7] = up[2];
  5859. matr[2] = -view[0];
  5860. matr[5] = -view[1];
  5861. matr[8] = -view[2];
  5862. return normalize(out, fromMat3(out, matr));
  5863. };
  5864. })();
  5865. const IDENTITY_QUATERNION = [0, 0, 0, 1];
  5866. class Quaternion extends MathArray {
  5867. constructor(x = 0, y = 0, z = 0, w = 1) {
  5868. super(-0, -0, -0, -0);
  5869. if (Array.isArray(x) && arguments.length === 1) {
  5870. this.copy(x);
  5871. } else {
  5872. this.set(x, y, z, w);
  5873. }
  5874. }
  5875. copy(array) {
  5876. this[0] = array[0];
  5877. this[1] = array[1];
  5878. this[2] = array[2];
  5879. this[3] = array[3];
  5880. return this.check();
  5881. }
  5882. set(x, y, z, w) {
  5883. this[0] = x;
  5884. this[1] = y;
  5885. this[2] = z;
  5886. this[3] = w;
  5887. return this.check();
  5888. }
  5889. fromObject(object) {
  5890. this[0] = object.x;
  5891. this[1] = object.y;
  5892. this[2] = object.z;
  5893. this[3] = object.w;
  5894. return this.check();
  5895. }
  5896. fromMatrix3(m) {
  5897. fromMat3(this, m);
  5898. return this.check();
  5899. }
  5900. fromAxisRotation(axis, rad) {
  5901. setAxisAngle(this, axis, rad);
  5902. return this.check();
  5903. }
  5904. identity() {
  5905. identity$1(this);
  5906. return this.check();
  5907. }
  5908. setAxisAngle(axis, rad) {
  5909. return this.fromAxisRotation(axis, rad);
  5910. }
  5911. get ELEMENTS() {
  5912. return 4;
  5913. }
  5914. get x() {
  5915. return this[0];
  5916. }
  5917. set x(value) {
  5918. this[0] = checkNumber(value);
  5919. }
  5920. get y() {
  5921. return this[1];
  5922. }
  5923. set y(value) {
  5924. this[1] = checkNumber(value);
  5925. }
  5926. get z() {
  5927. return this[2];
  5928. }
  5929. set z(value) {
  5930. this[2] = checkNumber(value);
  5931. }
  5932. get w() {
  5933. return this[3];
  5934. }
  5935. set w(value) {
  5936. this[3] = checkNumber(value);
  5937. }
  5938. len() {
  5939. return length(this);
  5940. }
  5941. lengthSquared() {
  5942. return squaredLength(this);
  5943. }
  5944. dot(a) {
  5945. return dot(this, a);
  5946. }
  5947. rotationTo(vectorA, vectorB) {
  5948. rotationTo(this, vectorA, vectorB);
  5949. return this.check();
  5950. }
  5951. add(a) {
  5952. add(this, this, a);
  5953. return this.check();
  5954. }
  5955. calculateW() {
  5956. calculateW(this, this);
  5957. return this.check();
  5958. }
  5959. conjugate() {
  5960. conjugate(this, this);
  5961. return this.check();
  5962. }
  5963. invert() {
  5964. invert(this, this);
  5965. return this.check();
  5966. }
  5967. lerp(a, b, t) {
  5968. if (t === undefined) {
  5969. return this.lerp(this, a, b);
  5970. }
  5971. lerp(this, a, b, t);
  5972. return this.check();
  5973. }
  5974. multiplyRight(a) {
  5975. multiply(this, this, a);
  5976. return this.check();
  5977. }
  5978. multiplyLeft(a) {
  5979. multiply(this, a, this);
  5980. return this.check();
  5981. }
  5982. normalize() {
  5983. const length = this.len();
  5984. const l = length > 0 ? 1 / length : 0;
  5985. this[0] = this[0] * l;
  5986. this[1] = this[1] * l;
  5987. this[2] = this[2] * l;
  5988. this[3] = this[3] * l;
  5989. if (length === 0) {
  5990. this[3] = 1;
  5991. }
  5992. return this.check();
  5993. }
  5994. rotateX(rad) {
  5995. rotateX(this, this, rad);
  5996. return this.check();
  5997. }
  5998. rotateY(rad) {
  5999. rotateY(this, this, rad);
  6000. return this.check();
  6001. }
  6002. rotateZ(rad) {
  6003. rotateZ(this, this, rad);
  6004. return this.check();
  6005. }
  6006. scale(b) {
  6007. scale(this, this, b);
  6008. return this.check();
  6009. }
  6010. slerp(arg0, arg1, arg2) {
  6011. let start;
  6012. let target;
  6013. let ratio;
  6014. switch (arguments.length) {
  6015. case 1:
  6016. ({
  6017. start = IDENTITY_QUATERNION,
  6018. target,
  6019. ratio
  6020. } = arg0);
  6021. break;
  6022. case 2:
  6023. start = this;
  6024. target = arg0;
  6025. ratio = arg1;
  6026. break;
  6027. default:
  6028. start = arg0;
  6029. target = arg1;
  6030. ratio = arg2;
  6031. }
  6032. slerp(this, start, target, ratio);
  6033. return this.check();
  6034. }
  6035. transformVector4(vector, result = new Vector4()) {
  6036. transformQuat(result, vector, this);
  6037. return checkVector(result, 4);
  6038. }
  6039. lengthSq() {
  6040. return this.lengthSquared();
  6041. }
  6042. setFromAxisAngle(axis, rad) {
  6043. return this.setAxisAngle(axis, rad);
  6044. }
  6045. premultiply(a) {
  6046. return this.multiplyLeft(a);
  6047. }
  6048. multiply(a) {
  6049. return this.multiplyRight(a);
  6050. }
  6051. }
  6052. var _MathUtils = {
  6053. EPSILON1: 1e-1,
  6054. EPSILON2: 1e-2,
  6055. EPSILON3: 1e-3,
  6056. EPSILON4: 1e-4,
  6057. EPSILON5: 1e-5,
  6058. EPSILON6: 1e-6,
  6059. EPSILON7: 1e-7,
  6060. EPSILON8: 1e-8,
  6061. EPSILON9: 1e-9,
  6062. EPSILON10: 1e-10,
  6063. EPSILON11: 1e-11,
  6064. EPSILON12: 1e-12,
  6065. EPSILON13: 1e-13,
  6066. EPSILON14: 1e-14,
  6067. EPSILON15: 1e-15,
  6068. EPSILON16: 1e-16,
  6069. EPSILON17: 1e-17,
  6070. EPSILON18: 1e-18,
  6071. EPSILON19: 1e-19,
  6072. EPSILON20: 1e-20,
  6073. PI_OVER_TWO: Math.PI / 2,
  6074. PI_OVER_FOUR: Math.PI / 4,
  6075. PI_OVER_SIX: Math.PI / 6,
  6076. TWO_PI: Math.PI * 2
  6077. };
  6078. const WGS84_RADIUS_X$1 = 6378137.0;
  6079. const WGS84_RADIUS_Y$1 = 6378137.0;
  6080. const WGS84_RADIUS_Z$1 = 6356752.3142451793;
  6081. function identity(x) {
  6082. return x;
  6083. }
  6084. new Vector3();
  6085. function fromCartographic(cartographic, result = [], map = identity) {
  6086. if ('longitude' in cartographic) {
  6087. result[0] = map(cartographic.longitude);
  6088. result[1] = map(cartographic.latitude);
  6089. result[2] = cartographic.height;
  6090. } else if ('x' in cartographic) {
  6091. result[0] = map(cartographic.x);
  6092. result[1] = map(cartographic.y);
  6093. result[2] = cartographic.z;
  6094. } else {
  6095. result[0] = map(cartographic[0]);
  6096. result[1] = map(cartographic[1]);
  6097. result[2] = cartographic[2];
  6098. }
  6099. return result;
  6100. }
  6101. function fromCartographicToRadians(cartographic, vector = []) {
  6102. return fromCartographic(cartographic, vector, config._cartographicRadians ? identity : toRadians);
  6103. }
  6104. function toCartographic(vector, cartographic, map = identity) {
  6105. if ('longitude' in cartographic) {
  6106. cartographic.longitude = map(vector[0]);
  6107. cartographic.latitude = map(vector[1]);
  6108. cartographic.height = vector[2];
  6109. } else if ('x' in cartographic) {
  6110. cartographic.x = map(vector[0]);
  6111. cartographic.y = map(vector[1]);
  6112. cartographic.z = vector[2];
  6113. } else {
  6114. cartographic[0] = map(vector[0]);
  6115. cartographic[1] = map(vector[1]);
  6116. cartographic[2] = vector[2];
  6117. }
  6118. return cartographic;
  6119. }
  6120. function toCartographicFromRadians(vector, cartographic) {
  6121. return toCartographic(vector, cartographic, config._cartographicRadians ? identity : toDegrees);
  6122. }
  6123. const scratchVector$5 = new Vector3();
  6124. const scaleToGeodeticSurfaceIntersection = new Vector3();
  6125. const scaleToGeodeticSurfaceGradient = new Vector3();
  6126. function scaleToGeodeticSurface(cartesian, ellipsoid, result = []) {
  6127. const {
  6128. oneOverRadii,
  6129. oneOverRadiiSquared,
  6130. centerToleranceSquared
  6131. } = ellipsoid;
  6132. scratchVector$5.from(cartesian);
  6133. const positionX = scratchVector$5.x;
  6134. const positionY = scratchVector$5.y;
  6135. const positionZ = scratchVector$5.z;
  6136. const oneOverRadiiX = oneOverRadii.x;
  6137. const oneOverRadiiY = oneOverRadii.y;
  6138. const oneOverRadiiZ = oneOverRadii.z;
  6139. const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
  6140. const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
  6141. const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
  6142. const squaredNorm = x2 + y2 + z2;
  6143. const ratio = Math.sqrt(1.0 / squaredNorm);
  6144. if (!Number.isFinite(ratio)) {
  6145. return undefined;
  6146. }
  6147. const intersection = scaleToGeodeticSurfaceIntersection;
  6148. intersection.copy(cartesian).scale(ratio);
  6149. if (squaredNorm < centerToleranceSquared) {
  6150. return intersection.to(result);
  6151. }
  6152. const oneOverRadiiSquaredX = oneOverRadiiSquared.x;
  6153. const oneOverRadiiSquaredY = oneOverRadiiSquared.y;
  6154. const oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
  6155. const gradient = scaleToGeodeticSurfaceGradient;
  6156. gradient.set(intersection.x * oneOverRadiiSquaredX * 2.0, intersection.y * oneOverRadiiSquaredY * 2.0, intersection.z * oneOverRadiiSquaredZ * 2.0);
  6157. let lambda = (1.0 - ratio) * scratchVector$5.len() / (0.5 * gradient.len());
  6158. let correction = 0.0;
  6159. let xMultiplier;
  6160. let yMultiplier;
  6161. let zMultiplier;
  6162. let func;
  6163. do {
  6164. lambda -= correction;
  6165. xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
  6166. yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
  6167. zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
  6168. const xMultiplier2 = xMultiplier * xMultiplier;
  6169. const yMultiplier2 = yMultiplier * yMultiplier;
  6170. const zMultiplier2 = zMultiplier * zMultiplier;
  6171. const xMultiplier3 = xMultiplier2 * xMultiplier;
  6172. const yMultiplier3 = yMultiplier2 * yMultiplier;
  6173. const zMultiplier3 = zMultiplier2 * zMultiplier;
  6174. func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
  6175. const denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
  6176. const derivative = -2.0 * denominator;
  6177. correction = func / derivative;
  6178. } while (Math.abs(func) > _MathUtils.EPSILON12);
  6179. return scratchVector$5.scale([xMultiplier, yMultiplier, zMultiplier]).to(result);
  6180. }
  6181. const EPSILON14 = 1e-14;
  6182. const scratchOrigin = new Vector3();
  6183. const VECTOR_PRODUCT_LOCAL_FRAME = {
  6184. up: {
  6185. south: 'east',
  6186. north: 'west',
  6187. west: 'south',
  6188. east: 'north'
  6189. },
  6190. down: {
  6191. south: 'west',
  6192. north: 'east',
  6193. west: 'north',
  6194. east: 'south'
  6195. },
  6196. south: {
  6197. up: 'west',
  6198. down: 'east',
  6199. west: 'down',
  6200. east: 'up'
  6201. },
  6202. north: {
  6203. up: 'east',
  6204. down: 'west',
  6205. west: 'up',
  6206. east: 'down'
  6207. },
  6208. west: {
  6209. up: 'north',
  6210. down: 'south',
  6211. north: 'down',
  6212. south: 'up'
  6213. },
  6214. east: {
  6215. up: 'south',
  6216. down: 'north',
  6217. north: 'up',
  6218. south: 'down'
  6219. }
  6220. };
  6221. const degeneratePositionLocalFrame = {
  6222. north: [-1, 0, 0],
  6223. east: [0, 1, 0],
  6224. up: [0, 0, 1],
  6225. south: [1, 0, 0],
  6226. west: [0, -1, 0],
  6227. down: [0, 0, -1]
  6228. };
  6229. const scratchAxisVectors = {
  6230. east: new Vector3(),
  6231. north: new Vector3(),
  6232. up: new Vector3(),
  6233. west: new Vector3(),
  6234. south: new Vector3(),
  6235. down: new Vector3()
  6236. };
  6237. const scratchVector1 = new Vector3();
  6238. const scratchVector2$1 = new Vector3();
  6239. const scratchVector3$1 = new Vector3();
  6240. function localFrameToFixedFrame(ellipsoid, firstAxis, secondAxis, thirdAxis, cartesianOrigin, result) {
  6241. const thirdAxisInferred = VECTOR_PRODUCT_LOCAL_FRAME[firstAxis] && VECTOR_PRODUCT_LOCAL_FRAME[firstAxis][secondAxis];
  6242. assert$4(thirdAxisInferred && (!thirdAxis || thirdAxis === thirdAxisInferred));
  6243. let firstAxisVector;
  6244. let secondAxisVector;
  6245. let thirdAxisVector;
  6246. const origin = scratchOrigin.copy(cartesianOrigin);
  6247. const atPole = equals(origin.x, 0.0, EPSILON14) && equals(origin.y, 0.0, EPSILON14);
  6248. if (atPole) {
  6249. const sign = Math.sign(origin.z);
  6250. firstAxisVector = scratchVector1.fromArray(degeneratePositionLocalFrame[firstAxis]);
  6251. if (firstAxis !== 'east' && firstAxis !== 'west') {
  6252. firstAxisVector.scale(sign);
  6253. }
  6254. secondAxisVector = scratchVector2$1.fromArray(degeneratePositionLocalFrame[secondAxis]);
  6255. if (secondAxis !== 'east' && secondAxis !== 'west') {
  6256. secondAxisVector.scale(sign);
  6257. }
  6258. thirdAxisVector = scratchVector3$1.fromArray(degeneratePositionLocalFrame[thirdAxis]);
  6259. if (thirdAxis !== 'east' && thirdAxis !== 'west') {
  6260. thirdAxisVector.scale(sign);
  6261. }
  6262. } else {
  6263. const {
  6264. up,
  6265. east,
  6266. north
  6267. } = scratchAxisVectors;
  6268. east.set(-origin.y, origin.x, 0.0).normalize();
  6269. ellipsoid.geodeticSurfaceNormal(origin, up);
  6270. north.copy(up).cross(east);
  6271. const {
  6272. down,
  6273. west,
  6274. south
  6275. } = scratchAxisVectors;
  6276. down.copy(up).scale(-1);
  6277. west.copy(east).scale(-1);
  6278. south.copy(north).scale(-1);
  6279. firstAxisVector = scratchAxisVectors[firstAxis];
  6280. secondAxisVector = scratchAxisVectors[secondAxis];
  6281. thirdAxisVector = scratchAxisVectors[thirdAxis];
  6282. }
  6283. result[0] = firstAxisVector.x;
  6284. result[1] = firstAxisVector.y;
  6285. result[2] = firstAxisVector.z;
  6286. result[3] = 0.0;
  6287. result[4] = secondAxisVector.x;
  6288. result[5] = secondAxisVector.y;
  6289. result[6] = secondAxisVector.z;
  6290. result[7] = 0.0;
  6291. result[8] = thirdAxisVector.x;
  6292. result[9] = thirdAxisVector.y;
  6293. result[10] = thirdAxisVector.z;
  6294. result[11] = 0.0;
  6295. result[12] = origin.x;
  6296. result[13] = origin.y;
  6297. result[14] = origin.z;
  6298. result[15] = 1.0;
  6299. return result;
  6300. }
  6301. const scratchVector$4 = new Vector3();
  6302. const scratchNormal$2 = new Vector3();
  6303. const scratchK = new Vector3();
  6304. const scratchPosition$2 = new Vector3();
  6305. const scratchHeight = new Vector3();
  6306. const scratchCartesian = new Vector3();
  6307. class Ellipsoid {
  6308. constructor(x = 0.0, y = 0.0, z = 0.0) {
  6309. _defineProperty(this, "radii", void 0);
  6310. _defineProperty(this, "radiiSquared", void 0);
  6311. _defineProperty(this, "radiiToTheFourth", void 0);
  6312. _defineProperty(this, "oneOverRadii", void 0);
  6313. _defineProperty(this, "oneOverRadiiSquared", void 0);
  6314. _defineProperty(this, "minimumRadius", void 0);
  6315. _defineProperty(this, "maximumRadius", void 0);
  6316. _defineProperty(this, "centerToleranceSquared", _MathUtils.EPSILON1);
  6317. _defineProperty(this, "squaredXOverSquaredZ", void 0);
  6318. assert$4(x >= 0.0);
  6319. assert$4(y >= 0.0);
  6320. assert$4(z >= 0.0);
  6321. this.radii = new Vector3(x, y, z);
  6322. this.radiiSquared = new Vector3(x * x, y * y, z * z);
  6323. this.radiiToTheFourth = new Vector3(x * x * x * x, y * y * y * y, z * z * z * z);
  6324. this.oneOverRadii = new Vector3(x === 0.0 ? 0.0 : 1.0 / x, y === 0.0 ? 0.0 : 1.0 / y, z === 0.0 ? 0.0 : 1.0 / z);
  6325. this.oneOverRadiiSquared = new Vector3(x === 0.0 ? 0.0 : 1.0 / (x * x), y === 0.0 ? 0.0 : 1.0 / (y * y), z === 0.0 ? 0.0 : 1.0 / (z * z));
  6326. this.minimumRadius = Math.min(x, y, z);
  6327. this.maximumRadius = Math.max(x, y, z);
  6328. if (this.radiiSquared.z !== 0) {
  6329. this.squaredXOverSquaredZ = this.radiiSquared.x / this.radiiSquared.z;
  6330. }
  6331. Object.freeze(this);
  6332. }
  6333. equals(right) {
  6334. return this === right || Boolean(right && this.radii.equals(right.radii));
  6335. }
  6336. toString() {
  6337. return this.radii.toString();
  6338. }
  6339. cartographicToCartesian(cartographic, result = [0, 0, 0]) {
  6340. const normal = scratchNormal$2;
  6341. const k = scratchK;
  6342. const [,, height] = cartographic;
  6343. this.geodeticSurfaceNormalCartographic(cartographic, normal);
  6344. k.copy(this.radiiSquared).scale(normal);
  6345. const gamma = Math.sqrt(normal.dot(k));
  6346. k.scale(1 / gamma);
  6347. normal.scale(height);
  6348. k.add(normal);
  6349. return k.to(result);
  6350. }
  6351. cartesianToCartographic(cartesian, result = [0, 0, 0]) {
  6352. scratchCartesian.from(cartesian);
  6353. const point = this.scaleToGeodeticSurface(scratchCartesian, scratchPosition$2);
  6354. if (!point) {
  6355. return undefined;
  6356. }
  6357. const normal = this.geodeticSurfaceNormal(point, scratchNormal$2);
  6358. const h = scratchHeight;
  6359. h.copy(scratchCartesian).subtract(point);
  6360. const longitude = Math.atan2(normal.y, normal.x);
  6361. const latitude = Math.asin(normal.z);
  6362. const height = Math.sign(dot$2(h, scratchCartesian)) * length$2(h);
  6363. return toCartographicFromRadians([longitude, latitude, height], result);
  6364. }
  6365. eastNorthUpToFixedFrame(origin, result = new Matrix4()) {
  6366. return localFrameToFixedFrame(this, 'east', 'north', 'up', origin, result);
  6367. }
  6368. localFrameToFixedFrame(firstAxis, secondAxis, thirdAxis, origin, result = new Matrix4()) {
  6369. return localFrameToFixedFrame(this, firstAxis, secondAxis, thirdAxis, origin, result);
  6370. }
  6371. geocentricSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6372. return scratchVector$4.from(cartesian).normalize().to(result);
  6373. }
  6374. geodeticSurfaceNormalCartographic(cartographic, result = [0, 0, 0]) {
  6375. const cartographicVectorRadians = fromCartographicToRadians(cartographic);
  6376. const longitude = cartographicVectorRadians[0];
  6377. const latitude = cartographicVectorRadians[1];
  6378. const cosLatitude = Math.cos(latitude);
  6379. scratchVector$4.set(cosLatitude * Math.cos(longitude), cosLatitude * Math.sin(longitude), Math.sin(latitude)).normalize();
  6380. return scratchVector$4.to(result);
  6381. }
  6382. geodeticSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6383. return scratchVector$4.from(cartesian).scale(this.oneOverRadiiSquared).normalize().to(result);
  6384. }
  6385. scaleToGeodeticSurface(cartesian, result) {
  6386. return scaleToGeodeticSurface(cartesian, this, result);
  6387. }
  6388. scaleToGeocentricSurface(cartesian, result = [0, 0, 0]) {
  6389. scratchPosition$2.from(cartesian);
  6390. const positionX = scratchPosition$2.x;
  6391. const positionY = scratchPosition$2.y;
  6392. const positionZ = scratchPosition$2.z;
  6393. const oneOverRadiiSquared = this.oneOverRadiiSquared;
  6394. const beta = 1.0 / Math.sqrt(positionX * positionX * oneOverRadiiSquared.x + positionY * positionY * oneOverRadiiSquared.y + positionZ * positionZ * oneOverRadiiSquared.z);
  6395. return scratchPosition$2.multiplyScalar(beta).to(result);
  6396. }
  6397. transformPositionToScaledSpace(position, result = [0, 0, 0]) {
  6398. return scratchPosition$2.from(position).scale(this.oneOverRadii).to(result);
  6399. }
  6400. transformPositionFromScaledSpace(position, result = [0, 0, 0]) {
  6401. return scratchPosition$2.from(position).scale(this.radii).to(result);
  6402. }
  6403. getSurfaceNormalIntersectionWithZAxis(position, buffer = 0, result = [0, 0, 0]) {
  6404. assert$4(equals(this.radii.x, this.radii.y, _MathUtils.EPSILON15));
  6405. assert$4(this.radii.z > 0);
  6406. scratchPosition$2.from(position);
  6407. const z = scratchPosition$2.z * (1 - this.squaredXOverSquaredZ);
  6408. if (Math.abs(z) >= this.radii.z - buffer) {
  6409. return undefined;
  6410. }
  6411. return scratchPosition$2.set(0.0, 0.0, z).to(result);
  6412. }
  6413. }
  6414. _defineProperty(Ellipsoid, "WGS84", new Ellipsoid(WGS84_RADIUS_X$1, WGS84_RADIUS_Y$1, WGS84_RADIUS_Z$1));
  6415. class DoublyLinkedListNode {
  6416. constructor(item, previous, next) {
  6417. _defineProperty(this, "item", void 0);
  6418. _defineProperty(this, "previous", void 0);
  6419. _defineProperty(this, "next", void 0);
  6420. this.item = item;
  6421. this.previous = previous;
  6422. this.next = next;
  6423. }
  6424. }
  6425. class DoublyLinkedList {
  6426. constructor() {
  6427. _defineProperty(this, "head", null);
  6428. _defineProperty(this, "tail", null);
  6429. _defineProperty(this, "_length", 0);
  6430. }
  6431. get length() {
  6432. return this._length;
  6433. }
  6434. add(item) {
  6435. const node = new DoublyLinkedListNode(item, this.tail, null);
  6436. if (this.tail) {
  6437. this.tail.next = node;
  6438. this.tail = node;
  6439. } else {
  6440. this.head = node;
  6441. this.tail = node;
  6442. }
  6443. ++this._length;
  6444. return node;
  6445. }
  6446. remove(node) {
  6447. if (!node) {
  6448. return;
  6449. }
  6450. if (node.previous && node.next) {
  6451. node.previous.next = node.next;
  6452. node.next.previous = node.previous;
  6453. } else if (node.previous) {
  6454. node.previous.next = null;
  6455. this.tail = node.previous;
  6456. } else if (node.next) {
  6457. node.next.previous = null;
  6458. this.head = node.next;
  6459. } else {
  6460. this.head = null;
  6461. this.tail = null;
  6462. }
  6463. node.next = null;
  6464. node.previous = null;
  6465. --this._length;
  6466. }
  6467. splice(node, nextNode) {
  6468. if (node === nextNode) {
  6469. return;
  6470. }
  6471. this.remove(nextNode);
  6472. this._insert(node, nextNode);
  6473. }
  6474. _insert(node, nextNode) {
  6475. const oldNodeNext = node.next;
  6476. node.next = nextNode;
  6477. if (this.tail === node) {
  6478. this.tail = nextNode;
  6479. } else {
  6480. oldNodeNext.previous = nextNode;
  6481. }
  6482. nextNode.next = oldNodeNext;
  6483. nextNode.previous = node;
  6484. ++this._length;
  6485. }
  6486. }
  6487. function defined$5(x) {
  6488. return x !== undefined && x !== null;
  6489. }
  6490. class TilesetCache {
  6491. constructor() {
  6492. _defineProperty(this, "_list", void 0);
  6493. _defineProperty(this, "_sentinel", void 0);
  6494. _defineProperty(this, "_trimTiles", void 0);
  6495. this._list = new DoublyLinkedList();
  6496. this._sentinel = this._list.add('sentinel');
  6497. this._trimTiles = false;
  6498. }
  6499. reset() {
  6500. this._list.splice(this._list.tail, this._sentinel);
  6501. }
  6502. touch(tile) {
  6503. const node = tile._cacheNode;
  6504. if (defined$5(node)) {
  6505. this._list.splice(this._sentinel, node);
  6506. }
  6507. }
  6508. add(tileset, tile, addCallback) {
  6509. if (!defined$5(tile._cacheNode)) {
  6510. tile._cacheNode = this._list.add(tile);
  6511. if (addCallback) {
  6512. addCallback(tileset, tile);
  6513. }
  6514. }
  6515. }
  6516. unloadTile(tileset, tile, unloadCallback) {
  6517. const node = tile._cacheNode;
  6518. if (!defined$5(node)) {
  6519. return;
  6520. }
  6521. this._list.remove(node);
  6522. tile._cacheNode = undefined;
  6523. if (unloadCallback) {
  6524. unloadCallback(tileset, tile);
  6525. }
  6526. }
  6527. unloadTiles(tileset, unloadCallback) {
  6528. const trimTiles = this._trimTiles;
  6529. this._trimTiles = false;
  6530. const list = this._list;
  6531. const maximumMemoryUsageInBytes = tileset.maximumMemoryUsage * 1024 * 1024;
  6532. const sentinel = this._sentinel;
  6533. let node = list.head;
  6534. while (node !== sentinel && (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)) {
  6535. const tile = node.item;
  6536. node = node.next;
  6537. this.unloadTile(tileset, tile, unloadCallback);
  6538. }
  6539. }
  6540. trim() {
  6541. this._trimTiles = true;
  6542. }
  6543. }
  6544. function calculateTransformProps(tileHeader, tile) {
  6545. assert$7(tileHeader);
  6546. assert$7(tile);
  6547. const {
  6548. rtcCenter,
  6549. gltfUpAxis
  6550. } = tile;
  6551. const {
  6552. computedTransform,
  6553. boundingVolume: {
  6554. center
  6555. }
  6556. } = tileHeader;
  6557. let modelMatrix = new Matrix4(computedTransform);
  6558. if (rtcCenter) {
  6559. modelMatrix.translate(rtcCenter);
  6560. }
  6561. switch (gltfUpAxis) {
  6562. case 'Z':
  6563. break;
  6564. case 'Y':
  6565. const rotationY = new Matrix4().rotateX(Math.PI / 2);
  6566. modelMatrix = modelMatrix.multiplyRight(rotationY);
  6567. break;
  6568. case 'X':
  6569. const rotationX = new Matrix4().rotateY(-Math.PI / 2);
  6570. modelMatrix = modelMatrix.multiplyRight(rotationX);
  6571. break;
  6572. }
  6573. if (tile.isQuantized) {
  6574. modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale);
  6575. }
  6576. const cartesianOrigin = new Vector3(center);
  6577. tile.cartesianModelMatrix = modelMatrix;
  6578. tile.cartesianOrigin = cartesianOrigin;
  6579. const cartographicOrigin = Ellipsoid.WGS84.cartesianToCartographic(cartesianOrigin, new Vector3());
  6580. const fromFixedFrameMatrix = Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin);
  6581. const toFixedFrameMatrix = fromFixedFrameMatrix.invert();
  6582. tile.cartographicModelMatrix = toFixedFrameMatrix.multiplyRight(modelMatrix);
  6583. tile.cartographicOrigin = cartographicOrigin;
  6584. if (!tile.coordinateSystem) {
  6585. tile.modelMatrix = tile.cartographicModelMatrix;
  6586. }
  6587. }
  6588. const INTERSECTION = {
  6589. OUTSIDE: -1,
  6590. INTERSECTING: 0,
  6591. INSIDE: 1
  6592. };
  6593. new Vector3();
  6594. new Vector3();
  6595. const scratchVector$3 = new Vector3();
  6596. const scratchVector2 = new Vector3();
  6597. class BoundingSphere {
  6598. constructor(center = [0, 0, 0], radius = 0.0) {
  6599. _defineProperty(this, "center", void 0);
  6600. _defineProperty(this, "radius", void 0);
  6601. this.radius = -0;
  6602. this.center = new Vector3();
  6603. this.fromCenterRadius(center, radius);
  6604. }
  6605. fromCenterRadius(center, radius) {
  6606. this.center.from(center);
  6607. this.radius = radius;
  6608. return this;
  6609. }
  6610. fromCornerPoints(corner, oppositeCorner) {
  6611. oppositeCorner = scratchVector$3.from(oppositeCorner);
  6612. this.center = new Vector3().from(corner).add(oppositeCorner).scale(0.5);
  6613. this.radius = this.center.distance(oppositeCorner);
  6614. return this;
  6615. }
  6616. equals(right) {
  6617. return this === right || Boolean(right) && this.center.equals(right.center) && this.radius === right.radius;
  6618. }
  6619. clone() {
  6620. return new BoundingSphere(this.center, this.radius);
  6621. }
  6622. union(boundingSphere) {
  6623. const leftCenter = this.center;
  6624. const leftRadius = this.radius;
  6625. const rightCenter = boundingSphere.center;
  6626. const rightRadius = boundingSphere.radius;
  6627. const toRightCenter = scratchVector$3.copy(rightCenter).subtract(leftCenter);
  6628. const centerSeparation = toRightCenter.magnitude();
  6629. if (leftRadius >= centerSeparation + rightRadius) {
  6630. return this.clone();
  6631. }
  6632. if (rightRadius >= centerSeparation + leftRadius) {
  6633. return boundingSphere.clone();
  6634. }
  6635. const halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  6636. scratchVector2.copy(toRightCenter).scale((-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation).add(leftCenter);
  6637. this.center.copy(scratchVector2);
  6638. this.radius = halfDistanceBetweenTangentPoints;
  6639. return this;
  6640. }
  6641. expand(point) {
  6642. const scratchPoint = scratchVector$3.from(point);
  6643. const radius = scratchPoint.subtract(this.center).magnitude();
  6644. if (radius > this.radius) {
  6645. this.radius = radius;
  6646. }
  6647. return this;
  6648. }
  6649. transform(transform) {
  6650. this.center.transform(transform);
  6651. const scale = getScaling(scratchVector$3, transform);
  6652. this.radius = Math.max(scale[0], Math.max(scale[1], scale[2])) * this.radius;
  6653. return this;
  6654. }
  6655. distanceSquaredTo(point) {
  6656. const d = this.distanceTo(point);
  6657. return d * d;
  6658. }
  6659. distanceTo(point) {
  6660. const scratchPoint = scratchVector$3.from(point);
  6661. const delta = scratchPoint.subtract(this.center);
  6662. return Math.max(0, delta.len() - this.radius);
  6663. }
  6664. intersectPlane(plane) {
  6665. const center = this.center;
  6666. const radius = this.radius;
  6667. const normal = plane.normal;
  6668. const distanceToPlane = normal.dot(center) + plane.distance;
  6669. if (distanceToPlane < -radius) {
  6670. return INTERSECTION.OUTSIDE;
  6671. }
  6672. if (distanceToPlane < radius) {
  6673. return INTERSECTION.INTERSECTING;
  6674. }
  6675. return INTERSECTION.INSIDE;
  6676. }
  6677. }
  6678. const scratchVector3 = new Vector3();
  6679. const scratchOffset = new Vector3();
  6680. const scratchVectorU = new Vector3();
  6681. const scratchVectorV = new Vector3();
  6682. const scratchVectorW = new Vector3();
  6683. const scratchCorner = new Vector3();
  6684. const scratchToCenter = new Vector3();
  6685. const MATRIX3 = {
  6686. COLUMN0ROW0: 0,
  6687. COLUMN0ROW1: 1,
  6688. COLUMN0ROW2: 2,
  6689. COLUMN1ROW0: 3,
  6690. COLUMN1ROW1: 4,
  6691. COLUMN1ROW2: 5,
  6692. COLUMN2ROW0: 6,
  6693. COLUMN2ROW1: 7,
  6694. COLUMN2ROW2: 8
  6695. };
  6696. class OrientedBoundingBox {
  6697. constructor(center = [0, 0, 0], halfAxes = [0, 0, 0, 0, 0, 0, 0, 0, 0]) {
  6698. _defineProperty(this, "center", void 0);
  6699. _defineProperty(this, "halfAxes", void 0);
  6700. this.center = new Vector3().from(center);
  6701. this.halfAxes = new Matrix3(halfAxes);
  6702. }
  6703. get halfSize() {
  6704. const xAxis = this.halfAxes.getColumn(0);
  6705. const yAxis = this.halfAxes.getColumn(1);
  6706. const zAxis = this.halfAxes.getColumn(2);
  6707. return [new Vector3(xAxis).len(), new Vector3(yAxis).len(), new Vector3(zAxis).len()];
  6708. }
  6709. get quaternion() {
  6710. const xAxis = this.halfAxes.getColumn(0);
  6711. const yAxis = this.halfAxes.getColumn(1);
  6712. const zAxis = this.halfAxes.getColumn(2);
  6713. const normXAxis = new Vector3(xAxis).normalize();
  6714. const normYAxis = new Vector3(yAxis).normalize();
  6715. const normZAxis = new Vector3(zAxis).normalize();
  6716. return new Quaternion().fromMatrix3(new Matrix3([...normXAxis, ...normYAxis, ...normZAxis]));
  6717. }
  6718. fromCenterHalfSizeQuaternion(center, halfSize, quaternion) {
  6719. const quaternionObject = new Quaternion(quaternion);
  6720. const directionsMatrix = new Matrix3().fromQuaternion(quaternionObject);
  6721. directionsMatrix[0] = directionsMatrix[0] * halfSize[0];
  6722. directionsMatrix[1] = directionsMatrix[1] * halfSize[0];
  6723. directionsMatrix[2] = directionsMatrix[2] * halfSize[0];
  6724. directionsMatrix[3] = directionsMatrix[3] * halfSize[1];
  6725. directionsMatrix[4] = directionsMatrix[4] * halfSize[1];
  6726. directionsMatrix[5] = directionsMatrix[5] * halfSize[1];
  6727. directionsMatrix[6] = directionsMatrix[6] * halfSize[2];
  6728. directionsMatrix[7] = directionsMatrix[7] * halfSize[2];
  6729. directionsMatrix[8] = directionsMatrix[8] * halfSize[2];
  6730. this.center = new Vector3().from(center);
  6731. this.halfAxes = directionsMatrix;
  6732. return this;
  6733. }
  6734. clone() {
  6735. return new OrientedBoundingBox(this.center, this.halfAxes);
  6736. }
  6737. equals(right) {
  6738. return this === right || Boolean(right) && this.center.equals(right.center) && this.halfAxes.equals(right.halfAxes);
  6739. }
  6740. getBoundingSphere(result = new BoundingSphere()) {
  6741. const halfAxes = this.halfAxes;
  6742. const u = halfAxes.getColumn(0, scratchVectorU);
  6743. const v = halfAxes.getColumn(1, scratchVectorV);
  6744. const w = halfAxes.getColumn(2, scratchVectorW);
  6745. const cornerVector = scratchVector3.copy(u).add(v).add(w);
  6746. result.center.copy(this.center);
  6747. result.radius = cornerVector.magnitude();
  6748. return result;
  6749. }
  6750. intersectPlane(plane) {
  6751. const center = this.center;
  6752. const normal = plane.normal;
  6753. const halfAxes = this.halfAxes;
  6754. const normalX = normal.x;
  6755. const normalY = normal.y;
  6756. const normalZ = normal.z;
  6757. const radEffective = Math.abs(normalX * halfAxes[MATRIX3.COLUMN0ROW0] + normalY * halfAxes[MATRIX3.COLUMN0ROW1] + normalZ * halfAxes[MATRIX3.COLUMN0ROW2]) + Math.abs(normalX * halfAxes[MATRIX3.COLUMN1ROW0] + normalY * halfAxes[MATRIX3.COLUMN1ROW1] + normalZ * halfAxes[MATRIX3.COLUMN1ROW2]) + Math.abs(normalX * halfAxes[MATRIX3.COLUMN2ROW0] + normalY * halfAxes[MATRIX3.COLUMN2ROW1] + normalZ * halfAxes[MATRIX3.COLUMN2ROW2]);
  6758. const distanceToPlane = normal.dot(center) + plane.distance;
  6759. if (distanceToPlane <= -radEffective) {
  6760. return INTERSECTION.OUTSIDE;
  6761. } else if (distanceToPlane >= radEffective) {
  6762. return INTERSECTION.INSIDE;
  6763. }
  6764. return INTERSECTION.INTERSECTING;
  6765. }
  6766. distanceTo(point) {
  6767. return Math.sqrt(this.distanceSquaredTo(point));
  6768. }
  6769. distanceSquaredTo(point) {
  6770. const offset = scratchOffset.from(point).subtract(this.center);
  6771. const halfAxes = this.halfAxes;
  6772. const u = halfAxes.getColumn(0, scratchVectorU);
  6773. const v = halfAxes.getColumn(1, scratchVectorV);
  6774. const w = halfAxes.getColumn(2, scratchVectorW);
  6775. const uHalf = u.magnitude();
  6776. const vHalf = v.magnitude();
  6777. const wHalf = w.magnitude();
  6778. u.normalize();
  6779. v.normalize();
  6780. w.normalize();
  6781. let distanceSquared = 0.0;
  6782. let d;
  6783. d = Math.abs(offset.dot(u)) - uHalf;
  6784. if (d > 0) {
  6785. distanceSquared += d * d;
  6786. }
  6787. d = Math.abs(offset.dot(v)) - vHalf;
  6788. if (d > 0) {
  6789. distanceSquared += d * d;
  6790. }
  6791. d = Math.abs(offset.dot(w)) - wHalf;
  6792. if (d > 0) {
  6793. distanceSquared += d * d;
  6794. }
  6795. return distanceSquared;
  6796. }
  6797. computePlaneDistances(position, direction, result = [-0, -0]) {
  6798. let minDist = Number.POSITIVE_INFINITY;
  6799. let maxDist = Number.NEGATIVE_INFINITY;
  6800. const center = this.center;
  6801. const halfAxes = this.halfAxes;
  6802. const u = halfAxes.getColumn(0, scratchVectorU);
  6803. const v = halfAxes.getColumn(1, scratchVectorV);
  6804. const w = halfAxes.getColumn(2, scratchVectorW);
  6805. const corner = scratchCorner.copy(u).add(v).add(w).add(center);
  6806. const toCenter = scratchToCenter.copy(corner).subtract(position);
  6807. let mag = direction.dot(toCenter);
  6808. minDist = Math.min(mag, minDist);
  6809. maxDist = Math.max(mag, maxDist);
  6810. corner.copy(center).add(u).add(v).subtract(w);
  6811. toCenter.copy(corner).subtract(position);
  6812. mag = direction.dot(toCenter);
  6813. minDist = Math.min(mag, minDist);
  6814. maxDist = Math.max(mag, maxDist);
  6815. corner.copy(center).add(u).subtract(v).add(w);
  6816. toCenter.copy(corner).subtract(position);
  6817. mag = direction.dot(toCenter);
  6818. minDist = Math.min(mag, minDist);
  6819. maxDist = Math.max(mag, maxDist);
  6820. corner.copy(center).add(u).subtract(v).subtract(w);
  6821. toCenter.copy(corner).subtract(position);
  6822. mag = direction.dot(toCenter);
  6823. minDist = Math.min(mag, minDist);
  6824. maxDist = Math.max(mag, maxDist);
  6825. center.copy(corner).subtract(u).add(v).add(w);
  6826. toCenter.copy(corner).subtract(position);
  6827. mag = direction.dot(toCenter);
  6828. minDist = Math.min(mag, minDist);
  6829. maxDist = Math.max(mag, maxDist);
  6830. center.copy(corner).subtract(u).add(v).subtract(w);
  6831. toCenter.copy(corner).subtract(position);
  6832. mag = direction.dot(toCenter);
  6833. minDist = Math.min(mag, minDist);
  6834. maxDist = Math.max(mag, maxDist);
  6835. center.copy(corner).subtract(u).subtract(v).add(w);
  6836. toCenter.copy(corner).subtract(position);
  6837. mag = direction.dot(toCenter);
  6838. minDist = Math.min(mag, minDist);
  6839. maxDist = Math.max(mag, maxDist);
  6840. center.copy(corner).subtract(u).subtract(v).subtract(w);
  6841. toCenter.copy(corner).subtract(position);
  6842. mag = direction.dot(toCenter);
  6843. minDist = Math.min(mag, minDist);
  6844. maxDist = Math.max(mag, maxDist);
  6845. result[0] = minDist;
  6846. result[1] = maxDist;
  6847. return result;
  6848. }
  6849. transform(transformation) {
  6850. this.center.transformAsPoint(transformation);
  6851. const xAxis = this.halfAxes.getColumn(0, scratchVectorU);
  6852. xAxis.transformAsPoint(transformation);
  6853. const yAxis = this.halfAxes.getColumn(1, scratchVectorV);
  6854. yAxis.transformAsPoint(transformation);
  6855. const zAxis = this.halfAxes.getColumn(2, scratchVectorW);
  6856. zAxis.transformAsPoint(transformation);
  6857. this.halfAxes = new Matrix3([...xAxis, ...yAxis, ...zAxis]);
  6858. return this;
  6859. }
  6860. getTransform() {
  6861. throw new Error('not implemented');
  6862. }
  6863. }
  6864. const scratchPosition$1 = new Vector3();
  6865. const scratchNormal$1 = new Vector3();
  6866. class Plane {
  6867. constructor(normal = [0, 0, 1], distance = 0) {
  6868. _defineProperty(this, "normal", void 0);
  6869. _defineProperty(this, "distance", void 0);
  6870. this.normal = new Vector3();
  6871. this.distance = -0;
  6872. this.fromNormalDistance(normal, distance);
  6873. }
  6874. fromNormalDistance(normal, distance) {
  6875. assert$4(Number.isFinite(distance));
  6876. this.normal.from(normal).normalize();
  6877. this.distance = distance;
  6878. return this;
  6879. }
  6880. fromPointNormal(point, normal) {
  6881. point = scratchPosition$1.from(point);
  6882. this.normal.from(normal).normalize();
  6883. const distance = -this.normal.dot(point);
  6884. this.distance = distance;
  6885. return this;
  6886. }
  6887. fromCoefficients(a, b, c, d) {
  6888. this.normal.set(a, b, c);
  6889. assert$4(equals(this.normal.len(), 1));
  6890. this.distance = d;
  6891. return this;
  6892. }
  6893. clone() {
  6894. return new Plane(this.normal, this.distance);
  6895. }
  6896. equals(right) {
  6897. return equals(this.distance, right.distance) && equals(this.normal, right.normal);
  6898. }
  6899. getPointDistance(point) {
  6900. return this.normal.dot(point) + this.distance;
  6901. }
  6902. transform(matrix4) {
  6903. const normal = scratchNormal$1.copy(this.normal).transformAsVector(matrix4).normalize();
  6904. const point = this.normal.scale(-this.distance).transform(matrix4);
  6905. return this.fromPointNormal(point, normal);
  6906. }
  6907. projectPointOntoPlane(point, result = [0, 0, 0]) {
  6908. point = scratchPosition$1.from(point);
  6909. const pointDistance = this.getPointDistance(point);
  6910. const scaledNormal = scratchNormal$1.copy(this.normal).scale(pointDistance);
  6911. return point.subtract(scaledNormal).to(result);
  6912. }
  6913. }
  6914. const faces = [new Vector3([1, 0, 0]), new Vector3([0, 1, 0]), new Vector3([0, 0, 1])];
  6915. const scratchPlaneCenter = new Vector3();
  6916. const scratchPlaneNormal$1 = new Vector3();
  6917. new Plane(new Vector3(1.0, 0.0, 0.0), 0.0);
  6918. class CullingVolume {
  6919. constructor(planes = []) {
  6920. _defineProperty(this, "planes", void 0);
  6921. this.planes = planes;
  6922. }
  6923. fromBoundingSphere(boundingSphere) {
  6924. this.planes.length = 2 * faces.length;
  6925. const center = boundingSphere.center;
  6926. const radius = boundingSphere.radius;
  6927. let planeIndex = 0;
  6928. for (const faceNormal of faces) {
  6929. let plane0 = this.planes[planeIndex];
  6930. let plane1 = this.planes[planeIndex + 1];
  6931. if (!plane0) {
  6932. plane0 = this.planes[planeIndex] = new Plane();
  6933. }
  6934. if (!plane1) {
  6935. plane1 = this.planes[planeIndex + 1] = new Plane();
  6936. }
  6937. const plane0Center = scratchPlaneCenter.copy(faceNormal).scale(-radius).add(center);
  6938. -faceNormal.dot(plane0Center);
  6939. plane0.fromPointNormal(plane0Center, faceNormal);
  6940. const plane1Center = scratchPlaneCenter.copy(faceNormal).scale(radius).add(center);
  6941. const negatedFaceNormal = scratchPlaneNormal$1.copy(faceNormal).negate();
  6942. -negatedFaceNormal.dot(plane1Center);
  6943. plane1.fromPointNormal(plane1Center, negatedFaceNormal);
  6944. planeIndex += 2;
  6945. }
  6946. return this;
  6947. }
  6948. computeVisibility(boundingVolume) {
  6949. let intersect = INTERSECTION.INSIDE;
  6950. for (const plane of this.planes) {
  6951. const result = boundingVolume.intersectPlane(plane);
  6952. switch (result) {
  6953. case INTERSECTION.OUTSIDE:
  6954. return INTERSECTION.OUTSIDE;
  6955. case INTERSECTION.INTERSECTING:
  6956. intersect = INTERSECTION.INTERSECTING;
  6957. break;
  6958. }
  6959. }
  6960. return intersect;
  6961. }
  6962. computeVisibilityWithPlaneMask(boundingVolume, parentPlaneMask) {
  6963. assert$4(Number.isFinite(parentPlaneMask), 'parentPlaneMask is required.');
  6964. if (parentPlaneMask === CullingVolume.MASK_OUTSIDE || parentPlaneMask === CullingVolume.MASK_INSIDE) {
  6965. return parentPlaneMask;
  6966. }
  6967. let mask = CullingVolume.MASK_INSIDE;
  6968. const planes = this.planes;
  6969. for (let k = 0; k < this.planes.length; ++k) {
  6970. const flag = k < 31 ? 1 << k : 0;
  6971. if (k < 31 && (parentPlaneMask & flag) === 0) {
  6972. continue;
  6973. }
  6974. const plane = planes[k];
  6975. const result = boundingVolume.intersectPlane(plane);
  6976. if (result === INTERSECTION.OUTSIDE) {
  6977. return CullingVolume.MASK_OUTSIDE;
  6978. } else if (result === INTERSECTION.INTERSECTING) {
  6979. mask |= flag;
  6980. }
  6981. }
  6982. return mask;
  6983. }
  6984. }
  6985. _defineProperty(CullingVolume, "MASK_OUTSIDE", 0xffffffff);
  6986. _defineProperty(CullingVolume, "MASK_INSIDE", 0x00000000);
  6987. _defineProperty(CullingVolume, "MASK_INDETERMINATE", 0x7fffffff);
  6988. const scratchPlaneUpVector = new Vector3();
  6989. const scratchPlaneRightVector = new Vector3();
  6990. const scratchPlaneNearCenter = new Vector3();
  6991. const scratchPlaneFarCenter = new Vector3();
  6992. const scratchPlaneNormal = new Vector3();
  6993. class PerspectiveOffCenterFrustum {
  6994. constructor(options = {}) {
  6995. _defineProperty(this, "left", void 0);
  6996. _defineProperty(this, "_left", void 0);
  6997. _defineProperty(this, "right", void 0);
  6998. _defineProperty(this, "_right", void 0);
  6999. _defineProperty(this, "top", void 0);
  7000. _defineProperty(this, "_top", void 0);
  7001. _defineProperty(this, "bottom", void 0);
  7002. _defineProperty(this, "_bottom", void 0);
  7003. _defineProperty(this, "near", void 0);
  7004. _defineProperty(this, "_near", void 0);
  7005. _defineProperty(this, "far", void 0);
  7006. _defineProperty(this, "_far", void 0);
  7007. _defineProperty(this, "_cullingVolume", new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]));
  7008. _defineProperty(this, "_perspectiveMatrix", new Matrix4());
  7009. _defineProperty(this, "_infinitePerspective", new Matrix4());
  7010. const {
  7011. near = 1.0,
  7012. far = 500000000.0
  7013. } = options;
  7014. this.left = options.left;
  7015. this._left = undefined;
  7016. this.right = options.right;
  7017. this._right = undefined;
  7018. this.top = options.top;
  7019. this._top = undefined;
  7020. this.bottom = options.bottom;
  7021. this._bottom = undefined;
  7022. this.near = near;
  7023. this._near = near;
  7024. this.far = far;
  7025. this._far = far;
  7026. }
  7027. clone() {
  7028. return new PerspectiveOffCenterFrustum({
  7029. right: this.right,
  7030. left: this.left,
  7031. top: this.top,
  7032. bottom: this.bottom,
  7033. near: this.near,
  7034. far: this.far
  7035. });
  7036. }
  7037. equals(other) {
  7038. return other && other instanceof PerspectiveOffCenterFrustum && this.right === other.right && this.left === other.left && this.top === other.top && this.bottom === other.bottom && this.near === other.near && this.far === other.far;
  7039. }
  7040. get projectionMatrix() {
  7041. this._update();
  7042. return this._perspectiveMatrix;
  7043. }
  7044. get infiniteProjectionMatrix() {
  7045. this._update();
  7046. return this._infinitePerspective;
  7047. }
  7048. computeCullingVolume(position, direction, up) {
  7049. assert$4(position, 'position is required.');
  7050. assert$4(direction, 'direction is required.');
  7051. assert$4(up, 'up is required.');
  7052. const planes = this._cullingVolume.planes;
  7053. up = scratchPlaneUpVector.copy(up).normalize();
  7054. const right = scratchPlaneRightVector.copy(direction).cross(up).normalize();
  7055. const nearCenter = scratchPlaneNearCenter.copy(direction).multiplyByScalar(this.near).add(position);
  7056. const farCenter = scratchPlaneFarCenter.copy(direction).multiplyByScalar(this.far).add(position);
  7057. let normal = scratchPlaneNormal;
  7058. normal.copy(right).multiplyByScalar(this.left).add(nearCenter).subtract(position).cross(up);
  7059. planes[0].fromPointNormal(position, normal);
  7060. normal.copy(right).multiplyByScalar(this.right).add(nearCenter).subtract(position).cross(up).negate();
  7061. planes[1].fromPointNormal(position, normal);
  7062. normal.copy(up).multiplyByScalar(this.bottom).add(nearCenter).subtract(position).cross(right).negate();
  7063. planes[2].fromPointNormal(position, normal);
  7064. normal.copy(up).multiplyByScalar(this.top).add(nearCenter).subtract(position).cross(right);
  7065. planes[3].fromPointNormal(position, normal);
  7066. normal = new Vector3().copy(direction);
  7067. planes[4].fromPointNormal(nearCenter, normal);
  7068. normal.negate();
  7069. planes[5].fromPointNormal(farCenter, normal);
  7070. return this._cullingVolume;
  7071. }
  7072. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  7073. this._update();
  7074. assert$4(Number.isFinite(drawingBufferWidth) && Number.isFinite(drawingBufferHeight));
  7075. assert$4(drawingBufferWidth > 0);
  7076. assert$4(drawingBufferHeight > 0);
  7077. assert$4(distance > 0);
  7078. assert$4(result);
  7079. const inverseNear = 1.0 / this.near;
  7080. let tanTheta = this.top * inverseNear;
  7081. const pixelHeight = 2.0 * distance * tanTheta / drawingBufferHeight;
  7082. tanTheta = this.right * inverseNear;
  7083. const pixelWidth = 2.0 * distance * tanTheta / drawingBufferWidth;
  7084. result.x = pixelWidth;
  7085. result.y = pixelHeight;
  7086. return result;
  7087. }
  7088. _update() {
  7089. assert$4(Number.isFinite(this.right) && Number.isFinite(this.left) && Number.isFinite(this.top) && Number.isFinite(this.bottom) && Number.isFinite(this.near) && Number.isFinite(this.far));
  7090. const {
  7091. top,
  7092. bottom,
  7093. right,
  7094. left,
  7095. near,
  7096. far
  7097. } = this;
  7098. if (top !== this._top || bottom !== this._bottom || left !== this._left || right !== this._right || near !== this._near || far !== this._far) {
  7099. assert$4(this.near > 0 && this.near < this.far, 'near must be greater than zero and less than far.');
  7100. this._left = left;
  7101. this._right = right;
  7102. this._top = top;
  7103. this._bottom = bottom;
  7104. this._near = near;
  7105. this._far = far;
  7106. this._perspectiveMatrix = new Matrix4().frustum({
  7107. left,
  7108. right,
  7109. bottom,
  7110. top,
  7111. near,
  7112. far
  7113. });
  7114. this._infinitePerspective = new Matrix4().frustum({
  7115. left,
  7116. right,
  7117. bottom,
  7118. top,
  7119. near,
  7120. far: Infinity
  7121. });
  7122. }
  7123. }
  7124. }
  7125. const defined$4 = val => val !== null && typeof val !== 'undefined';
  7126. class PerspectiveFrustum {
  7127. constructor(options = {}) {
  7128. _defineProperty(this, "_offCenterFrustum", new PerspectiveOffCenterFrustum());
  7129. _defineProperty(this, "fov", void 0);
  7130. _defineProperty(this, "_fov", void 0);
  7131. _defineProperty(this, "_fovy", void 0);
  7132. _defineProperty(this, "_sseDenominator", void 0);
  7133. _defineProperty(this, "aspectRatio", void 0);
  7134. _defineProperty(this, "_aspectRatio", void 0);
  7135. _defineProperty(this, "near", void 0);
  7136. _defineProperty(this, "_near", void 0);
  7137. _defineProperty(this, "far", void 0);
  7138. _defineProperty(this, "_far", void 0);
  7139. _defineProperty(this, "xOffset", void 0);
  7140. _defineProperty(this, "_xOffset", void 0);
  7141. _defineProperty(this, "yOffset", void 0);
  7142. _defineProperty(this, "_yOffset", void 0);
  7143. const {
  7144. fov,
  7145. aspectRatio,
  7146. near = 1.0,
  7147. far = 500000000.0,
  7148. xOffset = 0.0,
  7149. yOffset = 0.0
  7150. } = options;
  7151. this.fov = fov;
  7152. this.aspectRatio = aspectRatio;
  7153. this.near = near;
  7154. this.far = far;
  7155. this.xOffset = xOffset;
  7156. this.yOffset = yOffset;
  7157. }
  7158. clone() {
  7159. return new PerspectiveFrustum({
  7160. aspectRatio: this.aspectRatio,
  7161. fov: this.fov,
  7162. near: this.near,
  7163. far: this.far
  7164. });
  7165. }
  7166. equals(other) {
  7167. if (!defined$4(other) || !(other instanceof PerspectiveFrustum)) {
  7168. return false;
  7169. }
  7170. this._update();
  7171. other._update();
  7172. return this.fov === other.fov && this.aspectRatio === other.aspectRatio && this.near === other.near && this.far === other.far && this._offCenterFrustum.equals(other._offCenterFrustum);
  7173. }
  7174. get projectionMatrix() {
  7175. this._update();
  7176. return this._offCenterFrustum.projectionMatrix;
  7177. }
  7178. get infiniteProjectionMatrix() {
  7179. this._update();
  7180. return this._offCenterFrustum.infiniteProjectionMatrix;
  7181. }
  7182. get fovy() {
  7183. this._update();
  7184. return this._fovy;
  7185. }
  7186. get sseDenominator() {
  7187. this._update();
  7188. return this._sseDenominator;
  7189. }
  7190. computeCullingVolume(position, direction, up) {
  7191. this._update();
  7192. return this._offCenterFrustum.computeCullingVolume(position, direction, up);
  7193. }
  7194. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  7195. this._update();
  7196. return this._offCenterFrustum.getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result || new Vector2());
  7197. }
  7198. _update() {
  7199. assert$4(Number.isFinite(this.fov) && Number.isFinite(this.aspectRatio) && Number.isFinite(this.near) && Number.isFinite(this.far));
  7200. const f = this._offCenterFrustum;
  7201. if (this.fov !== this._fov || this.aspectRatio !== this._aspectRatio || this.near !== this._near || this.far !== this._far || this.xOffset !== this._xOffset || this.yOffset !== this._yOffset) {
  7202. assert$4(this.fov >= 0 && this.fov < Math.PI);
  7203. assert$4(this.aspectRatio > 0);
  7204. assert$4(this.near >= 0 && this.near < this.far);
  7205. this._aspectRatio = this.aspectRatio;
  7206. this._fov = this.fov;
  7207. this._fovy = this.aspectRatio <= 1 ? this.fov : Math.atan(Math.tan(this.fov * 0.5) / this.aspectRatio) * 2.0;
  7208. this._near = this.near;
  7209. this._far = this.far;
  7210. this._sseDenominator = 2.0 * Math.tan(0.5 * this._fovy);
  7211. this._xOffset = this.xOffset;
  7212. this._yOffset = this.yOffset;
  7213. f.top = this.near * Math.tan(0.5 * this._fovy);
  7214. f.bottom = -f.top;
  7215. f.right = this.aspectRatio * f.top;
  7216. f.left = -f.right;
  7217. f.near = this.near;
  7218. f.far = this.far;
  7219. f.right += this.xOffset;
  7220. f.left += this.xOffset;
  7221. f.top += this.yOffset;
  7222. f.bottom += this.yOffset;
  7223. }
  7224. }
  7225. }
  7226. new Vector3();
  7227. new Vector3();
  7228. new Vector3();
  7229. new Vector3();
  7230. new Vector3();
  7231. new Vector3();
  7232. new Vector3();
  7233. new Vector3();
  7234. new Vector3();
  7235. new Vector3();
  7236. new Vector3();
  7237. new Vector3();
  7238. new Matrix3();
  7239. new Matrix3();
  7240. new Matrix3();
  7241. new Matrix3();
  7242. new Matrix3();
  7243. new Vector3();
  7244. new Vector3();
  7245. new Vector3();
  7246. new Vector3();
  7247. new Vector3();
  7248. new Matrix3();
  7249. ({
  7250. diagonal: new Matrix3(),
  7251. unitary: new Matrix3()
  7252. });
  7253. const scratchVector$2 = new Vector3();
  7254. const scratchPosition = new Vector3();
  7255. const cullingVolume = new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]);
  7256. function getFrameState(viewport, frameNumber) {
  7257. const {
  7258. cameraDirection,
  7259. cameraUp,
  7260. height
  7261. } = viewport;
  7262. const {
  7263. metersPerUnit
  7264. } = viewport.distanceScales;
  7265. const viewportCenterCartographic = viewport.unprojectPosition(viewport.center);
  7266. const viewportCenterCartesian = Ellipsoid.WGS84.cartographicToCartesian(viewportCenterCartographic, new Vector3());
  7267. const enuToFixedTransform = Ellipsoid.WGS84.eastNorthUpToFixedFrame(viewportCenterCartesian);
  7268. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7269. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
  7270. const cameraDirectionCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraDirection).scale(metersPerUnit))).normalize();
  7271. const cameraUpCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraUp).scale(metersPerUnit))).normalize();
  7272. commonSpacePlanesToWGS84(viewport, viewportCenterCartesian);
  7273. const ViewportClass = viewport.constructor;
  7274. const {
  7275. longitude,
  7276. latitude,
  7277. width,
  7278. bearing,
  7279. zoom
  7280. } = viewport;
  7281. const topDownViewport = new ViewportClass({
  7282. longitude,
  7283. latitude,
  7284. height,
  7285. width,
  7286. bearing,
  7287. zoom,
  7288. pitch: 0
  7289. });
  7290. return {
  7291. camera: {
  7292. position: cameraPositionCartesian,
  7293. direction: cameraDirectionCartesian,
  7294. up: cameraUpCartesian
  7295. },
  7296. viewport,
  7297. topDownViewport,
  7298. height,
  7299. cullingVolume,
  7300. frameNumber,
  7301. sseDenominator: 1.15
  7302. };
  7303. }
  7304. function limitSelectedTiles(tiles, frameState, maximumTilesSelected) {
  7305. if (maximumTilesSelected === 0 || tiles.length <= maximumTilesSelected) {
  7306. return [tiles, []];
  7307. }
  7308. const tuples = [];
  7309. const {
  7310. longitude: viewportLongitude,
  7311. latitude: viewportLatitude
  7312. } = frameState.viewport;
  7313. for (const [index, tile] of tiles.entries()) {
  7314. const [longitude, latitude] = tile.header.mbs;
  7315. const deltaLon = Math.abs(viewportLongitude - longitude);
  7316. const deltaLat = Math.abs(viewportLatitude - latitude);
  7317. const distance = Math.sqrt(deltaLat * deltaLat + deltaLon * deltaLon);
  7318. tuples.push([index, distance]);
  7319. }
  7320. const tuplesSorted = tuples.sort((a, b) => a[1] - b[1]);
  7321. const selectedTiles = [];
  7322. for (let i = 0; i < maximumTilesSelected; i++) {
  7323. selectedTiles.push(tiles[tuplesSorted[i][0]]);
  7324. }
  7325. const unselectedTiles = [];
  7326. for (let i = maximumTilesSelected; i < tuplesSorted.length; i++) {
  7327. unselectedTiles.push(tiles[tuplesSorted[i][0]]);
  7328. }
  7329. return [selectedTiles, unselectedTiles];
  7330. }
  7331. function commonSpacePlanesToWGS84(viewport, viewportCenterCartesian) {
  7332. const frustumPlanes = viewport.getFrustumPlanes();
  7333. let i = 0;
  7334. for (const dir in frustumPlanes) {
  7335. const plane = frustumPlanes[dir];
  7336. const distanceToCenter = plane.normal.dot(viewport.center);
  7337. scratchPosition.copy(plane.normal).scale(plane.distance - distanceToCenter).add(viewport.center);
  7338. const cartographicPos = viewport.unprojectPosition(scratchPosition);
  7339. const cartesianPos = Ellipsoid.WGS84.cartographicToCartesian(cartographicPos, new Vector3());
  7340. cullingVolume.planes[i++].fromPointNormal(cartesianPos, scratchVector$2.copy(viewportCenterCartesian).subtract(cartesianPos));
  7341. }
  7342. }
  7343. const WGS84_RADIUS_X = 6378137.0;
  7344. const WGS84_RADIUS_Y = 6378137.0;
  7345. const WGS84_RADIUS_Z = 6356752.3142451793;
  7346. const scratchVector$1 = new Vector3();
  7347. function getZoomFromBoundingVolume(boundingVolume, cartorgraphicCenter) {
  7348. if (boundingVolume instanceof OrientedBoundingBox) {
  7349. const {
  7350. halfAxes
  7351. } = boundingVolume;
  7352. const obbSize = getObbSize(halfAxes);
  7353. return Math.log2(WGS84_RADIUS_Z / (obbSize + cartorgraphicCenter[2]));
  7354. } else if (boundingVolume instanceof BoundingSphere) {
  7355. const {
  7356. radius
  7357. } = boundingVolume;
  7358. return Math.log2(WGS84_RADIUS_Z / (radius + cartorgraphicCenter[2]));
  7359. } else if (boundingVolume.width && boundingVolume.height) {
  7360. const {
  7361. width,
  7362. height
  7363. } = boundingVolume;
  7364. const zoomX = Math.log2(WGS84_RADIUS_X / width);
  7365. const zoomY = Math.log2(WGS84_RADIUS_Y / height);
  7366. return (zoomX + zoomY) / 2;
  7367. }
  7368. return 1;
  7369. }
  7370. function getZoomFromFullExtent(fullExtent, cartorgraphicCenter, cartesianCenter) {
  7371. const extentVertex = Ellipsoid.WGS84.cartographicToCartesian([fullExtent.xmax, fullExtent.ymax, fullExtent.zmax], new Vector3());
  7372. const extentSize = Math.sqrt(Math.pow(extentVertex[0] - cartesianCenter[0], 2) + Math.pow(extentVertex[1] - cartesianCenter[1], 2) + Math.pow(extentVertex[2] - cartesianCenter[2], 2));
  7373. return Math.log2(WGS84_RADIUS_Z / (extentSize + cartorgraphicCenter[2]));
  7374. }
  7375. function getZoomFromExtent(extent, cartorgraphicCenter, cartesianCenter) {
  7376. const [xmin, ymin, xmax, ymax] = extent;
  7377. return getZoomFromFullExtent({
  7378. xmin,
  7379. xmax,
  7380. ymin,
  7381. ymax,
  7382. zmin: 0,
  7383. zmax: 0
  7384. }, cartorgraphicCenter, cartesianCenter);
  7385. }
  7386. function getObbSize(halfAxes) {
  7387. halfAxes.getColumn(0, scratchVector$1);
  7388. const axeY = halfAxes.getColumn(1);
  7389. const axeZ = halfAxes.getColumn(2);
  7390. const farthestVertex = scratchVector$1.add(axeY).add(axeZ);
  7391. const size = farthestVertex.len();
  7392. return size;
  7393. }
  7394. const TILE_CONTENT_STATE = {
  7395. UNLOADED: 0,
  7396. LOADING: 1,
  7397. PROCESSING: 2,
  7398. READY: 3,
  7399. EXPIRED: 4,
  7400. FAILED: 5
  7401. };
  7402. const TILE_REFINEMENT = {
  7403. ADD: 1,
  7404. REPLACE: 2
  7405. };
  7406. const TILE_TYPE = {
  7407. EMPTY: 'empty',
  7408. SCENEGRAPH: 'scenegraph',
  7409. POINTCLOUD: 'pointcloud',
  7410. MESH: 'mesh'
  7411. };
  7412. const TILESET_TYPE = {
  7413. I3S: 'I3S',
  7414. TILES3D: 'TILES3D'
  7415. };
  7416. const LOD_METRIC_TYPE = {
  7417. GEOMETRIC_ERROR: 'geometricError',
  7418. MAX_SCREEN_THRESHOLD: 'maxScreenThreshold'
  7419. };
  7420. const TILE3D_OPTIMIZATION_HINT = {
  7421. NOT_COMPUTED: -1,
  7422. USE_OPTIMIZATION: 1,
  7423. SKIP_OPTIMIZATION: 0
  7424. };
  7425. function defined$3(x) {
  7426. return x !== undefined && x !== null;
  7427. }
  7428. const scratchScale = new Vector3();
  7429. const scratchNorthWest = new Vector3();
  7430. const scratchSouthEast = new Vector3();
  7431. function createBoundingVolume(boundingVolumeHeader, transform, result) {
  7432. assert$7(boundingVolumeHeader, '3D Tile: boundingVolume must be defined');
  7433. if (boundingVolumeHeader.box) {
  7434. return createBox(boundingVolumeHeader.box, transform, result);
  7435. }
  7436. if (boundingVolumeHeader.region) {
  7437. const [west, south, east, north, minHeight, maxHeight] = boundingVolumeHeader.region;
  7438. const northWest = Ellipsoid.WGS84.cartographicToCartesian([degrees(west), degrees(north), minHeight], scratchNorthWest);
  7439. const southEast = Ellipsoid.WGS84.cartographicToCartesian([degrees(east), degrees(south), maxHeight], scratchSouthEast);
  7440. const centerInCartesian = new Vector3().addVectors(northWest, southEast).multiplyScalar(0.5);
  7441. const radius = new Vector3().subVectors(northWest, southEast).len() / 2.0;
  7442. return createSphere([centerInCartesian[0], centerInCartesian[1], centerInCartesian[2], radius], new Matrix4());
  7443. }
  7444. if (boundingVolumeHeader.sphere) {
  7445. return createSphere(boundingVolumeHeader.sphere, transform, result);
  7446. }
  7447. throw new Error('3D Tile: boundingVolume must contain a sphere, region, or box');
  7448. }
  7449. function createBox(box, transform, result) {
  7450. const center = new Vector3(box[0], box[1], box[2]);
  7451. transform.transform(center, center);
  7452. let origin = [];
  7453. if (box.length === 10) {
  7454. const halfSize = box.slice(3, 6);
  7455. const quaternion = new Quaternion();
  7456. quaternion.fromArray(box, 6);
  7457. const x = new Vector3([1, 0, 0]);
  7458. const y = new Vector3([0, 1, 0]);
  7459. const z = new Vector3([0, 0, 1]);
  7460. x.transformByQuaternion(quaternion);
  7461. x.scale(halfSize[0]);
  7462. y.transformByQuaternion(quaternion);
  7463. y.scale(halfSize[1]);
  7464. z.transformByQuaternion(quaternion);
  7465. z.scale(halfSize[2]);
  7466. origin = [...x.toArray(), ...y.toArray(), ...z.toArray()];
  7467. } else {
  7468. origin = [...box.slice(3, 6), ...box.slice(6, 9), ...box.slice(9, 12)];
  7469. }
  7470. const xAxis = transform.transformAsVector(origin.slice(0, 3));
  7471. const yAxis = transform.transformAsVector(origin.slice(3, 6));
  7472. const zAxis = transform.transformAsVector(origin.slice(6, 9));
  7473. const halfAxes = new Matrix3([xAxis[0], xAxis[1], xAxis[2], yAxis[0], yAxis[1], yAxis[2], zAxis[0], zAxis[1], zAxis[2]]);
  7474. if (defined$3(result)) {
  7475. result.center = center;
  7476. result.halfAxes = halfAxes;
  7477. return result;
  7478. }
  7479. return new OrientedBoundingBox(center, halfAxes);
  7480. }
  7481. function createSphere(sphere, transform, result) {
  7482. const center = new Vector3(sphere[0], sphere[1], sphere[2]);
  7483. transform.transform(center, center);
  7484. const scale = transform.getScale(scratchScale);
  7485. const uniformScale = Math.max(Math.max(scale[0], scale[1]), scale[2]);
  7486. const radius = sphere[3] * uniformScale;
  7487. if (defined$3(result)) {
  7488. result.center = center;
  7489. result.radius = radius;
  7490. return result;
  7491. }
  7492. return new BoundingSphere(center, radius);
  7493. }
  7494. new Vector3();
  7495. new Vector3();
  7496. new Matrix4();
  7497. new Vector3();
  7498. new Vector3();
  7499. new Vector3();
  7500. function fog(distanceToCamera, density) {
  7501. const scalar = distanceToCamera * density;
  7502. return 1.0 - Math.exp(-(scalar * scalar));
  7503. }
  7504. function getDynamicScreenSpaceError(tileset, distanceToCamera) {
  7505. if (tileset.dynamicScreenSpaceError && tileset.dynamicScreenSpaceErrorComputedDensity) {
  7506. const density = tileset.dynamicScreenSpaceErrorComputedDensity;
  7507. const factor = tileset.dynamicScreenSpaceErrorFactor;
  7508. const dynamicError = fog(distanceToCamera, density) * factor;
  7509. return dynamicError;
  7510. }
  7511. return 0;
  7512. }
  7513. function getTiles3DScreenSpaceError(tile, frameState, useParentLodMetric) {
  7514. const tileset = tile.tileset;
  7515. const parentLodMetricValue = tile.parent && tile.parent.lodMetricValue || tile.lodMetricValue;
  7516. const lodMetricValue = useParentLodMetric ? parentLodMetricValue : tile.lodMetricValue;
  7517. if (lodMetricValue === 0.0) {
  7518. return 0.0;
  7519. }
  7520. const distance = Math.max(tile._distanceToCamera, 1e-7);
  7521. const {
  7522. height,
  7523. sseDenominator
  7524. } = frameState;
  7525. const {
  7526. viewDistanceScale
  7527. } = tileset.options;
  7528. let error = lodMetricValue * height * (viewDistanceScale || 1.0) / (distance * sseDenominator);
  7529. error -= getDynamicScreenSpaceError(tileset, distance);
  7530. return error;
  7531. }
  7532. const cameraPositionCartesian = new Vector3();
  7533. const toEye = new Vector3();
  7534. const cameraPositionEnu = new Vector3();
  7535. const extraVertexEnu = new Vector3();
  7536. const projectedOriginVector = new Vector3();
  7537. const enuToCartesianMatrix = new Matrix4();
  7538. const cartesianToEnuMatrix = new Matrix4();
  7539. function getLodStatus(tile, frameState) {
  7540. if (tile.lodMetricValue === 0 || isNaN(tile.lodMetricValue)) {
  7541. return 'DIG';
  7542. }
  7543. const screenSize = 2 * getProjectedRadius(tile, frameState);
  7544. if (screenSize < 2) {
  7545. return 'OUT';
  7546. }
  7547. if (!tile.header.children || screenSize <= tile.lodMetricValue) {
  7548. return 'DRAW';
  7549. } else if (tile.header.children) {
  7550. return 'DIG';
  7551. }
  7552. return 'OUT';
  7553. }
  7554. function getProjectedRadius(tile, frameState) {
  7555. const {
  7556. topDownViewport: viewport
  7557. } = frameState;
  7558. const mbsLat = tile.header.mbs[1];
  7559. const mbsLon = tile.header.mbs[0];
  7560. const mbsZ = tile.header.mbs[2];
  7561. const mbsR = tile.header.mbs[3];
  7562. const mbsCenterCartesian = [...tile.boundingVolume.center];
  7563. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7564. Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, cameraPositionCartesian);
  7565. toEye.copy(cameraPositionCartesian).subtract(mbsCenterCartesian).normalize();
  7566. Ellipsoid.WGS84.eastNorthUpToFixedFrame(mbsCenterCartesian, enuToCartesianMatrix);
  7567. cartesianToEnuMatrix.copy(enuToCartesianMatrix).invert();
  7568. cameraPositionEnu.copy(cameraPositionCartesian).transform(cartesianToEnuMatrix);
  7569. const projection = Math.sqrt(cameraPositionEnu[0] * cameraPositionEnu[0] + cameraPositionEnu[1] * cameraPositionEnu[1]);
  7570. const extraZ = projection * projection / cameraPositionEnu[2];
  7571. extraVertexEnu.copy([cameraPositionEnu[0], cameraPositionEnu[1], extraZ]);
  7572. const extraVertexCartesian = extraVertexEnu.transform(enuToCartesianMatrix);
  7573. const extraVectorCartesian = extraVertexCartesian.subtract(mbsCenterCartesian).normalize();
  7574. const radiusVector = toEye.cross(extraVectorCartesian).normalize().scale(mbsR);
  7575. const sphereMbsBorderVertexCartesian = radiusVector.add(mbsCenterCartesian);
  7576. const sphereMbsBorderVertexCartographic = Ellipsoid.WGS84.cartesianToCartographic(sphereMbsBorderVertexCartesian);
  7577. const projectedOrigin = viewport.project([mbsLon, mbsLat, mbsZ]);
  7578. const projectedMbsBorderVertex = viewport.project(sphereMbsBorderVertexCartographic);
  7579. const projectedRadius = projectedOriginVector.copy(projectedOrigin).subtract(projectedMbsBorderVertex).magnitude();
  7580. return projectedRadius;
  7581. }
  7582. function get3dTilesOptions(tileset) {
  7583. return {
  7584. assetGltfUpAxis: tileset.asset && tileset.asset.gltfUpAxis || 'Y'
  7585. };
  7586. }
  7587. class ManagedArray {
  7588. constructor(length = 0) {
  7589. _defineProperty(this, "_map", new Map());
  7590. _defineProperty(this, "_array", void 0);
  7591. _defineProperty(this, "_length", void 0);
  7592. this._array = new Array(length);
  7593. this._length = length;
  7594. }
  7595. get length() {
  7596. return this._length;
  7597. }
  7598. set length(length) {
  7599. this._length = length;
  7600. if (length > this._array.length) {
  7601. this._array.length = length;
  7602. }
  7603. }
  7604. get values() {
  7605. return this._array;
  7606. }
  7607. get(index) {
  7608. assert$7(index < this._array.length);
  7609. return this._array[index];
  7610. }
  7611. set(index, element) {
  7612. assert$7(index >= 0);
  7613. if (index >= this.length) {
  7614. this.length = index + 1;
  7615. }
  7616. if (this._map.has(this._array[index])) {
  7617. this._map.delete(this._array[index]);
  7618. }
  7619. this._array[index] = element;
  7620. this._map.set(element, index);
  7621. }
  7622. delete(element) {
  7623. const index = this._map.get(element);
  7624. if (index >= 0) {
  7625. this._array.splice(index, 1);
  7626. this._map.delete(element);
  7627. this.length--;
  7628. }
  7629. }
  7630. peek() {
  7631. return this._array[this._length - 1];
  7632. }
  7633. push(element) {
  7634. if (!this._map.has(element)) {
  7635. const index = this.length++;
  7636. this._array[index] = element;
  7637. this._map.set(element, index);
  7638. }
  7639. }
  7640. pop() {
  7641. const element = this._array[--this.length];
  7642. this._map.delete(element);
  7643. return element;
  7644. }
  7645. reserve(length) {
  7646. assert$7(length >= 0);
  7647. if (length > this._array.length) {
  7648. this._array.length = length;
  7649. }
  7650. }
  7651. resize(length) {
  7652. assert$7(length >= 0);
  7653. this.length = length;
  7654. }
  7655. trim(length) {
  7656. if (length === null || length === undefined) {
  7657. length = this.length;
  7658. }
  7659. this._array.length = length;
  7660. }
  7661. reset() {
  7662. this._array = [];
  7663. this._map = new Map();
  7664. this._length = 0;
  7665. }
  7666. find(target) {
  7667. return this._map.has(target);
  7668. }
  7669. }
  7670. const DEFAULT_PROPS$1 = {
  7671. loadSiblings: false,
  7672. skipLevelOfDetail: false,
  7673. maximumScreenSpaceError: 2,
  7674. updateTransforms: true,
  7675. onTraversalEnd: () => {},
  7676. viewportTraversersMap: {},
  7677. basePath: ''
  7678. };
  7679. class TilesetTraverser {
  7680. get traversalFinished() {
  7681. return true;
  7682. }
  7683. constructor(options) {
  7684. _defineProperty(this, "options", void 0);
  7685. _defineProperty(this, "root", void 0);
  7686. _defineProperty(this, "requestedTiles", void 0);
  7687. _defineProperty(this, "selectedTiles", void 0);
  7688. _defineProperty(this, "emptyTiles", void 0);
  7689. _defineProperty(this, "lastUpdate", new Date().getTime());
  7690. _defineProperty(this, "updateDebounceTime", 1000);
  7691. _defineProperty(this, "_traversalStack", void 0);
  7692. _defineProperty(this, "_emptyTraversalStack", void 0);
  7693. _defineProperty(this, "_frameNumber", void 0);
  7694. this.options = { ...DEFAULT_PROPS$1,
  7695. ...options
  7696. };
  7697. this._traversalStack = new ManagedArray();
  7698. this._emptyTraversalStack = new ManagedArray();
  7699. this._frameNumber = null;
  7700. this.root = null;
  7701. this.selectedTiles = {};
  7702. this.requestedTiles = {};
  7703. this.emptyTiles = {};
  7704. }
  7705. traverse(root, frameState, options) {
  7706. this.root = root;
  7707. this.options = { ...this.options,
  7708. ...options
  7709. };
  7710. this.reset();
  7711. this.updateTile(root, frameState);
  7712. this._frameNumber = frameState.frameNumber;
  7713. this.executeTraversal(root, frameState);
  7714. }
  7715. reset() {
  7716. this.requestedTiles = {};
  7717. this.selectedTiles = {};
  7718. this.emptyTiles = {};
  7719. this._traversalStack.reset();
  7720. this._emptyTraversalStack.reset();
  7721. }
  7722. executeTraversal(root, frameState) {
  7723. const stack = this._traversalStack;
  7724. root._selectionDepth = 1;
  7725. stack.push(root);
  7726. while (stack.length > 0) {
  7727. const tile = stack.pop();
  7728. let shouldRefine = false;
  7729. if (this.canTraverse(tile, frameState)) {
  7730. this.updateChildTiles(tile, frameState);
  7731. shouldRefine = this.updateAndPushChildren(tile, frameState, stack, tile.hasRenderContent ? tile._selectionDepth + 1 : tile._selectionDepth);
  7732. }
  7733. const parent = tile.parent;
  7734. const parentRefines = Boolean(!parent || parent._shouldRefine);
  7735. const stoppedRefining = !shouldRefine;
  7736. if (!tile.hasRenderContent) {
  7737. this.emptyTiles[tile.id] = tile;
  7738. this.loadTile(tile, frameState);
  7739. if (stoppedRefining) {
  7740. this.selectTile(tile, frameState);
  7741. }
  7742. } else if (tile.refine === TILE_REFINEMENT.ADD) {
  7743. this.loadTile(tile, frameState);
  7744. this.selectTile(tile, frameState);
  7745. } else if (tile.refine === TILE_REFINEMENT.REPLACE) {
  7746. this.loadTile(tile, frameState);
  7747. if (stoppedRefining) {
  7748. this.selectTile(tile, frameState);
  7749. }
  7750. }
  7751. this.touchTile(tile, frameState);
  7752. tile._shouldRefine = shouldRefine && parentRefines;
  7753. }
  7754. const newTime = new Date().getTime();
  7755. if (this.traversalFinished || newTime - this.lastUpdate > this.updateDebounceTime) {
  7756. this.lastUpdate = newTime;
  7757. this.options.onTraversalEnd(frameState);
  7758. }
  7759. }
  7760. updateChildTiles(tile, frameState) {
  7761. const children = tile.children;
  7762. for (const child of children) {
  7763. this.updateTile(child, frameState);
  7764. }
  7765. return true;
  7766. }
  7767. updateAndPushChildren(tile, frameState, stack, depth) {
  7768. const {
  7769. loadSiblings,
  7770. skipLevelOfDetail
  7771. } = this.options;
  7772. const children = tile.children;
  7773. children.sort(this.compareDistanceToCamera.bind(this));
  7774. const checkRefines = tile.refine === TILE_REFINEMENT.REPLACE && tile.hasRenderContent && !skipLevelOfDetail;
  7775. let hasVisibleChild = false;
  7776. let refines = true;
  7777. for (const child of children) {
  7778. child._selectionDepth = depth;
  7779. if (child.isVisibleAndInRequestVolume) {
  7780. if (stack.find(child)) {
  7781. stack.delete(child);
  7782. }
  7783. stack.push(child);
  7784. hasVisibleChild = true;
  7785. } else if (checkRefines || loadSiblings) {
  7786. this.loadTile(child, frameState);
  7787. this.touchTile(child, frameState);
  7788. }
  7789. if (checkRefines) {
  7790. let childRefines;
  7791. if (!child._inRequestVolume) {
  7792. childRefines = false;
  7793. } else if (!child.hasRenderContent) {
  7794. childRefines = this.executeEmptyTraversal(child, frameState);
  7795. } else {
  7796. childRefines = child.contentAvailable;
  7797. }
  7798. refines = refines && childRefines;
  7799. if (!refines) {
  7800. return false;
  7801. }
  7802. }
  7803. }
  7804. if (!hasVisibleChild) {
  7805. refines = false;
  7806. }
  7807. return refines;
  7808. }
  7809. updateTile(tile, frameState) {
  7810. this.updateTileVisibility(tile, frameState);
  7811. }
  7812. selectTile(tile, frameState) {
  7813. if (this.shouldSelectTile(tile)) {
  7814. tile._selectedFrame = frameState.frameNumber;
  7815. this.selectedTiles[tile.id] = tile;
  7816. }
  7817. }
  7818. loadTile(tile, frameState) {
  7819. if (this.shouldLoadTile(tile)) {
  7820. tile._requestedFrame = frameState.frameNumber;
  7821. tile._priority = tile._getPriority();
  7822. this.requestedTiles[tile.id] = tile;
  7823. }
  7824. }
  7825. touchTile(tile, frameState) {
  7826. tile.tileset._cache.touch(tile);
  7827. tile._touchedFrame = frameState.frameNumber;
  7828. }
  7829. canTraverse(tile, frameState, useParentMetric = false, ignoreVisibility = false) {
  7830. if (!tile.hasChildren) {
  7831. return false;
  7832. }
  7833. if (tile.hasTilesetContent) {
  7834. return !tile.contentExpired;
  7835. }
  7836. if (!ignoreVisibility && !tile.isVisibleAndInRequestVolume) {
  7837. return false;
  7838. }
  7839. return this.shouldRefine(tile, frameState, useParentMetric);
  7840. }
  7841. shouldLoadTile(tile) {
  7842. return tile.hasUnloadedContent || tile.contentExpired;
  7843. }
  7844. shouldSelectTile(tile) {
  7845. return tile.contentAvailable && !this.options.skipLevelOfDetail;
  7846. }
  7847. shouldRefine(tile, frameState, useParentMetric) {
  7848. let screenSpaceError = tile._screenSpaceError;
  7849. if (useParentMetric) {
  7850. screenSpaceError = tile.getScreenSpaceError(frameState, true);
  7851. }
  7852. return screenSpaceError > this.options.maximumScreenSpaceError;
  7853. }
  7854. updateTileVisibility(tile, frameState) {
  7855. const viewportIds = [];
  7856. if (this.options.viewportTraversersMap) {
  7857. for (const key in this.options.viewportTraversersMap) {
  7858. const value = this.options.viewportTraversersMap[key];
  7859. if (value === frameState.viewport.id) {
  7860. viewportIds.push(key);
  7861. }
  7862. }
  7863. } else {
  7864. viewportIds.push(frameState.viewport.id);
  7865. }
  7866. tile.updateVisibility(frameState, viewportIds);
  7867. }
  7868. compareDistanceToCamera(b, a) {
  7869. return b._distanceToCamera - a._distanceToCamera;
  7870. }
  7871. anyChildrenVisible(tile, frameState) {
  7872. let anyVisible = false;
  7873. for (const child of tile.children) {
  7874. child.updateVisibility(frameState);
  7875. anyVisible = anyVisible || child.isVisibleAndInRequestVolume;
  7876. }
  7877. return anyVisible;
  7878. }
  7879. executeEmptyTraversal(root, frameState) {
  7880. let allDescendantsLoaded = true;
  7881. const stack = this._emptyTraversalStack;
  7882. stack.push(root);
  7883. while (stack.length > 0 && allDescendantsLoaded) {
  7884. const tile = stack.pop();
  7885. this.updateTile(tile, frameState);
  7886. if (!tile.isVisibleAndInRequestVolume) {
  7887. this.loadTile(tile, frameState);
  7888. }
  7889. this.touchTile(tile, frameState);
  7890. const traverse = !tile.hasRenderContent && this.canTraverse(tile, frameState, false, true);
  7891. if (traverse) {
  7892. const children = tile.children;
  7893. for (const child of children) {
  7894. if (stack.find(child)) {
  7895. stack.delete(child);
  7896. }
  7897. stack.push(child);
  7898. }
  7899. } else if (!tile.contentAvailable) {
  7900. allDescendantsLoaded = false;
  7901. }
  7902. }
  7903. return allDescendantsLoaded;
  7904. }
  7905. }
  7906. const scratchVector = new Vector3();
  7907. function defined$2(x) {
  7908. return x !== undefined && x !== null;
  7909. }
  7910. class TileHeader {
  7911. constructor(tileset, header, parentHeader, extendedId = '') {
  7912. _defineProperty(this, "tileset", void 0);
  7913. _defineProperty(this, "header", void 0);
  7914. _defineProperty(this, "id", void 0);
  7915. _defineProperty(this, "url", void 0);
  7916. _defineProperty(this, "parent", void 0);
  7917. _defineProperty(this, "refine", void 0);
  7918. _defineProperty(this, "type", void 0);
  7919. _defineProperty(this, "contentUrl", void 0);
  7920. _defineProperty(this, "lodMetricType", void 0);
  7921. _defineProperty(this, "lodMetricValue", void 0);
  7922. _defineProperty(this, "boundingVolume", void 0);
  7923. _defineProperty(this, "content", void 0);
  7924. _defineProperty(this, "contentState", void 0);
  7925. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  7926. _defineProperty(this, "children", void 0);
  7927. _defineProperty(this, "depth", void 0);
  7928. _defineProperty(this, "viewportIds", void 0);
  7929. _defineProperty(this, "transform", void 0);
  7930. _defineProperty(this, "extensions", void 0);
  7931. _defineProperty(this, "userData", void 0);
  7932. _defineProperty(this, "computedTransform", void 0);
  7933. _defineProperty(this, "hasEmptyContent", void 0);
  7934. _defineProperty(this, "hasTilesetContent", void 0);
  7935. _defineProperty(this, "traverser", void 0);
  7936. _defineProperty(this, "_cacheNode", void 0);
  7937. _defineProperty(this, "_frameNumber", void 0);
  7938. _defineProperty(this, "_lodJudge", void 0);
  7939. _defineProperty(this, "_expireDate", void 0);
  7940. _defineProperty(this, "_expiredContent", void 0);
  7941. _defineProperty(this, "_shouldRefine", void 0);
  7942. _defineProperty(this, "_distanceToCamera", void 0);
  7943. _defineProperty(this, "_centerZDepth", void 0);
  7944. _defineProperty(this, "_screenSpaceError", void 0);
  7945. _defineProperty(this, "_visibilityPlaneMask", void 0);
  7946. _defineProperty(this, "_visible", void 0);
  7947. _defineProperty(this, "_inRequestVolume", void 0);
  7948. _defineProperty(this, "_stackLength", void 0);
  7949. _defineProperty(this, "_selectionDepth", void 0);
  7950. _defineProperty(this, "_touchedFrame", void 0);
  7951. _defineProperty(this, "_visitedFrame", void 0);
  7952. _defineProperty(this, "_selectedFrame", void 0);
  7953. _defineProperty(this, "_requestedFrame", void 0);
  7954. _defineProperty(this, "_priority", void 0);
  7955. _defineProperty(this, "_contentBoundingVolume", void 0);
  7956. _defineProperty(this, "_viewerRequestVolume", void 0);
  7957. _defineProperty(this, "_initialTransform", void 0);
  7958. this.header = header;
  7959. this.tileset = tileset;
  7960. this.id = extendedId || header.id;
  7961. this.url = header.url;
  7962. this.parent = parentHeader;
  7963. this.refine = this._getRefine(header.refine);
  7964. this.type = header.type;
  7965. this.contentUrl = header.contentUrl;
  7966. this.lodMetricType = 'geometricError';
  7967. this.lodMetricValue = 0;
  7968. this.boundingVolume = null;
  7969. this.content = null;
  7970. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7971. this.gpuMemoryUsageInBytes = 0;
  7972. this.children = [];
  7973. this.hasEmptyContent = false;
  7974. this.hasTilesetContent = false;
  7975. this.depth = 0;
  7976. this.viewportIds = [];
  7977. this.userData = {};
  7978. this.extensions = null;
  7979. this._priority = 0;
  7980. this._touchedFrame = 0;
  7981. this._visitedFrame = 0;
  7982. this._selectedFrame = 0;
  7983. this._requestedFrame = 0;
  7984. this._screenSpaceError = 0;
  7985. this._cacheNode = null;
  7986. this._frameNumber = null;
  7987. this._cacheNode = null;
  7988. this.traverser = new TilesetTraverser({});
  7989. this._shouldRefine = false;
  7990. this._distanceToCamera = 0;
  7991. this._centerZDepth = 0;
  7992. this._visible = undefined;
  7993. this._inRequestVolume = false;
  7994. this._stackLength = 0;
  7995. this._selectionDepth = 0;
  7996. this._initialTransform = new Matrix4();
  7997. this.transform = new Matrix4();
  7998. this._initializeLodMetric(header);
  7999. this._initializeTransforms(header);
  8000. this._initializeBoundingVolumes(header);
  8001. this._initializeContent(header);
  8002. this._initializeRenderingState(header);
  8003. this._lodJudge = null;
  8004. this._expireDate = null;
  8005. this._expiredContent = null;
  8006. Object.seal(this);
  8007. }
  8008. destroy() {
  8009. this.header = null;
  8010. }
  8011. isDestroyed() {
  8012. return this.header === null;
  8013. }
  8014. get selected() {
  8015. return this._selectedFrame === this.tileset._frameNumber;
  8016. }
  8017. get isVisible() {
  8018. return this._visible;
  8019. }
  8020. get isVisibleAndInRequestVolume() {
  8021. return this._visible && this._inRequestVolume;
  8022. }
  8023. get hasRenderContent() {
  8024. return !this.hasEmptyContent && !this.hasTilesetContent;
  8025. }
  8026. get hasChildren() {
  8027. return this.children.length > 0 || this.header.children && this.header.children.length > 0;
  8028. }
  8029. get contentReady() {
  8030. return this.contentState === TILE_CONTENT_STATE.READY || this.hasEmptyContent;
  8031. }
  8032. get contentAvailable() {
  8033. return Boolean(this.contentReady && this.hasRenderContent || this._expiredContent && !this.contentFailed);
  8034. }
  8035. get hasUnloadedContent() {
  8036. return this.hasRenderContent && this.contentUnloaded;
  8037. }
  8038. get contentUnloaded() {
  8039. return this.contentState === TILE_CONTENT_STATE.UNLOADED;
  8040. }
  8041. get contentExpired() {
  8042. return this.contentState === TILE_CONTENT_STATE.EXPIRED;
  8043. }
  8044. get contentFailed() {
  8045. return this.contentState === TILE_CONTENT_STATE.FAILED;
  8046. }
  8047. getScreenSpaceError(frameState, useParentLodMetric) {
  8048. switch (this.tileset.type) {
  8049. case TILESET_TYPE.I3S:
  8050. return getProjectedRadius(this, frameState);
  8051. case TILESET_TYPE.TILES3D:
  8052. return getTiles3DScreenSpaceError(this, frameState, useParentLodMetric);
  8053. default:
  8054. throw new Error('Unsupported tileset type');
  8055. }
  8056. }
  8057. unselect() {
  8058. this._selectedFrame = 0;
  8059. }
  8060. _getPriority() {
  8061. const traverser = this.tileset._traverser;
  8062. const {
  8063. skipLevelOfDetail
  8064. } = traverser.options;
  8065. const maySkipTile = this.refine === TILE_REFINEMENT.ADD || skipLevelOfDetail;
  8066. if (maySkipTile && !this.isVisible && this._visible !== undefined) {
  8067. return -1;
  8068. }
  8069. if (this.tileset._frameNumber - this._touchedFrame >= 1) {
  8070. return -1;
  8071. }
  8072. if (this.contentState === TILE_CONTENT_STATE.UNLOADED) {
  8073. return -1;
  8074. }
  8075. const parent = this.parent;
  8076. const useParentScreenSpaceError = parent && (!maySkipTile || this._screenSpaceError === 0.0 || parent.hasTilesetContent);
  8077. const screenSpaceError = useParentScreenSpaceError ? parent._screenSpaceError : this._screenSpaceError;
  8078. const rootScreenSpaceError = traverser.root ? traverser.root._screenSpaceError : 0.0;
  8079. return Math.max(rootScreenSpaceError - screenSpaceError, 0);
  8080. }
  8081. async loadContent() {
  8082. if (this.hasEmptyContent) {
  8083. return false;
  8084. }
  8085. if (this.content) {
  8086. return true;
  8087. }
  8088. const expired = this.contentExpired;
  8089. if (expired) {
  8090. this._expireDate = null;
  8091. }
  8092. this.contentState = TILE_CONTENT_STATE.LOADING;
  8093. const requestToken = await this.tileset._requestScheduler.scheduleRequest(this.id, this._getPriority.bind(this));
  8094. if (!requestToken) {
  8095. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  8096. return false;
  8097. }
  8098. try {
  8099. const contentUrl = this.tileset.getTileUrl(this.contentUrl);
  8100. const loader = this.tileset.loader;
  8101. const options = { ...this.tileset.loadOptions,
  8102. [loader.id]: { ...this.tileset.loadOptions[loader.id],
  8103. isTileset: this.type === 'json',
  8104. ...this._getLoaderSpecificOptions(loader.id)
  8105. }
  8106. };
  8107. this.content = await load(contentUrl, loader, options);
  8108. if (this.tileset.options.contentLoader) {
  8109. await this.tileset.options.contentLoader(this);
  8110. }
  8111. if (this._isTileset()) {
  8112. this.tileset._initializeTileHeaders(this.content, this);
  8113. }
  8114. this.contentState = TILE_CONTENT_STATE.READY;
  8115. this._onContentLoaded();
  8116. return true;
  8117. } catch (error) {
  8118. this.contentState = TILE_CONTENT_STATE.FAILED;
  8119. throw error;
  8120. } finally {
  8121. requestToken.done();
  8122. }
  8123. }
  8124. unloadContent() {
  8125. if (this.content && this.content.destroy) {
  8126. this.content.destroy();
  8127. }
  8128. this.content = null;
  8129. if (this.header.content && this.header.content.destroy) {
  8130. this.header.content.destroy();
  8131. }
  8132. this.header.content = null;
  8133. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  8134. return true;
  8135. }
  8136. updateVisibility(frameState, viewportIds) {
  8137. if (this._frameNumber === frameState.frameNumber) {
  8138. return;
  8139. }
  8140. const parent = this.parent;
  8141. const parentVisibilityPlaneMask = parent ? parent._visibilityPlaneMask : CullingVolume.MASK_INDETERMINATE;
  8142. if (this.tileset._traverser.options.updateTransforms) {
  8143. const parentTransform = parent ? parent.computedTransform : this.tileset.modelMatrix;
  8144. this._updateTransform(parentTransform);
  8145. }
  8146. this._distanceToCamera = this.distanceToTile(frameState);
  8147. this._screenSpaceError = this.getScreenSpaceError(frameState, false);
  8148. this._visibilityPlaneMask = this.visibility(frameState, parentVisibilityPlaneMask);
  8149. this._visible = this._visibilityPlaneMask !== CullingVolume.MASK_OUTSIDE;
  8150. this._inRequestVolume = this.insideViewerRequestVolume(frameState);
  8151. this._frameNumber = frameState.frameNumber;
  8152. this.viewportIds = viewportIds;
  8153. }
  8154. visibility(frameState, parentVisibilityPlaneMask) {
  8155. const {
  8156. cullingVolume
  8157. } = frameState;
  8158. const {
  8159. boundingVolume
  8160. } = this;
  8161. return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume, parentVisibilityPlaneMask);
  8162. }
  8163. contentVisibility() {
  8164. return true;
  8165. }
  8166. distanceToTile(frameState) {
  8167. const boundingVolume = this.boundingVolume;
  8168. return Math.sqrt(Math.max(boundingVolume.distanceSquaredTo(frameState.camera.position), 0));
  8169. }
  8170. cameraSpaceZDepth({
  8171. camera
  8172. }) {
  8173. const boundingVolume = this.boundingVolume;
  8174. scratchVector.subVectors(boundingVolume.center, camera.position);
  8175. return camera.direction.dot(scratchVector);
  8176. }
  8177. insideViewerRequestVolume(frameState) {
  8178. const viewerRequestVolume = this._viewerRequestVolume;
  8179. return !viewerRequestVolume || viewerRequestVolume.distanceSquaredTo(frameState.camera.position) <= 0;
  8180. }
  8181. updateExpiration() {
  8182. if (defined$2(this._expireDate) && this.contentReady && !this.hasEmptyContent) {
  8183. const now = Date.now();
  8184. if (Date.lessThan(this._expireDate, now)) {
  8185. this.contentState = TILE_CONTENT_STATE.EXPIRED;
  8186. this._expiredContent = this.content;
  8187. }
  8188. }
  8189. }
  8190. get extras() {
  8191. return this.header.extras;
  8192. }
  8193. _initializeLodMetric(header) {
  8194. if ('lodMetricType' in header) {
  8195. this.lodMetricType = header.lodMetricType;
  8196. } else {
  8197. this.lodMetricType = this.parent && this.parent.lodMetricType || this.tileset.lodMetricType;
  8198. console.warn("3D Tile: Required prop lodMetricType is undefined. Using parent lodMetricType");
  8199. }
  8200. if ('lodMetricValue' in header) {
  8201. this.lodMetricValue = header.lodMetricValue;
  8202. } else {
  8203. this.lodMetricValue = this.parent && this.parent.lodMetricValue || this.tileset.lodMetricValue;
  8204. console.warn('3D Tile: Required prop lodMetricValue is undefined. Using parent lodMetricValue');
  8205. }
  8206. }
  8207. _initializeTransforms(tileHeader) {
  8208. this.transform = tileHeader.transform ? new Matrix4(tileHeader.transform) : new Matrix4();
  8209. const parent = this.parent;
  8210. const tileset = this.tileset;
  8211. const parentTransform = parent && parent.computedTransform ? parent.computedTransform.clone() : tileset.modelMatrix.clone();
  8212. this.computedTransform = new Matrix4(parentTransform).multiplyRight(this.transform);
  8213. const parentInitialTransform = parent && parent._initialTransform ? parent._initialTransform.clone() : new Matrix4();
  8214. this._initialTransform = new Matrix4(parentInitialTransform).multiplyRight(this.transform);
  8215. }
  8216. _initializeBoundingVolumes(tileHeader) {
  8217. this._contentBoundingVolume = null;
  8218. this._viewerRequestVolume = null;
  8219. this._updateBoundingVolume(tileHeader);
  8220. }
  8221. _initializeContent(tileHeader) {
  8222. this.content = {
  8223. _tileset: this.tileset,
  8224. _tile: this
  8225. };
  8226. this.hasEmptyContent = true;
  8227. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  8228. this.hasTilesetContent = false;
  8229. if (tileHeader.contentUrl) {
  8230. this.content = null;
  8231. this.hasEmptyContent = false;
  8232. }
  8233. }
  8234. _initializeRenderingState(header) {
  8235. this.depth = header.level || (this.parent ? this.parent.depth + 1 : 0);
  8236. this._shouldRefine = false;
  8237. this._distanceToCamera = 0;
  8238. this._centerZDepth = 0;
  8239. this._screenSpaceError = 0;
  8240. this._visibilityPlaneMask = CullingVolume.MASK_INDETERMINATE;
  8241. this._visible = undefined;
  8242. this._inRequestVolume = false;
  8243. this._stackLength = 0;
  8244. this._selectionDepth = 0;
  8245. this._frameNumber = 0;
  8246. this._touchedFrame = 0;
  8247. this._visitedFrame = 0;
  8248. this._selectedFrame = 0;
  8249. this._requestedFrame = 0;
  8250. this._priority = 0.0;
  8251. }
  8252. _getRefine(refine) {
  8253. return refine || this.parent && this.parent.refine || TILE_REFINEMENT.REPLACE;
  8254. }
  8255. _isTileset() {
  8256. return this.contentUrl.indexOf('.json') !== -1;
  8257. }
  8258. _onContentLoaded() {
  8259. switch (this.content && this.content.type) {
  8260. case 'vctr':
  8261. case 'geom':
  8262. this.tileset._traverser.disableSkipLevelOfDetail = true;
  8263. break;
  8264. }
  8265. if (this._isTileset()) {
  8266. this.hasTilesetContent = true;
  8267. }
  8268. }
  8269. _updateBoundingVolume(header) {
  8270. this.boundingVolume = createBoundingVolume(header.boundingVolume, this.computedTransform, this.boundingVolume);
  8271. const content = header.content;
  8272. if (!content) {
  8273. return;
  8274. }
  8275. if (content.boundingVolume) {
  8276. this._contentBoundingVolume = createBoundingVolume(content.boundingVolume, this.computedTransform, this._contentBoundingVolume);
  8277. }
  8278. if (header.viewerRequestVolume) {
  8279. this._viewerRequestVolume = createBoundingVolume(header.viewerRequestVolume, this.computedTransform, this._viewerRequestVolume);
  8280. }
  8281. }
  8282. _updateTransform(parentTransform = new Matrix4()) {
  8283. const computedTransform = parentTransform.clone().multiplyRight(this.transform);
  8284. const didTransformChange = !computedTransform.equals(this.computedTransform);
  8285. if (!didTransformChange) {
  8286. return;
  8287. }
  8288. this.computedTransform = computedTransform;
  8289. this._updateBoundingVolume(this.header);
  8290. }
  8291. _getLoaderSpecificOptions(loaderId) {
  8292. switch (loaderId) {
  8293. case 'i3s':
  8294. return { ...this.tileset.options.i3s,
  8295. tile: this.header,
  8296. tileset: this.tileset.tileset,
  8297. isTileHeader: false
  8298. };
  8299. case '3d-tiles':
  8300. case 'cesium-ion':
  8301. default:
  8302. return get3dTilesOptions(this.tileset.tileset);
  8303. }
  8304. }
  8305. }
  8306. class Tileset3DTraverser extends TilesetTraverser {
  8307. compareDistanceToCamera(a, b) {
  8308. return b._distanceToCamera === 0 && a._distanceToCamera === 0 ? b._centerZDepth - a._centerZDepth : b._distanceToCamera - a._distanceToCamera;
  8309. }
  8310. updateTileVisibility(tile, frameState) {
  8311. super.updateTileVisibility(tile, frameState);
  8312. if (!tile.isVisibleAndInRequestVolume) {
  8313. return;
  8314. }
  8315. const hasChildren = tile.children.length > 0;
  8316. if (tile.hasTilesetContent && hasChildren) {
  8317. const firstChild = tile.children[0];
  8318. this.updateTileVisibility(firstChild, frameState);
  8319. tile._visible = firstChild._visible;
  8320. return;
  8321. }
  8322. if (this.meetsScreenSpaceErrorEarly(tile, frameState)) {
  8323. tile._visible = false;
  8324. return;
  8325. }
  8326. const replace = tile.refine === TILE_REFINEMENT.REPLACE;
  8327. const useOptimization = tile._optimChildrenWithinParent === TILE3D_OPTIMIZATION_HINT.USE_OPTIMIZATION;
  8328. if (replace && useOptimization && hasChildren) {
  8329. if (!this.anyChildrenVisible(tile, frameState)) {
  8330. tile._visible = false;
  8331. return;
  8332. }
  8333. }
  8334. }
  8335. meetsScreenSpaceErrorEarly(tile, frameState) {
  8336. const {
  8337. parent
  8338. } = tile;
  8339. if (!parent || parent.hasTilesetContent || parent.refine !== TILE_REFINEMENT.ADD) {
  8340. return false;
  8341. }
  8342. return !this.shouldRefine(tile, frameState, true);
  8343. }
  8344. }
  8345. class I3SPendingTilesRegister {
  8346. constructor() {
  8347. _defineProperty(this, "frameNumberMap", new Map());
  8348. }
  8349. register(frameNumber) {
  8350. const oldCount = this.frameNumberMap.get(frameNumber) || 0;
  8351. this.frameNumberMap.set(frameNumber, oldCount + 1);
  8352. }
  8353. deregister(frameNumber) {
  8354. const oldCount = this.frameNumberMap.get(frameNumber) || 1;
  8355. this.frameNumberMap.set(frameNumber, oldCount - 1);
  8356. }
  8357. isZero(frameNumber) {
  8358. const count = this.frameNumberMap.get(frameNumber) || 0;
  8359. return count === 0;
  8360. }
  8361. }
  8362. const STATUS = {
  8363. REQUESTED: 'REQUESTED',
  8364. COMPLETED: 'COMPLETED',
  8365. ERROR: 'ERROR'
  8366. };
  8367. class I3STileManager {
  8368. constructor() {
  8369. _defineProperty(this, "_statusMap", void 0);
  8370. _defineProperty(this, "pendingTilesRegister", new I3SPendingTilesRegister());
  8371. this._statusMap = {};
  8372. }
  8373. add(request, key, callback, frameState) {
  8374. if (!this._statusMap[key]) {
  8375. const {
  8376. frameNumber
  8377. } = frameState;
  8378. this._statusMap[key] = {
  8379. request,
  8380. callback,
  8381. key,
  8382. frameState,
  8383. status: STATUS.REQUESTED
  8384. };
  8385. this.pendingTilesRegister.register(frameNumber);
  8386. request().then(data => {
  8387. this._statusMap[key].status = STATUS.COMPLETED;
  8388. const {
  8389. frameNumber: actualFrameNumber
  8390. } = this._statusMap[key].frameState;
  8391. this.pendingTilesRegister.deregister(actualFrameNumber);
  8392. this._statusMap[key].callback(data, frameState);
  8393. }).catch(error => {
  8394. this._statusMap[key].status = STATUS.ERROR;
  8395. const {
  8396. frameNumber: actualFrameNumber
  8397. } = this._statusMap[key].frameState;
  8398. this.pendingTilesRegister.deregister(actualFrameNumber);
  8399. callback(error);
  8400. });
  8401. }
  8402. }
  8403. update(key, frameState) {
  8404. if (this._statusMap[key]) {
  8405. this.pendingTilesRegister.deregister(this._statusMap[key].frameState.frameNumber);
  8406. this.pendingTilesRegister.register(frameState.frameNumber);
  8407. this._statusMap[key].frameState = frameState;
  8408. }
  8409. }
  8410. find(key) {
  8411. return this._statusMap[key];
  8412. }
  8413. hasPendingTiles(frameNumber) {
  8414. return !this.pendingTilesRegister.isZero(frameNumber);
  8415. }
  8416. }
  8417. class I3STilesetTraverser extends TilesetTraverser {
  8418. get traversalFinished() {
  8419. return !this._tileManager.hasPendingTiles(this._frameNumber || 0);
  8420. }
  8421. constructor(options) {
  8422. super(options);
  8423. _defineProperty(this, "_tileManager", void 0);
  8424. this._tileManager = new I3STileManager();
  8425. }
  8426. shouldRefine(tile, frameState) {
  8427. tile._lodJudge = getLodStatus(tile, frameState);
  8428. return tile._lodJudge === 'DIG';
  8429. }
  8430. updateChildTiles(tile, frameState) {
  8431. const children = tile.header.children || [];
  8432. const childTiles = tile.children;
  8433. const tileset = tile.tileset;
  8434. for (const child of children) {
  8435. const extendedId = "".concat(child.id, "-").concat(frameState.viewport.id);
  8436. const childTile = childTiles && childTiles.find(t => t.id === extendedId);
  8437. if (!childTile) {
  8438. let request = () => this._loadTile(child.id, tileset);
  8439. const cachedRequest = this._tileManager.find(extendedId);
  8440. if (!cachedRequest) {
  8441. if (tileset.tileset.nodePages) {
  8442. request = () => tileset.tileset.nodePagesTile.formTileFromNodePages(child.id);
  8443. }
  8444. this._tileManager.add(request, extendedId, header => this._onTileLoad(header, tile, extendedId), frameState);
  8445. } else {
  8446. this._tileManager.update(extendedId, frameState);
  8447. }
  8448. } else if (childTile) {
  8449. this.updateTile(childTile, frameState);
  8450. }
  8451. }
  8452. return false;
  8453. }
  8454. async _loadTile(nodeId, tileset) {
  8455. const {
  8456. loader
  8457. } = tileset;
  8458. const nodeUrl = tileset.getTileUrl("".concat(tileset.url, "/nodes/").concat(nodeId));
  8459. const options = { ...tileset.loadOptions,
  8460. i3s: { ...tileset.loadOptions.i3s,
  8461. isTileHeader: true,
  8462. loadContent: false
  8463. }
  8464. };
  8465. return await load(nodeUrl, loader, options);
  8466. }
  8467. _onTileLoad(header, tile, extendedId) {
  8468. const childTile = new TileHeader(tile.tileset, header, tile, extendedId);
  8469. tile.children.push(childTile);
  8470. const frameState = this._tileManager.find(childTile.id).frameState;
  8471. this.updateTile(childTile, frameState);
  8472. if (this._frameNumber === frameState.frameNumber && (this.traversalFinished || new Date().getTime() - this.lastUpdate > this.updateDebounceTime)) {
  8473. this.executeTraversal(childTile, frameState);
  8474. }
  8475. }
  8476. }
  8477. const DEFAULT_PROPS = {
  8478. description: '',
  8479. ellipsoid: Ellipsoid.WGS84,
  8480. modelMatrix: new Matrix4(),
  8481. throttleRequests: true,
  8482. maxRequests: 64,
  8483. maximumMemoryUsage: 32,
  8484. maximumTilesSelected: 0,
  8485. debounceTime: 0,
  8486. onTileLoad: () => {},
  8487. onTileUnload: () => {},
  8488. onTileError: () => {},
  8489. onTraversalComplete: selectedTiles => selectedTiles,
  8490. contentLoader: undefined,
  8491. viewDistanceScale: 1.0,
  8492. maximumScreenSpaceError: 8,
  8493. loadTiles: true,
  8494. updateTransforms: true,
  8495. viewportTraversersMap: null,
  8496. loadOptions: {
  8497. fetch: {}
  8498. },
  8499. attributions: [],
  8500. basePath: '',
  8501. i3s: {}
  8502. };
  8503. const TILES_TOTAL = 'Tiles In Tileset(s)';
  8504. const TILES_IN_MEMORY = 'Tiles In Memory';
  8505. const TILES_IN_VIEW = 'Tiles In View';
  8506. const TILES_RENDERABLE = 'Tiles To Render';
  8507. const TILES_LOADED = 'Tiles Loaded';
  8508. const TILES_LOADING = 'Tiles Loading';
  8509. const TILES_UNLOADED = 'Tiles Unloaded';
  8510. const TILES_LOAD_FAILED = 'Failed Tile Loads';
  8511. const POINTS_COUNT = 'Points/Vertices';
  8512. const TILES_GPU_MEMORY = 'Tile Memory Use';
  8513. class Tileset3D {
  8514. constructor(json, options) {
  8515. _defineProperty(this, "options", void 0);
  8516. _defineProperty(this, "loadOptions", void 0);
  8517. _defineProperty(this, "type", void 0);
  8518. _defineProperty(this, "tileset", void 0);
  8519. _defineProperty(this, "loader", void 0);
  8520. _defineProperty(this, "url", void 0);
  8521. _defineProperty(this, "basePath", void 0);
  8522. _defineProperty(this, "modelMatrix", void 0);
  8523. _defineProperty(this, "ellipsoid", void 0);
  8524. _defineProperty(this, "lodMetricType", void 0);
  8525. _defineProperty(this, "lodMetricValue", void 0);
  8526. _defineProperty(this, "refine", void 0);
  8527. _defineProperty(this, "root", void 0);
  8528. _defineProperty(this, "roots", void 0);
  8529. _defineProperty(this, "asset", void 0);
  8530. _defineProperty(this, "description", void 0);
  8531. _defineProperty(this, "properties", void 0);
  8532. _defineProperty(this, "extras", void 0);
  8533. _defineProperty(this, "attributions", void 0);
  8534. _defineProperty(this, "credits", void 0);
  8535. _defineProperty(this, "stats", void 0);
  8536. _defineProperty(this, "traverseCounter", void 0);
  8537. _defineProperty(this, "geometricError", void 0);
  8538. _defineProperty(this, "selectedTiles", void 0);
  8539. _defineProperty(this, "updatePromise", null);
  8540. _defineProperty(this, "tilesetInitializationPromise", void 0);
  8541. _defineProperty(this, "cartographicCenter", void 0);
  8542. _defineProperty(this, "cartesianCenter", void 0);
  8543. _defineProperty(this, "zoom", void 0);
  8544. _defineProperty(this, "boundingVolume", void 0);
  8545. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  8546. _defineProperty(this, "dynamicScreenSpaceErrorComputedDensity", void 0);
  8547. _defineProperty(this, "_traverser", void 0);
  8548. _defineProperty(this, "_cache", void 0);
  8549. _defineProperty(this, "_requestScheduler", void 0);
  8550. _defineProperty(this, "_frameNumber", void 0);
  8551. _defineProperty(this, "_queryParamsString", void 0);
  8552. _defineProperty(this, "_queryParams", void 0);
  8553. _defineProperty(this, "_extensionsUsed", void 0);
  8554. _defineProperty(this, "_tiles", void 0);
  8555. _defineProperty(this, "_pendingCount", void 0);
  8556. _defineProperty(this, "lastUpdatedVieports", void 0);
  8557. _defineProperty(this, "_requestedTiles", void 0);
  8558. _defineProperty(this, "_emptyTiles", void 0);
  8559. _defineProperty(this, "frameStateData", void 0);
  8560. _defineProperty(this, "maximumMemoryUsage", void 0);
  8561. assert$7(json);
  8562. this.options = { ...DEFAULT_PROPS,
  8563. ...options
  8564. };
  8565. this.tileset = json;
  8566. this.loader = json.loader;
  8567. this.type = json.type;
  8568. this.url = json.url;
  8569. this.basePath = json.basePath || dirname(this.url);
  8570. this.modelMatrix = this.options.modelMatrix;
  8571. this.ellipsoid = this.options.ellipsoid;
  8572. this.lodMetricType = json.lodMetricType;
  8573. this.lodMetricValue = json.lodMetricValue;
  8574. this.refine = json.root.refine;
  8575. this.loadOptions = this.options.loadOptions || {};
  8576. this.root = null;
  8577. this.roots = {};
  8578. this.cartographicCenter = null;
  8579. this.cartesianCenter = null;
  8580. this.zoom = 1;
  8581. this.boundingVolume = null;
  8582. this.traverseCounter = 0;
  8583. this.geometricError = 0;
  8584. this._traverser = this._initializeTraverser();
  8585. this._cache = new TilesetCache();
  8586. this._requestScheduler = new RequestScheduler({
  8587. throttleRequests: this.options.throttleRequests,
  8588. maxRequests: this.options.maxRequests
  8589. });
  8590. this._frameNumber = 0;
  8591. this._pendingCount = 0;
  8592. this._tiles = {};
  8593. this.selectedTiles = [];
  8594. this._emptyTiles = [];
  8595. this._requestedTiles = [];
  8596. this.frameStateData = {};
  8597. this.lastUpdatedVieports = null;
  8598. this._queryParams = {};
  8599. this._queryParamsString = '';
  8600. this.maximumMemoryUsage = this.options.maximumMemoryUsage || 32;
  8601. this.gpuMemoryUsageInBytes = 0;
  8602. this.stats = new Stats({
  8603. id: this.url
  8604. });
  8605. this._initializeStats();
  8606. this._extensionsUsed = undefined;
  8607. this.dynamicScreenSpaceErrorComputedDensity = 0.0;
  8608. this.extras = null;
  8609. this.asset = {};
  8610. this.credits = {};
  8611. this.description = this.options.description || '';
  8612. this.tilesetInitializationPromise = this._initializeTileSet(json);
  8613. }
  8614. destroy() {
  8615. this._destroy();
  8616. }
  8617. isLoaded() {
  8618. return this._pendingCount === 0 && this._frameNumber !== 0 && this._requestedTiles.length === 0;
  8619. }
  8620. get tiles() {
  8621. return Object.values(this._tiles);
  8622. }
  8623. get frameNumber() {
  8624. return this._frameNumber;
  8625. }
  8626. get queryParams() {
  8627. if (!this._queryParamsString) {
  8628. this._queryParamsString = getQueryParamString(this._queryParams);
  8629. }
  8630. return this._queryParamsString;
  8631. }
  8632. setProps(props) {
  8633. this.options = { ...this.options,
  8634. ...props
  8635. };
  8636. }
  8637. setOptions(options) {
  8638. this.options = { ...this.options,
  8639. ...options
  8640. };
  8641. }
  8642. getTileUrl(tilePath) {
  8643. const isDataUrl = tilePath.startsWith('data:');
  8644. if (isDataUrl) {
  8645. return tilePath;
  8646. }
  8647. return "".concat(tilePath).concat(this.queryParams);
  8648. }
  8649. hasExtension(extensionName) {
  8650. return Boolean(this._extensionsUsed && this._extensionsUsed.indexOf(extensionName) > -1);
  8651. }
  8652. update(viewports = null) {
  8653. this.tilesetInitializationPromise.then(() => {
  8654. if (!viewports && this.lastUpdatedVieports) {
  8655. viewports = this.lastUpdatedVieports;
  8656. } else {
  8657. this.lastUpdatedVieports = viewports;
  8658. }
  8659. this.doUpdate(viewports);
  8660. });
  8661. }
  8662. async selectTiles(viewports = null) {
  8663. await this.tilesetInitializationPromise;
  8664. if (viewports) {
  8665. this.lastUpdatedVieports = viewports;
  8666. }
  8667. if (!this.updatePromise) {
  8668. this.updatePromise = new Promise(resolve => {
  8669. setTimeout(() => {
  8670. this.doUpdate(this.lastUpdatedVieports);
  8671. resolve(this._frameNumber);
  8672. this.updatePromise = null;
  8673. }, this.options.debounceTime);
  8674. });
  8675. }
  8676. return this.updatePromise;
  8677. }
  8678. doUpdate(viewports = null) {
  8679. if ('loadTiles' in this.options && !this.options.loadTiles) {
  8680. return;
  8681. }
  8682. if (this.traverseCounter > 0) {
  8683. return;
  8684. }
  8685. if (!(viewports instanceof Array)) {
  8686. viewports = [viewports];
  8687. }
  8688. this._cache.reset();
  8689. this._frameNumber++;
  8690. this.traverseCounter = viewports.length;
  8691. const viewportsToTraverse = [];
  8692. for (const viewport of viewports) {
  8693. const id = viewport.id;
  8694. if (this._needTraverse(id)) {
  8695. viewportsToTraverse.push(id);
  8696. } else {
  8697. this.traverseCounter--;
  8698. }
  8699. }
  8700. for (const viewport of viewports) {
  8701. const id = viewport.id;
  8702. if (!this.roots[id]) {
  8703. this.roots[id] = this._initializeTileHeaders(this.tileset, null);
  8704. }
  8705. if (!viewportsToTraverse.includes(id)) {
  8706. continue;
  8707. }
  8708. const frameState = getFrameState(viewport, this._frameNumber);
  8709. this._traverser.traverse(this.roots[id], frameState, this.options);
  8710. }
  8711. }
  8712. _needTraverse(viewportId) {
  8713. let traverserId = viewportId;
  8714. if (this.options.viewportTraversersMap) {
  8715. traverserId = this.options.viewportTraversersMap[viewportId];
  8716. }
  8717. if (traverserId !== viewportId) {
  8718. return false;
  8719. }
  8720. return true;
  8721. }
  8722. _onTraversalEnd(frameState) {
  8723. const id = frameState.viewport.id;
  8724. if (!this.frameStateData[id]) {
  8725. this.frameStateData[id] = {
  8726. selectedTiles: [],
  8727. _requestedTiles: [],
  8728. _emptyTiles: []
  8729. };
  8730. }
  8731. const currentFrameStateData = this.frameStateData[id];
  8732. const selectedTiles = Object.values(this._traverser.selectedTiles);
  8733. const [filteredSelectedTiles, unselectedTiles] = limitSelectedTiles(selectedTiles, frameState, this.options.maximumTilesSelected);
  8734. currentFrameStateData.selectedTiles = filteredSelectedTiles;
  8735. for (const tile of unselectedTiles) {
  8736. tile.unselect();
  8737. }
  8738. currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);
  8739. currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);
  8740. this.traverseCounter--;
  8741. if (this.traverseCounter > 0) {
  8742. return;
  8743. }
  8744. this._updateTiles();
  8745. }
  8746. _updateTiles() {
  8747. this.selectedTiles = [];
  8748. this._requestedTiles = [];
  8749. this._emptyTiles = [];
  8750. for (const frameStateKey in this.frameStateData) {
  8751. const frameStateDataValue = this.frameStateData[frameStateKey];
  8752. this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);
  8753. this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);
  8754. this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);
  8755. }
  8756. this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);
  8757. for (const tile of this.selectedTiles) {
  8758. this._tiles[tile.id] = tile;
  8759. }
  8760. this._loadTiles();
  8761. this._unloadTiles();
  8762. this._updateStats();
  8763. }
  8764. _tilesChanged(oldSelectedTiles, selectedTiles) {
  8765. if (oldSelectedTiles.length !== selectedTiles.length) {
  8766. return true;
  8767. }
  8768. const set1 = new Set(oldSelectedTiles.map(t => t.id));
  8769. const set2 = new Set(selectedTiles.map(t => t.id));
  8770. let changed = oldSelectedTiles.filter(x => !set2.has(x.id)).length > 0;
  8771. changed = changed || selectedTiles.filter(x => !set1.has(x.id)).length > 0;
  8772. return changed;
  8773. }
  8774. _loadTiles() {
  8775. for (const tile of this._requestedTiles) {
  8776. if (tile.contentUnloaded) {
  8777. this._loadTile(tile);
  8778. }
  8779. }
  8780. }
  8781. _unloadTiles() {
  8782. this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));
  8783. }
  8784. _updateStats() {
  8785. let tilesRenderable = 0;
  8786. let pointsRenderable = 0;
  8787. for (const tile of this.selectedTiles) {
  8788. if (tile.contentAvailable && tile.content) {
  8789. tilesRenderable++;
  8790. if (tile.content.pointCount) {
  8791. pointsRenderable += tile.content.pointCount;
  8792. } else {
  8793. pointsRenderable += tile.content.vertexCount;
  8794. }
  8795. }
  8796. }
  8797. this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;
  8798. this.stats.get(TILES_RENDERABLE).count = tilesRenderable;
  8799. this.stats.get(POINTS_COUNT).count = pointsRenderable;
  8800. }
  8801. async _initializeTileSet(tilesetJson) {
  8802. if (this.type === TILESET_TYPE.I3S) {
  8803. this.calculateViewPropsI3S();
  8804. tilesetJson.root = await tilesetJson.root;
  8805. }
  8806. this.root = this._initializeTileHeaders(tilesetJson, null);
  8807. if (this.type === TILESET_TYPE.TILES3D) {
  8808. this._initializeTiles3DTileset(tilesetJson);
  8809. this.calculateViewPropsTiles3D();
  8810. }
  8811. if (this.type === TILESET_TYPE.I3S) {
  8812. this._initializeI3STileset();
  8813. }
  8814. }
  8815. calculateViewPropsI3S() {
  8816. var _this$tileset$store;
  8817. const fullExtent = this.tileset.fullExtent;
  8818. if (fullExtent) {
  8819. const {
  8820. xmin,
  8821. xmax,
  8822. ymin,
  8823. ymax,
  8824. zmin,
  8825. zmax
  8826. } = fullExtent;
  8827. this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, zmin + (zmax - zmin) / 2);
  8828. this.cartesianCenter = Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, new Vector3());
  8829. this.zoom = getZoomFromFullExtent(fullExtent, this.cartographicCenter, this.cartesianCenter);
  8830. return;
  8831. }
  8832. const extent = (_this$tileset$store = this.tileset.store) === null || _this$tileset$store === void 0 ? void 0 : _this$tileset$store.extent;
  8833. if (extent) {
  8834. const [xmin, ymin, xmax, ymax] = extent;
  8835. this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, 0);
  8836. this.cartesianCenter = Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, new Vector3());
  8837. this.zoom = getZoomFromExtent(extent, this.cartographicCenter, this.cartesianCenter);
  8838. return;
  8839. }
  8840. console.warn('Extent is not defined in the tileset header');
  8841. this.cartographicCenter = new Vector3();
  8842. this.zoom = 1;
  8843. return;
  8844. }
  8845. calculateViewPropsTiles3D() {
  8846. const root = this.root;
  8847. assert$7(root);
  8848. const {
  8849. center
  8850. } = root.boundingVolume;
  8851. if (!center) {
  8852. console.warn('center was not pre-calculated for the root tile');
  8853. this.cartographicCenter = new Vector3();
  8854. this.zoom = 1;
  8855. return;
  8856. }
  8857. this.cartographicCenter = Ellipsoid.WGS84.cartesianToCartographic(center, new Vector3());
  8858. this.cartesianCenter = center;
  8859. this.zoom = getZoomFromBoundingVolume(root.boundingVolume, this.cartographicCenter);
  8860. }
  8861. _initializeStats() {
  8862. this.stats.get(TILES_TOTAL);
  8863. this.stats.get(TILES_LOADING);
  8864. this.stats.get(TILES_IN_MEMORY);
  8865. this.stats.get(TILES_IN_VIEW);
  8866. this.stats.get(TILES_RENDERABLE);
  8867. this.stats.get(TILES_LOADED);
  8868. this.stats.get(TILES_UNLOADED);
  8869. this.stats.get(TILES_LOAD_FAILED);
  8870. this.stats.get(POINTS_COUNT, 'memory');
  8871. this.stats.get(TILES_GPU_MEMORY, 'memory');
  8872. }
  8873. _initializeTileHeaders(tilesetJson, parentTileHeader) {
  8874. const rootTile = new TileHeader(this, tilesetJson.root, parentTileHeader);
  8875. if (parentTileHeader) {
  8876. parentTileHeader.children.push(rootTile);
  8877. rootTile.depth = parentTileHeader.depth + 1;
  8878. }
  8879. if (this.type === TILESET_TYPE.TILES3D) {
  8880. const stack = [];
  8881. stack.push(rootTile);
  8882. while (stack.length > 0) {
  8883. const tile = stack.pop();
  8884. this.stats.get(TILES_TOTAL).incrementCount();
  8885. const children = tile.header.children || [];
  8886. for (const childHeader of children) {
  8887. const childTile = new TileHeader(this, childHeader, tile);
  8888. tile.children.push(childTile);
  8889. childTile.depth = tile.depth + 1;
  8890. stack.push(childTile);
  8891. }
  8892. }
  8893. }
  8894. return rootTile;
  8895. }
  8896. _initializeTraverser() {
  8897. let TraverserClass;
  8898. const type = this.type;
  8899. switch (type) {
  8900. case TILESET_TYPE.TILES3D:
  8901. TraverserClass = Tileset3DTraverser;
  8902. break;
  8903. case TILESET_TYPE.I3S:
  8904. TraverserClass = I3STilesetTraverser;
  8905. break;
  8906. default:
  8907. TraverserClass = TilesetTraverser;
  8908. }
  8909. return new TraverserClass({
  8910. basePath: this.basePath,
  8911. onTraversalEnd: this._onTraversalEnd.bind(this)
  8912. });
  8913. }
  8914. _destroyTileHeaders(parentTile) {
  8915. this._destroySubtree(parentTile);
  8916. }
  8917. async _loadTile(tile) {
  8918. let loaded;
  8919. try {
  8920. this._onStartTileLoading();
  8921. loaded = await tile.loadContent();
  8922. } catch (error) {
  8923. this._onTileLoadError(tile, error);
  8924. } finally {
  8925. this._onEndTileLoading();
  8926. this._onTileLoad(tile, loaded);
  8927. }
  8928. }
  8929. _onTileLoadError(tile, error) {
  8930. this.stats.get(TILES_LOAD_FAILED).incrementCount();
  8931. const message = error.message || error.toString();
  8932. const url = tile.url;
  8933. console.error("A 3D tile failed to load: ".concat(tile.url, " ").concat(message));
  8934. this.options.onTileError(tile, message, url);
  8935. }
  8936. _onTileLoad(tile, loaded) {
  8937. if (!loaded) {
  8938. return;
  8939. }
  8940. if (this.type === TILESET_TYPE.I3S) {
  8941. var _this$tileset, _this$tileset$nodePag;
  8942. const nodesInNodePages = ((_this$tileset = this.tileset) === null || _this$tileset === void 0 ? void 0 : (_this$tileset$nodePag = _this$tileset.nodePagesTile) === null || _this$tileset$nodePag === void 0 ? void 0 : _this$tileset$nodePag.nodesInNodePages) || 0;
  8943. this.stats.get(TILES_TOTAL).reset();
  8944. this.stats.get(TILES_TOTAL).addCount(nodesInNodePages);
  8945. }
  8946. if (tile && tile.content) {
  8947. calculateTransformProps(tile, tile.content);
  8948. }
  8949. this._addTileToCache(tile);
  8950. this.options.onTileLoad(tile);
  8951. }
  8952. _onStartTileLoading() {
  8953. this._pendingCount++;
  8954. this.stats.get(TILES_LOADING).incrementCount();
  8955. }
  8956. _onEndTileLoading() {
  8957. this._pendingCount--;
  8958. this.stats.get(TILES_LOADING).decrementCount();
  8959. }
  8960. _addTileToCache(tile) {
  8961. this._cache.add(this, tile, tileset => tileset._updateCacheStats(tile));
  8962. }
  8963. _updateCacheStats(tile) {
  8964. this.stats.get(TILES_LOADED).incrementCount();
  8965. this.stats.get(TILES_IN_MEMORY).incrementCount();
  8966. this.gpuMemoryUsageInBytes += tile.content.byteLength || 0;
  8967. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  8968. }
  8969. _unloadTile(tile) {
  8970. this.gpuMemoryUsageInBytes -= tile.content && tile.content.byteLength || 0;
  8971. this.stats.get(TILES_IN_MEMORY).decrementCount();
  8972. this.stats.get(TILES_UNLOADED).incrementCount();
  8973. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  8974. this.options.onTileUnload(tile);
  8975. tile.unloadContent();
  8976. }
  8977. _destroy() {
  8978. const stack = [];
  8979. if (this.root) {
  8980. stack.push(this.root);
  8981. }
  8982. while (stack.length > 0) {
  8983. const tile = stack.pop();
  8984. for (const child of tile.children) {
  8985. stack.push(child);
  8986. }
  8987. this._destroyTile(tile);
  8988. }
  8989. this.root = null;
  8990. }
  8991. _destroySubtree(tile) {
  8992. const root = tile;
  8993. const stack = [];
  8994. stack.push(root);
  8995. while (stack.length > 0) {
  8996. tile = stack.pop();
  8997. for (const child of tile.children) {
  8998. stack.push(child);
  8999. }
  9000. if (tile !== root) {
  9001. this._destroyTile(tile);
  9002. }
  9003. }
  9004. root.children = [];
  9005. }
  9006. _destroyTile(tile) {
  9007. this._cache.unloadTile(this, tile);
  9008. this._unloadTile(tile);
  9009. tile.destroy();
  9010. }
  9011. _initializeTiles3DTileset(tilesetJson) {
  9012. this.asset = tilesetJson.asset;
  9013. if (!this.asset) {
  9014. throw new Error('Tileset must have an asset property.');
  9015. }
  9016. if (this.asset.version !== '0.0' && this.asset.version !== '1.0') {
  9017. throw new Error('The tileset must be 3D Tiles version 0.0 or 1.0.');
  9018. }
  9019. if ('tilesetVersion' in this.asset) {
  9020. this._queryParams.v = this.asset.tilesetVersion;
  9021. }
  9022. this.credits = {
  9023. attributions: this.options.attributions || []
  9024. };
  9025. this.description = this.options.description || '';
  9026. this.properties = tilesetJson.properties;
  9027. this.geometricError = tilesetJson.geometricError;
  9028. this._extensionsUsed = tilesetJson.extensionsUsed;
  9029. this.extras = tilesetJson.extras;
  9030. }
  9031. _initializeI3STileset() {
  9032. if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) {
  9033. this._queryParams.token = this.loadOptions.i3s.token;
  9034. }
  9035. }
  9036. }
  9037. function getQueryParamString(queryParams) {
  9038. const queryParamStrings = [];
  9039. for (const key of Object.keys(queryParams)) {
  9040. queryParamStrings.push("".concat(key, "=").concat(queryParams[key]));
  9041. }
  9042. switch (queryParamStrings.length) {
  9043. case 0:
  9044. return '';
  9045. case 1:
  9046. return "?".concat(queryParamStrings[0]);
  9047. default:
  9048. return "?".concat(queryParamStrings.join('&'));
  9049. }
  9050. }
  9051. const VERSION$5 = "3.2.5" ;
  9052. const TILE3D_TYPE = {
  9053. COMPOSITE: 'cmpt',
  9054. POINT_CLOUD: 'pnts',
  9055. BATCHED_3D_MODEL: 'b3dm',
  9056. INSTANCED_3D_MODEL: 'i3dm',
  9057. GEOMETRY: 'geom',
  9058. VECTOR: 'vect',
  9059. GLTF: 'glTF'
  9060. };
  9061. function getStringFromArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  9062. assert$7(arrayBuffer instanceof ArrayBuffer);
  9063. const textDecoder = new TextDecoder('utf8');
  9064. const typedArray = new Uint8Array(arrayBuffer, byteOffset, byteLength);
  9065. const string = textDecoder.decode(typedArray);
  9066. return string;
  9067. }
  9068. function getMagicString$1(arrayBuffer, byteOffset = 0) {
  9069. const dataView = new DataView(arrayBuffer);
  9070. return "".concat(String.fromCharCode(dataView.getUint8(byteOffset + 0))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 1))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 2))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 3)));
  9071. }
  9072. const VERSION$4 = "3.2.5" ;
  9073. const DEFAULT_DRACO_OPTIONS = {
  9074. draco: {
  9075. decoderType: typeof WebAssembly === 'object' ? 'wasm' : 'js',
  9076. libraryPath: 'libs/',
  9077. extraAttributes: {},
  9078. attributeNameEntry: undefined
  9079. }
  9080. };
  9081. const DracoLoader$1 = {
  9082. name: 'Draco',
  9083. id: 'draco',
  9084. module: 'draco',
  9085. shapes: ['mesh'],
  9086. version: VERSION$4,
  9087. worker: true,
  9088. extensions: ['drc'],
  9089. mimeTypes: ['application/octet-stream'],
  9090. binary: true,
  9091. tests: ['DRACO'],
  9092. options: DEFAULT_DRACO_OPTIONS
  9093. };
  9094. function getMeshBoundingBox(attributes) {
  9095. let minX = Infinity;
  9096. let minY = Infinity;
  9097. let minZ = Infinity;
  9098. let maxX = -Infinity;
  9099. let maxY = -Infinity;
  9100. let maxZ = -Infinity;
  9101. const positions = attributes.POSITION ? attributes.POSITION.value : [];
  9102. const len = positions && positions.length;
  9103. for (let i = 0; i < len; i += 3) {
  9104. const x = positions[i];
  9105. const y = positions[i + 1];
  9106. const z = positions[i + 2];
  9107. minX = x < minX ? x : minX;
  9108. minY = y < minY ? y : minY;
  9109. minZ = z < minZ ? z : minZ;
  9110. maxX = x > maxX ? x : maxX;
  9111. maxY = y > maxY ? y : maxY;
  9112. maxZ = z > maxZ ? z : maxZ;
  9113. }
  9114. return [[minX, minY, minZ], [maxX, maxY, maxZ]];
  9115. }
  9116. function assert$3(condition, message) {
  9117. if (!condition) {
  9118. throw new Error(message || 'loader assertion failed.');
  9119. }
  9120. }
  9121. class Schema {
  9122. constructor(fields, metadata) {
  9123. _defineProperty(this, "fields", void 0);
  9124. _defineProperty(this, "metadata", void 0);
  9125. assert$3(Array.isArray(fields));
  9126. checkNames(fields);
  9127. this.fields = fields;
  9128. this.metadata = metadata || new Map();
  9129. }
  9130. compareTo(other) {
  9131. if (this.metadata !== other.metadata) {
  9132. return false;
  9133. }
  9134. if (this.fields.length !== other.fields.length) {
  9135. return false;
  9136. }
  9137. for (let i = 0; i < this.fields.length; ++i) {
  9138. if (!this.fields[i].compareTo(other.fields[i])) {
  9139. return false;
  9140. }
  9141. }
  9142. return true;
  9143. }
  9144. select(...columnNames) {
  9145. const nameMap = Object.create(null);
  9146. for (const name of columnNames) {
  9147. nameMap[name] = true;
  9148. }
  9149. const selectedFields = this.fields.filter(field => nameMap[field.name]);
  9150. return new Schema(selectedFields, this.metadata);
  9151. }
  9152. selectAt(...columnIndices) {
  9153. const selectedFields = columnIndices.map(index => this.fields[index]).filter(Boolean);
  9154. return new Schema(selectedFields, this.metadata);
  9155. }
  9156. assign(schemaOrFields) {
  9157. let fields;
  9158. let metadata = this.metadata;
  9159. if (schemaOrFields instanceof Schema) {
  9160. const otherSchema = schemaOrFields;
  9161. fields = otherSchema.fields;
  9162. metadata = mergeMaps(mergeMaps(new Map(), this.metadata), otherSchema.metadata);
  9163. } else {
  9164. fields = schemaOrFields;
  9165. }
  9166. const fieldMap = Object.create(null);
  9167. for (const field of this.fields) {
  9168. fieldMap[field.name] = field;
  9169. }
  9170. for (const field of fields) {
  9171. fieldMap[field.name] = field;
  9172. }
  9173. const mergedFields = Object.values(fieldMap);
  9174. return new Schema(mergedFields, metadata);
  9175. }
  9176. }
  9177. function checkNames(fields) {
  9178. const usedNames = {};
  9179. for (const field of fields) {
  9180. if (usedNames[field.name]) {
  9181. console.warn('Schema: duplicated field name', field.name, field);
  9182. }
  9183. usedNames[field.name] = true;
  9184. }
  9185. }
  9186. function mergeMaps(m1, m2) {
  9187. return new Map([...(m1 || new Map()), ...(m2 || new Map())]);
  9188. }
  9189. class Field {
  9190. constructor(name, type, nullable = false, metadata = new Map()) {
  9191. _defineProperty(this, "name", void 0);
  9192. _defineProperty(this, "type", void 0);
  9193. _defineProperty(this, "nullable", void 0);
  9194. _defineProperty(this, "metadata", void 0);
  9195. this.name = name;
  9196. this.type = type;
  9197. this.nullable = nullable;
  9198. this.metadata = metadata;
  9199. }
  9200. get typeId() {
  9201. return this.type && this.type.typeId;
  9202. }
  9203. clone() {
  9204. return new Field(this.name, this.type, this.nullable, this.metadata);
  9205. }
  9206. compareTo(other) {
  9207. return this.name === other.name && this.type === other.type && this.nullable === other.nullable && this.metadata === other.metadata;
  9208. }
  9209. toString() {
  9210. return "".concat(this.type).concat(this.nullable ? ', nullable' : '').concat(this.metadata ? ", metadata: ".concat(this.metadata) : '');
  9211. }
  9212. }
  9213. let Type;
  9214. (function (Type) {
  9215. Type[Type["NONE"] = 0] = "NONE";
  9216. Type[Type["Null"] = 1] = "Null";
  9217. Type[Type["Int"] = 2] = "Int";
  9218. Type[Type["Float"] = 3] = "Float";
  9219. Type[Type["Binary"] = 4] = "Binary";
  9220. Type[Type["Utf8"] = 5] = "Utf8";
  9221. Type[Type["Bool"] = 6] = "Bool";
  9222. Type[Type["Decimal"] = 7] = "Decimal";
  9223. Type[Type["Date"] = 8] = "Date";
  9224. Type[Type["Time"] = 9] = "Time";
  9225. Type[Type["Timestamp"] = 10] = "Timestamp";
  9226. Type[Type["Interval"] = 11] = "Interval";
  9227. Type[Type["List"] = 12] = "List";
  9228. Type[Type["Struct"] = 13] = "Struct";
  9229. Type[Type["Union"] = 14] = "Union";
  9230. Type[Type["FixedSizeBinary"] = 15] = "FixedSizeBinary";
  9231. Type[Type["FixedSizeList"] = 16] = "FixedSizeList";
  9232. Type[Type["Map"] = 17] = "Map";
  9233. Type[Type["Dictionary"] = -1] = "Dictionary";
  9234. Type[Type["Int8"] = -2] = "Int8";
  9235. Type[Type["Int16"] = -3] = "Int16";
  9236. Type[Type["Int32"] = -4] = "Int32";
  9237. Type[Type["Int64"] = -5] = "Int64";
  9238. Type[Type["Uint8"] = -6] = "Uint8";
  9239. Type[Type["Uint16"] = -7] = "Uint16";
  9240. Type[Type["Uint32"] = -8] = "Uint32";
  9241. Type[Type["Uint64"] = -9] = "Uint64";
  9242. Type[Type["Float16"] = -10] = "Float16";
  9243. Type[Type["Float32"] = -11] = "Float32";
  9244. Type[Type["Float64"] = -12] = "Float64";
  9245. Type[Type["DateDay"] = -13] = "DateDay";
  9246. Type[Type["DateMillisecond"] = -14] = "DateMillisecond";
  9247. Type[Type["TimestampSecond"] = -15] = "TimestampSecond";
  9248. Type[Type["TimestampMillisecond"] = -16] = "TimestampMillisecond";
  9249. Type[Type["TimestampMicrosecond"] = -17] = "TimestampMicrosecond";
  9250. Type[Type["TimestampNanosecond"] = -18] = "TimestampNanosecond";
  9251. Type[Type["TimeSecond"] = -19] = "TimeSecond";
  9252. Type[Type["TimeMillisecond"] = -20] = "TimeMillisecond";
  9253. Type[Type["TimeMicrosecond"] = -21] = "TimeMicrosecond";
  9254. Type[Type["TimeNanosecond"] = -22] = "TimeNanosecond";
  9255. Type[Type["DenseUnion"] = -23] = "DenseUnion";
  9256. Type[Type["SparseUnion"] = -24] = "SparseUnion";
  9257. Type[Type["IntervalDayTime"] = -25] = "IntervalDayTime";
  9258. Type[Type["IntervalYearMonth"] = -26] = "IntervalYearMonth";
  9259. })(Type || (Type = {}));
  9260. let _Symbol$toStringTag, _Symbol$toStringTag2, _Symbol$toStringTag7;
  9261. class DataType {
  9262. static isNull(x) {
  9263. return x && x.typeId === Type.Null;
  9264. }
  9265. static isInt(x) {
  9266. return x && x.typeId === Type.Int;
  9267. }
  9268. static isFloat(x) {
  9269. return x && x.typeId === Type.Float;
  9270. }
  9271. static isBinary(x) {
  9272. return x && x.typeId === Type.Binary;
  9273. }
  9274. static isUtf8(x) {
  9275. return x && x.typeId === Type.Utf8;
  9276. }
  9277. static isBool(x) {
  9278. return x && x.typeId === Type.Bool;
  9279. }
  9280. static isDecimal(x) {
  9281. return x && x.typeId === Type.Decimal;
  9282. }
  9283. static isDate(x) {
  9284. return x && x.typeId === Type.Date;
  9285. }
  9286. static isTime(x) {
  9287. return x && x.typeId === Type.Time;
  9288. }
  9289. static isTimestamp(x) {
  9290. return x && x.typeId === Type.Timestamp;
  9291. }
  9292. static isInterval(x) {
  9293. return x && x.typeId === Type.Interval;
  9294. }
  9295. static isList(x) {
  9296. return x && x.typeId === Type.List;
  9297. }
  9298. static isStruct(x) {
  9299. return x && x.typeId === Type.Struct;
  9300. }
  9301. static isUnion(x) {
  9302. return x && x.typeId === Type.Union;
  9303. }
  9304. static isFixedSizeBinary(x) {
  9305. return x && x.typeId === Type.FixedSizeBinary;
  9306. }
  9307. static isFixedSizeList(x) {
  9308. return x && x.typeId === Type.FixedSizeList;
  9309. }
  9310. static isMap(x) {
  9311. return x && x.typeId === Type.Map;
  9312. }
  9313. static isDictionary(x) {
  9314. return x && x.typeId === Type.Dictionary;
  9315. }
  9316. get typeId() {
  9317. return Type.NONE;
  9318. }
  9319. compareTo(other) {
  9320. return this === other;
  9321. }
  9322. }
  9323. _Symbol$toStringTag = Symbol.toStringTag;
  9324. class Int extends DataType {
  9325. constructor(isSigned, bitWidth) {
  9326. super();
  9327. _defineProperty(this, "isSigned", void 0);
  9328. _defineProperty(this, "bitWidth", void 0);
  9329. this.isSigned = isSigned;
  9330. this.bitWidth = bitWidth;
  9331. }
  9332. get typeId() {
  9333. return Type.Int;
  9334. }
  9335. get [_Symbol$toStringTag]() {
  9336. return 'Int';
  9337. }
  9338. toString() {
  9339. return "".concat(this.isSigned ? 'I' : 'Ui', "nt").concat(this.bitWidth);
  9340. }
  9341. }
  9342. class Int8 extends Int {
  9343. constructor() {
  9344. super(true, 8);
  9345. }
  9346. }
  9347. class Int16 extends Int {
  9348. constructor() {
  9349. super(true, 16);
  9350. }
  9351. }
  9352. class Int32 extends Int {
  9353. constructor() {
  9354. super(true, 32);
  9355. }
  9356. }
  9357. class Uint8 extends Int {
  9358. constructor() {
  9359. super(false, 8);
  9360. }
  9361. }
  9362. class Uint16 extends Int {
  9363. constructor() {
  9364. super(false, 16);
  9365. }
  9366. }
  9367. class Uint32 extends Int {
  9368. constructor() {
  9369. super(false, 32);
  9370. }
  9371. }
  9372. const Precision = {
  9373. HALF: 16,
  9374. SINGLE: 32,
  9375. DOUBLE: 64
  9376. };
  9377. _Symbol$toStringTag2 = Symbol.toStringTag;
  9378. class Float extends DataType {
  9379. constructor(precision) {
  9380. super();
  9381. _defineProperty(this, "precision", void 0);
  9382. this.precision = precision;
  9383. }
  9384. get typeId() {
  9385. return Type.Float;
  9386. }
  9387. get [_Symbol$toStringTag2]() {
  9388. return 'Float';
  9389. }
  9390. toString() {
  9391. return "Float".concat(this.precision);
  9392. }
  9393. }
  9394. class Float32 extends Float {
  9395. constructor() {
  9396. super(Precision.SINGLE);
  9397. }
  9398. }
  9399. class Float64 extends Float {
  9400. constructor() {
  9401. super(Precision.DOUBLE);
  9402. }
  9403. }
  9404. _Symbol$toStringTag7 = Symbol.toStringTag;
  9405. class FixedSizeList extends DataType {
  9406. constructor(listSize, child) {
  9407. super();
  9408. _defineProperty(this, "listSize", void 0);
  9409. _defineProperty(this, "children", void 0);
  9410. this.listSize = listSize;
  9411. this.children = [child];
  9412. }
  9413. get typeId() {
  9414. return Type.FixedSizeList;
  9415. }
  9416. get valueType() {
  9417. return this.children[0].type;
  9418. }
  9419. get valueField() {
  9420. return this.children[0];
  9421. }
  9422. get [_Symbol$toStringTag7]() {
  9423. return 'FixedSizeList';
  9424. }
  9425. toString() {
  9426. return "FixedSizeList[".concat(this.listSize, "]<").concat(this.valueType, ">");
  9427. }
  9428. }
  9429. function getArrowTypeFromTypedArray(array) {
  9430. switch (array.constructor) {
  9431. case Int8Array:
  9432. return new Int8();
  9433. case Uint8Array:
  9434. return new Uint8();
  9435. case Int16Array:
  9436. return new Int16();
  9437. case Uint16Array:
  9438. return new Uint16();
  9439. case Int32Array:
  9440. return new Int32();
  9441. case Uint32Array:
  9442. return new Uint32();
  9443. case Float32Array:
  9444. return new Float32();
  9445. case Float64Array:
  9446. return new Float64();
  9447. default:
  9448. throw new Error('array type not supported');
  9449. }
  9450. }
  9451. function deduceMeshField(attributeName, attribute, optionalMetadata) {
  9452. const type = getArrowTypeFromTypedArray(attribute.value);
  9453. const metadata = optionalMetadata ? optionalMetadata : makeMeshAttributeMetadata(attribute);
  9454. const field = new Field(attributeName, new FixedSizeList(attribute.size, new Field('value', type)), false, metadata);
  9455. return field;
  9456. }
  9457. function makeMeshAttributeMetadata(attribute) {
  9458. const result = new Map();
  9459. if ('byteOffset' in attribute) {
  9460. result.set('byteOffset', attribute.byteOffset.toString(10));
  9461. }
  9462. if ('byteStride' in attribute) {
  9463. result.set('byteStride', attribute.byteStride.toString(10));
  9464. }
  9465. if ('normalized' in attribute) {
  9466. result.set('normalized', attribute.normalized.toString());
  9467. }
  9468. return result;
  9469. }
  9470. function getDracoSchema(attributes, loaderData, indices) {
  9471. const metadataMap = makeMetadata(loaderData.metadata);
  9472. const fields = [];
  9473. const namedLoaderDataAttributes = transformAttributesLoaderData(loaderData.attributes);
  9474. for (const attributeName in attributes) {
  9475. const attribute = attributes[attributeName];
  9476. const field = getArrowFieldFromAttribute(attributeName, attribute, namedLoaderDataAttributes[attributeName]);
  9477. fields.push(field);
  9478. }
  9479. if (indices) {
  9480. const indicesField = getArrowFieldFromAttribute('indices', indices);
  9481. fields.push(indicesField);
  9482. }
  9483. return new Schema(fields, metadataMap);
  9484. }
  9485. function transformAttributesLoaderData(loaderData) {
  9486. const result = {};
  9487. for (const key in loaderData) {
  9488. const dracoAttribute = loaderData[key];
  9489. result[dracoAttribute.name || 'undefined'] = dracoAttribute;
  9490. }
  9491. return result;
  9492. }
  9493. function getArrowFieldFromAttribute(attributeName, attribute, loaderData) {
  9494. const metadataMap = loaderData ? makeMetadata(loaderData.metadata) : undefined;
  9495. const field = deduceMeshField(attributeName, attribute, metadataMap);
  9496. return field;
  9497. }
  9498. function makeMetadata(metadata) {
  9499. const metadataMap = new Map();
  9500. for (const key in metadata) {
  9501. metadataMap.set("".concat(key, ".string"), JSON.stringify(metadata[key]));
  9502. }
  9503. return metadataMap;
  9504. }
  9505. const DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP = {
  9506. POSITION: 'POSITION',
  9507. NORMAL: 'NORMAL',
  9508. COLOR: 'COLOR_0',
  9509. TEX_COORD: 'TEXCOORD_0'
  9510. };
  9511. const DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP = {
  9512. 1: Int8Array,
  9513. 2: Uint8Array,
  9514. 3: Int16Array,
  9515. 4: Uint16Array,
  9516. 5: Int32Array,
  9517. 6: Uint32Array,
  9518. 9: Float32Array
  9519. };
  9520. const INDEX_ITEM_SIZE = 4;
  9521. class DracoParser {
  9522. constructor(draco) {
  9523. _defineProperty(this, "draco", void 0);
  9524. _defineProperty(this, "decoder", void 0);
  9525. _defineProperty(this, "metadataQuerier", void 0);
  9526. this.draco = draco;
  9527. this.decoder = new this.draco.Decoder();
  9528. this.metadataQuerier = new this.draco.MetadataQuerier();
  9529. }
  9530. destroy() {
  9531. this.draco.destroy(this.decoder);
  9532. this.draco.destroy(this.metadataQuerier);
  9533. }
  9534. parseSync(arrayBuffer, options = {}) {
  9535. const buffer = new this.draco.DecoderBuffer();
  9536. buffer.Init(new Int8Array(arrayBuffer), arrayBuffer.byteLength);
  9537. this._disableAttributeTransforms(options);
  9538. const geometry_type = this.decoder.GetEncodedGeometryType(buffer);
  9539. const dracoGeometry = geometry_type === this.draco.TRIANGULAR_MESH ? new this.draco.Mesh() : new this.draco.PointCloud();
  9540. try {
  9541. let dracoStatus;
  9542. switch (geometry_type) {
  9543. case this.draco.TRIANGULAR_MESH:
  9544. dracoStatus = this.decoder.DecodeBufferToMesh(buffer, dracoGeometry);
  9545. break;
  9546. case this.draco.POINT_CLOUD:
  9547. dracoStatus = this.decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
  9548. break;
  9549. default:
  9550. throw new Error('DRACO: Unknown geometry type.');
  9551. }
  9552. if (!dracoStatus.ok() || !dracoGeometry.ptr) {
  9553. const message = "DRACO decompression failed: ".concat(dracoStatus.error_msg());
  9554. throw new Error(message);
  9555. }
  9556. const loaderData = this._getDracoLoaderData(dracoGeometry, geometry_type, options);
  9557. const geometry = this._getMeshData(dracoGeometry, loaderData, options);
  9558. const boundingBox = getMeshBoundingBox(geometry.attributes);
  9559. const schema = getDracoSchema(geometry.attributes, loaderData, geometry.indices);
  9560. const data = {
  9561. loader: 'draco',
  9562. loaderData,
  9563. header: {
  9564. vertexCount: dracoGeometry.num_points(),
  9565. boundingBox
  9566. },
  9567. ...geometry,
  9568. schema
  9569. };
  9570. return data;
  9571. } finally {
  9572. this.draco.destroy(buffer);
  9573. if (dracoGeometry) {
  9574. this.draco.destroy(dracoGeometry);
  9575. }
  9576. }
  9577. }
  9578. _getDracoLoaderData(dracoGeometry, geometry_type, options) {
  9579. const metadata = this._getTopLevelMetadata(dracoGeometry);
  9580. const attributes = this._getDracoAttributes(dracoGeometry, options);
  9581. return {
  9582. geometry_type,
  9583. num_attributes: dracoGeometry.num_attributes(),
  9584. num_points: dracoGeometry.num_points(),
  9585. num_faces: dracoGeometry instanceof this.draco.Mesh ? dracoGeometry.num_faces() : 0,
  9586. metadata,
  9587. attributes
  9588. };
  9589. }
  9590. _getDracoAttributes(dracoGeometry, options) {
  9591. const dracoAttributes = {};
  9592. for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {
  9593. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);
  9594. const metadata = this._getAttributeMetadata(dracoGeometry, attributeId);
  9595. dracoAttributes[dracoAttribute.unique_id()] = {
  9596. unique_id: dracoAttribute.unique_id(),
  9597. attribute_type: dracoAttribute.attribute_type(),
  9598. data_type: dracoAttribute.data_type(),
  9599. num_components: dracoAttribute.num_components(),
  9600. byte_offset: dracoAttribute.byte_offset(),
  9601. byte_stride: dracoAttribute.byte_stride(),
  9602. normalized: dracoAttribute.normalized(),
  9603. attribute_index: attributeId,
  9604. metadata
  9605. };
  9606. const quantization = this._getQuantizationTransform(dracoAttribute, options);
  9607. if (quantization) {
  9608. dracoAttributes[dracoAttribute.unique_id()].quantization_transform = quantization;
  9609. }
  9610. const octahedron = this._getOctahedronTransform(dracoAttribute, options);
  9611. if (octahedron) {
  9612. dracoAttributes[dracoAttribute.unique_id()].octahedron_transform = octahedron;
  9613. }
  9614. }
  9615. return dracoAttributes;
  9616. }
  9617. _getMeshData(dracoGeometry, loaderData, options) {
  9618. const attributes = this._getMeshAttributes(loaderData, dracoGeometry, options);
  9619. const positionAttribute = attributes.POSITION;
  9620. if (!positionAttribute) {
  9621. throw new Error('DRACO: No position attribute found.');
  9622. }
  9623. if (dracoGeometry instanceof this.draco.Mesh) {
  9624. switch (options.topology) {
  9625. case 'triangle-strip':
  9626. return {
  9627. topology: 'triangle-strip',
  9628. mode: 4,
  9629. attributes,
  9630. indices: {
  9631. value: this._getTriangleStripIndices(dracoGeometry),
  9632. size: 1
  9633. }
  9634. };
  9635. case 'triangle-list':
  9636. default:
  9637. return {
  9638. topology: 'triangle-list',
  9639. mode: 5,
  9640. attributes,
  9641. indices: {
  9642. value: this._getTriangleListIndices(dracoGeometry),
  9643. size: 1
  9644. }
  9645. };
  9646. }
  9647. }
  9648. return {
  9649. topology: 'point-list',
  9650. mode: 0,
  9651. attributes
  9652. };
  9653. }
  9654. _getMeshAttributes(loaderData, dracoGeometry, options) {
  9655. const attributes = {};
  9656. for (const loaderAttribute of Object.values(loaderData.attributes)) {
  9657. const attributeName = this._deduceAttributeName(loaderAttribute, options);
  9658. loaderAttribute.name = attributeName;
  9659. const {
  9660. value,
  9661. size
  9662. } = this._getAttributeValues(dracoGeometry, loaderAttribute);
  9663. attributes[attributeName] = {
  9664. value,
  9665. size,
  9666. byteOffset: loaderAttribute.byte_offset,
  9667. byteStride: loaderAttribute.byte_stride,
  9668. normalized: loaderAttribute.normalized
  9669. };
  9670. }
  9671. return attributes;
  9672. }
  9673. _getTriangleListIndices(dracoGeometry) {
  9674. const numFaces = dracoGeometry.num_faces();
  9675. const numIndices = numFaces * 3;
  9676. const byteLength = numIndices * INDEX_ITEM_SIZE;
  9677. const ptr = this.draco._malloc(byteLength);
  9678. try {
  9679. this.decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);
  9680. return new Uint32Array(this.draco.HEAPF32.buffer, ptr, numIndices).slice();
  9681. } finally {
  9682. this.draco._free(ptr);
  9683. }
  9684. }
  9685. _getTriangleStripIndices(dracoGeometry) {
  9686. const dracoArray = new this.draco.DracoInt32Array();
  9687. try {
  9688. this.decoder.GetTriangleStripsFromMesh(dracoGeometry, dracoArray);
  9689. return getUint32Array(dracoArray);
  9690. } finally {
  9691. this.draco.destroy(dracoArray);
  9692. }
  9693. }
  9694. _getAttributeValues(dracoGeometry, attribute) {
  9695. const TypedArrayCtor = DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP[attribute.data_type];
  9696. const numComponents = attribute.num_components;
  9697. const numPoints = dracoGeometry.num_points();
  9698. const numValues = numPoints * numComponents;
  9699. const byteLength = numValues * TypedArrayCtor.BYTES_PER_ELEMENT;
  9700. const dataType = getDracoDataType(this.draco, TypedArrayCtor);
  9701. let value;
  9702. const ptr = this.draco._malloc(byteLength);
  9703. try {
  9704. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attribute.attribute_index);
  9705. this.decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, dracoAttribute, dataType, byteLength, ptr);
  9706. value = new TypedArrayCtor(this.draco.HEAPF32.buffer, ptr, numValues).slice();
  9707. } finally {
  9708. this.draco._free(ptr);
  9709. }
  9710. return {
  9711. value,
  9712. size: numComponents
  9713. };
  9714. }
  9715. _deduceAttributeName(attribute, options) {
  9716. const uniqueId = attribute.unique_id;
  9717. for (const [attributeName, attributeUniqueId] of Object.entries(options.extraAttributes || {})) {
  9718. if (attributeUniqueId === uniqueId) {
  9719. return attributeName;
  9720. }
  9721. }
  9722. const thisAttributeType = attribute.attribute_type;
  9723. for (const dracoAttributeConstant in DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP) {
  9724. const attributeType = this.draco[dracoAttributeConstant];
  9725. if (attributeType === thisAttributeType) {
  9726. return DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP[dracoAttributeConstant];
  9727. }
  9728. }
  9729. const entryName = options.attributeNameEntry || 'name';
  9730. if (attribute.metadata[entryName]) {
  9731. return attribute.metadata[entryName].string;
  9732. }
  9733. return "CUSTOM_ATTRIBUTE_".concat(uniqueId);
  9734. }
  9735. _getTopLevelMetadata(dracoGeometry) {
  9736. const dracoMetadata = this.decoder.GetMetadata(dracoGeometry);
  9737. return this._getDracoMetadata(dracoMetadata);
  9738. }
  9739. _getAttributeMetadata(dracoGeometry, attributeId) {
  9740. const dracoMetadata = this.decoder.GetAttributeMetadata(dracoGeometry, attributeId);
  9741. return this._getDracoMetadata(dracoMetadata);
  9742. }
  9743. _getDracoMetadata(dracoMetadata) {
  9744. if (!dracoMetadata || !dracoMetadata.ptr) {
  9745. return {};
  9746. }
  9747. const result = {};
  9748. const numEntries = this.metadataQuerier.NumEntries(dracoMetadata);
  9749. for (let entryIndex = 0; entryIndex < numEntries; entryIndex++) {
  9750. const entryName = this.metadataQuerier.GetEntryName(dracoMetadata, entryIndex);
  9751. result[entryName] = this._getDracoMetadataField(dracoMetadata, entryName);
  9752. }
  9753. return result;
  9754. }
  9755. _getDracoMetadataField(dracoMetadata, entryName) {
  9756. const dracoArray = new this.draco.DracoInt32Array();
  9757. try {
  9758. this.metadataQuerier.GetIntEntryArray(dracoMetadata, entryName, dracoArray);
  9759. const intArray = getInt32Array(dracoArray);
  9760. return {
  9761. int: this.metadataQuerier.GetIntEntry(dracoMetadata, entryName),
  9762. string: this.metadataQuerier.GetStringEntry(dracoMetadata, entryName),
  9763. double: this.metadataQuerier.GetDoubleEntry(dracoMetadata, entryName),
  9764. intArray
  9765. };
  9766. } finally {
  9767. this.draco.destroy(dracoArray);
  9768. }
  9769. }
  9770. _disableAttributeTransforms(options) {
  9771. const {
  9772. quantizedAttributes = [],
  9773. octahedronAttributes = []
  9774. } = options;
  9775. const skipAttributes = [...quantizedAttributes, ...octahedronAttributes];
  9776. for (const dracoAttributeName of skipAttributes) {
  9777. this.decoder.SkipAttributeTransform(this.draco[dracoAttributeName]);
  9778. }
  9779. }
  9780. _getQuantizationTransform(dracoAttribute, options) {
  9781. const {
  9782. quantizedAttributes = []
  9783. } = options;
  9784. const attribute_type = dracoAttribute.attribute_type();
  9785. const skip = quantizedAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9786. if (skip) {
  9787. const transform = new this.draco.AttributeQuantizationTransform();
  9788. try {
  9789. if (transform.InitFromAttribute(dracoAttribute)) {
  9790. return {
  9791. quantization_bits: transform.quantization_bits(),
  9792. range: transform.range(),
  9793. min_values: new Float32Array([1, 2, 3]).map(i => transform.min_value(i))
  9794. };
  9795. }
  9796. } finally {
  9797. this.draco.destroy(transform);
  9798. }
  9799. }
  9800. return null;
  9801. }
  9802. _getOctahedronTransform(dracoAttribute, options) {
  9803. const {
  9804. octahedronAttributes = []
  9805. } = options;
  9806. const attribute_type = dracoAttribute.attribute_type();
  9807. const octahedron = octahedronAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9808. if (octahedron) {
  9809. const transform = new this.draco.AttributeQuantizationTransform();
  9810. try {
  9811. if (transform.InitFromAttribute(dracoAttribute)) {
  9812. return {
  9813. quantization_bits: transform.quantization_bits()
  9814. };
  9815. }
  9816. } finally {
  9817. this.draco.destroy(transform);
  9818. }
  9819. }
  9820. return null;
  9821. }
  9822. }
  9823. function getDracoDataType(draco, attributeType) {
  9824. switch (attributeType) {
  9825. case Float32Array:
  9826. return draco.DT_FLOAT32;
  9827. case Int8Array:
  9828. return draco.DT_INT8;
  9829. case Int16Array:
  9830. return draco.DT_INT16;
  9831. case Int32Array:
  9832. return draco.DT_INT32;
  9833. case Uint8Array:
  9834. return draco.DT_UINT8;
  9835. case Uint16Array:
  9836. return draco.DT_UINT16;
  9837. case Uint32Array:
  9838. return draco.DT_UINT32;
  9839. default:
  9840. return draco.DT_INVALID;
  9841. }
  9842. }
  9843. function getInt32Array(dracoArray) {
  9844. const numValues = dracoArray.size();
  9845. const intArray = new Int32Array(numValues);
  9846. for (let i = 0; i < numValues; i++) {
  9847. intArray[i] = dracoArray.GetValue(i);
  9848. }
  9849. return intArray;
  9850. }
  9851. function getUint32Array(dracoArray) {
  9852. const numValues = dracoArray.size();
  9853. const intArray = new Int32Array(numValues);
  9854. for (let i = 0; i < numValues; i++) {
  9855. intArray[i] = dracoArray.GetValue(i);
  9856. }
  9857. return intArray;
  9858. }
  9859. const DRACO_VERSION = '1.4.1';
  9860. const DRACO_JS_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.js");
  9861. const DRACO_WASM_WRAPPER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_wasm_wrapper.js");
  9862. const DRACO_WASM_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.wasm");
  9863. let loadDecoderPromise;
  9864. async function loadDracoDecoderModule(options) {
  9865. const modules = options.modules || {};
  9866. if (modules.draco3d) {
  9867. loadDecoderPromise = loadDecoderPromise || modules.draco3d.createDecoderModule({}).then(draco => {
  9868. return {
  9869. draco
  9870. };
  9871. });
  9872. } else {
  9873. loadDecoderPromise = loadDecoderPromise || loadDracoDecoder(options);
  9874. }
  9875. return await loadDecoderPromise;
  9876. }
  9877. async function loadDracoDecoder(options) {
  9878. let DracoDecoderModule;
  9879. let wasmBinary;
  9880. switch (options.draco && options.draco.decoderType) {
  9881. case 'js':
  9882. DracoDecoderModule = await loadLibrary(DRACO_JS_DECODER_URL, 'draco', options);
  9883. break;
  9884. case 'wasm':
  9885. default:
  9886. [DracoDecoderModule, wasmBinary] = await Promise.all([await loadLibrary(DRACO_WASM_WRAPPER_URL, 'draco', options), await loadLibrary(DRACO_WASM_DECODER_URL, 'draco', options)]);
  9887. }
  9888. DracoDecoderModule = DracoDecoderModule || globalThis.DracoDecoderModule;
  9889. return await initializeDracoDecoder(DracoDecoderModule, wasmBinary);
  9890. }
  9891. function initializeDracoDecoder(DracoDecoderModule, wasmBinary) {
  9892. const options = {};
  9893. if (wasmBinary) {
  9894. options.wasmBinary = wasmBinary;
  9895. }
  9896. return new Promise(resolve => {
  9897. DracoDecoderModule({ ...options,
  9898. onModuleLoaded: draco => resolve({
  9899. draco
  9900. })
  9901. });
  9902. });
  9903. }
  9904. ({
  9905. id: isBrowser$1 ? 'draco-writer' : 'draco-writer-nodejs',
  9906. name: 'Draco compressed geometry writer',
  9907. module: 'draco',
  9908. version: VERSION$4,
  9909. worker: true,
  9910. options: {
  9911. draco: {},
  9912. source: null
  9913. }
  9914. });
  9915. const DracoLoader = { ...DracoLoader$1,
  9916. parse: parse$2
  9917. };
  9918. async function parse$2(arrayBuffer, options) {
  9919. const {
  9920. draco
  9921. } = await loadDracoDecoderModule(options);
  9922. const dracoParser = new DracoParser(draco);
  9923. try {
  9924. return dracoParser.parseSync(arrayBuffer, options === null || options === void 0 ? void 0 : options.draco);
  9925. } finally {
  9926. dracoParser.destroy();
  9927. }
  9928. }
  9929. const GL_PRIMITIVE_MODE = {
  9930. POINTS: 0x0000,
  9931. LINES: 0x0001,
  9932. LINE_LOOP: 0x0002,
  9933. LINE_STRIP: 0x0003,
  9934. TRIANGLES: 0x0004,
  9935. TRIANGLE_STRIP: 0x0005,
  9936. TRIANGLE_FAN: 0x0006
  9937. };
  9938. const GL_TYPE = {
  9939. BYTE: 5120,
  9940. UNSIGNED_BYTE: 5121,
  9941. SHORT: 5122,
  9942. UNSIGNED_SHORT: 5123,
  9943. INT: 5124,
  9944. UNSIGNED_INT: 5125,
  9945. FLOAT: 5126,
  9946. DOUBLE: 5130
  9947. };
  9948. const GL$1 = { ...GL_PRIMITIVE_MODE,
  9949. ...GL_TYPE
  9950. };
  9951. const GL_TYPE_TO_ARRAY_TYPE = {
  9952. [GL_TYPE.DOUBLE]: Float64Array,
  9953. [GL_TYPE.FLOAT]: Float32Array,
  9954. [GL_TYPE.UNSIGNED_SHORT]: Uint16Array,
  9955. [GL_TYPE.UNSIGNED_INT]: Uint32Array,
  9956. [GL_TYPE.UNSIGNED_BYTE]: Uint8Array,
  9957. [GL_TYPE.BYTE]: Int8Array,
  9958. [GL_TYPE.SHORT]: Int16Array,
  9959. [GL_TYPE.INT]: Int32Array
  9960. };
  9961. const NAME_TO_GL_TYPE = {
  9962. DOUBLE: GL_TYPE.DOUBLE,
  9963. FLOAT: GL_TYPE.FLOAT,
  9964. UNSIGNED_SHORT: GL_TYPE.UNSIGNED_SHORT,
  9965. UNSIGNED_INT: GL_TYPE.UNSIGNED_INT,
  9966. UNSIGNED_BYTE: GL_TYPE.UNSIGNED_BYTE,
  9967. BYTE: GL_TYPE.BYTE,
  9968. SHORT: GL_TYPE.SHORT,
  9969. INT: GL_TYPE.INT
  9970. };
  9971. const ERR_TYPE_CONVERSION = 'Failed to convert GL type';
  9972. class GLType {
  9973. static fromTypedArray(arrayOrType) {
  9974. arrayOrType = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;
  9975. for (const glType in GL_TYPE_TO_ARRAY_TYPE) {
  9976. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  9977. if (ArrayType === arrayOrType) {
  9978. return glType;
  9979. }
  9980. }
  9981. throw new Error(ERR_TYPE_CONVERSION);
  9982. }
  9983. static fromName(name) {
  9984. const glType = NAME_TO_GL_TYPE[name];
  9985. if (!glType) {
  9986. throw new Error(ERR_TYPE_CONVERSION);
  9987. }
  9988. return glType;
  9989. }
  9990. static getArrayType(glType) {
  9991. switch (glType) {
  9992. case GL_TYPE.UNSIGNED_SHORT_5_6_5:
  9993. case GL_TYPE.UNSIGNED_SHORT_4_4_4_4:
  9994. case GL_TYPE.UNSIGNED_SHORT_5_5_5_1:
  9995. return Uint16Array;
  9996. default:
  9997. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  9998. if (!ArrayType) {
  9999. throw new Error(ERR_TYPE_CONVERSION);
  10000. }
  10001. return ArrayType;
  10002. }
  10003. }
  10004. static getByteSize(glType) {
  10005. const ArrayType = GLType.getArrayType(glType);
  10006. return ArrayType.BYTES_PER_ELEMENT;
  10007. }
  10008. static validate(glType) {
  10009. return Boolean(GLType.getArrayType(glType));
  10010. }
  10011. static createTypedArray(glType, buffer, byteOffset = 0, length) {
  10012. if (length === undefined) {
  10013. length = (buffer.byteLength - byteOffset) / GLType.getByteSize(glType);
  10014. }
  10015. const ArrayType = GLType.getArrayType(glType);
  10016. return new ArrayType(buffer, byteOffset, length);
  10017. }
  10018. }
  10019. function assert$2(condition, message) {
  10020. if (!condition) {
  10021. throw new Error("math.gl assertion failed. ".concat(message));
  10022. }
  10023. }
  10024. function decodeRGB565(rgb565, target = [0, 0, 0]) {
  10025. const r5 = rgb565 >> 11 & 31;
  10026. const g6 = rgb565 >> 5 & 63;
  10027. const b5 = rgb565 & 31;
  10028. target[0] = r5 << 3;
  10029. target[1] = g6 << 2;
  10030. target[2] = b5 << 3;
  10031. return target;
  10032. }
  10033. new Vector2();
  10034. new Vector3();
  10035. new Vector2();
  10036. new Vector2();
  10037. function fromSNorm(value, rangeMaximum = 255) {
  10038. return clamp(value, 0.0, rangeMaximum) / rangeMaximum * 2.0 - 1.0;
  10039. }
  10040. function signNotZero(value) {
  10041. return value < 0.0 ? -1.0 : 1.0;
  10042. }
  10043. function octDecodeInRange(x, y, rangeMax, result) {
  10044. assert$2(result);
  10045. if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
  10046. throw new Error("x and y must be unsigned normalized integers between 0 and ".concat(rangeMax));
  10047. }
  10048. result.x = fromSNorm(x, rangeMax);
  10049. result.y = fromSNorm(y, rangeMax);
  10050. result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));
  10051. if (result.z < 0.0) {
  10052. const oldVX = result.x;
  10053. result.x = (1.0 - Math.abs(result.y)) * signNotZero(oldVX);
  10054. result.y = (1.0 - Math.abs(oldVX)) * signNotZero(result.y);
  10055. }
  10056. return result.normalize();
  10057. }
  10058. function octDecode(x, y, result) {
  10059. return octDecodeInRange(x, y, 255, result);
  10060. }
  10061. class Tile3DFeatureTable {
  10062. constructor(featureTableJson, featureTableBinary) {
  10063. _defineProperty(this, "json", void 0);
  10064. _defineProperty(this, "buffer", void 0);
  10065. _defineProperty(this, "featuresLength", 0);
  10066. _defineProperty(this, "_cachedTypedArrays", {});
  10067. this.json = featureTableJson;
  10068. this.buffer = featureTableBinary;
  10069. }
  10070. getExtension(extensionName) {
  10071. return this.json.extensions && this.json.extensions[extensionName];
  10072. }
  10073. hasProperty(propertyName) {
  10074. return Boolean(this.json[propertyName]);
  10075. }
  10076. getGlobalProperty(propertyName, componentType = GL$1.UNSIGNED_INT, componentLength = 1) {
  10077. const jsonValue = this.json[propertyName];
  10078. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  10079. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, 1, jsonValue.byteOffset);
  10080. }
  10081. return jsonValue;
  10082. }
  10083. getPropertyArray(propertyName, componentType, componentLength) {
  10084. const jsonValue = this.json[propertyName];
  10085. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  10086. if ('componentType' in jsonValue) {
  10087. componentType = GLType.fromName(jsonValue.componentType);
  10088. }
  10089. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, this.featuresLength, jsonValue.byteOffset);
  10090. }
  10091. return this._getTypedArrayFromArray(propertyName, componentType, jsonValue);
  10092. }
  10093. getProperty(propertyName, componentType, componentLength, featureId, result) {
  10094. const jsonValue = this.json[propertyName];
  10095. if (!jsonValue) {
  10096. return jsonValue;
  10097. }
  10098. const typedArray = this.getPropertyArray(propertyName, componentType, componentLength);
  10099. if (componentLength === 1) {
  10100. return typedArray[featureId];
  10101. }
  10102. for (let i = 0; i < componentLength; ++i) {
  10103. result[i] = typedArray[componentLength * featureId + i];
  10104. }
  10105. return result;
  10106. }
  10107. _getTypedArrayFromBinary(propertyName, componentType, componentLength, count, byteOffset) {
  10108. const cachedTypedArrays = this._cachedTypedArrays;
  10109. let typedArray = cachedTypedArrays[propertyName];
  10110. if (!typedArray) {
  10111. typedArray = GLType.createTypedArray(componentType, this.buffer.buffer, this.buffer.byteOffset + byteOffset, count * componentLength);
  10112. cachedTypedArrays[propertyName] = typedArray;
  10113. }
  10114. return typedArray;
  10115. }
  10116. _getTypedArrayFromArray(propertyName, componentType, array) {
  10117. const cachedTypedArrays = this._cachedTypedArrays;
  10118. let typedArray = cachedTypedArrays[propertyName];
  10119. if (!typedArray) {
  10120. typedArray = GLType.createTypedArray(componentType, array);
  10121. cachedTypedArrays[propertyName] = typedArray;
  10122. }
  10123. return typedArray;
  10124. }
  10125. }
  10126. const COMPONENTS_PER_ATTRIBUTE = {
  10127. SCALAR: 1,
  10128. VEC2: 2,
  10129. VEC3: 3,
  10130. VEC4: 4,
  10131. MAT2: 4,
  10132. MAT3: 9,
  10133. MAT4: 16
  10134. };
  10135. const UNPACKER = {
  10136. SCALAR: (values, i) => values[i],
  10137. VEC2: (values, i) => [values[2 * i + 0], values[2 * i + 1]],
  10138. VEC3: (values, i) => [values[3 * i + 0], values[3 * i + 1], values[3 * i + 2]],
  10139. VEC4: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  10140. MAT2: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  10141. MAT3: (values, i) => [values[9 * i + 0], values[9 * i + 1], values[9 * i + 2], values[9 * i + 3], values[9 * i + 4], values[9 * i + 5], values[9 * i + 6], values[9 * i + 7], values[9 * i + 8]],
  10142. MAT4: (values, i) => [values[16 * i + 0], values[16 * i + 1], values[16 * i + 2], values[16 * i + 3], values[16 * i + 4], values[16 * i + 5], values[16 * i + 6], values[16 * i + 7], values[16 * i + 8], values[16 * i + 9], values[16 * i + 10], values[16 * i + 11], values[16 * i + 12], values[16 * i + 13], values[16 * i + 14], values[16 * i + 15]]
  10143. };
  10144. const PACKER = {
  10145. SCALAR: (x, values, i) => {
  10146. values[i] = x;
  10147. },
  10148. VEC2: (x, values, i) => {
  10149. values[2 * i + 0] = x[0];
  10150. values[2 * i + 1] = x[1];
  10151. },
  10152. VEC3: (x, values, i) => {
  10153. values[3 * i + 0] = x[0];
  10154. values[3 * i + 1] = x[1];
  10155. values[3 * i + 2] = x[2];
  10156. },
  10157. VEC4: (x, values, i) => {
  10158. values[4 * i + 0] = x[0];
  10159. values[4 * i + 1] = x[1];
  10160. values[4 * i + 2] = x[2];
  10161. values[4 * i + 3] = x[3];
  10162. },
  10163. MAT2: (x, values, i) => {
  10164. values[4 * i + 0] = x[0];
  10165. values[4 * i + 1] = x[1];
  10166. values[4 * i + 2] = x[2];
  10167. values[4 * i + 3] = x[3];
  10168. },
  10169. MAT3: (x, values, i) => {
  10170. values[9 * i + 0] = x[0];
  10171. values[9 * i + 1] = x[1];
  10172. values[9 * i + 2] = x[2];
  10173. values[9 * i + 3] = x[3];
  10174. values[9 * i + 4] = x[4];
  10175. values[9 * i + 5] = x[5];
  10176. values[9 * i + 6] = x[6];
  10177. values[9 * i + 7] = x[7];
  10178. values[9 * i + 8] = x[8];
  10179. values[9 * i + 9] = x[9];
  10180. },
  10181. MAT4: (x, values, i) => {
  10182. values[16 * i + 0] = x[0];
  10183. values[16 * i + 1] = x[1];
  10184. values[16 * i + 2] = x[2];
  10185. values[16 * i + 3] = x[3];
  10186. values[16 * i + 4] = x[4];
  10187. values[16 * i + 5] = x[5];
  10188. values[16 * i + 6] = x[6];
  10189. values[16 * i + 7] = x[7];
  10190. values[16 * i + 8] = x[8];
  10191. values[16 * i + 9] = x[9];
  10192. values[16 * i + 10] = x[10];
  10193. values[16 * i + 11] = x[11];
  10194. values[16 * i + 12] = x[12];
  10195. values[16 * i + 13] = x[13];
  10196. values[16 * i + 14] = x[14];
  10197. values[16 * i + 15] = x[15];
  10198. }
  10199. };
  10200. function createTypedArrayFromAccessor(tile3DAccessor, buffer, byteOffset, length) {
  10201. const {
  10202. componentType
  10203. } = tile3DAccessor;
  10204. assert$7(tile3DAccessor.componentType);
  10205. const type = typeof componentType === 'string' ? GLType.fromName(componentType) : componentType;
  10206. const size = COMPONENTS_PER_ATTRIBUTE[tile3DAccessor.type];
  10207. const unpacker = UNPACKER[tile3DAccessor.type];
  10208. const packer = PACKER[tile3DAccessor.type];
  10209. byteOffset += tile3DAccessor.byteOffset;
  10210. const values = GLType.createTypedArray(type, buffer, byteOffset, size * length);
  10211. return {
  10212. values,
  10213. type,
  10214. size,
  10215. unpacker,
  10216. packer
  10217. };
  10218. }
  10219. const defined$1 = x => x !== undefined;
  10220. function initializeHierarchy(batchTable, jsonHeader, binaryBody) {
  10221. if (!jsonHeader) {
  10222. return null;
  10223. }
  10224. let hierarchy = batchTable.getExtension('3DTILES_batch_table_hierarchy');
  10225. const legacyHierarchy = jsonHeader.HIERARCHY;
  10226. if (legacyHierarchy) {
  10227. console.warn('3D Tile Parser: HIERARCHY is deprecated. Use 3DTILES_batch_table_hierarchy.');
  10228. jsonHeader.extensions = jsonHeader.extensions || {};
  10229. jsonHeader.extensions['3DTILES_batch_table_hierarchy'] = legacyHierarchy;
  10230. hierarchy = legacyHierarchy;
  10231. }
  10232. if (!hierarchy) {
  10233. return null;
  10234. }
  10235. return initializeHierarchyValues(hierarchy, binaryBody);
  10236. }
  10237. function initializeHierarchyValues(hierarchyJson, binaryBody) {
  10238. let i;
  10239. let classId;
  10240. let binaryAccessor;
  10241. const instancesLength = hierarchyJson.instancesLength;
  10242. const classes = hierarchyJson.classes;
  10243. let classIds = hierarchyJson.classIds;
  10244. let parentCounts = hierarchyJson.parentCounts;
  10245. let parentIds = hierarchyJson.parentIds;
  10246. let parentIdsLength = instancesLength;
  10247. if (defined$1(classIds.byteOffset)) {
  10248. classIds.componentType = defaultValue(classIds.componentType, GL.UNSIGNED_SHORT);
  10249. classIds.type = AttributeType.SCALAR;
  10250. binaryAccessor = getBinaryAccessor(classIds);
  10251. classIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + classIds.byteOffset, instancesLength);
  10252. }
  10253. let parentIndexes;
  10254. if (defined$1(parentCounts)) {
  10255. if (defined$1(parentCounts.byteOffset)) {
  10256. parentCounts.componentType = defaultValue(parentCounts.componentType, GL.UNSIGNED_SHORT);
  10257. parentCounts.type = AttributeType.SCALAR;
  10258. binaryAccessor = getBinaryAccessor(parentCounts);
  10259. parentCounts = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentCounts.byteOffset, instancesLength);
  10260. }
  10261. parentIndexes = new Uint16Array(instancesLength);
  10262. parentIdsLength = 0;
  10263. for (i = 0; i < instancesLength; ++i) {
  10264. parentIndexes[i] = parentIdsLength;
  10265. parentIdsLength += parentCounts[i];
  10266. }
  10267. }
  10268. if (defined$1(parentIds) && defined$1(parentIds.byteOffset)) {
  10269. parentIds.componentType = defaultValue(parentIds.componentType, GL.UNSIGNED_SHORT);
  10270. parentIds.type = AttributeType.SCALAR;
  10271. binaryAccessor = getBinaryAccessor(parentIds);
  10272. parentIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentIds.byteOffset, parentIdsLength);
  10273. }
  10274. const classesLength = classes.length;
  10275. for (i = 0; i < classesLength; ++i) {
  10276. const classInstancesLength = classes[i].length;
  10277. const properties = classes[i].instances;
  10278. const binaryProperties = getBinaryProperties(classInstancesLength, properties, binaryBody);
  10279. classes[i].instances = combine(binaryProperties, properties);
  10280. }
  10281. const classCounts = new Array(classesLength).fill(0);
  10282. const classIndexes = new Uint16Array(instancesLength);
  10283. for (i = 0; i < instancesLength; ++i) {
  10284. classId = classIds[i];
  10285. classIndexes[i] = classCounts[classId];
  10286. ++classCounts[classId];
  10287. }
  10288. const hierarchy = {
  10289. classes,
  10290. classIds,
  10291. classIndexes,
  10292. parentCounts,
  10293. parentIndexes,
  10294. parentIds
  10295. };
  10296. validateHierarchy(hierarchy);
  10297. return hierarchy;
  10298. }
  10299. function traverseHierarchy(hierarchy, instanceIndex, endConditionCallback) {
  10300. if (!hierarchy) {
  10301. return;
  10302. }
  10303. const parentCounts = hierarchy.parentCounts;
  10304. const parentIds = hierarchy.parentIds;
  10305. if (parentIds) {
  10306. return endConditionCallback(hierarchy, instanceIndex);
  10307. }
  10308. if (parentCounts > 0) {
  10309. return traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback);
  10310. }
  10311. return traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback);
  10312. }
  10313. function traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback) {
  10314. const classIds = hierarchy.classIds;
  10315. const parentCounts = hierarchy.parentCounts;
  10316. const parentIds = hierarchy.parentIds;
  10317. const parentIndexes = hierarchy.parentIndexes;
  10318. const instancesLength = classIds.length;
  10319. const visited = scratchVisited;
  10320. visited.length = Math.max(visited.length, instancesLength);
  10321. const visitedMarker = ++marker;
  10322. const stack = scratchStack;
  10323. stack.length = 0;
  10324. stack.push(instanceIndex);
  10325. while (stack.length > 0) {
  10326. instanceIndex = stack.pop();
  10327. if (visited[instanceIndex] === visitedMarker) {
  10328. continue;
  10329. }
  10330. visited[instanceIndex] = visitedMarker;
  10331. const result = endConditionCallback(hierarchy, instanceIndex);
  10332. if (defined$1(result)) {
  10333. return result;
  10334. }
  10335. const parentCount = parentCounts[instanceIndex];
  10336. const parentIndex = parentIndexes[instanceIndex];
  10337. for (let i = 0; i < parentCount; ++i) {
  10338. const parentId = parentIds[parentIndex + i];
  10339. if (parentId !== instanceIndex) {
  10340. stack.push(parentId);
  10341. }
  10342. }
  10343. }
  10344. return null;
  10345. }
  10346. function traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback) {
  10347. let hasParent = true;
  10348. while (hasParent) {
  10349. const result = endConditionCallback(hierarchy, instanceIndex);
  10350. if (defined$1(result)) {
  10351. return result;
  10352. }
  10353. const parentId = hierarchy.parentIds[instanceIndex];
  10354. hasParent = parentId !== instanceIndex;
  10355. instanceIndex = parentId;
  10356. }
  10357. throw new Error('traverseHierarchySingleParent');
  10358. }
  10359. function validateHierarchy(hierarchy) {
  10360. const classIds = hierarchy.classIds;
  10361. const instancesLength = classIds.length;
  10362. for (let i = 0; i < instancesLength; ++i) {
  10363. validateInstance(hierarchy, i, stack);
  10364. }
  10365. }
  10366. function validateInstance(hierarchy, instanceIndex, stack) {
  10367. const parentCounts = hierarchy.parentCounts;
  10368. const parentIds = hierarchy.parentIds;
  10369. const parentIndexes = hierarchy.parentIndexes;
  10370. const classIds = hierarchy.classIds;
  10371. const instancesLength = classIds.length;
  10372. if (!defined$1(parentIds)) {
  10373. return;
  10374. }
  10375. assert(instanceIndex < instancesLength, "Parent index ".concat(instanceIndex, " exceeds the total number of instances: ").concat(instancesLength));
  10376. assert(stack.indexOf(instanceIndex) === -1, 'Circular dependency detected in the batch table hierarchy.');
  10377. stack.push(instanceIndex);
  10378. const parentCount = defined$1(parentCounts) ? parentCounts[instanceIndex] : 1;
  10379. const parentIndex = defined$1(parentCounts) ? parentIndexes[instanceIndex] : instanceIndex;
  10380. for (let i = 0; i < parentCount; ++i) {
  10381. const parentId = parentIds[parentIndex + i];
  10382. if (parentId !== instanceIndex) {
  10383. validateInstance(hierarchy, parentId, stack);
  10384. }
  10385. }
  10386. stack.pop(instanceIndex);
  10387. }
  10388. function defined(x) {
  10389. return x !== undefined && x !== null;
  10390. }
  10391. const clone = (x, y) => x;
  10392. const IGNORED_PROPERTY_FIELDS = {
  10393. HIERARCHY: true,
  10394. extensions: true,
  10395. extras: true
  10396. };
  10397. class Tile3DBatchTableParser {
  10398. constructor(json, binary, featureCount, options = {}) {
  10399. var _this$json;
  10400. _defineProperty(this, "json", void 0);
  10401. _defineProperty(this, "binary", void 0);
  10402. _defineProperty(this, "featureCount", void 0);
  10403. _defineProperty(this, "_extensions", void 0);
  10404. _defineProperty(this, "_properties", void 0);
  10405. _defineProperty(this, "_binaryProperties", void 0);
  10406. _defineProperty(this, "_hierarchy", void 0);
  10407. assert$7(featureCount >= 0);
  10408. this.json = json || {};
  10409. this.binary = binary;
  10410. this.featureCount = featureCount;
  10411. this._extensions = ((_this$json = this.json) === null || _this$json === void 0 ? void 0 : _this$json.extensions) || {};
  10412. this._properties = {};
  10413. for (const propertyName in this.json) {
  10414. if (!IGNORED_PROPERTY_FIELDS[propertyName]) {
  10415. this._properties[propertyName] = this.json[propertyName];
  10416. }
  10417. }
  10418. this._binaryProperties = this._initializeBinaryProperties();
  10419. if (options['3DTILES_batch_table_hierarchy']) {
  10420. this._hierarchy = initializeHierarchy(this, this.json, this.binary);
  10421. }
  10422. }
  10423. getExtension(extensionName) {
  10424. return this.json && this.json.extensions && this.json.extensions[extensionName];
  10425. }
  10426. memorySizeInBytes() {
  10427. return 0;
  10428. }
  10429. isClass(batchId, className) {
  10430. this._checkBatchId(batchId);
  10431. assert$7(typeof className === 'string', className);
  10432. if (this._hierarchy) {
  10433. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10434. const classId = hierarchy.classIds[instanceIndex];
  10435. const instanceClass = hierarchy.classes[classId];
  10436. return instanceClass.name === className;
  10437. });
  10438. return defined(result);
  10439. }
  10440. return false;
  10441. }
  10442. isExactClass(batchId, className) {
  10443. assert$7(typeof className === 'string', className);
  10444. return this.getExactClassName(batchId) === className;
  10445. }
  10446. getExactClassName(batchId) {
  10447. this._checkBatchId(batchId);
  10448. if (this._hierarchy) {
  10449. const classId = this._hierarchy.classIds[batchId];
  10450. const instanceClass = this._hierarchy.classes[classId];
  10451. return instanceClass.name;
  10452. }
  10453. return undefined;
  10454. }
  10455. hasProperty(batchId, name) {
  10456. this._checkBatchId(batchId);
  10457. assert$7(typeof name === 'string', name);
  10458. return defined(this._properties[name]) || this._hasPropertyInHierarchy(batchId, name);
  10459. }
  10460. getPropertyNames(batchId, results) {
  10461. this._checkBatchId(batchId);
  10462. results = defined(results) ? results : [];
  10463. results.length = 0;
  10464. const propertyNames = Object.keys(this._properties);
  10465. results.push(...propertyNames);
  10466. if (this._hierarchy) {
  10467. this._getPropertyNamesInHierarchy(batchId, results);
  10468. }
  10469. return results;
  10470. }
  10471. getProperty(batchId, name) {
  10472. this._checkBatchId(batchId);
  10473. assert$7(typeof name === 'string', name);
  10474. if (this._binaryProperties) {
  10475. const binaryProperty = this._binaryProperties[name];
  10476. if (defined(binaryProperty)) {
  10477. return this._getBinaryProperty(binaryProperty, batchId);
  10478. }
  10479. }
  10480. const propertyValues = this._properties[name];
  10481. if (defined(propertyValues)) {
  10482. return clone(propertyValues[batchId]);
  10483. }
  10484. if (this._hierarchy) {
  10485. const hierarchyProperty = this._getHierarchyProperty(batchId, name);
  10486. if (defined(hierarchyProperty)) {
  10487. return hierarchyProperty;
  10488. }
  10489. }
  10490. return undefined;
  10491. }
  10492. setProperty(batchId, name, value) {
  10493. const featureCount = this.featureCount;
  10494. this._checkBatchId(batchId);
  10495. assert$7(typeof name === 'string', name);
  10496. if (this._binaryProperties) {
  10497. const binaryProperty = this._binaryProperties[name];
  10498. if (binaryProperty) {
  10499. this._setBinaryProperty(binaryProperty, batchId, value);
  10500. return;
  10501. }
  10502. }
  10503. if (this._hierarchy) {
  10504. if (this._setHierarchyProperty(this, batchId, name, value)) {
  10505. return;
  10506. }
  10507. }
  10508. let propertyValues = this._properties[name];
  10509. if (!defined(propertyValues)) {
  10510. this._properties[name] = new Array(featureCount);
  10511. propertyValues = this._properties[name];
  10512. }
  10513. propertyValues[batchId] = clone(value);
  10514. }
  10515. _checkBatchId(batchId) {
  10516. const valid = batchId >= 0 && batchId < this.featureCount;
  10517. if (!valid) {
  10518. throw new Error('batchId not in range [0, featureCount - 1].');
  10519. }
  10520. }
  10521. _getBinaryProperty(binaryProperty, index) {
  10522. return binaryProperty.unpack(binaryProperty.typedArray, index);
  10523. }
  10524. _setBinaryProperty(binaryProperty, index, value) {
  10525. binaryProperty.pack(value, binaryProperty.typedArray, index);
  10526. }
  10527. _initializeBinaryProperties() {
  10528. let binaryProperties = null;
  10529. for (const name in this._properties) {
  10530. const property = this._properties[name];
  10531. const binaryProperty = this._initializeBinaryProperty(name, property);
  10532. if (binaryProperty) {
  10533. binaryProperties = binaryProperties || {};
  10534. binaryProperties[name] = binaryProperty;
  10535. }
  10536. }
  10537. return binaryProperties;
  10538. }
  10539. _initializeBinaryProperty(name, property) {
  10540. if ('byteOffset' in property) {
  10541. const tile3DAccessor = property;
  10542. assert$7(this.binary, "Property ".concat(name, " requires a batch table binary."));
  10543. assert$7(tile3DAccessor.type, "Property ".concat(name, " requires a type."));
  10544. const accessor = createTypedArrayFromAccessor(tile3DAccessor, this.binary.buffer, this.binary.byteOffset | 0, this.featureCount);
  10545. return {
  10546. typedArray: accessor.values,
  10547. componentCount: accessor.size,
  10548. unpack: accessor.unpacker,
  10549. pack: accessor.packer
  10550. };
  10551. }
  10552. return null;
  10553. }
  10554. _hasPropertyInHierarchy(batchId, name) {
  10555. if (!this._hierarchy) {
  10556. return false;
  10557. }
  10558. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10559. const classId = hierarchy.classIds[instanceIndex];
  10560. const instances = hierarchy.classes[classId].instances;
  10561. return defined(instances[name]);
  10562. });
  10563. return defined(result);
  10564. }
  10565. _getPropertyNamesInHierarchy(batchId, results) {
  10566. traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10567. const classId = hierarchy.classIds[instanceIndex];
  10568. const instances = hierarchy.classes[classId].instances;
  10569. for (const name in instances) {
  10570. if (instances.hasOwnProperty(name)) {
  10571. if (results.indexOf(name) === -1) {
  10572. results.push(name);
  10573. }
  10574. }
  10575. }
  10576. });
  10577. }
  10578. _getHierarchyProperty(batchId, name) {
  10579. return traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10580. const classId = hierarchy.classIds[instanceIndex];
  10581. const instanceClass = hierarchy.classes[classId];
  10582. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10583. const propertyValues = instanceClass.instances[name];
  10584. if (defined(propertyValues)) {
  10585. if (defined(propertyValues.typedArray)) {
  10586. return this._getBinaryProperty(propertyValues, indexInClass);
  10587. }
  10588. return clone(propertyValues[indexInClass]);
  10589. }
  10590. return null;
  10591. });
  10592. }
  10593. _setHierarchyProperty(batchTable, batchId, name, value) {
  10594. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10595. const classId = hierarchy.classIds[instanceIndex];
  10596. const instanceClass = hierarchy.classes[classId];
  10597. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10598. const propertyValues = instanceClass.instances[name];
  10599. if (defined(propertyValues)) {
  10600. assert$7(instanceIndex === batchId, "Inherited property \"".concat(name, "\" is read-only."));
  10601. if (defined(propertyValues.typedArray)) {
  10602. this._setBinaryProperty(propertyValues, indexInClass, value);
  10603. } else {
  10604. propertyValues[indexInClass] = clone(value);
  10605. }
  10606. return true;
  10607. }
  10608. return false;
  10609. });
  10610. return defined(result);
  10611. }
  10612. }
  10613. const SIZEOF_UINT32$1 = 4;
  10614. function parse3DTileHeaderSync(tile, arrayBuffer, byteOffset = 0) {
  10615. const view = new DataView(arrayBuffer);
  10616. tile.magic = view.getUint32(byteOffset, true);
  10617. byteOffset += SIZEOF_UINT32$1;
  10618. tile.version = view.getUint32(byteOffset, true);
  10619. byteOffset += SIZEOF_UINT32$1;
  10620. tile.byteLength = view.getUint32(byteOffset, true);
  10621. byteOffset += SIZEOF_UINT32$1;
  10622. if (tile.version !== 1) {
  10623. throw new Error("3D Tile Version ".concat(tile.version, " not supported"));
  10624. }
  10625. return byteOffset;
  10626. }
  10627. const SIZEOF_UINT32 = 4;
  10628. const DEPRECATION_WARNING = 'b3dm tile in legacy format.';
  10629. function parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset) {
  10630. const view = new DataView(arrayBuffer);
  10631. let batchLength;
  10632. tile.header = tile.header || {};
  10633. let featureTableJsonByteLength = view.getUint32(byteOffset, true);
  10634. byteOffset += SIZEOF_UINT32;
  10635. let featureTableBinaryByteLength = view.getUint32(byteOffset, true);
  10636. byteOffset += SIZEOF_UINT32;
  10637. let batchTableJsonByteLength = view.getUint32(byteOffset, true);
  10638. byteOffset += SIZEOF_UINT32;
  10639. let batchTableBinaryByteLength = view.getUint32(byteOffset, true);
  10640. byteOffset += SIZEOF_UINT32;
  10641. if (batchTableJsonByteLength >= 570425344) {
  10642. byteOffset -= SIZEOF_UINT32 * 2;
  10643. batchLength = featureTableJsonByteLength;
  10644. batchTableJsonByteLength = featureTableBinaryByteLength;
  10645. batchTableBinaryByteLength = 0;
  10646. featureTableJsonByteLength = 0;
  10647. featureTableBinaryByteLength = 0;
  10648. console.warn(DEPRECATION_WARNING);
  10649. } else if (batchTableBinaryByteLength >= 570425344) {
  10650. byteOffset -= SIZEOF_UINT32;
  10651. batchLength = batchTableJsonByteLength;
  10652. batchTableJsonByteLength = featureTableJsonByteLength;
  10653. batchTableBinaryByteLength = featureTableBinaryByteLength;
  10654. featureTableJsonByteLength = 0;
  10655. featureTableBinaryByteLength = 0;
  10656. console.warn(DEPRECATION_WARNING);
  10657. }
  10658. tile.header.featureTableJsonByteLength = featureTableJsonByteLength;
  10659. tile.header.featureTableBinaryByteLength = featureTableBinaryByteLength;
  10660. tile.header.batchTableJsonByteLength = batchTableJsonByteLength;
  10661. tile.header.batchTableBinaryByteLength = batchTableBinaryByteLength;
  10662. tile.header.batchLength = batchLength;
  10663. return byteOffset;
  10664. }
  10665. function parse3DTileTablesSync(tile, arrayBuffer, byteOffset, options) {
  10666. byteOffset = parse3DTileFeatureTable(tile, arrayBuffer, byteOffset);
  10667. byteOffset = parse3DTileBatchTable(tile, arrayBuffer, byteOffset);
  10668. return byteOffset;
  10669. }
  10670. function parse3DTileFeatureTable(tile, arrayBuffer, byteOffset, options) {
  10671. const {
  10672. featureTableJsonByteLength,
  10673. featureTableBinaryByteLength,
  10674. batchLength
  10675. } = tile.header;
  10676. tile.featureTableJson = {
  10677. BATCH_LENGTH: batchLength || 0
  10678. };
  10679. if (featureTableJsonByteLength > 0) {
  10680. const featureTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, featureTableJsonByteLength);
  10681. tile.featureTableJson = JSON.parse(featureTableString);
  10682. }
  10683. byteOffset += featureTableJsonByteLength;
  10684. tile.featureTableBinary = new Uint8Array(arrayBuffer, byteOffset, featureTableBinaryByteLength);
  10685. byteOffset += featureTableBinaryByteLength;
  10686. return byteOffset;
  10687. }
  10688. function parse3DTileBatchTable(tile, arrayBuffer, byteOffset, options) {
  10689. const {
  10690. batchTableJsonByteLength,
  10691. batchTableBinaryByteLength
  10692. } = tile.header;
  10693. if (batchTableJsonByteLength > 0) {
  10694. const batchTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, batchTableJsonByteLength);
  10695. tile.batchTableJson = JSON.parse(batchTableString);
  10696. byteOffset += batchTableJsonByteLength;
  10697. if (batchTableBinaryByteLength > 0) {
  10698. tile.batchTableBinary = new Uint8Array(arrayBuffer, byteOffset, batchTableBinaryByteLength);
  10699. tile.batchTableBinary = new Uint8Array(tile.batchTableBinary);
  10700. byteOffset += batchTableBinaryByteLength;
  10701. }
  10702. }
  10703. return byteOffset;
  10704. }
  10705. function normalize3DTileColorAttribute(tile, colors, batchTable) {
  10706. if (!colors && (!tile || !tile.batchIds || !batchTable)) {
  10707. return null;
  10708. }
  10709. const {
  10710. batchIds,
  10711. isRGB565,
  10712. pointCount
  10713. } = tile;
  10714. if (batchIds && batchTable) {
  10715. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10716. for (let i = 0; i < pointCount; i++) {
  10717. const batchId = batchIds[i];
  10718. const dimensions = batchTable.getProperty(batchId, 'dimensions');
  10719. const color = dimensions.map(d => d * 255);
  10720. colorArray[i * 3] = color[0];
  10721. colorArray[i * 3 + 1] = color[1];
  10722. colorArray[i * 3 + 2] = color[2];
  10723. }
  10724. return {
  10725. type: GL$1.UNSIGNED_BYTE,
  10726. value: colorArray,
  10727. size: 3,
  10728. normalized: true
  10729. };
  10730. }
  10731. if (isRGB565) {
  10732. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10733. for (let i = 0; i < pointCount; i++) {
  10734. const color = decodeRGB565(colors[i]);
  10735. colorArray[i * 3] = color[0];
  10736. colorArray[i * 3 + 1] = color[1];
  10737. colorArray[i * 3 + 2] = color[2];
  10738. }
  10739. return {
  10740. type: GL$1.UNSIGNED_BYTE,
  10741. value: colorArray,
  10742. size: 3,
  10743. normalized: true
  10744. };
  10745. }
  10746. if (colors && colors.length === pointCount * 3) {
  10747. return {
  10748. type: GL$1.UNSIGNED_BYTE,
  10749. value: colors,
  10750. size: 3,
  10751. normalized: true
  10752. };
  10753. }
  10754. return {
  10755. type: GL$1.UNSIGNED_BYTE,
  10756. value: colors,
  10757. size: 4,
  10758. normalized: true
  10759. };
  10760. }
  10761. const scratchNormal = new Vector3();
  10762. function normalize3DTileNormalAttribute(tile, normals) {
  10763. if (!normals) {
  10764. return null;
  10765. }
  10766. if (tile.isOctEncoded16P) {
  10767. const decodedArray = new Float32Array(tile.pointsLength * 3);
  10768. for (let i = 0; i < tile.pointsLength; i++) {
  10769. octDecode(normals[i * 2], normals[i * 2 + 1], scratchNormal);
  10770. scratchNormal.toArray(decodedArray, i * 3);
  10771. }
  10772. return {
  10773. type: GL$1.FLOAT,
  10774. size: 2,
  10775. value: decodedArray
  10776. };
  10777. }
  10778. return {
  10779. type: GL$1.FLOAT,
  10780. size: 2,
  10781. value: normals
  10782. };
  10783. }
  10784. function normalize3DTilePositionAttribute(tile, positions, options) {
  10785. if (!tile.isQuantized) {
  10786. return positions;
  10787. }
  10788. if (options['3d-tiles'] && options['3d-tiles'].decodeQuantizedPositions) {
  10789. tile.isQuantized = false;
  10790. return decodeQuantizedPositions(tile, positions);
  10791. }
  10792. return {
  10793. type: GL$1.UNSIGNED_SHORT,
  10794. value: positions,
  10795. size: 3,
  10796. normalized: true
  10797. };
  10798. }
  10799. function decodeQuantizedPositions(tile, positions) {
  10800. const scratchPosition = new Vector3();
  10801. const decodedArray = new Float32Array(tile.pointCount * 3);
  10802. for (let i = 0; i < tile.pointCount; i++) {
  10803. scratchPosition.set(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]).scale(1 / tile.quantizedRange).multiply(tile.quantizedVolumeScale).add(tile.quantizedVolumeOffset).toArray(decodedArray, i * 3);
  10804. }
  10805. return decodedArray;
  10806. }
  10807. async function parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context) {
  10808. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  10809. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  10810. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  10811. initializeTile(tile);
  10812. const {
  10813. featureTable,
  10814. batchTable
  10815. } = parsePointCloudTables(tile);
  10816. await parseDraco(tile, featureTable, batchTable, options, context);
  10817. parsePositions(tile, featureTable, options);
  10818. parseColors(tile, featureTable, batchTable);
  10819. parseNormals(tile, featureTable);
  10820. return byteOffset;
  10821. }
  10822. function initializeTile(tile) {
  10823. tile.attributes = {
  10824. positions: null,
  10825. colors: null,
  10826. normals: null,
  10827. batchIds: null
  10828. };
  10829. tile.isQuantized = false;
  10830. tile.isTranslucent = false;
  10831. tile.isRGB565 = false;
  10832. tile.isOctEncoded16P = false;
  10833. }
  10834. function parsePointCloudTables(tile) {
  10835. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  10836. const pointsLength = featureTable.getGlobalProperty('POINTS_LENGTH');
  10837. if (!Number.isFinite(pointsLength)) {
  10838. throw new Error('POINTS_LENGTH must be defined');
  10839. }
  10840. featureTable.featuresLength = pointsLength;
  10841. tile.featuresLength = pointsLength;
  10842. tile.pointsLength = pointsLength;
  10843. tile.pointCount = pointsLength;
  10844. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  10845. const batchTable = parseBatchIds(tile, featureTable);
  10846. return {
  10847. featureTable,
  10848. batchTable
  10849. };
  10850. }
  10851. function parsePositions(tile, featureTable, options) {
  10852. if (!tile.attributes.positions) {
  10853. if (featureTable.hasProperty('POSITION')) {
  10854. tile.attributes.positions = featureTable.getPropertyArray('POSITION', GL$1.FLOAT, 3);
  10855. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  10856. const positions = featureTable.getPropertyArray('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3);
  10857. tile.isQuantized = true;
  10858. tile.quantizedRange = (1 << 16) - 1;
  10859. tile.quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3);
  10860. if (!tile.quantizedVolumeScale) {
  10861. throw new Error('QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  10862. }
  10863. tile.quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3);
  10864. if (!tile.quantizedVolumeOffset) {
  10865. throw new Error('QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  10866. }
  10867. tile.attributes.positions = normalize3DTilePositionAttribute(tile, positions, options);
  10868. }
  10869. }
  10870. if (!tile.attributes.positions) {
  10871. throw new Error('Either POSITION or POSITION_QUANTIZED must be defined.');
  10872. }
  10873. }
  10874. function parseColors(tile, featureTable, batchTable) {
  10875. if (!tile.attributes.colors) {
  10876. let colors = null;
  10877. if (featureTable.hasProperty('RGBA')) {
  10878. colors = featureTable.getPropertyArray('RGBA', GL$1.UNSIGNED_BYTE, 4);
  10879. tile.isTranslucent = true;
  10880. } else if (featureTable.hasProperty('RGB')) {
  10881. colors = featureTable.getPropertyArray('RGB', GL$1.UNSIGNED_BYTE, 3);
  10882. } else if (featureTable.hasProperty('RGB565')) {
  10883. colors = featureTable.getPropertyArray('RGB565', GL$1.UNSIGNED_SHORT, 1);
  10884. tile.isRGB565 = true;
  10885. }
  10886. tile.attributes.colors = normalize3DTileColorAttribute(tile, colors, batchTable);
  10887. }
  10888. if (featureTable.hasProperty('CONSTANT_RGBA')) {
  10889. tile.constantRGBA = featureTable.getGlobalProperty('CONSTANT_RGBA', GL$1.UNSIGNED_BYTE, 4);
  10890. }
  10891. }
  10892. function parseNormals(tile, featureTable) {
  10893. if (!tile.attributes.normals) {
  10894. let normals = null;
  10895. if (featureTable.hasProperty('NORMAL')) {
  10896. normals = featureTable.getPropertyArray('NORMAL', GL$1.FLOAT, 3);
  10897. } else if (featureTable.hasProperty('NORMAL_OCT16P')) {
  10898. normals = featureTable.getPropertyArray('NORMAL_OCT16P', GL$1.UNSIGNED_BYTE, 2);
  10899. tile.isOctEncoded16P = true;
  10900. }
  10901. tile.attributes.normals = normalize3DTileNormalAttribute(tile, normals);
  10902. }
  10903. }
  10904. function parseBatchIds(tile, featureTable) {
  10905. let batchTable = null;
  10906. if (!tile.batchIds && featureTable.hasProperty('BATCH_ID')) {
  10907. tile.batchIds = featureTable.getPropertyArray('BATCH_ID', GL$1.UNSIGNED_SHORT, 1);
  10908. if (tile.batchIds) {
  10909. const batchFeatureLength = featureTable.getGlobalProperty('BATCH_LENGTH');
  10910. if (!batchFeatureLength) {
  10911. throw new Error('Global property: BATCH_LENGTH must be defined when BATCH_ID is defined.');
  10912. }
  10913. const {
  10914. batchTableJson,
  10915. batchTableBinary
  10916. } = tile;
  10917. batchTable = new Tile3DBatchTableParser(batchTableJson, batchTableBinary, batchFeatureLength);
  10918. }
  10919. }
  10920. return batchTable;
  10921. }
  10922. async function parseDraco(tile, featureTable, batchTable, options, context) {
  10923. let dracoBuffer;
  10924. let dracoFeatureTableProperties;
  10925. let dracoBatchTableProperties;
  10926. const batchTableDraco = tile.batchTableJson && tile.batchTableJson.extensions && tile.batchTableJson.extensions['3DTILES_draco_point_compression'];
  10927. if (batchTableDraco) {
  10928. dracoBatchTableProperties = batchTableDraco.properties;
  10929. }
  10930. const featureTableDraco = featureTable.getExtension('3DTILES_draco_point_compression');
  10931. if (featureTableDraco) {
  10932. dracoFeatureTableProperties = featureTableDraco.properties;
  10933. const dracoByteOffset = featureTableDraco.byteOffset;
  10934. const dracoByteLength = featureTableDraco.byteLength;
  10935. if (!dracoFeatureTableProperties || !Number.isFinite(dracoByteOffset) || !dracoByteLength) {
  10936. throw new Error('Draco properties, byteOffset, and byteLength must be defined');
  10937. }
  10938. dracoBuffer = tile.featureTableBinary.slice(dracoByteOffset, dracoByteOffset + dracoByteLength);
  10939. tile.hasPositions = Number.isFinite(dracoFeatureTableProperties.POSITION);
  10940. tile.hasColors = Number.isFinite(dracoFeatureTableProperties.RGB) || Number.isFinite(dracoFeatureTableProperties.RGBA);
  10941. tile.hasNormals = Number.isFinite(dracoFeatureTableProperties.NORMAL);
  10942. tile.hasBatchIds = Number.isFinite(dracoFeatureTableProperties.BATCH_ID);
  10943. tile.isTranslucent = Number.isFinite(dracoFeatureTableProperties.RGBA);
  10944. }
  10945. if (!dracoBuffer) {
  10946. return true;
  10947. }
  10948. const dracoData = {
  10949. buffer: dracoBuffer,
  10950. properties: { ...dracoFeatureTableProperties,
  10951. ...dracoBatchTableProperties
  10952. },
  10953. featureTableProperties: dracoFeatureTableProperties,
  10954. batchTableProperties: dracoBatchTableProperties,
  10955. dequantizeInShader: false
  10956. };
  10957. return await loadDraco(tile, dracoData, options, context);
  10958. }
  10959. async function loadDraco(tile, dracoData, options, context) {
  10960. const {
  10961. parse
  10962. } = context;
  10963. const dracoOptions = { ...options,
  10964. draco: { ...options.draco,
  10965. extraAttributes: dracoData.batchTableProperties || {}
  10966. }
  10967. };
  10968. delete dracoOptions['3d-tiles'];
  10969. const data = await parse(dracoData.buffer, DracoLoader, dracoOptions);
  10970. const decodedPositions = data.attributes.POSITION && data.attributes.POSITION.value;
  10971. const decodedColors = data.attributes.COLOR_0 && data.attributes.COLOR_0.value;
  10972. const decodedNormals = data.attributes.NORMAL && data.attributes.NORMAL.value;
  10973. const decodedBatchIds = data.attributes.BATCH_ID && data.attributes.BATCH_ID.value;
  10974. const isQuantizedDraco = decodedPositions && data.attributes.POSITION.value.quantization;
  10975. const isOctEncodedDraco = decodedNormals && data.attributes.NORMAL.value.quantization;
  10976. if (isQuantizedDraco) {
  10977. const quantization = data.POSITION.data.quantization;
  10978. const range = quantization.range;
  10979. tile.quantizedVolumeScale = new Vector3(range, range, range);
  10980. tile.quantizedVolumeOffset = new Vector3(quantization.minValues);
  10981. tile.quantizedRange = (1 << quantization.quantizationBits) - 1.0;
  10982. tile.isQuantizedDraco = true;
  10983. }
  10984. if (isOctEncodedDraco) {
  10985. tile.octEncodedRange = (1 << data.NORMAL.data.quantization.quantizationBits) - 1.0;
  10986. tile.isOctEncodedDraco = true;
  10987. }
  10988. const batchTableAttributes = {};
  10989. if (dracoData.batchTableProperties) {
  10990. for (const attributeName of Object.keys(dracoData.batchTableProperties)) {
  10991. if (data.attributes[attributeName] && data.attributes[attributeName].value) {
  10992. batchTableAttributes[attributeName.toLowerCase()] = data.attributes[attributeName].value;
  10993. }
  10994. }
  10995. }
  10996. tile.attributes = {
  10997. positions: decodedPositions,
  10998. colors: normalize3DTileColorAttribute(tile, decodedColors, undefined),
  10999. normals: decodedNormals,
  11000. batchIds: decodedBatchIds,
  11001. ...batchTableAttributes
  11002. };
  11003. }
  11004. const VERSION$3 = "3.2.5" ;
  11005. const VERSION$2 = "3.2.5" ;
  11006. const VERSION$1 = "3.2.5" ;
  11007. const BASIS_CDN_ENCODER_WASM = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.wasm");
  11008. const BASIS_CDN_ENCODER_JS = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.js");
  11009. let loadBasisTranscoderPromise;
  11010. async function loadBasisTrascoderModule(options) {
  11011. const modules = options.modules || {};
  11012. if (modules.basis) {
  11013. return modules.basis;
  11014. }
  11015. loadBasisTranscoderPromise = loadBasisTranscoderPromise || loadBasisTrascoder(options);
  11016. return await loadBasisTranscoderPromise;
  11017. }
  11018. async function loadBasisTrascoder(options) {
  11019. let BASIS = null;
  11020. let wasmBinary = null;
  11021. [BASIS, wasmBinary] = await Promise.all([await loadLibrary('basis_transcoder.js', 'textures', options), await loadLibrary('basis_transcoder.wasm', 'textures', options)]);
  11022. BASIS = BASIS || globalThis.BASIS;
  11023. return await initializeBasisTrascoderModule(BASIS, wasmBinary);
  11024. }
  11025. function initializeBasisTrascoderModule(BasisModule, wasmBinary) {
  11026. const options = {};
  11027. if (wasmBinary) {
  11028. options.wasmBinary = wasmBinary;
  11029. }
  11030. return new Promise(resolve => {
  11031. BasisModule(options).then(module => {
  11032. const {
  11033. BasisFile,
  11034. initializeBasis
  11035. } = module;
  11036. initializeBasis();
  11037. resolve({
  11038. BasisFile
  11039. });
  11040. });
  11041. });
  11042. }
  11043. let loadBasisEncoderPromise;
  11044. async function loadBasisEncoderModule(options) {
  11045. const modules = options.modules || {};
  11046. if (modules.basisEncoder) {
  11047. return modules.basisEncoder;
  11048. }
  11049. loadBasisEncoderPromise = loadBasisEncoderPromise || loadBasisEncoder(options);
  11050. return await loadBasisEncoderPromise;
  11051. }
  11052. async function loadBasisEncoder(options) {
  11053. let BASIS_ENCODER = null;
  11054. let wasmBinary = null;
  11055. [BASIS_ENCODER, wasmBinary] = await Promise.all([await loadLibrary(BASIS_CDN_ENCODER_JS, 'textures', options), await loadLibrary(BASIS_CDN_ENCODER_WASM, 'textures', options)]);
  11056. BASIS_ENCODER = BASIS_ENCODER || globalThis.BASIS;
  11057. return await initializeBasisEncoderModule(BASIS_ENCODER, wasmBinary);
  11058. }
  11059. function initializeBasisEncoderModule(BasisEncoderModule, wasmBinary) {
  11060. const options = {};
  11061. if (wasmBinary) {
  11062. options.wasmBinary = wasmBinary;
  11063. }
  11064. return new Promise(resolve => {
  11065. BasisEncoderModule(options).then(module => {
  11066. const {
  11067. BasisFile,
  11068. KTX2File,
  11069. initializeBasis,
  11070. BasisEncoder
  11071. } = module;
  11072. initializeBasis();
  11073. resolve({
  11074. BasisFile,
  11075. KTX2File,
  11076. BasisEncoder
  11077. });
  11078. });
  11079. });
  11080. }
  11081. const GL_EXTENSIONS_CONSTANTS = {
  11082. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83f0,
  11083. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83f1,
  11084. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83f2,
  11085. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83f3,
  11086. COMPRESSED_R11_EAC: 0x9270,
  11087. COMPRESSED_SIGNED_R11_EAC: 0x9271,
  11088. COMPRESSED_RG11_EAC: 0x9272,
  11089. COMPRESSED_SIGNED_RG11_EAC: 0x9273,
  11090. COMPRESSED_RGB8_ETC2: 0x9274,
  11091. COMPRESSED_RGBA8_ETC2_EAC: 0x9275,
  11092. COMPRESSED_SRGB8_ETC2: 0x9276,
  11093. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: 0x9277,
  11094. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9278,
  11095. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9279,
  11096. COMPRESSED_RGB_PVRTC_4BPPV1_IMG: 0x8c00,
  11097. COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: 0x8c02,
  11098. COMPRESSED_RGB_PVRTC_2BPPV1_IMG: 0x8c01,
  11099. COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: 0x8c03,
  11100. COMPRESSED_RGB_ETC1_WEBGL: 0x8d64,
  11101. COMPRESSED_RGB_ATC_WEBGL: 0x8c92,
  11102. COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL: 0x8c93,
  11103. COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL: 0x87ee,
  11104. COMPRESSED_RGBA_ASTC_4X4_KHR: 0x93b0,
  11105. COMPRESSED_RGBA_ASTC_5X4_KHR: 0x93b1,
  11106. COMPRESSED_RGBA_ASTC_5X5_KHR: 0x93b2,
  11107. COMPRESSED_RGBA_ASTC_6X5_KHR: 0x93b3,
  11108. COMPRESSED_RGBA_ASTC_6X6_KHR: 0x93b4,
  11109. COMPRESSED_RGBA_ASTC_8X5_KHR: 0x93b5,
  11110. COMPRESSED_RGBA_ASTC_8X6_KHR: 0x93b6,
  11111. COMPRESSED_RGBA_ASTC_8X8_KHR: 0x93b7,
  11112. COMPRESSED_RGBA_ASTC_10X5_KHR: 0x93b8,
  11113. COMPRESSED_RGBA_ASTC_10X6_KHR: 0x93b9,
  11114. COMPRESSED_RGBA_ASTC_10X8_KHR: 0x93ba,
  11115. COMPRESSED_RGBA_ASTC_10X10_KHR: 0x93bb,
  11116. COMPRESSED_RGBA_ASTC_12X10_KHR: 0x93bc,
  11117. COMPRESSED_RGBA_ASTC_12X12_KHR: 0x93bd,
  11118. COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR: 0x93d0,
  11119. COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR: 0x93d1,
  11120. COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR: 0x93d2,
  11121. COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR: 0x93d3,
  11122. COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR: 0x93d4,
  11123. COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR: 0x93d5,
  11124. COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR: 0x93d6,
  11125. COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR: 0x93d7,
  11126. COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR: 0x93d8,
  11127. COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR: 0x93d9,
  11128. COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR: 0x93da,
  11129. COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR: 0x93db,
  11130. COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR: 0x93dc,
  11131. COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR: 0x93dd,
  11132. COMPRESSED_RED_RGTC1_EXT: 0x8dbb,
  11133. COMPRESSED_SIGNED_RED_RGTC1_EXT: 0x8dbc,
  11134. COMPRESSED_RED_GREEN_RGTC2_EXT: 0x8dbd,
  11135. COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT: 0x8dbe,
  11136. COMPRESSED_SRGB_S3TC_DXT1_EXT: 0x8c4c,
  11137. COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: 0x8c4d,
  11138. COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: 0x8c4e,
  11139. COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: 0x8c4f
  11140. };
  11141. const BROWSER_PREFIXES = ['', 'WEBKIT_', 'MOZ_'];
  11142. const WEBGL_EXTENSIONS = {
  11143. WEBGL_compressed_texture_s3tc: 'dxt',
  11144. WEBGL_compressed_texture_s3tc_srgb: 'dxt-srgb',
  11145. WEBGL_compressed_texture_etc1: 'etc1',
  11146. WEBGL_compressed_texture_etc: 'etc2',
  11147. WEBGL_compressed_texture_pvrtc: 'pvrtc',
  11148. WEBGL_compressed_texture_atc: 'atc',
  11149. WEBGL_compressed_texture_astc: 'astc',
  11150. EXT_texture_compression_rgtc: 'rgtc'
  11151. };
  11152. let formats = null;
  11153. function getSupportedGPUTextureFormats(gl) {
  11154. if (!formats) {
  11155. gl = gl || getWebGLContext() || undefined;
  11156. formats = new Set();
  11157. for (const prefix of BROWSER_PREFIXES) {
  11158. for (const extension in WEBGL_EXTENSIONS) {
  11159. if (gl && gl.getExtension("".concat(prefix).concat(extension))) {
  11160. const gpuTextureFormat = WEBGL_EXTENSIONS[extension];
  11161. formats.add(gpuTextureFormat);
  11162. }
  11163. }
  11164. }
  11165. }
  11166. return formats;
  11167. }
  11168. function getWebGLContext() {
  11169. try {
  11170. const canvas = document.createElement('canvas');
  11171. return canvas.getContext('webgl');
  11172. } catch (error) {
  11173. return null;
  11174. }
  11175. }
  11176. var n,i,s,a,r,o,l,f;!function(t){t[t.NONE=0]="NONE",t[t.BASISLZ=1]="BASISLZ",t[t.ZSTD=2]="ZSTD",t[t.ZLIB=3]="ZLIB";}(n||(n={})),function(t){t[t.BASICFORMAT=0]="BASICFORMAT";}(i||(i={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.ETC1S=163]="ETC1S",t[t.UASTC=166]="UASTC";}(s||(s={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.SRGB=1]="SRGB";}(a||(a={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.LINEAR=1]="LINEAR",t[t.SRGB=2]="SRGB",t[t.ITU=3]="ITU",t[t.NTSC=4]="NTSC",t[t.SLOG=5]="SLOG",t[t.SLOG2=6]="SLOG2";}(r||(r={})),function(t){t[t.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",t[t.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED";}(o||(o={})),function(t){t[t.RGB=0]="RGB",t[t.RRR=3]="RRR",t[t.GGG=4]="GGG",t[t.AAA=15]="AAA";}(l||(l={})),function(t){t[t.RGB=0]="RGB",t[t.RGBA=3]="RGBA",t[t.RRR=4]="RRR",t[t.RRRG=5]="RRRG";}(f||(f={}));
  11177. const KTX2_ID = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];
  11178. function isKTX(data) {
  11179. const id = new Uint8Array(data);
  11180. const notKTX = id.byteLength < KTX2_ID.length || id[0] !== KTX2_ID[0] || id[1] !== KTX2_ID[1] || id[2] !== KTX2_ID[2] || id[3] !== KTX2_ID[3] || id[4] !== KTX2_ID[4] || id[5] !== KTX2_ID[5] || id[6] !== KTX2_ID[6] || id[7] !== KTX2_ID[7] || id[8] !== KTX2_ID[8] || id[9] !== KTX2_ID[9] || id[10] !== KTX2_ID[10] || id[11] !== KTX2_ID[11];
  11181. return !notKTX;
  11182. }
  11183. const OutputFormat = {
  11184. etc1: {
  11185. basisFormat: 0,
  11186. compressed: true,
  11187. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_ETC1_WEBGL
  11188. },
  11189. etc2: {
  11190. basisFormat: 1,
  11191. compressed: true
  11192. },
  11193. bc1: {
  11194. basisFormat: 2,
  11195. compressed: true,
  11196. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_S3TC_DXT1_EXT
  11197. },
  11198. bc3: {
  11199. basisFormat: 3,
  11200. compressed: true,
  11201. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_S3TC_DXT5_EXT
  11202. },
  11203. bc4: {
  11204. basisFormat: 4,
  11205. compressed: true
  11206. },
  11207. bc5: {
  11208. basisFormat: 5,
  11209. compressed: true
  11210. },
  11211. 'bc7-m6-opaque-only': {
  11212. basisFormat: 6,
  11213. compressed: true
  11214. },
  11215. 'bc7-m5': {
  11216. basisFormat: 7,
  11217. compressed: true
  11218. },
  11219. 'pvrtc1-4-rgb': {
  11220. basisFormat: 8,
  11221. compressed: true,
  11222. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG
  11223. },
  11224. 'pvrtc1-4-rgba': {
  11225. basisFormat: 9,
  11226. compressed: true,
  11227. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG
  11228. },
  11229. 'astc-4x4': {
  11230. basisFormat: 10,
  11231. compressed: true,
  11232. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_4X4_KHR
  11233. },
  11234. 'atc-rgb': {
  11235. basisFormat: 11,
  11236. compressed: true
  11237. },
  11238. 'atc-rgba-interpolated-alpha': {
  11239. basisFormat: 12,
  11240. compressed: true
  11241. },
  11242. rgba32: {
  11243. basisFormat: 13,
  11244. compressed: false
  11245. },
  11246. rgb565: {
  11247. basisFormat: 14,
  11248. compressed: false
  11249. },
  11250. bgr565: {
  11251. basisFormat: 15,
  11252. compressed: false
  11253. },
  11254. rgba4444: {
  11255. basisFormat: 16,
  11256. compressed: false
  11257. }
  11258. };
  11259. async function parseBasis(data, options) {
  11260. if (options.basis.containerFormat === 'auto') {
  11261. if (isKTX(data)) {
  11262. const fileConstructors = await loadBasisEncoderModule(options);
  11263. return parseKTX2File(fileConstructors.KTX2File, data, options);
  11264. }
  11265. const {
  11266. BasisFile
  11267. } = await loadBasisTrascoderModule(options);
  11268. return parseBasisFile(BasisFile, data, options);
  11269. }
  11270. switch (options.basis.module) {
  11271. case 'encoder':
  11272. const fileConstructors = await loadBasisEncoderModule(options);
  11273. switch (options.basis.containerFormat) {
  11274. case 'ktx2':
  11275. return parseKTX2File(fileConstructors.KTX2File, data, options);
  11276. case 'basis':
  11277. default:
  11278. return parseBasisFile(fileConstructors.BasisFile, data, options);
  11279. }
  11280. case 'transcoder':
  11281. default:
  11282. const {
  11283. BasisFile
  11284. } = await loadBasisTrascoderModule(options);
  11285. return parseBasisFile(BasisFile, data, options);
  11286. }
  11287. }
  11288. function parseBasisFile(BasisFile, data, options) {
  11289. const basisFile = new BasisFile(new Uint8Array(data));
  11290. try {
  11291. if (!basisFile.startTranscoding()) {
  11292. throw new Error('Failed to start basis transcoding');
  11293. }
  11294. const imageCount = basisFile.getNumImages();
  11295. const images = [];
  11296. for (let imageIndex = 0; imageIndex < imageCount; imageIndex++) {
  11297. const levelsCount = basisFile.getNumLevels(imageIndex);
  11298. const levels = [];
  11299. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  11300. levels.push(transcodeImage(basisFile, imageIndex, levelIndex, options));
  11301. }
  11302. images.push(levels);
  11303. }
  11304. return images;
  11305. } finally {
  11306. basisFile.close();
  11307. basisFile.delete();
  11308. }
  11309. }
  11310. function transcodeImage(basisFile, imageIndex, levelIndex, options) {
  11311. const width = basisFile.getImageWidth(imageIndex, levelIndex);
  11312. const height = basisFile.getImageHeight(imageIndex, levelIndex);
  11313. const hasAlpha = basisFile.getHasAlpha();
  11314. const {
  11315. compressed,
  11316. format,
  11317. basisFormat
  11318. } = getBasisOptions(options, hasAlpha);
  11319. const decodedSize = basisFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, basisFormat);
  11320. const decodedData = new Uint8Array(decodedSize);
  11321. if (!basisFile.transcodeImage(decodedData, imageIndex, levelIndex, basisFormat, 0, 0)) {
  11322. throw new Error('failed to start Basis transcoding');
  11323. }
  11324. return {
  11325. width,
  11326. height,
  11327. data: decodedData,
  11328. compressed,
  11329. format,
  11330. hasAlpha
  11331. };
  11332. }
  11333. function parseKTX2File(KTX2File, data, options) {
  11334. const ktx2File = new KTX2File(new Uint8Array(data));
  11335. try {
  11336. if (!ktx2File.startTranscoding()) {
  11337. throw new Error('failed to start KTX2 transcoding');
  11338. }
  11339. const levelsCount = ktx2File.getLevels();
  11340. const levels = [];
  11341. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  11342. levels.push(transcodeKTX2Image(ktx2File, levelIndex, options));
  11343. break;
  11344. }
  11345. return [levels];
  11346. } finally {
  11347. ktx2File.close();
  11348. ktx2File.delete();
  11349. }
  11350. }
  11351. function transcodeKTX2Image(ktx2File, levelIndex, options) {
  11352. const {
  11353. alphaFlag,
  11354. height,
  11355. width
  11356. } = ktx2File.getImageLevelInfo(levelIndex, 0, 0);
  11357. const {
  11358. compressed,
  11359. format,
  11360. basisFormat
  11361. } = getBasisOptions(options, alphaFlag);
  11362. const decodedSize = ktx2File.getImageTranscodedSizeInBytes(levelIndex, 0, 0, basisFormat);
  11363. const decodedData = new Uint8Array(decodedSize);
  11364. if (!ktx2File.transcodeImage(decodedData, levelIndex, 0, 0, basisFormat, 0, -1, -1)) {
  11365. throw new Error('Failed to transcode KTX2 image');
  11366. }
  11367. return {
  11368. width,
  11369. height,
  11370. data: decodedData,
  11371. compressed,
  11372. hasAlpha: alphaFlag,
  11373. format
  11374. };
  11375. }
  11376. function getBasisOptions(options, hasAlpha) {
  11377. let format = options && options.basis && options.basis.format;
  11378. if (format === 'auto') {
  11379. format = selectSupportedBasisFormat();
  11380. }
  11381. if (typeof format === 'object') {
  11382. format = hasAlpha ? format.alpha : format.noAlpha;
  11383. }
  11384. format = format.toLowerCase();
  11385. return OutputFormat[format];
  11386. }
  11387. function selectSupportedBasisFormat() {
  11388. const supportedFormats = getSupportedGPUTextureFormats();
  11389. if (supportedFormats.has('astc')) {
  11390. return 'astc-4x4';
  11391. } else if (supportedFormats.has('dxt')) {
  11392. return {
  11393. alpha: 'bc3',
  11394. noAlpha: 'bc1'
  11395. };
  11396. } else if (supportedFormats.has('pvrtc')) {
  11397. return {
  11398. alpha: 'pvrtc1-4-rgba',
  11399. noAlpha: 'pvrtc1-4-rgb'
  11400. };
  11401. } else if (supportedFormats.has('etc1')) {
  11402. return 'etc1';
  11403. } else if (supportedFormats.has('etc2')) {
  11404. return 'etc2';
  11405. }
  11406. return 'rgb565';
  11407. }
  11408. const BasisWorkerLoader = {
  11409. name: 'Basis',
  11410. id: 'basis',
  11411. module: 'textures',
  11412. version: VERSION$2,
  11413. worker: true,
  11414. extensions: ['basis', 'ktx2'],
  11415. mimeTypes: ['application/octet-stream', 'image/ktx2'],
  11416. tests: ['sB'],
  11417. binary: true,
  11418. options: {
  11419. basis: {
  11420. format: 'auto',
  11421. libraryPath: 'libs/',
  11422. containerFormat: 'auto',
  11423. module: 'transcoder'
  11424. }
  11425. }
  11426. };
  11427. const BasisLoader = { ...BasisWorkerLoader,
  11428. parse: parseBasis
  11429. };
  11430. const VERSION = "3.2.5" ;
  11431. const {
  11432. _parseImageNode
  11433. } = globalThis;
  11434. const IMAGE_SUPPORTED = typeof Image !== 'undefined';
  11435. const IMAGE_BITMAP_SUPPORTED = typeof ImageBitmap !== 'undefined';
  11436. const NODE_IMAGE_SUPPORTED = Boolean(_parseImageNode);
  11437. const DATA_SUPPORTED = isBrowser$2 ? true : NODE_IMAGE_SUPPORTED;
  11438. function isImageTypeSupported(type) {
  11439. switch (type) {
  11440. case 'auto':
  11441. return IMAGE_BITMAP_SUPPORTED || IMAGE_SUPPORTED || DATA_SUPPORTED;
  11442. case 'imagebitmap':
  11443. return IMAGE_BITMAP_SUPPORTED;
  11444. case 'image':
  11445. return IMAGE_SUPPORTED;
  11446. case 'data':
  11447. return DATA_SUPPORTED;
  11448. default:
  11449. throw new Error("@loaders.gl/images: image ".concat(type, " not supported in this environment"));
  11450. }
  11451. }
  11452. function getDefaultImageType() {
  11453. if (IMAGE_BITMAP_SUPPORTED) {
  11454. return 'imagebitmap';
  11455. }
  11456. if (IMAGE_SUPPORTED) {
  11457. return 'image';
  11458. }
  11459. if (DATA_SUPPORTED) {
  11460. return 'data';
  11461. }
  11462. throw new Error('Install \'@loaders.gl/polyfills\' to parse images under Node.js');
  11463. }
  11464. function getImageType(image) {
  11465. const format = getImageTypeOrNull(image);
  11466. if (!format) {
  11467. throw new Error('Not an image');
  11468. }
  11469. return format;
  11470. }
  11471. function getImageData(image) {
  11472. switch (getImageType(image)) {
  11473. case 'data':
  11474. return image;
  11475. case 'image':
  11476. case 'imagebitmap':
  11477. const canvas = document.createElement('canvas');
  11478. const context = canvas.getContext('2d');
  11479. if (!context) {
  11480. throw new Error('getImageData');
  11481. }
  11482. canvas.width = image.width;
  11483. canvas.height = image.height;
  11484. context.drawImage(image, 0, 0);
  11485. return context.getImageData(0, 0, image.width, image.height);
  11486. default:
  11487. throw new Error('getImageData');
  11488. }
  11489. }
  11490. function getImageTypeOrNull(image) {
  11491. if (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  11492. return 'imagebitmap';
  11493. }
  11494. if (typeof Image !== 'undefined' && image instanceof Image) {
  11495. return 'image';
  11496. }
  11497. if (image && typeof image === 'object' && image.data && image.width && image.height) {
  11498. return 'data';
  11499. }
  11500. return null;
  11501. }
  11502. const SVG_DATA_URL_PATTERN = /^data:image\/svg\+xml/;
  11503. const SVG_URL_PATTERN = /\.svg((\?|#).*)?$/;
  11504. function isSVG(url) {
  11505. return url && (SVG_DATA_URL_PATTERN.test(url) || SVG_URL_PATTERN.test(url));
  11506. }
  11507. function getBlobOrSVGDataUrl(arrayBuffer, url) {
  11508. if (isSVG(url)) {
  11509. const textDecoder = new TextDecoder();
  11510. let xmlText = textDecoder.decode(arrayBuffer);
  11511. try {
  11512. if (typeof unescape === 'function' && typeof encodeURIComponent === 'function') {
  11513. xmlText = unescape(encodeURIComponent(xmlText));
  11514. }
  11515. } catch (error) {
  11516. throw new Error(error.message);
  11517. }
  11518. const src = "data:image/svg+xml;base64,".concat(btoa(xmlText));
  11519. return src;
  11520. }
  11521. return getBlob(arrayBuffer, url);
  11522. }
  11523. function getBlob(arrayBuffer, url) {
  11524. if (isSVG(url)) {
  11525. throw new Error('SVG cannot be parsed directly to imagebitmap');
  11526. }
  11527. return new Blob([new Uint8Array(arrayBuffer)]);
  11528. }
  11529. async function parseToImage(arrayBuffer, options, url) {
  11530. const blobOrDataUrl = getBlobOrSVGDataUrl(arrayBuffer, url);
  11531. const URL = self.URL || self.webkitURL;
  11532. const objectUrl = typeof blobOrDataUrl !== 'string' && URL.createObjectURL(blobOrDataUrl);
  11533. try {
  11534. return await loadToImage(objectUrl || blobOrDataUrl, options);
  11535. } finally {
  11536. if (objectUrl) {
  11537. URL.revokeObjectURL(objectUrl);
  11538. }
  11539. }
  11540. }
  11541. async function loadToImage(url, options) {
  11542. const image = new Image();
  11543. image.src = url;
  11544. if (options.image && options.image.decode && image.decode) {
  11545. await image.decode();
  11546. return image;
  11547. }
  11548. return await new Promise((resolve, reject) => {
  11549. try {
  11550. image.onload = () => resolve(image);
  11551. image.onerror = err => reject(new Error("Could not load image ".concat(url, ": ").concat(err)));
  11552. } catch (error) {
  11553. reject(error);
  11554. }
  11555. });
  11556. }
  11557. const EMPTY_OBJECT = {};
  11558. let imagebitmapOptionsSupported = true;
  11559. async function parseToImageBitmap(arrayBuffer, options, url) {
  11560. let blob;
  11561. if (isSVG(url)) {
  11562. const image = await parseToImage(arrayBuffer, options, url);
  11563. blob = image;
  11564. } else {
  11565. blob = getBlob(arrayBuffer, url);
  11566. }
  11567. const imagebitmapOptions = options && options.imagebitmap;
  11568. return await safeCreateImageBitmap(blob, imagebitmapOptions);
  11569. }
  11570. async function safeCreateImageBitmap(blob, imagebitmapOptions = null) {
  11571. if (isEmptyObject(imagebitmapOptions) || !imagebitmapOptionsSupported) {
  11572. imagebitmapOptions = null;
  11573. }
  11574. if (imagebitmapOptions) {
  11575. try {
  11576. return await createImageBitmap(blob, imagebitmapOptions);
  11577. } catch (error) {
  11578. console.warn(error);
  11579. imagebitmapOptionsSupported = false;
  11580. }
  11581. }
  11582. return await createImageBitmap(blob);
  11583. }
  11584. function isEmptyObject(object) {
  11585. for (const key in object || EMPTY_OBJECT) {
  11586. return false;
  11587. }
  11588. return true;
  11589. }
  11590. const BIG_ENDIAN = false;
  11591. const LITTLE_ENDIAN = true;
  11592. function getBinaryImageMetadata(binaryData) {
  11593. const dataView = toDataView(binaryData);
  11594. return getPngMetadata(dataView) || getJpegMetadata(dataView) || getGifMetadata(dataView) || getBmpMetadata(dataView);
  11595. }
  11596. function getPngMetadata(binaryData) {
  11597. const dataView = toDataView(binaryData);
  11598. const isPng = dataView.byteLength >= 24 && dataView.getUint32(0, BIG_ENDIAN) === 0x89504e47;
  11599. if (!isPng) {
  11600. return null;
  11601. }
  11602. return {
  11603. mimeType: 'image/png',
  11604. width: dataView.getUint32(16, BIG_ENDIAN),
  11605. height: dataView.getUint32(20, BIG_ENDIAN)
  11606. };
  11607. }
  11608. function getGifMetadata(binaryData) {
  11609. const dataView = toDataView(binaryData);
  11610. const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 0x47494638;
  11611. if (!isGif) {
  11612. return null;
  11613. }
  11614. return {
  11615. mimeType: 'image/gif',
  11616. width: dataView.getUint16(6, LITTLE_ENDIAN),
  11617. height: dataView.getUint16(8, LITTLE_ENDIAN)
  11618. };
  11619. }
  11620. function getBmpMetadata(binaryData) {
  11621. const dataView = toDataView(binaryData);
  11622. const isBmp = dataView.byteLength >= 14 && dataView.getUint16(0, BIG_ENDIAN) === 0x424d && dataView.getUint32(2, LITTLE_ENDIAN) === dataView.byteLength;
  11623. if (!isBmp) {
  11624. return null;
  11625. }
  11626. return {
  11627. mimeType: 'image/bmp',
  11628. width: dataView.getUint32(18, LITTLE_ENDIAN),
  11629. height: dataView.getUint32(22, LITTLE_ENDIAN)
  11630. };
  11631. }
  11632. function getJpegMetadata(binaryData) {
  11633. const dataView = toDataView(binaryData);
  11634. const isJpeg = dataView.byteLength >= 3 && dataView.getUint16(0, BIG_ENDIAN) === 0xffd8 && dataView.getUint8(2) === 0xff;
  11635. if (!isJpeg) {
  11636. return null;
  11637. }
  11638. const {
  11639. tableMarkers,
  11640. sofMarkers
  11641. } = getJpegMarkers();
  11642. let i = 2;
  11643. while (i + 9 < dataView.byteLength) {
  11644. const marker = dataView.getUint16(i, BIG_ENDIAN);
  11645. if (sofMarkers.has(marker)) {
  11646. return {
  11647. mimeType: 'image/jpeg',
  11648. height: dataView.getUint16(i + 5, BIG_ENDIAN),
  11649. width: dataView.getUint16(i + 7, BIG_ENDIAN)
  11650. };
  11651. }
  11652. if (!tableMarkers.has(marker)) {
  11653. return null;
  11654. }
  11655. i += 2;
  11656. i += dataView.getUint16(i, BIG_ENDIAN);
  11657. }
  11658. return null;
  11659. }
  11660. function getJpegMarkers() {
  11661. const tableMarkers = new Set([0xffdb, 0xffc4, 0xffcc, 0xffdd, 0xfffe]);
  11662. for (let i = 0xffe0; i < 0xfff0; ++i) {
  11663. tableMarkers.add(i);
  11664. }
  11665. const sofMarkers = new Set([0xffc0, 0xffc1, 0xffc2, 0xffc3, 0xffc5, 0xffc6, 0xffc7, 0xffc9, 0xffca, 0xffcb, 0xffcd, 0xffce, 0xffcf, 0xffde]);
  11666. return {
  11667. tableMarkers,
  11668. sofMarkers
  11669. };
  11670. }
  11671. function toDataView(data) {
  11672. if (data instanceof DataView) {
  11673. return data;
  11674. }
  11675. if (ArrayBuffer.isView(data)) {
  11676. return new DataView(data.buffer);
  11677. }
  11678. if (data instanceof ArrayBuffer) {
  11679. return new DataView(data);
  11680. }
  11681. throw new Error('toDataView');
  11682. }
  11683. async function parseToNodeImage(arrayBuffer, options) {
  11684. const {
  11685. mimeType
  11686. } = getBinaryImageMetadata(arrayBuffer) || {};
  11687. const _parseImageNode = globalThis._parseImageNode;
  11688. assert$7(_parseImageNode);
  11689. return await _parseImageNode(arrayBuffer, mimeType);
  11690. }
  11691. async function parseImage(arrayBuffer, options, context) {
  11692. options = options || {};
  11693. const imageOptions = options.image || {};
  11694. const imageType = imageOptions.type || 'auto';
  11695. const {
  11696. url
  11697. } = context || {};
  11698. const loadType = getLoadableImageType(imageType);
  11699. let image;
  11700. switch (loadType) {
  11701. case 'imagebitmap':
  11702. image = await parseToImageBitmap(arrayBuffer, options, url);
  11703. break;
  11704. case 'image':
  11705. image = await parseToImage(arrayBuffer, options, url);
  11706. break;
  11707. case 'data':
  11708. image = await parseToNodeImage(arrayBuffer);
  11709. break;
  11710. default:
  11711. assert$7(false);
  11712. }
  11713. if (imageType === 'data') {
  11714. image = getImageData(image);
  11715. }
  11716. return image;
  11717. }
  11718. function getLoadableImageType(type) {
  11719. switch (type) {
  11720. case 'auto':
  11721. case 'data':
  11722. return getDefaultImageType();
  11723. default:
  11724. isImageTypeSupported(type);
  11725. return type;
  11726. }
  11727. }
  11728. const EXTENSIONS$1 = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'svg'];
  11729. const MIME_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'image/vnd.microsoft.icon', 'image/svg+xml'];
  11730. const DEFAULT_IMAGE_LOADER_OPTIONS = {
  11731. image: {
  11732. type: 'auto',
  11733. decode: true
  11734. }
  11735. };
  11736. const ImageLoader = {
  11737. id: 'image',
  11738. module: 'images',
  11739. name: 'Images',
  11740. version: VERSION,
  11741. mimeTypes: MIME_TYPES,
  11742. extensions: EXTENSIONS$1,
  11743. parse: parseImage,
  11744. tests: [arrayBuffer => Boolean(getBinaryImageMetadata(new DataView(arrayBuffer)))],
  11745. options: DEFAULT_IMAGE_LOADER_OPTIONS
  11746. };
  11747. const NODE_FORMAT_SUPPORT = ['image/png', 'image/jpeg', 'image/gif'];
  11748. const mimeTypeSupported = {};
  11749. function _isImageFormatSupported(mimeType) {
  11750. if (mimeTypeSupported[mimeType] === undefined) {
  11751. mimeTypeSupported[mimeType] = checkFormatSupport(mimeType);
  11752. }
  11753. return mimeTypeSupported[mimeType];
  11754. }
  11755. function checkFormatSupport(mimeType) {
  11756. switch (mimeType) {
  11757. case 'image/webp':
  11758. return checkWebPSupport();
  11759. case 'image/svg':
  11760. return isBrowser$2;
  11761. default:
  11762. if (!isBrowser$2) {
  11763. const {
  11764. _parseImageNode
  11765. } = globalThis;
  11766. return Boolean(_parseImageNode) && NODE_FORMAT_SUPPORT.includes(mimeType);
  11767. }
  11768. return true;
  11769. }
  11770. }
  11771. function checkWebPSupport() {
  11772. if (!isBrowser$2) {
  11773. return false;
  11774. }
  11775. try {
  11776. const element = document.createElement('canvas');
  11777. return element.toDataURL('image/webp').indexOf('data:image/webp') === 0;
  11778. } catch {
  11779. return false;
  11780. }
  11781. }
  11782. function assert$1(condition, message) {
  11783. if (!condition) {
  11784. throw new Error(message || 'assert failed: gltf');
  11785. }
  11786. }
  11787. function resolveUrl(url, options) {
  11788. const absolute = url.startsWith('data:') || url.startsWith('http:') || url.startsWith('https:');
  11789. if (absolute) {
  11790. return url;
  11791. }
  11792. const baseUrl = options.baseUri || options.uri;
  11793. if (!baseUrl) {
  11794. throw new Error("'baseUri' must be provided to resolve relative url ".concat(url));
  11795. }
  11796. return baseUrl.substr(0, baseUrl.lastIndexOf('/') + 1) + url;
  11797. }
  11798. function getTypedArrayForBufferView(json, buffers, bufferViewIndex) {
  11799. const bufferView = json.bufferViews[bufferViewIndex];
  11800. assert$1(bufferView);
  11801. const bufferIndex = bufferView.buffer;
  11802. const binChunk = buffers[bufferIndex];
  11803. assert$1(binChunk);
  11804. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  11805. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  11806. }
  11807. const TYPES = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'];
  11808. const ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT = [[Int8Array, 5120], [Uint8Array, 5121], [Int16Array, 5122], [Uint16Array, 5123], [Uint32Array, 5125], [Float32Array, 5126], [Float64Array, 5130]];
  11809. const ARRAY_TO_COMPONENT_TYPE = new Map(ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT);
  11810. const ATTRIBUTE_TYPE_TO_COMPONENTS = {
  11811. SCALAR: 1,
  11812. VEC2: 2,
  11813. VEC3: 3,
  11814. VEC4: 4,
  11815. MAT2: 4,
  11816. MAT3: 9,
  11817. MAT4: 16
  11818. };
  11819. const ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE = {
  11820. 5120: 1,
  11821. 5121: 1,
  11822. 5122: 2,
  11823. 5123: 2,
  11824. 5125: 4,
  11825. 5126: 4
  11826. };
  11827. const ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY = {
  11828. 5120: Int8Array,
  11829. 5121: Uint8Array,
  11830. 5122: Int16Array,
  11831. 5123: Uint16Array,
  11832. 5125: Uint32Array,
  11833. 5126: Float32Array
  11834. };
  11835. function getAccessorTypeFromSize(size) {
  11836. const type = TYPES[size - 1];
  11837. return type || TYPES[0];
  11838. }
  11839. function getComponentTypeFromArray(typedArray) {
  11840. const componentType = ARRAY_TO_COMPONENT_TYPE.get(typedArray.constructor);
  11841. if (!componentType) {
  11842. throw new Error('Illegal typed array');
  11843. }
  11844. return componentType;
  11845. }
  11846. function getAccessorArrayTypeAndLength(accessor, bufferView) {
  11847. const ArrayType = ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[accessor.componentType];
  11848. const components = ATTRIBUTE_TYPE_TO_COMPONENTS[accessor.type];
  11849. const bytesPerComponent = ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[accessor.componentType];
  11850. const length = accessor.count * components;
  11851. const byteLength = accessor.count * components * bytesPerComponent;
  11852. assert$1(byteLength >= 0 && byteLength <= bufferView.byteLength);
  11853. return {
  11854. ArrayType,
  11855. length,
  11856. byteLength
  11857. };
  11858. }
  11859. const DEFAULT_GLTF_JSON = {
  11860. asset: {
  11861. version: '2.0',
  11862. generator: 'loaders.gl'
  11863. },
  11864. buffers: []
  11865. };
  11866. class GLTFScenegraph {
  11867. constructor(gltf) {
  11868. _defineProperty(this, "gltf", void 0);
  11869. _defineProperty(this, "sourceBuffers", void 0);
  11870. _defineProperty(this, "byteLength", void 0);
  11871. this.gltf = gltf || {
  11872. json: { ...DEFAULT_GLTF_JSON
  11873. },
  11874. buffers: []
  11875. };
  11876. this.sourceBuffers = [];
  11877. this.byteLength = 0;
  11878. if (this.gltf.buffers && this.gltf.buffers[0]) {
  11879. this.byteLength = this.gltf.buffers[0].byteLength;
  11880. this.sourceBuffers = [this.gltf.buffers[0]];
  11881. }
  11882. }
  11883. get json() {
  11884. return this.gltf.json;
  11885. }
  11886. getApplicationData(key) {
  11887. const data = this.json[key];
  11888. return data;
  11889. }
  11890. getExtraData(key) {
  11891. const extras = this.json.extras || {};
  11892. return extras[key];
  11893. }
  11894. getExtension(extensionName) {
  11895. const isExtension = this.getUsedExtensions().find(name => name === extensionName);
  11896. const extensions = this.json.extensions || {};
  11897. return isExtension ? extensions[extensionName] || true : null;
  11898. }
  11899. getRequiredExtension(extensionName) {
  11900. const isRequired = this.getRequiredExtensions().find(name => name === extensionName);
  11901. return isRequired ? this.getExtension(extensionName) : null;
  11902. }
  11903. getRequiredExtensions() {
  11904. return this.json.extensionsRequired || [];
  11905. }
  11906. getUsedExtensions() {
  11907. return this.json.extensionsUsed || [];
  11908. }
  11909. getObjectExtension(object, extensionName) {
  11910. const extensions = object.extensions || {};
  11911. return extensions[extensionName];
  11912. }
  11913. getScene(index) {
  11914. return this.getObject('scenes', index);
  11915. }
  11916. getNode(index) {
  11917. return this.getObject('nodes', index);
  11918. }
  11919. getSkin(index) {
  11920. return this.getObject('skins', index);
  11921. }
  11922. getMesh(index) {
  11923. return this.getObject('meshes', index);
  11924. }
  11925. getMaterial(index) {
  11926. return this.getObject('materials', index);
  11927. }
  11928. getAccessor(index) {
  11929. return this.getObject('accessors', index);
  11930. }
  11931. getTexture(index) {
  11932. return this.getObject('textures', index);
  11933. }
  11934. getSampler(index) {
  11935. return this.getObject('samplers', index);
  11936. }
  11937. getImage(index) {
  11938. return this.getObject('images', index);
  11939. }
  11940. getBufferView(index) {
  11941. return this.getObject('bufferViews', index);
  11942. }
  11943. getBuffer(index) {
  11944. return this.getObject('buffers', index);
  11945. }
  11946. getObject(array, index) {
  11947. if (typeof index === 'object') {
  11948. return index;
  11949. }
  11950. const object = this.json[array] && this.json[array][index];
  11951. if (!object) {
  11952. throw new Error("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  11953. }
  11954. return object;
  11955. }
  11956. getTypedArrayForBufferView(bufferView) {
  11957. bufferView = this.getBufferView(bufferView);
  11958. const bufferIndex = bufferView.buffer;
  11959. const binChunk = this.gltf.buffers[bufferIndex];
  11960. assert$1(binChunk);
  11961. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  11962. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  11963. }
  11964. getTypedArrayForAccessor(accessor) {
  11965. accessor = this.getAccessor(accessor);
  11966. const bufferView = this.getBufferView(accessor.bufferView);
  11967. const buffer = this.getBuffer(bufferView.buffer);
  11968. const arrayBuffer = buffer.data;
  11969. const {
  11970. ArrayType,
  11971. length
  11972. } = getAccessorArrayTypeAndLength(accessor, bufferView);
  11973. const byteOffset = bufferView.byteOffset + accessor.byteOffset;
  11974. return new ArrayType(arrayBuffer, byteOffset, length);
  11975. }
  11976. getTypedArrayForImageData(image) {
  11977. image = this.getAccessor(image);
  11978. const bufferView = this.getBufferView(image.bufferView);
  11979. const buffer = this.getBuffer(bufferView.buffer);
  11980. const arrayBuffer = buffer.data;
  11981. const byteOffset = bufferView.byteOffset || 0;
  11982. return new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  11983. }
  11984. addApplicationData(key, data) {
  11985. this.json[key] = data;
  11986. return this;
  11987. }
  11988. addExtraData(key, data) {
  11989. this.json.extras = this.json.extras || {};
  11990. this.json.extras[key] = data;
  11991. return this;
  11992. }
  11993. addObjectExtension(object, extensionName, data) {
  11994. object.extensions = object.extensions || {};
  11995. object.extensions[extensionName] = data;
  11996. this.registerUsedExtension(extensionName);
  11997. return this;
  11998. }
  11999. setObjectExtension(object, extensionName, data) {
  12000. const extensions = object.extensions || {};
  12001. extensions[extensionName] = data;
  12002. }
  12003. removeObjectExtension(object, extensionName) {
  12004. const extensions = object.extensions || {};
  12005. const extension = extensions[extensionName];
  12006. delete extensions[extensionName];
  12007. return extension;
  12008. }
  12009. addExtension(extensionName, extensionData = {}) {
  12010. assert$1(extensionData);
  12011. this.json.extensions = this.json.extensions || {};
  12012. this.json.extensions[extensionName] = extensionData;
  12013. this.registerUsedExtension(extensionName);
  12014. return extensionData;
  12015. }
  12016. addRequiredExtension(extensionName, extensionData = {}) {
  12017. assert$1(extensionData);
  12018. this.addExtension(extensionName, extensionData);
  12019. this.registerRequiredExtension(extensionName);
  12020. return extensionData;
  12021. }
  12022. registerUsedExtension(extensionName) {
  12023. this.json.extensionsUsed = this.json.extensionsUsed || [];
  12024. if (!this.json.extensionsUsed.find(ext => ext === extensionName)) {
  12025. this.json.extensionsUsed.push(extensionName);
  12026. }
  12027. }
  12028. registerRequiredExtension(extensionName) {
  12029. this.registerUsedExtension(extensionName);
  12030. this.json.extensionsRequired = this.json.extensionsRequired || [];
  12031. if (!this.json.extensionsRequired.find(ext => ext === extensionName)) {
  12032. this.json.extensionsRequired.push(extensionName);
  12033. }
  12034. }
  12035. removeExtension(extensionName) {
  12036. if (this.json.extensionsRequired) {
  12037. this._removeStringFromArray(this.json.extensionsRequired, extensionName);
  12038. }
  12039. if (this.json.extensionsUsed) {
  12040. this._removeStringFromArray(this.json.extensionsUsed, extensionName);
  12041. }
  12042. if (this.json.extensions) {
  12043. delete this.json.extensions[extensionName];
  12044. }
  12045. }
  12046. setDefaultScene(sceneIndex) {
  12047. this.json.scene = sceneIndex;
  12048. }
  12049. addScene(scene) {
  12050. const {
  12051. nodeIndices
  12052. } = scene;
  12053. this.json.scenes = this.json.scenes || [];
  12054. this.json.scenes.push({
  12055. nodes: nodeIndices
  12056. });
  12057. return this.json.scenes.length - 1;
  12058. }
  12059. addNode(node) {
  12060. const {
  12061. meshIndex,
  12062. matrix
  12063. } = node;
  12064. this.json.nodes = this.json.nodes || [];
  12065. const nodeData = {
  12066. mesh: meshIndex
  12067. };
  12068. if (matrix) {
  12069. nodeData.matrix = matrix;
  12070. }
  12071. this.json.nodes.push(nodeData);
  12072. return this.json.nodes.length - 1;
  12073. }
  12074. addMesh(mesh) {
  12075. const {
  12076. attributes,
  12077. indices,
  12078. material,
  12079. mode = 4
  12080. } = mesh;
  12081. const accessors = this._addAttributes(attributes);
  12082. const glTFMesh = {
  12083. primitives: [{
  12084. attributes: accessors,
  12085. mode
  12086. }]
  12087. };
  12088. if (indices) {
  12089. const indicesAccessor = this._addIndices(indices);
  12090. glTFMesh.primitives[0].indices = indicesAccessor;
  12091. }
  12092. if (Number.isFinite(material)) {
  12093. glTFMesh.primitives[0].material = material;
  12094. }
  12095. this.json.meshes = this.json.meshes || [];
  12096. this.json.meshes.push(glTFMesh);
  12097. return this.json.meshes.length - 1;
  12098. }
  12099. addPointCloud(attributes) {
  12100. const accessorIndices = this._addAttributes(attributes);
  12101. const glTFMesh = {
  12102. primitives: [{
  12103. attributes: accessorIndices,
  12104. mode: 0
  12105. }]
  12106. };
  12107. this.json.meshes = this.json.meshes || [];
  12108. this.json.meshes.push(glTFMesh);
  12109. return this.json.meshes.length - 1;
  12110. }
  12111. addImage(imageData, mimeTypeOpt) {
  12112. const metadata = getBinaryImageMetadata(imageData);
  12113. const mimeType = mimeTypeOpt || (metadata === null || metadata === void 0 ? void 0 : metadata.mimeType);
  12114. const bufferViewIndex = this.addBufferView(imageData);
  12115. const glTFImage = {
  12116. bufferView: bufferViewIndex,
  12117. mimeType
  12118. };
  12119. this.json.images = this.json.images || [];
  12120. this.json.images.push(glTFImage);
  12121. return this.json.images.length - 1;
  12122. }
  12123. addBufferView(buffer) {
  12124. const byteLength = buffer.byteLength;
  12125. assert$1(Number.isFinite(byteLength));
  12126. this.sourceBuffers = this.sourceBuffers || [];
  12127. this.sourceBuffers.push(buffer);
  12128. const glTFBufferView = {
  12129. buffer: 0,
  12130. byteOffset: this.byteLength,
  12131. byteLength
  12132. };
  12133. this.byteLength += padToNBytes(byteLength, 4);
  12134. this.json.bufferViews = this.json.bufferViews || [];
  12135. this.json.bufferViews.push(glTFBufferView);
  12136. return this.json.bufferViews.length - 1;
  12137. }
  12138. addAccessor(bufferViewIndex, accessor) {
  12139. const glTFAccessor = {
  12140. bufferView: bufferViewIndex,
  12141. type: getAccessorTypeFromSize(accessor.size),
  12142. componentType: accessor.componentType,
  12143. count: accessor.count,
  12144. max: accessor.max,
  12145. min: accessor.min
  12146. };
  12147. this.json.accessors = this.json.accessors || [];
  12148. this.json.accessors.push(glTFAccessor);
  12149. return this.json.accessors.length - 1;
  12150. }
  12151. addBinaryBuffer(sourceBuffer, accessor = {
  12152. size: 3
  12153. }) {
  12154. const bufferViewIndex = this.addBufferView(sourceBuffer);
  12155. let minMax = {
  12156. min: accessor.min,
  12157. max: accessor.max
  12158. };
  12159. if (!minMax.min || !minMax.max) {
  12160. minMax = this._getAccessorMinMax(sourceBuffer, accessor.size);
  12161. }
  12162. const accessorDefaults = {
  12163. size: accessor.size,
  12164. componentType: getComponentTypeFromArray(sourceBuffer),
  12165. count: Math.round(sourceBuffer.length / accessor.size),
  12166. min: minMax.min,
  12167. max: minMax.max
  12168. };
  12169. return this.addAccessor(bufferViewIndex, Object.assign(accessorDefaults, accessor));
  12170. }
  12171. addTexture(texture) {
  12172. const {
  12173. imageIndex
  12174. } = texture;
  12175. const glTFTexture = {
  12176. source: imageIndex
  12177. };
  12178. this.json.textures = this.json.textures || [];
  12179. this.json.textures.push(glTFTexture);
  12180. return this.json.textures.length - 1;
  12181. }
  12182. addMaterial(pbrMaterialInfo) {
  12183. this.json.materials = this.json.materials || [];
  12184. this.json.materials.push(pbrMaterialInfo);
  12185. return this.json.materials.length - 1;
  12186. }
  12187. createBinaryChunk() {
  12188. var _this$json, _this$json$buffers;
  12189. this.gltf.buffers = [];
  12190. const totalByteLength = this.byteLength;
  12191. const arrayBuffer = new ArrayBuffer(totalByteLength);
  12192. const targetArray = new Uint8Array(arrayBuffer);
  12193. let dstByteOffset = 0;
  12194. for (const sourceBuffer of this.sourceBuffers || []) {
  12195. dstByteOffset = copyToArray(sourceBuffer, targetArray, dstByteOffset);
  12196. }
  12197. if ((_this$json = this.json) !== null && _this$json !== void 0 && (_this$json$buffers = _this$json.buffers) !== null && _this$json$buffers !== void 0 && _this$json$buffers[0]) {
  12198. this.json.buffers[0].byteLength = totalByteLength;
  12199. } else {
  12200. this.json.buffers = [{
  12201. byteLength: totalByteLength
  12202. }];
  12203. }
  12204. this.gltf.binary = arrayBuffer;
  12205. this.sourceBuffers = [arrayBuffer];
  12206. }
  12207. _removeStringFromArray(array, string) {
  12208. let found = true;
  12209. while (found) {
  12210. const index = array.indexOf(string);
  12211. if (index > -1) {
  12212. array.splice(index, 1);
  12213. } else {
  12214. found = false;
  12215. }
  12216. }
  12217. }
  12218. _addAttributes(attributes = {}) {
  12219. const result = {};
  12220. for (const attributeKey in attributes) {
  12221. const attributeData = attributes[attributeKey];
  12222. const attrName = this._getGltfAttributeName(attributeKey);
  12223. const accessor = this.addBinaryBuffer(attributeData.value, attributeData);
  12224. result[attrName] = accessor;
  12225. }
  12226. return result;
  12227. }
  12228. _addIndices(indices) {
  12229. return this.addBinaryBuffer(indices, {
  12230. size: 1
  12231. });
  12232. }
  12233. _getGltfAttributeName(attributeName) {
  12234. switch (attributeName.toLowerCase()) {
  12235. case 'position':
  12236. case 'positions':
  12237. case 'vertices':
  12238. return 'POSITION';
  12239. case 'normal':
  12240. case 'normals':
  12241. return 'NORMAL';
  12242. case 'color':
  12243. case 'colors':
  12244. return 'COLOR_0';
  12245. case 'texcoord':
  12246. case 'texcoords':
  12247. return 'TEXCOORD_0';
  12248. default:
  12249. return attributeName;
  12250. }
  12251. }
  12252. _getAccessorMinMax(buffer, size) {
  12253. const result = {
  12254. min: null,
  12255. max: null
  12256. };
  12257. if (buffer.length < size) {
  12258. return result;
  12259. }
  12260. result.min = [];
  12261. result.max = [];
  12262. const initValues = buffer.subarray(0, size);
  12263. for (const value of initValues) {
  12264. result.min.push(value);
  12265. result.max.push(value);
  12266. }
  12267. for (let index = size; index < buffer.length; index += size) {
  12268. for (let componentIndex = 0; componentIndex < size; componentIndex++) {
  12269. result.min[0 + componentIndex] = Math.min(result.min[0 + componentIndex], buffer[index + componentIndex]);
  12270. result.max[0 + componentIndex] = Math.max(result.max[0 + componentIndex], buffer[index + componentIndex]);
  12271. }
  12272. }
  12273. return result;
  12274. }
  12275. }
  12276. const wasm_base = 'B9h9z9tFBBBF8fL9gBB9gLaaaaaFa9gEaaaB9gFaFa9gEaaaFaEMcBFFFGGGEIIILF9wFFFLEFBFKNFaFCx/IFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBF8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBGy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBEn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBIi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBKI9z9iqlBOc+x8ycGBM/qQFTa8jUUUUBCU/EBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAGTkUUUBRNCUoBAG9uC/wgBZHKCUGAKCUG9JyRVAECFJRICBRcGXEXAcAF9PQFAVAFAclAcAVJAF9JyRMGXGXAG9FQBAMCbJHKC9wZRSAKCIrCEJCGrRQANCUGJRfCBRbAIRTEXGXAOATlAQ9PQBCBRISEMATAQJRIGXAS9FQBCBRtCBREEXGXAOAIlCi9PQBCBRISLMANCU/CBJAEJRKGXGXGXGXGXATAECKrJ2BBAtCKZrCEZfIBFGEBMAKhB83EBAKCNJhB83EBSEMAKAI2BIAI2BBHmCKrHYAYCE6HYy86BBAKCFJAICIJAYJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCGJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCEJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCIJAYAmJHY2BBAI2BFHmCKrHPAPCE6HPy86BBAKCLJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCKJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCOJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCNJAYAmJHY2BBAI2BGHmCKrHPAPCE6HPy86BBAKCVJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCcJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCMJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCSJAYAmJHm2BBAI2BEHICKrHYAYCE6HYy86BBAKCQJAmAYJHm2BBAICIrCEZHYAYCE6HYy86BBAKCfJAmAYJHm2BBAICGrCEZHYAYCE6HYy86BBAKCbJAmAYJHK2BBAICEZHIAICE6HIy86BBAKAIJRISGMAKAI2BNAI2BBHmCIrHYAYCb6HYy86BBAKCFJAICNJAYJHY2BBAmCbZHmAmCb6Hmy86BBAKCGJAYAmJHm2BBAI2BFHYCIrHPAPCb6HPy86BBAKCEJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCIJAmAYJHm2BBAI2BGHYCIrHPAPCb6HPy86BBAKCLJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCKJAmAYJHm2BBAI2BEHYCIrHPAPCb6HPy86BBAKCOJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCNJAmAYJHm2BBAI2BIHYCIrHPAPCb6HPy86BBAKCVJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCcJAmAYJHm2BBAI2BLHYCIrHPAPCb6HPy86BBAKCMJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCSJAmAYJHm2BBAI2BKHYCIrHPAPCb6HPy86BBAKCQJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCfJAmAYJHm2BBAI2BOHICIrHYAYCb6HYy86BBAKCbJAmAYJHK2BBAICbZHIAICb6HIy86BBAKAIJRISFMAKAI8pBB83BBAKCNJAICNJ8pBB83BBAICTJRIMAtCGJRtAECTJHEAS9JQBMMGXAIQBCBRISEMGXAM9FQBANAbJ2BBRtCBRKAfREEXAEANCU/CBJAKJ2BBHTCFrCBATCFZl9zAtJHt86BBAEAGJREAKCFJHKAM9HQBMMAfCFJRfAIRTAbCFJHbAG9HQBMMABAcAG9sJANCUGJAMAG9sTkUUUBpANANCUGJAMCaJAG9sJAGTkUUUBpMAMCBAIyAcJRcAIQBMC9+RKSFMCBC99AOAIlAGCAAGCA9Ly6yRKMALCU/EBJ8kUUUUBAKM+OmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUFT+JUUUBpALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM+lLKFaF99GaG99FaG99GXGXAGCI9HQBAF9FQFEXGXGX9DBBB8/9DBBB+/ABCGJHG1BB+yAB1BBHE+yHI+L+TABCFJHL1BBHK+yHO+L+THN9DBBBB9gHVyAN9DBB/+hANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE86BBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG86BBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG86BBABCIJRBAFCaJHFQBSGMMAF9FQBEXGXGX9DBBB8/9DBBB+/ABCIJHG8uFB+yAB8uFBHE+yHI+L+TABCGJHL8uFBHK+yHO+L+THN9DBBBB9gHVyAN9DB/+g6ANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE87FBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG87FBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG87FBABCNJRBAFCaJHFQBMMM/SEIEaE99EaF99GXAF9FQBCBREABRIEXGXGX9D/zI818/AICKJ8uFBHLCEq+y+VHKAI8uFB+y+UHO9DB/+g6+U9DBBB8/9DBBB+/AO9DBBBB9gy+SHN+L9DBBB9P9d9FQBAN+oRVSFMCUUUU94RVMAICIJ8uFBRcAICGJ8uFBRMABALCFJCEZAEqCFWJAV87FBGXGXAKAM+y+UHN9DB/+g6+U9DBBB8/9DBBB+/AN9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRMSFMCUUUU94RMMABALCGJCEZAEqCFWJAM87FBGXGXAKAc+y+UHK9DB/+g6+U9DBBB8/9DBBB+/AK9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRcSFMCUUUU94RcMABALCaJCEZAEqCFWJAc87FBGXGX9DBBU8/AOAO+U+TANAN+U+TAKAK+U+THO9DBBBBAO9DBBBB9gy+R9DB/+g6+U9DBBB8/+SHO+L9DBBB9P9d9FQBAO+oRcSFMCUUUU94RcMABALCEZAEqCFWJAc87FBAICNJRIAECIJREAFCaJHFQBMMM9JBGXAGCGrAF9sHF9FQBEXABAB8oGBHGCNWCN91+yAGCi91CnWCUUU/8EJ+++U84GBABCIJRBAFCaJHFQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEM/lFFFaGXGXAFABqCEZ9FQBABRESFMGXGXAGCT9PQBABRESFMABREEXAEAF8oGBjGBAECIJAFCIJ8oGBjGBAECNJAFCNJ8oGBjGBAECSJAFCSJ8oGBjGBAECTJREAFCTJRFAGC9wJHGCb9LQBMMAGCI9JQBEXAEAF8oGBjGBAFCIJRFAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF2BB86BBAECFJREAFCFJRFAGCaJHGQBMMABMoFFGaGXGXABCEZ9FQBABRESFMAFCgFZC+BwsN9sRIGXGXAGCT9PQBABRESFMABREEXAEAIjGBAECSJAIjGBAECNJAIjGBAECIJAIjGBAECTJREAGC9wJHGCb9LQBMMAGCI9JQBEXAEAIjGBAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF86BBAECFJREAGCaJHGQBMMABMMMFBCUNMIT9kBB';
  12277. const wasm_simd = 'B9h9z9tFBBBF8dL9gBB9gLaaaaaFa9gEaaaB9gGaaB9gFaFaEQSBBFBFFGEGEGIILF9wFFFLEFBFKNFaFCx/aFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBG8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBIy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBKi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBNn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBcI9z9iqlBMc/j9JSIBTEM9+FLa8jUUUUBCTlRBCBRFEXCBRGCBREEXABCNJAGJAECUaAFAGrCFZHIy86BBAEAIJREAGCFJHGCN9HQBMAFCx+YUUBJAE86BBAFCEWCxkUUBJAB8pEN83EBAFCFJHFCUG9HQBMMkRIbaG97FaK978jUUUUBCU/KBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAG/8cBBCUoBAG9uC/wgBZHKCUGAKCUG9JyRNAECFJRKCBRVGXEXAVAF9PQFANAFAVlAVANJAF9JyRcGXGXAG9FQBAcCbJHIC9wZHMCE9sRSAMCFWRQAICIrCEJCGrRfCBRbEXAKRTCBRtGXEXGXAOATlAf9PQBCBRKSLMALCU/CBJAtAM9sJRmATAfJRKCBREGXAMCoB9JQBAOAKlC/gB9JQBCBRIEXAmAIJREGXGXGXGXGXATAICKrJ2BBHYCEZfIBFGEBMAECBDtDMIBSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAEAKDBBBDMIBAKCTJRKMGXGXGXGXGXAYCGrCEZfIBFGEBMAECBDtDMITSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAEAKDBBBDMITAKCTJRKMGXGXGXGXGXAYCIrCEZfIBFGEBMAECBDtDMIASEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAEAKDBBBDMIAAKCTJRKMGXGXGXGXGXAYCKrfIBFGEBMAECBDtDMI8wSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCIJAnDeBJAYCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCNJAnDeBJAYCx+YUUBJ2BBJRKSFMAEAKDBBBDMI8wAKCTJRKMAICoBJREAICUFJAM9LQFAERIAOAKlC/fB9LQBMMGXAEAM9PQBAECErRIEXGXAOAKlCi9PQBCBRKSOMAmAEJRYGXGXGXGXGXATAECKrJ2BBAICKZrCEZfIBFGEBMAYCBDtDMIBSEMAYAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAYAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAYAKDBBBDMIBAKCTJRKMAICGJRIAECTJHEAM9JQBMMGXAK9FQBAKRTAtCFJHtCI6QGSFMMCBRKSEMGXAM9FQBALCUGJAbJREALAbJDBGBRnCBRYEXAEALCU/CBJAYJHIDBIBHdCFD9tAdCFDbHPD9OD9hD9RHdAIAMJDBIBHiCFD9tAiAPD9OD9hD9RHiDQBTFtGmEYIPLdKeOnH8ZAIAQJDBIBHpCFD9tApAPD9OD9hD9RHpAIASJDBIBHyCFD9tAyAPD9OD9hD9RHyDQBTFtGmEYIPLdKeOnH8cDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGEAnD9uHnDyBjGBAEAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJHIAnA8ZA8cDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHnDyBjGBAIAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJHIAnAdAiDQNiV8ZcpMyS8cQ8df8eb8fHdApAyDQNiV8ZcpMyS8cQ8df8eb8fHiDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGED9uHnDyBjGBAIAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJHIAnAdAiDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHnDyBjGBAIAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJREAYCTJHYAM9JQBMMAbCIJHbAG9JQBMMABAVAG9sJALCUGJAcAG9s/8cBBALALCUGJAcCaJAG9sJAG/8cBBMAcCBAKyAVJRVAKQBMC9+RKSFMCBC99AOAKlAGCAAGCA9Ly6yRKMALCU/KBJ8kUUUUBAKMNBT+BUUUBM+KmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUF/8MBALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM/xLGEaK978jUUUUBCAlHE8kUUUUBGXGXAGCI9HQBGXAFC98ZHI9FQBABRGCBRLEXAGAGDBBBHKCiD+rFCiD+sFD/6FHOAKCND+rFCiD+sFD/6FAOD/gFAKCTD+rFCiD+sFD/6FHND/gFD/kFD/lFHVCBDtD+2FHcAOCUUUU94DtHMD9OD9RD/kFHO9DBB/+hDYAOAOD/mFAVAVD/mFANAcANAMD9OD9RD/kFHOAOD/mFD/kFD/kFD/jFD/nFHND/mF9DBBX9LDYHcD/kFCgFDtD9OAKCUUU94DtD9OD9QAOAND/mFAcD/kFCND+rFCU/+EDtD9OD9QAVAND/mFAcD/kFCTD+rFCUU/8ODtD9OD9QDMBBAGCTJRGALCIJHLAI9JQBMMAIAF9PQFAEAFCEZHLCGWHGqCBCTAGl/8MBAEABAICGWJHIAG/8cBBGXAL9FQBAEAEDBIBHKCiD+rFCiD+sFD/6FHOAKCND+rFCiD+sFD/6FAOD/gFAKCTD+rFCiD+sFD/6FHND/gFD/kFD/lFHVCBDtD+2FHcAOCUUUU94DtHMD9OD9RD/kFHO9DBB/+hDYAOAOD/mFAVAVD/mFANAcANAMD9OD9RD/kFHOAOD/mFD/kFD/kFD/jFD/nFHND/mF9DBBX9LDYHcD/kFCgFDtD9OAKCUUU94DtD9OD9QAOAND/mFAcD/kFCND+rFCU/+EDtD9OD9QAVAND/mFAcD/kFCTD+rFCUU/8ODtD9OD9QDMIBMAIAEAG/8cBBSFMABAFC98ZHGT+HUUUBAGAF9PQBAEAFCEZHICEWHLJCBCAALl/8MBAEABAGCEWJHGAL/8cBBAEAIT+HUUUBAGAEAL/8cBBMAECAJ8kUUUUBM+yEGGaO97GXAF9FQBCBRGEXABCTJHEAEDBBBHICBDtHLCUU98D8cFCUU98D8cEHKD9OABDBBBHOAIDQILKOSQfbPden8c8d8e8fCggFDtD9OD/6FAOAIDQBFGENVcMTtmYi8ZpyHICTD+sFD/6FHND/gFAICTD+rFCTD+sFD/6FHVD/gFD/kFD/lFHI9DB/+g6DYAVAIALD+2FHLAVCUUUU94DtHcD9OD9RD/kFHVAVD/mFAIAID/mFANALANAcD9OD9RD/kFHIAID/mFD/kFD/kFD/jFD/nFHND/mF9DBBX9LDYHLD/kFCTD+rFAVAND/mFALD/kFCggEDtD9OD9QHVAIAND/mFALD/kFCaDbCBDnGCBDnECBDnKCBDnOCBDncCBDnMCBDnfCBDnbD9OHIDQNVi8ZcMpySQ8c8dfb8e8fD9QDMBBABAOAKD9OAVAIDQBFTtGEmYILPdKOenD9QDMBBABCAJRBAGCIJHGAF9JQBMMM94FEa8jUUUUBCAlHE8kUUUUBABAFC98ZHIT+JUUUBGXAIAF9PQBAEAFCEZHLCEWHFJCBCAAFl/8MBAEABAICEWJHBAF/8cBBAEALT+JUUUBABAEAF/8cBBMAECAJ8kUUUUBM/hEIGaF97FaL978jUUUUBCTlRGGXAF9FQBCBREEXAGABDBBBHIABCTJHLDBBBHKDQILKOSQfbPden8c8d8e8fHOCTD+sFHNCID+rFDMIBAB9DBBU8/DY9D/zI818/DYANCEDtD9QD/6FD/nFHNAIAKDQBFGENVcMTtmYi8ZpyHICTD+rFCTD+sFD/6FD/mFHKAKD/mFANAICTD+sFD/6FD/mFHVAVD/mFANAOCTD+rFCTD+sFD/6FD/mFHOAOD/mFD/kFD/kFD/lFCBDtD+4FD/jF9DB/+g6DYHND/mF9DBBX9LDYHID/kFCggEDtHcD9OAVAND/mFAID/kFCTD+rFD9QHVAOAND/mFAID/kFCTD+rFAKAND/mFAID/kFAcD9OD9QHNDQBFTtGEmYILPdKOenHID8dBAGDBIBDyB+t+J83EBABCNJAID8dFAGDBIBDyF+t+J83EBALAVANDQNVi8ZcMpySQ8c8dfb8e8fHND8dBAGDBIBDyG+t+J83EBABCiJAND8dFAGDBIBDyE+t+J83EBABCAJRBAECIJHEAF9JQBMMM/3FGEaF978jUUUUBCoBlREGXAGCGrAF9sHIC98ZHL9FQBCBRGABRFEXAFAFDBBBHKCND+rFCND+sFD/6FAKCiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMBBAFCTJRFAGCIJHGAL9JQBMMGXALAI9PQBAEAICEZHGCGWHFqCBCoBAFl/8MBAEABALCGWJHLAF/8cBBGXAG9FQBAEAEDBIBHKCND+rFCND+sFD/6FAKCiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMIBMALAEAF/8cBBMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEMMMFBCUNMIT9tBB';
  12278. const detector = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 3, 2, 0, 0, 5, 3, 1, 0, 1, 12, 1, 0, 10, 22, 2, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0, 11, 7, 0, 65, 0, 253, 15, 26, 11]);
  12279. const wasmpack = new Uint8Array([32, 0, 65, 253, 3, 1, 2, 34, 4, 106, 6, 5, 11, 8, 7, 20, 13, 33, 12, 16, 128, 9, 116, 64, 19, 113, 127, 15, 10, 21, 22, 14, 255, 66, 24, 54, 136, 107, 18, 23, 192, 26, 114, 118, 132, 17, 77, 101, 130, 144, 27, 87, 131, 44, 45, 74, 156, 154, 70, 167]);
  12280. const FILTERS = {
  12281. 0: '',
  12282. 1: 'meshopt_decodeFilterOct',
  12283. 2: 'meshopt_decodeFilterQuat',
  12284. 3: 'meshopt_decodeFilterExp',
  12285. NONE: '',
  12286. OCTAHEDRAL: 'meshopt_decodeFilterOct',
  12287. QUATERNION: 'meshopt_decodeFilterQuat',
  12288. EXPONENTIAL: 'meshopt_decodeFilterExp'
  12289. };
  12290. const DECODERS = {
  12291. 0: 'meshopt_decodeVertexBuffer',
  12292. 1: 'meshopt_decodeIndexBuffer',
  12293. 2: 'meshopt_decodeIndexSequence',
  12294. ATTRIBUTES: 'meshopt_decodeVertexBuffer',
  12295. TRIANGLES: 'meshopt_decodeIndexBuffer',
  12296. INDICES: 'meshopt_decodeIndexSequence'
  12297. };
  12298. async function meshoptDecodeGltfBuffer(target, count, size, source, mode, filter = 'NONE') {
  12299. const instance = await loadWasmInstance();
  12300. decode$5(instance, instance.exports[DECODERS[mode]], target, count, size, source, instance.exports[FILTERS[filter || 'NONE']]);
  12301. }
  12302. let wasmPromise;
  12303. async function loadWasmInstance() {
  12304. if (!wasmPromise) {
  12305. wasmPromise = loadWasmModule();
  12306. }
  12307. return wasmPromise;
  12308. }
  12309. async function loadWasmModule() {
  12310. let wasm = wasm_base;
  12311. if (WebAssembly.validate(detector)) {
  12312. wasm = wasm_simd;
  12313. console.log('Warning: meshopt_decoder is using experimental SIMD support');
  12314. }
  12315. const result = await WebAssembly.instantiate(unpack(wasm), {});
  12316. await result.instance.exports.__wasm_call_ctors();
  12317. return result.instance;
  12318. }
  12319. function unpack(data) {
  12320. const result = new Uint8Array(data.length);
  12321. for (let i = 0; i < data.length; ++i) {
  12322. const ch = data.charCodeAt(i);
  12323. result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  12324. }
  12325. let write = 0;
  12326. for (let i = 0; i < data.length; ++i) {
  12327. result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  12328. }
  12329. return result.buffer.slice(0, write);
  12330. }
  12331. function decode$5(instance, fun, target, count, size, source, filter) {
  12332. const sbrk = instance.exports.sbrk;
  12333. const count4 = count + 3 & ~3;
  12334. const tp = sbrk(count4 * size);
  12335. const sp = sbrk(source.length);
  12336. const heap = new Uint8Array(instance.exports.memory.buffer);
  12337. heap.set(source, sp);
  12338. const res = fun(tp, count, size, sp, source.length);
  12339. if (res === 0 && filter) {
  12340. filter(tp, count4, size);
  12341. }
  12342. target.set(heap.subarray(tp, tp + count * size));
  12343. sbrk(tp - sbrk(0));
  12344. if (res !== 0) {
  12345. throw new Error("Malformed buffer data: ".concat(res));
  12346. }
  12347. }
  12348. const EXT_MESHOPT_COMPRESSION = 'EXT_meshopt_compression';
  12349. const name$6 = EXT_MESHOPT_COMPRESSION;
  12350. async function decode$4(gltfData, options) {
  12351. var _options$gltf;
  12352. const scenegraph = new GLTFScenegraph(gltfData);
  12353. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  12354. return;
  12355. }
  12356. const promises = [];
  12357. for (const bufferViewIndex of gltfData.json.bufferViews || []) {
  12358. promises.push(decodeMeshoptBufferView(scenegraph, bufferViewIndex));
  12359. }
  12360. await Promise.all(promises);
  12361. scenegraph.removeExtension(EXT_MESHOPT_COMPRESSION);
  12362. }
  12363. async function decodeMeshoptBufferView(scenegraph, bufferView) {
  12364. const meshoptExtension = scenegraph.getObjectExtension(bufferView, EXT_MESHOPT_COMPRESSION);
  12365. if (meshoptExtension) {
  12366. const {
  12367. byteOffset = 0,
  12368. byteLength = 0,
  12369. byteStride,
  12370. count,
  12371. mode,
  12372. filter = 'NONE',
  12373. buffer: bufferIndex
  12374. } = meshoptExtension;
  12375. const buffer = scenegraph.gltf.buffers[bufferIndex];
  12376. const source = new Uint8Array(buffer.arrayBuffer, buffer.byteOffset + byteOffset, byteLength);
  12377. const result = new Uint8Array(scenegraph.gltf.buffers[bufferView.buffer].arrayBuffer, bufferView.byteOffset, bufferView.byteLength);
  12378. await meshoptDecodeGltfBuffer(result, count, byteStride, source, mode, filter);
  12379. return result;
  12380. }
  12381. return null;
  12382. }
  12383. var EXT_meshopt_compression = /*#__PURE__*/Object.freeze({
  12384. __proto__: null,
  12385. name: name$6,
  12386. decode: decode$4
  12387. });
  12388. const EXT_TEXTURE_WEBP = 'EXT_texture_webp';
  12389. const name$5 = EXT_TEXTURE_WEBP;
  12390. function preprocess$3(gltfData, options) {
  12391. const scenegraph = new GLTFScenegraph(gltfData);
  12392. if (!_isImageFormatSupported('image/webp')) {
  12393. if (scenegraph.getRequiredExtensions().includes(EXT_TEXTURE_WEBP)) {
  12394. throw new Error("gltf: Required extension ".concat(EXT_TEXTURE_WEBP, " not supported by browser"));
  12395. }
  12396. return;
  12397. }
  12398. const {
  12399. json
  12400. } = scenegraph;
  12401. for (const texture of json.textures || []) {
  12402. const extension = scenegraph.getObjectExtension(texture, EXT_TEXTURE_WEBP);
  12403. if (extension) {
  12404. texture.source = extension.source;
  12405. }
  12406. scenegraph.removeObjectExtension(texture, EXT_TEXTURE_WEBP);
  12407. }
  12408. scenegraph.removeExtension(EXT_TEXTURE_WEBP);
  12409. }
  12410. var EXT_texture_webp = /*#__PURE__*/Object.freeze({
  12411. __proto__: null,
  12412. name: name$5,
  12413. preprocess: preprocess$3
  12414. });
  12415. const KHR_TEXTURE_BASISU = 'KHR_texture_basisu';
  12416. const name$4 = KHR_TEXTURE_BASISU;
  12417. function preprocess$2(gltfData, options) {
  12418. const scene = new GLTFScenegraph(gltfData);
  12419. const {
  12420. json
  12421. } = scene;
  12422. for (const texture of json.textures || []) {
  12423. const extension = scene.getObjectExtension(texture, KHR_TEXTURE_BASISU);
  12424. if (extension) {
  12425. texture.source = extension.source;
  12426. }
  12427. scene.removeObjectExtension(texture, KHR_TEXTURE_BASISU);
  12428. }
  12429. scene.removeExtension(KHR_TEXTURE_BASISU);
  12430. }
  12431. var KHR_texture_basisu = /*#__PURE__*/Object.freeze({
  12432. __proto__: null,
  12433. name: name$4,
  12434. preprocess: preprocess$2
  12435. });
  12436. function getGLTFAccessors(attributes) {
  12437. const accessors = {};
  12438. for (const name in attributes) {
  12439. const attribute = attributes[name];
  12440. if (name !== 'indices') {
  12441. const glTFAccessor = getGLTFAccessor(attribute);
  12442. accessors[name] = glTFAccessor;
  12443. }
  12444. }
  12445. return accessors;
  12446. }
  12447. function getGLTFAccessor(attribute) {
  12448. const {
  12449. buffer,
  12450. size,
  12451. count
  12452. } = getAccessorData(attribute);
  12453. const glTFAccessor = {
  12454. value: buffer,
  12455. size,
  12456. byteOffset: 0,
  12457. count,
  12458. type: getAccessorTypeFromSize(size),
  12459. componentType: getComponentTypeFromArray(buffer)
  12460. };
  12461. return glTFAccessor;
  12462. }
  12463. function getAccessorData(attribute) {
  12464. let buffer = attribute;
  12465. let size = 1;
  12466. let count = 0;
  12467. if (attribute && attribute.value) {
  12468. buffer = attribute.value;
  12469. size = attribute.size || 1;
  12470. }
  12471. if (buffer) {
  12472. if (!ArrayBuffer.isView(buffer)) {
  12473. buffer = toTypedArray(buffer, Float32Array);
  12474. }
  12475. count = buffer.length / size;
  12476. }
  12477. return {
  12478. buffer,
  12479. size,
  12480. count
  12481. };
  12482. }
  12483. function toTypedArray(array, ArrayType, convertTypedArrays = false) {
  12484. if (!array) {
  12485. return null;
  12486. }
  12487. if (Array.isArray(array)) {
  12488. return new ArrayType(array);
  12489. }
  12490. if (convertTypedArrays && !(array instanceof ArrayType)) {
  12491. return new ArrayType(array);
  12492. }
  12493. return array;
  12494. }
  12495. const KHR_DRACO_MESH_COMPRESSION = 'KHR_draco_mesh_compression';
  12496. const name$3 = KHR_DRACO_MESH_COMPRESSION;
  12497. function preprocess$1(gltfData, options, context) {
  12498. const scenegraph = new GLTFScenegraph(gltfData);
  12499. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12500. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) ;
  12501. }
  12502. }
  12503. async function decode$3(gltfData, options, context) {
  12504. var _options$gltf;
  12505. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  12506. return;
  12507. }
  12508. const scenegraph = new GLTFScenegraph(gltfData);
  12509. const promises = [];
  12510. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12511. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) {
  12512. promises.push(decompressPrimitive(scenegraph, primitive, options, context));
  12513. }
  12514. }
  12515. await Promise.all(promises);
  12516. scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);
  12517. }
  12518. function encode$3(gltfData, options = {}) {
  12519. const scenegraph = new GLTFScenegraph(gltfData);
  12520. for (const mesh of scenegraph.json.meshes || []) {
  12521. compressMesh(mesh);
  12522. scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
  12523. }
  12524. }
  12525. async function decompressPrimitive(scenegraph, primitive, options, context) {
  12526. const dracoExtension = scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION);
  12527. if (!dracoExtension) {
  12528. return;
  12529. }
  12530. const buffer = scenegraph.getTypedArrayForBufferView(dracoExtension.bufferView);
  12531. const bufferCopy = sliceArrayBuffer(buffer.buffer, buffer.byteOffset);
  12532. const {
  12533. parse
  12534. } = context;
  12535. const dracoOptions = { ...options
  12536. };
  12537. delete dracoOptions['3d-tiles'];
  12538. const decodedData = await parse(bufferCopy, DracoLoader, dracoOptions, context);
  12539. const decodedAttributes = getGLTFAccessors(decodedData.attributes);
  12540. for (const [attributeName, decodedAttribute] of Object.entries(decodedAttributes)) {
  12541. if (attributeName in primitive.attributes) {
  12542. const accessorIndex = primitive.attributes[attributeName];
  12543. const accessor = scenegraph.getAccessor(accessorIndex);
  12544. if (accessor !== null && accessor !== void 0 && accessor.min && accessor !== null && accessor !== void 0 && accessor.max) {
  12545. decodedAttribute.min = accessor.min;
  12546. decodedAttribute.max = accessor.max;
  12547. }
  12548. }
  12549. }
  12550. primitive.attributes = decodedAttributes;
  12551. if (decodedData.indices) {
  12552. primitive.indices = getGLTFAccessor(decodedData.indices);
  12553. }
  12554. checkPrimitive(primitive);
  12555. }
  12556. function compressMesh(attributes, indices, mode = 4, options, context) {
  12557. var _context$parseSync;
  12558. if (!options.DracoWriter) {
  12559. throw new Error('options.gltf.DracoWriter not provided');
  12560. }
  12561. const compressedData = options.DracoWriter.encodeSync({
  12562. attributes
  12563. });
  12564. const decodedData = context === null || context === void 0 ? void 0 : (_context$parseSync = context.parseSync) === null || _context$parseSync === void 0 ? void 0 : _context$parseSync.call(context, {
  12565. attributes
  12566. });
  12567. const fauxAccessors = options._addFauxAttributes(decodedData.attributes);
  12568. const bufferViewIndex = options.addBufferView(compressedData);
  12569. const glTFMesh = {
  12570. primitives: [{
  12571. attributes: fauxAccessors,
  12572. mode,
  12573. extensions: {
  12574. [KHR_DRACO_MESH_COMPRESSION]: {
  12575. bufferView: bufferViewIndex,
  12576. attributes: fauxAccessors
  12577. }
  12578. }
  12579. }]
  12580. };
  12581. return glTFMesh;
  12582. }
  12583. function checkPrimitive(primitive) {
  12584. if (!primitive.attributes && Object.keys(primitive.attributes).length > 0) {
  12585. throw new Error('glTF: Empty primitive detected: Draco decompression failure?');
  12586. }
  12587. }
  12588. function* makeMeshPrimitiveIterator(scenegraph) {
  12589. for (const mesh of scenegraph.json.meshes || []) {
  12590. for (const primitive of mesh.primitives) {
  12591. yield primitive;
  12592. }
  12593. }
  12594. }
  12595. var KHR_draco_mesh_compression = /*#__PURE__*/Object.freeze({
  12596. __proto__: null,
  12597. name: name$3,
  12598. preprocess: preprocess$1,
  12599. decode: decode$3,
  12600. encode: encode$3
  12601. });
  12602. const KHR_LIGHTS_PUNCTUAL = 'KHR_lights_punctual';
  12603. const name$2 = KHR_LIGHTS_PUNCTUAL;
  12604. async function decode$2(gltfData) {
  12605. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12606. const {
  12607. json
  12608. } = gltfScenegraph;
  12609. const extension = gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL);
  12610. if (extension) {
  12611. gltfScenegraph.json.lights = extension.lights;
  12612. gltfScenegraph.removeExtension(KHR_LIGHTS_PUNCTUAL);
  12613. }
  12614. for (const node of json.nodes || []) {
  12615. const nodeExtension = gltfScenegraph.getObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12616. if (nodeExtension) {
  12617. node.light = nodeExtension.light;
  12618. }
  12619. gltfScenegraph.removeObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12620. }
  12621. }
  12622. async function encode$2(gltfData) {
  12623. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12624. const {
  12625. json
  12626. } = gltfScenegraph;
  12627. if (json.lights) {
  12628. const extension = gltfScenegraph.addExtension(KHR_LIGHTS_PUNCTUAL);
  12629. assert$1(!extension.lights);
  12630. extension.lights = json.lights;
  12631. delete json.lights;
  12632. }
  12633. if (gltfScenegraph.json.lights) {
  12634. for (const light of gltfScenegraph.json.lights) {
  12635. const node = light.node;
  12636. gltfScenegraph.addObjectExtension(node, KHR_LIGHTS_PUNCTUAL, light);
  12637. }
  12638. delete gltfScenegraph.json.lights;
  12639. }
  12640. }
  12641. var KHR_lights_punctual = /*#__PURE__*/Object.freeze({
  12642. __proto__: null,
  12643. name: name$2,
  12644. decode: decode$2,
  12645. encode: encode$2
  12646. });
  12647. const KHR_MATERIALS_UNLIT = 'KHR_materials_unlit';
  12648. const name$1 = KHR_MATERIALS_UNLIT;
  12649. async function decode$1(gltfData) {
  12650. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12651. const {
  12652. json
  12653. } = gltfScenegraph;
  12654. gltfScenegraph.removeExtension(KHR_MATERIALS_UNLIT);
  12655. for (const material of json.materials || []) {
  12656. const extension = material.extensions && material.extensions.KHR_materials_unlit;
  12657. if (extension) {
  12658. material.unlit = true;
  12659. }
  12660. gltfScenegraph.removeObjectExtension(material, KHR_MATERIALS_UNLIT);
  12661. }
  12662. }
  12663. function encode$1(gltfData) {
  12664. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12665. const {
  12666. json
  12667. } = gltfScenegraph;
  12668. if (gltfScenegraph.materials) {
  12669. for (const material of json.materials || []) {
  12670. if (material.unlit) {
  12671. delete material.unlit;
  12672. gltfScenegraph.addObjectExtension(material, KHR_MATERIALS_UNLIT, {});
  12673. gltfScenegraph.addExtension(KHR_MATERIALS_UNLIT);
  12674. }
  12675. }
  12676. }
  12677. }
  12678. var KHR_materials_unlit = /*#__PURE__*/Object.freeze({
  12679. __proto__: null,
  12680. name: name$1,
  12681. decode: decode$1,
  12682. encode: encode$1
  12683. });
  12684. const KHR_TECHNIQUES_WEBGL = 'KHR_techniques_webgl';
  12685. const name = KHR_TECHNIQUES_WEBGL;
  12686. async function decode(gltfData) {
  12687. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12688. const {
  12689. json
  12690. } = gltfScenegraph;
  12691. const extension = gltfScenegraph.getExtension(KHR_TECHNIQUES_WEBGL);
  12692. if (extension) {
  12693. const techniques = resolveTechniques(extension, gltfScenegraph);
  12694. for (const material of json.materials || []) {
  12695. const materialExtension = gltfScenegraph.getObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12696. if (materialExtension) {
  12697. material.technique = Object.assign({}, materialExtension, techniques[materialExtension.technique]);
  12698. material.technique.values = resolveValues(material.technique, gltfScenegraph);
  12699. }
  12700. gltfScenegraph.removeObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12701. }
  12702. gltfScenegraph.removeExtension(KHR_TECHNIQUES_WEBGL);
  12703. }
  12704. }
  12705. async function encode(gltfData, options) {}
  12706. function resolveTechniques(techniquesExtension, gltfScenegraph) {
  12707. const {
  12708. programs = [],
  12709. shaders = [],
  12710. techniques = []
  12711. } = techniquesExtension;
  12712. const textDecoder = new TextDecoder();
  12713. shaders.forEach(shader => {
  12714. if (Number.isFinite(shader.bufferView)) {
  12715. shader.code = textDecoder.decode(gltfScenegraph.getTypedArrayForBufferView(shader.bufferView));
  12716. } else {
  12717. throw new Error('KHR_techniques_webgl: no shader code');
  12718. }
  12719. });
  12720. programs.forEach(program => {
  12721. program.fragmentShader = shaders[program.fragmentShader];
  12722. program.vertexShader = shaders[program.vertexShader];
  12723. });
  12724. techniques.forEach(technique => {
  12725. technique.program = programs[technique.program];
  12726. });
  12727. return techniques;
  12728. }
  12729. function resolveValues(technique, gltfScenegraph) {
  12730. const values = Object.assign({}, technique.values);
  12731. Object.keys(technique.uniforms || {}).forEach(uniform => {
  12732. if (technique.uniforms[uniform].value && !(uniform in values)) {
  12733. values[uniform] = technique.uniforms[uniform].value;
  12734. }
  12735. });
  12736. Object.keys(values).forEach(uniform => {
  12737. if (typeof values[uniform] === 'object' && values[uniform].index !== undefined) {
  12738. values[uniform].texture = gltfScenegraph.getTexture(values[uniform].index);
  12739. }
  12740. });
  12741. return values;
  12742. }
  12743. var KHR_techniques_webgl = /*#__PURE__*/Object.freeze({
  12744. __proto__: null,
  12745. name: name,
  12746. decode: decode,
  12747. encode: encode
  12748. });
  12749. const EXTENSIONS = [EXT_meshopt_compression, EXT_texture_webp, KHR_texture_basisu, KHR_draco_mesh_compression, KHR_lights_punctual, KHR_materials_unlit, KHR_techniques_webgl];
  12750. function preprocessExtensions(gltf, options = {}, context) {
  12751. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12752. for (const extension of extensions) {
  12753. var _extension$preprocess;
  12754. (_extension$preprocess = extension.preprocess) === null || _extension$preprocess === void 0 ? void 0 : _extension$preprocess.call(extension, gltf, options, context);
  12755. }
  12756. }
  12757. async function decodeExtensions(gltf, options = {}, context) {
  12758. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12759. for (const extension of extensions) {
  12760. var _extension$decode;
  12761. await ((_extension$decode = extension.decode) === null || _extension$decode === void 0 ? void 0 : _extension$decode.call(extension, gltf, options, context));
  12762. }
  12763. }
  12764. function useExtension(extensionName, options) {
  12765. var _options$gltf;
  12766. const excludes = (options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.excludeExtensions) || {};
  12767. const exclude = extensionName in excludes && !excludes[extensionName];
  12768. return !exclude;
  12769. }
  12770. const KHR_BINARY_GLTF = 'KHR_binary_glTF';
  12771. function preprocess(gltfData) {
  12772. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12773. const {
  12774. json
  12775. } = gltfScenegraph;
  12776. for (const image of json.images || []) {
  12777. const extension = gltfScenegraph.getObjectExtension(image, KHR_BINARY_GLTF);
  12778. if (extension) {
  12779. Object.assign(image, extension);
  12780. }
  12781. gltfScenegraph.removeObjectExtension(image, KHR_BINARY_GLTF);
  12782. }
  12783. if (json.buffers && json.buffers[0]) {
  12784. delete json.buffers[0].uri;
  12785. }
  12786. gltfScenegraph.removeExtension(KHR_BINARY_GLTF);
  12787. }
  12788. const GLTF_ARRAYS = {
  12789. accessors: 'accessor',
  12790. animations: 'animation',
  12791. buffers: 'buffer',
  12792. bufferViews: 'bufferView',
  12793. images: 'image',
  12794. materials: 'material',
  12795. meshes: 'mesh',
  12796. nodes: 'node',
  12797. samplers: 'sampler',
  12798. scenes: 'scene',
  12799. skins: 'skin',
  12800. textures: 'texture'
  12801. };
  12802. const GLTF_KEYS = {
  12803. accessor: 'accessors',
  12804. animations: 'animation',
  12805. buffer: 'buffers',
  12806. bufferView: 'bufferViews',
  12807. image: 'images',
  12808. material: 'materials',
  12809. mesh: 'meshes',
  12810. node: 'nodes',
  12811. sampler: 'samplers',
  12812. scene: 'scenes',
  12813. skin: 'skins',
  12814. texture: 'textures'
  12815. };
  12816. class GLTFV1Normalizer {
  12817. constructor() {
  12818. _defineProperty(this, "idToIndexMap", {
  12819. animations: {},
  12820. accessors: {},
  12821. buffers: {},
  12822. bufferViews: {},
  12823. images: {},
  12824. materials: {},
  12825. meshes: {},
  12826. nodes: {},
  12827. samplers: {},
  12828. scenes: {},
  12829. skins: {},
  12830. textures: {}
  12831. });
  12832. _defineProperty(this, "json", void 0);
  12833. }
  12834. normalize(gltf, options) {
  12835. this.json = gltf.json;
  12836. const json = gltf.json;
  12837. switch (json.asset && json.asset.version) {
  12838. case '2.0':
  12839. return;
  12840. case undefined:
  12841. case '1.0':
  12842. break;
  12843. default:
  12844. console.warn("glTF: Unknown version ".concat(json.asset.version));
  12845. return;
  12846. }
  12847. if (!options.normalize) {
  12848. throw new Error('glTF v1 is not supported.');
  12849. }
  12850. console.warn('Converting glTF v1 to glTF v2 format. This is experimental and may fail.');
  12851. this._addAsset(json);
  12852. this._convertTopLevelObjectsToArrays(json);
  12853. preprocess(gltf);
  12854. this._convertObjectIdsToArrayIndices(json);
  12855. this._updateObjects(json);
  12856. this._updateMaterial(json);
  12857. }
  12858. _addAsset(json) {
  12859. json.asset = json.asset || {};
  12860. json.asset.version = '2.0';
  12861. json.asset.generator = json.asset.generator || 'Normalized to glTF 2.0 by loaders.gl';
  12862. }
  12863. _convertTopLevelObjectsToArrays(json) {
  12864. for (const arrayName in GLTF_ARRAYS) {
  12865. this._convertTopLevelObjectToArray(json, arrayName);
  12866. }
  12867. }
  12868. _convertTopLevelObjectToArray(json, mapName) {
  12869. const objectMap = json[mapName];
  12870. if (!objectMap || Array.isArray(objectMap)) {
  12871. return;
  12872. }
  12873. json[mapName] = [];
  12874. for (const id in objectMap) {
  12875. const object = objectMap[id];
  12876. object.id = object.id || id;
  12877. const index = json[mapName].length;
  12878. json[mapName].push(object);
  12879. this.idToIndexMap[mapName][id] = index;
  12880. }
  12881. }
  12882. _convertObjectIdsToArrayIndices(json) {
  12883. for (const arrayName in GLTF_ARRAYS) {
  12884. this._convertIdsToIndices(json, arrayName);
  12885. }
  12886. if ('scene' in json) {
  12887. json.scene = this._convertIdToIndex(json.scene, 'scene');
  12888. }
  12889. for (const texture of json.textures) {
  12890. this._convertTextureIds(texture);
  12891. }
  12892. for (const mesh of json.meshes) {
  12893. this._convertMeshIds(mesh);
  12894. }
  12895. for (const node of json.nodes) {
  12896. this._convertNodeIds(node);
  12897. }
  12898. for (const node of json.scenes) {
  12899. this._convertSceneIds(node);
  12900. }
  12901. }
  12902. _convertTextureIds(texture) {
  12903. if (texture.source) {
  12904. texture.source = this._convertIdToIndex(texture.source, 'image');
  12905. }
  12906. }
  12907. _convertMeshIds(mesh) {
  12908. for (const primitive of mesh.primitives) {
  12909. const {
  12910. attributes,
  12911. indices,
  12912. material
  12913. } = primitive;
  12914. for (const attributeName in attributes) {
  12915. attributes[attributeName] = this._convertIdToIndex(attributes[attributeName], 'accessor');
  12916. }
  12917. if (indices) {
  12918. primitive.indices = this._convertIdToIndex(indices, 'accessor');
  12919. }
  12920. if (material) {
  12921. primitive.material = this._convertIdToIndex(material, 'material');
  12922. }
  12923. }
  12924. }
  12925. _convertNodeIds(node) {
  12926. if (node.children) {
  12927. node.children = node.children.map(child => this._convertIdToIndex(child, 'node'));
  12928. }
  12929. if (node.meshes) {
  12930. node.meshes = node.meshes.map(mesh => this._convertIdToIndex(mesh, 'mesh'));
  12931. }
  12932. }
  12933. _convertSceneIds(scene) {
  12934. if (scene.nodes) {
  12935. scene.nodes = scene.nodes.map(node => this._convertIdToIndex(node, 'node'));
  12936. }
  12937. }
  12938. _convertIdsToIndices(json, topLevelArrayName) {
  12939. if (!json[topLevelArrayName]) {
  12940. console.warn("gltf v1: json doesn't contain attribute ".concat(topLevelArrayName));
  12941. json[topLevelArrayName] = [];
  12942. }
  12943. for (const object of json[topLevelArrayName]) {
  12944. for (const key in object) {
  12945. const id = object[key];
  12946. const index = this._convertIdToIndex(id, key);
  12947. object[key] = index;
  12948. }
  12949. }
  12950. }
  12951. _convertIdToIndex(id, key) {
  12952. const arrayName = GLTF_KEYS[key];
  12953. if (arrayName in this.idToIndexMap) {
  12954. const index = this.idToIndexMap[arrayName][id];
  12955. if (!Number.isFinite(index)) {
  12956. throw new Error("gltf v1: failed to resolve ".concat(key, " with id ").concat(id));
  12957. }
  12958. return index;
  12959. }
  12960. return id;
  12961. }
  12962. _updateObjects(json) {
  12963. for (const buffer of this.json.buffers) {
  12964. delete buffer.type;
  12965. }
  12966. }
  12967. _updateMaterial(json) {
  12968. for (const material of json.materials) {
  12969. var _material$values, _material$values2;
  12970. material.pbrMetallicRoughness = {
  12971. baseColorFactor: [1, 1, 1, 1],
  12972. metallicFactor: 1,
  12973. roughnessFactor: 1
  12974. };
  12975. const textureId = ((_material$values = material.values) === null || _material$values === void 0 ? void 0 : _material$values.tex) || ((_material$values2 = material.values) === null || _material$values2 === void 0 ? void 0 : _material$values2.texture2d_0);
  12976. const textureIndex = json.textures.findIndex(texture => texture.id === textureId);
  12977. if (textureIndex !== -1) {
  12978. material.pbrMetallicRoughness.baseColorTexture = {
  12979. index: textureIndex
  12980. };
  12981. }
  12982. }
  12983. }
  12984. }
  12985. function normalizeGLTFV1(gltf, options = {}) {
  12986. return new GLTFV1Normalizer().normalize(gltf, options);
  12987. }
  12988. const COMPONENTS = {
  12989. SCALAR: 1,
  12990. VEC2: 2,
  12991. VEC3: 3,
  12992. VEC4: 4,
  12993. MAT2: 4,
  12994. MAT3: 9,
  12995. MAT4: 16
  12996. };
  12997. const BYTES = {
  12998. 5120: 1,
  12999. 5121: 1,
  13000. 5122: 2,
  13001. 5123: 2,
  13002. 5125: 4,
  13003. 5126: 4
  13004. };
  13005. const GL_SAMPLER = {
  13006. TEXTURE_MAG_FILTER: 0x2800,
  13007. TEXTURE_MIN_FILTER: 0x2801,
  13008. TEXTURE_WRAP_S: 0x2802,
  13009. TEXTURE_WRAP_T: 0x2803,
  13010. REPEAT: 0x2901,
  13011. LINEAR: 0x2601,
  13012. NEAREST_MIPMAP_LINEAR: 0x2702
  13013. };
  13014. const SAMPLER_PARAMETER_GLTF_TO_GL = {
  13015. magFilter: GL_SAMPLER.TEXTURE_MAG_FILTER,
  13016. minFilter: GL_SAMPLER.TEXTURE_MIN_FILTER,
  13017. wrapS: GL_SAMPLER.TEXTURE_WRAP_S,
  13018. wrapT: GL_SAMPLER.TEXTURE_WRAP_T
  13019. };
  13020. const DEFAULT_SAMPLER = {
  13021. [GL_SAMPLER.TEXTURE_MAG_FILTER]: GL_SAMPLER.LINEAR,
  13022. [GL_SAMPLER.TEXTURE_MIN_FILTER]: GL_SAMPLER.NEAREST_MIPMAP_LINEAR,
  13023. [GL_SAMPLER.TEXTURE_WRAP_S]: GL_SAMPLER.REPEAT,
  13024. [GL_SAMPLER.TEXTURE_WRAP_T]: GL_SAMPLER.REPEAT
  13025. };
  13026. function getBytesFromComponentType(componentType) {
  13027. return BYTES[componentType];
  13028. }
  13029. function getSizeFromAccessorType(type) {
  13030. return COMPONENTS[type];
  13031. }
  13032. class GLTFPostProcessor {
  13033. constructor() {
  13034. _defineProperty(this, "baseUri", '');
  13035. _defineProperty(this, "json", {});
  13036. _defineProperty(this, "buffers", []);
  13037. _defineProperty(this, "images", []);
  13038. }
  13039. postProcess(gltf, options = {}) {
  13040. const {
  13041. json,
  13042. buffers = [],
  13043. images = [],
  13044. baseUri = ''
  13045. } = gltf;
  13046. assert$1(json);
  13047. this.baseUri = baseUri;
  13048. this.json = json;
  13049. this.buffers = buffers;
  13050. this.images = images;
  13051. this._resolveTree(this.json, options);
  13052. return this.json;
  13053. }
  13054. _resolveTree(json, options = {}) {
  13055. if (json.bufferViews) {
  13056. json.bufferViews = json.bufferViews.map((bufView, i) => this._resolveBufferView(bufView, i));
  13057. }
  13058. if (json.images) {
  13059. json.images = json.images.map((image, i) => this._resolveImage(image, i));
  13060. }
  13061. if (json.samplers) {
  13062. json.samplers = json.samplers.map((sampler, i) => this._resolveSampler(sampler, i));
  13063. }
  13064. if (json.textures) {
  13065. json.textures = json.textures.map((texture, i) => this._resolveTexture(texture, i));
  13066. }
  13067. if (json.accessors) {
  13068. json.accessors = json.accessors.map((accessor, i) => this._resolveAccessor(accessor, i));
  13069. }
  13070. if (json.materials) {
  13071. json.materials = json.materials.map((material, i) => this._resolveMaterial(material, i));
  13072. }
  13073. if (json.meshes) {
  13074. json.meshes = json.meshes.map((mesh, i) => this._resolveMesh(mesh, i));
  13075. }
  13076. if (json.nodes) {
  13077. json.nodes = json.nodes.map((node, i) => this._resolveNode(node, i));
  13078. }
  13079. if (json.skins) {
  13080. json.skins = json.skins.map((skin, i) => this._resolveSkin(skin, i));
  13081. }
  13082. if (json.scenes) {
  13083. json.scenes = json.scenes.map((scene, i) => this._resolveScene(scene, i));
  13084. }
  13085. if (json.scene !== undefined) {
  13086. json.scene = json.scenes[this.json.scene];
  13087. }
  13088. }
  13089. getScene(index) {
  13090. return this._get('scenes', index);
  13091. }
  13092. getNode(index) {
  13093. return this._get('nodes', index);
  13094. }
  13095. getSkin(index) {
  13096. return this._get('skins', index);
  13097. }
  13098. getMesh(index) {
  13099. return this._get('meshes', index);
  13100. }
  13101. getMaterial(index) {
  13102. return this._get('materials', index);
  13103. }
  13104. getAccessor(index) {
  13105. return this._get('accessors', index);
  13106. }
  13107. getCamera(index) {
  13108. return null;
  13109. }
  13110. getTexture(index) {
  13111. return this._get('textures', index);
  13112. }
  13113. getSampler(index) {
  13114. return this._get('samplers', index);
  13115. }
  13116. getImage(index) {
  13117. return this._get('images', index);
  13118. }
  13119. getBufferView(index) {
  13120. return this._get('bufferViews', index);
  13121. }
  13122. getBuffer(index) {
  13123. return this._get('buffers', index);
  13124. }
  13125. _get(array, index) {
  13126. if (typeof index === 'object') {
  13127. return index;
  13128. }
  13129. const object = this.json[array] && this.json[array][index];
  13130. if (!object) {
  13131. console.warn("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  13132. }
  13133. return object;
  13134. }
  13135. _resolveScene(scene, index) {
  13136. scene.id = scene.id || "scene-".concat(index);
  13137. scene.nodes = (scene.nodes || []).map(node => this.getNode(node));
  13138. return scene;
  13139. }
  13140. _resolveNode(node, index) {
  13141. node.id = node.id || "node-".concat(index);
  13142. if (node.children) {
  13143. node.children = node.children.map(child => this.getNode(child));
  13144. }
  13145. if (node.mesh !== undefined) {
  13146. node.mesh = this.getMesh(node.mesh);
  13147. } else if (node.meshes !== undefined && node.meshes.length) {
  13148. node.mesh = node.meshes.reduce((accum, meshIndex) => {
  13149. const mesh = this.getMesh(meshIndex);
  13150. accum.id = mesh.id;
  13151. accum.primitives = accum.primitives.concat(mesh.primitives);
  13152. return accum;
  13153. }, {
  13154. primitives: []
  13155. });
  13156. }
  13157. if (node.camera !== undefined) {
  13158. node.camera = this.getCamera(node.camera);
  13159. }
  13160. if (node.skin !== undefined) {
  13161. node.skin = this.getSkin(node.skin);
  13162. }
  13163. return node;
  13164. }
  13165. _resolveSkin(skin, index) {
  13166. skin.id = skin.id || "skin-".concat(index);
  13167. skin.inverseBindMatrices = this.getAccessor(skin.inverseBindMatrices);
  13168. return skin;
  13169. }
  13170. _resolveMesh(mesh, index) {
  13171. mesh.id = mesh.id || "mesh-".concat(index);
  13172. if (mesh.primitives) {
  13173. mesh.primitives = mesh.primitives.map(primitive => {
  13174. primitive = { ...primitive
  13175. };
  13176. const attributes = primitive.attributes;
  13177. primitive.attributes = {};
  13178. for (const attribute in attributes) {
  13179. primitive.attributes[attribute] = this.getAccessor(attributes[attribute]);
  13180. }
  13181. if (primitive.indices !== undefined) {
  13182. primitive.indices = this.getAccessor(primitive.indices);
  13183. }
  13184. if (primitive.material !== undefined) {
  13185. primitive.material = this.getMaterial(primitive.material);
  13186. }
  13187. return primitive;
  13188. });
  13189. }
  13190. return mesh;
  13191. }
  13192. _resolveMaterial(material, index) {
  13193. material.id = material.id || "material-".concat(index);
  13194. if (material.normalTexture) {
  13195. material.normalTexture = { ...material.normalTexture
  13196. };
  13197. material.normalTexture.texture = this.getTexture(material.normalTexture.index);
  13198. }
  13199. if (material.occlusionTexture) {
  13200. material.occlustionTexture = { ...material.occlustionTexture
  13201. };
  13202. material.occlusionTexture.texture = this.getTexture(material.occlusionTexture.index);
  13203. }
  13204. if (material.emissiveTexture) {
  13205. material.emmisiveTexture = { ...material.emmisiveTexture
  13206. };
  13207. material.emissiveTexture.texture = this.getTexture(material.emissiveTexture.index);
  13208. }
  13209. if (!material.emissiveFactor) {
  13210. material.emissiveFactor = material.emmisiveTexture ? [1, 1, 1] : [0, 0, 0];
  13211. }
  13212. if (material.pbrMetallicRoughness) {
  13213. material.pbrMetallicRoughness = { ...material.pbrMetallicRoughness
  13214. };
  13215. const mr = material.pbrMetallicRoughness;
  13216. if (mr.baseColorTexture) {
  13217. mr.baseColorTexture = { ...mr.baseColorTexture
  13218. };
  13219. mr.baseColorTexture.texture = this.getTexture(mr.baseColorTexture.index);
  13220. }
  13221. if (mr.metallicRoughnessTexture) {
  13222. mr.metallicRoughnessTexture = { ...mr.metallicRoughnessTexture
  13223. };
  13224. mr.metallicRoughnessTexture.texture = this.getTexture(mr.metallicRoughnessTexture.index);
  13225. }
  13226. }
  13227. return material;
  13228. }
  13229. _resolveAccessor(accessor, index) {
  13230. accessor.id = accessor.id || "accessor-".concat(index);
  13231. if (accessor.bufferView !== undefined) {
  13232. accessor.bufferView = this.getBufferView(accessor.bufferView);
  13233. }
  13234. accessor.bytesPerComponent = getBytesFromComponentType(accessor.componentType);
  13235. accessor.components = getSizeFromAccessorType(accessor.type);
  13236. accessor.bytesPerElement = accessor.bytesPerComponent * accessor.components;
  13237. if (accessor.bufferView) {
  13238. const buffer = accessor.bufferView.buffer;
  13239. const {
  13240. ArrayType,
  13241. byteLength
  13242. } = getAccessorArrayTypeAndLength(accessor, accessor.bufferView);
  13243. const byteOffset = (accessor.bufferView.byteOffset || 0) + (accessor.byteOffset || 0) + buffer.byteOffset;
  13244. let cutBuffer = buffer.arrayBuffer.slice(byteOffset, byteOffset + byteLength);
  13245. if (accessor.bufferView.byteStride) {
  13246. cutBuffer = this._getValueFromInterleavedBuffer(buffer, byteOffset, accessor.bufferView.byteStride, accessor.bytesPerElement, accessor.count);
  13247. }
  13248. accessor.value = new ArrayType(cutBuffer);
  13249. }
  13250. return accessor;
  13251. }
  13252. _getValueFromInterleavedBuffer(buffer, byteOffset, byteStride, bytesPerElement, count) {
  13253. const result = new Uint8Array(count * bytesPerElement);
  13254. for (let i = 0; i < count; i++) {
  13255. const elementOffset = byteOffset + i * byteStride;
  13256. result.set(new Uint8Array(buffer.arrayBuffer.slice(elementOffset, elementOffset + bytesPerElement)), i * bytesPerElement);
  13257. }
  13258. return result.buffer;
  13259. }
  13260. _resolveTexture(texture, index) {
  13261. texture.id = texture.id || "texture-".concat(index);
  13262. texture.sampler = 'sampler' in texture ? this.getSampler(texture.sampler) : DEFAULT_SAMPLER;
  13263. texture.source = this.getImage(texture.source);
  13264. return texture;
  13265. }
  13266. _resolveSampler(sampler, index) {
  13267. sampler.id = sampler.id || "sampler-".concat(index);
  13268. sampler.parameters = {};
  13269. for (const key in sampler) {
  13270. const glEnum = this._enumSamplerParameter(key);
  13271. if (glEnum !== undefined) {
  13272. sampler.parameters[glEnum] = sampler[key];
  13273. }
  13274. }
  13275. return sampler;
  13276. }
  13277. _enumSamplerParameter(key) {
  13278. return SAMPLER_PARAMETER_GLTF_TO_GL[key];
  13279. }
  13280. _resolveImage(image, index) {
  13281. image.id = image.id || "image-".concat(index);
  13282. if (image.bufferView !== undefined) {
  13283. image.bufferView = this.getBufferView(image.bufferView);
  13284. }
  13285. const preloadedImage = this.images[index];
  13286. if (preloadedImage) {
  13287. image.image = preloadedImage;
  13288. }
  13289. return image;
  13290. }
  13291. _resolveBufferView(bufferView, index) {
  13292. const bufferIndex = bufferView.buffer;
  13293. const result = {
  13294. id: "bufferView-".concat(index),
  13295. ...bufferView,
  13296. buffer: this.buffers[bufferIndex]
  13297. };
  13298. const arrayBuffer = this.buffers[bufferIndex].arrayBuffer;
  13299. let byteOffset = this.buffers[bufferIndex].byteOffset || 0;
  13300. if ('byteOffset' in bufferView) {
  13301. byteOffset += bufferView.byteOffset;
  13302. }
  13303. result.data = new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  13304. return result;
  13305. }
  13306. _resolveCamera(camera, index) {
  13307. camera.id = camera.id || "camera-".concat(index);
  13308. if (camera.perspective) ;
  13309. if (camera.orthographic) ;
  13310. return camera;
  13311. }
  13312. }
  13313. function postProcessGLTF(gltf, options) {
  13314. return new GLTFPostProcessor().postProcess(gltf, options);
  13315. }
  13316. const MAGIC_glTF = 0x676c5446;
  13317. const GLB_FILE_HEADER_SIZE = 12;
  13318. const GLB_CHUNK_HEADER_SIZE = 8;
  13319. const GLB_CHUNK_TYPE_JSON = 0x4e4f534a;
  13320. const GLB_CHUNK_TYPE_BIN = 0x004e4942;
  13321. const GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED = 0;
  13322. const GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED = 1;
  13323. const GLB_V1_CONTENT_FORMAT_JSON = 0x0;
  13324. const LE = true;
  13325. function getMagicString(dataView, byteOffset = 0) {
  13326. return "".concat(String.fromCharCode(dataView.getUint8(byteOffset + 0))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 1))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 2))).concat(String.fromCharCode(dataView.getUint8(byteOffset + 3)));
  13327. }
  13328. function isGLB(arrayBuffer, byteOffset = 0, options = {}) {
  13329. const dataView = new DataView(arrayBuffer);
  13330. const {
  13331. magic = MAGIC_glTF
  13332. } = options;
  13333. const magic1 = dataView.getUint32(byteOffset, false);
  13334. return magic1 === magic || magic1 === MAGIC_glTF;
  13335. }
  13336. function parseGLBSync(glb, arrayBuffer, byteOffset = 0, options = {}) {
  13337. const dataView = new DataView(arrayBuffer);
  13338. const type = getMagicString(dataView, byteOffset + 0);
  13339. const version = dataView.getUint32(byteOffset + 4, LE);
  13340. const byteLength = dataView.getUint32(byteOffset + 8, LE);
  13341. Object.assign(glb, {
  13342. header: {
  13343. byteOffset,
  13344. byteLength,
  13345. hasBinChunk: false
  13346. },
  13347. type,
  13348. version,
  13349. json: {},
  13350. binChunks: []
  13351. });
  13352. byteOffset += GLB_FILE_HEADER_SIZE;
  13353. switch (glb.version) {
  13354. case 1:
  13355. return parseGLBV1(glb, dataView, byteOffset);
  13356. case 2:
  13357. return parseGLBV2(glb, dataView, byteOffset, options = {});
  13358. default:
  13359. throw new Error("Invalid GLB version ".concat(glb.version, ". Only supports v1 and v2."));
  13360. }
  13361. }
  13362. function parseGLBV1(glb, dataView, byteOffset) {
  13363. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  13364. const contentLength = dataView.getUint32(byteOffset + 0, LE);
  13365. const contentFormat = dataView.getUint32(byteOffset + 4, LE);
  13366. byteOffset += GLB_CHUNK_HEADER_SIZE;
  13367. assert$7(contentFormat === GLB_V1_CONTENT_FORMAT_JSON);
  13368. parseJSONChunk(glb, dataView, byteOffset, contentLength);
  13369. byteOffset += contentLength;
  13370. byteOffset += parseBINChunk(glb, dataView, byteOffset, glb.header.byteLength);
  13371. return byteOffset;
  13372. }
  13373. function parseGLBV2(glb, dataView, byteOffset, options) {
  13374. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  13375. parseGLBChunksSync(glb, dataView, byteOffset, options);
  13376. return byteOffset + glb.header.byteLength;
  13377. }
  13378. function parseGLBChunksSync(glb, dataView, byteOffset, options) {
  13379. while (byteOffset + 8 <= glb.header.byteLength) {
  13380. const chunkLength = dataView.getUint32(byteOffset + 0, LE);
  13381. const chunkFormat = dataView.getUint32(byteOffset + 4, LE);
  13382. byteOffset += GLB_CHUNK_HEADER_SIZE;
  13383. switch (chunkFormat) {
  13384. case GLB_CHUNK_TYPE_JSON:
  13385. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  13386. break;
  13387. case GLB_CHUNK_TYPE_BIN:
  13388. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  13389. break;
  13390. case GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED:
  13391. if (!options.strict) {
  13392. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  13393. }
  13394. break;
  13395. case GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED:
  13396. if (!options.strict) {
  13397. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  13398. }
  13399. break;
  13400. }
  13401. byteOffset += padToNBytes(chunkLength, 4);
  13402. }
  13403. return byteOffset;
  13404. }
  13405. function parseJSONChunk(glb, dataView, byteOffset, chunkLength) {
  13406. const jsonChunk = new Uint8Array(dataView.buffer, byteOffset, chunkLength);
  13407. const textDecoder = new TextDecoder('utf8');
  13408. const jsonText = textDecoder.decode(jsonChunk);
  13409. glb.json = JSON.parse(jsonText);
  13410. return padToNBytes(chunkLength, 4);
  13411. }
  13412. function parseBINChunk(glb, dataView, byteOffset, chunkLength) {
  13413. glb.header.hasBinChunk = true;
  13414. glb.binChunks.push({
  13415. byteOffset,
  13416. byteLength: chunkLength,
  13417. arrayBuffer: dataView.buffer
  13418. });
  13419. return padToNBytes(chunkLength, 4);
  13420. }
  13421. async function parseGLTF(gltf, arrayBufferOrString, byteOffset = 0, options, context) {
  13422. var _options$gltf, _options$gltf2, _options$gltf3, _options$gltf4;
  13423. parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
  13424. normalizeGLTFV1(gltf, {
  13425. normalize: options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.normalize
  13426. });
  13427. preprocessExtensions(gltf, options, context);
  13428. const promises = [];
  13429. if (options !== null && options !== void 0 && (_options$gltf2 = options.gltf) !== null && _options$gltf2 !== void 0 && _options$gltf2.loadBuffers && gltf.json.buffers) {
  13430. await loadBuffers(gltf, options, context);
  13431. }
  13432. if (options !== null && options !== void 0 && (_options$gltf3 = options.gltf) !== null && _options$gltf3 !== void 0 && _options$gltf3.loadImages) {
  13433. const promise = loadImages(gltf, options, context);
  13434. promises.push(promise);
  13435. }
  13436. const promise = decodeExtensions(gltf, options, context);
  13437. promises.push(promise);
  13438. await Promise.all(promises);
  13439. return options !== null && options !== void 0 && (_options$gltf4 = options.gltf) !== null && _options$gltf4 !== void 0 && _options$gltf4.postProcess ? postProcessGLTF(gltf, options) : gltf;
  13440. }
  13441. function parseGLTFContainerSync(gltf, data, byteOffset, options) {
  13442. if (options.uri) {
  13443. gltf.baseUri = options.uri;
  13444. }
  13445. if (data instanceof ArrayBuffer && !isGLB(data, byteOffset, options)) {
  13446. const textDecoder = new TextDecoder();
  13447. data = textDecoder.decode(data);
  13448. }
  13449. if (typeof data === 'string') {
  13450. gltf.json = parseJSON(data);
  13451. } else if (data instanceof ArrayBuffer) {
  13452. const glb = {};
  13453. byteOffset = parseGLBSync(glb, data, byteOffset, options.glb);
  13454. assert$1(glb.type === 'glTF', "Invalid GLB magic string ".concat(glb.type));
  13455. gltf._glb = glb;
  13456. gltf.json = glb.json;
  13457. } else {
  13458. assert$1(false, 'GLTF: must be ArrayBuffer or string');
  13459. }
  13460. const buffers = gltf.json.buffers || [];
  13461. gltf.buffers = new Array(buffers.length).fill(null);
  13462. if (gltf._glb && gltf._glb.header.hasBinChunk) {
  13463. const {
  13464. binChunks
  13465. } = gltf._glb;
  13466. gltf.buffers[0] = {
  13467. arrayBuffer: binChunks[0].arrayBuffer,
  13468. byteOffset: binChunks[0].byteOffset,
  13469. byteLength: binChunks[0].byteLength
  13470. };
  13471. }
  13472. const images = gltf.json.images || [];
  13473. gltf.images = new Array(images.length).fill({});
  13474. }
  13475. async function loadBuffers(gltf, options, context) {
  13476. const buffers = gltf.json.buffers || [];
  13477. for (let i = 0; i < buffers.length; ++i) {
  13478. const buffer = buffers[i];
  13479. if (buffer.uri) {
  13480. var _context$fetch, _response$arrayBuffer;
  13481. const {
  13482. fetch
  13483. } = context;
  13484. assert$1(fetch);
  13485. const uri = resolveUrl(buffer.uri, options);
  13486. const response = await (context === null || context === void 0 ? void 0 : (_context$fetch = context.fetch) === null || _context$fetch === void 0 ? void 0 : _context$fetch.call(context, uri));
  13487. const arrayBuffer = await (response === null || response === void 0 ? void 0 : (_response$arrayBuffer = response.arrayBuffer) === null || _response$arrayBuffer === void 0 ? void 0 : _response$arrayBuffer.call(response));
  13488. gltf.buffers[i] = {
  13489. arrayBuffer,
  13490. byteOffset: 0,
  13491. byteLength: arrayBuffer.byteLength
  13492. };
  13493. delete buffer.uri;
  13494. } else if (gltf.buffers[i] === null) {
  13495. gltf.buffers[i] = {
  13496. arrayBuffer: new ArrayBuffer(buffer.byteLength),
  13497. byteOffset: 0,
  13498. byteLength: buffer.byteLength
  13499. };
  13500. }
  13501. }
  13502. }
  13503. async function loadImages(gltf, options, context) {
  13504. const imageIndices = getReferencesImageIndices(gltf);
  13505. const images = gltf.json.images || [];
  13506. const promises = [];
  13507. for (const imageIndex of imageIndices) {
  13508. promises.push(loadImage(gltf, images[imageIndex], imageIndex, options, context));
  13509. }
  13510. return await Promise.all(promises);
  13511. }
  13512. function getReferencesImageIndices(gltf) {
  13513. const imageIndices = new Set();
  13514. const textures = gltf.json.textures || [];
  13515. for (const texture of textures) {
  13516. if (texture.source !== undefined) {
  13517. imageIndices.add(texture.source);
  13518. }
  13519. }
  13520. return Array.from(imageIndices).sort();
  13521. }
  13522. async function loadImage(gltf, image, index, options, context) {
  13523. const {
  13524. fetch,
  13525. parse
  13526. } = context;
  13527. let arrayBuffer;
  13528. if (image.uri) {
  13529. const uri = resolveUrl(image.uri, options);
  13530. const response = await fetch(uri);
  13531. arrayBuffer = await response.arrayBuffer();
  13532. }
  13533. if (Number.isFinite(image.bufferView)) {
  13534. const array = getTypedArrayForBufferView(gltf.json, gltf.buffers, image.bufferView);
  13535. arrayBuffer = sliceArrayBuffer(array.buffer, array.byteOffset, array.byteLength);
  13536. }
  13537. assert$1(arrayBuffer, 'glTF image has no data');
  13538. let parsedImage = await parse(arrayBuffer, [ImageLoader, BasisLoader], {
  13539. mimeType: image.mimeType,
  13540. basis: options.basis || {
  13541. format: selectSupportedBasisFormat()
  13542. }
  13543. }, context);
  13544. if (parsedImage && parsedImage[0]) {
  13545. parsedImage = {
  13546. compressed: true,
  13547. mipmaps: false,
  13548. width: parsedImage[0].width,
  13549. height: parsedImage[0].height,
  13550. data: parsedImage[0]
  13551. };
  13552. }
  13553. gltf.images = gltf.images || [];
  13554. gltf.images[index] = parsedImage;
  13555. }
  13556. const GLTFLoader = {
  13557. name: 'glTF',
  13558. id: 'gltf',
  13559. module: 'gltf',
  13560. version: VERSION$3,
  13561. extensions: ['gltf', 'glb'],
  13562. mimeTypes: ['model/gltf+json', 'model/gltf-binary'],
  13563. text: true,
  13564. binary: true,
  13565. tests: ['glTF'],
  13566. parse: parse$1,
  13567. options: {
  13568. gltf: {
  13569. normalize: true,
  13570. loadBuffers: true,
  13571. loadImages: true,
  13572. decompressMeshes: true,
  13573. postProcess: true
  13574. },
  13575. log: console
  13576. },
  13577. deprecatedOptions: {
  13578. fetchImages: 'gltf.loadImages',
  13579. createImages: 'gltf.loadImages',
  13580. decompress: 'gltf.decompressMeshes',
  13581. postProcess: 'gltf.postProcess',
  13582. gltf: {
  13583. decompress: 'gltf.decompressMeshes'
  13584. }
  13585. }
  13586. };
  13587. async function parse$1(arrayBuffer, options = {}, context) {
  13588. options = { ...GLTFLoader.options,
  13589. ...options
  13590. };
  13591. options.gltf = { ...GLTFLoader.options.gltf,
  13592. ...options.gltf
  13593. };
  13594. const {
  13595. byteOffset = 0
  13596. } = options;
  13597. const gltf = {};
  13598. return await parseGLTF(gltf, arrayBuffer, byteOffset, options, context);
  13599. }
  13600. const GLTF_FORMAT = {
  13601. URI: 0,
  13602. EMBEDDED: 1
  13603. };
  13604. function parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options) {
  13605. tile.rotateYtoZ = true;
  13606. const gltfByteLength = tile.byteOffset + tile.byteLength - byteOffset;
  13607. if (gltfByteLength === 0) {
  13608. throw new Error('glTF byte length must be greater than 0.');
  13609. }
  13610. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13611. tile.gltfArrayBuffer = sliceArrayBuffer(arrayBuffer, byteOffset, gltfByteLength);
  13612. tile.gltfByteOffset = 0;
  13613. tile.gltfByteLength = gltfByteLength;
  13614. if (byteOffset % 4 === 0) ; else {
  13615. console.warn("".concat(tile.type, ": embedded glb is not aligned to a 4-byte boundary."));
  13616. }
  13617. return tile.byteOffset + tile.byteLength;
  13618. }
  13619. async function extractGLTF(tile, gltfFormat, options, context) {
  13620. const tile3DOptions = options['3d-tiles'] || {};
  13621. extractGLTFBufferOrURL(tile, gltfFormat);
  13622. if (tile3DOptions.loadGLTF) {
  13623. const {
  13624. parse,
  13625. fetch
  13626. } = context;
  13627. if (tile.gltfUrl) {
  13628. tile.gltfArrayBuffer = await fetch(tile.gltfUrl, options);
  13629. tile.gltfByteOffset = 0;
  13630. }
  13631. if (tile.gltfArrayBuffer) {
  13632. tile.gltf = await parse(tile.gltfArrayBuffer, GLTFLoader, options, context);
  13633. delete tile.gltfArrayBuffer;
  13634. delete tile.gltfByteOffset;
  13635. delete tile.gltfByteLength;
  13636. }
  13637. }
  13638. }
  13639. function extractGLTFBufferOrURL(tile, gltfFormat, options) {
  13640. switch (gltfFormat) {
  13641. case GLTF_FORMAT.URI:
  13642. const gltfUrlBytes = new Uint8Array(tile.gltfArrayBuffer, tile.gltfByteOffset);
  13643. const textDecoder = new TextDecoder();
  13644. const gltfUrl = textDecoder.decode(gltfUrlBytes);
  13645. tile.gltfUrl = gltfUrl.replace(/[\s\0]+$/, '');
  13646. delete tile.gltfArrayBuffer;
  13647. delete tile.gltfByteOffset;
  13648. delete tile.gltfByteLength;
  13649. break;
  13650. case GLTF_FORMAT.EMBEDDED:
  13651. break;
  13652. default:
  13653. throw new Error('b3dm: Illegal glTF format field');
  13654. }
  13655. }
  13656. async function parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13657. var _tile$gltf;
  13658. byteOffset = parseBatchedModel(tile, arrayBuffer, byteOffset, options);
  13659. await extractGLTF(tile, GLTF_FORMAT.EMBEDDED, options, context);
  13660. const extensions = tile === null || tile === void 0 ? void 0 : (_tile$gltf = tile.gltf) === null || _tile$gltf === void 0 ? void 0 : _tile$gltf.extensions;
  13661. if (extensions && extensions.CESIUM_RTC) {
  13662. tile.rtcCenter = extensions.CESIUM_RTC.center;
  13663. }
  13664. return byteOffset;
  13665. }
  13666. function parseBatchedModel(tile, arrayBuffer, byteOffset, options, context) {
  13667. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13668. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13669. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13670. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13671. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13672. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13673. return byteOffset;
  13674. }
  13675. async function parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13676. byteOffset = parseInstancedModel(tile, arrayBuffer, byteOffset, options);
  13677. await extractGLTF(tile, tile.gltfFormat, options, context);
  13678. return byteOffset;
  13679. }
  13680. function parseInstancedModel(tile, arrayBuffer, byteOffset, options, context) {
  13681. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13682. if (tile.version !== 1) {
  13683. throw new Error("Instanced 3D Model version ".concat(tile.version, " is not supported"));
  13684. }
  13685. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13686. const view = new DataView(arrayBuffer);
  13687. tile.gltfFormat = view.getUint32(byteOffset, true);
  13688. byteOffset += 4;
  13689. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13690. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13691. if (tile.featureTableJsonByteLength === 0) {
  13692. throw new Error('i3dm parser: featureTableJsonByteLength is zero.');
  13693. }
  13694. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13695. const instancesLength = featureTable.getGlobalProperty('INSTANCES_LENGTH');
  13696. featureTable.featuresLength = instancesLength;
  13697. if (!Number.isFinite(instancesLength)) {
  13698. throw new Error('i3dm parser: INSTANCES_LENGTH must be defined');
  13699. }
  13700. tile.eastNorthUp = featureTable.getGlobalProperty('EAST_NORTH_UP');
  13701. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13702. const batchTable = new Tile3DBatchTableParser(tile.batchTableJson, tile.batchTableBinary, instancesLength);
  13703. extractInstancedAttributes(tile, featureTable, batchTable, instancesLength);
  13704. return byteOffset;
  13705. }
  13706. function extractInstancedAttributes(tile, featureTable, batchTable, instancesLength) {
  13707. const collectionOptions = {
  13708. instances: new Array(instancesLength),
  13709. batchTable: tile._batchTable,
  13710. cull: false,
  13711. url: undefined,
  13712. gltf: undefined,
  13713. basePath: undefined,
  13714. incrementallyLoadTextures: false,
  13715. forwardAxis: [1, 0, 0]
  13716. };
  13717. const instances = collectionOptions.instances;
  13718. const instancePosition = new Vector3();
  13719. new Vector3();
  13720. new Vector3();
  13721. new Vector3();
  13722. const instanceRotation = new Matrix3();
  13723. const instanceQuaternion = new Quaternion();
  13724. const instanceScale = new Vector3();
  13725. const instanceTranslationRotationScale = {};
  13726. const instanceTransform = new Matrix4();
  13727. const scratch1 = [];
  13728. const scratch2 = [];
  13729. const scratchVector1 = new Vector3();
  13730. const scratchVector2 = new Vector3();
  13731. for (let i = 0; i < instancesLength; i++) {
  13732. let position;
  13733. if (featureTable.hasProperty('POSITION')) {
  13734. position = featureTable.getProperty('POSITION', GL$1.FLOAT, 3, i, instancePosition);
  13735. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  13736. position = featureTable.getProperty('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3, i, instancePosition);
  13737. const quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3, scratchVector1);
  13738. if (!quantizedVolumeOffset) {
  13739. throw new Error('i3dm parser: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  13740. }
  13741. const quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3, scratchVector2);
  13742. if (!quantizedVolumeScale) {
  13743. throw new Error('i3dm parser: QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  13744. }
  13745. const MAX_UNSIGNED_SHORT = 65535.0;
  13746. for (let j = 0; j < 3; j++) {
  13747. position[j] = position[j] / MAX_UNSIGNED_SHORT * quantizedVolumeScale[j] + quantizedVolumeOffset[j];
  13748. }
  13749. }
  13750. if (!position) {
  13751. throw new Error('i3dm: POSITION or POSITION_QUANTIZED must be defined for each instance.');
  13752. }
  13753. instancePosition.copy(position);
  13754. instanceTranslationRotationScale.translation = instancePosition;
  13755. tile.normalUp = featureTable.getProperty('NORMAL_UP', GL$1.FLOAT, 3, i, scratch1);
  13756. tile.normalRight = featureTable.getProperty('NORMAL_RIGHT', GL$1.FLOAT, 3, i, scratch2);
  13757. if (tile.normalUp) {
  13758. if (!tile.normalRight) {
  13759. throw new Error('i3dm: Custom orientation requires both NORMAL_UP and NORMAL_RIGHT.');
  13760. }
  13761. tile.hasCustomOrientation = true;
  13762. } else {
  13763. tile.octNormalUp = featureTable.getProperty('NORMAL_UP_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch1);
  13764. tile.octNormalRight = featureTable.getProperty('NORMAL_RIGHT_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch2);
  13765. if (tile.octNormalUp) {
  13766. if (!tile.octNormalRight) {
  13767. throw new Error('i3dm: oct-encoded orientation requires NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P');
  13768. }
  13769. throw new Error('i3dm: oct-encoded orientation not implemented');
  13770. } else if (tile.eastNorthUp) {
  13771. Ellipsoid.WGS84.eastNorthUpToFixedFrame(instancePosition, instanceTransform);
  13772. instanceTransform.getRotationMatrix3(instanceRotation);
  13773. } else {
  13774. instanceRotation.identity();
  13775. }
  13776. }
  13777. instanceQuaternion.fromMatrix3(instanceRotation);
  13778. instanceTranslationRotationScale.rotation = instanceQuaternion;
  13779. instanceScale.set(1.0, 1.0, 1.0);
  13780. const scale = featureTable.getProperty('SCALE', GL$1.FLOAT, 1, i);
  13781. if (Number.isFinite(scale)) {
  13782. instanceScale.multiplyByScalar(scale);
  13783. }
  13784. const nonUniformScale = featureTable.getProperty('SCALE_NON_UNIFORM', GL$1.FLOAT, 3, i, scratch1);
  13785. if (nonUniformScale) {
  13786. instanceScale.scale(nonUniformScale);
  13787. }
  13788. instanceTranslationRotationScale.scale = instanceScale;
  13789. let batchId = featureTable.getProperty('BATCH_ID', GL$1.UNSIGNED_SHORT, 1, i);
  13790. if (batchId === undefined) {
  13791. batchId = i;
  13792. }
  13793. const rotationMatrix = new Matrix4().fromQuaternion(instanceTranslationRotationScale.rotation);
  13794. instanceTransform.identity();
  13795. instanceTransform.translate(instanceTranslationRotationScale.translation);
  13796. instanceTransform.multiplyRight(rotationMatrix);
  13797. instanceTransform.scale(instanceTranslationRotationScale.scale);
  13798. const modelMatrix = instanceTransform.clone();
  13799. instances[i] = {
  13800. modelMatrix,
  13801. batchId
  13802. };
  13803. }
  13804. tile.instances = instances;
  13805. }
  13806. async function parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile) {
  13807. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13808. const view = new DataView(arrayBuffer);
  13809. tile.tilesLength = view.getUint32(byteOffset, true);
  13810. byteOffset += 4;
  13811. tile.tiles = [];
  13812. while (tile.tiles.length < tile.tilesLength && tile.byteLength - byteOffset > 12) {
  13813. const subtile = {};
  13814. tile.tiles.push(subtile);
  13815. byteOffset = await parse3DTile(arrayBuffer, byteOffset, options, context, subtile);
  13816. }
  13817. return byteOffset;
  13818. }
  13819. async function parseGltf3DTile(tile, arrayBuffer, options, context) {
  13820. tile.rotateYtoZ = true;
  13821. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13822. const {
  13823. parse
  13824. } = context;
  13825. tile.gltf = await parse(arrayBuffer, GLTFLoader, options, context);
  13826. }
  13827. async function parse3DTile(arrayBuffer, byteOffset = 0, options, context, tile = {}) {
  13828. tile.byteOffset = byteOffset;
  13829. tile.type = getMagicString$1(arrayBuffer, byteOffset);
  13830. switch (tile.type) {
  13831. case TILE3D_TYPE.COMPOSITE:
  13832. return await parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile);
  13833. case TILE3D_TYPE.BATCHED_3D_MODEL:
  13834. return await parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13835. case TILE3D_TYPE.GLTF:
  13836. return await parseGltf3DTile(tile, arrayBuffer, options, context);
  13837. case TILE3D_TYPE.INSTANCED_3D_MODEL:
  13838. return await parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13839. case TILE3D_TYPE.POINT_CLOUD:
  13840. return await parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context);
  13841. default:
  13842. throw new Error("3DTileLoader: unknown type ".concat(tile.type));
  13843. }
  13844. }
  13845. const SUBTREE_FILE_MAGIC = 0x74627573;
  13846. const SUBTREE_FILE_VERSION = 1;
  13847. async function parse3DTilesSubtree(data) {
  13848. const magic = new Uint32Array(data.slice(0, 4));
  13849. if (magic[0] !== SUBTREE_FILE_MAGIC) {
  13850. throw new Error('Wrong subtree file magic number');
  13851. }
  13852. const version = new Uint32Array(data.slice(4, 8));
  13853. if (version[0] !== SUBTREE_FILE_VERSION) {
  13854. throw new Error('Wrong subtree file verson, must be 1');
  13855. }
  13856. const jsonByteLength = parseUint64Value(data.slice(8, 16));
  13857. const stringAttribute = new Uint8Array(data, 24, jsonByteLength);
  13858. const textDecoder = new TextDecoder('utf8');
  13859. const string = textDecoder.decode(stringAttribute);
  13860. const subtree = JSON.parse(string);
  13861. const binaryByteLength = parseUint64Value(data.slice(16, 24));
  13862. let internalBinaryBuffer = new ArrayBuffer(0);
  13863. if (binaryByteLength) {
  13864. internalBinaryBuffer = data.slice(24 + jsonByteLength);
  13865. }
  13866. if ('bufferView' in subtree.tileAvailability) {
  13867. subtree.tileAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'tileAvailability', internalBinaryBuffer);
  13868. }
  13869. if ('bufferView' in subtree.contentAvailability) {
  13870. subtree.contentAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'contentAvailability', internalBinaryBuffer);
  13871. }
  13872. if ('bufferView' in subtree.childSubtreeAvailability) {
  13873. subtree.childSubtreeAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'childSubtreeAvailability', internalBinaryBuffer);
  13874. }
  13875. return subtree;
  13876. }
  13877. async function getExplicitBitstream(subtree, name, internalBinaryBuffer) {
  13878. const bufferViewIndex = subtree[name].bufferView;
  13879. const bufferView = subtree.bufferViews[bufferViewIndex];
  13880. const buffer = subtree.buffers[bufferView.buffer];
  13881. if (buffer.uri) {
  13882. const response = await fetchFile(buffer.uri);
  13883. const data = await response.arrayBuffer();
  13884. return new Uint8Array(data, bufferView.byteOffset, bufferView.byteLength);
  13885. }
  13886. return new Uint8Array(internalBinaryBuffer, bufferView.byteOffset, bufferView.byteLength);
  13887. }
  13888. function parseUint64Value(buffer) {
  13889. const dataView = new DataView(buffer);
  13890. const left = dataView.getUint32(0, true);
  13891. const right = dataView.getUint32(4, true);
  13892. return left + 2 ** 32 * right;
  13893. }
  13894. const Tile3DSubtreeLoader = {
  13895. id: '3d-tiles-subtree',
  13896. name: '3D Tiles Subtree',
  13897. module: '3d-tiles',
  13898. version: VERSION$5,
  13899. extensions: ['subtree'],
  13900. mimeTypes: ['application/octet-stream'],
  13901. tests: ['subtree'],
  13902. parse: parse3DTilesSubtree,
  13903. options: {}
  13904. };
  13905. const QUADTREE_DEVISION_COUNT = 4;
  13906. const OCTREE_DEVISION_COUNT = 8;
  13907. const SUBDIVISION_COUNT_MAP = {
  13908. QUADTREE: QUADTREE_DEVISION_COUNT,
  13909. OCTREE: OCTREE_DEVISION_COUNT
  13910. };
  13911. async function parseImplicitTiles(params) {
  13912. const {
  13913. options,
  13914. parentData = {
  13915. mortonIndex: 0,
  13916. x: 0,
  13917. y: 0,
  13918. z: 0
  13919. },
  13920. childIndex = 0,
  13921. globalData = {
  13922. level: 0,
  13923. mortonIndex: 0,
  13924. x: 0,
  13925. y: 0,
  13926. z: 0
  13927. }
  13928. } = params;
  13929. let {
  13930. subtree,
  13931. level = 0
  13932. } = params;
  13933. const {
  13934. subdivisionScheme,
  13935. subtreeLevels,
  13936. maximumLevel,
  13937. contentUrlTemplate,
  13938. subtreesUriTemplate,
  13939. basePath
  13940. } = options;
  13941. const tile = {
  13942. children: [],
  13943. lodMetricValue: 0,
  13944. contentUrl: ''
  13945. };
  13946. const childrenPerTile = SUBDIVISION_COUNT_MAP[subdivisionScheme];
  13947. const childX = childIndex & 0b01;
  13948. const childY = childIndex >> 1 & 0b01;
  13949. const childZ = childIndex >> 2 & 0b01;
  13950. const levelOffset = (childrenPerTile ** level - 1) / (childrenPerTile - 1);
  13951. let childTileMortonIndex = concatBits(parentData.mortonIndex, childIndex);
  13952. let tileAvailabilityIndex = levelOffset + childTileMortonIndex;
  13953. let childTileX = concatBits(parentData.x, childX);
  13954. let childTileY = concatBits(parentData.y, childY);
  13955. let childTileZ = concatBits(parentData.z, childZ);
  13956. let isChildSubtreeAvailable = false;
  13957. if (level + 1 > subtreeLevels) {
  13958. isChildSubtreeAvailable = getAvailabilityResult(subtree.childSubtreeAvailability, childTileMortonIndex);
  13959. }
  13960. const x = concatBits(globalData.x, childTileX);
  13961. const y = concatBits(globalData.y, childTileY);
  13962. const z = concatBits(globalData.z, childTileZ);
  13963. const lev = level + globalData.level;
  13964. if (isChildSubtreeAvailable) {
  13965. const subtreePath = "".concat(basePath, "/").concat(subtreesUriTemplate);
  13966. const childSubtreeUrl = replaceContentUrlTemplate(subtreePath, lev, x, y, z);
  13967. const childSubtree = await load(childSubtreeUrl, Tile3DSubtreeLoader);
  13968. subtree = childSubtree;
  13969. globalData.mortonIndex = childTileMortonIndex;
  13970. globalData.x = childTileX;
  13971. globalData.y = childTileY;
  13972. globalData.z = childTileZ;
  13973. globalData.level = level;
  13974. childTileMortonIndex = 0;
  13975. tileAvailabilityIndex = 0;
  13976. childTileX = 0;
  13977. childTileY = 0;
  13978. childTileZ = 0;
  13979. level = 0;
  13980. }
  13981. const isTileAvailable = getAvailabilityResult(subtree.tileAvailability, tileAvailabilityIndex);
  13982. if (!isTileAvailable || level > maximumLevel) {
  13983. return tile;
  13984. }
  13985. const isContentAvailable = getAvailabilityResult(subtree.contentAvailability, tileAvailabilityIndex);
  13986. if (isContentAvailable) {
  13987. tile.contentUrl = replaceContentUrlTemplate(contentUrlTemplate, lev, x, y, z);
  13988. }
  13989. const childTileLevel = level + 1;
  13990. const pData = {
  13991. mortonIndex: childTileMortonIndex,
  13992. x: childTileX,
  13993. y: childTileY,
  13994. z: childTileZ
  13995. };
  13996. for (let index = 0; index < childrenPerTile; index++) {
  13997. const currentTile = await parseImplicitTiles({
  13998. subtree,
  13999. options,
  14000. parentData: pData,
  14001. childIndex: index,
  14002. level: childTileLevel,
  14003. globalData
  14004. });
  14005. if (currentTile.contentUrl || currentTile.children.length) {
  14006. const globalLevel = lev + 1;
  14007. const childCoordinates = {
  14008. childTileX,
  14009. childTileY,
  14010. childTileZ
  14011. };
  14012. const formattedTile = formatTileData(currentTile, globalLevel, childCoordinates, options);
  14013. tile.children.push(formattedTile);
  14014. }
  14015. }
  14016. return tile;
  14017. }
  14018. function getAvailabilityResult(availabilityData, index) {
  14019. if ('constant' in availabilityData) {
  14020. return Boolean(availabilityData.constant);
  14021. }
  14022. if (availabilityData.explicitBitstream) {
  14023. return getBooleanValueFromBitstream(index, availabilityData.explicitBitstream);
  14024. }
  14025. return false;
  14026. }
  14027. function formatTileData(tile, level, childCoordinates, options) {
  14028. const {
  14029. basePath,
  14030. refine,
  14031. getRefine,
  14032. lodMetricType,
  14033. getTileType,
  14034. rootLodMetricValue,
  14035. rootBoundingVolume
  14036. } = options;
  14037. const uri = tile.contentUrl && tile.contentUrl.replace("".concat(basePath, "/"), '');
  14038. const lodMetricValue = rootLodMetricValue / 2 ** level;
  14039. const boundingVolume = calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates);
  14040. return {
  14041. children: tile.children,
  14042. contentUrl: tile.contentUrl,
  14043. content: {
  14044. uri
  14045. },
  14046. id: tile.contentUrl,
  14047. refine: getRefine(refine),
  14048. type: getTileType(tile),
  14049. lodMetricType,
  14050. lodMetricValue,
  14051. boundingVolume
  14052. };
  14053. }
  14054. function calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates) {
  14055. if (rootBoundingVolume.region) {
  14056. const {
  14057. childTileX,
  14058. childTileY,
  14059. childTileZ
  14060. } = childCoordinates;
  14061. const [west, south, east, north, minimumHeight, maximumHeight] = rootBoundingVolume.region;
  14062. const boundingVolumesCount = 2 ** level;
  14063. const sizeX = (east - west) / boundingVolumesCount;
  14064. const sizeY = (north - south) / boundingVolumesCount;
  14065. const sizeZ = (maximumHeight - minimumHeight) / boundingVolumesCount;
  14066. const [childWest, childEast] = [west + sizeX * childTileX, west + sizeX * (childTileX + 1)];
  14067. const [childSouth, childNorth] = [south + sizeY * childTileY, south + sizeY * (childTileY + 1)];
  14068. const [childMinimumHeight, childMaximumHeight] = [minimumHeight + sizeZ * childTileZ, minimumHeight + sizeZ * (childTileZ + 1)];
  14069. return {
  14070. region: [childWest, childSouth, childEast, childNorth, childMinimumHeight, childMaximumHeight]
  14071. };
  14072. }
  14073. console.warn('Unsupported bounding volume type: ', rootBoundingVolume);
  14074. return null;
  14075. }
  14076. function concatBits(first, second) {
  14077. return parseInt(first.toString(2) + second.toString(2), 2);
  14078. }
  14079. function replaceContentUrlTemplate(templateUrl, level, x, y, z) {
  14080. const mapUrl = generateMapUrl({
  14081. level,
  14082. x,
  14083. y,
  14084. z
  14085. });
  14086. return templateUrl.replace(/{level}|{x}|{y}|{z}/gi, matched => mapUrl[matched]);
  14087. }
  14088. function generateMapUrl(items) {
  14089. const mapUrl = {};
  14090. for (const key in items) {
  14091. mapUrl["{".concat(key, "}")] = items[key];
  14092. }
  14093. return mapUrl;
  14094. }
  14095. function getBooleanValueFromBitstream(availabilityIndex, availabilityBuffer) {
  14096. const byteIndex = Math.floor(availabilityIndex / 8);
  14097. const bitIndex = availabilityIndex % 8;
  14098. const bitValue = availabilityBuffer[byteIndex] >> bitIndex & 1;
  14099. return bitValue === 1;
  14100. }
  14101. function getTileType(tile) {
  14102. if (!tile.contentUrl) {
  14103. return TILE_TYPE.EMPTY;
  14104. }
  14105. const contentUrl = tile.contentUrl;
  14106. const fileExtension = contentUrl.split('.').pop();
  14107. switch (fileExtension) {
  14108. case 'pnts':
  14109. return TILE_TYPE.POINTCLOUD;
  14110. case 'i3dm':
  14111. case 'b3dm':
  14112. case 'glb':
  14113. case 'gltf':
  14114. return TILE_TYPE.SCENEGRAPH;
  14115. default:
  14116. return fileExtension;
  14117. }
  14118. }
  14119. function getRefine(refine) {
  14120. switch (refine) {
  14121. case 'REPLACE':
  14122. case 'replace':
  14123. return TILE_REFINEMENT.REPLACE;
  14124. case 'ADD':
  14125. case 'add':
  14126. return TILE_REFINEMENT.ADD;
  14127. default:
  14128. return refine;
  14129. }
  14130. }
  14131. function normalizeTileData(tile, options) {
  14132. if (!tile) {
  14133. return null;
  14134. }
  14135. if (tile.content) {
  14136. const contentUri = tile.content.uri || tile.content.url;
  14137. tile.contentUrl = "".concat(options.basePath, "/").concat(contentUri);
  14138. }
  14139. tile.id = tile.contentUrl;
  14140. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  14141. tile.lodMetricValue = tile.geometricError;
  14142. tile.transformMatrix = tile.transform;
  14143. tile.type = getTileType(tile);
  14144. tile.refine = getRefine(tile.refine);
  14145. return tile;
  14146. }
  14147. function normalizeTileHeaders(tileset) {
  14148. const basePath = tileset.basePath;
  14149. const root = normalizeTileData(tileset.root, tileset);
  14150. const stack = [];
  14151. stack.push(root);
  14152. while (stack.length > 0) {
  14153. const tile = stack.pop() || {};
  14154. const children = tile.children || [];
  14155. for (const childHeader of children) {
  14156. normalizeTileData(childHeader, {
  14157. basePath
  14158. });
  14159. stack.push(childHeader);
  14160. }
  14161. }
  14162. return root;
  14163. }
  14164. async function normalizeImplicitTileHeaders(tileset) {
  14165. if (!tileset.root) {
  14166. return null;
  14167. }
  14168. const basePath = tileset.basePath;
  14169. const implicitTilingExtension = tileset.root.extensions['3DTILES_implicit_tiling'];
  14170. const {
  14171. subdivisionScheme,
  14172. maximumLevel,
  14173. subtreeLevels,
  14174. subtrees: {
  14175. uri: subtreesUriTemplate
  14176. }
  14177. } = implicitTilingExtension;
  14178. const subtreeUrl = replaceContentUrlTemplate(subtreesUriTemplate, 0, 0, 0, 0);
  14179. const rootSubtreeUrl = "".concat(basePath, "/").concat(subtreeUrl);
  14180. const rootSubtree = await load(rootSubtreeUrl, Tile3DSubtreeLoader);
  14181. const contentUrlTemplate = "".concat(basePath, "/").concat(tileset.root.content.uri);
  14182. const refine = tileset.root.refine;
  14183. const rootLodMetricValue = tileset.root.geometricError;
  14184. const rootBoundingVolume = tileset.root.boundingVolume;
  14185. const options = {
  14186. contentUrlTemplate,
  14187. subtreesUriTemplate,
  14188. subdivisionScheme,
  14189. subtreeLevels,
  14190. maximumLevel,
  14191. refine,
  14192. basePath,
  14193. lodMetricType: LOD_METRIC_TYPE.GEOMETRIC_ERROR,
  14194. rootLodMetricValue,
  14195. rootBoundingVolume,
  14196. getTileType,
  14197. getRefine
  14198. };
  14199. return await normalizeImplicitTileData(tileset.root, rootSubtree, options);
  14200. }
  14201. async function normalizeImplicitTileData(tile, rootSubtree, options) {
  14202. if (!tile) {
  14203. return null;
  14204. }
  14205. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  14206. tile.lodMetricValue = tile.geometricError;
  14207. tile.transformMatrix = tile.transform;
  14208. const {
  14209. children,
  14210. contentUrl
  14211. } = await parseImplicitTiles({
  14212. subtree: rootSubtree,
  14213. options
  14214. });
  14215. if (contentUrl) {
  14216. tile.contentUrl = contentUrl;
  14217. tile.content = {
  14218. uri: contentUrl.replace("".concat(options.basePath, "/"), '')
  14219. };
  14220. }
  14221. tile.refine = getRefine(tile.refine);
  14222. tile.type = getTileType(tile);
  14223. tile.children = children;
  14224. tile.id = tile.contentUrl;
  14225. return tile;
  14226. }
  14227. const IMPLICIT_TILING_EXTENSION_NAME = '3DTILES_implicit_tiling';
  14228. const Tiles3DLoader = {
  14229. id: '3d-tiles',
  14230. name: '3D Tiles',
  14231. module: '3d-tiles',
  14232. version: VERSION$5,
  14233. extensions: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  14234. mimeTypes: ['application/octet-stream'],
  14235. tests: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  14236. parse,
  14237. options: {
  14238. '3d-tiles': {
  14239. loadGLTF: true,
  14240. decodeQuantizedPositions: false,
  14241. isTileset: 'auto',
  14242. assetGltfUpAxis: null
  14243. }
  14244. }
  14245. };
  14246. function getBaseUri(tileset) {
  14247. return dirname(tileset.url);
  14248. }
  14249. async function parseTile(arrayBuffer, options, context) {
  14250. const tile = {
  14251. content: {
  14252. featureIds: null
  14253. }
  14254. };
  14255. const byteOffset = 0;
  14256. await parse3DTile(arrayBuffer, byteOffset, options, context, tile.content);
  14257. return tile.content;
  14258. }
  14259. async function parseTileset(data, options, context) {
  14260. var _tilesetJson$root;
  14261. const tilesetJson = JSON.parse(new TextDecoder().decode(data));
  14262. tilesetJson.loader = options.loader || Tiles3DLoader;
  14263. tilesetJson.url = context.url;
  14264. tilesetJson.basePath = getBaseUri(tilesetJson);
  14265. tilesetJson.root = hasImplicitTilingExtension(tilesetJson) ? await normalizeImplicitTileHeaders(tilesetJson) : normalizeTileHeaders(tilesetJson);
  14266. tilesetJson.type = TILESET_TYPE.TILES3D;
  14267. tilesetJson.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  14268. tilesetJson.lodMetricValue = ((_tilesetJson$root = tilesetJson.root) === null || _tilesetJson$root === void 0 ? void 0 : _tilesetJson$root.lodMetricValue) || 0;
  14269. return tilesetJson;
  14270. }
  14271. async function parse(data, options, context) {
  14272. const loaderOptions = options['3d-tiles'] || {};
  14273. let isTileset;
  14274. if (loaderOptions.isTileset === 'auto') {
  14275. isTileset = context.url && context.url.indexOf('.json') !== -1;
  14276. } else {
  14277. isTileset = loaderOptions.isTileset;
  14278. }
  14279. if (isTileset) {
  14280. data = await parseTileset(data, options, context);
  14281. } else {
  14282. data = await parseTile(data, options, context);
  14283. }
  14284. return data;
  14285. }
  14286. function hasImplicitTilingExtension(tilesetJson) {
  14287. var _tilesetJson$extensio, _tilesetJson$extensio2;
  14288. return (tilesetJson === null || tilesetJson === void 0 ? void 0 : (_tilesetJson$extensio = tilesetJson.extensionsRequired) === null || _tilesetJson$extensio === void 0 ? void 0 : _tilesetJson$extensio.includes(IMPLICIT_TILING_EXTENSION_NAME)) && (tilesetJson === null || tilesetJson === void 0 ? void 0 : (_tilesetJson$extensio2 = tilesetJson.extensionsUsed) === null || _tilesetJson$extensio2 === void 0 ? void 0 : _tilesetJson$extensio2.includes(IMPLICIT_TILING_EXTENSION_NAME));
  14289. }
  14290. const CESIUM_ION_URL = 'https://api.cesium.com/v1/assets';
  14291. async function getIonTilesetMetadata(accessToken, assetId) {
  14292. if (!assetId) {
  14293. const assets = await getIonAssets(accessToken);
  14294. for (const item of assets.items) {
  14295. if (item.type === '3DTILES') {
  14296. assetId = item.id;
  14297. }
  14298. }
  14299. }
  14300. const ionAssetMetadata = await getIonAssetMetadata(accessToken, assetId);
  14301. const {
  14302. type,
  14303. url
  14304. } = ionAssetMetadata;
  14305. assert$7(type === '3DTILES' && url);
  14306. ionAssetMetadata.headers = {
  14307. Authorization: "Bearer ".concat(ionAssetMetadata.accessToken)
  14308. };
  14309. return ionAssetMetadata;
  14310. }
  14311. async function getIonAssets(accessToken) {
  14312. assert$7(accessToken);
  14313. const url = CESIUM_ION_URL;
  14314. const headers = {
  14315. Authorization: "Bearer ".concat(accessToken)
  14316. };
  14317. const response = await fetchFile(url, {
  14318. fetch: {
  14319. headers
  14320. }
  14321. });
  14322. if (!response.ok) {
  14323. throw new Error(response.statusText);
  14324. }
  14325. return await response.json();
  14326. }
  14327. async function getIonAssetMetadata(accessToken, assetId) {
  14328. assert$7(accessToken, assetId);
  14329. const headers = {
  14330. Authorization: "Bearer ".concat(accessToken)
  14331. };
  14332. const url = "".concat(CESIUM_ION_URL, "/").concat(assetId);
  14333. let response = await fetchFile("".concat(url), {
  14334. fetch: {
  14335. headers
  14336. }
  14337. });
  14338. if (!response.ok) {
  14339. throw new Error(response.statusText);
  14340. }
  14341. let metadata = await response.json();
  14342. response = await fetchFile("".concat(url, "/endpoint"), {
  14343. fetch: {
  14344. headers
  14345. }
  14346. });
  14347. if (!response.ok) {
  14348. throw new Error(response.statusText);
  14349. }
  14350. const tilesetInfo = await response.json();
  14351. metadata = { ...metadata,
  14352. ...tilesetInfo
  14353. };
  14354. return metadata;
  14355. }
  14356. async function preload(url, options = {}) {
  14357. options = options['cesium-ion'] || {};
  14358. const {
  14359. accessToken
  14360. } = options;
  14361. let assetId = options.assetId;
  14362. if (!Number.isFinite(assetId)) {
  14363. const matched = url.match(/\/([0-9]+)\/tileset.json/);
  14364. assetId = matched && matched[1];
  14365. }
  14366. return getIonTilesetMetadata(accessToken, assetId);
  14367. }
  14368. const CesiumIonLoader = { ...Tiles3DLoader,
  14369. id: 'cesium-ion',
  14370. name: 'Cesium Ion',
  14371. preload,
  14372. parse: async (data, options, context) => {
  14373. options = { ...options
  14374. };
  14375. options['3d-tiles'] = options['cesium-ion'];
  14376. options.loader = CesiumIonLoader;
  14377. return Tiles3DLoader.parse(data, options, context);
  14378. },
  14379. options: {
  14380. 'cesium-ion': { ...Tiles3DLoader.options['3d-tiles'],
  14381. accessToken: null
  14382. }
  14383. }
  14384. };
  14385. // From https://github.com/potree/potree/blob/master/src/materials/PointCloudMaterial.js
  14386. function generateGradientTexture(gradient) {
  14387. const size = 64;
  14388. // create canvas
  14389. const canvas = document.createElement('canvas');
  14390. canvas.width = size;
  14391. canvas.height = size;
  14392. // get context
  14393. const context = canvas.getContext('2d');
  14394. // draw gradient
  14395. context.rect(0, 0, size, size);
  14396. const ctxGradient = context.createLinearGradient(0, 0, size, size);
  14397. for (let i = 0; i < gradient.length; i++) {
  14398. const step = gradient[i];
  14399. ctxGradient.addColorStop(step[0], '#' + step[1].getHexString());
  14400. }
  14401. context.fillStyle = ctxGradient;
  14402. context.fill();
  14403. //let texture = new THREE.Texture(canvas);
  14404. const texture = new CanvasTexture(canvas);
  14405. texture.needsUpdate = true;
  14406. texture.minFilter = LinearFilter;
  14407. texture.wrapS = RepeatWrapping;
  14408. texture.wrapT = RepeatWrapping;
  14409. texture.repeat.set(2, 2);
  14410. // textureImage = texture.image;
  14411. return texture;
  14412. }
  14413. function getCameraFrustum(camera) {
  14414. camera.updateMatrix(); // make sure camera's local matrix is updated
  14415. camera.updateMatrixWorld(); // make sure camera's world matrix is updated
  14416. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14417. const frustum = new Frustum();
  14418. frustum.setFromProjectionMatrix(new Matrix4$1().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));
  14419. return frustum;
  14420. }
  14421. function loadersPlaneToMesh(plane) {
  14422. const group = new Group();
  14423. // Create a basic rectangle geometry from math.gl plane
  14424. const planeGeometry = new PlaneGeometry(10, 5);
  14425. // Align the geometry to the plane
  14426. const coplanarPoint = new Vector3$1(...plane.projectPointOntoPlane([0, 0, 0]));
  14427. const normal = new Vector3$1(plane.normal.x, plane.normal.y, plane.normal.z);
  14428. const focalPoint = new Vector3$1().copy(coplanarPoint).add(normal);
  14429. planeGeometry.lookAt(focalPoint);
  14430. planeGeometry.translate(coplanarPoint.x, coplanarPoint.y, coplanarPoint.z);
  14431. // Edges
  14432. /*
  14433. const edges = new EdgesGeometry(planeGeometry)
  14434. var dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: 0x00ffff }))*/
  14435. //plane
  14436. const material = new MeshBasicMaterial({ color: 0x00ffff, side: DoubleSide });
  14437. const mesh = new Mesh(planeGeometry, material);
  14438. const arrowHelper = new ArrowHelper(normal, coplanarPoint, 5, 0xffff00);
  14439. group.add(arrowHelper);
  14440. group.add(mesh);
  14441. return group;
  14442. }
  14443. function loadersBoundingBoxToMesh(tile) {
  14444. // Create a basic rectangle geometry from math.gl half-axes
  14445. const { boundingVolume } = tile;
  14446. let redColor = 0;
  14447. if (tile.content) {
  14448. redColor = Math.min(tile.content.byteLength / 500000, 1.0);
  14449. }
  14450. const boxColor = new Color(redColor, 1.0, 0.0);
  14451. const boxGeometry = new BoxGeometry(1, 1, 1);
  14452. const boxTransform = new Matrix4$1();
  14453. if (boundingVolume.halfAxes) {
  14454. boxTransform.copy(getMatrix4FromHalfAxes(boundingVolume.halfAxes));
  14455. }
  14456. else if (boundingVolume.radius) {
  14457. boxGeometry.scale(boundingVolume.radius * 2, boundingVolume.radius * 2, boundingVolume.radius * 2);
  14458. }
  14459. boxGeometry.applyMatrix4(boxTransform);
  14460. const edges = new EdgesGeometry(boxGeometry);
  14461. const dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: boxColor }));
  14462. dispPlane.position.copy(new Vector3$1(...boundingVolume.center));
  14463. return dispPlane;
  14464. }
  14465. function getMatrix4FromHalfAxes(halfAxes) {
  14466. const m = halfAxes;
  14467. const rotateMatrix = new Matrix4$1().fromArray([
  14468. m[0] * 2,
  14469. m[1] * 2,
  14470. m[2] * 2,
  14471. 0,
  14472. m[3] * 2,
  14473. m[4] * 2,
  14474. m[5] * 2,
  14475. 0,
  14476. m[6] * 2,
  14477. m[7] * 2,
  14478. m[8] * 2,
  14479. 0,
  14480. 0,
  14481. 0,
  14482. 0,
  14483. 1,
  14484. ]);
  14485. return rotateMatrix;
  14486. }
  14487. /*
  14488. * from https://github.com/tentone/geo-three
  14489. * Tree-shaking did not work, probably due to static class methods
  14490. */
  14491. function datumsToSpherical(latitude, longitude) {
  14492. const EARTH_RADIUS = 6378137;
  14493. const EARTH_PERIMETER = 2 * Math.PI * EARTH_RADIUS;
  14494. const EARTH_ORIGIN = EARTH_PERIMETER / 2.0;
  14495. const x = longitude * EARTH_ORIGIN / 180.0;
  14496. let y = Math.log(Math.tan((90 + latitude) * Math.PI / 360.0)) / (Math.PI / 180.0);
  14497. y = y * EARTH_ORIGIN / 180.0;
  14498. return new Vector2$1(x, y);
  14499. }
  14500. const Gradients = {
  14501. // From chroma spectral http://gka.github.io/chroma.js/
  14502. SPECTRAL: [
  14503. [0, new Color(0.3686, 0.3098, 0.6353)],
  14504. [0.1, new Color(0.1961, 0.5333, 0.7412)],
  14505. [0.2, new Color(0.4, 0.7608, 0.6471)],
  14506. [0.3, new Color(0.6706, 0.8667, 0.6431)],
  14507. [0.4, new Color(0.902, 0.9608, 0.5961)],
  14508. [0.5, new Color(1.0, 1.0, 0.749)],
  14509. [0.6, new Color(0.9961, 0.8784, 0.5451)],
  14510. [0.7, new Color(0.9922, 0.6824, 0.3804)],
  14511. [0.8, new Color(0.9569, 0.4275, 0.2627)],
  14512. [0.9, new Color(0.8353, 0.2431, 0.3098)],
  14513. [1, new Color(0.6196, 0.0039, 0.2588)],
  14514. ],
  14515. PLASMA: [
  14516. [0.0, new Color(0.241, 0.015, 0.61)],
  14517. [0.1, new Color(0.387, 0.001, 0.654)],
  14518. [0.2, new Color(0.524, 0.025, 0.653)],
  14519. [0.3, new Color(0.651, 0.125, 0.596)],
  14520. [0.4, new Color(0.752, 0.227, 0.513)],
  14521. [0.5, new Color(0.837, 0.329, 0.431)],
  14522. [0.6, new Color(0.907, 0.435, 0.353)],
  14523. [0.7, new Color(0.963, 0.554, 0.272)],
  14524. [0.8, new Color(0.992, 0.681, 0.195)],
  14525. [0.9, new Color(0.987, 0.822, 0.144)],
  14526. [1.0, new Color(0.94, 0.975, 0.131)],
  14527. ],
  14528. YELLOW_GREEN: [
  14529. [0, new Color(0.1647, 0.2824, 0.3451)],
  14530. [0.1, new Color(0.1338, 0.3555, 0.4227)],
  14531. [0.2, new Color(0.061, 0.4319, 0.4864)],
  14532. [0.3, new Color(0.0, 0.5099, 0.5319)],
  14533. [0.4, new Color(0.0, 0.5881, 0.5569)],
  14534. [0.5, new Color(0.137, 0.665, 0.5614)],
  14535. [0.6, new Color(0.2906, 0.7395, 0.5477)],
  14536. [0.7, new Color(0.4453, 0.8099, 0.5201)],
  14537. [0.8, new Color(0.6102, 0.8748, 0.485)],
  14538. [0.9, new Color(0.7883, 0.9323, 0.4514)],
  14539. [1, new Color(0.9804, 0.9804, 0.4314)],
  14540. ],
  14541. VIRIDIS: [
  14542. [0.0, new Color(0.267, 0.005, 0.329)],
  14543. [0.1, new Color(0.283, 0.141, 0.458)],
  14544. [0.2, new Color(0.254, 0.265, 0.53)],
  14545. [0.3, new Color(0.207, 0.372, 0.553)],
  14546. [0.4, new Color(0.164, 0.471, 0.558)],
  14547. [0.5, new Color(0.128, 0.567, 0.551)],
  14548. [0.6, new Color(0.135, 0.659, 0.518)],
  14549. [0.7, new Color(0.267, 0.749, 0.441)],
  14550. [0.8, new Color(0.478, 0.821, 0.318)],
  14551. [0.9, new Color(0.741, 0.873, 0.15)],
  14552. [1.0, new Color(0.993, 0.906, 0.144)],
  14553. ],
  14554. INFERNO: [
  14555. [0.0, new Color(0.077, 0.042, 0.206)],
  14556. [0.1, new Color(0.225, 0.036, 0.388)],
  14557. [0.2, new Color(0.373, 0.074, 0.432)],
  14558. [0.3, new Color(0.522, 0.128, 0.42)],
  14559. [0.4, new Color(0.665, 0.182, 0.37)],
  14560. [0.5, new Color(0.797, 0.255, 0.287)],
  14561. [0.6, new Color(0.902, 0.364, 0.184)],
  14562. [0.7, new Color(0.969, 0.516, 0.063)],
  14563. [0.8, new Color(0.988, 0.683, 0.072)],
  14564. [0.9, new Color(0.961, 0.859, 0.298)],
  14565. [1.0, new Color(0.988, 0.998, 0.645)],
  14566. ],
  14567. GRAYSCALE: [
  14568. [0, new Color(0, 0, 0)],
  14569. [1, new Color(1, 1, 1)],
  14570. ],
  14571. // 16 samples of the TURBU color scheme
  14572. // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f
  14573. // original file licensed under Apache-2.0
  14574. TURBO: [
  14575. [0.0, new Color(0.18995, 0.07176, 0.23217)],
  14576. [0.07, new Color(0.25107, 0.25237, 0.63374)],
  14577. [0.13, new Color(0.27628, 0.42118, 0.89123)],
  14578. [0.2, new Color(0.25862, 0.57958, 0.99876)],
  14579. [0.27, new Color(0.15844, 0.73551, 0.92305)],
  14580. [0.33, new Color(0.09267, 0.86554, 0.7623)],
  14581. [0.4, new Color(0.19659, 0.94901, 0.59466)],
  14582. [0.47, new Color(0.42778, 0.99419, 0.38575)],
  14583. [0.53, new Color(0.64362, 0.98999, 0.23356)],
  14584. [0.6, new Color(0.80473, 0.92452, 0.20459)],
  14585. [0.67, new Color(0.93301, 0.81236, 0.22667)],
  14586. [0.73, new Color(0.99314, 0.67408, 0.20348)],
  14587. [0.8, new Color(0.9836, 0.49291, 0.12849)],
  14588. [0.87, new Color(0.92105, 0.31489, 0.05475)],
  14589. [0.93, new Color(0.81608, 0.18462, 0.01809)],
  14590. [1.0, new Color(0.66449, 0.08436, 0.00424)],
  14591. ],
  14592. RAINBOW: [
  14593. [0, new Color(0.278, 0, 0.714)],
  14594. [1 / 6, new Color(0, 0, 1)],
  14595. [2 / 6, new Color(0, 1, 1)],
  14596. [3 / 6, new Color(0, 1, 0)],
  14597. [4 / 6, new Color(1, 1, 0)],
  14598. [5 / 6, new Color(1, 0.64, 0)],
  14599. [1, new Color(1, 0, 0)],
  14600. ],
  14601. CONTOUR: [
  14602. [0.0, new Color(0, 0, 0)],
  14603. [0.03, new Color(0, 0, 0)],
  14604. [0.04, new Color(1, 1, 1)],
  14605. [1.0, new Color(1, 1, 1)],
  14606. ],
  14607. };
  14608. const PointCloudFS = `
  14609. varying vec3 vColor;
  14610. uniform float alpha;
  14611. void main() {
  14612. if (vColor == vec3(0.0, 0.0, 0.0)) {
  14613. discard;
  14614. } else {
  14615. gl_FragColor = vec4( vColor, alpha);
  14616. }
  14617. }
  14618. `;
  14619. const PointCloudVS = `
  14620. varying vec3 vColor;
  14621. uniform sampler2D gradient;
  14622. uniform sampler2D grayscale;
  14623. attribute float intensity;
  14624. attribute float classification;
  14625. uniform vec3 rootCenter;
  14626. uniform vec3 rootNormal;
  14627. uniform vec2 elevationRange;
  14628. uniform int coloring;
  14629. uniform bool hideGround;
  14630. uniform float maxIntensity;
  14631. uniform float intensityContrast;
  14632. uniform float pointSize;
  14633. #ifdef USE_COLOR
  14634. vec3 getRGB() {
  14635. vec3 rgb = color;
  14636. return rgb;
  14637. }
  14638. #endif
  14639. vec3 getElevation(){
  14640. vec4 world = modelMatrix * vec4( position, 1.0 );
  14641. float diff = abs(dot(rootNormal, (vec3(world) - rootCenter)));
  14642. float w = max(diff - elevationRange.x,0.0) / max(elevationRange.y - elevationRange.x,1.0);
  14643. vec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;
  14644. return cElevation;
  14645. }
  14646. vec3 getIntensity(){
  14647. // TODO: real contrast enhancement. Check https://github.com/yuki-koyama/enhancer/blob/master/shaders/enhancer.fs
  14648. float intmod = pow(intensity, intensityContrast);
  14649. vec3 cIntensity = texture2D(grayscale, vec2(intmod / maxIntensity ,1.0-(intmod / maxIntensity))).rgb;
  14650. return cIntensity;
  14651. }
  14652. vec3 getClassification(){
  14653. float classNormalized = classification / 255.0;
  14654. vec3 cClassification = texture2D(gradient, vec2(classNormalized * 5.0,1.0-classNormalized * 5.0)).rgb;
  14655. return cClassification;
  14656. }
  14657. vec3 getColor(){
  14658. vec3 color;
  14659. if (hideGround && classification == 2.0) {
  14660. return vec3(0.0, 0.0, 0.0);
  14661. }
  14662. if (coloring == 1) {
  14663. color = getIntensity();
  14664. }
  14665. else if (coloring == 2) {
  14666. color = getClassification();
  14667. } else if (coloring == 3) {
  14668. color = getElevation();
  14669. }
  14670. #ifdef USE_COLOR
  14671. else if (coloring == 4) {
  14672. color = getRGB();
  14673. }
  14674. #endif
  14675. else {
  14676. color = vec3(1.0, 1.0, 1.0);
  14677. }
  14678. return color;
  14679. }
  14680. void main() {
  14681. vColor = getColor();
  14682. gl_PointSize = pointSize;
  14683. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  14684. }
  14685. `;
  14686. /** Types of coloring used when viewing point cloud tiles */
  14687. var PointCloudColoring;
  14688. (function (PointCloudColoring) {
  14689. PointCloudColoring[PointCloudColoring["Intensity"] = 1] = "Intensity";
  14690. PointCloudColoring[PointCloudColoring["Classification"] = 2] = "Classification";
  14691. PointCloudColoring[PointCloudColoring["Elevation"] = 3] = "Elevation";
  14692. PointCloudColoring[PointCloudColoring["RGB"] = 4] = "RGB";
  14693. PointCloudColoring[PointCloudColoring["White"] = 5] = "White";
  14694. })(PointCloudColoring || (PointCloudColoring = {}));
  14695. /** Types of shading used when viewing b3dm (mesh) tiles */
  14696. var Shading;
  14697. (function (Shading) {
  14698. Shading[Shading["FlatTexture"] = 1] = "FlatTexture";
  14699. Shading[Shading["ShadedTexture"] = 2] = "ShadedTexture";
  14700. Shading[Shading["ShadedNoTexture"] = 3] = "ShadedNoTexture";
  14701. })(Shading || (Shading = {}));
  14702. var GeoTransform;
  14703. (function (GeoTransform) {
  14704. GeoTransform[GeoTransform["Reset"] = 1] = "Reset";
  14705. GeoTransform[GeoTransform["Mercator"] = 2] = "Mercator";
  14706. GeoTransform[GeoTransform["WGS84Cartesian"] = 3] = "WGS84Cartesian";
  14707. })(GeoTransform || (GeoTransform = {}));
  14708. const Constant = {
  14709. //selectColor:new Color(25,0,0), //0xff0000
  14710. selectColor:0xff0000, //鼠标移动选中
  14711. defaultColor:0xffffff, //默认情况
  14712. clickColor:0x0000ff //点击选中
  14713. };
  14714. Constant.tilesMaterial = new MeshBasicMaterial({
  14715. transparent: false
  14716. });
  14717. const gradient = Gradients.RAINBOW;
  14718. const gradientTexture = typeof document != 'undefined' ? generateGradientTexture(gradient) : null;
  14719. const grayscale = Gradients.GRAYSCALE;
  14720. const grayscaleTexture = typeof document != 'undefined' ? generateGradientTexture(grayscale) : null;
  14721. const defaultOptions = {
  14722. throttleRequests: true,
  14723. maxRequests: 64,
  14724. updateInterval: 0.1,
  14725. maxConcurrency: 1,
  14726. maximumScreenSpaceError: 16,
  14727. maximumMemoryUsage: 32,
  14728. viewDistanceScale: 1.0,
  14729. skipLevelOfDetail: false,
  14730. updateTransforms: true,
  14731. shading: Shading.FlatTexture,
  14732. transparent: false,
  14733. pointCloudColoring: PointCloudColoring.White,
  14734. pointSize: 1.0,
  14735. worker: true,
  14736. wireframe: false,
  14737. debug: true,
  14738. basisTranscoderPath: null,
  14739. dracoDecoderPath: null,
  14740. material: null,
  14741. computeNormals: false,
  14742. shaderCallback: null,
  14743. geoTransform: GeoTransform.Reset,
  14744. preloadTilesCount: null
  14745. };
  14746. /** 3D Tiles Loader */
  14747. class Loader3DTiles {
  14748. /**
  14749. * Loads a tileset of 3D Tiles according to the given {@link LoaderProps}
  14750. * @public
  14751. *
  14752. * @param props - Properties for this load call {@link LoaderProps}.
  14753. * @returns An object containing the 3D Model to be added to the scene
  14754. * and a runtime engine to be updated every frame.
  14755. */
  14756. static load(props) {
  14757. return __awaiter(this, void 0, void 0, function* () {
  14758. const options = Object.assign(Object.assign({}, defaultOptions), props.options);
  14759. const { url } = props;
  14760. const UPDATE_INTERVAL = options.updateInterval;
  14761. const MAX_DEPTH_FOR_ORIENTATION = 5;
  14762. const loadersGLOptions = {};
  14763. if (options.cesiumIONToken) {
  14764. loadersGLOptions['cesium-ion'] = {
  14765. accessToken: options.cesiumIONToken,
  14766. };
  14767. const metadata = yield CesiumIonLoader.preload(url, loadersGLOptions);
  14768. loadersGLOptions['fetch'] = { headers: metadata.headers };
  14769. }
  14770. if (props.loadingManager) {
  14771. props.loadingManager.itemStart(url);
  14772. }
  14773. const tilesetJson = yield load(url, Tiles3DLoader, Object.assign({}, loadersGLOptions));
  14774. const renderMap = {};
  14775. const boxMap = {};
  14776. const unloadQueue = [];
  14777. const root = new Group();
  14778. const tileBoxes = new Group();
  14779. if (!options.debug) {
  14780. tileBoxes.visible = false;
  14781. }
  14782. const pointcloudUniforms = {
  14783. pointSize: { type: 'f', value: options.pointSize },
  14784. gradient: { type: 't', value: gradientTexture },
  14785. grayscale: { type: 't', value: grayscaleTexture },
  14786. rootCenter: { type: 'vec3', value: new Vector3$1() },
  14787. rootNormal: { type: 'vec3', value: new Vector3$1() },
  14788. coloring: { type: 'i', value: options.pointCloudColoring },
  14789. hideGround: { type: 'b', value: true },
  14790. elevationRange: { type: 'vec2', value: new Vector2$1(0, 400) },
  14791. maxIntensity: { type: 'f', value: 1.0 },
  14792. intensityContrast: { type: 'f', value: 1.0 },
  14793. alpha: { type: 'f', value: 1.0 },
  14794. };
  14795. const pointcloudMaterial = new ShaderMaterial({
  14796. uniforms: pointcloudUniforms,
  14797. vertexShader: PointCloudVS,
  14798. fragmentShader: PointCloudFS,
  14799. transparent: options.transparent,
  14800. vertexColors: true
  14801. });
  14802. let cameraReference = null;
  14803. let rendererReference = null;
  14804. const gltfLoader = new GLTFLoader$1();
  14805. let ktx2Loader = undefined;
  14806. let dracoLoader = undefined;
  14807. if (options.basisTranscoderPath) {
  14808. ktx2Loader = new KTX2Loader();
  14809. ktx2Loader.detectSupport(props.renderer);
  14810. ktx2Loader.setTranscoderPath(options.basisTranscoderPath + '/');
  14811. ktx2Loader.setWorkerLimit(1);
  14812. gltfLoader.setKTX2Loader(ktx2Loader);
  14813. }
  14814. if (options.dracoDecoderPath) {
  14815. dracoLoader = new DRACOLoader();
  14816. dracoLoader.setDecoderPath(options.dracoDecoderPath + '/');
  14817. dracoLoader.setWorkerLimit(options.maxConcurrency);
  14818. gltfLoader.setDRACOLoader(dracoLoader);
  14819. }
  14820. const unlitMaterial = new MeshBasicMaterial({ transparent: options.transparent });
  14821. const tileOptions = {
  14822. maximumMemoryUsage: options.maximumMemoryUsage,
  14823. maximumScreenSpaceError: options.maximumScreenSpaceError,
  14824. viewDistanceScale: options.viewDistanceScale,
  14825. skipLevelOfDetail: options.skipLevelOfDetail,
  14826. updateTransforms: options.updateTransforms,
  14827. throttleRequests: options.throttleRequests,
  14828. maxRequests: options.maxRequests,
  14829. contentLoader: (tile) => __awaiter(this, void 0, void 0, function* () {
  14830. let tileContent = null;
  14831. switch (tile.type) {
  14832. case TILE_TYPE.POINTCLOUD: {
  14833. tileContent = createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse);
  14834. break;
  14835. }
  14836. case TILE_TYPE.SCENEGRAPH:
  14837. case TILE_TYPE.MESH: {
  14838. tileContent = yield createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse);
  14839. //tileContent = await createGLTFNodes(gltfLoader, tile, options, rootTransformInverse);
  14840. break;
  14841. }
  14842. }
  14843. if (tileContent) {
  14844. tileContent.visible = false;
  14845. renderMap[tile.id] = tileContent;
  14846. root.add(renderMap[tile.id]);
  14847. if (options.debug) {
  14848. const box = loadersBoundingBoxToMesh(tile);
  14849. tileBoxes.add(box);
  14850. boxMap[tile.id] = box;
  14851. }
  14852. }
  14853. }),
  14854. onTileLoad: (tile) => __awaiter(this, void 0, void 0, function* () {
  14855. if (tileset) {
  14856. if (!orientationDetected && (tile === null || tile === void 0 ? void 0 : tile.depth) <= MAX_DEPTH_FOR_ORIENTATION) {
  14857. detectOrientation(tile);
  14858. }
  14859. tileset._frameNumber++;
  14860. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  14861. }
  14862. }),
  14863. onTileUnload: (tile) => {
  14864. unloadQueue.push(tile);
  14865. },
  14866. onTileError: (tile, message) => {
  14867. console.error('Tile error', tile.id, message);
  14868. },
  14869. };
  14870. const tileset = new Tileset3D(tilesetJson, Object.assign(Object.assign({}, tileOptions), { loadOptions: Object.assign(Object.assign({}, loadersGLOptions), { maxConcurrency: options.maxConcurrency, worker: options.worker, gltf: {
  14871. loadImages: false,
  14872. }, '3d-tiles': {
  14873. loadGLTF: false
  14874. } }) }));
  14875. //
  14876. // transformations
  14877. const threeMat = new Matrix4$1();
  14878. const tileTrasnform = new Matrix4$1();
  14879. const rootCenter = new Vector3$1();
  14880. let orientationDetected = false;
  14881. if (tileset.root.boundingVolume) {
  14882. if (tileset.root.header.boundingVolume.region) {
  14883. // TODO: Handle region type bounding volumes
  14884. // https://github.com/visgl/loaders.gl/issues/1994
  14885. console.warn("Cannot apply a model matrix to bounding volumes of type region. Tileset stays in original geo-coordinates.");
  14886. options.geoTransform = GeoTransform.WGS84Cartesian;
  14887. }
  14888. tileTrasnform.setPosition(tileset.root.boundingVolume.center[0], tileset.root.boundingVolume.center[1], tileset.root.boundingVolume.center[2]);
  14889. }
  14890. else {
  14891. console.warn("Bounding volume not found, no transformations applied");
  14892. }
  14893. if (options.debug) {
  14894. const box = loadersBoundingBoxToMesh(tileset.root);
  14895. tileBoxes.add(box);
  14896. boxMap[tileset.root.id] = box;
  14897. }
  14898. let disposeFlag = false;
  14899. let loadingEnded = false;
  14900. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  14901. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).normalize());
  14902. // Extra stats
  14903. tileset.stats.get('Loader concurrency').count = options.maxConcurrency;
  14904. tileset.stats.get('Maximum SSE').count = options.maximumScreenSpaceError;
  14905. tileset.stats.get('Maximum mem usage').count = options.maximumMemoryUsage;
  14906. let timer = 0;
  14907. const lastCameraTransform = new Matrix4$1().makeTranslation(Infinity, Infinity, Infinity);
  14908. let lastCameraAspect = null;
  14909. const lastCameraPosition = new Vector3$1(Infinity, Infinity, Infinity);
  14910. let sseDenominator = null;
  14911. root.updateMatrixWorld(true);
  14912. const lastRootTransform = new Matrix4$1().copy(root.matrixWorld);
  14913. const rootTransformInverse = new Matrix4$1().copy(lastRootTransform).invert();
  14914. detectOrientation(tileset.root);
  14915. updateResetTransform();
  14916. if (options.debug) {
  14917. boxMap[tileset.root.id].applyMatrix4(threeMat);
  14918. tileBoxes.matrixWorld.copy(root.matrixWorld);
  14919. }
  14920. if (options.geoTransform == GeoTransform.Mercator) {
  14921. const coords = datumsToSpherical(tileset.cartographicCenter[1], tileset.cartographicCenter[0]);
  14922. rootCenter.set(coords.x, 0, -coords.y);
  14923. root.position.copy(rootCenter);
  14924. root.rotation.set(-Math.PI / 2, 0, 0);
  14925. root.updateMatrixWorld(true);
  14926. }
  14927. else if (options.geoTransform == GeoTransform.WGS84Cartesian) {
  14928. root.applyMatrix4(tileTrasnform);
  14929. root.updateMatrixWorld(true);
  14930. rootCenter.copy(root.position);
  14931. }
  14932. function detectOrientation(tile) {
  14933. if (!tile.boundingVolume.halfAxes) {
  14934. return;
  14935. }
  14936. const halfAxes = tile.boundingVolume.halfAxes;
  14937. const orientationMatrix = new Matrix4$1()
  14938. .extractRotation(getMatrix4FromHalfAxes(halfAxes))
  14939. .premultiply(new Matrix4$1().extractRotation(rootTransformInverse));
  14940. const rotation = new Euler().setFromRotationMatrix(orientationMatrix);
  14941. if (!rotation.equals(new Euler())) {
  14942. orientationDetected = true;
  14943. const pos = new Vector3$1(tileTrasnform.elements[12], tileTrasnform.elements[13], tileTrasnform.elements[14]);
  14944. tileTrasnform.extractRotation(orientationMatrix);
  14945. tileTrasnform.setPosition(pos);
  14946. updateResetTransform();
  14947. }
  14948. }
  14949. function updateResetTransform() {
  14950. if (options.geoTransform != GeoTransform.WGS84Cartesian) {
  14951. // Reset the current model matrix and apply our own transformation
  14952. threeMat.copy(tileTrasnform).invert();
  14953. threeMat.premultiply(lastRootTransform);
  14954. threeMat.copy(lastRootTransform).multiply(new Matrix4$1().copy(tileTrasnform).invert());
  14955. tileset.modelMatrix = new Matrix4(threeMat.toArray());
  14956. }
  14957. }
  14958. function tilesetUpdate(tileset, renderMap, renderer, camera) {
  14959. if (disposeFlag) {
  14960. return;
  14961. }
  14962. // Assumes camera fov, near and far are not changing
  14963. if (!sseDenominator || camera.aspect != lastCameraAspect) {
  14964. const loadersFrustum = new PerspectiveFrustum({
  14965. fov: (camera.fov / 180) * Math.PI,
  14966. aspectRatio: camera.aspect,
  14967. near: camera.near,
  14968. far: camera.far,
  14969. });
  14970. sseDenominator = loadersFrustum.sseDenominator;
  14971. lastCameraAspect = camera.aspect;
  14972. if (options.debug) {
  14973. console.log('Updated sse denonimator:', sseDenominator);
  14974. }
  14975. }
  14976. const frustum = getCameraFrustum(camera);
  14977. const planes = frustum.planes.map((plane) => new Plane(plane.normal.toArray(), plane.constant));
  14978. const cullingVolume = new CullingVolume(planes);
  14979. const rendererSize = new Vector2$1();
  14980. renderer.getSize(rendererSize);
  14981. const frameState = {
  14982. camera: {
  14983. position: lastCameraPosition.toArray(),
  14984. },
  14985. height: rendererSize.y,
  14986. frameNumber: tileset._frameNumber,
  14987. sseDenominator: sseDenominator,
  14988. cullingVolume: cullingVolume,
  14989. viewport: {
  14990. id: 0,
  14991. },
  14992. };
  14993. tileset._cache.reset();
  14994. tileset._traverser.traverse(tileset.root, frameState, tileset.options);
  14995. for (const tile of tileset.tiles) {
  14996. if (tile.selected) {
  14997. if (!renderMap[tile.id]) {
  14998. console.error('TILE SELECTED BUT NOT LOADED!!', tile.id);
  14999. }
  15000. else {
  15001. // Make sure it's visible
  15002. renderMap[tile.id].visible = true;
  15003. }
  15004. }
  15005. else {
  15006. if (renderMap[tile.id]) {
  15007. renderMap[tile.id].visible = false;
  15008. }
  15009. }
  15010. }
  15011. while (unloadQueue.length > 0) {
  15012. const tile = unloadQueue.pop();
  15013. if (renderMap[tile.id] && tile.contentState == TILE_CONTENT_STATE.UNLOADED) {
  15014. root.remove(renderMap[tile.id]);
  15015. disposeNode(renderMap[tile.id]);
  15016. delete renderMap[tile.id];
  15017. }
  15018. if (boxMap[tile.id]) {
  15019. disposeNode(boxMap[tile.id]);
  15020. tileBoxes.remove(boxMap[tile.id]);
  15021. delete boxMap[tile.id];
  15022. }
  15023. }
  15024. const tilesLoaded = tileset.stats.get('Tiles Loaded').count;
  15025. const tilesLoading = tileset.stats.get('Tiles Loading').count;
  15026. if (props.onProgress) {
  15027. props.onProgress(tilesLoaded, tilesLoaded + tilesLoading);
  15028. }
  15029. if (props.loadingManager && !loadingEnded) {
  15030. if (tilesLoading == 0 &&
  15031. (options.preloadTilesCount == null ||
  15032. tilesLoaded >= options.preloadTilesCount)) {
  15033. loadingEnded = true;
  15034. props.loadingManager.itemEnd(props.url);
  15035. }
  15036. }
  15037. return frameState;
  15038. }
  15039. return {
  15040. model: root,
  15041. runtime: {
  15042. getTileset: () => {
  15043. return tileset;
  15044. },
  15045. getStats: () => {
  15046. return tileset.stats;
  15047. },
  15048. showTiles: (visible) => {
  15049. tileBoxes.visible = visible;
  15050. },
  15051. setWireframe: (wireframe) => {
  15052. options.wireframe = wireframe;
  15053. root.traverse((object) => {
  15054. if (object instanceof Mesh) {
  15055. object.material.wireframe = wireframe;
  15056. }
  15057. });
  15058. },
  15059. setDebug: (debug) => {
  15060. options.debug = debug;
  15061. tileBoxes.visible = debug;
  15062. },
  15063. setShading: (shading) => {
  15064. options.shading = shading;
  15065. },
  15066. getTileBoxes: () => {
  15067. return tileBoxes;
  15068. },
  15069. setViewDistanceScale: (scale) => {
  15070. tileset.options.viewDistanceScale = scale;
  15071. tileset._frameNumber++;
  15072. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  15073. },
  15074. setHideGround: (enabled) => {
  15075. pointcloudUniforms.hideGround.value = enabled;
  15076. },
  15077. setPointCloudColoring: (selection) => {
  15078. pointcloudUniforms.coloring.value = selection;
  15079. },
  15080. setElevationRange: (range) => {
  15081. pointcloudUniforms.elevationRange.value.set(range[0], range[1]);
  15082. },
  15083. setMaxIntensity: (intensity) => {
  15084. pointcloudUniforms.maxIntensity.value = intensity;
  15085. },
  15086. setIntensityContrast: (contrast) => {
  15087. pointcloudUniforms.intensityContrast.value = contrast;
  15088. },
  15089. setPointAlpha: (alpha) => {
  15090. pointcloudUniforms.alpha.value = alpha;
  15091. },
  15092. getLatLongHeightFromPosition: (position) => {
  15093. const cartographicPosition = tileset.ellipsoid.cartesianToCartographic(new Vector3$1().copy(position).applyMatrix4(new Matrix4$1().copy(threeMat).invert()).toArray());
  15094. return {
  15095. lat: cartographicPosition[1],
  15096. long: cartographicPosition[0],
  15097. height: cartographicPosition[2],
  15098. };
  15099. },
  15100. getPositionFromLatLongHeight: (coord) => {
  15101. const cartesianPosition = tileset.ellipsoid.cartographicToCartesian([coord.long, coord.lat, coord.height]);
  15102. return new Vector3$1(...cartesianPosition).applyMatrix4(threeMat);
  15103. },
  15104. getCameraFrustum: (camera) => {
  15105. const frustum = getCameraFrustum(camera);
  15106. const meshes = frustum.planes
  15107. .map((plane) => new Plane(plane.normal.toArray(), plane.constant))
  15108. .map((loadersPlane) => loadersPlaneToMesh(loadersPlane));
  15109. const model = new Group();
  15110. for (const mesh of meshes)
  15111. model.add(mesh);
  15112. return model;
  15113. },
  15114. update: function (dt, renderer, camera) {
  15115. cameraReference = camera;
  15116. rendererReference = renderer;
  15117. timer += dt;
  15118. if (tileset && timer >= UPDATE_INTERVAL) {
  15119. if (!lastRootTransform.equals(root.matrixWorld)) {
  15120. lastRootTransform.copy(root.matrixWorld);
  15121. updateResetTransform();
  15122. const rootCenter = new Vector3$1().setFromMatrixPosition(lastRootTransform);
  15123. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  15124. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).applyMatrix4(lastRootTransform).normalize());
  15125. rootTransformInverse.copy(lastRootTransform).invert();
  15126. if (options.debug) {
  15127. boxMap[tileset.root.id].matrixWorld.copy(threeMat);
  15128. boxMap[tileset.root.id].applyMatrix4(lastRootTransform);
  15129. }
  15130. }
  15131. const cameraChanged = !camera.matrixWorld.equals(lastCameraTransform) ||
  15132. !(camera.aspect == lastCameraAspect);
  15133. if (cameraChanged) {
  15134. timer = 0;
  15135. tileset._frameNumber++;
  15136. camera.getWorldPosition(lastCameraPosition);
  15137. lastCameraTransform.copy(camera.matrixWorld);
  15138. tilesetUpdate(tileset, renderMap, renderer, camera);
  15139. }
  15140. }
  15141. },
  15142. dispose: function () {
  15143. disposeFlag = true;
  15144. tileset._destroy();
  15145. while (root.children.length > 0) {
  15146. const obj = root.children[0];
  15147. disposeNode(obj);
  15148. root.remove(obj);
  15149. }
  15150. while (tileBoxes.children.length > 0) {
  15151. const obj = tileBoxes.children[0];
  15152. tileBoxes.remove(obj);
  15153. obj.geometry.dispose();
  15154. obj.material.dispose();
  15155. }
  15156. if (ktx2Loader) {
  15157. ktx2Loader.dispose();
  15158. }
  15159. if (dracoLoader) {
  15160. dracoLoader.dispose();
  15161. }
  15162. },
  15163. },
  15164. };
  15165. });
  15166. }
  15167. }
  15168. function createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse) {
  15169. return __awaiter(this, void 0, void 0, function* () {
  15170. //async function createGLTFNodes(gltfLoader, tile, options, rootTransformInverse): Promise<Object3D> {
  15171. return new Promise((resolve, reject) => {
  15172. var _a;
  15173. const rotateX = new Matrix4$1().makeRotationAxis(new Vector3$1(1, 0, 0), Math.PI / 2);
  15174. const shouldRotate = ((_a = tile.tileset.asset) === null || _a === void 0 ? void 0 : _a.gltfUpAxis) !== "Z";
  15175. // The computed trasnform already contains the root's transform, so we have to invert it
  15176. const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(rootTransformInverse);
  15177. console.log('tile.computedTransform:' + tile.computedTransform);
  15178. console.log('rootTransformInverse:' + rootTransformInverse.elements);
  15179. //console.log('contentTransform:'+contentTransform.elements);
  15180. if (shouldRotate) {
  15181. contentTransform.multiply(rotateX); // convert from GLTF Y-up to Z-up
  15182. }
  15183. gltfLoader.parse(tile.content.gltfArrayBuffer, tile.contentUrl ? tile.contentUrl.substr(0, tile.contentUrl.lastIndexOf('/') + 1) : '', (gltf) => {
  15184. const tileContent = gltf.scenes[0];
  15185. tileContent.applyMatrix4(contentTransform);
  15186. tileContent.traverse((object) => {
  15187. if (object.type == "Mesh") {
  15188. const mesh = object;
  15189. const originalMaterial = mesh.material;
  15190. const originalMap = originalMaterial.map;
  15191. if (options.material) {
  15192. mesh.material = options.material.clone();
  15193. originalMaterial.dispose();
  15194. }
  15195. else if (options.shading == Shading.FlatTexture) {
  15196. //mesh.material = unlitMaterial.clone();
  15197. mesh.material = Constant.tilesMaterial.clone();
  15198. originalMaterial.dispose();
  15199. }
  15200. if (options.shading != Shading.ShadedNoTexture) {
  15201. if (mesh.material.type == "ShaderMaterial") {
  15202. mesh.material.uniforms.map = { value: originalMap };
  15203. }
  15204. else {
  15205. mesh.material.map = originalMap;
  15206. }
  15207. }
  15208. else {
  15209. if (originalMap) {
  15210. originalMap.dispose();
  15211. }
  15212. mesh.material.map = null;
  15213. }
  15214. if (options.shaderCallback) {
  15215. mesh.onBeforeRender = options.shaderCallback;
  15216. }
  15217. mesh.material.wireframe = options.wireframe;
  15218. if (options.computeNormals) {
  15219. mesh.geometry.computeVertexNormals();
  15220. }
  15221. }
  15222. });
  15223. resolve(tileContent);
  15224. }, (e) => {
  15225. reject(new Error(`error parsing gltf in tile ${tile.id}: ${e}`));
  15226. });
  15227. });
  15228. });
  15229. }
  15230. function createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse) {
  15231. const d = {
  15232. rtc_center: tile.content.rtcCenter,
  15233. points: tile.content.attributes.positions,
  15234. intensities: tile.content.attributes.intensity,
  15235. classifications: tile.content.attributes.classification,
  15236. rgb: null,
  15237. rgba: null,
  15238. };
  15239. const { colors } = tile.content.attributes;
  15240. if (colors && colors.size === 3) {
  15241. d.rgb = colors.value;
  15242. }
  15243. if (colors && colors.size === 4) {
  15244. d.rgba = colors.value;
  15245. }
  15246. const geometry = new BufferGeometry();
  15247. geometry.setAttribute('position', new Float32BufferAttribute(d.points, 3));
  15248. const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(rootTransformInverse);
  15249. if (d.rgba) {
  15250. geometry.setAttribute('color', new Float32BufferAttribute(d.rgba, 4));
  15251. }
  15252. else if (d.rgb) {
  15253. geometry.setAttribute('color', new Uint8BufferAttribute(d.rgb, 3, true));
  15254. }
  15255. if (d.intensities) {
  15256. geometry.setAttribute('intensity',
  15257. // Handles both 16bit or 8bit intensity values
  15258. new BufferAttribute(d.intensities, 1, true));
  15259. }
  15260. if (d.classifications) {
  15261. geometry.setAttribute('classification', new Uint8BufferAttribute(d.classifications, 1, false));
  15262. }
  15263. const tileContent = new Points(geometry, options.material || pointcloudMaterial);
  15264. if (d.rtc_center) {
  15265. const c = d.rtc_center;
  15266. contentTransform.multiply(new Matrix4$1().makeTranslation(c[0], c[1], c[2]));
  15267. }
  15268. tileContent.applyMatrix4(contentTransform);
  15269. return tileContent;
  15270. }
  15271. function disposeMaterial(material) {
  15272. var _a, _b, _c, _d;
  15273. if ((_a = material === null || material === void 0 ? void 0 : material.uniforms) === null || _a === void 0 ? void 0 : _a.map) {
  15274. (_c = (_b = material === null || material === void 0 ? void 0 : material.uniforms) === null || _b === void 0 ? void 0 : _b.map.value) === null || _c === void 0 ? void 0 : _c.dispose();
  15275. }
  15276. else if (material.map) {
  15277. (_d = material.map) === null || _d === void 0 ? void 0 : _d.dispose();
  15278. }
  15279. material.dispose();
  15280. }
  15281. function disposeNode(node) {
  15282. node.traverse((object) => {
  15283. if (object.isMesh) {
  15284. object.geometry.dispose();
  15285. if (object.material.isMaterial) {
  15286. disposeMaterial(object.material);
  15287. }
  15288. else {
  15289. // an array of materials
  15290. for (const material of object.material) {
  15291. disposeMaterial(material);
  15292. }
  15293. }
  15294. }
  15295. });
  15296. for (let i = node.children.length - 1; i >= 0; i--) {
  15297. const obj = node.children[i];
  15298. node.remove(obj);
  15299. }
  15300. }
  15301. export { GeoTransform, Loader3DTiles, PointCloudColoring, Shading };
  15302. //# sourceMappingURL=three-loader-3dtiles.esm.js.map