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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274
  1. import { EventDispatcher, CanvasTexture, LinearFilter, RepeatWrapping, Vector2 as Vector2$1, Frustum, Matrix4 as Matrix4$1, Group, PlaneGeometry, Vector3 as Vector3$1/*, MeshBasicMaterial */, DoubleSide, Mesh, ArrowHelper, Color, BoxGeometry, EdgesGeometry, LineSegments, LineBasicMaterial, ShaderMaterial, Euler, BufferGeometry, Float32BufferAttribute, Uint8BufferAttribute, BufferAttribute, Points } from '../build/three.module.js';
  2. import { GLTFLoader as GLTFLoader$1 } from '../loaders/GLTFLoader.js';
  3. import { DRACOLoader } from '../loaders/DRACOLoader.js';
  4. import { KTX2Loader } from '../loaders/KTX2Loader.js';
  5. import MeshBasicMaterial from '../../../src/custom/materials/BasicMaterial.js' // xzw改 原先MeshBasicMaterial贴图发黑,可能和贴图有关
  6. let globalThis = window //add 有的app没有globalThis. 2023.1
  7. let rtcCenterGlobal = false//默认false,也就是scale.z要乘以-1
  8. /*! *****************************************************************************
  9. github: https://github.com/nytimes/three-loader-3dtiles
  10. Copyright (c) Microsoft Corporation.
  11. Permission to use, copy, modify, and/or distribute this software for any
  12. purpose with or without fee is hereby granted.
  13. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  14. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  15. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  16. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  17. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  18. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  19. PERFORMANCE OF THIS SOFTWARE.
  20. ***************************************************************************** */
  21. let visiVertexCount = 0
  22. let visiGeoCount = 0
  23. const maxVertexVisi = 5e6
  24. const maxTexVisi = 500
  25. const maxDepth = 100
  26. function getGpuMemoryUsage(win = window){//总的
  27. let c = 0
  28. viewer.objs.children.filter(e=>{
  29. if(e.fileType == '3dTiles'){
  30. e.traverse(child=>{
  31. if(child.runtime){
  32. let tileset3D = child.runtime.getTileset()
  33. c += tileset3D.gpuMemoryUsageInBytes
  34. return {stopContinue:true}
  35. }
  36. })
  37. }
  38. })
  39. if(win.parent != win){//还有父级页面。 暂时只有子级需要考虑父级,假设父级在前台时子级已经销毁
  40. c += getGpuMemoryUsage(win.parent)
  41. }
  42. viewer.tiles3dMemoryUsage = c
  43. viewer.tiles3dVisiVCount = visiVertexCount
  44. return c
  45. }
  46. function __awaiter(thisArg, _arguments, P, generator) {
  47. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  48. return new (P || (P = Promise))(function (resolve, reject) {
  49. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  50. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  51. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  52. step((generator = generator.apply(thisArg, _arguments || [])).next());
  53. });
  54. }
  55. function assert$7(condition, message) {
  56. if (!condition) {
  57. throw new Error(message || 'loader assertion failed.');
  58. }
  59. }
  60. const isBrowser$2 = Boolean(typeof process !== 'object' || String(process) !== '[object process]' || process.browser);
  61. const matches$1 = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  62. matches$1 && parseFloat(matches$1[1]) || 0;
  63. const VERSION$8 = "3.1.4" ;
  64. function assert$6(condition, message) {
  65. if (!condition) {
  66. throw new Error(message || 'loaders.gl assertion failed.');
  67. }
  68. }
  69. const globals$1 = {
  70. self: typeof self !== 'undefined' && self,
  71. window: typeof window !== 'undefined' && window,
  72. global: typeof global !== 'undefined' && global,
  73. document: typeof document !== 'undefined' && document
  74. };
  75. const global_ = globals$1.global || globals$1.self || globals$1.window || {};
  76. const isBrowser$1 = typeof process !== 'object' || String(process) !== '[object process]' || process.browser;
  77. const isWorker = typeof importScripts === 'function';
  78. const isMobile = typeof window !== 'undefined' && typeof window.orientation !== 'undefined';
  79. const matches = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  80. matches && parseFloat(matches[1]) || 0;
  81. function _defineProperty(obj, key, value) {
  82. if (key in obj) {
  83. Object.defineProperty(obj, key, {
  84. value: value,
  85. enumerable: true,
  86. configurable: true,
  87. writable: true
  88. });
  89. } else {
  90. obj[key] = value;
  91. }
  92. return obj;
  93. }
  94. class WorkerJob {
  95. constructor(jobName, workerThread) {
  96. _defineProperty(this, "name", void 0);
  97. _defineProperty(this, "workerThread", void 0);
  98. _defineProperty(this, "isRunning", void 0);
  99. _defineProperty(this, "result", void 0);
  100. _defineProperty(this, "_resolve", void 0);
  101. _defineProperty(this, "_reject", void 0);
  102. this.name = jobName;
  103. this.workerThread = workerThread;
  104. this.isRunning = true;
  105. this._resolve = () => {};
  106. this._reject = () => {};
  107. this.result = new Promise((resolve, reject) => {
  108. this._resolve = resolve;
  109. this._reject = reject;
  110. });
  111. }
  112. postMessage(type, payload) {
  113. this.workerThread.postMessage({
  114. source: 'loaders.gl',
  115. type,
  116. payload
  117. });
  118. }
  119. done(value) {
  120. assert$6(this.isRunning);
  121. this.isRunning = false;
  122. this._resolve(value);
  123. }
  124. error(error) {
  125. assert$6(this.isRunning);
  126. this.isRunning = false;
  127. this._reject(error);
  128. }
  129. }
  130. const workerURLCache = new Map();
  131. function getLoadableWorkerURL(props) {
  132. assert$6(props.source && !props.url || !props.source && props.url);
  133. let workerURL = workerURLCache.get(props.source || props.url);
  134. if (!workerURL) {
  135. if (props.url) {
  136. workerURL = getLoadableWorkerURLFromURL(props.url);
  137. workerURLCache.set(props.url, workerURL);
  138. }
  139. if (props.source) {
  140. workerURL = getLoadableWorkerURLFromSource(props.source);
  141. workerURLCache.set(props.source, workerURL);
  142. }
  143. }
  144. assert$6(workerURL);
  145. return workerURL;
  146. }
  147. function getLoadableWorkerURLFromURL(url) {
  148. if (!url.startsWith('http')) {
  149. return url;
  150. }
  151. const workerSource = buildScriptSource(url);
  152. return getLoadableWorkerURLFromSource(workerSource);
  153. }
  154. function getLoadableWorkerURLFromSource(workerSource) {
  155. const blob = new Blob([workerSource], {
  156. type: 'application/javascript'
  157. });
  158. return URL.createObjectURL(blob);
  159. }
  160. function buildScriptSource(workerUrl) {
  161. return "try {\n importScripts('".concat(workerUrl, "');\n} catch (error) {\n console.error(error);\n throw error;\n}");
  162. }
  163. function getTransferList(object, recursive = true, transfers) {
  164. const transfersSet = transfers || new Set();
  165. if (!object) ; else if (isTransferable(object)) {
  166. transfersSet.add(object);
  167. } else if (isTransferable(object.buffer)) {
  168. transfersSet.add(object.buffer);
  169. } else if (ArrayBuffer.isView(object)) ; else if (recursive && typeof object === 'object') {
  170. for (const key in object) {
  171. getTransferList(object[key], recursive, transfersSet);
  172. }
  173. }
  174. return transfers === undefined ? Array.from(transfersSet) : [];
  175. }
  176. function isTransferable(object) {
  177. if (!object) {
  178. return false;
  179. }
  180. if (object instanceof ArrayBuffer) {
  181. return true;
  182. }
  183. if (typeof MessagePort !== 'undefined' && object instanceof MessagePort) {
  184. return true;
  185. }
  186. if (typeof ImageBitmap !== 'undefined' && object instanceof ImageBitmap) {
  187. return true;
  188. }
  189. if (typeof OffscreenCanvas !== 'undefined' && object instanceof OffscreenCanvas) {
  190. return true;
  191. }
  192. return false;
  193. }
  194. const NOOP = () => {};
  195. class WorkerThread {
  196. static isSupported() {
  197. return typeof Worker !== 'undefined';
  198. }
  199. constructor(props) {
  200. _defineProperty(this, "name", void 0);
  201. _defineProperty(this, "source", void 0);
  202. _defineProperty(this, "url", void 0);
  203. _defineProperty(this, "terminated", false);
  204. _defineProperty(this, "worker", void 0);
  205. _defineProperty(this, "onMessage", void 0);
  206. _defineProperty(this, "onError", void 0);
  207. _defineProperty(this, "_loadableURL", '');
  208. const {
  209. name,
  210. source,
  211. url
  212. } = props;
  213. assert$6(source || url);
  214. this.name = name;
  215. this.source = source;
  216. this.url = url;
  217. this.onMessage = NOOP;
  218. this.onError = error => console.log(error);
  219. this.worker = this._createBrowserWorker();
  220. }
  221. destroy() {
  222. this.onMessage = NOOP;
  223. this.onError = NOOP;
  224. this.worker.terminate();
  225. this.terminated = true;
  226. }
  227. get isRunning() {
  228. return Boolean(this.onMessage);
  229. }
  230. postMessage(data, transferList) {
  231. transferList = transferList || getTransferList(data);
  232. this.worker.postMessage(data, transferList);
  233. }
  234. _getErrorFromErrorEvent(event) {
  235. let message = 'Failed to load ';
  236. message += "worker ".concat(this.name, " from ").concat(this.url, ". ");
  237. if (event.message) {
  238. message += "".concat(event.message, " in ");
  239. }
  240. if (event.lineno) {
  241. message += ":".concat(event.lineno, ":").concat(event.colno);
  242. }
  243. return new Error(message);
  244. }
  245. _createBrowserWorker() {
  246. this._loadableURL = getLoadableWorkerURL({
  247. source: this.source,
  248. url: this.url
  249. });
  250. const worker = new Worker(this._loadableURL, {
  251. name: this.name
  252. });
  253. worker.onmessage = event => {
  254. if (!event.data) {
  255. this.onError(new Error('No data received'));
  256. } else {
  257. this.onMessage(event.data);
  258. }
  259. };
  260. worker.onerror = error => {
  261. this.onError(this._getErrorFromErrorEvent(error));
  262. this.terminated = true;
  263. };
  264. worker.onmessageerror = event => console.error(event);
  265. return worker;
  266. }
  267. }
  268. class WorkerPool {
  269. constructor(props) {
  270. _defineProperty(this, "name", 'unnamed');
  271. _defineProperty(this, "source", void 0);
  272. _defineProperty(this, "url", void 0);
  273. _defineProperty(this, "maxConcurrency", 1);
  274. _defineProperty(this, "maxMobileConcurrency", 1);
  275. _defineProperty(this, "onDebug", () => {});
  276. _defineProperty(this, "reuseWorkers", true);
  277. _defineProperty(this, "props", {});
  278. _defineProperty(this, "jobQueue", []);
  279. _defineProperty(this, "idleQueue", []);
  280. _defineProperty(this, "count", 0);
  281. _defineProperty(this, "isDestroyed", false);
  282. this.source = props.source;
  283. this.url = props.url;
  284. this.setProps(props);
  285. }
  286. destroy() {
  287. this.idleQueue.forEach(worker => worker.destroy());
  288. this.isDestroyed = true;
  289. }
  290. setProps(props) {
  291. this.props = { ...this.props,
  292. ...props
  293. };
  294. if (props.name !== undefined) {
  295. this.name = props.name;
  296. }
  297. if (props.maxConcurrency !== undefined) {
  298. this.maxConcurrency = props.maxConcurrency;
  299. }
  300. if (props.maxMobileConcurrency !== undefined) {
  301. this.maxMobileConcurrency = props.maxMobileConcurrency;
  302. }
  303. if (props.reuseWorkers !== undefined) {
  304. this.reuseWorkers = props.reuseWorkers;
  305. }
  306. if (props.onDebug !== undefined) {
  307. this.onDebug = props.onDebug;
  308. }
  309. }
  310. async startJob(name, onMessage = (job, type, data) => job.done(data), onError = (job, error) => job.error(error)) {
  311. const startPromise = new Promise(onStart => {
  312. this.jobQueue.push({
  313. name,
  314. onMessage,
  315. onError,
  316. onStart
  317. });
  318. return this;
  319. });
  320. this._startQueuedJob();
  321. return await startPromise;
  322. }
  323. async _startQueuedJob() {
  324. if (!this.jobQueue.length) {
  325. return;
  326. }
  327. const workerThread = this._getAvailableWorker();
  328. if (!workerThread) {
  329. return;
  330. }
  331. const queuedJob = this.jobQueue.shift();
  332. if (queuedJob) {
  333. this.onDebug({
  334. message: 'Starting job',
  335. name: queuedJob.name,
  336. workerThread,
  337. backlog: this.jobQueue.length
  338. });
  339. const job = new WorkerJob(queuedJob.name, workerThread);
  340. workerThread.onMessage = data => queuedJob.onMessage(job, data.type, data.payload);
  341. workerThread.onError = error => queuedJob.onError(job, error);
  342. queuedJob.onStart(job);
  343. try {
  344. await job.result;
  345. } finally {
  346. this.returnWorkerToQueue(workerThread);
  347. }
  348. }
  349. }
  350. returnWorkerToQueue(worker) {
  351. const shouldDestroyWorker = this.isDestroyed || !this.reuseWorkers || this.count > this._getMaxConcurrency();
  352. if (shouldDestroyWorker) {
  353. worker.destroy();
  354. this.count--;
  355. } else {
  356. this.idleQueue.push(worker);
  357. }
  358. if (!this.isDestroyed) {
  359. this._startQueuedJob();
  360. }
  361. }
  362. _getAvailableWorker() {
  363. if (this.idleQueue.length > 0) {
  364. return this.idleQueue.shift() || null;
  365. }
  366. if (this.count < this._getMaxConcurrency()) {
  367. this.count++;
  368. const name = "".concat(this.name.toLowerCase(), " (#").concat(this.count, " of ").concat(this.maxConcurrency, ")");
  369. return new WorkerThread({
  370. name,
  371. source: this.source,
  372. url: this.url
  373. });
  374. }
  375. return null;
  376. }
  377. _getMaxConcurrency() {
  378. return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
  379. }
  380. }
  381. const DEFAULT_PROPS$3 = {
  382. maxConcurrency: 3,
  383. maxMobileConcurrency: 1,
  384. onDebug: () => {},
  385. reuseWorkers: true
  386. };
  387. class WorkerFarm {
  388. static isSupported() {
  389. return WorkerThread.isSupported();
  390. }
  391. static getWorkerFarm(props = {}) {
  392. WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});
  393. WorkerFarm._workerFarm.setProps(props);
  394. return WorkerFarm._workerFarm;
  395. }
  396. constructor(props) {
  397. _defineProperty(this, "props", void 0);
  398. _defineProperty(this, "workerPools", new Map());
  399. this.props = { ...DEFAULT_PROPS$3
  400. };
  401. this.setProps(props);
  402. this.workerPools = new Map();
  403. }
  404. destroy() {
  405. for (const workerPool of this.workerPools.values()) {
  406. workerPool.destroy();
  407. }
  408. }
  409. setProps(props) {
  410. this.props = { ...this.props,
  411. ...props
  412. };
  413. for (const workerPool of this.workerPools.values()) {
  414. workerPool.setProps(this._getWorkerPoolProps());
  415. }
  416. }
  417. getWorkerPool(options) {
  418. const {
  419. name,
  420. source,
  421. url
  422. } = options;
  423. let workerPool = this.workerPools.get(name);
  424. if (!workerPool) {
  425. workerPool = new WorkerPool({
  426. name,
  427. source,
  428. url
  429. });
  430. workerPool.setProps(this._getWorkerPoolProps());
  431. this.workerPools.set(name, workerPool);
  432. }
  433. return workerPool;
  434. }
  435. _getWorkerPoolProps() {
  436. return {
  437. maxConcurrency: this.props.maxConcurrency,
  438. maxMobileConcurrency: this.props.maxMobileConcurrency,
  439. reuseWorkers: this.props.reuseWorkers,
  440. onDebug: this.props.onDebug
  441. };
  442. }
  443. }
  444. _defineProperty(WorkerFarm, "_workerFarm", void 0);
  445. const NPM_TAG = 'latest';
  446. function getWorkerURL(worker, options = {}) {
  447. const workerOptions = options[worker.id] || {};
  448. const workerFile = "".concat(worker.id, "-worker.js");
  449. let url = workerOptions.workerUrl;
  450. if (!url && worker.id === 'compression') {
  451. url = options.workerUrl;
  452. }
  453. if (options._workerType === 'test') {
  454. url = "modules/".concat(worker.module, "/dist/").concat(workerFile);
  455. }
  456. if (!url) {
  457. let version = worker.version;
  458. if (version === 'latest') {
  459. version = NPM_TAG;
  460. }
  461. const versionTag = version ? "@".concat(version) : '';
  462. url = "https://unpkg.com/@loaders.gl/".concat(worker.module).concat(versionTag, "/dist/").concat(workerFile);
  463. }
  464. assert$6(url);
  465. return url;
  466. }
  467. function validateWorkerVersion(worker, coreVersion = VERSION$8) {
  468. assert$6(worker, 'no worker provided');
  469. const workerVersion = worker.version;
  470. if (!coreVersion || !workerVersion) {
  471. return false;
  472. }
  473. return true;
  474. }
  475. var ChildProcessProxy = {};
  476. var node = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), ChildProcessProxy, {
  477. 'default': ChildProcessProxy
  478. }));
  479. const VERSION$7 = "3.1.4" ;
  480. const loadLibraryPromises = {};
  481. async function loadLibrary(libraryUrl, moduleName = null, options = {}) {
  482. if (moduleName) {
  483. libraryUrl = getLibraryUrl(libraryUrl, moduleName, options);
  484. }
  485. loadLibraryPromises[libraryUrl] = loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
  486. return await loadLibraryPromises[libraryUrl];
  487. }
  488. function getLibraryUrl(library, moduleName, options) {
  489. if (library.startsWith('http')) {
  490. return library;
  491. }
  492. const modules = options.modules || {};
  493. if (modules[library]) {
  494. return modules[library];
  495. }
  496. if (!isBrowser$1) {
  497. return "modules/".concat(moduleName, "/dist/libs/").concat(library);
  498. }
  499. if (options.CDN) {
  500. assert$6(options.CDN.startsWith('http'));
  501. return "".concat(options.CDN, "/").concat(moduleName, "@").concat(VERSION$7, "/dist/libs/").concat(library);
  502. }
  503. if (isWorker) {
  504. return "../src/libs/".concat(library);
  505. }
  506. return "modules/".concat(moduleName, "/src/libs/").concat(library);
  507. }
  508. async function loadLibraryFromFile(libraryUrl) {
  509. if (libraryUrl.endsWith('wasm')) {
  510. const response = await fetch(libraryUrl);
  511. return await response.arrayBuffer();
  512. }
  513. if (!isBrowser$1) {
  514. try {
  515. return node && ChildProcessProxy.requireFromFile && (await ChildProcessProxy.requireFromFile(libraryUrl));
  516. } catch {
  517. return null;
  518. }
  519. }
  520. if (isWorker) {
  521. return importScripts(libraryUrl);
  522. }
  523. const response = await fetch(libraryUrl);
  524. const scriptSource = await response.text();
  525. return loadLibraryFromString(scriptSource, libraryUrl);
  526. }
  527. function loadLibraryFromString(scriptSource, id) {
  528. if (!isBrowser$1) {
  529. return ChildProcessProxy.requireFromString && ChildProcessProxy.requireFromString(scriptSource, id);
  530. }
  531. if (isWorker) {
  532. eval.call(global_, scriptSource);
  533. return null;
  534. }
  535. const script = document.createElement('script');
  536. script.id = id;
  537. try {
  538. script.appendChild(document.createTextNode(scriptSource));
  539. } catch (e) {
  540. script.text = scriptSource;
  541. }
  542. document.body.appendChild(script);
  543. return null;
  544. }
  545. function canParseWithWorker(loader, options) {
  546. if (!WorkerFarm.isSupported()) {
  547. return false;
  548. }
  549. return loader.worker && (options === null || options === void 0 ? void 0 : options.worker);
  550. }
  551. async function parseWithWorker(loader, data, options, context, parseOnMainThread) {
  552. const name = loader.id;
  553. const url = getWorkerURL(loader, options);
  554. const workerFarm = WorkerFarm.getWorkerFarm(options);
  555. const workerPool = workerFarm.getWorkerPool({
  556. name,
  557. url
  558. });
  559. options = JSON.parse(JSON.stringify(options));
  560. const job = await workerPool.startJob('process-on-worker', onMessage.bind(null, parseOnMainThread));
  561. job.postMessage('process', {
  562. input: data,
  563. options
  564. });
  565. const result = await job.result;
  566. return await result.result;
  567. }
  568. async function onMessage(parseOnMainThread, job, type, payload) {
  569. switch (type) {
  570. case 'done':
  571. job.done(payload);
  572. break;
  573. case 'error':
  574. job.error(new Error(payload.error));
  575. break;
  576. case 'process':
  577. const {
  578. id,
  579. input,
  580. options
  581. } = payload;
  582. try {
  583. const result = await parseOnMainThread(input, options);
  584. job.postMessage('done', {
  585. id,
  586. result
  587. });
  588. } catch (error) {
  589. const message = error instanceof Error ? error.message : 'unknown error';
  590. job.postMessage('error', {
  591. id,
  592. error: message
  593. });
  594. }
  595. break;
  596. default:
  597. console.warn("parse-with-worker unknown message ".concat(type));
  598. }
  599. }
  600. function getFirstCharacters$1(data, length = 5) {
  601. if (typeof data === 'string') {
  602. return data.slice(0, length);
  603. } else if (ArrayBuffer.isView(data)) {
  604. return getMagicString$3(data.buffer, data.byteOffset, length);
  605. } else if (data instanceof ArrayBuffer) {
  606. const byteOffset = 0;
  607. return getMagicString$3(data, byteOffset, length);
  608. }
  609. return '';
  610. }
  611. function getMagicString$3(arrayBuffer, byteOffset, length) {
  612. if (arrayBuffer.byteLength <= byteOffset + length) {
  613. return '';
  614. }
  615. const dataView = new DataView(arrayBuffer);
  616. let magic = '';
  617. for (let i = 0; i < length; i++) {
  618. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  619. }
  620. return magic;
  621. }
  622. function parseJSON(string) {
  623. try {
  624. return JSON.parse(string);
  625. } catch (_) {
  626. throw new Error("Failed to parse JSON from data starting with \"".concat(getFirstCharacters$1(string), "\""));
  627. }
  628. }
  629. function isBuffer$1(value) {
  630. return value && typeof value === 'object' && value.isBuffer;
  631. }
  632. function bufferToArrayBuffer(buffer) {
  633. if (isBuffer$1(buffer)) {
  634. const typedArray = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.length);
  635. return typedArray.slice().buffer;
  636. }
  637. return buffer;
  638. }
  639. function toArrayBuffer(data) {
  640. if (isBuffer$1(data)) {
  641. return bufferToArrayBuffer(data);
  642. }
  643. if (data instanceof ArrayBuffer) {
  644. return data;
  645. }
  646. if (ArrayBuffer.isView(data)) {
  647. if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
  648. return data.buffer;
  649. }
  650. return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
  651. }
  652. if (typeof data === 'string') {
  653. const text = data;
  654. const uint8Array = new TextEncoder().encode(text);
  655. return uint8Array.buffer;
  656. }
  657. if (data && typeof data === 'object' && data._toArrayBuffer) {
  658. return data._toArrayBuffer();
  659. }
  660. throw new Error('toArrayBuffer');
  661. }
  662. function compareArrayBuffers(arrayBuffer1, arrayBuffer2, byteLength) {
  663. byteLength = byteLength || arrayBuffer1.byteLength;
  664. if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {
  665. return false;
  666. }
  667. const array1 = new Uint8Array(arrayBuffer1);
  668. const array2 = new Uint8Array(arrayBuffer2);
  669. for (let i = 0; i < array1.length; ++i) {
  670. if (array1[i] !== array2[i]) {
  671. return false;
  672. }
  673. }
  674. return true;
  675. }
  676. function concatenateArrayBuffers(...sources) {
  677. const sourceArrays = sources.map(source2 => source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2);
  678. const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);
  679. const result = new Uint8Array(byteLength);
  680. let offset = 0;
  681. for (const sourceArray of sourceArrays) {
  682. result.set(sourceArray, offset);
  683. offset += sourceArray.byteLength;
  684. }
  685. return result.buffer;
  686. }
  687. function sliceArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  688. const subArray = byteLength !== undefined ? new Uint8Array(arrayBuffer).subarray(byteOffset, byteOffset + byteLength) : new Uint8Array(arrayBuffer).subarray(byteOffset);
  689. const arrayCopy = new Uint8Array(subArray);
  690. return arrayCopy.buffer;
  691. }
  692. function padToNBytes(byteLength, padding) {
  693. assert$7(byteLength >= 0);
  694. assert$7(padding > 0);
  695. return byteLength + (padding - 1) & ~(padding - 1);
  696. }
  697. function copyToArray(source, target, targetOffset) {
  698. let sourceArray;
  699. if (source instanceof ArrayBuffer) {
  700. sourceArray = new Uint8Array(source);
  701. } else {
  702. const srcByteOffset = source.byteOffset;
  703. const srcByteLength = source.byteLength;
  704. sourceArray = new Uint8Array(source.buffer || source.arrayBuffer, srcByteOffset, srcByteLength);
  705. }
  706. target.set(sourceArray, targetOffset);
  707. return targetOffset + padToNBytes(sourceArray.byteLength, 4);
  708. }
  709. async function concatenateArrayBuffersAsync(asyncIterator) {
  710. const arrayBuffers = [];
  711. for await (const chunk of asyncIterator) {
  712. arrayBuffers.push(chunk);
  713. }
  714. return concatenateArrayBuffers(...arrayBuffers);
  715. }
  716. function getHiResTimestamp$1() {
  717. let timestamp;
  718. if (typeof window !== 'undefined' && window.performance) {
  719. timestamp = window.performance.now();
  720. } else if (typeof process !== 'undefined' && process.hrtime) {
  721. const timeParts = process.hrtime();
  722. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  723. } else {
  724. timestamp = Date.now();
  725. }
  726. return timestamp;
  727. }
  728. class Stat {
  729. constructor(name, type) {
  730. _defineProperty(this, "name", void 0);
  731. _defineProperty(this, "type", void 0);
  732. _defineProperty(this, "sampleSize", 1);
  733. _defineProperty(this, "time", void 0);
  734. _defineProperty(this, "count", void 0);
  735. _defineProperty(this, "samples", void 0);
  736. _defineProperty(this, "lastTiming", void 0);
  737. _defineProperty(this, "lastSampleTime", void 0);
  738. _defineProperty(this, "lastSampleCount", void 0);
  739. _defineProperty(this, "_count", 0);
  740. _defineProperty(this, "_time", 0);
  741. _defineProperty(this, "_samples", 0);
  742. _defineProperty(this, "_startTime", 0);
  743. _defineProperty(this, "_timerPending", false);
  744. this.name = name;
  745. this.type = type;
  746. this.reset();
  747. }
  748. setSampleSize(samples) {
  749. this.sampleSize = samples;
  750. return this;
  751. }
  752. incrementCount() {
  753. this.addCount(1);
  754. return this;
  755. }
  756. decrementCount() {
  757. this.subtractCount(1);
  758. return this;
  759. }
  760. addCount(value) {
  761. this._count += value;
  762. this._samples++;
  763. this._checkSampling();
  764. return this;
  765. }
  766. subtractCount(value) {
  767. this._count -= value;
  768. this._samples++;
  769. this._checkSampling();
  770. return this;
  771. }
  772. addTime(time) {
  773. this._time += time;
  774. this.lastTiming = time;
  775. this._samples++;
  776. this._checkSampling();
  777. return this;
  778. }
  779. timeStart() {
  780. this._startTime = getHiResTimestamp$1();
  781. this._timerPending = true;
  782. return this;
  783. }
  784. timeEnd() {
  785. if (!this._timerPending) {
  786. return this;
  787. }
  788. this.addTime(getHiResTimestamp$1() - this._startTime);
  789. this._timerPending = false;
  790. this._checkSampling();
  791. return this;
  792. }
  793. getSampleAverageCount() {
  794. return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;
  795. }
  796. getSampleAverageTime() {
  797. return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;
  798. }
  799. getSampleHz() {
  800. return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1000) : 0;
  801. }
  802. getAverageCount() {
  803. return this.samples > 0 ? this.count / this.samples : 0;
  804. }
  805. getAverageTime() {
  806. return this.samples > 0 ? this.time / this.samples : 0;
  807. }
  808. getHz() {
  809. return this.time > 0 ? this.samples / (this.time / 1000) : 0;
  810. }
  811. reset() {
  812. this.time = 0;
  813. this.count = 0;
  814. this.samples = 0;
  815. this.lastTiming = 0;
  816. this.lastSampleTime = 0;
  817. this.lastSampleCount = 0;
  818. this._count = 0;
  819. this._time = 0;
  820. this._samples = 0;
  821. this._startTime = 0;
  822. this._timerPending = false;
  823. return this;
  824. }
  825. _checkSampling() {
  826. if (this._samples === this.sampleSize) {
  827. this.lastSampleTime = this._time;
  828. this.lastSampleCount = this._count;
  829. this.count += this._count;
  830. this.time += this._time;
  831. this.samples += this._samples;
  832. this._time = 0;
  833. this._count = 0;
  834. this._samples = 0;
  835. }
  836. }
  837. }
  838. class Stats {
  839. constructor(options) {
  840. _defineProperty(this, "id", void 0);
  841. _defineProperty(this, "stats", {});
  842. this.id = options.id;
  843. this.stats = {};
  844. this._initializeStats(options.stats);
  845. Object.seal(this);
  846. }
  847. get(name) {
  848. let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'count';
  849. return this._getOrCreate({
  850. name,
  851. type
  852. });
  853. }
  854. get size() {
  855. return Object.keys(this.stats).length;
  856. }
  857. reset() {
  858. for (const key in this.stats) {
  859. this.stats[key].reset();
  860. }
  861. return this;
  862. }
  863. forEach(fn) {
  864. for (const key in this.stats) {
  865. fn(this.stats[key]);
  866. }
  867. }
  868. getTable() {
  869. const table = {};
  870. this.forEach(stat => {
  871. table[stat.name] = {
  872. time: stat.time || 0,
  873. count: stat.count || 0,
  874. average: stat.getAverageTime() || 0,
  875. hz: stat.getHz() || 0
  876. };
  877. });
  878. return table;
  879. }
  880. _initializeStats() {
  881. let stats = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  882. stats.forEach(stat => this._getOrCreate(stat));
  883. }
  884. _getOrCreate(stat) {
  885. if (!stat || !stat.name) {
  886. return null;
  887. }
  888. const {
  889. name,
  890. type
  891. } = stat;
  892. if (!this.stats[name]) {
  893. if (stat instanceof Stat) {
  894. this.stats[name] = stat;
  895. } else {
  896. this.stats[name] = new Stat(name, type);
  897. }
  898. }
  899. return this.stats[name];
  900. }
  901. }
  902. const STAT_QUEUED_REQUESTS = 'Queued Requests';
  903. const STAT_ACTIVE_REQUESTS = 'Active Requests';
  904. const STAT_CANCELLED_REQUESTS = 'Cancelled Requests';
  905. const STAT_QUEUED_REQUESTS_EVER = 'Queued Requests Ever';
  906. const STAT_ACTIVE_REQUESTS_EVER = 'Active Requests Ever';
  907. const DEFAULT_PROPS$2 = {
  908. id: 'request-scheduler',
  909. throttleRequests: true,
  910. maxRequests: 6
  911. };
  912. class RequestScheduler {
  913. constructor(props = {}) {
  914. _defineProperty(this, "props", void 0);
  915. _defineProperty(this, "stats", void 0);
  916. _defineProperty(this, "activeRequestCount", 0);
  917. _defineProperty(this, "requestQueue", []);
  918. _defineProperty(this, "requestMap", new Map());
  919. _defineProperty(this, "deferredUpdate", null);
  920. this.props = { ...DEFAULT_PROPS$2,
  921. ...props
  922. };
  923. this.stats = new Stats({
  924. id: this.props.id
  925. });
  926. this.stats.get(STAT_QUEUED_REQUESTS);
  927. this.stats.get(STAT_ACTIVE_REQUESTS);
  928. this.stats.get(STAT_CANCELLED_REQUESTS);
  929. this.stats.get(STAT_QUEUED_REQUESTS_EVER);
  930. this.stats.get(STAT_ACTIVE_REQUESTS_EVER);
  931. }
  932. scheduleRequest(handle, getPriority = () => 0) {
  933. if (!this.props.throttleRequests) {
  934. return Promise.resolve({
  935. done: () => {}
  936. });
  937. }
  938. if (this.requestMap.has(handle)) {
  939. return this.requestMap.get(handle);
  940. }
  941. const request = {
  942. handle,
  943. priority: 0,
  944. getPriority
  945. };
  946. const promise = new Promise(resolve => {
  947. request.resolve = resolve;
  948. return request;
  949. });
  950. this.requestQueue.push(request);
  951. this.requestMap.set(handle, promise);
  952. this._issueNewRequests();
  953. return promise;
  954. }
  955. _issueRequest(request) {
  956. const {
  957. handle,
  958. resolve
  959. } = request;
  960. let isDone = false;
  961. const done = () => {
  962. if (!isDone) {
  963. isDone = true;
  964. this.requestMap.delete(handle);
  965. this.activeRequestCount--;
  966. this._issueNewRequests();
  967. }
  968. };
  969. this.activeRequestCount++;
  970. return resolve ? resolve({
  971. done
  972. }) : Promise.resolve({
  973. done
  974. });
  975. }
  976. _issueNewRequests() {
  977. if (!this.deferredUpdate) {
  978. this.deferredUpdate = setTimeout(() => this._issueNewRequestsAsync(), 0);
  979. }
  980. }
  981. _issueNewRequestsAsync() {
  982. this.deferredUpdate = null;
  983. const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);
  984. if (freeSlots === 0) {
  985. return;
  986. }
  987. this._updateAllRequests();
  988. for (let i = 0; i < freeSlots; ++i) {
  989. const request = this.requestQueue.shift();
  990. if (request) {
  991. this._issueRequest(request);
  992. }
  993. }
  994. }
  995. _updateAllRequests() {
  996. const requestQueue = this.requestQueue;
  997. for (let i = 0; i < requestQueue.length; ++i) {
  998. const request = requestQueue[i];
  999. if (!this._updateRequest(request)) {
  1000. requestQueue.splice(i, 1);
  1001. this.requestMap.delete(request.handle);
  1002. i--;
  1003. }
  1004. }
  1005. requestQueue.sort((a, b) => a.priority - b.priority);
  1006. }
  1007. _updateRequest(request) {
  1008. request.priority = request.getPriority(request.handle);
  1009. if (request.priority < 0) {
  1010. request.resolve(null);
  1011. return false;
  1012. }
  1013. return true;
  1014. }
  1015. }
  1016. let pathPrefix = '';
  1017. const fileAliases = {};
  1018. function resolvePath(filename) {
  1019. for (const alias in fileAliases) {
  1020. if (filename.startsWith(alias)) {
  1021. const replacement = fileAliases[alias];
  1022. filename = filename.replace(alias, replacement);
  1023. }
  1024. }
  1025. if (!filename.startsWith('http://') && !filename.startsWith('https://')) {
  1026. filename = "".concat(pathPrefix).concat(filename);
  1027. }
  1028. return filename;
  1029. }
  1030. function filename(url) {
  1031. const slashIndex = url && url.lastIndexOf('/');
  1032. return slashIndex >= 0 ? url.substr(slashIndex + 1) : '';
  1033. }
  1034. function dirname(url) {
  1035. const slashIndex = url && url.lastIndexOf('/');
  1036. return slashIndex >= 0 ? url.substr(0, slashIndex) : '';
  1037. }
  1038. const isBoolean = x => typeof x === 'boolean';
  1039. const isFunction = x => typeof x === 'function';
  1040. const isObject = x => x !== null && typeof x === 'object';
  1041. const isPureObject = x => isObject(x) && x.constructor === {}.constructor;
  1042. const isIterable = x => x && typeof x[Symbol.iterator] === 'function';
  1043. const isAsyncIterable = x => x && typeof x[Symbol.asyncIterator] === 'function';
  1044. const isResponse = x => typeof Response !== 'undefined' && x instanceof Response || x && x.arrayBuffer && x.text && x.json;
  1045. const isBlob = x => typeof Blob !== 'undefined' && x instanceof Blob;
  1046. const isBuffer = x => x && typeof x === 'object' && x.isBuffer;
  1047. const isReadableDOMStream = x => typeof ReadableStream !== 'undefined' && x instanceof ReadableStream || isObject(x) && isFunction(x.tee) && isFunction(x.cancel) && isFunction(x.getReader);
  1048. const isReadableNodeStream = x => isObject(x) && isFunction(x.read) && isFunction(x.pipe) && isBoolean(x.readable);
  1049. const isReadableStream = x => isReadableDOMStream(x) || isReadableNodeStream(x);
  1050. const DATA_URL_PATTERN = /^data:([-\w.]+\/[-\w.+]+)(;|,)/;
  1051. const MIME_TYPE_PATTERN = /^([-\w.]+\/[-\w.+]+)/;
  1052. function parseMIMEType(mimeString) {
  1053. const matches = MIME_TYPE_PATTERN.exec(mimeString);
  1054. if (matches) {
  1055. return matches[1];
  1056. }
  1057. return mimeString;
  1058. }
  1059. function parseMIMETypeFromURL(url) {
  1060. const matches = DATA_URL_PATTERN.exec(url);
  1061. if (matches) {
  1062. return matches[1];
  1063. }
  1064. return '';
  1065. }
  1066. const QUERY_STRING_PATTERN = /\?.*/;
  1067. function getResourceUrlAndType(resource) {
  1068. if (isResponse(resource)) {
  1069. const url = stripQueryString(resource.url || '');
  1070. const contentTypeHeader = resource.headers.get('content-type') || '';
  1071. return {
  1072. url,
  1073. type: parseMIMEType(contentTypeHeader) || parseMIMETypeFromURL(url)
  1074. };
  1075. }
  1076. if (isBlob(resource)) {
  1077. return {
  1078. url: stripQueryString(resource.name || ''),
  1079. type: resource.type || ''
  1080. };
  1081. }
  1082. if (typeof resource === 'string') {
  1083. return {
  1084. url: stripQueryString(resource),
  1085. type: parseMIMETypeFromURL(resource)
  1086. };
  1087. }
  1088. return {
  1089. url: '',
  1090. type: ''
  1091. };
  1092. }
  1093. function getResourceContentLength(resource) {
  1094. if (isResponse(resource)) {
  1095. return resource.headers['content-length'] || -1;
  1096. }
  1097. if (isBlob(resource)) {
  1098. return resource.size;
  1099. }
  1100. if (typeof resource === 'string') {
  1101. return resource.length;
  1102. }
  1103. if (resource instanceof ArrayBuffer) {
  1104. return resource.byteLength;
  1105. }
  1106. if (ArrayBuffer.isView(resource)) {
  1107. return resource.byteLength;
  1108. }
  1109. return -1;
  1110. }
  1111. function stripQueryString(url) {
  1112. return url.replace(QUERY_STRING_PATTERN, '');
  1113. }
  1114. async function makeResponse(resource) {
  1115. if (isResponse(resource)) {
  1116. return resource;
  1117. }
  1118. const headers = {};
  1119. const contentLength = getResourceContentLength(resource);
  1120. if (contentLength >= 0) {
  1121. headers['content-length'] = String(contentLength);
  1122. }
  1123. const {
  1124. url,
  1125. type
  1126. } = getResourceUrlAndType(resource);
  1127. if (type) {
  1128. headers['content-type'] = type;
  1129. }
  1130. const initialDataUrl = await getInitialDataUrl(resource);
  1131. if (initialDataUrl) {
  1132. headers['x-first-bytes'] = initialDataUrl;
  1133. }
  1134. if (typeof resource === 'string') {
  1135. resource = new TextEncoder().encode(resource);
  1136. }
  1137. const response = new Response(resource, {
  1138. headers
  1139. });
  1140. Object.defineProperty(response, 'url', {
  1141. value: url
  1142. });
  1143. return response;
  1144. }
  1145. async function checkResponse(response) {
  1146. if (!response.ok) {
  1147. const message = await getResponseError(response);
  1148. throw new Error(message);
  1149. }
  1150. }
  1151. async function getResponseError(response) {
  1152. let message = "Failed to fetch resource ".concat(response.url, " (").concat(response.status, "): ");
  1153. try {
  1154. const contentType = response.headers.get('Content-Type');
  1155. let text = response.statusText;
  1156. if (contentType.includes('application/json')) {
  1157. text += " ".concat(await response.text());
  1158. }
  1159. message += text;
  1160. message = message.length > 60 ? "".concat(message.slice(60), "...") : message;
  1161. } catch (error) {}
  1162. return message;
  1163. }
  1164. async function getInitialDataUrl(resource) {
  1165. const INITIAL_DATA_LENGTH = 5;
  1166. if (typeof resource === 'string') {
  1167. return "data:,".concat(resource.slice(0, INITIAL_DATA_LENGTH));
  1168. }
  1169. if (resource instanceof Blob) {
  1170. const blobSlice = resource.slice(0, 5);
  1171. return await new Promise(resolve => {
  1172. const reader = new FileReader();
  1173. reader.onload = event => {
  1174. var _event$target;
  1175. return resolve(event === null || event === void 0 ? void 0 : (_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.result);
  1176. };
  1177. reader.readAsDataURL(blobSlice);
  1178. });
  1179. }
  1180. if (resource instanceof ArrayBuffer) {
  1181. const slice = resource.slice(0, INITIAL_DATA_LENGTH);
  1182. const base64 = arrayBufferToBase64(slice);
  1183. return "data:base64,".concat(base64);
  1184. }
  1185. return null;
  1186. }
  1187. function arrayBufferToBase64(buffer) {
  1188. let binary = '';
  1189. const bytes = new Uint8Array(buffer);
  1190. for (let i = 0; i < bytes.byteLength; i++) {
  1191. binary += String.fromCharCode(bytes[i]);
  1192. }
  1193. return btoa(binary);
  1194. }
  1195. async function fetchFile(url, options) {
  1196. if (typeof url === 'string') {
  1197. url = resolvePath(url);
  1198. let fetchOptions = options;
  1199. if (options !== null && options !== void 0 && options.fetch && typeof (options === null || options === void 0 ? void 0 : options.fetch) !== 'function') {
  1200. fetchOptions = options.fetch;
  1201. }
  1202. return await fetch(url, fetchOptions);
  1203. }
  1204. return await makeResponse(url);
  1205. }
  1206. function isElectron(mockUserAgent) {
  1207. if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {
  1208. return true;
  1209. }
  1210. if (typeof process !== 'undefined' && typeof process.versions === 'object' && Boolean(process.versions.electron)) {
  1211. return true;
  1212. }
  1213. const realUserAgent = typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent;
  1214. const userAgent = mockUserAgent || realUserAgent;
  1215. if (userAgent && userAgent.indexOf('Electron') >= 0) {
  1216. return true;
  1217. }
  1218. return false;
  1219. }
  1220. function isBrowser() {
  1221. const isNode = typeof process === 'object' && String(process) === '[object process]' && !process.browser;
  1222. return !isNode || isElectron();
  1223. }
  1224. const globals = {
  1225. self: typeof self !== 'undefined' && self,
  1226. window: typeof window !== 'undefined' && window,
  1227. global: typeof global !== 'undefined' && global,
  1228. document: typeof document !== 'undefined' && document,
  1229. process: typeof process === 'object' && process
  1230. };
  1231. const window_ = globals.window || globals.self || globals.global;
  1232. const process_ = globals.process || {};
  1233. const VERSION$6 = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'untranspiled source';
  1234. isBrowser();
  1235. function getStorage(type) {
  1236. try {
  1237. const storage = window[type];
  1238. const x = '__storage_test__';
  1239. storage.setItem(x, x);
  1240. storage.removeItem(x);
  1241. return storage;
  1242. } catch (e) {
  1243. return null;
  1244. }
  1245. }
  1246. class LocalStorage {
  1247. constructor(id) {
  1248. let defaultSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1249. let type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'sessionStorage';
  1250. _defineProperty(this, "storage", void 0);
  1251. _defineProperty(this, "id", void 0);
  1252. _defineProperty(this, "config", {});
  1253. this.storage = getStorage(type);
  1254. this.id = id;
  1255. this.config = {};
  1256. Object.assign(this.config, defaultSettings);
  1257. this._loadConfiguration();
  1258. }
  1259. getConfiguration() {
  1260. return this.config;
  1261. }
  1262. setConfiguration(configuration) {
  1263. this.config = {};
  1264. return this.updateConfiguration(configuration);
  1265. }
  1266. updateConfiguration(configuration) {
  1267. Object.assign(this.config, configuration);
  1268. if (this.storage) {
  1269. const serialized = JSON.stringify(this.config);
  1270. this.storage.setItem(this.id, serialized);
  1271. }
  1272. return this;
  1273. }
  1274. _loadConfiguration() {
  1275. let configuration = {};
  1276. if (this.storage) {
  1277. const serializedConfiguration = this.storage.getItem(this.id);
  1278. configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {};
  1279. }
  1280. Object.assign(this.config, configuration);
  1281. return this;
  1282. }
  1283. }
  1284. function formatTime(ms) {
  1285. let formatted;
  1286. if (ms < 10) {
  1287. formatted = "".concat(ms.toFixed(2), "ms");
  1288. } else if (ms < 100) {
  1289. formatted = "".concat(ms.toFixed(1), "ms");
  1290. } else if (ms < 1000) {
  1291. formatted = "".concat(ms.toFixed(0), "ms");
  1292. } else {
  1293. formatted = "".concat((ms / 1000).toFixed(2), "s");
  1294. }
  1295. return formatted;
  1296. }
  1297. function leftPad(string) {
  1298. let length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 8;
  1299. const padLength = Math.max(length - string.length, 0);
  1300. return "".concat(' '.repeat(padLength)).concat(string);
  1301. }
  1302. function formatImage(image, message, scale) {
  1303. let maxWidth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 600;
  1304. const imageUrl = image.src.replace(/\(/g, '%28').replace(/\)/g, '%29');
  1305. if (image.width > maxWidth) {
  1306. scale = Math.min(scale, maxWidth / image.width);
  1307. }
  1308. const width = image.width * scale;
  1309. const height = image.height * scale;
  1310. 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('');
  1311. return ["".concat(message, " %c+"), style];
  1312. }
  1313. let COLOR;
  1314. (function (COLOR) {
  1315. COLOR[COLOR["BLACK"] = 30] = "BLACK";
  1316. COLOR[COLOR["RED"] = 31] = "RED";
  1317. COLOR[COLOR["GREEN"] = 32] = "GREEN";
  1318. COLOR[COLOR["YELLOW"] = 33] = "YELLOW";
  1319. COLOR[COLOR["BLUE"] = 34] = "BLUE";
  1320. COLOR[COLOR["MAGENTA"] = 35] = "MAGENTA";
  1321. COLOR[COLOR["CYAN"] = 36] = "CYAN";
  1322. COLOR[COLOR["WHITE"] = 37] = "WHITE";
  1323. COLOR[COLOR["BRIGHT_BLACK"] = 90] = "BRIGHT_BLACK";
  1324. COLOR[COLOR["BRIGHT_RED"] = 91] = "BRIGHT_RED";
  1325. COLOR[COLOR["BRIGHT_GREEN"] = 92] = "BRIGHT_GREEN";
  1326. COLOR[COLOR["BRIGHT_YELLOW"] = 93] = "BRIGHT_YELLOW";
  1327. COLOR[COLOR["BRIGHT_BLUE"] = 94] = "BRIGHT_BLUE";
  1328. COLOR[COLOR["BRIGHT_MAGENTA"] = 95] = "BRIGHT_MAGENTA";
  1329. COLOR[COLOR["BRIGHT_CYAN"] = 96] = "BRIGHT_CYAN";
  1330. COLOR[COLOR["BRIGHT_WHITE"] = 97] = "BRIGHT_WHITE";
  1331. })(COLOR || (COLOR = {}));
  1332. function getColor(color) {
  1333. return typeof color === 'string' ? COLOR[color.toUpperCase()] || COLOR.WHITE : color;
  1334. }
  1335. function addColor(string, color, background) {
  1336. if (!isBrowser && typeof string === 'string') {
  1337. if (color) {
  1338. color = getColor(color);
  1339. string = "\x1B[".concat(color, "m").concat(string, "\x1B[39m");
  1340. }
  1341. if (background) {
  1342. color = getColor(background);
  1343. string = "\x1B[".concat(background + 10, "m").concat(string, "\x1B[49m");
  1344. }
  1345. }
  1346. return string;
  1347. }
  1348. function autobind(obj) {
  1349. let predefined = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ['constructor'];
  1350. const proto = Object.getPrototypeOf(obj);
  1351. const propNames = Object.getOwnPropertyNames(proto);
  1352. for (const key of propNames) {
  1353. if (typeof obj[key] === 'function') {
  1354. if (!predefined.find(name => key === name)) {
  1355. obj[key] = obj[key].bind(obj);
  1356. }
  1357. }
  1358. }
  1359. }
  1360. function assert$5(condition, message) {
  1361. if (!condition) {
  1362. throw new Error(message || 'Assertion failed');
  1363. }
  1364. }
  1365. function getHiResTimestamp() {
  1366. let timestamp;
  1367. if (isBrowser && 'performance' in window_) {
  1368. var _window$performance, _window$performance$n;
  1369. 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);
  1370. } else if ('hrtime' in process_) {
  1371. var _process$hrtime;
  1372. const timeParts = process_ === null || process_ === void 0 ? void 0 : (_process$hrtime = process_.hrtime) === null || _process$hrtime === void 0 ? void 0 : _process$hrtime.call(process_);
  1373. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  1374. } else {
  1375. timestamp = Date.now();
  1376. }
  1377. return timestamp;
  1378. }
  1379. const originalConsole = {
  1380. debug: isBrowser ? console.debug || console.log : console.log,
  1381. log: console.log,
  1382. info: console.info,
  1383. warn: console.warn,
  1384. error: console.error
  1385. };
  1386. const DEFAULT_SETTINGS = {
  1387. enabled: true,
  1388. level: 0
  1389. };
  1390. function noop$1() {}
  1391. const cache = {};
  1392. const ONCE = {
  1393. once: true
  1394. };
  1395. class Log {
  1396. constructor() {
  1397. let {
  1398. id
  1399. } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
  1400. id: ''
  1401. };
  1402. _defineProperty(this, "id", void 0);
  1403. _defineProperty(this, "VERSION", VERSION$6);
  1404. _defineProperty(this, "_startTs", getHiResTimestamp());
  1405. _defineProperty(this, "_deltaTs", getHiResTimestamp());
  1406. _defineProperty(this, "_storage", void 0);
  1407. _defineProperty(this, "userData", {});
  1408. _defineProperty(this, "LOG_THROTTLE_TIMEOUT", 0);
  1409. this.id = id;
  1410. this._storage = new LocalStorage("__probe-".concat(this.id, "__"), DEFAULT_SETTINGS);
  1411. this.userData = {};
  1412. this.timeStamp("".concat(this.id, " started"));
  1413. autobind(this);
  1414. Object.seal(this);
  1415. }
  1416. set level(newLevel) {
  1417. this.setLevel(newLevel);
  1418. }
  1419. get level() {
  1420. return this.getLevel();
  1421. }
  1422. isEnabled() {
  1423. return this._storage.config.enabled;
  1424. }
  1425. getLevel() {
  1426. return this._storage.config.level;
  1427. }
  1428. getTotal() {
  1429. return Number((getHiResTimestamp() - this._startTs).toPrecision(10));
  1430. }
  1431. getDelta() {
  1432. return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10));
  1433. }
  1434. set priority(newPriority) {
  1435. this.level = newPriority;
  1436. }
  1437. get priority() {
  1438. return this.level;
  1439. }
  1440. getPriority() {
  1441. return this.level;
  1442. }
  1443. enable() {
  1444. let enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  1445. this._storage.updateConfiguration({
  1446. enabled
  1447. });
  1448. return this;
  1449. }
  1450. setLevel(level) {
  1451. this._storage.updateConfiguration({
  1452. level
  1453. });
  1454. return this;
  1455. }
  1456. get(setting) {
  1457. return this._storage.config[setting];
  1458. }
  1459. set(setting, value) {
  1460. this._storage.updateConfiguration({
  1461. [setting]: value
  1462. });
  1463. }
  1464. settings() {
  1465. if (console.table) {
  1466. console.table(this._storage.config);
  1467. } else {
  1468. console.log(this._storage.config);
  1469. }
  1470. }
  1471. assert(condition, message) {
  1472. assert$5(condition, message);
  1473. }
  1474. warn(message) {
  1475. return this._getLogFunction(0, message, originalConsole.warn, arguments, ONCE);
  1476. }
  1477. error(message) {
  1478. return this._getLogFunction(0, message, originalConsole.error, arguments);
  1479. }
  1480. deprecated(oldUsage, newUsage) {
  1481. return this.warn("`".concat(oldUsage, "` is deprecated and will be removed in a later version. Use `").concat(newUsage, "` instead"));
  1482. }
  1483. removed(oldUsage, newUsage) {
  1484. return this.error("`".concat(oldUsage, "` has been removed. Use `").concat(newUsage, "` instead"));
  1485. }
  1486. probe(logLevel, message) {
  1487. return this._getLogFunction(logLevel, message, originalConsole.log, arguments, {
  1488. time: true,
  1489. once: true
  1490. });
  1491. }
  1492. log(logLevel, message) {
  1493. return this._getLogFunction(logLevel, message, originalConsole.debug, arguments);
  1494. }
  1495. info(logLevel, message) {
  1496. return this._getLogFunction(logLevel, message, console.info, arguments);
  1497. }
  1498. once(logLevel, message) {
  1499. for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  1500. args[_key - 2] = arguments[_key];
  1501. }
  1502. return this._getLogFunction(logLevel, message, originalConsole.debug || originalConsole.info, arguments, ONCE);
  1503. }
  1504. table(logLevel, table, columns) {
  1505. if (table) {
  1506. return this._getLogFunction(logLevel, table, console.table || noop$1, columns && [columns], {
  1507. tag: getTableHeader(table)
  1508. });
  1509. }
  1510. return noop$1;
  1511. }
  1512. image(_ref) {
  1513. let {
  1514. logLevel,
  1515. priority,
  1516. image,
  1517. message = '',
  1518. scale = 1
  1519. } = _ref;
  1520. if (!this._shouldLog(logLevel || priority)) {
  1521. return noop$1;
  1522. }
  1523. return isBrowser ? logImageInBrowser({
  1524. image,
  1525. message,
  1526. scale
  1527. }) : logImageInNode({
  1528. image,
  1529. message,
  1530. scale
  1531. });
  1532. }
  1533. time(logLevel, message) {
  1534. return this._getLogFunction(logLevel, message, console.time ? console.time : console.info);
  1535. }
  1536. timeEnd(logLevel, message) {
  1537. return this._getLogFunction(logLevel, message, console.timeEnd ? console.timeEnd : console.info);
  1538. }
  1539. timeStamp(logLevel, message) {
  1540. return this._getLogFunction(logLevel, message, console.timeStamp || noop$1);
  1541. }
  1542. group(logLevel, message) {
  1543. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
  1544. collapsed: false
  1545. };
  1546. const options = normalizeArguments({
  1547. logLevel,
  1548. message,
  1549. opts
  1550. });
  1551. const {
  1552. collapsed
  1553. } = opts;
  1554. options.method = (collapsed ? console.groupCollapsed : console.group) || console.info;
  1555. return this._getLogFunction(options);
  1556. }
  1557. groupCollapsed(logLevel, message) {
  1558. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  1559. return this.group(logLevel, message, Object.assign({}, opts, {
  1560. collapsed: true
  1561. }));
  1562. }
  1563. groupEnd(logLevel) {
  1564. return this._getLogFunction(logLevel, '', console.groupEnd || noop$1);
  1565. }
  1566. withGroup(logLevel, message, func) {
  1567. this.group(logLevel, message)();
  1568. try {
  1569. func();
  1570. } finally {
  1571. this.groupEnd(logLevel)();
  1572. }
  1573. }
  1574. trace() {
  1575. if (console.trace) {
  1576. console.trace();
  1577. }
  1578. }
  1579. _shouldLog(logLevel) {
  1580. return this.isEnabled() && this.getLevel() >= normalizeLogLevel(logLevel);
  1581. }
  1582. _getLogFunction(logLevel, message, method, args, opts) {
  1583. if (this._shouldLog(logLevel)) {
  1584. opts = normalizeArguments({
  1585. logLevel,
  1586. message,
  1587. args,
  1588. opts
  1589. });
  1590. method = method || opts.method;
  1591. assert$5(method);
  1592. opts.total = this.getTotal();
  1593. opts.delta = this.getDelta();
  1594. this._deltaTs = getHiResTimestamp();
  1595. const tag = opts.tag || opts.message;
  1596. if (opts.once) {
  1597. if (!cache[tag]) {
  1598. cache[tag] = getHiResTimestamp();
  1599. } else {
  1600. return noop$1;
  1601. }
  1602. }
  1603. message = decorateMessage(this.id, opts.message, opts);
  1604. return method.bind(console, message, ...opts.args);
  1605. }
  1606. return noop$1;
  1607. }
  1608. }
  1609. _defineProperty(Log, "VERSION", VERSION$6);
  1610. function normalizeLogLevel(logLevel) {
  1611. if (!logLevel) {
  1612. return 0;
  1613. }
  1614. let resolvedLevel;
  1615. switch (typeof logLevel) {
  1616. case 'number':
  1617. resolvedLevel = logLevel;
  1618. break;
  1619. case 'object':
  1620. resolvedLevel = logLevel.logLevel || logLevel.priority || 0;
  1621. break;
  1622. default:
  1623. return 0;
  1624. }
  1625. assert$5(Number.isFinite(resolvedLevel) && resolvedLevel >= 0);
  1626. return resolvedLevel;
  1627. }
  1628. function normalizeArguments(opts) {
  1629. const {
  1630. logLevel,
  1631. message
  1632. } = opts;
  1633. opts.logLevel = normalizeLogLevel(logLevel);
  1634. const args = opts.args ? Array.from(opts.args) : [];
  1635. while (args.length && args.shift() !== message) {}
  1636. switch (typeof logLevel) {
  1637. case 'string':
  1638. case 'function':
  1639. if (message !== undefined) {
  1640. args.unshift(message);
  1641. }
  1642. opts.message = logLevel;
  1643. break;
  1644. case 'object':
  1645. Object.assign(opts, logLevel);
  1646. break;
  1647. }
  1648. if (typeof opts.message === 'function') {
  1649. opts.message = opts.message();
  1650. }
  1651. const messageType = typeof opts.message;
  1652. assert$5(messageType === 'string' || messageType === 'object');
  1653. return Object.assign(opts, {
  1654. args
  1655. }, opts.opts);
  1656. }
  1657. function decorateMessage(id, message, opts) {
  1658. if (typeof message === 'string') {
  1659. const time = opts.time ? leftPad(formatTime(opts.total)) : '';
  1660. message = opts.time ? "".concat(id, ": ").concat(time, " ").concat(message) : "".concat(id, ": ").concat(message);
  1661. message = addColor(message, opts.color, opts.background);
  1662. }
  1663. return message;
  1664. }
  1665. function logImageInNode(_ref2) {
  1666. let {
  1667. image,
  1668. message = '',
  1669. scale = 1
  1670. } = _ref2;
  1671. let asciify = null;
  1672. try {
  1673. asciify = module.require('asciify-image');
  1674. } catch (error) {}
  1675. if (asciify) {
  1676. return () => asciify(image, {
  1677. fit: 'box',
  1678. width: "".concat(Math.round(80 * scale), "%")
  1679. }).then(data => console.log(data));
  1680. }
  1681. return noop$1;
  1682. }
  1683. function logImageInBrowser(_ref3) {
  1684. let {
  1685. image,
  1686. message = '',
  1687. scale = 1
  1688. } = _ref3;
  1689. if (typeof image === 'string') {
  1690. const img = new Image();
  1691. img.onload = () => {
  1692. const args = formatImage(img, message, scale);
  1693. console.log(...args);
  1694. };
  1695. img.src = image;
  1696. return noop$1;
  1697. }
  1698. const element = image.nodeName || '';
  1699. if (element.toLowerCase() === 'img') {
  1700. console.log(...formatImage(image, message, scale));
  1701. return noop$1;
  1702. }
  1703. if (element.toLowerCase() === 'canvas') {
  1704. const img = new Image();
  1705. img.onload = () => console.log(...formatImage(img, message, scale));
  1706. img.src = image.toDataURL();
  1707. return noop$1;
  1708. }
  1709. return noop$1;
  1710. }
  1711. function getTableHeader(table) {
  1712. for (const key in table) {
  1713. for (const title in table[key]) {
  1714. return title || 'untitled';
  1715. }
  1716. }
  1717. return 'empty';
  1718. }
  1719. const probeLog = new Log({
  1720. id: 'loaders.gl'
  1721. });
  1722. class NullLog {
  1723. log() {
  1724. return () => {};
  1725. }
  1726. info() {
  1727. return () => {};
  1728. }
  1729. warn() {
  1730. return () => {};
  1731. }
  1732. error() {
  1733. return () => {};
  1734. }
  1735. }
  1736. class ConsoleLog {
  1737. constructor() {
  1738. _defineProperty(this, "console", void 0);
  1739. this.console = console;
  1740. }
  1741. log(...args) {
  1742. return this.console.log.bind(this.console, ...args);
  1743. }
  1744. info(...args) {
  1745. return this.console.info.bind(this.console, ...args);
  1746. }
  1747. warn(...args) {
  1748. return this.console.warn.bind(this.console, ...args);
  1749. }
  1750. error(...args) {
  1751. return this.console.error.bind(this.console, ...args);
  1752. }
  1753. }
  1754. const DEFAULT_LOADER_OPTIONS = {
  1755. fetch: null,
  1756. mimeType: undefined,
  1757. nothrow: false,
  1758. log: new ConsoleLog(),
  1759. CDN: 'https://unpkg.com/@loaders.gl',
  1760. worker: true,
  1761. maxConcurrency: 3,
  1762. maxMobileConcurrency: 1,
  1763. reuseWorkers: true,
  1764. _workerType: '',
  1765. limit: 0,
  1766. _limitMB: 0,
  1767. batchSize: 'auto',
  1768. batchDebounceMs: 0,
  1769. metadata: false,
  1770. transforms: []
  1771. };
  1772. const REMOVED_LOADER_OPTIONS = {
  1773. throws: 'nothrow',
  1774. dataType: '(no longer used)',
  1775. uri: 'baseUri',
  1776. method: 'fetch.method',
  1777. headers: 'fetch.headers',
  1778. body: 'fetch.body',
  1779. mode: 'fetch.mode',
  1780. credentials: 'fetch.credentials',
  1781. cache: 'fetch.cache',
  1782. redirect: 'fetch.redirect',
  1783. referrer: 'fetch.referrer',
  1784. referrerPolicy: 'fetch.referrerPolicy',
  1785. integrity: 'fetch.integrity',
  1786. keepalive: 'fetch.keepalive',
  1787. signal: 'fetch.signal'
  1788. };
  1789. function getGlobalLoaderState() {
  1790. globalThis.loaders = globalThis.loaders || {};
  1791. const {
  1792. loaders
  1793. } = globalThis;
  1794. loaders._state = loaders._state || {};
  1795. return loaders._state;
  1796. }
  1797. const getGlobalLoaderOptions = () => {
  1798. const state = getGlobalLoaderState();
  1799. state.globalOptions = state.globalOptions || { ...DEFAULT_LOADER_OPTIONS
  1800. };
  1801. return state.globalOptions;
  1802. };
  1803. function normalizeOptions(options, loader, loaders, url) {
  1804. loaders = loaders || [];
  1805. loaders = Array.isArray(loaders) ? loaders : [loaders];
  1806. validateOptions(options, loaders);
  1807. return normalizeOptionsInternal(loader, options, url);
  1808. }
  1809. function getFetchFunction(options, context) {
  1810. const globalOptions = getGlobalLoaderOptions();
  1811. const fetchOptions = options || globalOptions;
  1812. if (typeof fetchOptions.fetch === 'function') {
  1813. return fetchOptions.fetch;
  1814. }
  1815. if (isObject(fetchOptions.fetch)) {
  1816. return url => fetchFile(url, fetchOptions);
  1817. }
  1818. if (context !== null && context !== void 0 && context.fetch) {
  1819. return context === null || context === void 0 ? void 0 : context.fetch;
  1820. }
  1821. return fetchFile;
  1822. }
  1823. function validateOptions(options, loaders) {
  1824. validateOptionsObject(options, null, DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS, loaders);
  1825. for (const loader of loaders) {
  1826. const idOptions = options && options[loader.id] || {};
  1827. const loaderOptions = loader.options && loader.options[loader.id] || {};
  1828. const deprecatedOptions = loader.deprecatedOptions && loader.deprecatedOptions[loader.id] || {};
  1829. validateOptionsObject(idOptions, loader.id, loaderOptions, deprecatedOptions, loaders);
  1830. }
  1831. }
  1832. function validateOptionsObject(options, id, defaultOptions, deprecatedOptions, loaders) {
  1833. const loaderName = id || 'Top level';
  1834. const prefix = id ? "".concat(id, ".") : '';
  1835. for (const key in options) {
  1836. const isSubOptions = !id && isObject(options[key]);
  1837. const isBaseUriOption = key === 'baseUri' && !id;
  1838. const isWorkerUrlOption = key === 'workerUrl' && id;
  1839. if (!(key in defaultOptions) && !isBaseUriOption && !isWorkerUrlOption) {
  1840. if (key in deprecatedOptions) {
  1841. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' no longer supported, use '").concat(deprecatedOptions[key], "'"))();
  1842. } else if (!isSubOptions) {
  1843. const suggestion = findSimilarOption(key, loaders);
  1844. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' not recognized. ").concat(suggestion))();
  1845. }
  1846. }
  1847. }
  1848. }
  1849. function findSimilarOption(optionKey, loaders) {
  1850. const lowerCaseOptionKey = optionKey.toLowerCase();
  1851. let bestSuggestion = '';
  1852. for (const loader of loaders) {
  1853. for (const key in loader.options) {
  1854. if (optionKey === key) {
  1855. return "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1856. }
  1857. const lowerCaseKey = key.toLowerCase();
  1858. const isPartialMatch = lowerCaseOptionKey.startsWith(lowerCaseKey) || lowerCaseKey.startsWith(lowerCaseOptionKey);
  1859. if (isPartialMatch) {
  1860. bestSuggestion = bestSuggestion || "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1861. }
  1862. }
  1863. }
  1864. return bestSuggestion;
  1865. }
  1866. function normalizeOptionsInternal(loader, options, url) {
  1867. const loaderDefaultOptions = loader.options || {};
  1868. const mergedOptions = { ...loaderDefaultOptions
  1869. };
  1870. addUrlOptions(mergedOptions, url);
  1871. if (mergedOptions.log === null) {
  1872. mergedOptions.log = new NullLog();
  1873. }
  1874. mergeNestedFields(mergedOptions, getGlobalLoaderOptions());
  1875. mergeNestedFields(mergedOptions, options);
  1876. return mergedOptions;
  1877. }
  1878. function mergeNestedFields(mergedOptions, options) {
  1879. for (const key in options) {
  1880. if (key in options) {
  1881. const value = options[key];
  1882. if (isPureObject(value) && isPureObject(mergedOptions[key])) {
  1883. mergedOptions[key] = { ...mergedOptions[key],
  1884. ...options[key]
  1885. };
  1886. } else {
  1887. mergedOptions[key] = options[key];
  1888. }
  1889. }
  1890. }
  1891. }
  1892. function addUrlOptions(options, url) {
  1893. if (url && !('baseUri' in options)) {
  1894. options.baseUri = url;
  1895. }
  1896. }
  1897. function isLoaderObject(loader) {
  1898. var _loader;
  1899. if (!loader) {
  1900. return false;
  1901. }
  1902. if (Array.isArray(loader)) {
  1903. loader = loader[0];
  1904. }
  1905. const hasExtensions = Array.isArray((_loader = loader) === null || _loader === void 0 ? void 0 : _loader.extensions);
  1906. return hasExtensions;
  1907. }
  1908. function normalizeLoader(loader) {
  1909. var _loader2, _loader3;
  1910. assert$7(loader, 'null loader');
  1911. assert$7(isLoaderObject(loader), 'invalid loader');
  1912. let options;
  1913. if (Array.isArray(loader)) {
  1914. options = loader[1];
  1915. loader = loader[0];
  1916. loader = { ...loader,
  1917. options: { ...loader.options,
  1918. ...options
  1919. }
  1920. };
  1921. }
  1922. if ((_loader2 = loader) !== null && _loader2 !== void 0 && _loader2.parseTextSync || (_loader3 = loader) !== null && _loader3 !== void 0 && _loader3.parseText) {
  1923. loader.text = true;
  1924. }
  1925. if (!loader.text) {
  1926. loader.binary = true;
  1927. }
  1928. return loader;
  1929. }
  1930. const getGlobalLoaderRegistry = () => {
  1931. const state = getGlobalLoaderState();
  1932. state.loaderRegistry = state.loaderRegistry || [];
  1933. return state.loaderRegistry;
  1934. };
  1935. function getRegisteredLoaders() {
  1936. return getGlobalLoaderRegistry();
  1937. }
  1938. const EXT_PATTERN = /\.([^.]+)$/;
  1939. async function selectLoader(data, loaders = [], options, context) {
  1940. if (!validHTTPResponse(data)) {
  1941. return null;
  1942. }
  1943. let loader = selectLoaderSync(data, loaders, { ...options,
  1944. nothrow: true
  1945. }, context);
  1946. if (loader) {
  1947. return loader;
  1948. }
  1949. if (isBlob(data)) {
  1950. data = await data.slice(0, 10).arrayBuffer();
  1951. loader = selectLoaderSync(data, loaders, options, context);
  1952. }
  1953. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1954. throw new Error(getNoValidLoaderMessage(data));
  1955. }
  1956. return loader;
  1957. }
  1958. function selectLoaderSync(data, loaders = [], options, context) {
  1959. if (!validHTTPResponse(data)) {
  1960. return null;
  1961. }
  1962. if (loaders && !Array.isArray(loaders)) {
  1963. return normalizeLoader(loaders);
  1964. }
  1965. let candidateLoaders = [];
  1966. if (loaders) {
  1967. candidateLoaders = candidateLoaders.concat(loaders);
  1968. }
  1969. if (!(options !== null && options !== void 0 && options.ignoreRegisteredLoaders)) {
  1970. candidateLoaders.push(...getRegisteredLoaders());
  1971. }
  1972. normalizeLoaders(candidateLoaders);
  1973. const loader = selectLoaderInternal(data, candidateLoaders, options, context);
  1974. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1975. throw new Error(getNoValidLoaderMessage(data));
  1976. }
  1977. return loader;
  1978. }
  1979. function selectLoaderInternal(data, loaders, options, context) {
  1980. const {
  1981. url,
  1982. type
  1983. } = getResourceUrlAndType(data);
  1984. const testUrl = url || (context === null || context === void 0 ? void 0 : context.url);
  1985. let loader = null;
  1986. if (options !== null && options !== void 0 && options.mimeType) {
  1987. loader = findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.mimeType);
  1988. }
  1989. loader = loader || findLoaderByUrl(loaders, testUrl);
  1990. loader = loader || findLoaderByMIMEType(loaders, type);
  1991. loader = loader || findLoaderByInitialBytes(loaders, data);
  1992. loader = loader || findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.fallbackMimeType);
  1993. return loader;
  1994. }
  1995. function validHTTPResponse(data) {
  1996. if (data instanceof Response) {
  1997. if (data.status === 204) {
  1998. return false;
  1999. }
  2000. }
  2001. return true;
  2002. }
  2003. function getNoValidLoaderMessage(data) {
  2004. const {
  2005. url,
  2006. type
  2007. } = getResourceUrlAndType(data);
  2008. let message = 'No valid loader found (';
  2009. message += url ? "".concat(filename(url), ", ") : 'no url provided, ';
  2010. message += "MIME type: ".concat(type ? "\"".concat(type, "\"") : 'not provided', ", ");
  2011. const firstCharacters = data ? getFirstCharacters(data) : '';
  2012. message += firstCharacters ? " first bytes: \"".concat(firstCharacters, "\"") : 'first bytes: not available';
  2013. message += ')';
  2014. return message;
  2015. }
  2016. function normalizeLoaders(loaders) {
  2017. for (const loader of loaders) {
  2018. normalizeLoader(loader);
  2019. }
  2020. }
  2021. function findLoaderByUrl(loaders, url) {
  2022. const match = url && EXT_PATTERN.exec(url);
  2023. const extension = match && match[1];
  2024. return extension ? findLoaderByExtension(loaders, extension) : null;
  2025. }
  2026. function findLoaderByExtension(loaders, extension) {
  2027. extension = extension.toLowerCase();
  2028. for (const loader of loaders) {
  2029. for (const loaderExtension of loader.extensions) {
  2030. if (loaderExtension.toLowerCase() === extension) {
  2031. return loader;
  2032. }
  2033. }
  2034. }
  2035. return null;
  2036. }
  2037. function findLoaderByMIMEType(loaders, mimeType) {
  2038. for (const loader of loaders) {
  2039. if (loader.mimeTypes && loader.mimeTypes.includes(mimeType)) {
  2040. return loader;
  2041. }
  2042. if (mimeType === "application/x.".concat(loader.id)) {
  2043. return loader;
  2044. }
  2045. }
  2046. return null;
  2047. }
  2048. function findLoaderByInitialBytes(loaders, data) {
  2049. if (!data) {
  2050. return null;
  2051. }
  2052. for (const loader of loaders) {
  2053. if (typeof data === 'string') {
  2054. if (testDataAgainstText(data, loader)) {
  2055. return loader;
  2056. }
  2057. } else if (ArrayBuffer.isView(data)) {
  2058. if (testDataAgainstBinary(data.buffer, data.byteOffset, loader)) {
  2059. return loader;
  2060. }
  2061. } else if (data instanceof ArrayBuffer) {
  2062. const byteOffset = 0;
  2063. if (testDataAgainstBinary(data, byteOffset, loader)) {
  2064. return loader;
  2065. }
  2066. }
  2067. }
  2068. return null;
  2069. }
  2070. function testDataAgainstText(data, loader) {
  2071. if (loader.testText) {
  2072. return loader.testText(data);
  2073. }
  2074. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2075. return tests.some(test => data.startsWith(test));
  2076. }
  2077. function testDataAgainstBinary(data, byteOffset, loader) {
  2078. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2079. return tests.some(test => testBinary(data, byteOffset, loader, test));
  2080. }
  2081. function testBinary(data, byteOffset, loader, test) {
  2082. if (test instanceof ArrayBuffer) {
  2083. return compareArrayBuffers(test, data, test.byteLength);
  2084. }
  2085. switch (typeof test) {
  2086. case 'function':
  2087. return test(data, loader);
  2088. case 'string':
  2089. const magic = getMagicString$2(data, byteOffset, test.length);
  2090. return test === magic;
  2091. default:
  2092. return false;
  2093. }
  2094. }
  2095. function getFirstCharacters(data, length = 5) {
  2096. if (typeof data === 'string') {
  2097. return data.slice(0, length);
  2098. } else if (ArrayBuffer.isView(data)) {
  2099. return getMagicString$2(data.buffer, data.byteOffset, length);
  2100. } else if (data instanceof ArrayBuffer) {
  2101. const byteOffset = 0;
  2102. return getMagicString$2(data, byteOffset, length);
  2103. }
  2104. return '';
  2105. }
  2106. function getMagicString$2(arrayBuffer, byteOffset, length) {
  2107. if (arrayBuffer.byteLength < byteOffset + length) {
  2108. return '';
  2109. }
  2110. const dataView = new DataView(arrayBuffer);
  2111. let magic = '';
  2112. for (let i = 0; i < length; i++) {
  2113. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  2114. }
  2115. return magic;
  2116. }
  2117. const DEFAULT_CHUNK_SIZE$2 = 256 * 1024;
  2118. function* makeStringIterator(string, options) {
  2119. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE$2;
  2120. let offset = 0;
  2121. const textEncoder = new TextEncoder();
  2122. while (offset < string.length) {
  2123. const chunkLength = Math.min(string.length - offset, chunkSize);
  2124. const chunk = string.slice(offset, offset + chunkLength);
  2125. offset += chunkLength;
  2126. yield textEncoder.encode(chunk);
  2127. }
  2128. }
  2129. const DEFAULT_CHUNK_SIZE$1 = 256 * 1024;
  2130. function* makeArrayBufferIterator(arrayBuffer, options = {}) {
  2131. const {
  2132. chunkSize = DEFAULT_CHUNK_SIZE$1
  2133. } = options;
  2134. let byteOffset = 0;
  2135. while (byteOffset < arrayBuffer.byteLength) {
  2136. const chunkByteLength = Math.min(arrayBuffer.byteLength - byteOffset, chunkSize);
  2137. const chunk = new ArrayBuffer(chunkByteLength);
  2138. const sourceArray = new Uint8Array(arrayBuffer, byteOffset, chunkByteLength);
  2139. const chunkArray = new Uint8Array(chunk);
  2140. chunkArray.set(sourceArray);
  2141. byteOffset += chunkByteLength;
  2142. yield chunk;
  2143. }
  2144. }
  2145. const DEFAULT_CHUNK_SIZE = 1024 * 1024;
  2146. async function* makeBlobIterator(blob, options) {
  2147. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE;
  2148. let offset = 0;
  2149. while (offset < blob.size) {
  2150. const end = offset + chunkSize;
  2151. const chunk = await blob.slice(offset, end).arrayBuffer();
  2152. offset = end;
  2153. yield chunk;
  2154. }
  2155. }
  2156. function makeStreamIterator(stream, options) {
  2157. return isBrowser$2 ? makeBrowserStreamIterator(stream, options) : makeNodeStreamIterator(stream);
  2158. }
  2159. async function* makeBrowserStreamIterator(stream, options) {
  2160. const reader = stream.getReader();
  2161. let nextBatchPromise;
  2162. try {
  2163. while (true) {
  2164. const currentBatchPromise = nextBatchPromise || reader.read();
  2165. if (options !== null && options !== void 0 && options._streamReadAhead) {
  2166. nextBatchPromise = reader.read();
  2167. }
  2168. const {
  2169. done,
  2170. value
  2171. } = await currentBatchPromise;
  2172. if (done) {
  2173. return;
  2174. }
  2175. yield toArrayBuffer(value);
  2176. }
  2177. } catch (error) {
  2178. reader.releaseLock();
  2179. }
  2180. }
  2181. async function* makeNodeStreamIterator(stream, options) {
  2182. for await (const chunk of stream) {
  2183. yield toArrayBuffer(chunk);
  2184. }
  2185. }
  2186. function makeIterator(data, options) {
  2187. if (typeof data === 'string') {
  2188. return makeStringIterator(data, options);
  2189. }
  2190. if (data instanceof ArrayBuffer) {
  2191. return makeArrayBufferIterator(data, options);
  2192. }
  2193. if (isBlob(data)) {
  2194. return makeBlobIterator(data, options);
  2195. }
  2196. if (isReadableStream(data)) {
  2197. return makeStreamIterator(data, options);
  2198. }
  2199. if (isResponse(data)) {
  2200. const response = data;
  2201. return makeStreamIterator(response.body, options);
  2202. }
  2203. throw new Error('makeIterator');
  2204. }
  2205. const ERR_DATA = 'Cannot convert supplied data type';
  2206. function getArrayBufferOrStringFromDataSync(data, loader, options) {
  2207. if (loader.text && typeof data === 'string') {
  2208. return data;
  2209. }
  2210. if (isBuffer(data)) {
  2211. data = data.buffer;
  2212. }
  2213. if (data instanceof ArrayBuffer) {
  2214. const arrayBuffer = data;
  2215. if (loader.text && !loader.binary) {
  2216. const textDecoder = new TextDecoder('utf8');
  2217. return textDecoder.decode(arrayBuffer);
  2218. }
  2219. return arrayBuffer;
  2220. }
  2221. if (ArrayBuffer.isView(data)) {
  2222. if (loader.text && !loader.binary) {
  2223. const textDecoder = new TextDecoder('utf8');
  2224. return textDecoder.decode(data);
  2225. }
  2226. let arrayBuffer = data.buffer;
  2227. const byteLength = data.byteLength || data.length;
  2228. if (data.byteOffset !== 0 || byteLength !== arrayBuffer.byteLength) {
  2229. arrayBuffer = arrayBuffer.slice(data.byteOffset, data.byteOffset + byteLength);
  2230. }
  2231. return arrayBuffer;
  2232. }
  2233. throw new Error(ERR_DATA);
  2234. }
  2235. async function getArrayBufferOrStringFromData(data, loader, options) {
  2236. const isArrayBuffer = data instanceof ArrayBuffer || ArrayBuffer.isView(data);
  2237. if (typeof data === 'string' || isArrayBuffer) {
  2238. return getArrayBufferOrStringFromDataSync(data, loader);
  2239. }
  2240. if (isBlob(data)) {
  2241. data = await makeResponse(data);
  2242. }
  2243. if (isResponse(data)) {
  2244. const response = data;
  2245. await checkResponse(response);
  2246. return loader.binary ? await response.arrayBuffer() : await response.text();
  2247. }
  2248. if (isReadableStream(data)) {
  2249. data = makeIterator(data, options);
  2250. }
  2251. if (isIterable(data) || isAsyncIterable(data)) {
  2252. return concatenateArrayBuffersAsync(data);
  2253. }
  2254. throw new Error(ERR_DATA);
  2255. }
  2256. function getLoaderContext(context, options, previousContext = null) {
  2257. if (previousContext) {
  2258. return previousContext;
  2259. }
  2260. const resolvedContext = {
  2261. fetch: getFetchFunction(options, context),
  2262. ...context
  2263. };
  2264. if (!Array.isArray(resolvedContext.loaders)) {
  2265. resolvedContext.loaders = null;
  2266. }
  2267. return resolvedContext;
  2268. }
  2269. function getLoadersFromContext(loaders, context) {
  2270. if (!context && loaders && !Array.isArray(loaders)) {
  2271. return loaders;
  2272. }
  2273. let candidateLoaders;
  2274. if (loaders) {
  2275. candidateLoaders = Array.isArray(loaders) ? loaders : [loaders];
  2276. }
  2277. if (context && context.loaders) {
  2278. const contextLoaders = Array.isArray(context.loaders) ? context.loaders : [context.loaders];
  2279. candidateLoaders = candidateLoaders ? [...candidateLoaders, ...contextLoaders] : contextLoaders;
  2280. }
  2281. return candidateLoaders && candidateLoaders.length ? candidateLoaders : null;
  2282. }
  2283. async function parse$3(data, loaders, options, context) {
  2284. assert$6(!context || typeof context === 'object');
  2285. if (loaders && !Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2286. context = undefined;
  2287. options = loaders;
  2288. loaders = undefined;
  2289. }
  2290. data = await data;
  2291. options = options || {};
  2292. const {
  2293. url
  2294. } = getResourceUrlAndType(data);
  2295. const typedLoaders = loaders;
  2296. const candidateLoaders = getLoadersFromContext(typedLoaders, context);
  2297. const loader = await selectLoader(data, candidateLoaders, options);
  2298. if (!loader) {
  2299. return null;
  2300. }
  2301. options = normalizeOptions(options, loader, candidateLoaders, url);
  2302. context = getLoaderContext({
  2303. url,
  2304. parse: parse$3,
  2305. loaders: candidateLoaders
  2306. }, options, context);
  2307. return await parseWithLoader(loader, data, options, context);
  2308. }
  2309. async function parseWithLoader(loader, data, options, context) {
  2310. validateWorkerVersion(loader);
  2311. data = await getArrayBufferOrStringFromData(data, loader, options);
  2312. if (loader.parseTextSync && typeof data === 'string') {
  2313. options.dataType = 'text';
  2314. return loader.parseTextSync(data, options, context, loader);
  2315. }
  2316. if (canParseWithWorker(loader, options)) {
  2317. return await parseWithWorker(loader, data, options, context, parse$3);
  2318. }
  2319. if (loader.parseText && typeof data === 'string') {
  2320. return await loader.parseText(data, options, context, loader);
  2321. }
  2322. if (loader.parse) {
  2323. return await loader.parse(data, options, context, loader);
  2324. }
  2325. assert$6(!loader.parseSync);
  2326. throw new Error("".concat(loader.id, " loader - no parser found and worker is disabled"));
  2327. }
  2328. async function load(url, loaders, options, context) {
  2329. if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2330. options = loaders;
  2331. loaders = undefined;
  2332. }
  2333. const fetch = getFetchFunction(options);
  2334. let data = url;
  2335. if (typeof url === 'string') {
  2336. data = await fetch(url);
  2337. }
  2338. if (isBlob(url)) {
  2339. data = await fetch(url);
  2340. }
  2341. return await parse$3(data, loaders, options);
  2342. }
  2343. function assert$4(condition, message) {
  2344. if (!condition) {
  2345. throw new Error("math.gl assertion ".concat(message));
  2346. }
  2347. }
  2348. const RADIANS_TO_DEGREES = 1 / Math.PI * 180;
  2349. const DEGREES_TO_RADIANS = 1 / 180 * Math.PI;
  2350. const config = {};
  2351. config.EPSILON = 1e-12;
  2352. config.debug = false;
  2353. config.precision = 4;
  2354. config.printTypes = false;
  2355. config.printDegrees = false;
  2356. config.printRowMajor = true;
  2357. function round(value) {
  2358. return Math.round(value / config.EPSILON) * config.EPSILON;
  2359. }
  2360. function formatValue(value, {
  2361. precision = config.precision || 4
  2362. } = {}) {
  2363. value = round(value);
  2364. return "".concat(parseFloat(value.toPrecision(precision)));
  2365. }
  2366. function isArray(value) {
  2367. return Array.isArray(value) || ArrayBuffer.isView(value) && !(value instanceof DataView);
  2368. }
  2369. function duplicateArray(array) {
  2370. return array.clone ? array.clone() : new Array(array.length);
  2371. }
  2372. function map$1(value, func, result) {
  2373. if (isArray(value)) {
  2374. result = result || duplicateArray(value);
  2375. for (let i = 0; i < result.length && i < value.length; ++i) {
  2376. result[i] = func(value[i], i, result);
  2377. }
  2378. return result;
  2379. }
  2380. return func(value);
  2381. }
  2382. function toRadians(degrees) {
  2383. return radians(degrees);
  2384. }
  2385. function toDegrees(radians) {
  2386. return degrees(radians);
  2387. }
  2388. function radians(degrees, result) {
  2389. return map$1(degrees, degrees => degrees * DEGREES_TO_RADIANS, result);
  2390. }
  2391. function degrees(radians, result) {
  2392. return map$1(radians, radians => radians * RADIANS_TO_DEGREES, result);
  2393. }
  2394. function clamp(value, min, max) {
  2395. return map$1(value, value => Math.max(min, Math.min(max, value)));
  2396. }
  2397. function equals(a, b, epsilon) {
  2398. const oldEpsilon = config.EPSILON;
  2399. if (epsilon) {
  2400. config.EPSILON = epsilon;
  2401. }
  2402. try {
  2403. if (a === b) {
  2404. return true;
  2405. }
  2406. if (isArray(a) && isArray(b)) {
  2407. if (a.length !== b.length) {
  2408. return false;
  2409. }
  2410. for (let i = 0; i < a.length; ++i) {
  2411. if (!equals(a[i], b[i])) {
  2412. return false;
  2413. }
  2414. }
  2415. return true;
  2416. }
  2417. if (a && a.equals) {
  2418. return a.equals(b);
  2419. }
  2420. if (b && b.equals) {
  2421. return b.equals(a);
  2422. }
  2423. if (Number.isFinite(a) && Number.isFinite(b)) {
  2424. return Math.abs(a - b) <= config.EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));
  2425. }
  2426. return false;
  2427. } finally {
  2428. config.EPSILON = oldEpsilon;
  2429. }
  2430. }
  2431. function _extendableBuiltin(cls) {
  2432. function ExtendableBuiltin() {
  2433. var instance = Reflect.construct(cls, Array.from(arguments));
  2434. Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
  2435. return instance;
  2436. }
  2437. ExtendableBuiltin.prototype = Object.create(cls.prototype, {
  2438. constructor: {
  2439. value: cls,
  2440. enumerable: false,
  2441. writable: true,
  2442. configurable: true
  2443. }
  2444. });
  2445. if (Object.setPrototypeOf) {
  2446. Object.setPrototypeOf(ExtendableBuiltin, cls);
  2447. } else {
  2448. ExtendableBuiltin.__proto__ = cls;
  2449. }
  2450. return ExtendableBuiltin;
  2451. }
  2452. class MathArray extends _extendableBuiltin(Array) {
  2453. get ELEMENTS() {
  2454. assert$4(false);
  2455. return 0;
  2456. }
  2457. clone() {
  2458. return new this.constructor().copy(this);
  2459. }
  2460. from(arrayOrObject) {
  2461. return Array.isArray(arrayOrObject) ? this.copy(arrayOrObject) : this.fromObject(arrayOrObject);
  2462. }
  2463. fromArray(array, offset = 0) {
  2464. for (let i = 0; i < this.ELEMENTS; ++i) {
  2465. this[i] = array[i + offset];
  2466. }
  2467. return this.check();
  2468. }
  2469. to(arrayOrObject) {
  2470. if (arrayOrObject === this) {
  2471. return this;
  2472. }
  2473. return isArray(arrayOrObject) ? this.toArray(arrayOrObject) : this.toObject(arrayOrObject);
  2474. }
  2475. toTarget(target) {
  2476. return target ? this.to(target) : this;
  2477. }
  2478. toArray(array = [], offset = 0) {
  2479. for (let i = 0; i < this.ELEMENTS; ++i) {
  2480. array[offset + i] = this[i];
  2481. }
  2482. return array;
  2483. }
  2484. toFloat32Array() {
  2485. return new Float32Array(this);
  2486. }
  2487. toString() {
  2488. return this.formatString(config);
  2489. }
  2490. formatString(opts) {
  2491. let string = '';
  2492. for (let i = 0; i < this.ELEMENTS; ++i) {
  2493. string += (i > 0 ? ', ' : '') + formatValue(this[i], opts);
  2494. }
  2495. return "".concat(opts.printTypes ? this.constructor.name : '', "[").concat(string, "]");
  2496. }
  2497. equals(array) {
  2498. if (!array || this.length !== array.length) {
  2499. return false;
  2500. }
  2501. for (let i = 0; i < this.ELEMENTS; ++i) {
  2502. if (!equals(this[i], array[i])) {
  2503. return false;
  2504. }
  2505. }
  2506. return true;
  2507. }
  2508. exactEquals(array) {
  2509. if (!array || this.length !== array.length) {
  2510. return false;
  2511. }
  2512. for (let i = 0; i < this.ELEMENTS; ++i) {
  2513. if (this[i] !== array[i]) {
  2514. return false;
  2515. }
  2516. }
  2517. return true;
  2518. }
  2519. negate() {
  2520. for (let i = 0; i < this.ELEMENTS; ++i) {
  2521. this[i] = -this[i];
  2522. }
  2523. return this.check();
  2524. }
  2525. lerp(a, b, t) {
  2526. if (t === undefined) {
  2527. t = b;
  2528. b = a;
  2529. a = this;
  2530. }
  2531. for (let i = 0; i < this.ELEMENTS; ++i) {
  2532. const ai = a[i];
  2533. this[i] = ai + t * (b[i] - ai);
  2534. }
  2535. return this.check();
  2536. }
  2537. min(vector) {
  2538. for (let i = 0; i < this.ELEMENTS; ++i) {
  2539. this[i] = Math.min(vector[i], this[i]);
  2540. }
  2541. return this.check();
  2542. }
  2543. max(vector) {
  2544. for (let i = 0; i < this.ELEMENTS; ++i) {
  2545. this[i] = Math.max(vector[i], this[i]);
  2546. }
  2547. return this.check();
  2548. }
  2549. clamp(minVector, maxVector) {
  2550. for (let i = 0; i < this.ELEMENTS; ++i) {
  2551. this[i] = Math.min(Math.max(this[i], minVector[i]), maxVector[i]);
  2552. }
  2553. return this.check();
  2554. }
  2555. add(...vectors) {
  2556. for (const vector of vectors) {
  2557. for (let i = 0; i < this.ELEMENTS; ++i) {
  2558. this[i] += vector[i];
  2559. }
  2560. }
  2561. return this.check();
  2562. }
  2563. subtract(...vectors) {
  2564. for (const vector of vectors) {
  2565. for (let i = 0; i < this.ELEMENTS; ++i) {
  2566. this[i] -= vector[i];
  2567. }
  2568. }
  2569. return this.check();
  2570. }
  2571. scale(scale) {
  2572. if (Array.isArray(scale)) {
  2573. return this.multiply(scale);
  2574. }
  2575. for (let i = 0; i < this.ELEMENTS; ++i) {
  2576. this[i] *= scale;
  2577. }
  2578. return this.check();
  2579. }
  2580. sub(a) {
  2581. return this.subtract(a);
  2582. }
  2583. setScalar(a) {
  2584. for (let i = 0; i < this.ELEMENTS; ++i) {
  2585. this[i] = a;
  2586. }
  2587. return this.check();
  2588. }
  2589. addScalar(a) {
  2590. for (let i = 0; i < this.ELEMENTS; ++i) {
  2591. this[i] += a;
  2592. }
  2593. return this.check();
  2594. }
  2595. subScalar(a) {
  2596. return this.addScalar(-a);
  2597. }
  2598. multiplyScalar(scalar) {
  2599. for (let i = 0; i < this.ELEMENTS; ++i) {
  2600. this[i] *= scalar;
  2601. }
  2602. return this.check();
  2603. }
  2604. divideScalar(a) {
  2605. return this.scale(1 / a);
  2606. }
  2607. clampScalar(min, max) {
  2608. for (let i = 0; i < this.ELEMENTS; ++i) {
  2609. this[i] = Math.min(Math.max(this[i], min), max);
  2610. }
  2611. return this.check();
  2612. }
  2613. multiplyByScalar(scalar) {
  2614. return this.scale(scalar);
  2615. }
  2616. get elements() {
  2617. return this;
  2618. }
  2619. check() {
  2620. if (config.debug && !this.validate()) {
  2621. throw new Error("math.gl: ".concat(this.constructor.name, " some fields set to invalid numbers'"));
  2622. }
  2623. return this;
  2624. }
  2625. validate() {
  2626. let valid = this.length === this.ELEMENTS;
  2627. for (let i = 0; i < this.ELEMENTS; ++i) {
  2628. valid = valid && Number.isFinite(this[i]);
  2629. }
  2630. return valid;
  2631. }
  2632. }
  2633. function validateVector(v, length) {
  2634. if (v.length !== length) {
  2635. return false;
  2636. }
  2637. for (let i = 0; i < v.length; ++i) {
  2638. if (!Number.isFinite(v[i])) {
  2639. return false;
  2640. }
  2641. }
  2642. return true;
  2643. }
  2644. function checkNumber(value) {
  2645. if (!Number.isFinite(value)) {
  2646. throw new Error("Invalid number ".concat(value));
  2647. }
  2648. return value;
  2649. }
  2650. function checkVector(v, length, callerName = '') {
  2651. if (config.debug && !validateVector(v, length)) {
  2652. throw new Error("math.gl: ".concat(callerName, " some fields set to invalid numbers'"));
  2653. }
  2654. return v;
  2655. }
  2656. const map = {};
  2657. function deprecated(method, version) {
  2658. if (!map[method]) {
  2659. map[method] = true;
  2660. console.warn("".concat(method, " has been removed in version ").concat(version, ", see upgrade guide for more information"));
  2661. }
  2662. }
  2663. class Vector extends MathArray {
  2664. get ELEMENTS() {
  2665. assert$4(false);
  2666. return 0;
  2667. }
  2668. copy(vector) {
  2669. assert$4(false);
  2670. return this;
  2671. }
  2672. get x() {
  2673. return this[0];
  2674. }
  2675. set x(value) {
  2676. this[0] = checkNumber(value);
  2677. }
  2678. get y() {
  2679. return this[1];
  2680. }
  2681. set y(value) {
  2682. this[1] = checkNumber(value);
  2683. }
  2684. len() {
  2685. return Math.sqrt(this.lengthSquared());
  2686. }
  2687. magnitude() {
  2688. return this.len();
  2689. }
  2690. lengthSquared() {
  2691. let length = 0;
  2692. for (let i = 0; i < this.ELEMENTS; ++i) {
  2693. length += this[i] * this[i];
  2694. }
  2695. return length;
  2696. }
  2697. magnitudeSquared() {
  2698. return this.lengthSquared();
  2699. }
  2700. distance(mathArray) {
  2701. return Math.sqrt(this.distanceSquared(mathArray));
  2702. }
  2703. distanceSquared(mathArray) {
  2704. let length = 0;
  2705. for (let i = 0; i < this.ELEMENTS; ++i) {
  2706. const dist = this[i] - mathArray[i];
  2707. length += dist * dist;
  2708. }
  2709. return checkNumber(length);
  2710. }
  2711. dot(mathArray) {
  2712. let product = 0;
  2713. for (let i = 0; i < this.ELEMENTS; ++i) {
  2714. product += this[i] * mathArray[i];
  2715. }
  2716. return checkNumber(product);
  2717. }
  2718. normalize() {
  2719. const length = this.magnitude();
  2720. if (length !== 0) {
  2721. for (let i = 0; i < this.ELEMENTS; ++i) {
  2722. this[i] /= length;
  2723. }
  2724. }
  2725. return this.check();
  2726. }
  2727. multiply(...vectors) {
  2728. for (const vector of vectors) {
  2729. for (let i = 0; i < this.ELEMENTS; ++i) {
  2730. this[i] *= vector[i];
  2731. }
  2732. }
  2733. return this.check();
  2734. }
  2735. divide(...vectors) {
  2736. for (const vector of vectors) {
  2737. for (let i = 0; i < this.ELEMENTS; ++i) {
  2738. this[i] /= vector[i];
  2739. }
  2740. }
  2741. return this.check();
  2742. }
  2743. lengthSq() {
  2744. return this.lengthSquared();
  2745. }
  2746. distanceTo(vector) {
  2747. return this.distance(vector);
  2748. }
  2749. distanceToSquared(vector) {
  2750. return this.distanceSquared(vector);
  2751. }
  2752. getComponent(i) {
  2753. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2754. return checkNumber(this[i]);
  2755. }
  2756. setComponent(i, value) {
  2757. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2758. this[i] = value;
  2759. return this.check();
  2760. }
  2761. addVectors(a, b) {
  2762. return this.copy(a).add(b);
  2763. }
  2764. subVectors(a, b) {
  2765. return this.copy(a).subtract(b);
  2766. }
  2767. multiplyVectors(a, b) {
  2768. return this.copy(a).multiply(b);
  2769. }
  2770. addScaledVector(a, b) {
  2771. return this.add(new this.constructor(a).multiplyScalar(b));
  2772. }
  2773. }
  2774. /**
  2775. * Common utilities
  2776. * @module glMatrix
  2777. */
  2778. // Configuration Constants
  2779. var EPSILON = 0.000001;
  2780. var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  2781. if (!Math.hypot) Math.hypot = function () {
  2782. var y = 0,
  2783. i = arguments.length;
  2784. while (i--) {
  2785. y += arguments[i] * arguments[i];
  2786. }
  2787. return Math.sqrt(y);
  2788. };
  2789. /**
  2790. * 2 Dimensional Vector
  2791. * @module vec2
  2792. */
  2793. /**
  2794. * Creates a new, empty vec2
  2795. *
  2796. * @returns {vec2} a new 2D vector
  2797. */
  2798. function create$4() {
  2799. var out = new ARRAY_TYPE(2);
  2800. if (ARRAY_TYPE != Float32Array) {
  2801. out[0] = 0;
  2802. out[1] = 0;
  2803. }
  2804. return out;
  2805. }
  2806. /**
  2807. * Transforms the vec2 with a mat2
  2808. *
  2809. * @param {vec2} out the receiving vector
  2810. * @param {ReadonlyVec2} a the vector to transform
  2811. * @param {ReadonlyMat2} m matrix to transform with
  2812. * @returns {vec2} out
  2813. */
  2814. function transformMat2(out, a, m) {
  2815. var x = a[0],
  2816. y = a[1];
  2817. out[0] = m[0] * x + m[2] * y;
  2818. out[1] = m[1] * x + m[3] * y;
  2819. return out;
  2820. }
  2821. /**
  2822. * Transforms the vec2 with a mat2d
  2823. *
  2824. * @param {vec2} out the receiving vector
  2825. * @param {ReadonlyVec2} a the vector to transform
  2826. * @param {ReadonlyMat2d} m matrix to transform with
  2827. * @returns {vec2} out
  2828. */
  2829. function transformMat2d(out, a, m) {
  2830. var x = a[0],
  2831. y = a[1];
  2832. out[0] = m[0] * x + m[2] * y + m[4];
  2833. out[1] = m[1] * x + m[3] * y + m[5];
  2834. return out;
  2835. }
  2836. /**
  2837. * Transforms the vec2 with a mat3
  2838. * 3rd vector component is implicitly '1'
  2839. *
  2840. * @param {vec2} out the receiving vector
  2841. * @param {ReadonlyVec2} a the vector to transform
  2842. * @param {ReadonlyMat3} m matrix to transform with
  2843. * @returns {vec2} out
  2844. */
  2845. function transformMat3$1(out, a, m) {
  2846. var x = a[0],
  2847. y = a[1];
  2848. out[0] = m[0] * x + m[3] * y + m[6];
  2849. out[1] = m[1] * x + m[4] * y + m[7];
  2850. return out;
  2851. }
  2852. /**
  2853. * Transforms the vec2 with a mat4
  2854. * 3rd vector component is implicitly '0'
  2855. * 4th vector component is implicitly '1'
  2856. *
  2857. * @param {vec2} out the receiving vector
  2858. * @param {ReadonlyVec2} a the vector to transform
  2859. * @param {ReadonlyMat4} m matrix to transform with
  2860. * @returns {vec2} out
  2861. */
  2862. function transformMat4$2(out, a, m) {
  2863. var x = a[0];
  2864. var y = a[1];
  2865. out[0] = m[0] * x + m[4] * y + m[12];
  2866. out[1] = m[1] * x + m[5] * y + m[13];
  2867. return out;
  2868. }
  2869. /**
  2870. * Perform some operation over an array of vec2s.
  2871. *
  2872. * @param {Array} a the array of vectors to iterate over
  2873. * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
  2874. * @param {Number} offset Number of elements to skip at the beginning of the array
  2875. * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
  2876. * @param {Function} fn Function to call for each vector in the array
  2877. * @param {Object} [arg] additional argument to pass to fn
  2878. * @returns {Array} a
  2879. * @function
  2880. */
  2881. (function () {
  2882. var vec = create$4();
  2883. return function (a, stride, offset, count, fn, arg) {
  2884. var i, l;
  2885. if (!stride) {
  2886. stride = 2;
  2887. }
  2888. if (!offset) {
  2889. offset = 0;
  2890. }
  2891. if (count) {
  2892. l = Math.min(count * stride + offset, a.length);
  2893. } else {
  2894. l = a.length;
  2895. }
  2896. for (i = offset; i < l; i += stride) {
  2897. vec[0] = a[i];
  2898. vec[1] = a[i + 1];
  2899. fn(vec, vec, arg);
  2900. a[i] = vec[0];
  2901. a[i + 1] = vec[1];
  2902. }
  2903. return a;
  2904. };
  2905. })();
  2906. function vec2_transformMat4AsVector(out, a, m) {
  2907. const x = a[0];
  2908. const y = a[1];
  2909. const w = m[3] * x + m[7] * y || 1.0;
  2910. out[0] = (m[0] * x + m[4] * y) / w;
  2911. out[1] = (m[1] * x + m[5] * y) / w;
  2912. return out;
  2913. }
  2914. function vec3_transformMat4AsVector(out, a, m) {
  2915. const x = a[0];
  2916. const y = a[1];
  2917. const z = a[2];
  2918. const w = m[3] * x + m[7] * y + m[11] * z || 1.0;
  2919. out[0] = (m[0] * x + m[4] * y + m[8] * z) / w;
  2920. out[1] = (m[1] * x + m[5] * y + m[9] * z) / w;
  2921. out[2] = (m[2] * x + m[6] * y + m[10] * z) / w;
  2922. return out;
  2923. }
  2924. function vec3_transformMat2(out, a, m) {
  2925. const x = a[0];
  2926. const y = a[1];
  2927. out[0] = m[0] * x + m[2] * y;
  2928. out[1] = m[1] * x + m[3] * y;
  2929. out[2] = a[2];
  2930. return out;
  2931. }
  2932. function vec4_transformMat3(out, a, m) {
  2933. const x = a[0];
  2934. const y = a[1];
  2935. const z = a[2];
  2936. out[0] = m[0] * x + m[3] * y + m[6] * z;
  2937. out[1] = m[1] * x + m[4] * y + m[7] * z;
  2938. out[2] = m[2] * x + m[5] * y + m[8] * z;
  2939. out[3] = a[3];
  2940. return out;
  2941. }
  2942. class Vector2 extends Vector {
  2943. constructor(x = 0, y = 0) {
  2944. super(2);
  2945. if (isArray(x) && arguments.length === 1) {
  2946. this.copy(x);
  2947. } else {
  2948. if (config.debug) {
  2949. checkNumber(x);
  2950. checkNumber(y);
  2951. }
  2952. this[0] = x;
  2953. this[1] = y;
  2954. }
  2955. }
  2956. set(x, y) {
  2957. this[0] = x;
  2958. this[1] = y;
  2959. return this.check();
  2960. }
  2961. copy(array) {
  2962. this[0] = array[0];
  2963. this[1] = array[1];
  2964. return this.check();
  2965. }
  2966. fromObject(object) {
  2967. if (config.debug) {
  2968. checkNumber(object.x);
  2969. checkNumber(object.y);
  2970. }
  2971. this[0] = object.x;
  2972. this[1] = object.y;
  2973. return this.check();
  2974. }
  2975. toObject(object) {
  2976. object.x = this[0];
  2977. object.y = this[1];
  2978. return object;
  2979. }
  2980. get ELEMENTS() {
  2981. return 2;
  2982. }
  2983. horizontalAngle() {
  2984. return Math.atan2(this.y, this.x);
  2985. }
  2986. verticalAngle() {
  2987. return Math.atan2(this.x, this.y);
  2988. }
  2989. transform(matrix4) {
  2990. return this.transformAsPoint(matrix4);
  2991. }
  2992. transformAsPoint(matrix4) {
  2993. transformMat4$2(this, this, matrix4);
  2994. return this.check();
  2995. }
  2996. transformAsVector(matrix4) {
  2997. vec2_transformMat4AsVector(this, this, matrix4);
  2998. return this.check();
  2999. }
  3000. transformByMatrix3(matrix3) {
  3001. transformMat3$1(this, this, matrix3);
  3002. return this.check();
  3003. }
  3004. transformByMatrix2x3(matrix2x3) {
  3005. transformMat2d(this, this, matrix2x3);
  3006. return this.check();
  3007. }
  3008. transformByMatrix2(matrix2) {
  3009. transformMat2(this, this, matrix2);
  3010. return this.check();
  3011. }
  3012. }
  3013. /**
  3014. * 3 Dimensional Vector
  3015. * @module vec3
  3016. */
  3017. /**
  3018. * Creates a new, empty vec3
  3019. *
  3020. * @returns {vec3} a new 3D vector
  3021. */
  3022. function create$3() {
  3023. var out = new ARRAY_TYPE(3);
  3024. if (ARRAY_TYPE != Float32Array) {
  3025. out[0] = 0;
  3026. out[1] = 0;
  3027. out[2] = 0;
  3028. }
  3029. return out;
  3030. }
  3031. /**
  3032. * Calculates the length of a vec3
  3033. *
  3034. * @param {ReadonlyVec3} a vector to calculate length of
  3035. * @returns {Number} length of a
  3036. */
  3037. function length$2(a) {
  3038. var x = a[0];
  3039. var y = a[1];
  3040. var z = a[2];
  3041. return Math.hypot(x, y, z);
  3042. }
  3043. /**
  3044. * Creates a new vec3 initialized with the given values
  3045. *
  3046. * @param {Number} x X component
  3047. * @param {Number} y Y component
  3048. * @param {Number} z Z component
  3049. * @returns {vec3} a new 3D vector
  3050. */
  3051. function fromValues(x, y, z) {
  3052. var out = new ARRAY_TYPE(3);
  3053. out[0] = x;
  3054. out[1] = y;
  3055. out[2] = z;
  3056. return out;
  3057. }
  3058. /**
  3059. * Normalize a vec3
  3060. *
  3061. * @param {vec3} out the receiving vector
  3062. * @param {ReadonlyVec3} a vector to normalize
  3063. * @returns {vec3} out
  3064. */
  3065. function normalize$2(out, a) {
  3066. var x = a[0];
  3067. var y = a[1];
  3068. var z = a[2];
  3069. var len = x * x + y * y + z * z;
  3070. if (len > 0) {
  3071. //TODO: evaluate use of glm_invsqrt here?
  3072. len = 1 / Math.sqrt(len);
  3073. }
  3074. out[0] = a[0] * len;
  3075. out[1] = a[1] * len;
  3076. out[2] = a[2] * len;
  3077. return out;
  3078. }
  3079. /**
  3080. * Calculates the dot product of two vec3's
  3081. *
  3082. * @param {ReadonlyVec3} a the first operand
  3083. * @param {ReadonlyVec3} b the second operand
  3084. * @returns {Number} dot product of a and b
  3085. */
  3086. function dot$2(a, b) {
  3087. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  3088. }
  3089. /**
  3090. * Computes the cross product of two vec3's
  3091. *
  3092. * @param {vec3} out the receiving vector
  3093. * @param {ReadonlyVec3} a the first operand
  3094. * @param {ReadonlyVec3} b the second operand
  3095. * @returns {vec3} out
  3096. */
  3097. function cross(out, a, b) {
  3098. var ax = a[0],
  3099. ay = a[1],
  3100. az = a[2];
  3101. var bx = b[0],
  3102. by = b[1],
  3103. bz = b[2];
  3104. out[0] = ay * bz - az * by;
  3105. out[1] = az * bx - ax * bz;
  3106. out[2] = ax * by - ay * bx;
  3107. return out;
  3108. }
  3109. /**
  3110. * Transforms the vec3 with a mat4.
  3111. * 4th vector component is implicitly '1'
  3112. *
  3113. * @param {vec3} out the receiving vector
  3114. * @param {ReadonlyVec3} a the vector to transform
  3115. * @param {ReadonlyMat4} m matrix to transform with
  3116. * @returns {vec3} out
  3117. */
  3118. function transformMat4$1(out, a, m) {
  3119. var x = a[0],
  3120. y = a[1],
  3121. z = a[2];
  3122. var w = m[3] * x + m[7] * y + m[11] * z + m[15];
  3123. w = w || 1.0;
  3124. out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
  3125. out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
  3126. out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
  3127. return out;
  3128. }
  3129. /**
  3130. * Transforms the vec3 with a mat3.
  3131. *
  3132. * @param {vec3} out the receiving vector
  3133. * @param {ReadonlyVec3} a the vector to transform
  3134. * @param {ReadonlyMat3} m the 3x3 matrix to transform with
  3135. * @returns {vec3} out
  3136. */
  3137. function transformMat3(out, a, m) {
  3138. var x = a[0],
  3139. y = a[1],
  3140. z = a[2];
  3141. out[0] = x * m[0] + y * m[3] + z * m[6];
  3142. out[1] = x * m[1] + y * m[4] + z * m[7];
  3143. out[2] = x * m[2] + y * m[5] + z * m[8];
  3144. return out;
  3145. }
  3146. /**
  3147. * Transforms the vec3 with a quat
  3148. * Can also be used for dual quaternions. (Multiply it with the real part)
  3149. *
  3150. * @param {vec3} out the receiving vector
  3151. * @param {ReadonlyVec3} a the vector to transform
  3152. * @param {ReadonlyQuat} q quaternion to transform with
  3153. * @returns {vec3} out
  3154. */
  3155. function transformQuat$1(out, a, q) {
  3156. // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed
  3157. var qx = q[0],
  3158. qy = q[1],
  3159. qz = q[2],
  3160. qw = q[3];
  3161. var x = a[0],
  3162. y = a[1],
  3163. z = a[2]; // var qvec = [qx, qy, qz];
  3164. // var uv = vec3.cross([], qvec, a);
  3165. var uvx = qy * z - qz * y,
  3166. uvy = qz * x - qx * z,
  3167. uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);
  3168. var uuvx = qy * uvz - qz * uvy,
  3169. uuvy = qz * uvx - qx * uvz,
  3170. uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);
  3171. var w2 = qw * 2;
  3172. uvx *= w2;
  3173. uvy *= w2;
  3174. uvz *= w2; // vec3.scale(uuv, uuv, 2);
  3175. uuvx *= 2;
  3176. uuvy *= 2;
  3177. uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));
  3178. out[0] = x + uvx + uuvx;
  3179. out[1] = y + uvy + uuvy;
  3180. out[2] = z + uvz + uuvz;
  3181. return out;
  3182. }
  3183. /**
  3184. * Rotate a 3D vector around the x-axis
  3185. * @param {vec3} out The receiving vec3
  3186. * @param {ReadonlyVec3} a The vec3 point to rotate
  3187. * @param {ReadonlyVec3} b The origin of the rotation
  3188. * @param {Number} rad The angle of rotation in radians
  3189. * @returns {vec3} out
  3190. */
  3191. function rotateX$2(out, a, b, rad) {
  3192. var p = [],
  3193. r = []; //Translate point to the origin
  3194. p[0] = a[0] - b[0];
  3195. p[1] = a[1] - b[1];
  3196. p[2] = a[2] - b[2]; //perform rotation
  3197. r[0] = p[0];
  3198. r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);
  3199. r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position
  3200. out[0] = r[0] + b[0];
  3201. out[1] = r[1] + b[1];
  3202. out[2] = r[2] + b[2];
  3203. return out;
  3204. }
  3205. /**
  3206. * Rotate a 3D vector around the y-axis
  3207. * @param {vec3} out The receiving vec3
  3208. * @param {ReadonlyVec3} a The vec3 point to rotate
  3209. * @param {ReadonlyVec3} b The origin of the rotation
  3210. * @param {Number} rad The angle of rotation in radians
  3211. * @returns {vec3} out
  3212. */
  3213. function rotateY$2(out, a, b, rad) {
  3214. var p = [],
  3215. r = []; //Translate point to the origin
  3216. p[0] = a[0] - b[0];
  3217. p[1] = a[1] - b[1];
  3218. p[2] = a[2] - b[2]; //perform rotation
  3219. r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);
  3220. r[1] = p[1];
  3221. r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position
  3222. out[0] = r[0] + b[0];
  3223. out[1] = r[1] + b[1];
  3224. out[2] = r[2] + b[2];
  3225. return out;
  3226. }
  3227. /**
  3228. * Rotate a 3D vector around the z-axis
  3229. * @param {vec3} out The receiving vec3
  3230. * @param {ReadonlyVec3} a The vec3 point to rotate
  3231. * @param {ReadonlyVec3} b The origin of the rotation
  3232. * @param {Number} rad The angle of rotation in radians
  3233. * @returns {vec3} out
  3234. */
  3235. function rotateZ$2(out, a, b, rad) {
  3236. var p = [],
  3237. r = []; //Translate point to the origin
  3238. p[0] = a[0] - b[0];
  3239. p[1] = a[1] - b[1];
  3240. p[2] = a[2] - b[2]; //perform rotation
  3241. r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);
  3242. r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);
  3243. r[2] = p[2]; //translate to correct position
  3244. out[0] = r[0] + b[0];
  3245. out[1] = r[1] + b[1];
  3246. out[2] = r[2] + b[2];
  3247. return out;
  3248. }
  3249. /**
  3250. * Get the angle between two 3D vectors
  3251. * @param {ReadonlyVec3} a The first operand
  3252. * @param {ReadonlyVec3} b The second operand
  3253. * @returns {Number} The angle in radians
  3254. */
  3255. function angle(a, b) {
  3256. var ax = a[0],
  3257. ay = a[1],
  3258. az = a[2],
  3259. bx = b[0],
  3260. by = b[1],
  3261. bz = b[2],
  3262. mag1 = Math.sqrt(ax * ax + ay * ay + az * az),
  3263. mag2 = Math.sqrt(bx * bx + by * by + bz * bz),
  3264. mag = mag1 * mag2,
  3265. cosine = mag && dot$2(a, b) / mag;
  3266. return Math.acos(Math.min(Math.max(cosine, -1), 1));
  3267. }
  3268. /**
  3269. * Alias for {@link vec3.length}
  3270. * @function
  3271. */
  3272. var len = length$2;
  3273. /**
  3274. * Perform some operation over an array of vec3s.
  3275. *
  3276. * @param {Array} a the array of vectors to iterate over
  3277. * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
  3278. * @param {Number} offset Number of elements to skip at the beginning of the array
  3279. * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
  3280. * @param {Function} fn Function to call for each vector in the array
  3281. * @param {Object} [arg] additional argument to pass to fn
  3282. * @returns {Array} a
  3283. * @function
  3284. */
  3285. (function () {
  3286. var vec = create$3();
  3287. return function (a, stride, offset, count, fn, arg) {
  3288. var i, l;
  3289. if (!stride) {
  3290. stride = 3;
  3291. }
  3292. if (!offset) {
  3293. offset = 0;
  3294. }
  3295. if (count) {
  3296. l = Math.min(count * stride + offset, a.length);
  3297. } else {
  3298. l = a.length;
  3299. }
  3300. for (i = offset; i < l; i += stride) {
  3301. vec[0] = a[i];
  3302. vec[1] = a[i + 1];
  3303. vec[2] = a[i + 2];
  3304. fn(vec, vec, arg);
  3305. a[i] = vec[0];
  3306. a[i + 1] = vec[1];
  3307. a[i + 2] = vec[2];
  3308. }
  3309. return a;
  3310. };
  3311. })();
  3312. const ORIGIN = [0, 0, 0];
  3313. const constants$2 = {};
  3314. class Vector3 extends Vector {
  3315. static get ZERO() {
  3316. return constants$2.ZERO = constants$2.ZERO || Object.freeze(new Vector3(0, 0, 0, 0));
  3317. }
  3318. constructor(x = 0, y = 0, z = 0) {
  3319. super(-0, -0, -0);
  3320. if (arguments.length === 1 && isArray(x)) {
  3321. this.copy(x);
  3322. } else {
  3323. if (config.debug) {
  3324. checkNumber(x);
  3325. checkNumber(y);
  3326. checkNumber(z);
  3327. }
  3328. this[0] = x;
  3329. this[1] = y;
  3330. this[2] = z;
  3331. }
  3332. }
  3333. set(x, y, z) {
  3334. this[0] = x;
  3335. this[1] = y;
  3336. this[2] = z;
  3337. return this.check();
  3338. }
  3339. copy(array) {
  3340. this[0] = array[0];
  3341. this[1] = array[1];
  3342. this[2] = array[2];
  3343. return this.check();
  3344. }
  3345. fromObject(object) {
  3346. if (config.debug) {
  3347. checkNumber(object.x);
  3348. checkNumber(object.y);
  3349. checkNumber(object.z);
  3350. }
  3351. this[0] = object.x;
  3352. this[1] = object.y;
  3353. this[2] = object.z;
  3354. return this.check();
  3355. }
  3356. toObject(object) {
  3357. object.x = this[0];
  3358. object.y = this[1];
  3359. object.z = this[2];
  3360. return object;
  3361. }
  3362. get ELEMENTS() {
  3363. return 3;
  3364. }
  3365. get z() {
  3366. return this[2];
  3367. }
  3368. set z(value) {
  3369. this[2] = checkNumber(value);
  3370. }
  3371. angle(vector) {
  3372. return angle(this, vector);
  3373. }
  3374. cross(vector) {
  3375. cross(this, this, vector);
  3376. return this.check();
  3377. }
  3378. rotateX({
  3379. radians,
  3380. origin = ORIGIN
  3381. }) {
  3382. rotateX$2(this, this, origin, radians);
  3383. return this.check();
  3384. }
  3385. rotateY({
  3386. radians,
  3387. origin = ORIGIN
  3388. }) {
  3389. rotateY$2(this, this, origin, radians);
  3390. return this.check();
  3391. }
  3392. rotateZ({
  3393. radians,
  3394. origin = ORIGIN
  3395. }) {
  3396. rotateZ$2(this, this, origin, radians);
  3397. return this.check();
  3398. }
  3399. transform(matrix4) {
  3400. return this.transformAsPoint(matrix4);
  3401. }
  3402. transformAsPoint(matrix4) {
  3403. transformMat4$1(this, this, matrix4);
  3404. return this.check();
  3405. }
  3406. transformAsVector(matrix4) {
  3407. vec3_transformMat4AsVector(this, this, matrix4);
  3408. return this.check();
  3409. }
  3410. transformByMatrix3(matrix3) {
  3411. transformMat3(this, this, matrix3);
  3412. return this.check();
  3413. }
  3414. transformByMatrix2(matrix2) {
  3415. vec3_transformMat2(this, this, matrix2);
  3416. return this.check();
  3417. }
  3418. transformByQuaternion(quaternion) {
  3419. transformQuat$1(this, this, quaternion);
  3420. return this.check();
  3421. }
  3422. }
  3423. class Matrix extends MathArray {
  3424. get ELEMENTS() {
  3425. assert$4(false);
  3426. return 0;
  3427. }
  3428. get RANK() {
  3429. assert$4(false);
  3430. return 0;
  3431. }
  3432. toString() {
  3433. let string = '[';
  3434. if (config.printRowMajor) {
  3435. string += 'row-major:';
  3436. for (let row = 0; row < this.RANK; ++row) {
  3437. for (let col = 0; col < this.RANK; ++col) {
  3438. string += " ".concat(this[col * this.RANK + row]);
  3439. }
  3440. }
  3441. } else {
  3442. string += 'column-major:';
  3443. for (let i = 0; i < this.ELEMENTS; ++i) {
  3444. string += " ".concat(this[i]);
  3445. }
  3446. }
  3447. string += ']';
  3448. return string;
  3449. }
  3450. getElementIndex(row, col) {
  3451. return col * this.RANK + row;
  3452. }
  3453. getElement(row, col) {
  3454. return this[col * this.RANK + row];
  3455. }
  3456. setElement(row, col, value) {
  3457. this[col * this.RANK + row] = checkNumber(value);
  3458. return this;
  3459. }
  3460. getColumn(columnIndex, result = new Array(this.RANK).fill(-0)) {
  3461. const firstIndex = columnIndex * this.RANK;
  3462. for (let i = 0; i < this.RANK; ++i) {
  3463. result[i] = this[firstIndex + i];
  3464. }
  3465. return result;
  3466. }
  3467. setColumn(columnIndex, columnVector) {
  3468. const firstIndex = columnIndex * this.RANK;
  3469. for (let i = 0; i < this.RANK; ++i) {
  3470. this[firstIndex + i] = columnVector[i];
  3471. }
  3472. return this;
  3473. }
  3474. }
  3475. /**
  3476. * 3x3 Matrix
  3477. * @module mat3
  3478. */
  3479. /**
  3480. * Creates a new identity mat3
  3481. *
  3482. * @returns {mat3} a new 3x3 matrix
  3483. */
  3484. function create$2() {
  3485. var out = new ARRAY_TYPE(9);
  3486. if (ARRAY_TYPE != Float32Array) {
  3487. out[1] = 0;
  3488. out[2] = 0;
  3489. out[3] = 0;
  3490. out[5] = 0;
  3491. out[6] = 0;
  3492. out[7] = 0;
  3493. }
  3494. out[0] = 1;
  3495. out[4] = 1;
  3496. out[8] = 1;
  3497. return out;
  3498. }
  3499. /**
  3500. * Transpose the values of a mat3
  3501. *
  3502. * @param {mat3} out the receiving matrix
  3503. * @param {ReadonlyMat3} a the source matrix
  3504. * @returns {mat3} out
  3505. */
  3506. function transpose$1(out, a) {
  3507. // If we are transposing ourselves we can skip a few steps but have to cache some values
  3508. if (out === a) {
  3509. var a01 = a[1],
  3510. a02 = a[2],
  3511. a12 = a[5];
  3512. out[1] = a[3];
  3513. out[2] = a[6];
  3514. out[3] = a01;
  3515. out[5] = a[7];
  3516. out[6] = a02;
  3517. out[7] = a12;
  3518. } else {
  3519. out[0] = a[0];
  3520. out[1] = a[3];
  3521. out[2] = a[6];
  3522. out[3] = a[1];
  3523. out[4] = a[4];
  3524. out[5] = a[7];
  3525. out[6] = a[2];
  3526. out[7] = a[5];
  3527. out[8] = a[8];
  3528. }
  3529. return out;
  3530. }
  3531. /**
  3532. * Inverts a mat3
  3533. *
  3534. * @param {mat3} out the receiving matrix
  3535. * @param {ReadonlyMat3} a the source matrix
  3536. * @returns {mat3} out
  3537. */
  3538. function invert$2(out, a) {
  3539. var a00 = a[0],
  3540. a01 = a[1],
  3541. a02 = a[2];
  3542. var a10 = a[3],
  3543. a11 = a[4],
  3544. a12 = a[5];
  3545. var a20 = a[6],
  3546. a21 = a[7],
  3547. a22 = a[8];
  3548. var b01 = a22 * a11 - a12 * a21;
  3549. var b11 = -a22 * a10 + a12 * a20;
  3550. var b21 = a21 * a10 - a11 * a20; // Calculate the determinant
  3551. var det = a00 * b01 + a01 * b11 + a02 * b21;
  3552. if (!det) {
  3553. return null;
  3554. }
  3555. det = 1.0 / det;
  3556. out[0] = b01 * det;
  3557. out[1] = (-a22 * a01 + a02 * a21) * det;
  3558. out[2] = (a12 * a01 - a02 * a11) * det;
  3559. out[3] = b11 * det;
  3560. out[4] = (a22 * a00 - a02 * a20) * det;
  3561. out[5] = (-a12 * a00 + a02 * a10) * det;
  3562. out[6] = b21 * det;
  3563. out[7] = (-a21 * a00 + a01 * a20) * det;
  3564. out[8] = (a11 * a00 - a01 * a10) * det;
  3565. return out;
  3566. }
  3567. /**
  3568. * Calculates the determinant of a mat3
  3569. *
  3570. * @param {ReadonlyMat3} a the source matrix
  3571. * @returns {Number} determinant of a
  3572. */
  3573. function determinant$1(a) {
  3574. var a00 = a[0],
  3575. a01 = a[1],
  3576. a02 = a[2];
  3577. var a10 = a[3],
  3578. a11 = a[4],
  3579. a12 = a[5];
  3580. var a20 = a[6],
  3581. a21 = a[7],
  3582. a22 = a[8];
  3583. return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
  3584. }
  3585. /**
  3586. * Multiplies two mat3's
  3587. *
  3588. * @param {mat3} out the receiving matrix
  3589. * @param {ReadonlyMat3} a the first operand
  3590. * @param {ReadonlyMat3} b the second operand
  3591. * @returns {mat3} out
  3592. */
  3593. function multiply$2(out, a, b) {
  3594. var a00 = a[0],
  3595. a01 = a[1],
  3596. a02 = a[2];
  3597. var a10 = a[3],
  3598. a11 = a[4],
  3599. a12 = a[5];
  3600. var a20 = a[6],
  3601. a21 = a[7],
  3602. a22 = a[8];
  3603. var b00 = b[0],
  3604. b01 = b[1],
  3605. b02 = b[2];
  3606. var b10 = b[3],
  3607. b11 = b[4],
  3608. b12 = b[5];
  3609. var b20 = b[6],
  3610. b21 = b[7],
  3611. b22 = b[8];
  3612. out[0] = b00 * a00 + b01 * a10 + b02 * a20;
  3613. out[1] = b00 * a01 + b01 * a11 + b02 * a21;
  3614. out[2] = b00 * a02 + b01 * a12 + b02 * a22;
  3615. out[3] = b10 * a00 + b11 * a10 + b12 * a20;
  3616. out[4] = b10 * a01 + b11 * a11 + b12 * a21;
  3617. out[5] = b10 * a02 + b11 * a12 + b12 * a22;
  3618. out[6] = b20 * a00 + b21 * a10 + b22 * a20;
  3619. out[7] = b20 * a01 + b21 * a11 + b22 * a21;
  3620. out[8] = b20 * a02 + b21 * a12 + b22 * a22;
  3621. return out;
  3622. }
  3623. /**
  3624. * Translate a mat3 by the given vector
  3625. *
  3626. * @param {mat3} out the receiving matrix
  3627. * @param {ReadonlyMat3} a the matrix to translate
  3628. * @param {ReadonlyVec2} v vector to translate by
  3629. * @returns {mat3} out
  3630. */
  3631. function translate$1(out, a, v) {
  3632. var a00 = a[0],
  3633. a01 = a[1],
  3634. a02 = a[2],
  3635. a10 = a[3],
  3636. a11 = a[4],
  3637. a12 = a[5],
  3638. a20 = a[6],
  3639. a21 = a[7],
  3640. a22 = a[8],
  3641. x = v[0],
  3642. y = v[1];
  3643. out[0] = a00;
  3644. out[1] = a01;
  3645. out[2] = a02;
  3646. out[3] = a10;
  3647. out[4] = a11;
  3648. out[5] = a12;
  3649. out[6] = x * a00 + y * a10 + a20;
  3650. out[7] = x * a01 + y * a11 + a21;
  3651. out[8] = x * a02 + y * a12 + a22;
  3652. return out;
  3653. }
  3654. /**
  3655. * Rotates a mat3 by the given angle
  3656. *
  3657. * @param {mat3} out the receiving matrix
  3658. * @param {ReadonlyMat3} a the matrix to rotate
  3659. * @param {Number} rad the angle to rotate the matrix by
  3660. * @returns {mat3} out
  3661. */
  3662. function rotate$1(out, a, rad) {
  3663. var a00 = a[0],
  3664. a01 = a[1],
  3665. a02 = a[2],
  3666. a10 = a[3],
  3667. a11 = a[4],
  3668. a12 = a[5],
  3669. a20 = a[6],
  3670. a21 = a[7],
  3671. a22 = a[8],
  3672. s = Math.sin(rad),
  3673. c = Math.cos(rad);
  3674. out[0] = c * a00 + s * a10;
  3675. out[1] = c * a01 + s * a11;
  3676. out[2] = c * a02 + s * a12;
  3677. out[3] = c * a10 - s * a00;
  3678. out[4] = c * a11 - s * a01;
  3679. out[5] = c * a12 - s * a02;
  3680. out[6] = a20;
  3681. out[7] = a21;
  3682. out[8] = a22;
  3683. return out;
  3684. }
  3685. /**
  3686. * Scales the mat3 by the dimensions in the given vec2
  3687. *
  3688. * @param {mat3} out the receiving matrix
  3689. * @param {ReadonlyMat3} a the matrix to rotate
  3690. * @param {ReadonlyVec2} v the vec2 to scale the matrix by
  3691. * @returns {mat3} out
  3692. **/
  3693. function scale$3(out, a, v) {
  3694. var x = v[0],
  3695. y = v[1];
  3696. out[0] = x * a[0];
  3697. out[1] = x * a[1];
  3698. out[2] = x * a[2];
  3699. out[3] = y * a[3];
  3700. out[4] = y * a[4];
  3701. out[5] = y * a[5];
  3702. out[6] = a[6];
  3703. out[7] = a[7];
  3704. out[8] = a[8];
  3705. return out;
  3706. }
  3707. /**
  3708. * Calculates a 3x3 matrix from the given quaternion
  3709. *
  3710. * @param {mat3} out mat3 receiving operation result
  3711. * @param {ReadonlyQuat} q Quaternion to create matrix from
  3712. *
  3713. * @returns {mat3} out
  3714. */
  3715. function fromQuat$1(out, q) {
  3716. var x = q[0],
  3717. y = q[1],
  3718. z = q[2],
  3719. w = q[3];
  3720. var x2 = x + x;
  3721. var y2 = y + y;
  3722. var z2 = z + z;
  3723. var xx = x * x2;
  3724. var yx = y * x2;
  3725. var yy = y * y2;
  3726. var zx = z * x2;
  3727. var zy = z * y2;
  3728. var zz = z * z2;
  3729. var wx = w * x2;
  3730. var wy = w * y2;
  3731. var wz = w * z2;
  3732. out[0] = 1 - yy - zz;
  3733. out[3] = yx - wz;
  3734. out[6] = zx + wy;
  3735. out[1] = yx + wz;
  3736. out[4] = 1 - xx - zz;
  3737. out[7] = zy - wx;
  3738. out[2] = zx - wy;
  3739. out[5] = zy + wx;
  3740. out[8] = 1 - xx - yy;
  3741. return out;
  3742. }
  3743. const IDENTITY$1 = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1]);
  3744. const ZERO$1 = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0]);
  3745. const INDICES$1 = Object.freeze({
  3746. COL0ROW0: 0,
  3747. COL0ROW1: 1,
  3748. COL0ROW2: 2,
  3749. COL1ROW0: 3,
  3750. COL1ROW1: 4,
  3751. COL1ROW2: 5,
  3752. COL2ROW0: 6,
  3753. COL2ROW1: 7,
  3754. COL2ROW2: 8
  3755. });
  3756. const constants$1 = {};
  3757. class Matrix3 extends Matrix {
  3758. static get IDENTITY() {
  3759. constants$1.IDENTITY = constants$1.IDENTITY || Object.freeze(new Matrix3(IDENTITY$1));
  3760. return constants$1.IDENTITY;
  3761. }
  3762. static get ZERO() {
  3763. constants$1.ZERO = constants$1.ZERO || Object.freeze(new Matrix3(ZERO$1));
  3764. return constants$1.ZERO;
  3765. }
  3766. get ELEMENTS() {
  3767. return 9;
  3768. }
  3769. get RANK() {
  3770. return 3;
  3771. }
  3772. get INDICES() {
  3773. return INDICES$1;
  3774. }
  3775. constructor(array) {
  3776. super(-0, -0, -0, -0, -0, -0, -0, -0, -0);
  3777. if (arguments.length === 1 && Array.isArray(array)) {
  3778. this.copy(array);
  3779. } else {
  3780. this.identity();
  3781. }
  3782. }
  3783. copy(array) {
  3784. this[0] = array[0];
  3785. this[1] = array[1];
  3786. this[2] = array[2];
  3787. this[3] = array[3];
  3788. this[4] = array[4];
  3789. this[5] = array[5];
  3790. this[6] = array[6];
  3791. this[7] = array[7];
  3792. this[8] = array[8];
  3793. return this.check();
  3794. }
  3795. set(m00, m10, m20, m01, m11, m21, m02, m12, m22) {
  3796. this[0] = m00;
  3797. this[1] = m10;
  3798. this[2] = m20;
  3799. this[3] = m01;
  3800. this[4] = m11;
  3801. this[5] = m21;
  3802. this[6] = m02;
  3803. this[7] = m12;
  3804. this[8] = m22;
  3805. return this.check();
  3806. }
  3807. setRowMajor(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
  3808. this[0] = m00;
  3809. this[1] = m10;
  3810. this[2] = m20;
  3811. this[3] = m01;
  3812. this[4] = m11;
  3813. this[5] = m21;
  3814. this[6] = m02;
  3815. this[7] = m12;
  3816. this[8] = m22;
  3817. return this.check();
  3818. }
  3819. determinant() {
  3820. return determinant$1(this);
  3821. }
  3822. identity() {
  3823. return this.copy(IDENTITY$1);
  3824. }
  3825. fromQuaternion(q) {
  3826. fromQuat$1(this, q);
  3827. return this.check();
  3828. }
  3829. transpose() {
  3830. transpose$1(this, this);
  3831. return this.check();
  3832. }
  3833. invert() {
  3834. invert$2(this, this);
  3835. return this.check();
  3836. }
  3837. multiplyLeft(a) {
  3838. multiply$2(this, a, this);
  3839. return this.check();
  3840. }
  3841. multiplyRight(a) {
  3842. multiply$2(this, this, a);
  3843. return this.check();
  3844. }
  3845. rotate(radians) {
  3846. rotate$1(this, this, radians);
  3847. return this.check();
  3848. }
  3849. scale(factor) {
  3850. if (Array.isArray(factor)) {
  3851. scale$3(this, this, factor);
  3852. } else {
  3853. scale$3(this, this, [factor, factor, factor]);
  3854. }
  3855. return this.check();
  3856. }
  3857. translate(vec) {
  3858. translate$1(this, this, vec);
  3859. return this.check();
  3860. }
  3861. transform(vector, result) {
  3862. switch (vector.length) {
  3863. case 2:
  3864. result = transformMat3$1(result || [-0, -0], vector, this);
  3865. break;
  3866. case 3:
  3867. result = transformMat3(result || [-0, -0, -0], vector, this);
  3868. break;
  3869. case 4:
  3870. result = vec4_transformMat3(result || [-0, -0, -0, -0], vector, this);
  3871. break;
  3872. default:
  3873. throw new Error('Illegal vector');
  3874. }
  3875. checkVector(result, vector.length);
  3876. return result;
  3877. }
  3878. transformVector(vector, result) {
  3879. deprecated('Matrix3.transformVector');
  3880. return this.transform(vector, result);
  3881. }
  3882. transformVector2(vector, result) {
  3883. deprecated('Matrix3.transformVector');
  3884. return this.transform(vector, result);
  3885. }
  3886. transformVector3(vector, result) {
  3887. deprecated('Matrix3.transformVector');
  3888. return this.transform(vector, result);
  3889. }
  3890. }
  3891. /**
  3892. * Set a mat4 to the identity matrix
  3893. *
  3894. * @param {mat4} out the receiving matrix
  3895. * @returns {mat4} out
  3896. */
  3897. function identity$1(out) {
  3898. out[0] = 1;
  3899. out[1] = 0;
  3900. out[2] = 0;
  3901. out[3] = 0;
  3902. out[4] = 0;
  3903. out[5] = 1;
  3904. out[6] = 0;
  3905. out[7] = 0;
  3906. out[8] = 0;
  3907. out[9] = 0;
  3908. out[10] = 1;
  3909. out[11] = 0;
  3910. out[12] = 0;
  3911. out[13] = 0;
  3912. out[14] = 0;
  3913. out[15] = 1;
  3914. return out;
  3915. }
  3916. /**
  3917. * Transpose the values of a mat4
  3918. *
  3919. * @param {mat4} out the receiving matrix
  3920. * @param {ReadonlyMat4} a the source matrix
  3921. * @returns {mat4} out
  3922. */
  3923. function transpose(out, a) {
  3924. // If we are transposing ourselves we can skip a few steps but have to cache some values
  3925. if (out === a) {
  3926. var a01 = a[1],
  3927. a02 = a[2],
  3928. a03 = a[3];
  3929. var a12 = a[6],
  3930. a13 = a[7];
  3931. var a23 = a[11];
  3932. out[1] = a[4];
  3933. out[2] = a[8];
  3934. out[3] = a[12];
  3935. out[4] = a01;
  3936. out[6] = a[9];
  3937. out[7] = a[13];
  3938. out[8] = a02;
  3939. out[9] = a12;
  3940. out[11] = a[14];
  3941. out[12] = a03;
  3942. out[13] = a13;
  3943. out[14] = a23;
  3944. } else {
  3945. out[0] = a[0];
  3946. out[1] = a[4];
  3947. out[2] = a[8];
  3948. out[3] = a[12];
  3949. out[4] = a[1];
  3950. out[5] = a[5];
  3951. out[6] = a[9];
  3952. out[7] = a[13];
  3953. out[8] = a[2];
  3954. out[9] = a[6];
  3955. out[10] = a[10];
  3956. out[11] = a[14];
  3957. out[12] = a[3];
  3958. out[13] = a[7];
  3959. out[14] = a[11];
  3960. out[15] = a[15];
  3961. }
  3962. return out;
  3963. }
  3964. /**
  3965. * Inverts a mat4
  3966. *
  3967. * @param {mat4} out the receiving matrix
  3968. * @param {ReadonlyMat4} a the source matrix
  3969. * @returns {mat4} out
  3970. */
  3971. function invert$1(out, a) {
  3972. var a00 = a[0],
  3973. a01 = a[1],
  3974. a02 = a[2],
  3975. a03 = a[3];
  3976. var a10 = a[4],
  3977. a11 = a[5],
  3978. a12 = a[6],
  3979. a13 = a[7];
  3980. var a20 = a[8],
  3981. a21 = a[9],
  3982. a22 = a[10],
  3983. a23 = a[11];
  3984. var a30 = a[12],
  3985. a31 = a[13],
  3986. a32 = a[14],
  3987. a33 = a[15];
  3988. var b00 = a00 * a11 - a01 * a10;
  3989. var b01 = a00 * a12 - a02 * a10;
  3990. var b02 = a00 * a13 - a03 * a10;
  3991. var b03 = a01 * a12 - a02 * a11;
  3992. var b04 = a01 * a13 - a03 * a11;
  3993. var b05 = a02 * a13 - a03 * a12;
  3994. var b06 = a20 * a31 - a21 * a30;
  3995. var b07 = a20 * a32 - a22 * a30;
  3996. var b08 = a20 * a33 - a23 * a30;
  3997. var b09 = a21 * a32 - a22 * a31;
  3998. var b10 = a21 * a33 - a23 * a31;
  3999. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  4000. var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  4001. if (!det) {
  4002. return null;
  4003. }
  4004. det = 1.0 / det;
  4005. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  4006. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  4007. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  4008. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  4009. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  4010. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  4011. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  4012. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  4013. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  4014. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  4015. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  4016. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  4017. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  4018. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  4019. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  4020. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  4021. return out;
  4022. }
  4023. /**
  4024. * Calculates the determinant of a mat4
  4025. *
  4026. * @param {ReadonlyMat4} a the source matrix
  4027. * @returns {Number} determinant of a
  4028. */
  4029. function determinant(a) {
  4030. var a00 = a[0],
  4031. a01 = a[1],
  4032. a02 = a[2],
  4033. a03 = a[3];
  4034. var a10 = a[4],
  4035. a11 = a[5],
  4036. a12 = a[6],
  4037. a13 = a[7];
  4038. var a20 = a[8],
  4039. a21 = a[9],
  4040. a22 = a[10],
  4041. a23 = a[11];
  4042. var a30 = a[12],
  4043. a31 = a[13],
  4044. a32 = a[14],
  4045. a33 = a[15];
  4046. var b00 = a00 * a11 - a01 * a10;
  4047. var b01 = a00 * a12 - a02 * a10;
  4048. var b02 = a00 * a13 - a03 * a10;
  4049. var b03 = a01 * a12 - a02 * a11;
  4050. var b04 = a01 * a13 - a03 * a11;
  4051. var b05 = a02 * a13 - a03 * a12;
  4052. var b06 = a20 * a31 - a21 * a30;
  4053. var b07 = a20 * a32 - a22 * a30;
  4054. var b08 = a20 * a33 - a23 * a30;
  4055. var b09 = a21 * a32 - a22 * a31;
  4056. var b10 = a21 * a33 - a23 * a31;
  4057. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  4058. return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  4059. }
  4060. /**
  4061. * Multiplies two mat4s
  4062. *
  4063. * @param {mat4} out the receiving matrix
  4064. * @param {ReadonlyMat4} a the first operand
  4065. * @param {ReadonlyMat4} b the second operand
  4066. * @returns {mat4} out
  4067. */
  4068. function multiply$1(out, a, b) {
  4069. var a00 = a[0],
  4070. a01 = a[1],
  4071. a02 = a[2],
  4072. a03 = a[3];
  4073. var a10 = a[4],
  4074. a11 = a[5],
  4075. a12 = a[6],
  4076. a13 = a[7];
  4077. var a20 = a[8],
  4078. a21 = a[9],
  4079. a22 = a[10],
  4080. a23 = a[11];
  4081. var a30 = a[12],
  4082. a31 = a[13],
  4083. a32 = a[14],
  4084. a33 = a[15]; // Cache only the current line of the second matrix
  4085. var b0 = b[0],
  4086. b1 = b[1],
  4087. b2 = b[2],
  4088. b3 = b[3];
  4089. out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4090. out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4091. out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4092. out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4093. b0 = b[4];
  4094. b1 = b[5];
  4095. b2 = b[6];
  4096. b3 = b[7];
  4097. out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4098. out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4099. out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4100. out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4101. b0 = b[8];
  4102. b1 = b[9];
  4103. b2 = b[10];
  4104. b3 = b[11];
  4105. out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4106. out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4107. out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4108. out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4109. b0 = b[12];
  4110. b1 = b[13];
  4111. b2 = b[14];
  4112. b3 = b[15];
  4113. out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4114. out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4115. out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4116. out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4117. return out;
  4118. }
  4119. /**
  4120. * Translate a mat4 by the given vector
  4121. *
  4122. * @param {mat4} out the receiving matrix
  4123. * @param {ReadonlyMat4} a the matrix to translate
  4124. * @param {ReadonlyVec3} v vector to translate by
  4125. * @returns {mat4} out
  4126. */
  4127. function translate(out, a, v) {
  4128. var x = v[0],
  4129. y = v[1],
  4130. z = v[2];
  4131. var a00, a01, a02, a03;
  4132. var a10, a11, a12, a13;
  4133. var a20, a21, a22, a23;
  4134. if (a === out) {
  4135. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  4136. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  4137. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  4138. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  4139. } else {
  4140. a00 = a[0];
  4141. a01 = a[1];
  4142. a02 = a[2];
  4143. a03 = a[3];
  4144. a10 = a[4];
  4145. a11 = a[5];
  4146. a12 = a[6];
  4147. a13 = a[7];
  4148. a20 = a[8];
  4149. a21 = a[9];
  4150. a22 = a[10];
  4151. a23 = a[11];
  4152. out[0] = a00;
  4153. out[1] = a01;
  4154. out[2] = a02;
  4155. out[3] = a03;
  4156. out[4] = a10;
  4157. out[5] = a11;
  4158. out[6] = a12;
  4159. out[7] = a13;
  4160. out[8] = a20;
  4161. out[9] = a21;
  4162. out[10] = a22;
  4163. out[11] = a23;
  4164. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  4165. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  4166. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  4167. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  4168. }
  4169. return out;
  4170. }
  4171. /**
  4172. * Scales the mat4 by the dimensions in the given vec3 not using vectorization
  4173. *
  4174. * @param {mat4} out the receiving matrix
  4175. * @param {ReadonlyMat4} a the matrix to scale
  4176. * @param {ReadonlyVec3} v the vec3 to scale the matrix by
  4177. * @returns {mat4} out
  4178. **/
  4179. function scale$2(out, a, v) {
  4180. var x = v[0],
  4181. y = v[1],
  4182. z = v[2];
  4183. out[0] = a[0] * x;
  4184. out[1] = a[1] * x;
  4185. out[2] = a[2] * x;
  4186. out[3] = a[3] * x;
  4187. out[4] = a[4] * y;
  4188. out[5] = a[5] * y;
  4189. out[6] = a[6] * y;
  4190. out[7] = a[7] * y;
  4191. out[8] = a[8] * z;
  4192. out[9] = a[9] * z;
  4193. out[10] = a[10] * z;
  4194. out[11] = a[11] * z;
  4195. out[12] = a[12];
  4196. out[13] = a[13];
  4197. out[14] = a[14];
  4198. out[15] = a[15];
  4199. return out;
  4200. }
  4201. /**
  4202. * Rotates a mat4 by the given angle around the given axis
  4203. *
  4204. * @param {mat4} out the receiving matrix
  4205. * @param {ReadonlyMat4} a the matrix to rotate
  4206. * @param {Number} rad the angle to rotate the matrix by
  4207. * @param {ReadonlyVec3} axis the axis to rotate around
  4208. * @returns {mat4} out
  4209. */
  4210. function rotate(out, a, rad, axis) {
  4211. var x = axis[0],
  4212. y = axis[1],
  4213. z = axis[2];
  4214. var len = Math.hypot(x, y, z);
  4215. var s, c, t;
  4216. var a00, a01, a02, a03;
  4217. var a10, a11, a12, a13;
  4218. var a20, a21, a22, a23;
  4219. var b00, b01, b02;
  4220. var b10, b11, b12;
  4221. var b20, b21, b22;
  4222. if (len < EPSILON) {
  4223. return null;
  4224. }
  4225. len = 1 / len;
  4226. x *= len;
  4227. y *= len;
  4228. z *= len;
  4229. s = Math.sin(rad);
  4230. c = Math.cos(rad);
  4231. t = 1 - c;
  4232. a00 = a[0];
  4233. a01 = a[1];
  4234. a02 = a[2];
  4235. a03 = a[3];
  4236. a10 = a[4];
  4237. a11 = a[5];
  4238. a12 = a[6];
  4239. a13 = a[7];
  4240. a20 = a[8];
  4241. a21 = a[9];
  4242. a22 = a[10];
  4243. a23 = a[11]; // Construct the elements of the rotation matrix
  4244. b00 = x * x * t + c;
  4245. b01 = y * x * t + z * s;
  4246. b02 = z * x * t - y * s;
  4247. b10 = x * y * t - z * s;
  4248. b11 = y * y * t + c;
  4249. b12 = z * y * t + x * s;
  4250. b20 = x * z * t + y * s;
  4251. b21 = y * z * t - x * s;
  4252. b22 = z * z * t + c; // Perform rotation-specific matrix multiplication
  4253. out[0] = a00 * b00 + a10 * b01 + a20 * b02;
  4254. out[1] = a01 * b00 + a11 * b01 + a21 * b02;
  4255. out[2] = a02 * b00 + a12 * b01 + a22 * b02;
  4256. out[3] = a03 * b00 + a13 * b01 + a23 * b02;
  4257. out[4] = a00 * b10 + a10 * b11 + a20 * b12;
  4258. out[5] = a01 * b10 + a11 * b11 + a21 * b12;
  4259. out[6] = a02 * b10 + a12 * b11 + a22 * b12;
  4260. out[7] = a03 * b10 + a13 * b11 + a23 * b12;
  4261. out[8] = a00 * b20 + a10 * b21 + a20 * b22;
  4262. out[9] = a01 * b20 + a11 * b21 + a21 * b22;
  4263. out[10] = a02 * b20 + a12 * b21 + a22 * b22;
  4264. out[11] = a03 * b20 + a13 * b21 + a23 * b22;
  4265. if (a !== out) {
  4266. // If the source and destination differ, copy the unchanged last row
  4267. out[12] = a[12];
  4268. out[13] = a[13];
  4269. out[14] = a[14];
  4270. out[15] = a[15];
  4271. }
  4272. return out;
  4273. }
  4274. /**
  4275. * Rotates a matrix by the given angle around the X axis
  4276. *
  4277. * @param {mat4} out the receiving matrix
  4278. * @param {ReadonlyMat4} a the matrix to rotate
  4279. * @param {Number} rad the angle to rotate the matrix by
  4280. * @returns {mat4} out
  4281. */
  4282. function rotateX$1(out, a, rad) {
  4283. var s = Math.sin(rad);
  4284. var c = Math.cos(rad);
  4285. var a10 = a[4];
  4286. var a11 = a[5];
  4287. var a12 = a[6];
  4288. var a13 = a[7];
  4289. var a20 = a[8];
  4290. var a21 = a[9];
  4291. var a22 = a[10];
  4292. var a23 = a[11];
  4293. if (a !== out) {
  4294. // If the source and destination differ, copy the unchanged rows
  4295. out[0] = a[0];
  4296. out[1] = a[1];
  4297. out[2] = a[2];
  4298. out[3] = a[3];
  4299. out[12] = a[12];
  4300. out[13] = a[13];
  4301. out[14] = a[14];
  4302. out[15] = a[15];
  4303. } // Perform axis-specific matrix multiplication
  4304. out[4] = a10 * c + a20 * s;
  4305. out[5] = a11 * c + a21 * s;
  4306. out[6] = a12 * c + a22 * s;
  4307. out[7] = a13 * c + a23 * s;
  4308. out[8] = a20 * c - a10 * s;
  4309. out[9] = a21 * c - a11 * s;
  4310. out[10] = a22 * c - a12 * s;
  4311. out[11] = a23 * c - a13 * s;
  4312. return out;
  4313. }
  4314. /**
  4315. * Rotates a matrix by the given angle around the Y axis
  4316. *
  4317. * @param {mat4} out the receiving matrix
  4318. * @param {ReadonlyMat4} a the matrix to rotate
  4319. * @param {Number} rad the angle to rotate the matrix by
  4320. * @returns {mat4} out
  4321. */
  4322. function rotateY$1(out, a, rad) {
  4323. var s = Math.sin(rad);
  4324. var c = Math.cos(rad);
  4325. var a00 = a[0];
  4326. var a01 = a[1];
  4327. var a02 = a[2];
  4328. var a03 = a[3];
  4329. var a20 = a[8];
  4330. var a21 = a[9];
  4331. var a22 = a[10];
  4332. var a23 = a[11];
  4333. if (a !== out) {
  4334. // If the source and destination differ, copy the unchanged rows
  4335. out[4] = a[4];
  4336. out[5] = a[5];
  4337. out[6] = a[6];
  4338. out[7] = a[7];
  4339. out[12] = a[12];
  4340. out[13] = a[13];
  4341. out[14] = a[14];
  4342. out[15] = a[15];
  4343. } // Perform axis-specific matrix multiplication
  4344. out[0] = a00 * c - a20 * s;
  4345. out[1] = a01 * c - a21 * s;
  4346. out[2] = a02 * c - a22 * s;
  4347. out[3] = a03 * c - a23 * s;
  4348. out[8] = a00 * s + a20 * c;
  4349. out[9] = a01 * s + a21 * c;
  4350. out[10] = a02 * s + a22 * c;
  4351. out[11] = a03 * s + a23 * c;
  4352. return out;
  4353. }
  4354. /**
  4355. * Rotates a matrix by the given angle around the Z axis
  4356. *
  4357. * @param {mat4} out the receiving matrix
  4358. * @param {ReadonlyMat4} a the matrix to rotate
  4359. * @param {Number} rad the angle to rotate the matrix by
  4360. * @returns {mat4} out
  4361. */
  4362. function rotateZ$1(out, a, rad) {
  4363. var s = Math.sin(rad);
  4364. var c = Math.cos(rad);
  4365. var a00 = a[0];
  4366. var a01 = a[1];
  4367. var a02 = a[2];
  4368. var a03 = a[3];
  4369. var a10 = a[4];
  4370. var a11 = a[5];
  4371. var a12 = a[6];
  4372. var a13 = a[7];
  4373. if (a !== out) {
  4374. // If the source and destination differ, copy the unchanged last row
  4375. out[8] = a[8];
  4376. out[9] = a[9];
  4377. out[10] = a[10];
  4378. out[11] = a[11];
  4379. out[12] = a[12];
  4380. out[13] = a[13];
  4381. out[14] = a[14];
  4382. out[15] = a[15];
  4383. } // Perform axis-specific matrix multiplication
  4384. out[0] = a00 * c + a10 * s;
  4385. out[1] = a01 * c + a11 * s;
  4386. out[2] = a02 * c + a12 * s;
  4387. out[3] = a03 * c + a13 * s;
  4388. out[4] = a10 * c - a00 * s;
  4389. out[5] = a11 * c - a01 * s;
  4390. out[6] = a12 * c - a02 * s;
  4391. out[7] = a13 * c - a03 * s;
  4392. return out;
  4393. }
  4394. /**
  4395. * Returns the scaling factor component of a transformation
  4396. * matrix. If a matrix is built with fromRotationTranslationScale
  4397. * with a normalized Quaternion paramter, the returned vector will be
  4398. * the same as the scaling vector
  4399. * originally supplied.
  4400. * @param {vec3} out Vector to receive scaling factor component
  4401. * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
  4402. * @return {vec3} out
  4403. */
  4404. function getScaling(out, mat) {
  4405. var m11 = mat[0];
  4406. var m12 = mat[1];
  4407. var m13 = mat[2];
  4408. var m21 = mat[4];
  4409. var m22 = mat[5];
  4410. var m23 = mat[6];
  4411. var m31 = mat[8];
  4412. var m32 = mat[9];
  4413. var m33 = mat[10];
  4414. out[0] = Math.hypot(m11, m12, m13);
  4415. out[1] = Math.hypot(m21, m22, m23);
  4416. out[2] = Math.hypot(m31, m32, m33);
  4417. return out;
  4418. }
  4419. /**
  4420. * Calculates a 4x4 matrix from the given quaternion
  4421. *
  4422. * @param {mat4} out mat4 receiving operation result
  4423. * @param {ReadonlyQuat} q Quaternion to create matrix from
  4424. *
  4425. * @returns {mat4} out
  4426. */
  4427. function fromQuat(out, q) {
  4428. var x = q[0],
  4429. y = q[1],
  4430. z = q[2],
  4431. w = q[3];
  4432. var x2 = x + x;
  4433. var y2 = y + y;
  4434. var z2 = z + z;
  4435. var xx = x * x2;
  4436. var yx = y * x2;
  4437. var yy = y * y2;
  4438. var zx = z * x2;
  4439. var zy = z * y2;
  4440. var zz = z * z2;
  4441. var wx = w * x2;
  4442. var wy = w * y2;
  4443. var wz = w * z2;
  4444. out[0] = 1 - yy - zz;
  4445. out[1] = yx + wz;
  4446. out[2] = zx - wy;
  4447. out[3] = 0;
  4448. out[4] = yx - wz;
  4449. out[5] = 1 - xx - zz;
  4450. out[6] = zy + wx;
  4451. out[7] = 0;
  4452. out[8] = zx + wy;
  4453. out[9] = zy - wx;
  4454. out[10] = 1 - xx - yy;
  4455. out[11] = 0;
  4456. out[12] = 0;
  4457. out[13] = 0;
  4458. out[14] = 0;
  4459. out[15] = 1;
  4460. return out;
  4461. }
  4462. /**
  4463. * Generates a frustum matrix with the given bounds
  4464. *
  4465. * @param {mat4} out mat4 frustum matrix will be written into
  4466. * @param {Number} left Left bound of the frustum
  4467. * @param {Number} right Right bound of the frustum
  4468. * @param {Number} bottom Bottom bound of the frustum
  4469. * @param {Number} top Top bound of the frustum
  4470. * @param {Number} near Near bound of the frustum
  4471. * @param {Number} far Far bound of the frustum
  4472. * @returns {mat4} out
  4473. */
  4474. function frustum(out, left, right, bottom, top, near, far) {
  4475. var rl = 1 / (right - left);
  4476. var tb = 1 / (top - bottom);
  4477. var nf = 1 / (near - far);
  4478. out[0] = near * 2 * rl;
  4479. out[1] = 0;
  4480. out[2] = 0;
  4481. out[3] = 0;
  4482. out[4] = 0;
  4483. out[5] = near * 2 * tb;
  4484. out[6] = 0;
  4485. out[7] = 0;
  4486. out[8] = (right + left) * rl;
  4487. out[9] = (top + bottom) * tb;
  4488. out[10] = (far + near) * nf;
  4489. out[11] = -1;
  4490. out[12] = 0;
  4491. out[13] = 0;
  4492. out[14] = far * near * 2 * nf;
  4493. out[15] = 0;
  4494. return out;
  4495. }
  4496. /**
  4497. * Generates a perspective projection matrix with the given bounds.
  4498. * Passing null/undefined/no value for far will generate infinite projection matrix.
  4499. *
  4500. * @param {mat4} out mat4 frustum matrix will be written into
  4501. * @param {number} fovy Vertical field of view in radians
  4502. * @param {number} aspect Aspect ratio. typically viewport width/height
  4503. * @param {number} near Near bound of the frustum
  4504. * @param {number} far Far bound of the frustum, can be null or Infinity
  4505. * @returns {mat4} out
  4506. */
  4507. function perspective(out, fovy, aspect, near, far) {
  4508. var f = 1.0 / Math.tan(fovy / 2),
  4509. nf;
  4510. out[0] = f / aspect;
  4511. out[1] = 0;
  4512. out[2] = 0;
  4513. out[3] = 0;
  4514. out[4] = 0;
  4515. out[5] = f;
  4516. out[6] = 0;
  4517. out[7] = 0;
  4518. out[8] = 0;
  4519. out[9] = 0;
  4520. out[11] = -1;
  4521. out[12] = 0;
  4522. out[13] = 0;
  4523. out[15] = 0;
  4524. if (far != null && far !== Infinity) {
  4525. nf = 1 / (near - far);
  4526. out[10] = (far + near) * nf;
  4527. out[14] = 2 * far * near * nf;
  4528. } else {
  4529. out[10] = -1;
  4530. out[14] = -2 * near;
  4531. }
  4532. return out;
  4533. }
  4534. /**
  4535. * Generates a orthogonal projection matrix with the given bounds
  4536. *
  4537. * @param {mat4} out mat4 frustum matrix will be written into
  4538. * @param {number} left Left bound of the frustum
  4539. * @param {number} right Right bound of the frustum
  4540. * @param {number} bottom Bottom bound of the frustum
  4541. * @param {number} top Top bound of the frustum
  4542. * @param {number} near Near bound of the frustum
  4543. * @param {number} far Far bound of the frustum
  4544. * @returns {mat4} out
  4545. */
  4546. function ortho(out, left, right, bottom, top, near, far) {
  4547. var lr = 1 / (left - right);
  4548. var bt = 1 / (bottom - top);
  4549. var nf = 1 / (near - far);
  4550. out[0] = -2 * lr;
  4551. out[1] = 0;
  4552. out[2] = 0;
  4553. out[3] = 0;
  4554. out[4] = 0;
  4555. out[5] = -2 * bt;
  4556. out[6] = 0;
  4557. out[7] = 0;
  4558. out[8] = 0;
  4559. out[9] = 0;
  4560. out[10] = 2 * nf;
  4561. out[11] = 0;
  4562. out[12] = (left + right) * lr;
  4563. out[13] = (top + bottom) * bt;
  4564. out[14] = (far + near) * nf;
  4565. out[15] = 1;
  4566. return out;
  4567. }
  4568. /**
  4569. * Generates a look-at matrix with the given eye position, focal point, and up axis.
  4570. * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
  4571. *
  4572. * @param {mat4} out mat4 frustum matrix will be written into
  4573. * @param {ReadonlyVec3} eye Position of the viewer
  4574. * @param {ReadonlyVec3} center Point the viewer is looking at
  4575. * @param {ReadonlyVec3} up vec3 pointing up
  4576. * @returns {mat4} out
  4577. */
  4578. function lookAt(out, eye, center, up) {
  4579. var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
  4580. var eyex = eye[0];
  4581. var eyey = eye[1];
  4582. var eyez = eye[2];
  4583. var upx = up[0];
  4584. var upy = up[1];
  4585. var upz = up[2];
  4586. var centerx = center[0];
  4587. var centery = center[1];
  4588. var centerz = center[2];
  4589. if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) {
  4590. return identity$1(out);
  4591. }
  4592. z0 = eyex - centerx;
  4593. z1 = eyey - centery;
  4594. z2 = eyez - centerz;
  4595. len = 1 / Math.hypot(z0, z1, z2);
  4596. z0 *= len;
  4597. z1 *= len;
  4598. z2 *= len;
  4599. x0 = upy * z2 - upz * z1;
  4600. x1 = upz * z0 - upx * z2;
  4601. x2 = upx * z1 - upy * z0;
  4602. len = Math.hypot(x0, x1, x2);
  4603. if (!len) {
  4604. x0 = 0;
  4605. x1 = 0;
  4606. x2 = 0;
  4607. } else {
  4608. len = 1 / len;
  4609. x0 *= len;
  4610. x1 *= len;
  4611. x2 *= len;
  4612. }
  4613. y0 = z1 * x2 - z2 * x1;
  4614. y1 = z2 * x0 - z0 * x2;
  4615. y2 = z0 * x1 - z1 * x0;
  4616. len = Math.hypot(y0, y1, y2);
  4617. if (!len) {
  4618. y0 = 0;
  4619. y1 = 0;
  4620. y2 = 0;
  4621. } else {
  4622. len = 1 / len;
  4623. y0 *= len;
  4624. y1 *= len;
  4625. y2 *= len;
  4626. }
  4627. out[0] = x0;
  4628. out[1] = y0;
  4629. out[2] = z0;
  4630. out[3] = 0;
  4631. out[4] = x1;
  4632. out[5] = y1;
  4633. out[6] = z1;
  4634. out[7] = 0;
  4635. out[8] = x2;
  4636. out[9] = y2;
  4637. out[10] = z2;
  4638. out[11] = 0;
  4639. out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
  4640. out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
  4641. out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
  4642. out[15] = 1;
  4643. return out;
  4644. }
  4645. /**
  4646. * 4 Dimensional Vector
  4647. * @module vec4
  4648. */
  4649. /**
  4650. * Creates a new, empty vec4
  4651. *
  4652. * @returns {vec4} a new 4D vector
  4653. */
  4654. function create$1() {
  4655. var out = new ARRAY_TYPE(4);
  4656. if (ARRAY_TYPE != Float32Array) {
  4657. out[0] = 0;
  4658. out[1] = 0;
  4659. out[2] = 0;
  4660. out[3] = 0;
  4661. }
  4662. return out;
  4663. }
  4664. /**
  4665. * Adds two vec4's
  4666. *
  4667. * @param {vec4} out the receiving vector
  4668. * @param {ReadonlyVec4} a the first operand
  4669. * @param {ReadonlyVec4} b the second operand
  4670. * @returns {vec4} out
  4671. */
  4672. function add$1(out, a, b) {
  4673. out[0] = a[0] + b[0];
  4674. out[1] = a[1] + b[1];
  4675. out[2] = a[2] + b[2];
  4676. out[3] = a[3] + b[3];
  4677. return out;
  4678. }
  4679. /**
  4680. * Scales a vec4 by a scalar number
  4681. *
  4682. * @param {vec4} out the receiving vector
  4683. * @param {ReadonlyVec4} a the vector to scale
  4684. * @param {Number} b amount to scale the vector by
  4685. * @returns {vec4} out
  4686. */
  4687. function scale$1(out, a, b) {
  4688. out[0] = a[0] * b;
  4689. out[1] = a[1] * b;
  4690. out[2] = a[2] * b;
  4691. out[3] = a[3] * b;
  4692. return out;
  4693. }
  4694. /**
  4695. * Calculates the length of a vec4
  4696. *
  4697. * @param {ReadonlyVec4} a vector to calculate length of
  4698. * @returns {Number} length of a
  4699. */
  4700. function length$1(a) {
  4701. var x = a[0];
  4702. var y = a[1];
  4703. var z = a[2];
  4704. var w = a[3];
  4705. return Math.hypot(x, y, z, w);
  4706. }
  4707. /**
  4708. * Calculates the squared length of a vec4
  4709. *
  4710. * @param {ReadonlyVec4} a vector to calculate squared length of
  4711. * @returns {Number} squared length of a
  4712. */
  4713. function squaredLength$1(a) {
  4714. var x = a[0];
  4715. var y = a[1];
  4716. var z = a[2];
  4717. var w = a[3];
  4718. return x * x + y * y + z * z + w * w;
  4719. }
  4720. /**
  4721. * Normalize a vec4
  4722. *
  4723. * @param {vec4} out the receiving vector
  4724. * @param {ReadonlyVec4} a vector to normalize
  4725. * @returns {vec4} out
  4726. */
  4727. function normalize$1(out, a) {
  4728. var x = a[0];
  4729. var y = a[1];
  4730. var z = a[2];
  4731. var w = a[3];
  4732. var len = x * x + y * y + z * z + w * w;
  4733. if (len > 0) {
  4734. len = 1 / Math.sqrt(len);
  4735. }
  4736. out[0] = x * len;
  4737. out[1] = y * len;
  4738. out[2] = z * len;
  4739. out[3] = w * len;
  4740. return out;
  4741. }
  4742. /**
  4743. * Calculates the dot product of two vec4's
  4744. *
  4745. * @param {ReadonlyVec4} a the first operand
  4746. * @param {ReadonlyVec4} b the second operand
  4747. * @returns {Number} dot product of a and b
  4748. */
  4749. function dot$1(a, b) {
  4750. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
  4751. }
  4752. /**
  4753. * Performs a linear interpolation between two vec4's
  4754. *
  4755. * @param {vec4} out the receiving vector
  4756. * @param {ReadonlyVec4} a the first operand
  4757. * @param {ReadonlyVec4} b the second operand
  4758. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  4759. * @returns {vec4} out
  4760. */
  4761. function lerp$1(out, a, b, t) {
  4762. var ax = a[0];
  4763. var ay = a[1];
  4764. var az = a[2];
  4765. var aw = a[3];
  4766. out[0] = ax + t * (b[0] - ax);
  4767. out[1] = ay + t * (b[1] - ay);
  4768. out[2] = az + t * (b[2] - az);
  4769. out[3] = aw + t * (b[3] - aw);
  4770. return out;
  4771. }
  4772. /**
  4773. * Transforms the vec4 with a mat4.
  4774. *
  4775. * @param {vec4} out the receiving vector
  4776. * @param {ReadonlyVec4} a the vector to transform
  4777. * @param {ReadonlyMat4} m matrix to transform with
  4778. * @returns {vec4} out
  4779. */
  4780. function transformMat4(out, a, m) {
  4781. var x = a[0],
  4782. y = a[1],
  4783. z = a[2],
  4784. w = a[3];
  4785. out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
  4786. out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
  4787. out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
  4788. out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
  4789. return out;
  4790. }
  4791. /**
  4792. * Transforms the vec4 with a quat
  4793. *
  4794. * @param {vec4} out the receiving vector
  4795. * @param {ReadonlyVec4} a the vector to transform
  4796. * @param {ReadonlyQuat} q quaternion to transform with
  4797. * @returns {vec4} out
  4798. */
  4799. function transformQuat(out, a, q) {
  4800. var x = a[0],
  4801. y = a[1],
  4802. z = a[2];
  4803. var qx = q[0],
  4804. qy = q[1],
  4805. qz = q[2],
  4806. qw = q[3]; // calculate quat * vec
  4807. var ix = qw * x + qy * z - qz * y;
  4808. var iy = qw * y + qz * x - qx * z;
  4809. var iz = qw * z + qx * y - qy * x;
  4810. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  4811. out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  4812. out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  4813. out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  4814. out[3] = a[3];
  4815. return out;
  4816. }
  4817. /**
  4818. * Perform some operation over an array of vec4s.
  4819. *
  4820. * @param {Array} a the array of vectors to iterate over
  4821. * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
  4822. * @param {Number} offset Number of elements to skip at the beginning of the array
  4823. * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
  4824. * @param {Function} fn Function to call for each vector in the array
  4825. * @param {Object} [arg] additional argument to pass to fn
  4826. * @returns {Array} a
  4827. * @function
  4828. */
  4829. (function () {
  4830. var vec = create$1();
  4831. return function (a, stride, offset, count, fn, arg) {
  4832. var i, l;
  4833. if (!stride) {
  4834. stride = 4;
  4835. }
  4836. if (!offset) {
  4837. offset = 0;
  4838. }
  4839. if (count) {
  4840. l = Math.min(count * stride + offset, a.length);
  4841. } else {
  4842. l = a.length;
  4843. }
  4844. for (i = offset; i < l; i += stride) {
  4845. vec[0] = a[i];
  4846. vec[1] = a[i + 1];
  4847. vec[2] = a[i + 2];
  4848. vec[3] = a[i + 3];
  4849. fn(vec, vec, arg);
  4850. a[i] = vec[0];
  4851. a[i + 1] = vec[1];
  4852. a[i + 2] = vec[2];
  4853. a[i + 3] = vec[3];
  4854. }
  4855. return a;
  4856. };
  4857. })();
  4858. const IDENTITY = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
  4859. const ZERO = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  4860. const INDICES = Object.freeze({
  4861. COL0ROW0: 0,
  4862. COL0ROW1: 1,
  4863. COL0ROW2: 2,
  4864. COL0ROW3: 3,
  4865. COL1ROW0: 4,
  4866. COL1ROW1: 5,
  4867. COL1ROW2: 6,
  4868. COL1ROW3: 7,
  4869. COL2ROW0: 8,
  4870. COL2ROW1: 9,
  4871. COL2ROW2: 10,
  4872. COL2ROW3: 11,
  4873. COL3ROW0: 12,
  4874. COL3ROW1: 13,
  4875. COL3ROW2: 14,
  4876. COL3ROW3: 15
  4877. });
  4878. const constants = {};
  4879. class Matrix4 extends Matrix {
  4880. static get IDENTITY() {
  4881. constants.IDENTITY = constants.IDENTITY || Object.freeze(new Matrix4(IDENTITY));
  4882. return constants.IDENTITY;
  4883. }
  4884. static get ZERO() {
  4885. constants.ZERO = constants.ZERO || Object.freeze(new Matrix4(ZERO));
  4886. return constants.ZERO;
  4887. }
  4888. get INDICES() {
  4889. return INDICES;
  4890. }
  4891. get ELEMENTS() {
  4892. return 16;
  4893. }
  4894. get RANK() {
  4895. return 4;
  4896. }
  4897. constructor(array) {
  4898. super(-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0);
  4899. if (arguments.length === 1 && Array.isArray(array)) {
  4900. this.copy(array);
  4901. } else {
  4902. this.identity();
  4903. }
  4904. }
  4905. copy(array) {
  4906. this[0] = array[0];
  4907. this[1] = array[1];
  4908. this[2] = array[2];
  4909. this[3] = array[3];
  4910. this[4] = array[4];
  4911. this[5] = array[5];
  4912. this[6] = array[6];
  4913. this[7] = array[7];
  4914. this[8] = array[8];
  4915. this[9] = array[9];
  4916. this[10] = array[10];
  4917. this[11] = array[11];
  4918. this[12] = array[12];
  4919. this[13] = array[13];
  4920. this[14] = array[14];
  4921. this[15] = array[15];
  4922. return this.check();
  4923. }
  4924. set(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33) {
  4925. this[0] = m00;
  4926. this[1] = m10;
  4927. this[2] = m20;
  4928. this[3] = m30;
  4929. this[4] = m01;
  4930. this[5] = m11;
  4931. this[6] = m21;
  4932. this[7] = m31;
  4933. this[8] = m02;
  4934. this[9] = m12;
  4935. this[10] = m22;
  4936. this[11] = m32;
  4937. this[12] = m03;
  4938. this[13] = m13;
  4939. this[14] = m23;
  4940. this[15] = m33;
  4941. return this.check();
  4942. }
  4943. setRowMajor(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
  4944. this[0] = m00;
  4945. this[1] = m10;
  4946. this[2] = m20;
  4947. this[3] = m30;
  4948. this[4] = m01;
  4949. this[5] = m11;
  4950. this[6] = m21;
  4951. this[7] = m31;
  4952. this[8] = m02;
  4953. this[9] = m12;
  4954. this[10] = m22;
  4955. this[11] = m32;
  4956. this[12] = m03;
  4957. this[13] = m13;
  4958. this[14] = m23;
  4959. this[15] = m33;
  4960. return this.check();
  4961. }
  4962. toRowMajor(result) {
  4963. result[0] = this[0];
  4964. result[1] = this[4];
  4965. result[2] = this[8];
  4966. result[3] = this[12];
  4967. result[4] = this[1];
  4968. result[5] = this[5];
  4969. result[6] = this[9];
  4970. result[7] = this[13];
  4971. result[8] = this[2];
  4972. result[9] = this[6];
  4973. result[10] = this[10];
  4974. result[11] = this[14];
  4975. result[12] = this[3];
  4976. result[13] = this[7];
  4977. result[14] = this[11];
  4978. result[15] = this[15];
  4979. return result;
  4980. }
  4981. identity() {
  4982. return this.copy(IDENTITY);
  4983. }
  4984. fromQuaternion(q) {
  4985. fromQuat(this, q);
  4986. return this.check();
  4987. }
  4988. frustum({
  4989. left,
  4990. right,
  4991. bottom,
  4992. top,
  4993. near,
  4994. far
  4995. }) {
  4996. if (far === Infinity) {
  4997. Matrix4._computeInfinitePerspectiveOffCenter(this, left, right, bottom, top, near);
  4998. } else {
  4999. frustum(this, left, right, bottom, top, near, far);
  5000. }
  5001. return this.check();
  5002. }
  5003. static _computeInfinitePerspectiveOffCenter(result, left, right, bottom, top, near) {
  5004. const column0Row0 = 2.0 * near / (right - left);
  5005. const column1Row1 = 2.0 * near / (top - bottom);
  5006. const column2Row0 = (right + left) / (right - left);
  5007. const column2Row1 = (top + bottom) / (top - bottom);
  5008. const column2Row2 = -1.0;
  5009. const column2Row3 = -1.0;
  5010. const column3Row2 = -2.0 * near;
  5011. result[0] = column0Row0;
  5012. result[1] = 0.0;
  5013. result[2] = 0.0;
  5014. result[3] = 0.0;
  5015. result[4] = 0.0;
  5016. result[5] = column1Row1;
  5017. result[6] = 0.0;
  5018. result[7] = 0.0;
  5019. result[8] = column2Row0;
  5020. result[9] = column2Row1;
  5021. result[10] = column2Row2;
  5022. result[11] = column2Row3;
  5023. result[12] = 0.0;
  5024. result[13] = 0.0;
  5025. result[14] = column3Row2;
  5026. result[15] = 0.0;
  5027. return result;
  5028. }
  5029. lookAt(eye, center, up) {
  5030. if (arguments.length === 1) {
  5031. ({
  5032. eye,
  5033. center,
  5034. up
  5035. } = eye);
  5036. }
  5037. center = center || [0, 0, 0];
  5038. up = up || [0, 1, 0];
  5039. lookAt(this, eye, center, up);
  5040. return this.check();
  5041. }
  5042. ortho({
  5043. left,
  5044. right,
  5045. bottom,
  5046. top,
  5047. near = 0.1,
  5048. far = 500
  5049. }) {
  5050. ortho(this, left, right, bottom, top, near, far);
  5051. return this.check();
  5052. }
  5053. orthographic({
  5054. fovy = 45 * Math.PI / 180,
  5055. aspect = 1,
  5056. focalDistance = 1,
  5057. near = 0.1,
  5058. far = 500
  5059. }) {
  5060. if (fovy > Math.PI * 2) {
  5061. throw Error('radians');
  5062. }
  5063. const halfY = fovy / 2;
  5064. const top = focalDistance * Math.tan(halfY);
  5065. const right = top * aspect;
  5066. return new Matrix4().ortho({
  5067. left: -right,
  5068. right,
  5069. bottom: -top,
  5070. top,
  5071. near,
  5072. far
  5073. });
  5074. }
  5075. perspective({
  5076. fovy = undefined,
  5077. fov = 45 * Math.PI / 180,
  5078. aspect = 1,
  5079. near = 0.1,
  5080. far = 500
  5081. } = {}) {
  5082. fovy = fovy || fov;
  5083. if (fovy > Math.PI * 2) {
  5084. throw Error('radians');
  5085. }
  5086. perspective(this, fovy, aspect, near, far);
  5087. return this.check();
  5088. }
  5089. determinant() {
  5090. return determinant(this);
  5091. }
  5092. getScale(result = [-0, -0, -0]) {
  5093. result[0] = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);
  5094. result[1] = Math.sqrt(this[4] * this[4] + this[5] * this[5] + this[6] * this[6]);
  5095. result[2] = Math.sqrt(this[8] * this[8] + this[9] * this[9] + this[10] * this[10]);
  5096. return result;
  5097. }
  5098. getTranslation(result = [-0, -0, -0]) {
  5099. result[0] = this[12];
  5100. result[1] = this[13];
  5101. result[2] = this[14];
  5102. return result;
  5103. }
  5104. getRotation(result = [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0], scaleResult = null) {
  5105. const scale = this.getScale(scaleResult || [-0, -0, -0]);
  5106. const inverseScale0 = 1 / scale[0];
  5107. const inverseScale1 = 1 / scale[1];
  5108. const inverseScale2 = 1 / scale[2];
  5109. result[0] = this[0] * inverseScale0;
  5110. result[1] = this[1] * inverseScale1;
  5111. result[2] = this[2] * inverseScale2;
  5112. result[3] = 0;
  5113. result[4] = this[4] * inverseScale0;
  5114. result[5] = this[5] * inverseScale1;
  5115. result[6] = this[6] * inverseScale2;
  5116. result[7] = 0;
  5117. result[8] = this[8] * inverseScale0;
  5118. result[9] = this[9] * inverseScale1;
  5119. result[10] = this[10] * inverseScale2;
  5120. result[11] = 0;
  5121. result[12] = 0;
  5122. result[13] = 0;
  5123. result[14] = 0;
  5124. result[15] = 1;
  5125. return result;
  5126. }
  5127. getRotationMatrix3(result = [-0, -0, -0, -0, -0, -0, -0, -0, -0], scaleResult = null) {
  5128. const scale = this.getScale(scaleResult || [-0, -0, -0]);
  5129. const inverseScale0 = 1 / scale[0];
  5130. const inverseScale1 = 1 / scale[1];
  5131. const inverseScale2 = 1 / scale[2];
  5132. result[0] = this[0] * inverseScale0;
  5133. result[1] = this[1] * inverseScale1;
  5134. result[2] = this[2] * inverseScale2;
  5135. result[3] = this[4] * inverseScale0;
  5136. result[4] = this[5] * inverseScale1;
  5137. result[5] = this[6] * inverseScale2;
  5138. result[6] = this[8] * inverseScale0;
  5139. result[7] = this[9] * inverseScale1;
  5140. result[8] = this[10] * inverseScale2;
  5141. return result;
  5142. }
  5143. transpose() {
  5144. transpose(this, this);
  5145. return this.check();
  5146. }
  5147. invert() {
  5148. invert$1(this, this);
  5149. return this.check();
  5150. }
  5151. multiplyLeft(a) {
  5152. multiply$1(this, a, this);
  5153. return this.check();
  5154. }
  5155. multiplyRight(a) {
  5156. multiply$1(this, this, a);
  5157. return this.check();
  5158. }
  5159. rotateX(radians) {
  5160. rotateX$1(this, this, radians);
  5161. return this.check();
  5162. }
  5163. rotateY(radians) {
  5164. rotateY$1(this, this, radians);
  5165. return this.check();
  5166. }
  5167. rotateZ(radians) {
  5168. rotateZ$1(this, this, radians);
  5169. return this.check();
  5170. }
  5171. rotateXYZ([rx, ry, rz]) {
  5172. return this.rotateX(rx).rotateY(ry).rotateZ(rz);
  5173. }
  5174. rotateAxis(radians, axis) {
  5175. rotate(this, this, radians, axis);
  5176. return this.check();
  5177. }
  5178. scale(factor) {
  5179. if (Array.isArray(factor)) {
  5180. scale$2(this, this, factor);
  5181. } else {
  5182. scale$2(this, this, [factor, factor, factor]);
  5183. }
  5184. return this.check();
  5185. }
  5186. translate(vec) {
  5187. translate(this, this, vec);
  5188. return this.check();
  5189. }
  5190. transform(vector, result) {
  5191. if (vector.length === 4) {
  5192. result = transformMat4(result || [-0, -0, -0, -0], vector, this);
  5193. checkVector(result, 4);
  5194. return result;
  5195. }
  5196. return this.transformAsPoint(vector, result);
  5197. }
  5198. transformAsPoint(vector, result) {
  5199. const {
  5200. length
  5201. } = vector;
  5202. switch (length) {
  5203. case 2:
  5204. result = transformMat4$2(result || [-0, -0], vector, this);
  5205. break;
  5206. case 3:
  5207. result = transformMat4$1(result || [-0, -0, -0], vector, this);
  5208. break;
  5209. default:
  5210. throw new Error('Illegal vector');
  5211. }
  5212. checkVector(result, vector.length);
  5213. return result;
  5214. }
  5215. transformAsVector(vector, result) {
  5216. switch (vector.length) {
  5217. case 2:
  5218. result = vec2_transformMat4AsVector(result || [-0, -0], vector, this);
  5219. break;
  5220. case 3:
  5221. result = vec3_transformMat4AsVector(result || [-0, -0, -0], vector, this);
  5222. break;
  5223. default:
  5224. throw new Error('Illegal vector');
  5225. }
  5226. checkVector(result, vector.length);
  5227. return result;
  5228. }
  5229. makeRotationX(radians) {
  5230. return this.identity().rotateX(radians);
  5231. }
  5232. makeTranslation(x, y, z) {
  5233. return this.identity().translate([x, y, z]);
  5234. }
  5235. transformPoint(vector, result) {
  5236. deprecated('Matrix4.transformPoint', '3.0');
  5237. return this.transformAsPoint(vector, result);
  5238. }
  5239. transformVector(vector, result) {
  5240. deprecated('Matrix4.transformVector', '3.0');
  5241. return this.transformAsPoint(vector, result);
  5242. }
  5243. transformDirection(vector, result) {
  5244. deprecated('Matrix4.transformDirection', '3.0');
  5245. return this.transformAsVector(vector, result);
  5246. }
  5247. }
  5248. /**
  5249. * Quaternion
  5250. * @module quat
  5251. */
  5252. /**
  5253. * Creates a new identity quat
  5254. *
  5255. * @returns {quat} a new quaternion
  5256. */
  5257. function create() {
  5258. var out = new ARRAY_TYPE(4);
  5259. if (ARRAY_TYPE != Float32Array) {
  5260. out[0] = 0;
  5261. out[1] = 0;
  5262. out[2] = 0;
  5263. }
  5264. out[3] = 1;
  5265. return out;
  5266. }
  5267. /**
  5268. * Set a quat to the identity quaternion
  5269. *
  5270. * @param {quat} out the receiving quaternion
  5271. * @returns {quat} out
  5272. */
  5273. function identity(out) {
  5274. out[0] = 0;
  5275. out[1] = 0;
  5276. out[2] = 0;
  5277. out[3] = 1;
  5278. return out;
  5279. }
  5280. /**
  5281. * Sets a quat from the given angle and rotation axis,
  5282. * then returns it.
  5283. *
  5284. * @param {quat} out the receiving quaternion
  5285. * @param {ReadonlyVec3} axis the axis around which to rotate
  5286. * @param {Number} rad the angle in radians
  5287. * @returns {quat} out
  5288. **/
  5289. function setAxisAngle(out, axis, rad) {
  5290. rad = rad * 0.5;
  5291. var s = Math.sin(rad);
  5292. out[0] = s * axis[0];
  5293. out[1] = s * axis[1];
  5294. out[2] = s * axis[2];
  5295. out[3] = Math.cos(rad);
  5296. return out;
  5297. }
  5298. /**
  5299. * Multiplies two quat's
  5300. *
  5301. * @param {quat} out the receiving quaternion
  5302. * @param {ReadonlyQuat} a the first operand
  5303. * @param {ReadonlyQuat} b the second operand
  5304. * @returns {quat} out
  5305. */
  5306. function multiply(out, a, b) {
  5307. var ax = a[0],
  5308. ay = a[1],
  5309. az = a[2],
  5310. aw = a[3];
  5311. var bx = b[0],
  5312. by = b[1],
  5313. bz = b[2],
  5314. bw = b[3];
  5315. out[0] = ax * bw + aw * bx + ay * bz - az * by;
  5316. out[1] = ay * bw + aw * by + az * bx - ax * bz;
  5317. out[2] = az * bw + aw * bz + ax * by - ay * bx;
  5318. out[3] = aw * bw - ax * bx - ay * by - az * bz;
  5319. return out;
  5320. }
  5321. /**
  5322. * Rotates a quaternion by the given angle about the X axis
  5323. *
  5324. * @param {quat} out quat receiving operation result
  5325. * @param {ReadonlyQuat} a quat to rotate
  5326. * @param {number} rad angle (in radians) to rotate
  5327. * @returns {quat} out
  5328. */
  5329. function rotateX(out, a, rad) {
  5330. rad *= 0.5;
  5331. var ax = a[0],
  5332. ay = a[1],
  5333. az = a[2],
  5334. aw = a[3];
  5335. var bx = Math.sin(rad),
  5336. bw = Math.cos(rad);
  5337. out[0] = ax * bw + aw * bx;
  5338. out[1] = ay * bw + az * bx;
  5339. out[2] = az * bw - ay * bx;
  5340. out[3] = aw * bw - ax * bx;
  5341. return out;
  5342. }
  5343. /**
  5344. * Rotates a quaternion by the given angle about the Y axis
  5345. *
  5346. * @param {quat} out quat receiving operation result
  5347. * @param {ReadonlyQuat} a quat to rotate
  5348. * @param {number} rad angle (in radians) to rotate
  5349. * @returns {quat} out
  5350. */
  5351. function rotateY(out, a, rad) {
  5352. rad *= 0.5;
  5353. var ax = a[0],
  5354. ay = a[1],
  5355. az = a[2],
  5356. aw = a[3];
  5357. var by = Math.sin(rad),
  5358. bw = Math.cos(rad);
  5359. out[0] = ax * bw - az * by;
  5360. out[1] = ay * bw + aw * by;
  5361. out[2] = az * bw + ax * by;
  5362. out[3] = aw * bw - ay * by;
  5363. return out;
  5364. }
  5365. /**
  5366. * Rotates a quaternion by the given angle about the Z axis
  5367. *
  5368. * @param {quat} out quat receiving operation result
  5369. * @param {ReadonlyQuat} a quat to rotate
  5370. * @param {number} rad angle (in radians) to rotate
  5371. * @returns {quat} out
  5372. */
  5373. function rotateZ(out, a, rad) {
  5374. rad *= 0.5;
  5375. var ax = a[0],
  5376. ay = a[1],
  5377. az = a[2],
  5378. aw = a[3];
  5379. var bz = Math.sin(rad),
  5380. bw = Math.cos(rad);
  5381. out[0] = ax * bw + ay * bz;
  5382. out[1] = ay * bw - ax * bz;
  5383. out[2] = az * bw + aw * bz;
  5384. out[3] = aw * bw - az * bz;
  5385. return out;
  5386. }
  5387. /**
  5388. * Calculates the W component of a quat from the X, Y, and Z components.
  5389. * Assumes that quaternion is 1 unit in length.
  5390. * Any existing W component will be ignored.
  5391. *
  5392. * @param {quat} out the receiving quaternion
  5393. * @param {ReadonlyQuat} a quat to calculate W component of
  5394. * @returns {quat} out
  5395. */
  5396. function calculateW(out, a) {
  5397. var x = a[0],
  5398. y = a[1],
  5399. z = a[2];
  5400. out[0] = x;
  5401. out[1] = y;
  5402. out[2] = z;
  5403. out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
  5404. return out;
  5405. }
  5406. /**
  5407. * Performs a spherical linear interpolation between two quat
  5408. *
  5409. * @param {quat} out the receiving quaternion
  5410. * @param {ReadonlyQuat} a the first operand
  5411. * @param {ReadonlyQuat} b the second operand
  5412. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5413. * @returns {quat} out
  5414. */
  5415. function slerp(out, a, b, t) {
  5416. // benchmarks:
  5417. // http://jsperf.com/quaternion-slerp-implementations
  5418. var ax = a[0],
  5419. ay = a[1],
  5420. az = a[2],
  5421. aw = a[3];
  5422. var bx = b[0],
  5423. by = b[1],
  5424. bz = b[2],
  5425. bw = b[3];
  5426. var omega, cosom, sinom, scale0, scale1; // calc cosine
  5427. cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)
  5428. if (cosom < 0.0) {
  5429. cosom = -cosom;
  5430. bx = -bx;
  5431. by = -by;
  5432. bz = -bz;
  5433. bw = -bw;
  5434. } // calculate coefficients
  5435. if (1.0 - cosom > EPSILON) {
  5436. // standard case (slerp)
  5437. omega = Math.acos(cosom);
  5438. sinom = Math.sin(omega);
  5439. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  5440. scale1 = Math.sin(t * omega) / sinom;
  5441. } else {
  5442. // "from" and "to" quaternions are very close
  5443. // ... so we can do a linear interpolation
  5444. scale0 = 1.0 - t;
  5445. scale1 = t;
  5446. } // calculate final values
  5447. out[0] = scale0 * ax + scale1 * bx;
  5448. out[1] = scale0 * ay + scale1 * by;
  5449. out[2] = scale0 * az + scale1 * bz;
  5450. out[3] = scale0 * aw + scale1 * bw;
  5451. return out;
  5452. }
  5453. /**
  5454. * Calculates the inverse of a quat
  5455. *
  5456. * @param {quat} out the receiving quaternion
  5457. * @param {ReadonlyQuat} a quat to calculate inverse of
  5458. * @returns {quat} out
  5459. */
  5460. function invert(out, a) {
  5461. var a0 = a[0],
  5462. a1 = a[1],
  5463. a2 = a[2],
  5464. a3 = a[3];
  5465. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  5466. var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
  5467. out[0] = -a0 * invDot;
  5468. out[1] = -a1 * invDot;
  5469. out[2] = -a2 * invDot;
  5470. out[3] = a3 * invDot;
  5471. return out;
  5472. }
  5473. /**
  5474. * Calculates the conjugate of a quat
  5475. * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
  5476. *
  5477. * @param {quat} out the receiving quaternion
  5478. * @param {ReadonlyQuat} a quat to calculate conjugate of
  5479. * @returns {quat} out
  5480. */
  5481. function conjugate(out, a) {
  5482. out[0] = -a[0];
  5483. out[1] = -a[1];
  5484. out[2] = -a[2];
  5485. out[3] = a[3];
  5486. return out;
  5487. }
  5488. /**
  5489. * Creates a quaternion from the given 3x3 rotation matrix.
  5490. *
  5491. * NOTE: The resultant quaternion is not normalized, so you should be sure
  5492. * to renormalize the quaternion yourself where necessary.
  5493. *
  5494. * @param {quat} out the receiving quaternion
  5495. * @param {ReadonlyMat3} m rotation matrix
  5496. * @returns {quat} out
  5497. * @function
  5498. */
  5499. function fromMat3(out, m) {
  5500. // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  5501. // article "Quaternion Calculus and Fast Animation".
  5502. var fTrace = m[0] + m[4] + m[8];
  5503. var fRoot;
  5504. if (fTrace > 0.0) {
  5505. // |w| > 1/2, may as well choose w > 1/2
  5506. fRoot = Math.sqrt(fTrace + 1.0); // 2w
  5507. out[3] = 0.5 * fRoot;
  5508. fRoot = 0.5 / fRoot; // 1/(4w)
  5509. out[0] = (m[5] - m[7]) * fRoot;
  5510. out[1] = (m[6] - m[2]) * fRoot;
  5511. out[2] = (m[1] - m[3]) * fRoot;
  5512. } else {
  5513. // |w| <= 1/2
  5514. var i = 0;
  5515. if (m[4] > m[0]) i = 1;
  5516. if (m[8] > m[i * 3 + i]) i = 2;
  5517. var j = (i + 1) % 3;
  5518. var k = (i + 2) % 3;
  5519. fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);
  5520. out[i] = 0.5 * fRoot;
  5521. fRoot = 0.5 / fRoot;
  5522. out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
  5523. out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
  5524. out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
  5525. }
  5526. return out;
  5527. }
  5528. /**
  5529. * Adds two quat's
  5530. *
  5531. * @param {quat} out the receiving quaternion
  5532. * @param {ReadonlyQuat} a the first operand
  5533. * @param {ReadonlyQuat} b the second operand
  5534. * @returns {quat} out
  5535. * @function
  5536. */
  5537. var add = add$1;
  5538. /**
  5539. * Scales a quat by a scalar number
  5540. *
  5541. * @param {quat} out the receiving vector
  5542. * @param {ReadonlyQuat} a the vector to scale
  5543. * @param {Number} b amount to scale the vector by
  5544. * @returns {quat} out
  5545. * @function
  5546. */
  5547. var scale = scale$1;
  5548. /**
  5549. * Calculates the dot product of two quat's
  5550. *
  5551. * @param {ReadonlyQuat} a the first operand
  5552. * @param {ReadonlyQuat} b the second operand
  5553. * @returns {Number} dot product of a and b
  5554. * @function
  5555. */
  5556. var dot = dot$1;
  5557. /**
  5558. * Performs a linear interpolation between two quat's
  5559. *
  5560. * @param {quat} out the receiving quaternion
  5561. * @param {ReadonlyQuat} a the first operand
  5562. * @param {ReadonlyQuat} b the second operand
  5563. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5564. * @returns {quat} out
  5565. * @function
  5566. */
  5567. var lerp = lerp$1;
  5568. /**
  5569. * Calculates the length of a quat
  5570. *
  5571. * @param {ReadonlyQuat} a vector to calculate length of
  5572. * @returns {Number} length of a
  5573. */
  5574. var length = length$1;
  5575. /**
  5576. * Calculates the squared length of a quat
  5577. *
  5578. * @param {ReadonlyQuat} a vector to calculate squared length of
  5579. * @returns {Number} squared length of a
  5580. * @function
  5581. */
  5582. var squaredLength = squaredLength$1;
  5583. /**
  5584. * Normalize a quat
  5585. *
  5586. * @param {quat} out the receiving quaternion
  5587. * @param {ReadonlyQuat} a quaternion to normalize
  5588. * @returns {quat} out
  5589. * @function
  5590. */
  5591. var normalize = normalize$1;
  5592. /**
  5593. * Sets a quaternion to represent the shortest rotation from one
  5594. * vector to another.
  5595. *
  5596. * Both vectors are assumed to be unit length.
  5597. *
  5598. * @param {quat} out the receiving quaternion.
  5599. * @param {ReadonlyVec3} a the initial vector
  5600. * @param {ReadonlyVec3} b the destination vector
  5601. * @returns {quat} out
  5602. */
  5603. var rotationTo = function () {
  5604. var tmpvec3 = create$3();
  5605. var xUnitVec3 = fromValues(1, 0, 0);
  5606. var yUnitVec3 = fromValues(0, 1, 0);
  5607. return function (out, a, b) {
  5608. var dot = dot$2(a, b);
  5609. if (dot < -0.999999) {
  5610. cross(tmpvec3, xUnitVec3, a);
  5611. if (len(tmpvec3) < 0.000001) cross(tmpvec3, yUnitVec3, a);
  5612. normalize$2(tmpvec3, tmpvec3);
  5613. setAxisAngle(out, tmpvec3, Math.PI);
  5614. return out;
  5615. } else if (dot > 0.999999) {
  5616. out[0] = 0;
  5617. out[1] = 0;
  5618. out[2] = 0;
  5619. out[3] = 1;
  5620. return out;
  5621. } else {
  5622. cross(tmpvec3, a, b);
  5623. out[0] = tmpvec3[0];
  5624. out[1] = tmpvec3[1];
  5625. out[2] = tmpvec3[2];
  5626. out[3] = 1 + dot;
  5627. return normalize(out, out);
  5628. }
  5629. };
  5630. }();
  5631. /**
  5632. * Performs a spherical linear interpolation with two control points
  5633. *
  5634. * @param {quat} out the receiving quaternion
  5635. * @param {ReadonlyQuat} a the first operand
  5636. * @param {ReadonlyQuat} b the second operand
  5637. * @param {ReadonlyQuat} c the third operand
  5638. * @param {ReadonlyQuat} d the fourth operand
  5639. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5640. * @returns {quat} out
  5641. */
  5642. (function () {
  5643. var temp1 = create();
  5644. var temp2 = create();
  5645. return function (out, a, b, c, d, t) {
  5646. slerp(temp1, a, d, t);
  5647. slerp(temp2, b, c, t);
  5648. slerp(out, temp1, temp2, 2 * t * (1 - t));
  5649. return out;
  5650. };
  5651. })();
  5652. /**
  5653. * Sets the specified quaternion with values corresponding to the given
  5654. * axes. Each axis is a vec3 and is expected to be unit length and
  5655. * perpendicular to all other specified axes.
  5656. *
  5657. * @param {ReadonlyVec3} view the vector representing the viewing direction
  5658. * @param {ReadonlyVec3} right the vector representing the local "right" direction
  5659. * @param {ReadonlyVec3} up the vector representing the local "up" direction
  5660. * @returns {quat} out
  5661. */
  5662. (function () {
  5663. var matr = create$2();
  5664. return function (out, view, right, up) {
  5665. matr[0] = right[0];
  5666. matr[3] = right[1];
  5667. matr[6] = right[2];
  5668. matr[1] = up[0];
  5669. matr[4] = up[1];
  5670. matr[7] = up[2];
  5671. matr[2] = -view[0];
  5672. matr[5] = -view[1];
  5673. matr[8] = -view[2];
  5674. return normalize(out, fromMat3(out, matr));
  5675. };
  5676. })();
  5677. const IDENTITY_QUATERNION = [0, 0, 0, 1];
  5678. class Quaternion extends MathArray {
  5679. constructor(x = 0, y = 0, z = 0, w = 1) {
  5680. super(-0, -0, -0, -0);
  5681. if (Array.isArray(x) && arguments.length === 1) {
  5682. this.copy(x);
  5683. } else {
  5684. this.set(x, y, z, w);
  5685. }
  5686. }
  5687. copy(array) {
  5688. this[0] = array[0];
  5689. this[1] = array[1];
  5690. this[2] = array[2];
  5691. this[3] = array[3];
  5692. return this.check();
  5693. }
  5694. set(x, y, z, w) {
  5695. this[0] = x;
  5696. this[1] = y;
  5697. this[2] = z;
  5698. this[3] = w;
  5699. return this.check();
  5700. }
  5701. fromMatrix3(m) {
  5702. fromMat3(this, m);
  5703. return this.check();
  5704. }
  5705. identity() {
  5706. identity(this);
  5707. return this.check();
  5708. }
  5709. fromAxisRotation(axis, rad) {
  5710. setAxisAngle(this, axis, rad);
  5711. return this.check();
  5712. }
  5713. setAxisAngle(axis, rad) {
  5714. return this.fromAxisRotation(axis, rad);
  5715. }
  5716. get ELEMENTS() {
  5717. return 4;
  5718. }
  5719. get x() {
  5720. return this[0];
  5721. }
  5722. set x(value) {
  5723. this[0] = checkNumber(value);
  5724. }
  5725. get y() {
  5726. return this[1];
  5727. }
  5728. set y(value) {
  5729. this[1] = checkNumber(value);
  5730. }
  5731. get z() {
  5732. return this[2];
  5733. }
  5734. set z(value) {
  5735. this[2] = checkNumber(value);
  5736. }
  5737. get w() {
  5738. return this[3];
  5739. }
  5740. set w(value) {
  5741. this[3] = checkNumber(value);
  5742. }
  5743. len() {
  5744. return length(this);
  5745. }
  5746. lengthSquared() {
  5747. return squaredLength(this);
  5748. }
  5749. dot(a, b) {
  5750. if (b !== undefined) {
  5751. throw new Error('Quaternion.dot only takes one argument');
  5752. }
  5753. return dot(this, a);
  5754. }
  5755. rotationTo(vectorA, vectorB) {
  5756. rotationTo(this, vectorA, vectorB);
  5757. return this.check();
  5758. }
  5759. add(a, b) {
  5760. if (b !== undefined) {
  5761. throw new Error('Quaternion.add only takes one argument');
  5762. }
  5763. add(this, this, a);
  5764. return this.check();
  5765. }
  5766. calculateW() {
  5767. calculateW(this, this);
  5768. return this.check();
  5769. }
  5770. conjugate() {
  5771. conjugate(this, this);
  5772. return this.check();
  5773. }
  5774. invert() {
  5775. invert(this, this);
  5776. return this.check();
  5777. }
  5778. lerp(a, b, t) {
  5779. lerp(this, a, b, t);
  5780. return this.check();
  5781. }
  5782. multiplyRight(a, b) {
  5783. assert$4(!b);
  5784. multiply(this, this, a);
  5785. return this.check();
  5786. }
  5787. multiplyLeft(a, b) {
  5788. assert$4(!b);
  5789. multiply(this, a, this);
  5790. return this.check();
  5791. }
  5792. normalize() {
  5793. const length = this.len();
  5794. const l = length > 0 ? 1 / length : 0;
  5795. this[0] = this[0] * l;
  5796. this[1] = this[1] * l;
  5797. this[2] = this[2] * l;
  5798. this[3] = this[3] * l;
  5799. if (length === 0) {
  5800. this[3] = 1;
  5801. }
  5802. return this.check();
  5803. }
  5804. rotateX(rad) {
  5805. rotateX(this, this, rad);
  5806. return this.check();
  5807. }
  5808. rotateY(rad) {
  5809. rotateY(this, this, rad);
  5810. return this.check();
  5811. }
  5812. rotateZ(rad) {
  5813. rotateZ(this, this, rad);
  5814. return this.check();
  5815. }
  5816. scale(b) {
  5817. scale(this, this, b);
  5818. return this.check();
  5819. }
  5820. slerp(start, target, ratio) {
  5821. switch (arguments.length) {
  5822. case 1:
  5823. ({
  5824. start = IDENTITY_QUATERNION,
  5825. target,
  5826. ratio
  5827. } = arguments[0]);
  5828. break;
  5829. case 2:
  5830. [target, ratio] = arguments;
  5831. start = this;
  5832. break;
  5833. }
  5834. slerp(this, start, target, ratio);
  5835. return this.check();
  5836. }
  5837. transformVector4(vector, result = vector) {
  5838. transformQuat(result, vector, this);
  5839. return checkVector(result, 4);
  5840. }
  5841. lengthSq() {
  5842. return this.lengthSquared();
  5843. }
  5844. setFromAxisAngle(axis, rad) {
  5845. return this.setAxisAngle(axis, rad);
  5846. }
  5847. premultiply(a, b) {
  5848. return this.multiplyLeft(a, b);
  5849. }
  5850. multiply(a, b) {
  5851. return this.multiplyRight(a, b);
  5852. }
  5853. }
  5854. var _MathUtils = {
  5855. EPSILON1: 1e-1,
  5856. EPSILON2: 1e-2,
  5857. EPSILON3: 1e-3,
  5858. EPSILON4: 1e-4,
  5859. EPSILON5: 1e-5,
  5860. EPSILON6: 1e-6,
  5861. EPSILON7: 1e-7,
  5862. EPSILON8: 1e-8,
  5863. EPSILON9: 1e-9,
  5864. EPSILON10: 1e-10,
  5865. EPSILON11: 1e-11,
  5866. EPSILON12: 1e-12,
  5867. EPSILON13: 1e-13,
  5868. EPSILON14: 1e-14,
  5869. EPSILON15: 1e-15,
  5870. EPSILON16: 1e-16,
  5871. EPSILON17: 1e-17,
  5872. EPSILON18: 1e-18,
  5873. EPSILON19: 1e-19,
  5874. EPSILON20: 1e-20,
  5875. PI_OVER_TWO: Math.PI / 2,
  5876. PI_OVER_FOUR: Math.PI / 4,
  5877. PI_OVER_SIX: Math.PI / 6,
  5878. TWO_PI: Math.PI * 2
  5879. };
  5880. const WGS84_RADIUS_X$1 = 6378137.0;
  5881. const WGS84_RADIUS_Y$1 = 6378137.0;
  5882. const WGS84_RADIUS_Z$1 = 6356752.3142451793;
  5883. const noop = x => x;
  5884. const scratchVector$6 = new Vector3();
  5885. function fromCartographic(cartographic, result, map = noop) {
  5886. if (isArray(cartographic)) {
  5887. result[0] = map(cartographic[0]);
  5888. result[1] = map(cartographic[1]);
  5889. result[2] = cartographic[2];
  5890. } else if ('longitude' in cartographic) {
  5891. result[0] = map(cartographic.longitude);
  5892. result[1] = map(cartographic.latitude);
  5893. result[2] = cartographic.height;
  5894. } else {
  5895. result[0] = map(cartographic.x);
  5896. result[1] = map(cartographic.y);
  5897. result[2] = cartographic.z;
  5898. }
  5899. return result;
  5900. }
  5901. function fromCartographicToRadians(cartographic, vector = scratchVector$6) {
  5902. return fromCartographic(cartographic, vector, config._cartographicRadians ? noop : toRadians);
  5903. }
  5904. function toCartographic(vector, cartographic, map = noop) {
  5905. if (isArray(cartographic)) {
  5906. cartographic[0] = map(vector[0]);
  5907. cartographic[1] = map(vector[1]);
  5908. cartographic[2] = vector[2];
  5909. } else if ('longitude' in cartographic) {
  5910. cartographic.longitude = map(vector[0]);
  5911. cartographic.latitude = map(vector[1]);
  5912. cartographic.height = vector[2];
  5913. } else {
  5914. cartographic.x = map(vector[0]);
  5915. cartographic.y = map(vector[1]);
  5916. cartographic.z = vector[2];
  5917. }
  5918. return cartographic;
  5919. }
  5920. function toCartographicFromRadians(vector, cartographic) {
  5921. return toCartographic(vector, cartographic, config._cartographicRadians ? noop : toDegrees);
  5922. }
  5923. const scratchVector$5 = new Vector3();
  5924. const scaleToGeodeticSurfaceIntersection = new Vector3();
  5925. const scaleToGeodeticSurfaceGradient = new Vector3();
  5926. function scaleToGeodeticSurface(cartesian, ellipsoid, result = new Vector3()) {
  5927. const {
  5928. oneOverRadii,
  5929. oneOverRadiiSquared,
  5930. centerToleranceSquared
  5931. } = ellipsoid;
  5932. scratchVector$5.from(cartesian);
  5933. const positionX = cartesian.x;
  5934. const positionY = cartesian.y;
  5935. const positionZ = cartesian.z;
  5936. const oneOverRadiiX = oneOverRadii.x;
  5937. const oneOverRadiiY = oneOverRadii.y;
  5938. const oneOverRadiiZ = oneOverRadii.z;
  5939. const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
  5940. const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
  5941. const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
  5942. const squaredNorm = x2 + y2 + z2;
  5943. const ratio = Math.sqrt(1.0 / squaredNorm);
  5944. if (!Number.isFinite(ratio)) {
  5945. return undefined;
  5946. }
  5947. const intersection = scaleToGeodeticSurfaceIntersection;
  5948. intersection.copy(cartesian).scale(ratio);
  5949. if (squaredNorm < centerToleranceSquared) {
  5950. return intersection.to(result);
  5951. }
  5952. const oneOverRadiiSquaredX = oneOverRadiiSquared.x;
  5953. const oneOverRadiiSquaredY = oneOverRadiiSquared.y;
  5954. const oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
  5955. const gradient = scaleToGeodeticSurfaceGradient;
  5956. gradient.set(intersection.x * oneOverRadiiSquaredX * 2.0, intersection.y * oneOverRadiiSquaredY * 2.0, intersection.z * oneOverRadiiSquaredZ * 2.0);
  5957. let lambda = (1.0 - ratio) * cartesian.len() / (0.5 * gradient.len());
  5958. let correction = 0.0;
  5959. let xMultiplier;
  5960. let yMultiplier;
  5961. let zMultiplier;
  5962. let func;
  5963. do {
  5964. lambda -= correction;
  5965. xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
  5966. yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
  5967. zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
  5968. const xMultiplier2 = xMultiplier * xMultiplier;
  5969. const yMultiplier2 = yMultiplier * yMultiplier;
  5970. const zMultiplier2 = zMultiplier * zMultiplier;
  5971. const xMultiplier3 = xMultiplier2 * xMultiplier;
  5972. const yMultiplier3 = yMultiplier2 * yMultiplier;
  5973. const zMultiplier3 = zMultiplier2 * zMultiplier;
  5974. func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
  5975. const denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
  5976. const derivative = -2.0 * denominator;
  5977. correction = func / derivative;
  5978. } while (Math.abs(func) > _MathUtils.EPSILON12);
  5979. return scratchVector$5.scale([xMultiplier, yMultiplier, zMultiplier]).to(result);
  5980. }
  5981. const EPSILON14 = 1e-14;
  5982. const scratchOrigin = new Vector3();
  5983. const VECTOR_PRODUCT_LOCAL_FRAME = {
  5984. up: {
  5985. south: 'east',
  5986. north: 'west',
  5987. west: 'south',
  5988. east: 'north'
  5989. },
  5990. down: {
  5991. south: 'west',
  5992. north: 'east',
  5993. west: 'north',
  5994. east: 'south'
  5995. },
  5996. south: {
  5997. up: 'west',
  5998. down: 'east',
  5999. west: 'down',
  6000. east: 'up'
  6001. },
  6002. north: {
  6003. up: 'east',
  6004. down: 'west',
  6005. west: 'up',
  6006. east: 'down'
  6007. },
  6008. west: {
  6009. up: 'north',
  6010. down: 'south',
  6011. north: 'down',
  6012. south: 'up'
  6013. },
  6014. east: {
  6015. up: 'south',
  6016. down: 'north',
  6017. north: 'up',
  6018. south: 'down'
  6019. }
  6020. };
  6021. const degeneratePositionLocalFrame = {
  6022. north: [-1, 0, 0],
  6023. east: [0, 1, 0],
  6024. up: [0, 0, 1],
  6025. south: [1, 0, 0],
  6026. west: [0, -1, 0],
  6027. down: [0, 0, -1]
  6028. };
  6029. const scratchAxisVectors = {
  6030. east: new Vector3(),
  6031. north: new Vector3(),
  6032. up: new Vector3(),
  6033. west: new Vector3(),
  6034. south: new Vector3(),
  6035. down: new Vector3()
  6036. };
  6037. const scratchVector1 = new Vector3();
  6038. const scratchVector2$1 = new Vector3();
  6039. const scratchVector3$1 = new Vector3();
  6040. function localFrameToFixedFrame(ellipsoid, firstAxis, secondAxis, thirdAxis, cartesianOrigin, result) {
  6041. const thirdAxisInferred = VECTOR_PRODUCT_LOCAL_FRAME[firstAxis] && VECTOR_PRODUCT_LOCAL_FRAME[firstAxis][secondAxis];
  6042. assert$4(thirdAxisInferred && (!thirdAxis || thirdAxis === thirdAxisInferred));
  6043. let firstAxisVector;
  6044. let secondAxisVector;
  6045. let thirdAxisVector;
  6046. const origin = scratchOrigin.copy(cartesianOrigin);
  6047. const atPole = equals(origin.x, 0.0, EPSILON14) && equals(origin.y, 0.0, EPSILON14);
  6048. if (atPole) {
  6049. const sign = Math.sign(origin.z);
  6050. firstAxisVector = scratchVector1.fromArray(degeneratePositionLocalFrame[firstAxis]);
  6051. if (firstAxis !== 'east' && firstAxis !== 'west') {
  6052. firstAxisVector.scale(sign);
  6053. }
  6054. secondAxisVector = scratchVector2$1.fromArray(degeneratePositionLocalFrame[secondAxis]);
  6055. if (secondAxis !== 'east' && secondAxis !== 'west') {
  6056. secondAxisVector.scale(sign);
  6057. }
  6058. thirdAxisVector = scratchVector3$1.fromArray(degeneratePositionLocalFrame[thirdAxis]);
  6059. if (thirdAxis !== 'east' && thirdAxis !== 'west') {
  6060. thirdAxisVector.scale(sign);
  6061. }
  6062. } else {
  6063. const {
  6064. up,
  6065. east,
  6066. north
  6067. } = scratchAxisVectors;
  6068. east.set(-origin.y, origin.x, 0.0).normalize();
  6069. ellipsoid.geodeticSurfaceNormal(origin, up);
  6070. north.copy(up).cross(east);
  6071. const {
  6072. down,
  6073. west,
  6074. south
  6075. } = scratchAxisVectors;
  6076. down.copy(up).scale(-1);
  6077. west.copy(east).scale(-1);
  6078. south.copy(north).scale(-1);
  6079. firstAxisVector = scratchAxisVectors[firstAxis];
  6080. secondAxisVector = scratchAxisVectors[secondAxis];
  6081. thirdAxisVector = scratchAxisVectors[thirdAxis];
  6082. }
  6083. result[0] = firstAxisVector.x;
  6084. result[1] = firstAxisVector.y;
  6085. result[2] = firstAxisVector.z;
  6086. result[3] = 0.0;
  6087. result[4] = secondAxisVector.x;
  6088. result[5] = secondAxisVector.y;
  6089. result[6] = secondAxisVector.z;
  6090. result[7] = 0.0;
  6091. result[8] = thirdAxisVector.x;
  6092. result[9] = thirdAxisVector.y;
  6093. result[10] = thirdAxisVector.z;
  6094. result[11] = 0.0;
  6095. result[12] = origin.x;
  6096. result[13] = origin.y;
  6097. result[14] = origin.z;
  6098. result[15] = 1.0;
  6099. return result;
  6100. }
  6101. const scratchVector$4 = new Vector3();
  6102. const scratchNormal$2 = new Vector3();
  6103. const scratchK = new Vector3();
  6104. const scratchPosition$2 = new Vector3();
  6105. const scratchHeight = new Vector3();
  6106. const scratchCartesian = new Vector3();
  6107. let wgs84;
  6108. class Ellipsoid {
  6109. static get WGS84() {
  6110. wgs84 = wgs84 || new Ellipsoid(WGS84_RADIUS_X$1, WGS84_RADIUS_Y$1, WGS84_RADIUS_Z$1);
  6111. return wgs84;
  6112. }
  6113. constructor(x = 0.0, y = 0.0, z = 0.0) {
  6114. assert$4(x >= 0.0);
  6115. assert$4(y >= 0.0);
  6116. assert$4(z >= 0.0);
  6117. this.radii = new Vector3(x, y, z);
  6118. this.radiiSquared = new Vector3(x * x, y * y, z * z);
  6119. this.radiiToTheFourth = new Vector3(x * x * x * x, y * y * y * y, z * z * z * z);
  6120. 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);
  6121. 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));
  6122. this.minimumRadius = Math.min(x, y, z);
  6123. this.maximumRadius = Math.max(x, y, z);
  6124. this.centerToleranceSquared = _MathUtils.EPSILON1;
  6125. if (this.radiiSquared.z !== 0) {
  6126. this.squaredXOverSquaredZ = this.radiiSquared.x / this.radiiSquared.z;
  6127. }
  6128. Object.freeze(this);
  6129. }
  6130. equals(right) {
  6131. return this === right || Boolean(right && this.radii.equals(right.radii));
  6132. }
  6133. toString() {
  6134. return this.radii.toString();
  6135. }
  6136. cartographicToCartesian(cartographic, result = [0, 0, 0]) {
  6137. const normal = scratchNormal$2;
  6138. const k = scratchK;
  6139. const [,, height] = cartographic;
  6140. this.geodeticSurfaceNormalCartographic(cartographic, normal);
  6141. k.copy(this.radiiSquared).scale(normal);
  6142. const gamma = Math.sqrt(normal.dot(k));
  6143. k.scale(1 / gamma);
  6144. normal.scale(height);
  6145. k.add(normal);
  6146. return k.to(result);
  6147. }
  6148. cartesianToCartographic(cartesian, result = [0, 0, 0]) {
  6149. scratchCartesian.from(cartesian);
  6150. const point = this.scaleToGeodeticSurface(scratchCartesian, scratchPosition$2);
  6151. if (!point) {
  6152. return undefined;
  6153. }
  6154. const normal = this.geodeticSurfaceNormal(point, scratchNormal$2);
  6155. const h = scratchHeight;
  6156. h.copy(scratchCartesian).subtract(point);
  6157. const longitude = Math.atan2(normal.y, normal.x);
  6158. const latitude = Math.asin(normal.z);
  6159. const height = Math.sign(dot$2(h, scratchCartesian)) * length$2(h);
  6160. return toCartographicFromRadians([longitude, latitude, height], result);
  6161. }
  6162. eastNorthUpToFixedFrame(origin, result = new Matrix4()) {
  6163. return localFrameToFixedFrame(this, 'east', 'north', 'up', origin, result);
  6164. }
  6165. localFrameToFixedFrame(firstAxis, secondAxis, thirdAxis, origin, result = new Matrix4()) {
  6166. return localFrameToFixedFrame(this, firstAxis, secondAxis, thirdAxis, origin, result);
  6167. }
  6168. geocentricSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6169. return scratchVector$4.from(cartesian).normalize().to(result);
  6170. }
  6171. geodeticSurfaceNormalCartographic(cartographic, result = [0, 0, 0]) {
  6172. const cartographicVectorRadians = fromCartographicToRadians(cartographic);
  6173. const longitude = cartographicVectorRadians[0];
  6174. const latitude = cartographicVectorRadians[1];
  6175. const cosLatitude = Math.cos(latitude);
  6176. scratchVector$4.set(cosLatitude * Math.cos(longitude), cosLatitude * Math.sin(longitude), Math.sin(latitude)).normalize();
  6177. return scratchVector$4.to(result);
  6178. }
  6179. geodeticSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6180. return scratchVector$4.from(cartesian).scale(this.oneOverRadiiSquared).normalize().to(result);
  6181. }
  6182. scaleToGeodeticSurface(cartesian, result) {
  6183. return scaleToGeodeticSurface(cartesian, this, result);
  6184. }
  6185. scaleToGeocentricSurface(cartesian, result = [0, 0, 0]) {
  6186. scratchPosition$2.from(cartesian);
  6187. const positionX = scratchPosition$2.x;
  6188. const positionY = scratchPosition$2.y;
  6189. const positionZ = scratchPosition$2.z;
  6190. const oneOverRadiiSquared = this.oneOverRadiiSquared;
  6191. const beta = 1.0 / Math.sqrt(positionX * positionX * oneOverRadiiSquared.x + positionY * positionY * oneOverRadiiSquared.y + positionZ * positionZ * oneOverRadiiSquared.z);
  6192. return scratchPosition$2.multiplyScalar(beta).to(result);
  6193. }
  6194. transformPositionToScaledSpace(position, result = [0, 0, 0]) {
  6195. return scratchPosition$2.from(position).scale(this.oneOverRadii).to(result);
  6196. }
  6197. transformPositionFromScaledSpace(position, result = [0, 0, 0]) {
  6198. return scratchPosition$2.from(position).scale(this.radii).to(result);
  6199. }
  6200. getSurfaceNormalIntersectionWithZAxis(position, buffer = 0.0, result = [0, 0, 0]) {
  6201. assert$4(equals(this.radii.x, this.radii.y, _MathUtils.EPSILON15));
  6202. assert$4(this.radii.z > 0);
  6203. scratchPosition$2.from(position);
  6204. const z = scratchPosition$2.z * (1 - this.squaredXOverSquaredZ);
  6205. if (Math.abs(z) >= this.radii.z - buffer) {
  6206. return undefined;
  6207. }
  6208. return scratchPosition$2.set(0.0, 0.0, z).to(result);
  6209. }
  6210. }
  6211. class DoublyLinkedListNode {
  6212. constructor(item, previous, next) {
  6213. _defineProperty(this, "item", void 0);
  6214. _defineProperty(this, "previous", void 0);
  6215. _defineProperty(this, "next", void 0);
  6216. this.item = item;
  6217. this.previous = previous;
  6218. this.next = next;
  6219. }
  6220. }
  6221. class DoublyLinkedList {
  6222. constructor() {
  6223. _defineProperty(this, "head", null);
  6224. _defineProperty(this, "tail", null);
  6225. _defineProperty(this, "_length", 0);
  6226. }
  6227. get length() {
  6228. return this._length;
  6229. }
  6230. add(item) {
  6231. const node = new DoublyLinkedListNode(item, this.tail, null);
  6232. if (this.tail) {
  6233. this.tail.next = node;
  6234. this.tail = node;
  6235. } else {
  6236. this.head = node;
  6237. this.tail = node;
  6238. }
  6239. ++this._length;
  6240. return node;
  6241. }
  6242. remove(node) {
  6243. if (!node) {
  6244. return;
  6245. }
  6246. if (node.previous && node.next) {
  6247. node.previous.next = node.next;
  6248. node.next.previous = node.previous;
  6249. } else if (node.previous) {
  6250. node.previous.next = null;
  6251. this.tail = node.previous;
  6252. } else if (node.next) {
  6253. node.next.previous = null;
  6254. this.head = node.next;
  6255. } else {
  6256. this.head = null;
  6257. this.tail = null;
  6258. }
  6259. node.next = null;
  6260. node.previous = null;
  6261. --this._length;
  6262. }
  6263. splice(node, nextNode) {
  6264. if (node === nextNode) {
  6265. return;
  6266. }
  6267. this.remove(nextNode);
  6268. this._insert(node, nextNode);
  6269. }
  6270. _insert(node, nextNode) {
  6271. const oldNodeNext = node.next;
  6272. node.next = nextNode;
  6273. if (this.tail === node) {
  6274. this.tail = nextNode;
  6275. } else {
  6276. oldNodeNext.previous = nextNode;
  6277. }
  6278. nextNode.next = oldNodeNext;
  6279. nextNode.previous = node;
  6280. ++this._length;
  6281. }
  6282. }
  6283. function defined$5(x) {
  6284. return x !== undefined && x !== null;
  6285. }
  6286. class TilesetCache {
  6287. constructor() {
  6288. _defineProperty(this, "_list", void 0);
  6289. _defineProperty(this, "_sentinel", void 0);
  6290. _defineProperty(this, "_trimTiles", void 0);
  6291. this._list = new DoublyLinkedList();
  6292. this._sentinel = this._list.add('sentinel');
  6293. this._trimTiles = false;
  6294. }
  6295. reset() {
  6296. this._list.splice(this._list.tail, this._sentinel);
  6297. }
  6298. touch(tile) {
  6299. const node = tile._cacheNode;
  6300. if (defined$5(node)) {
  6301. this._list.splice(this._sentinel, node);
  6302. }
  6303. }
  6304. add(tileset, tile, addCallback) {
  6305. if (!defined$5(tile._cacheNode)) {
  6306. tile._cacheNode = this._list.add(tile);
  6307. if (addCallback) {
  6308. addCallback(tileset, tile);
  6309. }
  6310. }
  6311. }
  6312. unloadTile(tileset, tile, unloadCallback) {
  6313. const node = tile._cacheNode;
  6314. if (!defined$5(node)) {
  6315. return;
  6316. }
  6317. this._list.remove(node);
  6318. tile._cacheNode = undefined;
  6319. if (unloadCallback) {
  6320. unloadCallback(tileset, tile);
  6321. }
  6322. }
  6323. unloadTiles(tileset, unloadCallback) {
  6324. const trimTiles = this._trimTiles;
  6325. this._trimTiles = false;
  6326. const list = this._list;
  6327. const maximumMemoryUsageInBytes = (Potree.settings.tiles3DMaxMemory || tileset.maximumMemoryUsage) * 1024 * 1024;
  6328. const sentinel = this._sentinel;
  6329. let node = list.head;
  6330. /* while (node !== sentinel && (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)) {
  6331. const tile = node.item;
  6332. node = node.next;
  6333. this.unloadTile(tileset, tile, unloadCallback);
  6334. } */
  6335. //改
  6336. while (node !== sentinel && ( getGpuMemoryUsage() > maximumMemoryUsageInBytes || trimTiles)) {
  6337. const tile = node.item;
  6338. node = node.next;
  6339. this.unloadTile(tileset, tile, unloadCallback);
  6340. }
  6341. }
  6342. trim() {
  6343. this._trimTiles = true;
  6344. }
  6345. }
  6346. function calculateTransformProps(tileHeader, tile) {
  6347. assert$7(tileHeader);
  6348. assert$7(tile);
  6349. const {
  6350. rtcCenter,
  6351. gltfUpAxis
  6352. } = tile;
  6353. const {
  6354. computedTransform,
  6355. boundingVolume: {
  6356. center
  6357. }
  6358. } = tileHeader;
  6359. let modelMatrix = new Matrix4(computedTransform);
  6360. if (rtcCenter) {
  6361. modelMatrix.translate(rtcCenter);
  6362. }
  6363. switch (gltfUpAxis) {
  6364. case 'Z':
  6365. break;
  6366. case 'Y':
  6367. const rotationY = new Matrix4().rotateX(Math.PI / 2);
  6368. modelMatrix = modelMatrix.multiplyRight(rotationY);
  6369. break;
  6370. case 'X':
  6371. const rotationX = new Matrix4().rotateY(-Math.PI / 2);
  6372. modelMatrix = modelMatrix.multiplyRight(rotationX);
  6373. break;
  6374. }
  6375. if (tile.isQuantized) {
  6376. modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale);
  6377. }
  6378. const cartesianOrigin = new Vector3(center);
  6379. tile.cartesianModelMatrix = modelMatrix;
  6380. tile.cartesianOrigin = cartesianOrigin;
  6381. const cartographicOrigin = Ellipsoid.WGS84.cartesianToCartographic(cartesianOrigin, new Vector3());
  6382. const fromFixedFrameMatrix = Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin);
  6383. const toFixedFrameMatrix = fromFixedFrameMatrix.invert();
  6384. tile.cartographicModelMatrix = toFixedFrameMatrix.multiplyRight(modelMatrix);
  6385. tile.cartographicOrigin = cartographicOrigin;
  6386. if (!tile.coordinateSystem) {
  6387. tile.modelMatrix = tile.cartographicModelMatrix;
  6388. }
  6389. }
  6390. const INTERSECTION = Object.freeze({
  6391. OUTSIDE: -1,
  6392. INTERSECTING: 0,
  6393. INSIDE: 1
  6394. });
  6395. new Vector3();
  6396. new Vector3();
  6397. const scratchVector$3 = new Vector3();
  6398. const scratchVector2 = new Vector3();
  6399. class BoundingSphere {
  6400. constructor(center = [0, 0, 0], radius = 0.0) {
  6401. this.radius = -0;
  6402. this.center = new Vector3();
  6403. this.fromCenterRadius(center, radius);
  6404. }
  6405. fromCenterRadius(center, radius) {
  6406. this.center.from(center);
  6407. this.radius = radius;
  6408. return this;
  6409. }
  6410. fromCornerPoints(corner, oppositeCorner) {
  6411. oppositeCorner = scratchVector$3.from(oppositeCorner);
  6412. this.center = new Vector3().from(corner).add(oppositeCorner).scale(0.5);
  6413. this.radius = this.center.distance(oppositeCorner);
  6414. return this;
  6415. }
  6416. equals(right) {
  6417. return this === right || Boolean(right) && this.center.equals(right.center) && this.radius === right.radius;
  6418. }
  6419. clone() {
  6420. return new BoundingSphere(this.center, this.radius);
  6421. }
  6422. union(boundingSphere) {
  6423. const leftCenter = this.center;
  6424. const leftRadius = this.radius;
  6425. const rightCenter = boundingSphere.center;
  6426. const rightRadius = boundingSphere.radius;
  6427. const toRightCenter = scratchVector$3.copy(rightCenter).subtract(leftCenter);
  6428. const centerSeparation = toRightCenter.magnitude();
  6429. if (leftRadius >= centerSeparation + rightRadius) {
  6430. return this.clone();
  6431. }
  6432. if (rightRadius >= centerSeparation + leftRadius) {
  6433. return boundingSphere.clone();
  6434. }
  6435. const halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  6436. scratchVector2.copy(toRightCenter).scale((-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation).add(leftCenter);
  6437. this.center.copy(scratchVector2);
  6438. this.radius = halfDistanceBetweenTangentPoints;
  6439. return this;
  6440. }
  6441. expand(point) {
  6442. point = scratchVector$3.from(point);
  6443. const radius = point.subtract(this.center).magnitude();
  6444. if (radius > this.radius) {
  6445. this.radius = radius;
  6446. }
  6447. return this;
  6448. }
  6449. transform(transform) {
  6450. this.center.transform(transform);
  6451. const scale = getScaling(scratchVector$3, transform);
  6452. this.radius = Math.max(scale[0], Math.max(scale[1], scale[2])) * this.radius;
  6453. return this;
  6454. }
  6455. distanceSquaredTo(point) {
  6456. const d = this.distanceTo(point);
  6457. return d * d;
  6458. }
  6459. distanceTo(point) {
  6460. point = scratchVector$3.from(point);
  6461. const delta = point.subtract(this.center);
  6462. return Math.max(0, delta.len() - this.radius);
  6463. }
  6464. intersectPlane(plane) {
  6465. const center = this.center;
  6466. const radius = this.radius;
  6467. const normal = plane.normal;
  6468. const distanceToPlane = normal.dot(center) + plane.distance;
  6469. if (distanceToPlane < -radius) {
  6470. return INTERSECTION.OUTSIDE;
  6471. }
  6472. if (distanceToPlane < radius) {
  6473. return INTERSECTION.INTERSECTING;
  6474. }
  6475. return INTERSECTION.INSIDE;
  6476. }
  6477. }
  6478. const scratchVector3 = new Vector3();
  6479. const scratchOffset = new Vector3();
  6480. const scratchVectorU = new Vector3();
  6481. const scratchVectorV = new Vector3();
  6482. const scratchVectorW = new Vector3();
  6483. const scratchCorner = new Vector3();
  6484. const scratchToCenter = new Vector3();
  6485. const MATRIX3 = {
  6486. COLUMN0ROW0: 0,
  6487. COLUMN0ROW1: 1,
  6488. COLUMN0ROW2: 2,
  6489. COLUMN1ROW0: 3,
  6490. COLUMN1ROW1: 4,
  6491. COLUMN1ROW2: 5,
  6492. COLUMN2ROW0: 6,
  6493. COLUMN2ROW1: 7,
  6494. COLUMN2ROW2: 8
  6495. };
  6496. class OrientedBoundingBox {
  6497. constructor(center = [0, 0, 0], halfAxes = [0, 0, 0, 0, 0, 0, 0, 0, 0]) {
  6498. this.center = new Vector3().from(center);
  6499. this.halfAxes = new Matrix3(halfAxes);
  6500. }
  6501. get halfSize() {
  6502. const xAxis = this.halfAxes.getColumn(0);
  6503. const yAxis = this.halfAxes.getColumn(1);
  6504. const zAxis = this.halfAxes.getColumn(2);
  6505. return [new Vector3(xAxis).len(), new Vector3(yAxis).len(), new Vector3(zAxis).len()];
  6506. }
  6507. get quaternion() {
  6508. const xAxis = this.halfAxes.getColumn(0);
  6509. const yAxis = this.halfAxes.getColumn(1);
  6510. const zAxis = this.halfAxes.getColumn(2);
  6511. const normXAxis = new Vector3(xAxis).normalize();
  6512. const normYAxis = new Vector3(yAxis).normalize();
  6513. const normZAxis = new Vector3(zAxis).normalize();
  6514. return new Quaternion().fromMatrix3(new Matrix3([...normXAxis, ...normYAxis, ...normZAxis]));
  6515. }
  6516. fromCenterHalfSizeQuaternion(center, halfSize, quaternion) {
  6517. const quaternionObject = new Quaternion(quaternion);
  6518. const directionsMatrix = new Matrix3().fromQuaternion(quaternionObject);
  6519. directionsMatrix[0] = directionsMatrix[0] * halfSize[0];
  6520. directionsMatrix[1] = directionsMatrix[1] * halfSize[0];
  6521. directionsMatrix[2] = directionsMatrix[2] * halfSize[0];
  6522. directionsMatrix[3] = directionsMatrix[3] * halfSize[1];
  6523. directionsMatrix[4] = directionsMatrix[4] * halfSize[1];
  6524. directionsMatrix[5] = directionsMatrix[5] * halfSize[1];
  6525. directionsMatrix[6] = directionsMatrix[6] * halfSize[2];
  6526. directionsMatrix[7] = directionsMatrix[7] * halfSize[2];
  6527. directionsMatrix[8] = directionsMatrix[8] * halfSize[2];
  6528. this.center = new Vector3().from(center);
  6529. this.halfAxes = directionsMatrix;
  6530. return this;
  6531. }
  6532. clone() {
  6533. return new OrientedBoundingBox(this.center, this.halfAxes);
  6534. }
  6535. equals(right) {
  6536. return this === right || Boolean(right) && this.center.equals(right.center) && this.halfAxes.equals(right.halfAxes);
  6537. }
  6538. getBoundingSphere(result = new BoundingSphere()) {
  6539. const halfAxes = this.halfAxes;
  6540. const u = halfAxes.getColumn(0, scratchVectorU);//前三个
  6541. const v = halfAxes.getColumn(1, scratchVectorV);
  6542. const w = halfAxes.getColumn(2, scratchVectorW);
  6543. const cornerVector = scratchVector3.copy(u).add(v).add(w);
  6544. result.center.copy(this.center);
  6545. result.radius = cornerVector.magnitude();
  6546. return result;
  6547. }
  6548. intersectPlane(plane) {
  6549. const center = this.center;
  6550. const normal = plane.normal;
  6551. const halfAxes = this.halfAxes;
  6552. const normalX = normal.x;
  6553. const normalY = normal.y;
  6554. const normalZ = normal.z;
  6555. 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]);
  6556. const distanceToPlane = normal.dot(center) + plane.distance;
  6557. if (distanceToPlane <= -radEffective) {
  6558. return INTERSECTION.OUTSIDE;
  6559. } else if (distanceToPlane >= radEffective) {
  6560. return INTERSECTION.INSIDE;
  6561. }
  6562. return INTERSECTION.INTERSECTING; //在相机frustum内
  6563. }
  6564. distanceTo(point) {
  6565. return Math.sqrt(this.distanceSquaredTo(point));
  6566. }
  6567. /* distanceSquaredTo(point) {//相机到bound外壳的距离平方
  6568. let center = this.center.clone()
  6569. center.z *= -1
  6570. const offset = scratchOffset.from(point).subtract(center);
  6571. const halfAxes = this.halfAxes;
  6572. const u = halfAxes.getColumn(0, scratchVectorU);
  6573. const v = halfAxes.getColumn(1, scratchVectorV);
  6574. const w = halfAxes.getColumn(2, scratchVectorW);
  6575. u.z *= -1
  6576. v.z *= -1
  6577. w.z *= -1
  6578. const uHalf = u.magnitude();
  6579. const vHalf = v.magnitude();
  6580. const wHalf = w.magnitude();
  6581. u.normalize();
  6582. v.normalize();
  6583. w.normalize();
  6584. let distanceSquared = 0.0;
  6585. let d;
  6586. d = Math.abs(offset.dot(u)) - uHalf;
  6587. if (d > 0) {
  6588. distanceSquared += d * d;
  6589. }
  6590. d = Math.abs(offset.dot(v)) - vHalf;
  6591. if (d > 0) {
  6592. distanceSquared += d * d;
  6593. }
  6594. d = Math.abs(offset.dot(w)) - wHalf;
  6595. if (d > 0) {
  6596. distanceSquared += d * d;
  6597. }
  6598. return distanceSquared;
  6599. } */
  6600. distanceSquaredTo(point) {//相机到bound外壳的距离平方
  6601. const offset = scratchOffset.from(point).subtract(this.center);
  6602. const halfAxes = this.halfAxes;
  6603. const u = halfAxes.getColumn(0, scratchVectorU);
  6604. const v = halfAxes.getColumn(1, scratchVectorV);
  6605. const w = halfAxes.getColumn(2, scratchVectorW);
  6606. const uHalf = u.magnitude();
  6607. const vHalf = v.magnitude();
  6608. const wHalf = w.magnitude();
  6609. u.normalize();
  6610. v.normalize();
  6611. w.normalize();
  6612. let distanceSquared = 0.0;
  6613. let d;
  6614. d = Math.abs(offset.dot(u)) - uHalf;
  6615. if (d > 0) {
  6616. distanceSquared += d * d;
  6617. }
  6618. d = Math.abs(offset.dot(v)) - vHalf;
  6619. if (d > 0) {
  6620. distanceSquared += d * d;
  6621. }
  6622. d = Math.abs(offset.dot(w)) - wHalf;
  6623. if (d > 0) {
  6624. distanceSquared += d * d;
  6625. }
  6626. return distanceSquared;
  6627. }
  6628. computePlaneDistances(position, direction, result = [-0, -0]) {
  6629. let minDist = Number.POSITIVE_INFINITY;
  6630. let maxDist = Number.NEGATIVE_INFINITY;
  6631. const center = this.center;
  6632. const halfAxes = this.halfAxes;
  6633. const u = halfAxes.getColumn(0, scratchVectorU);
  6634. const v = halfAxes.getColumn(1, scratchVectorV);
  6635. const w = halfAxes.getColumn(2, scratchVectorW);
  6636. const corner = scratchCorner.copy(u).add(v).add(w).add(center);
  6637. const toCenter = scratchToCenter.copy(corner).subtract(position);
  6638. let mag = direction.dot(toCenter);
  6639. minDist = Math.min(mag, minDist);
  6640. maxDist = Math.max(mag, maxDist);
  6641. corner.copy(center).add(u).add(v).subtract(w);
  6642. toCenter.copy(corner).subtract(position);
  6643. mag = direction.dot(toCenter);
  6644. minDist = Math.min(mag, minDist);
  6645. maxDist = Math.max(mag, maxDist);
  6646. corner.copy(center).add(u).subtract(v).add(w);
  6647. toCenter.copy(corner).subtract(position);
  6648. mag = direction.dot(toCenter);
  6649. minDist = Math.min(mag, minDist);
  6650. maxDist = Math.max(mag, maxDist);
  6651. corner.copy(center).add(u).subtract(v).subtract(w);
  6652. toCenter.copy(corner).subtract(position);
  6653. mag = direction.dot(toCenter);
  6654. minDist = Math.min(mag, minDist);
  6655. maxDist = Math.max(mag, maxDist);
  6656. center.copy(corner).subtract(u).add(v).add(w);
  6657. toCenter.copy(corner).subtract(position);
  6658. mag = direction.dot(toCenter);
  6659. minDist = Math.min(mag, minDist);
  6660. maxDist = Math.max(mag, maxDist);
  6661. center.copy(corner).subtract(u).add(v).subtract(w);
  6662. toCenter.copy(corner).subtract(position);
  6663. mag = direction.dot(toCenter);
  6664. minDist = Math.min(mag, minDist);
  6665. maxDist = Math.max(mag, maxDist);
  6666. center.copy(corner).subtract(u).subtract(v).add(w);
  6667. toCenter.copy(corner).subtract(position);
  6668. mag = direction.dot(toCenter);
  6669. minDist = Math.min(mag, minDist);
  6670. maxDist = Math.max(mag, maxDist);
  6671. center.copy(corner).subtract(u).subtract(v).subtract(w);
  6672. toCenter.copy(corner).subtract(position);
  6673. mag = direction.dot(toCenter);
  6674. minDist = Math.min(mag, minDist);
  6675. maxDist = Math.max(mag, maxDist);
  6676. result[0] = minDist;
  6677. result[1] = maxDist;
  6678. return result;
  6679. }
  6680. transform(transformation) {
  6681. this.center.transformAsPoint(transformation);
  6682. const xAxis = this.halfAxes.getColumn(0, scratchVectorU);
  6683. xAxis.transformAsPoint(transformation);
  6684. const yAxis = this.halfAxes.getColumn(1, scratchVectorV);
  6685. yAxis.transformAsPoint(transformation);
  6686. const zAxis = this.halfAxes.getColumn(2, scratchVectorW);
  6687. zAxis.transformAsPoint(transformation);
  6688. this.halfAxes = new Matrix3([...xAxis, ...yAxis, ...zAxis]);
  6689. return this;
  6690. }
  6691. getTransform() {
  6692. throw new Error('not implemented');
  6693. }
  6694. }
  6695. const scratchPosition$1 = new Vector3();
  6696. const scratchNormal$1 = new Vector3();
  6697. class Plane {
  6698. constructor(normal = [0, 0, 1], distance = 0) {
  6699. this.normal = new Vector3();
  6700. this.distance = -0;
  6701. this.fromNormalDistance(normal, distance);
  6702. }
  6703. fromNormalDistance(normal, distance) {
  6704. assert$4(Number.isFinite(distance));
  6705. this.normal.from(normal).normalize();
  6706. this.distance = distance;
  6707. return this;
  6708. }
  6709. fromPointNormal(point, normal) {
  6710. point = scratchPosition$1.from(point);
  6711. this.normal.from(normal).normalize();
  6712. const distance = -this.normal.dot(point);
  6713. this.distance = distance;
  6714. return this;
  6715. }
  6716. fromCoefficients(a, b, c, d) {
  6717. this.normal.set(a, b, c);
  6718. assert$4(equals(this.normal.len(), 1));
  6719. this.distance = d;
  6720. return this;
  6721. }
  6722. clone(plane) {
  6723. return new Plane(this.normal, this.distance);
  6724. }
  6725. equals(right) {
  6726. return equals(this.distance, right.distance) && equals(this.normal, right.normal);
  6727. }
  6728. getPointDistance(point) {
  6729. return this.normal.dot(point) + this.distance;
  6730. }
  6731. transform(matrix4) {
  6732. const normal = scratchNormal$1.copy(this.normal).transformAsVector(matrix4).normalize();
  6733. const point = this.normal.scale(-this.distance).transform(matrix4);
  6734. return this.fromPointNormal(point, normal);
  6735. }
  6736. projectPointOntoPlane(point, result = [0, 0, 0]) {
  6737. point = scratchPosition$1.from(point);
  6738. const pointDistance = this.getPointDistance(point);
  6739. const scaledNormal = scratchNormal$1.copy(this.normal).scale(pointDistance);
  6740. return point.subtract(scaledNormal).to(result);
  6741. }
  6742. }
  6743. const faces = [new Vector3([1, 0, 0]), new Vector3([0, 1, 0]), new Vector3([0, 0, 1])];
  6744. const scratchPlaneCenter = new Vector3();
  6745. const scratchPlaneNormal$1 = new Vector3();
  6746. new Plane(new Vector3(1.0, 0.0, 0.0), 0.0);
  6747. class CullingVolume {
  6748. static get MASK_OUTSIDE() {
  6749. return 0xffffffff;
  6750. }
  6751. static get MASK_INSIDE() {
  6752. return 0x00000000;
  6753. }
  6754. static get MASK_INDETERMINATE() {
  6755. return 0x7fffffff;
  6756. }
  6757. constructor(planes = []) {
  6758. this.planes = planes;
  6759. assert$4(this.planes.every(plane => plane instanceof Plane));
  6760. }
  6761. fromBoundingSphere(boundingSphere) {
  6762. this.planes.length = 2 * faces.length;
  6763. const center = boundingSphere.center;
  6764. const radius = boundingSphere.radius;
  6765. let planeIndex = 0;
  6766. for (const faceNormal of faces) {
  6767. let plane0 = this.planes[planeIndex];
  6768. let plane1 = this.planes[planeIndex + 1];
  6769. if (!plane0) {
  6770. plane0 = this.planes[planeIndex] = new Plane();
  6771. }
  6772. if (!plane1) {
  6773. plane1 = this.planes[planeIndex + 1] = new Plane();
  6774. }
  6775. const plane0Center = scratchPlaneCenter.copy(faceNormal).scale(-radius).add(center);
  6776. -faceNormal.dot(plane0Center);
  6777. plane0.fromPointNormal(plane0Center, faceNormal);
  6778. const plane1Center = scratchPlaneCenter.copy(faceNormal).scale(radius).add(center);
  6779. const negatedFaceNormal = scratchPlaneNormal$1.copy(faceNormal).negate();
  6780. -negatedFaceNormal.dot(plane1Center);
  6781. plane1.fromPointNormal(plane1Center, negatedFaceNormal);
  6782. planeIndex += 2;
  6783. }
  6784. return this;
  6785. }
  6786. computeVisibility(boundingVolume) {
  6787. assert$4(boundingVolume);
  6788. let intersect = INTERSECTION.INSIDE;
  6789. for (const plane of this.planes) {
  6790. const result = boundingVolume.intersectPlane(plane);
  6791. switch (result) {
  6792. case INTERSECTION.OUTSIDE:
  6793. return INTERSECTION.OUTSIDE;
  6794. case INTERSECTION.INTERSECTING:
  6795. intersect = INTERSECTION.INTERSECTING;
  6796. break;
  6797. }
  6798. }
  6799. return intersect;
  6800. }
  6801. computeVisibilityWithPlaneMask(boundingVolume, parentPlaneMask) {
  6802. assert$4(boundingVolume, 'boundingVolume is required.');
  6803. assert$4(Number.isFinite(parentPlaneMask), 'parentPlaneMask is required.');
  6804. if (parentPlaneMask === CullingVolume.MASK_OUTSIDE || parentPlaneMask === CullingVolume.MASK_INSIDE) {
  6805. return parentPlaneMask;
  6806. }
  6807. let mask = CullingVolume.MASK_INSIDE;
  6808. const planes = this.planes;
  6809. for (let k = 0; k < this.planes.length; ++k) {
  6810. const flag = k < 31 ? 1 << k : 0;
  6811. if (k < 31 && (parentPlaneMask & flag) === 0) {
  6812. continue;
  6813. }
  6814. const plane = planes[k];
  6815. const result = boundingVolume.intersectPlane(plane);
  6816. if (result === INTERSECTION.OUTSIDE) {
  6817. return CullingVolume.MASK_OUTSIDE;
  6818. } else if (result === INTERSECTION.INTERSECTING) {
  6819. mask |= flag;
  6820. }
  6821. }
  6822. return mask;
  6823. }
  6824. }
  6825. const scratchPlaneUpVector = new Vector3();
  6826. const scratchPlaneRightVector = new Vector3();
  6827. const scratchPlaneNearCenter = new Vector3();
  6828. const scratchPlaneFarCenter = new Vector3();
  6829. const scratchPlaneNormal = new Vector3();
  6830. class PerspectiveOffCenterFrustum {
  6831. constructor(options = {}) {
  6832. options = {
  6833. near: 1.0,
  6834. far: 500000000.0,
  6835. ...options
  6836. };
  6837. this.left = options.left;
  6838. this._left = undefined;
  6839. this.right = options.right;
  6840. this._right = undefined;
  6841. this.top = options.top;
  6842. this._top = undefined;
  6843. this.bottom = options.bottom;
  6844. this._bottom = undefined;
  6845. this.near = options.near;
  6846. this._near = this.near;
  6847. this.far = options.far;
  6848. this._far = this.far;
  6849. this._cullingVolume = new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]);
  6850. this._perspectiveMatrix = new Matrix4();
  6851. this._infinitePerspective = new Matrix4();
  6852. }
  6853. clone() {
  6854. return new PerspectiveOffCenterFrustum({
  6855. right: this.right,
  6856. left: this.left,
  6857. top: this.top,
  6858. bottom: this.bottom,
  6859. near: this.near,
  6860. far: this.far
  6861. });
  6862. }
  6863. equals(other) {
  6864. 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;
  6865. }
  6866. get projectionMatrix() {
  6867. update$1(this);
  6868. return this._perspectiveMatrix;
  6869. }
  6870. get infiniteProjectionMatrix() {
  6871. update$1(this);
  6872. return this._infinitePerspective;
  6873. }
  6874. computeCullingVolume(position, direction, up) {
  6875. assert$4(position, 'position is required.');
  6876. assert$4(direction, 'direction is required.');
  6877. assert$4(up, 'up is required.');
  6878. const planes = this._cullingVolume.planes;
  6879. up = scratchPlaneUpVector.copy(up).normalize();
  6880. const right = scratchPlaneRightVector.copy(direction).cross(up).normalize();
  6881. const nearCenter = scratchPlaneNearCenter.copy(direction).multiplyByScalar(this.near).add(position);
  6882. const farCenter = scratchPlaneFarCenter.copy(direction).multiplyByScalar(this.far).add(position);
  6883. let normal = scratchPlaneNormal;
  6884. normal.copy(right).multiplyByScalar(this.left).add(nearCenter).subtract(position).cross(up);
  6885. planes[0].fromPointNormal(position, normal);
  6886. normal.copy(right).multiplyByScalar(this.right).add(nearCenter).subtract(position).cross(up).negate();
  6887. planes[1].fromPointNormal(position, normal);
  6888. normal.copy(up).multiplyByScalar(this.bottom).add(nearCenter).subtract(position).cross(right).negate();
  6889. planes[2].fromPointNormal(position, normal);
  6890. normal.copy(up).multiplyByScalar(this.top).add(nearCenter).subtract(position).cross(right);
  6891. planes[3].fromPointNormal(position, normal);
  6892. normal = new Vector3().copy(direction);
  6893. planes[4].fromPointNormal(nearCenter, normal);
  6894. normal.negate();
  6895. planes[5].fromPointNormal(farCenter, normal);
  6896. return this._cullingVolume;
  6897. }
  6898. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  6899. update$1(this);
  6900. assert$4(Number.isFinite(drawingBufferWidth) && Number.isFinite(drawingBufferHeight));
  6901. assert$4(drawingBufferWidth > 0);
  6902. assert$4(drawingBufferHeight > 0);
  6903. assert$4(distance > 0);
  6904. assert$4(result);
  6905. const inverseNear = 1.0 / this.near;
  6906. let tanTheta = this.top * inverseNear;
  6907. const pixelHeight = 2.0 * distance * tanTheta / drawingBufferHeight;
  6908. tanTheta = this.right * inverseNear;
  6909. const pixelWidth = 2.0 * distance * tanTheta / drawingBufferWidth;
  6910. result.x = pixelWidth;
  6911. result.y = pixelHeight;
  6912. return result;
  6913. }
  6914. }
  6915. function update$1(frustum) {
  6916. assert$4(Number.isFinite(frustum.right) && Number.isFinite(frustum.left) && Number.isFinite(frustum.top) && Number.isFinite(frustum.bottom) && Number.isFinite(frustum.near) && Number.isFinite(frustum.far));
  6917. const {
  6918. top,
  6919. bottom,
  6920. right,
  6921. left,
  6922. near,
  6923. far
  6924. } = frustum;
  6925. if (top !== frustum._top || bottom !== frustum._bottom || left !== frustum._left || right !== frustum._right || near !== frustum._near || far !== frustum._far) {
  6926. assert$4(frustum.near > 0 && frustum.near < frustum.far, 'near must be greater than zero and less than far.');
  6927. frustum._left = left;
  6928. frustum._right = right;
  6929. frustum._top = top;
  6930. frustum._bottom = bottom;
  6931. frustum._near = near;
  6932. frustum._far = far;
  6933. frustum._perspectiveMatrix = new Matrix4().frustum({
  6934. left,
  6935. right,
  6936. bottom,
  6937. top,
  6938. near,
  6939. far
  6940. });
  6941. frustum._infinitePerspective = new Matrix4().frustum({
  6942. left,
  6943. right,
  6944. bottom,
  6945. top,
  6946. near,
  6947. far: Infinity
  6948. });
  6949. }
  6950. }
  6951. const defined$4 = val => val !== null && typeof val !== 'undefined';
  6952. class PerspectiveFrustum {
  6953. constructor(options = {}) {
  6954. options = {
  6955. near: 1.0,
  6956. far: 500000000.0,
  6957. xOffset: 0.0,
  6958. yOffset: 0.0,
  6959. ...options
  6960. };
  6961. this._offCenterFrustum = new PerspectiveOffCenterFrustum();
  6962. this.fov = options.fov;
  6963. this._fov = undefined;
  6964. this._fovy = undefined;
  6965. this._sseDenominator = undefined;
  6966. this.aspectRatio = options.aspectRatio;
  6967. this._aspectRatio = undefined;
  6968. this.near = options.near;
  6969. this._near = this.near;
  6970. this.far = options.far;
  6971. this._far = this.far;
  6972. this.xOffset = options.xOffset;
  6973. this._xOffset = this.xOffset;
  6974. this.yOffset = options.yOffset;
  6975. this._yOffset = this.yOffset;
  6976. }
  6977. clone() {
  6978. return new PerspectiveFrustum({
  6979. aspectRatio: this.aspectRatio,
  6980. fov: this.fov,
  6981. near: this.near,
  6982. far: this.far
  6983. });
  6984. }
  6985. equals(other) {
  6986. if (!defined$4(other) || !(other instanceof PerspectiveFrustum)) {
  6987. return false;
  6988. }
  6989. update(this);
  6990. update(other);
  6991. return this.fov === other.fov && this.aspectRatio === other.aspectRatio && this.near === other.near && this.far === other.far && this._offCenterFrustum.equals(other._offCenterFrustum);
  6992. }
  6993. get projectionMatrix() {
  6994. update(this);
  6995. return this._offCenterFrustum.projectionMatrix;
  6996. }
  6997. get infiniteProjectionMatrix() {
  6998. update(this);
  6999. return this._offCenterFrustum.infiniteProjectionMatrix;
  7000. }
  7001. get fovy() {
  7002. update(this);
  7003. return this._fovy;
  7004. }
  7005. get sseDenominator() {
  7006. update(this);
  7007. return this._sseDenominator;
  7008. }
  7009. computeCullingVolume(position, direction, up) {
  7010. update(this);
  7011. return this._offCenterFrustum.computeCullingVolume(position, direction, up);
  7012. }
  7013. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  7014. update(this);
  7015. return this._offCenterFrustum.getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result);
  7016. }
  7017. }
  7018. function update(frustum) {
  7019. assert$4(Number.isFinite(frustum.fov) && Number.isFinite(frustum.aspectRatio) && Number.isFinite(frustum.near) && Number.isFinite(frustum.far));
  7020. const f = frustum._offCenterFrustum;
  7021. if (frustum.fov !== frustum._fov || frustum.aspectRatio !== frustum._aspectRatio || frustum.near !== frustum._near || frustum.far !== frustum._far || frustum.xOffset !== frustum._xOffset || frustum.yOffset !== frustum._yOffset) {
  7022. assert$4(frustum.fov >= 0 && frustum.fov < Math.PI);
  7023. //assert$4(frustum.aspectRatio > 0);
  7024. if(frustum.aspectRatio == 0){
  7025. console.log(1)
  7026. }
  7027. assert$4(frustum.near >= 0 && frustum.near < frustum.far);
  7028. frustum._aspectRatio = Math.max(0.001, frustum.aspectRatio);
  7029. frustum._fov = frustum.fov;
  7030. frustum._fovy = frustum._aspectRatio <= 1 ? frustum.fov : Math.atan(Math.tan(frustum.fov * 0.5) / frustum._aspectRatio) * 2.0;
  7031. frustum._near = frustum.near;
  7032. frustum._far = frustum.far;
  7033. frustum._sseDenominator = 2.0 * Math.tan(0.5 * frustum._fovy);
  7034. frustum._xOffset = frustum.xOffset;
  7035. frustum._yOffset = frustum.yOffset;
  7036. f.top = frustum.near * Math.tan(0.5 * frustum._fovy);
  7037. f.bottom = -f.top;
  7038. f.right = frustum._aspectRatio * f.top;
  7039. f.left = -f.right;
  7040. f.near = frustum.near;
  7041. f.far = frustum.far;
  7042. f.right += frustum.xOffset;
  7043. f.left += frustum.xOffset;
  7044. f.top += frustum.yOffset;
  7045. f.bottom += frustum.yOffset;
  7046. }
  7047. }
  7048. new Vector3();
  7049. new Vector3();
  7050. new Vector3();
  7051. new Vector3();
  7052. new Vector3();
  7053. new Vector3();
  7054. new Vector3();
  7055. new Vector3();
  7056. new Vector3();
  7057. new Vector3();
  7058. new Vector3();
  7059. new Vector3();
  7060. new Matrix3();
  7061. new Matrix3();
  7062. new Matrix3();
  7063. new Matrix3();
  7064. new Matrix3();
  7065. new Vector3();
  7066. new Vector3();
  7067. new Vector3();
  7068. new Vector3();
  7069. new Vector3();
  7070. new Matrix3();
  7071. ({
  7072. diagonal: new Matrix3(),
  7073. unitary: new Matrix3()
  7074. });
  7075. const scratchVector$2 = new Vector3();
  7076. const scratchPosition = new Vector3();
  7077. const cullingVolume = new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]);
  7078. function getFrameState(viewport, frameNumber) {
  7079. const {
  7080. cameraDirection,
  7081. cameraUp,
  7082. height
  7083. } = viewport;
  7084. const {
  7085. metersPerUnit
  7086. } = viewport.distanceScales;
  7087. const viewportCenterCartographic = viewport.unprojectPosition(viewport.center);
  7088. const viewportCenterCartesian = Ellipsoid.WGS84.cartographicToCartesian(viewportCenterCartographic, new Vector3());
  7089. const enuToFixedTransform = Ellipsoid.WGS84.eastNorthUpToFixedFrame(viewportCenterCartesian);
  7090. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7091. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
  7092. const cameraDirectionCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraDirection).scale(metersPerUnit))).normalize();
  7093. const cameraUpCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraUp).scale(metersPerUnit))).normalize();
  7094. commonSpacePlanesToWGS84(viewport, viewportCenterCartesian);
  7095. return {
  7096. camera: {
  7097. position: cameraPositionCartesian,
  7098. direction: cameraDirectionCartesian,
  7099. up: cameraUpCartesian
  7100. },
  7101. viewport,
  7102. height,
  7103. cullingVolume,
  7104. frameNumber,
  7105. sseDenominator: 1.15
  7106. };
  7107. }
  7108. function commonSpacePlanesToWGS84(viewport, viewportCenterCartesian) {
  7109. const frustumPlanes = viewport.getFrustumPlanes();
  7110. let i = 0;
  7111. for (const dir in frustumPlanes) {
  7112. const plane = frustumPlanes[dir];
  7113. const distanceToCenter = plane.normal.dot(viewport.center);
  7114. scratchPosition.copy(plane.normal).scale(plane.distance - distanceToCenter).add(viewport.center);
  7115. const cartographicPos = viewport.unprojectPosition(scratchPosition);
  7116. const cartesianPos = Ellipsoid.WGS84.cartographicToCartesian(cartographicPos, new Vector3());
  7117. cullingVolume.planes[i++].fromPointNormal(cartesianPos, scratchVector$2.copy(viewportCenterCartesian).subtract(cartesianPos));
  7118. }
  7119. }
  7120. const WGS84_RADIUS_X = 6378137.0;
  7121. const WGS84_RADIUS_Y = 6378137.0;
  7122. const WGS84_RADIUS_Z = 6356752.3142451793;
  7123. const scratchVector$1 = new Vector3();
  7124. function getZoomFromBoundingVolume(boundingVolume) {
  7125. const {
  7126. halfAxes,
  7127. radius,
  7128. width,
  7129. height
  7130. } = boundingVolume;
  7131. if (halfAxes) {
  7132. const obbSize = getObbSize(halfAxes);
  7133. return Math.log2(WGS84_RADIUS_Z / obbSize);
  7134. } else if (radius) {
  7135. return Math.log2(WGS84_RADIUS_Z / radius);
  7136. } else if (height && width) {
  7137. const zoomX = Math.log2(WGS84_RADIUS_X / width);
  7138. const zoomY = Math.log2(WGS84_RADIUS_Y / height);
  7139. return (zoomX + zoomY) / 2;
  7140. }
  7141. return 1;
  7142. }
  7143. function getObbSize(halfAxes) {
  7144. halfAxes.getColumn(0, scratchVector$1);
  7145. const axeY = halfAxes.getColumn(1);
  7146. const axeZ = halfAxes.getColumn(2);
  7147. const farthestVertex = scratchVector$1.add(axeY).add(axeZ);
  7148. const size = farthestVertex.len();
  7149. return size;
  7150. }
  7151. const TILE_CONTENT_STATE = {
  7152. UNLOADED: 0,
  7153. LOADING: 1,
  7154. PROCESSING: 2,
  7155. READY: 3,
  7156. EXPIRED: 4,
  7157. FAILED: 5
  7158. };
  7159. const TILE_REFINEMENT = {
  7160. ADD: 1,
  7161. REPLACE: 2
  7162. };
  7163. const TILE_TYPE = {
  7164. EMPTY: 'empty',
  7165. SCENEGRAPH: 'scenegraph',
  7166. POINTCLOUD: 'pointcloud',
  7167. MESH: 'mesh'
  7168. };
  7169. const TILESET_TYPE = {
  7170. I3S: 'I3S',
  7171. TILES3D: 'TILES3D'
  7172. };
  7173. const LOD_METRIC_TYPE = {
  7174. GEOMETRIC_ERROR: 'geometricError',
  7175. MAX_SCREEN_THRESHOLD: 'maxScreenThreshold'
  7176. };
  7177. const TILE3D_OPTIMIZATION_HINT = {
  7178. NOT_COMPUTED: -1,
  7179. USE_OPTIMIZATION: 1,
  7180. SKIP_OPTIMIZATION: 0
  7181. };
  7182. function defined$3(x) {
  7183. return x !== undefined && x !== null;
  7184. }
  7185. const scratchScale = new Vector3();
  7186. const scratchNorthWest = new Vector3();
  7187. const scratchSouthEast = new Vector3();
  7188. function createBoundingVolume(boundingVolumeHeader, transform, result) {
  7189. assert$7(boundingVolumeHeader, '3D Tile: boundingVolume must be defined');
  7190. if (boundingVolumeHeader.box) {
  7191. return createBox(boundingVolumeHeader.box, transform, result);
  7192. }
  7193. if (boundingVolumeHeader.region) {
  7194. const [west, south, east, north, minHeight, maxHeight] = boundingVolumeHeader.region;
  7195. const northWest = Ellipsoid.WGS84.cartographicToCartesian([degrees(west), degrees(north), minHeight], scratchNorthWest);
  7196. const southEast = Ellipsoid.WGS84.cartographicToCartesian([degrees(east), degrees(south), maxHeight], scratchSouthEast);
  7197. const centerInCartesian = new Vector3().addVectors(northWest, southEast).multiplyScalar(0.5);
  7198. const radius = new Vector3().subVectors(northWest, southEast).len() / 2.0;
  7199. return createSphere([centerInCartesian[0], centerInCartesian[1], centerInCartesian[2], radius], new Matrix4());
  7200. }
  7201. if (boundingVolumeHeader.sphere) {
  7202. return createSphere(boundingVolumeHeader.sphere, transform, result);
  7203. }
  7204. throw new Error('3D Tile: boundingVolume must contain a sphere, region, or box');
  7205. }
  7206. function createBox(box, transform, result) {
  7207. const center = new Vector3(box[0], box[1], box[2]);
  7208. result && (result.oriCenter = center)//add
  7209. transform.transform(center, center);
  7210. let origin = [];
  7211. if (box.length === 10) {
  7212. const halfSize = box.slice(3, 6);
  7213. const quaternion = new Quaternion();
  7214. quaternion.fromArray(box, 6);
  7215. const x = new Vector3([1, 0, 0]);
  7216. const y = new Vector3([0, 1, 0]);
  7217. const z = new Vector3([0, 0, 1]);
  7218. x.transformByQuaternion(quaternion);
  7219. x.scale(halfSize[0]);
  7220. y.transformByQuaternion(quaternion);
  7221. y.scale(halfSize[1]);
  7222. z.transformByQuaternion(quaternion);
  7223. z.scale(halfSize[2]);
  7224. origin = [...x.toArray(), ...y.toArray(), ...z.toArray()];
  7225. } else {
  7226. origin = [...box.slice(3, 6), ...box.slice(6, 9), ...box.slice(9, 12)];
  7227. }
  7228. const xAxis = transform.transformAsVector(origin.slice(0, 3));
  7229. const yAxis = transform.transformAsVector(origin.slice(3, 6));
  7230. const zAxis = transform.transformAsVector(origin.slice(6, 9));
  7231. const halfAxes = new Matrix3([xAxis[0], xAxis[1], xAxis[2], yAxis[0], yAxis[1], yAxis[2], zAxis[0], zAxis[1], zAxis[2]]);
  7232. //const halfAxes = new Matrix3([xAxis[0], xAxis[1], -xAxis[2], yAxis[0], yAxis[1], -yAxis[2], zAxis[0], zAxis[1], -zAxis[2]]);//改
  7233. //center.z *= -1//add
  7234. if (defined$3(result)) {
  7235. result.center = center;
  7236. result.halfAxes = halfAxes;
  7237. return result;
  7238. }
  7239. return new OrientedBoundingBox(center, halfAxes);
  7240. }
  7241. function createSphere(sphere, transform, result) {
  7242. const center = new Vector3(sphere[0], sphere[1], sphere[2]);
  7243. transform.transform(center, center);
  7244. const scale = transform.getScale(scratchScale);
  7245. const uniformScale = Math.max(Math.max(scale[0], scale[1]), scale[2]);
  7246. const radius = sphere[3] * uniformScale;
  7247. if (defined$3(result)) {
  7248. result.center = center;
  7249. result.radius = radius;
  7250. return result;
  7251. }
  7252. return new BoundingSphere(center, radius);
  7253. }
  7254. new Vector3();
  7255. new Vector3();
  7256. new Matrix4();
  7257. new Vector3();
  7258. new Vector3();
  7259. new Vector3();
  7260. function fog(distanceToCamera, density) {
  7261. const scalar = distanceToCamera * density;
  7262. return 1.0 - Math.exp(-(scalar * scalar));
  7263. }
  7264. function getDynamicScreenSpaceError(tileset, distanceToCamera) {
  7265. if (tileset.dynamicScreenSpaceError && tileset.dynamicScreenSpaceErrorComputedDensity) {
  7266. const density = tileset.dynamicScreenSpaceErrorComputedDensity;
  7267. const factor = tileset.dynamicScreenSpaceErrorFactor;
  7268. const dynamicError = fog(distanceToCamera, density) * factor;
  7269. return dynamicError;
  7270. }
  7271. return 0;
  7272. }
  7273. function getTiles3DScreenSpaceError(tile, frameState, useParentLodMetric) {
  7274. const tileset = tile.tileset;
  7275. const parentLodMetricValue = tile.parent && tile.parent.lodMetricValue || tile.lodMetricValue;
  7276. const lodMetricValue = useParentLodMetric ? parentLodMetricValue : tile.lodMetricValue;
  7277. if (lodMetricValue === 0.0) {
  7278. return 0.0;
  7279. }
  7280. const distance = Math.max(tile._distanceToCamera, 1e-7);
  7281. const {
  7282. height,
  7283. sseDenominator
  7284. } = frameState;
  7285. const {
  7286. viewDistanceScale
  7287. } = tileset.options;
  7288. let error = lodMetricValue * height * (viewDistanceScale || 1.0) / (distance * sseDenominator);
  7289. error -= getDynamicScreenSpaceError(tileset, distance);
  7290. return error;
  7291. }
  7292. function getLodStatus(tile, frameState) {
  7293. if (tile.lodMetricValue === 0 || isNaN(tile.lodMetricValue)) {
  7294. return 'DIG';
  7295. }
  7296. const screenSize = 2 * getProjectedRadius(tile, frameState);
  7297. if (screenSize < 2) {
  7298. return 'OUT';
  7299. }
  7300. if (!tile.header.children || screenSize <= tile.lodMetricValue) {
  7301. return 'DRAW';
  7302. } else if (tile.header.children) {
  7303. return 'DIG';
  7304. }
  7305. return 'OUT';
  7306. }
  7307. function getProjectedRadius(tile, frameState) {
  7308. const originalViewport = frameState.viewport;
  7309. const ViewportClass = originalViewport.constructor;
  7310. const {
  7311. longitude,
  7312. latitude,
  7313. height,
  7314. width,
  7315. bearing,
  7316. zoom
  7317. } = originalViewport;
  7318. const viewport = new ViewportClass({
  7319. longitude,
  7320. latitude,
  7321. height,
  7322. width,
  7323. bearing,
  7324. zoom,
  7325. pitch: 0
  7326. });
  7327. const mbsLat = tile.header.mbs[1];
  7328. const mbsLon = tile.header.mbs[0];
  7329. const mbsZ = tile.header.mbs[2];
  7330. const mbsR = tile.header.mbs[3];
  7331. const mbsCenterCartesian = [...tile.boundingVolume.center];
  7332. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7333. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
  7334. const toEye = new Vector3(cameraPositionCartesian).subtract(mbsCenterCartesian).normalize();
  7335. const enuToCartesianMatrix = new Matrix4();
  7336. Ellipsoid.WGS84.eastNorthUpToFixedFrame(mbsCenterCartesian, enuToCartesianMatrix);
  7337. const cartesianToEnuMatrix = new Matrix4(enuToCartesianMatrix).invert();
  7338. const cameraPositionEnu = new Vector3(cameraPositionCartesian).transform(cartesianToEnuMatrix);
  7339. const projection = Math.sqrt(cameraPositionEnu[0] * cameraPositionEnu[0] + cameraPositionEnu[1] * cameraPositionEnu[1]);
  7340. const extraZ = projection * projection / cameraPositionEnu[2];
  7341. const extraVertexEnu = new Vector3([cameraPositionEnu[0], cameraPositionEnu[1], extraZ]);
  7342. const extraVertexCartesian = extraVertexEnu.transform(enuToCartesianMatrix);
  7343. const extraVectorCartesian = new Vector3(extraVertexCartesian).subtract(mbsCenterCartesian).normalize();
  7344. const radiusVector = toEye.cross(extraVectorCartesian).normalize().scale(mbsR);
  7345. const sphereMbsBorderVertexCartesian = new Vector3(mbsCenterCartesian).add(radiusVector);
  7346. const sphereMbsBorderVertexCartographic = Ellipsoid.WGS84.cartesianToCartographic(sphereMbsBorderVertexCartesian);
  7347. const projectedOrigin = viewport.project([mbsLon, mbsLat, mbsZ]);
  7348. const projectedMbsBorderVertex = viewport.project(sphereMbsBorderVertexCartographic);
  7349. const projectedRadius = new Vector3(projectedOrigin).subtract(projectedMbsBorderVertex).magnitude();
  7350. return projectedRadius;
  7351. }
  7352. function get3dTilesOptions(tileset) {
  7353. return {
  7354. assetGltfUpAxis: tileset.asset && tileset.asset.gltfUpAxis || 'Y'
  7355. };
  7356. }
  7357. class ManagedArray {
  7358. constructor(length = 0) {
  7359. _defineProperty(this, "_map", new Map());
  7360. _defineProperty(this, "_array", void 0);
  7361. _defineProperty(this, "_length", void 0);
  7362. this._array = new Array(length);
  7363. this._length = length;
  7364. }
  7365. get length() {
  7366. return this._length;
  7367. }
  7368. set length(length) {
  7369. this._length = length;
  7370. if (length > this._array.length) {
  7371. this._array.length = length;
  7372. }
  7373. }
  7374. get values() {
  7375. return this._array;
  7376. }
  7377. get(index) {
  7378. assert$7(index < this._array.length);
  7379. return this._array[index];
  7380. }
  7381. set(index, element) {
  7382. assert$7(index >= 0);
  7383. if (index >= this.length) {
  7384. this.length = index + 1;
  7385. }
  7386. if (this._map.has(this._array[index])) {
  7387. this._map.delete(this._array[index]);
  7388. }
  7389. this._array[index] = element;
  7390. this._map.set(element, index);
  7391. }
  7392. delete(element) {
  7393. const index = this._map.get(element);
  7394. if (index >= 0) {
  7395. this._array.splice(index, 1);
  7396. this._map.delete(element);
  7397. this.length--;
  7398. }
  7399. }
  7400. peek() {
  7401. return this._array[this._length - 1];
  7402. }
  7403. push(element) {
  7404. if (!this._map.has(element)) {
  7405. const index = this.length++;
  7406. this._array[index] = element;
  7407. this._map.set(element, index);
  7408. }
  7409. }
  7410. pop() {
  7411. const element = this._array[--this.length];
  7412. this._map.delete(element);
  7413. return element;
  7414. }
  7415. reserve(length) {
  7416. assert$7(length >= 0);
  7417. if (length > this._array.length) {
  7418. this._array.length = length;
  7419. }
  7420. }
  7421. resize(length) {
  7422. assert$7(length >= 0);
  7423. this.length = length;
  7424. }
  7425. trim(length) {
  7426. if (length === null || length === undefined) {
  7427. length = this.length;
  7428. }
  7429. this._array.length = length;
  7430. }
  7431. reset() {
  7432. this._array = [];
  7433. this._map = new Map();
  7434. this._length = 0;
  7435. }
  7436. find(target) {
  7437. return this._map.has(target);
  7438. }
  7439. }
  7440. const DEFAULT_PROPS$1 = {
  7441. loadSiblings: false,
  7442. skipLevelOfDetail: false,
  7443. maximumScreenSpaceError: 2,
  7444. updateTransforms: true,
  7445. onTraversalEnd: () => {},
  7446. viewportTraversersMap: {},
  7447. basePath: ''
  7448. };
  7449. class TilesetTraverser {
  7450. constructor(options) {
  7451. _defineProperty(this, "options", void 0);
  7452. _defineProperty(this, "root", void 0);
  7453. _defineProperty(this, "requestedTiles", void 0);
  7454. _defineProperty(this, "selectedTiles", void 0);
  7455. _defineProperty(this, "emptyTiles", void 0);
  7456. _defineProperty(this, "_traversalStack", void 0);
  7457. _defineProperty(this, "_emptyTraversalStack", void 0);
  7458. _defineProperty(this, "_frameNumber", void 0);
  7459. this.options = { ...DEFAULT_PROPS$1,
  7460. ...options
  7461. };
  7462. this._traversalStack = new ManagedArray();
  7463. this._emptyTraversalStack = new ManagedArray();
  7464. this._frameNumber = null;
  7465. this.root = null;
  7466. this.selectedTiles = {};
  7467. this.requestedTiles = {};
  7468. this.emptyTiles = {};
  7469. }
  7470. traverse(root, frameState, options) {
  7471. this.root = root;
  7472. this.options = { ...this.options,
  7473. ...options
  7474. };
  7475. this.reset();
  7476. this.updateTile(root, frameState);
  7477. this._frameNumber = frameState.frameNumber;
  7478. this.executeTraversal(root, frameState);
  7479. }
  7480. reset() {
  7481. this.requestedTiles = {};
  7482. this.selectedTiles = {};
  7483. this.emptyTiles = {};
  7484. this._traversalStack.reset();
  7485. this._emptyTraversalStack.reset();
  7486. }
  7487. executeTraversal(root, frameState) {// 遍历root
  7488. const stack = this._traversalStack;
  7489. root._selectionDepth = 1;
  7490. stack.push(root);
  7491. while (stack.length > 0) {
  7492. const tile = stack.pop();
  7493. let shouldRefine = false;
  7494. // !zeg改 循环遍历子tile, maxDepth用来限制可加载的最大深度
  7495. if (this.canTraverse(tile, frameState) && (tile.depth < /* this.options. */maxDepth || tile.type != 'scenegraph' )) {//add maxDepth 是否继续遍历子集
  7496. this.updateChildTiles(tile, frameState);
  7497. shouldRefine = this.updateAndPushChildren(tile, frameState, stack, tile.hasRenderContent ? tile._selectionDepth + 1 : tile._selectionDepth);
  7498. }
  7499. const parent = tile.parent;
  7500. const parentRefines = Boolean(!parent || parent._shouldRefine);
  7501. const stoppedRefining = !shouldRefine;
  7502. if (!tile.hasRenderContent) {
  7503. this.emptyTiles[tile.id] = tile;
  7504. this.loadTile(tile, frameState);
  7505. if (stoppedRefining) {
  7506. this.selectTile(tile, frameState);
  7507. }
  7508. } else if (tile.refine === TILE_REFINEMENT.ADD) {
  7509. this.loadTile(tile, frameState);
  7510. this.selectTile(tile, frameState);
  7511. } else if (tile.refine === TILE_REFINEMENT.REPLACE) {
  7512. this.loadTile(tile, frameState);
  7513. if (stoppedRefining) {
  7514. this.selectTile(tile, frameState);
  7515. }
  7516. }
  7517. this.touchTile(tile, frameState);
  7518. tile._shouldRefine = shouldRefine && parentRefines;
  7519. }
  7520. this.options.onTraversalEnd(frameState);
  7521. }
  7522. updateChildTiles(tile, frameState) {
  7523. const children = tile.children;
  7524. for (const child of children) {
  7525. this.updateTile(child, frameState);
  7526. }
  7527. return true;
  7528. }
  7529. updateAndPushChildren(tile, frameState, stack, depth) {
  7530. const {
  7531. loadSiblings,
  7532. skipLevelOfDetail
  7533. } = this.options;
  7534. const children = tile.children;
  7535. children.sort(this.compareDistanceToCamera.bind(this));
  7536. const checkRefines = tile.refine === TILE_REFINEMENT.REPLACE && tile.hasRenderContent && !skipLevelOfDetail;
  7537. let hasVisibleChild = false;
  7538. let refines = true;
  7539. for (const child of children) {
  7540. child._selectionDepth = depth;
  7541. if (child.isVisibleAndInRequestVolume) {
  7542. if (stack.find(child)) {
  7543. stack.delete(child);
  7544. }
  7545. stack.push(child);
  7546. hasVisibleChild = true;
  7547. } else if (checkRefines || loadSiblings) {
  7548. this.loadTile(child, frameState);
  7549. this.touchTile(child, frameState);
  7550. }
  7551. if (checkRefines) {
  7552. let childRefines;
  7553. if (!child._inRequestVolume) {
  7554. childRefines = false;
  7555. } else if (!child.hasRenderContent) {
  7556. childRefines = this.executeEmptyTraversal(child, frameState);
  7557. } else {
  7558. childRefines = child.contentAvailable;
  7559. }
  7560. refines = refines && childRefines;
  7561. if (!refines) {
  7562. return false;
  7563. }
  7564. }
  7565. }
  7566. if (!hasVisibleChild) {
  7567. refines = false;
  7568. }
  7569. return refines;
  7570. }
  7571. updateTile(tile, frameState) {
  7572. this.updateTileVisibility(tile, frameState);
  7573. }
  7574. selectTile(tile, frameState) {
  7575. if (this.shouldSelectTile(tile)) {
  7576. tile._selectedFrame = frameState.frameNumber;
  7577. this.selectedTiles[tile.id] = tile;
  7578. }
  7579. }
  7580. loadTile(tile, frameState) {
  7581. if (this.shouldLoadTile(tile)) {
  7582. tile._requestedFrame = frameState.frameNumber;
  7583. tile._priority = tile._getPriority();
  7584. this.requestedTiles[tile.id] = tile;
  7585. }
  7586. }
  7587. touchTile(tile, frameState) {
  7588. tile.tileset._cache.touch(tile);
  7589. tile._touchedFrame = frameState.frameNumber;
  7590. }
  7591. canTraverse(tile, frameState, useParentMetric = false, ignoreVisibility = false) {
  7592. if (!tile.hasChildren) {
  7593. return false;
  7594. }
  7595. if (tile.hasTilesetContent) {
  7596. return !tile.contentExpired;
  7597. }
  7598. if (!ignoreVisibility && !tile.isVisibleAndInRequestVolume) {
  7599. return false;
  7600. }
  7601. return this.shouldRefine(tile, frameState, useParentMetric);
  7602. }
  7603. shouldLoadTile(tile) {
  7604. return tile.hasUnloadedContent || tile.contentExpired;
  7605. }
  7606. shouldSelectTile(tile) {
  7607. return tile.contentAvailable && !this.options.skipLevelOfDetail;
  7608. }
  7609. shouldRefine(tile, frameState, useParentMetric) {
  7610. let screenSpaceError = tile._screenSpaceError;
  7611. if (useParentMetric) {
  7612. screenSpaceError = tile.getScreenSpaceError(frameState, true);
  7613. }
  7614. return screenSpaceError > this.options.maximumScreenSpaceError;
  7615. }
  7616. updateTileVisibility(tile, frameState) {
  7617. const viewportIds = [];
  7618. if (this.options.viewportTraversersMap) {
  7619. for (const key in this.options.viewportTraversersMap) {
  7620. const value = this.options.viewportTraversersMap[key];
  7621. if (value === frameState.viewport.id) {
  7622. viewportIds.push(key);
  7623. }
  7624. }
  7625. } else {
  7626. viewportIds.push(frameState.viewport.id);
  7627. }
  7628. tile.updateVisibility(frameState, viewportIds);
  7629. }
  7630. compareDistanceToCamera(b, a) {
  7631. return b._distanceToCamera - a._distanceToCamera;
  7632. }
  7633. anyChildrenVisible(tile, frameState) {
  7634. let anyVisible = false;
  7635. for (const child of tile.children) {
  7636. child.updateVisibility(frameState);
  7637. anyVisible = anyVisible || child.isVisibleAndInRequestVolume;
  7638. }
  7639. return anyVisible;
  7640. }
  7641. executeEmptyTraversal(root, frameState) {
  7642. let allDescendantsLoaded = true;
  7643. const stack = this._emptyTraversalStack;
  7644. stack.push(root);
  7645. while (stack.length > 0 && allDescendantsLoaded) {
  7646. const tile = stack.pop();
  7647. this.updateTile(tile, frameState);
  7648. if (!tile.isVisibleAndInRequestVolume) {
  7649. this.loadTile(tile, frameState);
  7650. }
  7651. this.touchTile(tile, frameState);
  7652. const traverse = !tile.hasRenderContent && this.canTraverse(tile, frameState, false, true);
  7653. if (traverse) {
  7654. const children = tile.children;
  7655. for (const child of children) {
  7656. if (stack.find(child)) {
  7657. stack.delete(child);
  7658. }
  7659. stack.push(child);
  7660. }
  7661. } else if (!tile.contentAvailable) {
  7662. allDescendantsLoaded = false;
  7663. }
  7664. }
  7665. return allDescendantsLoaded;
  7666. }
  7667. }
  7668. const scratchVector = new Vector3();
  7669. function defined$2(x) {
  7670. return x !== undefined && x !== null;
  7671. }
  7672. class TileHeader {
  7673. constructor(tileset, header, parentHeader, extendedId = '') {
  7674. _defineProperty(this, "tileset", void 0);
  7675. _defineProperty(this, "header", void 0);
  7676. _defineProperty(this, "id", void 0);
  7677. _defineProperty(this, "url", void 0);
  7678. _defineProperty(this, "parent", void 0);
  7679. _defineProperty(this, "refine", void 0);
  7680. _defineProperty(this, "type", void 0);
  7681. _defineProperty(this, "contentUrl", void 0);
  7682. _defineProperty(this, "lodMetricType", void 0);
  7683. _defineProperty(this, "lodMetricValue", void 0);
  7684. _defineProperty(this, "boundingVolume", void 0);
  7685. _defineProperty(this, "content", void 0);
  7686. _defineProperty(this, "contentState", void 0);
  7687. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  7688. _defineProperty(this, "children", void 0);
  7689. _defineProperty(this, "depth", void 0);
  7690. _defineProperty(this, "viewportIds", void 0);
  7691. _defineProperty(this, "transform", void 0);
  7692. _defineProperty(this, "extensions", void 0);
  7693. _defineProperty(this, "userData", void 0);
  7694. _defineProperty(this, "computedTransform", void 0);
  7695. _defineProperty(this, "hasEmptyContent", void 0);
  7696. _defineProperty(this, "hasTilesetContent", void 0);
  7697. _defineProperty(this, "traverser", void 0);
  7698. _defineProperty(this, "_cacheNode", void 0);
  7699. _defineProperty(this, "_frameNumber", void 0);
  7700. _defineProperty(this, "_lodJudge", void 0);
  7701. _defineProperty(this, "_expireDate", void 0);
  7702. _defineProperty(this, "_expiredContent", void 0);
  7703. _defineProperty(this, "_shouldRefine", void 0);
  7704. _defineProperty(this, "_distanceToCamera", void 0);
  7705. _defineProperty(this, "_centerZDepth", void 0);
  7706. _defineProperty(this, "_screenSpaceError", void 0);
  7707. _defineProperty(this, "_visibilityPlaneMask", void 0);
  7708. _defineProperty(this, "_visible", void 0);
  7709. _defineProperty(this, "_inRequestVolume", void 0);
  7710. _defineProperty(this, "_stackLength", void 0);
  7711. _defineProperty(this, "_selectionDepth", void 0);
  7712. _defineProperty(this, "_touchedFrame", void 0);
  7713. _defineProperty(this, "_visitedFrame", void 0);
  7714. _defineProperty(this, "_selectedFrame", void 0);
  7715. _defineProperty(this, "_requestedFrame", void 0);
  7716. _defineProperty(this, "_priority", void 0);
  7717. _defineProperty(this, "_contentBoundingVolume", void 0);
  7718. _defineProperty(this, "_viewerRequestVolume", void 0);
  7719. _defineProperty(this, "_initialTransform", void 0);
  7720. _defineProperty(this, "tilesetMatrix", void 0);//add
  7721. _defineProperty(this, "tileContent", void 0);//add
  7722. _defineProperty(this, "contentTransform", void 0);//add
  7723. _defineProperty(this, "volumeBox", void 0);//add
  7724. _defineProperty(this, "boundUntransformed", void 0);//add
  7725. _defineProperty(this, "rtcCenterState", rtcCenterGlobal);//add 初始时的状态,当mesh加载完检查下
  7726. this.header = header;
  7727. this.tileset = tileset;
  7728. this.id = extendedId || header.id;
  7729. this.url = header.url;
  7730. this.parent = parentHeader;
  7731. this.refine = this._getRefine(header.refine);
  7732. this.type = header.type;
  7733. this.contentUrl = header.contentUrl;
  7734. this.lodMetricType = 'geometricError';
  7735. this.lodMetricValue = 0;
  7736. this.boundingVolume = null;
  7737. this.content = null;
  7738. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7739. this.gpuMemoryUsageInBytes = 0;
  7740. this.children = [];
  7741. this.hasEmptyContent = false;
  7742. this.hasTilesetContent = false;
  7743. this.depth = 0;
  7744. this.viewportIds = [];
  7745. this.userData = {};
  7746. this.extensions = null;
  7747. this._priority = 0;
  7748. this._touchedFrame = 0;
  7749. this._visitedFrame = 0;
  7750. this._selectedFrame = 0;
  7751. this._requestedFrame = 0;
  7752. this._screenSpaceError = 0;
  7753. this._cacheNode = null;
  7754. this._frameNumber = null;
  7755. this._cacheNode = null;
  7756. this.traverser = new TilesetTraverser({});
  7757. this._shouldRefine = false;
  7758. this._distanceToCamera = 0;
  7759. this._centerZDepth = 0;
  7760. this._visible = undefined;
  7761. this._inRequestVolume = false;
  7762. this._stackLength = 0;
  7763. this._selectionDepth = 0;
  7764. this._initialTransform = new Matrix4();
  7765. this.transform = new Matrix4();
  7766. this._initializeLodMetric(header);
  7767. this._initializeTransforms(header);
  7768. this._initializeBoundingVolumes(header);
  7769. this._initializeContent(header);
  7770. this._initializeRenderingState(header);
  7771. this._lodJudge = null;
  7772. this._expireDate = null;
  7773. this._expiredContent = null;
  7774. Object.seal(this);
  7775. }
  7776. destroy() {
  7777. this.header = null;
  7778. }
  7779. isDestroyed() {
  7780. return this.header === null;
  7781. }
  7782. get selected() {
  7783. return this._selectedFrame === this.tileset._frameNumber;
  7784. }
  7785. get isVisible() {
  7786. return this._visible;
  7787. }
  7788. get isVisibleAndInRequestVolume() {
  7789. let v = /* this._visible && */this.tileset.visible && this._inRequestVolume; //用_updateBoundingVolume这个算的在相机靠近时不准确,容易缺块
  7790. if(window.tileVisi2)v = this._visible && v
  7791. return v
  7792. }
  7793. get hasRenderContent() {
  7794. return !this.hasEmptyContent && !this.hasTilesetContent;
  7795. }
  7796. get hasChildren() {
  7797. return this.children.length > 0 || this.header.children && this.header.children.length > 0;
  7798. }
  7799. get contentReady() {
  7800. return this.contentState === TILE_CONTENT_STATE.READY || this.hasEmptyContent;
  7801. }
  7802. get contentAvailable() {
  7803. return Boolean(this.contentReady && this.hasRenderContent || this._expiredContent && !this.contentFailed);
  7804. }
  7805. get hasUnloadedContent() {
  7806. return this.hasRenderContent && this.contentUnloaded;
  7807. }
  7808. get contentUnloaded() {
  7809. return this.contentState === TILE_CONTENT_STATE.UNLOADED;
  7810. }
  7811. get contentExpired() {
  7812. return this.contentState === TILE_CONTENT_STATE.EXPIRED;
  7813. }
  7814. get contentFailed() {
  7815. return this.contentState === TILE_CONTENT_STATE.FAILED;
  7816. }
  7817. getScreenSpaceError(frameState, useParentLodMetric) {
  7818. switch (this.tileset.type) {
  7819. case TILESET_TYPE.I3S:
  7820. return getProjectedRadius(this, frameState);
  7821. case TILESET_TYPE.TILES3D:
  7822. return getTiles3DScreenSpaceError(this, frameState, useParentLodMetric);
  7823. default:
  7824. throw new Error('Unsupported tileset type');
  7825. }
  7826. }
  7827. _getPriority() {
  7828. const traverser = this.tileset._traverser;
  7829. const {
  7830. skipLevelOfDetail
  7831. } = traverser.options;
  7832. const maySkipTile = this.refine === TILE_REFINEMENT.ADD || skipLevelOfDetail;
  7833. if (maySkipTile && !this.isVisible && this._visible !== undefined) {
  7834. return -1;
  7835. }
  7836. if (this.tileset._frameNumber - this._touchedFrame >= 1) {
  7837. return -1;
  7838. }
  7839. if (this.contentState === TILE_CONTENT_STATE.UNLOADED) {
  7840. return -1;
  7841. }
  7842. const parent = this.parent;
  7843. const useParentScreenSpaceError = parent && (!maySkipTile || this._screenSpaceError === 0.0 || parent.hasTilesetContent);
  7844. const screenSpaceError = useParentScreenSpaceError ? parent._screenSpaceError : this._screenSpaceError;
  7845. const rootScreenSpaceError = traverser.root ? traverser.root._screenSpaceError : 0.0;
  7846. let v = Math.max(rootScreenSpaceError - screenSpaceError, 0);
  7847. if(!this._visible){
  7848. v = THREE.Math.clamp(v * 0.1, -0.9, 100);//xzw add 因为this._visible我也令其显示所以这里降低这些的优先级
  7849. }
  7850. return v
  7851. }
  7852. async loadContent() {
  7853. if (this.hasEmptyContent) {
  7854. return false;
  7855. }
  7856. if (this.content) {
  7857. return true;
  7858. }
  7859. const expired = this.contentExpired;
  7860. if (expired) {
  7861. this._expireDate = null;
  7862. }
  7863. this.contentState = TILE_CONTENT_STATE.LOADING;
  7864. const requestToken = await this.tileset._requestScheduler.scheduleRequest(this.id, this._getPriority.bind(this));
  7865. if (!requestToken) {
  7866. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7867. return false;
  7868. }
  7869. try {
  7870. const contentUrl = this.tileset.getTileUrl(this.contentUrl)+ `?_=${this.tileset.options.updateTime}` // !zeg改 添加version后缀 原:imageVersion
  7871. const loader = this.tileset.loader;
  7872. const options = { ...this.tileset.loadOptions,
  7873. [loader.id]: { ...this.tileset.loadOptions[loader.id],
  7874. isTileset: this.type === 'json',
  7875. ...this._getLoaderSpecificOptions(loader.id)
  7876. }
  7877. };
  7878. this.content = await load(contentUrl, loader, options);
  7879. // !zeg改
  7880. if (/* this.tileset.options. */maxDepth < this.depth && this.type == 'scenegraph') {//有的场景depth为1的不是mesh,只是json,即实际最低depth>1
  7881. this.unloadContent()
  7882. return false
  7883. }
  7884. if (this.tileset.options.contentLoader) {
  7885. await this.tileset.options.contentLoader(this);
  7886. }
  7887. if (this._isTileset()) {
  7888. this.tileset._initializeTileHeaders(this.content, this);
  7889. }
  7890. this.contentState = TILE_CONTENT_STATE.READY;
  7891. this._onContentLoaded();
  7892. return true;
  7893. } catch (error) {
  7894. this.contentState = TILE_CONTENT_STATE.FAILED;
  7895. throw error;
  7896. } finally {
  7897. requestToken.done();
  7898. }
  7899. }
  7900. unloadContent() {
  7901. if (this.content && this.content.destroy) {
  7902. this.content.destroy();
  7903. }
  7904. this.content = null;
  7905. if (this.header.content && this.header.content.destroy) {
  7906. this.header.content.destroy();
  7907. }
  7908. this.header.content = null;
  7909. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7910. return true;
  7911. }
  7912. updateVisibility(frameState, viewportIds) {
  7913. if (this._frameNumber === frameState.frameNumber) {
  7914. return;
  7915. }
  7916. const parent = this.parent;
  7917. const parentVisibilityPlaneMask = parent ? parent._visibilityPlaneMask : CullingVolume.MASK_INDETERMINATE;
  7918. if (this.tileset._traverser.options.updateTransforms) {
  7919. const parentTransform = parent ? parent.computedTransform : new Matrix4().elements //this.tileset.modelMatrix; 改:去掉左乘modelMatrix
  7920. this._updateTransform(parentTransform);
  7921. }
  7922. this._distanceToCamera = this.distanceToTile(frameState);
  7923. this._screenSpaceError = this.getScreenSpaceError(frameState, false);
  7924. this._visibilityPlaneMask = this.visibility(frameState, parentVisibilityPlaneMask);
  7925. this._visible = this._visibilityPlaneMask !== CullingVolume.MASK_OUTSIDE;
  7926. this._inRequestVolume = this.insideViewerRequestVolume(frameState);
  7927. this._frameNumber = frameState.frameNumber;
  7928. this.viewportIds = viewportIds;
  7929. }
  7930. visibility(frameState, parentVisibilityPlaneMask) {
  7931. const {
  7932. cullingVolume
  7933. } = frameState;
  7934. const {
  7935. boundingVolume
  7936. } = this;
  7937. return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume, parentVisibilityPlaneMask);
  7938. }
  7939. contentVisibility() {
  7940. return true;
  7941. }
  7942. distanceToTile(frameState) {
  7943. const boundingVolume = this.boundingVolume;
  7944. return Math.sqrt(Math.max(boundingVolume.distanceSquaredTo(frameState.camera.position), 0));
  7945. }
  7946. cameraSpaceZDepth({
  7947. camera
  7948. }) {
  7949. const boundingVolume = this.boundingVolume;
  7950. scratchVector.subVectors(boundingVolume.center, camera.position);
  7951. return camera.direction.dot(scratchVector);
  7952. }
  7953. insideViewerRequestVolume(frameState) {
  7954. const viewerRequestVolume = this._viewerRequestVolume;
  7955. return !viewerRequestVolume || viewerRequestVolume.distanceSquaredTo(frameState.camera.position) <= 0;
  7956. }
  7957. updateExpiration() {
  7958. if (defined$2(this._expireDate) && this.contentReady && !this.hasEmptyContent) {
  7959. const now = Date.now();
  7960. if (Date.lessThan(this._expireDate, now)) {
  7961. this.contentState = TILE_CONTENT_STATE.EXPIRED;
  7962. this._expiredContent = this.content;
  7963. }
  7964. }
  7965. }
  7966. get extras() {
  7967. return this.header.extras;
  7968. }
  7969. _initializeLodMetric(header) {
  7970. if ('lodMetricType' in header) {
  7971. this.lodMetricType = header.lodMetricType;
  7972. } else {
  7973. this.lodMetricType = this.parent && this.parent.lodMetricType || this.tileset.lodMetricType;
  7974. console.warn("3D Tile: Required prop lodMetricType is undefined. Using parent lodMetricType");
  7975. }
  7976. if ('lodMetricValue' in header) {
  7977. this.lodMetricValue = header.lodMetricValue;
  7978. } else {
  7979. this.lodMetricValue = this.parent && this.parent.lodMetricValue || this.tileset.lodMetricValue;
  7980. console.warn('3D Tile: Required prop lodMetricValue is undefined. Using parent lodMetricValue');
  7981. }
  7982. }
  7983. _initializeTransforms(tileHeader) {
  7984. this.transform = tileHeader.transform ? new Matrix4(tileHeader.transform) : new Matrix4();
  7985. const parent = this.parent;
  7986. const tileset = this.tileset;
  7987. const parentTransform = parent && parent.computedTransform ? parent.computedTransform.clone() : new Matrix4().elements // tileset.modelMatrix.clone(); 改:去掉左乘modelMatrix
  7988. this.computedTransform = new Matrix4(parentTransform).multiplyRight(this.transform);
  7989. const parentInitialTransform = parent && parent._initialTransform ? parent._initialTransform.clone() : new Matrix4();
  7990. this._initialTransform = new Matrix4(parentInitialTransform).multiplyRight(this.transform);
  7991. }
  7992. _initializeBoundingVolumes(tileHeader) {
  7993. this._contentBoundingVolume = null;
  7994. this._viewerRequestVolume = null;
  7995. this._updateBoundingVolume(tileHeader);
  7996. }
  7997. _initializeContent(tileHeader) {
  7998. this.content = {
  7999. _tileset: this.tileset,
  8000. _tile: this
  8001. };
  8002. this.hasEmptyContent = true;
  8003. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  8004. this.hasTilesetContent = false;
  8005. if (tileHeader.contentUrl) {
  8006. this.content = null;
  8007. this.hasEmptyContent = false;
  8008. }
  8009. }
  8010. _initializeRenderingState(header) {
  8011. this.depth = header.level || (this.parent ? this.parent.depth + 1 : 0);
  8012. this._shouldRefine = false;
  8013. this._distanceToCamera = 0;
  8014. this._centerZDepth = 0;
  8015. this._screenSpaceError = 0;
  8016. this._visibilityPlaneMask = CullingVolume.MASK_INDETERMINATE;
  8017. this._visible = undefined;
  8018. this._inRequestVolume = false;
  8019. this._stackLength = 0;
  8020. this._selectionDepth = 0;
  8021. this._frameNumber = 0;
  8022. this._touchedFrame = 0;
  8023. this._visitedFrame = 0;
  8024. this._selectedFrame = 0;
  8025. this._requestedFrame = 0;
  8026. this._priority = 0.0;
  8027. }
  8028. _getRefine(refine) {
  8029. return refine || this.parent && this.parent.refine || TILE_REFINEMENT.REPLACE;
  8030. }
  8031. _isTileset() {
  8032. return this.contentUrl.indexOf('.json') !== -1;
  8033. }
  8034. _onContentLoaded() {
  8035. switch (this.content && this.content.type) {
  8036. case 'vctr':
  8037. case 'geom':
  8038. this.tileset._traverser.disableSkipLevelOfDetail = true;
  8039. break;
  8040. }
  8041. if (this._isTileset()) {
  8042. this.hasTilesetContent = true;
  8043. }
  8044. }
  8045. _updateBoundingVolume(header) {
  8046. let computedTransform
  8047. if(header.id == 'root_0' || !header.id){
  8048. console.log('root_0')
  8049. }
  8050. if(!this.tileset.lastRootTransform){//没事过后会因_updateTransform重算
  8051. computedTransform = new Matrix4(this.tileset.modelMatrix).multiplyRight(this.computedTransform); //add
  8052. }else{
  8053. computedTransform = new Matrix4(new Matrix4$1().multiplyMatrices(this.tileset.lastRootTransform, this.getContentTransform()).elements)
  8054. }
  8055. this.boundingVolume = createBoundingVolume(header.boundingVolume, computedTransform/* this.computedTransform */, this.boundingVolume);
  8056. const content = header.content;
  8057. if (!content) {
  8058. return;
  8059. }
  8060. if (content.boundingVolume) {
  8061. this._contentBoundingVolume = createBoundingVolume(content.boundingVolume, computedTransform, this._contentBoundingVolume);
  8062. }
  8063. if (header.viewerRequestVolume) {
  8064. this._viewerRequestVolume = createBoundingVolume(header.viewerRequestVolume, computedTransform, this._viewerRequestVolume);
  8065. }
  8066. }
  8067. getBoundUntransformed(){//add 这个会在mesh加载好后才会执行
  8068. if(!this.contentTransform){
  8069. console.error('?')
  8070. }
  8071. this.getContentTransform()
  8072. let computedTransform2 = new Matrix4(this.contentTransform.elements)
  8073. this.boundUntransformed = createBoundingVolume(this.header.boundingVolume, computedTransform2 , this.boundUntransformed);//add
  8074. return this.boundUntransformed
  8075. }
  8076. getContentTransform(force){ //add 获取该tile在创建boundingVolume时需要的matrix,不包含最外层对整体模型的变换.
  8077. let rtcCenter, contentTransform
  8078. if(this.contentTransform && !force){//无需更新
  8079. return this.contentTransform.clone()
  8080. }
  8081. if(!this.tileset.tileTransInvert){
  8082. this.tileset.tileTransInvert = new Matrix4()
  8083. }
  8084. this.contentTransform = new Matrix4$1().fromArray(this.computedTransform).premultiply(new Matrix4$1().fromArray(this.tileset.tileTransInvert))
  8085. if(this.tileContent){
  8086. rtcCenter = this.content.rtcCenter
  8087. }else{
  8088. rtcCenter = this.rtcCenterState
  8089. }
  8090. if(!rtcCenter) {
  8091. let tranM = new Matrix4$1()
  8092. tranM.makeScale(1,1,-1)//大部分是这种情况. 就是因为这个变换才加的这个函数,之前bounding没考虑这个不准。不知道为什么原生的代码不用scaleZ
  8093. this.contentTransform.premultiply(tranM)
  8094. }
  8095. //如果有rtcCenter的话一开始boundingVolume不准?会不会有显示问题?
  8096. return this.contentTransform.clone()
  8097. }
  8098. _updateTransform(parentTransform = new Matrix4()) {
  8099. const computedTransform = parentTransform.clone().multiplyRight(this.transform);
  8100. const didTransformChange = !computedTransform.equals(this.computedTransform) || !this.tilesetMatrix || !this.tilesetMatrix.equals(this.tileset.modelMatrix) //改 后面加了两个判断,为了在模型移动后更新_updateBoundingVolume
  8101. if (!didTransformChange) {
  8102. return;
  8103. }
  8104. this.tileset.modelMatrix
  8105. this.computedTransform = computedTransform;
  8106. this.tilesetMatrix = this.tileset.modelMatrix; //add 标记
  8107. this._updateBoundingVolume(this.header);
  8108. }
  8109. _getLoaderSpecificOptions(loaderId) {
  8110. switch (loaderId) {
  8111. case 'i3s':
  8112. return { ...this.tileset.options.i3s,
  8113. tile: this.header,
  8114. tileset: this.tileset.tileset,
  8115. isTileHeader: false
  8116. };
  8117. case '3d-tiles':
  8118. case 'cesium-ion':
  8119. default:
  8120. return get3dTilesOptions(this.tileset.tileset);
  8121. }
  8122. }
  8123. }
  8124. class Tileset3DTraverser extends TilesetTraverser {
  8125. compareDistanceToCamera(a, b) {
  8126. return b._distanceToCamera === 0 && a._distanceToCamera === 0 ? b._centerZDepth - a._centerZDepth : b._distanceToCamera - a._distanceToCamera;
  8127. }
  8128. updateTileVisibility(tile, frameState) {
  8129. super.updateTileVisibility(tile, frameState);
  8130. if (!tile.isVisibleAndInRequestVolume) {
  8131. return;
  8132. }
  8133. const hasChildren = tile.children.length > 0;
  8134. if (tile.hasTilesetContent && hasChildren) {
  8135. const firstChild = tile.children[0];
  8136. this.updateTileVisibility(firstChild, frameState);
  8137. tile._visible = firstChild._visible;
  8138. return;
  8139. }
  8140. if (this.meetsScreenSpaceErrorEarly(tile, frameState)) {
  8141. tile._visible = false;
  8142. return;
  8143. }
  8144. const replace = tile.refine === TILE_REFINEMENT.REPLACE;
  8145. const useOptimization = tile._optimChildrenWithinParent === TILE3D_OPTIMIZATION_HINT.USE_OPTIMIZATION;
  8146. if (replace && useOptimization && hasChildren) {
  8147. if (!this.anyChildrenVisible(tile, frameState)) {
  8148. tile._visible = false;
  8149. return;
  8150. }
  8151. }
  8152. }
  8153. meetsScreenSpaceErrorEarly(tile, frameState) {
  8154. const {
  8155. parent
  8156. } = tile;
  8157. if (!parent || parent.hasTilesetContent || parent.refine !== TILE_REFINEMENT.ADD) {
  8158. return false;
  8159. }
  8160. return !this.shouldRefine(tile, frameState, true);
  8161. }
  8162. }
  8163. const STATUS = {
  8164. REQUESTED: 'REQUESTED',
  8165. COMPLETED: 'COMPLETED',
  8166. ERROR: 'ERROR'
  8167. };
  8168. class I3STileManager {
  8169. constructor() {
  8170. _defineProperty(this, "_statusMap", void 0);
  8171. this._statusMap = {};
  8172. }
  8173. add(request, key, callback, frameState) {
  8174. if (!this._statusMap[key]) {
  8175. this._statusMap[key] = {
  8176. request,
  8177. callback,
  8178. key,
  8179. frameState,
  8180. status: STATUS.REQUESTED
  8181. };
  8182. request().then(data => {
  8183. this._statusMap[key].status = STATUS.COMPLETED;
  8184. this._statusMap[key].callback(data, frameState);
  8185. }).catch(error => {
  8186. this._statusMap[key].status = STATUS.ERROR;
  8187. callback(error);
  8188. });
  8189. }
  8190. }
  8191. update(key, frameState) {
  8192. if (this._statusMap[key]) {
  8193. this._statusMap[key].frameState = frameState;
  8194. }
  8195. }
  8196. find(key) {
  8197. return this._statusMap[key];
  8198. }
  8199. }
  8200. class I3STilesetTraverser extends TilesetTraverser {
  8201. constructor(options) {
  8202. super(options);
  8203. _defineProperty(this, "_tileManager", void 0);
  8204. this._tileManager = new I3STileManager();
  8205. }
  8206. shouldRefine(tile, frameState) {
  8207. tile._lodJudge = getLodStatus(tile, frameState);
  8208. return tile._lodJudge === 'DIG';
  8209. }
  8210. updateChildTiles(tile, frameState) {
  8211. const children = tile.header.children || [];
  8212. const childTiles = tile.children;
  8213. const tileset = tile.tileset;
  8214. for (const child of children) {
  8215. const extendedId = "".concat(child.id, "-").concat(frameState.viewport.id);
  8216. const childTile = childTiles && childTiles.find(t => t.id === extendedId);
  8217. if (!childTile) {
  8218. let request = () => this._loadTile(child.id, tileset);
  8219. const cachedRequest = this._tileManager.find(extendedId);
  8220. if (!cachedRequest) {
  8221. if (tileset.tileset.nodePages) {
  8222. request = () => tileset.tileset.nodePagesTile.formTileFromNodePages(child.id);
  8223. }
  8224. this._tileManager.add(request, extendedId, header => this._onTileLoad(header, tile, extendedId), frameState);
  8225. } else {
  8226. this._tileManager.update(extendedId, frameState);
  8227. }
  8228. } else if (childTile) {
  8229. this.updateTile(childTile, frameState);
  8230. }
  8231. }
  8232. return false;
  8233. }
  8234. async _loadTile(nodeId, tileset) {
  8235. const {
  8236. loader
  8237. } = tileset;
  8238. const nodeUrl = tileset.getTileUrl("".concat(tileset.url, "/nodes/").concat(nodeId));
  8239. const options = { ...tileset.loadOptions,
  8240. i3s: { ...tileset.loadOptions.i3s,
  8241. isTileHeader: true,
  8242. loadContent: false
  8243. }
  8244. };
  8245. return await load(nodeUrl, loader, options);
  8246. }
  8247. _onTileLoad(header, tile, extendedId) {
  8248. const childTile = new TileHeader(tile.tileset, header, tile, extendedId);
  8249. tile.children.push(childTile);
  8250. const frameState = this._tileManager.find(childTile.id).frameState;
  8251. this.updateTile(childTile, frameState);
  8252. if (this._frameNumber === frameState.frameNumber) {
  8253. this.executeTraversal(childTile, frameState);
  8254. }
  8255. }
  8256. }
  8257. const DEFAULT_PROPS = {
  8258. description: '',
  8259. ellipsoid: Ellipsoid.WGS84,
  8260. modelMatrix: new Matrix4(),
  8261. throttleRequests: true,
  8262. maxRequests: 64,
  8263. maximumMemoryUsage: 32,
  8264. onTileLoad: () => {},
  8265. onTileUnload: () => {},
  8266. onTileError: () => {},
  8267. onTraversalComplete: selectedTiles => selectedTiles,
  8268. contentLoader: undefined,
  8269. viewDistanceScale: 1.0,
  8270. maximumScreenSpaceError: 8,
  8271. loadTiles: true,
  8272. updateTransforms: true,
  8273. viewportTraversersMap: null,
  8274. loadOptions: {
  8275. fetch: {}
  8276. },
  8277. attributions: [],
  8278. basePath: '',
  8279. i3s: {}
  8280. };
  8281. const TILES_TOTAL = 'Tiles In Tileset(s)';
  8282. const TILES_IN_MEMORY = 'Tiles In Memory';
  8283. const TILES_IN_VIEW = 'Tiles In View';
  8284. const TILES_RENDERABLE = 'Tiles To Render';
  8285. const TILES_LOADED = 'Tiles Loaded';
  8286. const TILES_LOADING = 'Tiles Loading';
  8287. const TILES_UNLOADED = 'Tiles Unloaded';
  8288. const TILES_LOAD_FAILED = 'Failed Tile Loads';
  8289. const POINTS_COUNT = 'Points';
  8290. const TILES_GPU_MEMORY = 'Tile Memory Use';
  8291. let tilesetSid = 0//add
  8292. class Tileset3D extends EventDispatcher{//xzw add EventDispatcher
  8293. constructor(json, options) {
  8294. super()
  8295. _defineProperty(this, "options", void 0);
  8296. _defineProperty(this, "loadOptions", void 0);
  8297. _defineProperty(this, "type", void 0);
  8298. _defineProperty(this, "tileset", void 0);
  8299. _defineProperty(this, "loader", void 0);
  8300. _defineProperty(this, "url", void 0);
  8301. _defineProperty(this, "basePath", void 0);
  8302. _defineProperty(this, "modelMatrix", void 0);
  8303. _defineProperty(this, "ellipsoid", void 0);
  8304. _defineProperty(this, "lodMetricType", void 0);
  8305. _defineProperty(this, "lodMetricValue", void 0);
  8306. _defineProperty(this, "refine", void 0);
  8307. _defineProperty(this, "root", void 0);
  8308. _defineProperty(this, "roots", void 0);
  8309. _defineProperty(this, "asset", void 0);
  8310. _defineProperty(this, "description", void 0);
  8311. _defineProperty(this, "properties", void 0);
  8312. _defineProperty(this, "extras", void 0);
  8313. _defineProperty(this, "attributions", void 0);
  8314. _defineProperty(this, "credits", void 0);
  8315. _defineProperty(this, "stats", void 0);
  8316. _defineProperty(this, "traverseCounter", void 0);
  8317. _defineProperty(this, "geometricError", void 0);
  8318. _defineProperty(this, "selectedTiles", void 0);
  8319. _defineProperty(this, "cartographicCenter", void 0);
  8320. _defineProperty(this, "cartesianCenter", void 0);
  8321. _defineProperty(this, "zoom", void 0);
  8322. _defineProperty(this, "boundingVolume", void 0);
  8323. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  8324. _defineProperty(this, "dynamicScreenSpaceErrorComputedDensity", void 0);
  8325. _defineProperty(this, "_traverser", void 0);
  8326. _defineProperty(this, "_cache", void 0);
  8327. _defineProperty(this, "_requestScheduler", void 0);
  8328. _defineProperty(this, "_frameNumber", void 0);
  8329. _defineProperty(this, "_queryParamsString", void 0);
  8330. _defineProperty(this, "_queryParams", void 0);
  8331. _defineProperty(this, "_extensionsUsed", void 0);
  8332. _defineProperty(this, "_tiles", void 0);
  8333. _defineProperty(this, "_pendingCount", void 0);
  8334. _defineProperty(this, "lastUpdatedVieports", void 0);
  8335. _defineProperty(this, "_requestedTiles", void 0);
  8336. _defineProperty(this, "_emptyTiles", void 0);
  8337. _defineProperty(this, "frameStateData", void 0);
  8338. _defineProperty(this, "maximumMemoryUsage", void 0);
  8339. _defineProperty(this, "visible", true);//add
  8340. assert$7(json);
  8341. this.options = { ...DEFAULT_PROPS,
  8342. ...options
  8343. };
  8344. this.tileset = json;
  8345. this.loader = json.loader;
  8346. this.type = json.type;
  8347. this.url = json.url;
  8348. this.basePath = json.basePath || dirname(this.url);
  8349. this.modelMatrix = this.options.modelMatrix;
  8350. this.ellipsoid = this.options.ellipsoid;
  8351. this.lodMetricType = json.lodMetricType;
  8352. this.lodMetricValue = json.lodMetricValue;
  8353. this.refine = json.root.refine;
  8354. this.loadOptions = this.options.loadOptions || {};
  8355. this.root = null;
  8356. this.roots = {};
  8357. this.cartographicCenter = null;
  8358. this.cartesianCenter = null;
  8359. this.zoom = 1;
  8360. this.boundingVolume = null;
  8361. this.traverseCounter = 0;
  8362. this.geometricError = 0;
  8363. this._traverser = this._initializeTraverser();
  8364. this._cache = new TilesetCache();
  8365. this._requestScheduler = new RequestScheduler({
  8366. throttleRequests: this.options.throttleRequests,
  8367. maxRequests: this.options.maxRequests
  8368. });
  8369. this._frameNumber = 0;
  8370. this._pendingCount = 0;
  8371. this._tiles = {};
  8372. this.selectedTiles = [];
  8373. this._emptyTiles = [];
  8374. this._requestedTiles = [];
  8375. this.frameStateData = {};
  8376. this.lastUpdatedVieports = null;
  8377. this._queryParams = {};
  8378. this._queryParamsString = '';
  8379. this.maximumMemoryUsage = this.options.maximumMemoryUsage || 32;
  8380. this.gpuMemoryUsageInBytes = 0;
  8381. this.stats = new Stats({
  8382. id: this.url
  8383. });
  8384. this._initializeStats();
  8385. this._extensionsUsed = undefined;
  8386. this.dynamicScreenSpaceErrorComputedDensity = 0.0;
  8387. this.extras = null;
  8388. this.asset = {};
  8389. this.credits = {};
  8390. this.description = this.options.description || '';
  8391. this._initializeTileSet(json);
  8392. }
  8393. destroy() {
  8394. this._destroy();
  8395. }
  8396. isLoaded() {
  8397. return this._pendingCount === 0 && this._frameNumber !== 0;
  8398. }
  8399. get tiles() {
  8400. return Object.values(this._tiles);
  8401. }
  8402. get frameNumber() {
  8403. return this._frameNumber;
  8404. }
  8405. get queryParams() {
  8406. if (!this._queryParamsString) {
  8407. this._queryParamsString = getQueryParamString(this._queryParams);
  8408. }
  8409. return this._queryParamsString;
  8410. }
  8411. setProps(props) {
  8412. this.options = { ...this.options,
  8413. ...props
  8414. };
  8415. }
  8416. setOptions(options) {
  8417. this.options = { ...this.options,
  8418. ...options
  8419. };
  8420. }
  8421. getTileUrl(tilePath) {
  8422. const isDataUrl = tilePath.startsWith('data:');
  8423. tilePath = Potree.Common.dealURL(tilePath) //add 去除'+'
  8424. if (isDataUrl) {
  8425. return tilePath;
  8426. }
  8427. return "".concat(tilePath).concat(this.queryParams);
  8428. }
  8429. hasExtension(extensionName) {
  8430. return Boolean(this._extensionsUsed && this._extensionsUsed.indexOf(extensionName) > -1);
  8431. }
  8432. update(viewports) {
  8433. if ('loadTiles' in this.options && !this.options.loadTiles) {
  8434. return;
  8435. }
  8436. if (this.traverseCounter > 0) {
  8437. return;
  8438. }
  8439. if (!viewports && this.lastUpdatedVieports) {
  8440. viewports = this.lastUpdatedVieports;
  8441. } else {
  8442. this.lastUpdatedVieports = viewports;
  8443. }
  8444. if (!(viewports instanceof Array)) {
  8445. viewports = [viewports];
  8446. }
  8447. this._cache.reset();
  8448. this._frameNumber++;
  8449. this.traverseCounter = viewports.length;
  8450. const viewportsToTraverse = [];
  8451. for (const viewport of viewports) {
  8452. const id = viewport.id;
  8453. if (this._needTraverse(id)) {
  8454. viewportsToTraverse.push(id);
  8455. } else {
  8456. this.traverseCounter--;
  8457. }
  8458. }
  8459. for (const viewport of viewports) {
  8460. const id = viewport.id;
  8461. if (!this.roots[id]) {
  8462. this.roots[id] = this._initializeTileHeaders(this.tileset, null);
  8463. }
  8464. if (!viewportsToTraverse.includes(id)) {
  8465. continue;
  8466. }
  8467. const frameState = getFrameState(viewport, this._frameNumber);
  8468. this._traverser.traverse(this.roots[id], frameState, this.options);
  8469. }
  8470. }
  8471. _needTraverse(viewportId) {
  8472. let traverserId = viewportId;
  8473. if (this.options.viewportTraversersMap) {
  8474. traverserId = this.options.viewportTraversersMap[viewportId];
  8475. }
  8476. if (traverserId !== viewportId) {
  8477. return false;
  8478. }
  8479. return true;
  8480. }
  8481. _onTraversalEnd(frameState) {
  8482. const id = frameState.viewport.id;
  8483. if (!this.frameStateData[id]) {
  8484. this.frameStateData[id] = {
  8485. selectedTiles: [],
  8486. _requestedTiles: [],
  8487. _emptyTiles: []
  8488. };
  8489. }
  8490. const currentFrameStateData = this.frameStateData[id];
  8491. const selectedTiles = Object.values(this._traverser.selectedTiles);
  8492. currentFrameStateData.selectedTiles = selectedTiles;
  8493. currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);
  8494. currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);
  8495. this.traverseCounter--;
  8496. if (this.traverseCounter > 0) {
  8497. return;
  8498. }
  8499. this._updateTiles();
  8500. }
  8501. _updateTiles() {
  8502. this.selectedTiles = [];
  8503. this._requestedTiles = [];
  8504. this._emptyTiles = [];
  8505. for (const frameStateKey in this.frameStateData) {
  8506. const frameStateDataValue = this.frameStateData[frameStateKey];
  8507. this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);
  8508. this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);
  8509. this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);
  8510. }
  8511. this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);
  8512. for (const tile of this.selectedTiles) {
  8513. this._tiles[tile.id] = tile;
  8514. }
  8515. this._loadTiles();
  8516. this._unloadTiles();
  8517. this._updateStats();
  8518. }
  8519. _tilesChanged(oldSelectedTiles, selectedTiles) {
  8520. if (oldSelectedTiles.length !== selectedTiles.length) {
  8521. return true;
  8522. }
  8523. const set1 = new Set(oldSelectedTiles.map(t => t.id));
  8524. const set2 = new Set(selectedTiles.map(t => t.id));
  8525. let changed = oldSelectedTiles.filter(x => !set2.has(x.id)).length > 0;
  8526. changed = changed || selectedTiles.filter(x => !set1.has(x.id)).length > 0;
  8527. return changed;
  8528. }
  8529. _loadTiles() {
  8530. for (const tile of this._requestedTiles) {
  8531. if (tile.contentUnloaded) {
  8532. this._loadTile(tile);
  8533. }
  8534. }
  8535. }
  8536. _unloadTiles() {
  8537. this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));
  8538. }
  8539. _updateStats() {
  8540. let tilesRenderable = 0;
  8541. let pointsRenderable = 0;
  8542. for (const tile of this.selectedTiles) {
  8543. if (tile.contentAvailable && tile.content) {
  8544. tilesRenderable++;
  8545. if (tile.content.pointCount) {
  8546. pointsRenderable += tile.content.pointCount;
  8547. }
  8548. }
  8549. }
  8550. this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;
  8551. this.stats.get(TILES_RENDERABLE).count = tilesRenderable;
  8552. this.stats.get(POINTS_COUNT).count = pointsRenderable;
  8553. }
  8554. _initializeTileSet(tilesetJson) {
  8555. this.root = this._initializeTileHeaders(tilesetJson, null);
  8556. if (this.type === TILESET_TYPE.TILES3D) {
  8557. this._initializeCesiumTileset(tilesetJson);
  8558. }
  8559. if (this.type === TILESET_TYPE.I3S) {
  8560. this._initializeI3STileset();
  8561. }
  8562. this._calculateViewProps();
  8563. }
  8564. _calculateViewProps() {
  8565. const root = this.root;
  8566. assert$7(root);
  8567. const {
  8568. center
  8569. } = root.boundingVolume;
  8570. if (!center) {
  8571. console.warn('center was not pre-calculated for the root tile');
  8572. this.cartographicCenter = new Vector3();
  8573. this.zoom = 1;
  8574. return;
  8575. }
  8576. this.cartographicCenter = Ellipsoid.WGS84.cartesianToCartographic(center, new Vector3());
  8577. this.cartesianCenter = center;
  8578. this.zoom = getZoomFromBoundingVolume(root.boundingVolume);
  8579. }
  8580. _initializeStats() {
  8581. this.stats.get(TILES_TOTAL);
  8582. this.stats.get(TILES_LOADING);
  8583. this.stats.get(TILES_IN_MEMORY);
  8584. this.stats.get(TILES_IN_VIEW);
  8585. this.stats.get(TILES_RENDERABLE);
  8586. this.stats.get(TILES_LOADED);
  8587. this.stats.get(TILES_UNLOADED);
  8588. this.stats.get(TILES_LOAD_FAILED);
  8589. this.stats.get(POINTS_COUNT, 'memory');
  8590. this.stats.get(TILES_GPU_MEMORY, 'memory');
  8591. }
  8592. _initializeTileHeaders(tilesetJson, parentTileHeader) {
  8593. const rootTile = new TileHeader(this, tilesetJson.root, parentTileHeader, parentTileHeader == void 0 && 'root_'+tilesetSid++);
  8594. if (parentTileHeader) {
  8595. parentTileHeader.children.push(rootTile);
  8596. rootTile.depth = parentTileHeader.depth + 1;
  8597. }
  8598. if (this.type === TILESET_TYPE.TILES3D) {
  8599. const stack = [];
  8600. stack.push(rootTile);
  8601. while (stack.length > 0) {
  8602. const tile = stack.pop();
  8603. this.stats.get(TILES_TOTAL).incrementCount();
  8604. const children = tile.header.children || [];
  8605. // !zeg改
  8606. if(tile.depth < /* this.options. */maxDepth){
  8607. for (const childHeader of children) {
  8608. const childTile = new TileHeader(this, childHeader, tile);
  8609. tile.children.push(childTile);
  8610. childTile.depth = tile.depth + 1;
  8611. stack.push(childTile);
  8612. }
  8613. }
  8614. window.maxTileDepth = Math.max(window.maxTileDepth||0, tile.depth)
  8615. }
  8616. }
  8617. return rootTile;
  8618. }
  8619. _initializeTraverser() {
  8620. let TraverserClass;
  8621. const type = this.type;
  8622. switch (type) {
  8623. case TILESET_TYPE.TILES3D:
  8624. TraverserClass = Tileset3DTraverser;
  8625. break;
  8626. case TILESET_TYPE.I3S:
  8627. TraverserClass = I3STilesetTraverser;
  8628. break;
  8629. default:
  8630. TraverserClass = TilesetTraverser;
  8631. }
  8632. return new TraverserClass({
  8633. basePath: this.basePath,
  8634. onTraversalEnd: this._onTraversalEnd.bind(this)
  8635. });
  8636. }
  8637. _destroyTileHeaders(parentTile) {
  8638. this._destroySubtree(parentTile);
  8639. }
  8640. async _loadTile(tile) {
  8641. let loaded;
  8642. try {
  8643. this._onStartTileLoading();
  8644. loaded = await tile.loadContent();
  8645. } catch (error) {
  8646. this._onTileLoadError(tile, error);
  8647. } finally {
  8648. this._onEndTileLoading(tile);//
  8649. this._onTileLoad(tile, loaded);
  8650. }
  8651. }
  8652. _onTileLoadError(tile, error) {
  8653. this.stats.get(TILES_LOAD_FAILED).incrementCount();
  8654. const message = error.message || error.toString();
  8655. const url = tile.url;
  8656. console.error("A 3D tile failed to load: ".concat(tile.url, " ").concat(message));
  8657. this.options.onTileError(tile, message, url);
  8658. }
  8659. _onTileLoad(tile, loaded) {
  8660. if (!loaded) {
  8661. return;
  8662. }
  8663. if (tile && tile.content) {
  8664. calculateTransformProps(tile, tile.content);
  8665. }
  8666. this._addTileToCache(tile);
  8667. this.options.onTileLoad(tile);
  8668. }
  8669. _onStartTileLoading() {
  8670. this._pendingCount++;
  8671. this.stats.get(TILES_LOADING).incrementCount();
  8672. }
  8673. _onEndTileLoading(tile) {
  8674. this._pendingCount--;
  8675. this.stats.get(TILES_LOADING).decrementCount();
  8676. this.dispatchEvent({type:'endTileLoading', tile, loadingCount: this._pendingCount }) // !zeg改
  8677. }
  8678. _addTileToCache(tile) {
  8679. this._cache.add(this, tile, tileset => tileset._updateCacheStats(tile));
  8680. }
  8681. _updateCacheStats(tile) {
  8682. this.stats.get(TILES_LOADED).incrementCount();
  8683. this.stats.get(TILES_IN_MEMORY).incrementCount();
  8684. this.gpuMemoryUsageInBytes += tile.content.byteLength || 0;
  8685. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  8686. }
  8687. _unloadTile(tile) {
  8688. this.gpuMemoryUsageInBytes -= tile.content && tile.content.byteLength || 0;
  8689. this.stats.get(TILES_IN_MEMORY).decrementCount();
  8690. this.stats.get(TILES_UNLOADED).incrementCount();
  8691. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  8692. this.options.onTileUnload(tile);
  8693. tile.unloadContent();
  8694. }
  8695. _destroy() {
  8696. const stack = [];
  8697. if (this.root) {
  8698. stack.push(this.root);
  8699. }
  8700. while (stack.length > 0) {
  8701. const tile = stack.pop();
  8702. for (const child of tile.children) {
  8703. stack.push(child);
  8704. }
  8705. this._destroyTile(tile);
  8706. }
  8707. this.root = null;
  8708. }
  8709. _destroySubtree(tile) {
  8710. const root = tile;
  8711. const stack = [];
  8712. stack.push(root);
  8713. while (stack.length > 0) {
  8714. tile = stack.pop();
  8715. for (const child of tile.children) {
  8716. stack.push(child);
  8717. }
  8718. if (tile !== root) {
  8719. this._destroyTile(tile);
  8720. }
  8721. }
  8722. root.children = [];
  8723. }
  8724. _destroyTile(tile) {
  8725. this._cache.unloadTile(this, tile);
  8726. this._unloadTile(tile);
  8727. tile.destroy();
  8728. }
  8729. _initializeCesiumTileset(tilesetJson) {
  8730. this.asset = tilesetJson.asset;
  8731. if (!this.asset) {
  8732. throw new Error('Tileset must have an asset property.');
  8733. }
  8734. if (this.asset.version !== '0.0' && this.asset.version !== '1.0') {
  8735. throw new Error('The tileset must be 3D Tiles version 0.0 or 1.0.');
  8736. }
  8737. if ('tilesetVersion' in this.asset) {
  8738. this._queryParams.v = this.asset.tilesetVersion;
  8739. }
  8740. this.credits = {
  8741. attributions: this.options.attributions || []
  8742. };
  8743. this.description = this.options.description || '';
  8744. this.properties = tilesetJson.properties;
  8745. this.geometricError = tilesetJson.geometricError;
  8746. this._extensionsUsed = tilesetJson.extensionsUsed;
  8747. this.extras = tilesetJson.extras;
  8748. }
  8749. _initializeI3STileset() {
  8750. if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) {
  8751. this._queryParams.token = this.loadOptions.i3s.token;
  8752. }
  8753. }
  8754. }
  8755. function getQueryParamString(queryParams) {
  8756. const queryParamStrings = [];
  8757. for (const key of Object.keys(queryParams)) {
  8758. queryParamStrings.push("".concat(key, "=").concat(queryParams[key]));
  8759. }
  8760. switch (queryParamStrings.length) {
  8761. case 0:
  8762. return '';
  8763. case 1:
  8764. return "?".concat(queryParamStrings[0]);
  8765. default:
  8766. return "?".concat(queryParamStrings.join('&'));
  8767. }
  8768. }
  8769. const VERSION$5 = "3.1.4" ;
  8770. const TILE3D_TYPE = {
  8771. COMPOSITE: 'cmpt',
  8772. POINT_CLOUD: 'pnts',
  8773. BATCHED_3D_MODEL: 'b3dm',
  8774. INSTANCED_3D_MODEL: 'i3dm',
  8775. GEOMETRY: 'geom',
  8776. VECTOR: 'vect',
  8777. GLTF: 'glTF'
  8778. };
  8779. function getStringFromArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  8780. assert$7(arrayBuffer instanceof ArrayBuffer);
  8781. const textDecoder = new TextDecoder('utf8');
  8782. const typedArray = new Uint8Array(arrayBuffer, byteOffset, byteLength);
  8783. const string = textDecoder.decode(typedArray);
  8784. return string;
  8785. }
  8786. function getMagicString$1(arrayBuffer, byteOffset = 0) {
  8787. const dataView = new DataView(arrayBuffer);
  8788. 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)));
  8789. }
  8790. const VERSION$4 = "3.1.4" ;
  8791. const DEFAULT_DRACO_OPTIONS = {
  8792. draco: {
  8793. decoderType: typeof WebAssembly === 'object' ? 'wasm' : 'js',
  8794. libraryPath: 'libs/',
  8795. extraAttributes: {},
  8796. attributeNameEntry: undefined
  8797. }
  8798. };
  8799. const DracoLoader$1 = {
  8800. name: 'Draco',
  8801. id: 'draco',
  8802. module: 'draco',
  8803. shapes: ['mesh'],
  8804. version: VERSION$4,
  8805. worker: true,
  8806. extensions: ['drc'],
  8807. mimeTypes: ['application/octet-stream'],
  8808. binary: true,
  8809. tests: ['DRACO'],
  8810. options: DEFAULT_DRACO_OPTIONS
  8811. };
  8812. function getMeshBoundingBox(attributes) {
  8813. let minX = Infinity;
  8814. let minY = Infinity;
  8815. let minZ = Infinity;
  8816. let maxX = -Infinity;
  8817. let maxY = -Infinity;
  8818. let maxZ = -Infinity;
  8819. const positions = attributes.POSITION ? attributes.POSITION.value : [];
  8820. const len = positions && positions.length;
  8821. for (let i = 0; i < len; i += 3) {
  8822. const x = positions[i];
  8823. const y = positions[i + 1];
  8824. const z = positions[i + 2];
  8825. minX = x < minX ? x : minX;
  8826. minY = y < minY ? y : minY;
  8827. minZ = z < minZ ? z : minZ;
  8828. maxX = x > maxX ? x : maxX;
  8829. maxY = y > maxY ? y : maxY;
  8830. maxZ = z > maxZ ? z : maxZ;
  8831. }
  8832. return [[minX, minY, minZ], [maxX, maxY, maxZ]];
  8833. }
  8834. function assert$3(condition, message) {
  8835. if (!condition) {
  8836. throw new Error(message || 'loader assertion failed.');
  8837. }
  8838. }
  8839. class Schema {
  8840. constructor(fields, metadata) {
  8841. _defineProperty(this, "fields", void 0);
  8842. _defineProperty(this, "metadata", void 0);
  8843. assert$3(Array.isArray(fields));
  8844. checkNames(fields);
  8845. this.fields = fields;
  8846. this.metadata = metadata || new Map();
  8847. }
  8848. compareTo(other) {
  8849. if (this.metadata !== other.metadata) {
  8850. return false;
  8851. }
  8852. if (this.fields.length !== other.fields.length) {
  8853. return false;
  8854. }
  8855. for (let i = 0; i < this.fields.length; ++i) {
  8856. if (!this.fields[i].compareTo(other.fields[i])) {
  8857. return false;
  8858. }
  8859. }
  8860. return true;
  8861. }
  8862. select(...columnNames) {
  8863. const nameMap = Object.create(null);
  8864. for (const name of columnNames) {
  8865. nameMap[name] = true;
  8866. }
  8867. const selectedFields = this.fields.filter(field => nameMap[field.name]);
  8868. return new Schema(selectedFields, this.metadata);
  8869. }
  8870. selectAt(...columnIndices) {
  8871. const selectedFields = columnIndices.map(index => this.fields[index]).filter(Boolean);
  8872. return new Schema(selectedFields, this.metadata);
  8873. }
  8874. assign(schemaOrFields) {
  8875. let fields;
  8876. let metadata = this.metadata;
  8877. if (schemaOrFields instanceof Schema) {
  8878. const otherSchema = schemaOrFields;
  8879. fields = otherSchema.fields;
  8880. metadata = mergeMaps(mergeMaps(new Map(), this.metadata), otherSchema.metadata);
  8881. } else {
  8882. fields = schemaOrFields;
  8883. }
  8884. const fieldMap = Object.create(null);
  8885. for (const field of this.fields) {
  8886. fieldMap[field.name] = field;
  8887. }
  8888. for (const field of fields) {
  8889. fieldMap[field.name] = field;
  8890. }
  8891. const mergedFields = Object.values(fieldMap);
  8892. return new Schema(mergedFields, metadata);
  8893. }
  8894. }
  8895. function checkNames(fields) {
  8896. const usedNames = {};
  8897. for (const field of fields) {
  8898. if (usedNames[field.name]) {
  8899. console.warn('Schema: duplicated field name', field.name, field);
  8900. }
  8901. usedNames[field.name] = true;
  8902. }
  8903. }
  8904. function mergeMaps(m1, m2) {
  8905. return new Map([...(m1 || new Map()), ...(m2 || new Map())]);
  8906. }
  8907. class Field {
  8908. constructor(name, type, nullable = false, metadata = new Map()) {
  8909. _defineProperty(this, "name", void 0);
  8910. _defineProperty(this, "type", void 0);
  8911. _defineProperty(this, "nullable", void 0);
  8912. _defineProperty(this, "metadata", void 0);
  8913. this.name = name;
  8914. this.type = type;
  8915. this.nullable = nullable;
  8916. this.metadata = metadata;
  8917. }
  8918. get typeId() {
  8919. return this.type && this.type.typeId;
  8920. }
  8921. clone() {
  8922. return new Field(this.name, this.type, this.nullable, this.metadata);
  8923. }
  8924. compareTo(other) {
  8925. return this.name === other.name && this.type === other.type && this.nullable === other.nullable && this.metadata === other.metadata;
  8926. }
  8927. toString() {
  8928. return "".concat(this.type).concat(this.nullable ? ', nullable' : '').concat(this.metadata ? ", metadata: ".concat(this.metadata) : '');
  8929. }
  8930. }
  8931. let Type;
  8932. (function (Type) {
  8933. Type[Type["NONE"] = 0] = "NONE";
  8934. Type[Type["Null"] = 1] = "Null";
  8935. Type[Type["Int"] = 2] = "Int";
  8936. Type[Type["Float"] = 3] = "Float";
  8937. Type[Type["Binary"] = 4] = "Binary";
  8938. Type[Type["Utf8"] = 5] = "Utf8";
  8939. Type[Type["Bool"] = 6] = "Bool";
  8940. Type[Type["Decimal"] = 7] = "Decimal";
  8941. Type[Type["Date"] = 8] = "Date";
  8942. Type[Type["Time"] = 9] = "Time";
  8943. Type[Type["Timestamp"] = 10] = "Timestamp";
  8944. Type[Type["Interval"] = 11] = "Interval";
  8945. Type[Type["List"] = 12] = "List";
  8946. Type[Type["Struct"] = 13] = "Struct";
  8947. Type[Type["Union"] = 14] = "Union";
  8948. Type[Type["FixedSizeBinary"] = 15] = "FixedSizeBinary";
  8949. Type[Type["FixedSizeList"] = 16] = "FixedSizeList";
  8950. Type[Type["Map"] = 17] = "Map";
  8951. Type[Type["Dictionary"] = -1] = "Dictionary";
  8952. Type[Type["Int8"] = -2] = "Int8";
  8953. Type[Type["Int16"] = -3] = "Int16";
  8954. Type[Type["Int32"] = -4] = "Int32";
  8955. Type[Type["Int64"] = -5] = "Int64";
  8956. Type[Type["Uint8"] = -6] = "Uint8";
  8957. Type[Type["Uint16"] = -7] = "Uint16";
  8958. Type[Type["Uint32"] = -8] = "Uint32";
  8959. Type[Type["Uint64"] = -9] = "Uint64";
  8960. Type[Type["Float16"] = -10] = "Float16";
  8961. Type[Type["Float32"] = -11] = "Float32";
  8962. Type[Type["Float64"] = -12] = "Float64";
  8963. Type[Type["DateDay"] = -13] = "DateDay";
  8964. Type[Type["DateMillisecond"] = -14] = "DateMillisecond";
  8965. Type[Type["TimestampSecond"] = -15] = "TimestampSecond";
  8966. Type[Type["TimestampMillisecond"] = -16] = "TimestampMillisecond";
  8967. Type[Type["TimestampMicrosecond"] = -17] = "TimestampMicrosecond";
  8968. Type[Type["TimestampNanosecond"] = -18] = "TimestampNanosecond";
  8969. Type[Type["TimeSecond"] = -19] = "TimeSecond";
  8970. Type[Type["TimeMillisecond"] = -20] = "TimeMillisecond";
  8971. Type[Type["TimeMicrosecond"] = -21] = "TimeMicrosecond";
  8972. Type[Type["TimeNanosecond"] = -22] = "TimeNanosecond";
  8973. Type[Type["DenseUnion"] = -23] = "DenseUnion";
  8974. Type[Type["SparseUnion"] = -24] = "SparseUnion";
  8975. Type[Type["IntervalDayTime"] = -25] = "IntervalDayTime";
  8976. Type[Type["IntervalYearMonth"] = -26] = "IntervalYearMonth";
  8977. })(Type || (Type = {}));
  8978. let _Symbol$toStringTag, _Symbol$toStringTag2, _Symbol$toStringTag7;
  8979. class DataType {
  8980. static isNull(x) {
  8981. return x && x.typeId === Type.Null;
  8982. }
  8983. static isInt(x) {
  8984. return x && x.typeId === Type.Int;
  8985. }
  8986. static isFloat(x) {
  8987. return x && x.typeId === Type.Float;
  8988. }
  8989. static isBinary(x) {
  8990. return x && x.typeId === Type.Binary;
  8991. }
  8992. static isUtf8(x) {
  8993. return x && x.typeId === Type.Utf8;
  8994. }
  8995. static isBool(x) {
  8996. return x && x.typeId === Type.Bool;
  8997. }
  8998. static isDecimal(x) {
  8999. return x && x.typeId === Type.Decimal;
  9000. }
  9001. static isDate(x) {
  9002. return x && x.typeId === Type.Date;
  9003. }
  9004. static isTime(x) {
  9005. return x && x.typeId === Type.Time;
  9006. }
  9007. static isTimestamp(x) {
  9008. return x && x.typeId === Type.Timestamp;
  9009. }
  9010. static isInterval(x) {
  9011. return x && x.typeId === Type.Interval;
  9012. }
  9013. static isList(x) {
  9014. return x && x.typeId === Type.List;
  9015. }
  9016. static isStruct(x) {
  9017. return x && x.typeId === Type.Struct;
  9018. }
  9019. static isUnion(x) {
  9020. return x && x.typeId === Type.Union;
  9021. }
  9022. static isFixedSizeBinary(x) {
  9023. return x && x.typeId === Type.FixedSizeBinary;
  9024. }
  9025. static isFixedSizeList(x) {
  9026. return x && x.typeId === Type.FixedSizeList;
  9027. }
  9028. static isMap(x) {
  9029. return x && x.typeId === Type.Map;
  9030. }
  9031. static isDictionary(x) {
  9032. return x && x.typeId === Type.Dictionary;
  9033. }
  9034. get typeId() {
  9035. return Type.NONE;
  9036. }
  9037. compareTo(other) {
  9038. return this === other;
  9039. }
  9040. }
  9041. _Symbol$toStringTag = Symbol.toStringTag;
  9042. class Int extends DataType {
  9043. constructor(isSigned, bitWidth) {
  9044. super();
  9045. _defineProperty(this, "isSigned", void 0);
  9046. _defineProperty(this, "bitWidth", void 0);
  9047. this.isSigned = isSigned;
  9048. this.bitWidth = bitWidth;
  9049. }
  9050. get typeId() {
  9051. return Type.Int;
  9052. }
  9053. get [_Symbol$toStringTag]() {
  9054. return 'Int';
  9055. }
  9056. toString() {
  9057. return "".concat(this.isSigned ? 'I' : 'Ui', "nt").concat(this.bitWidth);
  9058. }
  9059. }
  9060. class Int8 extends Int {
  9061. constructor() {
  9062. super(true, 8);
  9063. }
  9064. }
  9065. class Int16 extends Int {
  9066. constructor() {
  9067. super(true, 16);
  9068. }
  9069. }
  9070. class Int32 extends Int {
  9071. constructor() {
  9072. super(true, 32);
  9073. }
  9074. }
  9075. class Uint8 extends Int {
  9076. constructor() {
  9077. super(false, 8);
  9078. }
  9079. }
  9080. class Uint16 extends Int {
  9081. constructor() {
  9082. super(false, 16);
  9083. }
  9084. }
  9085. class Uint32 extends Int {
  9086. constructor() {
  9087. super(false, 32);
  9088. }
  9089. }
  9090. const Precision = {
  9091. HALF: 16,
  9092. SINGLE: 32,
  9093. DOUBLE: 64
  9094. };
  9095. _Symbol$toStringTag2 = Symbol.toStringTag;
  9096. class Float extends DataType {
  9097. constructor(precision) {
  9098. super();
  9099. _defineProperty(this, "precision", void 0);
  9100. this.precision = precision;
  9101. }
  9102. get typeId() {
  9103. return Type.Float;
  9104. }
  9105. get [_Symbol$toStringTag2]() {
  9106. return 'Float';
  9107. }
  9108. toString() {
  9109. return "Float".concat(this.precision);
  9110. }
  9111. }
  9112. class Float32 extends Float {
  9113. constructor() {
  9114. super(Precision.SINGLE);
  9115. }
  9116. }
  9117. class Float64 extends Float {
  9118. constructor() {
  9119. super(Precision.DOUBLE);
  9120. }
  9121. }
  9122. _Symbol$toStringTag7 = Symbol.toStringTag;
  9123. class FixedSizeList extends DataType {
  9124. constructor(listSize, child) {
  9125. super();
  9126. _defineProperty(this, "listSize", void 0);
  9127. _defineProperty(this, "children", void 0);
  9128. this.listSize = listSize;
  9129. this.children = [child];
  9130. }
  9131. get typeId() {
  9132. return Type.FixedSizeList;
  9133. }
  9134. get valueType() {
  9135. return this.children[0].type;
  9136. }
  9137. get valueField() {
  9138. return this.children[0];
  9139. }
  9140. get [_Symbol$toStringTag7]() {
  9141. return 'FixedSizeList';
  9142. }
  9143. toString() {
  9144. return "FixedSizeList[".concat(this.listSize, "]<").concat(this.valueType, ">");
  9145. }
  9146. }
  9147. function getArrowTypeFromTypedArray(array) {
  9148. switch (array.constructor) {
  9149. case Int8Array:
  9150. return new Int8();
  9151. case Uint8Array:
  9152. return new Uint8();
  9153. case Int16Array:
  9154. return new Int16();
  9155. case Uint16Array:
  9156. return new Uint16();
  9157. case Int32Array:
  9158. return new Int32();
  9159. case Uint32Array:
  9160. return new Uint32();
  9161. case Float32Array:
  9162. return new Float32();
  9163. case Float64Array:
  9164. return new Float64();
  9165. default:
  9166. throw new Error('array type not supported');
  9167. }
  9168. }
  9169. function deduceMeshField(attributeName, attribute, optionalMetadata) {
  9170. const type = getArrowTypeFromTypedArray(attribute.value);
  9171. const metadata = optionalMetadata ? optionalMetadata : makeMeshAttributeMetadata(attribute);
  9172. const field = new Field(attributeName, new FixedSizeList(attribute.size, new Field('value', type)), false, metadata);
  9173. return field;
  9174. }
  9175. function makeMeshAttributeMetadata(attribute) {
  9176. const result = new Map();
  9177. if ('byteOffset' in attribute) {
  9178. result.set('byteOffset', attribute.byteOffset.toString(10));
  9179. }
  9180. if ('byteStride' in attribute) {
  9181. result.set('byteStride', attribute.byteStride.toString(10));
  9182. }
  9183. if ('normalized' in attribute) {
  9184. result.set('normalized', attribute.normalized.toString());
  9185. }
  9186. return result;
  9187. }
  9188. function getDracoSchema(attributes, loaderData, indices) {
  9189. const metadataMap = makeMetadata(loaderData.metadata);
  9190. const fields = [];
  9191. const namedLoaderDataAttributes = transformAttributesLoaderData(loaderData.attributes);
  9192. for (const attributeName in attributes) {
  9193. const attribute = attributes[attributeName];
  9194. const field = getArrowFieldFromAttribute(attributeName, attribute, namedLoaderDataAttributes[attributeName]);
  9195. fields.push(field);
  9196. }
  9197. if (indices) {
  9198. const indicesField = getArrowFieldFromAttribute('indices', indices);
  9199. fields.push(indicesField);
  9200. }
  9201. return new Schema(fields, metadataMap);
  9202. }
  9203. function transformAttributesLoaderData(loaderData) {
  9204. const result = {};
  9205. for (const key in loaderData) {
  9206. const dracoAttribute = loaderData[key];
  9207. result[dracoAttribute.name || 'undefined'] = dracoAttribute;
  9208. }
  9209. return result;
  9210. }
  9211. function getArrowFieldFromAttribute(attributeName, attribute, loaderData) {
  9212. const metadataMap = loaderData ? makeMetadata(loaderData.metadata) : undefined;
  9213. const field = deduceMeshField(attributeName, attribute, metadataMap);
  9214. return field;
  9215. }
  9216. function makeMetadata(metadata) {
  9217. const metadataMap = new Map();
  9218. for (const key in metadata) {
  9219. metadataMap.set("".concat(key, ".string"), JSON.stringify(metadata[key]));
  9220. }
  9221. return metadataMap;
  9222. }
  9223. const DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP = {
  9224. POSITION: 'POSITION',
  9225. NORMAL: 'NORMAL',
  9226. COLOR: 'COLOR_0',
  9227. TEX_COORD: 'TEXCOORD_0'
  9228. };
  9229. const DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP = {
  9230. 1: Int8Array,
  9231. 2: Uint8Array,
  9232. 3: Int16Array,
  9233. 4: Uint16Array,
  9234. 5: Int32Array,
  9235. 6: Uint32Array,
  9236. 9: Float32Array
  9237. };
  9238. const INDEX_ITEM_SIZE = 4;
  9239. class DracoParser {
  9240. constructor(draco) {
  9241. _defineProperty(this, "draco", void 0);
  9242. _defineProperty(this, "decoder", void 0);
  9243. _defineProperty(this, "metadataQuerier", void 0);
  9244. this.draco = draco;
  9245. this.decoder = new this.draco.Decoder();
  9246. this.metadataQuerier = new this.draco.MetadataQuerier();
  9247. }
  9248. destroy() {
  9249. this.draco.destroy(this.decoder);
  9250. this.draco.destroy(this.metadataQuerier);
  9251. }
  9252. parseSync(arrayBuffer, options = {}) {
  9253. const buffer = new this.draco.DecoderBuffer();
  9254. buffer.Init(new Int8Array(arrayBuffer), arrayBuffer.byteLength);
  9255. this._disableAttributeTransforms(options);
  9256. const geometry_type = this.decoder.GetEncodedGeometryType(buffer);
  9257. const dracoGeometry = geometry_type === this.draco.TRIANGULAR_MESH ? new this.draco.Mesh() : new this.draco.PointCloud();
  9258. try {
  9259. let dracoStatus;
  9260. switch (geometry_type) {
  9261. case this.draco.TRIANGULAR_MESH:
  9262. dracoStatus = this.decoder.DecodeBufferToMesh(buffer, dracoGeometry);
  9263. break;
  9264. case this.draco.POINT_CLOUD:
  9265. dracoStatus = this.decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
  9266. break;
  9267. default:
  9268. throw new Error('DRACO: Unknown geometry type.');
  9269. }
  9270. if (!dracoStatus.ok() || !dracoGeometry.ptr) {
  9271. const message = "DRACO decompression failed: ".concat(dracoStatus.error_msg());
  9272. throw new Error(message);
  9273. }
  9274. const loaderData = this._getDracoLoaderData(dracoGeometry, geometry_type, options);
  9275. const geometry = this._getMeshData(dracoGeometry, loaderData, options);
  9276. const boundingBox = getMeshBoundingBox(geometry.attributes);
  9277. const schema = getDracoSchema(geometry.attributes, loaderData, geometry.indices);
  9278. const data = {
  9279. loader: 'draco',
  9280. loaderData,
  9281. header: {
  9282. vertexCount: dracoGeometry.num_points(),
  9283. boundingBox
  9284. },
  9285. ...geometry,
  9286. schema
  9287. };
  9288. return data;
  9289. } finally {
  9290. this.draco.destroy(buffer);
  9291. if (dracoGeometry) {
  9292. this.draco.destroy(dracoGeometry);
  9293. }
  9294. }
  9295. }
  9296. _getDracoLoaderData(dracoGeometry, geometry_type, options) {
  9297. const metadata = this._getTopLevelMetadata(dracoGeometry);
  9298. const attributes = this._getDracoAttributes(dracoGeometry, options);
  9299. return {
  9300. geometry_type,
  9301. num_attributes: dracoGeometry.num_attributes(),
  9302. num_points: dracoGeometry.num_points(),
  9303. num_faces: dracoGeometry instanceof this.draco.Mesh ? dracoGeometry.num_faces() : 0,
  9304. metadata,
  9305. attributes
  9306. };
  9307. }
  9308. _getDracoAttributes(dracoGeometry, options) {
  9309. const dracoAttributes = {};
  9310. for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {
  9311. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);
  9312. const metadata = this._getAttributeMetadata(dracoGeometry, attributeId);
  9313. dracoAttributes[dracoAttribute.unique_id()] = {
  9314. unique_id: dracoAttribute.unique_id(),
  9315. attribute_type: dracoAttribute.attribute_type(),
  9316. data_type: dracoAttribute.data_type(),
  9317. num_components: dracoAttribute.num_components(),
  9318. byte_offset: dracoAttribute.byte_offset(),
  9319. byte_stride: dracoAttribute.byte_stride(),
  9320. normalized: dracoAttribute.normalized(),
  9321. attribute_index: attributeId,
  9322. metadata
  9323. };
  9324. const quantization = this._getQuantizationTransform(dracoAttribute, options);
  9325. if (quantization) {
  9326. dracoAttributes[dracoAttribute.unique_id()].quantization_transform = quantization;
  9327. }
  9328. const octahedron = this._getOctahedronTransform(dracoAttribute, options);
  9329. if (octahedron) {
  9330. dracoAttributes[dracoAttribute.unique_id()].octahedron_transform = octahedron;
  9331. }
  9332. }
  9333. return dracoAttributes;
  9334. }
  9335. _getMeshData(dracoGeometry, loaderData, options) {
  9336. const attributes = this._getMeshAttributes(loaderData, dracoGeometry, options);
  9337. const positionAttribute = attributes.POSITION;
  9338. if (!positionAttribute) {
  9339. throw new Error('DRACO: No position attribute found.');
  9340. }
  9341. if (dracoGeometry instanceof this.draco.Mesh) {
  9342. switch (options.topology) {
  9343. case 'triangle-strip':
  9344. return {
  9345. topology: 'triangle-strip',
  9346. mode: 4,
  9347. attributes,
  9348. indices: {
  9349. value: this._getTriangleStripIndices(dracoGeometry),
  9350. size: 1
  9351. }
  9352. };
  9353. case 'triangle-list':
  9354. default:
  9355. return {
  9356. topology: 'triangle-list',
  9357. mode: 5,
  9358. attributes,
  9359. indices: {
  9360. value: this._getTriangleListIndices(dracoGeometry),
  9361. size: 1
  9362. }
  9363. };
  9364. }
  9365. }
  9366. return {
  9367. topology: 'point-list',
  9368. mode: 0,
  9369. attributes
  9370. };
  9371. }
  9372. _getMeshAttributes(loaderData, dracoGeometry, options) {
  9373. const attributes = {};
  9374. for (const loaderAttribute of Object.values(loaderData.attributes)) {
  9375. const attributeName = this._deduceAttributeName(loaderAttribute, options);
  9376. loaderAttribute.name = attributeName;
  9377. const {
  9378. value,
  9379. size
  9380. } = this._getAttributeValues(dracoGeometry, loaderAttribute);
  9381. attributes[attributeName] = {
  9382. value,
  9383. size,
  9384. byteOffset: loaderAttribute.byte_offset,
  9385. byteStride: loaderAttribute.byte_stride,
  9386. normalized: loaderAttribute.normalized
  9387. };
  9388. }
  9389. return attributes;
  9390. }
  9391. _getTriangleListIndices(dracoGeometry) {
  9392. const numFaces = dracoGeometry.num_faces();
  9393. const numIndices = numFaces * 3;
  9394. const byteLength = numIndices * INDEX_ITEM_SIZE;
  9395. const ptr = this.draco._malloc(byteLength);
  9396. try {
  9397. this.decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);
  9398. return new Uint32Array(this.draco.HEAPF32.buffer, ptr, numIndices).slice();
  9399. } finally {
  9400. this.draco._free(ptr);
  9401. }
  9402. }
  9403. _getTriangleStripIndices(dracoGeometry) {
  9404. const dracoArray = new this.draco.DracoInt32Array();
  9405. try {
  9406. this.decoder.GetTriangleStripsFromMesh(dracoGeometry, dracoArray);
  9407. return getUint32Array(dracoArray);
  9408. } finally {
  9409. this.draco.destroy(dracoArray);
  9410. }
  9411. }
  9412. _getAttributeValues(dracoGeometry, attribute) {
  9413. const TypedArrayCtor = DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP[attribute.data_type];
  9414. const numComponents = attribute.num_components;
  9415. const numPoints = dracoGeometry.num_points();
  9416. const numValues = numPoints * numComponents;
  9417. const byteLength = numValues * TypedArrayCtor.BYTES_PER_ELEMENT;
  9418. const dataType = getDracoDataType(this.draco, TypedArrayCtor);
  9419. let value;
  9420. const ptr = this.draco._malloc(byteLength);
  9421. try {
  9422. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attribute.attribute_index);
  9423. this.decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, dracoAttribute, dataType, byteLength, ptr);
  9424. value = new TypedArrayCtor(this.draco.HEAPF32.buffer, ptr, numValues).slice();
  9425. } finally {
  9426. this.draco._free(ptr);
  9427. }
  9428. return {
  9429. value,
  9430. size: numComponents
  9431. };
  9432. }
  9433. _deduceAttributeName(attribute, options) {
  9434. const uniqueId = attribute.unique_id;
  9435. for (const [attributeName, attributeUniqueId] of Object.entries(options.extraAttributes || {})) {
  9436. if (attributeUniqueId === uniqueId) {
  9437. return attributeName;
  9438. }
  9439. }
  9440. const thisAttributeType = attribute.attribute_type;
  9441. for (const dracoAttributeConstant in DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP) {
  9442. const attributeType = this.draco[dracoAttributeConstant];
  9443. if (attributeType === thisAttributeType) {
  9444. return DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP[dracoAttributeConstant];
  9445. }
  9446. }
  9447. const entryName = options.attributeNameEntry || 'name';
  9448. if (attribute.metadata[entryName]) {
  9449. return attribute.metadata[entryName].string;
  9450. }
  9451. return "CUSTOM_ATTRIBUTE_".concat(uniqueId);
  9452. }
  9453. _getTopLevelMetadata(dracoGeometry) {
  9454. const dracoMetadata = this.decoder.GetMetadata(dracoGeometry);
  9455. return this._getDracoMetadata(dracoMetadata);
  9456. }
  9457. _getAttributeMetadata(dracoGeometry, attributeId) {
  9458. const dracoMetadata = this.decoder.GetAttributeMetadata(dracoGeometry, attributeId);
  9459. return this._getDracoMetadata(dracoMetadata);
  9460. }
  9461. _getDracoMetadata(dracoMetadata) {
  9462. if (!dracoMetadata || !dracoMetadata.ptr) {
  9463. return {};
  9464. }
  9465. const result = {};
  9466. const numEntries = this.metadataQuerier.NumEntries(dracoMetadata);
  9467. for (let entryIndex = 0; entryIndex < numEntries; entryIndex++) {
  9468. const entryName = this.metadataQuerier.GetEntryName(dracoMetadata, entryIndex);
  9469. result[entryName] = this._getDracoMetadataField(dracoMetadata, entryName);
  9470. }
  9471. return result;
  9472. }
  9473. _getDracoMetadataField(dracoMetadata, entryName) {
  9474. const dracoArray = new this.draco.DracoInt32Array();
  9475. try {
  9476. this.metadataQuerier.GetIntEntryArray(dracoMetadata, entryName, dracoArray);
  9477. const intArray = getInt32Array(dracoArray);
  9478. return {
  9479. int: this.metadataQuerier.GetIntEntry(dracoMetadata, entryName),
  9480. string: this.metadataQuerier.GetStringEntry(dracoMetadata, entryName),
  9481. double: this.metadataQuerier.GetDoubleEntry(dracoMetadata, entryName),
  9482. intArray
  9483. };
  9484. } finally {
  9485. this.draco.destroy(dracoArray);
  9486. }
  9487. }
  9488. _disableAttributeTransforms(options) {
  9489. const {
  9490. quantizedAttributes = [],
  9491. octahedronAttributes = []
  9492. } = options;
  9493. const skipAttributes = [...quantizedAttributes, ...octahedronAttributes];
  9494. for (const dracoAttributeName of skipAttributes) {
  9495. this.decoder.SkipAttributeTransform(this.draco[dracoAttributeName]);
  9496. }
  9497. }
  9498. _getQuantizationTransform(dracoAttribute, options) {
  9499. const {
  9500. quantizedAttributes = []
  9501. } = options;
  9502. const attribute_type = dracoAttribute.attribute_type();
  9503. const skip = quantizedAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9504. if (skip) {
  9505. const transform = new this.draco.AttributeQuantizationTransform();
  9506. try {
  9507. if (transform.InitFromAttribute(dracoAttribute)) {
  9508. return {
  9509. quantization_bits: transform.quantization_bits(),
  9510. range: transform.range(),
  9511. min_values: new Float32Array([1, 2, 3]).map(i => transform.min_value(i))
  9512. };
  9513. }
  9514. } finally {
  9515. this.draco.destroy(transform);
  9516. }
  9517. }
  9518. return null;
  9519. }
  9520. _getOctahedronTransform(dracoAttribute, options) {
  9521. const {
  9522. octahedronAttributes = []
  9523. } = options;
  9524. const attribute_type = dracoAttribute.attribute_type();
  9525. const octahedron = octahedronAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9526. if (octahedron) {
  9527. const transform = new this.draco.AttributeQuantizationTransform();
  9528. try {
  9529. if (transform.InitFromAttribute(dracoAttribute)) {
  9530. return {
  9531. quantization_bits: transform.quantization_bits()
  9532. };
  9533. }
  9534. } finally {
  9535. this.draco.destroy(transform);
  9536. }
  9537. }
  9538. return null;
  9539. }
  9540. }
  9541. function getDracoDataType(draco, attributeType) {
  9542. switch (attributeType) {
  9543. case Float32Array:
  9544. return draco.DT_FLOAT32;
  9545. case Int8Array:
  9546. return draco.DT_INT8;
  9547. case Int16Array:
  9548. return draco.DT_INT16;
  9549. case Int32Array:
  9550. return draco.DT_INT32;
  9551. case Uint8Array:
  9552. return draco.DT_UINT8;
  9553. case Uint16Array:
  9554. return draco.DT_UINT16;
  9555. case Uint32Array:
  9556. return draco.DT_UINT32;
  9557. default:
  9558. return draco.DT_INVALID;
  9559. }
  9560. }
  9561. function getInt32Array(dracoArray) {
  9562. const numValues = dracoArray.size();
  9563. const intArray = new Int32Array(numValues);
  9564. for (let i = 0; i < numValues; i++) {
  9565. intArray[i] = dracoArray.GetValue(i);
  9566. }
  9567. return intArray;
  9568. }
  9569. function getUint32Array(dracoArray) {
  9570. const numValues = dracoArray.size();
  9571. const intArray = new Int32Array(numValues);
  9572. for (let i = 0; i < numValues; i++) {
  9573. intArray[i] = dracoArray.GetValue(i);
  9574. }
  9575. return intArray;
  9576. }
  9577. const DRACO_VERSION = '1.4.1';
  9578. const DRACO_JS_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.js");
  9579. const DRACO_WASM_WRAPPER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_wasm_wrapper.js");
  9580. const DRACO_WASM_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.wasm");
  9581. let loadDecoderPromise;
  9582. async function loadDracoDecoderModule(options) {
  9583. const modules = options.modules || {};
  9584. if (modules.draco3d) {
  9585. loadDecoderPromise = loadDecoderPromise || modules.draco3d.createDecoderModule({}).then(draco => {
  9586. return {
  9587. draco
  9588. };
  9589. });
  9590. } else {
  9591. loadDecoderPromise = loadDecoderPromise || loadDracoDecoder(options);
  9592. }
  9593. return await loadDecoderPromise;
  9594. }
  9595. async function loadDracoDecoder(options) {
  9596. let DracoDecoderModule;
  9597. let wasmBinary;
  9598. switch (options.draco && options.draco.decoderType) {
  9599. case 'js':
  9600. DracoDecoderModule = await loadLibrary(DRACO_JS_DECODER_URL, 'draco', options);
  9601. break;
  9602. case 'wasm':
  9603. default:
  9604. [DracoDecoderModule, wasmBinary] = await Promise.all([await loadLibrary(DRACO_WASM_WRAPPER_URL, 'draco', options), await loadLibrary(DRACO_WASM_DECODER_URL, 'draco', options)]);
  9605. }
  9606. DracoDecoderModule = DracoDecoderModule || globalThis.DracoDecoderModule;
  9607. return await initializeDracoDecoder(DracoDecoderModule, wasmBinary);
  9608. }
  9609. function initializeDracoDecoder(DracoDecoderModule, wasmBinary) {
  9610. const options = {};
  9611. if (wasmBinary) {
  9612. options.wasmBinary = wasmBinary;
  9613. }
  9614. return new Promise(resolve => {
  9615. DracoDecoderModule({ ...options,
  9616. onModuleLoaded: draco => resolve({
  9617. draco
  9618. })
  9619. });
  9620. });
  9621. }
  9622. const DracoLoader = { ...DracoLoader$1,
  9623. parse: parse$2
  9624. };
  9625. async function parse$2(arrayBuffer, options) {
  9626. const {
  9627. draco
  9628. } = await loadDracoDecoderModule(options);
  9629. const dracoParser = new DracoParser(draco);
  9630. try {
  9631. return dracoParser.parseSync(arrayBuffer, options === null || options === void 0 ? void 0 : options.draco);
  9632. } finally {
  9633. dracoParser.destroy();
  9634. }
  9635. }
  9636. const GL_PRIMITIVE_MODE = {
  9637. POINTS: 0x0000,
  9638. LINES: 0x0001,
  9639. LINE_LOOP: 0x0002,
  9640. LINE_STRIP: 0x0003,
  9641. TRIANGLES: 0x0004,
  9642. TRIANGLE_STRIP: 0x0005,
  9643. TRIANGLE_FAN: 0x0006
  9644. };
  9645. const GL_TYPE = {
  9646. BYTE: 5120,
  9647. UNSIGNED_BYTE: 5121,
  9648. SHORT: 5122,
  9649. UNSIGNED_SHORT: 5123,
  9650. INT: 5124,
  9651. UNSIGNED_INT: 5125,
  9652. FLOAT: 5126,
  9653. DOUBLE: 5130
  9654. };
  9655. const GL$1 = { ...GL_PRIMITIVE_MODE,
  9656. ...GL_TYPE
  9657. };
  9658. const GL_TYPE_TO_ARRAY_TYPE = {
  9659. [GL_TYPE.DOUBLE]: Float64Array,
  9660. [GL_TYPE.FLOAT]: Float32Array,
  9661. [GL_TYPE.UNSIGNED_SHORT]: Uint16Array,
  9662. [GL_TYPE.UNSIGNED_INT]: Uint32Array,
  9663. [GL_TYPE.UNSIGNED_BYTE]: Uint8Array,
  9664. [GL_TYPE.BYTE]: Int8Array,
  9665. [GL_TYPE.SHORT]: Int16Array,
  9666. [GL_TYPE.INT]: Int32Array
  9667. };
  9668. const NAME_TO_GL_TYPE = {
  9669. DOUBLE: GL_TYPE.DOUBLE,
  9670. FLOAT: GL_TYPE.FLOAT,
  9671. UNSIGNED_SHORT: GL_TYPE.UNSIGNED_SHORT,
  9672. UNSIGNED_INT: GL_TYPE.UNSIGNED_INT,
  9673. UNSIGNED_BYTE: GL_TYPE.UNSIGNED_BYTE,
  9674. BYTE: GL_TYPE.BYTE,
  9675. SHORT: GL_TYPE.SHORT,
  9676. INT: GL_TYPE.INT
  9677. };
  9678. const ERR_TYPE_CONVERSION = 'Failed to convert GL type';
  9679. class GLType {
  9680. static fromTypedArray(arrayOrType) {
  9681. arrayOrType = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;
  9682. for (const glType in GL_TYPE_TO_ARRAY_TYPE) {
  9683. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  9684. if (ArrayType === arrayOrType) {
  9685. return glType;
  9686. }
  9687. }
  9688. throw new Error(ERR_TYPE_CONVERSION);
  9689. }
  9690. static fromName(name) {
  9691. const glType = NAME_TO_GL_TYPE[name];
  9692. if (!glType) {
  9693. throw new Error(ERR_TYPE_CONVERSION);
  9694. }
  9695. return glType;
  9696. }
  9697. static getArrayType(glType) {
  9698. switch (glType) {
  9699. case GL_TYPE.UNSIGNED_SHORT_5_6_5:
  9700. case GL_TYPE.UNSIGNED_SHORT_4_4_4_4:
  9701. case GL_TYPE.UNSIGNED_SHORT_5_5_5_1:
  9702. return Uint16Array;
  9703. default:
  9704. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  9705. if (!ArrayType) {
  9706. throw new Error(ERR_TYPE_CONVERSION);
  9707. }
  9708. return ArrayType;
  9709. }
  9710. }
  9711. static getByteSize(glType) {
  9712. const ArrayType = GLType.getArrayType(glType);
  9713. return ArrayType.BYTES_PER_ELEMENT;
  9714. }
  9715. static validate(glType) {
  9716. return Boolean(GLType.getArrayType(glType));
  9717. }
  9718. static createTypedArray(glType, buffer, byteOffset = 0, length) {
  9719. if (length === undefined) {
  9720. length = (buffer.byteLength - byteOffset) / GLType.getByteSize(glType);
  9721. }
  9722. const ArrayType = GLType.getArrayType(glType);
  9723. return new ArrayType(buffer, byteOffset, length);
  9724. }
  9725. }
  9726. function assert$2(condition, message) {
  9727. if (!condition) {
  9728. throw new Error("math.gl assertion failed. ".concat(message));
  9729. }
  9730. }
  9731. function decodeRGB565(rgb565, target = [0, 0, 0]) {
  9732. const r5 = rgb565 >> 11 & 31;
  9733. const g6 = rgb565 >> 5 & 63;
  9734. const b5 = rgb565 & 31;
  9735. target[0] = r5 << 3;
  9736. target[1] = g6 << 2;
  9737. target[2] = b5 << 3;
  9738. return target;
  9739. }
  9740. new Vector2();
  9741. new Vector3();
  9742. new Vector2();
  9743. new Vector2();
  9744. function fromSNorm(value, rangeMaximum = 255) {
  9745. return clamp(value, 0.0, rangeMaximum) / rangeMaximum * 2.0 - 1.0;
  9746. }
  9747. function signNotZero(value) {
  9748. return value < 0.0 ? -1.0 : 1.0;
  9749. }
  9750. function octDecodeInRange(x, y, rangeMax, result) {
  9751. assert$2(result);
  9752. if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
  9753. throw new Error("x and y must be unsigned normalized integers between 0 and ".concat(rangeMax));
  9754. }
  9755. result.x = fromSNorm(x, rangeMax);
  9756. result.y = fromSNorm(y, rangeMax);
  9757. result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));
  9758. if (result.z < 0.0) {
  9759. const oldVX = result.x;
  9760. result.x = (1.0 - Math.abs(result.y)) * signNotZero(oldVX);
  9761. result.y = (1.0 - Math.abs(oldVX)) * signNotZero(result.y);
  9762. }
  9763. return result.normalize();
  9764. }
  9765. function octDecode(x, y, result) {
  9766. return octDecodeInRange(x, y, 255, result);
  9767. }
  9768. class Tile3DFeatureTable {
  9769. constructor(featureTableJson, featureTableBinary) {
  9770. _defineProperty(this, "json", void 0);
  9771. _defineProperty(this, "buffer", void 0);
  9772. _defineProperty(this, "featuresLength", 0);
  9773. _defineProperty(this, "_cachedTypedArrays", {});
  9774. this.json = featureTableJson;
  9775. this.buffer = featureTableBinary;
  9776. }
  9777. getExtension(extensionName) {
  9778. return this.json.extensions && this.json.extensions[extensionName];
  9779. }
  9780. hasProperty(propertyName) {
  9781. return Boolean(this.json[propertyName]);
  9782. }
  9783. getGlobalProperty(propertyName, componentType = GL$1.UNSIGNED_INT, componentLength = 1) {
  9784. const jsonValue = this.json[propertyName];
  9785. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  9786. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, 1, jsonValue.byteOffset);
  9787. }
  9788. return jsonValue;
  9789. }
  9790. getPropertyArray(propertyName, componentType, componentLength) {
  9791. const jsonValue = this.json[propertyName];
  9792. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  9793. if ('componentType' in jsonValue) {
  9794. componentType = GLType.fromName(jsonValue.componentType);
  9795. }
  9796. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, this.featuresLength, jsonValue.byteOffset);
  9797. }
  9798. return this._getTypedArrayFromArray(propertyName, componentType, jsonValue);
  9799. }
  9800. getProperty(propertyName, componentType, componentLength, featureId, result) {
  9801. const jsonValue = this.json[propertyName];
  9802. if (!jsonValue) {
  9803. return jsonValue;
  9804. }
  9805. const typedArray = this.getPropertyArray(propertyName, componentType, componentLength);
  9806. if (componentLength === 1) {
  9807. return typedArray[featureId];
  9808. }
  9809. for (let i = 0; i < componentLength; ++i) {
  9810. result[i] = typedArray[componentLength * featureId + i];
  9811. }
  9812. return result;
  9813. }
  9814. _getTypedArrayFromBinary(propertyName, componentType, componentLength, count, byteOffset) {
  9815. const cachedTypedArrays = this._cachedTypedArrays;
  9816. let typedArray = cachedTypedArrays[propertyName];
  9817. if (!typedArray) {
  9818. typedArray = GLType.createTypedArray(componentType, this.buffer.buffer, this.buffer.byteOffset + byteOffset, count * componentLength);
  9819. cachedTypedArrays[propertyName] = typedArray;
  9820. }
  9821. return typedArray;
  9822. }
  9823. _getTypedArrayFromArray(propertyName, componentType, array) {
  9824. const cachedTypedArrays = this._cachedTypedArrays;
  9825. let typedArray = cachedTypedArrays[propertyName];
  9826. if (!typedArray) {
  9827. typedArray = GLType.createTypedArray(componentType, array);
  9828. cachedTypedArrays[propertyName] = typedArray;
  9829. }
  9830. return typedArray;
  9831. }
  9832. }
  9833. const COMPONENTS_PER_ATTRIBUTE = {
  9834. SCALAR: 1,
  9835. VEC2: 2,
  9836. VEC3: 3,
  9837. VEC4: 4,
  9838. MAT2: 4,
  9839. MAT3: 9,
  9840. MAT4: 16
  9841. };
  9842. const UNPACKER = {
  9843. SCALAR: (values, i) => values[i],
  9844. VEC2: (values, i) => [values[2 * i + 0], values[2 * i + 1]],
  9845. VEC3: (values, i) => [values[3 * i + 0], values[3 * i + 1], values[3 * i + 2]],
  9846. VEC4: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  9847. MAT2: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  9848. 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]],
  9849. 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]]
  9850. };
  9851. const PACKER = {
  9852. SCALAR: (x, values, i) => {
  9853. values[i] = x;
  9854. },
  9855. VEC2: (x, values, i) => {
  9856. values[2 * i + 0] = x[0];
  9857. values[2 * i + 1] = x[1];
  9858. },
  9859. VEC3: (x, values, i) => {
  9860. values[3 * i + 0] = x[0];
  9861. values[3 * i + 1] = x[1];
  9862. values[3 * i + 2] = x[2];
  9863. },
  9864. VEC4: (x, values, i) => {
  9865. values[4 * i + 0] = x[0];
  9866. values[4 * i + 1] = x[1];
  9867. values[4 * i + 2] = x[2];
  9868. values[4 * i + 3] = x[3];
  9869. },
  9870. MAT2: (x, values, i) => {
  9871. values[4 * i + 0] = x[0];
  9872. values[4 * i + 1] = x[1];
  9873. values[4 * i + 2] = x[2];
  9874. values[4 * i + 3] = x[3];
  9875. },
  9876. MAT3: (x, values, i) => {
  9877. values[9 * i + 0] = x[0];
  9878. values[9 * i + 1] = x[1];
  9879. values[9 * i + 2] = x[2];
  9880. values[9 * i + 3] = x[3];
  9881. values[9 * i + 4] = x[4];
  9882. values[9 * i + 5] = x[5];
  9883. values[9 * i + 6] = x[6];
  9884. values[9 * i + 7] = x[7];
  9885. values[9 * i + 8] = x[8];
  9886. values[9 * i + 9] = x[9];
  9887. },
  9888. MAT4: (x, values, i) => {
  9889. values[16 * i + 0] = x[0];
  9890. values[16 * i + 1] = x[1];
  9891. values[16 * i + 2] = x[2];
  9892. values[16 * i + 3] = x[3];
  9893. values[16 * i + 4] = x[4];
  9894. values[16 * i + 5] = x[5];
  9895. values[16 * i + 6] = x[6];
  9896. values[16 * i + 7] = x[7];
  9897. values[16 * i + 8] = x[8];
  9898. values[16 * i + 9] = x[9];
  9899. values[16 * i + 10] = x[10];
  9900. values[16 * i + 11] = x[11];
  9901. values[16 * i + 12] = x[12];
  9902. values[16 * i + 13] = x[13];
  9903. values[16 * i + 14] = x[14];
  9904. values[16 * i + 15] = x[15];
  9905. }
  9906. };
  9907. function createTypedArrayFromAccessor(tile3DAccessor, buffer, byteOffset, length) {
  9908. const {
  9909. componentType
  9910. } = tile3DAccessor;
  9911. assert$7(tile3DAccessor.componentType);
  9912. const type = typeof componentType === 'string' ? GLType.fromName(componentType) : componentType;
  9913. const size = COMPONENTS_PER_ATTRIBUTE[tile3DAccessor.type];
  9914. const unpacker = UNPACKER[tile3DAccessor.type];
  9915. const packer = PACKER[tile3DAccessor.type];
  9916. byteOffset += tile3DAccessor.byteOffset;
  9917. const values = GLType.createTypedArray(type, buffer, byteOffset, size * length);
  9918. return {
  9919. values,
  9920. type,
  9921. size,
  9922. unpacker,
  9923. packer
  9924. };
  9925. }
  9926. const defined$1 = x => x !== undefined;
  9927. function initializeHierarchy(batchTable, jsonHeader, binaryBody) {
  9928. if (!jsonHeader) {
  9929. return null;
  9930. }
  9931. let hierarchy = batchTable.getExtension('3DTILES_batch_table_hierarchy');
  9932. const legacyHierarchy = jsonHeader.HIERARCHY;
  9933. if (legacyHierarchy) {
  9934. console.warn('3D Tile Parser: HIERARCHY is deprecated. Use 3DTILES_batch_table_hierarchy.');
  9935. jsonHeader.extensions = jsonHeader.extensions || {};
  9936. jsonHeader.extensions['3DTILES_batch_table_hierarchy'] = legacyHierarchy;
  9937. hierarchy = legacyHierarchy;
  9938. }
  9939. if (!hierarchy) {
  9940. return null;
  9941. }
  9942. return initializeHierarchyValues(hierarchy, binaryBody);
  9943. }
  9944. function initializeHierarchyValues(hierarchyJson, binaryBody) {
  9945. let i;
  9946. let classId;
  9947. let binaryAccessor;
  9948. const instancesLength = hierarchyJson.instancesLength;
  9949. const classes = hierarchyJson.classes;
  9950. let classIds = hierarchyJson.classIds;
  9951. let parentCounts = hierarchyJson.parentCounts;
  9952. let parentIds = hierarchyJson.parentIds;
  9953. let parentIdsLength = instancesLength;
  9954. if (defined$1(classIds.byteOffset)) {
  9955. classIds.componentType = defaultValue(classIds.componentType, GL.UNSIGNED_SHORT);
  9956. classIds.type = AttributeType.SCALAR;
  9957. binaryAccessor = getBinaryAccessor(classIds);
  9958. classIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + classIds.byteOffset, instancesLength);
  9959. }
  9960. let parentIndexes;
  9961. if (defined$1(parentCounts)) {
  9962. if (defined$1(parentCounts.byteOffset)) {
  9963. parentCounts.componentType = defaultValue(parentCounts.componentType, GL.UNSIGNED_SHORT);
  9964. parentCounts.type = AttributeType.SCALAR;
  9965. binaryAccessor = getBinaryAccessor(parentCounts);
  9966. parentCounts = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentCounts.byteOffset, instancesLength);
  9967. }
  9968. parentIndexes = new Uint16Array(instancesLength);
  9969. parentIdsLength = 0;
  9970. for (i = 0; i < instancesLength; ++i) {
  9971. parentIndexes[i] = parentIdsLength;
  9972. parentIdsLength += parentCounts[i];
  9973. }
  9974. }
  9975. if (defined$1(parentIds) && defined$1(parentIds.byteOffset)) {
  9976. parentIds.componentType = defaultValue(parentIds.componentType, GL.UNSIGNED_SHORT);
  9977. parentIds.type = AttributeType.SCALAR;
  9978. binaryAccessor = getBinaryAccessor(parentIds);
  9979. parentIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentIds.byteOffset, parentIdsLength);
  9980. }
  9981. const classesLength = classes.length;
  9982. for (i = 0; i < classesLength; ++i) {
  9983. const classInstancesLength = classes[i].length;
  9984. const properties = classes[i].instances;
  9985. const binaryProperties = getBinaryProperties(classInstancesLength, properties, binaryBody);
  9986. classes[i].instances = combine(binaryProperties, properties);
  9987. }
  9988. const classCounts = new Array(classesLength).fill(0);
  9989. const classIndexes = new Uint16Array(instancesLength);
  9990. for (i = 0; i < instancesLength; ++i) {
  9991. classId = classIds[i];
  9992. classIndexes[i] = classCounts[classId];
  9993. ++classCounts[classId];
  9994. }
  9995. const hierarchy = {
  9996. classes,
  9997. classIds,
  9998. classIndexes,
  9999. parentCounts,
  10000. parentIndexes,
  10001. parentIds
  10002. };
  10003. validateHierarchy(hierarchy);
  10004. return hierarchy;
  10005. }
  10006. function traverseHierarchy(hierarchy, instanceIndex, endConditionCallback) {
  10007. if (!hierarchy) {
  10008. return;
  10009. }
  10010. const parentCounts = hierarchy.parentCounts;
  10011. const parentIds = hierarchy.parentIds;
  10012. if (parentIds) {
  10013. return endConditionCallback(hierarchy, instanceIndex);
  10014. }
  10015. if (parentCounts > 0) {
  10016. return traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback);
  10017. }
  10018. return traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback);
  10019. }
  10020. function traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback) {
  10021. const classIds = hierarchy.classIds;
  10022. const parentCounts = hierarchy.parentCounts;
  10023. const parentIds = hierarchy.parentIds;
  10024. const parentIndexes = hierarchy.parentIndexes;
  10025. const instancesLength = classIds.length;
  10026. const visited = scratchVisited;
  10027. visited.length = Math.max(visited.length, instancesLength);
  10028. const visitedMarker = ++marker;
  10029. const stack = scratchStack;
  10030. stack.length = 0;
  10031. stack.push(instanceIndex);
  10032. while (stack.length > 0) {
  10033. instanceIndex = stack.pop();
  10034. if (visited[instanceIndex] === visitedMarker) {
  10035. continue;
  10036. }
  10037. visited[instanceIndex] = visitedMarker;
  10038. const result = endConditionCallback(hierarchy, instanceIndex);
  10039. if (defined$1(result)) {
  10040. return result;
  10041. }
  10042. const parentCount = parentCounts[instanceIndex];
  10043. const parentIndex = parentIndexes[instanceIndex];
  10044. for (let i = 0; i < parentCount; ++i) {
  10045. const parentId = parentIds[parentIndex + i];
  10046. if (parentId !== instanceIndex) {
  10047. stack.push(parentId);
  10048. }
  10049. }
  10050. }
  10051. return null;
  10052. }
  10053. function traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback) {
  10054. let hasParent = true;
  10055. while (hasParent) {
  10056. const result = endConditionCallback(hierarchy, instanceIndex);
  10057. if (defined$1(result)) {
  10058. return result;
  10059. }
  10060. const parentId = hierarchy.parentIds[instanceIndex];
  10061. hasParent = parentId !== instanceIndex;
  10062. instanceIndex = parentId;
  10063. }
  10064. throw new Error('traverseHierarchySingleParent');
  10065. }
  10066. function validateHierarchy(hierarchy) {
  10067. const classIds = hierarchy.classIds;
  10068. const instancesLength = classIds.length;
  10069. for (let i = 0; i < instancesLength; ++i) {
  10070. validateInstance(hierarchy, i, stack);
  10071. }
  10072. }
  10073. function validateInstance(hierarchy, instanceIndex, stack) {
  10074. const parentCounts = hierarchy.parentCounts;
  10075. const parentIds = hierarchy.parentIds;
  10076. const parentIndexes = hierarchy.parentIndexes;
  10077. const classIds = hierarchy.classIds;
  10078. const instancesLength = classIds.length;
  10079. if (!defined$1(parentIds)) {
  10080. return;
  10081. }
  10082. assert(instanceIndex < instancesLength, "Parent index ".concat(instanceIndex, " exceeds the total number of instances: ").concat(instancesLength));
  10083. assert(stack.indexOf(instanceIndex) === -1, 'Circular dependency detected in the batch table hierarchy.');
  10084. stack.push(instanceIndex);
  10085. const parentCount = defined$1(parentCounts) ? parentCounts[instanceIndex] : 1;
  10086. const parentIndex = defined$1(parentCounts) ? parentIndexes[instanceIndex] : instanceIndex;
  10087. for (let i = 0; i < parentCount; ++i) {
  10088. const parentId = parentIds[parentIndex + i];
  10089. if (parentId !== instanceIndex) {
  10090. validateInstance(hierarchy, parentId, stack);
  10091. }
  10092. }
  10093. stack.pop(instanceIndex);
  10094. }
  10095. function defined(x) {
  10096. return x !== undefined && x !== null;
  10097. }
  10098. const clone = (x, y) => x;
  10099. const IGNORED_PROPERTY_FIELDS = {
  10100. HIERARCHY: true,
  10101. extensions: true,
  10102. extras: true
  10103. };
  10104. class Tile3DBatchTableParser {
  10105. constructor(json, binary, featureCount, options = {}) {
  10106. var _this$json;
  10107. _defineProperty(this, "json", void 0);
  10108. _defineProperty(this, "binary", void 0);
  10109. _defineProperty(this, "featureCount", void 0);
  10110. _defineProperty(this, "_extensions", void 0);
  10111. _defineProperty(this, "_properties", void 0);
  10112. _defineProperty(this, "_binaryProperties", void 0);
  10113. _defineProperty(this, "_hierarchy", void 0);
  10114. assert$7(featureCount >= 0);
  10115. this.json = json || {};
  10116. this.binary = binary;
  10117. this.featureCount = featureCount;
  10118. this._extensions = ((_this$json = this.json) === null || _this$json === void 0 ? void 0 : _this$json.extensions) || {};
  10119. this._properties = {};
  10120. for (const propertyName in this.json) {
  10121. if (!IGNORED_PROPERTY_FIELDS[propertyName]) {
  10122. this._properties[propertyName] = this.json[propertyName];
  10123. }
  10124. }
  10125. this._binaryProperties = this._initializeBinaryProperties();
  10126. if (options['3DTILES_batch_table_hierarchy']) {
  10127. this._hierarchy = initializeHierarchy(this, this.json, this.binary);
  10128. }
  10129. }
  10130. getExtension(extensionName) {
  10131. return this.json && this.json.extensions && this.json.extensions[extensionName];
  10132. }
  10133. memorySizeInBytes() {
  10134. return 0;
  10135. }
  10136. isClass(batchId, className) {
  10137. this._checkBatchId(batchId);
  10138. assert$7(typeof className === 'string', className);
  10139. if (this._hierarchy) {
  10140. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10141. const classId = hierarchy.classIds[instanceIndex];
  10142. const instanceClass = hierarchy.classes[classId];
  10143. return instanceClass.name === className;
  10144. });
  10145. return defined(result);
  10146. }
  10147. return false;
  10148. }
  10149. isExactClass(batchId, className) {
  10150. assert$7(typeof className === 'string', className);
  10151. return this.getExactClassName(batchId) === className;
  10152. }
  10153. getExactClassName(batchId) {
  10154. this._checkBatchId(batchId);
  10155. if (this._hierarchy) {
  10156. const classId = this._hierarchy.classIds[batchId];
  10157. const instanceClass = this._hierarchy.classes[classId];
  10158. return instanceClass.name;
  10159. }
  10160. return undefined;
  10161. }
  10162. hasProperty(batchId, name) {
  10163. this._checkBatchId(batchId);
  10164. assert$7(typeof name === 'string', name);
  10165. return defined(this._properties[name]) || this._hasPropertyInHierarchy(batchId, name);
  10166. }
  10167. getPropertyNames(batchId, results) {
  10168. this._checkBatchId(batchId);
  10169. results = defined(results) ? results : [];
  10170. results.length = 0;
  10171. const propertyNames = Object.keys(this._properties);
  10172. results.push(...propertyNames);
  10173. if (this._hierarchy) {
  10174. this._getPropertyNamesInHierarchy(batchId, results);
  10175. }
  10176. return results;
  10177. }
  10178. getProperty(batchId, name) {
  10179. this._checkBatchId(batchId);
  10180. assert$7(typeof name === 'string', name);
  10181. if (this._binaryProperties) {
  10182. const binaryProperty = this._binaryProperties[name];
  10183. if (defined(binaryProperty)) {
  10184. return this._getBinaryProperty(binaryProperty, batchId);
  10185. }
  10186. }
  10187. const propertyValues = this._properties[name];
  10188. if (defined(propertyValues)) {
  10189. return clone(propertyValues[batchId]);
  10190. }
  10191. if (this._hierarchy) {
  10192. const hierarchyProperty = this._getHierarchyProperty(batchId, name);
  10193. if (defined(hierarchyProperty)) {
  10194. return hierarchyProperty;
  10195. }
  10196. }
  10197. return undefined;
  10198. }
  10199. setProperty(batchId, name, value) {
  10200. const featureCount = this.featureCount;
  10201. this._checkBatchId(batchId);
  10202. assert$7(typeof name === 'string', name);
  10203. if (this._binaryProperties) {
  10204. const binaryProperty = this._binaryProperties[name];
  10205. if (binaryProperty) {
  10206. this._setBinaryProperty(binaryProperty, batchId, value);
  10207. return;
  10208. }
  10209. }
  10210. if (this._hierarchy) {
  10211. if (this._setHierarchyProperty(this, batchId, name, value)) {
  10212. return;
  10213. }
  10214. }
  10215. let propertyValues = this._properties[name];
  10216. if (!defined(propertyValues)) {
  10217. this._properties[name] = new Array(featureCount);
  10218. propertyValues = this._properties[name];
  10219. }
  10220. propertyValues[batchId] = clone(value);
  10221. }
  10222. _checkBatchId(batchId) {
  10223. const valid = batchId >= 0 && batchId < this.featureCount;
  10224. if (!valid) {
  10225. throw new Error('batchId not in range [0, featureCount - 1].');
  10226. }
  10227. }
  10228. _getBinaryProperty(binaryProperty, index) {
  10229. return binaryProperty.unpack(binaryProperty.typedArray, index);
  10230. }
  10231. _setBinaryProperty(binaryProperty, index, value) {
  10232. binaryProperty.pack(value, binaryProperty.typedArray, index);
  10233. }
  10234. _initializeBinaryProperties() {
  10235. let binaryProperties = null;
  10236. for (const name in this._properties) {
  10237. const property = this._properties[name];
  10238. const binaryProperty = this._initializeBinaryProperty(name, property);
  10239. if (binaryProperty) {
  10240. binaryProperties = binaryProperties || {};
  10241. binaryProperties[name] = binaryProperty;
  10242. }
  10243. }
  10244. return binaryProperties;
  10245. }
  10246. _initializeBinaryProperty(name, property) {
  10247. if ('byteOffset' in property) {
  10248. const tile3DAccessor = property;
  10249. assert$7(this.binary, "Property ".concat(name, " requires a batch table binary."));
  10250. assert$7(tile3DAccessor.type, "Property ".concat(name, " requires a type."));
  10251. const accessor = createTypedArrayFromAccessor(tile3DAccessor, this.binary.buffer, this.binary.byteOffset | 0, this.featureCount);
  10252. return {
  10253. typedArray: accessor.values,
  10254. componentCount: accessor.size,
  10255. unpack: accessor.unpacker,
  10256. pack: accessor.packer
  10257. };
  10258. }
  10259. return null;
  10260. }
  10261. _hasPropertyInHierarchy(batchId, name) {
  10262. if (!this._hierarchy) {
  10263. return false;
  10264. }
  10265. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10266. const classId = hierarchy.classIds[instanceIndex];
  10267. const instances = hierarchy.classes[classId].instances;
  10268. return defined(instances[name]);
  10269. });
  10270. return defined(result);
  10271. }
  10272. _getPropertyNamesInHierarchy(batchId, results) {
  10273. traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10274. const classId = hierarchy.classIds[instanceIndex];
  10275. const instances = hierarchy.classes[classId].instances;
  10276. for (const name in instances) {
  10277. if (instances.hasOwnProperty(name)) {
  10278. if (results.indexOf(name) === -1) {
  10279. results.push(name);
  10280. }
  10281. }
  10282. }
  10283. });
  10284. }
  10285. _getHierarchyProperty(batchId, name) {
  10286. return traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10287. const classId = hierarchy.classIds[instanceIndex];
  10288. const instanceClass = hierarchy.classes[classId];
  10289. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10290. const propertyValues = instanceClass.instances[name];
  10291. if (defined(propertyValues)) {
  10292. if (defined(propertyValues.typedArray)) {
  10293. return this._getBinaryProperty(propertyValues, indexInClass);
  10294. }
  10295. return clone(propertyValues[indexInClass]);
  10296. }
  10297. return null;
  10298. });
  10299. }
  10300. _setHierarchyProperty(batchTable, batchId, name, value) {
  10301. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10302. const classId = hierarchy.classIds[instanceIndex];
  10303. const instanceClass = hierarchy.classes[classId];
  10304. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10305. const propertyValues = instanceClass.instances[name];
  10306. if (defined(propertyValues)) {
  10307. assert$7(instanceIndex === batchId, "Inherited property \"".concat(name, "\" is read-only."));
  10308. if (defined(propertyValues.typedArray)) {
  10309. this._setBinaryProperty(propertyValues, indexInClass, value);
  10310. } else {
  10311. propertyValues[indexInClass] = clone(value);
  10312. }
  10313. return true;
  10314. }
  10315. return false;
  10316. });
  10317. return defined(result);
  10318. }
  10319. }
  10320. const SIZEOF_UINT32$1 = 4;
  10321. function parse3DTileHeaderSync(tile, arrayBuffer, byteOffset = 0) {
  10322. const view = new DataView(arrayBuffer);
  10323. tile.magic = view.getUint32(byteOffset, true);
  10324. byteOffset += SIZEOF_UINT32$1;
  10325. tile.version = view.getUint32(byteOffset, true);
  10326. byteOffset += SIZEOF_UINT32$1;
  10327. tile.byteLength = view.getUint32(byteOffset, true);
  10328. byteOffset += SIZEOF_UINT32$1;
  10329. if (tile.version !== 1) {
  10330. throw new Error("3D Tile Version ".concat(tile.version, " not supported"));
  10331. }
  10332. return byteOffset;
  10333. }
  10334. const SIZEOF_UINT32 = 4;
  10335. const DEPRECATION_WARNING = 'b3dm tile in legacy format.';
  10336. function parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset) {
  10337. const view = new DataView(arrayBuffer);
  10338. let batchLength;
  10339. tile.header = tile.header || {};
  10340. let featureTableJsonByteLength = view.getUint32(byteOffset, true);
  10341. byteOffset += SIZEOF_UINT32;
  10342. let featureTableBinaryByteLength = view.getUint32(byteOffset, true);
  10343. byteOffset += SIZEOF_UINT32;
  10344. let batchTableJsonByteLength = view.getUint32(byteOffset, true);
  10345. byteOffset += SIZEOF_UINT32;
  10346. let batchTableBinaryByteLength = view.getUint32(byteOffset, true);
  10347. byteOffset += SIZEOF_UINT32;
  10348. if (batchTableJsonByteLength >= 570425344) {
  10349. byteOffset -= SIZEOF_UINT32 * 2;
  10350. batchLength = featureTableJsonByteLength;
  10351. batchTableJsonByteLength = featureTableBinaryByteLength;
  10352. batchTableBinaryByteLength = 0;
  10353. featureTableJsonByteLength = 0;
  10354. featureTableBinaryByteLength = 0;
  10355. console.warn(DEPRECATION_WARNING);
  10356. } else if (batchTableBinaryByteLength >= 570425344) {
  10357. byteOffset -= SIZEOF_UINT32;
  10358. batchLength = batchTableJsonByteLength;
  10359. batchTableJsonByteLength = featureTableJsonByteLength;
  10360. batchTableBinaryByteLength = featureTableBinaryByteLength;
  10361. featureTableJsonByteLength = 0;
  10362. featureTableBinaryByteLength = 0;
  10363. console.warn(DEPRECATION_WARNING);
  10364. }
  10365. tile.header.featureTableJsonByteLength = featureTableJsonByteLength;
  10366. tile.header.featureTableBinaryByteLength = featureTableBinaryByteLength;
  10367. tile.header.batchTableJsonByteLength = batchTableJsonByteLength;
  10368. tile.header.batchTableBinaryByteLength = batchTableBinaryByteLength;
  10369. tile.header.batchLength = batchLength;
  10370. return byteOffset;
  10371. }
  10372. function parse3DTileTablesSync(tile, arrayBuffer, byteOffset, options) {
  10373. byteOffset = parse3DTileFeatureTable(tile, arrayBuffer, byteOffset);
  10374. byteOffset = parse3DTileBatchTable(tile, arrayBuffer, byteOffset);
  10375. return byteOffset;
  10376. }
  10377. function parse3DTileFeatureTable(tile, arrayBuffer, byteOffset, options) {
  10378. const {
  10379. featureTableJsonByteLength,
  10380. featureTableBinaryByteLength,
  10381. batchLength
  10382. } = tile.header;
  10383. tile.featureTableJson = {
  10384. BATCH_LENGTH: batchLength || 0
  10385. };
  10386. if (featureTableJsonByteLength > 0) {
  10387. const featureTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, featureTableJsonByteLength);
  10388. tile.featureTableJson = JSON.parse(featureTableString);
  10389. }
  10390. byteOffset += featureTableJsonByteLength;
  10391. tile.featureTableBinary = new Uint8Array(arrayBuffer, byteOffset, featureTableBinaryByteLength);
  10392. byteOffset += featureTableBinaryByteLength;
  10393. return byteOffset;
  10394. }
  10395. function parse3DTileBatchTable(tile, arrayBuffer, byteOffset, options) {
  10396. const {
  10397. batchTableJsonByteLength,
  10398. batchTableBinaryByteLength
  10399. } = tile.header;
  10400. if (batchTableJsonByteLength > 0) {
  10401. const batchTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, batchTableJsonByteLength);
  10402. tile.batchTableJson = JSON.parse(batchTableString);
  10403. byteOffset += batchTableJsonByteLength;
  10404. if (batchTableBinaryByteLength > 0) {
  10405. tile.batchTableBinary = new Uint8Array(arrayBuffer, byteOffset, batchTableBinaryByteLength);
  10406. tile.batchTableBinary = new Uint8Array(tile.batchTableBinary);
  10407. byteOffset += batchTableBinaryByteLength;
  10408. }
  10409. }
  10410. return byteOffset;
  10411. }
  10412. function normalize3DTileColorAttribute(tile, colors, batchTable) {
  10413. if (!colors && (!tile || !tile.batchIds || !batchTable)) {
  10414. return null;
  10415. }
  10416. const {
  10417. batchIds,
  10418. isRGB565,
  10419. pointCount
  10420. } = tile;
  10421. if (batchIds && batchTable) {
  10422. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10423. for (let i = 0; i < pointCount; i++) {
  10424. const batchId = batchIds[i];
  10425. const dimensions = batchTable.getProperty(batchId, 'dimensions');
  10426. const color = dimensions.map(d => d * 255);
  10427. colorArray[i * 3] = color[0];
  10428. colorArray[i * 3 + 1] = color[1];
  10429. colorArray[i * 3 + 2] = color[2];
  10430. }
  10431. return {
  10432. type: GL$1.UNSIGNED_BYTE,
  10433. value: colorArray,
  10434. size: 3,
  10435. normalized: true
  10436. };
  10437. }
  10438. if (isRGB565) {
  10439. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10440. for (let i = 0; i < pointCount; i++) {
  10441. const color = decodeRGB565(colors[i]);
  10442. colorArray[i * 3] = color[0];
  10443. colorArray[i * 3 + 1] = color[1];
  10444. colorArray[i * 3 + 2] = color[2];
  10445. }
  10446. return {
  10447. type: GL$1.UNSIGNED_BYTE,
  10448. value: colorArray,
  10449. size: 3,
  10450. normalized: true
  10451. };
  10452. }
  10453. if (colors && colors.length === pointCount * 3) {
  10454. return {
  10455. type: GL$1.UNSIGNED_BYTE,
  10456. value: colors,
  10457. size: 3,
  10458. normalized: true
  10459. };
  10460. }
  10461. return {
  10462. type: GL$1.UNSIGNED_BYTE,
  10463. value: colors,
  10464. size: 4,
  10465. normalized: true
  10466. };
  10467. }
  10468. const scratchNormal = new Vector3();
  10469. function normalize3DTileNormalAttribute(tile, normals) {
  10470. if (!normals) {
  10471. return null;
  10472. }
  10473. if (tile.isOctEncoded16P) {
  10474. const decodedArray = new Float32Array(tile.pointsLength * 3);
  10475. for (let i = 0; i < tile.pointsLength; i++) {
  10476. octDecode(normals[i * 2], normals[i * 2 + 1], scratchNormal);
  10477. scratchNormal.toArray(decodedArray, i * 3);
  10478. }
  10479. return {
  10480. type: GL$1.FLOAT,
  10481. size: 2,
  10482. value: decodedArray
  10483. };
  10484. }
  10485. return {
  10486. type: GL$1.FLOAT,
  10487. size: 2,
  10488. value: normals
  10489. };
  10490. }
  10491. function normalize3DTilePositionAttribute(tile, positions, options) {
  10492. if (!tile.isQuantized) {
  10493. return positions;
  10494. }
  10495. if (options['3d-tiles'] && options['3d-tiles'].decodeQuantizedPositions) {
  10496. tile.isQuantized = false;
  10497. return decodeQuantizedPositions(tile, positions);
  10498. }
  10499. return {
  10500. type: GL$1.UNSIGNED_SHORT,
  10501. value: positions,
  10502. size: 3,
  10503. normalized: true
  10504. };
  10505. }
  10506. function decodeQuantizedPositions(tile, positions) {
  10507. const scratchPosition = new Vector3();
  10508. const decodedArray = new Float32Array(tile.pointCount * 3);
  10509. for (let i = 0; i < tile.pointCount; i++) {
  10510. 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);
  10511. }
  10512. return decodedArray;
  10513. }
  10514. async function parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context) {
  10515. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  10516. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  10517. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  10518. initializeTile(tile);
  10519. const {
  10520. featureTable,
  10521. batchTable
  10522. } = parsePointCloudTables(tile);
  10523. await parseDraco(tile, featureTable, batchTable, options, context);
  10524. parsePositions(tile, featureTable, options);
  10525. parseColors(tile, featureTable, batchTable);
  10526. parseNormals(tile, featureTable);
  10527. return byteOffset;
  10528. }
  10529. function initializeTile(tile) {
  10530. tile.attributes = {
  10531. positions: null,
  10532. colors: null,
  10533. normals: null,
  10534. batchIds: null
  10535. };
  10536. tile.isQuantized = false;
  10537. tile.isTranslucent = false;
  10538. tile.isRGB565 = false;
  10539. tile.isOctEncoded16P = false;
  10540. }
  10541. function parsePointCloudTables(tile) {
  10542. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  10543. const pointsLength = featureTable.getGlobalProperty('POINTS_LENGTH');
  10544. if (!Number.isFinite(pointsLength)) {
  10545. throw new Error('POINTS_LENGTH must be defined');
  10546. }
  10547. featureTable.featuresLength = pointsLength;
  10548. tile.featuresLength = pointsLength;
  10549. tile.pointsLength = pointsLength;
  10550. tile.pointCount = pointsLength;
  10551. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  10552. const batchTable = parseBatchIds(tile, featureTable);
  10553. return {
  10554. featureTable,
  10555. batchTable
  10556. };
  10557. }
  10558. function parsePositions(tile, featureTable, options) {
  10559. if (!tile.attributes.positions) {
  10560. if (featureTable.hasProperty('POSITION')) {
  10561. tile.attributes.positions = featureTable.getPropertyArray('POSITION', GL$1.FLOAT, 3);
  10562. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  10563. const positions = featureTable.getPropertyArray('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3);
  10564. tile.isQuantized = true;
  10565. tile.quantizedRange = (1 << 16) - 1;
  10566. tile.quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3);
  10567. if (!tile.quantizedVolumeScale) {
  10568. throw new Error('QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  10569. }
  10570. tile.quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3);
  10571. if (!tile.quantizedVolumeOffset) {
  10572. throw new Error('QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  10573. }
  10574. tile.attributes.positions = normalize3DTilePositionAttribute(tile, positions, options);
  10575. }
  10576. }
  10577. if (!tile.attributes.positions) {
  10578. throw new Error('Either POSITION or POSITION_QUANTIZED must be defined.');
  10579. }
  10580. }
  10581. function parseColors(tile, featureTable, batchTable) {
  10582. if (!tile.attributes.colors) {
  10583. let colors = null;
  10584. if (featureTable.hasProperty('RGBA')) {
  10585. colors = featureTable.getPropertyArray('RGBA', GL$1.UNSIGNED_BYTE, 4);
  10586. tile.isTranslucent = true;
  10587. } else if (featureTable.hasProperty('RGB')) {
  10588. colors = featureTable.getPropertyArray('RGB', GL$1.UNSIGNED_BYTE, 3);
  10589. } else if (featureTable.hasProperty('RGB565')) {
  10590. colors = featureTable.getPropertyArray('RGB565', GL$1.UNSIGNED_SHORT, 1);
  10591. tile.isRGB565 = true;
  10592. }
  10593. tile.attributes.colors = normalize3DTileColorAttribute(tile, colors, batchTable);
  10594. }
  10595. if (featureTable.hasProperty('CONSTANT_RGBA')) {
  10596. tile.constantRGBA = featureTable.getGlobalProperty('CONSTANT_RGBA', GL$1.UNSIGNED_BYTE, 4);
  10597. }
  10598. }
  10599. function parseNormals(tile, featureTable) {
  10600. if (!tile.attributes.normals) {
  10601. let normals = null;
  10602. if (featureTable.hasProperty('NORMAL')) {
  10603. normals = featureTable.getPropertyArray('NORMAL', GL$1.FLOAT, 3);
  10604. } else if (featureTable.hasProperty('NORMAL_OCT16P')) {
  10605. normals = featureTable.getPropertyArray('NORMAL_OCT16P', GL$1.UNSIGNED_BYTE, 2);
  10606. tile.isOctEncoded16P = true;
  10607. }
  10608. tile.attributes.normals = normalize3DTileNormalAttribute(tile, normals);
  10609. }
  10610. }
  10611. function parseBatchIds(tile, featureTable) {
  10612. let batchTable = null;
  10613. if (!tile.batchIds && featureTable.hasProperty('BATCH_ID')) {
  10614. tile.batchIds = featureTable.getPropertyArray('BATCH_ID', GL$1.UNSIGNED_SHORT, 1);
  10615. if (tile.batchIds) {
  10616. const batchFeatureLength = featureTable.getGlobalProperty('BATCH_LENGTH');
  10617. if (!batchFeatureLength) {
  10618. throw new Error('Global property: BATCH_LENGTH must be defined when BATCH_ID is defined.');
  10619. }
  10620. const {
  10621. batchTableJson,
  10622. batchTableBinary
  10623. } = tile;
  10624. batchTable = new Tile3DBatchTableParser(batchTableJson, batchTableBinary, batchFeatureLength);
  10625. }
  10626. }
  10627. return batchTable;
  10628. }
  10629. async function parseDraco(tile, featureTable, batchTable, options, context) {
  10630. let dracoBuffer;
  10631. let dracoFeatureTableProperties;
  10632. let dracoBatchTableProperties;
  10633. const batchTableDraco = tile.batchTableJson && tile.batchTableJson.extensions && tile.batchTableJson.extensions['3DTILES_draco_point_compression'];
  10634. if (batchTableDraco) {
  10635. dracoBatchTableProperties = batchTableDraco.properties;
  10636. }
  10637. const featureTableDraco = featureTable.getExtension('3DTILES_draco_point_compression');
  10638. if (featureTableDraco) {
  10639. dracoFeatureTableProperties = featureTableDraco.properties;
  10640. const dracoByteOffset = featureTableDraco.byteOffset;
  10641. const dracoByteLength = featureTableDraco.byteLength;
  10642. if (!dracoFeatureTableProperties || !Number.isFinite(dracoByteOffset) || !dracoByteLength) {
  10643. throw new Error('Draco properties, byteOffset, and byteLength must be defined');
  10644. }
  10645. dracoBuffer = tile.featureTableBinary.slice(dracoByteOffset, dracoByteOffset + dracoByteLength);
  10646. tile.hasPositions = Number.isFinite(dracoFeatureTableProperties.POSITION);
  10647. tile.hasColors = Number.isFinite(dracoFeatureTableProperties.RGB) || Number.isFinite(dracoFeatureTableProperties.RGBA);
  10648. tile.hasNormals = Number.isFinite(dracoFeatureTableProperties.NORMAL);
  10649. tile.hasBatchIds = Number.isFinite(dracoFeatureTableProperties.BATCH_ID);
  10650. tile.isTranslucent = Number.isFinite(dracoFeatureTableProperties.RGBA);
  10651. }
  10652. if (!dracoBuffer) {
  10653. return true;
  10654. }
  10655. const dracoData = {
  10656. buffer: dracoBuffer,
  10657. properties: { ...dracoFeatureTableProperties,
  10658. ...dracoBatchTableProperties
  10659. },
  10660. featureTableProperties: dracoFeatureTableProperties,
  10661. batchTableProperties: dracoBatchTableProperties,
  10662. dequantizeInShader: false
  10663. };
  10664. return await loadDraco(tile, dracoData, options, context);
  10665. }
  10666. async function loadDraco(tile, dracoData, options, context) {
  10667. const {
  10668. parse
  10669. } = context;
  10670. const dracoOptions = { ...options,
  10671. draco: { ...options.draco,
  10672. extraAttributes: dracoData.batchTableProperties || {}
  10673. }
  10674. };
  10675. delete dracoOptions['3d-tiles'];
  10676. const data = await parse(dracoData.buffer, DracoLoader, dracoOptions);
  10677. const decodedPositions = data.attributes.POSITION && data.attributes.POSITION.value;
  10678. const decodedColors = data.attributes.COLOR_0 && data.attributes.COLOR_0.value;
  10679. const decodedNormals = data.attributes.NORMAL && data.attributes.NORMAL.value;
  10680. const decodedBatchIds = data.attributes.BATCH_ID && data.attributes.BATCH_ID.value;
  10681. const isQuantizedDraco = decodedPositions && data.attributes.POSITION.value.quantization;
  10682. const isOctEncodedDraco = decodedNormals && data.attributes.NORMAL.value.quantization;
  10683. if (isQuantizedDraco) {
  10684. const quantization = data.POSITION.data.quantization;
  10685. const range = quantization.range;
  10686. tile.quantizedVolumeScale = new Vector3(range, range, range);
  10687. tile.quantizedVolumeOffset = new Vector3(quantization.minValues);
  10688. tile.quantizedRange = (1 << quantization.quantizationBits) - 1.0;
  10689. tile.isQuantizedDraco = true;
  10690. }
  10691. if (isOctEncodedDraco) {
  10692. tile.octEncodedRange = (1 << data.NORMAL.data.quantization.quantizationBits) - 1.0;
  10693. tile.isOctEncodedDraco = true;
  10694. }
  10695. const batchTableAttributes = {};
  10696. if (dracoData.batchTableProperties) {
  10697. for (const attributeName of Object.keys(dracoData.batchTableProperties)) {
  10698. if (data.attributes[attributeName] && data.attributes[attributeName].value) {
  10699. batchTableAttributes[attributeName.toLowerCase()] = data.attributes[attributeName].value;
  10700. }
  10701. }
  10702. }
  10703. tile.attributes = {
  10704. positions: decodedPositions,
  10705. colors: normalize3DTileColorAttribute(tile, decodedColors, undefined),
  10706. normals: decodedNormals,
  10707. batchIds: decodedBatchIds,
  10708. ...batchTableAttributes
  10709. };
  10710. }
  10711. const VERSION$3 = "3.1.4" ;
  10712. const VERSION$2 = "3.1.4" ;
  10713. const VERSION$1 = "3.1.4" ;
  10714. const BASIS_CDN_ENCODER_WASM = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.wasm");
  10715. const BASIS_CDN_ENCODER_JS = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.js");
  10716. let loadBasisTranscoderPromise;
  10717. async function loadBasisTrascoderModule(options) {
  10718. const modules = options.modules || {};
  10719. if (modules.basis) {
  10720. return modules.basis;
  10721. }
  10722. loadBasisTranscoderPromise = loadBasisTranscoderPromise || loadBasisTrascoder(options);
  10723. return await loadBasisTranscoderPromise;
  10724. }
  10725. async function loadBasisTrascoder(options) {
  10726. let BASIS = null;
  10727. let wasmBinary = null;
  10728. [BASIS, wasmBinary] = await Promise.all([await loadLibrary('basis_transcoder.js', 'textures', options), await loadLibrary('basis_transcoder.wasm', 'textures', options)]);
  10729. BASIS = BASIS || globalThis.BASIS;
  10730. return await initializeBasisTrascoderModule(BASIS, wasmBinary);
  10731. }
  10732. function initializeBasisTrascoderModule(BasisModule, wasmBinary) {
  10733. const options = {};
  10734. if (wasmBinary) {
  10735. options.wasmBinary = wasmBinary;
  10736. }
  10737. return new Promise(resolve => {
  10738. BasisModule(options).then(module => {
  10739. const {
  10740. BasisFile,
  10741. initializeBasis
  10742. } = module;
  10743. initializeBasis();
  10744. resolve({
  10745. BasisFile
  10746. });
  10747. });
  10748. });
  10749. }
  10750. let loadBasisEncoderPromise;
  10751. async function loadBasisEncoderModule(options) {
  10752. const modules = options.modules || {};
  10753. if (modules.basisEncoder) {
  10754. return modules.basisEncoder;
  10755. }
  10756. loadBasisEncoderPromise = loadBasisEncoderPromise || loadBasisEncoder(options);
  10757. return await loadBasisEncoderPromise;
  10758. }
  10759. async function loadBasisEncoder(options) {
  10760. let BASIS_ENCODER = null;
  10761. let wasmBinary = null;
  10762. [BASIS_ENCODER, wasmBinary] = await Promise.all([await loadLibrary(BASIS_CDN_ENCODER_JS, 'textures', options), await loadLibrary(BASIS_CDN_ENCODER_WASM, 'textures', options)]);
  10763. BASIS_ENCODER = BASIS_ENCODER || globalThis.BASIS;
  10764. return await initializeBasisEncoderModule(BASIS_ENCODER, wasmBinary);
  10765. }
  10766. function initializeBasisEncoderModule(BasisEncoderModule, wasmBinary) {
  10767. const options = {};
  10768. if (wasmBinary) {
  10769. options.wasmBinary = wasmBinary;
  10770. }
  10771. return new Promise(resolve => {
  10772. BasisEncoderModule(options).then(module => {
  10773. const {
  10774. BasisFile,
  10775. KTX2File,
  10776. initializeBasis,
  10777. BasisEncoder
  10778. } = module;
  10779. initializeBasis();
  10780. resolve({
  10781. BasisFile,
  10782. KTX2File,
  10783. BasisEncoder
  10784. });
  10785. });
  10786. });
  10787. }
  10788. const GL_EXTENSIONS_CONSTANTS = {
  10789. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83f0,
  10790. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83f1,
  10791. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83f2,
  10792. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83f3,
  10793. COMPRESSED_R11_EAC: 0x9270,
  10794. COMPRESSED_SIGNED_R11_EAC: 0x9271,
  10795. COMPRESSED_RG11_EAC: 0x9272,
  10796. COMPRESSED_SIGNED_RG11_EAC: 0x9273,
  10797. COMPRESSED_RGB8_ETC2: 0x9274,
  10798. COMPRESSED_RGBA8_ETC2_EAC: 0x9275,
  10799. COMPRESSED_SRGB8_ETC2: 0x9276,
  10800. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: 0x9277,
  10801. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9278,
  10802. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9279,
  10803. COMPRESSED_RGB_PVRTC_4BPPV1_IMG: 0x8c00,
  10804. COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: 0x8c02,
  10805. COMPRESSED_RGB_PVRTC_2BPPV1_IMG: 0x8c01,
  10806. COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: 0x8c03,
  10807. COMPRESSED_RGB_ETC1_WEBGL: 0x8d64,
  10808. COMPRESSED_RGB_ATC_WEBGL: 0x8c92,
  10809. COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL: 0x8c93,
  10810. COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL: 0x87ee,
  10811. COMPRESSED_RGBA_ASTC_4X4_KHR: 0x93b0,
  10812. COMPRESSED_RGBA_ASTC_5X4_KHR: 0x93b1,
  10813. COMPRESSED_RGBA_ASTC_5X5_KHR: 0x93b2,
  10814. COMPRESSED_RGBA_ASTC_6X5_KHR: 0x93b3,
  10815. COMPRESSED_RGBA_ASTC_6X6_KHR: 0x93b4,
  10816. COMPRESSED_RGBA_ASTC_8X5_KHR: 0x93b5,
  10817. COMPRESSED_RGBA_ASTC_8X6_KHR: 0x93b6,
  10818. COMPRESSED_RGBA_ASTC_8X8_KHR: 0x93b7,
  10819. COMPRESSED_RGBA_ASTC_10X5_KHR: 0x93b8,
  10820. COMPRESSED_RGBA_ASTC_10X6_KHR: 0x93b9,
  10821. COMPRESSED_RGBA_ASTC_10X8_KHR: 0x93ba,
  10822. COMPRESSED_RGBA_ASTC_10X10_KHR: 0x93bb,
  10823. COMPRESSED_RGBA_ASTC_12X10_KHR: 0x93bc,
  10824. COMPRESSED_RGBA_ASTC_12X12_KHR: 0x93bd,
  10825. COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR: 0x93d0,
  10826. COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR: 0x93d1,
  10827. COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR: 0x93d2,
  10828. COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR: 0x93d3,
  10829. COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR: 0x93d4,
  10830. COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR: 0x93d5,
  10831. COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR: 0x93d6,
  10832. COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR: 0x93d7,
  10833. COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR: 0x93d8,
  10834. COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR: 0x93d9,
  10835. COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR: 0x93da,
  10836. COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR: 0x93db,
  10837. COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR: 0x93dc,
  10838. COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR: 0x93dd,
  10839. COMPRESSED_RED_RGTC1_EXT: 0x8dbb,
  10840. COMPRESSED_SIGNED_RED_RGTC1_EXT: 0x8dbc,
  10841. COMPRESSED_RED_GREEN_RGTC2_EXT: 0x8dbd,
  10842. COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT: 0x8dbe,
  10843. COMPRESSED_SRGB_S3TC_DXT1_EXT: 0x8c4c,
  10844. COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: 0x8c4d,
  10845. COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: 0x8c4e,
  10846. COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: 0x8c4f
  10847. };
  10848. const BROWSER_PREFIXES = ['', 'WEBKIT_', 'MOZ_'];
  10849. const WEBGL_EXTENSIONS = {
  10850. WEBGL_compressed_texture_s3tc: 'dxt',
  10851. WEBGL_compressed_texture_s3tc_srgb: 'dxt-srgb',
  10852. WEBGL_compressed_texture_etc1: 'etc1',
  10853. WEBGL_compressed_texture_etc: 'etc2',
  10854. WEBGL_compressed_texture_pvrtc: 'pvrtc',
  10855. WEBGL_compressed_texture_atc: 'atc',
  10856. WEBGL_compressed_texture_astc: 'astc',
  10857. EXT_texture_compression_rgtc: 'rgtc'
  10858. };
  10859. let formats = null;
  10860. function getSupportedGPUTextureFormats(gl) {
  10861. if (!formats) {
  10862. gl = gl || getWebGLContext() || undefined;
  10863. formats = new Set();
  10864. for (const prefix of BROWSER_PREFIXES) {
  10865. for (const extension in WEBGL_EXTENSIONS) {
  10866. if (gl && gl.getExtension("".concat(prefix).concat(extension))) {
  10867. const gpuTextureFormat = WEBGL_EXTENSIONS[extension];
  10868. formats.add(gpuTextureFormat);
  10869. }
  10870. }
  10871. }
  10872. }
  10873. return formats;
  10874. }
  10875. function getWebGLContext() {
  10876. try {
  10877. const canvas = document.createElement('canvas');
  10878. return canvas.getContext('webgl');
  10879. } catch (error) {
  10880. return null;
  10881. }
  10882. }
  10883. 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={}));
  10884. const KTX2_ID = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];
  10885. function isKTX(data) {
  10886. const id = new Uint8Array(data);
  10887. 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];
  10888. return !notKTX;
  10889. }
  10890. const OutputFormat = {
  10891. etc1: {
  10892. basisFormat: 0,
  10893. compressed: true,
  10894. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_ETC1_WEBGL
  10895. },
  10896. etc2: {
  10897. basisFormat: 1,
  10898. compressed: true
  10899. },
  10900. bc1: {
  10901. basisFormat: 2,
  10902. compressed: true,
  10903. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_S3TC_DXT1_EXT
  10904. },
  10905. bc3: {
  10906. basisFormat: 3,
  10907. compressed: true,
  10908. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_S3TC_DXT5_EXT
  10909. },
  10910. bc4: {
  10911. basisFormat: 4,
  10912. compressed: true
  10913. },
  10914. bc5: {
  10915. basisFormat: 5,
  10916. compressed: true
  10917. },
  10918. 'bc7-m6-opaque-only': {
  10919. basisFormat: 6,
  10920. compressed: true
  10921. },
  10922. 'bc7-m5': {
  10923. basisFormat: 7,
  10924. compressed: true
  10925. },
  10926. 'pvrtc1-4-rgb': {
  10927. basisFormat: 8,
  10928. compressed: true,
  10929. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG
  10930. },
  10931. 'pvrtc1-4-rgba': {
  10932. basisFormat: 9,
  10933. compressed: true,
  10934. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG
  10935. },
  10936. 'astc-4x4': {
  10937. basisFormat: 10,
  10938. compressed: true,
  10939. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_4X4_KHR
  10940. },
  10941. 'atc-rgb': {
  10942. basisFormat: 11,
  10943. compressed: true
  10944. },
  10945. 'atc-rgba-interpolated-alpha': {
  10946. basisFormat: 12,
  10947. compressed: true
  10948. },
  10949. rgba32: {
  10950. basisFormat: 13,
  10951. compressed: false
  10952. },
  10953. rgb565: {
  10954. basisFormat: 14,
  10955. compressed: false
  10956. },
  10957. bgr565: {
  10958. basisFormat: 15,
  10959. compressed: false
  10960. },
  10961. rgba4444: {
  10962. basisFormat: 16,
  10963. compressed: false
  10964. }
  10965. };
  10966. async function parseBasis(data, options) {
  10967. if (options.basis.containerFormat === 'auto') {
  10968. if (isKTX(data)) {
  10969. const fileConstructors = await loadBasisEncoderModule(options);
  10970. return parseKTX2File(fileConstructors.KTX2File, data, options);
  10971. }
  10972. const {
  10973. BasisFile
  10974. } = await loadBasisTrascoderModule(options);
  10975. return parseBasisFile(BasisFile, data, options);
  10976. }
  10977. switch (options.basis.module) {
  10978. case 'encoder':
  10979. const fileConstructors = await loadBasisEncoderModule(options);
  10980. switch (options.basis.containerFormat) {
  10981. case 'ktx2':
  10982. return parseKTX2File(fileConstructors.KTX2File, data, options);
  10983. case 'basis':
  10984. default:
  10985. return parseBasisFile(fileConstructors.BasisFile, data, options);
  10986. }
  10987. case 'transcoder':
  10988. default:
  10989. const {
  10990. BasisFile
  10991. } = await loadBasisTrascoderModule(options);
  10992. return parseBasisFile(BasisFile, data, options);
  10993. }
  10994. }
  10995. function parseBasisFile(BasisFile, data, options) {
  10996. const basisFile = new BasisFile(new Uint8Array(data));
  10997. try {
  10998. if (!basisFile.startTranscoding()) {
  10999. return null;
  11000. }
  11001. const imageCount = basisFile.getNumImages();
  11002. const images = [];
  11003. for (let imageIndex = 0; imageIndex < imageCount; imageIndex++) {
  11004. const levelsCount = basisFile.getNumLevels(imageIndex);
  11005. const levels = [];
  11006. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  11007. levels.push(transcodeImage(basisFile, imageIndex, levelIndex, options));
  11008. }
  11009. images.push(levels);
  11010. }
  11011. return images;
  11012. } finally {
  11013. basisFile.close();
  11014. basisFile.delete();
  11015. }
  11016. }
  11017. function transcodeImage(basisFile, imageIndex, levelIndex, options) {
  11018. const width = basisFile.getImageWidth(imageIndex, levelIndex);
  11019. const height = basisFile.getImageHeight(imageIndex, levelIndex);
  11020. const hasAlpha = basisFile.getHasAlpha();
  11021. const {
  11022. compressed,
  11023. format,
  11024. basisFormat
  11025. } = getBasisOptions(options, hasAlpha);
  11026. const decodedSize = basisFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, basisFormat);
  11027. const decodedData = new Uint8Array(decodedSize);
  11028. if (!basisFile.transcodeImage(decodedData, imageIndex, levelIndex, basisFormat, 0, 0)) {
  11029. return null;
  11030. }
  11031. return {
  11032. width,
  11033. height,
  11034. data: decodedData,
  11035. compressed,
  11036. hasAlpha,
  11037. format
  11038. };
  11039. }
  11040. function parseKTX2File(KTX2File, data, options) {
  11041. const ktx2File = new KTX2File(new Uint8Array(data));
  11042. try {
  11043. if (!ktx2File.startTranscoding()) {
  11044. return null;
  11045. }
  11046. const levelsCount = ktx2File.getLevels();
  11047. const levels = [];
  11048. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  11049. levels.push(transcodeKTX2Image(ktx2File, levelIndex, options));
  11050. break;
  11051. }
  11052. return levels;
  11053. } finally {
  11054. ktx2File.close();
  11055. ktx2File.delete();
  11056. }
  11057. }
  11058. function transcodeKTX2Image(ktx2File, levelIndex, options) {
  11059. const {
  11060. alphaFlag,
  11061. height,
  11062. width
  11063. } = ktx2File.getImageLevelInfo(levelIndex, 0, 0);
  11064. const {
  11065. compressed,
  11066. format,
  11067. basisFormat
  11068. } = getBasisOptions(options, alphaFlag);
  11069. const decodedSize = ktx2File.getImageTranscodedSizeInBytes(levelIndex, 0, 0, basisFormat);
  11070. const decodedData = new Uint8Array(decodedSize);
  11071. if (!ktx2File.transcodeImage(decodedData, levelIndex, 0, 0, basisFormat, 0, -1, -1)) {
  11072. return null;
  11073. }
  11074. return {
  11075. width,
  11076. height,
  11077. data: decodedData,
  11078. compressed,
  11079. alphaFlag,
  11080. format
  11081. };
  11082. }
  11083. function getBasisOptions(options, hasAlpha) {
  11084. let format = options && options.basis && options.basis.format;
  11085. if (format === 'auto') {
  11086. format = selectSupportedBasisFormat();
  11087. }
  11088. if (typeof format === 'object') {
  11089. format = hasAlpha ? format.alpha : format.noAlpha;
  11090. }
  11091. format = format.toLowerCase();
  11092. return OutputFormat[format];
  11093. }
  11094. function selectSupportedBasisFormat() {
  11095. const supportedFormats = getSupportedGPUTextureFormats();
  11096. if (supportedFormats.has('astc')) {
  11097. return 'astc-4x4';
  11098. } else if (supportedFormats.has('dxt')) {
  11099. return {
  11100. alpha: 'bc3',
  11101. noAlpha: 'bc1'
  11102. };
  11103. } else if (supportedFormats.has('pvrtc')) {
  11104. return {
  11105. alpha: 'pvrtc1-4-rgba',
  11106. noAlpha: 'pvrtc1-4-rgb'
  11107. };
  11108. } else if (supportedFormats.has('etc1')) {
  11109. return 'etc1';
  11110. } else if (supportedFormats.has('etc2')) {
  11111. return 'etc2';
  11112. }
  11113. return 'rgb565';
  11114. }
  11115. const BasisWorkerLoader = {
  11116. name: 'Basis',
  11117. id: 'basis',
  11118. module: 'textures',
  11119. version: VERSION$2,
  11120. worker: true,
  11121. extensions: ['basis', 'ktx2'],
  11122. mimeTypes: ['application/octet-stream', 'image/ktx2'],
  11123. tests: ['sB'],
  11124. binary: true,
  11125. options: {
  11126. basis: {
  11127. format: 'auto',
  11128. libraryPath: 'libs/',
  11129. containerFormat: 'auto',
  11130. module: 'transcoder'
  11131. }
  11132. }
  11133. };
  11134. const BasisLoader = { ...BasisWorkerLoader,
  11135. parse: parseBasis
  11136. };
  11137. const VERSION = "3.1.4" ;
  11138. const {
  11139. _parseImageNode
  11140. } = globalThis;
  11141. const IMAGE_SUPPORTED = typeof Image !== 'undefined';
  11142. const IMAGE_BITMAP_SUPPORTED = typeof ImageBitmap !== 'undefined';
  11143. const NODE_IMAGE_SUPPORTED = Boolean(_parseImageNode);
  11144. const DATA_SUPPORTED = isBrowser$2 ? true : NODE_IMAGE_SUPPORTED;
  11145. function isImageTypeSupported(type) {
  11146. switch (type) {
  11147. case 'auto':
  11148. return IMAGE_BITMAP_SUPPORTED || IMAGE_SUPPORTED || DATA_SUPPORTED;
  11149. case 'imagebitmap':
  11150. return IMAGE_BITMAP_SUPPORTED;
  11151. case 'image':
  11152. return IMAGE_SUPPORTED;
  11153. case 'data':
  11154. return DATA_SUPPORTED;
  11155. default:
  11156. throw new Error("@loaders.gl/images: image ".concat(type, " not supported in this environment"));
  11157. }
  11158. }
  11159. function getDefaultImageType() {
  11160. if (IMAGE_BITMAP_SUPPORTED) {
  11161. return 'imagebitmap';
  11162. }
  11163. if (IMAGE_SUPPORTED) {
  11164. return 'image';
  11165. }
  11166. if (DATA_SUPPORTED) {
  11167. return 'data';
  11168. }
  11169. throw new Error('Install \'@loaders.gl/polyfills\' to parse images under Node.js');
  11170. }
  11171. function getImageType(image) {
  11172. const format = getImageTypeOrNull(image);
  11173. if (!format) {
  11174. throw new Error('Not an image');
  11175. }
  11176. return format;
  11177. }
  11178. function getImageData(image) {
  11179. switch (getImageType(image)) {
  11180. case 'data':
  11181. return image;
  11182. case 'image':
  11183. case 'imagebitmap':
  11184. const canvas = document.createElement('canvas');
  11185. const context = canvas.getContext('2d');
  11186. if (!context) {
  11187. throw new Error('getImageData');
  11188. }
  11189. canvas.width = image.width;
  11190. canvas.height = image.height;
  11191. context.drawImage(image, 0, 0);
  11192. return context.getImageData(0, 0, image.width, image.height);
  11193. default:
  11194. throw new Error('getImageData');
  11195. }
  11196. }
  11197. function getImageTypeOrNull(image) {
  11198. if (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  11199. return 'imagebitmap';
  11200. }
  11201. if (typeof Image !== 'undefined' && image instanceof Image) {
  11202. return 'image';
  11203. }
  11204. if (image && typeof image === 'object' && image.data && image.width && image.height) {
  11205. return 'data';
  11206. }
  11207. return null;
  11208. }
  11209. const SVG_DATA_URL_PATTERN = /^data:image\/svg\+xml/;
  11210. const SVG_URL_PATTERN = /\.svg((\?|#).*)?$/;
  11211. function isSVG(url) {
  11212. return url && (SVG_DATA_URL_PATTERN.test(url) || SVG_URL_PATTERN.test(url));
  11213. }
  11214. function getBlobOrSVGDataUrl(arrayBuffer, url) {
  11215. if (isSVG(url)) {
  11216. const textDecoder = new TextDecoder();
  11217. let xmlText = textDecoder.decode(arrayBuffer);
  11218. try {
  11219. if (typeof unescape === 'function' && typeof encodeURIComponent === 'function') {
  11220. xmlText = unescape(encodeURIComponent(xmlText));
  11221. }
  11222. } catch (error) {
  11223. throw new Error(error.message);
  11224. }
  11225. const src = "data:image/svg+xml;base64,".concat(btoa(xmlText));
  11226. return src;
  11227. }
  11228. return getBlob(arrayBuffer, url);
  11229. }
  11230. function getBlob(arrayBuffer, url) {
  11231. if (isSVG(url)) {
  11232. throw new Error('SVG cannot be parsed directly to imagebitmap');
  11233. }
  11234. return new Blob([new Uint8Array(arrayBuffer)]);
  11235. }
  11236. async function parseToImage(arrayBuffer, options, url) {
  11237. const blobOrDataUrl = getBlobOrSVGDataUrl(arrayBuffer, url);
  11238. const URL = self.URL || self.webkitURL;
  11239. const objectUrl = typeof blobOrDataUrl !== 'string' && URL.createObjectURL(blobOrDataUrl);
  11240. try {
  11241. return await loadToImage(objectUrl || blobOrDataUrl, options);
  11242. } finally {
  11243. if (objectUrl) {
  11244. URL.revokeObjectURL(objectUrl);
  11245. }
  11246. }
  11247. }
  11248. async function loadToImage(url, options) {
  11249. const image = new Image();
  11250. image.src = url;
  11251. if (options.image && options.image.decode && image.decode) {
  11252. await image.decode();
  11253. return image;
  11254. }
  11255. return await new Promise((resolve, reject) => {
  11256. try {
  11257. image.onload = () => resolve(image);
  11258. image.onerror = err => reject(new Error("Could not load image ".concat(url, ": ").concat(err)));
  11259. } catch (error) {
  11260. reject(error);
  11261. }
  11262. });
  11263. }
  11264. const EMPTY_OBJECT = {};
  11265. let imagebitmapOptionsSupported = true;
  11266. async function parseToImageBitmap(arrayBuffer, options, url) {
  11267. let blob;
  11268. if (isSVG(url)) {
  11269. const image = await parseToImage(arrayBuffer, options, url);
  11270. blob = image;
  11271. } else {
  11272. blob = getBlob(arrayBuffer, url);
  11273. }
  11274. const imagebitmapOptions = options && options.imagebitmap;
  11275. return await safeCreateImageBitmap(blob, imagebitmapOptions);
  11276. }
  11277. async function safeCreateImageBitmap(blob, imagebitmapOptions = null) {
  11278. if (isEmptyObject(imagebitmapOptions) || !imagebitmapOptionsSupported) {
  11279. imagebitmapOptions = null;
  11280. }
  11281. if (imagebitmapOptions) {
  11282. try {
  11283. return await createImageBitmap(blob, imagebitmapOptions);
  11284. } catch (error) {
  11285. console.warn(error);
  11286. imagebitmapOptionsSupported = false;
  11287. }
  11288. }
  11289. return await createImageBitmap(blob);
  11290. }
  11291. function isEmptyObject(object) {
  11292. for (const key in object || EMPTY_OBJECT) {
  11293. return false;
  11294. }
  11295. return true;
  11296. }
  11297. const BIG_ENDIAN = false;
  11298. const LITTLE_ENDIAN = true;
  11299. function getBinaryImageMetadata(binaryData) {
  11300. const dataView = toDataView(binaryData);
  11301. return getPngMetadata(dataView) || getJpegMetadata(dataView) || getGifMetadata(dataView) || getBmpMetadata(dataView);
  11302. }
  11303. function getPngMetadata(binaryData) {
  11304. const dataView = toDataView(binaryData);
  11305. const isPng = dataView.byteLength >= 24 && dataView.getUint32(0, BIG_ENDIAN) === 0x89504e47;
  11306. if (!isPng) {
  11307. return null;
  11308. }
  11309. return {
  11310. mimeType: 'image/png',
  11311. width: dataView.getUint32(16, BIG_ENDIAN),
  11312. height: dataView.getUint32(20, BIG_ENDIAN)
  11313. };
  11314. }
  11315. function getGifMetadata(binaryData) {
  11316. const dataView = toDataView(binaryData);
  11317. const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 0x47494638;
  11318. if (!isGif) {
  11319. return null;
  11320. }
  11321. return {
  11322. mimeType: 'image/gif',
  11323. width: dataView.getUint16(6, LITTLE_ENDIAN),
  11324. height: dataView.getUint16(8, LITTLE_ENDIAN)
  11325. };
  11326. }
  11327. function getBmpMetadata(binaryData) {
  11328. const dataView = toDataView(binaryData);
  11329. const isBmp = dataView.byteLength >= 14 && dataView.getUint16(0, BIG_ENDIAN) === 0x424d && dataView.getUint32(2, LITTLE_ENDIAN) === dataView.byteLength;
  11330. if (!isBmp) {
  11331. return null;
  11332. }
  11333. return {
  11334. mimeType: 'image/bmp',
  11335. width: dataView.getUint32(18, LITTLE_ENDIAN),
  11336. height: dataView.getUint32(22, LITTLE_ENDIAN)
  11337. };
  11338. }
  11339. function getJpegMetadata(binaryData) {
  11340. const dataView = toDataView(binaryData);
  11341. const isJpeg = dataView.byteLength >= 3 && dataView.getUint16(0, BIG_ENDIAN) === 0xffd8 && dataView.getUint8(2) === 0xff;
  11342. if (!isJpeg) {
  11343. return null;
  11344. }
  11345. const {
  11346. tableMarkers,
  11347. sofMarkers
  11348. } = getJpegMarkers();
  11349. let i = 2;
  11350. while (i + 9 < dataView.byteLength) {
  11351. const marker = dataView.getUint16(i, BIG_ENDIAN);
  11352. if (sofMarkers.has(marker)) {
  11353. return {
  11354. mimeType: 'image/jpeg',
  11355. height: dataView.getUint16(i + 5, BIG_ENDIAN),
  11356. width: dataView.getUint16(i + 7, BIG_ENDIAN)
  11357. };
  11358. }
  11359. if (!tableMarkers.has(marker)) {
  11360. return null;
  11361. }
  11362. i += 2;
  11363. i += dataView.getUint16(i, BIG_ENDIAN);
  11364. }
  11365. return null;
  11366. }
  11367. function getJpegMarkers() {
  11368. const tableMarkers = new Set([0xffdb, 0xffc4, 0xffcc, 0xffdd, 0xfffe]);
  11369. for (let i = 0xffe0; i < 0xfff0; ++i) {
  11370. tableMarkers.add(i);
  11371. }
  11372. const sofMarkers = new Set([0xffc0, 0xffc1, 0xffc2, 0xffc3, 0xffc5, 0xffc6, 0xffc7, 0xffc9, 0xffca, 0xffcb, 0xffcd, 0xffce, 0xffcf, 0xffde]);
  11373. return {
  11374. tableMarkers,
  11375. sofMarkers
  11376. };
  11377. }
  11378. function toDataView(data) {
  11379. if (data instanceof DataView) {
  11380. return data;
  11381. }
  11382. if (ArrayBuffer.isView(data)) {
  11383. return new DataView(data.buffer);
  11384. }
  11385. if (data instanceof ArrayBuffer) {
  11386. return new DataView(data);
  11387. }
  11388. throw new Error('toDataView');
  11389. }
  11390. async function parseToNodeImage(arrayBuffer, options) {
  11391. const {
  11392. mimeType
  11393. } = getBinaryImageMetadata(arrayBuffer) || {};
  11394. const _parseImageNode = globalThis._parseImageNode;
  11395. assert$7(_parseImageNode);
  11396. return await _parseImageNode(arrayBuffer, mimeType);
  11397. }
  11398. async function parseImage(arrayBuffer, options, context) {
  11399. options = options || {};
  11400. const imageOptions = options.image || {};
  11401. const imageType = imageOptions.type || 'auto';
  11402. const {
  11403. url
  11404. } = context || {};
  11405. const loadType = getLoadableImageType(imageType);
  11406. let image;
  11407. switch (loadType) {
  11408. case 'imagebitmap':
  11409. image = await parseToImageBitmap(arrayBuffer, options, url);
  11410. break;
  11411. case 'image':
  11412. image = await parseToImage(arrayBuffer, options, url);
  11413. break;
  11414. case 'data':
  11415. image = await parseToNodeImage(arrayBuffer);
  11416. break;
  11417. default:
  11418. assert$7(false);
  11419. }
  11420. if (imageType === 'data') {
  11421. image = getImageData(image);
  11422. }
  11423. return image;
  11424. }
  11425. function getLoadableImageType(type) {
  11426. switch (type) {
  11427. case 'auto':
  11428. case 'data':
  11429. return getDefaultImageType();
  11430. default:
  11431. isImageTypeSupported(type);
  11432. return type;
  11433. }
  11434. }
  11435. const EXTENSIONS$1 = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'svg'];
  11436. const MIME_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'image/vnd.microsoft.icon', 'image/svg+xml'];
  11437. const DEFAULT_IMAGE_LOADER_OPTIONS = {
  11438. image: {
  11439. type: 'auto',
  11440. decode: true
  11441. }
  11442. };
  11443. const ImageLoader = {
  11444. id: 'image',
  11445. module: 'images',
  11446. name: 'Images',
  11447. version: VERSION,
  11448. mimeTypes: MIME_TYPES,
  11449. extensions: EXTENSIONS$1,
  11450. parse: parseImage,
  11451. tests: [arrayBuffer => Boolean(getBinaryImageMetadata(new DataView(arrayBuffer)))],
  11452. options: DEFAULT_IMAGE_LOADER_OPTIONS
  11453. };
  11454. const NODE_FORMAT_SUPPORT = ['image/png', 'image/jpeg', 'image/gif'];
  11455. const mimeTypeSupported = {};
  11456. function _isImageFormatSupported(mimeType) {
  11457. if (mimeTypeSupported[mimeType] === undefined) {
  11458. mimeTypeSupported[mimeType] = checkFormatSupport(mimeType);
  11459. }
  11460. return mimeTypeSupported[mimeType];
  11461. }
  11462. function checkFormatSupport(mimeType) {
  11463. switch (mimeType) {
  11464. case 'image/webp':
  11465. return checkWebPSupport();
  11466. case 'image/svg':
  11467. return isBrowser$2;
  11468. default:
  11469. if (!isBrowser$2) {
  11470. const {
  11471. _parseImageNode
  11472. } = globalThis;
  11473. return Boolean(_parseImageNode) && NODE_FORMAT_SUPPORT.includes(mimeType);
  11474. }
  11475. return true;
  11476. }
  11477. }
  11478. function checkWebPSupport() {
  11479. if (!isBrowser$2) {
  11480. return false;
  11481. }
  11482. try {
  11483. const element = document.createElement('canvas');
  11484. return element.toDataURL('image/webp').indexOf('data:image/webp') === 0;
  11485. } catch {
  11486. return false;
  11487. }
  11488. }
  11489. function assert$1(condition, message) {
  11490. if (!condition) {
  11491. throw new Error(message || 'assert failed: gltf');
  11492. }
  11493. }
  11494. function resolveUrl(url, options) {
  11495. const absolute = url.startsWith('data:') || url.startsWith('http:') || url.startsWith('https:');
  11496. if (absolute) {
  11497. return url;
  11498. }
  11499. const baseUrl = options.baseUri || options.uri;
  11500. if (!baseUrl) {
  11501. throw new Error("'baseUri' must be provided to resolve relative url ".concat(url));
  11502. }
  11503. return baseUrl.substr(0, baseUrl.lastIndexOf('/') + 1) + url;
  11504. }
  11505. function getTypedArrayForBufferView(json, buffers, bufferViewIndex) {
  11506. const bufferView = json.bufferViews[bufferViewIndex];
  11507. assert$1(bufferView);
  11508. const bufferIndex = bufferView.buffer;
  11509. const binChunk = buffers[bufferIndex];
  11510. assert$1(binChunk);
  11511. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  11512. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  11513. }
  11514. const TYPES = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'];
  11515. const ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT = [[Int8Array, 5120], [Uint8Array, 5121], [Int16Array, 5122], [Uint16Array, 5123], [Uint32Array, 5125], [Float32Array, 5126], [Float64Array, 5130]];
  11516. const ARRAY_TO_COMPONENT_TYPE = new Map(ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT);
  11517. const ATTRIBUTE_TYPE_TO_COMPONENTS = {
  11518. SCALAR: 1,
  11519. VEC2: 2,
  11520. VEC3: 3,
  11521. VEC4: 4,
  11522. MAT2: 4,
  11523. MAT3: 9,
  11524. MAT4: 16
  11525. };
  11526. const ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE = {
  11527. 5120: 1,
  11528. 5121: 1,
  11529. 5122: 2,
  11530. 5123: 2,
  11531. 5125: 4,
  11532. 5126: 4
  11533. };
  11534. const ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY = {
  11535. 5120: Int8Array,
  11536. 5121: Uint8Array,
  11537. 5122: Int16Array,
  11538. 5123: Uint16Array,
  11539. 5125: Uint32Array,
  11540. 5126: Float32Array
  11541. };
  11542. function getAccessorTypeFromSize(size) {
  11543. const type = TYPES[size - 1];
  11544. return type || TYPES[0];
  11545. }
  11546. function getComponentTypeFromArray(typedArray) {
  11547. const componentType = ARRAY_TO_COMPONENT_TYPE.get(typedArray.constructor);
  11548. if (!componentType) {
  11549. throw new Error('Illegal typed array');
  11550. }
  11551. return componentType;
  11552. }
  11553. function getAccessorArrayTypeAndLength(accessor, bufferView) {
  11554. const ArrayType = ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[accessor.componentType];
  11555. const components = ATTRIBUTE_TYPE_TO_COMPONENTS[accessor.type];
  11556. const bytesPerComponent = ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[accessor.componentType];
  11557. const length = accessor.count * components;
  11558. const byteLength = accessor.count * components * bytesPerComponent;
  11559. assert$1(byteLength >= 0 && byteLength <= bufferView.byteLength);
  11560. return {
  11561. ArrayType,
  11562. length,
  11563. byteLength
  11564. };
  11565. }
  11566. const DEFAULT_GLTF_JSON = {
  11567. asset: {
  11568. version: '2.0',
  11569. generator: 'loaders.gl'
  11570. },
  11571. buffers: []
  11572. };
  11573. class GLTFScenegraph {
  11574. constructor(gltf) {
  11575. _defineProperty(this, "gltf", void 0);
  11576. _defineProperty(this, "sourceBuffers", void 0);
  11577. _defineProperty(this, "byteLength", void 0);
  11578. this.gltf = gltf || {
  11579. json: { ...DEFAULT_GLTF_JSON
  11580. },
  11581. buffers: []
  11582. };
  11583. this.sourceBuffers = [];
  11584. this.byteLength = 0;
  11585. if (this.gltf.buffers && this.gltf.buffers[0]) {
  11586. this.byteLength = this.gltf.buffers[0].byteLength;
  11587. this.sourceBuffers = [this.gltf.buffers[0]];
  11588. }
  11589. }
  11590. get json() {
  11591. return this.gltf.json;
  11592. }
  11593. getApplicationData(key) {
  11594. const data = this.json[key];
  11595. return data;
  11596. }
  11597. getExtraData(key) {
  11598. const extras = this.json.extras || {};
  11599. return extras[key];
  11600. }
  11601. getExtension(extensionName) {
  11602. const isExtension = this.getUsedExtensions().find(name => name === extensionName);
  11603. const extensions = this.json.extensions || {};
  11604. return isExtension ? extensions[extensionName] || true : null;
  11605. }
  11606. getRequiredExtension(extensionName) {
  11607. const isRequired = this.getRequiredExtensions().find(name => name === extensionName);
  11608. return isRequired ? this.getExtension(extensionName) : null;
  11609. }
  11610. getRequiredExtensions() {
  11611. return this.json.extensionsRequired || [];
  11612. }
  11613. getUsedExtensions() {
  11614. return this.json.extensionsUsed || [];
  11615. }
  11616. getObjectExtension(object, extensionName) {
  11617. const extensions = object.extensions || {};
  11618. return extensions[extensionName];
  11619. }
  11620. getScene(index) {
  11621. return this.getObject('scenes', index);
  11622. }
  11623. getNode(index) {
  11624. return this.getObject('nodes', index);
  11625. }
  11626. getSkin(index) {
  11627. return this.getObject('skins', index);
  11628. }
  11629. getMesh(index) {
  11630. return this.getObject('meshes', index);
  11631. }
  11632. getMaterial(index) {
  11633. return this.getObject('materials', index);
  11634. }
  11635. getAccessor(index) {
  11636. return this.getObject('accessors', index);
  11637. }
  11638. getTexture(index) {
  11639. return this.getObject('textures', index);
  11640. }
  11641. getSampler(index) {
  11642. return this.getObject('samplers', index);
  11643. }
  11644. getImage(index) {
  11645. return this.getObject('images', index);
  11646. }
  11647. getBufferView(index) {
  11648. return this.getObject('bufferViews', index);
  11649. }
  11650. getBuffer(index) {
  11651. return this.getObject('buffers', index);
  11652. }
  11653. getObject(array, index) {
  11654. if (typeof index === 'object') {
  11655. return index;
  11656. }
  11657. const object = this.json[array] && this.json[array][index];
  11658. if (!object) {
  11659. throw new Error("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  11660. }
  11661. return object;
  11662. }
  11663. getTypedArrayForBufferView(bufferView) {
  11664. bufferView = this.getBufferView(bufferView);
  11665. const bufferIndex = bufferView.buffer;
  11666. const binChunk = this.gltf.buffers[bufferIndex];
  11667. assert$1(binChunk);
  11668. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  11669. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  11670. }
  11671. getTypedArrayForAccessor(accessor) {
  11672. accessor = this.getAccessor(accessor);
  11673. const bufferView = this.getBufferView(accessor.bufferView);
  11674. const buffer = this.getBuffer(bufferView.buffer);
  11675. const arrayBuffer = buffer.data;
  11676. const {
  11677. ArrayType,
  11678. length
  11679. } = getAccessorArrayTypeAndLength(accessor, bufferView);
  11680. const byteOffset = bufferView.byteOffset + accessor.byteOffset;
  11681. return new ArrayType(arrayBuffer, byteOffset, length);
  11682. }
  11683. getTypedArrayForImageData(image) {
  11684. image = this.getAccessor(image);
  11685. const bufferView = this.getBufferView(image.bufferView);
  11686. const buffer = this.getBuffer(bufferView.buffer);
  11687. const arrayBuffer = buffer.data;
  11688. const byteOffset = bufferView.byteOffset || 0;
  11689. return new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  11690. }
  11691. addApplicationData(key, data) {
  11692. this.json[key] = data;
  11693. return this;
  11694. }
  11695. addExtraData(key, data) {
  11696. this.json.extras = this.json.extras || {};
  11697. this.json.extras[key] = data;
  11698. return this;
  11699. }
  11700. addObjectExtension(object, extensionName, data) {
  11701. object.extensions = object.extensions || {};
  11702. object.extensions[extensionName] = data;
  11703. this.registerUsedExtension(extensionName);
  11704. return this;
  11705. }
  11706. setObjectExtension(object, extensionName, data) {
  11707. const extensions = object.extensions || {};
  11708. extensions[extensionName] = data;
  11709. }
  11710. removeObjectExtension(object, extensionName) {
  11711. const extensions = object.extensions || {};
  11712. const extension = extensions[extensionName];
  11713. delete extensions[extensionName];
  11714. return extension;
  11715. }
  11716. addExtension(extensionName, extensionData = {}) {
  11717. assert$1(extensionData);
  11718. this.json.extensions = this.json.extensions || {};
  11719. this.json.extensions[extensionName] = extensionData;
  11720. this.registerUsedExtension(extensionName);
  11721. return extensionData;
  11722. }
  11723. addRequiredExtension(extensionName, extensionData = {}) {
  11724. assert$1(extensionData);
  11725. this.addExtension(extensionName, extensionData);
  11726. this.registerRequiredExtension(extensionName);
  11727. return extensionData;
  11728. }
  11729. registerUsedExtension(extensionName) {
  11730. this.json.extensionsUsed = this.json.extensionsUsed || [];
  11731. if (!this.json.extensionsUsed.find(ext => ext === extensionName)) {
  11732. this.json.extensionsUsed.push(extensionName);
  11733. }
  11734. }
  11735. registerRequiredExtension(extensionName) {
  11736. this.registerUsedExtension(extensionName);
  11737. this.json.extensionsRequired = this.json.extensionsRequired || [];
  11738. if (!this.json.extensionsRequired.find(ext => ext === extensionName)) {
  11739. this.json.extensionsRequired.push(extensionName);
  11740. }
  11741. }
  11742. removeExtension(extensionName) {
  11743. if (this.json.extensionsRequired) {
  11744. this._removeStringFromArray(this.json.extensionsRequired, extensionName);
  11745. }
  11746. if (this.json.extensionsUsed) {
  11747. this._removeStringFromArray(this.json.extensionsUsed, extensionName);
  11748. }
  11749. if (this.json.extensions) {
  11750. delete this.json.extensions[extensionName];
  11751. }
  11752. }
  11753. setDefaultScene(sceneIndex) {
  11754. this.json.scene = sceneIndex;
  11755. }
  11756. addScene(scene) {
  11757. const {
  11758. nodeIndices
  11759. } = scene;
  11760. this.json.scenes = this.json.scenes || [];
  11761. this.json.scenes.push({
  11762. nodes: nodeIndices
  11763. });
  11764. return this.json.scenes.length - 1;
  11765. }
  11766. addNode(node) {
  11767. const {
  11768. meshIndex,
  11769. matrix
  11770. } = node;
  11771. this.json.nodes = this.json.nodes || [];
  11772. const nodeData = {
  11773. mesh: meshIndex
  11774. };
  11775. if (matrix) {
  11776. nodeData.matrix = matrix;
  11777. }
  11778. this.json.nodes.push(nodeData);
  11779. return this.json.nodes.length - 1;
  11780. }
  11781. addMesh(mesh) {
  11782. const {
  11783. attributes,
  11784. indices,
  11785. material,
  11786. mode = 4
  11787. } = mesh;
  11788. const accessors = this._addAttributes(attributes);
  11789. const glTFMesh = {
  11790. primitives: [{
  11791. attributes: accessors,
  11792. mode
  11793. }]
  11794. };
  11795. if (indices) {
  11796. const indicesAccessor = this._addIndices(indices);
  11797. glTFMesh.primitives[0].indices = indicesAccessor;
  11798. }
  11799. if (Number.isFinite(material)) {
  11800. glTFMesh.primitives[0].material = material;
  11801. }
  11802. this.json.meshes = this.json.meshes || [];
  11803. this.json.meshes.push(glTFMesh);
  11804. return this.json.meshes.length - 1;
  11805. }
  11806. addPointCloud(attributes) {
  11807. const accessorIndices = this._addAttributes(attributes);
  11808. const glTFMesh = {
  11809. primitives: [{
  11810. attributes: accessorIndices,
  11811. mode: 0
  11812. }]
  11813. };
  11814. this.json.meshes = this.json.meshes || [];
  11815. this.json.meshes.push(glTFMesh);
  11816. return this.json.meshes.length - 1;
  11817. }
  11818. addImage(imageData, mimeTypeOpt) {
  11819. const metadata = getBinaryImageMetadata(imageData);
  11820. const mimeType = mimeTypeOpt || (metadata === null || metadata === void 0 ? void 0 : metadata.mimeType);
  11821. const bufferViewIndex = this.addBufferView(imageData);
  11822. const glTFImage = {
  11823. bufferView: bufferViewIndex,
  11824. mimeType
  11825. };
  11826. this.json.images = this.json.images || [];
  11827. this.json.images.push(glTFImage);
  11828. return this.json.images.length - 1;
  11829. }
  11830. addBufferView(buffer) {
  11831. const byteLength = buffer.byteLength;
  11832. assert$1(Number.isFinite(byteLength));
  11833. this.sourceBuffers = this.sourceBuffers || [];
  11834. this.sourceBuffers.push(buffer);
  11835. const glTFBufferView = {
  11836. buffer: 0,
  11837. byteOffset: this.byteLength,
  11838. byteLength
  11839. };
  11840. this.byteLength += padToNBytes(byteLength, 4);
  11841. this.json.bufferViews = this.json.bufferViews || [];
  11842. this.json.bufferViews.push(glTFBufferView);
  11843. return this.json.bufferViews.length - 1;
  11844. }
  11845. addAccessor(bufferViewIndex, accessor) {
  11846. const glTFAccessor = {
  11847. bufferView: bufferViewIndex,
  11848. type: getAccessorTypeFromSize(accessor.size),
  11849. componentType: accessor.componentType,
  11850. count: accessor.count,
  11851. max: accessor.max,
  11852. min: accessor.min
  11853. };
  11854. this.json.accessors = this.json.accessors || [];
  11855. this.json.accessors.push(glTFAccessor);
  11856. return this.json.accessors.length - 1;
  11857. }
  11858. addBinaryBuffer(sourceBuffer, accessor = {
  11859. size: 3
  11860. }) {
  11861. const bufferViewIndex = this.addBufferView(sourceBuffer);
  11862. let minMax = {
  11863. min: accessor.min,
  11864. max: accessor.max
  11865. };
  11866. if (!minMax.min || !minMax.max) {
  11867. minMax = this._getAccessorMinMax(sourceBuffer, accessor.size);
  11868. }
  11869. const accessorDefaults = {
  11870. size: accessor.size,
  11871. componentType: getComponentTypeFromArray(sourceBuffer),
  11872. count: Math.round(sourceBuffer.length / accessor.size),
  11873. min: minMax.min,
  11874. max: minMax.max
  11875. };
  11876. return this.addAccessor(bufferViewIndex, Object.assign(accessorDefaults, accessor));
  11877. }
  11878. addTexture(texture) {
  11879. const {
  11880. imageIndex
  11881. } = texture;
  11882. const glTFTexture = {
  11883. source: imageIndex
  11884. };
  11885. this.json.textures = this.json.textures || [];
  11886. this.json.textures.push(glTFTexture);
  11887. return this.json.textures.length - 1;
  11888. }
  11889. addMaterial(pbrMaterialInfo) {
  11890. this.json.materials = this.json.materials || [];
  11891. this.json.materials.push(pbrMaterialInfo);
  11892. return this.json.materials.length - 1;
  11893. }
  11894. createBinaryChunk() {
  11895. var _this$json, _this$json$buffers;
  11896. this.gltf.buffers = [];
  11897. const totalByteLength = this.byteLength;
  11898. const arrayBuffer = new ArrayBuffer(totalByteLength);
  11899. const targetArray = new Uint8Array(arrayBuffer);
  11900. let dstByteOffset = 0;
  11901. for (const sourceBuffer of this.sourceBuffers || []) {
  11902. dstByteOffset = copyToArray(sourceBuffer, targetArray, dstByteOffset);
  11903. }
  11904. 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]) {
  11905. this.json.buffers[0].byteLength = totalByteLength;
  11906. } else {
  11907. this.json.buffers = [{
  11908. byteLength: totalByteLength
  11909. }];
  11910. }
  11911. this.gltf.binary = arrayBuffer;
  11912. this.sourceBuffers = [arrayBuffer];
  11913. }
  11914. _removeStringFromArray(array, string) {
  11915. let found = true;
  11916. while (found) {
  11917. const index = array.indexOf(string);
  11918. if (index > -1) {
  11919. array.splice(index, 1);
  11920. } else {
  11921. found = false;
  11922. }
  11923. }
  11924. }
  11925. _addAttributes(attributes = {}) {
  11926. const result = {};
  11927. for (const attributeKey in attributes) {
  11928. const attributeData = attributes[attributeKey];
  11929. const attrName = this._getGltfAttributeName(attributeKey);
  11930. const accessor = this.addBinaryBuffer(attributeData.value, attributeData);
  11931. result[attrName] = accessor;
  11932. }
  11933. return result;
  11934. }
  11935. _addIndices(indices) {
  11936. return this.addBinaryBuffer(indices, {
  11937. size: 1
  11938. });
  11939. }
  11940. _getGltfAttributeName(attributeName) {
  11941. switch (attributeName.toLowerCase()) {
  11942. case 'position':
  11943. case 'positions':
  11944. case 'vertices':
  11945. return 'POSITION';
  11946. case 'normal':
  11947. case 'normals':
  11948. return 'NORMAL';
  11949. case 'color':
  11950. case 'colors':
  11951. return 'COLOR_0';
  11952. case 'texcoord':
  11953. case 'texcoords':
  11954. return 'TEXCOORD_0';
  11955. default:
  11956. return attributeName;
  11957. }
  11958. }
  11959. _getAccessorMinMax(buffer, size) {
  11960. const result = {
  11961. min: null,
  11962. max: null
  11963. };
  11964. if (buffer.length < size) {
  11965. return result;
  11966. }
  11967. result.min = [];
  11968. result.max = [];
  11969. const initValues = buffer.subarray(0, size);
  11970. for (const value of initValues) {
  11971. result.min.push(value);
  11972. result.max.push(value);
  11973. }
  11974. for (let index = size; index < buffer.length; index += size) {
  11975. for (let componentIndex = 0; componentIndex < size; componentIndex++) {
  11976. result.min[0 + componentIndex] = Math.min(result.min[0 + componentIndex], buffer[index + componentIndex]);
  11977. result.max[0 + componentIndex] = Math.max(result.max[0 + componentIndex], buffer[index + componentIndex]);
  11978. }
  11979. }
  11980. return result;
  11981. }
  11982. }
  11983. const isWebAssemblySupported = typeof WebAssembly !== 'object';
  11984. 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';
  11985. 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';
  11986. 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]);
  11987. 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]);
  11988. const FILTERS = {
  11989. 0: '',
  11990. 1: 'meshopt_decodeFilterOct',
  11991. 2: 'meshopt_decodeFilterQuat',
  11992. 3: 'meshopt_decodeFilterExp',
  11993. NONE: '',
  11994. OCTAHEDRAL: 'meshopt_decodeFilterOct',
  11995. QUATERNION: 'meshopt_decodeFilterQuat',
  11996. EXPONENTIAL: 'meshopt_decodeFilterExp'
  11997. };
  11998. const DECODERS = {
  11999. 0: 'meshopt_decodeVertexBuffer',
  12000. 1: 'meshopt_decodeIndexBuffer',
  12001. 2: 'meshopt_decodeIndexSequence',
  12002. ATTRIBUTES: 'meshopt_decodeVertexBuffer',
  12003. TRIANGLES: 'meshopt_decodeIndexBuffer',
  12004. INDICES: 'meshopt_decodeIndexSequence'
  12005. };
  12006. function isMeshoptSupported() {
  12007. return isWebAssemblySupported;
  12008. }
  12009. async function meshoptDecodeGltfBuffer(target, count, size, source, mode, filter = 'NONE') {
  12010. const instance = await loadWasmInstance();
  12011. decode$5(instance, instance.exports[DECODERS[mode]], target, count, size, source, instance.exports[FILTERS[filter || 'NONE']]);
  12012. }
  12013. let wasmPromise;
  12014. async function loadWasmInstance() {
  12015. if (!wasmPromise) {
  12016. wasmPromise = loadWasmModule();
  12017. }
  12018. return wasmPromise;
  12019. }
  12020. async function loadWasmModule() {
  12021. let wasm = wasm_base;
  12022. if (WebAssembly.validate(detector)) {
  12023. wasm = wasm_simd;
  12024. console.log('Warning: meshopt_decoder is using experimental SIMD support');
  12025. }
  12026. const result = await WebAssembly.instantiate(unpack(wasm), {});
  12027. await result.instance.exports.__wasm_call_ctors();
  12028. return result.instance;
  12029. }
  12030. function unpack(data) {
  12031. const result = new Uint8Array(data.length);
  12032. for (let i = 0; i < data.length; ++i) {
  12033. const ch = data.charCodeAt(i);
  12034. result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  12035. }
  12036. let write = 0;
  12037. for (let i = 0; i < data.length; ++i) {
  12038. result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  12039. }
  12040. return result.buffer.slice(0, write);
  12041. }
  12042. function decode$5(instance, fun, target, count, size, source, filter) {
  12043. const sbrk = instance.exports.sbrk;
  12044. const count4 = count + 3 & ~3;
  12045. const tp = sbrk(count4 * size);
  12046. const sp = sbrk(source.length);
  12047. const heap = new Uint8Array(instance.exports.memory.buffer);
  12048. heap.set(source, sp);
  12049. const res = fun(tp, count, size, sp, source.length);
  12050. if (res === 0 && filter) {
  12051. filter(tp, count4, size);
  12052. }
  12053. target.set(heap.subarray(tp, tp + count * size));
  12054. sbrk(tp - sbrk(0));
  12055. if (res !== 0) {
  12056. throw new Error("Malformed buffer data: ".concat(res));
  12057. }
  12058. }
  12059. const EXT_MESHOPT_COMPRESSION = 'EXT_meshopt_compression';
  12060. const name$6 = EXT_MESHOPT_COMPRESSION;
  12061. function preprocess$4(gltfData) {
  12062. const scenegraph = new GLTFScenegraph(gltfData);
  12063. if (scenegraph.getRequiredExtensions().includes(EXT_MESHOPT_COMPRESSION) && !isMeshoptSupported()) {
  12064. throw new Error("gltf: Required extension ".concat(EXT_MESHOPT_COMPRESSION, " not supported by browser"));
  12065. }
  12066. }
  12067. async function decode$4(gltfData, options) {
  12068. var _options$gltf;
  12069. const scenegraph = new GLTFScenegraph(gltfData);
  12070. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  12071. return;
  12072. }
  12073. const promises = [];
  12074. for (const bufferViewIndex of gltfData.json.bufferViews || []) {
  12075. promises.push(decodeMeshoptBufferView(scenegraph, bufferViewIndex));
  12076. }
  12077. await Promise.all(promises);
  12078. scenegraph.removeExtension(EXT_MESHOPT_COMPRESSION);
  12079. }
  12080. async function decodeMeshoptBufferView(scenegraph, bufferView) {
  12081. const meshoptExtension = scenegraph.getObjectExtension(bufferView, EXT_MESHOPT_COMPRESSION);
  12082. if (meshoptExtension) {
  12083. const buffer = bufferView.buffer;
  12084. const {
  12085. byteOffset = 0,
  12086. byteLength = 0,
  12087. byteStride,
  12088. count,
  12089. mode,
  12090. filter = 'NONE'
  12091. } = meshoptExtension;
  12092. const source = new Uint8Array(buffer, byteOffset, byteLength);
  12093. const result = new ArrayBuffer(count * byteStride);
  12094. await meshoptDecodeGltfBuffer(new Uint8Array(result), count, byteStride, source, mode, filter);
  12095. return result;
  12096. }
  12097. return null;
  12098. }
  12099. var EXT_meshopt_compression = /*#__PURE__*/Object.freeze({
  12100. __proto__: null,
  12101. name: name$6,
  12102. preprocess: preprocess$4,
  12103. decode: decode$4
  12104. });
  12105. const EXT_TEXTURE_WEBP = 'EXT_texture_webp';
  12106. const name$5 = EXT_TEXTURE_WEBP;
  12107. function preprocess$3(gltfData, options) {
  12108. const scenegraph = new GLTFScenegraph(gltfData);
  12109. if (!_isImageFormatSupported('image/webp')) {
  12110. if (scenegraph.getRequiredExtensions().includes(EXT_TEXTURE_WEBP)) {
  12111. throw new Error("gltf: Required extension ".concat(EXT_TEXTURE_WEBP, " not supported by browser"));
  12112. }
  12113. return;
  12114. }
  12115. const {
  12116. json
  12117. } = scenegraph;
  12118. for (const texture of json.textures || []) {
  12119. const extension = scenegraph.getObjectExtension(texture, EXT_TEXTURE_WEBP);
  12120. if (extension) {
  12121. texture.source = extension.source;
  12122. }
  12123. scenegraph.removeObjectExtension(texture, EXT_TEXTURE_WEBP);
  12124. }
  12125. scenegraph.removeExtension(EXT_TEXTURE_WEBP);
  12126. }
  12127. var EXT_texture_webp = /*#__PURE__*/Object.freeze({
  12128. __proto__: null,
  12129. name: name$5,
  12130. preprocess: preprocess$3
  12131. });
  12132. const KHR_TEXTURE_BASISU = 'KHR_texture_basisu';
  12133. const name$4 = KHR_TEXTURE_BASISU;
  12134. function preprocess$2(gltfData, options) {
  12135. const scene = new GLTFScenegraph(gltfData);
  12136. const {
  12137. json
  12138. } = scene;
  12139. for (const texture of json.textures || []) {
  12140. const extension = scene.getObjectExtension(texture, KHR_TEXTURE_BASISU);
  12141. if (extension) {
  12142. texture.source = extension.source;
  12143. }
  12144. scene.removeObjectExtension(texture, KHR_TEXTURE_BASISU);
  12145. }
  12146. scene.removeExtension(KHR_TEXTURE_BASISU);
  12147. }
  12148. var KHR_texture_basisu = /*#__PURE__*/Object.freeze({
  12149. __proto__: null,
  12150. name: name$4,
  12151. preprocess: preprocess$2
  12152. });
  12153. function getGLTFAccessors(attributes) {
  12154. const accessors = {};
  12155. for (const name in attributes) {
  12156. const attribute = attributes[name];
  12157. if (name !== 'indices') {
  12158. const glTFAccessor = getGLTFAccessor(attribute);
  12159. accessors[name] = glTFAccessor;
  12160. }
  12161. }
  12162. return accessors;
  12163. }
  12164. function getGLTFAccessor(attribute) {
  12165. const {
  12166. buffer,
  12167. size,
  12168. count
  12169. } = getAccessorData(attribute);
  12170. const glTFAccessor = {
  12171. value: buffer,
  12172. size,
  12173. byteOffset: 0,
  12174. count,
  12175. type: getAccessorTypeFromSize(size),
  12176. componentType: getComponentTypeFromArray(buffer)
  12177. };
  12178. return glTFAccessor;
  12179. }
  12180. function getAccessorData(attribute) {
  12181. let buffer = attribute;
  12182. let size = 1;
  12183. let count = 0;
  12184. if (attribute && attribute.value) {
  12185. buffer = attribute.value;
  12186. size = attribute.size || 1;
  12187. }
  12188. if (buffer) {
  12189. if (!ArrayBuffer.isView(buffer)) {
  12190. buffer = toTypedArray(buffer, Float32Array);
  12191. }
  12192. count = buffer.length / size;
  12193. }
  12194. return {
  12195. buffer,
  12196. size,
  12197. count
  12198. };
  12199. }
  12200. function toTypedArray(array, ArrayType, convertTypedArrays = false) {
  12201. if (!array) {
  12202. return null;
  12203. }
  12204. if (Array.isArray(array)) {
  12205. return new ArrayType(array);
  12206. }
  12207. if (convertTypedArrays && !(array instanceof ArrayType)) {
  12208. return new ArrayType(array);
  12209. }
  12210. return array;
  12211. }
  12212. const KHR_DRACO_MESH_COMPRESSION = 'KHR_draco_mesh_compression';
  12213. const name$3 = KHR_DRACO_MESH_COMPRESSION;
  12214. function preprocess$1(gltfData, options, context) {
  12215. const scenegraph = new GLTFScenegraph(gltfData);
  12216. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12217. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) ;
  12218. }
  12219. }
  12220. async function decode$3(gltfData, options, context) {
  12221. var _options$gltf;
  12222. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  12223. return;
  12224. }
  12225. const scenegraph = new GLTFScenegraph(gltfData);
  12226. const promises = [];
  12227. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12228. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) {
  12229. promises.push(decompressPrimitive(scenegraph, primitive, options, context));
  12230. }
  12231. }
  12232. await Promise.all(promises);
  12233. scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);
  12234. }
  12235. function encode$3(gltfData, options = {}) {
  12236. const scenegraph = new GLTFScenegraph(gltfData);
  12237. for (const mesh of scenegraph.json.meshes || []) {
  12238. compressMesh(mesh);
  12239. scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
  12240. }
  12241. }
  12242. async function decompressPrimitive(scenegraph, primitive, options, context) {
  12243. const dracoExtension = scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION);
  12244. if (!dracoExtension) {
  12245. return;
  12246. }
  12247. const buffer = scenegraph.getTypedArrayForBufferView(dracoExtension.bufferView);
  12248. const bufferCopy = sliceArrayBuffer(buffer.buffer, buffer.byteOffset);
  12249. const {
  12250. parse
  12251. } = context;
  12252. const dracoOptions = { ...options
  12253. };
  12254. delete dracoOptions['3d-tiles'];
  12255. const decodedData = await parse(bufferCopy, DracoLoader, dracoOptions, context);
  12256. const decodedAttributes = getGLTFAccessors(decodedData.attributes);
  12257. for (const [attributeName, decodedAttribute] of Object.entries(decodedAttributes)) {
  12258. if (attributeName in primitive.attributes) {
  12259. const accessorIndex = primitive.attributes[attributeName];
  12260. const accessor = scenegraph.getAccessor(accessorIndex);
  12261. if (accessor !== null && accessor !== void 0 && accessor.min && accessor !== null && accessor !== void 0 && accessor.max) {
  12262. decodedAttribute.min = accessor.min;
  12263. decodedAttribute.max = accessor.max;
  12264. }
  12265. }
  12266. }
  12267. primitive.attributes = decodedAttributes;
  12268. if (decodedData.indices) {
  12269. primitive.indices = getGLTFAccessor(decodedData.indices);
  12270. }
  12271. checkPrimitive(primitive);
  12272. }
  12273. function compressMesh(attributes, indices, mode = 4, options, context) {
  12274. var _context$parseSync;
  12275. if (!options.DracoWriter) {
  12276. throw new Error('options.gltf.DracoWriter not provided');
  12277. }
  12278. const compressedData = options.DracoWriter.encodeSync({
  12279. attributes
  12280. });
  12281. const decodedData = context === null || context === void 0 ? void 0 : (_context$parseSync = context.parseSync) === null || _context$parseSync === void 0 ? void 0 : _context$parseSync.call(context, {
  12282. attributes
  12283. });
  12284. const fauxAccessors = options._addFauxAttributes(decodedData.attributes);
  12285. const bufferViewIndex = options.addBufferView(compressedData);
  12286. const glTFMesh = {
  12287. primitives: [{
  12288. attributes: fauxAccessors,
  12289. mode,
  12290. extensions: {
  12291. [KHR_DRACO_MESH_COMPRESSION]: {
  12292. bufferView: bufferViewIndex,
  12293. attributes: fauxAccessors
  12294. }
  12295. }
  12296. }]
  12297. };
  12298. return glTFMesh;
  12299. }
  12300. function checkPrimitive(primitive) {
  12301. if (!primitive.attributes && Object.keys(primitive.attributes).length > 0) {
  12302. throw new Error('glTF: Empty primitive detected: Draco decompression failure?');
  12303. }
  12304. }
  12305. function* makeMeshPrimitiveIterator(scenegraph) {
  12306. for (const mesh of scenegraph.json.meshes || []) {
  12307. for (const primitive of mesh.primitives) {
  12308. yield primitive;
  12309. }
  12310. }
  12311. }
  12312. var KHR_draco_mesh_compression = /*#__PURE__*/Object.freeze({
  12313. __proto__: null,
  12314. name: name$3,
  12315. preprocess: preprocess$1,
  12316. decode: decode$3,
  12317. encode: encode$3
  12318. });
  12319. const KHR_LIGHTS_PUNCTUAL = 'KHR_lights_punctual';
  12320. const name$2 = KHR_LIGHTS_PUNCTUAL;
  12321. async function decode$2(gltfData) {
  12322. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12323. const {
  12324. json
  12325. } = gltfScenegraph;
  12326. const extension = gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL);
  12327. if (extension) {
  12328. gltfScenegraph.json.lights = extension.lights;
  12329. gltfScenegraph.removeExtension(KHR_LIGHTS_PUNCTUAL);
  12330. }
  12331. for (const node of json.nodes || []) {
  12332. const nodeExtension = gltfScenegraph.getObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12333. if (nodeExtension) {
  12334. node.light = nodeExtension.light;
  12335. }
  12336. gltfScenegraph.removeObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12337. }
  12338. }
  12339. async function encode$2(gltfData) {
  12340. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12341. const {
  12342. json
  12343. } = gltfScenegraph;
  12344. if (json.lights) {
  12345. const extension = gltfScenegraph.addExtension(KHR_LIGHTS_PUNCTUAL);
  12346. assert$1(!extension.lights);
  12347. extension.lights = json.lights;
  12348. delete json.lights;
  12349. }
  12350. if (gltfScenegraph.json.lights) {
  12351. for (const light of gltfScenegraph.json.lights) {
  12352. const node = light.node;
  12353. gltfScenegraph.addObjectExtension(node, KHR_LIGHTS_PUNCTUAL, light);
  12354. }
  12355. delete gltfScenegraph.json.lights;
  12356. }
  12357. }
  12358. var KHR_lights_punctual = /*#__PURE__*/Object.freeze({
  12359. __proto__: null,
  12360. name: name$2,
  12361. decode: decode$2,
  12362. encode: encode$2
  12363. });
  12364. const KHR_MATERIALS_UNLIT = 'KHR_materials_unlit';
  12365. const name$1 = KHR_MATERIALS_UNLIT;
  12366. async function decode$1(gltfData) {
  12367. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12368. const {
  12369. json
  12370. } = gltfScenegraph;
  12371. gltfScenegraph.removeExtension(KHR_MATERIALS_UNLIT);
  12372. for (const material of json.materials || []) {
  12373. const extension = material.extensions && material.extensions.KHR_materials_unlit;
  12374. if (extension) {
  12375. material.unlit = true;
  12376. }
  12377. gltfScenegraph.removeObjectExtension(material, KHR_MATERIALS_UNLIT);
  12378. }
  12379. }
  12380. function encode$1(gltfData) {
  12381. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12382. const {
  12383. json
  12384. } = gltfScenegraph;
  12385. if (gltfScenegraph.materials) {
  12386. for (const material of json.materials || []) {
  12387. if (material.unlit) {
  12388. delete material.unlit;
  12389. gltfScenegraph.addObjectExtension(material, KHR_MATERIALS_UNLIT, {});
  12390. gltfScenegraph.addExtension(KHR_MATERIALS_UNLIT);
  12391. }
  12392. }
  12393. }
  12394. }
  12395. var KHR_materials_unlit = /*#__PURE__*/Object.freeze({
  12396. __proto__: null,
  12397. name: name$1,
  12398. decode: decode$1,
  12399. encode: encode$1
  12400. });
  12401. const KHR_TECHNIQUES_WEBGL = 'KHR_techniques_webgl';
  12402. const name = KHR_TECHNIQUES_WEBGL;
  12403. async function decode(gltfData) {
  12404. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12405. const {
  12406. json
  12407. } = gltfScenegraph;
  12408. const extension = gltfScenegraph.getExtension(KHR_TECHNIQUES_WEBGL);
  12409. if (extension) {
  12410. const techniques = resolveTechniques(extension, gltfScenegraph);
  12411. for (const material of json.materials || []) {
  12412. const materialExtension = gltfScenegraph.getObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12413. if (materialExtension) {
  12414. material.technique = Object.assign({}, materialExtension, techniques[materialExtension.technique]);
  12415. material.technique.values = resolveValues(material.technique, gltfScenegraph);
  12416. }
  12417. gltfScenegraph.removeObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12418. }
  12419. gltfScenegraph.removeExtension(KHR_TECHNIQUES_WEBGL);
  12420. }
  12421. }
  12422. async function encode(gltfData, options) {}
  12423. function resolveTechniques(techniquesExtension, gltfScenegraph) {
  12424. const {
  12425. programs = [],
  12426. shaders = [],
  12427. techniques = []
  12428. } = techniquesExtension;
  12429. const textDecoder = new TextDecoder();
  12430. shaders.forEach(shader => {
  12431. if (Number.isFinite(shader.bufferView)) {
  12432. shader.code = textDecoder.decode(gltfScenegraph.getTypedArrayForBufferView(shader.bufferView));
  12433. } else {
  12434. throw new Error('KHR_techniques_webgl: no shader code');
  12435. }
  12436. });
  12437. programs.forEach(program => {
  12438. program.fragmentShader = shaders[program.fragmentShader];
  12439. program.vertexShader = shaders[program.vertexShader];
  12440. });
  12441. techniques.forEach(technique => {
  12442. technique.program = programs[technique.program];
  12443. });
  12444. return techniques;
  12445. }
  12446. function resolveValues(technique, gltfScenegraph) {
  12447. const values = Object.assign({}, technique.values);
  12448. Object.keys(technique.uniforms || {}).forEach(uniform => {
  12449. if (technique.uniforms[uniform].value && !(uniform in values)) {
  12450. values[uniform] = technique.uniforms[uniform].value;
  12451. }
  12452. });
  12453. Object.keys(values).forEach(uniform => {
  12454. if (typeof values[uniform] === 'object' && values[uniform].index !== undefined) {
  12455. values[uniform].texture = gltfScenegraph.getTexture(values[uniform].index);
  12456. }
  12457. });
  12458. return values;
  12459. }
  12460. var KHR_techniques_webgl = /*#__PURE__*/Object.freeze({
  12461. __proto__: null,
  12462. name: name,
  12463. decode: decode,
  12464. encode: encode
  12465. });
  12466. const EXTENSIONS = [EXT_meshopt_compression, EXT_texture_webp, KHR_texture_basisu, KHR_draco_mesh_compression, KHR_lights_punctual, KHR_materials_unlit, KHR_techniques_webgl];
  12467. function preprocessExtensions(gltf, options = {}, context) {
  12468. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12469. for (const extension of extensions) {
  12470. var _extension$preprocess;
  12471. (_extension$preprocess = extension.preprocess) === null || _extension$preprocess === void 0 ? void 0 : _extension$preprocess.call(extension, gltf, options, context);
  12472. }
  12473. }
  12474. async function decodeExtensions(gltf, options = {}, context) {
  12475. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12476. for (const extension of extensions) {
  12477. var _extension$decode;
  12478. await ((_extension$decode = extension.decode) === null || _extension$decode === void 0 ? void 0 : _extension$decode.call(extension, gltf, options, context));
  12479. }
  12480. }
  12481. function useExtension(extensionName, options) {
  12482. var _options$gltf;
  12483. const excludes = (options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.excludeExtensions) || {};
  12484. const exclude = extensionName in excludes && !excludes[extensionName];
  12485. return !exclude;
  12486. }
  12487. const KHR_BINARY_GLTF = 'KHR_binary_glTF';
  12488. function preprocess(gltfData) {
  12489. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12490. const {
  12491. json
  12492. } = gltfScenegraph;
  12493. for (const image of json.images || []) {
  12494. const extension = gltfScenegraph.getObjectExtension(image, KHR_BINARY_GLTF);
  12495. if (extension) {
  12496. Object.assign(image, extension);
  12497. }
  12498. gltfScenegraph.removeObjectExtension(image, KHR_BINARY_GLTF);
  12499. }
  12500. if (json.buffers && json.buffers[0]) {
  12501. delete json.buffers[0].uri;
  12502. }
  12503. gltfScenegraph.removeExtension(KHR_BINARY_GLTF);
  12504. }
  12505. const GLTF_ARRAYS = {
  12506. accessors: 'accessor',
  12507. animations: 'animation',
  12508. buffers: 'buffer',
  12509. bufferViews: 'bufferView',
  12510. images: 'image',
  12511. materials: 'material',
  12512. meshes: 'mesh',
  12513. nodes: 'node',
  12514. samplers: 'sampler',
  12515. scenes: 'scene',
  12516. skins: 'skin',
  12517. textures: 'texture'
  12518. };
  12519. const GLTF_KEYS = {
  12520. accessor: 'accessors',
  12521. animations: 'animation',
  12522. buffer: 'buffers',
  12523. bufferView: 'bufferViews',
  12524. image: 'images',
  12525. material: 'materials',
  12526. mesh: 'meshes',
  12527. node: 'nodes',
  12528. sampler: 'samplers',
  12529. scene: 'scenes',
  12530. skin: 'skins',
  12531. texture: 'textures'
  12532. };
  12533. class GLTFV1Normalizer {
  12534. constructor() {
  12535. _defineProperty(this, "idToIndexMap", {
  12536. animations: {},
  12537. accessors: {},
  12538. buffers: {},
  12539. bufferViews: {},
  12540. images: {},
  12541. materials: {},
  12542. meshes: {},
  12543. nodes: {},
  12544. samplers: {},
  12545. scenes: {},
  12546. skins: {},
  12547. textures: {}
  12548. });
  12549. _defineProperty(this, "json", void 0);
  12550. }
  12551. normalize(gltf, options) {
  12552. this.json = gltf.json;
  12553. const json = gltf.json;
  12554. switch (json.asset && json.asset.version) {
  12555. case '2.0':
  12556. return;
  12557. case undefined:
  12558. case '1.0':
  12559. break;
  12560. default:
  12561. console.warn("glTF: Unknown version ".concat(json.asset.version));
  12562. return;
  12563. }
  12564. if (!options.normalize) {
  12565. throw new Error('glTF v1 is not supported.');
  12566. }
  12567. console.warn('Converting glTF v1 to glTF v2 format. This is experimental and may fail.');
  12568. this._addAsset(json);
  12569. this._convertTopLevelObjectsToArrays(json);
  12570. preprocess(gltf);
  12571. this._convertObjectIdsToArrayIndices(json);
  12572. this._updateObjects(json);
  12573. this._updateMaterial(json);
  12574. }
  12575. _addAsset(json) {
  12576. json.asset = json.asset || {};
  12577. json.asset.version = '2.0';
  12578. json.asset.generator = json.asset.generator || 'Normalized to glTF 2.0 by loaders.gl';
  12579. }
  12580. _convertTopLevelObjectsToArrays(json) {
  12581. for (const arrayName in GLTF_ARRAYS) {
  12582. this._convertTopLevelObjectToArray(json, arrayName);
  12583. }
  12584. }
  12585. _convertTopLevelObjectToArray(json, mapName) {
  12586. const objectMap = json[mapName];
  12587. if (!objectMap || Array.isArray(objectMap)) {
  12588. return;
  12589. }
  12590. json[mapName] = [];
  12591. for (const id in objectMap) {
  12592. const object = objectMap[id];
  12593. object.id = object.id || id;
  12594. const index = json[mapName].length;
  12595. json[mapName].push(object);
  12596. this.idToIndexMap[mapName][id] = index;
  12597. }
  12598. }
  12599. _convertObjectIdsToArrayIndices(json) {
  12600. for (const arrayName in GLTF_ARRAYS) {
  12601. this._convertIdsToIndices(json, arrayName);
  12602. }
  12603. if ('scene' in json) {
  12604. json.scene = this._convertIdToIndex(json.scene, 'scene');
  12605. }
  12606. for (const texture of json.textures) {
  12607. this._convertTextureIds(texture);
  12608. }
  12609. for (const mesh of json.meshes) {
  12610. this._convertMeshIds(mesh);
  12611. }
  12612. for (const node of json.nodes) {
  12613. this._convertNodeIds(node);
  12614. }
  12615. for (const node of json.scenes) {
  12616. this._convertSceneIds(node);
  12617. }
  12618. }
  12619. _convertTextureIds(texture) {
  12620. if (texture.source) {
  12621. texture.source = this._convertIdToIndex(texture.source, 'image');
  12622. }
  12623. }
  12624. _convertMeshIds(mesh) {
  12625. for (const primitive of mesh.primitives) {
  12626. const {
  12627. attributes,
  12628. indices,
  12629. material
  12630. } = primitive;
  12631. for (const attributeName in attributes) {
  12632. attributes[attributeName] = this._convertIdToIndex(attributes[attributeName], 'accessor');
  12633. }
  12634. if (indices) {
  12635. primitive.indices = this._convertIdToIndex(indices, 'accessor');
  12636. }
  12637. if (material) {
  12638. primitive.material = this._convertIdToIndex(material, 'material');
  12639. }
  12640. }
  12641. }
  12642. _convertNodeIds(node) {
  12643. if (node.children) {
  12644. node.children = node.children.map(child => this._convertIdToIndex(child, 'node'));
  12645. }
  12646. if (node.meshes) {
  12647. node.meshes = node.meshes.map(mesh => this._convertIdToIndex(mesh, 'mesh'));
  12648. }
  12649. }
  12650. _convertSceneIds(scene) {
  12651. if (scene.nodes) {
  12652. scene.nodes = scene.nodes.map(node => this._convertIdToIndex(node, 'node'));
  12653. }
  12654. }
  12655. _convertIdsToIndices(json, topLevelArrayName) {
  12656. if (!json[topLevelArrayName]) {
  12657. console.warn("gltf v1: json doesn't contain attribute ".concat(topLevelArrayName));
  12658. json[topLevelArrayName] = [];
  12659. }
  12660. for (const object of json[topLevelArrayName]) {
  12661. for (const key in object) {
  12662. const id = object[key];
  12663. const index = this._convertIdToIndex(id, key);
  12664. object[key] = index;
  12665. }
  12666. }
  12667. }
  12668. _convertIdToIndex(id, key) {
  12669. const arrayName = GLTF_KEYS[key];
  12670. if (arrayName in this.idToIndexMap) {
  12671. const index = this.idToIndexMap[arrayName][id];
  12672. if (!Number.isFinite(index)) {
  12673. throw new Error("gltf v1: failed to resolve ".concat(key, " with id ").concat(id));
  12674. }
  12675. return index;
  12676. }
  12677. return id;
  12678. }
  12679. _updateObjects(json) {
  12680. for (const buffer of this.json.buffers) {
  12681. delete buffer.type;
  12682. }
  12683. }
  12684. _updateMaterial(json) {
  12685. for (const material of json.materials) {
  12686. material.pbrMetallicRoughness = {
  12687. baseColorFactor: [1, 1, 1, 1],
  12688. metallicFactor: 1,
  12689. roughnessFactor: 1
  12690. };
  12691. const textureId = material.values && material.values.tex;
  12692. const textureIndex = json.textures.findIndex(texture => texture.id === textureId);
  12693. if (textureIndex !== -1) {
  12694. material.pbrMetallicRoughness.baseColorTexture = {
  12695. index: textureIndex
  12696. };
  12697. }
  12698. }
  12699. }
  12700. }
  12701. function normalizeGLTFV1(gltf, options = {}) {
  12702. return new GLTFV1Normalizer().normalize(gltf, options);
  12703. }
  12704. const COMPONENTS = {
  12705. SCALAR: 1,
  12706. VEC2: 2,
  12707. VEC3: 3,
  12708. VEC4: 4,
  12709. MAT2: 4,
  12710. MAT3: 9,
  12711. MAT4: 16
  12712. };
  12713. const BYTES = {
  12714. 5120: 1,
  12715. 5121: 1,
  12716. 5122: 2,
  12717. 5123: 2,
  12718. 5125: 4,
  12719. 5126: 4
  12720. };
  12721. const GL_SAMPLER = {
  12722. TEXTURE_MAG_FILTER: 0x2800,
  12723. TEXTURE_MIN_FILTER: 0x2801,
  12724. TEXTURE_WRAP_S: 0x2802,
  12725. TEXTURE_WRAP_T: 0x2803,
  12726. REPEAT: 0x2901,
  12727. LINEAR: 0x2601,
  12728. NEAREST_MIPMAP_LINEAR: 0x2702
  12729. };
  12730. const SAMPLER_PARAMETER_GLTF_TO_GL = {
  12731. magFilter: GL_SAMPLER.TEXTURE_MAG_FILTER,
  12732. minFilter: GL_SAMPLER.TEXTURE_MIN_FILTER,
  12733. wrapS: GL_SAMPLER.TEXTURE_WRAP_S,
  12734. wrapT: GL_SAMPLER.TEXTURE_WRAP_T
  12735. };
  12736. const DEFAULT_SAMPLER = {
  12737. [GL_SAMPLER.TEXTURE_MAG_FILTER]: GL_SAMPLER.LINEAR,
  12738. [GL_SAMPLER.TEXTURE_MIN_FILTER]: GL_SAMPLER.NEAREST_MIPMAP_LINEAR,
  12739. [GL_SAMPLER.TEXTURE_WRAP_S]: GL_SAMPLER.REPEAT,
  12740. [GL_SAMPLER.TEXTURE_WRAP_T]: GL_SAMPLER.REPEAT
  12741. };
  12742. function getBytesFromComponentType(componentType) {
  12743. return BYTES[componentType];
  12744. }
  12745. function getSizeFromAccessorType(type) {
  12746. return COMPONENTS[type];
  12747. }
  12748. class GLTFPostProcessor {
  12749. constructor() {
  12750. _defineProperty(this, "baseUri", '');
  12751. _defineProperty(this, "json", {});
  12752. _defineProperty(this, "buffers", []);
  12753. _defineProperty(this, "images", []);
  12754. }
  12755. postProcess(gltf, options = {}) {
  12756. const {
  12757. json,
  12758. buffers = [],
  12759. images = [],
  12760. baseUri = ''
  12761. } = gltf;
  12762. assert$1(json);
  12763. this.baseUri = baseUri;
  12764. this.json = json;
  12765. this.buffers = buffers;
  12766. this.images = images;
  12767. this._resolveTree(this.json, options);
  12768. return this.json;
  12769. }
  12770. _resolveTree(json, options = {}) {
  12771. if (json.bufferViews) {
  12772. json.bufferViews = json.bufferViews.map((bufView, i) => this._resolveBufferView(bufView, i));
  12773. }
  12774. if (json.images) {
  12775. json.images = json.images.map((image, i) => this._resolveImage(image, i));
  12776. }
  12777. if (json.samplers) {
  12778. json.samplers = json.samplers.map((sampler, i) => this._resolveSampler(sampler, i));
  12779. }
  12780. if (json.textures) {
  12781. json.textures = json.textures.map((texture, i) => this._resolveTexture(texture, i));
  12782. }
  12783. if (json.accessors) {
  12784. json.accessors = json.accessors.map((accessor, i) => this._resolveAccessor(accessor, i));
  12785. }
  12786. if (json.materials) {
  12787. json.materials = json.materials.map((material, i) => this._resolveMaterial(material, i));
  12788. }
  12789. if (json.meshes) {
  12790. json.meshes = json.meshes.map((mesh, i) => this._resolveMesh(mesh, i));
  12791. }
  12792. if (json.nodes) {
  12793. json.nodes = json.nodes.map((node, i) => this._resolveNode(node, i));
  12794. }
  12795. if (json.skins) {
  12796. json.skins = json.skins.map((skin, i) => this._resolveSkin(skin, i));
  12797. }
  12798. if (json.scenes) {
  12799. json.scenes = json.scenes.map((scene, i) => this._resolveScene(scene, i));
  12800. }
  12801. if (json.scene !== undefined) {
  12802. json.scene = json.scenes[this.json.scene];
  12803. }
  12804. }
  12805. getScene(index) {
  12806. return this._get('scenes', index);
  12807. }
  12808. getNode(index) {
  12809. return this._get('nodes', index);
  12810. }
  12811. getSkin(index) {
  12812. return this._get('skins', index);
  12813. }
  12814. getMesh(index) {
  12815. return this._get('meshes', index);
  12816. }
  12817. getMaterial(index) {
  12818. return this._get('materials', index);
  12819. }
  12820. getAccessor(index) {
  12821. return this._get('accessors', index);
  12822. }
  12823. getCamera(index) {
  12824. return null;
  12825. }
  12826. getTexture(index) {
  12827. return this._get('textures', index);
  12828. }
  12829. getSampler(index) {
  12830. return this._get('samplers', index);
  12831. }
  12832. getImage(index) {
  12833. return this._get('images', index);
  12834. }
  12835. getBufferView(index) {
  12836. return this._get('bufferViews', index);
  12837. }
  12838. getBuffer(index) {
  12839. return this._get('buffers', index);
  12840. }
  12841. _get(array, index) {
  12842. if (typeof index === 'object') {
  12843. return index;
  12844. }
  12845. const object = this.json[array] && this.json[array][index];
  12846. if (!object) {
  12847. console.warn("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  12848. }
  12849. return object;
  12850. }
  12851. _resolveScene(scene, index) {
  12852. scene.id = scene.id || "scene-".concat(index);
  12853. scene.nodes = (scene.nodes || []).map(node => this.getNode(node));
  12854. return scene;
  12855. }
  12856. _resolveNode(node, index) {
  12857. node.id = node.id || "node-".concat(index);
  12858. if (node.children) {
  12859. node.children = node.children.map(child => this.getNode(child));
  12860. }
  12861. if (node.mesh !== undefined) {
  12862. node.mesh = this.getMesh(node.mesh);
  12863. } else if (node.meshes !== undefined && node.meshes.length) {
  12864. node.mesh = node.meshes.reduce((accum, meshIndex) => {
  12865. const mesh = this.getMesh(meshIndex);
  12866. accum.id = mesh.id;
  12867. accum.primitives = accum.primitives.concat(mesh.primitives);
  12868. return accum;
  12869. }, {
  12870. primitives: []
  12871. });
  12872. }
  12873. if (node.camera !== undefined) {
  12874. node.camera = this.getCamera(node.camera);
  12875. }
  12876. if (node.skin !== undefined) {
  12877. node.skin = this.getSkin(node.skin);
  12878. }
  12879. return node;
  12880. }
  12881. _resolveSkin(skin, index) {
  12882. skin.id = skin.id || "skin-".concat(index);
  12883. skin.inverseBindMatrices = this.getAccessor(skin.inverseBindMatrices);
  12884. return skin;
  12885. }
  12886. _resolveMesh(mesh, index) {
  12887. mesh.id = mesh.id || "mesh-".concat(index);
  12888. if (mesh.primitives) {
  12889. mesh.primitives = mesh.primitives.map(primitive => {
  12890. primitive = { ...primitive
  12891. };
  12892. const attributes = primitive.attributes;
  12893. primitive.attributes = {};
  12894. for (const attribute in attributes) {
  12895. primitive.attributes[attribute] = this.getAccessor(attributes[attribute]);
  12896. }
  12897. if (primitive.indices !== undefined) {
  12898. primitive.indices = this.getAccessor(primitive.indices);
  12899. }
  12900. if (primitive.material !== undefined) {
  12901. primitive.material = this.getMaterial(primitive.material);
  12902. }
  12903. return primitive;
  12904. });
  12905. }
  12906. return mesh;
  12907. }
  12908. _resolveMaterial(material, index) {
  12909. material.id = material.id || "material-".concat(index);
  12910. if (material.normalTexture) {
  12911. material.normalTexture = { ...material.normalTexture
  12912. };
  12913. material.normalTexture.texture = this.getTexture(material.normalTexture.index);
  12914. }
  12915. if (material.occlusionTexture) {
  12916. material.occlustionTexture = { ...material.occlustionTexture
  12917. };
  12918. material.occlusionTexture.texture = this.getTexture(material.occlusionTexture.index);
  12919. }
  12920. if (material.emissiveTexture) {
  12921. material.emmisiveTexture = { ...material.emmisiveTexture
  12922. };
  12923. material.emissiveTexture.texture = this.getTexture(material.emissiveTexture.index);
  12924. }
  12925. if (!material.emissiveFactor) {
  12926. material.emissiveFactor = material.emmisiveTexture ? [1, 1, 1] : [0, 0, 0];
  12927. }
  12928. if (material.pbrMetallicRoughness) {
  12929. material.pbrMetallicRoughness = { ...material.pbrMetallicRoughness
  12930. };
  12931. const mr = material.pbrMetallicRoughness;
  12932. if (mr.baseColorTexture) {
  12933. mr.baseColorTexture = { ...mr.baseColorTexture
  12934. };
  12935. mr.baseColorTexture.texture = this.getTexture(mr.baseColorTexture.index);
  12936. }
  12937. if (mr.metallicRoughnessTexture) {
  12938. mr.metallicRoughnessTexture = { ...mr.metallicRoughnessTexture
  12939. };
  12940. mr.metallicRoughnessTexture.texture = this.getTexture(mr.metallicRoughnessTexture.index);
  12941. }
  12942. }
  12943. return material;
  12944. }
  12945. _resolveAccessor(accessor, index) {
  12946. accessor.id = accessor.id || "accessor-".concat(index);
  12947. if (accessor.bufferView !== undefined) {
  12948. accessor.bufferView = this.getBufferView(accessor.bufferView);
  12949. }
  12950. accessor.bytesPerComponent = getBytesFromComponentType(accessor.componentType);
  12951. accessor.components = getSizeFromAccessorType(accessor.type);
  12952. accessor.bytesPerElement = accessor.bytesPerComponent * accessor.components;
  12953. if (accessor.bufferView) {
  12954. const buffer = accessor.bufferView.buffer;
  12955. const {
  12956. ArrayType,
  12957. byteLength
  12958. } = getAccessorArrayTypeAndLength(accessor, accessor.bufferView);
  12959. const byteOffset = (accessor.bufferView.byteOffset || 0) + (accessor.byteOffset || 0) + buffer.byteOffset;
  12960. let cutBuffer = buffer.arrayBuffer.slice(byteOffset, byteOffset + byteLength);
  12961. if (accessor.bufferView.byteStride) {
  12962. cutBuffer = this._getValueFromInterleavedBuffer(buffer, byteOffset, accessor.bufferView.byteStride, accessor.bytesPerElement, accessor.count);
  12963. }
  12964. accessor.value = new ArrayType(cutBuffer);
  12965. }
  12966. return accessor;
  12967. }
  12968. _getValueFromInterleavedBuffer(buffer, byteOffset, byteStride, bytesPerElement, count) {
  12969. const result = new Uint8Array(count * bytesPerElement);
  12970. for (let i = 0; i < count; i++) {
  12971. const elementOffset = byteOffset + i * byteStride;
  12972. result.set(new Uint8Array(buffer.arrayBuffer.slice(elementOffset, elementOffset + bytesPerElement)), i * bytesPerElement);
  12973. }
  12974. return result.buffer;
  12975. }
  12976. _resolveTexture(texture, index) {
  12977. texture.id = texture.id || "texture-".concat(index);
  12978. texture.sampler = 'sampler' in texture ? this.getSampler(texture.sampler) : DEFAULT_SAMPLER;
  12979. texture.source = this.getImage(texture.source);
  12980. return texture;
  12981. }
  12982. _resolveSampler(sampler, index) {
  12983. sampler.id = sampler.id || "sampler-".concat(index);
  12984. sampler.parameters = {};
  12985. for (const key in sampler) {
  12986. const glEnum = this._enumSamplerParameter(key);
  12987. if (glEnum !== undefined) {
  12988. sampler.parameters[glEnum] = sampler[key];
  12989. }
  12990. }
  12991. return sampler;
  12992. }
  12993. _enumSamplerParameter(key) {
  12994. return SAMPLER_PARAMETER_GLTF_TO_GL[key];
  12995. }
  12996. _resolveImage(image, index) {
  12997. image.id = image.id || "image-".concat(index);
  12998. if (image.bufferView !== undefined) {
  12999. image.bufferView = this.getBufferView(image.bufferView);
  13000. }
  13001. const preloadedImage = this.images[index];
  13002. if (preloadedImage) {
  13003. image.image = preloadedImage;
  13004. }
  13005. return image;
  13006. }
  13007. _resolveBufferView(bufferView, index) {
  13008. const bufferIndex = bufferView.buffer;
  13009. const result = {
  13010. id: "bufferView-".concat(index),
  13011. ...bufferView,
  13012. buffer: this.buffers[bufferIndex]
  13013. };
  13014. const arrayBuffer = this.buffers[bufferIndex].arrayBuffer;
  13015. let byteOffset = this.buffers[bufferIndex].byteOffset || 0;
  13016. if ('byteOffset' in bufferView) {
  13017. byteOffset += bufferView.byteOffset;
  13018. }
  13019. result.data = new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  13020. return result;
  13021. }
  13022. _resolveCamera(camera, index) {
  13023. camera.id = camera.id || "camera-".concat(index);
  13024. if (camera.perspective) ;
  13025. if (camera.orthographic) ;
  13026. return camera;
  13027. }
  13028. }
  13029. function postProcessGLTF(gltf, options) {
  13030. return new GLTFPostProcessor().postProcess(gltf, options);
  13031. }
  13032. const MAGIC_glTF = 0x676c5446;
  13033. const GLB_FILE_HEADER_SIZE = 12;
  13034. const GLB_CHUNK_HEADER_SIZE = 8;
  13035. const GLB_CHUNK_TYPE_JSON = 0x4e4f534a;
  13036. const GLB_CHUNK_TYPE_BIN = 0x004e4942;
  13037. const GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED = 0;
  13038. const GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED = 1;
  13039. const GLB_V1_CONTENT_FORMAT_JSON = 0x0;
  13040. const LE = true;
  13041. function getMagicString(dataView, byteOffset = 0) {
  13042. 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)));
  13043. }
  13044. function isGLB(arrayBuffer, byteOffset = 0, options = {}) {
  13045. const dataView = new DataView(arrayBuffer);
  13046. const {
  13047. magic = MAGIC_glTF
  13048. } = options;
  13049. const magic1 = dataView.getUint32(byteOffset, false);
  13050. return magic1 === magic || magic1 === MAGIC_glTF;
  13051. }
  13052. function parseGLBSync(glb, arrayBuffer, byteOffset = 0, options = {}) {
  13053. const dataView = new DataView(arrayBuffer);
  13054. const type = getMagicString(dataView, byteOffset + 0);
  13055. const version = dataView.getUint32(byteOffset + 4, LE);
  13056. const byteLength = dataView.getUint32(byteOffset + 8, LE);
  13057. Object.assign(glb, {
  13058. header: {
  13059. byteOffset,
  13060. byteLength,
  13061. hasBinChunk: false
  13062. },
  13063. type,
  13064. version,
  13065. json: {},
  13066. binChunks: []
  13067. });
  13068. byteOffset += GLB_FILE_HEADER_SIZE;
  13069. switch (glb.version) {
  13070. case 1:
  13071. return parseGLBV1(glb, dataView, byteOffset);
  13072. case 2:
  13073. return parseGLBV2(glb, dataView, byteOffset, options = {});
  13074. default:
  13075. throw new Error("Invalid GLB version ".concat(glb.version, ". Only supports v1 and v2."));
  13076. }
  13077. }
  13078. function parseGLBV1(glb, dataView, byteOffset) {
  13079. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  13080. const contentLength = dataView.getUint32(byteOffset + 0, LE);
  13081. const contentFormat = dataView.getUint32(byteOffset + 4, LE);
  13082. byteOffset += GLB_CHUNK_HEADER_SIZE;
  13083. assert$7(contentFormat === GLB_V1_CONTENT_FORMAT_JSON);
  13084. parseJSONChunk(glb, dataView, byteOffset, contentLength);
  13085. byteOffset += contentLength;
  13086. byteOffset += parseBINChunk(glb, dataView, byteOffset, glb.header.byteLength);
  13087. return byteOffset;
  13088. }
  13089. function parseGLBV2(glb, dataView, byteOffset, options) {
  13090. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  13091. parseGLBChunksSync(glb, dataView, byteOffset, options);
  13092. return byteOffset + glb.header.byteLength;
  13093. }
  13094. function parseGLBChunksSync(glb, dataView, byteOffset, options) {
  13095. while (byteOffset + 8 <= glb.header.byteLength) {
  13096. const chunkLength = dataView.getUint32(byteOffset + 0, LE);
  13097. const chunkFormat = dataView.getUint32(byteOffset + 4, LE);
  13098. byteOffset += GLB_CHUNK_HEADER_SIZE;
  13099. switch (chunkFormat) {
  13100. case GLB_CHUNK_TYPE_JSON:
  13101. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  13102. break;
  13103. case GLB_CHUNK_TYPE_BIN:
  13104. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  13105. break;
  13106. case GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED:
  13107. if (!options.strict) {
  13108. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  13109. }
  13110. break;
  13111. case GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED:
  13112. if (!options.strict) {
  13113. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  13114. }
  13115. break;
  13116. }
  13117. byteOffset += padToNBytes(chunkLength, 4);
  13118. }
  13119. return byteOffset;
  13120. }
  13121. function parseJSONChunk(glb, dataView, byteOffset, chunkLength) {
  13122. const jsonChunk = new Uint8Array(dataView.buffer, byteOffset, chunkLength);
  13123. const textDecoder = new TextDecoder('utf8');
  13124. const jsonText = textDecoder.decode(jsonChunk);
  13125. glb.json = JSON.parse(jsonText);
  13126. return padToNBytes(chunkLength, 4);
  13127. }
  13128. function parseBINChunk(glb, dataView, byteOffset, chunkLength) {
  13129. glb.header.hasBinChunk = true;
  13130. glb.binChunks.push({
  13131. byteOffset,
  13132. byteLength: chunkLength,
  13133. arrayBuffer: dataView.buffer
  13134. });
  13135. return padToNBytes(chunkLength, 4);
  13136. }
  13137. async function parseGLTF(gltf, arrayBufferOrString, byteOffset = 0, options, context) {
  13138. var _options$gltf, _options$gltf2, _options$gltf3, _options$gltf4;
  13139. parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
  13140. normalizeGLTFV1(gltf, {
  13141. normalize: options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.normalize
  13142. });
  13143. preprocessExtensions(gltf, options, context);
  13144. const promises = [];
  13145. if (options !== null && options !== void 0 && (_options$gltf2 = options.gltf) !== null && _options$gltf2 !== void 0 && _options$gltf2.loadBuffers && gltf.json.buffers) {
  13146. await loadBuffers(gltf, options, context);
  13147. }
  13148. if (options !== null && options !== void 0 && (_options$gltf3 = options.gltf) !== null && _options$gltf3 !== void 0 && _options$gltf3.loadImages) {
  13149. const promise = loadImages(gltf, options, context);
  13150. promises.push(promise);
  13151. }
  13152. const promise = decodeExtensions(gltf, options, context);
  13153. promises.push(promise);
  13154. await Promise.all(promises);
  13155. gltf.json.gltfArrayBuffer = arrayBufferOrString // !zeg add 兼容gltf
  13156. return options !== null && options !== void 0 && (_options$gltf4 = options.gltf) !== null && _options$gltf4 !== void 0 && _options$gltf4.postProcess ? postProcessGLTF(gltf, options) : gltf;
  13157. }
  13158. function parseGLTFContainerSync(gltf, data, byteOffset, options) {
  13159. if (options.uri) {
  13160. gltf.baseUri = options.uri;
  13161. }
  13162. if (data instanceof ArrayBuffer && !isGLB(data, byteOffset, options)) {
  13163. const textDecoder = new TextDecoder();
  13164. data = textDecoder.decode(data);
  13165. }
  13166. if (typeof data === 'string') {
  13167. gltf.json = parseJSON(data);
  13168. } else if (data instanceof ArrayBuffer) {
  13169. const glb = {};
  13170. byteOffset = parseGLBSync(glb, data, byteOffset, options.glb);
  13171. assert$1(glb.type === 'glTF', "Invalid GLB magic string ".concat(glb.type));
  13172. gltf._glb = glb;
  13173. gltf.json = glb.json;
  13174. } else {
  13175. assert$1(false, 'GLTF: must be ArrayBuffer or string');
  13176. }
  13177. const buffers = gltf.json.buffers || [];
  13178. gltf.buffers = new Array(buffers.length).fill(null);
  13179. if (gltf._glb && gltf._glb.header.hasBinChunk) {
  13180. const {
  13181. binChunks
  13182. } = gltf._glb;
  13183. gltf.buffers[0] = {
  13184. arrayBuffer: binChunks[0].arrayBuffer,
  13185. byteOffset: binChunks[0].byteOffset,
  13186. byteLength: binChunks[0].byteLength
  13187. };
  13188. }
  13189. const images = gltf.json.images || [];
  13190. gltf.images = new Array(images.length).fill({});
  13191. }
  13192. async function loadBuffers(gltf, options, context) {
  13193. const buffers = gltf.json.buffers || [];
  13194. for (let i = 0; i < buffers.length; ++i) {
  13195. const buffer = buffers[i];
  13196. if (buffer.uri) {
  13197. var _context$fetch, _response$arrayBuffer;
  13198. const {
  13199. fetch
  13200. } = context;
  13201. assert$1(fetch);
  13202. const uri = resolveUrl(buffer.uri, options);
  13203. 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));
  13204. 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));
  13205. gltf.buffers[i] = {
  13206. arrayBuffer,
  13207. byteOffset: 0,
  13208. byteLength: arrayBuffer.byteLength
  13209. };
  13210. delete buffer.uri;
  13211. }
  13212. }
  13213. }
  13214. async function loadImages(gltf, options, context) {
  13215. const imageIndices = getReferencesImageIndices(gltf);
  13216. const images = gltf.json.images || [];
  13217. const promises = [];
  13218. for (const imageIndex of imageIndices) {
  13219. promises.push(loadImage(gltf, images[imageIndex], imageIndex, options, context));
  13220. }
  13221. return await Promise.all(promises);
  13222. }
  13223. function getReferencesImageIndices(gltf) {
  13224. const imageIndices = new Set();
  13225. const textures = gltf.json.textures || [];
  13226. for (const texture of textures) {
  13227. if (texture.source !== undefined) {
  13228. imageIndices.add(texture.source);
  13229. }
  13230. }
  13231. return Array.from(imageIndices).sort();
  13232. }
  13233. async function loadImage(gltf, image, index, options, context) {
  13234. const {
  13235. fetch,
  13236. parse
  13237. } = context;
  13238. let arrayBuffer;
  13239. if (image.uri) {
  13240. const uri = resolveUrl(image.uri, options);
  13241. const response = await fetch(uri);
  13242. arrayBuffer = await response.arrayBuffer();
  13243. }
  13244. if (Number.isFinite(image.bufferView)) {
  13245. const array = getTypedArrayForBufferView(gltf.json, gltf.buffers, image.bufferView);
  13246. arrayBuffer = sliceArrayBuffer(array.buffer, array.byteOffset, array.byteLength);
  13247. }
  13248. assert$1(arrayBuffer, 'glTF image has no data');
  13249. let parsedImage = await parse(arrayBuffer, [ImageLoader, BasisLoader], {
  13250. mimeType: image.mimeType,
  13251. basis: options.basis || {
  13252. format: selectSupportedBasisFormat()
  13253. }
  13254. }, context);
  13255. if (parsedImage && parsedImage[0]) {
  13256. parsedImage = {
  13257. compressed: true,
  13258. mipmaps: false,
  13259. width: parsedImage[0].width,
  13260. height: parsedImage[0].height,
  13261. data: parsedImage
  13262. };
  13263. }
  13264. gltf.images = gltf.images || [];
  13265. gltf.images[index] = parsedImage;
  13266. }
  13267. const GLTFLoader = {
  13268. name: 'glTF',
  13269. id: 'gltf',
  13270. module: 'gltf',
  13271. version: VERSION$3,
  13272. extensions: ['gltf', 'glb'],
  13273. mimeTypes: ['model/gltf+json', 'model/gltf-binary'],
  13274. text: true,
  13275. binary: true,
  13276. tests: ['glTF'],
  13277. parse: parse$1,
  13278. options: {
  13279. gltf: {
  13280. normalize: true,
  13281. loadBuffers: true,
  13282. loadImages: true,
  13283. decompressMeshes: true,
  13284. postProcess: true
  13285. },
  13286. log: console
  13287. },
  13288. deprecatedOptions: {
  13289. fetchImages: 'gltf.loadImages',
  13290. createImages: 'gltf.loadImages',
  13291. decompress: 'gltf.decompressMeshes',
  13292. postProcess: 'gltf.postProcess',
  13293. gltf: {
  13294. decompress: 'gltf.decompressMeshes'
  13295. }
  13296. }
  13297. };
  13298. async function parse$1(arrayBuffer, options = {}, context) {
  13299. options = { ...GLTFLoader.options,
  13300. ...options
  13301. };
  13302. options.gltf = { ...GLTFLoader.options.gltf,
  13303. ...options.gltf
  13304. };
  13305. const {
  13306. byteOffset = 0
  13307. } = options;
  13308. const gltf = {};
  13309. return await parseGLTF(gltf, arrayBuffer, byteOffset, options, context);
  13310. }
  13311. const GLTF_FORMAT = {
  13312. URI: 0,
  13313. EMBEDDED: 1
  13314. };
  13315. function parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options) {
  13316. tile.rotateYtoZ = true;
  13317. const gltfByteLength = tile.byteOffset + tile.byteLength - byteOffset;
  13318. if (gltfByteLength === 0) {
  13319. throw new Error('glTF byte length must be greater than 0.');
  13320. }
  13321. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13322. tile.gltfArrayBuffer = sliceArrayBuffer(arrayBuffer, byteOffset, gltfByteLength);
  13323. tile.gltfByteOffset = 0;
  13324. tile.gltfByteLength = gltfByteLength;
  13325. if (byteOffset % 4 === 0) ; else {
  13326. console.warn("".concat(tile.type, ": embedded glb is not aligned to a 4-byte boundary."));
  13327. }
  13328. return tile.byteOffset + tile.byteLength;
  13329. }
  13330. async function extractGLTF(tile, gltfFormat, options, context) {
  13331. const tile3DOptions = options['3d-tiles'] || {};
  13332. extractGLTFBufferOrURL(tile, gltfFormat);
  13333. if (tile3DOptions.loadGLTF) {
  13334. const {
  13335. parse,
  13336. fetch
  13337. } = context;
  13338. if (tile.gltfUrl) {
  13339. tile.gltfArrayBuffer = await fetch(tile.gltfUrl, options);
  13340. tile.gltfByteOffset = 0;
  13341. }
  13342. if (tile.gltfArrayBuffer) {
  13343. tile.gltf = await parse(tile.gltfArrayBuffer, GLTFLoader, options, context);
  13344. delete tile.gltfArrayBuffer;
  13345. delete tile.gltfByteOffset;
  13346. delete tile.gltfByteLength;
  13347. }
  13348. }
  13349. }
  13350. function extractGLTFBufferOrURL(tile, gltfFormat, options) {
  13351. switch (gltfFormat) {
  13352. case GLTF_FORMAT.URI:
  13353. const gltfUrlBytes = new Uint8Array(tile.gltfArrayBuffer, tile.gltfByteOffset);
  13354. const textDecoder = new TextDecoder();
  13355. const gltfUrl = textDecoder.decode(gltfUrlBytes);
  13356. tile.gltfUrl = gltfUrl.replace(/[\s\0]+$/, '');
  13357. delete tile.gltfArrayBuffer;
  13358. delete tile.gltfByteOffset;
  13359. delete tile.gltfByteLength;
  13360. break;
  13361. case GLTF_FORMAT.EMBEDDED:
  13362. break;
  13363. default:
  13364. throw new Error('b3dm: Illegal glTF format field');
  13365. }
  13366. }
  13367. async function parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13368. var _tile$gltf;
  13369. byteOffset = parseBatchedModel(tile, arrayBuffer, byteOffset, options);
  13370. await extractGLTF(tile, GLTF_FORMAT.EMBEDDED, options, context);
  13371. const extensions = tile === null || tile === void 0 ? void 0 : (_tile$gltf = tile.gltf) === null || _tile$gltf === void 0 ? void 0 : _tile$gltf.extensions;
  13372. if (extensions && extensions.CESIUM_RTC) {
  13373. tile.rtcCenter = extensions.CESIUM_RTC.center;
  13374. }
  13375. return byteOffset;
  13376. }
  13377. function parseBatchedModel(tile, arrayBuffer, byteOffset, options, context) {
  13378. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13379. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13380. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13381. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13382. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13383. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13384. return byteOffset;
  13385. }
  13386. async function parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13387. byteOffset = parseInstancedModel(tile, arrayBuffer, byteOffset, options);
  13388. await extractGLTF(tile, tile.gltfFormat, options, context);
  13389. return byteOffset;
  13390. }
  13391. function parseInstancedModel(tile, arrayBuffer, byteOffset, options, context) {
  13392. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13393. if (tile.version !== 1) {
  13394. throw new Error("Instanced 3D Model version ".concat(tile.version, " is not supported"));
  13395. }
  13396. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13397. const view = new DataView(arrayBuffer);
  13398. tile.gltfFormat = view.getUint32(byteOffset, true);
  13399. byteOffset += 4;
  13400. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13401. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13402. if (tile.featureTableJsonByteLength === 0) {
  13403. throw new Error('i3dm parser: featureTableJsonByteLength is zero.');
  13404. }
  13405. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13406. const instancesLength = featureTable.getGlobalProperty('INSTANCES_LENGTH');
  13407. featureTable.featuresLength = instancesLength;
  13408. if (!Number.isFinite(instancesLength)) {
  13409. throw new Error('i3dm parser: INSTANCES_LENGTH must be defined');
  13410. }
  13411. tile.eastNorthUp = featureTable.getGlobalProperty('EAST_NORTH_UP');
  13412. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13413. const batchTable = new Tile3DBatchTableParser(tile.batchTableJson, tile.batchTableBinary, instancesLength);
  13414. extractInstancedAttributes(tile, featureTable, batchTable, instancesLength);
  13415. return byteOffset;
  13416. }
  13417. function extractInstancedAttributes(tile, featureTable, batchTable, instancesLength) {
  13418. const collectionOptions = {
  13419. instances: new Array(instancesLength),
  13420. batchTable: tile._batchTable,
  13421. cull: false,
  13422. url: undefined,
  13423. gltf: undefined,
  13424. basePath: undefined,
  13425. incrementallyLoadTextures: false,
  13426. forwardAxis: [1, 0, 0]
  13427. };
  13428. const instances = collectionOptions.instances;
  13429. const instancePosition = new Vector3();
  13430. new Vector3();
  13431. new Vector3();
  13432. new Vector3();
  13433. const instanceRotation = new Matrix3();
  13434. const instanceQuaternion = new Quaternion();
  13435. const instanceScale = new Vector3();
  13436. const instanceTranslationRotationScale = {};
  13437. const instanceTransform = new Matrix4();
  13438. const scratch1 = [];
  13439. const scratch2 = [];
  13440. const scratchVector1 = new Vector3();
  13441. const scratchVector2 = new Vector3();
  13442. for (let i = 0; i < instancesLength; i++) {
  13443. let position;
  13444. if (featureTable.hasProperty('POSITION')) {
  13445. position = featureTable.getProperty('POSITION', GL$1.FLOAT, 3, i, instancePosition);
  13446. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  13447. position = featureTable.getProperty('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3, i, instancePosition);
  13448. const quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3, scratchVector1);
  13449. if (!quantizedVolumeOffset) {
  13450. throw new Error('i3dm parser: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  13451. }
  13452. const quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3, scratchVector2);
  13453. if (!quantizedVolumeScale) {
  13454. throw new Error('i3dm parser: QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  13455. }
  13456. const MAX_UNSIGNED_SHORT = 65535.0;
  13457. for (let j = 0; j < 3; j++) {
  13458. position[j] = position[j] / MAX_UNSIGNED_SHORT * quantizedVolumeScale[j] + quantizedVolumeOffset[j];
  13459. }
  13460. }
  13461. if (!position) {
  13462. throw new Error('i3dm: POSITION or POSITION_QUANTIZED must be defined for each instance.');
  13463. }
  13464. instancePosition.copy(position);
  13465. instanceTranslationRotationScale.translation = instancePosition;
  13466. tile.normalUp = featureTable.getProperty('NORMAL_UP', GL$1.FLOAT, 3, i, scratch1);
  13467. tile.normalRight = featureTable.getProperty('NORMAL_RIGHT', GL$1.FLOAT, 3, i, scratch2);
  13468. if (tile.normalUp) {
  13469. if (!tile.normalRight) {
  13470. throw new Error('i3dm: Custom orientation requires both NORMAL_UP and NORMAL_RIGHT.');
  13471. }
  13472. tile.hasCustomOrientation = true;
  13473. } else {
  13474. tile.octNormalUp = featureTable.getProperty('NORMAL_UP_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch1);
  13475. tile.octNormalRight = featureTable.getProperty('NORMAL_RIGHT_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch2);
  13476. if (tile.octNormalUp) {
  13477. if (!tile.octNormalRight) {
  13478. throw new Error('i3dm: oct-encoded orientation requires NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P');
  13479. }
  13480. throw new Error('i3dm: oct-encoded orientation not implemented');
  13481. } else if (tile.eastNorthUp) {
  13482. Ellipsoid.WGS84.eastNorthUpToFixedFrame(instancePosition, instanceTransform);
  13483. instanceTransform.getRotationMatrix3(instanceRotation);
  13484. } else {
  13485. instanceRotation.identity();
  13486. }
  13487. }
  13488. instanceQuaternion.fromMatrix3(instanceRotation);
  13489. instanceTranslationRotationScale.rotation = instanceQuaternion;
  13490. instanceScale.set(1.0, 1.0, 1.0);
  13491. const scale = featureTable.getProperty('SCALE', GL$1.FLOAT, 1, i);
  13492. if (Number.isFinite(scale)) {
  13493. instanceScale.multiplyByScalar(scale);
  13494. }
  13495. const nonUniformScale = featureTable.getProperty('SCALE_NON_UNIFORM', GL$1.FLOAT, 3, i, scratch1);
  13496. if (nonUniformScale) {
  13497. instanceScale.scale(nonUniformScale);
  13498. }
  13499. instanceTranslationRotationScale.scale = instanceScale;
  13500. let batchId = featureTable.getProperty('BATCH_ID', GL$1.UNSIGNED_SHORT, 1, i);
  13501. if (batchId === undefined) {
  13502. batchId = i;
  13503. }
  13504. const rotationMatrix = new Matrix4().fromQuaternion(instanceTranslationRotationScale.rotation);
  13505. instanceTransform.identity();
  13506. instanceTransform.translate(instanceTranslationRotationScale.translation);
  13507. instanceTransform.multiplyRight(rotationMatrix);
  13508. instanceTransform.scale(instanceTranslationRotationScale.scale);
  13509. const modelMatrix = instanceTransform.clone();
  13510. instances[i] = {
  13511. modelMatrix,
  13512. batchId
  13513. };
  13514. }
  13515. tile.instances = instances;
  13516. }
  13517. async function parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile) {
  13518. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13519. const view = new DataView(arrayBuffer);
  13520. tile.tilesLength = view.getUint32(byteOffset, true);
  13521. byteOffset += 4;
  13522. tile.tiles = [];
  13523. while (tile.tiles.length < tile.tilesLength && tile.byteLength - byteOffset > 12) {
  13524. const subtile = {};
  13525. tile.tiles.push(subtile);
  13526. byteOffset = await parse3DTile(arrayBuffer, byteOffset, options, context, subtile);
  13527. }
  13528. return byteOffset;
  13529. }
  13530. async function parseGltf3DTile(tile, arrayBuffer, options, context) {
  13531. tile.rotateYtoZ = true;
  13532. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13533. const {
  13534. parse
  13535. } = context;
  13536. tile.gltf = await parse(arrayBuffer, GLTFLoader, options, context);
  13537. }
  13538. async function parse3DTile(arrayBuffer, byteOffset = 0, options, context, tile = {}) {
  13539. tile.byteOffset = byteOffset;
  13540. tile.type = getMagicString$1(arrayBuffer, byteOffset);
  13541. switch (tile.type) {
  13542. case TILE3D_TYPE.COMPOSITE:
  13543. return await parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile);
  13544. case TILE3D_TYPE.BATCHED_3D_MODEL:
  13545. return await parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13546. case TILE3D_TYPE.GLTF:
  13547. return await parseGltf3DTile(tile, arrayBuffer, options, context);
  13548. case TILE3D_TYPE.INSTANCED_3D_MODEL:
  13549. return await parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13550. case TILE3D_TYPE.POINT_CLOUD:
  13551. return await parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context);
  13552. default:
  13553. throw new Error("3DTileLoader: unknown type ".concat(tile.type));
  13554. }
  13555. }
  13556. const SUBTREE_FILE_MAGIC = 0x74627573;
  13557. const SUBTREE_FILE_VERSION = 1;
  13558. async function parse3DTilesSubtree(data) {
  13559. const magic = new Uint32Array(data.slice(0, 4));
  13560. if (magic[0] !== SUBTREE_FILE_MAGIC) {
  13561. throw new Error('Wrong subtree file magic number');
  13562. }
  13563. const version = new Uint32Array(data.slice(4, 8));
  13564. if (version[0] !== SUBTREE_FILE_VERSION) {
  13565. throw new Error('Wrong subtree file verson, must be 1');
  13566. }
  13567. const jsonByteLength = parseUint64Value(data.slice(8, 16));
  13568. const stringAttribute = new Uint8Array(data, 24, jsonByteLength);
  13569. const textDecoder = new TextDecoder('utf8');
  13570. const string = textDecoder.decode(stringAttribute);
  13571. const subtree = JSON.parse(string);
  13572. const binaryByteLength = parseUint64Value(data.slice(16, 24));
  13573. let internalBinaryBuffer = new ArrayBuffer(0);
  13574. if (binaryByteLength) {
  13575. internalBinaryBuffer = data.slice(24 + jsonByteLength);
  13576. }
  13577. if ('bufferView' in subtree.tileAvailability) {
  13578. subtree.tileAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'tileAvailability', internalBinaryBuffer);
  13579. }
  13580. if ('bufferView' in subtree.contentAvailability) {
  13581. subtree.contentAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'contentAvailability', internalBinaryBuffer);
  13582. }
  13583. if ('bufferView' in subtree.childSubtreeAvailability) {
  13584. subtree.childSubtreeAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'childSubtreeAvailability', internalBinaryBuffer);
  13585. }
  13586. return subtree;
  13587. }
  13588. async function getExplicitBitstream(subtree, name, internalBinaryBuffer) {
  13589. const bufferViewIndex = subtree[name].bufferView;
  13590. const bufferView = subtree.bufferViews[bufferViewIndex];
  13591. const buffer = subtree.buffers[bufferView.buffer];
  13592. if (buffer.uri) {
  13593. const response = await fetchFile(buffer.uri);
  13594. const data = await response.arrayBuffer();
  13595. return new Uint8Array(data, bufferView.byteOffset, bufferView.byteLength);
  13596. }
  13597. return new Uint8Array(internalBinaryBuffer, bufferView.byteOffset, bufferView.byteLength);
  13598. }
  13599. function parseUint64Value(buffer) {
  13600. const dataView = new DataView(buffer);
  13601. const left = dataView.getUint32(0, true);
  13602. const right = dataView.getUint32(4, true);
  13603. return left + 2 ** 32 * right;
  13604. }
  13605. const Tile3DSubtreeLoader = {
  13606. id: '3d-tiles-subtree',
  13607. name: '3D Tiles Subtree',
  13608. module: '3d-tiles',
  13609. version: VERSION$5,
  13610. extensions: ['subtree'],
  13611. mimeTypes: ['application/octet-stream'],
  13612. tests: ['subtree'],
  13613. parse: parse3DTilesSubtree,
  13614. options: {}
  13615. };
  13616. const QUADTREE_DEVISION_COUNT = 4;
  13617. const OCTREE_DEVISION_COUNT = 8;
  13618. const SUBDIVISION_COUNT_MAP = {
  13619. QUADTREE: QUADTREE_DEVISION_COUNT,
  13620. OCTREE: OCTREE_DEVISION_COUNT
  13621. };
  13622. async function parseImplicitTiles(subtree, options, parentData = {
  13623. mortonIndex: 0,
  13624. x: 0,
  13625. y: 0,
  13626. z: 0
  13627. }, childIndex = 0, level = 0, globalData = {
  13628. level: 0,
  13629. mortonIndex: 0,
  13630. x: 0,
  13631. y: 0,
  13632. z: 0
  13633. }) {
  13634. const {
  13635. subdivisionScheme,
  13636. subtreeLevels,
  13637. maximumLevel,
  13638. contentUrlTemplate,
  13639. subtreesUriTemplate,
  13640. basePath
  13641. } = options;
  13642. const tile = {
  13643. children: [],
  13644. lodMetricValue: 0,
  13645. contentUrl: ''
  13646. };
  13647. const childrenPerTile = SUBDIVISION_COUNT_MAP[subdivisionScheme];
  13648. const childX = childIndex & 0b01;
  13649. const childY = childIndex >> 1 & 0b01;
  13650. const childZ = childIndex >> 2 & 0b01;
  13651. const levelOffset = (childrenPerTile ** level - 1) / (childrenPerTile - 1);
  13652. let childTileMortonIndex = concatBits(parentData.mortonIndex, childIndex);
  13653. let tileAvailabilityIndex = levelOffset + childTileMortonIndex;
  13654. let childTileX = concatBits(parentData.x, childX);
  13655. let childTileY = concatBits(parentData.y, childY);
  13656. let childTileZ = concatBits(parentData.z, childZ);
  13657. let isChildSubtreeAvailable = false;
  13658. if (level + 1 > subtreeLevels) {
  13659. isChildSubtreeAvailable = getAvailabilityResult(subtree.childSubtreeAvailability, childTileMortonIndex);
  13660. }
  13661. const x = concatBits(globalData.x, childTileX);
  13662. const y = concatBits(globalData.y, childTileY);
  13663. const z = concatBits(globalData.z, childTileZ);
  13664. const lev = level + globalData.level;
  13665. if (isChildSubtreeAvailable) {
  13666. const subtreePath = "".concat(basePath, "/").concat(subtreesUriTemplate);
  13667. const childSubtreeUrl = replaceContentUrlTemplate(subtreePath, lev, x, y, z);
  13668. const childSubtree = await load(childSubtreeUrl, Tile3DSubtreeLoader);
  13669. subtree = childSubtree;
  13670. globalData.mortonIndex = childTileMortonIndex;
  13671. globalData.x = childTileX;
  13672. globalData.y = childTileY;
  13673. globalData.z = childTileZ;
  13674. globalData.level = level;
  13675. childTileMortonIndex = 0;
  13676. tileAvailabilityIndex = 0;
  13677. childTileX = 0;
  13678. childTileY = 0;
  13679. childTileZ = 0;
  13680. level = 0;
  13681. }
  13682. const isTileAvailable = getAvailabilityResult(subtree.tileAvailability, tileAvailabilityIndex);
  13683. if (!isTileAvailable || level > maximumLevel) {
  13684. return tile;
  13685. }
  13686. const isContentAvailable = getAvailabilityResult(subtree.contentAvailability, tileAvailabilityIndex);
  13687. if (isContentAvailable) {
  13688. tile.contentUrl = replaceContentUrlTemplate(contentUrlTemplate, lev, x, y, z);
  13689. }
  13690. const childTileLevel = level + 1;
  13691. const pData = {
  13692. mortonIndex: childTileMortonIndex,
  13693. x: childTileX,
  13694. y: childTileY,
  13695. z: childTileZ
  13696. };
  13697. for (let index = 0; index < childrenPerTile; index++) {
  13698. const currentTile = await parseImplicitTiles(subtree, options, pData, index, childTileLevel, globalData);
  13699. if (currentTile.contentUrl || currentTile.children.length) {
  13700. const globalLevel = lev + 1;
  13701. const childCoordinates = {
  13702. childTileX,
  13703. childTileY,
  13704. childTileZ
  13705. };
  13706. const formattedTile = formatTileData(currentTile, globalLevel, childCoordinates, options);
  13707. tile.children.push(formattedTile);
  13708. }
  13709. }
  13710. return tile;
  13711. }
  13712. function getAvailabilityResult(availabilityData, index) {
  13713. if ('constant' in availabilityData) {
  13714. return Boolean(availabilityData.constant);
  13715. }
  13716. if (availabilityData.explicitBitstream) {
  13717. return getBooleanValueFromBitstream(index, availabilityData.explicitBitstream);
  13718. }
  13719. return false;
  13720. }
  13721. function formatTileData(tile, level, childCoordinates, options) {
  13722. const {
  13723. basePath,
  13724. refine,
  13725. getRefine,
  13726. lodMetricType,
  13727. getTileType,
  13728. rootLodMetricValue,
  13729. rootBoundingVolume
  13730. } = options;
  13731. const uri = tile.contentUrl && tile.contentUrl.replace("".concat(basePath, "/"), '');
  13732. const lodMetricValue = rootLodMetricValue / 2 ** level;
  13733. const boundingVolume = calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates);
  13734. return {
  13735. children: tile.children,
  13736. contentUrl: tile.contentUrl,
  13737. content: {
  13738. uri
  13739. },
  13740. id: tile.contentUrl,
  13741. refine: getRefine(refine),
  13742. type: getTileType(tile),
  13743. lodMetricType,
  13744. lodMetricValue,
  13745. boundingVolume
  13746. };
  13747. }
  13748. function calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates) {
  13749. if (rootBoundingVolume.region) {
  13750. const {
  13751. childTileX,
  13752. childTileY,
  13753. childTileZ
  13754. } = childCoordinates;
  13755. const [west, south, east, north, minimumHeight, maximumHeight] = rootBoundingVolume.region;
  13756. const boundingVolumesCount = 2 ** level;
  13757. const sizeX = (east - west) / boundingVolumesCount;
  13758. const sizeY = (north - south) / boundingVolumesCount;
  13759. const sizeZ = (maximumHeight - minimumHeight) / boundingVolumesCount;
  13760. const [childWest, childEast] = [west + sizeX * childTileX, west + sizeX * (childTileX + 1)];
  13761. const [childSouth, childNorth] = [south + sizeY * childTileY, south + sizeY * (childTileY + 1)];
  13762. const [childMinimumHeight, childMaximumHeight] = [minimumHeight + sizeZ * childTileZ, minimumHeight + sizeZ * (childTileZ + 1)];
  13763. return {
  13764. region: [childWest, childSouth, childEast, childNorth, childMinimumHeight, childMaximumHeight]
  13765. };
  13766. }
  13767. console.warn('Unsupported bounding volume type: ', rootBoundingVolume);
  13768. return null;
  13769. }
  13770. function concatBits(first, second) {
  13771. return parseInt(first.toString(2) + second.toString(2), 2);
  13772. }
  13773. function replaceContentUrlTemplate(templateUrl, level, x, y, z) {
  13774. const mapUrl = generateMapUrl({
  13775. level,
  13776. x,
  13777. y,
  13778. z
  13779. });
  13780. return templateUrl.replace(/{level}|{x}|{y}|{z}/gi, matched => mapUrl[matched]);
  13781. }
  13782. function generateMapUrl(items) {
  13783. const mapUrl = {};
  13784. for (const key in items) {
  13785. mapUrl["{".concat(key, "}")] = items[key];
  13786. }
  13787. return mapUrl;
  13788. }
  13789. function getBooleanValueFromBitstream(availabilityIndex, availabilityBuffer) {
  13790. const byteIndex = Math.floor(availabilityIndex / 8);
  13791. const bitIndex = availabilityIndex % 8;
  13792. const bitValue = availabilityBuffer[byteIndex] >> bitIndex & 1;
  13793. return bitValue === 1;
  13794. }
  13795. function getTileType(tile) {
  13796. if (!tile.contentUrl) {
  13797. return TILE_TYPE.EMPTY;
  13798. }
  13799. const contentUrl = tile.contentUrl;
  13800. const fileExtension = contentUrl.split('.').pop();
  13801. switch (fileExtension) {
  13802. case 'pnts':
  13803. return TILE_TYPE.POINTCLOUD;
  13804. case 'i3dm':
  13805. case 'b3dm':
  13806. case 'glb':
  13807. case 'gltf':
  13808. return TILE_TYPE.SCENEGRAPH;
  13809. default:
  13810. return fileExtension;
  13811. }
  13812. }
  13813. function getRefine(refine) {
  13814. switch (refine) {
  13815. case 'REPLACE':
  13816. case 'replace':
  13817. return TILE_REFINEMENT.REPLACE;
  13818. case 'ADD':
  13819. case 'add':
  13820. return TILE_REFINEMENT.ADD;
  13821. default:
  13822. return refine;
  13823. }
  13824. }
  13825. function normalizeTileData(tile, options) {
  13826. if (!tile) {
  13827. return null;
  13828. }
  13829. if (tile.content) {
  13830. const contentUri = tile.content.uri || tile.content.url;
  13831. tile.contentUrl = "".concat(options.basePath, "/").concat(contentUri);
  13832. }
  13833. tile.id = tile.contentUrl;
  13834. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13835. tile.lodMetricValue = tile.geometricError;
  13836. tile.transformMatrix = tile.transform;
  13837. tile.type = getTileType(tile);
  13838. tile.refine = getRefine(tile.refine);
  13839. return tile;
  13840. }
  13841. function normalizeTileHeaders(tileset) {
  13842. const basePath = tileset.basePath;
  13843. const root = normalizeTileData(tileset.root, tileset);
  13844. const stack = [];
  13845. stack.push(root);
  13846. while (stack.length > 0) {
  13847. const tile = stack.pop() || {};
  13848. const children = tile.children || [];
  13849. for (const childHeader of children) {
  13850. normalizeTileData(childHeader, {
  13851. basePath
  13852. });
  13853. stack.push(childHeader);
  13854. }
  13855. }
  13856. return root;
  13857. }
  13858. async function normalizeImplicitTileHeaders(tileset) {
  13859. if (!tileset.root) {
  13860. return null;
  13861. }
  13862. const basePath = tileset.basePath;
  13863. const implicitTilingExtension = tileset.root.extensions['3DTILES_implicit_tiling'];
  13864. const {
  13865. subdivisionScheme,
  13866. maximumLevel,
  13867. subtreeLevels,
  13868. subtrees: {
  13869. uri: subtreesUriTemplate
  13870. }
  13871. } = implicitTilingExtension;
  13872. const subtreeUrl = replaceContentUrlTemplate(subtreesUriTemplate, 0, 0, 0, 0);
  13873. const rootSubtreeUrl = "".concat(basePath, "/").concat(subtreeUrl);
  13874. const rootSubtree = await load(rootSubtreeUrl, Tile3DSubtreeLoader);
  13875. const contentUrlTemplate = "".concat(basePath, "/").concat(tileset.root.content.uri);
  13876. const refine = tileset.root.refine;
  13877. const rootLodMetricValue = tileset.root.geometricError;
  13878. const rootBoundingVolume = tileset.root.boundingVolume;
  13879. const options = {
  13880. contentUrlTemplate,
  13881. subtreesUriTemplate,
  13882. subdivisionScheme,
  13883. subtreeLevels,
  13884. maximumLevel,
  13885. refine,
  13886. basePath,
  13887. lodMetricType: LOD_METRIC_TYPE.GEOMETRIC_ERROR,
  13888. rootLodMetricValue,
  13889. rootBoundingVolume,
  13890. getTileType,
  13891. getRefine
  13892. };
  13893. return await normalizeImplicitTileData(tileset.root, rootSubtree, options);
  13894. }
  13895. async function normalizeImplicitTileData(tile, rootSubtree, options) {
  13896. if (!tile) {
  13897. return null;
  13898. }
  13899. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13900. tile.lodMetricValue = tile.geometricError;
  13901. tile.transformMatrix = tile.transform;
  13902. const {
  13903. children,
  13904. contentUrl
  13905. } = await parseImplicitTiles(rootSubtree, options);
  13906. if (contentUrl) {
  13907. tile.contentUrl = contentUrl;
  13908. tile.content = {
  13909. uri: contentUrl.replace("".concat(options.basePath, "/"), '')
  13910. };
  13911. }
  13912. tile.refine = getRefine(tile.refine);
  13913. tile.type = getTileType(tile);
  13914. tile.children = children;
  13915. tile.id = tile.contentUrl;
  13916. return tile;
  13917. }
  13918. const IMPLICIT_TILING_EXTENSION_NAME = '3DTILES_implicit_tiling';
  13919. const Tiles3DLoader = {
  13920. id: '3d-tiles',
  13921. name: '3D Tiles',
  13922. module: '3d-tiles',
  13923. version: VERSION$5,
  13924. extensions: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  13925. mimeTypes: ['application/octet-stream'],
  13926. tests: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  13927. parse,
  13928. options: {
  13929. '3d-tiles': {
  13930. loadGLTF: true,
  13931. decodeQuantizedPositions: false,
  13932. isTileset: 'auto',
  13933. assetGltfUpAxis: null
  13934. }
  13935. }
  13936. };
  13937. function getBaseUri(tileset) {
  13938. return dirname(tileset.url);
  13939. }
  13940. async function parseTile(arrayBuffer, options, context) {
  13941. const tile = {
  13942. content: {
  13943. featureIds: null
  13944. }
  13945. };
  13946. const byteOffset = 0;
  13947. await parse3DTile(arrayBuffer, byteOffset, options, context, tile.content);
  13948. return tile.content;
  13949. }
  13950. async function parseTileset(data, options, context) {
  13951. var _tilesetJson$root;
  13952. const tilesetJson = JSON.parse(new TextDecoder().decode(data));
  13953. tilesetJson.loader = options.loader || Tiles3DLoader;
  13954. tilesetJson.url = context.url;
  13955. tilesetJson.basePath = getBaseUri(tilesetJson);
  13956. tilesetJson.root = hasImplicitTilingExtension(tilesetJson) ? await normalizeImplicitTileHeaders(tilesetJson) : normalizeTileHeaders(tilesetJson);
  13957. tilesetJson.type = TILESET_TYPE.TILES3D;
  13958. tilesetJson.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13959. tilesetJson.lodMetricValue = ((_tilesetJson$root = tilesetJson.root) === null || _tilesetJson$root === void 0 ? void 0 : _tilesetJson$root.lodMetricValue) || 0;
  13960. return tilesetJson;
  13961. }
  13962. async function parse(data, options, context) {
  13963. const loaderOptions = options['3d-tiles'] || {};
  13964. let isTileset;
  13965. if (loaderOptions.isTileset === 'auto') {
  13966. isTileset = context.url && context.url.indexOf('.json') !== -1;
  13967. } else {
  13968. isTileset = loaderOptions.isTileset;
  13969. }
  13970. if (isTileset) {
  13971. data = await parseTileset(data, options, context);
  13972. } else {
  13973. data = await parseTile(data, options, context);
  13974. }
  13975. return data;
  13976. }
  13977. function hasImplicitTilingExtension(tilesetJson) {
  13978. var _tilesetJson$extensio, _tilesetJson$extensio2;
  13979. 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));
  13980. }
  13981. const CESIUM_ION_URL = 'https://api.cesium.com/v1/assets';
  13982. async function getIonTilesetMetadata(accessToken, assetId) {
  13983. if (!assetId) {
  13984. const assets = await getIonAssets(accessToken);
  13985. for (const item of assets.items) {
  13986. if (item.type === '3DTILES') {
  13987. assetId = item.id;
  13988. }
  13989. }
  13990. }
  13991. const ionAssetMetadata = await getIonAssetMetadata(accessToken, assetId);
  13992. const {
  13993. type,
  13994. url
  13995. } = ionAssetMetadata;
  13996. assert$7(type === '3DTILES' && url);
  13997. ionAssetMetadata.headers = {
  13998. Authorization: "Bearer ".concat(ionAssetMetadata.accessToken)
  13999. };
  14000. return ionAssetMetadata;
  14001. }
  14002. async function getIonAssets(accessToken) {
  14003. assert$7(accessToken);
  14004. const url = CESIUM_ION_URL;
  14005. const headers = {
  14006. Authorization: "Bearer ".concat(accessToken)
  14007. };
  14008. const response = await fetchFile(url, {
  14009. fetch: {
  14010. headers
  14011. }
  14012. });
  14013. if (!response.ok) {
  14014. throw new Error(response.statusText);
  14015. }
  14016. return await response.json();
  14017. }
  14018. async function getIonAssetMetadata(accessToken, assetId) {
  14019. assert$7(accessToken, assetId);
  14020. const headers = {
  14021. Authorization: "Bearer ".concat(accessToken)
  14022. };
  14023. const url = "".concat(CESIUM_ION_URL, "/").concat(assetId);
  14024. let response = await fetchFile("".concat(url), {
  14025. fetch: {
  14026. headers
  14027. }
  14028. });
  14029. if (!response.ok) {
  14030. throw new Error(response.statusText);
  14031. }
  14032. let metadata = await response.json();
  14033. response = await fetchFile("".concat(url, "/endpoint"), {
  14034. fetch: {
  14035. headers
  14036. }
  14037. });
  14038. if (!response.ok) {
  14039. throw new Error(response.statusText);
  14040. }
  14041. const tilesetInfo = await response.json();
  14042. metadata = { ...metadata,
  14043. ...tilesetInfo
  14044. };
  14045. return metadata;
  14046. }
  14047. async function preload(url, options = {}) {
  14048. options = options['cesium-ion'] || {};
  14049. const {
  14050. accessToken
  14051. } = options;
  14052. let assetId = options.assetId;
  14053. if (!Number.isFinite(assetId)) {
  14054. const matched = url.match(/\/([0-9]+)\/tileset.json/);
  14055. assetId = matched && matched[1];
  14056. }
  14057. return getIonTilesetMetadata(accessToken, assetId);
  14058. }
  14059. const CesiumIonLoader = { ...Tiles3DLoader,
  14060. id: 'cesium-ion',
  14061. name: 'Cesium Ion',
  14062. preload,
  14063. parse: async (data, options, context) => {
  14064. options = { ...options
  14065. };
  14066. options['3d-tiles'] = options['cesium-ion'];
  14067. options.loader = CesiumIonLoader;
  14068. return Tiles3DLoader.parse(data, options, context);
  14069. },
  14070. options: {
  14071. 'cesium-ion': { ...Tiles3DLoader.options['3d-tiles'],
  14072. accessToken: null
  14073. }
  14074. }
  14075. };
  14076. // From https://github.com/potree/potree/blob/master/src/materials/PointCloudMaterial.js
  14077. function generateGradientTexture(gradient) {
  14078. const size = 64;
  14079. // create canvas
  14080. const canvas = document.createElement('canvas');
  14081. canvas.width = size;
  14082. canvas.height = size;
  14083. // get context
  14084. const context = canvas.getContext('2d');
  14085. // draw gradient
  14086. context.rect(0, 0, size, size);
  14087. const ctxGradient = context.createLinearGradient(0, 0, size, size);
  14088. for (let i = 0; i < gradient.length; i++) {
  14089. const step = gradient[i];
  14090. ctxGradient.addColorStop(step[0], '#' + step[1].getHexString());
  14091. }
  14092. context.fillStyle = ctxGradient;
  14093. context.fill();
  14094. //let texture = new THREE.Texture(canvas);
  14095. const texture = new CanvasTexture(canvas);
  14096. texture.needsUpdate = true;
  14097. texture.minFilter = LinearFilter;
  14098. texture.wrapS = RepeatWrapping;
  14099. texture.wrapT = RepeatWrapping;
  14100. texture.repeat.set(2, 2);
  14101. // textureImage = texture.image;
  14102. return texture;
  14103. }
  14104. function getCameraFrustum(camera) {
  14105. camera.updateMatrix(); // make sure camera's local matrix is updated
  14106. camera.updateMatrixWorld(); // make sure camera's world matrix is updated
  14107. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14108. const frustum = new Frustum();
  14109. frustum.setFromProjectionMatrix(new Matrix4$1().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));
  14110. return frustum;
  14111. }
  14112. function loadersPlaneToMesh(plane) {
  14113. const group = new Group();
  14114. // Create a basic rectangle geometry from math.gl plane
  14115. const planeGeometry = new PlaneGeometry(10, 5);
  14116. // Align the geometry to the plane
  14117. const coplanarPoint = new Vector3$1(...plane.projectPointOntoPlane([0, 0, 0]));
  14118. const normal = new Vector3$1(plane.normal.x, plane.normal.y, plane.normal.z);
  14119. const focalPoint = new Vector3$1().copy(coplanarPoint).add(normal);
  14120. planeGeometry.lookAt(focalPoint);
  14121. planeGeometry.translate(coplanarPoint.x, coplanarPoint.y, coplanarPoint.z);
  14122. // Edges
  14123. /*
  14124. const edges = new EdgesGeometry(planeGeometry)
  14125. var dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: 0x00ffff }))*/
  14126. //plane
  14127. const material = new MeshBasicMaterial({ color: 0x00ffff, side: DoubleSide });
  14128. const mesh = new Mesh(planeGeometry, material);
  14129. const arrowHelper = new ArrowHelper(normal, coplanarPoint, 5, 0xffff00);
  14130. group.add(arrowHelper);
  14131. group.add(mesh);
  14132. return group;
  14133. }
  14134. function loadersBoundingBoxToMesh(tile) {
  14135. // Create a basic rectangle geometry from math.gl half-axes
  14136. const boundUntransformed = tile.type == 'empty' ? tile.boundingVolume : tile.getBoundUntransformed() //empty时没创建好,直接给boundingVolume一样
  14137. /* let redColor = 0;
  14138. if (tile.content) {
  14139. //redColor = Math.min((tile.content.byteLength != void 0 ? tile.content.byteLength : 0) / 500000, 1.0);
  14140. redColor = Math.min( tile.depth / 10 , 1.0); //改
  14141. } */
  14142. let hue = 0
  14143. if(tile.content){
  14144. hue = Math.min( tile.depth / 10 , 1.0); //改
  14145. }
  14146. const boxColor = new THREE.Color().setHSL(hue, 0.9, 0.85)
  14147. //const boxColor = new Color(redColor, 1.0, 0.0);
  14148. const boxGeometry = new BoxGeometry(1, 1, 1);
  14149. const boxTransform = new Matrix4$1();
  14150. if (boundUntransformed.halfAxes) {
  14151. boxTransform.copy(getMatrix4FromHalfAxes(boundUntransformed.halfAxes));
  14152. }
  14153. else if (boundUntransformed.radius) {
  14154. boxGeometry.scale(boundUntransformed.radius * 2, boundUntransformed.radius * 2, boundUntransformed.radius * 2);
  14155. }
  14156. boxTransform.premultiply((new Matrix4$1()).setPosition(...boundUntransformed.center)) //add
  14157. /* if(tile.type != "empty"){ //root单独处理了
  14158. boxTransform.premultiply((new Matrix4$1()).makeScale(1,1,-1))//xzw 因为mesh倒转了所以box也
  14159. }else{
  14160. console.log('empty')
  14161. } */
  14162. boxGeometry.applyMatrix4(boxTransform);
  14163. const edges = new EdgesGeometry(boxGeometry);
  14164. const dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: boxColor, transparent:true }));
  14165. //dispPlane.position.copy(new Vector3$1(...boundingVolume.center));
  14166. dispPlane.matrixAutoUpdate = false //add
  14167. let label = new Potree.TextSprite({
  14168. mat: new THREE.MeshBasicMaterial({transparent:true }), //depthTest:false会导致经常显示不出
  14169. backgroundColor: {r: 0, g: 0, b: 0, a:0.1},
  14170. textColor: {r: boxColor.r*255, g: boxColor.g*255, b: boxColor.b*255, a:0.9},
  14171. fontsize:100,
  14172. //useDepth : true ,
  14173. renderOrder : 5,
  14174. text: tile.id.split('/').pop().split('.b3dm')[0], //Tile_+094_-010.b3dm'
  14175. name:'tile'
  14176. })
  14177. label.addEventListener('mouseover',()=>{
  14178. if(label.sprite.material.opacity < 1)return
  14179. window.hoverTile = tile
  14180. console.log('hoverLabel',tile.id, tile._distanceToCamera)
  14181. })
  14182. /* let s = 0.6
  14183. label.scale.set(s,s,s) */
  14184. let s = tile.tileset.options.maximumScreenSpaceError / 400
  14185. label.scale.set(s,s,s)
  14186. dispPlane.add(label)
  14187. label.position.set(...boundUntransformed.center)
  14188. //label.position.z *= -1
  14189. /* if(tile.content.byteLength == void 0){
  14190. let oldUpdate = dispPlane.updateMatrixWorld.bind(dispPlane)
  14191. dispPlane.updateMatrixWorld = (a,b)=>{
  14192. oldUpdate(a,b)
  14193. }
  14194. let oldU = dispPlane.updateMatrix.bind(dispPlane)
  14195. dispPlane.updateMatrix = (a,b)=>{
  14196. oldU(a,b)
  14197. }
  14198. } */
  14199. tile.volumeBox = dispPlane
  14200. return dispPlane;
  14201. }
  14202. function getMatrix4FromHalfAxes(halfAxes) {
  14203. const m = halfAxes;
  14204. const rotateMatrix = new Matrix4$1().fromArray([
  14205. m[0] * 2,
  14206. m[1] * 2,
  14207. m[2] * 2,
  14208. 0,
  14209. m[3] * 2,
  14210. m[4] * 2,
  14211. m[5] * 2,
  14212. 0,
  14213. m[6] * 2,
  14214. m[7] * 2,
  14215. m[8] * 2,
  14216. 0,
  14217. 0,
  14218. 0,
  14219. 0,
  14220. 1,
  14221. ]);
  14222. return rotateMatrix;
  14223. }
  14224. /*
  14225. * from https://github.com/tentone/geo-three
  14226. * Tree-shaking did not work, probably due to static class methods
  14227. */
  14228. function datumsToSpherical(latitude, longitude) {
  14229. const EARTH_RADIUS = 6378137;
  14230. const EARTH_PERIMETER = 2 * Math.PI * EARTH_RADIUS;
  14231. const EARTH_ORIGIN = EARTH_PERIMETER / 2.0;
  14232. const x = longitude * EARTH_ORIGIN / 180.0;
  14233. let y = Math.log(Math.tan((90 + latitude) * Math.PI / 360.0)) / (Math.PI / 180.0);
  14234. y = y * EARTH_ORIGIN / 180.0;
  14235. return new Vector2$1(x, y);
  14236. }
  14237. const Gradients = {
  14238. // From chroma spectral http://gka.github.io/chroma.js/
  14239. SPECTRAL: [
  14240. [0, new Color(0.3686, 0.3098, 0.6353)],
  14241. [0.1, new Color(0.1961, 0.5333, 0.7412)],
  14242. [0.2, new Color(0.4, 0.7608, 0.6471)],
  14243. [0.3, new Color(0.6706, 0.8667, 0.6431)],
  14244. [0.4, new Color(0.902, 0.9608, 0.5961)],
  14245. [0.5, new Color(1.0, 1.0, 0.749)],
  14246. [0.6, new Color(0.9961, 0.8784, 0.5451)],
  14247. [0.7, new Color(0.9922, 0.6824, 0.3804)],
  14248. [0.8, new Color(0.9569, 0.4275, 0.2627)],
  14249. [0.9, new Color(0.8353, 0.2431, 0.3098)],
  14250. [1, new Color(0.6196, 0.0039, 0.2588)],
  14251. ],
  14252. PLASMA: [
  14253. [0.0, new Color(0.241, 0.015, 0.61)],
  14254. [0.1, new Color(0.387, 0.001, 0.654)],
  14255. [0.2, new Color(0.524, 0.025, 0.653)],
  14256. [0.3, new Color(0.651, 0.125, 0.596)],
  14257. [0.4, new Color(0.752, 0.227, 0.513)],
  14258. [0.5, new Color(0.837, 0.329, 0.431)],
  14259. [0.6, new Color(0.907, 0.435, 0.353)],
  14260. [0.7, new Color(0.963, 0.554, 0.272)],
  14261. [0.8, new Color(0.992, 0.681, 0.195)],
  14262. [0.9, new Color(0.987, 0.822, 0.144)],
  14263. [1.0, new Color(0.94, 0.975, 0.131)],
  14264. ],
  14265. YELLOW_GREEN: [
  14266. [0, new Color(0.1647, 0.2824, 0.3451)],
  14267. [0.1, new Color(0.1338, 0.3555, 0.4227)],
  14268. [0.2, new Color(0.061, 0.4319, 0.4864)],
  14269. [0.3, new Color(0.0, 0.5099, 0.5319)],
  14270. [0.4, new Color(0.0, 0.5881, 0.5569)],
  14271. [0.5, new Color(0.137, 0.665, 0.5614)],
  14272. [0.6, new Color(0.2906, 0.7395, 0.5477)],
  14273. [0.7, new Color(0.4453, 0.8099, 0.5201)],
  14274. [0.8, new Color(0.6102, 0.8748, 0.485)],
  14275. [0.9, new Color(0.7883, 0.9323, 0.4514)],
  14276. [1, new Color(0.9804, 0.9804, 0.4314)],
  14277. ],
  14278. VIRIDIS: [
  14279. [0.0, new Color(0.267, 0.005, 0.329)],
  14280. [0.1, new Color(0.283, 0.141, 0.458)],
  14281. [0.2, new Color(0.254, 0.265, 0.53)],
  14282. [0.3, new Color(0.207, 0.372, 0.553)],
  14283. [0.4, new Color(0.164, 0.471, 0.558)],
  14284. [0.5, new Color(0.128, 0.567, 0.551)],
  14285. [0.6, new Color(0.135, 0.659, 0.518)],
  14286. [0.7, new Color(0.267, 0.749, 0.441)],
  14287. [0.8, new Color(0.478, 0.821, 0.318)],
  14288. [0.9, new Color(0.741, 0.873, 0.15)],
  14289. [1.0, new Color(0.993, 0.906, 0.144)],
  14290. ],
  14291. INFERNO: [
  14292. [0.0, new Color(0.077, 0.042, 0.206)],
  14293. [0.1, new Color(0.225, 0.036, 0.388)],
  14294. [0.2, new Color(0.373, 0.074, 0.432)],
  14295. [0.3, new Color(0.522, 0.128, 0.42)],
  14296. [0.4, new Color(0.665, 0.182, 0.37)],
  14297. [0.5, new Color(0.797, 0.255, 0.287)],
  14298. [0.6, new Color(0.902, 0.364, 0.184)],
  14299. [0.7, new Color(0.969, 0.516, 0.063)],
  14300. [0.8, new Color(0.988, 0.683, 0.072)],
  14301. [0.9, new Color(0.961, 0.859, 0.298)],
  14302. [1.0, new Color(0.988, 0.998, 0.645)],
  14303. ],
  14304. GRAYSCALE: [
  14305. [0, new Color(0, 0, 0)],
  14306. [1, new Color(1, 1, 1)],
  14307. ],
  14308. // 16 samples of the TURBU color scheme
  14309. // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f
  14310. // original file licensed under Apache-2.0
  14311. TURBO: [
  14312. [0.0, new Color(0.18995, 0.07176, 0.23217)],
  14313. [0.07, new Color(0.25107, 0.25237, 0.63374)],
  14314. [0.13, new Color(0.27628, 0.42118, 0.89123)],
  14315. [0.2, new Color(0.25862, 0.57958, 0.99876)],
  14316. [0.27, new Color(0.15844, 0.73551, 0.92305)],
  14317. [0.33, new Color(0.09267, 0.86554, 0.7623)],
  14318. [0.4, new Color(0.19659, 0.94901, 0.59466)],
  14319. [0.47, new Color(0.42778, 0.99419, 0.38575)],
  14320. [0.53, new Color(0.64362, 0.98999, 0.23356)],
  14321. [0.6, new Color(0.80473, 0.92452, 0.20459)],
  14322. [0.67, new Color(0.93301, 0.81236, 0.22667)],
  14323. [0.73, new Color(0.99314, 0.67408, 0.20348)],
  14324. [0.8, new Color(0.9836, 0.49291, 0.12849)],
  14325. [0.87, new Color(0.92105, 0.31489, 0.05475)],
  14326. [0.93, new Color(0.81608, 0.18462, 0.01809)],
  14327. [1.0, new Color(0.66449, 0.08436, 0.00424)],
  14328. ],
  14329. RAINBOW: [
  14330. [0, new Color(0.278, 0, 0.714)],
  14331. [1 / 6, new Color(0, 0, 1)],
  14332. [2 / 6, new Color(0, 1, 1)],
  14333. [3 / 6, new Color(0, 1, 0)],
  14334. [4 / 6, new Color(1, 1, 0)],
  14335. [5 / 6, new Color(1, 0.64, 0)],
  14336. [1, new Color(1, 0, 0)],
  14337. ],
  14338. CONTOUR: [
  14339. [0.0, new Color(0, 0, 0)],
  14340. [0.03, new Color(0, 0, 0)],
  14341. [0.04, new Color(1, 1, 1)],
  14342. [1.0, new Color(1, 1, 1)],
  14343. ],
  14344. };
  14345. const PointCloudFS = `
  14346. varying vec3 vColor;
  14347. uniform float alpha;
  14348. void main() {
  14349. if (vColor == vec3(0.0, 0.0, 0.0)) {
  14350. discard;
  14351. } else {
  14352. gl_FragColor = vec4( vColor, alpha);
  14353. }
  14354. }
  14355. `;
  14356. const PointCloudVS = `
  14357. varying vec3 vColor;
  14358. uniform sampler2D gradient;
  14359. uniform sampler2D grayscale;
  14360. attribute float intensity;
  14361. attribute float classification;
  14362. uniform vec3 rootCenter;
  14363. uniform vec3 rootNormal;
  14364. uniform vec2 elevationRange;
  14365. uniform int coloring;
  14366. uniform bool hideGround;
  14367. uniform float maxIntensity;
  14368. uniform float intensityContrast;
  14369. uniform float pointSize;
  14370. #ifdef USE_COLOR
  14371. vec3 getRGB() {
  14372. vec3 rgb = color;
  14373. return rgb;
  14374. }
  14375. #endif
  14376. vec3 getElevation(){
  14377. vec4 world = modelMatrix * vec4( position, 1.0 );
  14378. float diff = abs(dot(rootNormal, (vec3(world) - rootCenter)));
  14379. float w = max(diff - elevationRange.x,0.0) / max(elevationRange.y - elevationRange.x,1.0);
  14380. vec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;
  14381. return cElevation;
  14382. }
  14383. vec3 getIntensity(){
  14384. // TODO: real contrast enhancement. Check https://github.com/yuki-koyama/enhancer/blob/master/shaders/enhancer.fs
  14385. float intmod = pow(intensity, intensityContrast);
  14386. vec3 cIntensity = texture2D(grayscale, vec2(intmod / maxIntensity ,1.0-(intmod / maxIntensity))).rgb;
  14387. return cIntensity;
  14388. }
  14389. vec3 getClassification(){
  14390. float classNormalized = classification / 255.0;
  14391. vec3 cClassification = texture2D(gradient, vec2(classNormalized * 5.0,1.0-classNormalized * 5.0)).rgb;
  14392. return cClassification;
  14393. }
  14394. vec3 getColor(){
  14395. vec3 color;
  14396. if (hideGround && classification == 2.0) {
  14397. return vec3(0.0, 0.0, 0.0);
  14398. }
  14399. if (coloring == 1) {
  14400. color = getIntensity();
  14401. }
  14402. else if (coloring == 2) {
  14403. color = getClassification();
  14404. } else if (coloring == 3) {
  14405. color = getElevation();
  14406. }
  14407. #ifdef USE_COLOR
  14408. else if (coloring == 4) {
  14409. color = getRGB();
  14410. }
  14411. #endif
  14412. else {
  14413. color = vec3(1.0, 1.0, 1.0);
  14414. }
  14415. return color;
  14416. }
  14417. void main() {
  14418. vColor = getColor();
  14419. gl_PointSize = pointSize;
  14420. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  14421. }
  14422. `;
  14423. /** Types of coloring used when viewing point cloud tiles */
  14424. var PointCloudColoring;
  14425. (function (PointCloudColoring) {
  14426. PointCloudColoring[PointCloudColoring["Intensity"] = 1] = "Intensity";
  14427. PointCloudColoring[PointCloudColoring["Classification"] = 2] = "Classification";
  14428. PointCloudColoring[PointCloudColoring["Elevation"] = 3] = "Elevation";
  14429. PointCloudColoring[PointCloudColoring["RGB"] = 4] = "RGB";
  14430. PointCloudColoring[PointCloudColoring["White"] = 5] = "White";
  14431. })(PointCloudColoring || (PointCloudColoring = {}));
  14432. /** Types of shading used when viewing b3dm (mesh) tiles */
  14433. var Shading;
  14434. (function (Shading) {
  14435. Shading[Shading["FlatTexture"] = 1] = "FlatTexture";
  14436. Shading[Shading["ShadedTexture"] = 2] = "ShadedTexture";
  14437. Shading[Shading["ShadedNoTexture"] = 3] = "ShadedNoTexture";
  14438. })(Shading || (Shading = {}));
  14439. var GeoTransform;
  14440. (function (GeoTransform) {
  14441. GeoTransform[GeoTransform["Reset"] = 1] = "Reset";
  14442. GeoTransform[GeoTransform["Mercator"] = 2] = "Mercator";
  14443. GeoTransform[GeoTransform["WGS84Cartesian"] = 3] = "WGS84Cartesian";
  14444. })(GeoTransform || (GeoTransform = {}));
  14445. const gradient = Gradients.RAINBOW;
  14446. const gradientTexture = typeof document != 'undefined' ? generateGradientTexture(gradient) : null;
  14447. const grayscale = Gradients.GRAYSCALE;
  14448. const grayscaleTexture = typeof document != 'undefined' ? generateGradientTexture(grayscale) : null;
  14449. const defaultOptions = {
  14450. throttleRequests: true,
  14451. maxRequests: 64,
  14452. updateInterval: 0.1,
  14453. maxConcurrency: 1,
  14454. maximumScreenSpaceError: 16,
  14455. maximumMemoryUsage: 32,
  14456. viewDistanceScale: 1.0,
  14457. skipLevelOfDetail: false,
  14458. updateTransforms: true,
  14459. shading: Shading.FlatTexture,
  14460. transparent: false,
  14461. pointCloudColoring: PointCloudColoring.White,
  14462. pointSize: 1.0,
  14463. worker: true,
  14464. wireframe: false,
  14465. debug: false,
  14466. basisTranscoderPath: null,
  14467. dracoDecoderPath: null,
  14468. material: null,
  14469. computeNormals: false,
  14470. shaderCallback: null,
  14471. geoTransform: GeoTransform.Reset,
  14472. preloadTilesCount: null
  14473. };
  14474. /** 3D Tiles Loader */
  14475. class Loader3DTiles {
  14476. /**
  14477. * Loads a tileset of 3D Tiles according to the given {@link LoaderProps}
  14478. * @public
  14479. *
  14480. * @param props - Properties for this load call {@link LoaderProps}.
  14481. * @returns An object containing the 3D Model to be added to the scene
  14482. * and a runtime engine to be updated every frame.
  14483. */
  14484. static load(props) {
  14485. return __awaiter(this, void 0, void 0, function* () {
  14486. const options = Object.assign(Object.assign({}, defaultOptions), props.options);
  14487. const { url } = props;
  14488. const UPDATE_INTERVAL = options.updateInterval;
  14489. const MAX_DEPTH_FOR_ORIENTATION = 5;
  14490. const loadersGLOptions = {};
  14491. if (options.cesiumIONToken) {
  14492. loadersGLOptions['cesium-ion'] = {
  14493. accessToken: options.cesiumIONToken,
  14494. };
  14495. const metadata = yield CesiumIonLoader.preload(url, loadersGLOptions);
  14496. loadersGLOptions['fetch'] = { headers: metadata.headers };
  14497. }
  14498. if (props.loadingManager) {
  14499. props.loadingManager.itemStart(url);
  14500. }
  14501. const tilesetJson = yield load(url, Tiles3DLoader, Object.assign({}, loadersGLOptions));
  14502. const renderMap = {};
  14503. const boxMap = {};
  14504. const unloadQueue = [];
  14505. const root = new Group();
  14506. const tileBoxes = new Group();
  14507. tileBoxes.matrixAutoUpdate = false//add
  14508. if (!options.debug) {
  14509. tileBoxes.visible = false;
  14510. }else{
  14511. options.parent.add(tileBoxes) //add
  14512. }
  14513. const pointcloudUniforms = {
  14514. pointSize: { type: 'f', value: options.pointSize },
  14515. gradient: { type: 't', value: gradientTexture },
  14516. grayscale: { type: 't', value: grayscaleTexture },
  14517. rootCenter: { type: 'vec3', value: new Vector3$1() },
  14518. rootNormal: { type: 'vec3', value: new Vector3$1() },
  14519. coloring: { type: 'i', value: options.pointCloudColoring },
  14520. hideGround: { type: 'b', value: true },
  14521. elevationRange: { type: 'vec2', value: new Vector2$1(0, 400) },
  14522. maxIntensity: { type: 'f', value: 1.0 },
  14523. intensityContrast: { type: 'f', value: 1.0 },
  14524. alpha: { type: 'f', value: 1.0 },
  14525. };
  14526. const pointcloudMaterial = new ShaderMaterial({
  14527. uniforms: pointcloudUniforms,
  14528. vertexShader: PointCloudVS,
  14529. fragmentShader: PointCloudFS,
  14530. transparent: options.transparent,
  14531. vertexColors: true
  14532. });
  14533. let cameraReference = null;
  14534. let rendererReference = null;
  14535. const gltfLoader = props.gltfLoader || new GLTFLoader$1(); //xzw改
  14536. let ktx2Loader = undefined;
  14537. let dracoLoader = undefined;
  14538. if (options.basisTranscoderPath) {
  14539. ktx2Loader = new KTX2Loader();
  14540. ktx2Loader.detectSupport(props.renderer);
  14541. ktx2Loader.setTranscoderPath(options.basisTranscoderPath + '/');
  14542. ktx2Loader.setWorkerLimit(1);
  14543. gltfLoader.setKTX2Loader(ktx2Loader);
  14544. }
  14545. if (options.dracoDecoderPath) {
  14546. dracoLoader = new DRACOLoader();
  14547. dracoLoader.setDecoderPath(options.dracoDecoderPath + '/');
  14548. dracoLoader.setWorkerLimit(options.maxConcurrency);
  14549. gltfLoader.setDRACOLoader(dracoLoader);
  14550. }
  14551. const unlitMaterial = new MeshBasicMaterial({ transparent: options.transparent });
  14552. const tileOptions = {
  14553. maximumMemoryUsage: options.maximumMemoryUsage,
  14554. maximumScreenSpaceError: options.maximumScreenSpaceError,
  14555. viewDistanceScale: options.viewDistanceScale,
  14556. skipLevelOfDetail: options.skipLevelOfDetail,
  14557. updateTransforms: options.updateTransforms,
  14558. throttleRequests: options.throttleRequests,
  14559. maxRequests: options.maxRequests,
  14560. updateTime: options.updateTime || 0, //add
  14561. //maxDepth: options.maxDepth || 50, // !zeg改
  14562. contentLoader: (tile) => __awaiter(this, void 0, void 0, function* () {
  14563. let tileContent = null;
  14564. switch (tile.type) {
  14565. case TILE_TYPE.POINTCLOUD: {
  14566. tileContent = createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse);
  14567. break;
  14568. }
  14569. case TILE_TYPE.SCENEGRAPH:
  14570. case TILE_TYPE.MESH: {
  14571. tileContent = yield createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse);
  14572. break;
  14573. }
  14574. }
  14575. if (tileContent) {
  14576. tileContent.visible = false;
  14577. renderMap[tile.id] = tileContent;
  14578. tileContent.name = tile.id //add
  14579. root.add(renderMap[tile.id]);
  14580. if (options.debug) {
  14581. const box = loadersBoundingBoxToMesh(tile);
  14582. tileBoxes.add(box);
  14583. boxMap[tile.id] = box;
  14584. }
  14585. //xzw :
  14586. tileset.dispatchEvent({type:'tileLoaded',tileContent}) //每一个tile加载完要更改透明度等
  14587. }
  14588. }),
  14589. onTileLoad: (tile) => __awaiter(this, void 0, void 0, function* () {
  14590. if (tileset) {
  14591. if (!orientationDetected && (tile === null || tile === void 0 ? void 0 : tile.depth) <= MAX_DEPTH_FOR_ORIENTATION) {
  14592. detectOrientation(tile);
  14593. }
  14594. tileset._frameNumber++;
  14595. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  14596. }
  14597. }),
  14598. onTileUnload: (tile) => {
  14599. unloadQueue.push(tile);
  14600. },
  14601. onTileError: (tile, message) => {
  14602. console.error('Tile error', tile.id, message);
  14603. },
  14604. };
  14605. const tileset = new Tileset3D(tilesetJson, Object.assign(Object.assign({}, tileOptions), { loadOptions: Object.assign(Object.assign({}, loadersGLOptions), { maxConcurrency: options.maxConcurrency, worker: options.worker, gltf: {
  14606. loadImages: false,
  14607. }, '3d-tiles': {
  14608. loadGLTF: false
  14609. } }) }));
  14610. tileset.boxMap = boxMap //add
  14611. // transformations
  14612. const threeMat = new Matrix4$1();
  14613. const tileTransform = new Matrix4$1();
  14614. const rootCenter = new Vector3$1();
  14615. let orientationDetected = false;
  14616. if (tileset.root.boundingVolume) {
  14617. if (tileset.root.header.boundingVolume.region) {
  14618. // TODO: Handle region type bounding volumes
  14619. // https://github.com/visgl/loaders.gl/issues/1994
  14620. console.warn("Cannot apply a model matrix to bounding volumes of type region. Tileset stays in original geo-coordinates.");
  14621. options.geoTransform = GeoTransform.WGS84Cartesian;
  14622. }
  14623. tileTransform.setPosition(tileset.root.boundingVolume.center[0], tileset.root.boundingVolume.center[1], tileset.root.boundingVolume.center[2]);
  14624. }
  14625. else {
  14626. console.warn("Bounding volume not found, no transformations applied");
  14627. }
  14628. if (options.debug) {
  14629. const box = loadersBoundingBoxToMesh(tileset.root);
  14630. tileBoxes.add(box);
  14631. boxMap[tileset.root.id] = box;
  14632. }
  14633. let disposeFlag = false;
  14634. let loadingEnded = false;
  14635. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  14636. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).normalize());
  14637. // Extra stats
  14638. tileset.stats.get('Loader concurrency').count = options.maxConcurrency;
  14639. tileset.stats.get('Maximum SSE').count = options.maximumScreenSpaceError;
  14640. tileset.stats.get('Maximum mem usage').count = options.maximumMemoryUsage;
  14641. let timer = 0;
  14642. let lastCameraTransform = null;
  14643. let lastCameraAspect = null;
  14644. const lastCameraPosition = new Vector3$1(Infinity, Infinity, Infinity);
  14645. let sseDenominator = null;
  14646. root.updateMatrixWorld(true);
  14647. const lastRootTransform = new Matrix4$1().copy(root.matrixWorld);
  14648. const rootTransformInverse = new Matrix4$1().copy(lastRootTransform).invert();
  14649. tileset.lastRootTransform = lastRootTransform //add
  14650. detectOrientation(tileset.root);
  14651. updateResetTransform();
  14652. if (options.debug) {
  14653. boxMap[tileset.root.id].applyMatrix4(threeMat);
  14654. tileBoxes.matrixWorld.copy(root.matrixWorld);
  14655. }
  14656. if (options.geoTransform == GeoTransform.Mercator) {
  14657. const coords = datumsToSpherical(tileset.cartographicCenter[1], tileset.cartographicCenter[0]);
  14658. rootCenter.set(coords.x, 0, -coords.y);
  14659. root.position.copy(rootCenter);
  14660. root.rotation.set(-Math.PI / 2, 0, 0);
  14661. root.updateMatrixWorld(true);
  14662. }
  14663. else if (options.geoTransform == GeoTransform.WGS84Cartesian) {
  14664. root.applyMatrix4(tileTransform);
  14665. root.updateMatrixWorld(true);
  14666. rootCenter.copy(root.position);
  14667. }
  14668. function detectOrientation(tile) {
  14669. if (!tile.boundingVolume.halfAxes) {
  14670. return;
  14671. }
  14672. const halfAxes = tile.boundingVolume.halfAxes;
  14673. const orientationMatrix = new Matrix4$1()
  14674. .extractRotation(getMatrix4FromHalfAxes(halfAxes))
  14675. .premultiply(new Matrix4$1().extractRotation(rootTransformInverse));
  14676. const rotation = new Euler().setFromRotationMatrix(orientationMatrix);
  14677. if (!rotation.equals(new Euler())) {
  14678. orientationDetected = true;
  14679. const pos = new Vector3$1(tileTransform.elements[12], tileTransform.elements[13], tileTransform.elements[14]);
  14680. tileTransform.extractRotation(orientationMatrix);
  14681. tileTransform.setPosition(pos);
  14682. updateResetTransform();
  14683. }
  14684. }
  14685. function updateResetTransform() {
  14686. if (options.geoTransform != GeoTransform.WGS84Cartesian) {
  14687. // Reset the current model matrix and apply our own transformation
  14688. //threeMat.copy(tileTransform).invert();
  14689. //threeMat.premultiply(lastRootTransform); //xzw删 被下面copy这句覆盖了
  14690. let tileTransInvert = new Matrix4$1().copy(tileTransform).invert()
  14691. threeMat.copy(lastRootTransform).multiply(tileTransInvert);
  14692. tileset.modelMatrix = new Matrix4(threeMat.toArray());
  14693. //console.log('update tileset ModelMatrix', tileset.modelMatrix.elements)
  14694. tileset.tileTransInvert = tileTransInvert.toArray() // add for volumebox
  14695. }
  14696. }
  14697. // 更新瓦片显隐和瓦片迭代更新
  14698. function tilesetUpdate(tileset, renderMap, renderer, camera) {
  14699. if (disposeFlag || options.pauseTilesetUpdate) {// !zeg改 pauseTilesetUpdate
  14700. return
  14701. }
  14702. // Assumes camera fov, near and far are not changing
  14703. if (!sseDenominator || camera.aspect != lastCameraAspect) {
  14704. const loadersFrustum = new PerspectiveFrustum({
  14705. fov: (camera.fov / 180) * Math.PI,
  14706. aspectRatio: camera.aspect,
  14707. near: camera.near,
  14708. far: camera.far,
  14709. });
  14710. sseDenominator = loadersFrustum.sseDenominator;
  14711. lastCameraAspect = camera.aspect;
  14712. if(camera.aspect == 0)return//add
  14713. if (options.debug) {
  14714. console.log('Updated sse denonimator:', sseDenominator);
  14715. }
  14716. }
  14717. const frustum = getCameraFrustum(camera);
  14718. const planes = frustum.planes.map((plane) => new Plane(plane.normal.toArray(), plane.constant));
  14719. const cullingVolume = new CullingVolume(planes);
  14720. const rendererSize = new Vector2$1();
  14721. renderer.getSize(rendererSize);
  14722. const frameState = {
  14723. camera: {
  14724. position: lastCameraPosition.toArray(),
  14725. },
  14726. height: rendererSize.y,
  14727. frameNumber: tileset._frameNumber,
  14728. sseDenominator: sseDenominator,
  14729. cullingVolume: cullingVolume,
  14730. viewport: {
  14731. id: 0,
  14732. },
  14733. };
  14734. tileset._cache.reset();
  14735. tileset._traverser.traverse(tileset.root, frameState, tileset.options);
  14736. for (const tile of tileset.tiles) {
  14737. if (tile.selected) {
  14738. if (!renderMap[tile.id]) {
  14739. console.error('TILE SELECTED BUT NOT LOADED!!', tile.id);
  14740. }
  14741. else {
  14742. // Make sure it's visible
  14743. if(!renderMap[tile.id].visible){
  14744. if(visiVertexCount<maxVertexVisi){
  14745. renderMap[tile.id].visible = true;
  14746. visiVertexCount += renderMap[tile.id].vertexCount //xzw add
  14747. options.debug && (boxMap[tile.id].material.opacity = 1 , boxMap[tile.id].children[0].sprite.material.opacity = 1 )
  14748. }else{
  14749. //console.log('超出', visiVertexCount)
  14750. }
  14751. }
  14752. /* if(!renderMap[tile.id].realVisible()){
  14753. console.error('!realVisible')
  14754. } */
  14755. }
  14756. }
  14757. else {
  14758. if (renderMap[tile.id]) {
  14759. if(renderMap[tile.id].visible){
  14760. renderMap[tile.id].visible = false;
  14761. options.debug && (boxMap[tile.id].material.opacity = 0.1, boxMap[tile.id].children[0].sprite.material.opacity = 0.1)
  14762. visiVertexCount -= renderMap[tile.id].vertexCount //xzw add
  14763. }
  14764. }
  14765. }
  14766. }
  14767. while (unloadQueue.length > 0) {
  14768. const tile = unloadQueue.pop();
  14769. if (renderMap[tile.id] && tile.contentState == TILE_CONTENT_STATE.UNLOADED) {
  14770. //console.log('removevisi', renderMap[tile.id].visible) 如果是true,visiVertexCount要减
  14771. root.remove(renderMap[tile.id]);
  14772. disposeNode(renderMap[tile.id]);
  14773. delete renderMap[tile.id];
  14774. }
  14775. if (boxMap[tile.id]) {
  14776. disposeNode(boxMap[tile.id]);
  14777. tileBoxes.remove(boxMap[tile.id]);
  14778. delete boxMap[tile.id];
  14779. }
  14780. }
  14781. const tilesLoaded = tileset.stats.get('Tiles Loaded').count;
  14782. const tilesLoading = tileset.stats.get('Tiles Loading').count;
  14783. if (props.onProgress) {
  14784. props.onProgress(tilesLoaded, tilesLoaded + tilesLoading);
  14785. }
  14786. if (props.loadingManager && !loadingEnded) {
  14787. if (tilesLoading == 0 &&
  14788. (options.preloadTilesCount == null ||
  14789. tilesLoaded >= options.preloadTilesCount)) {
  14790. loadingEnded = true;
  14791. props.loadingManager.itemEnd(props.url);
  14792. }
  14793. }
  14794. return frameState;
  14795. }
  14796. return {
  14797. model: root,
  14798. runtime: {
  14799. getTileset: () => {
  14800. return tileset;
  14801. },
  14802. getStats: () => {
  14803. return tileset.stats;
  14804. },
  14805. showTiles: (visible) => {
  14806. tileBoxes.visible = visible;
  14807. },
  14808. setWireframe: (wireframe) => {
  14809. options.wireframe = wireframe;
  14810. root.traverse((object) => {
  14811. if (object instanceof Mesh) {
  14812. object.material.wireframe = wireframe;
  14813. }
  14814. });
  14815. },
  14816. setDebug: (debug) => {
  14817. options.debug = debug;
  14818. tileBoxes.visible = debug;
  14819. },
  14820. setShading: (shading) => {
  14821. options.shading = shading;
  14822. },
  14823. getTileBoxes: () => {
  14824. return tileBoxes;
  14825. },
  14826. setViewDistanceScale: (scale) => {
  14827. tileset.options.viewDistanceScale = scale;
  14828. tileset._frameNumber++;
  14829. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  14830. },
  14831. setHideGround: (enabled) => {
  14832. pointcloudUniforms.hideGround.value = enabled;
  14833. },
  14834. setPointCloudColoring: (selection) => {
  14835. pointcloudUniforms.coloring.value = selection;
  14836. },
  14837. setElevationRange: (range) => {
  14838. pointcloudUniforms.elevationRange.value.set(range[0], range[1]);
  14839. },
  14840. setMaxIntensity: (intensity) => {
  14841. pointcloudUniforms.maxIntensity.value = intensity;
  14842. },
  14843. setIntensityContrast: (contrast) => {
  14844. pointcloudUniforms.intensityContrast.value = contrast;
  14845. },
  14846. setPointAlpha: (alpha) => {
  14847. pointcloudUniforms.alpha.value = alpha;
  14848. },
  14849. getLatLongHeightFromPosition: (position) => {
  14850. const cartographicPosition = tileset.ellipsoid.cartesianToCartographic(new Vector3$1().copy(position).applyMatrix4(new Matrix4$1().copy(threeMat).invert()).toArray());
  14851. return {
  14852. lat: cartographicPosition[1],
  14853. long: cartographicPosition[0],
  14854. height: cartographicPosition[2],
  14855. };
  14856. },
  14857. getPositionFromLatLongHeight: (coord) => {
  14858. const cartesianPosition = tileset.ellipsoid.cartographicToCartesian([coord.long, coord.lat, coord.height]);
  14859. return new Vector3$1(...cartesianPosition).applyMatrix4(threeMat);
  14860. },
  14861. getCameraFrustum: (camera) => {
  14862. const frustum = getCameraFrustum(camera);
  14863. const meshes = frustum.planes
  14864. .map((plane) => new Plane(plane.normal.toArray(), plane.constant))
  14865. .map((loadersPlane) => loadersPlaneToMesh(loadersPlane));
  14866. const model = new Group();
  14867. for (const mesh of meshes)
  14868. model.add(mesh);
  14869. return model;
  14870. },
  14871. update: function (dt, renderer, camera, ifForce) {
  14872. cameraReference = camera;
  14873. rendererReference = renderer;
  14874. timer += dt;
  14875. if(!ifForce) ifForce = tileset.nextForceUpdate
  14876. tileset.nextForceUpdate = false
  14877. if(tileset.needRenderNext){//必须在下一帧渲染刷新否则无法显示
  14878. viewer.dispatchEvent('content_changed')
  14879. }
  14880. tileset.needRenderNext = ifForce
  14881. if (tileset && (timer >= UPDATE_INTERVAL || ifForce)) {
  14882. if (!lastRootTransform.equals(root.matrixWorld)) {
  14883. timer = 0;
  14884. lastRootTransform.copy(root.matrixWorld);
  14885. updateResetTransform();
  14886. const rootCenter = new Vector3$1().setFromMatrixPosition(lastRootTransform);
  14887. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  14888. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).applyMatrix4(lastRootTransform).normalize());
  14889. rootTransformInverse.copy(lastRootTransform).invert();
  14890. if (options.debug) {
  14891. /* console.log('move', tileset.root.id, boxMap[tileset.root.id].matrix.elements, boxMap[tileset.root.id].matrixWorld.elements)
  14892. boxMap[tileset.root.id].matrix.copy(root.matrixWorld);
  14893. boxMap[tileset.root.id].matrixWorld.copy(root.matrixWorld); */
  14894. //boxMap[tileset.root.id].applyMatrix4(threeMat);
  14895. tileBoxes.matrix.copy(root.matrixWorld);
  14896. //boxMap[tileset.root.id].matrixWorld.copy(threeMat);
  14897. //boxMap[tileset.root.id].applyMatrix4(lastRootTransform);//boxMap[tileset.root.id].applyMatrix4(lastRootTransform);
  14898. //boxMap[tileset.root.id].updateWorldMatrix()
  14899. }
  14900. }
  14901. if (this.lastCameraTransform == null) {
  14902. this.lastCameraTransform = new Matrix4$1().copy(camera.matrixWorld);
  14903. }
  14904. else {
  14905. const cameraChanged = !camera.matrixWorld.equals(this.lastCameraTransform) ||
  14906. !(camera.aspect == lastCameraAspect);
  14907. if (cameraChanged || ifForce) {
  14908. timer = 0;
  14909. tileset._frameNumber++;
  14910. camera.getWorldPosition(lastCameraPosition);
  14911. this.lastCameraTransform.copy(camera.matrixWorld);
  14912. tilesetUpdate(tileset, renderMap, renderer, camera);
  14913. }
  14914. }
  14915. }/* else{
  14916. console.log('11')
  14917. } */
  14918. },
  14919. dispose: function () {
  14920. disposeFlag = true;
  14921. tileset._destroy();
  14922. while (root.children.length > 0) {
  14923. const obj = root.children[0];
  14924. disposeNode(obj);
  14925. root.remove(obj);
  14926. }
  14927. while (tileBoxes.children.length > 0) {
  14928. const obj = tileBoxes.children[0];
  14929. tileBoxes.remove(obj);
  14930. obj.geometry.dispose();
  14931. obj.material.dispose();
  14932. }
  14933. if (ktx2Loader) {
  14934. ktx2Loader.dispose();
  14935. }
  14936. if (dracoLoader) {
  14937. dracoLoader.dispose();
  14938. }
  14939. },
  14940. limit2lowestDepth: isLowest => {//zeg add 设置是否限制为最低精度tile深度
  14941. maxDepth = isLowest ? 1 : 100 //影响到shouldRefine, 检查方法:可以看到当maxDepth降低了之后viewer.objs.children[0].runtime.getTileset().tiles.filter(e=> e.tileContent.visible)变少
  14942. if (cameraReference) {
  14943. tileset._frameNumber++
  14944. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference)
  14945. }
  14946. },
  14947. },
  14948. };
  14949. });
  14950. }
  14951. }
  14952. function createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse) {
  14953. return __awaiter(this, void 0, void 0, function* () {
  14954. return new Promise((resolve, reject) => {
  14955. var _a;
  14956. const rotateX = new Matrix4$1().makeRotationAxis(new Vector3$1(1, 0, 0), Math.PI / 2);
  14957. const shouldRotate = ((_a = tile.tileset.asset) === null || _a === void 0 ? void 0 : _a.gltfUpAxis) !== "Z";
  14958. // The computed trasnform already contains the root's transform, so we have to invert it
  14959. //const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(tileMatrix)//.premultiply(rootTransformInverse); //xzw 删。原先的会造成移动后tiles错乱
  14960. //const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(tile.tileset.modelMatrix).premultiply(rootTransformInverse)
  14961. // 这句同tile.computedTransform左乘tileTransform。 因为tileTransform拿不到所以使用modelMatrix。modelMatrix为tileTransform左乘rootTransform, 所以再左乘rootTransformInverse
  14962. //改动:contentTransform中的computedTransform 去掉左乘 root.modelMatrixWorld , 因为移动过后这个computedTransform没更新
  14963. gltfLoader.parse(
  14964. tile.content.type == 'glTF' ? tile.content.gltf.gltfArrayBuffer : tile.content.gltfArrayBuffer,//tile.content.gltfArrayBuffer,
  14965. tile.contentUrl ? tile.contentUrl.substr(0, tile.contentUrl.lastIndexOf('/') + 1) : '',
  14966. (gltf) => {
  14967. const tileContent = gltf.scenes[0];
  14968. tileContent.vertexCount = 0 //xzw add
  14969. tile.tileContent = tileContent //xzw add
  14970. let needUpdate
  14971. if(tile.rtcCenterState != !!tile.content.rtcCenter){ // 等mesh加载好才知道rtcCenter,每个mesh坐标都不一样
  14972. needUpdate = true
  14973. //console.error('rtcCenter有变化?!')
  14974. }
  14975. tile.rtcCenterState = rtcCenterGlobal = !!tile.content.rtcCenter
  14976. let contentTransform = tile.getContentTransform(needUpdate)
  14977. if(tile.content.rtcCenter){//大部分模型无 rtcCenter
  14978. //console.error('rtcCenter有?!') //似乎bounding中包含这个信息了 所以getContentTransform不含这个
  14979. let tranM = new Matrix4$1()
  14980. tranM.makeTranslation(tile.content.rtcCenter[0], tile.content.rtcCenter[1], tile.content.rtcCenter[2])
  14981. contentTransform.premultiply(tranM)
  14982. }
  14983. if(needUpdate ){
  14984. tile._updateBoundingVolume(tile.header) //add 重新更新
  14985. }
  14986. if (shouldRotate) { //大部分模型 无需 Rotate
  14987. contentTransform.multiply(rotateX); // convert from GLTF Y-up to Z-up
  14988. }
  14989. tileContent.applyMatrix4(contentTransform);
  14990. //'https://testgis.4dage.com/LVBADUI_qp/tileset.json', //村庄 这个案例是 要rotateX 且有rtcCenter的。boundingVolume已经是转换这两者后的值所以getContentTransform不加这个
  14991. //tile总共要左乘的矩阵 rotateX -> tileTransInvert * computedTransform -> 对geometry的tranM修改 -> 整个模型的matrixWorld
  14992. tileContent.traverse((object) => {
  14993. if (object.type == "Mesh") {
  14994. const mesh = object;
  14995. //mesh.tileId = tile.id//add
  14996. const originalMaterial = mesh.material;
  14997. const originalMap = originalMaterial.map;
  14998. if (options.material) {
  14999. mesh.material = options.material.clone();
  15000. originalMaterial.dispose();
  15001. }
  15002. else if (options.shading == Shading.FlatTexture) {
  15003. mesh.material = unlitMaterial.clone();
  15004. originalMaterial.dispose();
  15005. }
  15006. if (options.shading != Shading.ShadedNoTexture) {
  15007. if (mesh.material.type == "ShaderMaterial" && !(mesh.material instanceof MeshBasicMaterial)) {//改
  15008. mesh.material.uniforms.map = { value: originalMap };
  15009. }
  15010. else {
  15011. mesh.material.map = originalMap;
  15012. }
  15013. }
  15014. else {
  15015. if (originalMap) {
  15016. originalMap.dispose();
  15017. }
  15018. mesh.material.map = null;
  15019. }
  15020. if (options.shaderCallback) {
  15021. mesh.onBeforeRender = options.shaderCallback;
  15022. }
  15023. mesh.material.wireframe = options.wireframe;
  15024. if (options.computeNormals) {
  15025. mesh.geometry.computeVertexNormals();
  15026. }
  15027. //xzw add:
  15028. tileContent.vertexCount += mesh.geometry.attributes.position.count
  15029. //------------------add on 2023.1.16----zeg
  15030. //mesh.geometry.applyMatrix4(contentTransform)
  15031. /* if (tile.content.rtcCenter) {
  15032. // 有些b3dm模型会将坐标写在源码的rtcCenter里 如https://testgis.4dage.com/LVBADUI_qp/tileset.json
  15033. mesh.geometry.translate(tile.content.rtcCenter[0], tile.content.rtcCenter[1], tile.content.rtcCenter[2])
  15034. } else {
  15035. mesh.geometry.scale(1, 1, -1) // 调整缩放,对应box也要进行变换(scaleZ对应box[2])
  15036. } */
  15037. //---------------------
  15038. }
  15039. });
  15040. resolve(tileContent);
  15041. },
  15042. (e) => {
  15043. reject(new Error(`error parsing gltf in tile ${tile.id}: ${e}`));
  15044. }
  15045. );
  15046. });
  15047. });
  15048. }
  15049. function createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse) {
  15050. const d = {
  15051. rtc_center: tile.content.rtcCenter,
  15052. points: tile.content.attributes.positions,
  15053. intensities: tile.content.attributes.intensity,
  15054. classifications: tile.content.attributes.classification,
  15055. rgb: null,
  15056. rgba: null,
  15057. };
  15058. const { colors } = tile.content.attributes;
  15059. if (colors && colors.size === 3) {
  15060. d.rgb = colors.value;
  15061. }
  15062. if (colors && colors.size === 4) {
  15063. d.rgba = colors.value;
  15064. }
  15065. const geometry = new BufferGeometry();
  15066. geometry.setAttribute('position', new Float32BufferAttribute(d.points, 3));
  15067. const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(rootTransformInverse);
  15068. if (d.rgba) {
  15069. geometry.setAttribute('color', new Float32BufferAttribute(d.rgba, 4));
  15070. }
  15071. else if (d.rgb) {
  15072. geometry.setAttribute('color', new Uint8BufferAttribute(d.rgb, 3, true));
  15073. }
  15074. if (d.intensities) {
  15075. geometry.setAttribute('intensity',
  15076. // Handles both 16bit or 8bit intensity values
  15077. new BufferAttribute(d.intensities, 1, true));
  15078. }
  15079. if (d.classifications) {
  15080. geometry.setAttribute('classification', new Uint8BufferAttribute(d.classifications, 1, false));
  15081. }
  15082. const tileContent = new Points(geometry, options.material || pointcloudMaterial);
  15083. if (d.rtc_center) {
  15084. const c = d.rtc_center;
  15085. contentTransform.multiply(new Matrix4$1().makeTranslation(c[0], c[1], c[2]));
  15086. }
  15087. tileContent.applyMatrix4(contentTransform);
  15088. return tileContent;
  15089. }
  15090. function disposeMaterial(material) {
  15091. var _a, _b, _c, _d;
  15092. if ((_a = material === null || material === void 0 ? void 0 : material.uniforms) === null || _a === void 0 ? void 0 : _a.map) {
  15093. (_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();
  15094. }
  15095. else if (material.map) {
  15096. (_d = material.map) === null || _d === void 0 ? void 0 : _d.dispose();
  15097. }
  15098. material.dispose();
  15099. }
  15100. function disposeNode(node) {
  15101. node.traverse((object) => {
  15102. if (object.isMesh) {
  15103. object.geometry.dispose();
  15104. if (object.material.isMaterial) {
  15105. disposeMaterial(object.material);
  15106. }
  15107. else {
  15108. // an array of materials
  15109. for (const material of object.material) {
  15110. disposeMaterial(material);
  15111. }
  15112. }
  15113. }
  15114. });
  15115. for (let i = node.children.length - 1; i >= 0; i--) {
  15116. const obj = node.children[i];
  15117. node.remove(obj);
  15118. }
  15119. }
  15120. export { GeoTransform, Loader3DTiles, PointCloudColoring, Shading };
  15121. //# sourceMappingURL=three-loader-3dtiles.esm.js.map
  15122. /*
  15123. 关键搜寻:
  15124. Loader3DTiles : const tileset = new Tileset3D
  15125. tileset.dispatchEvent({type:'tileLoaded',tileContent})
  15126. createGLTFNodes(gltfLoader 创建tile
  15127. executeTraversal(root, frameState) 遍历root
  15128. lastRootTransform rootTransformInverse
  15129. tileset._loadTiles 依次加载tiles
  15130. _getPriority 加载优先级 加了一句
  15131. 笔记:
  15132. 主要类:
  15133. class tileset3D 最外层整体。 获取方法: viewer.objs.children[index].runtime.getTileset()。 .tiles包含所有tiles
  15134. class tileHeader 也就是tileset里面的一个个tile 。 其上有.tileset
  15135. tileset里算的tileTransform之后是不会改变的, tile.transform也是,是json里的。
  15136. tileset.modelMatrix (通常这个值很大) 会随着位移改变
  15137. tile.computedTransform 被我修改了,之前左乘了tileset.modelMatrix,现只包含了transform信息 _updateTransform(parentTransfor 其中有_updateBoundingVolume,这个影响可见性, 在computeVisibilityWithPlaneMask中计算
  15138. tileset._cache.trim(), 然后再update //可以将所有不可见的tiles dispose
  15139. 相机靠近容易缺块的bug暂时修改如下: _visible是由computeVisibilityWithPlaneMask计算得
  15140. get isVisibleAndInRequestVolume() {
  15141. return this._inRequestVolume; //去掉了_visible ||
  15142. }
  15143. 显示所有tile似乎也不会卡顿. 但好像影响了加载顺序从而变慢了。visiVertexCount过量。 怀疑应该还是文件的bound有问题。
  15144. 原本会消失的地方虽然不会消失了但一直是模糊的
  15145. =========
  15146. 访问所有tile:
  15147. viewer.objs.children[0].runtime.getTileset().tiles
  15148. 它的mesh: tile.tileContent
  15149. 或者直接得到所有mesh: viewer.objs.children[0].children
  15150. tile.depth最低为1 , root是0
  15151. */