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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284
  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 visiGeoCount = 0
  22. const maxVertexVisi = 5e6
  23. const maxTexVisi = 500
  24. const maxDepth = 100
  25. function getGpuMemoryUsage(win = window){//总的
  26. let c = 0
  27. viewer.objs.children.filter(e=>{
  28. if(e.fileType == '3dTiles'){
  29. e.traverse(child=>{
  30. if(child.runtime){
  31. let tileset3D = child.runtime.getTileset()
  32. c += tileset3D.gpuMemoryUsageInBytes
  33. return {stopContinue:true}
  34. }
  35. })
  36. }
  37. })
  38. if(win.parent != win){//还有父级页面。 暂时只有子级需要考虑父级,假设父级在前台时子级已经销毁
  39. c += getGpuMemoryUsage(win.parent)
  40. }
  41. viewer.tiles3dMemoryUsage = c
  42. return c
  43. }
  44. function __awaiter(thisArg, _arguments, P, generator) {
  45. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  46. return new (P || (P = Promise))(function (resolve, reject) {
  47. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  48. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  49. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  50. step((generator = generator.apply(thisArg, _arguments || [])).next());
  51. });
  52. }
  53. function assert$7(condition, message) {
  54. if (!condition) {
  55. throw new Error(message || 'loader assertion failed.');
  56. }
  57. }
  58. const isBrowser$2 = Boolean(typeof process !== 'object' || String(process) !== '[object process]' || process.browser);
  59. const matches$1 = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  60. matches$1 && parseFloat(matches$1[1]) || 0;
  61. const VERSION$8 = "3.1.4" ;
  62. function assert$6(condition, message) {
  63. if (!condition) {
  64. throw new Error(message || 'loaders.gl assertion failed.');
  65. }
  66. }
  67. const globals$1 = {
  68. self: typeof self !== 'undefined' && self,
  69. window: typeof window !== 'undefined' && window,
  70. global: typeof global !== 'undefined' && global,
  71. document: typeof document !== 'undefined' && document
  72. };
  73. const global_ = globals$1.global || globals$1.self || globals$1.window || {};
  74. const isBrowser$1 = typeof process !== 'object' || String(process) !== '[object process]' || process.browser;
  75. const isWorker = typeof importScripts === 'function';
  76. const isMobile = typeof window !== 'undefined' && typeof window.orientation !== 'undefined';
  77. const matches = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  78. matches && parseFloat(matches[1]) || 0;
  79. function _defineProperty(obj, key, value) {
  80. if (key in obj) {
  81. Object.defineProperty(obj, key, {
  82. value: value,
  83. enumerable: true,
  84. configurable: true,
  85. writable: true
  86. });
  87. } else {
  88. obj[key] = value;
  89. }
  90. return obj;
  91. }
  92. class WorkerJob {
  93. constructor(jobName, workerThread) {
  94. _defineProperty(this, "name", void 0);
  95. _defineProperty(this, "workerThread", void 0);
  96. _defineProperty(this, "isRunning", void 0);
  97. _defineProperty(this, "result", void 0);
  98. _defineProperty(this, "_resolve", void 0);
  99. _defineProperty(this, "_reject", void 0);
  100. this.name = jobName;
  101. this.workerThread = workerThread;
  102. this.isRunning = true;
  103. this._resolve = () => {};
  104. this._reject = () => {};
  105. this.result = new Promise((resolve, reject) => {
  106. this._resolve = resolve;
  107. this._reject = reject;
  108. });
  109. }
  110. postMessage(type, payload) {
  111. this.workerThread.postMessage({
  112. source: 'loaders.gl',
  113. type,
  114. payload
  115. });
  116. }
  117. done(value) {
  118. assert$6(this.isRunning);
  119. this.isRunning = false;
  120. this._resolve(value);
  121. }
  122. error(error) {
  123. assert$6(this.isRunning);
  124. this.isRunning = false;
  125. this._reject(error);
  126. }
  127. }
  128. const workerURLCache = new Map();
  129. function getLoadableWorkerURL(props) {
  130. assert$6(props.source && !props.url || !props.source && props.url);
  131. let workerURL = workerURLCache.get(props.source || props.url);
  132. if (!workerURL) {
  133. if (props.url) {
  134. workerURL = getLoadableWorkerURLFromURL(props.url);
  135. workerURLCache.set(props.url, workerURL);
  136. }
  137. if (props.source) {
  138. workerURL = getLoadableWorkerURLFromSource(props.source);
  139. workerURLCache.set(props.source, workerURL);
  140. }
  141. }
  142. assert$6(workerURL);
  143. return workerURL;
  144. }
  145. function getLoadableWorkerURLFromURL(url) {
  146. if (!url.startsWith('http')) {
  147. return url;
  148. }
  149. const workerSource = buildScriptSource(url);
  150. return getLoadableWorkerURLFromSource(workerSource);
  151. }
  152. function getLoadableWorkerURLFromSource(workerSource) {
  153. const blob = new Blob([workerSource], {
  154. type: 'application/javascript'
  155. });
  156. return URL.createObjectURL(blob);
  157. }
  158. function buildScriptSource(workerUrl) {
  159. return "try {\n importScripts('".concat(workerUrl, "');\n} catch (error) {\n console.error(error);\n throw error;\n}");
  160. }
  161. function getTransferList(object, recursive = true, transfers) {
  162. const transfersSet = transfers || new Set();
  163. if (!object) ; else if (isTransferable(object)) {
  164. transfersSet.add(object);
  165. } else if (isTransferable(object.buffer)) {
  166. transfersSet.add(object.buffer);
  167. } else if (ArrayBuffer.isView(object)) ; else if (recursive && typeof object === 'object') {
  168. for (const key in object) {
  169. getTransferList(object[key], recursive, transfersSet);
  170. }
  171. }
  172. return transfers === undefined ? Array.from(transfersSet) : [];
  173. }
  174. function isTransferable(object) {
  175. if (!object) {
  176. return false;
  177. }
  178. if (object instanceof ArrayBuffer) {
  179. return true;
  180. }
  181. if (typeof MessagePort !== 'undefined' && object instanceof MessagePort) {
  182. return true;
  183. }
  184. if (typeof ImageBitmap !== 'undefined' && object instanceof ImageBitmap) {
  185. return true;
  186. }
  187. if (typeof OffscreenCanvas !== 'undefined' && object instanceof OffscreenCanvas) {
  188. return true;
  189. }
  190. return false;
  191. }
  192. const NOOP = () => {};
  193. class WorkerThread {
  194. static isSupported() {
  195. return typeof Worker !== 'undefined';
  196. }
  197. constructor(props) {
  198. _defineProperty(this, "name", void 0);
  199. _defineProperty(this, "source", void 0);
  200. _defineProperty(this, "url", void 0);
  201. _defineProperty(this, "terminated", false);
  202. _defineProperty(this, "worker", void 0);
  203. _defineProperty(this, "onMessage", void 0);
  204. _defineProperty(this, "onError", void 0);
  205. _defineProperty(this, "_loadableURL", '');
  206. const {
  207. name,
  208. source,
  209. url
  210. } = props;
  211. assert$6(source || url);
  212. this.name = name;
  213. this.source = source;
  214. this.url = url;
  215. this.onMessage = NOOP;
  216. this.onError = error => console.log(error);
  217. this.worker = this._createBrowserWorker();
  218. }
  219. destroy() {
  220. this.onMessage = NOOP;
  221. this.onError = NOOP;
  222. this.worker.terminate();
  223. this.terminated = true;
  224. }
  225. get isRunning() {
  226. return Boolean(this.onMessage);
  227. }
  228. postMessage(data, transferList) {
  229. transferList = transferList || getTransferList(data);
  230. this.worker.postMessage(data, transferList);
  231. }
  232. _getErrorFromErrorEvent(event) {
  233. let message = 'Failed to load ';
  234. message += "worker ".concat(this.name, " from ").concat(this.url, ". ");
  235. if (event.message) {
  236. message += "".concat(event.message, " in ");
  237. }
  238. if (event.lineno) {
  239. message += ":".concat(event.lineno, ":").concat(event.colno);
  240. }
  241. return new Error(message);
  242. }
  243. _createBrowserWorker() {
  244. this._loadableURL = getLoadableWorkerURL({
  245. source: this.source,
  246. url: this.url
  247. });
  248. const worker = new Worker(this._loadableURL, {
  249. name: this.name
  250. });
  251. worker.onmessage = event => {
  252. if (!event.data) {
  253. this.onError(new Error('No data received'));
  254. } else {
  255. this.onMessage(event.data);
  256. }
  257. };
  258. worker.onerror = error => {
  259. this.onError(this._getErrorFromErrorEvent(error));
  260. this.terminated = true;
  261. };
  262. worker.onmessageerror = event => console.error(event);
  263. return worker;
  264. }
  265. }
  266. class WorkerPool {
  267. constructor(props) {
  268. _defineProperty(this, "name", 'unnamed');
  269. _defineProperty(this, "source", void 0);
  270. _defineProperty(this, "url", void 0);
  271. _defineProperty(this, "maxConcurrency", 1);
  272. _defineProperty(this, "maxMobileConcurrency", 1);
  273. _defineProperty(this, "onDebug", () => {});
  274. _defineProperty(this, "reuseWorkers", true);
  275. _defineProperty(this, "props", {});
  276. _defineProperty(this, "jobQueue", []);
  277. _defineProperty(this, "idleQueue", []);
  278. _defineProperty(this, "count", 0);
  279. _defineProperty(this, "isDestroyed", false);
  280. this.source = props.source;
  281. this.url = props.url;
  282. this.setProps(props);
  283. }
  284. destroy() {
  285. this.idleQueue.forEach(worker => worker.destroy());
  286. this.isDestroyed = true;
  287. }
  288. setProps(props) {
  289. this.props = { ...this.props,
  290. ...props
  291. };
  292. if (props.name !== undefined) {
  293. this.name = props.name;
  294. }
  295. if (props.maxConcurrency !== undefined) {
  296. this.maxConcurrency = props.maxConcurrency;
  297. }
  298. if (props.maxMobileConcurrency !== undefined) {
  299. this.maxMobileConcurrency = props.maxMobileConcurrency;
  300. }
  301. if (props.reuseWorkers !== undefined) {
  302. this.reuseWorkers = props.reuseWorkers;
  303. }
  304. if (props.onDebug !== undefined) {
  305. this.onDebug = props.onDebug;
  306. }
  307. }
  308. async startJob(name, onMessage = (job, type, data) => job.done(data), onError = (job, error) => job.error(error)) {
  309. const startPromise = new Promise(onStart => {
  310. this.jobQueue.push({
  311. name,
  312. onMessage,
  313. onError,
  314. onStart
  315. });
  316. return this;
  317. });
  318. this._startQueuedJob();
  319. return await startPromise;
  320. }
  321. async _startQueuedJob() {
  322. if (!this.jobQueue.length) {
  323. return;
  324. }
  325. const workerThread = this._getAvailableWorker();
  326. if (!workerThread) {
  327. return;
  328. }
  329. const queuedJob = this.jobQueue.shift();
  330. if (queuedJob) {
  331. this.onDebug({
  332. message: 'Starting job',
  333. name: queuedJob.name,
  334. workerThread,
  335. backlog: this.jobQueue.length
  336. });
  337. const job = new WorkerJob(queuedJob.name, workerThread);
  338. workerThread.onMessage = data => queuedJob.onMessage(job, data.type, data.payload);
  339. workerThread.onError = error => queuedJob.onError(job, error);
  340. queuedJob.onStart(job);
  341. try {
  342. await job.result;
  343. } finally {
  344. this.returnWorkerToQueue(workerThread);
  345. }
  346. }
  347. }
  348. returnWorkerToQueue(worker) {
  349. const shouldDestroyWorker = this.isDestroyed || !this.reuseWorkers || this.count > this._getMaxConcurrency();
  350. if (shouldDestroyWorker) {
  351. worker.destroy();
  352. this.count--;
  353. } else {
  354. this.idleQueue.push(worker);
  355. }
  356. if (!this.isDestroyed) {
  357. this._startQueuedJob();
  358. }
  359. }
  360. _getAvailableWorker() {
  361. if (this.idleQueue.length > 0) {
  362. return this.idleQueue.shift() || null;
  363. }
  364. if (this.count < this._getMaxConcurrency()) {
  365. this.count++;
  366. const name = "".concat(this.name.toLowerCase(), " (#").concat(this.count, " of ").concat(this.maxConcurrency, ")");
  367. return new WorkerThread({
  368. name,
  369. source: this.source,
  370. url: this.url
  371. });
  372. }
  373. return null;
  374. }
  375. _getMaxConcurrency() {
  376. return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
  377. }
  378. }
  379. const DEFAULT_PROPS$3 = {
  380. maxConcurrency: 3,
  381. maxMobileConcurrency: 1,
  382. onDebug: () => {},
  383. reuseWorkers: true
  384. };
  385. class WorkerFarm {
  386. static isSupported() {
  387. return WorkerThread.isSupported();
  388. }
  389. static getWorkerFarm(props = {}) {
  390. WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});
  391. WorkerFarm._workerFarm.setProps(props);
  392. return WorkerFarm._workerFarm;
  393. }
  394. constructor(props) {
  395. _defineProperty(this, "props", void 0);
  396. _defineProperty(this, "workerPools", new Map());
  397. this.props = { ...DEFAULT_PROPS$3
  398. };
  399. this.setProps(props);
  400. this.workerPools = new Map();
  401. }
  402. destroy() {
  403. for (const workerPool of this.workerPools.values()) {
  404. workerPool.destroy();
  405. }
  406. }
  407. setProps(props) {
  408. this.props = { ...this.props,
  409. ...props
  410. };
  411. for (const workerPool of this.workerPools.values()) {
  412. workerPool.setProps(this._getWorkerPoolProps());
  413. }
  414. }
  415. getWorkerPool(options) {
  416. const {
  417. name,
  418. source,
  419. url
  420. } = options;
  421. let workerPool = this.workerPools.get(name);
  422. if (!workerPool) {
  423. workerPool = new WorkerPool({
  424. name,
  425. source,
  426. url
  427. });
  428. workerPool.setProps(this._getWorkerPoolProps());
  429. this.workerPools.set(name, workerPool);
  430. }
  431. return workerPool;
  432. }
  433. _getWorkerPoolProps() {
  434. return {
  435. maxConcurrency: this.props.maxConcurrency,
  436. maxMobileConcurrency: this.props.maxMobileConcurrency,
  437. reuseWorkers: this.props.reuseWorkers,
  438. onDebug: this.props.onDebug
  439. };
  440. }
  441. }
  442. _defineProperty(WorkerFarm, "_workerFarm", void 0);
  443. const NPM_TAG = 'latest';
  444. function getWorkerURL(worker, options = {}) {
  445. const workerOptions = options[worker.id] || {};
  446. const workerFile = "".concat(worker.id, "-worker.js");
  447. let url = workerOptions.workerUrl;
  448. if (!url && worker.id === 'compression') {
  449. url = options.workerUrl;
  450. }
  451. if (options._workerType === 'test') {
  452. url = "modules/".concat(worker.module, "/dist/").concat(workerFile);
  453. }
  454. if (!url) {
  455. let version = worker.version;
  456. if (version === 'latest') {
  457. version = NPM_TAG;
  458. }
  459. const versionTag = version ? "@".concat(version) : '';
  460. url = "https://unpkg.com/@loaders.gl/".concat(worker.module).concat(versionTag, "/dist/").concat(workerFile);
  461. }
  462. assert$6(url);
  463. return url;
  464. }
  465. function validateWorkerVersion(worker, coreVersion = VERSION$8) {
  466. assert$6(worker, 'no worker provided');
  467. const workerVersion = worker.version;
  468. if (!coreVersion || !workerVersion) {
  469. return false;
  470. }
  471. return true;
  472. }
  473. var ChildProcessProxy = {};
  474. var node = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), ChildProcessProxy, {
  475. 'default': ChildProcessProxy
  476. }));
  477. const VERSION$7 = "3.1.4" ;
  478. const loadLibraryPromises = {};
  479. async function loadLibrary(libraryUrl, moduleName = null, options = {}) {
  480. if (moduleName) {
  481. libraryUrl = getLibraryUrl(libraryUrl, moduleName, options);
  482. }
  483. loadLibraryPromises[libraryUrl] = loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
  484. return await loadLibraryPromises[libraryUrl];
  485. }
  486. function getLibraryUrl(library, moduleName, options) {
  487. if (library.startsWith('http')) {
  488. return library;
  489. }
  490. const modules = options.modules || {};
  491. if (modules[library]) {
  492. return modules[library];
  493. }
  494. if (!isBrowser$1) {
  495. return "modules/".concat(moduleName, "/dist/libs/").concat(library);
  496. }
  497. if (options.CDN) {
  498. assert$6(options.CDN.startsWith('http'));
  499. return "".concat(options.CDN, "/").concat(moduleName, "@").concat(VERSION$7, "/dist/libs/").concat(library);
  500. }
  501. if (isWorker) {
  502. return "../src/libs/".concat(library);
  503. }
  504. return "modules/".concat(moduleName, "/src/libs/").concat(library);
  505. }
  506. async function loadLibraryFromFile(libraryUrl) {
  507. if (libraryUrl.endsWith('wasm')) {
  508. const response = await fetch(libraryUrl);
  509. return await response.arrayBuffer();
  510. }
  511. if (!isBrowser$1) {
  512. try {
  513. return node && ChildProcessProxy.requireFromFile && (await ChildProcessProxy.requireFromFile(libraryUrl));
  514. } catch {
  515. return null;
  516. }
  517. }
  518. if (isWorker) {
  519. return importScripts(libraryUrl);
  520. }
  521. const response = await fetch(libraryUrl);
  522. const scriptSource = await response.text();
  523. return loadLibraryFromString(scriptSource, libraryUrl);
  524. }
  525. function loadLibraryFromString(scriptSource, id) {
  526. if (!isBrowser$1) {
  527. return ChildProcessProxy.requireFromString && ChildProcessProxy.requireFromString(scriptSource, id);
  528. }
  529. if (isWorker) {
  530. eval.call(global_, scriptSource);
  531. return null;
  532. }
  533. const script = document.createElement('script');
  534. script.id = id;
  535. try {
  536. script.appendChild(document.createTextNode(scriptSource));
  537. } catch (e) {
  538. script.text = scriptSource;
  539. }
  540. document.body.appendChild(script);
  541. return null;
  542. }
  543. function canParseWithWorker(loader, options) {
  544. if (!WorkerFarm.isSupported()) {
  545. return false;
  546. }
  547. return loader.worker && (options === null || options === void 0 ? void 0 : options.worker);
  548. }
  549. async function parseWithWorker(loader, data, options, context, parseOnMainThread) {
  550. const name = loader.id;
  551. const url = getWorkerURL(loader, options);
  552. const workerFarm = WorkerFarm.getWorkerFarm(options);
  553. const workerPool = workerFarm.getWorkerPool({
  554. name,
  555. url
  556. });
  557. options = JSON.parse(JSON.stringify(options));
  558. const job = await workerPool.startJob('process-on-worker', onMessage.bind(null, parseOnMainThread));
  559. job.postMessage('process', {
  560. input: data,
  561. options
  562. });
  563. const result = await job.result;
  564. return await result.result;
  565. }
  566. async function onMessage(parseOnMainThread, job, type, payload) {
  567. switch (type) {
  568. case 'done':
  569. job.done(payload);
  570. break;
  571. case 'error':
  572. job.error(new Error(payload.error));
  573. break;
  574. case 'process':
  575. const {
  576. id,
  577. input,
  578. options
  579. } = payload;
  580. try {
  581. const result = await parseOnMainThread(input, options);
  582. job.postMessage('done', {
  583. id,
  584. result
  585. });
  586. } catch (error) {
  587. const message = error instanceof Error ? error.message : 'unknown error';
  588. job.postMessage('error', {
  589. id,
  590. error: message
  591. });
  592. }
  593. break;
  594. default:
  595. console.warn("parse-with-worker unknown message ".concat(type));
  596. }
  597. }
  598. function getFirstCharacters$1(data, length = 5) {
  599. if (typeof data === 'string') {
  600. return data.slice(0, length);
  601. } else if (ArrayBuffer.isView(data)) {
  602. return getMagicString$3(data.buffer, data.byteOffset, length);
  603. } else if (data instanceof ArrayBuffer) {
  604. const byteOffset = 0;
  605. return getMagicString$3(data, byteOffset, length);
  606. }
  607. return '';
  608. }
  609. function getMagicString$3(arrayBuffer, byteOffset, length) {
  610. if (arrayBuffer.byteLength <= byteOffset + length) {
  611. return '';
  612. }
  613. const dataView = new DataView(arrayBuffer);
  614. let magic = '';
  615. for (let i = 0; i < length; i++) {
  616. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  617. }
  618. return magic;
  619. }
  620. function parseJSON(string) {
  621. try {
  622. return JSON.parse(string);
  623. } catch (_) {
  624. throw new Error("Failed to parse JSON from data starting with \"".concat(getFirstCharacters$1(string), "\""));
  625. }
  626. }
  627. function isBuffer$1(value) {
  628. return value && typeof value === 'object' && value.isBuffer;
  629. }
  630. function bufferToArrayBuffer(buffer) {
  631. if (isBuffer$1(buffer)) {
  632. const typedArray = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.length);
  633. return typedArray.slice().buffer;
  634. }
  635. return buffer;
  636. }
  637. function toArrayBuffer(data) {
  638. if (isBuffer$1(data)) {
  639. return bufferToArrayBuffer(data);
  640. }
  641. if (data instanceof ArrayBuffer) {
  642. return data;
  643. }
  644. if (ArrayBuffer.isView(data)) {
  645. if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
  646. return data.buffer;
  647. }
  648. return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
  649. }
  650. if (typeof data === 'string') {
  651. const text = data;
  652. const uint8Array = new TextEncoder().encode(text);
  653. return uint8Array.buffer;
  654. }
  655. if (data && typeof data === 'object' && data._toArrayBuffer) {
  656. return data._toArrayBuffer();
  657. }
  658. throw new Error('toArrayBuffer');
  659. }
  660. function compareArrayBuffers(arrayBuffer1, arrayBuffer2, byteLength) {
  661. byteLength = byteLength || arrayBuffer1.byteLength;
  662. if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {
  663. return false;
  664. }
  665. const array1 = new Uint8Array(arrayBuffer1);
  666. const array2 = new Uint8Array(arrayBuffer2);
  667. for (let i = 0; i < array1.length; ++i) {
  668. if (array1[i] !== array2[i]) {
  669. return false;
  670. }
  671. }
  672. return true;
  673. }
  674. function concatenateArrayBuffers(...sources) {
  675. const sourceArrays = sources.map(source2 => source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2);
  676. const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);
  677. const result = new Uint8Array(byteLength);
  678. let offset = 0;
  679. for (const sourceArray of sourceArrays) {
  680. result.set(sourceArray, offset);
  681. offset += sourceArray.byteLength;
  682. }
  683. return result.buffer;
  684. }
  685. function sliceArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  686. const subArray = byteLength !== undefined ? new Uint8Array(arrayBuffer).subarray(byteOffset, byteOffset + byteLength) : new Uint8Array(arrayBuffer).subarray(byteOffset);
  687. const arrayCopy = new Uint8Array(subArray);
  688. return arrayCopy.buffer;
  689. }
  690. function padToNBytes(byteLength, padding) {
  691. assert$7(byteLength >= 0);
  692. assert$7(padding > 0);
  693. return byteLength + (padding - 1) & ~(padding - 1);
  694. }
  695. function copyToArray(source, target, targetOffset) {
  696. let sourceArray;
  697. if (source instanceof ArrayBuffer) {
  698. sourceArray = new Uint8Array(source);
  699. } else {
  700. const srcByteOffset = source.byteOffset;
  701. const srcByteLength = source.byteLength;
  702. sourceArray = new Uint8Array(source.buffer || source.arrayBuffer, srcByteOffset, srcByteLength);
  703. }
  704. target.set(sourceArray, targetOffset);
  705. return targetOffset + padToNBytes(sourceArray.byteLength, 4);
  706. }
  707. async function concatenateArrayBuffersAsync(asyncIterator) {
  708. const arrayBuffers = [];
  709. for await (const chunk of asyncIterator) {
  710. arrayBuffers.push(chunk);
  711. }
  712. return concatenateArrayBuffers(...arrayBuffers);
  713. }
  714. function getHiResTimestamp$1() {
  715. let timestamp;
  716. if (typeof window !== 'undefined' && window.performance) {
  717. timestamp = window.performance.now();
  718. } else if (typeof process !== 'undefined' && process.hrtime) {
  719. const timeParts = process.hrtime();
  720. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  721. } else {
  722. timestamp = Date.now();
  723. }
  724. return timestamp;
  725. }
  726. class Stat {
  727. constructor(name, type) {
  728. _defineProperty(this, "name", void 0);
  729. _defineProperty(this, "type", void 0);
  730. _defineProperty(this, "sampleSize", 1);
  731. _defineProperty(this, "time", void 0);
  732. _defineProperty(this, "count", void 0);
  733. _defineProperty(this, "samples", void 0);
  734. _defineProperty(this, "lastTiming", void 0);
  735. _defineProperty(this, "lastSampleTime", void 0);
  736. _defineProperty(this, "lastSampleCount", void 0);
  737. _defineProperty(this, "_count", 0);
  738. _defineProperty(this, "_time", 0);
  739. _defineProperty(this, "_samples", 0);
  740. _defineProperty(this, "_startTime", 0);
  741. _defineProperty(this, "_timerPending", false);
  742. this.name = name;
  743. this.type = type;
  744. this.reset();
  745. }
  746. setSampleSize(samples) {
  747. this.sampleSize = samples;
  748. return this;
  749. }
  750. incrementCount() {
  751. this.addCount(1);
  752. return this;
  753. }
  754. decrementCount() {
  755. this.subtractCount(1);
  756. return this;
  757. }
  758. addCount(value) {
  759. this._count += value;
  760. this._samples++;
  761. this._checkSampling();
  762. return this;
  763. }
  764. subtractCount(value) {
  765. this._count -= value;
  766. this._samples++;
  767. this._checkSampling();
  768. return this;
  769. }
  770. addTime(time) {
  771. this._time += time;
  772. this.lastTiming = time;
  773. this._samples++;
  774. this._checkSampling();
  775. return this;
  776. }
  777. timeStart() {
  778. this._startTime = getHiResTimestamp$1();
  779. this._timerPending = true;
  780. return this;
  781. }
  782. timeEnd() {
  783. if (!this._timerPending) {
  784. return this;
  785. }
  786. this.addTime(getHiResTimestamp$1() - this._startTime);
  787. this._timerPending = false;
  788. this._checkSampling();
  789. return this;
  790. }
  791. getSampleAverageCount() {
  792. return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;
  793. }
  794. getSampleAverageTime() {
  795. return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;
  796. }
  797. getSampleHz() {
  798. return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1000) : 0;
  799. }
  800. getAverageCount() {
  801. return this.samples > 0 ? this.count / this.samples : 0;
  802. }
  803. getAverageTime() {
  804. return this.samples > 0 ? this.time / this.samples : 0;
  805. }
  806. getHz() {
  807. return this.time > 0 ? this.samples / (this.time / 1000) : 0;
  808. }
  809. reset() {
  810. this.time = 0;
  811. this.count = 0;
  812. this.samples = 0;
  813. this.lastTiming = 0;
  814. this.lastSampleTime = 0;
  815. this.lastSampleCount = 0;
  816. this._count = 0;
  817. this._time = 0;
  818. this._samples = 0;
  819. this._startTime = 0;
  820. this._timerPending = false;
  821. return this;
  822. }
  823. _checkSampling() {
  824. if (this._samples === this.sampleSize) {
  825. this.lastSampleTime = this._time;
  826. this.lastSampleCount = this._count;
  827. this.count += this._count;
  828. this.time += this._time;
  829. this.samples += this._samples;
  830. this._time = 0;
  831. this._count = 0;
  832. this._samples = 0;
  833. }
  834. }
  835. }
  836. class Stats {
  837. constructor(options) {
  838. _defineProperty(this, "id", void 0);
  839. _defineProperty(this, "stats", {});
  840. this.id = options.id;
  841. this.stats = {};
  842. this._initializeStats(options.stats);
  843. Object.seal(this);
  844. }
  845. get(name) {
  846. let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'count';
  847. return this._getOrCreate({
  848. name,
  849. type
  850. });
  851. }
  852. get size() {
  853. return Object.keys(this.stats).length;
  854. }
  855. reset() {
  856. for (const key in this.stats) {
  857. this.stats[key].reset();
  858. }
  859. return this;
  860. }
  861. forEach(fn) {
  862. for (const key in this.stats) {
  863. fn(this.stats[key]);
  864. }
  865. }
  866. getTable() {
  867. const table = {};
  868. this.forEach(stat => {
  869. table[stat.name] = {
  870. time: stat.time || 0,
  871. count: stat.count || 0,
  872. average: stat.getAverageTime() || 0,
  873. hz: stat.getHz() || 0
  874. };
  875. });
  876. return table;
  877. }
  878. _initializeStats() {
  879. let stats = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  880. stats.forEach(stat => this._getOrCreate(stat));
  881. }
  882. _getOrCreate(stat) {
  883. if (!stat || !stat.name) {
  884. return null;
  885. }
  886. const {
  887. name,
  888. type
  889. } = stat;
  890. if (!this.stats[name]) {
  891. if (stat instanceof Stat) {
  892. this.stats[name] = stat;
  893. } else {
  894. this.stats[name] = new Stat(name, type);
  895. }
  896. }
  897. return this.stats[name];
  898. }
  899. }
  900. const STAT_QUEUED_REQUESTS = 'Queued Requests';
  901. const STAT_ACTIVE_REQUESTS = 'Active Requests';
  902. const STAT_CANCELLED_REQUESTS = 'Cancelled Requests';
  903. const STAT_QUEUED_REQUESTS_EVER = 'Queued Requests Ever';
  904. const STAT_ACTIVE_REQUESTS_EVER = 'Active Requests Ever';
  905. const DEFAULT_PROPS$2 = {
  906. id: 'request-scheduler',
  907. throttleRequests: true,
  908. maxRequests: 6
  909. };
  910. class RequestScheduler {
  911. constructor(props = {}) {
  912. _defineProperty(this, "props", void 0);
  913. _defineProperty(this, "stats", void 0);
  914. _defineProperty(this, "activeRequestCount", 0);
  915. _defineProperty(this, "requestQueue", []);
  916. _defineProperty(this, "requestMap", new Map());
  917. _defineProperty(this, "deferredUpdate", null);
  918. this.props = { ...DEFAULT_PROPS$2,
  919. ...props
  920. };
  921. this.stats = new Stats({
  922. id: this.props.id
  923. });
  924. this.stats.get(STAT_QUEUED_REQUESTS);
  925. this.stats.get(STAT_ACTIVE_REQUESTS);
  926. this.stats.get(STAT_CANCELLED_REQUESTS);
  927. this.stats.get(STAT_QUEUED_REQUESTS_EVER);
  928. this.stats.get(STAT_ACTIVE_REQUESTS_EVER);
  929. }
  930. scheduleRequest(handle, getPriority = () => 0) {
  931. if (!this.props.throttleRequests) {
  932. return Promise.resolve({
  933. done: () => {}
  934. });
  935. }
  936. if (this.requestMap.has(handle)) {
  937. return this.requestMap.get(handle);
  938. }
  939. const request = {
  940. handle,
  941. priority: 0,
  942. getPriority
  943. };
  944. const promise = new Promise(resolve => {
  945. request.resolve = resolve;
  946. return request;
  947. });
  948. this.requestQueue.push(request);
  949. this.requestMap.set(handle, promise);
  950. this._issueNewRequests();
  951. return promise;
  952. }
  953. _issueRequest(request) {
  954. const {
  955. handle,
  956. resolve
  957. } = request;
  958. let isDone = false;
  959. const done = () => {
  960. if (!isDone) {
  961. isDone = true;
  962. this.requestMap.delete(handle);
  963. this.activeRequestCount--;
  964. this._issueNewRequests();
  965. }
  966. };
  967. this.activeRequestCount++;
  968. return resolve ? resolve({
  969. done
  970. }) : Promise.resolve({
  971. done
  972. });
  973. }
  974. _issueNewRequests() {
  975. if (!this.deferredUpdate) {
  976. this.deferredUpdate = setTimeout(() => this._issueNewRequestsAsync(), 0);
  977. }
  978. }
  979. _issueNewRequestsAsync() {
  980. this.deferredUpdate = null;
  981. const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);
  982. if (freeSlots === 0) {
  983. return;
  984. }
  985. this._updateAllRequests();
  986. for (let i = 0; i < freeSlots; ++i) {
  987. const request = this.requestQueue.shift();
  988. if (request) {
  989. this._issueRequest(request);
  990. }
  991. }
  992. }
  993. _updateAllRequests() {
  994. const requestQueue = this.requestQueue;
  995. for (let i = 0; i < requestQueue.length; ++i) {
  996. const request = requestQueue[i];
  997. if (!this._updateRequest(request)) {
  998. requestQueue.splice(i, 1);
  999. this.requestMap.delete(request.handle);
  1000. i--;
  1001. }
  1002. }
  1003. requestQueue.sort((a, b) => a.priority - b.priority);
  1004. }
  1005. _updateRequest(request) {
  1006. request.priority = request.getPriority(request.handle);
  1007. if (request.priority < 0) {
  1008. request.resolve(null);
  1009. return false;
  1010. }
  1011. return true;
  1012. }
  1013. }
  1014. let pathPrefix = '';
  1015. const fileAliases = {};
  1016. function resolvePath(filename) {
  1017. for (const alias in fileAliases) {
  1018. if (filename.startsWith(alias)) {
  1019. const replacement = fileAliases[alias];
  1020. filename = filename.replace(alias, replacement);
  1021. }
  1022. }
  1023. if (!filename.startsWith('http://') && !filename.startsWith('https://')) {
  1024. filename = "".concat(pathPrefix).concat(filename);
  1025. }
  1026. return filename;
  1027. }
  1028. function filename(url) {
  1029. const slashIndex = url && url.lastIndexOf('/');
  1030. return slashIndex >= 0 ? url.substr(slashIndex + 1) : '';
  1031. }
  1032. function dirname(url) {
  1033. const slashIndex = url && url.lastIndexOf('/');
  1034. return slashIndex >= 0 ? url.substr(0, slashIndex) : '';
  1035. }
  1036. const isBoolean = x => typeof x === 'boolean';
  1037. const isFunction = x => typeof x === 'function';
  1038. const isObject = x => x !== null && typeof x === 'object';
  1039. const isPureObject = x => isObject(x) && x.constructor === {}.constructor;
  1040. const isIterable = x => x && typeof x[Symbol.iterator] === 'function';
  1041. const isAsyncIterable = x => x && typeof x[Symbol.asyncIterator] === 'function';
  1042. const isResponse = x => typeof Response !== 'undefined' && x instanceof Response || x && x.arrayBuffer && x.text && x.json;
  1043. const isBlob = x => typeof Blob !== 'undefined' && x instanceof Blob;
  1044. const isBuffer = x => x && typeof x === 'object' && x.isBuffer;
  1045. const isReadableDOMStream = x => typeof ReadableStream !== 'undefined' && x instanceof ReadableStream || isObject(x) && isFunction(x.tee) && isFunction(x.cancel) && isFunction(x.getReader);
  1046. const isReadableNodeStream = x => isObject(x) && isFunction(x.read) && isFunction(x.pipe) && isBoolean(x.readable);
  1047. const isReadableStream = x => isReadableDOMStream(x) || isReadableNodeStream(x);
  1048. const DATA_URL_PATTERN = /^data:([-\w.]+\/[-\w.+]+)(;|,)/;
  1049. const MIME_TYPE_PATTERN = /^([-\w.]+\/[-\w.+]+)/;
  1050. function parseMIMEType(mimeString) {
  1051. const matches = MIME_TYPE_PATTERN.exec(mimeString);
  1052. if (matches) {
  1053. return matches[1];
  1054. }
  1055. return mimeString;
  1056. }
  1057. function parseMIMETypeFromURL(url) {
  1058. const matches = DATA_URL_PATTERN.exec(url);
  1059. if (matches) {
  1060. return matches[1];
  1061. }
  1062. return '';
  1063. }
  1064. const QUERY_STRING_PATTERN = /\?.*/;
  1065. function getResourceUrlAndType(resource) {
  1066. if (isResponse(resource)) {
  1067. const url = stripQueryString(resource.url || '');
  1068. const contentTypeHeader = resource.headers.get('content-type') || '';
  1069. return {
  1070. url,
  1071. type: parseMIMEType(contentTypeHeader) || parseMIMETypeFromURL(url)
  1072. };
  1073. }
  1074. if (isBlob(resource)) {
  1075. return {
  1076. url: stripQueryString(resource.name || ''),
  1077. type: resource.type || ''
  1078. };
  1079. }
  1080. if (typeof resource === 'string') {
  1081. return {
  1082. url: stripQueryString(resource),
  1083. type: parseMIMETypeFromURL(resource)
  1084. };
  1085. }
  1086. return {
  1087. url: '',
  1088. type: ''
  1089. };
  1090. }
  1091. function getResourceContentLength(resource) {
  1092. if (isResponse(resource)) {
  1093. return resource.headers['content-length'] || -1;
  1094. }
  1095. if (isBlob(resource)) {
  1096. return resource.size;
  1097. }
  1098. if (typeof resource === 'string') {
  1099. return resource.length;
  1100. }
  1101. if (resource instanceof ArrayBuffer) {
  1102. return resource.byteLength;
  1103. }
  1104. if (ArrayBuffer.isView(resource)) {
  1105. return resource.byteLength;
  1106. }
  1107. return -1;
  1108. }
  1109. function stripQueryString(url) {
  1110. return url.replace(QUERY_STRING_PATTERN, '');
  1111. }
  1112. async function makeResponse(resource) {
  1113. if (isResponse(resource)) {
  1114. return resource;
  1115. }
  1116. const headers = {};
  1117. const contentLength = getResourceContentLength(resource);
  1118. if (contentLength >= 0) {
  1119. headers['content-length'] = String(contentLength);
  1120. }
  1121. const {
  1122. url,
  1123. type
  1124. } = getResourceUrlAndType(resource);
  1125. if (type) {
  1126. headers['content-type'] = type;
  1127. }
  1128. const initialDataUrl = await getInitialDataUrl(resource);
  1129. if (initialDataUrl) {
  1130. headers['x-first-bytes'] = initialDataUrl;
  1131. }
  1132. if (typeof resource === 'string') {
  1133. resource = new TextEncoder().encode(resource);
  1134. }
  1135. const response = new Response(resource, {
  1136. headers
  1137. });
  1138. Object.defineProperty(response, 'url', {
  1139. value: url
  1140. });
  1141. return response;
  1142. }
  1143. async function checkResponse(response) {
  1144. if (!response.ok) {
  1145. const message = await getResponseError(response);
  1146. throw new Error(message);
  1147. }
  1148. }
  1149. async function getResponseError(response) {
  1150. let message = "Failed to fetch resource ".concat(response.url, " (").concat(response.status, "): ");
  1151. try {
  1152. const contentType = response.headers.get('Content-Type');
  1153. let text = response.statusText;
  1154. if (contentType.includes('application/json')) {
  1155. text += " ".concat(await response.text());
  1156. }
  1157. message += text;
  1158. message = message.length > 60 ? "".concat(message.slice(60), "...") : message;
  1159. } catch (error) {}
  1160. return message;
  1161. }
  1162. async function getInitialDataUrl(resource) {
  1163. const INITIAL_DATA_LENGTH = 5;
  1164. if (typeof resource === 'string') {
  1165. return "data:,".concat(resource.slice(0, INITIAL_DATA_LENGTH));
  1166. }
  1167. if (resource instanceof Blob) {
  1168. const blobSlice = resource.slice(0, 5);
  1169. return await new Promise(resolve => {
  1170. const reader = new FileReader();
  1171. reader.onload = event => {
  1172. var _event$target;
  1173. return resolve(event === null || event === void 0 ? void 0 : (_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.result);
  1174. };
  1175. reader.readAsDataURL(blobSlice);
  1176. });
  1177. }
  1178. if (resource instanceof ArrayBuffer) {
  1179. const slice = resource.slice(0, INITIAL_DATA_LENGTH);
  1180. const base64 = arrayBufferToBase64(slice);
  1181. return "data:base64,".concat(base64);
  1182. }
  1183. return null;
  1184. }
  1185. function arrayBufferToBase64(buffer) {
  1186. let binary = '';
  1187. const bytes = new Uint8Array(buffer);
  1188. for (let i = 0; i < bytes.byteLength; i++) {
  1189. binary += String.fromCharCode(bytes[i]);
  1190. }
  1191. return btoa(binary);
  1192. }
  1193. async function fetchFile(url, options) {
  1194. if (typeof url === 'string') {
  1195. url = resolvePath(url);
  1196. let fetchOptions = options;
  1197. if (options !== null && options !== void 0 && options.fetch && typeof (options === null || options === void 0 ? void 0 : options.fetch) !== 'function') {
  1198. fetchOptions = options.fetch;
  1199. }
  1200. return await fetch(url, fetchOptions);
  1201. }
  1202. return await makeResponse(url);
  1203. }
  1204. function isElectron(mockUserAgent) {
  1205. if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {
  1206. return true;
  1207. }
  1208. if (typeof process !== 'undefined' && typeof process.versions === 'object' && Boolean(process.versions.electron)) {
  1209. return true;
  1210. }
  1211. const realUserAgent = typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent;
  1212. const userAgent = mockUserAgent || realUserAgent;
  1213. if (userAgent && userAgent.indexOf('Electron') >= 0) {
  1214. return true;
  1215. }
  1216. return false;
  1217. }
  1218. function isBrowser() {
  1219. const isNode = typeof process === 'object' && String(process) === '[object process]' && !process.browser;
  1220. return !isNode || isElectron();
  1221. }
  1222. const globals = {
  1223. self: typeof self !== 'undefined' && self,
  1224. window: typeof window !== 'undefined' && window,
  1225. global: typeof global !== 'undefined' && global,
  1226. document: typeof document !== 'undefined' && document,
  1227. process: typeof process === 'object' && process
  1228. };
  1229. const window_ = globals.window || globals.self || globals.global;
  1230. const process_ = globals.process || {};
  1231. const VERSION$6 = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'untranspiled source';
  1232. isBrowser();
  1233. function getStorage(type) {
  1234. try {
  1235. const storage = window[type];
  1236. const x = '__storage_test__';
  1237. storage.setItem(x, x);
  1238. storage.removeItem(x);
  1239. return storage;
  1240. } catch (e) {
  1241. return null;
  1242. }
  1243. }
  1244. class LocalStorage {
  1245. constructor(id) {
  1246. let defaultSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1247. let type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'sessionStorage';
  1248. _defineProperty(this, "storage", void 0);
  1249. _defineProperty(this, "id", void 0);
  1250. _defineProperty(this, "config", {});
  1251. this.storage = getStorage(type);
  1252. this.id = id;
  1253. this.config = {};
  1254. Object.assign(this.config, defaultSettings);
  1255. this._loadConfiguration();
  1256. }
  1257. getConfiguration() {
  1258. return this.config;
  1259. }
  1260. setConfiguration(configuration) {
  1261. this.config = {};
  1262. return this.updateConfiguration(configuration);
  1263. }
  1264. updateConfiguration(configuration) {
  1265. Object.assign(this.config, configuration);
  1266. if (this.storage) {
  1267. const serialized = JSON.stringify(this.config);
  1268. this.storage.setItem(this.id, serialized);
  1269. }
  1270. return this;
  1271. }
  1272. _loadConfiguration() {
  1273. let configuration = {};
  1274. if (this.storage) {
  1275. const serializedConfiguration = this.storage.getItem(this.id);
  1276. configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {};
  1277. }
  1278. Object.assign(this.config, configuration);
  1279. return this;
  1280. }
  1281. }
  1282. function formatTime(ms) {
  1283. let formatted;
  1284. if (ms < 10) {
  1285. formatted = "".concat(ms.toFixed(2), "ms");
  1286. } else if (ms < 100) {
  1287. formatted = "".concat(ms.toFixed(1), "ms");
  1288. } else if (ms < 1000) {
  1289. formatted = "".concat(ms.toFixed(0), "ms");
  1290. } else {
  1291. formatted = "".concat((ms / 1000).toFixed(2), "s");
  1292. }
  1293. return formatted;
  1294. }
  1295. function leftPad(string) {
  1296. let length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 8;
  1297. const padLength = Math.max(length - string.length, 0);
  1298. return "".concat(' '.repeat(padLength)).concat(string);
  1299. }
  1300. function formatImage(image, message, scale) {
  1301. let maxWidth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 600;
  1302. const imageUrl = image.src.replace(/\(/g, '%28').replace(/\)/g, '%29');
  1303. if (image.width > maxWidth) {
  1304. scale = Math.min(scale, maxWidth / image.width);
  1305. }
  1306. const width = image.width * scale;
  1307. const height = image.height * scale;
  1308. 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('');
  1309. return ["".concat(message, " %c+"), style];
  1310. }
  1311. let COLOR;
  1312. (function (COLOR) {
  1313. COLOR[COLOR["BLACK"] = 30] = "BLACK";
  1314. COLOR[COLOR["RED"] = 31] = "RED";
  1315. COLOR[COLOR["GREEN"] = 32] = "GREEN";
  1316. COLOR[COLOR["YELLOW"] = 33] = "YELLOW";
  1317. COLOR[COLOR["BLUE"] = 34] = "BLUE";
  1318. COLOR[COLOR["MAGENTA"] = 35] = "MAGENTA";
  1319. COLOR[COLOR["CYAN"] = 36] = "CYAN";
  1320. COLOR[COLOR["WHITE"] = 37] = "WHITE";
  1321. COLOR[COLOR["BRIGHT_BLACK"] = 90] = "BRIGHT_BLACK";
  1322. COLOR[COLOR["BRIGHT_RED"] = 91] = "BRIGHT_RED";
  1323. COLOR[COLOR["BRIGHT_GREEN"] = 92] = "BRIGHT_GREEN";
  1324. COLOR[COLOR["BRIGHT_YELLOW"] = 93] = "BRIGHT_YELLOW";
  1325. COLOR[COLOR["BRIGHT_BLUE"] = 94] = "BRIGHT_BLUE";
  1326. COLOR[COLOR["BRIGHT_MAGENTA"] = 95] = "BRIGHT_MAGENTA";
  1327. COLOR[COLOR["BRIGHT_CYAN"] = 96] = "BRIGHT_CYAN";
  1328. COLOR[COLOR["BRIGHT_WHITE"] = 97] = "BRIGHT_WHITE";
  1329. })(COLOR || (COLOR = {}));
  1330. function getColor(color) {
  1331. return typeof color === 'string' ? COLOR[color.toUpperCase()] || COLOR.WHITE : color;
  1332. }
  1333. function addColor(string, color, background) {
  1334. if (!isBrowser && typeof string === 'string') {
  1335. if (color) {
  1336. color = getColor(color);
  1337. string = "\x1B[".concat(color, "m").concat(string, "\x1B[39m");
  1338. }
  1339. if (background) {
  1340. color = getColor(background);
  1341. string = "\x1B[".concat(background + 10, "m").concat(string, "\x1B[49m");
  1342. }
  1343. }
  1344. return string;
  1345. }
  1346. function autobind(obj) {
  1347. let predefined = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ['constructor'];
  1348. const proto = Object.getPrototypeOf(obj);
  1349. const propNames = Object.getOwnPropertyNames(proto);
  1350. for (const key of propNames) {
  1351. if (typeof obj[key] === 'function') {
  1352. if (!predefined.find(name => key === name)) {
  1353. obj[key] = obj[key].bind(obj);
  1354. }
  1355. }
  1356. }
  1357. }
  1358. function assert$5(condition, message) {
  1359. if (!condition) {
  1360. throw new Error(message || 'Assertion failed');
  1361. }
  1362. }
  1363. function getHiResTimestamp() {
  1364. let timestamp;
  1365. if (isBrowser && 'performance' in window_) {
  1366. var _window$performance, _window$performance$n;
  1367. 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);
  1368. } else if ('hrtime' in process_) {
  1369. var _process$hrtime;
  1370. const timeParts = process_ === null || process_ === void 0 ? void 0 : (_process$hrtime = process_.hrtime) === null || _process$hrtime === void 0 ? void 0 : _process$hrtime.call(process_);
  1371. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  1372. } else {
  1373. timestamp = Date.now();
  1374. }
  1375. return timestamp;
  1376. }
  1377. const originalConsole = {
  1378. debug: isBrowser ? console.debug || console.log : console.log,
  1379. log: console.log,
  1380. info: console.info,
  1381. warn: console.warn,
  1382. error: console.error
  1383. };
  1384. const DEFAULT_SETTINGS = {
  1385. enabled: true,
  1386. level: 0
  1387. };
  1388. function noop$1() {}
  1389. const cache = {};
  1390. const ONCE = {
  1391. once: true
  1392. };
  1393. class Log {
  1394. constructor() {
  1395. let {
  1396. id
  1397. } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
  1398. id: ''
  1399. };
  1400. _defineProperty(this, "id", void 0);
  1401. _defineProperty(this, "VERSION", VERSION$6);
  1402. _defineProperty(this, "_startTs", getHiResTimestamp());
  1403. _defineProperty(this, "_deltaTs", getHiResTimestamp());
  1404. _defineProperty(this, "_storage", void 0);
  1405. _defineProperty(this, "userData", {});
  1406. _defineProperty(this, "LOG_THROTTLE_TIMEOUT", 0);
  1407. this.id = id;
  1408. this._storage = new LocalStorage("__probe-".concat(this.id, "__"), DEFAULT_SETTINGS);
  1409. this.userData = {};
  1410. this.timeStamp("".concat(this.id, " started"));
  1411. autobind(this);
  1412. Object.seal(this);
  1413. }
  1414. set level(newLevel) {
  1415. this.setLevel(newLevel);
  1416. }
  1417. get level() {
  1418. return this.getLevel();
  1419. }
  1420. isEnabled() {
  1421. return this._storage.config.enabled;
  1422. }
  1423. getLevel() {
  1424. return this._storage.config.level;
  1425. }
  1426. getTotal() {
  1427. return Number((getHiResTimestamp() - this._startTs).toPrecision(10));
  1428. }
  1429. getDelta() {
  1430. return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10));
  1431. }
  1432. set priority(newPriority) {
  1433. this.level = newPriority;
  1434. }
  1435. get priority() {
  1436. return this.level;
  1437. }
  1438. getPriority() {
  1439. return this.level;
  1440. }
  1441. enable() {
  1442. let enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  1443. this._storage.updateConfiguration({
  1444. enabled
  1445. });
  1446. return this;
  1447. }
  1448. setLevel(level) {
  1449. this._storage.updateConfiguration({
  1450. level
  1451. });
  1452. return this;
  1453. }
  1454. get(setting) {
  1455. return this._storage.config[setting];
  1456. }
  1457. set(setting, value) {
  1458. this._storage.updateConfiguration({
  1459. [setting]: value
  1460. });
  1461. }
  1462. settings() {
  1463. if (console.table) {
  1464. console.table(this._storage.config);
  1465. } else {
  1466. console.log(this._storage.config);
  1467. }
  1468. }
  1469. assert(condition, message) {
  1470. assert$5(condition, message);
  1471. }
  1472. warn(message) {
  1473. return this._getLogFunction(0, message, originalConsole.warn, arguments, ONCE);
  1474. }
  1475. error(message) {
  1476. return this._getLogFunction(0, message, originalConsole.error, arguments);
  1477. }
  1478. deprecated(oldUsage, newUsage) {
  1479. return this.warn("`".concat(oldUsage, "` is deprecated and will be removed in a later version. Use `").concat(newUsage, "` instead"));
  1480. }
  1481. removed(oldUsage, newUsage) {
  1482. return this.error("`".concat(oldUsage, "` has been removed. Use `").concat(newUsage, "` instead"));
  1483. }
  1484. probe(logLevel, message) {
  1485. return this._getLogFunction(logLevel, message, originalConsole.log, arguments, {
  1486. time: true,
  1487. once: true
  1488. });
  1489. }
  1490. log(logLevel, message) {
  1491. return this._getLogFunction(logLevel, message, originalConsole.debug, arguments);
  1492. }
  1493. info(logLevel, message) {
  1494. return this._getLogFunction(logLevel, message, console.info, arguments);
  1495. }
  1496. once(logLevel, message) {
  1497. for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  1498. args[_key - 2] = arguments[_key];
  1499. }
  1500. return this._getLogFunction(logLevel, message, originalConsole.debug || originalConsole.info, arguments, ONCE);
  1501. }
  1502. table(logLevel, table, columns) {
  1503. if (table) {
  1504. return this._getLogFunction(logLevel, table, console.table || noop$1, columns && [columns], {
  1505. tag: getTableHeader(table)
  1506. });
  1507. }
  1508. return noop$1;
  1509. }
  1510. image(_ref) {
  1511. let {
  1512. logLevel,
  1513. priority,
  1514. image,
  1515. message = '',
  1516. scale = 1
  1517. } = _ref;
  1518. if (!this._shouldLog(logLevel || priority)) {
  1519. return noop$1;
  1520. }
  1521. return isBrowser ? logImageInBrowser({
  1522. image,
  1523. message,
  1524. scale
  1525. }) : logImageInNode({
  1526. image,
  1527. message,
  1528. scale
  1529. });
  1530. }
  1531. time(logLevel, message) {
  1532. return this._getLogFunction(logLevel, message, console.time ? console.time : console.info);
  1533. }
  1534. timeEnd(logLevel, message) {
  1535. return this._getLogFunction(logLevel, message, console.timeEnd ? console.timeEnd : console.info);
  1536. }
  1537. timeStamp(logLevel, message) {
  1538. return this._getLogFunction(logLevel, message, console.timeStamp || noop$1);
  1539. }
  1540. group(logLevel, message) {
  1541. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
  1542. collapsed: false
  1543. };
  1544. const options = normalizeArguments({
  1545. logLevel,
  1546. message,
  1547. opts
  1548. });
  1549. const {
  1550. collapsed
  1551. } = opts;
  1552. options.method = (collapsed ? console.groupCollapsed : console.group) || console.info;
  1553. return this._getLogFunction(options);
  1554. }
  1555. groupCollapsed(logLevel, message) {
  1556. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  1557. return this.group(logLevel, message, Object.assign({}, opts, {
  1558. collapsed: true
  1559. }));
  1560. }
  1561. groupEnd(logLevel) {
  1562. return this._getLogFunction(logLevel, '', console.groupEnd || noop$1);
  1563. }
  1564. withGroup(logLevel, message, func) {
  1565. this.group(logLevel, message)();
  1566. try {
  1567. func();
  1568. } finally {
  1569. this.groupEnd(logLevel)();
  1570. }
  1571. }
  1572. trace() {
  1573. if (console.trace) {
  1574. console.trace();
  1575. }
  1576. }
  1577. _shouldLog(logLevel) {
  1578. return this.isEnabled() && this.getLevel() >= normalizeLogLevel(logLevel);
  1579. }
  1580. _getLogFunction(logLevel, message, method, args, opts) {
  1581. if (this._shouldLog(logLevel)) {
  1582. opts = normalizeArguments({
  1583. logLevel,
  1584. message,
  1585. args,
  1586. opts
  1587. });
  1588. method = method || opts.method;
  1589. assert$5(method);
  1590. opts.total = this.getTotal();
  1591. opts.delta = this.getDelta();
  1592. this._deltaTs = getHiResTimestamp();
  1593. const tag = opts.tag || opts.message;
  1594. if (opts.once) {
  1595. if (!cache[tag]) {
  1596. cache[tag] = getHiResTimestamp();
  1597. } else {
  1598. return noop$1;
  1599. }
  1600. }
  1601. message = decorateMessage(this.id, opts.message, opts);
  1602. return method.bind(console, message, ...opts.args);
  1603. }
  1604. return noop$1;
  1605. }
  1606. }
  1607. _defineProperty(Log, "VERSION", VERSION$6);
  1608. function normalizeLogLevel(logLevel) {
  1609. if (!logLevel) {
  1610. return 0;
  1611. }
  1612. let resolvedLevel;
  1613. switch (typeof logLevel) {
  1614. case 'number':
  1615. resolvedLevel = logLevel;
  1616. break;
  1617. case 'object':
  1618. resolvedLevel = logLevel.logLevel || logLevel.priority || 0;
  1619. break;
  1620. default:
  1621. return 0;
  1622. }
  1623. assert$5(Number.isFinite(resolvedLevel) && resolvedLevel >= 0);
  1624. return resolvedLevel;
  1625. }
  1626. function normalizeArguments(opts) {
  1627. const {
  1628. logLevel,
  1629. message
  1630. } = opts;
  1631. opts.logLevel = normalizeLogLevel(logLevel);
  1632. const args = opts.args ? Array.from(opts.args) : [];
  1633. while (args.length && args.shift() !== message) {}
  1634. switch (typeof logLevel) {
  1635. case 'string':
  1636. case 'function':
  1637. if (message !== undefined) {
  1638. args.unshift(message);
  1639. }
  1640. opts.message = logLevel;
  1641. break;
  1642. case 'object':
  1643. Object.assign(opts, logLevel);
  1644. break;
  1645. }
  1646. if (typeof opts.message === 'function') {
  1647. opts.message = opts.message();
  1648. }
  1649. const messageType = typeof opts.message;
  1650. assert$5(messageType === 'string' || messageType === 'object');
  1651. return Object.assign(opts, {
  1652. args
  1653. }, opts.opts);
  1654. }
  1655. function decorateMessage(id, message, opts) {
  1656. if (typeof message === 'string') {
  1657. const time = opts.time ? leftPad(formatTime(opts.total)) : '';
  1658. message = opts.time ? "".concat(id, ": ").concat(time, " ").concat(message) : "".concat(id, ": ").concat(message);
  1659. message = addColor(message, opts.color, opts.background);
  1660. }
  1661. return message;
  1662. }
  1663. function logImageInNode(_ref2) {
  1664. let {
  1665. image,
  1666. message = '',
  1667. scale = 1
  1668. } = _ref2;
  1669. let asciify = null;
  1670. try {
  1671. asciify = module.require('asciify-image');
  1672. } catch (error) {}
  1673. if (asciify) {
  1674. return () => asciify(image, {
  1675. fit: 'box',
  1676. width: "".concat(Math.round(80 * scale), "%")
  1677. }).then(data => console.log(data));
  1678. }
  1679. return noop$1;
  1680. }
  1681. function logImageInBrowser(_ref3) {
  1682. let {
  1683. image,
  1684. message = '',
  1685. scale = 1
  1686. } = _ref3;
  1687. if (typeof image === 'string') {
  1688. const img = new Image();
  1689. img.onload = () => {
  1690. const args = formatImage(img, message, scale);
  1691. console.log(...args);
  1692. };
  1693. img.src = image;
  1694. return noop$1;
  1695. }
  1696. const element = image.nodeName || '';
  1697. if (element.toLowerCase() === 'img') {
  1698. console.log(...formatImage(image, message, scale));
  1699. return noop$1;
  1700. }
  1701. if (element.toLowerCase() === 'canvas') {
  1702. const img = new Image();
  1703. img.onload = () => console.log(...formatImage(img, message, scale));
  1704. img.src = image.toDataURL();
  1705. return noop$1;
  1706. }
  1707. return noop$1;
  1708. }
  1709. function getTableHeader(table) {
  1710. for (const key in table) {
  1711. for (const title in table[key]) {
  1712. return title || 'untitled';
  1713. }
  1714. }
  1715. return 'empty';
  1716. }
  1717. const probeLog = new Log({
  1718. id: 'loaders.gl'
  1719. });
  1720. class NullLog {
  1721. log() {
  1722. return () => {};
  1723. }
  1724. info() {
  1725. return () => {};
  1726. }
  1727. warn() {
  1728. return () => {};
  1729. }
  1730. error() {
  1731. return () => {};
  1732. }
  1733. }
  1734. class ConsoleLog {
  1735. constructor() {
  1736. _defineProperty(this, "console", void 0);
  1737. this.console = console;
  1738. }
  1739. log(...args) {
  1740. return this.console.log.bind(this.console, ...args);
  1741. }
  1742. info(...args) {
  1743. return this.console.info.bind(this.console, ...args);
  1744. }
  1745. warn(...args) {
  1746. return this.console.warn.bind(this.console, ...args);
  1747. }
  1748. error(...args) {
  1749. return this.console.error.bind(this.console, ...args);
  1750. }
  1751. }
  1752. const DEFAULT_LOADER_OPTIONS = {
  1753. fetch: null,
  1754. mimeType: undefined,
  1755. nothrow: false,
  1756. log: new ConsoleLog(),
  1757. CDN: 'https://unpkg.com/@loaders.gl',
  1758. worker: true,
  1759. maxConcurrency: 3,
  1760. maxMobileConcurrency: 1,
  1761. reuseWorkers: true,
  1762. _workerType: '',
  1763. limit: 0,
  1764. _limitMB: 0,
  1765. batchSize: 'auto',
  1766. batchDebounceMs: 0,
  1767. metadata: false,
  1768. transforms: []
  1769. };
  1770. const REMOVED_LOADER_OPTIONS = {
  1771. throws: 'nothrow',
  1772. dataType: '(no longer used)',
  1773. uri: 'baseUri',
  1774. method: 'fetch.method',
  1775. headers: 'fetch.headers',
  1776. body: 'fetch.body',
  1777. mode: 'fetch.mode',
  1778. credentials: 'fetch.credentials',
  1779. cache: 'fetch.cache',
  1780. redirect: 'fetch.redirect',
  1781. referrer: 'fetch.referrer',
  1782. referrerPolicy: 'fetch.referrerPolicy',
  1783. integrity: 'fetch.integrity',
  1784. keepalive: 'fetch.keepalive',
  1785. signal: 'fetch.signal'
  1786. };
  1787. function getGlobalLoaderState() {
  1788. globalThis.loaders = globalThis.loaders || {};
  1789. const {
  1790. loaders
  1791. } = globalThis;
  1792. loaders._state = loaders._state || {};
  1793. return loaders._state;
  1794. }
  1795. const getGlobalLoaderOptions = () => {
  1796. const state = getGlobalLoaderState();
  1797. state.globalOptions = state.globalOptions || { ...DEFAULT_LOADER_OPTIONS
  1798. };
  1799. return state.globalOptions;
  1800. };
  1801. function normalizeOptions(options, loader, loaders, url) {
  1802. loaders = loaders || [];
  1803. loaders = Array.isArray(loaders) ? loaders : [loaders];
  1804. validateOptions(options, loaders);
  1805. return normalizeOptionsInternal(loader, options, url);
  1806. }
  1807. function getFetchFunction(options, context) {
  1808. const globalOptions = getGlobalLoaderOptions();
  1809. const fetchOptions = options || globalOptions;
  1810. if (typeof fetchOptions.fetch === 'function') {
  1811. return fetchOptions.fetch;
  1812. }
  1813. if (isObject(fetchOptions.fetch)) {
  1814. return url => fetchFile(url, fetchOptions);
  1815. }
  1816. if (context !== null && context !== void 0 && context.fetch) {
  1817. return context === null || context === void 0 ? void 0 : context.fetch;
  1818. }
  1819. return fetchFile;
  1820. }
  1821. function validateOptions(options, loaders) {
  1822. validateOptionsObject(options, null, DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS, loaders);
  1823. for (const loader of loaders) {
  1824. const idOptions = options && options[loader.id] || {};
  1825. const loaderOptions = loader.options && loader.options[loader.id] || {};
  1826. const deprecatedOptions = loader.deprecatedOptions && loader.deprecatedOptions[loader.id] || {};
  1827. validateOptionsObject(idOptions, loader.id, loaderOptions, deprecatedOptions, loaders);
  1828. }
  1829. }
  1830. function validateOptionsObject(options, id, defaultOptions, deprecatedOptions, loaders) {
  1831. const loaderName = id || 'Top level';
  1832. const prefix = id ? "".concat(id, ".") : '';
  1833. for (const key in options) {
  1834. const isSubOptions = !id && isObject(options[key]);
  1835. const isBaseUriOption = key === 'baseUri' && !id;
  1836. const isWorkerUrlOption = key === 'workerUrl' && id;
  1837. if (!(key in defaultOptions) && !isBaseUriOption && !isWorkerUrlOption) {
  1838. if (key in deprecatedOptions) {
  1839. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' no longer supported, use '").concat(deprecatedOptions[key], "'"))();
  1840. } else if (!isSubOptions) {
  1841. const suggestion = findSimilarOption(key, loaders);
  1842. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' not recognized. ").concat(suggestion))();
  1843. }
  1844. }
  1845. }
  1846. }
  1847. function findSimilarOption(optionKey, loaders) {
  1848. const lowerCaseOptionKey = optionKey.toLowerCase();
  1849. let bestSuggestion = '';
  1850. for (const loader of loaders) {
  1851. for (const key in loader.options) {
  1852. if (optionKey === key) {
  1853. return "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1854. }
  1855. const lowerCaseKey = key.toLowerCase();
  1856. const isPartialMatch = lowerCaseOptionKey.startsWith(lowerCaseKey) || lowerCaseKey.startsWith(lowerCaseOptionKey);
  1857. if (isPartialMatch) {
  1858. bestSuggestion = bestSuggestion || "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  1859. }
  1860. }
  1861. }
  1862. return bestSuggestion;
  1863. }
  1864. function normalizeOptionsInternal(loader, options, url) {
  1865. const loaderDefaultOptions = loader.options || {};
  1866. const mergedOptions = { ...loaderDefaultOptions
  1867. };
  1868. addUrlOptions(mergedOptions, url);
  1869. if (mergedOptions.log === null) {
  1870. mergedOptions.log = new NullLog();
  1871. }
  1872. mergeNestedFields(mergedOptions, getGlobalLoaderOptions());
  1873. mergeNestedFields(mergedOptions, options);
  1874. return mergedOptions;
  1875. }
  1876. function mergeNestedFields(mergedOptions, options) {
  1877. for (const key in options) {
  1878. if (key in options) {
  1879. const value = options[key];
  1880. if (isPureObject(value) && isPureObject(mergedOptions[key])) {
  1881. mergedOptions[key] = { ...mergedOptions[key],
  1882. ...options[key]
  1883. };
  1884. } else {
  1885. mergedOptions[key] = options[key];
  1886. }
  1887. }
  1888. }
  1889. }
  1890. function addUrlOptions(options, url) {
  1891. if (url && !('baseUri' in options)) {
  1892. options.baseUri = url;
  1893. }
  1894. }
  1895. function isLoaderObject(loader) {
  1896. var _loader;
  1897. if (!loader) {
  1898. return false;
  1899. }
  1900. if (Array.isArray(loader)) {
  1901. loader = loader[0];
  1902. }
  1903. const hasExtensions = Array.isArray((_loader = loader) === null || _loader === void 0 ? void 0 : _loader.extensions);
  1904. return hasExtensions;
  1905. }
  1906. function normalizeLoader(loader) {
  1907. var _loader2, _loader3;
  1908. assert$7(loader, 'null loader');
  1909. assert$7(isLoaderObject(loader), 'invalid loader');
  1910. let options;
  1911. if (Array.isArray(loader)) {
  1912. options = loader[1];
  1913. loader = loader[0];
  1914. loader = { ...loader,
  1915. options: { ...loader.options,
  1916. ...options
  1917. }
  1918. };
  1919. }
  1920. if ((_loader2 = loader) !== null && _loader2 !== void 0 && _loader2.parseTextSync || (_loader3 = loader) !== null && _loader3 !== void 0 && _loader3.parseText) {
  1921. loader.text = true;
  1922. }
  1923. if (!loader.text) {
  1924. loader.binary = true;
  1925. }
  1926. return loader;
  1927. }
  1928. const getGlobalLoaderRegistry = () => {
  1929. const state = getGlobalLoaderState();
  1930. state.loaderRegistry = state.loaderRegistry || [];
  1931. return state.loaderRegistry;
  1932. };
  1933. function getRegisteredLoaders() {
  1934. return getGlobalLoaderRegistry();
  1935. }
  1936. const EXT_PATTERN = /\.([^.]+)$/;
  1937. async function selectLoader(data, loaders = [], options, context) {
  1938. if (!validHTTPResponse(data)) {
  1939. return null;
  1940. }
  1941. let loader = selectLoaderSync(data, loaders, { ...options,
  1942. nothrow: true
  1943. }, context);
  1944. if (loader) {
  1945. return loader;
  1946. }
  1947. if (isBlob(data)) {
  1948. data = await data.slice(0, 10).arrayBuffer();
  1949. loader = selectLoaderSync(data, loaders, options, context);
  1950. }
  1951. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1952. throw new Error(getNoValidLoaderMessage(data));
  1953. }
  1954. return loader;
  1955. }
  1956. function selectLoaderSync(data, loaders = [], options, context) {
  1957. if (!validHTTPResponse(data)) {
  1958. return null;
  1959. }
  1960. if (loaders && !Array.isArray(loaders)) {
  1961. return normalizeLoader(loaders);
  1962. }
  1963. let candidateLoaders = [];
  1964. if (loaders) {
  1965. candidateLoaders = candidateLoaders.concat(loaders);
  1966. }
  1967. if (!(options !== null && options !== void 0 && options.ignoreRegisteredLoaders)) {
  1968. candidateLoaders.push(...getRegisteredLoaders());
  1969. }
  1970. normalizeLoaders(candidateLoaders);
  1971. const loader = selectLoaderInternal(data, candidateLoaders, options, context);
  1972. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  1973. throw new Error(getNoValidLoaderMessage(data));
  1974. }
  1975. return loader;
  1976. }
  1977. function selectLoaderInternal(data, loaders, options, context) {
  1978. const {
  1979. url,
  1980. type
  1981. } = getResourceUrlAndType(data);
  1982. const testUrl = url || (context === null || context === void 0 ? void 0 : context.url);
  1983. let loader = null;
  1984. if (options !== null && options !== void 0 && options.mimeType) {
  1985. loader = findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.mimeType);
  1986. }
  1987. loader = loader || findLoaderByUrl(loaders, testUrl);
  1988. loader = loader || findLoaderByMIMEType(loaders, type);
  1989. loader = loader || findLoaderByInitialBytes(loaders, data);
  1990. loader = loader || findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.fallbackMimeType);
  1991. return loader;
  1992. }
  1993. function validHTTPResponse(data) {
  1994. if (data instanceof Response) {
  1995. if (data.status === 204) {
  1996. return false;
  1997. }
  1998. }
  1999. return true;
  2000. }
  2001. function getNoValidLoaderMessage(data) {
  2002. const {
  2003. url,
  2004. type
  2005. } = getResourceUrlAndType(data);
  2006. let message = 'No valid loader found (';
  2007. message += url ? "".concat(filename(url), ", ") : 'no url provided, ';
  2008. message += "MIME type: ".concat(type ? "\"".concat(type, "\"") : 'not provided', ", ");
  2009. const firstCharacters = data ? getFirstCharacters(data) : '';
  2010. message += firstCharacters ? " first bytes: \"".concat(firstCharacters, "\"") : 'first bytes: not available';
  2011. message += ')';
  2012. return message;
  2013. }
  2014. function normalizeLoaders(loaders) {
  2015. for (const loader of loaders) {
  2016. normalizeLoader(loader);
  2017. }
  2018. }
  2019. function findLoaderByUrl(loaders, url) {
  2020. const match = url && EXT_PATTERN.exec(url);
  2021. const extension = match && match[1];
  2022. return extension ? findLoaderByExtension(loaders, extension) : null;
  2023. }
  2024. function findLoaderByExtension(loaders, extension) {
  2025. extension = extension.toLowerCase();
  2026. for (const loader of loaders) {
  2027. for (const loaderExtension of loader.extensions) {
  2028. if (loaderExtension.toLowerCase() === extension) {
  2029. return loader;
  2030. }
  2031. }
  2032. }
  2033. return null;
  2034. }
  2035. function findLoaderByMIMEType(loaders, mimeType) {
  2036. for (const loader of loaders) {
  2037. if (loader.mimeTypes && loader.mimeTypes.includes(mimeType)) {
  2038. return loader;
  2039. }
  2040. if (mimeType === "application/x.".concat(loader.id)) {
  2041. return loader;
  2042. }
  2043. }
  2044. return null;
  2045. }
  2046. function findLoaderByInitialBytes(loaders, data) {
  2047. if (!data) {
  2048. return null;
  2049. }
  2050. for (const loader of loaders) {
  2051. if (typeof data === 'string') {
  2052. if (testDataAgainstText(data, loader)) {
  2053. return loader;
  2054. }
  2055. } else if (ArrayBuffer.isView(data)) {
  2056. if (testDataAgainstBinary(data.buffer, data.byteOffset, loader)) {
  2057. return loader;
  2058. }
  2059. } else if (data instanceof ArrayBuffer) {
  2060. const byteOffset = 0;
  2061. if (testDataAgainstBinary(data, byteOffset, loader)) {
  2062. return loader;
  2063. }
  2064. }
  2065. }
  2066. return null;
  2067. }
  2068. function testDataAgainstText(data, loader) {
  2069. if (loader.testText) {
  2070. return loader.testText(data);
  2071. }
  2072. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2073. return tests.some(test => data.startsWith(test));
  2074. }
  2075. function testDataAgainstBinary(data, byteOffset, loader) {
  2076. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  2077. return tests.some(test => testBinary(data, byteOffset, loader, test));
  2078. }
  2079. function testBinary(data, byteOffset, loader, test) {
  2080. if (test instanceof ArrayBuffer) {
  2081. return compareArrayBuffers(test, data, test.byteLength);
  2082. }
  2083. switch (typeof test) {
  2084. case 'function':
  2085. return test(data, loader);
  2086. case 'string':
  2087. const magic = getMagicString$2(data, byteOffset, test.length);
  2088. return test === magic;
  2089. default:
  2090. return false;
  2091. }
  2092. }
  2093. function getFirstCharacters(data, length = 5) {
  2094. if (typeof data === 'string') {
  2095. return data.slice(0, length);
  2096. } else if (ArrayBuffer.isView(data)) {
  2097. return getMagicString$2(data.buffer, data.byteOffset, length);
  2098. } else if (data instanceof ArrayBuffer) {
  2099. const byteOffset = 0;
  2100. return getMagicString$2(data, byteOffset, length);
  2101. }
  2102. return '';
  2103. }
  2104. function getMagicString$2(arrayBuffer, byteOffset, length) {
  2105. if (arrayBuffer.byteLength < byteOffset + length) {
  2106. return '';
  2107. }
  2108. const dataView = new DataView(arrayBuffer);
  2109. let magic = '';
  2110. for (let i = 0; i < length; i++) {
  2111. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  2112. }
  2113. return magic;
  2114. }
  2115. const DEFAULT_CHUNK_SIZE$2 = 256 * 1024;
  2116. function* makeStringIterator(string, options) {
  2117. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE$2;
  2118. let offset = 0;
  2119. const textEncoder = new TextEncoder();
  2120. while (offset < string.length) {
  2121. const chunkLength = Math.min(string.length - offset, chunkSize);
  2122. const chunk = string.slice(offset, offset + chunkLength);
  2123. offset += chunkLength;
  2124. yield textEncoder.encode(chunk);
  2125. }
  2126. }
  2127. const DEFAULT_CHUNK_SIZE$1 = 256 * 1024;
  2128. function* makeArrayBufferIterator(arrayBuffer, options = {}) {
  2129. const {
  2130. chunkSize = DEFAULT_CHUNK_SIZE$1
  2131. } = options;
  2132. let byteOffset = 0;
  2133. while (byteOffset < arrayBuffer.byteLength) {
  2134. const chunkByteLength = Math.min(arrayBuffer.byteLength - byteOffset, chunkSize);
  2135. const chunk = new ArrayBuffer(chunkByteLength);
  2136. const sourceArray = new Uint8Array(arrayBuffer, byteOffset, chunkByteLength);
  2137. const chunkArray = new Uint8Array(chunk);
  2138. chunkArray.set(sourceArray);
  2139. byteOffset += chunkByteLength;
  2140. yield chunk;
  2141. }
  2142. }
  2143. const DEFAULT_CHUNK_SIZE = 1024 * 1024;
  2144. async function* makeBlobIterator(blob, options) {
  2145. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE;
  2146. let offset = 0;
  2147. while (offset < blob.size) {
  2148. const end = offset + chunkSize;
  2149. const chunk = await blob.slice(offset, end).arrayBuffer();
  2150. offset = end;
  2151. yield chunk;
  2152. }
  2153. }
  2154. function makeStreamIterator(stream, options) {
  2155. return isBrowser$2 ? makeBrowserStreamIterator(stream, options) : makeNodeStreamIterator(stream);
  2156. }
  2157. async function* makeBrowserStreamIterator(stream, options) {
  2158. const reader = stream.getReader();
  2159. let nextBatchPromise;
  2160. try {
  2161. while (true) {
  2162. const currentBatchPromise = nextBatchPromise || reader.read();
  2163. if (options !== null && options !== void 0 && options._streamReadAhead) {
  2164. nextBatchPromise = reader.read();
  2165. }
  2166. const {
  2167. done,
  2168. value
  2169. } = await currentBatchPromise;
  2170. if (done) {
  2171. return;
  2172. }
  2173. yield toArrayBuffer(value);
  2174. }
  2175. } catch (error) {
  2176. reader.releaseLock();
  2177. }
  2178. }
  2179. async function* makeNodeStreamIterator(stream, options) {
  2180. for await (const chunk of stream) {
  2181. yield toArrayBuffer(chunk);
  2182. }
  2183. }
  2184. function makeIterator(data, options) {
  2185. if (typeof data === 'string') {
  2186. return makeStringIterator(data, options);
  2187. }
  2188. if (data instanceof ArrayBuffer) {
  2189. return makeArrayBufferIterator(data, options);
  2190. }
  2191. if (isBlob(data)) {
  2192. return makeBlobIterator(data, options);
  2193. }
  2194. if (isReadableStream(data)) {
  2195. return makeStreamIterator(data, options);
  2196. }
  2197. if (isResponse(data)) {
  2198. const response = data;
  2199. return makeStreamIterator(response.body, options);
  2200. }
  2201. throw new Error('makeIterator');
  2202. }
  2203. const ERR_DATA = 'Cannot convert supplied data type';
  2204. function getArrayBufferOrStringFromDataSync(data, loader, options) {
  2205. if (loader.text && typeof data === 'string') {
  2206. return data;
  2207. }
  2208. if (isBuffer(data)) {
  2209. data = data.buffer;
  2210. }
  2211. if (data instanceof ArrayBuffer) {
  2212. const arrayBuffer = data;
  2213. if (loader.text && !loader.binary) {
  2214. const textDecoder = new TextDecoder('utf8');
  2215. return textDecoder.decode(arrayBuffer);
  2216. }
  2217. return arrayBuffer;
  2218. }
  2219. if (ArrayBuffer.isView(data)) {
  2220. if (loader.text && !loader.binary) {
  2221. const textDecoder = new TextDecoder('utf8');
  2222. return textDecoder.decode(data);
  2223. }
  2224. let arrayBuffer = data.buffer;
  2225. const byteLength = data.byteLength || data.length;
  2226. if (data.byteOffset !== 0 || byteLength !== arrayBuffer.byteLength) {
  2227. arrayBuffer = arrayBuffer.slice(data.byteOffset, data.byteOffset + byteLength);
  2228. }
  2229. return arrayBuffer;
  2230. }
  2231. throw new Error(ERR_DATA);
  2232. }
  2233. async function getArrayBufferOrStringFromData(data, loader, options) {
  2234. const isArrayBuffer = data instanceof ArrayBuffer || ArrayBuffer.isView(data);
  2235. if (typeof data === 'string' || isArrayBuffer) {
  2236. return getArrayBufferOrStringFromDataSync(data, loader);
  2237. }
  2238. if (isBlob(data)) {
  2239. data = await makeResponse(data);
  2240. }
  2241. if (isResponse(data)) {
  2242. const response = data;
  2243. await checkResponse(response);
  2244. return loader.binary ? await response.arrayBuffer() : await response.text();
  2245. }
  2246. if (isReadableStream(data)) {
  2247. data = makeIterator(data, options);
  2248. }
  2249. if (isIterable(data) || isAsyncIterable(data)) {
  2250. return concatenateArrayBuffersAsync(data);
  2251. }
  2252. throw new Error(ERR_DATA);
  2253. }
  2254. function getLoaderContext(context, options, previousContext = null) {
  2255. if (previousContext) {
  2256. return previousContext;
  2257. }
  2258. const resolvedContext = {
  2259. fetch: getFetchFunction(options, context),
  2260. ...context
  2261. };
  2262. if (!Array.isArray(resolvedContext.loaders)) {
  2263. resolvedContext.loaders = null;
  2264. }
  2265. return resolvedContext;
  2266. }
  2267. function getLoadersFromContext(loaders, context) {
  2268. if (!context && loaders && !Array.isArray(loaders)) {
  2269. return loaders;
  2270. }
  2271. let candidateLoaders;
  2272. if (loaders) {
  2273. candidateLoaders = Array.isArray(loaders) ? loaders : [loaders];
  2274. }
  2275. if (context && context.loaders) {
  2276. const contextLoaders = Array.isArray(context.loaders) ? context.loaders : [context.loaders];
  2277. candidateLoaders = candidateLoaders ? [...candidateLoaders, ...contextLoaders] : contextLoaders;
  2278. }
  2279. return candidateLoaders && candidateLoaders.length ? candidateLoaders : null;
  2280. }
  2281. async function parse$3(data, loaders, options, context) {
  2282. assert$6(!context || typeof context === 'object');
  2283. if (loaders && !Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2284. context = undefined;
  2285. options = loaders;
  2286. loaders = undefined;
  2287. }
  2288. data = await data;
  2289. options = options || {};
  2290. const {
  2291. url
  2292. } = getResourceUrlAndType(data);
  2293. const typedLoaders = loaders;
  2294. const candidateLoaders = getLoadersFromContext(typedLoaders, context);
  2295. const loader = await selectLoader(data, candidateLoaders, options);
  2296. if (!loader) {
  2297. return null;
  2298. }
  2299. options = normalizeOptions(options, loader, candidateLoaders, url);
  2300. context = getLoaderContext({
  2301. url,
  2302. parse: parse$3,
  2303. loaders: candidateLoaders
  2304. }, options, context);
  2305. return await parseWithLoader(loader, data, options, context);
  2306. }
  2307. async function parseWithLoader(loader, data, options, context) {
  2308. validateWorkerVersion(loader);
  2309. data = await getArrayBufferOrStringFromData(data, loader, options);
  2310. if (loader.parseTextSync && typeof data === 'string') {
  2311. options.dataType = 'text';
  2312. return loader.parseTextSync(data, options, context, loader);
  2313. }
  2314. if (canParseWithWorker(loader, options)) {
  2315. return await parseWithWorker(loader, data, options, context, parse$3);
  2316. }
  2317. if (loader.parseText && typeof data === 'string') {
  2318. return await loader.parseText(data, options, context, loader);
  2319. }
  2320. if (loader.parse) {
  2321. return await loader.parse(data, options, context, loader);
  2322. }
  2323. assert$6(!loader.parseSync);
  2324. throw new Error("".concat(loader.id, " loader - no parser found and worker is disabled"));
  2325. }
  2326. async function load(url, loaders, options, context) {
  2327. if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
  2328. options = loaders;
  2329. loaders = undefined;
  2330. }
  2331. const fetch = getFetchFunction(options);
  2332. let data = url;
  2333. if (typeof url === 'string') {
  2334. data = await fetch(url);
  2335. }
  2336. if (isBlob(url)) {
  2337. data = await fetch(url);
  2338. }
  2339. return await parse$3(data, loaders, options);
  2340. }
  2341. function assert$4(condition, message) {
  2342. if (!condition) {
  2343. throw new Error("math.gl assertion ".concat(message));
  2344. }
  2345. }
  2346. const RADIANS_TO_DEGREES = 1 / Math.PI * 180;
  2347. const DEGREES_TO_RADIANS = 1 / 180 * Math.PI;
  2348. const config = {};
  2349. config.EPSILON = 1e-12;
  2350. config.debug = false;
  2351. config.precision = 4;
  2352. config.printTypes = false;
  2353. config.printDegrees = false;
  2354. config.printRowMajor = true;
  2355. function round(value) {
  2356. return Math.round(value / config.EPSILON) * config.EPSILON;
  2357. }
  2358. function formatValue(value, {
  2359. precision = config.precision || 4
  2360. } = {}) {
  2361. value = round(value);
  2362. return "".concat(parseFloat(value.toPrecision(precision)));
  2363. }
  2364. function isArray(value) {
  2365. return Array.isArray(value) || ArrayBuffer.isView(value) && !(value instanceof DataView);
  2366. }
  2367. function duplicateArray(array) {
  2368. return array.clone ? array.clone() : new Array(array.length);
  2369. }
  2370. function map$1(value, func, result) {
  2371. if (isArray(value)) {
  2372. result = result || duplicateArray(value);
  2373. for (let i = 0; i < result.length && i < value.length; ++i) {
  2374. result[i] = func(value[i], i, result);
  2375. }
  2376. return result;
  2377. }
  2378. return func(value);
  2379. }
  2380. function toRadians(degrees) {
  2381. return radians(degrees);
  2382. }
  2383. function toDegrees(radians) {
  2384. return degrees(radians);
  2385. }
  2386. function radians(degrees, result) {
  2387. return map$1(degrees, degrees => degrees * DEGREES_TO_RADIANS, result);
  2388. }
  2389. function degrees(radians, result) {
  2390. return map$1(radians, radians => radians * RADIANS_TO_DEGREES, result);
  2391. }
  2392. function clamp(value, min, max) {
  2393. return map$1(value, value => Math.max(min, Math.min(max, value)));
  2394. }
  2395. function equals(a, b, epsilon) {
  2396. const oldEpsilon = config.EPSILON;
  2397. if (epsilon) {
  2398. config.EPSILON = epsilon;
  2399. }
  2400. try {
  2401. if (a === b) {
  2402. return true;
  2403. }
  2404. if (isArray(a) && isArray(b)) {
  2405. if (a.length !== b.length) {
  2406. return false;
  2407. }
  2408. for (let i = 0; i < a.length; ++i) {
  2409. if (!equals(a[i], b[i])) {
  2410. return false;
  2411. }
  2412. }
  2413. return true;
  2414. }
  2415. if (a && a.equals) {
  2416. return a.equals(b);
  2417. }
  2418. if (b && b.equals) {
  2419. return b.equals(a);
  2420. }
  2421. if (Number.isFinite(a) && Number.isFinite(b)) {
  2422. return Math.abs(a - b) <= config.EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));
  2423. }
  2424. return false;
  2425. } finally {
  2426. config.EPSILON = oldEpsilon;
  2427. }
  2428. }
  2429. function _extendableBuiltin(cls) {
  2430. function ExtendableBuiltin() {
  2431. var instance = Reflect.construct(cls, Array.from(arguments));
  2432. Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
  2433. return instance;
  2434. }
  2435. ExtendableBuiltin.prototype = Object.create(cls.prototype, {
  2436. constructor: {
  2437. value: cls,
  2438. enumerable: false,
  2439. writable: true,
  2440. configurable: true
  2441. }
  2442. });
  2443. if (Object.setPrototypeOf) {
  2444. Object.setPrototypeOf(ExtendableBuiltin, cls);
  2445. } else {
  2446. ExtendableBuiltin.__proto__ = cls;
  2447. }
  2448. return ExtendableBuiltin;
  2449. }
  2450. class MathArray extends _extendableBuiltin(Array) {
  2451. get ELEMENTS() {
  2452. assert$4(false);
  2453. return 0;
  2454. }
  2455. clone() {
  2456. return new this.constructor().copy(this);
  2457. }
  2458. from(arrayOrObject) {
  2459. return Array.isArray(arrayOrObject) ? this.copy(arrayOrObject) : this.fromObject(arrayOrObject);
  2460. }
  2461. fromArray(array, offset = 0) {
  2462. for (let i = 0; i < this.ELEMENTS; ++i) {
  2463. this[i] = array[i + offset];
  2464. }
  2465. return this.check();
  2466. }
  2467. to(arrayOrObject) {
  2468. if (arrayOrObject === this) {
  2469. return this;
  2470. }
  2471. return isArray(arrayOrObject) ? this.toArray(arrayOrObject) : this.toObject(arrayOrObject);
  2472. }
  2473. toTarget(target) {
  2474. return target ? this.to(target) : this;
  2475. }
  2476. toArray(array = [], offset = 0) {
  2477. for (let i = 0; i < this.ELEMENTS; ++i) {
  2478. array[offset + i] = this[i];
  2479. }
  2480. return array;
  2481. }
  2482. toFloat32Array() {
  2483. return new Float32Array(this);
  2484. }
  2485. toString() {
  2486. return this.formatString(config);
  2487. }
  2488. formatString(opts) {
  2489. let string = '';
  2490. for (let i = 0; i < this.ELEMENTS; ++i) {
  2491. string += (i > 0 ? ', ' : '') + formatValue(this[i], opts);
  2492. }
  2493. return "".concat(opts.printTypes ? this.constructor.name : '', "[").concat(string, "]");
  2494. }
  2495. equals(array) {
  2496. if (!array || this.length !== array.length) {
  2497. return false;
  2498. }
  2499. for (let i = 0; i < this.ELEMENTS; ++i) {
  2500. if (!equals(this[i], array[i])) {
  2501. return false;
  2502. }
  2503. }
  2504. return true;
  2505. }
  2506. exactEquals(array) {
  2507. if (!array || this.length !== array.length) {
  2508. return false;
  2509. }
  2510. for (let i = 0; i < this.ELEMENTS; ++i) {
  2511. if (this[i] !== array[i]) {
  2512. return false;
  2513. }
  2514. }
  2515. return true;
  2516. }
  2517. negate() {
  2518. for (let i = 0; i < this.ELEMENTS; ++i) {
  2519. this[i] = -this[i];
  2520. }
  2521. return this.check();
  2522. }
  2523. lerp(a, b, t) {
  2524. if (t === undefined) {
  2525. t = b;
  2526. b = a;
  2527. a = this;
  2528. }
  2529. for (let i = 0; i < this.ELEMENTS; ++i) {
  2530. const ai = a[i];
  2531. this[i] = ai + t * (b[i] - ai);
  2532. }
  2533. return this.check();
  2534. }
  2535. min(vector) {
  2536. for (let i = 0; i < this.ELEMENTS; ++i) {
  2537. this[i] = Math.min(vector[i], this[i]);
  2538. }
  2539. return this.check();
  2540. }
  2541. max(vector) {
  2542. for (let i = 0; i < this.ELEMENTS; ++i) {
  2543. this[i] = Math.max(vector[i], this[i]);
  2544. }
  2545. return this.check();
  2546. }
  2547. clamp(minVector, maxVector) {
  2548. for (let i = 0; i < this.ELEMENTS; ++i) {
  2549. this[i] = Math.min(Math.max(this[i], minVector[i]), maxVector[i]);
  2550. }
  2551. return this.check();
  2552. }
  2553. add(...vectors) {
  2554. for (const vector of vectors) {
  2555. for (let i = 0; i < this.ELEMENTS; ++i) {
  2556. this[i] += vector[i];
  2557. }
  2558. }
  2559. return this.check();
  2560. }
  2561. subtract(...vectors) {
  2562. for (const vector of vectors) {
  2563. for (let i = 0; i < this.ELEMENTS; ++i) {
  2564. this[i] -= vector[i];
  2565. }
  2566. }
  2567. return this.check();
  2568. }
  2569. scale(scale) {
  2570. if (Array.isArray(scale)) {
  2571. return this.multiply(scale);
  2572. }
  2573. for (let i = 0; i < this.ELEMENTS; ++i) {
  2574. this[i] *= scale;
  2575. }
  2576. return this.check();
  2577. }
  2578. sub(a) {
  2579. return this.subtract(a);
  2580. }
  2581. setScalar(a) {
  2582. for (let i = 0; i < this.ELEMENTS; ++i) {
  2583. this[i] = a;
  2584. }
  2585. return this.check();
  2586. }
  2587. addScalar(a) {
  2588. for (let i = 0; i < this.ELEMENTS; ++i) {
  2589. this[i] += a;
  2590. }
  2591. return this.check();
  2592. }
  2593. subScalar(a) {
  2594. return this.addScalar(-a);
  2595. }
  2596. multiplyScalar(scalar) {
  2597. for (let i = 0; i < this.ELEMENTS; ++i) {
  2598. this[i] *= scalar;
  2599. }
  2600. return this.check();
  2601. }
  2602. divideScalar(a) {
  2603. return this.scale(1 / a);
  2604. }
  2605. clampScalar(min, max) {
  2606. for (let i = 0; i < this.ELEMENTS; ++i) {
  2607. this[i] = Math.min(Math.max(this[i], min), max);
  2608. }
  2609. return this.check();
  2610. }
  2611. multiplyByScalar(scalar) {
  2612. return this.scale(scalar);
  2613. }
  2614. get elements() {
  2615. return this;
  2616. }
  2617. check() {
  2618. if (config.debug && !this.validate()) {
  2619. throw new Error("math.gl: ".concat(this.constructor.name, " some fields set to invalid numbers'"));
  2620. }
  2621. return this;
  2622. }
  2623. validate() {
  2624. let valid = this.length === this.ELEMENTS;
  2625. for (let i = 0; i < this.ELEMENTS; ++i) {
  2626. valid = valid && Number.isFinite(this[i]);
  2627. }
  2628. return valid;
  2629. }
  2630. }
  2631. function validateVector(v, length) {
  2632. if (v.length !== length) {
  2633. return false;
  2634. }
  2635. for (let i = 0; i < v.length; ++i) {
  2636. if (!Number.isFinite(v[i])) {
  2637. return false;
  2638. }
  2639. }
  2640. return true;
  2641. }
  2642. function checkNumber(value) {
  2643. if (!Number.isFinite(value)) {
  2644. throw new Error("Invalid number ".concat(value));
  2645. }
  2646. return value;
  2647. }
  2648. function checkVector(v, length, callerName = '') {
  2649. if (config.debug && !validateVector(v, length)) {
  2650. throw new Error("math.gl: ".concat(callerName, " some fields set to invalid numbers'"));
  2651. }
  2652. return v;
  2653. }
  2654. const map = {};
  2655. function deprecated(method, version) {
  2656. if (!map[method]) {
  2657. map[method] = true;
  2658. console.warn("".concat(method, " has been removed in version ").concat(version, ", see upgrade guide for more information"));
  2659. }
  2660. }
  2661. class Vector extends MathArray {
  2662. get ELEMENTS() {
  2663. assert$4(false);
  2664. return 0;
  2665. }
  2666. copy(vector) {
  2667. assert$4(false);
  2668. return this;
  2669. }
  2670. get x() {
  2671. return this[0];
  2672. }
  2673. set x(value) {
  2674. this[0] = checkNumber(value);
  2675. }
  2676. get y() {
  2677. return this[1];
  2678. }
  2679. set y(value) {
  2680. this[1] = checkNumber(value);
  2681. }
  2682. len() {
  2683. return Math.sqrt(this.lengthSquared());
  2684. }
  2685. magnitude() {
  2686. return this.len();
  2687. }
  2688. lengthSquared() {
  2689. let length = 0;
  2690. for (let i = 0; i < this.ELEMENTS; ++i) {
  2691. length += this[i] * this[i];
  2692. }
  2693. return length;
  2694. }
  2695. magnitudeSquared() {
  2696. return this.lengthSquared();
  2697. }
  2698. distance(mathArray) {
  2699. return Math.sqrt(this.distanceSquared(mathArray));
  2700. }
  2701. distanceSquared(mathArray) {
  2702. let length = 0;
  2703. for (let i = 0; i < this.ELEMENTS; ++i) {
  2704. const dist = this[i] - mathArray[i];
  2705. length += dist * dist;
  2706. }
  2707. return checkNumber(length);
  2708. }
  2709. dot(mathArray) {
  2710. let product = 0;
  2711. for (let i = 0; i < this.ELEMENTS; ++i) {
  2712. product += this[i] * mathArray[i];
  2713. }
  2714. return checkNumber(product);
  2715. }
  2716. normalize() {
  2717. const length = this.magnitude();
  2718. if (length !== 0) {
  2719. for (let i = 0; i < this.ELEMENTS; ++i) {
  2720. this[i] /= length;
  2721. }
  2722. }
  2723. return this.check();
  2724. }
  2725. multiply(...vectors) {
  2726. for (const vector of vectors) {
  2727. for (let i = 0; i < this.ELEMENTS; ++i) {
  2728. this[i] *= vector[i];
  2729. }
  2730. }
  2731. return this.check();
  2732. }
  2733. divide(...vectors) {
  2734. for (const vector of vectors) {
  2735. for (let i = 0; i < this.ELEMENTS; ++i) {
  2736. this[i] /= vector[i];
  2737. }
  2738. }
  2739. return this.check();
  2740. }
  2741. lengthSq() {
  2742. return this.lengthSquared();
  2743. }
  2744. distanceTo(vector) {
  2745. return this.distance(vector);
  2746. }
  2747. distanceToSquared(vector) {
  2748. return this.distanceSquared(vector);
  2749. }
  2750. getComponent(i) {
  2751. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2752. return checkNumber(this[i]);
  2753. }
  2754. setComponent(i, value) {
  2755. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  2756. this[i] = value;
  2757. return this.check();
  2758. }
  2759. addVectors(a, b) {
  2760. return this.copy(a).add(b);
  2761. }
  2762. subVectors(a, b) {
  2763. return this.copy(a).subtract(b);
  2764. }
  2765. multiplyVectors(a, b) {
  2766. return this.copy(a).multiply(b);
  2767. }
  2768. addScaledVector(a, b) {
  2769. return this.add(new this.constructor(a).multiplyScalar(b));
  2770. }
  2771. }
  2772. /**
  2773. * Common utilities
  2774. * @module glMatrix
  2775. */
  2776. // Configuration Constants
  2777. var EPSILON = 0.000001;
  2778. var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  2779. if (!Math.hypot) Math.hypot = function () {
  2780. var y = 0,
  2781. i = arguments.length;
  2782. while (i--) {
  2783. y += arguments[i] * arguments[i];
  2784. }
  2785. return Math.sqrt(y);
  2786. };
  2787. /**
  2788. * 2 Dimensional Vector
  2789. * @module vec2
  2790. */
  2791. /**
  2792. * Creates a new, empty vec2
  2793. *
  2794. * @returns {vec2} a new 2D vector
  2795. */
  2796. function create$4() {
  2797. var out = new ARRAY_TYPE(2);
  2798. if (ARRAY_TYPE != Float32Array) {
  2799. out[0] = 0;
  2800. out[1] = 0;
  2801. }
  2802. return out;
  2803. }
  2804. /**
  2805. * Transforms the vec2 with a mat2
  2806. *
  2807. * @param {vec2} out the receiving vector
  2808. * @param {ReadonlyVec2} a the vector to transform
  2809. * @param {ReadonlyMat2} m matrix to transform with
  2810. * @returns {vec2} out
  2811. */
  2812. function transformMat2(out, a, m) {
  2813. var x = a[0],
  2814. y = a[1];
  2815. out[0] = m[0] * x + m[2] * y;
  2816. out[1] = m[1] * x + m[3] * y;
  2817. return out;
  2818. }
  2819. /**
  2820. * Transforms the vec2 with a mat2d
  2821. *
  2822. * @param {vec2} out the receiving vector
  2823. * @param {ReadonlyVec2} a the vector to transform
  2824. * @param {ReadonlyMat2d} m matrix to transform with
  2825. * @returns {vec2} out
  2826. */
  2827. function transformMat2d(out, a, m) {
  2828. var x = a[0],
  2829. y = a[1];
  2830. out[0] = m[0] * x + m[2] * y + m[4];
  2831. out[1] = m[1] * x + m[3] * y + m[5];
  2832. return out;
  2833. }
  2834. /**
  2835. * Transforms the vec2 with a mat3
  2836. * 3rd vector component is implicitly '1'
  2837. *
  2838. * @param {vec2} out the receiving vector
  2839. * @param {ReadonlyVec2} a the vector to transform
  2840. * @param {ReadonlyMat3} m matrix to transform with
  2841. * @returns {vec2} out
  2842. */
  2843. function transformMat3$1(out, a, m) {
  2844. var x = a[0],
  2845. y = a[1];
  2846. out[0] = m[0] * x + m[3] * y + m[6];
  2847. out[1] = m[1] * x + m[4] * y + m[7];
  2848. return out;
  2849. }
  2850. /**
  2851. * Transforms the vec2 with a mat4
  2852. * 3rd vector component is implicitly '0'
  2853. * 4th vector component is implicitly '1'
  2854. *
  2855. * @param {vec2} out the receiving vector
  2856. * @param {ReadonlyVec2} a the vector to transform
  2857. * @param {ReadonlyMat4} m matrix to transform with
  2858. * @returns {vec2} out
  2859. */
  2860. function transformMat4$2(out, a, m) {
  2861. var x = a[0];
  2862. var y = a[1];
  2863. out[0] = m[0] * x + m[4] * y + m[12];
  2864. out[1] = m[1] * x + m[5] * y + m[13];
  2865. return out;
  2866. }
  2867. /**
  2868. * Perform some operation over an array of vec2s.
  2869. *
  2870. * @param {Array} a the array of vectors to iterate over
  2871. * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
  2872. * @param {Number} offset Number of elements to skip at the beginning of the array
  2873. * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
  2874. * @param {Function} fn Function to call for each vector in the array
  2875. * @param {Object} [arg] additional argument to pass to fn
  2876. * @returns {Array} a
  2877. * @function
  2878. */
  2879. (function () {
  2880. var vec = create$4();
  2881. return function (a, stride, offset, count, fn, arg) {
  2882. var i, l;
  2883. if (!stride) {
  2884. stride = 2;
  2885. }
  2886. if (!offset) {
  2887. offset = 0;
  2888. }
  2889. if (count) {
  2890. l = Math.min(count * stride + offset, a.length);
  2891. } else {
  2892. l = a.length;
  2893. }
  2894. for (i = offset; i < l; i += stride) {
  2895. vec[0] = a[i];
  2896. vec[1] = a[i + 1];
  2897. fn(vec, vec, arg);
  2898. a[i] = vec[0];
  2899. a[i + 1] = vec[1];
  2900. }
  2901. return a;
  2902. };
  2903. })();
  2904. function vec2_transformMat4AsVector(out, a, m) {
  2905. const x = a[0];
  2906. const y = a[1];
  2907. const w = m[3] * x + m[7] * y || 1.0;
  2908. out[0] = (m[0] * x + m[4] * y) / w;
  2909. out[1] = (m[1] * x + m[5] * y) / w;
  2910. return out;
  2911. }
  2912. function vec3_transformMat4AsVector(out, a, m) {
  2913. const x = a[0];
  2914. const y = a[1];
  2915. const z = a[2];
  2916. const w = m[3] * x + m[7] * y + m[11] * z || 1.0;
  2917. out[0] = (m[0] * x + m[4] * y + m[8] * z) / w;
  2918. out[1] = (m[1] * x + m[5] * y + m[9] * z) / w;
  2919. out[2] = (m[2] * x + m[6] * y + m[10] * z) / w;
  2920. return out;
  2921. }
  2922. function vec3_transformMat2(out, a, m) {
  2923. const x = a[0];
  2924. const y = a[1];
  2925. out[0] = m[0] * x + m[2] * y;
  2926. out[1] = m[1] * x + m[3] * y;
  2927. out[2] = a[2];
  2928. return out;
  2929. }
  2930. function vec4_transformMat3(out, a, m) {
  2931. const x = a[0];
  2932. const y = a[1];
  2933. const z = a[2];
  2934. out[0] = m[0] * x + m[3] * y + m[6] * z;
  2935. out[1] = m[1] * x + m[4] * y + m[7] * z;
  2936. out[2] = m[2] * x + m[5] * y + m[8] * z;
  2937. out[3] = a[3];
  2938. return out;
  2939. }
  2940. class Vector2 extends Vector {
  2941. constructor(x = 0, y = 0) {
  2942. super(2);
  2943. if (isArray(x) && arguments.length === 1) {
  2944. this.copy(x);
  2945. } else {
  2946. if (config.debug) {
  2947. checkNumber(x);
  2948. checkNumber(y);
  2949. }
  2950. this[0] = x;
  2951. this[1] = y;
  2952. }
  2953. }
  2954. set(x, y) {
  2955. this[0] = x;
  2956. this[1] = y;
  2957. return this.check();
  2958. }
  2959. copy(array) {
  2960. this[0] = array[0];
  2961. this[1] = array[1];
  2962. return this.check();
  2963. }
  2964. fromObject(object) {
  2965. if (config.debug) {
  2966. checkNumber(object.x);
  2967. checkNumber(object.y);
  2968. }
  2969. this[0] = object.x;
  2970. this[1] = object.y;
  2971. return this.check();
  2972. }
  2973. toObject(object) {
  2974. object.x = this[0];
  2975. object.y = this[1];
  2976. return object;
  2977. }
  2978. get ELEMENTS() {
  2979. return 2;
  2980. }
  2981. horizontalAngle() {
  2982. return Math.atan2(this.y, this.x);
  2983. }
  2984. verticalAngle() {
  2985. return Math.atan2(this.x, this.y);
  2986. }
  2987. transform(matrix4) {
  2988. return this.transformAsPoint(matrix4);
  2989. }
  2990. transformAsPoint(matrix4) {
  2991. transformMat4$2(this, this, matrix4);
  2992. return this.check();
  2993. }
  2994. transformAsVector(matrix4) {
  2995. vec2_transformMat4AsVector(this, this, matrix4);
  2996. return this.check();
  2997. }
  2998. transformByMatrix3(matrix3) {
  2999. transformMat3$1(this, this, matrix3);
  3000. return this.check();
  3001. }
  3002. transformByMatrix2x3(matrix2x3) {
  3003. transformMat2d(this, this, matrix2x3);
  3004. return this.check();
  3005. }
  3006. transformByMatrix2(matrix2) {
  3007. transformMat2(this, this, matrix2);
  3008. return this.check();
  3009. }
  3010. }
  3011. /**
  3012. * 3 Dimensional Vector
  3013. * @module vec3
  3014. */
  3015. /**
  3016. * Creates a new, empty vec3
  3017. *
  3018. * @returns {vec3} a new 3D vector
  3019. */
  3020. function create$3() {
  3021. var out = new ARRAY_TYPE(3);
  3022. if (ARRAY_TYPE != Float32Array) {
  3023. out[0] = 0;
  3024. out[1] = 0;
  3025. out[2] = 0;
  3026. }
  3027. return out;
  3028. }
  3029. /**
  3030. * Calculates the length of a vec3
  3031. *
  3032. * @param {ReadonlyVec3} a vector to calculate length of
  3033. * @returns {Number} length of a
  3034. */
  3035. function length$2(a) {
  3036. var x = a[0];
  3037. var y = a[1];
  3038. var z = a[2];
  3039. return Math.hypot(x, y, z);
  3040. }
  3041. /**
  3042. * Creates a new vec3 initialized with the given values
  3043. *
  3044. * @param {Number} x X component
  3045. * @param {Number} y Y component
  3046. * @param {Number} z Z component
  3047. * @returns {vec3} a new 3D vector
  3048. */
  3049. function fromValues(x, y, z) {
  3050. var out = new ARRAY_TYPE(3);
  3051. out[0] = x;
  3052. out[1] = y;
  3053. out[2] = z;
  3054. return out;
  3055. }
  3056. /**
  3057. * Normalize a vec3
  3058. *
  3059. * @param {vec3} out the receiving vector
  3060. * @param {ReadonlyVec3} a vector to normalize
  3061. * @returns {vec3} out
  3062. */
  3063. function normalize$2(out, a) {
  3064. var x = a[0];
  3065. var y = a[1];
  3066. var z = a[2];
  3067. var len = x * x + y * y + z * z;
  3068. if (len > 0) {
  3069. //TODO: evaluate use of glm_invsqrt here?
  3070. len = 1 / Math.sqrt(len);
  3071. }
  3072. out[0] = a[0] * len;
  3073. out[1] = a[1] * len;
  3074. out[2] = a[2] * len;
  3075. return out;
  3076. }
  3077. /**
  3078. * Calculates the dot product of two vec3's
  3079. *
  3080. * @param {ReadonlyVec3} a the first operand
  3081. * @param {ReadonlyVec3} b the second operand
  3082. * @returns {Number} dot product of a and b
  3083. */
  3084. function dot$2(a, b) {
  3085. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  3086. }
  3087. /**
  3088. * Computes the cross product of two vec3's
  3089. *
  3090. * @param {vec3} out the receiving vector
  3091. * @param {ReadonlyVec3} a the first operand
  3092. * @param {ReadonlyVec3} b the second operand
  3093. * @returns {vec3} out
  3094. */
  3095. function cross(out, a, b) {
  3096. var ax = a[0],
  3097. ay = a[1],
  3098. az = a[2];
  3099. var bx = b[0],
  3100. by = b[1],
  3101. bz = b[2];
  3102. out[0] = ay * bz - az * by;
  3103. out[1] = az * bx - ax * bz;
  3104. out[2] = ax * by - ay * bx;
  3105. return out;
  3106. }
  3107. /**
  3108. * Transforms the vec3 with a mat4.
  3109. * 4th vector component is implicitly '1'
  3110. *
  3111. * @param {vec3} out the receiving vector
  3112. * @param {ReadonlyVec3} a the vector to transform
  3113. * @param {ReadonlyMat4} m matrix to transform with
  3114. * @returns {vec3} out
  3115. */
  3116. function transformMat4$1(out, a, m) {
  3117. var x = a[0],
  3118. y = a[1],
  3119. z = a[2];
  3120. var w = m[3] * x + m[7] * y + m[11] * z + m[15];
  3121. w = w || 1.0;
  3122. out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
  3123. out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
  3124. out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
  3125. return out;
  3126. }
  3127. /**
  3128. * Transforms the vec3 with a mat3.
  3129. *
  3130. * @param {vec3} out the receiving vector
  3131. * @param {ReadonlyVec3} a the vector to transform
  3132. * @param {ReadonlyMat3} m the 3x3 matrix to transform with
  3133. * @returns {vec3} out
  3134. */
  3135. function transformMat3(out, a, m) {
  3136. var x = a[0],
  3137. y = a[1],
  3138. z = a[2];
  3139. out[0] = x * m[0] + y * m[3] + z * m[6];
  3140. out[1] = x * m[1] + y * m[4] + z * m[7];
  3141. out[2] = x * m[2] + y * m[5] + z * m[8];
  3142. return out;
  3143. }
  3144. /**
  3145. * Transforms the vec3 with a quat
  3146. * Can also be used for dual quaternions. (Multiply it with the real part)
  3147. *
  3148. * @param {vec3} out the receiving vector
  3149. * @param {ReadonlyVec3} a the vector to transform
  3150. * @param {ReadonlyQuat} q quaternion to transform with
  3151. * @returns {vec3} out
  3152. */
  3153. function transformQuat$1(out, a, q) {
  3154. // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed
  3155. var qx = q[0],
  3156. qy = q[1],
  3157. qz = q[2],
  3158. qw = q[3];
  3159. var x = a[0],
  3160. y = a[1],
  3161. z = a[2]; // var qvec = [qx, qy, qz];
  3162. // var uv = vec3.cross([], qvec, a);
  3163. var uvx = qy * z - qz * y,
  3164. uvy = qz * x - qx * z,
  3165. uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);
  3166. var uuvx = qy * uvz - qz * uvy,
  3167. uuvy = qz * uvx - qx * uvz,
  3168. uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);
  3169. var w2 = qw * 2;
  3170. uvx *= w2;
  3171. uvy *= w2;
  3172. uvz *= w2; // vec3.scale(uuv, uuv, 2);
  3173. uuvx *= 2;
  3174. uuvy *= 2;
  3175. uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));
  3176. out[0] = x + uvx + uuvx;
  3177. out[1] = y + uvy + uuvy;
  3178. out[2] = z + uvz + uuvz;
  3179. return out;
  3180. }
  3181. /**
  3182. * Rotate a 3D vector around the x-axis
  3183. * @param {vec3} out The receiving vec3
  3184. * @param {ReadonlyVec3} a The vec3 point to rotate
  3185. * @param {ReadonlyVec3} b The origin of the rotation
  3186. * @param {Number} rad The angle of rotation in radians
  3187. * @returns {vec3} out
  3188. */
  3189. function rotateX$2(out, a, b, rad) {
  3190. var p = [],
  3191. r = []; //Translate point to the origin
  3192. p[0] = a[0] - b[0];
  3193. p[1] = a[1] - b[1];
  3194. p[2] = a[2] - b[2]; //perform rotation
  3195. r[0] = p[0];
  3196. r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);
  3197. r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position
  3198. out[0] = r[0] + b[0];
  3199. out[1] = r[1] + b[1];
  3200. out[2] = r[2] + b[2];
  3201. return out;
  3202. }
  3203. /**
  3204. * Rotate a 3D vector around the y-axis
  3205. * @param {vec3} out The receiving vec3
  3206. * @param {ReadonlyVec3} a The vec3 point to rotate
  3207. * @param {ReadonlyVec3} b The origin of the rotation
  3208. * @param {Number} rad The angle of rotation in radians
  3209. * @returns {vec3} out
  3210. */
  3211. function rotateY$2(out, a, b, rad) {
  3212. var p = [],
  3213. r = []; //Translate point to the origin
  3214. p[0] = a[0] - b[0];
  3215. p[1] = a[1] - b[1];
  3216. p[2] = a[2] - b[2]; //perform rotation
  3217. r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);
  3218. r[1] = p[1];
  3219. r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position
  3220. out[0] = r[0] + b[0];
  3221. out[1] = r[1] + b[1];
  3222. out[2] = r[2] + b[2];
  3223. return out;
  3224. }
  3225. /**
  3226. * Rotate a 3D vector around the z-axis
  3227. * @param {vec3} out The receiving vec3
  3228. * @param {ReadonlyVec3} a The vec3 point to rotate
  3229. * @param {ReadonlyVec3} b The origin of the rotation
  3230. * @param {Number} rad The angle of rotation in radians
  3231. * @returns {vec3} out
  3232. */
  3233. function rotateZ$2(out, a, b, rad) {
  3234. var p = [],
  3235. r = []; //Translate point to the origin
  3236. p[0] = a[0] - b[0];
  3237. p[1] = a[1] - b[1];
  3238. p[2] = a[2] - b[2]; //perform rotation
  3239. r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);
  3240. r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);
  3241. r[2] = p[2]; //translate to correct position
  3242. out[0] = r[0] + b[0];
  3243. out[1] = r[1] + b[1];
  3244. out[2] = r[2] + b[2];
  3245. return out;
  3246. }
  3247. /**
  3248. * Get the angle between two 3D vectors
  3249. * @param {ReadonlyVec3} a The first operand
  3250. * @param {ReadonlyVec3} b The second operand
  3251. * @returns {Number} The angle in radians
  3252. */
  3253. function angle(a, b) {
  3254. var ax = a[0],
  3255. ay = a[1],
  3256. az = a[2],
  3257. bx = b[0],
  3258. by = b[1],
  3259. bz = b[2],
  3260. mag1 = Math.sqrt(ax * ax + ay * ay + az * az),
  3261. mag2 = Math.sqrt(bx * bx + by * by + bz * bz),
  3262. mag = mag1 * mag2,
  3263. cosine = mag && dot$2(a, b) / mag;
  3264. return Math.acos(Math.min(Math.max(cosine, -1), 1));
  3265. }
  3266. /**
  3267. * Alias for {@link vec3.length}
  3268. * @function
  3269. */
  3270. var len = length$2;
  3271. /**
  3272. * Perform some operation over an array of vec3s.
  3273. *
  3274. * @param {Array} a the array of vectors to iterate over
  3275. * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
  3276. * @param {Number} offset Number of elements to skip at the beginning of the array
  3277. * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
  3278. * @param {Function} fn Function to call for each vector in the array
  3279. * @param {Object} [arg] additional argument to pass to fn
  3280. * @returns {Array} a
  3281. * @function
  3282. */
  3283. (function () {
  3284. var vec = create$3();
  3285. return function (a, stride, offset, count, fn, arg) {
  3286. var i, l;
  3287. if (!stride) {
  3288. stride = 3;
  3289. }
  3290. if (!offset) {
  3291. offset = 0;
  3292. }
  3293. if (count) {
  3294. l = Math.min(count * stride + offset, a.length);
  3295. } else {
  3296. l = a.length;
  3297. }
  3298. for (i = offset; i < l; i += stride) {
  3299. vec[0] = a[i];
  3300. vec[1] = a[i + 1];
  3301. vec[2] = a[i + 2];
  3302. fn(vec, vec, arg);
  3303. a[i] = vec[0];
  3304. a[i + 1] = vec[1];
  3305. a[i + 2] = vec[2];
  3306. }
  3307. return a;
  3308. };
  3309. })();
  3310. const ORIGIN = [0, 0, 0];
  3311. const constants$2 = {};
  3312. class Vector3 extends Vector {
  3313. static get ZERO() {
  3314. return constants$2.ZERO = constants$2.ZERO || Object.freeze(new Vector3(0, 0, 0, 0));
  3315. }
  3316. constructor(x = 0, y = 0, z = 0) {
  3317. super(-0, -0, -0);
  3318. if (arguments.length === 1 && isArray(x)) {
  3319. this.copy(x);
  3320. } else {
  3321. if (config.debug) {
  3322. checkNumber(x);
  3323. checkNumber(y);
  3324. checkNumber(z);
  3325. }
  3326. this[0] = x;
  3327. this[1] = y;
  3328. this[2] = z;
  3329. }
  3330. }
  3331. set(x, y, z) {
  3332. this[0] = x;
  3333. this[1] = y;
  3334. this[2] = z;
  3335. return this.check();
  3336. }
  3337. copy(array) {
  3338. this[0] = array[0];
  3339. this[1] = array[1];
  3340. this[2] = array[2];
  3341. return this.check();
  3342. }
  3343. fromObject(object) {
  3344. if (config.debug) {
  3345. checkNumber(object.x);
  3346. checkNumber(object.y);
  3347. checkNumber(object.z);
  3348. }
  3349. this[0] = object.x;
  3350. this[1] = object.y;
  3351. this[2] = object.z;
  3352. return this.check();
  3353. }
  3354. toObject(object) {
  3355. object.x = this[0];
  3356. object.y = this[1];
  3357. object.z = this[2];
  3358. return object;
  3359. }
  3360. get ELEMENTS() {
  3361. return 3;
  3362. }
  3363. get z() {
  3364. return this[2];
  3365. }
  3366. set z(value) {
  3367. this[2] = checkNumber(value);
  3368. }
  3369. angle(vector) {
  3370. return angle(this, vector);
  3371. }
  3372. cross(vector) {
  3373. cross(this, this, vector);
  3374. return this.check();
  3375. }
  3376. rotateX({
  3377. radians,
  3378. origin = ORIGIN
  3379. }) {
  3380. rotateX$2(this, this, origin, radians);
  3381. return this.check();
  3382. }
  3383. rotateY({
  3384. radians,
  3385. origin = ORIGIN
  3386. }) {
  3387. rotateY$2(this, this, origin, radians);
  3388. return this.check();
  3389. }
  3390. rotateZ({
  3391. radians,
  3392. origin = ORIGIN
  3393. }) {
  3394. rotateZ$2(this, this, origin, radians);
  3395. return this.check();
  3396. }
  3397. transform(matrix4) {
  3398. return this.transformAsPoint(matrix4);
  3399. }
  3400. transformAsPoint(matrix4) {
  3401. transformMat4$1(this, this, matrix4);
  3402. return this.check();
  3403. }
  3404. transformAsVector(matrix4) {
  3405. vec3_transformMat4AsVector(this, this, matrix4);
  3406. return this.check();
  3407. }
  3408. transformByMatrix3(matrix3) {
  3409. transformMat3(this, this, matrix3);
  3410. return this.check();
  3411. }
  3412. transformByMatrix2(matrix2) {
  3413. vec3_transformMat2(this, this, matrix2);
  3414. return this.check();
  3415. }
  3416. transformByQuaternion(quaternion) {
  3417. transformQuat$1(this, this, quaternion);
  3418. return this.check();
  3419. }
  3420. }
  3421. class Matrix extends MathArray {
  3422. get ELEMENTS() {
  3423. assert$4(false);
  3424. return 0;
  3425. }
  3426. get RANK() {
  3427. assert$4(false);
  3428. return 0;
  3429. }
  3430. toString() {
  3431. let string = '[';
  3432. if (config.printRowMajor) {
  3433. string += 'row-major:';
  3434. for (let row = 0; row < this.RANK; ++row) {
  3435. for (let col = 0; col < this.RANK; ++col) {
  3436. string += " ".concat(this[col * this.RANK + row]);
  3437. }
  3438. }
  3439. } else {
  3440. string += 'column-major:';
  3441. for (let i = 0; i < this.ELEMENTS; ++i) {
  3442. string += " ".concat(this[i]);
  3443. }
  3444. }
  3445. string += ']';
  3446. return string;
  3447. }
  3448. getElementIndex(row, col) {
  3449. return col * this.RANK + row;
  3450. }
  3451. getElement(row, col) {
  3452. return this[col * this.RANK + row];
  3453. }
  3454. setElement(row, col, value) {
  3455. this[col * this.RANK + row] = checkNumber(value);
  3456. return this;
  3457. }
  3458. getColumn(columnIndex, result = new Array(this.RANK).fill(-0)) {
  3459. const firstIndex = columnIndex * this.RANK;
  3460. for (let i = 0; i < this.RANK; ++i) {
  3461. result[i] = this[firstIndex + i];
  3462. }
  3463. return result;
  3464. }
  3465. setColumn(columnIndex, columnVector) {
  3466. const firstIndex = columnIndex * this.RANK;
  3467. for (let i = 0; i < this.RANK; ++i) {
  3468. this[firstIndex + i] = columnVector[i];
  3469. }
  3470. return this;
  3471. }
  3472. }
  3473. /**
  3474. * 3x3 Matrix
  3475. * @module mat3
  3476. */
  3477. /**
  3478. * Creates a new identity mat3
  3479. *
  3480. * @returns {mat3} a new 3x3 matrix
  3481. */
  3482. function create$2() {
  3483. var out = new ARRAY_TYPE(9);
  3484. if (ARRAY_TYPE != Float32Array) {
  3485. out[1] = 0;
  3486. out[2] = 0;
  3487. out[3] = 0;
  3488. out[5] = 0;
  3489. out[6] = 0;
  3490. out[7] = 0;
  3491. }
  3492. out[0] = 1;
  3493. out[4] = 1;
  3494. out[8] = 1;
  3495. return out;
  3496. }
  3497. /**
  3498. * Transpose the values of a mat3
  3499. *
  3500. * @param {mat3} out the receiving matrix
  3501. * @param {ReadonlyMat3} a the source matrix
  3502. * @returns {mat3} out
  3503. */
  3504. function transpose$1(out, a) {
  3505. // If we are transposing ourselves we can skip a few steps but have to cache some values
  3506. if (out === a) {
  3507. var a01 = a[1],
  3508. a02 = a[2],
  3509. a12 = a[5];
  3510. out[1] = a[3];
  3511. out[2] = a[6];
  3512. out[3] = a01;
  3513. out[5] = a[7];
  3514. out[6] = a02;
  3515. out[7] = a12;
  3516. } else {
  3517. out[0] = a[0];
  3518. out[1] = a[3];
  3519. out[2] = a[6];
  3520. out[3] = a[1];
  3521. out[4] = a[4];
  3522. out[5] = a[7];
  3523. out[6] = a[2];
  3524. out[7] = a[5];
  3525. out[8] = a[8];
  3526. }
  3527. return out;
  3528. }
  3529. /**
  3530. * Inverts a mat3
  3531. *
  3532. * @param {mat3} out the receiving matrix
  3533. * @param {ReadonlyMat3} a the source matrix
  3534. * @returns {mat3} out
  3535. */
  3536. function invert$2(out, a) {
  3537. var a00 = a[0],
  3538. a01 = a[1],
  3539. a02 = a[2];
  3540. var a10 = a[3],
  3541. a11 = a[4],
  3542. a12 = a[5];
  3543. var a20 = a[6],
  3544. a21 = a[7],
  3545. a22 = a[8];
  3546. var b01 = a22 * a11 - a12 * a21;
  3547. var b11 = -a22 * a10 + a12 * a20;
  3548. var b21 = a21 * a10 - a11 * a20; // Calculate the determinant
  3549. var det = a00 * b01 + a01 * b11 + a02 * b21;
  3550. if (!det) {
  3551. return null;
  3552. }
  3553. det = 1.0 / det;
  3554. out[0] = b01 * det;
  3555. out[1] = (-a22 * a01 + a02 * a21) * det;
  3556. out[2] = (a12 * a01 - a02 * a11) * det;
  3557. out[3] = b11 * det;
  3558. out[4] = (a22 * a00 - a02 * a20) * det;
  3559. out[5] = (-a12 * a00 + a02 * a10) * det;
  3560. out[6] = b21 * det;
  3561. out[7] = (-a21 * a00 + a01 * a20) * det;
  3562. out[8] = (a11 * a00 - a01 * a10) * det;
  3563. return out;
  3564. }
  3565. /**
  3566. * Calculates the determinant of a mat3
  3567. *
  3568. * @param {ReadonlyMat3} a the source matrix
  3569. * @returns {Number} determinant of a
  3570. */
  3571. function determinant$1(a) {
  3572. var a00 = a[0],
  3573. a01 = a[1],
  3574. a02 = a[2];
  3575. var a10 = a[3],
  3576. a11 = a[4],
  3577. a12 = a[5];
  3578. var a20 = a[6],
  3579. a21 = a[7],
  3580. a22 = a[8];
  3581. return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
  3582. }
  3583. /**
  3584. * Multiplies two mat3's
  3585. *
  3586. * @param {mat3} out the receiving matrix
  3587. * @param {ReadonlyMat3} a the first operand
  3588. * @param {ReadonlyMat3} b the second operand
  3589. * @returns {mat3} out
  3590. */
  3591. function multiply$2(out, a, b) {
  3592. var a00 = a[0],
  3593. a01 = a[1],
  3594. a02 = a[2];
  3595. var a10 = a[3],
  3596. a11 = a[4],
  3597. a12 = a[5];
  3598. var a20 = a[6],
  3599. a21 = a[7],
  3600. a22 = a[8];
  3601. var b00 = b[0],
  3602. b01 = b[1],
  3603. b02 = b[2];
  3604. var b10 = b[3],
  3605. b11 = b[4],
  3606. b12 = b[5];
  3607. var b20 = b[6],
  3608. b21 = b[7],
  3609. b22 = b[8];
  3610. out[0] = b00 * a00 + b01 * a10 + b02 * a20;
  3611. out[1] = b00 * a01 + b01 * a11 + b02 * a21;
  3612. out[2] = b00 * a02 + b01 * a12 + b02 * a22;
  3613. out[3] = b10 * a00 + b11 * a10 + b12 * a20;
  3614. out[4] = b10 * a01 + b11 * a11 + b12 * a21;
  3615. out[5] = b10 * a02 + b11 * a12 + b12 * a22;
  3616. out[6] = b20 * a00 + b21 * a10 + b22 * a20;
  3617. out[7] = b20 * a01 + b21 * a11 + b22 * a21;
  3618. out[8] = b20 * a02 + b21 * a12 + b22 * a22;
  3619. return out;
  3620. }
  3621. /**
  3622. * Translate a mat3 by the given vector
  3623. *
  3624. * @param {mat3} out the receiving matrix
  3625. * @param {ReadonlyMat3} a the matrix to translate
  3626. * @param {ReadonlyVec2} v vector to translate by
  3627. * @returns {mat3} out
  3628. */
  3629. function translate$1(out, a, v) {
  3630. var a00 = a[0],
  3631. a01 = a[1],
  3632. a02 = a[2],
  3633. a10 = a[3],
  3634. a11 = a[4],
  3635. a12 = a[5],
  3636. a20 = a[6],
  3637. a21 = a[7],
  3638. a22 = a[8],
  3639. x = v[0],
  3640. y = v[1];
  3641. out[0] = a00;
  3642. out[1] = a01;
  3643. out[2] = a02;
  3644. out[3] = a10;
  3645. out[4] = a11;
  3646. out[5] = a12;
  3647. out[6] = x * a00 + y * a10 + a20;
  3648. out[7] = x * a01 + y * a11 + a21;
  3649. out[8] = x * a02 + y * a12 + a22;
  3650. return out;
  3651. }
  3652. /**
  3653. * Rotates a mat3 by the given angle
  3654. *
  3655. * @param {mat3} out the receiving matrix
  3656. * @param {ReadonlyMat3} a the matrix to rotate
  3657. * @param {Number} rad the angle to rotate the matrix by
  3658. * @returns {mat3} out
  3659. */
  3660. function rotate$1(out, a, rad) {
  3661. var a00 = a[0],
  3662. a01 = a[1],
  3663. a02 = a[2],
  3664. a10 = a[3],
  3665. a11 = a[4],
  3666. a12 = a[5],
  3667. a20 = a[6],
  3668. a21 = a[7],
  3669. a22 = a[8],
  3670. s = Math.sin(rad),
  3671. c = Math.cos(rad);
  3672. out[0] = c * a00 + s * a10;
  3673. out[1] = c * a01 + s * a11;
  3674. out[2] = c * a02 + s * a12;
  3675. out[3] = c * a10 - s * a00;
  3676. out[4] = c * a11 - s * a01;
  3677. out[5] = c * a12 - s * a02;
  3678. out[6] = a20;
  3679. out[7] = a21;
  3680. out[8] = a22;
  3681. return out;
  3682. }
  3683. /**
  3684. * Scales the mat3 by the dimensions in the given vec2
  3685. *
  3686. * @param {mat3} out the receiving matrix
  3687. * @param {ReadonlyMat3} a the matrix to rotate
  3688. * @param {ReadonlyVec2} v the vec2 to scale the matrix by
  3689. * @returns {mat3} out
  3690. **/
  3691. function scale$3(out, a, v) {
  3692. var x = v[0],
  3693. y = v[1];
  3694. out[0] = x * a[0];
  3695. out[1] = x * a[1];
  3696. out[2] = x * a[2];
  3697. out[3] = y * a[3];
  3698. out[4] = y * a[4];
  3699. out[5] = y * a[5];
  3700. out[6] = a[6];
  3701. out[7] = a[7];
  3702. out[8] = a[8];
  3703. return out;
  3704. }
  3705. /**
  3706. * Calculates a 3x3 matrix from the given quaternion
  3707. *
  3708. * @param {mat3} out mat3 receiving operation result
  3709. * @param {ReadonlyQuat} q Quaternion to create matrix from
  3710. *
  3711. * @returns {mat3} out
  3712. */
  3713. function fromQuat$1(out, q) {
  3714. var x = q[0],
  3715. y = q[1],
  3716. z = q[2],
  3717. w = q[3];
  3718. var x2 = x + x;
  3719. var y2 = y + y;
  3720. var z2 = z + z;
  3721. var xx = x * x2;
  3722. var yx = y * x2;
  3723. var yy = y * y2;
  3724. var zx = z * x2;
  3725. var zy = z * y2;
  3726. var zz = z * z2;
  3727. var wx = w * x2;
  3728. var wy = w * y2;
  3729. var wz = w * z2;
  3730. out[0] = 1 - yy - zz;
  3731. out[3] = yx - wz;
  3732. out[6] = zx + wy;
  3733. out[1] = yx + wz;
  3734. out[4] = 1 - xx - zz;
  3735. out[7] = zy - wx;
  3736. out[2] = zx - wy;
  3737. out[5] = zy + wx;
  3738. out[8] = 1 - xx - yy;
  3739. return out;
  3740. }
  3741. const IDENTITY$1 = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1]);
  3742. const ZERO$1 = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0]);
  3743. const INDICES$1 = Object.freeze({
  3744. COL0ROW0: 0,
  3745. COL0ROW1: 1,
  3746. COL0ROW2: 2,
  3747. COL1ROW0: 3,
  3748. COL1ROW1: 4,
  3749. COL1ROW2: 5,
  3750. COL2ROW0: 6,
  3751. COL2ROW1: 7,
  3752. COL2ROW2: 8
  3753. });
  3754. const constants$1 = {};
  3755. class Matrix3 extends Matrix {
  3756. static get IDENTITY() {
  3757. constants$1.IDENTITY = constants$1.IDENTITY || Object.freeze(new Matrix3(IDENTITY$1));
  3758. return constants$1.IDENTITY;
  3759. }
  3760. static get ZERO() {
  3761. constants$1.ZERO = constants$1.ZERO || Object.freeze(new Matrix3(ZERO$1));
  3762. return constants$1.ZERO;
  3763. }
  3764. get ELEMENTS() {
  3765. return 9;
  3766. }
  3767. get RANK() {
  3768. return 3;
  3769. }
  3770. get INDICES() {
  3771. return INDICES$1;
  3772. }
  3773. constructor(array) {
  3774. super(-0, -0, -0, -0, -0, -0, -0, -0, -0);
  3775. if (arguments.length === 1 && Array.isArray(array)) {
  3776. this.copy(array);
  3777. } else {
  3778. this.identity();
  3779. }
  3780. }
  3781. copy(array) {
  3782. this[0] = array[0];
  3783. this[1] = array[1];
  3784. this[2] = array[2];
  3785. this[3] = array[3];
  3786. this[4] = array[4];
  3787. this[5] = array[5];
  3788. this[6] = array[6];
  3789. this[7] = array[7];
  3790. this[8] = array[8];
  3791. return this.check();
  3792. }
  3793. set(m00, m10, m20, m01, m11, m21, m02, m12, m22) {
  3794. this[0] = m00;
  3795. this[1] = m10;
  3796. this[2] = m20;
  3797. this[3] = m01;
  3798. this[4] = m11;
  3799. this[5] = m21;
  3800. this[6] = m02;
  3801. this[7] = m12;
  3802. this[8] = m22;
  3803. return this.check();
  3804. }
  3805. setRowMajor(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
  3806. this[0] = m00;
  3807. this[1] = m10;
  3808. this[2] = m20;
  3809. this[3] = m01;
  3810. this[4] = m11;
  3811. this[5] = m21;
  3812. this[6] = m02;
  3813. this[7] = m12;
  3814. this[8] = m22;
  3815. return this.check();
  3816. }
  3817. determinant() {
  3818. return determinant$1(this);
  3819. }
  3820. identity() {
  3821. return this.copy(IDENTITY$1);
  3822. }
  3823. fromQuaternion(q) {
  3824. fromQuat$1(this, q);
  3825. return this.check();
  3826. }
  3827. transpose() {
  3828. transpose$1(this, this);
  3829. return this.check();
  3830. }
  3831. invert() {
  3832. invert$2(this, this);
  3833. return this.check();
  3834. }
  3835. multiplyLeft(a) {
  3836. multiply$2(this, a, this);
  3837. return this.check();
  3838. }
  3839. multiplyRight(a) {
  3840. multiply$2(this, this, a);
  3841. return this.check();
  3842. }
  3843. rotate(radians) {
  3844. rotate$1(this, this, radians);
  3845. return this.check();
  3846. }
  3847. scale(factor) {
  3848. if (Array.isArray(factor)) {
  3849. scale$3(this, this, factor);
  3850. } else {
  3851. scale$3(this, this, [factor, factor, factor]);
  3852. }
  3853. return this.check();
  3854. }
  3855. translate(vec) {
  3856. translate$1(this, this, vec);
  3857. return this.check();
  3858. }
  3859. transform(vector, result) {
  3860. switch (vector.length) {
  3861. case 2:
  3862. result = transformMat3$1(result || [-0, -0], vector, this);
  3863. break;
  3864. case 3:
  3865. result = transformMat3(result || [-0, -0, -0], vector, this);
  3866. break;
  3867. case 4:
  3868. result = vec4_transformMat3(result || [-0, -0, -0, -0], vector, this);
  3869. break;
  3870. default:
  3871. throw new Error('Illegal vector');
  3872. }
  3873. checkVector(result, vector.length);
  3874. return result;
  3875. }
  3876. transformVector(vector, result) {
  3877. deprecated('Matrix3.transformVector');
  3878. return this.transform(vector, result);
  3879. }
  3880. transformVector2(vector, result) {
  3881. deprecated('Matrix3.transformVector');
  3882. return this.transform(vector, result);
  3883. }
  3884. transformVector3(vector, result) {
  3885. deprecated('Matrix3.transformVector');
  3886. return this.transform(vector, result);
  3887. }
  3888. }
  3889. /**
  3890. * Set a mat4 to the identity matrix
  3891. *
  3892. * @param {mat4} out the receiving matrix
  3893. * @returns {mat4} out
  3894. */
  3895. function identity$1(out) {
  3896. out[0] = 1;
  3897. out[1] = 0;
  3898. out[2] = 0;
  3899. out[3] = 0;
  3900. out[4] = 0;
  3901. out[5] = 1;
  3902. out[6] = 0;
  3903. out[7] = 0;
  3904. out[8] = 0;
  3905. out[9] = 0;
  3906. out[10] = 1;
  3907. out[11] = 0;
  3908. out[12] = 0;
  3909. out[13] = 0;
  3910. out[14] = 0;
  3911. out[15] = 1;
  3912. return out;
  3913. }
  3914. /**
  3915. * Transpose the values of a mat4
  3916. *
  3917. * @param {mat4} out the receiving matrix
  3918. * @param {ReadonlyMat4} a the source matrix
  3919. * @returns {mat4} out
  3920. */
  3921. function transpose(out, a) {
  3922. // If we are transposing ourselves we can skip a few steps but have to cache some values
  3923. if (out === a) {
  3924. var a01 = a[1],
  3925. a02 = a[2],
  3926. a03 = a[3];
  3927. var a12 = a[6],
  3928. a13 = a[7];
  3929. var a23 = a[11];
  3930. out[1] = a[4];
  3931. out[2] = a[8];
  3932. out[3] = a[12];
  3933. out[4] = a01;
  3934. out[6] = a[9];
  3935. out[7] = a[13];
  3936. out[8] = a02;
  3937. out[9] = a12;
  3938. out[11] = a[14];
  3939. out[12] = a03;
  3940. out[13] = a13;
  3941. out[14] = a23;
  3942. } else {
  3943. out[0] = a[0];
  3944. out[1] = a[4];
  3945. out[2] = a[8];
  3946. out[3] = a[12];
  3947. out[4] = a[1];
  3948. out[5] = a[5];
  3949. out[6] = a[9];
  3950. out[7] = a[13];
  3951. out[8] = a[2];
  3952. out[9] = a[6];
  3953. out[10] = a[10];
  3954. out[11] = a[14];
  3955. out[12] = a[3];
  3956. out[13] = a[7];
  3957. out[14] = a[11];
  3958. out[15] = a[15];
  3959. }
  3960. return out;
  3961. }
  3962. /**
  3963. * Inverts a mat4
  3964. *
  3965. * @param {mat4} out the receiving matrix
  3966. * @param {ReadonlyMat4} a the source matrix
  3967. * @returns {mat4} out
  3968. */
  3969. function invert$1(out, a) {
  3970. var a00 = a[0],
  3971. a01 = a[1],
  3972. a02 = a[2],
  3973. a03 = a[3];
  3974. var a10 = a[4],
  3975. a11 = a[5],
  3976. a12 = a[6],
  3977. a13 = a[7];
  3978. var a20 = a[8],
  3979. a21 = a[9],
  3980. a22 = a[10],
  3981. a23 = a[11];
  3982. var a30 = a[12],
  3983. a31 = a[13],
  3984. a32 = a[14],
  3985. a33 = a[15];
  3986. var b00 = a00 * a11 - a01 * a10;
  3987. var b01 = a00 * a12 - a02 * a10;
  3988. var b02 = a00 * a13 - a03 * a10;
  3989. var b03 = a01 * a12 - a02 * a11;
  3990. var b04 = a01 * a13 - a03 * a11;
  3991. var b05 = a02 * a13 - a03 * a12;
  3992. var b06 = a20 * a31 - a21 * a30;
  3993. var b07 = a20 * a32 - a22 * a30;
  3994. var b08 = a20 * a33 - a23 * a30;
  3995. var b09 = a21 * a32 - a22 * a31;
  3996. var b10 = a21 * a33 - a23 * a31;
  3997. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  3998. var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  3999. if (!det) {
  4000. return null;
  4001. }
  4002. det = 1.0 / det;
  4003. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  4004. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  4005. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  4006. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  4007. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  4008. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  4009. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  4010. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  4011. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  4012. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  4013. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  4014. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  4015. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  4016. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  4017. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  4018. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  4019. return out;
  4020. }
  4021. /**
  4022. * Calculates the determinant of a mat4
  4023. *
  4024. * @param {ReadonlyMat4} a the source matrix
  4025. * @returns {Number} determinant of a
  4026. */
  4027. function determinant(a) {
  4028. var a00 = a[0],
  4029. a01 = a[1],
  4030. a02 = a[2],
  4031. a03 = a[3];
  4032. var a10 = a[4],
  4033. a11 = a[5],
  4034. a12 = a[6],
  4035. a13 = a[7];
  4036. var a20 = a[8],
  4037. a21 = a[9],
  4038. a22 = a[10],
  4039. a23 = a[11];
  4040. var a30 = a[12],
  4041. a31 = a[13],
  4042. a32 = a[14],
  4043. a33 = a[15];
  4044. var b00 = a00 * a11 - a01 * a10;
  4045. var b01 = a00 * a12 - a02 * a10;
  4046. var b02 = a00 * a13 - a03 * a10;
  4047. var b03 = a01 * a12 - a02 * a11;
  4048. var b04 = a01 * a13 - a03 * a11;
  4049. var b05 = a02 * a13 - a03 * a12;
  4050. var b06 = a20 * a31 - a21 * a30;
  4051. var b07 = a20 * a32 - a22 * a30;
  4052. var b08 = a20 * a33 - a23 * a30;
  4053. var b09 = a21 * a32 - a22 * a31;
  4054. var b10 = a21 * a33 - a23 * a31;
  4055. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  4056. return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  4057. }
  4058. /**
  4059. * Multiplies two mat4s
  4060. *
  4061. * @param {mat4} out the receiving matrix
  4062. * @param {ReadonlyMat4} a the first operand
  4063. * @param {ReadonlyMat4} b the second operand
  4064. * @returns {mat4} out
  4065. */
  4066. function multiply$1(out, a, b) {
  4067. var a00 = a[0],
  4068. a01 = a[1],
  4069. a02 = a[2],
  4070. a03 = a[3];
  4071. var a10 = a[4],
  4072. a11 = a[5],
  4073. a12 = a[6],
  4074. a13 = a[7];
  4075. var a20 = a[8],
  4076. a21 = a[9],
  4077. a22 = a[10],
  4078. a23 = a[11];
  4079. var a30 = a[12],
  4080. a31 = a[13],
  4081. a32 = a[14],
  4082. a33 = a[15]; // Cache only the current line of the second matrix
  4083. var b0 = b[0],
  4084. b1 = b[1],
  4085. b2 = b[2],
  4086. b3 = b[3];
  4087. out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4088. out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4089. out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4090. out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4091. b0 = b[4];
  4092. b1 = b[5];
  4093. b2 = b[6];
  4094. b3 = b[7];
  4095. out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4096. out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4097. out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4098. out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4099. b0 = b[8];
  4100. b1 = b[9];
  4101. b2 = b[10];
  4102. b3 = b[11];
  4103. out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4104. out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4105. out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4106. out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4107. b0 = b[12];
  4108. b1 = b[13];
  4109. b2 = b[14];
  4110. b3 = b[15];
  4111. out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  4112. out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  4113. out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  4114. out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  4115. return out;
  4116. }
  4117. /**
  4118. * Translate a mat4 by the given vector
  4119. *
  4120. * @param {mat4} out the receiving matrix
  4121. * @param {ReadonlyMat4} a the matrix to translate
  4122. * @param {ReadonlyVec3} v vector to translate by
  4123. * @returns {mat4} out
  4124. */
  4125. function translate(out, a, v) {
  4126. var x = v[0],
  4127. y = v[1],
  4128. z = v[2];
  4129. var a00, a01, a02, a03;
  4130. var a10, a11, a12, a13;
  4131. var a20, a21, a22, a23;
  4132. if (a === out) {
  4133. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  4134. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  4135. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  4136. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  4137. } else {
  4138. a00 = a[0];
  4139. a01 = a[1];
  4140. a02 = a[2];
  4141. a03 = a[3];
  4142. a10 = a[4];
  4143. a11 = a[5];
  4144. a12 = a[6];
  4145. a13 = a[7];
  4146. a20 = a[8];
  4147. a21 = a[9];
  4148. a22 = a[10];
  4149. a23 = a[11];
  4150. out[0] = a00;
  4151. out[1] = a01;
  4152. out[2] = a02;
  4153. out[3] = a03;
  4154. out[4] = a10;
  4155. out[5] = a11;
  4156. out[6] = a12;
  4157. out[7] = a13;
  4158. out[8] = a20;
  4159. out[9] = a21;
  4160. out[10] = a22;
  4161. out[11] = a23;
  4162. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  4163. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  4164. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  4165. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  4166. }
  4167. return out;
  4168. }
  4169. /**
  4170. * Scales the mat4 by the dimensions in the given vec3 not using vectorization
  4171. *
  4172. * @param {mat4} out the receiving matrix
  4173. * @param {ReadonlyMat4} a the matrix to scale
  4174. * @param {ReadonlyVec3} v the vec3 to scale the matrix by
  4175. * @returns {mat4} out
  4176. **/
  4177. function scale$2(out, a, v) {
  4178. var x = v[0],
  4179. y = v[1],
  4180. z = v[2];
  4181. out[0] = a[0] * x;
  4182. out[1] = a[1] * x;
  4183. out[2] = a[2] * x;
  4184. out[3] = a[3] * x;
  4185. out[4] = a[4] * y;
  4186. out[5] = a[5] * y;
  4187. out[6] = a[6] * y;
  4188. out[7] = a[7] * y;
  4189. out[8] = a[8] * z;
  4190. out[9] = a[9] * z;
  4191. out[10] = a[10] * z;
  4192. out[11] = a[11] * z;
  4193. out[12] = a[12];
  4194. out[13] = a[13];
  4195. out[14] = a[14];
  4196. out[15] = a[15];
  4197. return out;
  4198. }
  4199. /**
  4200. * Rotates a mat4 by the given angle around the given axis
  4201. *
  4202. * @param {mat4} out the receiving matrix
  4203. * @param {ReadonlyMat4} a the matrix to rotate
  4204. * @param {Number} rad the angle to rotate the matrix by
  4205. * @param {ReadonlyVec3} axis the axis to rotate around
  4206. * @returns {mat4} out
  4207. */
  4208. function rotate(out, a, rad, axis) {
  4209. var x = axis[0],
  4210. y = axis[1],
  4211. z = axis[2];
  4212. var len = Math.hypot(x, y, z);
  4213. var s, c, t;
  4214. var a00, a01, a02, a03;
  4215. var a10, a11, a12, a13;
  4216. var a20, a21, a22, a23;
  4217. var b00, b01, b02;
  4218. var b10, b11, b12;
  4219. var b20, b21, b22;
  4220. if (len < EPSILON) {
  4221. return null;
  4222. }
  4223. len = 1 / len;
  4224. x *= len;
  4225. y *= len;
  4226. z *= len;
  4227. s = Math.sin(rad);
  4228. c = Math.cos(rad);
  4229. t = 1 - c;
  4230. a00 = a[0];
  4231. a01 = a[1];
  4232. a02 = a[2];
  4233. a03 = a[3];
  4234. a10 = a[4];
  4235. a11 = a[5];
  4236. a12 = a[6];
  4237. a13 = a[7];
  4238. a20 = a[8];
  4239. a21 = a[9];
  4240. a22 = a[10];
  4241. a23 = a[11]; // Construct the elements of the rotation matrix
  4242. b00 = x * x * t + c;
  4243. b01 = y * x * t + z * s;
  4244. b02 = z * x * t - y * s;
  4245. b10 = x * y * t - z * s;
  4246. b11 = y * y * t + c;
  4247. b12 = z * y * t + x * s;
  4248. b20 = x * z * t + y * s;
  4249. b21 = y * z * t - x * s;
  4250. b22 = z * z * t + c; // Perform rotation-specific matrix multiplication
  4251. out[0] = a00 * b00 + a10 * b01 + a20 * b02;
  4252. out[1] = a01 * b00 + a11 * b01 + a21 * b02;
  4253. out[2] = a02 * b00 + a12 * b01 + a22 * b02;
  4254. out[3] = a03 * b00 + a13 * b01 + a23 * b02;
  4255. out[4] = a00 * b10 + a10 * b11 + a20 * b12;
  4256. out[5] = a01 * b10 + a11 * b11 + a21 * b12;
  4257. out[6] = a02 * b10 + a12 * b11 + a22 * b12;
  4258. out[7] = a03 * b10 + a13 * b11 + a23 * b12;
  4259. out[8] = a00 * b20 + a10 * b21 + a20 * b22;
  4260. out[9] = a01 * b20 + a11 * b21 + a21 * b22;
  4261. out[10] = a02 * b20 + a12 * b21 + a22 * b22;
  4262. out[11] = a03 * b20 + a13 * b21 + a23 * b22;
  4263. if (a !== out) {
  4264. // If the source and destination differ, copy the unchanged last row
  4265. out[12] = a[12];
  4266. out[13] = a[13];
  4267. out[14] = a[14];
  4268. out[15] = a[15];
  4269. }
  4270. return out;
  4271. }
  4272. /**
  4273. * Rotates a matrix by the given angle around the X axis
  4274. *
  4275. * @param {mat4} out the receiving matrix
  4276. * @param {ReadonlyMat4} a the matrix to rotate
  4277. * @param {Number} rad the angle to rotate the matrix by
  4278. * @returns {mat4} out
  4279. */
  4280. function rotateX$1(out, a, rad) {
  4281. var s = Math.sin(rad);
  4282. var c = Math.cos(rad);
  4283. var a10 = a[4];
  4284. var a11 = a[5];
  4285. var a12 = a[6];
  4286. var a13 = a[7];
  4287. var a20 = a[8];
  4288. var a21 = a[9];
  4289. var a22 = a[10];
  4290. var a23 = a[11];
  4291. if (a !== out) {
  4292. // If the source and destination differ, copy the unchanged rows
  4293. out[0] = a[0];
  4294. out[1] = a[1];
  4295. out[2] = a[2];
  4296. out[3] = a[3];
  4297. out[12] = a[12];
  4298. out[13] = a[13];
  4299. out[14] = a[14];
  4300. out[15] = a[15];
  4301. } // Perform axis-specific matrix multiplication
  4302. out[4] = a10 * c + a20 * s;
  4303. out[5] = a11 * c + a21 * s;
  4304. out[6] = a12 * c + a22 * s;
  4305. out[7] = a13 * c + a23 * s;
  4306. out[8] = a20 * c - a10 * s;
  4307. out[9] = a21 * c - a11 * s;
  4308. out[10] = a22 * c - a12 * s;
  4309. out[11] = a23 * c - a13 * s;
  4310. return out;
  4311. }
  4312. /**
  4313. * Rotates a matrix by the given angle around the Y axis
  4314. *
  4315. * @param {mat4} out the receiving matrix
  4316. * @param {ReadonlyMat4} a the matrix to rotate
  4317. * @param {Number} rad the angle to rotate the matrix by
  4318. * @returns {mat4} out
  4319. */
  4320. function rotateY$1(out, a, rad) {
  4321. var s = Math.sin(rad);
  4322. var c = Math.cos(rad);
  4323. var a00 = a[0];
  4324. var a01 = a[1];
  4325. var a02 = a[2];
  4326. var a03 = a[3];
  4327. var a20 = a[8];
  4328. var a21 = a[9];
  4329. var a22 = a[10];
  4330. var a23 = a[11];
  4331. if (a !== out) {
  4332. // If the source and destination differ, copy the unchanged rows
  4333. out[4] = a[4];
  4334. out[5] = a[5];
  4335. out[6] = a[6];
  4336. out[7] = a[7];
  4337. out[12] = a[12];
  4338. out[13] = a[13];
  4339. out[14] = a[14];
  4340. out[15] = a[15];
  4341. } // Perform axis-specific matrix multiplication
  4342. out[0] = a00 * c - a20 * s;
  4343. out[1] = a01 * c - a21 * s;
  4344. out[2] = a02 * c - a22 * s;
  4345. out[3] = a03 * c - a23 * s;
  4346. out[8] = a00 * s + a20 * c;
  4347. out[9] = a01 * s + a21 * c;
  4348. out[10] = a02 * s + a22 * c;
  4349. out[11] = a03 * s + a23 * c;
  4350. return out;
  4351. }
  4352. /**
  4353. * Rotates a matrix by the given angle around the Z axis
  4354. *
  4355. * @param {mat4} out the receiving matrix
  4356. * @param {ReadonlyMat4} a the matrix to rotate
  4357. * @param {Number} rad the angle to rotate the matrix by
  4358. * @returns {mat4} out
  4359. */
  4360. function rotateZ$1(out, a, rad) {
  4361. var s = Math.sin(rad);
  4362. var c = Math.cos(rad);
  4363. var a00 = a[0];
  4364. var a01 = a[1];
  4365. var a02 = a[2];
  4366. var a03 = a[3];
  4367. var a10 = a[4];
  4368. var a11 = a[5];
  4369. var a12 = a[6];
  4370. var a13 = a[7];
  4371. if (a !== out) {
  4372. // If the source and destination differ, copy the unchanged last row
  4373. out[8] = a[8];
  4374. out[9] = a[9];
  4375. out[10] = a[10];
  4376. out[11] = a[11];
  4377. out[12] = a[12];
  4378. out[13] = a[13];
  4379. out[14] = a[14];
  4380. out[15] = a[15];
  4381. } // Perform axis-specific matrix multiplication
  4382. out[0] = a00 * c + a10 * s;
  4383. out[1] = a01 * c + a11 * s;
  4384. out[2] = a02 * c + a12 * s;
  4385. out[3] = a03 * c + a13 * s;
  4386. out[4] = a10 * c - a00 * s;
  4387. out[5] = a11 * c - a01 * s;
  4388. out[6] = a12 * c - a02 * s;
  4389. out[7] = a13 * c - a03 * s;
  4390. return out;
  4391. }
  4392. /**
  4393. * Returns the scaling factor component of a transformation
  4394. * matrix. If a matrix is built with fromRotationTranslationScale
  4395. * with a normalized Quaternion paramter, the returned vector will be
  4396. * the same as the scaling vector
  4397. * originally supplied.
  4398. * @param {vec3} out Vector to receive scaling factor component
  4399. * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
  4400. * @return {vec3} out
  4401. */
  4402. function getScaling(out, mat) {
  4403. var m11 = mat[0];
  4404. var m12 = mat[1];
  4405. var m13 = mat[2];
  4406. var m21 = mat[4];
  4407. var m22 = mat[5];
  4408. var m23 = mat[6];
  4409. var m31 = mat[8];
  4410. var m32 = mat[9];
  4411. var m33 = mat[10];
  4412. out[0] = Math.hypot(m11, m12, m13);
  4413. out[1] = Math.hypot(m21, m22, m23);
  4414. out[2] = Math.hypot(m31, m32, m33);
  4415. return out;
  4416. }
  4417. /**
  4418. * Calculates a 4x4 matrix from the given quaternion
  4419. *
  4420. * @param {mat4} out mat4 receiving operation result
  4421. * @param {ReadonlyQuat} q Quaternion to create matrix from
  4422. *
  4423. * @returns {mat4} out
  4424. */
  4425. function fromQuat(out, q) {
  4426. var x = q[0],
  4427. y = q[1],
  4428. z = q[2],
  4429. w = q[3];
  4430. var x2 = x + x;
  4431. var y2 = y + y;
  4432. var z2 = z + z;
  4433. var xx = x * x2;
  4434. var yx = y * x2;
  4435. var yy = y * y2;
  4436. var zx = z * x2;
  4437. var zy = z * y2;
  4438. var zz = z * z2;
  4439. var wx = w * x2;
  4440. var wy = w * y2;
  4441. var wz = w * z2;
  4442. out[0] = 1 - yy - zz;
  4443. out[1] = yx + wz;
  4444. out[2] = zx - wy;
  4445. out[3] = 0;
  4446. out[4] = yx - wz;
  4447. out[5] = 1 - xx - zz;
  4448. out[6] = zy + wx;
  4449. out[7] = 0;
  4450. out[8] = zx + wy;
  4451. out[9] = zy - wx;
  4452. out[10] = 1 - xx - yy;
  4453. out[11] = 0;
  4454. out[12] = 0;
  4455. out[13] = 0;
  4456. out[14] = 0;
  4457. out[15] = 1;
  4458. return out;
  4459. }
  4460. /**
  4461. * Generates a frustum matrix with the given bounds
  4462. *
  4463. * @param {mat4} out mat4 frustum matrix will be written into
  4464. * @param {Number} left Left bound of the frustum
  4465. * @param {Number} right Right bound of the frustum
  4466. * @param {Number} bottom Bottom bound of the frustum
  4467. * @param {Number} top Top bound of the frustum
  4468. * @param {Number} near Near bound of the frustum
  4469. * @param {Number} far Far bound of the frustum
  4470. * @returns {mat4} out
  4471. */
  4472. function frustum(out, left, right, bottom, top, near, far) {
  4473. var rl = 1 / (right - left);
  4474. var tb = 1 / (top - bottom);
  4475. var nf = 1 / (near - far);
  4476. out[0] = near * 2 * rl;
  4477. out[1] = 0;
  4478. out[2] = 0;
  4479. out[3] = 0;
  4480. out[4] = 0;
  4481. out[5] = near * 2 * tb;
  4482. out[6] = 0;
  4483. out[7] = 0;
  4484. out[8] = (right + left) * rl;
  4485. out[9] = (top + bottom) * tb;
  4486. out[10] = (far + near) * nf;
  4487. out[11] = -1;
  4488. out[12] = 0;
  4489. out[13] = 0;
  4490. out[14] = far * near * 2 * nf;
  4491. out[15] = 0;
  4492. return out;
  4493. }
  4494. /**
  4495. * Generates a perspective projection matrix with the given bounds.
  4496. * Passing null/undefined/no value for far will generate infinite projection matrix.
  4497. *
  4498. * @param {mat4} out mat4 frustum matrix will be written into
  4499. * @param {number} fovy Vertical field of view in radians
  4500. * @param {number} aspect Aspect ratio. typically viewport width/height
  4501. * @param {number} near Near bound of the frustum
  4502. * @param {number} far Far bound of the frustum, can be null or Infinity
  4503. * @returns {mat4} out
  4504. */
  4505. function perspective(out, fovy, aspect, near, far) {
  4506. var f = 1.0 / Math.tan(fovy / 2),
  4507. nf;
  4508. out[0] = f / aspect;
  4509. out[1] = 0;
  4510. out[2] = 0;
  4511. out[3] = 0;
  4512. out[4] = 0;
  4513. out[5] = f;
  4514. out[6] = 0;
  4515. out[7] = 0;
  4516. out[8] = 0;
  4517. out[9] = 0;
  4518. out[11] = -1;
  4519. out[12] = 0;
  4520. out[13] = 0;
  4521. out[15] = 0;
  4522. if (far != null && far !== Infinity) {
  4523. nf = 1 / (near - far);
  4524. out[10] = (far + near) * nf;
  4525. out[14] = 2 * far * near * nf;
  4526. } else {
  4527. out[10] = -1;
  4528. out[14] = -2 * near;
  4529. }
  4530. return out;
  4531. }
  4532. /**
  4533. * Generates a orthogonal projection matrix with the given bounds
  4534. *
  4535. * @param {mat4} out mat4 frustum matrix will be written into
  4536. * @param {number} left Left bound of the frustum
  4537. * @param {number} right Right bound of the frustum
  4538. * @param {number} bottom Bottom bound of the frustum
  4539. * @param {number} top Top bound of the frustum
  4540. * @param {number} near Near bound of the frustum
  4541. * @param {number} far Far bound of the frustum
  4542. * @returns {mat4} out
  4543. */
  4544. function ortho(out, left, right, bottom, top, near, far) {
  4545. var lr = 1 / (left - right);
  4546. var bt = 1 / (bottom - top);
  4547. var nf = 1 / (near - far);
  4548. out[0] = -2 * lr;
  4549. out[1] = 0;
  4550. out[2] = 0;
  4551. out[3] = 0;
  4552. out[4] = 0;
  4553. out[5] = -2 * bt;
  4554. out[6] = 0;
  4555. out[7] = 0;
  4556. out[8] = 0;
  4557. out[9] = 0;
  4558. out[10] = 2 * nf;
  4559. out[11] = 0;
  4560. out[12] = (left + right) * lr;
  4561. out[13] = (top + bottom) * bt;
  4562. out[14] = (far + near) * nf;
  4563. out[15] = 1;
  4564. return out;
  4565. }
  4566. /**
  4567. * Generates a look-at matrix with the given eye position, focal point, and up axis.
  4568. * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
  4569. *
  4570. * @param {mat4} out mat4 frustum matrix will be written into
  4571. * @param {ReadonlyVec3} eye Position of the viewer
  4572. * @param {ReadonlyVec3} center Point the viewer is looking at
  4573. * @param {ReadonlyVec3} up vec3 pointing up
  4574. * @returns {mat4} out
  4575. */
  4576. function lookAt(out, eye, center, up) {
  4577. var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
  4578. var eyex = eye[0];
  4579. var eyey = eye[1];
  4580. var eyez = eye[2];
  4581. var upx = up[0];
  4582. var upy = up[1];
  4583. var upz = up[2];
  4584. var centerx = center[0];
  4585. var centery = center[1];
  4586. var centerz = center[2];
  4587. if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) {
  4588. return identity$1(out);
  4589. }
  4590. z0 = eyex - centerx;
  4591. z1 = eyey - centery;
  4592. z2 = eyez - centerz;
  4593. len = 1 / Math.hypot(z0, z1, z2);
  4594. z0 *= len;
  4595. z1 *= len;
  4596. z2 *= len;
  4597. x0 = upy * z2 - upz * z1;
  4598. x1 = upz * z0 - upx * z2;
  4599. x2 = upx * z1 - upy * z0;
  4600. len = Math.hypot(x0, x1, x2);
  4601. if (!len) {
  4602. x0 = 0;
  4603. x1 = 0;
  4604. x2 = 0;
  4605. } else {
  4606. len = 1 / len;
  4607. x0 *= len;
  4608. x1 *= len;
  4609. x2 *= len;
  4610. }
  4611. y0 = z1 * x2 - z2 * x1;
  4612. y1 = z2 * x0 - z0 * x2;
  4613. y2 = z0 * x1 - z1 * x0;
  4614. len = Math.hypot(y0, y1, y2);
  4615. if (!len) {
  4616. y0 = 0;
  4617. y1 = 0;
  4618. y2 = 0;
  4619. } else {
  4620. len = 1 / len;
  4621. y0 *= len;
  4622. y1 *= len;
  4623. y2 *= len;
  4624. }
  4625. out[0] = x0;
  4626. out[1] = y0;
  4627. out[2] = z0;
  4628. out[3] = 0;
  4629. out[4] = x1;
  4630. out[5] = y1;
  4631. out[6] = z1;
  4632. out[7] = 0;
  4633. out[8] = x2;
  4634. out[9] = y2;
  4635. out[10] = z2;
  4636. out[11] = 0;
  4637. out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
  4638. out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
  4639. out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
  4640. out[15] = 1;
  4641. return out;
  4642. }
  4643. /**
  4644. * 4 Dimensional Vector
  4645. * @module vec4
  4646. */
  4647. /**
  4648. * Creates a new, empty vec4
  4649. *
  4650. * @returns {vec4} a new 4D vector
  4651. */
  4652. function create$1() {
  4653. var out = new ARRAY_TYPE(4);
  4654. if (ARRAY_TYPE != Float32Array) {
  4655. out[0] = 0;
  4656. out[1] = 0;
  4657. out[2] = 0;
  4658. out[3] = 0;
  4659. }
  4660. return out;
  4661. }
  4662. /**
  4663. * Adds two vec4's
  4664. *
  4665. * @param {vec4} out the receiving vector
  4666. * @param {ReadonlyVec4} a the first operand
  4667. * @param {ReadonlyVec4} b the second operand
  4668. * @returns {vec4} out
  4669. */
  4670. function add$1(out, a, b) {
  4671. out[0] = a[0] + b[0];
  4672. out[1] = a[1] + b[1];
  4673. out[2] = a[2] + b[2];
  4674. out[3] = a[3] + b[3];
  4675. return out;
  4676. }
  4677. /**
  4678. * Scales a vec4 by a scalar number
  4679. *
  4680. * @param {vec4} out the receiving vector
  4681. * @param {ReadonlyVec4} a the vector to scale
  4682. * @param {Number} b amount to scale the vector by
  4683. * @returns {vec4} out
  4684. */
  4685. function scale$1(out, a, b) {
  4686. out[0] = a[0] * b;
  4687. out[1] = a[1] * b;
  4688. out[2] = a[2] * b;
  4689. out[3] = a[3] * b;
  4690. return out;
  4691. }
  4692. /**
  4693. * Calculates the length of a vec4
  4694. *
  4695. * @param {ReadonlyVec4} a vector to calculate length of
  4696. * @returns {Number} length of a
  4697. */
  4698. function length$1(a) {
  4699. var x = a[0];
  4700. var y = a[1];
  4701. var z = a[2];
  4702. var w = a[3];
  4703. return Math.hypot(x, y, z, w);
  4704. }
  4705. /**
  4706. * Calculates the squared length of a vec4
  4707. *
  4708. * @param {ReadonlyVec4} a vector to calculate squared length of
  4709. * @returns {Number} squared length of a
  4710. */
  4711. function squaredLength$1(a) {
  4712. var x = a[0];
  4713. var y = a[1];
  4714. var z = a[2];
  4715. var w = a[3];
  4716. return x * x + y * y + z * z + w * w;
  4717. }
  4718. /**
  4719. * Normalize a vec4
  4720. *
  4721. * @param {vec4} out the receiving vector
  4722. * @param {ReadonlyVec4} a vector to normalize
  4723. * @returns {vec4} out
  4724. */
  4725. function normalize$1(out, a) {
  4726. var x = a[0];
  4727. var y = a[1];
  4728. var z = a[2];
  4729. var w = a[3];
  4730. var len = x * x + y * y + z * z + w * w;
  4731. if (len > 0) {
  4732. len = 1 / Math.sqrt(len);
  4733. }
  4734. out[0] = x * len;
  4735. out[1] = y * len;
  4736. out[2] = z * len;
  4737. out[3] = w * len;
  4738. return out;
  4739. }
  4740. /**
  4741. * Calculates the dot product of two vec4's
  4742. *
  4743. * @param {ReadonlyVec4} a the first operand
  4744. * @param {ReadonlyVec4} b the second operand
  4745. * @returns {Number} dot product of a and b
  4746. */
  4747. function dot$1(a, b) {
  4748. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
  4749. }
  4750. /**
  4751. * Performs a linear interpolation between two vec4's
  4752. *
  4753. * @param {vec4} out the receiving vector
  4754. * @param {ReadonlyVec4} a the first operand
  4755. * @param {ReadonlyVec4} b the second operand
  4756. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  4757. * @returns {vec4} out
  4758. */
  4759. function lerp$1(out, a, b, t) {
  4760. var ax = a[0];
  4761. var ay = a[1];
  4762. var az = a[2];
  4763. var aw = a[3];
  4764. out[0] = ax + t * (b[0] - ax);
  4765. out[1] = ay + t * (b[1] - ay);
  4766. out[2] = az + t * (b[2] - az);
  4767. out[3] = aw + t * (b[3] - aw);
  4768. return out;
  4769. }
  4770. /**
  4771. * Transforms the vec4 with a mat4.
  4772. *
  4773. * @param {vec4} out the receiving vector
  4774. * @param {ReadonlyVec4} a the vector to transform
  4775. * @param {ReadonlyMat4} m matrix to transform with
  4776. * @returns {vec4} out
  4777. */
  4778. function transformMat4(out, a, m) {
  4779. var x = a[0],
  4780. y = a[1],
  4781. z = a[2],
  4782. w = a[3];
  4783. out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
  4784. out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
  4785. out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
  4786. out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
  4787. return out;
  4788. }
  4789. /**
  4790. * Transforms the vec4 with a quat
  4791. *
  4792. * @param {vec4} out the receiving vector
  4793. * @param {ReadonlyVec4} a the vector to transform
  4794. * @param {ReadonlyQuat} q quaternion to transform with
  4795. * @returns {vec4} out
  4796. */
  4797. function transformQuat(out, a, q) {
  4798. var x = a[0],
  4799. y = a[1],
  4800. z = a[2];
  4801. var qx = q[0],
  4802. qy = q[1],
  4803. qz = q[2],
  4804. qw = q[3]; // calculate quat * vec
  4805. var ix = qw * x + qy * z - qz * y;
  4806. var iy = qw * y + qz * x - qx * z;
  4807. var iz = qw * z + qx * y - qy * x;
  4808. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  4809. out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  4810. out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  4811. out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  4812. out[3] = a[3];
  4813. return out;
  4814. }
  4815. /**
  4816. * Perform some operation over an array of vec4s.
  4817. *
  4818. * @param {Array} a the array of vectors to iterate over
  4819. * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
  4820. * @param {Number} offset Number of elements to skip at the beginning of the array
  4821. * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
  4822. * @param {Function} fn Function to call for each vector in the array
  4823. * @param {Object} [arg] additional argument to pass to fn
  4824. * @returns {Array} a
  4825. * @function
  4826. */
  4827. (function () {
  4828. var vec = create$1();
  4829. return function (a, stride, offset, count, fn, arg) {
  4830. var i, l;
  4831. if (!stride) {
  4832. stride = 4;
  4833. }
  4834. if (!offset) {
  4835. offset = 0;
  4836. }
  4837. if (count) {
  4838. l = Math.min(count * stride + offset, a.length);
  4839. } else {
  4840. l = a.length;
  4841. }
  4842. for (i = offset; i < l; i += stride) {
  4843. vec[0] = a[i];
  4844. vec[1] = a[i + 1];
  4845. vec[2] = a[i + 2];
  4846. vec[3] = a[i + 3];
  4847. fn(vec, vec, arg);
  4848. a[i] = vec[0];
  4849. a[i + 1] = vec[1];
  4850. a[i + 2] = vec[2];
  4851. a[i + 3] = vec[3];
  4852. }
  4853. return a;
  4854. };
  4855. })();
  4856. const IDENTITY = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
  4857. const ZERO = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  4858. const INDICES = Object.freeze({
  4859. COL0ROW0: 0,
  4860. COL0ROW1: 1,
  4861. COL0ROW2: 2,
  4862. COL0ROW3: 3,
  4863. COL1ROW0: 4,
  4864. COL1ROW1: 5,
  4865. COL1ROW2: 6,
  4866. COL1ROW3: 7,
  4867. COL2ROW0: 8,
  4868. COL2ROW1: 9,
  4869. COL2ROW2: 10,
  4870. COL2ROW3: 11,
  4871. COL3ROW0: 12,
  4872. COL3ROW1: 13,
  4873. COL3ROW2: 14,
  4874. COL3ROW3: 15
  4875. });
  4876. const constants = {};
  4877. class Matrix4 extends Matrix {
  4878. static get IDENTITY() {
  4879. constants.IDENTITY = constants.IDENTITY || Object.freeze(new Matrix4(IDENTITY));
  4880. return constants.IDENTITY;
  4881. }
  4882. static get ZERO() {
  4883. constants.ZERO = constants.ZERO || Object.freeze(new Matrix4(ZERO));
  4884. return constants.ZERO;
  4885. }
  4886. get INDICES() {
  4887. return INDICES;
  4888. }
  4889. get ELEMENTS() {
  4890. return 16;
  4891. }
  4892. get RANK() {
  4893. return 4;
  4894. }
  4895. constructor(array) {
  4896. super(-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0);
  4897. if (arguments.length === 1 && Array.isArray(array)) {
  4898. this.copy(array);
  4899. } else {
  4900. this.identity();
  4901. }
  4902. }
  4903. copy(array) {
  4904. this[0] = array[0];
  4905. this[1] = array[1];
  4906. this[2] = array[2];
  4907. this[3] = array[3];
  4908. this[4] = array[4];
  4909. this[5] = array[5];
  4910. this[6] = array[6];
  4911. this[7] = array[7];
  4912. this[8] = array[8];
  4913. this[9] = array[9];
  4914. this[10] = array[10];
  4915. this[11] = array[11];
  4916. this[12] = array[12];
  4917. this[13] = array[13];
  4918. this[14] = array[14];
  4919. this[15] = array[15];
  4920. return this.check();
  4921. }
  4922. set(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33) {
  4923. this[0] = m00;
  4924. this[1] = m10;
  4925. this[2] = m20;
  4926. this[3] = m30;
  4927. this[4] = m01;
  4928. this[5] = m11;
  4929. this[6] = m21;
  4930. this[7] = m31;
  4931. this[8] = m02;
  4932. this[9] = m12;
  4933. this[10] = m22;
  4934. this[11] = m32;
  4935. this[12] = m03;
  4936. this[13] = m13;
  4937. this[14] = m23;
  4938. this[15] = m33;
  4939. return this.check();
  4940. }
  4941. setRowMajor(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
  4942. this[0] = m00;
  4943. this[1] = m10;
  4944. this[2] = m20;
  4945. this[3] = m30;
  4946. this[4] = m01;
  4947. this[5] = m11;
  4948. this[6] = m21;
  4949. this[7] = m31;
  4950. this[8] = m02;
  4951. this[9] = m12;
  4952. this[10] = m22;
  4953. this[11] = m32;
  4954. this[12] = m03;
  4955. this[13] = m13;
  4956. this[14] = m23;
  4957. this[15] = m33;
  4958. return this.check();
  4959. }
  4960. toRowMajor(result) {
  4961. result[0] = this[0];
  4962. result[1] = this[4];
  4963. result[2] = this[8];
  4964. result[3] = this[12];
  4965. result[4] = this[1];
  4966. result[5] = this[5];
  4967. result[6] = this[9];
  4968. result[7] = this[13];
  4969. result[8] = this[2];
  4970. result[9] = this[6];
  4971. result[10] = this[10];
  4972. result[11] = this[14];
  4973. result[12] = this[3];
  4974. result[13] = this[7];
  4975. result[14] = this[11];
  4976. result[15] = this[15];
  4977. return result;
  4978. }
  4979. identity() {
  4980. return this.copy(IDENTITY);
  4981. }
  4982. fromQuaternion(q) {
  4983. fromQuat(this, q);
  4984. return this.check();
  4985. }
  4986. frustum({
  4987. left,
  4988. right,
  4989. bottom,
  4990. top,
  4991. near,
  4992. far
  4993. }) {
  4994. if (far === Infinity) {
  4995. Matrix4._computeInfinitePerspectiveOffCenter(this, left, right, bottom, top, near);
  4996. } else {
  4997. frustum(this, left, right, bottom, top, near, far);
  4998. }
  4999. return this.check();
  5000. }
  5001. static _computeInfinitePerspectiveOffCenter(result, left, right, bottom, top, near) {
  5002. const column0Row0 = 2.0 * near / (right - left);
  5003. const column1Row1 = 2.0 * near / (top - bottom);
  5004. const column2Row0 = (right + left) / (right - left);
  5005. const column2Row1 = (top + bottom) / (top - bottom);
  5006. const column2Row2 = -1.0;
  5007. const column2Row3 = -1.0;
  5008. const column3Row2 = -2.0 * near;
  5009. result[0] = column0Row0;
  5010. result[1] = 0.0;
  5011. result[2] = 0.0;
  5012. result[3] = 0.0;
  5013. result[4] = 0.0;
  5014. result[5] = column1Row1;
  5015. result[6] = 0.0;
  5016. result[7] = 0.0;
  5017. result[8] = column2Row0;
  5018. result[9] = column2Row1;
  5019. result[10] = column2Row2;
  5020. result[11] = column2Row3;
  5021. result[12] = 0.0;
  5022. result[13] = 0.0;
  5023. result[14] = column3Row2;
  5024. result[15] = 0.0;
  5025. return result;
  5026. }
  5027. lookAt(eye, center, up) {
  5028. if (arguments.length === 1) {
  5029. ({
  5030. eye,
  5031. center,
  5032. up
  5033. } = eye);
  5034. }
  5035. center = center || [0, 0, 0];
  5036. up = up || [0, 1, 0];
  5037. lookAt(this, eye, center, up);
  5038. return this.check();
  5039. }
  5040. ortho({
  5041. left,
  5042. right,
  5043. bottom,
  5044. top,
  5045. near = 0.1,
  5046. far = 500
  5047. }) {
  5048. ortho(this, left, right, bottom, top, near, far);
  5049. return this.check();
  5050. }
  5051. orthographic({
  5052. fovy = 45 * Math.PI / 180,
  5053. aspect = 1,
  5054. focalDistance = 1,
  5055. near = 0.1,
  5056. far = 500
  5057. }) {
  5058. if (fovy > Math.PI * 2) {
  5059. throw Error('radians');
  5060. }
  5061. const halfY = fovy / 2;
  5062. const top = focalDistance * Math.tan(halfY);
  5063. const right = top * aspect;
  5064. return new Matrix4().ortho({
  5065. left: -right,
  5066. right,
  5067. bottom: -top,
  5068. top,
  5069. near,
  5070. far
  5071. });
  5072. }
  5073. perspective({
  5074. fovy = undefined,
  5075. fov = 45 * Math.PI / 180,
  5076. aspect = 1,
  5077. near = 0.1,
  5078. far = 500
  5079. } = {}) {
  5080. fovy = fovy || fov;
  5081. if (fovy > Math.PI * 2) {
  5082. throw Error('radians');
  5083. }
  5084. perspective(this, fovy, aspect, near, far);
  5085. return this.check();
  5086. }
  5087. determinant() {
  5088. return determinant(this);
  5089. }
  5090. getScale(result = [-0, -0, -0]) {
  5091. result[0] = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);
  5092. result[1] = Math.sqrt(this[4] * this[4] + this[5] * this[5] + this[6] * this[6]);
  5093. result[2] = Math.sqrt(this[8] * this[8] + this[9] * this[9] + this[10] * this[10]);
  5094. return result;
  5095. }
  5096. getTranslation(result = [-0, -0, -0]) {
  5097. result[0] = this[12];
  5098. result[1] = this[13];
  5099. result[2] = this[14];
  5100. return result;
  5101. }
  5102. getRotation(result = [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0], scaleResult = null) {
  5103. const scale = this.getScale(scaleResult || [-0, -0, -0]);
  5104. const inverseScale0 = 1 / scale[0];
  5105. const inverseScale1 = 1 / scale[1];
  5106. const inverseScale2 = 1 / scale[2];
  5107. result[0] = this[0] * inverseScale0;
  5108. result[1] = this[1] * inverseScale1;
  5109. result[2] = this[2] * inverseScale2;
  5110. result[3] = 0;
  5111. result[4] = this[4] * inverseScale0;
  5112. result[5] = this[5] * inverseScale1;
  5113. result[6] = this[6] * inverseScale2;
  5114. result[7] = 0;
  5115. result[8] = this[8] * inverseScale0;
  5116. result[9] = this[9] * inverseScale1;
  5117. result[10] = this[10] * inverseScale2;
  5118. result[11] = 0;
  5119. result[12] = 0;
  5120. result[13] = 0;
  5121. result[14] = 0;
  5122. result[15] = 1;
  5123. return result;
  5124. }
  5125. getRotationMatrix3(result = [-0, -0, -0, -0, -0, -0, -0, -0, -0], scaleResult = null) {
  5126. const scale = this.getScale(scaleResult || [-0, -0, -0]);
  5127. const inverseScale0 = 1 / scale[0];
  5128. const inverseScale1 = 1 / scale[1];
  5129. const inverseScale2 = 1 / scale[2];
  5130. result[0] = this[0] * inverseScale0;
  5131. result[1] = this[1] * inverseScale1;
  5132. result[2] = this[2] * inverseScale2;
  5133. result[3] = this[4] * inverseScale0;
  5134. result[4] = this[5] * inverseScale1;
  5135. result[5] = this[6] * inverseScale2;
  5136. result[6] = this[8] * inverseScale0;
  5137. result[7] = this[9] * inverseScale1;
  5138. result[8] = this[10] * inverseScale2;
  5139. return result;
  5140. }
  5141. transpose() {
  5142. transpose(this, this);
  5143. return this.check();
  5144. }
  5145. invert() {
  5146. invert$1(this, this);
  5147. return this.check();
  5148. }
  5149. multiplyLeft(a) {
  5150. multiply$1(this, a, this);
  5151. return this.check();
  5152. }
  5153. multiplyRight(a) {
  5154. multiply$1(this, this, a);
  5155. return this.check();
  5156. }
  5157. rotateX(radians) {
  5158. rotateX$1(this, this, radians);
  5159. return this.check();
  5160. }
  5161. rotateY(radians) {
  5162. rotateY$1(this, this, radians);
  5163. return this.check();
  5164. }
  5165. rotateZ(radians) {
  5166. rotateZ$1(this, this, radians);
  5167. return this.check();
  5168. }
  5169. rotateXYZ([rx, ry, rz]) {
  5170. return this.rotateX(rx).rotateY(ry).rotateZ(rz);
  5171. }
  5172. rotateAxis(radians, axis) {
  5173. rotate(this, this, radians, axis);
  5174. return this.check();
  5175. }
  5176. scale(factor) {
  5177. if (Array.isArray(factor)) {
  5178. scale$2(this, this, factor);
  5179. } else {
  5180. scale$2(this, this, [factor, factor, factor]);
  5181. }
  5182. return this.check();
  5183. }
  5184. translate(vec) {
  5185. translate(this, this, vec);
  5186. return this.check();
  5187. }
  5188. transform(vector, result) {
  5189. if (vector.length === 4) {
  5190. result = transformMat4(result || [-0, -0, -0, -0], vector, this);
  5191. checkVector(result, 4);
  5192. return result;
  5193. }
  5194. return this.transformAsPoint(vector, result);
  5195. }
  5196. transformAsPoint(vector, result) {
  5197. const {
  5198. length
  5199. } = vector;
  5200. switch (length) {
  5201. case 2:
  5202. result = transformMat4$2(result || [-0, -0], vector, this);
  5203. break;
  5204. case 3:
  5205. result = transformMat4$1(result || [-0, -0, -0], vector, this);
  5206. break;
  5207. default:
  5208. throw new Error('Illegal vector');
  5209. }
  5210. checkVector(result, vector.length);
  5211. return result;
  5212. }
  5213. transformAsVector(vector, result) {
  5214. switch (vector.length) {
  5215. case 2:
  5216. result = vec2_transformMat4AsVector(result || [-0, -0], vector, this);
  5217. break;
  5218. case 3:
  5219. result = vec3_transformMat4AsVector(result || [-0, -0, -0], vector, this);
  5220. break;
  5221. default:
  5222. throw new Error('Illegal vector');
  5223. }
  5224. checkVector(result, vector.length);
  5225. return result;
  5226. }
  5227. makeRotationX(radians) {
  5228. return this.identity().rotateX(radians);
  5229. }
  5230. makeTranslation(x, y, z) {
  5231. return this.identity().translate([x, y, z]);
  5232. }
  5233. transformPoint(vector, result) {
  5234. deprecated('Matrix4.transformPoint', '3.0');
  5235. return this.transformAsPoint(vector, result);
  5236. }
  5237. transformVector(vector, result) {
  5238. deprecated('Matrix4.transformVector', '3.0');
  5239. return this.transformAsPoint(vector, result);
  5240. }
  5241. transformDirection(vector, result) {
  5242. deprecated('Matrix4.transformDirection', '3.0');
  5243. return this.transformAsVector(vector, result);
  5244. }
  5245. }
  5246. /**
  5247. * Quaternion
  5248. * @module quat
  5249. */
  5250. /**
  5251. * Creates a new identity quat
  5252. *
  5253. * @returns {quat} a new quaternion
  5254. */
  5255. function create() {
  5256. var out = new ARRAY_TYPE(4);
  5257. if (ARRAY_TYPE != Float32Array) {
  5258. out[0] = 0;
  5259. out[1] = 0;
  5260. out[2] = 0;
  5261. }
  5262. out[3] = 1;
  5263. return out;
  5264. }
  5265. /**
  5266. * Set a quat to the identity quaternion
  5267. *
  5268. * @param {quat} out the receiving quaternion
  5269. * @returns {quat} out
  5270. */
  5271. function identity(out) {
  5272. out[0] = 0;
  5273. out[1] = 0;
  5274. out[2] = 0;
  5275. out[3] = 1;
  5276. return out;
  5277. }
  5278. /**
  5279. * Sets a quat from the given angle and rotation axis,
  5280. * then returns it.
  5281. *
  5282. * @param {quat} out the receiving quaternion
  5283. * @param {ReadonlyVec3} axis the axis around which to rotate
  5284. * @param {Number} rad the angle in radians
  5285. * @returns {quat} out
  5286. **/
  5287. function setAxisAngle(out, axis, rad) {
  5288. rad = rad * 0.5;
  5289. var s = Math.sin(rad);
  5290. out[0] = s * axis[0];
  5291. out[1] = s * axis[1];
  5292. out[2] = s * axis[2];
  5293. out[3] = Math.cos(rad);
  5294. return out;
  5295. }
  5296. /**
  5297. * Multiplies two quat's
  5298. *
  5299. * @param {quat} out the receiving quaternion
  5300. * @param {ReadonlyQuat} a the first operand
  5301. * @param {ReadonlyQuat} b the second operand
  5302. * @returns {quat} out
  5303. */
  5304. function multiply(out, a, b) {
  5305. var ax = a[0],
  5306. ay = a[1],
  5307. az = a[2],
  5308. aw = a[3];
  5309. var bx = b[0],
  5310. by = b[1],
  5311. bz = b[2],
  5312. bw = b[3];
  5313. out[0] = ax * bw + aw * bx + ay * bz - az * by;
  5314. out[1] = ay * bw + aw * by + az * bx - ax * bz;
  5315. out[2] = az * bw + aw * bz + ax * by - ay * bx;
  5316. out[3] = aw * bw - ax * bx - ay * by - az * bz;
  5317. return out;
  5318. }
  5319. /**
  5320. * Rotates a quaternion by the given angle about the X axis
  5321. *
  5322. * @param {quat} out quat receiving operation result
  5323. * @param {ReadonlyQuat} a quat to rotate
  5324. * @param {number} rad angle (in radians) to rotate
  5325. * @returns {quat} out
  5326. */
  5327. function rotateX(out, a, rad) {
  5328. rad *= 0.5;
  5329. var ax = a[0],
  5330. ay = a[1],
  5331. az = a[2],
  5332. aw = a[3];
  5333. var bx = Math.sin(rad),
  5334. bw = Math.cos(rad);
  5335. out[0] = ax * bw + aw * bx;
  5336. out[1] = ay * bw + az * bx;
  5337. out[2] = az * bw - ay * bx;
  5338. out[3] = aw * bw - ax * bx;
  5339. return out;
  5340. }
  5341. /**
  5342. * Rotates a quaternion by the given angle about the Y axis
  5343. *
  5344. * @param {quat} out quat receiving operation result
  5345. * @param {ReadonlyQuat} a quat to rotate
  5346. * @param {number} rad angle (in radians) to rotate
  5347. * @returns {quat} out
  5348. */
  5349. function rotateY(out, a, rad) {
  5350. rad *= 0.5;
  5351. var ax = a[0],
  5352. ay = a[1],
  5353. az = a[2],
  5354. aw = a[3];
  5355. var by = Math.sin(rad),
  5356. bw = Math.cos(rad);
  5357. out[0] = ax * bw - az * by;
  5358. out[1] = ay * bw + aw * by;
  5359. out[2] = az * bw + ax * by;
  5360. out[3] = aw * bw - ay * by;
  5361. return out;
  5362. }
  5363. /**
  5364. * Rotates a quaternion by the given angle about the Z axis
  5365. *
  5366. * @param {quat} out quat receiving operation result
  5367. * @param {ReadonlyQuat} a quat to rotate
  5368. * @param {number} rad angle (in radians) to rotate
  5369. * @returns {quat} out
  5370. */
  5371. function rotateZ(out, a, rad) {
  5372. rad *= 0.5;
  5373. var ax = a[0],
  5374. ay = a[1],
  5375. az = a[2],
  5376. aw = a[3];
  5377. var bz = Math.sin(rad),
  5378. bw = Math.cos(rad);
  5379. out[0] = ax * bw + ay * bz;
  5380. out[1] = ay * bw - ax * bz;
  5381. out[2] = az * bw + aw * bz;
  5382. out[3] = aw * bw - az * bz;
  5383. return out;
  5384. }
  5385. /**
  5386. * Calculates the W component of a quat from the X, Y, and Z components.
  5387. * Assumes that quaternion is 1 unit in length.
  5388. * Any existing W component will be ignored.
  5389. *
  5390. * @param {quat} out the receiving quaternion
  5391. * @param {ReadonlyQuat} a quat to calculate W component of
  5392. * @returns {quat} out
  5393. */
  5394. function calculateW(out, a) {
  5395. var x = a[0],
  5396. y = a[1],
  5397. z = a[2];
  5398. out[0] = x;
  5399. out[1] = y;
  5400. out[2] = z;
  5401. out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
  5402. return out;
  5403. }
  5404. /**
  5405. * Performs a spherical linear interpolation between two quat
  5406. *
  5407. * @param {quat} out the receiving quaternion
  5408. * @param {ReadonlyQuat} a the first operand
  5409. * @param {ReadonlyQuat} b the second operand
  5410. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5411. * @returns {quat} out
  5412. */
  5413. function slerp(out, a, b, t) {
  5414. // benchmarks:
  5415. // http://jsperf.com/quaternion-slerp-implementations
  5416. var ax = a[0],
  5417. ay = a[1],
  5418. az = a[2],
  5419. aw = a[3];
  5420. var bx = b[0],
  5421. by = b[1],
  5422. bz = b[2],
  5423. bw = b[3];
  5424. var omega, cosom, sinom, scale0, scale1; // calc cosine
  5425. cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)
  5426. if (cosom < 0.0) {
  5427. cosom = -cosom;
  5428. bx = -bx;
  5429. by = -by;
  5430. bz = -bz;
  5431. bw = -bw;
  5432. } // calculate coefficients
  5433. if (1.0 - cosom > EPSILON) {
  5434. // standard case (slerp)
  5435. omega = Math.acos(cosom);
  5436. sinom = Math.sin(omega);
  5437. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  5438. scale1 = Math.sin(t * omega) / sinom;
  5439. } else {
  5440. // "from" and "to" quaternions are very close
  5441. // ... so we can do a linear interpolation
  5442. scale0 = 1.0 - t;
  5443. scale1 = t;
  5444. } // calculate final values
  5445. out[0] = scale0 * ax + scale1 * bx;
  5446. out[1] = scale0 * ay + scale1 * by;
  5447. out[2] = scale0 * az + scale1 * bz;
  5448. out[3] = scale0 * aw + scale1 * bw;
  5449. return out;
  5450. }
  5451. /**
  5452. * Calculates the inverse of a quat
  5453. *
  5454. * @param {quat} out the receiving quaternion
  5455. * @param {ReadonlyQuat} a quat to calculate inverse of
  5456. * @returns {quat} out
  5457. */
  5458. function invert(out, a) {
  5459. var a0 = a[0],
  5460. a1 = a[1],
  5461. a2 = a[2],
  5462. a3 = a[3];
  5463. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  5464. var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
  5465. out[0] = -a0 * invDot;
  5466. out[1] = -a1 * invDot;
  5467. out[2] = -a2 * invDot;
  5468. out[3] = a3 * invDot;
  5469. return out;
  5470. }
  5471. /**
  5472. * Calculates the conjugate of a quat
  5473. * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
  5474. *
  5475. * @param {quat} out the receiving quaternion
  5476. * @param {ReadonlyQuat} a quat to calculate conjugate of
  5477. * @returns {quat} out
  5478. */
  5479. function conjugate(out, a) {
  5480. out[0] = -a[0];
  5481. out[1] = -a[1];
  5482. out[2] = -a[2];
  5483. out[3] = a[3];
  5484. return out;
  5485. }
  5486. /**
  5487. * Creates a quaternion from the given 3x3 rotation matrix.
  5488. *
  5489. * NOTE: The resultant quaternion is not normalized, so you should be sure
  5490. * to renormalize the quaternion yourself where necessary.
  5491. *
  5492. * @param {quat} out the receiving quaternion
  5493. * @param {ReadonlyMat3} m rotation matrix
  5494. * @returns {quat} out
  5495. * @function
  5496. */
  5497. function fromMat3(out, m) {
  5498. // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  5499. // article "Quaternion Calculus and Fast Animation".
  5500. var fTrace = m[0] + m[4] + m[8];
  5501. var fRoot;
  5502. if (fTrace > 0.0) {
  5503. // |w| > 1/2, may as well choose w > 1/2
  5504. fRoot = Math.sqrt(fTrace + 1.0); // 2w
  5505. out[3] = 0.5 * fRoot;
  5506. fRoot = 0.5 / fRoot; // 1/(4w)
  5507. out[0] = (m[5] - m[7]) * fRoot;
  5508. out[1] = (m[6] - m[2]) * fRoot;
  5509. out[2] = (m[1] - m[3]) * fRoot;
  5510. } else {
  5511. // |w| <= 1/2
  5512. var i = 0;
  5513. if (m[4] > m[0]) i = 1;
  5514. if (m[8] > m[i * 3 + i]) i = 2;
  5515. var j = (i + 1) % 3;
  5516. var k = (i + 2) % 3;
  5517. fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);
  5518. out[i] = 0.5 * fRoot;
  5519. fRoot = 0.5 / fRoot;
  5520. out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
  5521. out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
  5522. out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
  5523. }
  5524. return out;
  5525. }
  5526. /**
  5527. * Adds two quat's
  5528. *
  5529. * @param {quat} out the receiving quaternion
  5530. * @param {ReadonlyQuat} a the first operand
  5531. * @param {ReadonlyQuat} b the second operand
  5532. * @returns {quat} out
  5533. * @function
  5534. */
  5535. var add = add$1;
  5536. /**
  5537. * Scales a quat by a scalar number
  5538. *
  5539. * @param {quat} out the receiving vector
  5540. * @param {ReadonlyQuat} a the vector to scale
  5541. * @param {Number} b amount to scale the vector by
  5542. * @returns {quat} out
  5543. * @function
  5544. */
  5545. var scale = scale$1;
  5546. /**
  5547. * Calculates the dot product of two quat's
  5548. *
  5549. * @param {ReadonlyQuat} a the first operand
  5550. * @param {ReadonlyQuat} b the second operand
  5551. * @returns {Number} dot product of a and b
  5552. * @function
  5553. */
  5554. var dot = dot$1;
  5555. /**
  5556. * Performs a linear interpolation between two quat's
  5557. *
  5558. * @param {quat} out the receiving quaternion
  5559. * @param {ReadonlyQuat} a the first operand
  5560. * @param {ReadonlyQuat} b the second operand
  5561. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5562. * @returns {quat} out
  5563. * @function
  5564. */
  5565. var lerp = lerp$1;
  5566. /**
  5567. * Calculates the length of a quat
  5568. *
  5569. * @param {ReadonlyQuat} a vector to calculate length of
  5570. * @returns {Number} length of a
  5571. */
  5572. var length = length$1;
  5573. /**
  5574. * Calculates the squared length of a quat
  5575. *
  5576. * @param {ReadonlyQuat} a vector to calculate squared length of
  5577. * @returns {Number} squared length of a
  5578. * @function
  5579. */
  5580. var squaredLength = squaredLength$1;
  5581. /**
  5582. * Normalize a quat
  5583. *
  5584. * @param {quat} out the receiving quaternion
  5585. * @param {ReadonlyQuat} a quaternion to normalize
  5586. * @returns {quat} out
  5587. * @function
  5588. */
  5589. var normalize = normalize$1;
  5590. /**
  5591. * Sets a quaternion to represent the shortest rotation from one
  5592. * vector to another.
  5593. *
  5594. * Both vectors are assumed to be unit length.
  5595. *
  5596. * @param {quat} out the receiving quaternion.
  5597. * @param {ReadonlyVec3} a the initial vector
  5598. * @param {ReadonlyVec3} b the destination vector
  5599. * @returns {quat} out
  5600. */
  5601. var rotationTo = function () {
  5602. var tmpvec3 = create$3();
  5603. var xUnitVec3 = fromValues(1, 0, 0);
  5604. var yUnitVec3 = fromValues(0, 1, 0);
  5605. return function (out, a, b) {
  5606. var dot = dot$2(a, b);
  5607. if (dot < -0.999999) {
  5608. cross(tmpvec3, xUnitVec3, a);
  5609. if (len(tmpvec3) < 0.000001) cross(tmpvec3, yUnitVec3, a);
  5610. normalize$2(tmpvec3, tmpvec3);
  5611. setAxisAngle(out, tmpvec3, Math.PI);
  5612. return out;
  5613. } else if (dot > 0.999999) {
  5614. out[0] = 0;
  5615. out[1] = 0;
  5616. out[2] = 0;
  5617. out[3] = 1;
  5618. return out;
  5619. } else {
  5620. cross(tmpvec3, a, b);
  5621. out[0] = tmpvec3[0];
  5622. out[1] = tmpvec3[1];
  5623. out[2] = tmpvec3[2];
  5624. out[3] = 1 + dot;
  5625. return normalize(out, out);
  5626. }
  5627. };
  5628. }();
  5629. /**
  5630. * Performs a spherical linear interpolation with two control points
  5631. *
  5632. * @param {quat} out the receiving quaternion
  5633. * @param {ReadonlyQuat} a the first operand
  5634. * @param {ReadonlyQuat} b the second operand
  5635. * @param {ReadonlyQuat} c the third operand
  5636. * @param {ReadonlyQuat} d the fourth operand
  5637. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  5638. * @returns {quat} out
  5639. */
  5640. (function () {
  5641. var temp1 = create();
  5642. var temp2 = create();
  5643. return function (out, a, b, c, d, t) {
  5644. slerp(temp1, a, d, t);
  5645. slerp(temp2, b, c, t);
  5646. slerp(out, temp1, temp2, 2 * t * (1 - t));
  5647. return out;
  5648. };
  5649. })();
  5650. /**
  5651. * Sets the specified quaternion with values corresponding to the given
  5652. * axes. Each axis is a vec3 and is expected to be unit length and
  5653. * perpendicular to all other specified axes.
  5654. *
  5655. * @param {ReadonlyVec3} view the vector representing the viewing direction
  5656. * @param {ReadonlyVec3} right the vector representing the local "right" direction
  5657. * @param {ReadonlyVec3} up the vector representing the local "up" direction
  5658. * @returns {quat} out
  5659. */
  5660. (function () {
  5661. var matr = create$2();
  5662. return function (out, view, right, up) {
  5663. matr[0] = right[0];
  5664. matr[3] = right[1];
  5665. matr[6] = right[2];
  5666. matr[1] = up[0];
  5667. matr[4] = up[1];
  5668. matr[7] = up[2];
  5669. matr[2] = -view[0];
  5670. matr[5] = -view[1];
  5671. matr[8] = -view[2];
  5672. return normalize(out, fromMat3(out, matr));
  5673. };
  5674. })();
  5675. const IDENTITY_QUATERNION = [0, 0, 0, 1];
  5676. class Quaternion extends MathArray {
  5677. constructor(x = 0, y = 0, z = 0, w = 1) {
  5678. super(-0, -0, -0, -0);
  5679. if (Array.isArray(x) && arguments.length === 1) {
  5680. this.copy(x);
  5681. } else {
  5682. this.set(x, y, z, w);
  5683. }
  5684. }
  5685. copy(array) {
  5686. this[0] = array[0];
  5687. this[1] = array[1];
  5688. this[2] = array[2];
  5689. this[3] = array[3];
  5690. return this.check();
  5691. }
  5692. set(x, y, z, w) {
  5693. this[0] = x;
  5694. this[1] = y;
  5695. this[2] = z;
  5696. this[3] = w;
  5697. return this.check();
  5698. }
  5699. fromMatrix3(m) {
  5700. fromMat3(this, m);
  5701. return this.check();
  5702. }
  5703. identity() {
  5704. identity(this);
  5705. return this.check();
  5706. }
  5707. fromAxisRotation(axis, rad) {
  5708. setAxisAngle(this, axis, rad);
  5709. return this.check();
  5710. }
  5711. setAxisAngle(axis, rad) {
  5712. return this.fromAxisRotation(axis, rad);
  5713. }
  5714. get ELEMENTS() {
  5715. return 4;
  5716. }
  5717. get x() {
  5718. return this[0];
  5719. }
  5720. set x(value) {
  5721. this[0] = checkNumber(value);
  5722. }
  5723. get y() {
  5724. return this[1];
  5725. }
  5726. set y(value) {
  5727. this[1] = checkNumber(value);
  5728. }
  5729. get z() {
  5730. return this[2];
  5731. }
  5732. set z(value) {
  5733. this[2] = checkNumber(value);
  5734. }
  5735. get w() {
  5736. return this[3];
  5737. }
  5738. set w(value) {
  5739. this[3] = checkNumber(value);
  5740. }
  5741. len() {
  5742. return length(this);
  5743. }
  5744. lengthSquared() {
  5745. return squaredLength(this);
  5746. }
  5747. dot(a, b) {
  5748. if (b !== undefined) {
  5749. throw new Error('Quaternion.dot only takes one argument');
  5750. }
  5751. return dot(this, a);
  5752. }
  5753. rotationTo(vectorA, vectorB) {
  5754. rotationTo(this, vectorA, vectorB);
  5755. return this.check();
  5756. }
  5757. add(a, b) {
  5758. if (b !== undefined) {
  5759. throw new Error('Quaternion.add only takes one argument');
  5760. }
  5761. add(this, this, a);
  5762. return this.check();
  5763. }
  5764. calculateW() {
  5765. calculateW(this, this);
  5766. return this.check();
  5767. }
  5768. conjugate() {
  5769. conjugate(this, this);
  5770. return this.check();
  5771. }
  5772. invert() {
  5773. invert(this, this);
  5774. return this.check();
  5775. }
  5776. lerp(a, b, t) {
  5777. lerp(this, a, b, t);
  5778. return this.check();
  5779. }
  5780. multiplyRight(a, b) {
  5781. assert$4(!b);
  5782. multiply(this, this, a);
  5783. return this.check();
  5784. }
  5785. multiplyLeft(a, b) {
  5786. assert$4(!b);
  5787. multiply(this, a, this);
  5788. return this.check();
  5789. }
  5790. normalize() {
  5791. const length = this.len();
  5792. const l = length > 0 ? 1 / length : 0;
  5793. this[0] = this[0] * l;
  5794. this[1] = this[1] * l;
  5795. this[2] = this[2] * l;
  5796. this[3] = this[3] * l;
  5797. if (length === 0) {
  5798. this[3] = 1;
  5799. }
  5800. return this.check();
  5801. }
  5802. rotateX(rad) {
  5803. rotateX(this, this, rad);
  5804. return this.check();
  5805. }
  5806. rotateY(rad) {
  5807. rotateY(this, this, rad);
  5808. return this.check();
  5809. }
  5810. rotateZ(rad) {
  5811. rotateZ(this, this, rad);
  5812. return this.check();
  5813. }
  5814. scale(b) {
  5815. scale(this, this, b);
  5816. return this.check();
  5817. }
  5818. slerp(start, target, ratio) {
  5819. switch (arguments.length) {
  5820. case 1:
  5821. ({
  5822. start = IDENTITY_QUATERNION,
  5823. target,
  5824. ratio
  5825. } = arguments[0]);
  5826. break;
  5827. case 2:
  5828. [target, ratio] = arguments;
  5829. start = this;
  5830. break;
  5831. }
  5832. slerp(this, start, target, ratio);
  5833. return this.check();
  5834. }
  5835. transformVector4(vector, result = vector) {
  5836. transformQuat(result, vector, this);
  5837. return checkVector(result, 4);
  5838. }
  5839. lengthSq() {
  5840. return this.lengthSquared();
  5841. }
  5842. setFromAxisAngle(axis, rad) {
  5843. return this.setAxisAngle(axis, rad);
  5844. }
  5845. premultiply(a, b) {
  5846. return this.multiplyLeft(a, b);
  5847. }
  5848. multiply(a, b) {
  5849. return this.multiplyRight(a, b);
  5850. }
  5851. }
  5852. var _MathUtils = {
  5853. EPSILON1: 1e-1,
  5854. EPSILON2: 1e-2,
  5855. EPSILON3: 1e-3,
  5856. EPSILON4: 1e-4,
  5857. EPSILON5: 1e-5,
  5858. EPSILON6: 1e-6,
  5859. EPSILON7: 1e-7,
  5860. EPSILON8: 1e-8,
  5861. EPSILON9: 1e-9,
  5862. EPSILON10: 1e-10,
  5863. EPSILON11: 1e-11,
  5864. EPSILON12: 1e-12,
  5865. EPSILON13: 1e-13,
  5866. EPSILON14: 1e-14,
  5867. EPSILON15: 1e-15,
  5868. EPSILON16: 1e-16,
  5869. EPSILON17: 1e-17,
  5870. EPSILON18: 1e-18,
  5871. EPSILON19: 1e-19,
  5872. EPSILON20: 1e-20,
  5873. PI_OVER_TWO: Math.PI / 2,
  5874. PI_OVER_FOUR: Math.PI / 4,
  5875. PI_OVER_SIX: Math.PI / 6,
  5876. TWO_PI: Math.PI * 2
  5877. };
  5878. const WGS84_RADIUS_X$1 = 6378137.0;
  5879. const WGS84_RADIUS_Y$1 = 6378137.0;
  5880. const WGS84_RADIUS_Z$1 = 6356752.3142451793;
  5881. const noop = x => x;
  5882. const scratchVector$6 = new Vector3();
  5883. function fromCartographic(cartographic, result, map = noop) {
  5884. if (isArray(cartographic)) {
  5885. result[0] = map(cartographic[0]);
  5886. result[1] = map(cartographic[1]);
  5887. result[2] = cartographic[2];
  5888. } else if ('longitude' in cartographic) {
  5889. result[0] = map(cartographic.longitude);
  5890. result[1] = map(cartographic.latitude);
  5891. result[2] = cartographic.height;
  5892. } else {
  5893. result[0] = map(cartographic.x);
  5894. result[1] = map(cartographic.y);
  5895. result[2] = cartographic.z;
  5896. }
  5897. return result;
  5898. }
  5899. function fromCartographicToRadians(cartographic, vector = scratchVector$6) {
  5900. return fromCartographic(cartographic, vector, config._cartographicRadians ? noop : toRadians);
  5901. }
  5902. function toCartographic(vector, cartographic, map = noop) {
  5903. if (isArray(cartographic)) {
  5904. cartographic[0] = map(vector[0]);
  5905. cartographic[1] = map(vector[1]);
  5906. cartographic[2] = vector[2];
  5907. } else if ('longitude' in cartographic) {
  5908. cartographic.longitude = map(vector[0]);
  5909. cartographic.latitude = map(vector[1]);
  5910. cartographic.height = vector[2];
  5911. } else {
  5912. cartographic.x = map(vector[0]);
  5913. cartographic.y = map(vector[1]);
  5914. cartographic.z = vector[2];
  5915. }
  5916. return cartographic;
  5917. }
  5918. function toCartographicFromRadians(vector, cartographic) {
  5919. return toCartographic(vector, cartographic, config._cartographicRadians ? noop : toDegrees);
  5920. }
  5921. const scratchVector$5 = new Vector3();
  5922. const scaleToGeodeticSurfaceIntersection = new Vector3();
  5923. const scaleToGeodeticSurfaceGradient = new Vector3();
  5924. function scaleToGeodeticSurface(cartesian, ellipsoid, result = new Vector3()) {
  5925. const {
  5926. oneOverRadii,
  5927. oneOverRadiiSquared,
  5928. centerToleranceSquared
  5929. } = ellipsoid;
  5930. scratchVector$5.from(cartesian);
  5931. const positionX = cartesian.x;
  5932. const positionY = cartesian.y;
  5933. const positionZ = cartesian.z;
  5934. const oneOverRadiiX = oneOverRadii.x;
  5935. const oneOverRadiiY = oneOverRadii.y;
  5936. const oneOverRadiiZ = oneOverRadii.z;
  5937. const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
  5938. const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
  5939. const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
  5940. const squaredNorm = x2 + y2 + z2;
  5941. const ratio = Math.sqrt(1.0 / squaredNorm);
  5942. if (!Number.isFinite(ratio)) {
  5943. return undefined;
  5944. }
  5945. const intersection = scaleToGeodeticSurfaceIntersection;
  5946. intersection.copy(cartesian).scale(ratio);
  5947. if (squaredNorm < centerToleranceSquared) {
  5948. return intersection.to(result);
  5949. }
  5950. const oneOverRadiiSquaredX = oneOverRadiiSquared.x;
  5951. const oneOverRadiiSquaredY = oneOverRadiiSquared.y;
  5952. const oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
  5953. const gradient = scaleToGeodeticSurfaceGradient;
  5954. gradient.set(intersection.x * oneOverRadiiSquaredX * 2.0, intersection.y * oneOverRadiiSquaredY * 2.0, intersection.z * oneOverRadiiSquaredZ * 2.0);
  5955. let lambda = (1.0 - ratio) * cartesian.len() / (0.5 * gradient.len());
  5956. let correction = 0.0;
  5957. let xMultiplier;
  5958. let yMultiplier;
  5959. let zMultiplier;
  5960. let func;
  5961. do {
  5962. lambda -= correction;
  5963. xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
  5964. yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
  5965. zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
  5966. const xMultiplier2 = xMultiplier * xMultiplier;
  5967. const yMultiplier2 = yMultiplier * yMultiplier;
  5968. const zMultiplier2 = zMultiplier * zMultiplier;
  5969. const xMultiplier3 = xMultiplier2 * xMultiplier;
  5970. const yMultiplier3 = yMultiplier2 * yMultiplier;
  5971. const zMultiplier3 = zMultiplier2 * zMultiplier;
  5972. func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
  5973. const denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
  5974. const derivative = -2.0 * denominator;
  5975. correction = func / derivative;
  5976. } while (Math.abs(func) > _MathUtils.EPSILON12);
  5977. return scratchVector$5.scale([xMultiplier, yMultiplier, zMultiplier]).to(result);
  5978. }
  5979. const EPSILON14 = 1e-14;
  5980. const scratchOrigin = new Vector3();
  5981. const VECTOR_PRODUCT_LOCAL_FRAME = {
  5982. up: {
  5983. south: 'east',
  5984. north: 'west',
  5985. west: 'south',
  5986. east: 'north'
  5987. },
  5988. down: {
  5989. south: 'west',
  5990. north: 'east',
  5991. west: 'north',
  5992. east: 'south'
  5993. },
  5994. south: {
  5995. up: 'west',
  5996. down: 'east',
  5997. west: 'down',
  5998. east: 'up'
  5999. },
  6000. north: {
  6001. up: 'east',
  6002. down: 'west',
  6003. west: 'up',
  6004. east: 'down'
  6005. },
  6006. west: {
  6007. up: 'north',
  6008. down: 'south',
  6009. north: 'down',
  6010. south: 'up'
  6011. },
  6012. east: {
  6013. up: 'south',
  6014. down: 'north',
  6015. north: 'up',
  6016. south: 'down'
  6017. }
  6018. };
  6019. const degeneratePositionLocalFrame = {
  6020. north: [-1, 0, 0],
  6021. east: [0, 1, 0],
  6022. up: [0, 0, 1],
  6023. south: [1, 0, 0],
  6024. west: [0, -1, 0],
  6025. down: [0, 0, -1]
  6026. };
  6027. const scratchAxisVectors = {
  6028. east: new Vector3(),
  6029. north: new Vector3(),
  6030. up: new Vector3(),
  6031. west: new Vector3(),
  6032. south: new Vector3(),
  6033. down: new Vector3()
  6034. };
  6035. const scratchVector1 = new Vector3();
  6036. const scratchVector2$1 = new Vector3();
  6037. const scratchVector3$1 = new Vector3();
  6038. function localFrameToFixedFrame(ellipsoid, firstAxis, secondAxis, thirdAxis, cartesianOrigin, result) {
  6039. const thirdAxisInferred = VECTOR_PRODUCT_LOCAL_FRAME[firstAxis] && VECTOR_PRODUCT_LOCAL_FRAME[firstAxis][secondAxis];
  6040. assert$4(thirdAxisInferred && (!thirdAxis || thirdAxis === thirdAxisInferred));
  6041. let firstAxisVector;
  6042. let secondAxisVector;
  6043. let thirdAxisVector;
  6044. const origin = scratchOrigin.copy(cartesianOrigin);
  6045. const atPole = equals(origin.x, 0.0, EPSILON14) && equals(origin.y, 0.0, EPSILON14);
  6046. if (atPole) {
  6047. const sign = Math.sign(origin.z);
  6048. firstAxisVector = scratchVector1.fromArray(degeneratePositionLocalFrame[firstAxis]);
  6049. if (firstAxis !== 'east' && firstAxis !== 'west') {
  6050. firstAxisVector.scale(sign);
  6051. }
  6052. secondAxisVector = scratchVector2$1.fromArray(degeneratePositionLocalFrame[secondAxis]);
  6053. if (secondAxis !== 'east' && secondAxis !== 'west') {
  6054. secondAxisVector.scale(sign);
  6055. }
  6056. thirdAxisVector = scratchVector3$1.fromArray(degeneratePositionLocalFrame[thirdAxis]);
  6057. if (thirdAxis !== 'east' && thirdAxis !== 'west') {
  6058. thirdAxisVector.scale(sign);
  6059. }
  6060. } else {
  6061. const {
  6062. up,
  6063. east,
  6064. north
  6065. } = scratchAxisVectors;
  6066. east.set(-origin.y, origin.x, 0.0).normalize();
  6067. ellipsoid.geodeticSurfaceNormal(origin, up);
  6068. north.copy(up).cross(east);
  6069. const {
  6070. down,
  6071. west,
  6072. south
  6073. } = scratchAxisVectors;
  6074. down.copy(up).scale(-1);
  6075. west.copy(east).scale(-1);
  6076. south.copy(north).scale(-1);
  6077. firstAxisVector = scratchAxisVectors[firstAxis];
  6078. secondAxisVector = scratchAxisVectors[secondAxis];
  6079. thirdAxisVector = scratchAxisVectors[thirdAxis];
  6080. }
  6081. result[0] = firstAxisVector.x;
  6082. result[1] = firstAxisVector.y;
  6083. result[2] = firstAxisVector.z;
  6084. result[3] = 0.0;
  6085. result[4] = secondAxisVector.x;
  6086. result[5] = secondAxisVector.y;
  6087. result[6] = secondAxisVector.z;
  6088. result[7] = 0.0;
  6089. result[8] = thirdAxisVector.x;
  6090. result[9] = thirdAxisVector.y;
  6091. result[10] = thirdAxisVector.z;
  6092. result[11] = 0.0;
  6093. result[12] = origin.x;
  6094. result[13] = origin.y;
  6095. result[14] = origin.z;
  6096. result[15] = 1.0;
  6097. return result;
  6098. }
  6099. const scratchVector$4 = new Vector3();
  6100. const scratchNormal$2 = new Vector3();
  6101. const scratchK = new Vector3();
  6102. const scratchPosition$2 = new Vector3();
  6103. const scratchHeight = new Vector3();
  6104. const scratchCartesian = new Vector3();
  6105. let wgs84;
  6106. class Ellipsoid {
  6107. static get WGS84() {
  6108. wgs84 = wgs84 || new Ellipsoid(WGS84_RADIUS_X$1, WGS84_RADIUS_Y$1, WGS84_RADIUS_Z$1);
  6109. return wgs84;
  6110. }
  6111. constructor(x = 0.0, y = 0.0, z = 0.0) {
  6112. assert$4(x >= 0.0);
  6113. assert$4(y >= 0.0);
  6114. assert$4(z >= 0.0);
  6115. this.radii = new Vector3(x, y, z);
  6116. this.radiiSquared = new Vector3(x * x, y * y, z * z);
  6117. this.radiiToTheFourth = new Vector3(x * x * x * x, y * y * y * y, z * z * z * z);
  6118. 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);
  6119. 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));
  6120. this.minimumRadius = Math.min(x, y, z);
  6121. this.maximumRadius = Math.max(x, y, z);
  6122. this.centerToleranceSquared = _MathUtils.EPSILON1;
  6123. if (this.radiiSquared.z !== 0) {
  6124. this.squaredXOverSquaredZ = this.radiiSquared.x / this.radiiSquared.z;
  6125. }
  6126. Object.freeze(this);
  6127. }
  6128. equals(right) {
  6129. return this === right || Boolean(right && this.radii.equals(right.radii));
  6130. }
  6131. toString() {
  6132. return this.radii.toString();
  6133. }
  6134. cartographicToCartesian(cartographic, result = [0, 0, 0]) {
  6135. const normal = scratchNormal$2;
  6136. const k = scratchK;
  6137. const [,, height] = cartographic;
  6138. this.geodeticSurfaceNormalCartographic(cartographic, normal);
  6139. k.copy(this.radiiSquared).scale(normal);
  6140. const gamma = Math.sqrt(normal.dot(k));
  6141. k.scale(1 / gamma);
  6142. normal.scale(height);
  6143. k.add(normal);
  6144. return k.to(result);
  6145. }
  6146. cartesianToCartographic(cartesian, result = [0, 0, 0]) {
  6147. scratchCartesian.from(cartesian);
  6148. const point = this.scaleToGeodeticSurface(scratchCartesian, scratchPosition$2);
  6149. if (!point) {
  6150. return undefined;
  6151. }
  6152. const normal = this.geodeticSurfaceNormal(point, scratchNormal$2);
  6153. const h = scratchHeight;
  6154. h.copy(scratchCartesian).subtract(point);
  6155. const longitude = Math.atan2(normal.y, normal.x);
  6156. const latitude = Math.asin(normal.z);
  6157. const height = Math.sign(dot$2(h, scratchCartesian)) * length$2(h);
  6158. return toCartographicFromRadians([longitude, latitude, height], result);
  6159. }
  6160. eastNorthUpToFixedFrame(origin, result = new Matrix4()) {
  6161. return localFrameToFixedFrame(this, 'east', 'north', 'up', origin, result);
  6162. }
  6163. localFrameToFixedFrame(firstAxis, secondAxis, thirdAxis, origin, result = new Matrix4()) {
  6164. return localFrameToFixedFrame(this, firstAxis, secondAxis, thirdAxis, origin, result);
  6165. }
  6166. geocentricSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6167. return scratchVector$4.from(cartesian).normalize().to(result);
  6168. }
  6169. geodeticSurfaceNormalCartographic(cartographic, result = [0, 0, 0]) {
  6170. const cartographicVectorRadians = fromCartographicToRadians(cartographic);
  6171. const longitude = cartographicVectorRadians[0];
  6172. const latitude = cartographicVectorRadians[1];
  6173. const cosLatitude = Math.cos(latitude);
  6174. scratchVector$4.set(cosLatitude * Math.cos(longitude), cosLatitude * Math.sin(longitude), Math.sin(latitude)).normalize();
  6175. return scratchVector$4.to(result);
  6176. }
  6177. geodeticSurfaceNormal(cartesian, result = [0, 0, 0]) {
  6178. return scratchVector$4.from(cartesian).scale(this.oneOverRadiiSquared).normalize().to(result);
  6179. }
  6180. scaleToGeodeticSurface(cartesian, result) {
  6181. return scaleToGeodeticSurface(cartesian, this, result);
  6182. }
  6183. scaleToGeocentricSurface(cartesian, result = [0, 0, 0]) {
  6184. scratchPosition$2.from(cartesian);
  6185. const positionX = scratchPosition$2.x;
  6186. const positionY = scratchPosition$2.y;
  6187. const positionZ = scratchPosition$2.z;
  6188. const oneOverRadiiSquared = this.oneOverRadiiSquared;
  6189. const beta = 1.0 / Math.sqrt(positionX * positionX * oneOverRadiiSquared.x + positionY * positionY * oneOverRadiiSquared.y + positionZ * positionZ * oneOverRadiiSquared.z);
  6190. return scratchPosition$2.multiplyScalar(beta).to(result);
  6191. }
  6192. transformPositionToScaledSpace(position, result = [0, 0, 0]) {
  6193. return scratchPosition$2.from(position).scale(this.oneOverRadii).to(result);
  6194. }
  6195. transformPositionFromScaledSpace(position, result = [0, 0, 0]) {
  6196. return scratchPosition$2.from(position).scale(this.radii).to(result);
  6197. }
  6198. getSurfaceNormalIntersectionWithZAxis(position, buffer = 0.0, result = [0, 0, 0]) {
  6199. assert$4(equals(this.radii.x, this.radii.y, _MathUtils.EPSILON15));
  6200. assert$4(this.radii.z > 0);
  6201. scratchPosition$2.from(position);
  6202. const z = scratchPosition$2.z * (1 - this.squaredXOverSquaredZ);
  6203. if (Math.abs(z) >= this.radii.z - buffer) {
  6204. return undefined;
  6205. }
  6206. return scratchPosition$2.set(0.0, 0.0, z).to(result);
  6207. }
  6208. }
  6209. class DoublyLinkedListNode {
  6210. constructor(item, previous, next) {
  6211. _defineProperty(this, "item", void 0);
  6212. _defineProperty(this, "previous", void 0);
  6213. _defineProperty(this, "next", void 0);
  6214. this.item = item;
  6215. this.previous = previous;
  6216. this.next = next;
  6217. }
  6218. }
  6219. class DoublyLinkedList {
  6220. constructor() {
  6221. _defineProperty(this, "head", null);
  6222. _defineProperty(this, "tail", null);
  6223. _defineProperty(this, "_length", 0);
  6224. }
  6225. get length() {
  6226. return this._length;
  6227. }
  6228. add(item) {
  6229. const node = new DoublyLinkedListNode(item, this.tail, null);
  6230. if (this.tail) {
  6231. this.tail.next = node;
  6232. this.tail = node;
  6233. } else {
  6234. this.head = node;
  6235. this.tail = node;
  6236. }
  6237. ++this._length;
  6238. return node;
  6239. }
  6240. remove(node) {
  6241. if (!node) {
  6242. return;
  6243. }
  6244. if (node.previous && node.next) {
  6245. node.previous.next = node.next;
  6246. node.next.previous = node.previous;
  6247. } else if (node.previous) {
  6248. node.previous.next = null;
  6249. this.tail = node.previous;
  6250. } else if (node.next) {
  6251. node.next.previous = null;
  6252. this.head = node.next;
  6253. } else {
  6254. this.head = null;
  6255. this.tail = null;
  6256. }
  6257. node.next = null;
  6258. node.previous = null;
  6259. --this._length;
  6260. }
  6261. splice(node, nextNode) {
  6262. if (node === nextNode) {
  6263. return;
  6264. }
  6265. this.remove(nextNode);
  6266. this._insert(node, nextNode);
  6267. }
  6268. _insert(node, nextNode) {
  6269. const oldNodeNext = node.next;
  6270. node.next = nextNode;
  6271. if (this.tail === node) {
  6272. this.tail = nextNode;
  6273. } else {
  6274. oldNodeNext.previous = nextNode;
  6275. }
  6276. nextNode.next = oldNodeNext;
  6277. nextNode.previous = node;
  6278. ++this._length;
  6279. }
  6280. }
  6281. function defined$5(x) {
  6282. return x !== undefined && x !== null;
  6283. }
  6284. class TilesetCache {
  6285. constructor() {
  6286. _defineProperty(this, "_list", void 0);
  6287. _defineProperty(this, "_sentinel", void 0);
  6288. _defineProperty(this, "_trimTiles", void 0);
  6289. this._list = new DoublyLinkedList();
  6290. this._sentinel = this._list.add('sentinel');
  6291. this._trimTiles = false;
  6292. }
  6293. reset() {
  6294. this._list.splice(this._list.tail, this._sentinel);
  6295. }
  6296. touch(tile) {
  6297. const node = tile._cacheNode;
  6298. if (defined$5(node)) {
  6299. this._list.splice(this._sentinel, node);
  6300. }
  6301. }
  6302. add(tileset, tile, addCallback) {
  6303. if (!defined$5(tile._cacheNode)) {
  6304. tile._cacheNode = this._list.add(tile);
  6305. if (addCallback) {
  6306. addCallback(tileset, tile);
  6307. }
  6308. }
  6309. }
  6310. unloadTile(tileset, tile, unloadCallback) {
  6311. const node = tile._cacheNode;
  6312. if (!defined$5(node)) {
  6313. return;
  6314. }
  6315. this._list.remove(node);
  6316. tile._cacheNode = undefined;
  6317. if (unloadCallback) {
  6318. unloadCallback(tileset, tile);
  6319. }
  6320. }
  6321. unloadTiles(tileset, unloadCallback) {
  6322. const trimTiles = this._trimTiles;
  6323. this._trimTiles = false;
  6324. const list = this._list;
  6325. const maximumMemoryUsageInBytes = (Potree.settings.tiles3DMaxMemory || tileset.maximumMemoryUsage) * 1024 * 1024;
  6326. const sentinel = this._sentinel;
  6327. let node = list.head;
  6328. /* while (node !== sentinel && (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)) {
  6329. const tile = node.item;
  6330. node = node.next;
  6331. this.unloadTile(tileset, tile, unloadCallback);
  6332. } */
  6333. //改
  6334. while (node !== sentinel && ( getGpuMemoryUsage() > maximumMemoryUsageInBytes || trimTiles)) {
  6335. const tile = node.item;
  6336. node = node.next;
  6337. this.unloadTile(tileset, tile, unloadCallback);
  6338. if(viewer.visiVertexCount > 1500000){ //add: 针对部分特别精细的很卡如 https://4dkk.4dage.com/scene_view_data/SG-t-WReTBN204dQ/images/3dtiles/tileset.json
  6339. tileset.options.maximumScreenSpaceError *= 1.1
  6340. tileset.options.maximumScreenSpaceError = Math.min(1000, tileset.options.maximumScreenSpaceError)
  6341. }
  6342. }
  6343. }
  6344. trim() {
  6345. this._trimTiles = true;
  6346. }
  6347. }
  6348. function calculateTransformProps(tileHeader, tile) {
  6349. assert$7(tileHeader);
  6350. assert$7(tile);
  6351. const {
  6352. rtcCenter,
  6353. gltfUpAxis
  6354. } = tile;
  6355. const {
  6356. computedTransform,
  6357. boundingVolume: {
  6358. center
  6359. }
  6360. } = tileHeader;
  6361. let modelMatrix = new Matrix4(computedTransform);
  6362. if (rtcCenter) {
  6363. modelMatrix.translate(rtcCenter);
  6364. }
  6365. switch (gltfUpAxis) {
  6366. case 'Z':
  6367. break;
  6368. case 'Y':
  6369. const rotationY = new Matrix4().rotateX(Math.PI / 2);
  6370. modelMatrix = modelMatrix.multiplyRight(rotationY);
  6371. break;
  6372. case 'X':
  6373. const rotationX = new Matrix4().rotateY(-Math.PI / 2);
  6374. modelMatrix = modelMatrix.multiplyRight(rotationX);
  6375. break;
  6376. }
  6377. if (tile.isQuantized) {
  6378. modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale);
  6379. }
  6380. const cartesianOrigin = new Vector3(center);
  6381. tile.cartesianModelMatrix = modelMatrix;
  6382. tile.cartesianOrigin = cartesianOrigin;
  6383. const cartographicOrigin = Ellipsoid.WGS84.cartesianToCartographic(cartesianOrigin, new Vector3());
  6384. const fromFixedFrameMatrix = Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin);
  6385. const toFixedFrameMatrix = fromFixedFrameMatrix.invert();
  6386. tile.cartographicModelMatrix = toFixedFrameMatrix.multiplyRight(modelMatrix);
  6387. tile.cartographicOrigin = cartographicOrigin;
  6388. if (!tile.coordinateSystem) {
  6389. tile.modelMatrix = tile.cartographicModelMatrix;
  6390. }
  6391. }
  6392. const INTERSECTION = Object.freeze({
  6393. OUTSIDE: -1,
  6394. INTERSECTING: 0,
  6395. INSIDE: 1
  6396. });
  6397. new Vector3();
  6398. new Vector3();
  6399. const scratchVector$3 = new Vector3();
  6400. const scratchVector2 = new Vector3();
  6401. class BoundingSphere {
  6402. constructor(center = [0, 0, 0], radius = 0.0) {
  6403. this.radius = -0;
  6404. this.center = new Vector3();
  6405. this.fromCenterRadius(center, radius);
  6406. }
  6407. fromCenterRadius(center, radius) {
  6408. this.center.from(center);
  6409. this.radius = radius;
  6410. return this;
  6411. }
  6412. fromCornerPoints(corner, oppositeCorner) {
  6413. oppositeCorner = scratchVector$3.from(oppositeCorner);
  6414. this.center = new Vector3().from(corner).add(oppositeCorner).scale(0.5);
  6415. this.radius = this.center.distance(oppositeCorner);
  6416. return this;
  6417. }
  6418. equals(right) {
  6419. return this === right || Boolean(right) && this.center.equals(right.center) && this.radius === right.radius;
  6420. }
  6421. clone() {
  6422. return new BoundingSphere(this.center, this.radius);
  6423. }
  6424. union(boundingSphere) {
  6425. const leftCenter = this.center;
  6426. const leftRadius = this.radius;
  6427. const rightCenter = boundingSphere.center;
  6428. const rightRadius = boundingSphere.radius;
  6429. const toRightCenter = scratchVector$3.copy(rightCenter).subtract(leftCenter);
  6430. const centerSeparation = toRightCenter.magnitude();
  6431. if (leftRadius >= centerSeparation + rightRadius) {
  6432. return this.clone();
  6433. }
  6434. if (rightRadius >= centerSeparation + leftRadius) {
  6435. return boundingSphere.clone();
  6436. }
  6437. const halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  6438. scratchVector2.copy(toRightCenter).scale((-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation).add(leftCenter);
  6439. this.center.copy(scratchVector2);
  6440. this.radius = halfDistanceBetweenTangentPoints;
  6441. return this;
  6442. }
  6443. expand(point) {
  6444. point = scratchVector$3.from(point);
  6445. const radius = point.subtract(this.center).magnitude();
  6446. if (radius > this.radius) {
  6447. this.radius = radius;
  6448. }
  6449. return this;
  6450. }
  6451. transform(transform) {
  6452. this.center.transform(transform);
  6453. const scale = getScaling(scratchVector$3, transform);
  6454. this.radius = Math.max(scale[0], Math.max(scale[1], scale[2])) * this.radius;
  6455. return this;
  6456. }
  6457. distanceSquaredTo(point) {
  6458. const d = this.distanceTo(point);
  6459. return d * d;
  6460. }
  6461. distanceTo(point) {
  6462. point = scratchVector$3.from(point);
  6463. const delta = point.subtract(this.center);
  6464. return Math.max(0, delta.len() - this.radius);
  6465. }
  6466. intersectPlane(plane) {
  6467. const center = this.center;
  6468. const radius = this.radius;
  6469. const normal = plane.normal;
  6470. const distanceToPlane = normal.dot(center) + plane.distance;
  6471. if (distanceToPlane < -radius) {
  6472. return INTERSECTION.OUTSIDE;
  6473. }
  6474. if (distanceToPlane < radius) {
  6475. return INTERSECTION.INTERSECTING;
  6476. }
  6477. return INTERSECTION.INSIDE;
  6478. }
  6479. }
  6480. const scratchVector3 = new Vector3();
  6481. const scratchOffset = new Vector3();
  6482. const scratchVectorU = new Vector3();
  6483. const scratchVectorV = new Vector3();
  6484. const scratchVectorW = new Vector3();
  6485. const scratchCorner = new Vector3();
  6486. const scratchToCenter = new Vector3();
  6487. const MATRIX3 = {
  6488. COLUMN0ROW0: 0,
  6489. COLUMN0ROW1: 1,
  6490. COLUMN0ROW2: 2,
  6491. COLUMN1ROW0: 3,
  6492. COLUMN1ROW1: 4,
  6493. COLUMN1ROW2: 5,
  6494. COLUMN2ROW0: 6,
  6495. COLUMN2ROW1: 7,
  6496. COLUMN2ROW2: 8
  6497. };
  6498. class OrientedBoundingBox {
  6499. constructor(center = [0, 0, 0], halfAxes = [0, 0, 0, 0, 0, 0, 0, 0, 0]) {
  6500. this.center = new Vector3().from(center);
  6501. this.halfAxes = new Matrix3(halfAxes);
  6502. }
  6503. get halfSize() {
  6504. const xAxis = this.halfAxes.getColumn(0);
  6505. const yAxis = this.halfAxes.getColumn(1);
  6506. const zAxis = this.halfAxes.getColumn(2);
  6507. return [new Vector3(xAxis).len(), new Vector3(yAxis).len(), new Vector3(zAxis).len()];
  6508. }
  6509. get quaternion() {
  6510. const xAxis = this.halfAxes.getColumn(0);
  6511. const yAxis = this.halfAxes.getColumn(1);
  6512. const zAxis = this.halfAxes.getColumn(2);
  6513. const normXAxis = new Vector3(xAxis).normalize();
  6514. const normYAxis = new Vector3(yAxis).normalize();
  6515. const normZAxis = new Vector3(zAxis).normalize();
  6516. return new Quaternion().fromMatrix3(new Matrix3([...normXAxis, ...normYAxis, ...normZAxis]));
  6517. }
  6518. fromCenterHalfSizeQuaternion(center, halfSize, quaternion) {
  6519. const quaternionObject = new Quaternion(quaternion);
  6520. const directionsMatrix = new Matrix3().fromQuaternion(quaternionObject);
  6521. directionsMatrix[0] = directionsMatrix[0] * halfSize[0];
  6522. directionsMatrix[1] = directionsMatrix[1] * halfSize[0];
  6523. directionsMatrix[2] = directionsMatrix[2] * halfSize[0];
  6524. directionsMatrix[3] = directionsMatrix[3] * halfSize[1];
  6525. directionsMatrix[4] = directionsMatrix[4] * halfSize[1];
  6526. directionsMatrix[5] = directionsMatrix[5] * halfSize[1];
  6527. directionsMatrix[6] = directionsMatrix[6] * halfSize[2];
  6528. directionsMatrix[7] = directionsMatrix[7] * halfSize[2];
  6529. directionsMatrix[8] = directionsMatrix[8] * halfSize[2];
  6530. this.center = new Vector3().from(center);
  6531. this.halfAxes = directionsMatrix;
  6532. return this;
  6533. }
  6534. clone() {
  6535. return new OrientedBoundingBox(this.center, this.halfAxes);
  6536. }
  6537. equals(right) {
  6538. return this === right || Boolean(right) && this.center.equals(right.center) && this.halfAxes.equals(right.halfAxes);
  6539. }
  6540. getBoundingSphere(result = new BoundingSphere()) {
  6541. const halfAxes = this.halfAxes;
  6542. const u = halfAxes.getColumn(0, scratchVectorU);//前三个
  6543. const v = halfAxes.getColumn(1, scratchVectorV);
  6544. const w = halfAxes.getColumn(2, scratchVectorW);
  6545. const cornerVector = scratchVector3.copy(u).add(v).add(w);
  6546. result.center.copy(this.center);
  6547. result.radius = cornerVector.magnitude();
  6548. return result;
  6549. }
  6550. intersectPlane(plane) {
  6551. const center = this.center;
  6552. const normal = plane.normal;
  6553. const halfAxes = this.halfAxes;
  6554. const normalX = normal.x;
  6555. const normalY = normal.y;
  6556. const normalZ = normal.z;
  6557. 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]);
  6558. const distanceToPlane = normal.dot(center) + plane.distance;
  6559. if (distanceToPlane <= -radEffective) {
  6560. return INTERSECTION.OUTSIDE;
  6561. } else if (distanceToPlane >= radEffective) {
  6562. return INTERSECTION.INSIDE;
  6563. }
  6564. return INTERSECTION.INTERSECTING; //在相机frustum内
  6565. }
  6566. distanceTo(point) {
  6567. return Math.sqrt(this.distanceSquaredTo(point));
  6568. }
  6569. /* distanceSquaredTo(point) {//相机到bound外壳的距离平方
  6570. let center = this.center.clone()
  6571. center.z *= -1
  6572. const offset = scratchOffset.from(point).subtract(center);
  6573. const halfAxes = this.halfAxes;
  6574. const u = halfAxes.getColumn(0, scratchVectorU);
  6575. const v = halfAxes.getColumn(1, scratchVectorV);
  6576. const w = halfAxes.getColumn(2, scratchVectorW);
  6577. u.z *= -1
  6578. v.z *= -1
  6579. w.z *= -1
  6580. const uHalf = u.magnitude();
  6581. const vHalf = v.magnitude();
  6582. const wHalf = w.magnitude();
  6583. u.normalize();
  6584. v.normalize();
  6585. w.normalize();
  6586. let distanceSquared = 0.0;
  6587. let d;
  6588. d = Math.abs(offset.dot(u)) - uHalf;
  6589. if (d > 0) {
  6590. distanceSquared += d * d;
  6591. }
  6592. d = Math.abs(offset.dot(v)) - vHalf;
  6593. if (d > 0) {
  6594. distanceSquared += d * d;
  6595. }
  6596. d = Math.abs(offset.dot(w)) - wHalf;
  6597. if (d > 0) {
  6598. distanceSquared += d * d;
  6599. }
  6600. return distanceSquared;
  6601. } */
  6602. distanceSquaredTo(point) {//相机到bound外壳的距离平方
  6603. const offset = scratchOffset.from(point).subtract(this.center);
  6604. const halfAxes = this.halfAxes;
  6605. const u = halfAxes.getColumn(0, scratchVectorU);
  6606. const v = halfAxes.getColumn(1, scratchVectorV);
  6607. const w = halfAxes.getColumn(2, scratchVectorW);
  6608. const uHalf = u.magnitude();
  6609. const vHalf = v.magnitude();
  6610. const wHalf = w.magnitude();
  6611. u.normalize();
  6612. v.normalize();
  6613. w.normalize();
  6614. let distanceSquared = 0.0;
  6615. let d;
  6616. d = Math.abs(offset.dot(u)) - uHalf;
  6617. if (d > 0) {
  6618. distanceSquared += d * d;
  6619. }
  6620. d = Math.abs(offset.dot(v)) - vHalf;
  6621. if (d > 0) {
  6622. distanceSquared += d * d;
  6623. }
  6624. d = Math.abs(offset.dot(w)) - wHalf;
  6625. if (d > 0) {
  6626. distanceSquared += d * d;
  6627. }
  6628. return distanceSquared;
  6629. }
  6630. computePlaneDistances(position, direction, result = [-0, -0]) {
  6631. let minDist = Number.POSITIVE_INFINITY;
  6632. let maxDist = Number.NEGATIVE_INFINITY;
  6633. const center = this.center;
  6634. const halfAxes = this.halfAxes;
  6635. const u = halfAxes.getColumn(0, scratchVectorU);
  6636. const v = halfAxes.getColumn(1, scratchVectorV);
  6637. const w = halfAxes.getColumn(2, scratchVectorW);
  6638. const corner = scratchCorner.copy(u).add(v).add(w).add(center);
  6639. const toCenter = scratchToCenter.copy(corner).subtract(position);
  6640. let mag = direction.dot(toCenter);
  6641. minDist = Math.min(mag, minDist);
  6642. maxDist = Math.max(mag, maxDist);
  6643. corner.copy(center).add(u).add(v).subtract(w);
  6644. toCenter.copy(corner).subtract(position);
  6645. mag = direction.dot(toCenter);
  6646. minDist = Math.min(mag, minDist);
  6647. maxDist = Math.max(mag, maxDist);
  6648. corner.copy(center).add(u).subtract(v).add(w);
  6649. toCenter.copy(corner).subtract(position);
  6650. mag = direction.dot(toCenter);
  6651. minDist = Math.min(mag, minDist);
  6652. maxDist = Math.max(mag, maxDist);
  6653. corner.copy(center).add(u).subtract(v).subtract(w);
  6654. toCenter.copy(corner).subtract(position);
  6655. mag = direction.dot(toCenter);
  6656. minDist = Math.min(mag, minDist);
  6657. maxDist = Math.max(mag, maxDist);
  6658. center.copy(corner).subtract(u).add(v).add(w);
  6659. toCenter.copy(corner).subtract(position);
  6660. mag = direction.dot(toCenter);
  6661. minDist = Math.min(mag, minDist);
  6662. maxDist = Math.max(mag, maxDist);
  6663. center.copy(corner).subtract(u).add(v).subtract(w);
  6664. toCenter.copy(corner).subtract(position);
  6665. mag = direction.dot(toCenter);
  6666. minDist = Math.min(mag, minDist);
  6667. maxDist = Math.max(mag, maxDist);
  6668. center.copy(corner).subtract(u).subtract(v).add(w);
  6669. toCenter.copy(corner).subtract(position);
  6670. mag = direction.dot(toCenter);
  6671. minDist = Math.min(mag, minDist);
  6672. maxDist = Math.max(mag, maxDist);
  6673. center.copy(corner).subtract(u).subtract(v).subtract(w);
  6674. toCenter.copy(corner).subtract(position);
  6675. mag = direction.dot(toCenter);
  6676. minDist = Math.min(mag, minDist);
  6677. maxDist = Math.max(mag, maxDist);
  6678. result[0] = minDist;
  6679. result[1] = maxDist;
  6680. return result;
  6681. }
  6682. transform(transformation) {
  6683. this.center.transformAsPoint(transformation);
  6684. const xAxis = this.halfAxes.getColumn(0, scratchVectorU);
  6685. xAxis.transformAsPoint(transformation);
  6686. const yAxis = this.halfAxes.getColumn(1, scratchVectorV);
  6687. yAxis.transformAsPoint(transformation);
  6688. const zAxis = this.halfAxes.getColumn(2, scratchVectorW);
  6689. zAxis.transformAsPoint(transformation);
  6690. this.halfAxes = new Matrix3([...xAxis, ...yAxis, ...zAxis]);
  6691. return this;
  6692. }
  6693. getTransform() {
  6694. throw new Error('not implemented');
  6695. }
  6696. }
  6697. const scratchPosition$1 = new Vector3();
  6698. const scratchNormal$1 = new Vector3();
  6699. class Plane {
  6700. constructor(normal = [0, 0, 1], distance = 0) {
  6701. this.normal = new Vector3();
  6702. this.distance = -0;
  6703. this.fromNormalDistance(normal, distance);
  6704. }
  6705. fromNormalDistance(normal, distance) {
  6706. assert$4(Number.isFinite(distance));
  6707. this.normal.from(normal).normalize();
  6708. this.distance = distance;
  6709. return this;
  6710. }
  6711. fromPointNormal(point, normal) {
  6712. point = scratchPosition$1.from(point);
  6713. this.normal.from(normal).normalize();
  6714. const distance = -this.normal.dot(point);
  6715. this.distance = distance;
  6716. return this;
  6717. }
  6718. fromCoefficients(a, b, c, d) {
  6719. this.normal.set(a, b, c);
  6720. assert$4(equals(this.normal.len(), 1));
  6721. this.distance = d;
  6722. return this;
  6723. }
  6724. clone(plane) {
  6725. return new Plane(this.normal, this.distance);
  6726. }
  6727. equals(right) {
  6728. return equals(this.distance, right.distance) && equals(this.normal, right.normal);
  6729. }
  6730. getPointDistance(point) {
  6731. return this.normal.dot(point) + this.distance;
  6732. }
  6733. transform(matrix4) {
  6734. const normal = scratchNormal$1.copy(this.normal).transformAsVector(matrix4).normalize();
  6735. const point = this.normal.scale(-this.distance).transform(matrix4);
  6736. return this.fromPointNormal(point, normal);
  6737. }
  6738. projectPointOntoPlane(point, result = [0, 0, 0]) {
  6739. point = scratchPosition$1.from(point);
  6740. const pointDistance = this.getPointDistance(point);
  6741. const scaledNormal = scratchNormal$1.copy(this.normal).scale(pointDistance);
  6742. return point.subtract(scaledNormal).to(result);
  6743. }
  6744. }
  6745. const faces = [new Vector3([1, 0, 0]), new Vector3([0, 1, 0]), new Vector3([0, 0, 1])];
  6746. const scratchPlaneCenter = new Vector3();
  6747. const scratchPlaneNormal$1 = new Vector3();
  6748. new Plane(new Vector3(1.0, 0.0, 0.0), 0.0);
  6749. class CullingVolume {
  6750. static get MASK_OUTSIDE() {
  6751. return 0xffffffff;
  6752. }
  6753. static get MASK_INSIDE() {
  6754. return 0x00000000;
  6755. }
  6756. static get MASK_INDETERMINATE() {
  6757. return 0x7fffffff;
  6758. }
  6759. constructor(planes = []) {
  6760. this.planes = planes;
  6761. assert$4(this.planes.every(plane => plane instanceof Plane));
  6762. }
  6763. fromBoundingSphere(boundingSphere) {
  6764. this.planes.length = 2 * faces.length;
  6765. const center = boundingSphere.center;
  6766. const radius = boundingSphere.radius;
  6767. let planeIndex = 0;
  6768. for (const faceNormal of faces) {
  6769. let plane0 = this.planes[planeIndex];
  6770. let plane1 = this.planes[planeIndex + 1];
  6771. if (!plane0) {
  6772. plane0 = this.planes[planeIndex] = new Plane();
  6773. }
  6774. if (!plane1) {
  6775. plane1 = this.planes[planeIndex + 1] = new Plane();
  6776. }
  6777. const plane0Center = scratchPlaneCenter.copy(faceNormal).scale(-radius).add(center);
  6778. -faceNormal.dot(plane0Center);
  6779. plane0.fromPointNormal(plane0Center, faceNormal);
  6780. const plane1Center = scratchPlaneCenter.copy(faceNormal).scale(radius).add(center);
  6781. const negatedFaceNormal = scratchPlaneNormal$1.copy(faceNormal).negate();
  6782. -negatedFaceNormal.dot(plane1Center);
  6783. plane1.fromPointNormal(plane1Center, negatedFaceNormal);
  6784. planeIndex += 2;
  6785. }
  6786. return this;
  6787. }
  6788. computeVisibility(boundingVolume) {
  6789. assert$4(boundingVolume);
  6790. let intersect = INTERSECTION.INSIDE;
  6791. for (const plane of this.planes) {
  6792. const result = boundingVolume.intersectPlane(plane);
  6793. switch (result) {
  6794. case INTERSECTION.OUTSIDE:
  6795. return INTERSECTION.OUTSIDE;
  6796. case INTERSECTION.INTERSECTING:
  6797. intersect = INTERSECTION.INTERSECTING;
  6798. break;
  6799. }
  6800. }
  6801. return intersect;
  6802. }
  6803. computeVisibilityWithPlaneMask(boundingVolume, parentPlaneMask) {
  6804. assert$4(boundingVolume, 'boundingVolume is required.');
  6805. assert$4(Number.isFinite(parentPlaneMask), 'parentPlaneMask is required.');
  6806. if (parentPlaneMask === CullingVolume.MASK_OUTSIDE || parentPlaneMask === CullingVolume.MASK_INSIDE) {
  6807. return parentPlaneMask;
  6808. }
  6809. let mask = CullingVolume.MASK_INSIDE;
  6810. const planes = this.planes;
  6811. for (let k = 0; k < this.planes.length; ++k) {
  6812. const flag = k < 31 ? 1 << k : 0;
  6813. if (k < 31 && (parentPlaneMask & flag) === 0) {
  6814. continue;
  6815. }
  6816. const plane = planes[k];
  6817. const result = boundingVolume.intersectPlane(plane);
  6818. if (result === INTERSECTION.OUTSIDE) {
  6819. return CullingVolume.MASK_OUTSIDE;
  6820. } else if (result === INTERSECTION.INTERSECTING) {
  6821. mask |= flag;
  6822. }
  6823. }
  6824. return mask;
  6825. }
  6826. }
  6827. const scratchPlaneUpVector = new Vector3();
  6828. const scratchPlaneRightVector = new Vector3();
  6829. const scratchPlaneNearCenter = new Vector3();
  6830. const scratchPlaneFarCenter = new Vector3();
  6831. const scratchPlaneNormal = new Vector3();
  6832. class PerspectiveOffCenterFrustum {
  6833. constructor(options = {}) {
  6834. options = {
  6835. near: 1.0,
  6836. far: 500000000.0,
  6837. ...options
  6838. };
  6839. this.left = options.left;
  6840. this._left = undefined;
  6841. this.right = options.right;
  6842. this._right = undefined;
  6843. this.top = options.top;
  6844. this._top = undefined;
  6845. this.bottom = options.bottom;
  6846. this._bottom = undefined;
  6847. this.near = options.near;
  6848. this._near = this.near;
  6849. this.far = options.far;
  6850. this._far = this.far;
  6851. this._cullingVolume = new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]);
  6852. this._perspectiveMatrix = new Matrix4();
  6853. this._infinitePerspective = new Matrix4();
  6854. }
  6855. clone() {
  6856. return new PerspectiveOffCenterFrustum({
  6857. right: this.right,
  6858. left: this.left,
  6859. top: this.top,
  6860. bottom: this.bottom,
  6861. near: this.near,
  6862. far: this.far
  6863. });
  6864. }
  6865. equals(other) {
  6866. 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;
  6867. }
  6868. get projectionMatrix() {
  6869. update$1(this);
  6870. return this._perspectiveMatrix;
  6871. }
  6872. get infiniteProjectionMatrix() {
  6873. update$1(this);
  6874. return this._infinitePerspective;
  6875. }
  6876. computeCullingVolume(position, direction, up) {
  6877. assert$4(position, 'position is required.');
  6878. assert$4(direction, 'direction is required.');
  6879. assert$4(up, 'up is required.');
  6880. const planes = this._cullingVolume.planes;
  6881. up = scratchPlaneUpVector.copy(up).normalize();
  6882. const right = scratchPlaneRightVector.copy(direction).cross(up).normalize();
  6883. const nearCenter = scratchPlaneNearCenter.copy(direction).multiplyByScalar(this.near).add(position);
  6884. const farCenter = scratchPlaneFarCenter.copy(direction).multiplyByScalar(this.far).add(position);
  6885. let normal = scratchPlaneNormal;
  6886. normal.copy(right).multiplyByScalar(this.left).add(nearCenter).subtract(position).cross(up);
  6887. planes[0].fromPointNormal(position, normal);
  6888. normal.copy(right).multiplyByScalar(this.right).add(nearCenter).subtract(position).cross(up).negate();
  6889. planes[1].fromPointNormal(position, normal);
  6890. normal.copy(up).multiplyByScalar(this.bottom).add(nearCenter).subtract(position).cross(right).negate();
  6891. planes[2].fromPointNormal(position, normal);
  6892. normal.copy(up).multiplyByScalar(this.top).add(nearCenter).subtract(position).cross(right);
  6893. planes[3].fromPointNormal(position, normal);
  6894. normal = new Vector3().copy(direction);
  6895. planes[4].fromPointNormal(nearCenter, normal);
  6896. normal.negate();
  6897. planes[5].fromPointNormal(farCenter, normal);
  6898. return this._cullingVolume;
  6899. }
  6900. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  6901. update$1(this);
  6902. assert$4(Number.isFinite(drawingBufferWidth) && Number.isFinite(drawingBufferHeight));
  6903. assert$4(drawingBufferWidth > 0);
  6904. assert$4(drawingBufferHeight > 0);
  6905. assert$4(distance > 0);
  6906. assert$4(result);
  6907. const inverseNear = 1.0 / this.near;
  6908. let tanTheta = this.top * inverseNear;
  6909. const pixelHeight = 2.0 * distance * tanTheta / drawingBufferHeight;
  6910. tanTheta = this.right * inverseNear;
  6911. const pixelWidth = 2.0 * distance * tanTheta / drawingBufferWidth;
  6912. result.x = pixelWidth;
  6913. result.y = pixelHeight;
  6914. return result;
  6915. }
  6916. }
  6917. function update$1(frustum) {
  6918. 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));
  6919. const {
  6920. top,
  6921. bottom,
  6922. right,
  6923. left,
  6924. near,
  6925. far
  6926. } = frustum;
  6927. if (top !== frustum._top || bottom !== frustum._bottom || left !== frustum._left || right !== frustum._right || near !== frustum._near || far !== frustum._far) {
  6928. assert$4(frustum.near > 0 && frustum.near < frustum.far, 'near must be greater than zero and less than far.');
  6929. frustum._left = left;
  6930. frustum._right = right;
  6931. frustum._top = top;
  6932. frustum._bottom = bottom;
  6933. frustum._near = near;
  6934. frustum._far = far;
  6935. frustum._perspectiveMatrix = new Matrix4().frustum({
  6936. left,
  6937. right,
  6938. bottom,
  6939. top,
  6940. near,
  6941. far
  6942. });
  6943. frustum._infinitePerspective = new Matrix4().frustum({
  6944. left,
  6945. right,
  6946. bottom,
  6947. top,
  6948. near,
  6949. far: Infinity
  6950. });
  6951. }
  6952. }
  6953. const defined$4 = val => val !== null && typeof val !== 'undefined';
  6954. class PerspectiveFrustum {
  6955. constructor(options = {}) {
  6956. options = {
  6957. near: 1.0,
  6958. far: 500000000.0,
  6959. xOffset: 0.0,
  6960. yOffset: 0.0,
  6961. ...options
  6962. };
  6963. this._offCenterFrustum = new PerspectiveOffCenterFrustum();
  6964. this.fov = options.fov;
  6965. this._fov = undefined;
  6966. this._fovy = undefined;
  6967. this._sseDenominator = undefined;
  6968. this.aspectRatio = options.aspectRatio;
  6969. this._aspectRatio = undefined;
  6970. this.near = options.near;
  6971. this._near = this.near;
  6972. this.far = options.far;
  6973. this._far = this.far;
  6974. this.xOffset = options.xOffset;
  6975. this._xOffset = this.xOffset;
  6976. this.yOffset = options.yOffset;
  6977. this._yOffset = this.yOffset;
  6978. }
  6979. clone() {
  6980. return new PerspectiveFrustum({
  6981. aspectRatio: this.aspectRatio,
  6982. fov: this.fov,
  6983. near: this.near,
  6984. far: this.far
  6985. });
  6986. }
  6987. equals(other) {
  6988. if (!defined$4(other) || !(other instanceof PerspectiveFrustum)) {
  6989. return false;
  6990. }
  6991. update(this);
  6992. update(other);
  6993. return this.fov === other.fov && this.aspectRatio === other.aspectRatio && this.near === other.near && this.far === other.far && this._offCenterFrustum.equals(other._offCenterFrustum);
  6994. }
  6995. get projectionMatrix() {
  6996. update(this);
  6997. return this._offCenterFrustum.projectionMatrix;
  6998. }
  6999. get infiniteProjectionMatrix() {
  7000. update(this);
  7001. return this._offCenterFrustum.infiniteProjectionMatrix;
  7002. }
  7003. get fovy() {
  7004. update(this);
  7005. return this._fovy;
  7006. }
  7007. get sseDenominator() {
  7008. update(this);
  7009. return this._sseDenominator;
  7010. }
  7011. computeCullingVolume(position, direction, up) {
  7012. update(this);
  7013. return this._offCenterFrustum.computeCullingVolume(position, direction, up);
  7014. }
  7015. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  7016. update(this);
  7017. return this._offCenterFrustum.getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result);
  7018. }
  7019. }
  7020. function update(frustum) {
  7021. assert$4(Number.isFinite(frustum.fov) && Number.isFinite(frustum.aspectRatio) && Number.isFinite(frustum.near) && Number.isFinite(frustum.far));
  7022. const f = frustum._offCenterFrustum;
  7023. 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) {
  7024. assert$4(frustum.fov >= 0 && frustum.fov < Math.PI);
  7025. //assert$4(frustum.aspectRatio > 0);
  7026. if(frustum.aspectRatio == 0){
  7027. console.log(1)
  7028. }
  7029. assert$4(frustum.near >= 0 && frustum.near < frustum.far);
  7030. frustum._aspectRatio = Math.max(0.001, frustum.aspectRatio);
  7031. frustum._fov = frustum.fov;
  7032. frustum._fovy = frustum._aspectRatio <= 1 ? frustum.fov : Math.atan(Math.tan(frustum.fov * 0.5) / frustum._aspectRatio) * 2.0;
  7033. frustum._near = frustum.near;
  7034. frustum._far = frustum.far;
  7035. frustum._sseDenominator = 2.0 * Math.tan(0.5 * frustum._fovy);
  7036. frustum._xOffset = frustum.xOffset;
  7037. frustum._yOffset = frustum.yOffset;
  7038. f.top = frustum.near * Math.tan(0.5 * frustum._fovy);
  7039. f.bottom = -f.top;
  7040. f.right = frustum._aspectRatio * f.top;
  7041. f.left = -f.right;
  7042. f.near = frustum.near;
  7043. f.far = frustum.far;
  7044. f.right += frustum.xOffset;
  7045. f.left += frustum.xOffset;
  7046. f.top += frustum.yOffset;
  7047. f.bottom += frustum.yOffset;
  7048. }
  7049. }
  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 Vector3();
  7061. new Vector3();
  7062. new Matrix3();
  7063. new Matrix3();
  7064. new Matrix3();
  7065. new Matrix3();
  7066. new Matrix3();
  7067. new Vector3();
  7068. new Vector3();
  7069. new Vector3();
  7070. new Vector3();
  7071. new Vector3();
  7072. new Matrix3();
  7073. ({
  7074. diagonal: new Matrix3(),
  7075. unitary: new Matrix3()
  7076. });
  7077. const scratchVector$2 = new Vector3();
  7078. const scratchPosition = new Vector3();
  7079. const cullingVolume = new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]);
  7080. function getFrameState(viewport, frameNumber) {
  7081. const {
  7082. cameraDirection,
  7083. cameraUp,
  7084. height
  7085. } = viewport;
  7086. const {
  7087. metersPerUnit
  7088. } = viewport.distanceScales;
  7089. const viewportCenterCartographic = viewport.unprojectPosition(viewport.center);
  7090. const viewportCenterCartesian = Ellipsoid.WGS84.cartographicToCartesian(viewportCenterCartographic, new Vector3());
  7091. const enuToFixedTransform = Ellipsoid.WGS84.eastNorthUpToFixedFrame(viewportCenterCartesian);
  7092. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7093. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
  7094. const cameraDirectionCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraDirection).scale(metersPerUnit))).normalize();
  7095. const cameraUpCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraUp).scale(metersPerUnit))).normalize();
  7096. commonSpacePlanesToWGS84(viewport, viewportCenterCartesian);
  7097. return {
  7098. camera: {
  7099. position: cameraPositionCartesian,
  7100. direction: cameraDirectionCartesian,
  7101. up: cameraUpCartesian
  7102. },
  7103. viewport,
  7104. height,
  7105. cullingVolume,
  7106. frameNumber,
  7107. sseDenominator: 1.15
  7108. };
  7109. }
  7110. function commonSpacePlanesToWGS84(viewport, viewportCenterCartesian) {
  7111. const frustumPlanes = viewport.getFrustumPlanes();
  7112. let i = 0;
  7113. for (const dir in frustumPlanes) {
  7114. const plane = frustumPlanes[dir];
  7115. const distanceToCenter = plane.normal.dot(viewport.center);
  7116. scratchPosition.copy(plane.normal).scale(plane.distance - distanceToCenter).add(viewport.center);
  7117. const cartographicPos = viewport.unprojectPosition(scratchPosition);
  7118. const cartesianPos = Ellipsoid.WGS84.cartographicToCartesian(cartographicPos, new Vector3());
  7119. cullingVolume.planes[i++].fromPointNormal(cartesianPos, scratchVector$2.copy(viewportCenterCartesian).subtract(cartesianPos));
  7120. }
  7121. }
  7122. const WGS84_RADIUS_X = 6378137.0;
  7123. const WGS84_RADIUS_Y = 6378137.0;
  7124. const WGS84_RADIUS_Z = 6356752.3142451793;
  7125. const scratchVector$1 = new Vector3();
  7126. function getZoomFromBoundingVolume(boundingVolume) {
  7127. const {
  7128. halfAxes,
  7129. radius,
  7130. width,
  7131. height
  7132. } = boundingVolume;
  7133. if (halfAxes) {
  7134. const obbSize = getObbSize(halfAxes);
  7135. return Math.log2(WGS84_RADIUS_Z / obbSize);
  7136. } else if (radius) {
  7137. return Math.log2(WGS84_RADIUS_Z / radius);
  7138. } else if (height && width) {
  7139. const zoomX = Math.log2(WGS84_RADIUS_X / width);
  7140. const zoomY = Math.log2(WGS84_RADIUS_Y / height);
  7141. return (zoomX + zoomY) / 2;
  7142. }
  7143. return 1;
  7144. }
  7145. function getObbSize(halfAxes) {
  7146. halfAxes.getColumn(0, scratchVector$1);
  7147. const axeY = halfAxes.getColumn(1);
  7148. const axeZ = halfAxes.getColumn(2);
  7149. const farthestVertex = scratchVector$1.add(axeY).add(axeZ);
  7150. const size = farthestVertex.len();
  7151. return size;
  7152. }
  7153. const TILE_CONTENT_STATE = {
  7154. UNLOADED: 0,
  7155. LOADING: 1,
  7156. PROCESSING: 2,
  7157. READY: 3,
  7158. EXPIRED: 4,
  7159. FAILED: 5
  7160. };
  7161. const TILE_REFINEMENT = {
  7162. ADD: 1,
  7163. REPLACE: 2
  7164. };
  7165. const TILE_TYPE = {
  7166. EMPTY: 'empty',
  7167. SCENEGRAPH: 'scenegraph',
  7168. POINTCLOUD: 'pointcloud',
  7169. MESH: 'mesh'
  7170. };
  7171. const TILESET_TYPE = {
  7172. I3S: 'I3S',
  7173. TILES3D: 'TILES3D'
  7174. };
  7175. const LOD_METRIC_TYPE = {
  7176. GEOMETRIC_ERROR: 'geometricError',
  7177. MAX_SCREEN_THRESHOLD: 'maxScreenThreshold'
  7178. };
  7179. const TILE3D_OPTIMIZATION_HINT = {
  7180. NOT_COMPUTED: -1,
  7181. USE_OPTIMIZATION: 1,
  7182. SKIP_OPTIMIZATION: 0
  7183. };
  7184. function defined$3(x) {
  7185. return x !== undefined && x !== null;
  7186. }
  7187. const scratchScale = new Vector3();
  7188. const scratchNorthWest = new Vector3();
  7189. const scratchSouthEast = new Vector3();
  7190. function createBoundingVolume(boundingVolumeHeader, transform, result) {
  7191. assert$7(boundingVolumeHeader, '3D Tile: boundingVolume must be defined');
  7192. if (boundingVolumeHeader.box) {
  7193. return createBox(boundingVolumeHeader.box, transform, result);
  7194. }
  7195. if (boundingVolumeHeader.region) {
  7196. const [west, south, east, north, minHeight, maxHeight] = boundingVolumeHeader.region;
  7197. const northWest = Ellipsoid.WGS84.cartographicToCartesian([degrees(west), degrees(north), minHeight], scratchNorthWest);
  7198. const southEast = Ellipsoid.WGS84.cartographicToCartesian([degrees(east), degrees(south), maxHeight], scratchSouthEast);
  7199. const centerInCartesian = new Vector3().addVectors(northWest, southEast).multiplyScalar(0.5);
  7200. const radius = new Vector3().subVectors(northWest, southEast).len() / 2.0;
  7201. return createSphere([centerInCartesian[0], centerInCartesian[1], centerInCartesian[2], radius], new Matrix4());
  7202. }
  7203. if (boundingVolumeHeader.sphere) {
  7204. return createSphere(boundingVolumeHeader.sphere, transform, result);
  7205. }
  7206. throw new Error('3D Tile: boundingVolume must contain a sphere, region, or box');
  7207. }
  7208. function createBox(box, transform, result) {
  7209. const center = new Vector3(box[0], box[1], box[2]);
  7210. result && (result.oriCenter = center)//add
  7211. transform.transform(center, center);
  7212. let origin = [];
  7213. if (box.length === 10) {
  7214. const halfSize = box.slice(3, 6);
  7215. const quaternion = new Quaternion();
  7216. quaternion.fromArray(box, 6);
  7217. const x = new Vector3([1, 0, 0]);
  7218. const y = new Vector3([0, 1, 0]);
  7219. const z = new Vector3([0, 0, 1]);
  7220. x.transformByQuaternion(quaternion);
  7221. x.scale(halfSize[0]);
  7222. y.transformByQuaternion(quaternion);
  7223. y.scale(halfSize[1]);
  7224. z.transformByQuaternion(quaternion);
  7225. z.scale(halfSize[2]);
  7226. origin = [...x.toArray(), ...y.toArray(), ...z.toArray()];
  7227. } else {
  7228. origin = [...box.slice(3, 6), ...box.slice(6, 9), ...box.slice(9, 12)];
  7229. }
  7230. const xAxis = transform.transformAsVector(origin.slice(0, 3));
  7231. const yAxis = transform.transformAsVector(origin.slice(3, 6));
  7232. const zAxis = transform.transformAsVector(origin.slice(6, 9));
  7233. const halfAxes = new Matrix3([xAxis[0], xAxis[1], xAxis[2], yAxis[0], yAxis[1], yAxis[2], zAxis[0], zAxis[1], zAxis[2]]);
  7234. //const halfAxes = new Matrix3([xAxis[0], xAxis[1], -xAxis[2], yAxis[0], yAxis[1], -yAxis[2], zAxis[0], zAxis[1], -zAxis[2]]);//改
  7235. //center.z *= -1//add
  7236. if (defined$3(result)) {
  7237. result.center = center;
  7238. result.halfAxes = halfAxes;
  7239. return result;
  7240. }
  7241. return new OrientedBoundingBox(center, halfAxes);
  7242. }
  7243. function createSphere(sphere, transform, result) {
  7244. const center = new Vector3(sphere[0], sphere[1], sphere[2]);
  7245. transform.transform(center, center);
  7246. const scale = transform.getScale(scratchScale);
  7247. const uniformScale = Math.max(Math.max(scale[0], scale[1]), scale[2]);
  7248. const radius = sphere[3] * uniformScale;
  7249. if (defined$3(result)) {
  7250. result.center = center;
  7251. result.radius = radius;
  7252. return result;
  7253. }
  7254. return new BoundingSphere(center, radius);
  7255. }
  7256. new Vector3();
  7257. new Vector3();
  7258. new Matrix4();
  7259. new Vector3();
  7260. new Vector3();
  7261. new Vector3();
  7262. function fog(distanceToCamera, density) {
  7263. const scalar = distanceToCamera * density;
  7264. return 1.0 - Math.exp(-(scalar * scalar));
  7265. }
  7266. function getDynamicScreenSpaceError(tileset, distanceToCamera) {
  7267. if (tileset.dynamicScreenSpaceError && tileset.dynamicScreenSpaceErrorComputedDensity) {
  7268. const density = tileset.dynamicScreenSpaceErrorComputedDensity;
  7269. const factor = tileset.dynamicScreenSpaceErrorFactor;
  7270. const dynamicError = fog(distanceToCamera, density) * factor;
  7271. return dynamicError;
  7272. }
  7273. return 0;
  7274. }
  7275. function getTiles3DScreenSpaceError(tile, frameState, useParentLodMetric) {
  7276. const tileset = tile.tileset;
  7277. const parentLodMetricValue = tile.parent && tile.parent.lodMetricValue || tile.lodMetricValue;
  7278. const lodMetricValue = useParentLodMetric ? parentLodMetricValue : tile.lodMetricValue;
  7279. if (lodMetricValue === 0.0) {
  7280. return 0.0;
  7281. }
  7282. const distance = Math.max(tile._distanceToCamera, 1e-7);
  7283. const {
  7284. height,
  7285. sseDenominator
  7286. } = frameState;
  7287. const {
  7288. viewDistanceScale
  7289. } = tileset.options;
  7290. let error = lodMetricValue * height * (viewDistanceScale || 1.0) / (distance * sseDenominator);
  7291. error -= getDynamicScreenSpaceError(tileset, distance);
  7292. return error;
  7293. }
  7294. function getLodStatus(tile, frameState) {
  7295. if (tile.lodMetricValue === 0 || isNaN(tile.lodMetricValue)) {
  7296. return 'DIG';
  7297. }
  7298. const screenSize = 2 * getProjectedRadius(tile, frameState);
  7299. if (screenSize < 2) {
  7300. return 'OUT';
  7301. }
  7302. if (!tile.header.children || screenSize <= tile.lodMetricValue) {
  7303. return 'DRAW';
  7304. } else if (tile.header.children) {
  7305. return 'DIG';
  7306. }
  7307. return 'OUT';
  7308. }
  7309. function getProjectedRadius(tile, frameState) {
  7310. const originalViewport = frameState.viewport;
  7311. const ViewportClass = originalViewport.constructor;
  7312. const {
  7313. longitude,
  7314. latitude,
  7315. height,
  7316. width,
  7317. bearing,
  7318. zoom
  7319. } = originalViewport;
  7320. const viewport = new ViewportClass({
  7321. longitude,
  7322. latitude,
  7323. height,
  7324. width,
  7325. bearing,
  7326. zoom,
  7327. pitch: 0
  7328. });
  7329. const mbsLat = tile.header.mbs[1];
  7330. const mbsLon = tile.header.mbs[0];
  7331. const mbsZ = tile.header.mbs[2];
  7332. const mbsR = tile.header.mbs[3];
  7333. const mbsCenterCartesian = [...tile.boundingVolume.center];
  7334. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  7335. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
  7336. const toEye = new Vector3(cameraPositionCartesian).subtract(mbsCenterCartesian).normalize();
  7337. const enuToCartesianMatrix = new Matrix4();
  7338. Ellipsoid.WGS84.eastNorthUpToFixedFrame(mbsCenterCartesian, enuToCartesianMatrix);
  7339. const cartesianToEnuMatrix = new Matrix4(enuToCartesianMatrix).invert();
  7340. const cameraPositionEnu = new Vector3(cameraPositionCartesian).transform(cartesianToEnuMatrix);
  7341. const projection = Math.sqrt(cameraPositionEnu[0] * cameraPositionEnu[0] + cameraPositionEnu[1] * cameraPositionEnu[1]);
  7342. const extraZ = projection * projection / cameraPositionEnu[2];
  7343. const extraVertexEnu = new Vector3([cameraPositionEnu[0], cameraPositionEnu[1], extraZ]);
  7344. const extraVertexCartesian = extraVertexEnu.transform(enuToCartesianMatrix);
  7345. const extraVectorCartesian = new Vector3(extraVertexCartesian).subtract(mbsCenterCartesian).normalize();
  7346. const radiusVector = toEye.cross(extraVectorCartesian).normalize().scale(mbsR);
  7347. const sphereMbsBorderVertexCartesian = new Vector3(mbsCenterCartesian).add(radiusVector);
  7348. const sphereMbsBorderVertexCartographic = Ellipsoid.WGS84.cartesianToCartographic(sphereMbsBorderVertexCartesian);
  7349. const projectedOrigin = viewport.project([mbsLon, mbsLat, mbsZ]);
  7350. const projectedMbsBorderVertex = viewport.project(sphereMbsBorderVertexCartographic);
  7351. const projectedRadius = new Vector3(projectedOrigin).subtract(projectedMbsBorderVertex).magnitude();
  7352. return projectedRadius;
  7353. }
  7354. function get3dTilesOptions(tileset) {
  7355. return {
  7356. assetGltfUpAxis: tileset.asset && tileset.asset.gltfUpAxis || 'Y'
  7357. };
  7358. }
  7359. class ManagedArray {
  7360. constructor(length = 0) {
  7361. _defineProperty(this, "_map", new Map());
  7362. _defineProperty(this, "_array", void 0);
  7363. _defineProperty(this, "_length", void 0);
  7364. this._array = new Array(length);
  7365. this._length = length;
  7366. }
  7367. get length() {
  7368. return this._length;
  7369. }
  7370. set length(length) {
  7371. this._length = length;
  7372. if (length > this._array.length) {
  7373. this._array.length = length;
  7374. }
  7375. }
  7376. get values() {
  7377. return this._array;
  7378. }
  7379. get(index) {
  7380. assert$7(index < this._array.length);
  7381. return this._array[index];
  7382. }
  7383. set(index, element) {
  7384. assert$7(index >= 0);
  7385. if (index >= this.length) {
  7386. this.length = index + 1;
  7387. }
  7388. if (this._map.has(this._array[index])) {
  7389. this._map.delete(this._array[index]);
  7390. }
  7391. this._array[index] = element;
  7392. this._map.set(element, index);
  7393. }
  7394. delete(element) {
  7395. const index = this._map.get(element);
  7396. if (index >= 0) {
  7397. this._array.splice(index, 1);
  7398. this._map.delete(element);
  7399. this.length--;
  7400. }
  7401. }
  7402. peek() {
  7403. return this._array[this._length - 1];
  7404. }
  7405. push(element) {
  7406. if (!this._map.has(element)) {
  7407. const index = this.length++;
  7408. this._array[index] = element;
  7409. this._map.set(element, index);
  7410. }
  7411. }
  7412. pop() {
  7413. const element = this._array[--this.length];
  7414. this._map.delete(element);
  7415. return element;
  7416. }
  7417. reserve(length) {
  7418. assert$7(length >= 0);
  7419. if (length > this._array.length) {
  7420. this._array.length = length;
  7421. }
  7422. }
  7423. resize(length) {
  7424. assert$7(length >= 0);
  7425. this.length = length;
  7426. }
  7427. trim(length) {
  7428. if (length === null || length === undefined) {
  7429. length = this.length;
  7430. }
  7431. this._array.length = length;
  7432. }
  7433. reset() {
  7434. this._array = [];
  7435. this._map = new Map();
  7436. this._length = 0;
  7437. }
  7438. find(target) {
  7439. return this._map.has(target);
  7440. }
  7441. }
  7442. const DEFAULT_PROPS$1 = {
  7443. loadSiblings: false,
  7444. skipLevelOfDetail: false,
  7445. maximumScreenSpaceError: 2,
  7446. updateTransforms: true,
  7447. onTraversalEnd: () => {},
  7448. viewportTraversersMap: {},
  7449. basePath: ''
  7450. };
  7451. class TilesetTraverser {
  7452. constructor(options) {
  7453. _defineProperty(this, "options", void 0);
  7454. _defineProperty(this, "root", void 0);
  7455. _defineProperty(this, "requestedTiles", void 0);
  7456. _defineProperty(this, "selectedTiles", void 0);
  7457. _defineProperty(this, "emptyTiles", void 0);
  7458. _defineProperty(this, "_traversalStack", void 0);
  7459. _defineProperty(this, "_emptyTraversalStack", void 0);
  7460. _defineProperty(this, "_frameNumber", void 0);
  7461. this.options = { ...DEFAULT_PROPS$1,
  7462. ...options
  7463. };
  7464. this._traversalStack = new ManagedArray();
  7465. this._emptyTraversalStack = new ManagedArray();
  7466. this._frameNumber = null;
  7467. this.root = null;
  7468. this.selectedTiles = {};
  7469. this.requestedTiles = {};
  7470. this.emptyTiles = {};
  7471. }
  7472. traverse(root, frameState, options) {
  7473. this.root = root;
  7474. this.options = { ...this.options,
  7475. ...options
  7476. };
  7477. this.reset();
  7478. this.updateTile(root, frameState);
  7479. this._frameNumber = frameState.frameNumber;
  7480. this.executeTraversal(root, frameState);
  7481. }
  7482. reset() {
  7483. this.requestedTiles = {};
  7484. this.selectedTiles = {};
  7485. this.emptyTiles = {};
  7486. this._traversalStack.reset();
  7487. this._emptyTraversalStack.reset();
  7488. }
  7489. executeTraversal(root, frameState) {// 遍历root
  7490. const stack = this._traversalStack;
  7491. root._selectionDepth = 1;
  7492. stack.push(root);
  7493. while (stack.length > 0) {
  7494. const tile = stack.pop();
  7495. let shouldRefine = false;
  7496. // !zeg改 循环遍历子tile, maxDepth用来限制可加载的最大深度
  7497. if (this.canTraverse(tile, frameState) && (tile.depth < /* this.options. */maxDepth || tile.type != 'scenegraph' )) {//add maxDepth 是否继续遍历子集
  7498. this.updateChildTiles(tile, frameState);
  7499. shouldRefine = this.updateAndPushChildren(tile, frameState, stack, tile.hasRenderContent ? tile._selectionDepth + 1 : tile._selectionDepth);
  7500. }
  7501. const parent = tile.parent;
  7502. const parentRefines = Boolean(!parent || parent._shouldRefine);
  7503. const stoppedRefining = !shouldRefine;
  7504. if (!tile.hasRenderContent) {
  7505. this.emptyTiles[tile.id] = tile;
  7506. this.loadTile(tile, frameState);
  7507. if (stoppedRefining) {
  7508. this.selectTile(tile, frameState);
  7509. }
  7510. } else if (tile.refine === TILE_REFINEMENT.ADD) {
  7511. this.loadTile(tile, frameState);
  7512. this.selectTile(tile, frameState);
  7513. } else if (tile.refine === TILE_REFINEMENT.REPLACE) {
  7514. this.loadTile(tile, frameState);
  7515. if (stoppedRefining) {
  7516. this.selectTile(tile, frameState);
  7517. }
  7518. }
  7519. this.touchTile(tile, frameState);
  7520. tile._shouldRefine = shouldRefine && parentRefines;
  7521. }
  7522. this.options.onTraversalEnd(frameState);
  7523. }
  7524. updateChildTiles(tile, frameState) {
  7525. const children = tile.children;
  7526. for (const child of children) {
  7527. this.updateTile(child, frameState);
  7528. }
  7529. return true;
  7530. }
  7531. updateAndPushChildren(tile, frameState, stack, depth) {
  7532. const {
  7533. loadSiblings,
  7534. skipLevelOfDetail
  7535. } = this.options;
  7536. const children = tile.children;
  7537. children.sort(this.compareDistanceToCamera.bind(this));
  7538. const checkRefines = tile.refine === TILE_REFINEMENT.REPLACE && tile.hasRenderContent && !skipLevelOfDetail;
  7539. let hasVisibleChild = false;
  7540. let refines = true;
  7541. for (const child of children) {
  7542. child._selectionDepth = depth;
  7543. if (child.isVisibleAndInRequestVolume) {
  7544. if (stack.find(child)) {
  7545. stack.delete(child);
  7546. }
  7547. stack.push(child);
  7548. hasVisibleChild = true;
  7549. } else if (checkRefines || loadSiblings) {
  7550. this.loadTile(child, frameState);
  7551. this.touchTile(child, frameState);
  7552. }
  7553. if (checkRefines) {
  7554. let childRefines;
  7555. if (!child._inRequestVolume) {
  7556. childRefines = false;
  7557. } else if (!child.hasRenderContent) {
  7558. childRefines = this.executeEmptyTraversal(child, frameState);
  7559. } else {
  7560. childRefines = child.contentAvailable;
  7561. }
  7562. refines = refines && childRefines;
  7563. if (!refines) {
  7564. return false;
  7565. }
  7566. }
  7567. }
  7568. if (!hasVisibleChild) {
  7569. refines = false;
  7570. }
  7571. return refines;
  7572. }
  7573. updateTile(tile, frameState) {
  7574. this.updateTileVisibility(tile, frameState);
  7575. }
  7576. selectTile(tile, frameState) {
  7577. if (this.shouldSelectTile(tile)) {
  7578. tile._selectedFrame = frameState.frameNumber;
  7579. this.selectedTiles[tile.id] = tile;
  7580. }
  7581. }
  7582. loadTile(tile, frameState) {
  7583. if (this.shouldLoadTile(tile)) {
  7584. tile._requestedFrame = frameState.frameNumber;
  7585. tile._priority = tile._getPriority();
  7586. this.requestedTiles[tile.id] = tile;
  7587. }
  7588. }
  7589. touchTile(tile, frameState) {
  7590. tile.tileset._cache.touch(tile);
  7591. tile._touchedFrame = frameState.frameNumber;
  7592. }
  7593. canTraverse(tile, frameState, useParentMetric = false, ignoreVisibility = false) {
  7594. if (!tile.hasChildren) {
  7595. return false;
  7596. }
  7597. if (tile.hasTilesetContent) {
  7598. return !tile.contentExpired;
  7599. }
  7600. if (!ignoreVisibility && !tile.isVisibleAndInRequestVolume) {
  7601. return false;
  7602. }
  7603. return this.shouldRefine(tile, frameState, useParentMetric);
  7604. }
  7605. shouldLoadTile(tile) {
  7606. return tile.hasUnloadedContent || tile.contentExpired;
  7607. }
  7608. shouldSelectTile(tile) {
  7609. return tile.contentAvailable && !this.options.skipLevelOfDetail;
  7610. }
  7611. shouldRefine(tile, frameState, useParentMetric) {
  7612. let screenSpaceError = tile._screenSpaceError;
  7613. if (useParentMetric) {
  7614. screenSpaceError = tile.getScreenSpaceError(frameState, true);
  7615. }
  7616. return screenSpaceError > this.options.maximumScreenSpaceError;
  7617. }
  7618. updateTileVisibility(tile, frameState) {
  7619. const viewportIds = [];
  7620. if (this.options.viewportTraversersMap) {
  7621. for (const key in this.options.viewportTraversersMap) {
  7622. const value = this.options.viewportTraversersMap[key];
  7623. if (value === frameState.viewport.id) {
  7624. viewportIds.push(key);
  7625. }
  7626. }
  7627. } else {
  7628. viewportIds.push(frameState.viewport.id);
  7629. }
  7630. tile.updateVisibility(frameState, viewportIds);
  7631. }
  7632. compareDistanceToCamera(b, a) {
  7633. return b._distanceToCamera - a._distanceToCamera;
  7634. }
  7635. anyChildrenVisible(tile, frameState) {
  7636. let anyVisible = false;
  7637. for (const child of tile.children) {
  7638. child.updateVisibility(frameState);
  7639. anyVisible = anyVisible || child.isVisibleAndInRequestVolume;
  7640. }
  7641. return anyVisible;
  7642. }
  7643. executeEmptyTraversal(root, frameState) {
  7644. let allDescendantsLoaded = true;
  7645. const stack = this._emptyTraversalStack;
  7646. stack.push(root);
  7647. while (stack.length > 0 && allDescendantsLoaded) {
  7648. const tile = stack.pop();
  7649. this.updateTile(tile, frameState);
  7650. if (!tile.isVisibleAndInRequestVolume) {
  7651. this.loadTile(tile, frameState);
  7652. }
  7653. this.touchTile(tile, frameState);
  7654. const traverse = !tile.hasRenderContent && this.canTraverse(tile, frameState, false, true);
  7655. if (traverse) {
  7656. const children = tile.children;
  7657. for (const child of children) {
  7658. if (stack.find(child)) {
  7659. stack.delete(child);
  7660. }
  7661. stack.push(child);
  7662. }
  7663. } else if (!tile.contentAvailable) {
  7664. allDescendantsLoaded = false;
  7665. }
  7666. }
  7667. return allDescendantsLoaded;
  7668. }
  7669. }
  7670. const scratchVector = new Vector3();
  7671. function defined$2(x) {
  7672. return x !== undefined && x !== null;
  7673. }
  7674. class TileHeader {
  7675. constructor(tileset, header, parentHeader, extendedId = '') {
  7676. _defineProperty(this, "tileset", void 0);
  7677. _defineProperty(this, "header", void 0);
  7678. _defineProperty(this, "id", void 0);
  7679. _defineProperty(this, "url", void 0);
  7680. _defineProperty(this, "parent", void 0);
  7681. _defineProperty(this, "refine", void 0);
  7682. _defineProperty(this, "type", void 0);
  7683. _defineProperty(this, "contentUrl", void 0);
  7684. _defineProperty(this, "lodMetricType", void 0);
  7685. _defineProperty(this, "lodMetricValue", void 0);
  7686. _defineProperty(this, "boundingVolume", void 0);
  7687. _defineProperty(this, "content", void 0);
  7688. _defineProperty(this, "contentState", void 0);
  7689. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  7690. _defineProperty(this, "children", void 0);
  7691. _defineProperty(this, "depth", void 0);
  7692. _defineProperty(this, "viewportIds", void 0);
  7693. _defineProperty(this, "transform", void 0);
  7694. _defineProperty(this, "extensions", void 0);
  7695. _defineProperty(this, "userData", void 0);
  7696. _defineProperty(this, "computedTransform", void 0);
  7697. _defineProperty(this, "hasEmptyContent", void 0);
  7698. _defineProperty(this, "hasTilesetContent", void 0);
  7699. _defineProperty(this, "traverser", void 0);
  7700. _defineProperty(this, "_cacheNode", void 0);
  7701. _defineProperty(this, "_frameNumber", void 0);
  7702. _defineProperty(this, "_lodJudge", void 0);
  7703. _defineProperty(this, "_expireDate", void 0);
  7704. _defineProperty(this, "_expiredContent", void 0);
  7705. _defineProperty(this, "_shouldRefine", void 0);
  7706. _defineProperty(this, "_distanceToCamera", void 0);
  7707. _defineProperty(this, "_centerZDepth", void 0);
  7708. _defineProperty(this, "_screenSpaceError", void 0);
  7709. _defineProperty(this, "_visibilityPlaneMask", void 0);
  7710. _defineProperty(this, "_visible", void 0);
  7711. _defineProperty(this, "_inRequestVolume", void 0);
  7712. _defineProperty(this, "_stackLength", void 0);
  7713. _defineProperty(this, "_selectionDepth", void 0);
  7714. _defineProperty(this, "_touchedFrame", void 0);
  7715. _defineProperty(this, "_visitedFrame", void 0);
  7716. _defineProperty(this, "_selectedFrame", void 0);
  7717. _defineProperty(this, "_requestedFrame", void 0);
  7718. _defineProperty(this, "_priority", void 0);
  7719. _defineProperty(this, "_contentBoundingVolume", void 0);
  7720. _defineProperty(this, "_viewerRequestVolume", void 0);
  7721. _defineProperty(this, "_initialTransform", void 0);
  7722. _defineProperty(this, "tilesetMatrix", void 0);//add
  7723. _defineProperty(this, "tileContent", void 0);//add
  7724. _defineProperty(this, "contentTransform", void 0);//add
  7725. _defineProperty(this, "volumeBox", void 0);//add
  7726. _defineProperty(this, "boundUntransformed", void 0);//add
  7727. _defineProperty(this, "rtcCenterState", rtcCenterGlobal);//add 初始时的状态,当mesh加载完检查下
  7728. this.header = header;
  7729. this.tileset = tileset;
  7730. this.id = extendedId || header.id;
  7731. this.url = header.url;
  7732. this.parent = parentHeader;
  7733. this.refine = this._getRefine(header.refine);
  7734. this.type = header.type;
  7735. this.contentUrl = header.contentUrl;
  7736. this.lodMetricType = 'geometricError';
  7737. this.lodMetricValue = 0;
  7738. this.boundingVolume = null;
  7739. this.content = null;
  7740. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7741. this.gpuMemoryUsageInBytes = 0;
  7742. this.children = [];
  7743. this.hasEmptyContent = false;
  7744. this.hasTilesetContent = false;
  7745. this.depth = 0;
  7746. this.viewportIds = [];
  7747. this.userData = {};
  7748. this.extensions = null;
  7749. this._priority = 0;
  7750. this._touchedFrame = 0;
  7751. this._visitedFrame = 0;
  7752. this._selectedFrame = 0;
  7753. this._requestedFrame = 0;
  7754. this._screenSpaceError = 0;
  7755. this._cacheNode = null;
  7756. this._frameNumber = null;
  7757. this._cacheNode = null;
  7758. this.traverser = new TilesetTraverser({});
  7759. this._shouldRefine = false;
  7760. this._distanceToCamera = 0;
  7761. this._centerZDepth = 0;
  7762. this._visible = undefined;
  7763. this._inRequestVolume = false;
  7764. this._stackLength = 0;
  7765. this._selectionDepth = 0;
  7766. this._initialTransform = new Matrix4();
  7767. this.transform = new Matrix4();
  7768. this._initializeLodMetric(header);
  7769. this._initializeTransforms(header);
  7770. this._initializeBoundingVolumes(header);
  7771. this._initializeContent(header);
  7772. this._initializeRenderingState(header);
  7773. this._lodJudge = null;
  7774. this._expireDate = null;
  7775. this._expiredContent = null;
  7776. Object.seal(this);
  7777. }
  7778. destroy() {
  7779. this.header = null;
  7780. }
  7781. isDestroyed() {
  7782. return this.header === null;
  7783. }
  7784. get selected() {
  7785. return this._selectedFrame === this.tileset._frameNumber;
  7786. }
  7787. get isVisible() {
  7788. return this._visible;
  7789. }
  7790. get isVisibleAndInRequestVolume() {
  7791. let v = /* this._visible && */this.tileset.visible && this._inRequestVolume; //用_updateBoundingVolume这个算的在相机靠近时不准确,容易缺块
  7792. if(window.tileVisi2)v = this._visible && v
  7793. return v
  7794. }
  7795. get hasRenderContent() {
  7796. return !this.hasEmptyContent && !this.hasTilesetContent;
  7797. }
  7798. get hasChildren() {
  7799. return this.children.length > 0 || this.header.children && this.header.children.length > 0;
  7800. }
  7801. get contentReady() {
  7802. return this.contentState === TILE_CONTENT_STATE.READY || this.hasEmptyContent;
  7803. }
  7804. get contentAvailable() {
  7805. return Boolean(this.contentReady && this.hasRenderContent || this._expiredContent && !this.contentFailed);
  7806. }
  7807. get hasUnloadedContent() {
  7808. return this.hasRenderContent && this.contentUnloaded;
  7809. }
  7810. get contentUnloaded() {
  7811. return this.contentState === TILE_CONTENT_STATE.UNLOADED;
  7812. }
  7813. get contentExpired() {
  7814. return this.contentState === TILE_CONTENT_STATE.EXPIRED;
  7815. }
  7816. get contentFailed() {
  7817. return this.contentState === TILE_CONTENT_STATE.FAILED;
  7818. }
  7819. getScreenSpaceError(frameState, useParentLodMetric) {
  7820. switch (this.tileset.type) {
  7821. case TILESET_TYPE.I3S:
  7822. return getProjectedRadius(this, frameState);
  7823. case TILESET_TYPE.TILES3D:
  7824. return getTiles3DScreenSpaceError(this, frameState, useParentLodMetric);
  7825. default:
  7826. throw new Error('Unsupported tileset type');
  7827. }
  7828. }
  7829. _getPriority() {
  7830. const traverser = this.tileset._traverser;
  7831. const {
  7832. skipLevelOfDetail
  7833. } = traverser.options;
  7834. const maySkipTile = this.refine === TILE_REFINEMENT.ADD || skipLevelOfDetail;
  7835. if (maySkipTile && !this.isVisible && this._visible !== undefined) {
  7836. return -1;
  7837. }
  7838. if (this.tileset._frameNumber - this._touchedFrame >= 1) {
  7839. return -1;
  7840. }
  7841. if (this.contentState === TILE_CONTENT_STATE.UNLOADED) {
  7842. return -1;
  7843. }
  7844. const parent = this.parent;
  7845. const useParentScreenSpaceError = parent && (!maySkipTile || this._screenSpaceError === 0.0 || parent.hasTilesetContent);
  7846. const screenSpaceError = useParentScreenSpaceError ? parent._screenSpaceError : this._screenSpaceError;
  7847. const rootScreenSpaceError = traverser.root ? traverser.root._screenSpaceError : 0.0;
  7848. let v = Math.max(rootScreenSpaceError - screenSpaceError, 0);
  7849. if(!this._visible){
  7850. v = THREE.Math.clamp(v * 0.1, -0.9, 100);//xzw add 因为this._visible我也令其显示所以这里降低这些的优先级
  7851. }
  7852. return v
  7853. }
  7854. async loadContent() {
  7855. if (this.hasEmptyContent) {
  7856. return false;
  7857. }
  7858. if (this.content) {
  7859. return true;
  7860. }
  7861. const expired = this.contentExpired;
  7862. if (expired) {
  7863. this._expireDate = null;
  7864. }
  7865. this.contentState = TILE_CONTENT_STATE.LOADING;
  7866. const requestToken = await this.tileset._requestScheduler.scheduleRequest(this.id, this._getPriority.bind(this));
  7867. if (!requestToken) {
  7868. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7869. return false;
  7870. }
  7871. try {
  7872. const contentUrl = this.tileset.getTileUrl(this.contentUrl)+ `?_=${this.tileset.options.updateTime}` // !zeg改 添加version后缀 原:imageVersion
  7873. const loader = this.tileset.loader;
  7874. const options = { ...this.tileset.loadOptions,
  7875. [loader.id]: { ...this.tileset.loadOptions[loader.id],
  7876. isTileset: this.type === 'json',
  7877. ...this._getLoaderSpecificOptions(loader.id)
  7878. }
  7879. };
  7880. this.content = await load(contentUrl, loader, options);
  7881. // !zeg改
  7882. if (/* this.tileset.options. */maxDepth < this.depth && this.type == 'scenegraph') {//有的场景depth为1的不是mesh,只是json,即实际最低depth>1
  7883. this.unloadContent()
  7884. return false
  7885. }
  7886. if (this.tileset.options.contentLoader) {
  7887. await this.tileset.options.contentLoader(this);
  7888. }
  7889. if (this._isTileset()) {
  7890. this.tileset._initializeTileHeaders(this.content, this);
  7891. }
  7892. this.contentState = TILE_CONTENT_STATE.READY;
  7893. this._onContentLoaded();
  7894. return true;
  7895. } catch (error) {
  7896. this.contentState = TILE_CONTENT_STATE.FAILED;
  7897. throw error;
  7898. } finally {
  7899. requestToken.done();
  7900. }
  7901. }
  7902. unloadContent() {
  7903. if (this.content && this.content.destroy) {
  7904. this.content.destroy();
  7905. }
  7906. this.content = null;
  7907. if (this.header.content && this.header.content.destroy) {
  7908. this.header.content.destroy();
  7909. }
  7910. this.header.content = null;
  7911. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  7912. return true;
  7913. }
  7914. updateVisibility(frameState, viewportIds) {
  7915. if (this._frameNumber === frameState.frameNumber) {
  7916. return;
  7917. }
  7918. const parent = this.parent;
  7919. const parentVisibilityPlaneMask = parent ? parent._visibilityPlaneMask : CullingVolume.MASK_INDETERMINATE;
  7920. if (this.tileset._traverser.options.updateTransforms) {
  7921. const parentTransform = parent ? parent.computedTransform : new Matrix4().elements //this.tileset.modelMatrix; 改:去掉左乘modelMatrix
  7922. this._updateTransform(parentTransform);
  7923. }
  7924. this._distanceToCamera = this.distanceToTile(frameState);
  7925. this._screenSpaceError = this.getScreenSpaceError(frameState, false);
  7926. this._visibilityPlaneMask = this.visibility(frameState, parentVisibilityPlaneMask);
  7927. this._visible = this._visibilityPlaneMask !== CullingVolume.MASK_OUTSIDE;
  7928. this._inRequestVolume = this.insideViewerRequestVolume(frameState);
  7929. this._frameNumber = frameState.frameNumber;
  7930. this.viewportIds = viewportIds;
  7931. }
  7932. visibility(frameState, parentVisibilityPlaneMask) {
  7933. const {
  7934. cullingVolume
  7935. } = frameState;
  7936. const {
  7937. boundingVolume
  7938. } = this;
  7939. return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume, parentVisibilityPlaneMask);
  7940. }
  7941. contentVisibility() {
  7942. return true;
  7943. }
  7944. distanceToTile(frameState) {
  7945. const boundingVolume = this.boundingVolume;
  7946. return Math.sqrt(Math.max(boundingVolume.distanceSquaredTo(frameState.camera.position), 0));
  7947. }
  7948. cameraSpaceZDepth({
  7949. camera
  7950. }) {
  7951. const boundingVolume = this.boundingVolume;
  7952. scratchVector.subVectors(boundingVolume.center, camera.position);
  7953. return camera.direction.dot(scratchVector);
  7954. }
  7955. insideViewerRequestVolume(frameState) {
  7956. const viewerRequestVolume = this._viewerRequestVolume;
  7957. return !viewerRequestVolume || viewerRequestVolume.distanceSquaredTo(frameState.camera.position) <= 0;
  7958. }
  7959. updateExpiration() {
  7960. if (defined$2(this._expireDate) && this.contentReady && !this.hasEmptyContent) {
  7961. const now = Date.now();
  7962. if (Date.lessThan(this._expireDate, now)) {
  7963. this.contentState = TILE_CONTENT_STATE.EXPIRED;
  7964. this._expiredContent = this.content;
  7965. }
  7966. }
  7967. }
  7968. get extras() {
  7969. return this.header.extras;
  7970. }
  7971. _initializeLodMetric(header) {
  7972. if ('lodMetricType' in header) {
  7973. this.lodMetricType = header.lodMetricType;
  7974. } else {
  7975. this.lodMetricType = this.parent && this.parent.lodMetricType || this.tileset.lodMetricType;
  7976. console.warn("3D Tile: Required prop lodMetricType is undefined. Using parent lodMetricType");
  7977. }
  7978. if ('lodMetricValue' in header) {
  7979. this.lodMetricValue = header.lodMetricValue;
  7980. } else {
  7981. this.lodMetricValue = this.parent && this.parent.lodMetricValue || this.tileset.lodMetricValue;
  7982. console.warn('3D Tile: Required prop lodMetricValue is undefined. Using parent lodMetricValue');
  7983. }
  7984. }
  7985. _initializeTransforms(tileHeader) {
  7986. this.transform = tileHeader.transform ? new Matrix4(tileHeader.transform) : new Matrix4();
  7987. const parent = this.parent;
  7988. const tileset = this.tileset;
  7989. const parentTransform = parent && parent.computedTransform ? parent.computedTransform.clone() : new Matrix4().elements // tileset.modelMatrix.clone(); 改:去掉左乘modelMatrix
  7990. this.computedTransform = new Matrix4(parentTransform).multiplyRight(this.transform);
  7991. const parentInitialTransform = parent && parent._initialTransform ? parent._initialTransform.clone() : new Matrix4();
  7992. this._initialTransform = new Matrix4(parentInitialTransform).multiplyRight(this.transform);
  7993. }
  7994. _initializeBoundingVolumes(tileHeader) {
  7995. this._contentBoundingVolume = null;
  7996. this._viewerRequestVolume = null;
  7997. this._updateBoundingVolume(tileHeader);
  7998. }
  7999. _initializeContent(tileHeader) {
  8000. this.content = {
  8001. _tileset: this.tileset,
  8002. _tile: this
  8003. };
  8004. this.hasEmptyContent = true;
  8005. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  8006. this.hasTilesetContent = false;
  8007. if (tileHeader.contentUrl) {
  8008. this.content = null;
  8009. this.hasEmptyContent = false;
  8010. }
  8011. }
  8012. _initializeRenderingState(header) {
  8013. this.depth = header.level || (this.parent ? this.parent.depth + 1 : 0);
  8014. this._shouldRefine = false;
  8015. this._distanceToCamera = 0;
  8016. this._centerZDepth = 0;
  8017. this._screenSpaceError = 0;
  8018. this._visibilityPlaneMask = CullingVolume.MASK_INDETERMINATE;
  8019. this._visible = undefined;
  8020. this._inRequestVolume = false;
  8021. this._stackLength = 0;
  8022. this._selectionDepth = 0;
  8023. this._frameNumber = 0;
  8024. this._touchedFrame = 0;
  8025. this._visitedFrame = 0;
  8026. this._selectedFrame = 0;
  8027. this._requestedFrame = 0;
  8028. this._priority = 0.0;
  8029. }
  8030. _getRefine(refine) {
  8031. return refine || this.parent && this.parent.refine || TILE_REFINEMENT.REPLACE;
  8032. }
  8033. _isTileset() {
  8034. return this.contentUrl.indexOf('.json') !== -1;
  8035. }
  8036. _onContentLoaded() {
  8037. switch (this.content && this.content.type) {
  8038. case 'vctr':
  8039. case 'geom':
  8040. this.tileset._traverser.disableSkipLevelOfDetail = true;
  8041. break;
  8042. }
  8043. if (this._isTileset()) {
  8044. this.hasTilesetContent = true;
  8045. }
  8046. }
  8047. _updateBoundingVolume(header) {
  8048. let computedTransform
  8049. if(header.id == 'root_0' || !header.id){
  8050. console.log('root_0')
  8051. }
  8052. if(!this.tileset.lastRootTransform){//没事过后会因_updateTransform重算
  8053. computedTransform = new Matrix4(this.tileset.modelMatrix).multiplyRight(this.computedTransform); //add
  8054. }else{
  8055. computedTransform = new Matrix4(new Matrix4$1().multiplyMatrices(this.tileset.lastRootTransform, this.getContentTransform()).elements)
  8056. }
  8057. this.boundingVolume = createBoundingVolume(header.boundingVolume, computedTransform/* this.computedTransform */, this.boundingVolume);
  8058. const content = header.content;
  8059. if (!content) {
  8060. return;
  8061. }
  8062. if (content.boundingVolume) {
  8063. this._contentBoundingVolume = createBoundingVolume(content.boundingVolume, computedTransform, this._contentBoundingVolume);
  8064. }
  8065. if (header.viewerRequestVolume) {
  8066. this._viewerRequestVolume = createBoundingVolume(header.viewerRequestVolume, computedTransform, this._viewerRequestVolume);
  8067. }
  8068. }
  8069. getBoundUntransformed(){//add 这个会在mesh加载好后才会执行
  8070. if(!this.contentTransform){
  8071. console.error('?')
  8072. }
  8073. this.getContentTransform()
  8074. let computedTransform2 = new Matrix4(this.contentTransform.elements)
  8075. this.boundUntransformed = createBoundingVolume(this.header.boundingVolume, computedTransform2 , this.boundUntransformed);//add
  8076. return this.boundUntransformed
  8077. }
  8078. getContentTransform(force){ //add 获取该tile在创建boundingVolume时需要的matrix,不包含最外层对整体模型的变换.
  8079. let rtcCenter, contentTransform
  8080. if(this.contentTransform && !force){//无需更新
  8081. return this.contentTransform.clone()
  8082. }
  8083. if(!this.tileset.tileTransInvert){
  8084. this.tileset.tileTransInvert = new Matrix4()
  8085. }
  8086. this.contentTransform = new Matrix4$1().fromArray(this.computedTransform).premultiply(new Matrix4$1().fromArray(this.tileset.tileTransInvert))
  8087. if(this.tileContent){
  8088. rtcCenter = this.content.rtcCenter
  8089. }else{
  8090. rtcCenter = this.rtcCenterState
  8091. }
  8092. if(!rtcCenter) {
  8093. let tranM = new Matrix4$1()
  8094. tranM.makeScale(1,1,-1)//大部分是这种情况. 就是因为这个变换才加的这个函数,之前bounding没考虑这个不准。不知道为什么原生的代码不用scaleZ
  8095. this.contentTransform.premultiply(tranM)
  8096. }
  8097. //如果有rtcCenter的话一开始boundingVolume不准?会不会有显示问题?
  8098. return this.contentTransform.clone()
  8099. }
  8100. _updateTransform(parentTransform = new Matrix4()) {
  8101. const computedTransform = parentTransform.clone().multiplyRight(this.transform);
  8102. const didTransformChange = !computedTransform.equals(this.computedTransform) || !this.tilesetMatrix || !this.tilesetMatrix.equals(this.tileset.modelMatrix) //改 后面加了两个判断,为了在模型移动后更新_updateBoundingVolume
  8103. if (!didTransformChange) {
  8104. return;
  8105. }
  8106. this.tileset.modelMatrix
  8107. this.computedTransform = computedTransform;
  8108. this.tilesetMatrix = this.tileset.modelMatrix; //add 标记
  8109. this._updateBoundingVolume(this.header);
  8110. }
  8111. _getLoaderSpecificOptions(loaderId) {
  8112. switch (loaderId) {
  8113. case 'i3s':
  8114. return { ...this.tileset.options.i3s,
  8115. tile: this.header,
  8116. tileset: this.tileset.tileset,
  8117. isTileHeader: false
  8118. };
  8119. case '3d-tiles':
  8120. case 'cesium-ion':
  8121. default:
  8122. return get3dTilesOptions(this.tileset.tileset);
  8123. }
  8124. }
  8125. }
  8126. class Tileset3DTraverser extends TilesetTraverser {
  8127. compareDistanceToCamera(a, b) {
  8128. return b._distanceToCamera === 0 && a._distanceToCamera === 0 ? b._centerZDepth - a._centerZDepth : b._distanceToCamera - a._distanceToCamera;
  8129. }
  8130. updateTileVisibility(tile, frameState) {
  8131. super.updateTileVisibility(tile, frameState);
  8132. if (!tile.isVisibleAndInRequestVolume) {
  8133. return;
  8134. }
  8135. const hasChildren = tile.children.length > 0;
  8136. if (tile.hasTilesetContent && hasChildren) {
  8137. const firstChild = tile.children[0];
  8138. this.updateTileVisibility(firstChild, frameState);
  8139. tile._visible = firstChild._visible;
  8140. return;
  8141. }
  8142. if (this.meetsScreenSpaceErrorEarly(tile, frameState)) {
  8143. tile._visible = false;
  8144. return;
  8145. }
  8146. const replace = tile.refine === TILE_REFINEMENT.REPLACE;
  8147. const useOptimization = tile._optimChildrenWithinParent === TILE3D_OPTIMIZATION_HINT.USE_OPTIMIZATION;
  8148. if (replace && useOptimization && hasChildren) {
  8149. if (!this.anyChildrenVisible(tile, frameState)) {
  8150. tile._visible = false;
  8151. return;
  8152. }
  8153. }
  8154. }
  8155. meetsScreenSpaceErrorEarly(tile, frameState) {
  8156. const {
  8157. parent
  8158. } = tile;
  8159. if (!parent || parent.hasTilesetContent || parent.refine !== TILE_REFINEMENT.ADD) {
  8160. return false;
  8161. }
  8162. return !this.shouldRefine(tile, frameState, true);
  8163. }
  8164. }
  8165. const STATUS = {
  8166. REQUESTED: 'REQUESTED',
  8167. COMPLETED: 'COMPLETED',
  8168. ERROR: 'ERROR'
  8169. };
  8170. class I3STileManager {
  8171. constructor() {
  8172. _defineProperty(this, "_statusMap", void 0);
  8173. this._statusMap = {};
  8174. }
  8175. add(request, key, callback, frameState) {
  8176. if (!this._statusMap[key]) {
  8177. this._statusMap[key] = {
  8178. request,
  8179. callback,
  8180. key,
  8181. frameState,
  8182. status: STATUS.REQUESTED
  8183. };
  8184. request().then(data => {
  8185. this._statusMap[key].status = STATUS.COMPLETED;
  8186. this._statusMap[key].callback(data, frameState);
  8187. }).catch(error => {
  8188. this._statusMap[key].status = STATUS.ERROR;
  8189. callback(error);
  8190. });
  8191. }
  8192. }
  8193. update(key, frameState) {
  8194. if (this._statusMap[key]) {
  8195. this._statusMap[key].frameState = frameState;
  8196. }
  8197. }
  8198. find(key) {
  8199. return this._statusMap[key];
  8200. }
  8201. }
  8202. class I3STilesetTraverser extends TilesetTraverser {
  8203. constructor(options) {
  8204. super(options);
  8205. _defineProperty(this, "_tileManager", void 0);
  8206. this._tileManager = new I3STileManager();
  8207. }
  8208. shouldRefine(tile, frameState) {
  8209. tile._lodJudge = getLodStatus(tile, frameState);
  8210. return tile._lodJudge === 'DIG';
  8211. }
  8212. updateChildTiles(tile, frameState) {
  8213. const children = tile.header.children || [];
  8214. const childTiles = tile.children;
  8215. const tileset = tile.tileset;
  8216. for (const child of children) {
  8217. const extendedId = "".concat(child.id, "-").concat(frameState.viewport.id);
  8218. const childTile = childTiles && childTiles.find(t => t.id === extendedId);
  8219. if (!childTile) {
  8220. let request = () => this._loadTile(child.id, tileset);
  8221. const cachedRequest = this._tileManager.find(extendedId);
  8222. if (!cachedRequest) {
  8223. if (tileset.tileset.nodePages) {
  8224. request = () => tileset.tileset.nodePagesTile.formTileFromNodePages(child.id);
  8225. }
  8226. this._tileManager.add(request, extendedId, header => this._onTileLoad(header, tile, extendedId), frameState);
  8227. } else {
  8228. this._tileManager.update(extendedId, frameState);
  8229. }
  8230. } else if (childTile) {
  8231. this.updateTile(childTile, frameState);
  8232. }
  8233. }
  8234. return false;
  8235. }
  8236. async _loadTile(nodeId, tileset) {
  8237. const {
  8238. loader
  8239. } = tileset;
  8240. const nodeUrl = tileset.getTileUrl("".concat(tileset.url, "/nodes/").concat(nodeId));
  8241. const options = { ...tileset.loadOptions,
  8242. i3s: { ...tileset.loadOptions.i3s,
  8243. isTileHeader: true,
  8244. loadContent: false
  8245. }
  8246. };
  8247. return await load(nodeUrl, loader, options);
  8248. }
  8249. _onTileLoad(header, tile, extendedId) {
  8250. const childTile = new TileHeader(tile.tileset, header, tile, extendedId);
  8251. tile.children.push(childTile);
  8252. const frameState = this._tileManager.find(childTile.id).frameState;
  8253. this.updateTile(childTile, frameState);
  8254. if (this._frameNumber === frameState.frameNumber) {
  8255. this.executeTraversal(childTile, frameState);
  8256. }
  8257. }
  8258. }
  8259. const DEFAULT_PROPS = {
  8260. description: '',
  8261. ellipsoid: Ellipsoid.WGS84,
  8262. modelMatrix: new Matrix4(),
  8263. throttleRequests: true,
  8264. maxRequests: 64,
  8265. maximumMemoryUsage: 32,
  8266. onTileLoad: () => {},
  8267. onTileUnload: () => {},
  8268. onTileError: () => {},
  8269. onTraversalComplete: selectedTiles => selectedTiles,
  8270. contentLoader: undefined,
  8271. viewDistanceScale: 1.0,
  8272. maximumScreenSpaceError: 8,
  8273. loadTiles: true,
  8274. updateTransforms: true,
  8275. viewportTraversersMap: null,
  8276. loadOptions: {
  8277. fetch: {}
  8278. },
  8279. attributions: [],
  8280. basePath: '',
  8281. i3s: {}
  8282. };
  8283. const TILES_TOTAL = 'Tiles In Tileset(s)';
  8284. const TILES_IN_MEMORY = 'Tiles In Memory';
  8285. const TILES_IN_VIEW = 'Tiles In View';
  8286. const TILES_RENDERABLE = 'Tiles To Render';
  8287. const TILES_LOADED = 'Tiles Loaded';
  8288. const TILES_LOADING = 'Tiles Loading';
  8289. const TILES_UNLOADED = 'Tiles Unloaded';
  8290. const TILES_LOAD_FAILED = 'Failed Tile Loads';
  8291. const POINTS_COUNT = 'Points';
  8292. const TILES_GPU_MEMORY = 'Tile Memory Use';
  8293. let tilesetSid = 0//add
  8294. class Tileset3D extends EventDispatcher{//xzw add EventDispatcher
  8295. constructor(json, options) {
  8296. super()
  8297. viewer.visiVertexCount = viewer.visiVertexCount || 0
  8298. _defineProperty(this, "options", void 0);
  8299. _defineProperty(this, "loadOptions", void 0);
  8300. _defineProperty(this, "type", void 0);
  8301. _defineProperty(this, "tileset", void 0);
  8302. _defineProperty(this, "loader", void 0);
  8303. _defineProperty(this, "url", void 0);
  8304. _defineProperty(this, "basePath", void 0);
  8305. _defineProperty(this, "modelMatrix", void 0);
  8306. _defineProperty(this, "ellipsoid", void 0);
  8307. _defineProperty(this, "lodMetricType", void 0);
  8308. _defineProperty(this, "lodMetricValue", void 0);
  8309. _defineProperty(this, "refine", void 0);
  8310. _defineProperty(this, "root", void 0);
  8311. _defineProperty(this, "roots", void 0);
  8312. _defineProperty(this, "asset", void 0);
  8313. _defineProperty(this, "description", void 0);
  8314. _defineProperty(this, "properties", void 0);
  8315. _defineProperty(this, "extras", void 0);
  8316. _defineProperty(this, "attributions", void 0);
  8317. _defineProperty(this, "credits", void 0);
  8318. _defineProperty(this, "stats", void 0);
  8319. _defineProperty(this, "traverseCounter", void 0);
  8320. _defineProperty(this, "geometricError", void 0);
  8321. _defineProperty(this, "selectedTiles", void 0);
  8322. _defineProperty(this, "cartographicCenter", void 0);
  8323. _defineProperty(this, "cartesianCenter", void 0);
  8324. _defineProperty(this, "zoom", void 0);
  8325. _defineProperty(this, "boundingVolume", void 0);
  8326. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  8327. _defineProperty(this, "dynamicScreenSpaceErrorComputedDensity", void 0);
  8328. _defineProperty(this, "_traverser", void 0);
  8329. _defineProperty(this, "_cache", void 0);
  8330. _defineProperty(this, "_requestScheduler", void 0);
  8331. _defineProperty(this, "_frameNumber", void 0);
  8332. _defineProperty(this, "_queryParamsString", void 0);
  8333. _defineProperty(this, "_queryParams", void 0);
  8334. _defineProperty(this, "_extensionsUsed", void 0);
  8335. _defineProperty(this, "_tiles", void 0);
  8336. _defineProperty(this, "_pendingCount", void 0);
  8337. _defineProperty(this, "lastUpdatedVieports", void 0);
  8338. _defineProperty(this, "_requestedTiles", void 0);
  8339. _defineProperty(this, "_emptyTiles", void 0);
  8340. _defineProperty(this, "frameStateData", void 0);
  8341. _defineProperty(this, "maximumMemoryUsage", void 0);
  8342. _defineProperty(this, "visible", true);//add
  8343. assert$7(json);
  8344. this.options = { ...DEFAULT_PROPS,
  8345. ...options
  8346. };
  8347. this.tileset = json;
  8348. this.loader = json.loader;
  8349. this.type = json.type;
  8350. this.url = json.url;
  8351. this.basePath = json.basePath || dirname(this.url);
  8352. this.modelMatrix = this.options.modelMatrix;
  8353. this.ellipsoid = this.options.ellipsoid;
  8354. this.lodMetricType = json.lodMetricType;
  8355. this.lodMetricValue = json.lodMetricValue;
  8356. this.refine = json.root.refine;
  8357. this.loadOptions = this.options.loadOptions || {};
  8358. this.root = null;
  8359. this.roots = {};
  8360. this.cartographicCenter = null;
  8361. this.cartesianCenter = null;
  8362. this.zoom = 1;
  8363. this.boundingVolume = null;
  8364. this.traverseCounter = 0;
  8365. this.geometricError = 0;
  8366. this._traverser = this._initializeTraverser();
  8367. this._cache = new TilesetCache();
  8368. this._requestScheduler = new RequestScheduler({
  8369. throttleRequests: this.options.throttleRequests,
  8370. maxRequests: this.options.maxRequests
  8371. });
  8372. this._frameNumber = 0;
  8373. this._pendingCount = 0;
  8374. this._tiles = {};
  8375. this.selectedTiles = [];
  8376. this._emptyTiles = [];
  8377. this._requestedTiles = [];
  8378. this.frameStateData = {};
  8379. this.lastUpdatedVieports = null;
  8380. this._queryParams = {};
  8381. this._queryParamsString = '';
  8382. this.maximumMemoryUsage = this.options.maximumMemoryUsage || 32;
  8383. this.gpuMemoryUsageInBytes = 0;
  8384. this.stats = new Stats({
  8385. id: this.url
  8386. });
  8387. this._initializeStats();
  8388. this._extensionsUsed = undefined;
  8389. this.dynamicScreenSpaceErrorComputedDensity = 0.0;
  8390. this.extras = null;
  8391. this.asset = {};
  8392. this.credits = {};
  8393. this.description = this.options.description || '';
  8394. this._initializeTileSet(json);
  8395. }
  8396. destroy() {
  8397. this._destroy();
  8398. }
  8399. isLoaded() {
  8400. return this._pendingCount === 0 && this._frameNumber !== 0;
  8401. }
  8402. get tiles() {
  8403. return Object.values(this._tiles);
  8404. }
  8405. get frameNumber() {
  8406. return this._frameNumber;
  8407. }
  8408. get queryParams() {
  8409. if (!this._queryParamsString) {
  8410. this._queryParamsString = getQueryParamString(this._queryParams);
  8411. }
  8412. return this._queryParamsString;
  8413. }
  8414. setProps(props) {
  8415. this.options = { ...this.options,
  8416. ...props
  8417. };
  8418. }
  8419. setOptions(options) {
  8420. this.options = { ...this.options,
  8421. ...options
  8422. };
  8423. }
  8424. getTileUrl(tilePath) {
  8425. const isDataUrl = tilePath.startsWith('data:');
  8426. tilePath = Potree.Common.dealURL(tilePath) //add 去除'+'
  8427. if (isDataUrl) {
  8428. return tilePath;
  8429. }
  8430. return "".concat(tilePath).concat(this.queryParams);
  8431. }
  8432. hasExtension(extensionName) {
  8433. return Boolean(this._extensionsUsed && this._extensionsUsed.indexOf(extensionName) > -1);
  8434. }
  8435. update(viewports) {
  8436. if ('loadTiles' in this.options && !this.options.loadTiles) {
  8437. return;
  8438. }
  8439. if (this.traverseCounter > 0) {
  8440. return;
  8441. }
  8442. if (!viewports && this.lastUpdatedVieports) {
  8443. viewports = this.lastUpdatedVieports;
  8444. } else {
  8445. this.lastUpdatedVieports = viewports;
  8446. }
  8447. if (!(viewports instanceof Array)) {
  8448. viewports = [viewports];
  8449. }
  8450. this._cache.reset();
  8451. this._frameNumber++;
  8452. this.traverseCounter = viewports.length;
  8453. const viewportsToTraverse = [];
  8454. for (const viewport of viewports) {
  8455. const id = viewport.id;
  8456. if (this._needTraverse(id)) {
  8457. viewportsToTraverse.push(id);
  8458. } else {
  8459. this.traverseCounter--;
  8460. }
  8461. }
  8462. for (const viewport of viewports) {
  8463. const id = viewport.id;
  8464. if (!this.roots[id]) {
  8465. this.roots[id] = this._initializeTileHeaders(this.tileset, null);
  8466. }
  8467. if (!viewportsToTraverse.includes(id)) {
  8468. continue;
  8469. }
  8470. const frameState = getFrameState(viewport, this._frameNumber);
  8471. this._traverser.traverse(this.roots[id], frameState, this.options);
  8472. }
  8473. }
  8474. _needTraverse(viewportId) {
  8475. let traverserId = viewportId;
  8476. if (this.options.viewportTraversersMap) {
  8477. traverserId = this.options.viewportTraversersMap[viewportId];
  8478. }
  8479. if (traverserId !== viewportId) {
  8480. return false;
  8481. }
  8482. return true;
  8483. }
  8484. _onTraversalEnd(frameState) {
  8485. const id = frameState.viewport.id;
  8486. if (!this.frameStateData[id]) {
  8487. this.frameStateData[id] = {
  8488. selectedTiles: [],
  8489. _requestedTiles: [],
  8490. _emptyTiles: []
  8491. };
  8492. }
  8493. const currentFrameStateData = this.frameStateData[id];
  8494. const selectedTiles = Object.values(this._traverser.selectedTiles);
  8495. currentFrameStateData.selectedTiles = selectedTiles;
  8496. currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);
  8497. currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);
  8498. this.traverseCounter--;
  8499. if (this.traverseCounter > 0) {
  8500. return;
  8501. }
  8502. this._updateTiles();
  8503. }
  8504. _updateTiles() {
  8505. this.selectedTiles = [];
  8506. this._requestedTiles = [];
  8507. this._emptyTiles = [];
  8508. for (const frameStateKey in this.frameStateData) {
  8509. const frameStateDataValue = this.frameStateData[frameStateKey];
  8510. this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);
  8511. this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);
  8512. this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);
  8513. }
  8514. this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);
  8515. for (const tile of this.selectedTiles) {
  8516. this._tiles[tile.id] = tile;
  8517. }
  8518. this._loadTiles();
  8519. this._unloadTiles();
  8520. this._updateStats();
  8521. }
  8522. _tilesChanged(oldSelectedTiles, selectedTiles) {
  8523. if (oldSelectedTiles.length !== selectedTiles.length) {
  8524. return true;
  8525. }
  8526. const set1 = new Set(oldSelectedTiles.map(t => t.id));
  8527. const set2 = new Set(selectedTiles.map(t => t.id));
  8528. let changed = oldSelectedTiles.filter(x => !set2.has(x.id)).length > 0;
  8529. changed = changed || selectedTiles.filter(x => !set1.has(x.id)).length > 0;
  8530. return changed;
  8531. }
  8532. _loadTiles() {
  8533. for (const tile of this._requestedTiles) {
  8534. if (tile.contentUnloaded) {
  8535. this._loadTile(tile);
  8536. }
  8537. }
  8538. }
  8539. _unloadTiles() {
  8540. this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));
  8541. }
  8542. _updateStats() {
  8543. let tilesRenderable = 0;
  8544. let pointsRenderable = 0;
  8545. for (const tile of this.selectedTiles) {
  8546. if (tile.contentAvailable && tile.content) {
  8547. tilesRenderable++;
  8548. if (tile.content.pointCount) {
  8549. pointsRenderable += tile.content.pointCount;
  8550. }
  8551. }
  8552. }
  8553. this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;
  8554. this.stats.get(TILES_RENDERABLE).count = tilesRenderable;
  8555. this.stats.get(POINTS_COUNT).count = pointsRenderable;
  8556. }
  8557. _initializeTileSet(tilesetJson) {
  8558. this.root = this._initializeTileHeaders(tilesetJson, null);
  8559. if (this.type === TILESET_TYPE.TILES3D) {
  8560. this._initializeCesiumTileset(tilesetJson);
  8561. }
  8562. if (this.type === TILESET_TYPE.I3S) {
  8563. this._initializeI3STileset();
  8564. }
  8565. this._calculateViewProps();
  8566. }
  8567. _calculateViewProps() {
  8568. const root = this.root;
  8569. assert$7(root);
  8570. const {
  8571. center
  8572. } = root.boundingVolume;
  8573. if (!center) {
  8574. console.warn('center was not pre-calculated for the root tile');
  8575. this.cartographicCenter = new Vector3();
  8576. this.zoom = 1;
  8577. return;
  8578. }
  8579. this.cartographicCenter = Ellipsoid.WGS84.cartesianToCartographic(center, new Vector3());
  8580. this.cartesianCenter = center;
  8581. this.zoom = getZoomFromBoundingVolume(root.boundingVolume);
  8582. }
  8583. _initializeStats() {
  8584. this.stats.get(TILES_TOTAL);
  8585. this.stats.get(TILES_LOADING);
  8586. this.stats.get(TILES_IN_MEMORY);
  8587. this.stats.get(TILES_IN_VIEW);
  8588. this.stats.get(TILES_RENDERABLE);
  8589. this.stats.get(TILES_LOADED);
  8590. this.stats.get(TILES_UNLOADED);
  8591. this.stats.get(TILES_LOAD_FAILED);
  8592. this.stats.get(POINTS_COUNT, 'memory');
  8593. this.stats.get(TILES_GPU_MEMORY, 'memory');
  8594. }
  8595. _initializeTileHeaders(tilesetJson, parentTileHeader) {
  8596. const rootTile = new TileHeader(this, tilesetJson.root, parentTileHeader, parentTileHeader == void 0 && 'root_'+tilesetSid++);
  8597. if (parentTileHeader) {
  8598. parentTileHeader.children.push(rootTile);
  8599. rootTile.depth = parentTileHeader.depth + 1;
  8600. }
  8601. if (this.type === TILESET_TYPE.TILES3D) {
  8602. const stack = [];
  8603. stack.push(rootTile);
  8604. while (stack.length > 0) {
  8605. const tile = stack.pop();
  8606. this.stats.get(TILES_TOTAL).incrementCount();
  8607. const children = tile.header.children || [];
  8608. // !zeg改
  8609. if(tile.depth < /* this.options. */maxDepth){
  8610. for (const childHeader of children) {
  8611. const childTile = new TileHeader(this, childHeader, tile);
  8612. tile.children.push(childTile);
  8613. childTile.depth = tile.depth + 1;
  8614. stack.push(childTile);
  8615. }
  8616. }
  8617. window.maxTileDepth = Math.max(window.maxTileDepth||0, tile.depth)
  8618. }
  8619. }
  8620. return rootTile;
  8621. }
  8622. _initializeTraverser() {
  8623. let TraverserClass;
  8624. const type = this.type;
  8625. switch (type) {
  8626. case TILESET_TYPE.TILES3D:
  8627. TraverserClass = Tileset3DTraverser;
  8628. break;
  8629. case TILESET_TYPE.I3S:
  8630. TraverserClass = I3STilesetTraverser;
  8631. break;
  8632. default:
  8633. TraverserClass = TilesetTraverser;
  8634. }
  8635. return new TraverserClass({
  8636. basePath: this.basePath,
  8637. onTraversalEnd: this._onTraversalEnd.bind(this)
  8638. });
  8639. }
  8640. _destroyTileHeaders(parentTile) {
  8641. this._destroySubtree(parentTile);
  8642. }
  8643. async _loadTile(tile) {
  8644. let loaded;
  8645. try {
  8646. this._onStartTileLoading();
  8647. loaded = await tile.loadContent();
  8648. } catch (error) {
  8649. this._onTileLoadError(tile, error);
  8650. } finally {
  8651. this._onEndTileLoading(tile);//
  8652. this._onTileLoad(tile, loaded);
  8653. }
  8654. }
  8655. _onTileLoadError(tile, error) {
  8656. this.stats.get(TILES_LOAD_FAILED).incrementCount();
  8657. const message = error.message || error.toString();
  8658. const url = tile.url;
  8659. console.error("A 3D tile failed to load: ".concat(tile.url, " ").concat(message));
  8660. this.options.onTileError(tile, message, url);
  8661. }
  8662. _onTileLoad(tile, loaded) {
  8663. if (!loaded) {
  8664. return;
  8665. }
  8666. if (tile && tile.content) {
  8667. calculateTransformProps(tile, tile.content);
  8668. }
  8669. this._addTileToCache(tile);
  8670. this.options.onTileLoad(tile);
  8671. }
  8672. _onStartTileLoading() {
  8673. this._pendingCount++;
  8674. this.stats.get(TILES_LOADING).incrementCount();
  8675. }
  8676. _onEndTileLoading(tile) {
  8677. this._pendingCount--;
  8678. this.stats.get(TILES_LOADING).decrementCount();
  8679. this.dispatchEvent({type:'endTileLoading', tile, loadingCount: this._pendingCount }) // !zeg改
  8680. }
  8681. _addTileToCache(tile) {
  8682. this._cache.add(this, tile, tileset => tileset._updateCacheStats(tile));
  8683. }
  8684. _updateCacheStats(tile) {
  8685. this.stats.get(TILES_LOADED).incrementCount();
  8686. this.stats.get(TILES_IN_MEMORY).incrementCount();
  8687. this.gpuMemoryUsageInBytes += tile.content.byteLength || 0;
  8688. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  8689. }
  8690. _unloadTile(tile) {
  8691. this.gpuMemoryUsageInBytes -= tile.content && tile.content.byteLength || 0;
  8692. this.stats.get(TILES_IN_MEMORY).decrementCount();
  8693. this.stats.get(TILES_UNLOADED).incrementCount();
  8694. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  8695. this.options.onTileUnload(tile);
  8696. tile.unloadContent();
  8697. }
  8698. _destroy() {
  8699. const stack = [];
  8700. if (this.root) {
  8701. stack.push(this.root);
  8702. }
  8703. while (stack.length > 0) {
  8704. const tile = stack.pop();
  8705. for (const child of tile.children) {
  8706. stack.push(child);
  8707. }
  8708. this._destroyTile(tile);
  8709. }
  8710. this.root = null;
  8711. }
  8712. _destroySubtree(tile) {
  8713. const root = tile;
  8714. const stack = [];
  8715. stack.push(root);
  8716. while (stack.length > 0) {
  8717. tile = stack.pop();
  8718. for (const child of tile.children) {
  8719. stack.push(child);
  8720. }
  8721. if (tile !== root) {
  8722. this._destroyTile(tile);
  8723. }
  8724. }
  8725. root.children = [];
  8726. }
  8727. _destroyTile(tile) {
  8728. this._cache.unloadTile(this, tile);
  8729. this._unloadTile(tile);
  8730. tile.destroy();
  8731. }
  8732. _initializeCesiumTileset(tilesetJson) {
  8733. this.asset = tilesetJson.asset;
  8734. if (!this.asset) {
  8735. throw new Error('Tileset must have an asset property.');
  8736. }
  8737. if (this.asset.version !== '0.0' && this.asset.version !== '1.0') {
  8738. throw new Error('The tileset must be 3D Tiles version 0.0 or 1.0.');
  8739. }
  8740. if ('tilesetVersion' in this.asset) {
  8741. this._queryParams.v = this.asset.tilesetVersion;
  8742. }
  8743. this.credits = {
  8744. attributions: this.options.attributions || []
  8745. };
  8746. this.description = this.options.description || '';
  8747. this.properties = tilesetJson.properties;
  8748. this.geometricError = tilesetJson.geometricError;
  8749. this._extensionsUsed = tilesetJson.extensionsUsed;
  8750. this.extras = tilesetJson.extras;
  8751. }
  8752. _initializeI3STileset() {
  8753. if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) {
  8754. this._queryParams.token = this.loadOptions.i3s.token;
  8755. }
  8756. }
  8757. }
  8758. function getQueryParamString(queryParams) {
  8759. const queryParamStrings = [];
  8760. for (const key of Object.keys(queryParams)) {
  8761. queryParamStrings.push("".concat(key, "=").concat(queryParams[key]));
  8762. }
  8763. switch (queryParamStrings.length) {
  8764. case 0:
  8765. return '';
  8766. case 1:
  8767. return "?".concat(queryParamStrings[0]);
  8768. default:
  8769. return "?".concat(queryParamStrings.join('&'));
  8770. }
  8771. }
  8772. const VERSION$5 = "3.1.4" ;
  8773. const TILE3D_TYPE = {
  8774. COMPOSITE: 'cmpt',
  8775. POINT_CLOUD: 'pnts',
  8776. BATCHED_3D_MODEL: 'b3dm',
  8777. INSTANCED_3D_MODEL: 'i3dm',
  8778. GEOMETRY: 'geom',
  8779. VECTOR: 'vect',
  8780. GLTF: 'glTF'
  8781. };
  8782. function getStringFromArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  8783. assert$7(arrayBuffer instanceof ArrayBuffer);
  8784. const textDecoder = new TextDecoder('utf8');
  8785. const typedArray = new Uint8Array(arrayBuffer, byteOffset, byteLength);
  8786. const string = textDecoder.decode(typedArray);
  8787. return string;
  8788. }
  8789. function getMagicString$1(arrayBuffer, byteOffset = 0) {
  8790. const dataView = new DataView(arrayBuffer);
  8791. 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)));
  8792. }
  8793. const VERSION$4 = "3.1.4" ;
  8794. const DEFAULT_DRACO_OPTIONS = {
  8795. draco: {
  8796. decoderType: typeof WebAssembly === 'object' ? 'wasm' : 'js',
  8797. libraryPath: 'libs/',
  8798. extraAttributes: {},
  8799. attributeNameEntry: undefined
  8800. }
  8801. };
  8802. const DracoLoader$1 = {
  8803. name: 'Draco',
  8804. id: 'draco',
  8805. module: 'draco',
  8806. shapes: ['mesh'],
  8807. version: VERSION$4,
  8808. worker: true,
  8809. extensions: ['drc'],
  8810. mimeTypes: ['application/octet-stream'],
  8811. binary: true,
  8812. tests: ['DRACO'],
  8813. options: DEFAULT_DRACO_OPTIONS
  8814. };
  8815. function getMeshBoundingBox(attributes) {
  8816. let minX = Infinity;
  8817. let minY = Infinity;
  8818. let minZ = Infinity;
  8819. let maxX = -Infinity;
  8820. let maxY = -Infinity;
  8821. let maxZ = -Infinity;
  8822. const positions = attributes.POSITION ? attributes.POSITION.value : [];
  8823. const len = positions && positions.length;
  8824. for (let i = 0; i < len; i += 3) {
  8825. const x = positions[i];
  8826. const y = positions[i + 1];
  8827. const z = positions[i + 2];
  8828. minX = x < minX ? x : minX;
  8829. minY = y < minY ? y : minY;
  8830. minZ = z < minZ ? z : minZ;
  8831. maxX = x > maxX ? x : maxX;
  8832. maxY = y > maxY ? y : maxY;
  8833. maxZ = z > maxZ ? z : maxZ;
  8834. }
  8835. return [[minX, minY, minZ], [maxX, maxY, maxZ]];
  8836. }
  8837. function assert$3(condition, message) {
  8838. if (!condition) {
  8839. throw new Error(message || 'loader assertion failed.');
  8840. }
  8841. }
  8842. class Schema {
  8843. constructor(fields, metadata) {
  8844. _defineProperty(this, "fields", void 0);
  8845. _defineProperty(this, "metadata", void 0);
  8846. assert$3(Array.isArray(fields));
  8847. checkNames(fields);
  8848. this.fields = fields;
  8849. this.metadata = metadata || new Map();
  8850. }
  8851. compareTo(other) {
  8852. if (this.metadata !== other.metadata) {
  8853. return false;
  8854. }
  8855. if (this.fields.length !== other.fields.length) {
  8856. return false;
  8857. }
  8858. for (let i = 0; i < this.fields.length; ++i) {
  8859. if (!this.fields[i].compareTo(other.fields[i])) {
  8860. return false;
  8861. }
  8862. }
  8863. return true;
  8864. }
  8865. select(...columnNames) {
  8866. const nameMap = Object.create(null);
  8867. for (const name of columnNames) {
  8868. nameMap[name] = true;
  8869. }
  8870. const selectedFields = this.fields.filter(field => nameMap[field.name]);
  8871. return new Schema(selectedFields, this.metadata);
  8872. }
  8873. selectAt(...columnIndices) {
  8874. const selectedFields = columnIndices.map(index => this.fields[index]).filter(Boolean);
  8875. return new Schema(selectedFields, this.metadata);
  8876. }
  8877. assign(schemaOrFields) {
  8878. let fields;
  8879. let metadata = this.metadata;
  8880. if (schemaOrFields instanceof Schema) {
  8881. const otherSchema = schemaOrFields;
  8882. fields = otherSchema.fields;
  8883. metadata = mergeMaps(mergeMaps(new Map(), this.metadata), otherSchema.metadata);
  8884. } else {
  8885. fields = schemaOrFields;
  8886. }
  8887. const fieldMap = Object.create(null);
  8888. for (const field of this.fields) {
  8889. fieldMap[field.name] = field;
  8890. }
  8891. for (const field of fields) {
  8892. fieldMap[field.name] = field;
  8893. }
  8894. const mergedFields = Object.values(fieldMap);
  8895. return new Schema(mergedFields, metadata);
  8896. }
  8897. }
  8898. function checkNames(fields) {
  8899. const usedNames = {};
  8900. for (const field of fields) {
  8901. if (usedNames[field.name]) {
  8902. console.warn('Schema: duplicated field name', field.name, field);
  8903. }
  8904. usedNames[field.name] = true;
  8905. }
  8906. }
  8907. function mergeMaps(m1, m2) {
  8908. return new Map([...(m1 || new Map()), ...(m2 || new Map())]);
  8909. }
  8910. class Field {
  8911. constructor(name, type, nullable = false, metadata = new Map()) {
  8912. _defineProperty(this, "name", void 0);
  8913. _defineProperty(this, "type", void 0);
  8914. _defineProperty(this, "nullable", void 0);
  8915. _defineProperty(this, "metadata", void 0);
  8916. this.name = name;
  8917. this.type = type;
  8918. this.nullable = nullable;
  8919. this.metadata = metadata;
  8920. }
  8921. get typeId() {
  8922. return this.type && this.type.typeId;
  8923. }
  8924. clone() {
  8925. return new Field(this.name, this.type, this.nullable, this.metadata);
  8926. }
  8927. compareTo(other) {
  8928. return this.name === other.name && this.type === other.type && this.nullable === other.nullable && this.metadata === other.metadata;
  8929. }
  8930. toString() {
  8931. return "".concat(this.type).concat(this.nullable ? ', nullable' : '').concat(this.metadata ? ", metadata: ".concat(this.metadata) : '');
  8932. }
  8933. }
  8934. let Type;
  8935. (function (Type) {
  8936. Type[Type["NONE"] = 0] = "NONE";
  8937. Type[Type["Null"] = 1] = "Null";
  8938. Type[Type["Int"] = 2] = "Int";
  8939. Type[Type["Float"] = 3] = "Float";
  8940. Type[Type["Binary"] = 4] = "Binary";
  8941. Type[Type["Utf8"] = 5] = "Utf8";
  8942. Type[Type["Bool"] = 6] = "Bool";
  8943. Type[Type["Decimal"] = 7] = "Decimal";
  8944. Type[Type["Date"] = 8] = "Date";
  8945. Type[Type["Time"] = 9] = "Time";
  8946. Type[Type["Timestamp"] = 10] = "Timestamp";
  8947. Type[Type["Interval"] = 11] = "Interval";
  8948. Type[Type["List"] = 12] = "List";
  8949. Type[Type["Struct"] = 13] = "Struct";
  8950. Type[Type["Union"] = 14] = "Union";
  8951. Type[Type["FixedSizeBinary"] = 15] = "FixedSizeBinary";
  8952. Type[Type["FixedSizeList"] = 16] = "FixedSizeList";
  8953. Type[Type["Map"] = 17] = "Map";
  8954. Type[Type["Dictionary"] = -1] = "Dictionary";
  8955. Type[Type["Int8"] = -2] = "Int8";
  8956. Type[Type["Int16"] = -3] = "Int16";
  8957. Type[Type["Int32"] = -4] = "Int32";
  8958. Type[Type["Int64"] = -5] = "Int64";
  8959. Type[Type["Uint8"] = -6] = "Uint8";
  8960. Type[Type["Uint16"] = -7] = "Uint16";
  8961. Type[Type["Uint32"] = -8] = "Uint32";
  8962. Type[Type["Uint64"] = -9] = "Uint64";
  8963. Type[Type["Float16"] = -10] = "Float16";
  8964. Type[Type["Float32"] = -11] = "Float32";
  8965. Type[Type["Float64"] = -12] = "Float64";
  8966. Type[Type["DateDay"] = -13] = "DateDay";
  8967. Type[Type["DateMillisecond"] = -14] = "DateMillisecond";
  8968. Type[Type["TimestampSecond"] = -15] = "TimestampSecond";
  8969. Type[Type["TimestampMillisecond"] = -16] = "TimestampMillisecond";
  8970. Type[Type["TimestampMicrosecond"] = -17] = "TimestampMicrosecond";
  8971. Type[Type["TimestampNanosecond"] = -18] = "TimestampNanosecond";
  8972. Type[Type["TimeSecond"] = -19] = "TimeSecond";
  8973. Type[Type["TimeMillisecond"] = -20] = "TimeMillisecond";
  8974. Type[Type["TimeMicrosecond"] = -21] = "TimeMicrosecond";
  8975. Type[Type["TimeNanosecond"] = -22] = "TimeNanosecond";
  8976. Type[Type["DenseUnion"] = -23] = "DenseUnion";
  8977. Type[Type["SparseUnion"] = -24] = "SparseUnion";
  8978. Type[Type["IntervalDayTime"] = -25] = "IntervalDayTime";
  8979. Type[Type["IntervalYearMonth"] = -26] = "IntervalYearMonth";
  8980. })(Type || (Type = {}));
  8981. let _Symbol$toStringTag, _Symbol$toStringTag2, _Symbol$toStringTag7;
  8982. class DataType {
  8983. static isNull(x) {
  8984. return x && x.typeId === Type.Null;
  8985. }
  8986. static isInt(x) {
  8987. return x && x.typeId === Type.Int;
  8988. }
  8989. static isFloat(x) {
  8990. return x && x.typeId === Type.Float;
  8991. }
  8992. static isBinary(x) {
  8993. return x && x.typeId === Type.Binary;
  8994. }
  8995. static isUtf8(x) {
  8996. return x && x.typeId === Type.Utf8;
  8997. }
  8998. static isBool(x) {
  8999. return x && x.typeId === Type.Bool;
  9000. }
  9001. static isDecimal(x) {
  9002. return x && x.typeId === Type.Decimal;
  9003. }
  9004. static isDate(x) {
  9005. return x && x.typeId === Type.Date;
  9006. }
  9007. static isTime(x) {
  9008. return x && x.typeId === Type.Time;
  9009. }
  9010. static isTimestamp(x) {
  9011. return x && x.typeId === Type.Timestamp;
  9012. }
  9013. static isInterval(x) {
  9014. return x && x.typeId === Type.Interval;
  9015. }
  9016. static isList(x) {
  9017. return x && x.typeId === Type.List;
  9018. }
  9019. static isStruct(x) {
  9020. return x && x.typeId === Type.Struct;
  9021. }
  9022. static isUnion(x) {
  9023. return x && x.typeId === Type.Union;
  9024. }
  9025. static isFixedSizeBinary(x) {
  9026. return x && x.typeId === Type.FixedSizeBinary;
  9027. }
  9028. static isFixedSizeList(x) {
  9029. return x && x.typeId === Type.FixedSizeList;
  9030. }
  9031. static isMap(x) {
  9032. return x && x.typeId === Type.Map;
  9033. }
  9034. static isDictionary(x) {
  9035. return x && x.typeId === Type.Dictionary;
  9036. }
  9037. get typeId() {
  9038. return Type.NONE;
  9039. }
  9040. compareTo(other) {
  9041. return this === other;
  9042. }
  9043. }
  9044. _Symbol$toStringTag = Symbol.toStringTag;
  9045. class Int extends DataType {
  9046. constructor(isSigned, bitWidth) {
  9047. super();
  9048. _defineProperty(this, "isSigned", void 0);
  9049. _defineProperty(this, "bitWidth", void 0);
  9050. this.isSigned = isSigned;
  9051. this.bitWidth = bitWidth;
  9052. }
  9053. get typeId() {
  9054. return Type.Int;
  9055. }
  9056. get [_Symbol$toStringTag]() {
  9057. return 'Int';
  9058. }
  9059. toString() {
  9060. return "".concat(this.isSigned ? 'I' : 'Ui', "nt").concat(this.bitWidth);
  9061. }
  9062. }
  9063. class Int8 extends Int {
  9064. constructor() {
  9065. super(true, 8);
  9066. }
  9067. }
  9068. class Int16 extends Int {
  9069. constructor() {
  9070. super(true, 16);
  9071. }
  9072. }
  9073. class Int32 extends Int {
  9074. constructor() {
  9075. super(true, 32);
  9076. }
  9077. }
  9078. class Uint8 extends Int {
  9079. constructor() {
  9080. super(false, 8);
  9081. }
  9082. }
  9083. class Uint16 extends Int {
  9084. constructor() {
  9085. super(false, 16);
  9086. }
  9087. }
  9088. class Uint32 extends Int {
  9089. constructor() {
  9090. super(false, 32);
  9091. }
  9092. }
  9093. const Precision = {
  9094. HALF: 16,
  9095. SINGLE: 32,
  9096. DOUBLE: 64
  9097. };
  9098. _Symbol$toStringTag2 = Symbol.toStringTag;
  9099. class Float extends DataType {
  9100. constructor(precision) {
  9101. super();
  9102. _defineProperty(this, "precision", void 0);
  9103. this.precision = precision;
  9104. }
  9105. get typeId() {
  9106. return Type.Float;
  9107. }
  9108. get [_Symbol$toStringTag2]() {
  9109. return 'Float';
  9110. }
  9111. toString() {
  9112. return "Float".concat(this.precision);
  9113. }
  9114. }
  9115. class Float32 extends Float {
  9116. constructor() {
  9117. super(Precision.SINGLE);
  9118. }
  9119. }
  9120. class Float64 extends Float {
  9121. constructor() {
  9122. super(Precision.DOUBLE);
  9123. }
  9124. }
  9125. _Symbol$toStringTag7 = Symbol.toStringTag;
  9126. class FixedSizeList extends DataType {
  9127. constructor(listSize, child) {
  9128. super();
  9129. _defineProperty(this, "listSize", void 0);
  9130. _defineProperty(this, "children", void 0);
  9131. this.listSize = listSize;
  9132. this.children = [child];
  9133. }
  9134. get typeId() {
  9135. return Type.FixedSizeList;
  9136. }
  9137. get valueType() {
  9138. return this.children[0].type;
  9139. }
  9140. get valueField() {
  9141. return this.children[0];
  9142. }
  9143. get [_Symbol$toStringTag7]() {
  9144. return 'FixedSizeList';
  9145. }
  9146. toString() {
  9147. return "FixedSizeList[".concat(this.listSize, "]<").concat(this.valueType, ">");
  9148. }
  9149. }
  9150. function getArrowTypeFromTypedArray(array) {
  9151. switch (array.constructor) {
  9152. case Int8Array:
  9153. return new Int8();
  9154. case Uint8Array:
  9155. return new Uint8();
  9156. case Int16Array:
  9157. return new Int16();
  9158. case Uint16Array:
  9159. return new Uint16();
  9160. case Int32Array:
  9161. return new Int32();
  9162. case Uint32Array:
  9163. return new Uint32();
  9164. case Float32Array:
  9165. return new Float32();
  9166. case Float64Array:
  9167. return new Float64();
  9168. default:
  9169. throw new Error('array type not supported');
  9170. }
  9171. }
  9172. function deduceMeshField(attributeName, attribute, optionalMetadata) {
  9173. const type = getArrowTypeFromTypedArray(attribute.value);
  9174. const metadata = optionalMetadata ? optionalMetadata : makeMeshAttributeMetadata(attribute);
  9175. const field = new Field(attributeName, new FixedSizeList(attribute.size, new Field('value', type)), false, metadata);
  9176. return field;
  9177. }
  9178. function makeMeshAttributeMetadata(attribute) {
  9179. const result = new Map();
  9180. if ('byteOffset' in attribute) {
  9181. result.set('byteOffset', attribute.byteOffset.toString(10));
  9182. }
  9183. if ('byteStride' in attribute) {
  9184. result.set('byteStride', attribute.byteStride.toString(10));
  9185. }
  9186. if ('normalized' in attribute) {
  9187. result.set('normalized', attribute.normalized.toString());
  9188. }
  9189. return result;
  9190. }
  9191. function getDracoSchema(attributes, loaderData, indices) {
  9192. const metadataMap = makeMetadata(loaderData.metadata);
  9193. const fields = [];
  9194. const namedLoaderDataAttributes = transformAttributesLoaderData(loaderData.attributes);
  9195. for (const attributeName in attributes) {
  9196. const attribute = attributes[attributeName];
  9197. const field = getArrowFieldFromAttribute(attributeName, attribute, namedLoaderDataAttributes[attributeName]);
  9198. fields.push(field);
  9199. }
  9200. if (indices) {
  9201. const indicesField = getArrowFieldFromAttribute('indices', indices);
  9202. fields.push(indicesField);
  9203. }
  9204. return new Schema(fields, metadataMap);
  9205. }
  9206. function transformAttributesLoaderData(loaderData) {
  9207. const result = {};
  9208. for (const key in loaderData) {
  9209. const dracoAttribute = loaderData[key];
  9210. result[dracoAttribute.name || 'undefined'] = dracoAttribute;
  9211. }
  9212. return result;
  9213. }
  9214. function getArrowFieldFromAttribute(attributeName, attribute, loaderData) {
  9215. const metadataMap = loaderData ? makeMetadata(loaderData.metadata) : undefined;
  9216. const field = deduceMeshField(attributeName, attribute, metadataMap);
  9217. return field;
  9218. }
  9219. function makeMetadata(metadata) {
  9220. const metadataMap = new Map();
  9221. for (const key in metadata) {
  9222. metadataMap.set("".concat(key, ".string"), JSON.stringify(metadata[key]));
  9223. }
  9224. return metadataMap;
  9225. }
  9226. const DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP = {
  9227. POSITION: 'POSITION',
  9228. NORMAL: 'NORMAL',
  9229. COLOR: 'COLOR_0',
  9230. TEX_COORD: 'TEXCOORD_0'
  9231. };
  9232. const DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP = {
  9233. 1: Int8Array,
  9234. 2: Uint8Array,
  9235. 3: Int16Array,
  9236. 4: Uint16Array,
  9237. 5: Int32Array,
  9238. 6: Uint32Array,
  9239. 9: Float32Array
  9240. };
  9241. const INDEX_ITEM_SIZE = 4;
  9242. class DracoParser {
  9243. constructor(draco) {
  9244. _defineProperty(this, "draco", void 0);
  9245. _defineProperty(this, "decoder", void 0);
  9246. _defineProperty(this, "metadataQuerier", void 0);
  9247. this.draco = draco;
  9248. this.decoder = new this.draco.Decoder();
  9249. this.metadataQuerier = new this.draco.MetadataQuerier();
  9250. }
  9251. destroy() {
  9252. this.draco.destroy(this.decoder);
  9253. this.draco.destroy(this.metadataQuerier);
  9254. }
  9255. parseSync(arrayBuffer, options = {}) {
  9256. const buffer = new this.draco.DecoderBuffer();
  9257. buffer.Init(new Int8Array(arrayBuffer), arrayBuffer.byteLength);
  9258. this._disableAttributeTransforms(options);
  9259. const geometry_type = this.decoder.GetEncodedGeometryType(buffer);
  9260. const dracoGeometry = geometry_type === this.draco.TRIANGULAR_MESH ? new this.draco.Mesh() : new this.draco.PointCloud();
  9261. try {
  9262. let dracoStatus;
  9263. switch (geometry_type) {
  9264. case this.draco.TRIANGULAR_MESH:
  9265. dracoStatus = this.decoder.DecodeBufferToMesh(buffer, dracoGeometry);
  9266. break;
  9267. case this.draco.POINT_CLOUD:
  9268. dracoStatus = this.decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
  9269. break;
  9270. default:
  9271. throw new Error('DRACO: Unknown geometry type.');
  9272. }
  9273. if (!dracoStatus.ok() || !dracoGeometry.ptr) {
  9274. const message = "DRACO decompression failed: ".concat(dracoStatus.error_msg());
  9275. throw new Error(message);
  9276. }
  9277. const loaderData = this._getDracoLoaderData(dracoGeometry, geometry_type, options);
  9278. const geometry = this._getMeshData(dracoGeometry, loaderData, options);
  9279. const boundingBox = getMeshBoundingBox(geometry.attributes);
  9280. const schema = getDracoSchema(geometry.attributes, loaderData, geometry.indices);
  9281. const data = {
  9282. loader: 'draco',
  9283. loaderData,
  9284. header: {
  9285. vertexCount: dracoGeometry.num_points(),
  9286. boundingBox
  9287. },
  9288. ...geometry,
  9289. schema
  9290. };
  9291. return data;
  9292. } finally {
  9293. this.draco.destroy(buffer);
  9294. if (dracoGeometry) {
  9295. this.draco.destroy(dracoGeometry);
  9296. }
  9297. }
  9298. }
  9299. _getDracoLoaderData(dracoGeometry, geometry_type, options) {
  9300. const metadata = this._getTopLevelMetadata(dracoGeometry);
  9301. const attributes = this._getDracoAttributes(dracoGeometry, options);
  9302. return {
  9303. geometry_type,
  9304. num_attributes: dracoGeometry.num_attributes(),
  9305. num_points: dracoGeometry.num_points(),
  9306. num_faces: dracoGeometry instanceof this.draco.Mesh ? dracoGeometry.num_faces() : 0,
  9307. metadata,
  9308. attributes
  9309. };
  9310. }
  9311. _getDracoAttributes(dracoGeometry, options) {
  9312. const dracoAttributes = {};
  9313. for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {
  9314. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);
  9315. const metadata = this._getAttributeMetadata(dracoGeometry, attributeId);
  9316. dracoAttributes[dracoAttribute.unique_id()] = {
  9317. unique_id: dracoAttribute.unique_id(),
  9318. attribute_type: dracoAttribute.attribute_type(),
  9319. data_type: dracoAttribute.data_type(),
  9320. num_components: dracoAttribute.num_components(),
  9321. byte_offset: dracoAttribute.byte_offset(),
  9322. byte_stride: dracoAttribute.byte_stride(),
  9323. normalized: dracoAttribute.normalized(),
  9324. attribute_index: attributeId,
  9325. metadata
  9326. };
  9327. const quantization = this._getQuantizationTransform(dracoAttribute, options);
  9328. if (quantization) {
  9329. dracoAttributes[dracoAttribute.unique_id()].quantization_transform = quantization;
  9330. }
  9331. const octahedron = this._getOctahedronTransform(dracoAttribute, options);
  9332. if (octahedron) {
  9333. dracoAttributes[dracoAttribute.unique_id()].octahedron_transform = octahedron;
  9334. }
  9335. }
  9336. return dracoAttributes;
  9337. }
  9338. _getMeshData(dracoGeometry, loaderData, options) {
  9339. const attributes = this._getMeshAttributes(loaderData, dracoGeometry, options);
  9340. const positionAttribute = attributes.POSITION;
  9341. if (!positionAttribute) {
  9342. throw new Error('DRACO: No position attribute found.');
  9343. }
  9344. if (dracoGeometry instanceof this.draco.Mesh) {
  9345. switch (options.topology) {
  9346. case 'triangle-strip':
  9347. return {
  9348. topology: 'triangle-strip',
  9349. mode: 4,
  9350. attributes,
  9351. indices: {
  9352. value: this._getTriangleStripIndices(dracoGeometry),
  9353. size: 1
  9354. }
  9355. };
  9356. case 'triangle-list':
  9357. default:
  9358. return {
  9359. topology: 'triangle-list',
  9360. mode: 5,
  9361. attributes,
  9362. indices: {
  9363. value: this._getTriangleListIndices(dracoGeometry),
  9364. size: 1
  9365. }
  9366. };
  9367. }
  9368. }
  9369. return {
  9370. topology: 'point-list',
  9371. mode: 0,
  9372. attributes
  9373. };
  9374. }
  9375. _getMeshAttributes(loaderData, dracoGeometry, options) {
  9376. const attributes = {};
  9377. for (const loaderAttribute of Object.values(loaderData.attributes)) {
  9378. const attributeName = this._deduceAttributeName(loaderAttribute, options);
  9379. loaderAttribute.name = attributeName;
  9380. const {
  9381. value,
  9382. size
  9383. } = this._getAttributeValues(dracoGeometry, loaderAttribute);
  9384. attributes[attributeName] = {
  9385. value,
  9386. size,
  9387. byteOffset: loaderAttribute.byte_offset,
  9388. byteStride: loaderAttribute.byte_stride,
  9389. normalized: loaderAttribute.normalized
  9390. };
  9391. }
  9392. return attributes;
  9393. }
  9394. _getTriangleListIndices(dracoGeometry) {
  9395. const numFaces = dracoGeometry.num_faces();
  9396. const numIndices = numFaces * 3;
  9397. const byteLength = numIndices * INDEX_ITEM_SIZE;
  9398. const ptr = this.draco._malloc(byteLength);
  9399. try {
  9400. this.decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);
  9401. return new Uint32Array(this.draco.HEAPF32.buffer, ptr, numIndices).slice();
  9402. } finally {
  9403. this.draco._free(ptr);
  9404. }
  9405. }
  9406. _getTriangleStripIndices(dracoGeometry) {
  9407. const dracoArray = new this.draco.DracoInt32Array();
  9408. try {
  9409. this.decoder.GetTriangleStripsFromMesh(dracoGeometry, dracoArray);
  9410. return getUint32Array(dracoArray);
  9411. } finally {
  9412. this.draco.destroy(dracoArray);
  9413. }
  9414. }
  9415. _getAttributeValues(dracoGeometry, attribute) {
  9416. const TypedArrayCtor = DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP[attribute.data_type];
  9417. const numComponents = attribute.num_components;
  9418. const numPoints = dracoGeometry.num_points();
  9419. const numValues = numPoints * numComponents;
  9420. const byteLength = numValues * TypedArrayCtor.BYTES_PER_ELEMENT;
  9421. const dataType = getDracoDataType(this.draco, TypedArrayCtor);
  9422. let value;
  9423. const ptr = this.draco._malloc(byteLength);
  9424. try {
  9425. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attribute.attribute_index);
  9426. this.decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, dracoAttribute, dataType, byteLength, ptr);
  9427. value = new TypedArrayCtor(this.draco.HEAPF32.buffer, ptr, numValues).slice();
  9428. } finally {
  9429. this.draco._free(ptr);
  9430. }
  9431. return {
  9432. value,
  9433. size: numComponents
  9434. };
  9435. }
  9436. _deduceAttributeName(attribute, options) {
  9437. const uniqueId = attribute.unique_id;
  9438. for (const [attributeName, attributeUniqueId] of Object.entries(options.extraAttributes || {})) {
  9439. if (attributeUniqueId === uniqueId) {
  9440. return attributeName;
  9441. }
  9442. }
  9443. const thisAttributeType = attribute.attribute_type;
  9444. for (const dracoAttributeConstant in DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP) {
  9445. const attributeType = this.draco[dracoAttributeConstant];
  9446. if (attributeType === thisAttributeType) {
  9447. return DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP[dracoAttributeConstant];
  9448. }
  9449. }
  9450. const entryName = options.attributeNameEntry || 'name';
  9451. if (attribute.metadata[entryName]) {
  9452. return attribute.metadata[entryName].string;
  9453. }
  9454. return "CUSTOM_ATTRIBUTE_".concat(uniqueId);
  9455. }
  9456. _getTopLevelMetadata(dracoGeometry) {
  9457. const dracoMetadata = this.decoder.GetMetadata(dracoGeometry);
  9458. return this._getDracoMetadata(dracoMetadata);
  9459. }
  9460. _getAttributeMetadata(dracoGeometry, attributeId) {
  9461. const dracoMetadata = this.decoder.GetAttributeMetadata(dracoGeometry, attributeId);
  9462. return this._getDracoMetadata(dracoMetadata);
  9463. }
  9464. _getDracoMetadata(dracoMetadata) {
  9465. if (!dracoMetadata || !dracoMetadata.ptr) {
  9466. return {};
  9467. }
  9468. const result = {};
  9469. const numEntries = this.metadataQuerier.NumEntries(dracoMetadata);
  9470. for (let entryIndex = 0; entryIndex < numEntries; entryIndex++) {
  9471. const entryName = this.metadataQuerier.GetEntryName(dracoMetadata, entryIndex);
  9472. result[entryName] = this._getDracoMetadataField(dracoMetadata, entryName);
  9473. }
  9474. return result;
  9475. }
  9476. _getDracoMetadataField(dracoMetadata, entryName) {
  9477. const dracoArray = new this.draco.DracoInt32Array();
  9478. try {
  9479. this.metadataQuerier.GetIntEntryArray(dracoMetadata, entryName, dracoArray);
  9480. const intArray = getInt32Array(dracoArray);
  9481. return {
  9482. int: this.metadataQuerier.GetIntEntry(dracoMetadata, entryName),
  9483. string: this.metadataQuerier.GetStringEntry(dracoMetadata, entryName),
  9484. double: this.metadataQuerier.GetDoubleEntry(dracoMetadata, entryName),
  9485. intArray
  9486. };
  9487. } finally {
  9488. this.draco.destroy(dracoArray);
  9489. }
  9490. }
  9491. _disableAttributeTransforms(options) {
  9492. const {
  9493. quantizedAttributes = [],
  9494. octahedronAttributes = []
  9495. } = options;
  9496. const skipAttributes = [...quantizedAttributes, ...octahedronAttributes];
  9497. for (const dracoAttributeName of skipAttributes) {
  9498. this.decoder.SkipAttributeTransform(this.draco[dracoAttributeName]);
  9499. }
  9500. }
  9501. _getQuantizationTransform(dracoAttribute, options) {
  9502. const {
  9503. quantizedAttributes = []
  9504. } = options;
  9505. const attribute_type = dracoAttribute.attribute_type();
  9506. const skip = quantizedAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9507. if (skip) {
  9508. const transform = new this.draco.AttributeQuantizationTransform();
  9509. try {
  9510. if (transform.InitFromAttribute(dracoAttribute)) {
  9511. return {
  9512. quantization_bits: transform.quantization_bits(),
  9513. range: transform.range(),
  9514. min_values: new Float32Array([1, 2, 3]).map(i => transform.min_value(i))
  9515. };
  9516. }
  9517. } finally {
  9518. this.draco.destroy(transform);
  9519. }
  9520. }
  9521. return null;
  9522. }
  9523. _getOctahedronTransform(dracoAttribute, options) {
  9524. const {
  9525. octahedronAttributes = []
  9526. } = options;
  9527. const attribute_type = dracoAttribute.attribute_type();
  9528. const octahedron = octahedronAttributes.map(type => this.decoder[type]).includes(attribute_type);
  9529. if (octahedron) {
  9530. const transform = new this.draco.AttributeQuantizationTransform();
  9531. try {
  9532. if (transform.InitFromAttribute(dracoAttribute)) {
  9533. return {
  9534. quantization_bits: transform.quantization_bits()
  9535. };
  9536. }
  9537. } finally {
  9538. this.draco.destroy(transform);
  9539. }
  9540. }
  9541. return null;
  9542. }
  9543. }
  9544. function getDracoDataType(draco, attributeType) {
  9545. switch (attributeType) {
  9546. case Float32Array:
  9547. return draco.DT_FLOAT32;
  9548. case Int8Array:
  9549. return draco.DT_INT8;
  9550. case Int16Array:
  9551. return draco.DT_INT16;
  9552. case Int32Array:
  9553. return draco.DT_INT32;
  9554. case Uint8Array:
  9555. return draco.DT_UINT8;
  9556. case Uint16Array:
  9557. return draco.DT_UINT16;
  9558. case Uint32Array:
  9559. return draco.DT_UINT32;
  9560. default:
  9561. return draco.DT_INVALID;
  9562. }
  9563. }
  9564. function getInt32Array(dracoArray) {
  9565. const numValues = dracoArray.size();
  9566. const intArray = new Int32Array(numValues);
  9567. for (let i = 0; i < numValues; i++) {
  9568. intArray[i] = dracoArray.GetValue(i);
  9569. }
  9570. return intArray;
  9571. }
  9572. function getUint32Array(dracoArray) {
  9573. const numValues = dracoArray.size();
  9574. const intArray = new Int32Array(numValues);
  9575. for (let i = 0; i < numValues; i++) {
  9576. intArray[i] = dracoArray.GetValue(i);
  9577. }
  9578. return intArray;
  9579. }
  9580. const DRACO_VERSION = '1.4.1';
  9581. const DRACO_JS_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.js");
  9582. const DRACO_WASM_WRAPPER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_wasm_wrapper.js");
  9583. const DRACO_WASM_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.wasm");
  9584. let loadDecoderPromise;
  9585. async function loadDracoDecoderModule(options) {
  9586. const modules = options.modules || {};
  9587. if (modules.draco3d) {
  9588. loadDecoderPromise = loadDecoderPromise || modules.draco3d.createDecoderModule({}).then(draco => {
  9589. return {
  9590. draco
  9591. };
  9592. });
  9593. } else {
  9594. loadDecoderPromise = loadDecoderPromise || loadDracoDecoder(options);
  9595. }
  9596. return await loadDecoderPromise;
  9597. }
  9598. async function loadDracoDecoder(options) {
  9599. let DracoDecoderModule;
  9600. let wasmBinary;
  9601. switch (options.draco && options.draco.decoderType) {
  9602. case 'js':
  9603. DracoDecoderModule = await loadLibrary(DRACO_JS_DECODER_URL, 'draco', options);
  9604. break;
  9605. case 'wasm':
  9606. default:
  9607. [DracoDecoderModule, wasmBinary] = await Promise.all([await loadLibrary(DRACO_WASM_WRAPPER_URL, 'draco', options), await loadLibrary(DRACO_WASM_DECODER_URL, 'draco', options)]);
  9608. }
  9609. DracoDecoderModule = DracoDecoderModule || globalThis.DracoDecoderModule;
  9610. return await initializeDracoDecoder(DracoDecoderModule, wasmBinary);
  9611. }
  9612. function initializeDracoDecoder(DracoDecoderModule, wasmBinary) {
  9613. const options = {};
  9614. if (wasmBinary) {
  9615. options.wasmBinary = wasmBinary;
  9616. }
  9617. return new Promise(resolve => {
  9618. DracoDecoderModule({ ...options,
  9619. onModuleLoaded: draco => resolve({
  9620. draco
  9621. })
  9622. });
  9623. });
  9624. }
  9625. const DracoLoader = { ...DracoLoader$1,
  9626. parse: parse$2
  9627. };
  9628. async function parse$2(arrayBuffer, options) {
  9629. const {
  9630. draco
  9631. } = await loadDracoDecoderModule(options);
  9632. const dracoParser = new DracoParser(draco);
  9633. try {
  9634. return dracoParser.parseSync(arrayBuffer, options === null || options === void 0 ? void 0 : options.draco);
  9635. } finally {
  9636. dracoParser.destroy();
  9637. }
  9638. }
  9639. const GL_PRIMITIVE_MODE = {
  9640. POINTS: 0x0000,
  9641. LINES: 0x0001,
  9642. LINE_LOOP: 0x0002,
  9643. LINE_STRIP: 0x0003,
  9644. TRIANGLES: 0x0004,
  9645. TRIANGLE_STRIP: 0x0005,
  9646. TRIANGLE_FAN: 0x0006
  9647. };
  9648. const GL_TYPE = {
  9649. BYTE: 5120,
  9650. UNSIGNED_BYTE: 5121,
  9651. SHORT: 5122,
  9652. UNSIGNED_SHORT: 5123,
  9653. INT: 5124,
  9654. UNSIGNED_INT: 5125,
  9655. FLOAT: 5126,
  9656. DOUBLE: 5130
  9657. };
  9658. const GL$1 = { ...GL_PRIMITIVE_MODE,
  9659. ...GL_TYPE
  9660. };
  9661. const GL_TYPE_TO_ARRAY_TYPE = {
  9662. [GL_TYPE.DOUBLE]: Float64Array,
  9663. [GL_TYPE.FLOAT]: Float32Array,
  9664. [GL_TYPE.UNSIGNED_SHORT]: Uint16Array,
  9665. [GL_TYPE.UNSIGNED_INT]: Uint32Array,
  9666. [GL_TYPE.UNSIGNED_BYTE]: Uint8Array,
  9667. [GL_TYPE.BYTE]: Int8Array,
  9668. [GL_TYPE.SHORT]: Int16Array,
  9669. [GL_TYPE.INT]: Int32Array
  9670. };
  9671. const NAME_TO_GL_TYPE = {
  9672. DOUBLE: GL_TYPE.DOUBLE,
  9673. FLOAT: GL_TYPE.FLOAT,
  9674. UNSIGNED_SHORT: GL_TYPE.UNSIGNED_SHORT,
  9675. UNSIGNED_INT: GL_TYPE.UNSIGNED_INT,
  9676. UNSIGNED_BYTE: GL_TYPE.UNSIGNED_BYTE,
  9677. BYTE: GL_TYPE.BYTE,
  9678. SHORT: GL_TYPE.SHORT,
  9679. INT: GL_TYPE.INT
  9680. };
  9681. const ERR_TYPE_CONVERSION = 'Failed to convert GL type';
  9682. class GLType {
  9683. static fromTypedArray(arrayOrType) {
  9684. arrayOrType = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;
  9685. for (const glType in GL_TYPE_TO_ARRAY_TYPE) {
  9686. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  9687. if (ArrayType === arrayOrType) {
  9688. return glType;
  9689. }
  9690. }
  9691. throw new Error(ERR_TYPE_CONVERSION);
  9692. }
  9693. static fromName(name) {
  9694. const glType = NAME_TO_GL_TYPE[name];
  9695. if (!glType) {
  9696. throw new Error(ERR_TYPE_CONVERSION);
  9697. }
  9698. return glType;
  9699. }
  9700. static getArrayType(glType) {
  9701. switch (glType) {
  9702. case GL_TYPE.UNSIGNED_SHORT_5_6_5:
  9703. case GL_TYPE.UNSIGNED_SHORT_4_4_4_4:
  9704. case GL_TYPE.UNSIGNED_SHORT_5_5_5_1:
  9705. return Uint16Array;
  9706. default:
  9707. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  9708. if (!ArrayType) {
  9709. throw new Error(ERR_TYPE_CONVERSION);
  9710. }
  9711. return ArrayType;
  9712. }
  9713. }
  9714. static getByteSize(glType) {
  9715. const ArrayType = GLType.getArrayType(glType);
  9716. return ArrayType.BYTES_PER_ELEMENT;
  9717. }
  9718. static validate(glType) {
  9719. return Boolean(GLType.getArrayType(glType));
  9720. }
  9721. static createTypedArray(glType, buffer, byteOffset = 0, length) {
  9722. if (length === undefined) {
  9723. length = (buffer.byteLength - byteOffset) / GLType.getByteSize(glType);
  9724. }
  9725. const ArrayType = GLType.getArrayType(glType);
  9726. return new ArrayType(buffer, byteOffset, length);
  9727. }
  9728. }
  9729. function assert$2(condition, message) {
  9730. if (!condition) {
  9731. throw new Error("math.gl assertion failed. ".concat(message));
  9732. }
  9733. }
  9734. function decodeRGB565(rgb565, target = [0, 0, 0]) {
  9735. const r5 = rgb565 >> 11 & 31;
  9736. const g6 = rgb565 >> 5 & 63;
  9737. const b5 = rgb565 & 31;
  9738. target[0] = r5 << 3;
  9739. target[1] = g6 << 2;
  9740. target[2] = b5 << 3;
  9741. return target;
  9742. }
  9743. new Vector2();
  9744. new Vector3();
  9745. new Vector2();
  9746. new Vector2();
  9747. function fromSNorm(value, rangeMaximum = 255) {
  9748. return clamp(value, 0.0, rangeMaximum) / rangeMaximum * 2.0 - 1.0;
  9749. }
  9750. function signNotZero(value) {
  9751. return value < 0.0 ? -1.0 : 1.0;
  9752. }
  9753. function octDecodeInRange(x, y, rangeMax, result) {
  9754. assert$2(result);
  9755. if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
  9756. throw new Error("x and y must be unsigned normalized integers between 0 and ".concat(rangeMax));
  9757. }
  9758. result.x = fromSNorm(x, rangeMax);
  9759. result.y = fromSNorm(y, rangeMax);
  9760. result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));
  9761. if (result.z < 0.0) {
  9762. const oldVX = result.x;
  9763. result.x = (1.0 - Math.abs(result.y)) * signNotZero(oldVX);
  9764. result.y = (1.0 - Math.abs(oldVX)) * signNotZero(result.y);
  9765. }
  9766. return result.normalize();
  9767. }
  9768. function octDecode(x, y, result) {
  9769. return octDecodeInRange(x, y, 255, result);
  9770. }
  9771. class Tile3DFeatureTable {
  9772. constructor(featureTableJson, featureTableBinary) {
  9773. _defineProperty(this, "json", void 0);
  9774. _defineProperty(this, "buffer", void 0);
  9775. _defineProperty(this, "featuresLength", 0);
  9776. _defineProperty(this, "_cachedTypedArrays", {});
  9777. this.json = featureTableJson;
  9778. this.buffer = featureTableBinary;
  9779. }
  9780. getExtension(extensionName) {
  9781. return this.json.extensions && this.json.extensions[extensionName];
  9782. }
  9783. hasProperty(propertyName) {
  9784. return Boolean(this.json[propertyName]);
  9785. }
  9786. getGlobalProperty(propertyName, componentType = GL$1.UNSIGNED_INT, componentLength = 1) {
  9787. const jsonValue = this.json[propertyName];
  9788. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  9789. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, 1, jsonValue.byteOffset);
  9790. }
  9791. return jsonValue;
  9792. }
  9793. getPropertyArray(propertyName, componentType, componentLength) {
  9794. const jsonValue = this.json[propertyName];
  9795. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  9796. if ('componentType' in jsonValue) {
  9797. componentType = GLType.fromName(jsonValue.componentType);
  9798. }
  9799. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, this.featuresLength, jsonValue.byteOffset);
  9800. }
  9801. return this._getTypedArrayFromArray(propertyName, componentType, jsonValue);
  9802. }
  9803. getProperty(propertyName, componentType, componentLength, featureId, result) {
  9804. const jsonValue = this.json[propertyName];
  9805. if (!jsonValue) {
  9806. return jsonValue;
  9807. }
  9808. const typedArray = this.getPropertyArray(propertyName, componentType, componentLength);
  9809. if (componentLength === 1) {
  9810. return typedArray[featureId];
  9811. }
  9812. for (let i = 0; i < componentLength; ++i) {
  9813. result[i] = typedArray[componentLength * featureId + i];
  9814. }
  9815. return result;
  9816. }
  9817. _getTypedArrayFromBinary(propertyName, componentType, componentLength, count, byteOffset) {
  9818. const cachedTypedArrays = this._cachedTypedArrays;
  9819. let typedArray = cachedTypedArrays[propertyName];
  9820. if (!typedArray) {
  9821. typedArray = GLType.createTypedArray(componentType, this.buffer.buffer, this.buffer.byteOffset + byteOffset, count * componentLength);
  9822. cachedTypedArrays[propertyName] = typedArray;
  9823. }
  9824. return typedArray;
  9825. }
  9826. _getTypedArrayFromArray(propertyName, componentType, array) {
  9827. const cachedTypedArrays = this._cachedTypedArrays;
  9828. let typedArray = cachedTypedArrays[propertyName];
  9829. if (!typedArray) {
  9830. typedArray = GLType.createTypedArray(componentType, array);
  9831. cachedTypedArrays[propertyName] = typedArray;
  9832. }
  9833. return typedArray;
  9834. }
  9835. }
  9836. const COMPONENTS_PER_ATTRIBUTE = {
  9837. SCALAR: 1,
  9838. VEC2: 2,
  9839. VEC3: 3,
  9840. VEC4: 4,
  9841. MAT2: 4,
  9842. MAT3: 9,
  9843. MAT4: 16
  9844. };
  9845. const UNPACKER = {
  9846. SCALAR: (values, i) => values[i],
  9847. VEC2: (values, i) => [values[2 * i + 0], values[2 * i + 1]],
  9848. VEC3: (values, i) => [values[3 * i + 0], values[3 * i + 1], values[3 * i + 2]],
  9849. VEC4: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  9850. MAT2: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  9851. 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]],
  9852. 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]]
  9853. };
  9854. const PACKER = {
  9855. SCALAR: (x, values, i) => {
  9856. values[i] = x;
  9857. },
  9858. VEC2: (x, values, i) => {
  9859. values[2 * i + 0] = x[0];
  9860. values[2 * i + 1] = x[1];
  9861. },
  9862. VEC3: (x, values, i) => {
  9863. values[3 * i + 0] = x[0];
  9864. values[3 * i + 1] = x[1];
  9865. values[3 * i + 2] = x[2];
  9866. },
  9867. VEC4: (x, values, i) => {
  9868. values[4 * i + 0] = x[0];
  9869. values[4 * i + 1] = x[1];
  9870. values[4 * i + 2] = x[2];
  9871. values[4 * i + 3] = x[3];
  9872. },
  9873. MAT2: (x, values, i) => {
  9874. values[4 * i + 0] = x[0];
  9875. values[4 * i + 1] = x[1];
  9876. values[4 * i + 2] = x[2];
  9877. values[4 * i + 3] = x[3];
  9878. },
  9879. MAT3: (x, values, i) => {
  9880. values[9 * i + 0] = x[0];
  9881. values[9 * i + 1] = x[1];
  9882. values[9 * i + 2] = x[2];
  9883. values[9 * i + 3] = x[3];
  9884. values[9 * i + 4] = x[4];
  9885. values[9 * i + 5] = x[5];
  9886. values[9 * i + 6] = x[6];
  9887. values[9 * i + 7] = x[7];
  9888. values[9 * i + 8] = x[8];
  9889. values[9 * i + 9] = x[9];
  9890. },
  9891. MAT4: (x, values, i) => {
  9892. values[16 * i + 0] = x[0];
  9893. values[16 * i + 1] = x[1];
  9894. values[16 * i + 2] = x[2];
  9895. values[16 * i + 3] = x[3];
  9896. values[16 * i + 4] = x[4];
  9897. values[16 * i + 5] = x[5];
  9898. values[16 * i + 6] = x[6];
  9899. values[16 * i + 7] = x[7];
  9900. values[16 * i + 8] = x[8];
  9901. values[16 * i + 9] = x[9];
  9902. values[16 * i + 10] = x[10];
  9903. values[16 * i + 11] = x[11];
  9904. values[16 * i + 12] = x[12];
  9905. values[16 * i + 13] = x[13];
  9906. values[16 * i + 14] = x[14];
  9907. values[16 * i + 15] = x[15];
  9908. }
  9909. };
  9910. function createTypedArrayFromAccessor(tile3DAccessor, buffer, byteOffset, length) {
  9911. const {
  9912. componentType
  9913. } = tile3DAccessor;
  9914. assert$7(tile3DAccessor.componentType);
  9915. const type = typeof componentType === 'string' ? GLType.fromName(componentType) : componentType;
  9916. const size = COMPONENTS_PER_ATTRIBUTE[tile3DAccessor.type];
  9917. const unpacker = UNPACKER[tile3DAccessor.type];
  9918. const packer = PACKER[tile3DAccessor.type];
  9919. byteOffset += tile3DAccessor.byteOffset;
  9920. const values = GLType.createTypedArray(type, buffer, byteOffset, size * length);
  9921. return {
  9922. values,
  9923. type,
  9924. size,
  9925. unpacker,
  9926. packer
  9927. };
  9928. }
  9929. const defined$1 = x => x !== undefined;
  9930. function initializeHierarchy(batchTable, jsonHeader, binaryBody) {
  9931. if (!jsonHeader) {
  9932. return null;
  9933. }
  9934. let hierarchy = batchTable.getExtension('3DTILES_batch_table_hierarchy');
  9935. const legacyHierarchy = jsonHeader.HIERARCHY;
  9936. if (legacyHierarchy) {
  9937. console.warn('3D Tile Parser: HIERARCHY is deprecated. Use 3DTILES_batch_table_hierarchy.');
  9938. jsonHeader.extensions = jsonHeader.extensions || {};
  9939. jsonHeader.extensions['3DTILES_batch_table_hierarchy'] = legacyHierarchy;
  9940. hierarchy = legacyHierarchy;
  9941. }
  9942. if (!hierarchy) {
  9943. return null;
  9944. }
  9945. return initializeHierarchyValues(hierarchy, binaryBody);
  9946. }
  9947. function initializeHierarchyValues(hierarchyJson, binaryBody) {
  9948. let i;
  9949. let classId;
  9950. let binaryAccessor;
  9951. const instancesLength = hierarchyJson.instancesLength;
  9952. const classes = hierarchyJson.classes;
  9953. let classIds = hierarchyJson.classIds;
  9954. let parentCounts = hierarchyJson.parentCounts;
  9955. let parentIds = hierarchyJson.parentIds;
  9956. let parentIdsLength = instancesLength;
  9957. if (defined$1(classIds.byteOffset)) {
  9958. classIds.componentType = defaultValue(classIds.componentType, GL.UNSIGNED_SHORT);
  9959. classIds.type = AttributeType.SCALAR;
  9960. binaryAccessor = getBinaryAccessor(classIds);
  9961. classIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + classIds.byteOffset, instancesLength);
  9962. }
  9963. let parentIndexes;
  9964. if (defined$1(parentCounts)) {
  9965. if (defined$1(parentCounts.byteOffset)) {
  9966. parentCounts.componentType = defaultValue(parentCounts.componentType, GL.UNSIGNED_SHORT);
  9967. parentCounts.type = AttributeType.SCALAR;
  9968. binaryAccessor = getBinaryAccessor(parentCounts);
  9969. parentCounts = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentCounts.byteOffset, instancesLength);
  9970. }
  9971. parentIndexes = new Uint16Array(instancesLength);
  9972. parentIdsLength = 0;
  9973. for (i = 0; i < instancesLength; ++i) {
  9974. parentIndexes[i] = parentIdsLength;
  9975. parentIdsLength += parentCounts[i];
  9976. }
  9977. }
  9978. if (defined$1(parentIds) && defined$1(parentIds.byteOffset)) {
  9979. parentIds.componentType = defaultValue(parentIds.componentType, GL.UNSIGNED_SHORT);
  9980. parentIds.type = AttributeType.SCALAR;
  9981. binaryAccessor = getBinaryAccessor(parentIds);
  9982. parentIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentIds.byteOffset, parentIdsLength);
  9983. }
  9984. const classesLength = classes.length;
  9985. for (i = 0; i < classesLength; ++i) {
  9986. const classInstancesLength = classes[i].length;
  9987. const properties = classes[i].instances;
  9988. const binaryProperties = getBinaryProperties(classInstancesLength, properties, binaryBody);
  9989. classes[i].instances = combine(binaryProperties, properties);
  9990. }
  9991. const classCounts = new Array(classesLength).fill(0);
  9992. const classIndexes = new Uint16Array(instancesLength);
  9993. for (i = 0; i < instancesLength; ++i) {
  9994. classId = classIds[i];
  9995. classIndexes[i] = classCounts[classId];
  9996. ++classCounts[classId];
  9997. }
  9998. const hierarchy = {
  9999. classes,
  10000. classIds,
  10001. classIndexes,
  10002. parentCounts,
  10003. parentIndexes,
  10004. parentIds
  10005. };
  10006. validateHierarchy(hierarchy);
  10007. return hierarchy;
  10008. }
  10009. function traverseHierarchy(hierarchy, instanceIndex, endConditionCallback) {
  10010. if (!hierarchy) {
  10011. return;
  10012. }
  10013. const parentCounts = hierarchy.parentCounts;
  10014. const parentIds = hierarchy.parentIds;
  10015. if (parentIds) {
  10016. return endConditionCallback(hierarchy, instanceIndex);
  10017. }
  10018. if (parentCounts > 0) {
  10019. return traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback);
  10020. }
  10021. return traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback);
  10022. }
  10023. function traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback) {
  10024. const classIds = hierarchy.classIds;
  10025. const parentCounts = hierarchy.parentCounts;
  10026. const parentIds = hierarchy.parentIds;
  10027. const parentIndexes = hierarchy.parentIndexes;
  10028. const instancesLength = classIds.length;
  10029. const visited = scratchVisited;
  10030. visited.length = Math.max(visited.length, instancesLength);
  10031. const visitedMarker = ++marker;
  10032. const stack = scratchStack;
  10033. stack.length = 0;
  10034. stack.push(instanceIndex);
  10035. while (stack.length > 0) {
  10036. instanceIndex = stack.pop();
  10037. if (visited[instanceIndex] === visitedMarker) {
  10038. continue;
  10039. }
  10040. visited[instanceIndex] = visitedMarker;
  10041. const result = endConditionCallback(hierarchy, instanceIndex);
  10042. if (defined$1(result)) {
  10043. return result;
  10044. }
  10045. const parentCount = parentCounts[instanceIndex];
  10046. const parentIndex = parentIndexes[instanceIndex];
  10047. for (let i = 0; i < parentCount; ++i) {
  10048. const parentId = parentIds[parentIndex + i];
  10049. if (parentId !== instanceIndex) {
  10050. stack.push(parentId);
  10051. }
  10052. }
  10053. }
  10054. return null;
  10055. }
  10056. function traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback) {
  10057. let hasParent = true;
  10058. while (hasParent) {
  10059. const result = endConditionCallback(hierarchy, instanceIndex);
  10060. if (defined$1(result)) {
  10061. return result;
  10062. }
  10063. const parentId = hierarchy.parentIds[instanceIndex];
  10064. hasParent = parentId !== instanceIndex;
  10065. instanceIndex = parentId;
  10066. }
  10067. throw new Error('traverseHierarchySingleParent');
  10068. }
  10069. function validateHierarchy(hierarchy) {
  10070. const classIds = hierarchy.classIds;
  10071. const instancesLength = classIds.length;
  10072. for (let i = 0; i < instancesLength; ++i) {
  10073. validateInstance(hierarchy, i, stack);
  10074. }
  10075. }
  10076. function validateInstance(hierarchy, instanceIndex, stack) {
  10077. const parentCounts = hierarchy.parentCounts;
  10078. const parentIds = hierarchy.parentIds;
  10079. const parentIndexes = hierarchy.parentIndexes;
  10080. const classIds = hierarchy.classIds;
  10081. const instancesLength = classIds.length;
  10082. if (!defined$1(parentIds)) {
  10083. return;
  10084. }
  10085. assert(instanceIndex < instancesLength, "Parent index ".concat(instanceIndex, " exceeds the total number of instances: ").concat(instancesLength));
  10086. assert(stack.indexOf(instanceIndex) === -1, 'Circular dependency detected in the batch table hierarchy.');
  10087. stack.push(instanceIndex);
  10088. const parentCount = defined$1(parentCounts) ? parentCounts[instanceIndex] : 1;
  10089. const parentIndex = defined$1(parentCounts) ? parentIndexes[instanceIndex] : instanceIndex;
  10090. for (let i = 0; i < parentCount; ++i) {
  10091. const parentId = parentIds[parentIndex + i];
  10092. if (parentId !== instanceIndex) {
  10093. validateInstance(hierarchy, parentId, stack);
  10094. }
  10095. }
  10096. stack.pop(instanceIndex);
  10097. }
  10098. function defined(x) {
  10099. return x !== undefined && x !== null;
  10100. }
  10101. const clone = (x, y) => x;
  10102. const IGNORED_PROPERTY_FIELDS = {
  10103. HIERARCHY: true,
  10104. extensions: true,
  10105. extras: true
  10106. };
  10107. class Tile3DBatchTableParser {
  10108. constructor(json, binary, featureCount, options = {}) {
  10109. var _this$json;
  10110. _defineProperty(this, "json", void 0);
  10111. _defineProperty(this, "binary", void 0);
  10112. _defineProperty(this, "featureCount", void 0);
  10113. _defineProperty(this, "_extensions", void 0);
  10114. _defineProperty(this, "_properties", void 0);
  10115. _defineProperty(this, "_binaryProperties", void 0);
  10116. _defineProperty(this, "_hierarchy", void 0);
  10117. assert$7(featureCount >= 0);
  10118. this.json = json || {};
  10119. this.binary = binary;
  10120. this.featureCount = featureCount;
  10121. this._extensions = ((_this$json = this.json) === null || _this$json === void 0 ? void 0 : _this$json.extensions) || {};
  10122. this._properties = {};
  10123. for (const propertyName in this.json) {
  10124. if (!IGNORED_PROPERTY_FIELDS[propertyName]) {
  10125. this._properties[propertyName] = this.json[propertyName];
  10126. }
  10127. }
  10128. this._binaryProperties = this._initializeBinaryProperties();
  10129. if (options['3DTILES_batch_table_hierarchy']) {
  10130. this._hierarchy = initializeHierarchy(this, this.json, this.binary);
  10131. }
  10132. }
  10133. getExtension(extensionName) {
  10134. return this.json && this.json.extensions && this.json.extensions[extensionName];
  10135. }
  10136. memorySizeInBytes() {
  10137. return 0;
  10138. }
  10139. isClass(batchId, className) {
  10140. this._checkBatchId(batchId);
  10141. assert$7(typeof className === 'string', className);
  10142. if (this._hierarchy) {
  10143. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10144. const classId = hierarchy.classIds[instanceIndex];
  10145. const instanceClass = hierarchy.classes[classId];
  10146. return instanceClass.name === className;
  10147. });
  10148. return defined(result);
  10149. }
  10150. return false;
  10151. }
  10152. isExactClass(batchId, className) {
  10153. assert$7(typeof className === 'string', className);
  10154. return this.getExactClassName(batchId) === className;
  10155. }
  10156. getExactClassName(batchId) {
  10157. this._checkBatchId(batchId);
  10158. if (this._hierarchy) {
  10159. const classId = this._hierarchy.classIds[batchId];
  10160. const instanceClass = this._hierarchy.classes[classId];
  10161. return instanceClass.name;
  10162. }
  10163. return undefined;
  10164. }
  10165. hasProperty(batchId, name) {
  10166. this._checkBatchId(batchId);
  10167. assert$7(typeof name === 'string', name);
  10168. return defined(this._properties[name]) || this._hasPropertyInHierarchy(batchId, name);
  10169. }
  10170. getPropertyNames(batchId, results) {
  10171. this._checkBatchId(batchId);
  10172. results = defined(results) ? results : [];
  10173. results.length = 0;
  10174. const propertyNames = Object.keys(this._properties);
  10175. results.push(...propertyNames);
  10176. if (this._hierarchy) {
  10177. this._getPropertyNamesInHierarchy(batchId, results);
  10178. }
  10179. return results;
  10180. }
  10181. getProperty(batchId, name) {
  10182. this._checkBatchId(batchId);
  10183. assert$7(typeof name === 'string', name);
  10184. if (this._binaryProperties) {
  10185. const binaryProperty = this._binaryProperties[name];
  10186. if (defined(binaryProperty)) {
  10187. return this._getBinaryProperty(binaryProperty, batchId);
  10188. }
  10189. }
  10190. const propertyValues = this._properties[name];
  10191. if (defined(propertyValues)) {
  10192. return clone(propertyValues[batchId]);
  10193. }
  10194. if (this._hierarchy) {
  10195. const hierarchyProperty = this._getHierarchyProperty(batchId, name);
  10196. if (defined(hierarchyProperty)) {
  10197. return hierarchyProperty;
  10198. }
  10199. }
  10200. return undefined;
  10201. }
  10202. setProperty(batchId, name, value) {
  10203. const featureCount = this.featureCount;
  10204. this._checkBatchId(batchId);
  10205. assert$7(typeof name === 'string', name);
  10206. if (this._binaryProperties) {
  10207. const binaryProperty = this._binaryProperties[name];
  10208. if (binaryProperty) {
  10209. this._setBinaryProperty(binaryProperty, batchId, value);
  10210. return;
  10211. }
  10212. }
  10213. if (this._hierarchy) {
  10214. if (this._setHierarchyProperty(this, batchId, name, value)) {
  10215. return;
  10216. }
  10217. }
  10218. let propertyValues = this._properties[name];
  10219. if (!defined(propertyValues)) {
  10220. this._properties[name] = new Array(featureCount);
  10221. propertyValues = this._properties[name];
  10222. }
  10223. propertyValues[batchId] = clone(value);
  10224. }
  10225. _checkBatchId(batchId) {
  10226. const valid = batchId >= 0 && batchId < this.featureCount;
  10227. if (!valid) {
  10228. throw new Error('batchId not in range [0, featureCount - 1].');
  10229. }
  10230. }
  10231. _getBinaryProperty(binaryProperty, index) {
  10232. return binaryProperty.unpack(binaryProperty.typedArray, index);
  10233. }
  10234. _setBinaryProperty(binaryProperty, index, value) {
  10235. binaryProperty.pack(value, binaryProperty.typedArray, index);
  10236. }
  10237. _initializeBinaryProperties() {
  10238. let binaryProperties = null;
  10239. for (const name in this._properties) {
  10240. const property = this._properties[name];
  10241. const binaryProperty = this._initializeBinaryProperty(name, property);
  10242. if (binaryProperty) {
  10243. binaryProperties = binaryProperties || {};
  10244. binaryProperties[name] = binaryProperty;
  10245. }
  10246. }
  10247. return binaryProperties;
  10248. }
  10249. _initializeBinaryProperty(name, property) {
  10250. if ('byteOffset' in property) {
  10251. const tile3DAccessor = property;
  10252. assert$7(this.binary, "Property ".concat(name, " requires a batch table binary."));
  10253. assert$7(tile3DAccessor.type, "Property ".concat(name, " requires a type."));
  10254. const accessor = createTypedArrayFromAccessor(tile3DAccessor, this.binary.buffer, this.binary.byteOffset | 0, this.featureCount);
  10255. return {
  10256. typedArray: accessor.values,
  10257. componentCount: accessor.size,
  10258. unpack: accessor.unpacker,
  10259. pack: accessor.packer
  10260. };
  10261. }
  10262. return null;
  10263. }
  10264. _hasPropertyInHierarchy(batchId, name) {
  10265. if (!this._hierarchy) {
  10266. return false;
  10267. }
  10268. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10269. const classId = hierarchy.classIds[instanceIndex];
  10270. const instances = hierarchy.classes[classId].instances;
  10271. return defined(instances[name]);
  10272. });
  10273. return defined(result);
  10274. }
  10275. _getPropertyNamesInHierarchy(batchId, results) {
  10276. traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10277. const classId = hierarchy.classIds[instanceIndex];
  10278. const instances = hierarchy.classes[classId].instances;
  10279. for (const name in instances) {
  10280. if (instances.hasOwnProperty(name)) {
  10281. if (results.indexOf(name) === -1) {
  10282. results.push(name);
  10283. }
  10284. }
  10285. }
  10286. });
  10287. }
  10288. _getHierarchyProperty(batchId, name) {
  10289. return traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10290. const classId = hierarchy.classIds[instanceIndex];
  10291. const instanceClass = hierarchy.classes[classId];
  10292. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10293. const propertyValues = instanceClass.instances[name];
  10294. if (defined(propertyValues)) {
  10295. if (defined(propertyValues.typedArray)) {
  10296. return this._getBinaryProperty(propertyValues, indexInClass);
  10297. }
  10298. return clone(propertyValues[indexInClass]);
  10299. }
  10300. return null;
  10301. });
  10302. }
  10303. _setHierarchyProperty(batchTable, batchId, name, value) {
  10304. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  10305. const classId = hierarchy.classIds[instanceIndex];
  10306. const instanceClass = hierarchy.classes[classId];
  10307. const indexInClass = hierarchy.classIndexes[instanceIndex];
  10308. const propertyValues = instanceClass.instances[name];
  10309. if (defined(propertyValues)) {
  10310. assert$7(instanceIndex === batchId, "Inherited property \"".concat(name, "\" is read-only."));
  10311. if (defined(propertyValues.typedArray)) {
  10312. this._setBinaryProperty(propertyValues, indexInClass, value);
  10313. } else {
  10314. propertyValues[indexInClass] = clone(value);
  10315. }
  10316. return true;
  10317. }
  10318. return false;
  10319. });
  10320. return defined(result);
  10321. }
  10322. }
  10323. const SIZEOF_UINT32$1 = 4;
  10324. function parse3DTileHeaderSync(tile, arrayBuffer, byteOffset = 0) {
  10325. const view = new DataView(arrayBuffer);
  10326. tile.magic = view.getUint32(byteOffset, true);
  10327. byteOffset += SIZEOF_UINT32$1;
  10328. tile.version = view.getUint32(byteOffset, true);
  10329. byteOffset += SIZEOF_UINT32$1;
  10330. tile.byteLength = view.getUint32(byteOffset, true);
  10331. byteOffset += SIZEOF_UINT32$1;
  10332. if (tile.version !== 1) {
  10333. throw new Error("3D Tile Version ".concat(tile.version, " not supported"));
  10334. }
  10335. return byteOffset;
  10336. }
  10337. const SIZEOF_UINT32 = 4;
  10338. const DEPRECATION_WARNING = 'b3dm tile in legacy format.';
  10339. function parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset) {
  10340. const view = new DataView(arrayBuffer);
  10341. let batchLength;
  10342. tile.header = tile.header || {};
  10343. let featureTableJsonByteLength = view.getUint32(byteOffset, true);
  10344. byteOffset += SIZEOF_UINT32;
  10345. let featureTableBinaryByteLength = view.getUint32(byteOffset, true);
  10346. byteOffset += SIZEOF_UINT32;
  10347. let batchTableJsonByteLength = view.getUint32(byteOffset, true);
  10348. byteOffset += SIZEOF_UINT32;
  10349. let batchTableBinaryByteLength = view.getUint32(byteOffset, true);
  10350. byteOffset += SIZEOF_UINT32;
  10351. if (batchTableJsonByteLength >= 570425344) {
  10352. byteOffset -= SIZEOF_UINT32 * 2;
  10353. batchLength = featureTableJsonByteLength;
  10354. batchTableJsonByteLength = featureTableBinaryByteLength;
  10355. batchTableBinaryByteLength = 0;
  10356. featureTableJsonByteLength = 0;
  10357. featureTableBinaryByteLength = 0;
  10358. console.warn(DEPRECATION_WARNING);
  10359. } else if (batchTableBinaryByteLength >= 570425344) {
  10360. byteOffset -= SIZEOF_UINT32;
  10361. batchLength = batchTableJsonByteLength;
  10362. batchTableJsonByteLength = featureTableJsonByteLength;
  10363. batchTableBinaryByteLength = featureTableBinaryByteLength;
  10364. featureTableJsonByteLength = 0;
  10365. featureTableBinaryByteLength = 0;
  10366. console.warn(DEPRECATION_WARNING);
  10367. }
  10368. tile.header.featureTableJsonByteLength = featureTableJsonByteLength;
  10369. tile.header.featureTableBinaryByteLength = featureTableBinaryByteLength;
  10370. tile.header.batchTableJsonByteLength = batchTableJsonByteLength;
  10371. tile.header.batchTableBinaryByteLength = batchTableBinaryByteLength;
  10372. tile.header.batchLength = batchLength;
  10373. return byteOffset;
  10374. }
  10375. function parse3DTileTablesSync(tile, arrayBuffer, byteOffset, options) {
  10376. byteOffset = parse3DTileFeatureTable(tile, arrayBuffer, byteOffset);
  10377. byteOffset = parse3DTileBatchTable(tile, arrayBuffer, byteOffset);
  10378. return byteOffset;
  10379. }
  10380. function parse3DTileFeatureTable(tile, arrayBuffer, byteOffset, options) {
  10381. const {
  10382. featureTableJsonByteLength,
  10383. featureTableBinaryByteLength,
  10384. batchLength
  10385. } = tile.header;
  10386. tile.featureTableJson = {
  10387. BATCH_LENGTH: batchLength || 0
  10388. };
  10389. if (featureTableJsonByteLength > 0) {
  10390. const featureTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, featureTableJsonByteLength);
  10391. tile.featureTableJson = JSON.parse(featureTableString);
  10392. }
  10393. byteOffset += featureTableJsonByteLength;
  10394. tile.featureTableBinary = new Uint8Array(arrayBuffer, byteOffset, featureTableBinaryByteLength);
  10395. byteOffset += featureTableBinaryByteLength;
  10396. return byteOffset;
  10397. }
  10398. function parse3DTileBatchTable(tile, arrayBuffer, byteOffset, options) {
  10399. const {
  10400. batchTableJsonByteLength,
  10401. batchTableBinaryByteLength
  10402. } = tile.header;
  10403. if (batchTableJsonByteLength > 0) {
  10404. const batchTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, batchTableJsonByteLength);
  10405. tile.batchTableJson = JSON.parse(batchTableString);
  10406. byteOffset += batchTableJsonByteLength;
  10407. if (batchTableBinaryByteLength > 0) {
  10408. tile.batchTableBinary = new Uint8Array(arrayBuffer, byteOffset, batchTableBinaryByteLength);
  10409. tile.batchTableBinary = new Uint8Array(tile.batchTableBinary);
  10410. byteOffset += batchTableBinaryByteLength;
  10411. }
  10412. }
  10413. return byteOffset;
  10414. }
  10415. function normalize3DTileColorAttribute(tile, colors, batchTable) {
  10416. if (!colors && (!tile || !tile.batchIds || !batchTable)) {
  10417. return null;
  10418. }
  10419. const {
  10420. batchIds,
  10421. isRGB565,
  10422. pointCount
  10423. } = tile;
  10424. if (batchIds && batchTable) {
  10425. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10426. for (let i = 0; i < pointCount; i++) {
  10427. const batchId = batchIds[i];
  10428. const dimensions = batchTable.getProperty(batchId, 'dimensions');
  10429. const color = dimensions.map(d => d * 255);
  10430. colorArray[i * 3] = color[0];
  10431. colorArray[i * 3 + 1] = color[1];
  10432. colorArray[i * 3 + 2] = color[2];
  10433. }
  10434. return {
  10435. type: GL$1.UNSIGNED_BYTE,
  10436. value: colorArray,
  10437. size: 3,
  10438. normalized: true
  10439. };
  10440. }
  10441. if (isRGB565) {
  10442. const colorArray = new Uint8ClampedArray(pointCount * 3);
  10443. for (let i = 0; i < pointCount; i++) {
  10444. const color = decodeRGB565(colors[i]);
  10445. colorArray[i * 3] = color[0];
  10446. colorArray[i * 3 + 1] = color[1];
  10447. colorArray[i * 3 + 2] = color[2];
  10448. }
  10449. return {
  10450. type: GL$1.UNSIGNED_BYTE,
  10451. value: colorArray,
  10452. size: 3,
  10453. normalized: true
  10454. };
  10455. }
  10456. if (colors && colors.length === pointCount * 3) {
  10457. return {
  10458. type: GL$1.UNSIGNED_BYTE,
  10459. value: colors,
  10460. size: 3,
  10461. normalized: true
  10462. };
  10463. }
  10464. return {
  10465. type: GL$1.UNSIGNED_BYTE,
  10466. value: colors,
  10467. size: 4,
  10468. normalized: true
  10469. };
  10470. }
  10471. const scratchNormal = new Vector3();
  10472. function normalize3DTileNormalAttribute(tile, normals) {
  10473. if (!normals) {
  10474. return null;
  10475. }
  10476. if (tile.isOctEncoded16P) {
  10477. const decodedArray = new Float32Array(tile.pointsLength * 3);
  10478. for (let i = 0; i < tile.pointsLength; i++) {
  10479. octDecode(normals[i * 2], normals[i * 2 + 1], scratchNormal);
  10480. scratchNormal.toArray(decodedArray, i * 3);
  10481. }
  10482. return {
  10483. type: GL$1.FLOAT,
  10484. size: 2,
  10485. value: decodedArray
  10486. };
  10487. }
  10488. return {
  10489. type: GL$1.FLOAT,
  10490. size: 2,
  10491. value: normals
  10492. };
  10493. }
  10494. function normalize3DTilePositionAttribute(tile, positions, options) {
  10495. if (!tile.isQuantized) {
  10496. return positions;
  10497. }
  10498. if (options['3d-tiles'] && options['3d-tiles'].decodeQuantizedPositions) {
  10499. tile.isQuantized = false;
  10500. return decodeQuantizedPositions(tile, positions);
  10501. }
  10502. return {
  10503. type: GL$1.UNSIGNED_SHORT,
  10504. value: positions,
  10505. size: 3,
  10506. normalized: true
  10507. };
  10508. }
  10509. function decodeQuantizedPositions(tile, positions) {
  10510. const scratchPosition = new Vector3();
  10511. const decodedArray = new Float32Array(tile.pointCount * 3);
  10512. for (let i = 0; i < tile.pointCount; i++) {
  10513. 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);
  10514. }
  10515. return decodedArray;
  10516. }
  10517. async function parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context) {
  10518. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  10519. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  10520. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  10521. initializeTile(tile);
  10522. const {
  10523. featureTable,
  10524. batchTable
  10525. } = parsePointCloudTables(tile);
  10526. await parseDraco(tile, featureTable, batchTable, options, context);
  10527. parsePositions(tile, featureTable, options);
  10528. parseColors(tile, featureTable, batchTable);
  10529. parseNormals(tile, featureTable);
  10530. return byteOffset;
  10531. }
  10532. function initializeTile(tile) {
  10533. tile.attributes = {
  10534. positions: null,
  10535. colors: null,
  10536. normals: null,
  10537. batchIds: null
  10538. };
  10539. tile.isQuantized = false;
  10540. tile.isTranslucent = false;
  10541. tile.isRGB565 = false;
  10542. tile.isOctEncoded16P = false;
  10543. }
  10544. function parsePointCloudTables(tile) {
  10545. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  10546. const pointsLength = featureTable.getGlobalProperty('POINTS_LENGTH');
  10547. if (!Number.isFinite(pointsLength)) {
  10548. throw new Error('POINTS_LENGTH must be defined');
  10549. }
  10550. featureTable.featuresLength = pointsLength;
  10551. tile.featuresLength = pointsLength;
  10552. tile.pointsLength = pointsLength;
  10553. tile.pointCount = pointsLength;
  10554. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  10555. const batchTable = parseBatchIds(tile, featureTable);
  10556. return {
  10557. featureTable,
  10558. batchTable
  10559. };
  10560. }
  10561. function parsePositions(tile, featureTable, options) {
  10562. if (!tile.attributes.positions) {
  10563. if (featureTable.hasProperty('POSITION')) {
  10564. tile.attributes.positions = featureTable.getPropertyArray('POSITION', GL$1.FLOAT, 3);
  10565. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  10566. const positions = featureTable.getPropertyArray('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3);
  10567. tile.isQuantized = true;
  10568. tile.quantizedRange = (1 << 16) - 1;
  10569. tile.quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3);
  10570. if (!tile.quantizedVolumeScale) {
  10571. throw new Error('QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  10572. }
  10573. tile.quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3);
  10574. if (!tile.quantizedVolumeOffset) {
  10575. throw new Error('QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  10576. }
  10577. tile.attributes.positions = normalize3DTilePositionAttribute(tile, positions, options);
  10578. }
  10579. }
  10580. if (!tile.attributes.positions) {
  10581. throw new Error('Either POSITION or POSITION_QUANTIZED must be defined.');
  10582. }
  10583. }
  10584. function parseColors(tile, featureTable, batchTable) {
  10585. if (!tile.attributes.colors) {
  10586. let colors = null;
  10587. if (featureTable.hasProperty('RGBA')) {
  10588. colors = featureTable.getPropertyArray('RGBA', GL$1.UNSIGNED_BYTE, 4);
  10589. tile.isTranslucent = true;
  10590. } else if (featureTable.hasProperty('RGB')) {
  10591. colors = featureTable.getPropertyArray('RGB', GL$1.UNSIGNED_BYTE, 3);
  10592. } else if (featureTable.hasProperty('RGB565')) {
  10593. colors = featureTable.getPropertyArray('RGB565', GL$1.UNSIGNED_SHORT, 1);
  10594. tile.isRGB565 = true;
  10595. }
  10596. tile.attributes.colors = normalize3DTileColorAttribute(tile, colors, batchTable);
  10597. }
  10598. if (featureTable.hasProperty('CONSTANT_RGBA')) {
  10599. tile.constantRGBA = featureTable.getGlobalProperty('CONSTANT_RGBA', GL$1.UNSIGNED_BYTE, 4);
  10600. }
  10601. }
  10602. function parseNormals(tile, featureTable) {
  10603. if (!tile.attributes.normals) {
  10604. let normals = null;
  10605. if (featureTable.hasProperty('NORMAL')) {
  10606. normals = featureTable.getPropertyArray('NORMAL', GL$1.FLOAT, 3);
  10607. } else if (featureTable.hasProperty('NORMAL_OCT16P')) {
  10608. normals = featureTable.getPropertyArray('NORMAL_OCT16P', GL$1.UNSIGNED_BYTE, 2);
  10609. tile.isOctEncoded16P = true;
  10610. }
  10611. tile.attributes.normals = normalize3DTileNormalAttribute(tile, normals);
  10612. }
  10613. }
  10614. function parseBatchIds(tile, featureTable) {
  10615. let batchTable = null;
  10616. if (!tile.batchIds && featureTable.hasProperty('BATCH_ID')) {
  10617. tile.batchIds = featureTable.getPropertyArray('BATCH_ID', GL$1.UNSIGNED_SHORT, 1);
  10618. if (tile.batchIds) {
  10619. const batchFeatureLength = featureTable.getGlobalProperty('BATCH_LENGTH');
  10620. if (!batchFeatureLength) {
  10621. throw new Error('Global property: BATCH_LENGTH must be defined when BATCH_ID is defined.');
  10622. }
  10623. const {
  10624. batchTableJson,
  10625. batchTableBinary
  10626. } = tile;
  10627. batchTable = new Tile3DBatchTableParser(batchTableJson, batchTableBinary, batchFeatureLength);
  10628. }
  10629. }
  10630. return batchTable;
  10631. }
  10632. async function parseDraco(tile, featureTable, batchTable, options, context) {
  10633. let dracoBuffer;
  10634. let dracoFeatureTableProperties;
  10635. let dracoBatchTableProperties;
  10636. const batchTableDraco = tile.batchTableJson && tile.batchTableJson.extensions && tile.batchTableJson.extensions['3DTILES_draco_point_compression'];
  10637. if (batchTableDraco) {
  10638. dracoBatchTableProperties = batchTableDraco.properties;
  10639. }
  10640. const featureTableDraco = featureTable.getExtension('3DTILES_draco_point_compression');
  10641. if (featureTableDraco) {
  10642. dracoFeatureTableProperties = featureTableDraco.properties;
  10643. const dracoByteOffset = featureTableDraco.byteOffset;
  10644. const dracoByteLength = featureTableDraco.byteLength;
  10645. if (!dracoFeatureTableProperties || !Number.isFinite(dracoByteOffset) || !dracoByteLength) {
  10646. throw new Error('Draco properties, byteOffset, and byteLength must be defined');
  10647. }
  10648. dracoBuffer = tile.featureTableBinary.slice(dracoByteOffset, dracoByteOffset + dracoByteLength);
  10649. tile.hasPositions = Number.isFinite(dracoFeatureTableProperties.POSITION);
  10650. tile.hasColors = Number.isFinite(dracoFeatureTableProperties.RGB) || Number.isFinite(dracoFeatureTableProperties.RGBA);
  10651. tile.hasNormals = Number.isFinite(dracoFeatureTableProperties.NORMAL);
  10652. tile.hasBatchIds = Number.isFinite(dracoFeatureTableProperties.BATCH_ID);
  10653. tile.isTranslucent = Number.isFinite(dracoFeatureTableProperties.RGBA);
  10654. }
  10655. if (!dracoBuffer) {
  10656. return true;
  10657. }
  10658. const dracoData = {
  10659. buffer: dracoBuffer,
  10660. properties: { ...dracoFeatureTableProperties,
  10661. ...dracoBatchTableProperties
  10662. },
  10663. featureTableProperties: dracoFeatureTableProperties,
  10664. batchTableProperties: dracoBatchTableProperties,
  10665. dequantizeInShader: false
  10666. };
  10667. return await loadDraco(tile, dracoData, options, context);
  10668. }
  10669. async function loadDraco(tile, dracoData, options, context) {
  10670. const {
  10671. parse
  10672. } = context;
  10673. const dracoOptions = { ...options,
  10674. draco: { ...options.draco,
  10675. extraAttributes: dracoData.batchTableProperties || {}
  10676. }
  10677. };
  10678. delete dracoOptions['3d-tiles'];
  10679. const data = await parse(dracoData.buffer, DracoLoader, dracoOptions);
  10680. const decodedPositions = data.attributes.POSITION && data.attributes.POSITION.value;
  10681. const decodedColors = data.attributes.COLOR_0 && data.attributes.COLOR_0.value;
  10682. const decodedNormals = data.attributes.NORMAL && data.attributes.NORMAL.value;
  10683. const decodedBatchIds = data.attributes.BATCH_ID && data.attributes.BATCH_ID.value;
  10684. const isQuantizedDraco = decodedPositions && data.attributes.POSITION.value.quantization;
  10685. const isOctEncodedDraco = decodedNormals && data.attributes.NORMAL.value.quantization;
  10686. if (isQuantizedDraco) {
  10687. const quantization = data.POSITION.data.quantization;
  10688. const range = quantization.range;
  10689. tile.quantizedVolumeScale = new Vector3(range, range, range);
  10690. tile.quantizedVolumeOffset = new Vector3(quantization.minValues);
  10691. tile.quantizedRange = (1 << quantization.quantizationBits) - 1.0;
  10692. tile.isQuantizedDraco = true;
  10693. }
  10694. if (isOctEncodedDraco) {
  10695. tile.octEncodedRange = (1 << data.NORMAL.data.quantization.quantizationBits) - 1.0;
  10696. tile.isOctEncodedDraco = true;
  10697. }
  10698. const batchTableAttributes = {};
  10699. if (dracoData.batchTableProperties) {
  10700. for (const attributeName of Object.keys(dracoData.batchTableProperties)) {
  10701. if (data.attributes[attributeName] && data.attributes[attributeName].value) {
  10702. batchTableAttributes[attributeName.toLowerCase()] = data.attributes[attributeName].value;
  10703. }
  10704. }
  10705. }
  10706. tile.attributes = {
  10707. positions: decodedPositions,
  10708. colors: normalize3DTileColorAttribute(tile, decodedColors, undefined),
  10709. normals: decodedNormals,
  10710. batchIds: decodedBatchIds,
  10711. ...batchTableAttributes
  10712. };
  10713. }
  10714. const VERSION$3 = "3.1.4" ;
  10715. const VERSION$2 = "3.1.4" ;
  10716. const VERSION$1 = "3.1.4" ;
  10717. const BASIS_CDN_ENCODER_WASM = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.wasm");
  10718. const BASIS_CDN_ENCODER_JS = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.js");
  10719. let loadBasisTranscoderPromise;
  10720. async function loadBasisTrascoderModule(options) {
  10721. const modules = options.modules || {};
  10722. if (modules.basis) {
  10723. return modules.basis;
  10724. }
  10725. loadBasisTranscoderPromise = loadBasisTranscoderPromise || loadBasisTrascoder(options);
  10726. return await loadBasisTranscoderPromise;
  10727. }
  10728. async function loadBasisTrascoder(options) {
  10729. let BASIS = null;
  10730. let wasmBinary = null;
  10731. [BASIS, wasmBinary] = await Promise.all([await loadLibrary('basis_transcoder.js', 'textures', options), await loadLibrary('basis_transcoder.wasm', 'textures', options)]);
  10732. BASIS = BASIS || globalThis.BASIS;
  10733. return await initializeBasisTrascoderModule(BASIS, wasmBinary);
  10734. }
  10735. function initializeBasisTrascoderModule(BasisModule, wasmBinary) {
  10736. const options = {};
  10737. if (wasmBinary) {
  10738. options.wasmBinary = wasmBinary;
  10739. }
  10740. return new Promise(resolve => {
  10741. BasisModule(options).then(module => {
  10742. const {
  10743. BasisFile,
  10744. initializeBasis
  10745. } = module;
  10746. initializeBasis();
  10747. resolve({
  10748. BasisFile
  10749. });
  10750. });
  10751. });
  10752. }
  10753. let loadBasisEncoderPromise;
  10754. async function loadBasisEncoderModule(options) {
  10755. const modules = options.modules || {};
  10756. if (modules.basisEncoder) {
  10757. return modules.basisEncoder;
  10758. }
  10759. loadBasisEncoderPromise = loadBasisEncoderPromise || loadBasisEncoder(options);
  10760. return await loadBasisEncoderPromise;
  10761. }
  10762. async function loadBasisEncoder(options) {
  10763. let BASIS_ENCODER = null;
  10764. let wasmBinary = null;
  10765. [BASIS_ENCODER, wasmBinary] = await Promise.all([await loadLibrary(BASIS_CDN_ENCODER_JS, 'textures', options), await loadLibrary(BASIS_CDN_ENCODER_WASM, 'textures', options)]);
  10766. BASIS_ENCODER = BASIS_ENCODER || globalThis.BASIS;
  10767. return await initializeBasisEncoderModule(BASIS_ENCODER, wasmBinary);
  10768. }
  10769. function initializeBasisEncoderModule(BasisEncoderModule, wasmBinary) {
  10770. const options = {};
  10771. if (wasmBinary) {
  10772. options.wasmBinary = wasmBinary;
  10773. }
  10774. return new Promise(resolve => {
  10775. BasisEncoderModule(options).then(module => {
  10776. const {
  10777. BasisFile,
  10778. KTX2File,
  10779. initializeBasis,
  10780. BasisEncoder
  10781. } = module;
  10782. initializeBasis();
  10783. resolve({
  10784. BasisFile,
  10785. KTX2File,
  10786. BasisEncoder
  10787. });
  10788. });
  10789. });
  10790. }
  10791. const GL_EXTENSIONS_CONSTANTS = {
  10792. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83f0,
  10793. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83f1,
  10794. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83f2,
  10795. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83f3,
  10796. COMPRESSED_R11_EAC: 0x9270,
  10797. COMPRESSED_SIGNED_R11_EAC: 0x9271,
  10798. COMPRESSED_RG11_EAC: 0x9272,
  10799. COMPRESSED_SIGNED_RG11_EAC: 0x9273,
  10800. COMPRESSED_RGB8_ETC2: 0x9274,
  10801. COMPRESSED_RGBA8_ETC2_EAC: 0x9275,
  10802. COMPRESSED_SRGB8_ETC2: 0x9276,
  10803. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: 0x9277,
  10804. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9278,
  10805. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9279,
  10806. COMPRESSED_RGB_PVRTC_4BPPV1_IMG: 0x8c00,
  10807. COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: 0x8c02,
  10808. COMPRESSED_RGB_PVRTC_2BPPV1_IMG: 0x8c01,
  10809. COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: 0x8c03,
  10810. COMPRESSED_RGB_ETC1_WEBGL: 0x8d64,
  10811. COMPRESSED_RGB_ATC_WEBGL: 0x8c92,
  10812. COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL: 0x8c93,
  10813. COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL: 0x87ee,
  10814. COMPRESSED_RGBA_ASTC_4X4_KHR: 0x93b0,
  10815. COMPRESSED_RGBA_ASTC_5X4_KHR: 0x93b1,
  10816. COMPRESSED_RGBA_ASTC_5X5_KHR: 0x93b2,
  10817. COMPRESSED_RGBA_ASTC_6X5_KHR: 0x93b3,
  10818. COMPRESSED_RGBA_ASTC_6X6_KHR: 0x93b4,
  10819. COMPRESSED_RGBA_ASTC_8X5_KHR: 0x93b5,
  10820. COMPRESSED_RGBA_ASTC_8X6_KHR: 0x93b6,
  10821. COMPRESSED_RGBA_ASTC_8X8_KHR: 0x93b7,
  10822. COMPRESSED_RGBA_ASTC_10X5_KHR: 0x93b8,
  10823. COMPRESSED_RGBA_ASTC_10X6_KHR: 0x93b9,
  10824. COMPRESSED_RGBA_ASTC_10X8_KHR: 0x93ba,
  10825. COMPRESSED_RGBA_ASTC_10X10_KHR: 0x93bb,
  10826. COMPRESSED_RGBA_ASTC_12X10_KHR: 0x93bc,
  10827. COMPRESSED_RGBA_ASTC_12X12_KHR: 0x93bd,
  10828. COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR: 0x93d0,
  10829. COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR: 0x93d1,
  10830. COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR: 0x93d2,
  10831. COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR: 0x93d3,
  10832. COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR: 0x93d4,
  10833. COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR: 0x93d5,
  10834. COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR: 0x93d6,
  10835. COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR: 0x93d7,
  10836. COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR: 0x93d8,
  10837. COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR: 0x93d9,
  10838. COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR: 0x93da,
  10839. COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR: 0x93db,
  10840. COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR: 0x93dc,
  10841. COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR: 0x93dd,
  10842. COMPRESSED_RED_RGTC1_EXT: 0x8dbb,
  10843. COMPRESSED_SIGNED_RED_RGTC1_EXT: 0x8dbc,
  10844. COMPRESSED_RED_GREEN_RGTC2_EXT: 0x8dbd,
  10845. COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT: 0x8dbe,
  10846. COMPRESSED_SRGB_S3TC_DXT1_EXT: 0x8c4c,
  10847. COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: 0x8c4d,
  10848. COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: 0x8c4e,
  10849. COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: 0x8c4f
  10850. };
  10851. const BROWSER_PREFIXES = ['', 'WEBKIT_', 'MOZ_'];
  10852. const WEBGL_EXTENSIONS = {
  10853. WEBGL_compressed_texture_s3tc: 'dxt',
  10854. WEBGL_compressed_texture_s3tc_srgb: 'dxt-srgb',
  10855. WEBGL_compressed_texture_etc1: 'etc1',
  10856. WEBGL_compressed_texture_etc: 'etc2',
  10857. WEBGL_compressed_texture_pvrtc: 'pvrtc',
  10858. WEBGL_compressed_texture_atc: 'atc',
  10859. WEBGL_compressed_texture_astc: 'astc',
  10860. EXT_texture_compression_rgtc: 'rgtc'
  10861. };
  10862. let formats = null;
  10863. function getSupportedGPUTextureFormats(gl) {
  10864. if (!formats) {
  10865. gl = gl || getWebGLContext() || undefined;
  10866. formats = new Set();
  10867. for (const prefix of BROWSER_PREFIXES) {
  10868. for (const extension in WEBGL_EXTENSIONS) {
  10869. if (gl && gl.getExtension("".concat(prefix).concat(extension))) {
  10870. const gpuTextureFormat = WEBGL_EXTENSIONS[extension];
  10871. formats.add(gpuTextureFormat);
  10872. }
  10873. }
  10874. }
  10875. }
  10876. return formats;
  10877. }
  10878. function getWebGLContext() {
  10879. try {
  10880. const canvas = document.createElement('canvas');
  10881. return canvas.getContext('webgl');
  10882. } catch (error) {
  10883. return null;
  10884. }
  10885. }
  10886. 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={}));
  10887. const KTX2_ID = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];
  10888. function isKTX(data) {
  10889. const id = new Uint8Array(data);
  10890. 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];
  10891. return !notKTX;
  10892. }
  10893. const OutputFormat = {
  10894. etc1: {
  10895. basisFormat: 0,
  10896. compressed: true,
  10897. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_ETC1_WEBGL
  10898. },
  10899. etc2: {
  10900. basisFormat: 1,
  10901. compressed: true
  10902. },
  10903. bc1: {
  10904. basisFormat: 2,
  10905. compressed: true,
  10906. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_S3TC_DXT1_EXT
  10907. },
  10908. bc3: {
  10909. basisFormat: 3,
  10910. compressed: true,
  10911. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_S3TC_DXT5_EXT
  10912. },
  10913. bc4: {
  10914. basisFormat: 4,
  10915. compressed: true
  10916. },
  10917. bc5: {
  10918. basisFormat: 5,
  10919. compressed: true
  10920. },
  10921. 'bc7-m6-opaque-only': {
  10922. basisFormat: 6,
  10923. compressed: true
  10924. },
  10925. 'bc7-m5': {
  10926. basisFormat: 7,
  10927. compressed: true
  10928. },
  10929. 'pvrtc1-4-rgb': {
  10930. basisFormat: 8,
  10931. compressed: true,
  10932. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG
  10933. },
  10934. 'pvrtc1-4-rgba': {
  10935. basisFormat: 9,
  10936. compressed: true,
  10937. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG
  10938. },
  10939. 'astc-4x4': {
  10940. basisFormat: 10,
  10941. compressed: true,
  10942. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_4X4_KHR
  10943. },
  10944. 'atc-rgb': {
  10945. basisFormat: 11,
  10946. compressed: true
  10947. },
  10948. 'atc-rgba-interpolated-alpha': {
  10949. basisFormat: 12,
  10950. compressed: true
  10951. },
  10952. rgba32: {
  10953. basisFormat: 13,
  10954. compressed: false
  10955. },
  10956. rgb565: {
  10957. basisFormat: 14,
  10958. compressed: false
  10959. },
  10960. bgr565: {
  10961. basisFormat: 15,
  10962. compressed: false
  10963. },
  10964. rgba4444: {
  10965. basisFormat: 16,
  10966. compressed: false
  10967. }
  10968. };
  10969. async function parseBasis(data, options) {
  10970. if (options.basis.containerFormat === 'auto') {
  10971. if (isKTX(data)) {
  10972. const fileConstructors = await loadBasisEncoderModule(options);
  10973. return parseKTX2File(fileConstructors.KTX2File, data, options);
  10974. }
  10975. const {
  10976. BasisFile
  10977. } = await loadBasisTrascoderModule(options);
  10978. return parseBasisFile(BasisFile, data, options);
  10979. }
  10980. switch (options.basis.module) {
  10981. case 'encoder':
  10982. const fileConstructors = await loadBasisEncoderModule(options);
  10983. switch (options.basis.containerFormat) {
  10984. case 'ktx2':
  10985. return parseKTX2File(fileConstructors.KTX2File, data, options);
  10986. case 'basis':
  10987. default:
  10988. return parseBasisFile(fileConstructors.BasisFile, data, options);
  10989. }
  10990. case 'transcoder':
  10991. default:
  10992. const {
  10993. BasisFile
  10994. } = await loadBasisTrascoderModule(options);
  10995. return parseBasisFile(BasisFile, data, options);
  10996. }
  10997. }
  10998. function parseBasisFile(BasisFile, data, options) {
  10999. const basisFile = new BasisFile(new Uint8Array(data));
  11000. try {
  11001. if (!basisFile.startTranscoding()) {
  11002. return null;
  11003. }
  11004. const imageCount = basisFile.getNumImages();
  11005. const images = [];
  11006. for (let imageIndex = 0; imageIndex < imageCount; imageIndex++) {
  11007. const levelsCount = basisFile.getNumLevels(imageIndex);
  11008. const levels = [];
  11009. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  11010. levels.push(transcodeImage(basisFile, imageIndex, levelIndex, options));
  11011. }
  11012. images.push(levels);
  11013. }
  11014. return images;
  11015. } finally {
  11016. basisFile.close();
  11017. basisFile.delete();
  11018. }
  11019. }
  11020. function transcodeImage(basisFile, imageIndex, levelIndex, options) {
  11021. const width = basisFile.getImageWidth(imageIndex, levelIndex);
  11022. const height = basisFile.getImageHeight(imageIndex, levelIndex);
  11023. const hasAlpha = basisFile.getHasAlpha();
  11024. const {
  11025. compressed,
  11026. format,
  11027. basisFormat
  11028. } = getBasisOptions(options, hasAlpha);
  11029. const decodedSize = basisFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, basisFormat);
  11030. const decodedData = new Uint8Array(decodedSize);
  11031. if (!basisFile.transcodeImage(decodedData, imageIndex, levelIndex, basisFormat, 0, 0)) {
  11032. return null;
  11033. }
  11034. return {
  11035. width,
  11036. height,
  11037. data: decodedData,
  11038. compressed,
  11039. hasAlpha,
  11040. format
  11041. };
  11042. }
  11043. function parseKTX2File(KTX2File, data, options) {
  11044. const ktx2File = new KTX2File(new Uint8Array(data));
  11045. try {
  11046. if (!ktx2File.startTranscoding()) {
  11047. return null;
  11048. }
  11049. const levelsCount = ktx2File.getLevels();
  11050. const levels = [];
  11051. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  11052. levels.push(transcodeKTX2Image(ktx2File, levelIndex, options));
  11053. break;
  11054. }
  11055. return levels;
  11056. } finally {
  11057. ktx2File.close();
  11058. ktx2File.delete();
  11059. }
  11060. }
  11061. function transcodeKTX2Image(ktx2File, levelIndex, options) {
  11062. const {
  11063. alphaFlag,
  11064. height,
  11065. width
  11066. } = ktx2File.getImageLevelInfo(levelIndex, 0, 0);
  11067. const {
  11068. compressed,
  11069. format,
  11070. basisFormat
  11071. } = getBasisOptions(options, alphaFlag);
  11072. const decodedSize = ktx2File.getImageTranscodedSizeInBytes(levelIndex, 0, 0, basisFormat);
  11073. const decodedData = new Uint8Array(decodedSize);
  11074. if (!ktx2File.transcodeImage(decodedData, levelIndex, 0, 0, basisFormat, 0, -1, -1)) {
  11075. return null;
  11076. }
  11077. return {
  11078. width,
  11079. height,
  11080. data: decodedData,
  11081. compressed,
  11082. alphaFlag,
  11083. format
  11084. };
  11085. }
  11086. function getBasisOptions(options, hasAlpha) {
  11087. let format = options && options.basis && options.basis.format;
  11088. if (format === 'auto') {
  11089. format = selectSupportedBasisFormat();
  11090. }
  11091. if (typeof format === 'object') {
  11092. format = hasAlpha ? format.alpha : format.noAlpha;
  11093. }
  11094. format = format.toLowerCase();
  11095. return OutputFormat[format];
  11096. }
  11097. function selectSupportedBasisFormat() {
  11098. const supportedFormats = getSupportedGPUTextureFormats();
  11099. if (supportedFormats.has('astc')) {
  11100. return 'astc-4x4';
  11101. } else if (supportedFormats.has('dxt')) {
  11102. return {
  11103. alpha: 'bc3',
  11104. noAlpha: 'bc1'
  11105. };
  11106. } else if (supportedFormats.has('pvrtc')) {
  11107. return {
  11108. alpha: 'pvrtc1-4-rgba',
  11109. noAlpha: 'pvrtc1-4-rgb'
  11110. };
  11111. } else if (supportedFormats.has('etc1')) {
  11112. return 'etc1';
  11113. } else if (supportedFormats.has('etc2')) {
  11114. return 'etc2';
  11115. }
  11116. return 'rgb565';
  11117. }
  11118. const BasisWorkerLoader = {
  11119. name: 'Basis',
  11120. id: 'basis',
  11121. module: 'textures',
  11122. version: VERSION$2,
  11123. worker: true,
  11124. extensions: ['basis', 'ktx2'],
  11125. mimeTypes: ['application/octet-stream', 'image/ktx2'],
  11126. tests: ['sB'],
  11127. binary: true,
  11128. options: {
  11129. basis: {
  11130. format: 'auto',
  11131. libraryPath: 'libs/',
  11132. containerFormat: 'auto',
  11133. module: 'transcoder'
  11134. }
  11135. }
  11136. };
  11137. const BasisLoader = { ...BasisWorkerLoader,
  11138. parse: parseBasis
  11139. };
  11140. const VERSION = "3.1.4" ;
  11141. const {
  11142. _parseImageNode
  11143. } = globalThis;
  11144. const IMAGE_SUPPORTED = typeof Image !== 'undefined';
  11145. const IMAGE_BITMAP_SUPPORTED = typeof ImageBitmap !== 'undefined';
  11146. const NODE_IMAGE_SUPPORTED = Boolean(_parseImageNode);
  11147. const DATA_SUPPORTED = isBrowser$2 ? true : NODE_IMAGE_SUPPORTED;
  11148. function isImageTypeSupported(type) {
  11149. switch (type) {
  11150. case 'auto':
  11151. return IMAGE_BITMAP_SUPPORTED || IMAGE_SUPPORTED || DATA_SUPPORTED;
  11152. case 'imagebitmap':
  11153. return IMAGE_BITMAP_SUPPORTED;
  11154. case 'image':
  11155. return IMAGE_SUPPORTED;
  11156. case 'data':
  11157. return DATA_SUPPORTED;
  11158. default:
  11159. throw new Error("@loaders.gl/images: image ".concat(type, " not supported in this environment"));
  11160. }
  11161. }
  11162. function getDefaultImageType() {
  11163. if (IMAGE_BITMAP_SUPPORTED) {
  11164. return 'imagebitmap';
  11165. }
  11166. if (IMAGE_SUPPORTED) {
  11167. return 'image';
  11168. }
  11169. if (DATA_SUPPORTED) {
  11170. return 'data';
  11171. }
  11172. throw new Error('Install \'@loaders.gl/polyfills\' to parse images under Node.js');
  11173. }
  11174. function getImageType(image) {
  11175. const format = getImageTypeOrNull(image);
  11176. if (!format) {
  11177. throw new Error('Not an image');
  11178. }
  11179. return format;
  11180. }
  11181. function getImageData(image) {
  11182. switch (getImageType(image)) {
  11183. case 'data':
  11184. return image;
  11185. case 'image':
  11186. case 'imagebitmap':
  11187. const canvas = document.createElement('canvas');
  11188. const context = canvas.getContext('2d');
  11189. if (!context) {
  11190. throw new Error('getImageData');
  11191. }
  11192. canvas.width = image.width;
  11193. canvas.height = image.height;
  11194. context.drawImage(image, 0, 0);
  11195. return context.getImageData(0, 0, image.width, image.height);
  11196. default:
  11197. throw new Error('getImageData');
  11198. }
  11199. }
  11200. function getImageTypeOrNull(image) {
  11201. if (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  11202. return 'imagebitmap';
  11203. }
  11204. if (typeof Image !== 'undefined' && image instanceof Image) {
  11205. return 'image';
  11206. }
  11207. if (image && typeof image === 'object' && image.data && image.width && image.height) {
  11208. return 'data';
  11209. }
  11210. return null;
  11211. }
  11212. const SVG_DATA_URL_PATTERN = /^data:image\/svg\+xml/;
  11213. const SVG_URL_PATTERN = /\.svg((\?|#).*)?$/;
  11214. function isSVG(url) {
  11215. return url && (SVG_DATA_URL_PATTERN.test(url) || SVG_URL_PATTERN.test(url));
  11216. }
  11217. function getBlobOrSVGDataUrl(arrayBuffer, url) {
  11218. if (isSVG(url)) {
  11219. const textDecoder = new TextDecoder();
  11220. let xmlText = textDecoder.decode(arrayBuffer);
  11221. try {
  11222. if (typeof unescape === 'function' && typeof encodeURIComponent === 'function') {
  11223. xmlText = unescape(encodeURIComponent(xmlText));
  11224. }
  11225. } catch (error) {
  11226. throw new Error(error.message);
  11227. }
  11228. const src = "data:image/svg+xml;base64,".concat(btoa(xmlText));
  11229. return src;
  11230. }
  11231. return getBlob(arrayBuffer, url);
  11232. }
  11233. function getBlob(arrayBuffer, url) {
  11234. if (isSVG(url)) {
  11235. throw new Error('SVG cannot be parsed directly to imagebitmap');
  11236. }
  11237. return new Blob([new Uint8Array(arrayBuffer)]);
  11238. }
  11239. async function parseToImage(arrayBuffer, options, url) {
  11240. const blobOrDataUrl = getBlobOrSVGDataUrl(arrayBuffer, url);
  11241. const URL = self.URL || self.webkitURL;
  11242. const objectUrl = typeof blobOrDataUrl !== 'string' && URL.createObjectURL(blobOrDataUrl);
  11243. try {
  11244. return await loadToImage(objectUrl || blobOrDataUrl, options);
  11245. } finally {
  11246. if (objectUrl) {
  11247. URL.revokeObjectURL(objectUrl);
  11248. }
  11249. }
  11250. }
  11251. async function loadToImage(url, options) {
  11252. const image = new Image();
  11253. image.src = url;
  11254. if (options.image && options.image.decode && image.decode) {
  11255. await image.decode();
  11256. return image;
  11257. }
  11258. return await new Promise((resolve, reject) => {
  11259. try {
  11260. image.onload = () => resolve(image);
  11261. image.onerror = err => reject(new Error("Could not load image ".concat(url, ": ").concat(err)));
  11262. } catch (error) {
  11263. reject(error);
  11264. }
  11265. });
  11266. }
  11267. const EMPTY_OBJECT = {};
  11268. let imagebitmapOptionsSupported = true;
  11269. async function parseToImageBitmap(arrayBuffer, options, url) {
  11270. let blob;
  11271. if (isSVG(url)) {
  11272. const image = await parseToImage(arrayBuffer, options, url);
  11273. blob = image;
  11274. } else {
  11275. blob = getBlob(arrayBuffer, url);
  11276. }
  11277. const imagebitmapOptions = options && options.imagebitmap;
  11278. return await safeCreateImageBitmap(blob, imagebitmapOptions);
  11279. }
  11280. async function safeCreateImageBitmap(blob, imagebitmapOptions = null) {
  11281. if (isEmptyObject(imagebitmapOptions) || !imagebitmapOptionsSupported) {
  11282. imagebitmapOptions = null;
  11283. }
  11284. if (imagebitmapOptions) {
  11285. try {
  11286. return await createImageBitmap(blob, imagebitmapOptions);
  11287. } catch (error) {
  11288. console.warn(error);
  11289. imagebitmapOptionsSupported = false;
  11290. }
  11291. }
  11292. return await createImageBitmap(blob);
  11293. }
  11294. function isEmptyObject(object) {
  11295. for (const key in object || EMPTY_OBJECT) {
  11296. return false;
  11297. }
  11298. return true;
  11299. }
  11300. const BIG_ENDIAN = false;
  11301. const LITTLE_ENDIAN = true;
  11302. function getBinaryImageMetadata(binaryData) {
  11303. const dataView = toDataView(binaryData);
  11304. return getPngMetadata(dataView) || getJpegMetadata(dataView) || getGifMetadata(dataView) || getBmpMetadata(dataView);
  11305. }
  11306. function getPngMetadata(binaryData) {
  11307. const dataView = toDataView(binaryData);
  11308. const isPng = dataView.byteLength >= 24 && dataView.getUint32(0, BIG_ENDIAN) === 0x89504e47;
  11309. if (!isPng) {
  11310. return null;
  11311. }
  11312. return {
  11313. mimeType: 'image/png',
  11314. width: dataView.getUint32(16, BIG_ENDIAN),
  11315. height: dataView.getUint32(20, BIG_ENDIAN)
  11316. };
  11317. }
  11318. function getGifMetadata(binaryData) {
  11319. const dataView = toDataView(binaryData);
  11320. const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 0x47494638;
  11321. if (!isGif) {
  11322. return null;
  11323. }
  11324. return {
  11325. mimeType: 'image/gif',
  11326. width: dataView.getUint16(6, LITTLE_ENDIAN),
  11327. height: dataView.getUint16(8, LITTLE_ENDIAN)
  11328. };
  11329. }
  11330. function getBmpMetadata(binaryData) {
  11331. const dataView = toDataView(binaryData);
  11332. const isBmp = dataView.byteLength >= 14 && dataView.getUint16(0, BIG_ENDIAN) === 0x424d && dataView.getUint32(2, LITTLE_ENDIAN) === dataView.byteLength;
  11333. if (!isBmp) {
  11334. return null;
  11335. }
  11336. return {
  11337. mimeType: 'image/bmp',
  11338. width: dataView.getUint32(18, LITTLE_ENDIAN),
  11339. height: dataView.getUint32(22, LITTLE_ENDIAN)
  11340. };
  11341. }
  11342. function getJpegMetadata(binaryData) {
  11343. const dataView = toDataView(binaryData);
  11344. const isJpeg = dataView.byteLength >= 3 && dataView.getUint16(0, BIG_ENDIAN) === 0xffd8 && dataView.getUint8(2) === 0xff;
  11345. if (!isJpeg) {
  11346. return null;
  11347. }
  11348. const {
  11349. tableMarkers,
  11350. sofMarkers
  11351. } = getJpegMarkers();
  11352. let i = 2;
  11353. while (i + 9 < dataView.byteLength) {
  11354. const marker = dataView.getUint16(i, BIG_ENDIAN);
  11355. if (sofMarkers.has(marker)) {
  11356. return {
  11357. mimeType: 'image/jpeg',
  11358. height: dataView.getUint16(i + 5, BIG_ENDIAN),
  11359. width: dataView.getUint16(i + 7, BIG_ENDIAN)
  11360. };
  11361. }
  11362. if (!tableMarkers.has(marker)) {
  11363. return null;
  11364. }
  11365. i += 2;
  11366. i += dataView.getUint16(i, BIG_ENDIAN);
  11367. }
  11368. return null;
  11369. }
  11370. function getJpegMarkers() {
  11371. const tableMarkers = new Set([0xffdb, 0xffc4, 0xffcc, 0xffdd, 0xfffe]);
  11372. for (let i = 0xffe0; i < 0xfff0; ++i) {
  11373. tableMarkers.add(i);
  11374. }
  11375. const sofMarkers = new Set([0xffc0, 0xffc1, 0xffc2, 0xffc3, 0xffc5, 0xffc6, 0xffc7, 0xffc9, 0xffca, 0xffcb, 0xffcd, 0xffce, 0xffcf, 0xffde]);
  11376. return {
  11377. tableMarkers,
  11378. sofMarkers
  11379. };
  11380. }
  11381. function toDataView(data) {
  11382. if (data instanceof DataView) {
  11383. return data;
  11384. }
  11385. if (ArrayBuffer.isView(data)) {
  11386. return new DataView(data.buffer);
  11387. }
  11388. if (data instanceof ArrayBuffer) {
  11389. return new DataView(data);
  11390. }
  11391. throw new Error('toDataView');
  11392. }
  11393. async function parseToNodeImage(arrayBuffer, options) {
  11394. const {
  11395. mimeType
  11396. } = getBinaryImageMetadata(arrayBuffer) || {};
  11397. const _parseImageNode = globalThis._parseImageNode;
  11398. assert$7(_parseImageNode);
  11399. return await _parseImageNode(arrayBuffer, mimeType);
  11400. }
  11401. async function parseImage(arrayBuffer, options, context) {
  11402. options = options || {};
  11403. const imageOptions = options.image || {};
  11404. const imageType = imageOptions.type || 'auto';
  11405. const {
  11406. url
  11407. } = context || {};
  11408. const loadType = getLoadableImageType(imageType);
  11409. let image;
  11410. switch (loadType) {
  11411. case 'imagebitmap':
  11412. image = await parseToImageBitmap(arrayBuffer, options, url);
  11413. break;
  11414. case 'image':
  11415. image = await parseToImage(arrayBuffer, options, url);
  11416. break;
  11417. case 'data':
  11418. image = await parseToNodeImage(arrayBuffer);
  11419. break;
  11420. default:
  11421. assert$7(false);
  11422. }
  11423. if (imageType === 'data') {
  11424. image = getImageData(image);
  11425. }
  11426. return image;
  11427. }
  11428. function getLoadableImageType(type) {
  11429. switch (type) {
  11430. case 'auto':
  11431. case 'data':
  11432. return getDefaultImageType();
  11433. default:
  11434. isImageTypeSupported(type);
  11435. return type;
  11436. }
  11437. }
  11438. const EXTENSIONS$1 = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'svg'];
  11439. const MIME_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'image/vnd.microsoft.icon', 'image/svg+xml'];
  11440. const DEFAULT_IMAGE_LOADER_OPTIONS = {
  11441. image: {
  11442. type: 'auto',
  11443. decode: true
  11444. }
  11445. };
  11446. const ImageLoader = {
  11447. id: 'image',
  11448. module: 'images',
  11449. name: 'Images',
  11450. version: VERSION,
  11451. mimeTypes: MIME_TYPES,
  11452. extensions: EXTENSIONS$1,
  11453. parse: parseImage,
  11454. tests: [arrayBuffer => Boolean(getBinaryImageMetadata(new DataView(arrayBuffer)))],
  11455. options: DEFAULT_IMAGE_LOADER_OPTIONS
  11456. };
  11457. const NODE_FORMAT_SUPPORT = ['image/png', 'image/jpeg', 'image/gif'];
  11458. const mimeTypeSupported = {};
  11459. function _isImageFormatSupported(mimeType) {
  11460. if (mimeTypeSupported[mimeType] === undefined) {
  11461. mimeTypeSupported[mimeType] = checkFormatSupport(mimeType);
  11462. }
  11463. return mimeTypeSupported[mimeType];
  11464. }
  11465. function checkFormatSupport(mimeType) {
  11466. switch (mimeType) {
  11467. case 'image/webp':
  11468. return checkWebPSupport();
  11469. case 'image/svg':
  11470. return isBrowser$2;
  11471. default:
  11472. if (!isBrowser$2) {
  11473. const {
  11474. _parseImageNode
  11475. } = globalThis;
  11476. return Boolean(_parseImageNode) && NODE_FORMAT_SUPPORT.includes(mimeType);
  11477. }
  11478. return true;
  11479. }
  11480. }
  11481. function checkWebPSupport() {
  11482. if (!isBrowser$2) {
  11483. return false;
  11484. }
  11485. try {
  11486. const element = document.createElement('canvas');
  11487. return element.toDataURL('image/webp').indexOf('data:image/webp') === 0;
  11488. } catch {
  11489. return false;
  11490. }
  11491. }
  11492. function assert$1(condition, message) {
  11493. if (!condition) {
  11494. throw new Error(message || 'assert failed: gltf');
  11495. }
  11496. }
  11497. function resolveUrl(url, options) {
  11498. const absolute = url.startsWith('data:') || url.startsWith('http:') || url.startsWith('https:');
  11499. if (absolute) {
  11500. return url;
  11501. }
  11502. const baseUrl = options.baseUri || options.uri;
  11503. if (!baseUrl) {
  11504. throw new Error("'baseUri' must be provided to resolve relative url ".concat(url));
  11505. }
  11506. return baseUrl.substr(0, baseUrl.lastIndexOf('/') + 1) + url;
  11507. }
  11508. function getTypedArrayForBufferView(json, buffers, bufferViewIndex) {
  11509. const bufferView = json.bufferViews[bufferViewIndex];
  11510. assert$1(bufferView);
  11511. const bufferIndex = bufferView.buffer;
  11512. const binChunk = buffers[bufferIndex];
  11513. assert$1(binChunk);
  11514. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  11515. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  11516. }
  11517. const TYPES = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'];
  11518. const ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT = [[Int8Array, 5120], [Uint8Array, 5121], [Int16Array, 5122], [Uint16Array, 5123], [Uint32Array, 5125], [Float32Array, 5126], [Float64Array, 5130]];
  11519. const ARRAY_TO_COMPONENT_TYPE = new Map(ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT);
  11520. const ATTRIBUTE_TYPE_TO_COMPONENTS = {
  11521. SCALAR: 1,
  11522. VEC2: 2,
  11523. VEC3: 3,
  11524. VEC4: 4,
  11525. MAT2: 4,
  11526. MAT3: 9,
  11527. MAT4: 16
  11528. };
  11529. const ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE = {
  11530. 5120: 1,
  11531. 5121: 1,
  11532. 5122: 2,
  11533. 5123: 2,
  11534. 5125: 4,
  11535. 5126: 4
  11536. };
  11537. const ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY = {
  11538. 5120: Int8Array,
  11539. 5121: Uint8Array,
  11540. 5122: Int16Array,
  11541. 5123: Uint16Array,
  11542. 5125: Uint32Array,
  11543. 5126: Float32Array
  11544. };
  11545. function getAccessorTypeFromSize(size) {
  11546. const type = TYPES[size - 1];
  11547. return type || TYPES[0];
  11548. }
  11549. function getComponentTypeFromArray(typedArray) {
  11550. const componentType = ARRAY_TO_COMPONENT_TYPE.get(typedArray.constructor);
  11551. if (!componentType) {
  11552. throw new Error('Illegal typed array');
  11553. }
  11554. return componentType;
  11555. }
  11556. function getAccessorArrayTypeAndLength(accessor, bufferView) {
  11557. const ArrayType = ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[accessor.componentType];
  11558. const components = ATTRIBUTE_TYPE_TO_COMPONENTS[accessor.type];
  11559. const bytesPerComponent = ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[accessor.componentType];
  11560. const length = accessor.count * components;
  11561. const byteLength = accessor.count * components * bytesPerComponent;
  11562. assert$1(byteLength >= 0 && byteLength <= bufferView.byteLength);
  11563. return {
  11564. ArrayType,
  11565. length,
  11566. byteLength
  11567. };
  11568. }
  11569. const DEFAULT_GLTF_JSON = {
  11570. asset: {
  11571. version: '2.0',
  11572. generator: 'loaders.gl'
  11573. },
  11574. buffers: []
  11575. };
  11576. class GLTFScenegraph {
  11577. constructor(gltf) {
  11578. _defineProperty(this, "gltf", void 0);
  11579. _defineProperty(this, "sourceBuffers", void 0);
  11580. _defineProperty(this, "byteLength", void 0);
  11581. this.gltf = gltf || {
  11582. json: { ...DEFAULT_GLTF_JSON
  11583. },
  11584. buffers: []
  11585. };
  11586. this.sourceBuffers = [];
  11587. this.byteLength = 0;
  11588. if (this.gltf.buffers && this.gltf.buffers[0]) {
  11589. this.byteLength = this.gltf.buffers[0].byteLength;
  11590. this.sourceBuffers = [this.gltf.buffers[0]];
  11591. }
  11592. }
  11593. get json() {
  11594. return this.gltf.json;
  11595. }
  11596. getApplicationData(key) {
  11597. const data = this.json[key];
  11598. return data;
  11599. }
  11600. getExtraData(key) {
  11601. const extras = this.json.extras || {};
  11602. return extras[key];
  11603. }
  11604. getExtension(extensionName) {
  11605. const isExtension = this.getUsedExtensions().find(name => name === extensionName);
  11606. const extensions = this.json.extensions || {};
  11607. return isExtension ? extensions[extensionName] || true : null;
  11608. }
  11609. getRequiredExtension(extensionName) {
  11610. const isRequired = this.getRequiredExtensions().find(name => name === extensionName);
  11611. return isRequired ? this.getExtension(extensionName) : null;
  11612. }
  11613. getRequiredExtensions() {
  11614. return this.json.extensionsRequired || [];
  11615. }
  11616. getUsedExtensions() {
  11617. return this.json.extensionsUsed || [];
  11618. }
  11619. getObjectExtension(object, extensionName) {
  11620. const extensions = object.extensions || {};
  11621. return extensions[extensionName];
  11622. }
  11623. getScene(index) {
  11624. return this.getObject('scenes', index);
  11625. }
  11626. getNode(index) {
  11627. return this.getObject('nodes', index);
  11628. }
  11629. getSkin(index) {
  11630. return this.getObject('skins', index);
  11631. }
  11632. getMesh(index) {
  11633. return this.getObject('meshes', index);
  11634. }
  11635. getMaterial(index) {
  11636. return this.getObject('materials', index);
  11637. }
  11638. getAccessor(index) {
  11639. return this.getObject('accessors', index);
  11640. }
  11641. getTexture(index) {
  11642. return this.getObject('textures', index);
  11643. }
  11644. getSampler(index) {
  11645. return this.getObject('samplers', index);
  11646. }
  11647. getImage(index) {
  11648. return this.getObject('images', index);
  11649. }
  11650. getBufferView(index) {
  11651. return this.getObject('bufferViews', index);
  11652. }
  11653. getBuffer(index) {
  11654. return this.getObject('buffers', index);
  11655. }
  11656. getObject(array, index) {
  11657. if (typeof index === 'object') {
  11658. return index;
  11659. }
  11660. const object = this.json[array] && this.json[array][index];
  11661. if (!object) {
  11662. throw new Error("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  11663. }
  11664. return object;
  11665. }
  11666. getTypedArrayForBufferView(bufferView) {
  11667. bufferView = this.getBufferView(bufferView);
  11668. const bufferIndex = bufferView.buffer;
  11669. const binChunk = this.gltf.buffers[bufferIndex];
  11670. assert$1(binChunk);
  11671. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  11672. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  11673. }
  11674. getTypedArrayForAccessor(accessor) {
  11675. accessor = this.getAccessor(accessor);
  11676. const bufferView = this.getBufferView(accessor.bufferView);
  11677. const buffer = this.getBuffer(bufferView.buffer);
  11678. const arrayBuffer = buffer.data;
  11679. const {
  11680. ArrayType,
  11681. length
  11682. } = getAccessorArrayTypeAndLength(accessor, bufferView);
  11683. const byteOffset = bufferView.byteOffset + accessor.byteOffset;
  11684. return new ArrayType(arrayBuffer, byteOffset, length);
  11685. }
  11686. getTypedArrayForImageData(image) {
  11687. image = this.getAccessor(image);
  11688. const bufferView = this.getBufferView(image.bufferView);
  11689. const buffer = this.getBuffer(bufferView.buffer);
  11690. const arrayBuffer = buffer.data;
  11691. const byteOffset = bufferView.byteOffset || 0;
  11692. return new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  11693. }
  11694. addApplicationData(key, data) {
  11695. this.json[key] = data;
  11696. return this;
  11697. }
  11698. addExtraData(key, data) {
  11699. this.json.extras = this.json.extras || {};
  11700. this.json.extras[key] = data;
  11701. return this;
  11702. }
  11703. addObjectExtension(object, extensionName, data) {
  11704. object.extensions = object.extensions || {};
  11705. object.extensions[extensionName] = data;
  11706. this.registerUsedExtension(extensionName);
  11707. return this;
  11708. }
  11709. setObjectExtension(object, extensionName, data) {
  11710. const extensions = object.extensions || {};
  11711. extensions[extensionName] = data;
  11712. }
  11713. removeObjectExtension(object, extensionName) {
  11714. const extensions = object.extensions || {};
  11715. const extension = extensions[extensionName];
  11716. delete extensions[extensionName];
  11717. return extension;
  11718. }
  11719. addExtension(extensionName, extensionData = {}) {
  11720. assert$1(extensionData);
  11721. this.json.extensions = this.json.extensions || {};
  11722. this.json.extensions[extensionName] = extensionData;
  11723. this.registerUsedExtension(extensionName);
  11724. return extensionData;
  11725. }
  11726. addRequiredExtension(extensionName, extensionData = {}) {
  11727. assert$1(extensionData);
  11728. this.addExtension(extensionName, extensionData);
  11729. this.registerRequiredExtension(extensionName);
  11730. return extensionData;
  11731. }
  11732. registerUsedExtension(extensionName) {
  11733. this.json.extensionsUsed = this.json.extensionsUsed || [];
  11734. if (!this.json.extensionsUsed.find(ext => ext === extensionName)) {
  11735. this.json.extensionsUsed.push(extensionName);
  11736. }
  11737. }
  11738. registerRequiredExtension(extensionName) {
  11739. this.registerUsedExtension(extensionName);
  11740. this.json.extensionsRequired = this.json.extensionsRequired || [];
  11741. if (!this.json.extensionsRequired.find(ext => ext === extensionName)) {
  11742. this.json.extensionsRequired.push(extensionName);
  11743. }
  11744. }
  11745. removeExtension(extensionName) {
  11746. if (this.json.extensionsRequired) {
  11747. this._removeStringFromArray(this.json.extensionsRequired, extensionName);
  11748. }
  11749. if (this.json.extensionsUsed) {
  11750. this._removeStringFromArray(this.json.extensionsUsed, extensionName);
  11751. }
  11752. if (this.json.extensions) {
  11753. delete this.json.extensions[extensionName];
  11754. }
  11755. }
  11756. setDefaultScene(sceneIndex) {
  11757. this.json.scene = sceneIndex;
  11758. }
  11759. addScene(scene) {
  11760. const {
  11761. nodeIndices
  11762. } = scene;
  11763. this.json.scenes = this.json.scenes || [];
  11764. this.json.scenes.push({
  11765. nodes: nodeIndices
  11766. });
  11767. return this.json.scenes.length - 1;
  11768. }
  11769. addNode(node) {
  11770. const {
  11771. meshIndex,
  11772. matrix
  11773. } = node;
  11774. this.json.nodes = this.json.nodes || [];
  11775. const nodeData = {
  11776. mesh: meshIndex
  11777. };
  11778. if (matrix) {
  11779. nodeData.matrix = matrix;
  11780. }
  11781. this.json.nodes.push(nodeData);
  11782. return this.json.nodes.length - 1;
  11783. }
  11784. addMesh(mesh) {
  11785. const {
  11786. attributes,
  11787. indices,
  11788. material,
  11789. mode = 4
  11790. } = mesh;
  11791. const accessors = this._addAttributes(attributes);
  11792. const glTFMesh = {
  11793. primitives: [{
  11794. attributes: accessors,
  11795. mode
  11796. }]
  11797. };
  11798. if (indices) {
  11799. const indicesAccessor = this._addIndices(indices);
  11800. glTFMesh.primitives[0].indices = indicesAccessor;
  11801. }
  11802. if (Number.isFinite(material)) {
  11803. glTFMesh.primitives[0].material = material;
  11804. }
  11805. this.json.meshes = this.json.meshes || [];
  11806. this.json.meshes.push(glTFMesh);
  11807. return this.json.meshes.length - 1;
  11808. }
  11809. addPointCloud(attributes) {
  11810. const accessorIndices = this._addAttributes(attributes);
  11811. const glTFMesh = {
  11812. primitives: [{
  11813. attributes: accessorIndices,
  11814. mode: 0
  11815. }]
  11816. };
  11817. this.json.meshes = this.json.meshes || [];
  11818. this.json.meshes.push(glTFMesh);
  11819. return this.json.meshes.length - 1;
  11820. }
  11821. addImage(imageData, mimeTypeOpt) {
  11822. const metadata = getBinaryImageMetadata(imageData);
  11823. const mimeType = mimeTypeOpt || (metadata === null || metadata === void 0 ? void 0 : metadata.mimeType);
  11824. const bufferViewIndex = this.addBufferView(imageData);
  11825. const glTFImage = {
  11826. bufferView: bufferViewIndex,
  11827. mimeType
  11828. };
  11829. this.json.images = this.json.images || [];
  11830. this.json.images.push(glTFImage);
  11831. return this.json.images.length - 1;
  11832. }
  11833. addBufferView(buffer) {
  11834. const byteLength = buffer.byteLength;
  11835. assert$1(Number.isFinite(byteLength));
  11836. this.sourceBuffers = this.sourceBuffers || [];
  11837. this.sourceBuffers.push(buffer);
  11838. const glTFBufferView = {
  11839. buffer: 0,
  11840. byteOffset: this.byteLength,
  11841. byteLength
  11842. };
  11843. this.byteLength += padToNBytes(byteLength, 4);
  11844. this.json.bufferViews = this.json.bufferViews || [];
  11845. this.json.bufferViews.push(glTFBufferView);
  11846. return this.json.bufferViews.length - 1;
  11847. }
  11848. addAccessor(bufferViewIndex, accessor) {
  11849. const glTFAccessor = {
  11850. bufferView: bufferViewIndex,
  11851. type: getAccessorTypeFromSize(accessor.size),
  11852. componentType: accessor.componentType,
  11853. count: accessor.count,
  11854. max: accessor.max,
  11855. min: accessor.min
  11856. };
  11857. this.json.accessors = this.json.accessors || [];
  11858. this.json.accessors.push(glTFAccessor);
  11859. return this.json.accessors.length - 1;
  11860. }
  11861. addBinaryBuffer(sourceBuffer, accessor = {
  11862. size: 3
  11863. }) {
  11864. const bufferViewIndex = this.addBufferView(sourceBuffer);
  11865. let minMax = {
  11866. min: accessor.min,
  11867. max: accessor.max
  11868. };
  11869. if (!minMax.min || !minMax.max) {
  11870. minMax = this._getAccessorMinMax(sourceBuffer, accessor.size);
  11871. }
  11872. const accessorDefaults = {
  11873. size: accessor.size,
  11874. componentType: getComponentTypeFromArray(sourceBuffer),
  11875. count: Math.round(sourceBuffer.length / accessor.size),
  11876. min: minMax.min,
  11877. max: minMax.max
  11878. };
  11879. return this.addAccessor(bufferViewIndex, Object.assign(accessorDefaults, accessor));
  11880. }
  11881. addTexture(texture) {
  11882. const {
  11883. imageIndex
  11884. } = texture;
  11885. const glTFTexture = {
  11886. source: imageIndex
  11887. };
  11888. this.json.textures = this.json.textures || [];
  11889. this.json.textures.push(glTFTexture);
  11890. return this.json.textures.length - 1;
  11891. }
  11892. addMaterial(pbrMaterialInfo) {
  11893. this.json.materials = this.json.materials || [];
  11894. this.json.materials.push(pbrMaterialInfo);
  11895. return this.json.materials.length - 1;
  11896. }
  11897. createBinaryChunk() {
  11898. var _this$json, _this$json$buffers;
  11899. this.gltf.buffers = [];
  11900. const totalByteLength = this.byteLength;
  11901. const arrayBuffer = new ArrayBuffer(totalByteLength);
  11902. const targetArray = new Uint8Array(arrayBuffer);
  11903. let dstByteOffset = 0;
  11904. for (const sourceBuffer of this.sourceBuffers || []) {
  11905. dstByteOffset = copyToArray(sourceBuffer, targetArray, dstByteOffset);
  11906. }
  11907. 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]) {
  11908. this.json.buffers[0].byteLength = totalByteLength;
  11909. } else {
  11910. this.json.buffers = [{
  11911. byteLength: totalByteLength
  11912. }];
  11913. }
  11914. this.gltf.binary = arrayBuffer;
  11915. this.sourceBuffers = [arrayBuffer];
  11916. }
  11917. _removeStringFromArray(array, string) {
  11918. let found = true;
  11919. while (found) {
  11920. const index = array.indexOf(string);
  11921. if (index > -1) {
  11922. array.splice(index, 1);
  11923. } else {
  11924. found = false;
  11925. }
  11926. }
  11927. }
  11928. _addAttributes(attributes = {}) {
  11929. const result = {};
  11930. for (const attributeKey in attributes) {
  11931. const attributeData = attributes[attributeKey];
  11932. const attrName = this._getGltfAttributeName(attributeKey);
  11933. const accessor = this.addBinaryBuffer(attributeData.value, attributeData);
  11934. result[attrName] = accessor;
  11935. }
  11936. return result;
  11937. }
  11938. _addIndices(indices) {
  11939. return this.addBinaryBuffer(indices, {
  11940. size: 1
  11941. });
  11942. }
  11943. _getGltfAttributeName(attributeName) {
  11944. switch (attributeName.toLowerCase()) {
  11945. case 'position':
  11946. case 'positions':
  11947. case 'vertices':
  11948. return 'POSITION';
  11949. case 'normal':
  11950. case 'normals':
  11951. return 'NORMAL';
  11952. case 'color':
  11953. case 'colors':
  11954. return 'COLOR_0';
  11955. case 'texcoord':
  11956. case 'texcoords':
  11957. return 'TEXCOORD_0';
  11958. default:
  11959. return attributeName;
  11960. }
  11961. }
  11962. _getAccessorMinMax(buffer, size) {
  11963. const result = {
  11964. min: null,
  11965. max: null
  11966. };
  11967. if (buffer.length < size) {
  11968. return result;
  11969. }
  11970. result.min = [];
  11971. result.max = [];
  11972. const initValues = buffer.subarray(0, size);
  11973. for (const value of initValues) {
  11974. result.min.push(value);
  11975. result.max.push(value);
  11976. }
  11977. for (let index = size; index < buffer.length; index += size) {
  11978. for (let componentIndex = 0; componentIndex < size; componentIndex++) {
  11979. result.min[0 + componentIndex] = Math.min(result.min[0 + componentIndex], buffer[index + componentIndex]);
  11980. result.max[0 + componentIndex] = Math.max(result.max[0 + componentIndex], buffer[index + componentIndex]);
  11981. }
  11982. }
  11983. return result;
  11984. }
  11985. }
  11986. const isWebAssemblySupported = typeof WebAssembly !== 'object';
  11987. 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';
  11988. 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';
  11989. 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]);
  11990. 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]);
  11991. const FILTERS = {
  11992. 0: '',
  11993. 1: 'meshopt_decodeFilterOct',
  11994. 2: 'meshopt_decodeFilterQuat',
  11995. 3: 'meshopt_decodeFilterExp',
  11996. NONE: '',
  11997. OCTAHEDRAL: 'meshopt_decodeFilterOct',
  11998. QUATERNION: 'meshopt_decodeFilterQuat',
  11999. EXPONENTIAL: 'meshopt_decodeFilterExp'
  12000. };
  12001. const DECODERS = {
  12002. 0: 'meshopt_decodeVertexBuffer',
  12003. 1: 'meshopt_decodeIndexBuffer',
  12004. 2: 'meshopt_decodeIndexSequence',
  12005. ATTRIBUTES: 'meshopt_decodeVertexBuffer',
  12006. TRIANGLES: 'meshopt_decodeIndexBuffer',
  12007. INDICES: 'meshopt_decodeIndexSequence'
  12008. };
  12009. function isMeshoptSupported() {
  12010. return isWebAssemblySupported;
  12011. }
  12012. async function meshoptDecodeGltfBuffer(target, count, size, source, mode, filter = 'NONE') {
  12013. const instance = await loadWasmInstance();
  12014. decode$5(instance, instance.exports[DECODERS[mode]], target, count, size, source, instance.exports[FILTERS[filter || 'NONE']]);
  12015. }
  12016. let wasmPromise;
  12017. async function loadWasmInstance() {
  12018. if (!wasmPromise) {
  12019. wasmPromise = loadWasmModule();
  12020. }
  12021. return wasmPromise;
  12022. }
  12023. async function loadWasmModule() {
  12024. let wasm = wasm_base;
  12025. if (WebAssembly.validate(detector)) {
  12026. wasm = wasm_simd;
  12027. console.log('Warning: meshopt_decoder is using experimental SIMD support');
  12028. }
  12029. const result = await WebAssembly.instantiate(unpack(wasm), {});
  12030. await result.instance.exports.__wasm_call_ctors();
  12031. return result.instance;
  12032. }
  12033. function unpack(data) {
  12034. const result = new Uint8Array(data.length);
  12035. for (let i = 0; i < data.length; ++i) {
  12036. const ch = data.charCodeAt(i);
  12037. result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  12038. }
  12039. let write = 0;
  12040. for (let i = 0; i < data.length; ++i) {
  12041. result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  12042. }
  12043. return result.buffer.slice(0, write);
  12044. }
  12045. function decode$5(instance, fun, target, count, size, source, filter) {
  12046. const sbrk = instance.exports.sbrk;
  12047. const count4 = count + 3 & ~3;
  12048. const tp = sbrk(count4 * size);
  12049. const sp = sbrk(source.length);
  12050. const heap = new Uint8Array(instance.exports.memory.buffer);
  12051. heap.set(source, sp);
  12052. const res = fun(tp, count, size, sp, source.length);
  12053. if (res === 0 && filter) {
  12054. filter(tp, count4, size);
  12055. }
  12056. target.set(heap.subarray(tp, tp + count * size));
  12057. sbrk(tp - sbrk(0));
  12058. if (res !== 0) {
  12059. throw new Error("Malformed buffer data: ".concat(res));
  12060. }
  12061. }
  12062. const EXT_MESHOPT_COMPRESSION = 'EXT_meshopt_compression';
  12063. const name$6 = EXT_MESHOPT_COMPRESSION;
  12064. function preprocess$4(gltfData) {
  12065. const scenegraph = new GLTFScenegraph(gltfData);
  12066. if (scenegraph.getRequiredExtensions().includes(EXT_MESHOPT_COMPRESSION) && !isMeshoptSupported()) {
  12067. throw new Error("gltf: Required extension ".concat(EXT_MESHOPT_COMPRESSION, " not supported by browser"));
  12068. }
  12069. }
  12070. async function decode$4(gltfData, options) {
  12071. var _options$gltf;
  12072. const scenegraph = new GLTFScenegraph(gltfData);
  12073. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  12074. return;
  12075. }
  12076. const promises = [];
  12077. for (const bufferViewIndex of gltfData.json.bufferViews || []) {
  12078. promises.push(decodeMeshoptBufferView(scenegraph, bufferViewIndex));
  12079. }
  12080. await Promise.all(promises);
  12081. scenegraph.removeExtension(EXT_MESHOPT_COMPRESSION);
  12082. }
  12083. async function decodeMeshoptBufferView(scenegraph, bufferView) {
  12084. const meshoptExtension = scenegraph.getObjectExtension(bufferView, EXT_MESHOPT_COMPRESSION);
  12085. if (meshoptExtension) {
  12086. const buffer = bufferView.buffer;
  12087. const {
  12088. byteOffset = 0,
  12089. byteLength = 0,
  12090. byteStride,
  12091. count,
  12092. mode,
  12093. filter = 'NONE'
  12094. } = meshoptExtension;
  12095. const source = new Uint8Array(buffer, byteOffset, byteLength);
  12096. const result = new ArrayBuffer(count * byteStride);
  12097. await meshoptDecodeGltfBuffer(new Uint8Array(result), count, byteStride, source, mode, filter);
  12098. return result;
  12099. }
  12100. return null;
  12101. }
  12102. var EXT_meshopt_compression = /*#__PURE__*/Object.freeze({
  12103. __proto__: null,
  12104. name: name$6,
  12105. preprocess: preprocess$4,
  12106. decode: decode$4
  12107. });
  12108. const EXT_TEXTURE_WEBP = 'EXT_texture_webp';
  12109. const name$5 = EXT_TEXTURE_WEBP;
  12110. function preprocess$3(gltfData, options) {
  12111. const scenegraph = new GLTFScenegraph(gltfData);
  12112. if (!_isImageFormatSupported('image/webp')) {
  12113. if (scenegraph.getRequiredExtensions().includes(EXT_TEXTURE_WEBP)) {
  12114. throw new Error("gltf: Required extension ".concat(EXT_TEXTURE_WEBP, " not supported by browser"));
  12115. }
  12116. return;
  12117. }
  12118. const {
  12119. json
  12120. } = scenegraph;
  12121. for (const texture of json.textures || []) {
  12122. const extension = scenegraph.getObjectExtension(texture, EXT_TEXTURE_WEBP);
  12123. if (extension) {
  12124. texture.source = extension.source;
  12125. }
  12126. scenegraph.removeObjectExtension(texture, EXT_TEXTURE_WEBP);
  12127. }
  12128. scenegraph.removeExtension(EXT_TEXTURE_WEBP);
  12129. }
  12130. var EXT_texture_webp = /*#__PURE__*/Object.freeze({
  12131. __proto__: null,
  12132. name: name$5,
  12133. preprocess: preprocess$3
  12134. });
  12135. const KHR_TEXTURE_BASISU = 'KHR_texture_basisu';
  12136. const name$4 = KHR_TEXTURE_BASISU;
  12137. function preprocess$2(gltfData, options) {
  12138. const scene = new GLTFScenegraph(gltfData);
  12139. const {
  12140. json
  12141. } = scene;
  12142. for (const texture of json.textures || []) {
  12143. const extension = scene.getObjectExtension(texture, KHR_TEXTURE_BASISU);
  12144. if (extension) {
  12145. texture.source = extension.source;
  12146. }
  12147. scene.removeObjectExtension(texture, KHR_TEXTURE_BASISU);
  12148. }
  12149. scene.removeExtension(KHR_TEXTURE_BASISU);
  12150. }
  12151. var KHR_texture_basisu = /*#__PURE__*/Object.freeze({
  12152. __proto__: null,
  12153. name: name$4,
  12154. preprocess: preprocess$2
  12155. });
  12156. function getGLTFAccessors(attributes) {
  12157. const accessors = {};
  12158. for (const name in attributes) {
  12159. const attribute = attributes[name];
  12160. if (name !== 'indices') {
  12161. const glTFAccessor = getGLTFAccessor(attribute);
  12162. accessors[name] = glTFAccessor;
  12163. }
  12164. }
  12165. return accessors;
  12166. }
  12167. function getGLTFAccessor(attribute) {
  12168. const {
  12169. buffer,
  12170. size,
  12171. count
  12172. } = getAccessorData(attribute);
  12173. const glTFAccessor = {
  12174. value: buffer,
  12175. size,
  12176. byteOffset: 0,
  12177. count,
  12178. type: getAccessorTypeFromSize(size),
  12179. componentType: getComponentTypeFromArray(buffer)
  12180. };
  12181. return glTFAccessor;
  12182. }
  12183. function getAccessorData(attribute) {
  12184. let buffer = attribute;
  12185. let size = 1;
  12186. let count = 0;
  12187. if (attribute && attribute.value) {
  12188. buffer = attribute.value;
  12189. size = attribute.size || 1;
  12190. }
  12191. if (buffer) {
  12192. if (!ArrayBuffer.isView(buffer)) {
  12193. buffer = toTypedArray(buffer, Float32Array);
  12194. }
  12195. count = buffer.length / size;
  12196. }
  12197. return {
  12198. buffer,
  12199. size,
  12200. count
  12201. };
  12202. }
  12203. function toTypedArray(array, ArrayType, convertTypedArrays = false) {
  12204. if (!array) {
  12205. return null;
  12206. }
  12207. if (Array.isArray(array)) {
  12208. return new ArrayType(array);
  12209. }
  12210. if (convertTypedArrays && !(array instanceof ArrayType)) {
  12211. return new ArrayType(array);
  12212. }
  12213. return array;
  12214. }
  12215. const KHR_DRACO_MESH_COMPRESSION = 'KHR_draco_mesh_compression';
  12216. const name$3 = KHR_DRACO_MESH_COMPRESSION;
  12217. function preprocess$1(gltfData, options, context) {
  12218. const scenegraph = new GLTFScenegraph(gltfData);
  12219. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12220. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) ;
  12221. }
  12222. }
  12223. async function decode$3(gltfData, options, context) {
  12224. var _options$gltf;
  12225. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  12226. return;
  12227. }
  12228. const scenegraph = new GLTFScenegraph(gltfData);
  12229. const promises = [];
  12230. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  12231. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) {
  12232. promises.push(decompressPrimitive(scenegraph, primitive, options, context));
  12233. }
  12234. }
  12235. await Promise.all(promises);
  12236. scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);
  12237. }
  12238. function encode$3(gltfData, options = {}) {
  12239. const scenegraph = new GLTFScenegraph(gltfData);
  12240. for (const mesh of scenegraph.json.meshes || []) {
  12241. compressMesh(mesh);
  12242. scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
  12243. }
  12244. }
  12245. async function decompressPrimitive(scenegraph, primitive, options, context) {
  12246. const dracoExtension = scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION);
  12247. if (!dracoExtension) {
  12248. return;
  12249. }
  12250. const buffer = scenegraph.getTypedArrayForBufferView(dracoExtension.bufferView);
  12251. const bufferCopy = sliceArrayBuffer(buffer.buffer, buffer.byteOffset);
  12252. const {
  12253. parse
  12254. } = context;
  12255. const dracoOptions = { ...options
  12256. };
  12257. delete dracoOptions['3d-tiles'];
  12258. const decodedData = await parse(bufferCopy, DracoLoader, dracoOptions, context);
  12259. const decodedAttributes = getGLTFAccessors(decodedData.attributes);
  12260. for (const [attributeName, decodedAttribute] of Object.entries(decodedAttributes)) {
  12261. if (attributeName in primitive.attributes) {
  12262. const accessorIndex = primitive.attributes[attributeName];
  12263. const accessor = scenegraph.getAccessor(accessorIndex);
  12264. if (accessor !== null && accessor !== void 0 && accessor.min && accessor !== null && accessor !== void 0 && accessor.max) {
  12265. decodedAttribute.min = accessor.min;
  12266. decodedAttribute.max = accessor.max;
  12267. }
  12268. }
  12269. }
  12270. primitive.attributes = decodedAttributes;
  12271. if (decodedData.indices) {
  12272. primitive.indices = getGLTFAccessor(decodedData.indices);
  12273. }
  12274. checkPrimitive(primitive);
  12275. }
  12276. function compressMesh(attributes, indices, mode = 4, options, context) {
  12277. var _context$parseSync;
  12278. if (!options.DracoWriter) {
  12279. throw new Error('options.gltf.DracoWriter not provided');
  12280. }
  12281. const compressedData = options.DracoWriter.encodeSync({
  12282. attributes
  12283. });
  12284. const decodedData = context === null || context === void 0 ? void 0 : (_context$parseSync = context.parseSync) === null || _context$parseSync === void 0 ? void 0 : _context$parseSync.call(context, {
  12285. attributes
  12286. });
  12287. const fauxAccessors = options._addFauxAttributes(decodedData.attributes);
  12288. const bufferViewIndex = options.addBufferView(compressedData);
  12289. const glTFMesh = {
  12290. primitives: [{
  12291. attributes: fauxAccessors,
  12292. mode,
  12293. extensions: {
  12294. [KHR_DRACO_MESH_COMPRESSION]: {
  12295. bufferView: bufferViewIndex,
  12296. attributes: fauxAccessors
  12297. }
  12298. }
  12299. }]
  12300. };
  12301. return glTFMesh;
  12302. }
  12303. function checkPrimitive(primitive) {
  12304. if (!primitive.attributes && Object.keys(primitive.attributes).length > 0) {
  12305. throw new Error('glTF: Empty primitive detected: Draco decompression failure?');
  12306. }
  12307. }
  12308. function* makeMeshPrimitiveIterator(scenegraph) {
  12309. for (const mesh of scenegraph.json.meshes || []) {
  12310. for (const primitive of mesh.primitives) {
  12311. yield primitive;
  12312. }
  12313. }
  12314. }
  12315. var KHR_draco_mesh_compression = /*#__PURE__*/Object.freeze({
  12316. __proto__: null,
  12317. name: name$3,
  12318. preprocess: preprocess$1,
  12319. decode: decode$3,
  12320. encode: encode$3
  12321. });
  12322. const KHR_LIGHTS_PUNCTUAL = 'KHR_lights_punctual';
  12323. const name$2 = KHR_LIGHTS_PUNCTUAL;
  12324. async function decode$2(gltfData) {
  12325. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12326. const {
  12327. json
  12328. } = gltfScenegraph;
  12329. const extension = gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL);
  12330. if (extension) {
  12331. gltfScenegraph.json.lights = extension.lights;
  12332. gltfScenegraph.removeExtension(KHR_LIGHTS_PUNCTUAL);
  12333. }
  12334. for (const node of json.nodes || []) {
  12335. const nodeExtension = gltfScenegraph.getObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12336. if (nodeExtension) {
  12337. node.light = nodeExtension.light;
  12338. }
  12339. gltfScenegraph.removeObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  12340. }
  12341. }
  12342. async function encode$2(gltfData) {
  12343. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12344. const {
  12345. json
  12346. } = gltfScenegraph;
  12347. if (json.lights) {
  12348. const extension = gltfScenegraph.addExtension(KHR_LIGHTS_PUNCTUAL);
  12349. assert$1(!extension.lights);
  12350. extension.lights = json.lights;
  12351. delete json.lights;
  12352. }
  12353. if (gltfScenegraph.json.lights) {
  12354. for (const light of gltfScenegraph.json.lights) {
  12355. const node = light.node;
  12356. gltfScenegraph.addObjectExtension(node, KHR_LIGHTS_PUNCTUAL, light);
  12357. }
  12358. delete gltfScenegraph.json.lights;
  12359. }
  12360. }
  12361. var KHR_lights_punctual = /*#__PURE__*/Object.freeze({
  12362. __proto__: null,
  12363. name: name$2,
  12364. decode: decode$2,
  12365. encode: encode$2
  12366. });
  12367. const KHR_MATERIALS_UNLIT = 'KHR_materials_unlit';
  12368. const name$1 = KHR_MATERIALS_UNLIT;
  12369. async function decode$1(gltfData) {
  12370. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12371. const {
  12372. json
  12373. } = gltfScenegraph;
  12374. gltfScenegraph.removeExtension(KHR_MATERIALS_UNLIT);
  12375. for (const material of json.materials || []) {
  12376. const extension = material.extensions && material.extensions.KHR_materials_unlit;
  12377. if (extension) {
  12378. material.unlit = true;
  12379. }
  12380. gltfScenegraph.removeObjectExtension(material, KHR_MATERIALS_UNLIT);
  12381. }
  12382. }
  12383. function encode$1(gltfData) {
  12384. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12385. const {
  12386. json
  12387. } = gltfScenegraph;
  12388. if (gltfScenegraph.materials) {
  12389. for (const material of json.materials || []) {
  12390. if (material.unlit) {
  12391. delete material.unlit;
  12392. gltfScenegraph.addObjectExtension(material, KHR_MATERIALS_UNLIT, {});
  12393. gltfScenegraph.addExtension(KHR_MATERIALS_UNLIT);
  12394. }
  12395. }
  12396. }
  12397. }
  12398. var KHR_materials_unlit = /*#__PURE__*/Object.freeze({
  12399. __proto__: null,
  12400. name: name$1,
  12401. decode: decode$1,
  12402. encode: encode$1
  12403. });
  12404. const KHR_TECHNIQUES_WEBGL = 'KHR_techniques_webgl';
  12405. const name = KHR_TECHNIQUES_WEBGL;
  12406. async function decode(gltfData) {
  12407. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12408. const {
  12409. json
  12410. } = gltfScenegraph;
  12411. const extension = gltfScenegraph.getExtension(KHR_TECHNIQUES_WEBGL);
  12412. if (extension) {
  12413. const techniques = resolveTechniques(extension, gltfScenegraph);
  12414. for (const material of json.materials || []) {
  12415. const materialExtension = gltfScenegraph.getObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12416. if (materialExtension) {
  12417. material.technique = Object.assign({}, materialExtension, techniques[materialExtension.technique]);
  12418. material.technique.values = resolveValues(material.technique, gltfScenegraph);
  12419. }
  12420. gltfScenegraph.removeObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  12421. }
  12422. gltfScenegraph.removeExtension(KHR_TECHNIQUES_WEBGL);
  12423. }
  12424. }
  12425. async function encode(gltfData, options) {}
  12426. function resolveTechniques(techniquesExtension, gltfScenegraph) {
  12427. const {
  12428. programs = [],
  12429. shaders = [],
  12430. techniques = []
  12431. } = techniquesExtension;
  12432. const textDecoder = new TextDecoder();
  12433. shaders.forEach(shader => {
  12434. if (Number.isFinite(shader.bufferView)) {
  12435. shader.code = textDecoder.decode(gltfScenegraph.getTypedArrayForBufferView(shader.bufferView));
  12436. } else {
  12437. throw new Error('KHR_techniques_webgl: no shader code');
  12438. }
  12439. });
  12440. programs.forEach(program => {
  12441. program.fragmentShader = shaders[program.fragmentShader];
  12442. program.vertexShader = shaders[program.vertexShader];
  12443. });
  12444. techniques.forEach(technique => {
  12445. technique.program = programs[technique.program];
  12446. });
  12447. return techniques;
  12448. }
  12449. function resolveValues(technique, gltfScenegraph) {
  12450. const values = Object.assign({}, technique.values);
  12451. Object.keys(technique.uniforms || {}).forEach(uniform => {
  12452. if (technique.uniforms[uniform].value && !(uniform in values)) {
  12453. values[uniform] = technique.uniforms[uniform].value;
  12454. }
  12455. });
  12456. Object.keys(values).forEach(uniform => {
  12457. if (typeof values[uniform] === 'object' && values[uniform].index !== undefined) {
  12458. values[uniform].texture = gltfScenegraph.getTexture(values[uniform].index);
  12459. }
  12460. });
  12461. return values;
  12462. }
  12463. var KHR_techniques_webgl = /*#__PURE__*/Object.freeze({
  12464. __proto__: null,
  12465. name: name,
  12466. decode: decode,
  12467. encode: encode
  12468. });
  12469. const EXTENSIONS = [EXT_meshopt_compression, EXT_texture_webp, KHR_texture_basisu, KHR_draco_mesh_compression, KHR_lights_punctual, KHR_materials_unlit, KHR_techniques_webgl];
  12470. function preprocessExtensions(gltf, options = {}, context) {
  12471. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12472. for (const extension of extensions) {
  12473. var _extension$preprocess;
  12474. (_extension$preprocess = extension.preprocess) === null || _extension$preprocess === void 0 ? void 0 : _extension$preprocess.call(extension, gltf, options, context);
  12475. }
  12476. }
  12477. async function decodeExtensions(gltf, options = {}, context) {
  12478. const extensions = EXTENSIONS.filter(extension => useExtension(extension.name, options));
  12479. for (const extension of extensions) {
  12480. var _extension$decode;
  12481. await ((_extension$decode = extension.decode) === null || _extension$decode === void 0 ? void 0 : _extension$decode.call(extension, gltf, options, context));
  12482. }
  12483. }
  12484. function useExtension(extensionName, options) {
  12485. var _options$gltf;
  12486. const excludes = (options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.excludeExtensions) || {};
  12487. const exclude = extensionName in excludes && !excludes[extensionName];
  12488. return !exclude;
  12489. }
  12490. const KHR_BINARY_GLTF = 'KHR_binary_glTF';
  12491. function preprocess(gltfData) {
  12492. const gltfScenegraph = new GLTFScenegraph(gltfData);
  12493. const {
  12494. json
  12495. } = gltfScenegraph;
  12496. for (const image of json.images || []) {
  12497. const extension = gltfScenegraph.getObjectExtension(image, KHR_BINARY_GLTF);
  12498. if (extension) {
  12499. Object.assign(image, extension);
  12500. }
  12501. gltfScenegraph.removeObjectExtension(image, KHR_BINARY_GLTF);
  12502. }
  12503. if (json.buffers && json.buffers[0]) {
  12504. delete json.buffers[0].uri;
  12505. }
  12506. gltfScenegraph.removeExtension(KHR_BINARY_GLTF);
  12507. }
  12508. const GLTF_ARRAYS = {
  12509. accessors: 'accessor',
  12510. animations: 'animation',
  12511. buffers: 'buffer',
  12512. bufferViews: 'bufferView',
  12513. images: 'image',
  12514. materials: 'material',
  12515. meshes: 'mesh',
  12516. nodes: 'node',
  12517. samplers: 'sampler',
  12518. scenes: 'scene',
  12519. skins: 'skin',
  12520. textures: 'texture'
  12521. };
  12522. const GLTF_KEYS = {
  12523. accessor: 'accessors',
  12524. animations: 'animation',
  12525. buffer: 'buffers',
  12526. bufferView: 'bufferViews',
  12527. image: 'images',
  12528. material: 'materials',
  12529. mesh: 'meshes',
  12530. node: 'nodes',
  12531. sampler: 'samplers',
  12532. scene: 'scenes',
  12533. skin: 'skins',
  12534. texture: 'textures'
  12535. };
  12536. class GLTFV1Normalizer {
  12537. constructor() {
  12538. _defineProperty(this, "idToIndexMap", {
  12539. animations: {},
  12540. accessors: {},
  12541. buffers: {},
  12542. bufferViews: {},
  12543. images: {},
  12544. materials: {},
  12545. meshes: {},
  12546. nodes: {},
  12547. samplers: {},
  12548. scenes: {},
  12549. skins: {},
  12550. textures: {}
  12551. });
  12552. _defineProperty(this, "json", void 0);
  12553. }
  12554. normalize(gltf, options) {
  12555. this.json = gltf.json;
  12556. const json = gltf.json;
  12557. switch (json.asset && json.asset.version) {
  12558. case '2.0':
  12559. return;
  12560. case undefined:
  12561. case '1.0':
  12562. break;
  12563. default:
  12564. console.warn("glTF: Unknown version ".concat(json.asset.version));
  12565. return;
  12566. }
  12567. if (!options.normalize) {
  12568. throw new Error('glTF v1 is not supported.');
  12569. }
  12570. console.warn('Converting glTF v1 to glTF v2 format. This is experimental and may fail.');
  12571. this._addAsset(json);
  12572. this._convertTopLevelObjectsToArrays(json);
  12573. preprocess(gltf);
  12574. this._convertObjectIdsToArrayIndices(json);
  12575. this._updateObjects(json);
  12576. this._updateMaterial(json);
  12577. }
  12578. _addAsset(json) {
  12579. json.asset = json.asset || {};
  12580. json.asset.version = '2.0';
  12581. json.asset.generator = json.asset.generator || 'Normalized to glTF 2.0 by loaders.gl';
  12582. }
  12583. _convertTopLevelObjectsToArrays(json) {
  12584. for (const arrayName in GLTF_ARRAYS) {
  12585. this._convertTopLevelObjectToArray(json, arrayName);
  12586. }
  12587. }
  12588. _convertTopLevelObjectToArray(json, mapName) {
  12589. const objectMap = json[mapName];
  12590. if (!objectMap || Array.isArray(objectMap)) {
  12591. return;
  12592. }
  12593. json[mapName] = [];
  12594. for (const id in objectMap) {
  12595. const object = objectMap[id];
  12596. object.id = object.id || id;
  12597. const index = json[mapName].length;
  12598. json[mapName].push(object);
  12599. this.idToIndexMap[mapName][id] = index;
  12600. }
  12601. }
  12602. _convertObjectIdsToArrayIndices(json) {
  12603. for (const arrayName in GLTF_ARRAYS) {
  12604. this._convertIdsToIndices(json, arrayName);
  12605. }
  12606. if ('scene' in json) {
  12607. json.scene = this._convertIdToIndex(json.scene, 'scene');
  12608. }
  12609. for (const texture of json.textures) {
  12610. this._convertTextureIds(texture);
  12611. }
  12612. for (const mesh of json.meshes) {
  12613. this._convertMeshIds(mesh);
  12614. }
  12615. for (const node of json.nodes) {
  12616. this._convertNodeIds(node);
  12617. }
  12618. for (const node of json.scenes) {
  12619. this._convertSceneIds(node);
  12620. }
  12621. }
  12622. _convertTextureIds(texture) {
  12623. if (texture.source) {
  12624. texture.source = this._convertIdToIndex(texture.source, 'image');
  12625. }
  12626. }
  12627. _convertMeshIds(mesh) {
  12628. for (const primitive of mesh.primitives) {
  12629. const {
  12630. attributes,
  12631. indices,
  12632. material
  12633. } = primitive;
  12634. for (const attributeName in attributes) {
  12635. attributes[attributeName] = this._convertIdToIndex(attributes[attributeName], 'accessor');
  12636. }
  12637. if (indices) {
  12638. primitive.indices = this._convertIdToIndex(indices, 'accessor');
  12639. }
  12640. if (material) {
  12641. primitive.material = this._convertIdToIndex(material, 'material');
  12642. }
  12643. }
  12644. }
  12645. _convertNodeIds(node) {
  12646. if (node.children) {
  12647. node.children = node.children.map(child => this._convertIdToIndex(child, 'node'));
  12648. }
  12649. if (node.meshes) {
  12650. node.meshes = node.meshes.map(mesh => this._convertIdToIndex(mesh, 'mesh'));
  12651. }
  12652. }
  12653. _convertSceneIds(scene) {
  12654. if (scene.nodes) {
  12655. scene.nodes = scene.nodes.map(node => this._convertIdToIndex(node, 'node'));
  12656. }
  12657. }
  12658. _convertIdsToIndices(json, topLevelArrayName) {
  12659. if (!json[topLevelArrayName]) {
  12660. console.warn("gltf v1: json doesn't contain attribute ".concat(topLevelArrayName));
  12661. json[topLevelArrayName] = [];
  12662. }
  12663. for (const object of json[topLevelArrayName]) {
  12664. for (const key in object) {
  12665. const id = object[key];
  12666. const index = this._convertIdToIndex(id, key);
  12667. object[key] = index;
  12668. }
  12669. }
  12670. }
  12671. _convertIdToIndex(id, key) {
  12672. const arrayName = GLTF_KEYS[key];
  12673. if (arrayName in this.idToIndexMap) {
  12674. const index = this.idToIndexMap[arrayName][id];
  12675. if (!Number.isFinite(index)) {
  12676. throw new Error("gltf v1: failed to resolve ".concat(key, " with id ").concat(id));
  12677. }
  12678. return index;
  12679. }
  12680. return id;
  12681. }
  12682. _updateObjects(json) {
  12683. for (const buffer of this.json.buffers) {
  12684. delete buffer.type;
  12685. }
  12686. }
  12687. _updateMaterial(json) {
  12688. for (const material of json.materials) {
  12689. material.pbrMetallicRoughness = {
  12690. baseColorFactor: [1, 1, 1, 1],
  12691. metallicFactor: 1,
  12692. roughnessFactor: 1
  12693. };
  12694. const textureId = material.values && material.values.tex;
  12695. const textureIndex = json.textures.findIndex(texture => texture.id === textureId);
  12696. if (textureIndex !== -1) {
  12697. material.pbrMetallicRoughness.baseColorTexture = {
  12698. index: textureIndex
  12699. };
  12700. }
  12701. }
  12702. }
  12703. }
  12704. function normalizeGLTFV1(gltf, options = {}) {
  12705. return new GLTFV1Normalizer().normalize(gltf, options);
  12706. }
  12707. const COMPONENTS = {
  12708. SCALAR: 1,
  12709. VEC2: 2,
  12710. VEC3: 3,
  12711. VEC4: 4,
  12712. MAT2: 4,
  12713. MAT3: 9,
  12714. MAT4: 16
  12715. };
  12716. const BYTES = {
  12717. 5120: 1,
  12718. 5121: 1,
  12719. 5122: 2,
  12720. 5123: 2,
  12721. 5125: 4,
  12722. 5126: 4
  12723. };
  12724. const GL_SAMPLER = {
  12725. TEXTURE_MAG_FILTER: 0x2800,
  12726. TEXTURE_MIN_FILTER: 0x2801,
  12727. TEXTURE_WRAP_S: 0x2802,
  12728. TEXTURE_WRAP_T: 0x2803,
  12729. REPEAT: 0x2901,
  12730. LINEAR: 0x2601,
  12731. NEAREST_MIPMAP_LINEAR: 0x2702
  12732. };
  12733. const SAMPLER_PARAMETER_GLTF_TO_GL = {
  12734. magFilter: GL_SAMPLER.TEXTURE_MAG_FILTER,
  12735. minFilter: GL_SAMPLER.TEXTURE_MIN_FILTER,
  12736. wrapS: GL_SAMPLER.TEXTURE_WRAP_S,
  12737. wrapT: GL_SAMPLER.TEXTURE_WRAP_T
  12738. };
  12739. const DEFAULT_SAMPLER = {
  12740. [GL_SAMPLER.TEXTURE_MAG_FILTER]: GL_SAMPLER.LINEAR,
  12741. [GL_SAMPLER.TEXTURE_MIN_FILTER]: GL_SAMPLER.NEAREST_MIPMAP_LINEAR,
  12742. [GL_SAMPLER.TEXTURE_WRAP_S]: GL_SAMPLER.REPEAT,
  12743. [GL_SAMPLER.TEXTURE_WRAP_T]: GL_SAMPLER.REPEAT
  12744. };
  12745. function getBytesFromComponentType(componentType) {
  12746. return BYTES[componentType];
  12747. }
  12748. function getSizeFromAccessorType(type) {
  12749. return COMPONENTS[type];
  12750. }
  12751. class GLTFPostProcessor {
  12752. constructor() {
  12753. _defineProperty(this, "baseUri", '');
  12754. _defineProperty(this, "json", {});
  12755. _defineProperty(this, "buffers", []);
  12756. _defineProperty(this, "images", []);
  12757. }
  12758. postProcess(gltf, options = {}) {
  12759. const {
  12760. json,
  12761. buffers = [],
  12762. images = [],
  12763. baseUri = ''
  12764. } = gltf;
  12765. assert$1(json);
  12766. this.baseUri = baseUri;
  12767. this.json = json;
  12768. this.buffers = buffers;
  12769. this.images = images;
  12770. this._resolveTree(this.json, options);
  12771. return this.json;
  12772. }
  12773. _resolveTree(json, options = {}) {
  12774. if (json.bufferViews) {
  12775. json.bufferViews = json.bufferViews.map((bufView, i) => this._resolveBufferView(bufView, i));
  12776. }
  12777. if (json.images) {
  12778. json.images = json.images.map((image, i) => this._resolveImage(image, i));
  12779. }
  12780. if (json.samplers) {
  12781. json.samplers = json.samplers.map((sampler, i) => this._resolveSampler(sampler, i));
  12782. }
  12783. if (json.textures) {
  12784. json.textures = json.textures.map((texture, i) => this._resolveTexture(texture, i));
  12785. }
  12786. if (json.accessors) {
  12787. json.accessors = json.accessors.map((accessor, i) => this._resolveAccessor(accessor, i));
  12788. }
  12789. if (json.materials) {
  12790. json.materials = json.materials.map((material, i) => this._resolveMaterial(material, i));
  12791. }
  12792. if (json.meshes) {
  12793. json.meshes = json.meshes.map((mesh, i) => this._resolveMesh(mesh, i));
  12794. }
  12795. if (json.nodes) {
  12796. json.nodes = json.nodes.map((node, i) => this._resolveNode(node, i));
  12797. }
  12798. if (json.skins) {
  12799. json.skins = json.skins.map((skin, i) => this._resolveSkin(skin, i));
  12800. }
  12801. if (json.scenes) {
  12802. json.scenes = json.scenes.map((scene, i) => this._resolveScene(scene, i));
  12803. }
  12804. if (json.scene !== undefined) {
  12805. json.scene = json.scenes[this.json.scene];
  12806. }
  12807. }
  12808. getScene(index) {
  12809. return this._get('scenes', index);
  12810. }
  12811. getNode(index) {
  12812. return this._get('nodes', index);
  12813. }
  12814. getSkin(index) {
  12815. return this._get('skins', index);
  12816. }
  12817. getMesh(index) {
  12818. return this._get('meshes', index);
  12819. }
  12820. getMaterial(index) {
  12821. return this._get('materials', index);
  12822. }
  12823. getAccessor(index) {
  12824. return this._get('accessors', index);
  12825. }
  12826. getCamera(index) {
  12827. return null;
  12828. }
  12829. getTexture(index) {
  12830. return this._get('textures', index);
  12831. }
  12832. getSampler(index) {
  12833. return this._get('samplers', index);
  12834. }
  12835. getImage(index) {
  12836. return this._get('images', index);
  12837. }
  12838. getBufferView(index) {
  12839. return this._get('bufferViews', index);
  12840. }
  12841. getBuffer(index) {
  12842. return this._get('buffers', index);
  12843. }
  12844. _get(array, index) {
  12845. if (typeof index === 'object') {
  12846. return index;
  12847. }
  12848. const object = this.json[array] && this.json[array][index];
  12849. if (!object) {
  12850. console.warn("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  12851. }
  12852. return object;
  12853. }
  12854. _resolveScene(scene, index) {
  12855. scene.id = scene.id || "scene-".concat(index);
  12856. scene.nodes = (scene.nodes || []).map(node => this.getNode(node));
  12857. return scene;
  12858. }
  12859. _resolveNode(node, index) {
  12860. node.id = node.id || "node-".concat(index);
  12861. if (node.children) {
  12862. node.children = node.children.map(child => this.getNode(child));
  12863. }
  12864. if (node.mesh !== undefined) {
  12865. node.mesh = this.getMesh(node.mesh);
  12866. } else if (node.meshes !== undefined && node.meshes.length) {
  12867. node.mesh = node.meshes.reduce((accum, meshIndex) => {
  12868. const mesh = this.getMesh(meshIndex);
  12869. accum.id = mesh.id;
  12870. accum.primitives = accum.primitives.concat(mesh.primitives);
  12871. return accum;
  12872. }, {
  12873. primitives: []
  12874. });
  12875. }
  12876. if (node.camera !== undefined) {
  12877. node.camera = this.getCamera(node.camera);
  12878. }
  12879. if (node.skin !== undefined) {
  12880. node.skin = this.getSkin(node.skin);
  12881. }
  12882. return node;
  12883. }
  12884. _resolveSkin(skin, index) {
  12885. skin.id = skin.id || "skin-".concat(index);
  12886. skin.inverseBindMatrices = this.getAccessor(skin.inverseBindMatrices);
  12887. return skin;
  12888. }
  12889. _resolveMesh(mesh, index) {
  12890. mesh.id = mesh.id || "mesh-".concat(index);
  12891. if (mesh.primitives) {
  12892. mesh.primitives = mesh.primitives.map(primitive => {
  12893. primitive = { ...primitive
  12894. };
  12895. const attributes = primitive.attributes;
  12896. primitive.attributes = {};
  12897. for (const attribute in attributes) {
  12898. primitive.attributes[attribute] = this.getAccessor(attributes[attribute]);
  12899. }
  12900. if (primitive.indices !== undefined) {
  12901. primitive.indices = this.getAccessor(primitive.indices);
  12902. }
  12903. if (primitive.material !== undefined) {
  12904. primitive.material = this.getMaterial(primitive.material);
  12905. }
  12906. return primitive;
  12907. });
  12908. }
  12909. return mesh;
  12910. }
  12911. _resolveMaterial(material, index) {
  12912. material.id = material.id || "material-".concat(index);
  12913. if (material.normalTexture) {
  12914. material.normalTexture = { ...material.normalTexture
  12915. };
  12916. material.normalTexture.texture = this.getTexture(material.normalTexture.index);
  12917. }
  12918. if (material.occlusionTexture) {
  12919. material.occlustionTexture = { ...material.occlustionTexture
  12920. };
  12921. material.occlusionTexture.texture = this.getTexture(material.occlusionTexture.index);
  12922. }
  12923. if (material.emissiveTexture) {
  12924. material.emmisiveTexture = { ...material.emmisiveTexture
  12925. };
  12926. material.emissiveTexture.texture = this.getTexture(material.emissiveTexture.index);
  12927. }
  12928. if (!material.emissiveFactor) {
  12929. material.emissiveFactor = material.emmisiveTexture ? [1, 1, 1] : [0, 0, 0];
  12930. }
  12931. if (material.pbrMetallicRoughness) {
  12932. material.pbrMetallicRoughness = { ...material.pbrMetallicRoughness
  12933. };
  12934. const mr = material.pbrMetallicRoughness;
  12935. if (mr.baseColorTexture) {
  12936. mr.baseColorTexture = { ...mr.baseColorTexture
  12937. };
  12938. mr.baseColorTexture.texture = this.getTexture(mr.baseColorTexture.index);
  12939. }
  12940. if (mr.metallicRoughnessTexture) {
  12941. mr.metallicRoughnessTexture = { ...mr.metallicRoughnessTexture
  12942. };
  12943. mr.metallicRoughnessTexture.texture = this.getTexture(mr.metallicRoughnessTexture.index);
  12944. }
  12945. }
  12946. return material;
  12947. }
  12948. _resolveAccessor(accessor, index) {
  12949. accessor.id = accessor.id || "accessor-".concat(index);
  12950. if (accessor.bufferView !== undefined) {
  12951. accessor.bufferView = this.getBufferView(accessor.bufferView);
  12952. }
  12953. accessor.bytesPerComponent = getBytesFromComponentType(accessor.componentType);
  12954. accessor.components = getSizeFromAccessorType(accessor.type);
  12955. accessor.bytesPerElement = accessor.bytesPerComponent * accessor.components;
  12956. if (accessor.bufferView) {
  12957. const buffer = accessor.bufferView.buffer;
  12958. const {
  12959. ArrayType,
  12960. byteLength
  12961. } = getAccessorArrayTypeAndLength(accessor, accessor.bufferView);
  12962. const byteOffset = (accessor.bufferView.byteOffset || 0) + (accessor.byteOffset || 0) + buffer.byteOffset;
  12963. let cutBuffer = buffer.arrayBuffer.slice(byteOffset, byteOffset + byteLength);
  12964. if (accessor.bufferView.byteStride) {
  12965. cutBuffer = this._getValueFromInterleavedBuffer(buffer, byteOffset, accessor.bufferView.byteStride, accessor.bytesPerElement, accessor.count);
  12966. }
  12967. accessor.value = new ArrayType(cutBuffer);
  12968. }
  12969. return accessor;
  12970. }
  12971. _getValueFromInterleavedBuffer(buffer, byteOffset, byteStride, bytesPerElement, count) {
  12972. const result = new Uint8Array(count * bytesPerElement);
  12973. for (let i = 0; i < count; i++) {
  12974. const elementOffset = byteOffset + i * byteStride;
  12975. result.set(new Uint8Array(buffer.arrayBuffer.slice(elementOffset, elementOffset + bytesPerElement)), i * bytesPerElement);
  12976. }
  12977. return result.buffer;
  12978. }
  12979. _resolveTexture(texture, index) {
  12980. texture.id = texture.id || "texture-".concat(index);
  12981. texture.sampler = 'sampler' in texture ? this.getSampler(texture.sampler) : DEFAULT_SAMPLER;
  12982. texture.source = this.getImage(texture.source);
  12983. return texture;
  12984. }
  12985. _resolveSampler(sampler, index) {
  12986. sampler.id = sampler.id || "sampler-".concat(index);
  12987. sampler.parameters = {};
  12988. for (const key in sampler) {
  12989. const glEnum = this._enumSamplerParameter(key);
  12990. if (glEnum !== undefined) {
  12991. sampler.parameters[glEnum] = sampler[key];
  12992. }
  12993. }
  12994. return sampler;
  12995. }
  12996. _enumSamplerParameter(key) {
  12997. return SAMPLER_PARAMETER_GLTF_TO_GL[key];
  12998. }
  12999. _resolveImage(image, index) {
  13000. image.id = image.id || "image-".concat(index);
  13001. if (image.bufferView !== undefined) {
  13002. image.bufferView = this.getBufferView(image.bufferView);
  13003. }
  13004. const preloadedImage = this.images[index];
  13005. if (preloadedImage) {
  13006. image.image = preloadedImage;
  13007. }
  13008. return image;
  13009. }
  13010. _resolveBufferView(bufferView, index) {
  13011. const bufferIndex = bufferView.buffer;
  13012. const result = {
  13013. id: "bufferView-".concat(index),
  13014. ...bufferView,
  13015. buffer: this.buffers[bufferIndex]
  13016. };
  13017. const arrayBuffer = this.buffers[bufferIndex].arrayBuffer;
  13018. let byteOffset = this.buffers[bufferIndex].byteOffset || 0;
  13019. if ('byteOffset' in bufferView) {
  13020. byteOffset += bufferView.byteOffset;
  13021. }
  13022. result.data = new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  13023. return result;
  13024. }
  13025. _resolveCamera(camera, index) {
  13026. camera.id = camera.id || "camera-".concat(index);
  13027. if (camera.perspective) ;
  13028. if (camera.orthographic) ;
  13029. return camera;
  13030. }
  13031. }
  13032. function postProcessGLTF(gltf, options) {
  13033. return new GLTFPostProcessor().postProcess(gltf, options);
  13034. }
  13035. const MAGIC_glTF = 0x676c5446;
  13036. const GLB_FILE_HEADER_SIZE = 12;
  13037. const GLB_CHUNK_HEADER_SIZE = 8;
  13038. const GLB_CHUNK_TYPE_JSON = 0x4e4f534a;
  13039. const GLB_CHUNK_TYPE_BIN = 0x004e4942;
  13040. const GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED = 0;
  13041. const GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED = 1;
  13042. const GLB_V1_CONTENT_FORMAT_JSON = 0x0;
  13043. const LE = true;
  13044. function getMagicString(dataView, byteOffset = 0) {
  13045. 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)));
  13046. }
  13047. function isGLB(arrayBuffer, byteOffset = 0, options = {}) {
  13048. const dataView = new DataView(arrayBuffer);
  13049. const {
  13050. magic = MAGIC_glTF
  13051. } = options;
  13052. const magic1 = dataView.getUint32(byteOffset, false);
  13053. return magic1 === magic || magic1 === MAGIC_glTF;
  13054. }
  13055. function parseGLBSync(glb, arrayBuffer, byteOffset = 0, options = {}) {
  13056. const dataView = new DataView(arrayBuffer);
  13057. const type = getMagicString(dataView, byteOffset + 0);
  13058. const version = dataView.getUint32(byteOffset + 4, LE);
  13059. const byteLength = dataView.getUint32(byteOffset + 8, LE);
  13060. Object.assign(glb, {
  13061. header: {
  13062. byteOffset,
  13063. byteLength,
  13064. hasBinChunk: false
  13065. },
  13066. type,
  13067. version,
  13068. json: {},
  13069. binChunks: []
  13070. });
  13071. byteOffset += GLB_FILE_HEADER_SIZE;
  13072. switch (glb.version) {
  13073. case 1:
  13074. return parseGLBV1(glb, dataView, byteOffset);
  13075. case 2:
  13076. return parseGLBV2(glb, dataView, byteOffset, options = {});
  13077. default:
  13078. throw new Error("Invalid GLB version ".concat(glb.version, ". Only supports v1 and v2."));
  13079. }
  13080. }
  13081. function parseGLBV1(glb, dataView, byteOffset) {
  13082. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  13083. const contentLength = dataView.getUint32(byteOffset + 0, LE);
  13084. const contentFormat = dataView.getUint32(byteOffset + 4, LE);
  13085. byteOffset += GLB_CHUNK_HEADER_SIZE;
  13086. assert$7(contentFormat === GLB_V1_CONTENT_FORMAT_JSON);
  13087. parseJSONChunk(glb, dataView, byteOffset, contentLength);
  13088. byteOffset += contentLength;
  13089. byteOffset += parseBINChunk(glb, dataView, byteOffset, glb.header.byteLength);
  13090. return byteOffset;
  13091. }
  13092. function parseGLBV2(glb, dataView, byteOffset, options) {
  13093. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  13094. parseGLBChunksSync(glb, dataView, byteOffset, options);
  13095. return byteOffset + glb.header.byteLength;
  13096. }
  13097. function parseGLBChunksSync(glb, dataView, byteOffset, options) {
  13098. while (byteOffset + 8 <= glb.header.byteLength) {
  13099. const chunkLength = dataView.getUint32(byteOffset + 0, LE);
  13100. const chunkFormat = dataView.getUint32(byteOffset + 4, LE);
  13101. byteOffset += GLB_CHUNK_HEADER_SIZE;
  13102. switch (chunkFormat) {
  13103. case GLB_CHUNK_TYPE_JSON:
  13104. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  13105. break;
  13106. case GLB_CHUNK_TYPE_BIN:
  13107. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  13108. break;
  13109. case GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED:
  13110. if (!options.strict) {
  13111. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  13112. }
  13113. break;
  13114. case GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED:
  13115. if (!options.strict) {
  13116. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  13117. }
  13118. break;
  13119. }
  13120. byteOffset += padToNBytes(chunkLength, 4);
  13121. }
  13122. return byteOffset;
  13123. }
  13124. function parseJSONChunk(glb, dataView, byteOffset, chunkLength) {
  13125. const jsonChunk = new Uint8Array(dataView.buffer, byteOffset, chunkLength);
  13126. const textDecoder = new TextDecoder('utf8');
  13127. const jsonText = textDecoder.decode(jsonChunk);
  13128. glb.json = JSON.parse(jsonText);
  13129. return padToNBytes(chunkLength, 4);
  13130. }
  13131. function parseBINChunk(glb, dataView, byteOffset, chunkLength) {
  13132. glb.header.hasBinChunk = true;
  13133. glb.binChunks.push({
  13134. byteOffset,
  13135. byteLength: chunkLength,
  13136. arrayBuffer: dataView.buffer
  13137. });
  13138. return padToNBytes(chunkLength, 4);
  13139. }
  13140. async function parseGLTF(gltf, arrayBufferOrString, byteOffset = 0, options, context) {
  13141. var _options$gltf, _options$gltf2, _options$gltf3, _options$gltf4;
  13142. parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
  13143. normalizeGLTFV1(gltf, {
  13144. normalize: options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.normalize
  13145. });
  13146. preprocessExtensions(gltf, options, context);
  13147. const promises = [];
  13148. if (options !== null && options !== void 0 && (_options$gltf2 = options.gltf) !== null && _options$gltf2 !== void 0 && _options$gltf2.loadBuffers && gltf.json.buffers) {
  13149. await loadBuffers(gltf, options, context);
  13150. }
  13151. if (options !== null && options !== void 0 && (_options$gltf3 = options.gltf) !== null && _options$gltf3 !== void 0 && _options$gltf3.loadImages) {
  13152. const promise = loadImages(gltf, options, context);
  13153. promises.push(promise);
  13154. }
  13155. const promise = decodeExtensions(gltf, options, context);
  13156. promises.push(promise);
  13157. await Promise.all(promises);
  13158. gltf.json.gltfArrayBuffer = arrayBufferOrString // !zeg add 兼容gltf
  13159. return options !== null && options !== void 0 && (_options$gltf4 = options.gltf) !== null && _options$gltf4 !== void 0 && _options$gltf4.postProcess ? postProcessGLTF(gltf, options) : gltf;
  13160. }
  13161. function parseGLTFContainerSync(gltf, data, byteOffset, options) {
  13162. if (options.uri) {
  13163. gltf.baseUri = options.uri;
  13164. }
  13165. if (data instanceof ArrayBuffer && !isGLB(data, byteOffset, options)) {
  13166. const textDecoder = new TextDecoder();
  13167. data = textDecoder.decode(data);
  13168. }
  13169. if (typeof data === 'string') {
  13170. gltf.json = parseJSON(data);
  13171. } else if (data instanceof ArrayBuffer) {
  13172. const glb = {};
  13173. byteOffset = parseGLBSync(glb, data, byteOffset, options.glb);
  13174. assert$1(glb.type === 'glTF', "Invalid GLB magic string ".concat(glb.type));
  13175. gltf._glb = glb;
  13176. gltf.json = glb.json;
  13177. } else {
  13178. assert$1(false, 'GLTF: must be ArrayBuffer or string');
  13179. }
  13180. const buffers = gltf.json.buffers || [];
  13181. gltf.buffers = new Array(buffers.length).fill(null);
  13182. if (gltf._glb && gltf._glb.header.hasBinChunk) {
  13183. const {
  13184. binChunks
  13185. } = gltf._glb;
  13186. gltf.buffers[0] = {
  13187. arrayBuffer: binChunks[0].arrayBuffer,
  13188. byteOffset: binChunks[0].byteOffset,
  13189. byteLength: binChunks[0].byteLength
  13190. };
  13191. }
  13192. const images = gltf.json.images || [];
  13193. gltf.images = new Array(images.length).fill({});
  13194. }
  13195. async function loadBuffers(gltf, options, context) {
  13196. const buffers = gltf.json.buffers || [];
  13197. for (let i = 0; i < buffers.length; ++i) {
  13198. const buffer = buffers[i];
  13199. if (buffer.uri) {
  13200. var _context$fetch, _response$arrayBuffer;
  13201. const {
  13202. fetch
  13203. } = context;
  13204. assert$1(fetch);
  13205. const uri = resolveUrl(buffer.uri, options);
  13206. 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));
  13207. 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));
  13208. gltf.buffers[i] = {
  13209. arrayBuffer,
  13210. byteOffset: 0,
  13211. byteLength: arrayBuffer.byteLength
  13212. };
  13213. delete buffer.uri;
  13214. }
  13215. }
  13216. }
  13217. async function loadImages(gltf, options, context) {
  13218. const imageIndices = getReferencesImageIndices(gltf);
  13219. const images = gltf.json.images || [];
  13220. const promises = [];
  13221. for (const imageIndex of imageIndices) {
  13222. promises.push(loadImage(gltf, images[imageIndex], imageIndex, options, context));
  13223. }
  13224. return await Promise.all(promises);
  13225. }
  13226. function getReferencesImageIndices(gltf) {
  13227. const imageIndices = new Set();
  13228. const textures = gltf.json.textures || [];
  13229. for (const texture of textures) {
  13230. if (texture.source !== undefined) {
  13231. imageIndices.add(texture.source);
  13232. }
  13233. }
  13234. return Array.from(imageIndices).sort();
  13235. }
  13236. async function loadImage(gltf, image, index, options, context) {
  13237. const {
  13238. fetch,
  13239. parse
  13240. } = context;
  13241. let arrayBuffer;
  13242. if (image.uri) {
  13243. const uri = resolveUrl(image.uri, options);
  13244. const response = await fetch(uri);
  13245. arrayBuffer = await response.arrayBuffer();
  13246. }
  13247. if (Number.isFinite(image.bufferView)) {
  13248. const array = getTypedArrayForBufferView(gltf.json, gltf.buffers, image.bufferView);
  13249. arrayBuffer = sliceArrayBuffer(array.buffer, array.byteOffset, array.byteLength);
  13250. }
  13251. assert$1(arrayBuffer, 'glTF image has no data');
  13252. let parsedImage = await parse(arrayBuffer, [ImageLoader, BasisLoader], {
  13253. mimeType: image.mimeType,
  13254. basis: options.basis || {
  13255. format: selectSupportedBasisFormat()
  13256. }
  13257. }, context);
  13258. if (parsedImage && parsedImage[0]) {
  13259. parsedImage = {
  13260. compressed: true,
  13261. mipmaps: false,
  13262. width: parsedImage[0].width,
  13263. height: parsedImage[0].height,
  13264. data: parsedImage
  13265. };
  13266. }
  13267. gltf.images = gltf.images || [];
  13268. gltf.images[index] = parsedImage;
  13269. }
  13270. const GLTFLoader = {
  13271. name: 'glTF',
  13272. id: 'gltf',
  13273. module: 'gltf',
  13274. version: VERSION$3,
  13275. extensions: ['gltf', 'glb'],
  13276. mimeTypes: ['model/gltf+json', 'model/gltf-binary'],
  13277. text: true,
  13278. binary: true,
  13279. tests: ['glTF'],
  13280. parse: parse$1,
  13281. options: {
  13282. gltf: {
  13283. normalize: true,
  13284. loadBuffers: true,
  13285. loadImages: true,
  13286. decompressMeshes: true,
  13287. postProcess: true
  13288. },
  13289. log: console
  13290. },
  13291. deprecatedOptions: {
  13292. fetchImages: 'gltf.loadImages',
  13293. createImages: 'gltf.loadImages',
  13294. decompress: 'gltf.decompressMeshes',
  13295. postProcess: 'gltf.postProcess',
  13296. gltf: {
  13297. decompress: 'gltf.decompressMeshes'
  13298. }
  13299. }
  13300. };
  13301. async function parse$1(arrayBuffer, options = {}, context) {
  13302. options = { ...GLTFLoader.options,
  13303. ...options
  13304. };
  13305. options.gltf = { ...GLTFLoader.options.gltf,
  13306. ...options.gltf
  13307. };
  13308. const {
  13309. byteOffset = 0
  13310. } = options;
  13311. const gltf = {};
  13312. return await parseGLTF(gltf, arrayBuffer, byteOffset, options, context);
  13313. }
  13314. const GLTF_FORMAT = {
  13315. URI: 0,
  13316. EMBEDDED: 1
  13317. };
  13318. function parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options) {
  13319. tile.rotateYtoZ = true;
  13320. const gltfByteLength = tile.byteOffset + tile.byteLength - byteOffset;
  13321. if (gltfByteLength === 0) {
  13322. throw new Error('glTF byte length must be greater than 0.');
  13323. }
  13324. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13325. tile.gltfArrayBuffer = sliceArrayBuffer(arrayBuffer, byteOffset, gltfByteLength);
  13326. tile.gltfByteOffset = 0;
  13327. tile.gltfByteLength = gltfByteLength;
  13328. if (byteOffset % 4 === 0) ; else {
  13329. console.warn("".concat(tile.type, ": embedded glb is not aligned to a 4-byte boundary."));
  13330. }
  13331. return tile.byteOffset + tile.byteLength;
  13332. }
  13333. async function extractGLTF(tile, gltfFormat, options, context) {
  13334. const tile3DOptions = options['3d-tiles'] || {};
  13335. extractGLTFBufferOrURL(tile, gltfFormat);
  13336. if (tile3DOptions.loadGLTF) {
  13337. const {
  13338. parse,
  13339. fetch
  13340. } = context;
  13341. if (tile.gltfUrl) {
  13342. tile.gltfArrayBuffer = await fetch(tile.gltfUrl, options);
  13343. tile.gltfByteOffset = 0;
  13344. }
  13345. if (tile.gltfArrayBuffer) {
  13346. tile.gltf = await parse(tile.gltfArrayBuffer, GLTFLoader, options, context);
  13347. delete tile.gltfArrayBuffer;
  13348. delete tile.gltfByteOffset;
  13349. delete tile.gltfByteLength;
  13350. }
  13351. }
  13352. }
  13353. function extractGLTFBufferOrURL(tile, gltfFormat, options) {
  13354. switch (gltfFormat) {
  13355. case GLTF_FORMAT.URI:
  13356. const gltfUrlBytes = new Uint8Array(tile.gltfArrayBuffer, tile.gltfByteOffset);
  13357. const textDecoder = new TextDecoder();
  13358. const gltfUrl = textDecoder.decode(gltfUrlBytes);
  13359. tile.gltfUrl = gltfUrl.replace(/[\s\0]+$/, '');
  13360. delete tile.gltfArrayBuffer;
  13361. delete tile.gltfByteOffset;
  13362. delete tile.gltfByteLength;
  13363. break;
  13364. case GLTF_FORMAT.EMBEDDED:
  13365. break;
  13366. default:
  13367. throw new Error('b3dm: Illegal glTF format field');
  13368. }
  13369. }
  13370. async function parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13371. var _tile$gltf;
  13372. byteOffset = parseBatchedModel(tile, arrayBuffer, byteOffset, options);
  13373. await extractGLTF(tile, GLTF_FORMAT.EMBEDDED, options, context);
  13374. const extensions = tile === null || tile === void 0 ? void 0 : (_tile$gltf = tile.gltf) === null || _tile$gltf === void 0 ? void 0 : _tile$gltf.extensions;
  13375. if (extensions && extensions.CESIUM_RTC) {
  13376. tile.rtcCenter = extensions.CESIUM_RTC.center;
  13377. }
  13378. return byteOffset;
  13379. }
  13380. function parseBatchedModel(tile, arrayBuffer, byteOffset, options, context) {
  13381. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13382. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13383. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13384. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13385. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13386. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13387. return byteOffset;
  13388. }
  13389. async function parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  13390. byteOffset = parseInstancedModel(tile, arrayBuffer, byteOffset, options);
  13391. await extractGLTF(tile, tile.gltfFormat, options, context);
  13392. return byteOffset;
  13393. }
  13394. function parseInstancedModel(tile, arrayBuffer, byteOffset, options, context) {
  13395. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13396. if (tile.version !== 1) {
  13397. throw new Error("Instanced 3D Model version ".concat(tile.version, " is not supported"));
  13398. }
  13399. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  13400. const view = new DataView(arrayBuffer);
  13401. tile.gltfFormat = view.getUint32(byteOffset, true);
  13402. byteOffset += 4;
  13403. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  13404. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  13405. if (tile.featureTableJsonByteLength === 0) {
  13406. throw new Error('i3dm parser: featureTableJsonByteLength is zero.');
  13407. }
  13408. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  13409. const instancesLength = featureTable.getGlobalProperty('INSTANCES_LENGTH');
  13410. featureTable.featuresLength = instancesLength;
  13411. if (!Number.isFinite(instancesLength)) {
  13412. throw new Error('i3dm parser: INSTANCES_LENGTH must be defined');
  13413. }
  13414. tile.eastNorthUp = featureTable.getGlobalProperty('EAST_NORTH_UP');
  13415. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  13416. const batchTable = new Tile3DBatchTableParser(tile.batchTableJson, tile.batchTableBinary, instancesLength);
  13417. extractInstancedAttributes(tile, featureTable, batchTable, instancesLength);
  13418. return byteOffset;
  13419. }
  13420. function extractInstancedAttributes(tile, featureTable, batchTable, instancesLength) {
  13421. const collectionOptions = {
  13422. instances: new Array(instancesLength),
  13423. batchTable: tile._batchTable,
  13424. cull: false,
  13425. url: undefined,
  13426. gltf: undefined,
  13427. basePath: undefined,
  13428. incrementallyLoadTextures: false,
  13429. forwardAxis: [1, 0, 0]
  13430. };
  13431. const instances = collectionOptions.instances;
  13432. const instancePosition = new Vector3();
  13433. new Vector3();
  13434. new Vector3();
  13435. new Vector3();
  13436. const instanceRotation = new Matrix3();
  13437. const instanceQuaternion = new Quaternion();
  13438. const instanceScale = new Vector3();
  13439. const instanceTranslationRotationScale = {};
  13440. const instanceTransform = new Matrix4();
  13441. const scratch1 = [];
  13442. const scratch2 = [];
  13443. const scratchVector1 = new Vector3();
  13444. const scratchVector2 = new Vector3();
  13445. for (let i = 0; i < instancesLength; i++) {
  13446. let position;
  13447. if (featureTable.hasProperty('POSITION')) {
  13448. position = featureTable.getProperty('POSITION', GL$1.FLOAT, 3, i, instancePosition);
  13449. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  13450. position = featureTable.getProperty('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3, i, instancePosition);
  13451. const quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3, scratchVector1);
  13452. if (!quantizedVolumeOffset) {
  13453. throw new Error('i3dm parser: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  13454. }
  13455. const quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3, scratchVector2);
  13456. if (!quantizedVolumeScale) {
  13457. throw new Error('i3dm parser: QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  13458. }
  13459. const MAX_UNSIGNED_SHORT = 65535.0;
  13460. for (let j = 0; j < 3; j++) {
  13461. position[j] = position[j] / MAX_UNSIGNED_SHORT * quantizedVolumeScale[j] + quantizedVolumeOffset[j];
  13462. }
  13463. }
  13464. if (!position) {
  13465. throw new Error('i3dm: POSITION or POSITION_QUANTIZED must be defined for each instance.');
  13466. }
  13467. instancePosition.copy(position);
  13468. instanceTranslationRotationScale.translation = instancePosition;
  13469. tile.normalUp = featureTable.getProperty('NORMAL_UP', GL$1.FLOAT, 3, i, scratch1);
  13470. tile.normalRight = featureTable.getProperty('NORMAL_RIGHT', GL$1.FLOAT, 3, i, scratch2);
  13471. if (tile.normalUp) {
  13472. if (!tile.normalRight) {
  13473. throw new Error('i3dm: Custom orientation requires both NORMAL_UP and NORMAL_RIGHT.');
  13474. }
  13475. tile.hasCustomOrientation = true;
  13476. } else {
  13477. tile.octNormalUp = featureTable.getProperty('NORMAL_UP_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch1);
  13478. tile.octNormalRight = featureTable.getProperty('NORMAL_RIGHT_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch2);
  13479. if (tile.octNormalUp) {
  13480. if (!tile.octNormalRight) {
  13481. throw new Error('i3dm: oct-encoded orientation requires NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P');
  13482. }
  13483. throw new Error('i3dm: oct-encoded orientation not implemented');
  13484. } else if (tile.eastNorthUp) {
  13485. Ellipsoid.WGS84.eastNorthUpToFixedFrame(instancePosition, instanceTransform);
  13486. instanceTransform.getRotationMatrix3(instanceRotation);
  13487. } else {
  13488. instanceRotation.identity();
  13489. }
  13490. }
  13491. instanceQuaternion.fromMatrix3(instanceRotation);
  13492. instanceTranslationRotationScale.rotation = instanceQuaternion;
  13493. instanceScale.set(1.0, 1.0, 1.0);
  13494. const scale = featureTable.getProperty('SCALE', GL$1.FLOAT, 1, i);
  13495. if (Number.isFinite(scale)) {
  13496. instanceScale.multiplyByScalar(scale);
  13497. }
  13498. const nonUniformScale = featureTable.getProperty('SCALE_NON_UNIFORM', GL$1.FLOAT, 3, i, scratch1);
  13499. if (nonUniformScale) {
  13500. instanceScale.scale(nonUniformScale);
  13501. }
  13502. instanceTranslationRotationScale.scale = instanceScale;
  13503. let batchId = featureTable.getProperty('BATCH_ID', GL$1.UNSIGNED_SHORT, 1, i);
  13504. if (batchId === undefined) {
  13505. batchId = i;
  13506. }
  13507. const rotationMatrix = new Matrix4().fromQuaternion(instanceTranslationRotationScale.rotation);
  13508. instanceTransform.identity();
  13509. instanceTransform.translate(instanceTranslationRotationScale.translation);
  13510. instanceTransform.multiplyRight(rotationMatrix);
  13511. instanceTransform.scale(instanceTranslationRotationScale.scale);
  13512. const modelMatrix = instanceTransform.clone();
  13513. instances[i] = {
  13514. modelMatrix,
  13515. batchId
  13516. };
  13517. }
  13518. tile.instances = instances;
  13519. }
  13520. async function parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile) {
  13521. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  13522. const view = new DataView(arrayBuffer);
  13523. tile.tilesLength = view.getUint32(byteOffset, true);
  13524. byteOffset += 4;
  13525. tile.tiles = [];
  13526. while (tile.tiles.length < tile.tilesLength && tile.byteLength - byteOffset > 12) {
  13527. const subtile = {};
  13528. tile.tiles.push(subtile);
  13529. byteOffset = await parse3DTile(arrayBuffer, byteOffset, options, context, subtile);
  13530. }
  13531. return byteOffset;
  13532. }
  13533. async function parseGltf3DTile(tile, arrayBuffer, options, context) {
  13534. tile.rotateYtoZ = true;
  13535. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  13536. const {
  13537. parse
  13538. } = context;
  13539. tile.gltf = await parse(arrayBuffer, GLTFLoader, options, context);
  13540. }
  13541. async function parse3DTile(arrayBuffer, byteOffset = 0, options, context, tile = {}) {
  13542. tile.byteOffset = byteOffset;
  13543. tile.type = getMagicString$1(arrayBuffer, byteOffset);
  13544. switch (tile.type) {
  13545. case TILE3D_TYPE.COMPOSITE:
  13546. return await parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile);
  13547. case TILE3D_TYPE.BATCHED_3D_MODEL:
  13548. return await parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13549. case TILE3D_TYPE.GLTF:
  13550. return await parseGltf3DTile(tile, arrayBuffer, options, context);
  13551. case TILE3D_TYPE.INSTANCED_3D_MODEL:
  13552. return await parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  13553. case TILE3D_TYPE.POINT_CLOUD:
  13554. return await parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context);
  13555. default:
  13556. throw new Error("3DTileLoader: unknown type ".concat(tile.type));
  13557. }
  13558. }
  13559. const SUBTREE_FILE_MAGIC = 0x74627573;
  13560. const SUBTREE_FILE_VERSION = 1;
  13561. async function parse3DTilesSubtree(data) {
  13562. const magic = new Uint32Array(data.slice(0, 4));
  13563. if (magic[0] !== SUBTREE_FILE_MAGIC) {
  13564. throw new Error('Wrong subtree file magic number');
  13565. }
  13566. const version = new Uint32Array(data.slice(4, 8));
  13567. if (version[0] !== SUBTREE_FILE_VERSION) {
  13568. throw new Error('Wrong subtree file verson, must be 1');
  13569. }
  13570. const jsonByteLength = parseUint64Value(data.slice(8, 16));
  13571. const stringAttribute = new Uint8Array(data, 24, jsonByteLength);
  13572. const textDecoder = new TextDecoder('utf8');
  13573. const string = textDecoder.decode(stringAttribute);
  13574. const subtree = JSON.parse(string);
  13575. const binaryByteLength = parseUint64Value(data.slice(16, 24));
  13576. let internalBinaryBuffer = new ArrayBuffer(0);
  13577. if (binaryByteLength) {
  13578. internalBinaryBuffer = data.slice(24 + jsonByteLength);
  13579. }
  13580. if ('bufferView' in subtree.tileAvailability) {
  13581. subtree.tileAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'tileAvailability', internalBinaryBuffer);
  13582. }
  13583. if ('bufferView' in subtree.contentAvailability) {
  13584. subtree.contentAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'contentAvailability', internalBinaryBuffer);
  13585. }
  13586. if ('bufferView' in subtree.childSubtreeAvailability) {
  13587. subtree.childSubtreeAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'childSubtreeAvailability', internalBinaryBuffer);
  13588. }
  13589. return subtree;
  13590. }
  13591. async function getExplicitBitstream(subtree, name, internalBinaryBuffer) {
  13592. const bufferViewIndex = subtree[name].bufferView;
  13593. const bufferView = subtree.bufferViews[bufferViewIndex];
  13594. const buffer = subtree.buffers[bufferView.buffer];
  13595. if (buffer.uri) {
  13596. const response = await fetchFile(buffer.uri);
  13597. const data = await response.arrayBuffer();
  13598. return new Uint8Array(data, bufferView.byteOffset, bufferView.byteLength);
  13599. }
  13600. return new Uint8Array(internalBinaryBuffer, bufferView.byteOffset, bufferView.byteLength);
  13601. }
  13602. function parseUint64Value(buffer) {
  13603. const dataView = new DataView(buffer);
  13604. const left = dataView.getUint32(0, true);
  13605. const right = dataView.getUint32(4, true);
  13606. return left + 2 ** 32 * right;
  13607. }
  13608. const Tile3DSubtreeLoader = {
  13609. id: '3d-tiles-subtree',
  13610. name: '3D Tiles Subtree',
  13611. module: '3d-tiles',
  13612. version: VERSION$5,
  13613. extensions: ['subtree'],
  13614. mimeTypes: ['application/octet-stream'],
  13615. tests: ['subtree'],
  13616. parse: parse3DTilesSubtree,
  13617. options: {}
  13618. };
  13619. const QUADTREE_DEVISION_COUNT = 4;
  13620. const OCTREE_DEVISION_COUNT = 8;
  13621. const SUBDIVISION_COUNT_MAP = {
  13622. QUADTREE: QUADTREE_DEVISION_COUNT,
  13623. OCTREE: OCTREE_DEVISION_COUNT
  13624. };
  13625. async function parseImplicitTiles(subtree, options, parentData = {
  13626. mortonIndex: 0,
  13627. x: 0,
  13628. y: 0,
  13629. z: 0
  13630. }, childIndex = 0, level = 0, globalData = {
  13631. level: 0,
  13632. mortonIndex: 0,
  13633. x: 0,
  13634. y: 0,
  13635. z: 0
  13636. }) {
  13637. const {
  13638. subdivisionScheme,
  13639. subtreeLevels,
  13640. maximumLevel,
  13641. contentUrlTemplate,
  13642. subtreesUriTemplate,
  13643. basePath
  13644. } = options;
  13645. const tile = {
  13646. children: [],
  13647. lodMetricValue: 0,
  13648. contentUrl: ''
  13649. };
  13650. const childrenPerTile = SUBDIVISION_COUNT_MAP[subdivisionScheme];
  13651. const childX = childIndex & 0b01;
  13652. const childY = childIndex >> 1 & 0b01;
  13653. const childZ = childIndex >> 2 & 0b01;
  13654. const levelOffset = (childrenPerTile ** level - 1) / (childrenPerTile - 1);
  13655. let childTileMortonIndex = concatBits(parentData.mortonIndex, childIndex);
  13656. let tileAvailabilityIndex = levelOffset + childTileMortonIndex;
  13657. let childTileX = concatBits(parentData.x, childX);
  13658. let childTileY = concatBits(parentData.y, childY);
  13659. let childTileZ = concatBits(parentData.z, childZ);
  13660. let isChildSubtreeAvailable = false;
  13661. if (level + 1 > subtreeLevels) {
  13662. isChildSubtreeAvailable = getAvailabilityResult(subtree.childSubtreeAvailability, childTileMortonIndex);
  13663. }
  13664. const x = concatBits(globalData.x, childTileX);
  13665. const y = concatBits(globalData.y, childTileY);
  13666. const z = concatBits(globalData.z, childTileZ);
  13667. const lev = level + globalData.level;
  13668. if (isChildSubtreeAvailable) {
  13669. const subtreePath = "".concat(basePath, "/").concat(subtreesUriTemplate);
  13670. const childSubtreeUrl = replaceContentUrlTemplate(subtreePath, lev, x, y, z);
  13671. const childSubtree = await load(childSubtreeUrl, Tile3DSubtreeLoader);
  13672. subtree = childSubtree;
  13673. globalData.mortonIndex = childTileMortonIndex;
  13674. globalData.x = childTileX;
  13675. globalData.y = childTileY;
  13676. globalData.z = childTileZ;
  13677. globalData.level = level;
  13678. childTileMortonIndex = 0;
  13679. tileAvailabilityIndex = 0;
  13680. childTileX = 0;
  13681. childTileY = 0;
  13682. childTileZ = 0;
  13683. level = 0;
  13684. }
  13685. const isTileAvailable = getAvailabilityResult(subtree.tileAvailability, tileAvailabilityIndex);
  13686. if (!isTileAvailable || level > maximumLevel) {
  13687. return tile;
  13688. }
  13689. const isContentAvailable = getAvailabilityResult(subtree.contentAvailability, tileAvailabilityIndex);
  13690. if (isContentAvailable) {
  13691. tile.contentUrl = replaceContentUrlTemplate(contentUrlTemplate, lev, x, y, z);
  13692. }
  13693. const childTileLevel = level + 1;
  13694. const pData = {
  13695. mortonIndex: childTileMortonIndex,
  13696. x: childTileX,
  13697. y: childTileY,
  13698. z: childTileZ
  13699. };
  13700. for (let index = 0; index < childrenPerTile; index++) {
  13701. const currentTile = await parseImplicitTiles(subtree, options, pData, index, childTileLevel, globalData);
  13702. if (currentTile.contentUrl || currentTile.children.length) {
  13703. const globalLevel = lev + 1;
  13704. const childCoordinates = {
  13705. childTileX,
  13706. childTileY,
  13707. childTileZ
  13708. };
  13709. const formattedTile = formatTileData(currentTile, globalLevel, childCoordinates, options);
  13710. tile.children.push(formattedTile);
  13711. }
  13712. }
  13713. return tile;
  13714. }
  13715. function getAvailabilityResult(availabilityData, index) {
  13716. if ('constant' in availabilityData) {
  13717. return Boolean(availabilityData.constant);
  13718. }
  13719. if (availabilityData.explicitBitstream) {
  13720. return getBooleanValueFromBitstream(index, availabilityData.explicitBitstream);
  13721. }
  13722. return false;
  13723. }
  13724. function formatTileData(tile, level, childCoordinates, options) {
  13725. const {
  13726. basePath,
  13727. refine,
  13728. getRefine,
  13729. lodMetricType,
  13730. getTileType,
  13731. rootLodMetricValue,
  13732. rootBoundingVolume
  13733. } = options;
  13734. const uri = tile.contentUrl && tile.contentUrl.replace("".concat(basePath, "/"), '');
  13735. const lodMetricValue = rootLodMetricValue / 2 ** level;
  13736. const boundingVolume = calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates);
  13737. return {
  13738. children: tile.children,
  13739. contentUrl: tile.contentUrl,
  13740. content: {
  13741. uri
  13742. },
  13743. id: tile.contentUrl,
  13744. refine: getRefine(refine),
  13745. type: getTileType(tile),
  13746. lodMetricType,
  13747. lodMetricValue,
  13748. boundingVolume
  13749. };
  13750. }
  13751. function calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates) {
  13752. if (rootBoundingVolume.region) {
  13753. const {
  13754. childTileX,
  13755. childTileY,
  13756. childTileZ
  13757. } = childCoordinates;
  13758. const [west, south, east, north, minimumHeight, maximumHeight] = rootBoundingVolume.region;
  13759. const boundingVolumesCount = 2 ** level;
  13760. const sizeX = (east - west) / boundingVolumesCount;
  13761. const sizeY = (north - south) / boundingVolumesCount;
  13762. const sizeZ = (maximumHeight - minimumHeight) / boundingVolumesCount;
  13763. const [childWest, childEast] = [west + sizeX * childTileX, west + sizeX * (childTileX + 1)];
  13764. const [childSouth, childNorth] = [south + sizeY * childTileY, south + sizeY * (childTileY + 1)];
  13765. const [childMinimumHeight, childMaximumHeight] = [minimumHeight + sizeZ * childTileZ, minimumHeight + sizeZ * (childTileZ + 1)];
  13766. return {
  13767. region: [childWest, childSouth, childEast, childNorth, childMinimumHeight, childMaximumHeight]
  13768. };
  13769. }
  13770. console.warn('Unsupported bounding volume type: ', rootBoundingVolume);
  13771. return null;
  13772. }
  13773. function concatBits(first, second) {
  13774. return parseInt(first.toString(2) + second.toString(2), 2);
  13775. }
  13776. function replaceContentUrlTemplate(templateUrl, level, x, y, z) {
  13777. const mapUrl = generateMapUrl({
  13778. level,
  13779. x,
  13780. y,
  13781. z
  13782. });
  13783. return templateUrl.replace(/{level}|{x}|{y}|{z}/gi, matched => mapUrl[matched]);
  13784. }
  13785. function generateMapUrl(items) {
  13786. const mapUrl = {};
  13787. for (const key in items) {
  13788. mapUrl["{".concat(key, "}")] = items[key];
  13789. }
  13790. return mapUrl;
  13791. }
  13792. function getBooleanValueFromBitstream(availabilityIndex, availabilityBuffer) {
  13793. const byteIndex = Math.floor(availabilityIndex / 8);
  13794. const bitIndex = availabilityIndex % 8;
  13795. const bitValue = availabilityBuffer[byteIndex] >> bitIndex & 1;
  13796. return bitValue === 1;
  13797. }
  13798. function getTileType(tile) {
  13799. if (!tile.contentUrl) {
  13800. return TILE_TYPE.EMPTY;
  13801. }
  13802. const contentUrl = tile.contentUrl;
  13803. const fileExtension = contentUrl.split('.').pop();
  13804. switch (fileExtension) {
  13805. case 'pnts':
  13806. return TILE_TYPE.POINTCLOUD;
  13807. case 'i3dm':
  13808. case 'b3dm':
  13809. case 'glb':
  13810. case 'gltf':
  13811. return TILE_TYPE.SCENEGRAPH;
  13812. default:
  13813. return fileExtension;
  13814. }
  13815. }
  13816. function getRefine(refine) {
  13817. switch (refine) {
  13818. case 'REPLACE':
  13819. case 'replace':
  13820. return TILE_REFINEMENT.REPLACE;
  13821. case 'ADD':
  13822. case 'add':
  13823. return TILE_REFINEMENT.ADD;
  13824. default:
  13825. return refine;
  13826. }
  13827. }
  13828. function normalizeTileData(tile, options) {
  13829. if (!tile) {
  13830. return null;
  13831. }
  13832. if (tile.content) {
  13833. const contentUri = tile.content.uri || tile.content.url;
  13834. tile.contentUrl = "".concat(options.basePath, "/").concat(contentUri);
  13835. }
  13836. tile.id = tile.contentUrl;
  13837. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13838. tile.lodMetricValue = tile.geometricError;
  13839. tile.transformMatrix = tile.transform;
  13840. tile.type = getTileType(tile);
  13841. tile.refine = getRefine(tile.refine);
  13842. return tile;
  13843. }
  13844. function normalizeTileHeaders(tileset) {
  13845. const basePath = tileset.basePath;
  13846. const root = normalizeTileData(tileset.root, tileset);
  13847. const stack = [];
  13848. stack.push(root);
  13849. while (stack.length > 0) {
  13850. const tile = stack.pop() || {};
  13851. const children = tile.children || [];
  13852. for (const childHeader of children) {
  13853. normalizeTileData(childHeader, {
  13854. basePath
  13855. });
  13856. stack.push(childHeader);
  13857. }
  13858. }
  13859. return root;
  13860. }
  13861. async function normalizeImplicitTileHeaders(tileset) {
  13862. if (!tileset.root) {
  13863. return null;
  13864. }
  13865. const basePath = tileset.basePath;
  13866. const implicitTilingExtension = tileset.root.extensions['3DTILES_implicit_tiling'];
  13867. const {
  13868. subdivisionScheme,
  13869. maximumLevel,
  13870. subtreeLevels,
  13871. subtrees: {
  13872. uri: subtreesUriTemplate
  13873. }
  13874. } = implicitTilingExtension;
  13875. const subtreeUrl = replaceContentUrlTemplate(subtreesUriTemplate, 0, 0, 0, 0);
  13876. const rootSubtreeUrl = "".concat(basePath, "/").concat(subtreeUrl);
  13877. const rootSubtree = await load(rootSubtreeUrl, Tile3DSubtreeLoader);
  13878. const contentUrlTemplate = "".concat(basePath, "/").concat(tileset.root.content.uri);
  13879. const refine = tileset.root.refine;
  13880. const rootLodMetricValue = tileset.root.geometricError;
  13881. const rootBoundingVolume = tileset.root.boundingVolume;
  13882. const options = {
  13883. contentUrlTemplate,
  13884. subtreesUriTemplate,
  13885. subdivisionScheme,
  13886. subtreeLevels,
  13887. maximumLevel,
  13888. refine,
  13889. basePath,
  13890. lodMetricType: LOD_METRIC_TYPE.GEOMETRIC_ERROR,
  13891. rootLodMetricValue,
  13892. rootBoundingVolume,
  13893. getTileType,
  13894. getRefine
  13895. };
  13896. return await normalizeImplicitTileData(tileset.root, rootSubtree, options);
  13897. }
  13898. async function normalizeImplicitTileData(tile, rootSubtree, options) {
  13899. if (!tile) {
  13900. return null;
  13901. }
  13902. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13903. tile.lodMetricValue = tile.geometricError;
  13904. tile.transformMatrix = tile.transform;
  13905. const {
  13906. children,
  13907. contentUrl
  13908. } = await parseImplicitTiles(rootSubtree, options);
  13909. if (contentUrl) {
  13910. tile.contentUrl = contentUrl;
  13911. tile.content = {
  13912. uri: contentUrl.replace("".concat(options.basePath, "/"), '')
  13913. };
  13914. }
  13915. tile.refine = getRefine(tile.refine);
  13916. tile.type = getTileType(tile);
  13917. tile.children = children;
  13918. tile.id = tile.contentUrl;
  13919. return tile;
  13920. }
  13921. const IMPLICIT_TILING_EXTENSION_NAME = '3DTILES_implicit_tiling';
  13922. const Tiles3DLoader = {
  13923. id: '3d-tiles',
  13924. name: '3D Tiles',
  13925. module: '3d-tiles',
  13926. version: VERSION$5,
  13927. extensions: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  13928. mimeTypes: ['application/octet-stream'],
  13929. tests: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  13930. parse,
  13931. options: {
  13932. '3d-tiles': {
  13933. loadGLTF: true,
  13934. decodeQuantizedPositions: false,
  13935. isTileset: 'auto',
  13936. assetGltfUpAxis: null
  13937. }
  13938. }
  13939. };
  13940. function getBaseUri(tileset) {
  13941. return dirname(tileset.url);
  13942. }
  13943. async function parseTile(arrayBuffer, options, context) {
  13944. const tile = {
  13945. content: {
  13946. featureIds: null
  13947. }
  13948. };
  13949. const byteOffset = 0;
  13950. await parse3DTile(arrayBuffer, byteOffset, options, context, tile.content);
  13951. return tile.content;
  13952. }
  13953. async function parseTileset(data, options, context) {
  13954. var _tilesetJson$root;
  13955. const tilesetJson = JSON.parse(new TextDecoder().decode(data));
  13956. tilesetJson.loader = options.loader || Tiles3DLoader;
  13957. tilesetJson.url = context.url;
  13958. tilesetJson.basePath = getBaseUri(tilesetJson);
  13959. tilesetJson.root = hasImplicitTilingExtension(tilesetJson) ? await normalizeImplicitTileHeaders(tilesetJson) : normalizeTileHeaders(tilesetJson);
  13960. tilesetJson.type = TILESET_TYPE.TILES3D;
  13961. tilesetJson.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  13962. tilesetJson.lodMetricValue = ((_tilesetJson$root = tilesetJson.root) === null || _tilesetJson$root === void 0 ? void 0 : _tilesetJson$root.lodMetricValue) || 0;
  13963. return tilesetJson;
  13964. }
  13965. async function parse(data, options, context) {
  13966. const loaderOptions = options['3d-tiles'] || {};
  13967. let isTileset;
  13968. if (loaderOptions.isTileset === 'auto') {
  13969. isTileset = context.url && context.url.indexOf('.json') !== -1;
  13970. } else {
  13971. isTileset = loaderOptions.isTileset;
  13972. }
  13973. if (isTileset) {
  13974. data = await parseTileset(data, options, context);
  13975. } else {
  13976. data = await parseTile(data, options, context);
  13977. }
  13978. return data;
  13979. }
  13980. function hasImplicitTilingExtension(tilesetJson) {
  13981. var _tilesetJson$extensio, _tilesetJson$extensio2;
  13982. 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));
  13983. }
  13984. const CESIUM_ION_URL = 'https://api.cesium.com/v1/assets';
  13985. async function getIonTilesetMetadata(accessToken, assetId) {
  13986. if (!assetId) {
  13987. const assets = await getIonAssets(accessToken);
  13988. for (const item of assets.items) {
  13989. if (item.type === '3DTILES') {
  13990. assetId = item.id;
  13991. }
  13992. }
  13993. }
  13994. const ionAssetMetadata = await getIonAssetMetadata(accessToken, assetId);
  13995. const {
  13996. type,
  13997. url
  13998. } = ionAssetMetadata;
  13999. assert$7(type === '3DTILES' && url);
  14000. ionAssetMetadata.headers = {
  14001. Authorization: "Bearer ".concat(ionAssetMetadata.accessToken)
  14002. };
  14003. return ionAssetMetadata;
  14004. }
  14005. async function getIonAssets(accessToken) {
  14006. assert$7(accessToken);
  14007. const url = CESIUM_ION_URL;
  14008. const headers = {
  14009. Authorization: "Bearer ".concat(accessToken)
  14010. };
  14011. const response = await fetchFile(url, {
  14012. fetch: {
  14013. headers
  14014. }
  14015. });
  14016. if (!response.ok) {
  14017. throw new Error(response.statusText);
  14018. }
  14019. return await response.json();
  14020. }
  14021. async function getIonAssetMetadata(accessToken, assetId) {
  14022. assert$7(accessToken, assetId);
  14023. const headers = {
  14024. Authorization: "Bearer ".concat(accessToken)
  14025. };
  14026. const url = "".concat(CESIUM_ION_URL, "/").concat(assetId);
  14027. let response = await fetchFile("".concat(url), {
  14028. fetch: {
  14029. headers
  14030. }
  14031. });
  14032. if (!response.ok) {
  14033. throw new Error(response.statusText);
  14034. }
  14035. let metadata = await response.json();
  14036. response = await fetchFile("".concat(url, "/endpoint"), {
  14037. fetch: {
  14038. headers
  14039. }
  14040. });
  14041. if (!response.ok) {
  14042. throw new Error(response.statusText);
  14043. }
  14044. const tilesetInfo = await response.json();
  14045. metadata = { ...metadata,
  14046. ...tilesetInfo
  14047. };
  14048. return metadata;
  14049. }
  14050. async function preload(url, options = {}) {
  14051. options = options['cesium-ion'] || {};
  14052. const {
  14053. accessToken
  14054. } = options;
  14055. let assetId = options.assetId;
  14056. if (!Number.isFinite(assetId)) {
  14057. const matched = url.match(/\/([0-9]+)\/tileset.json/);
  14058. assetId = matched && matched[1];
  14059. }
  14060. return getIonTilesetMetadata(accessToken, assetId);
  14061. }
  14062. const CesiumIonLoader = { ...Tiles3DLoader,
  14063. id: 'cesium-ion',
  14064. name: 'Cesium Ion',
  14065. preload,
  14066. parse: async (data, options, context) => {
  14067. options = { ...options
  14068. };
  14069. options['3d-tiles'] = options['cesium-ion'];
  14070. options.loader = CesiumIonLoader;
  14071. return Tiles3DLoader.parse(data, options, context);
  14072. },
  14073. options: {
  14074. 'cesium-ion': { ...Tiles3DLoader.options['3d-tiles'],
  14075. accessToken: null
  14076. }
  14077. }
  14078. };
  14079. // From https://github.com/potree/potree/blob/master/src/materials/PointCloudMaterial.js
  14080. function generateGradientTexture(gradient) {
  14081. const size = 64;
  14082. // create canvas
  14083. const canvas = document.createElement('canvas');
  14084. canvas.width = size;
  14085. canvas.height = size;
  14086. // get context
  14087. const context = canvas.getContext('2d');
  14088. // draw gradient
  14089. context.rect(0, 0, size, size);
  14090. const ctxGradient = context.createLinearGradient(0, 0, size, size);
  14091. for (let i = 0; i < gradient.length; i++) {
  14092. const step = gradient[i];
  14093. ctxGradient.addColorStop(step[0], '#' + step[1].getHexString());
  14094. }
  14095. context.fillStyle = ctxGradient;
  14096. context.fill();
  14097. //let texture = new THREE.Texture(canvas);
  14098. const texture = new CanvasTexture(canvas);
  14099. texture.needsUpdate = true;
  14100. texture.minFilter = LinearFilter;
  14101. texture.wrapS = RepeatWrapping;
  14102. texture.wrapT = RepeatWrapping;
  14103. texture.repeat.set(2, 2);
  14104. // textureImage = texture.image;
  14105. return texture;
  14106. }
  14107. function getCameraFrustum(camera) {
  14108. camera.updateMatrix(); // make sure camera's local matrix is updated
  14109. camera.updateMatrixWorld(); // make sure camera's world matrix is updated
  14110. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14111. const frustum = new Frustum();
  14112. frustum.setFromProjectionMatrix(new Matrix4$1().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));
  14113. return frustum;
  14114. }
  14115. function loadersPlaneToMesh(plane) {
  14116. const group = new Group();
  14117. // Create a basic rectangle geometry from math.gl plane
  14118. const planeGeometry = new PlaneGeometry(10, 5);
  14119. // Align the geometry to the plane
  14120. const coplanarPoint = new Vector3$1(...plane.projectPointOntoPlane([0, 0, 0]));
  14121. const normal = new Vector3$1(plane.normal.x, plane.normal.y, plane.normal.z);
  14122. const focalPoint = new Vector3$1().copy(coplanarPoint).add(normal);
  14123. planeGeometry.lookAt(focalPoint);
  14124. planeGeometry.translate(coplanarPoint.x, coplanarPoint.y, coplanarPoint.z);
  14125. // Edges
  14126. /*
  14127. const edges = new EdgesGeometry(planeGeometry)
  14128. var dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: 0x00ffff }))*/
  14129. //plane
  14130. const material = new MeshBasicMaterial({ color: 0x00ffff, side: DoubleSide });
  14131. const mesh = new Mesh(planeGeometry, material);
  14132. const arrowHelper = new ArrowHelper(normal, coplanarPoint, 5, 0xffff00);
  14133. group.add(arrowHelper);
  14134. group.add(mesh);
  14135. return group;
  14136. }
  14137. function loadersBoundingBoxToMesh(tile) {
  14138. // Create a basic rectangle geometry from math.gl half-axes
  14139. const boundUntransformed = tile.type == 'empty' ? tile.boundingVolume : tile.getBoundUntransformed() //empty时没创建好,直接给boundingVolume一样
  14140. /* let redColor = 0;
  14141. if (tile.content) {
  14142. //redColor = Math.min((tile.content.byteLength != void 0 ? tile.content.byteLength : 0) / 500000, 1.0);
  14143. redColor = Math.min( tile.depth / 10 , 1.0); //改
  14144. } */
  14145. let hue = 0
  14146. if(tile.content){
  14147. hue = Math.min( tile.depth / 10 , 1.0); //改
  14148. }
  14149. const boxColor = new THREE.Color().setHSL(hue, 0.9, 0.85)
  14150. //const boxColor = new Color(redColor, 1.0, 0.0);
  14151. const boxGeometry = new BoxGeometry(1, 1, 1);
  14152. const boxTransform = new Matrix4$1();
  14153. if (boundUntransformed.halfAxes) {
  14154. boxTransform.copy(getMatrix4FromHalfAxes(boundUntransformed.halfAxes));
  14155. }
  14156. else if (boundUntransformed.radius) {
  14157. boxGeometry.scale(boundUntransformed.radius * 2, boundUntransformed.radius * 2, boundUntransformed.radius * 2);
  14158. }
  14159. boxTransform.premultiply((new Matrix4$1()).setPosition(...boundUntransformed.center)) //add
  14160. /* if(tile.type != "empty"){ //root单独处理了
  14161. boxTransform.premultiply((new Matrix4$1()).makeScale(1,1,-1))//xzw 因为mesh倒转了所以box也
  14162. }else{
  14163. console.log('empty')
  14164. } */
  14165. boxGeometry.applyMatrix4(boxTransform);
  14166. const edges = new EdgesGeometry(boxGeometry);
  14167. const dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: boxColor, transparent:true }));
  14168. //dispPlane.position.copy(new Vector3$1(...boundingVolume.center));
  14169. dispPlane.matrixAutoUpdate = false //add
  14170. let label = new Potree.TextSprite({
  14171. mat: new THREE.MeshBasicMaterial({transparent:true }), //depthTest:false会导致经常显示不出
  14172. backgroundColor: {r: 0, g: 0, b: 0, a:0.1},
  14173. textColor: {r: boxColor.r*255, g: boxColor.g*255, b: boxColor.b*255, a:0.9},
  14174. fontsize:100,
  14175. //useDepth : true ,
  14176. renderOrder : 5,
  14177. text: tile.id.split('/').pop().split('.b3dm')[0], //Tile_+094_-010.b3dm'
  14178. name:'tile'
  14179. })
  14180. label.addEventListener('mouseover',()=>{
  14181. if(label.sprite.material.opacity < 1)return
  14182. window.hoverTile = tile
  14183. console.log('hoverLabel',tile.id, tile._distanceToCamera)
  14184. })
  14185. /* let s = 0.6
  14186. label.scale.set(s,s,s) */
  14187. let s = tile.tileset.options.maximumScreenSpaceError / 400
  14188. label.scale.set(s,s,s)
  14189. dispPlane.add(label)
  14190. label.position.set(...boundUntransformed.center)
  14191. //label.position.z *= -1
  14192. /* if(tile.content.byteLength == void 0){
  14193. let oldUpdate = dispPlane.updateMatrixWorld.bind(dispPlane)
  14194. dispPlane.updateMatrixWorld = (a,b)=>{
  14195. oldUpdate(a,b)
  14196. }
  14197. let oldU = dispPlane.updateMatrix.bind(dispPlane)
  14198. dispPlane.updateMatrix = (a,b)=>{
  14199. oldU(a,b)
  14200. }
  14201. } */
  14202. tile.volumeBox = dispPlane
  14203. return dispPlane;
  14204. }
  14205. function getMatrix4FromHalfAxes(halfAxes) {
  14206. const m = halfAxes;
  14207. const rotateMatrix = new Matrix4$1().fromArray([
  14208. m[0] * 2,
  14209. m[1] * 2,
  14210. m[2] * 2,
  14211. 0,
  14212. m[3] * 2,
  14213. m[4] * 2,
  14214. m[5] * 2,
  14215. 0,
  14216. m[6] * 2,
  14217. m[7] * 2,
  14218. m[8] * 2,
  14219. 0,
  14220. 0,
  14221. 0,
  14222. 0,
  14223. 1,
  14224. ]);
  14225. return rotateMatrix;
  14226. }
  14227. /*
  14228. * from https://github.com/tentone/geo-three
  14229. * Tree-shaking did not work, probably due to static class methods
  14230. */
  14231. function datumsToSpherical(latitude, longitude) {
  14232. const EARTH_RADIUS = 6378137;
  14233. const EARTH_PERIMETER = 2 * Math.PI * EARTH_RADIUS;
  14234. const EARTH_ORIGIN = EARTH_PERIMETER / 2.0;
  14235. const x = longitude * EARTH_ORIGIN / 180.0;
  14236. let y = Math.log(Math.tan((90 + latitude) * Math.PI / 360.0)) / (Math.PI / 180.0);
  14237. y = y * EARTH_ORIGIN / 180.0;
  14238. return new Vector2$1(x, y);
  14239. }
  14240. const Gradients = {
  14241. // From chroma spectral http://gka.github.io/chroma.js/
  14242. SPECTRAL: [
  14243. [0, new Color(0.3686, 0.3098, 0.6353)],
  14244. [0.1, new Color(0.1961, 0.5333, 0.7412)],
  14245. [0.2, new Color(0.4, 0.7608, 0.6471)],
  14246. [0.3, new Color(0.6706, 0.8667, 0.6431)],
  14247. [0.4, new Color(0.902, 0.9608, 0.5961)],
  14248. [0.5, new Color(1.0, 1.0, 0.749)],
  14249. [0.6, new Color(0.9961, 0.8784, 0.5451)],
  14250. [0.7, new Color(0.9922, 0.6824, 0.3804)],
  14251. [0.8, new Color(0.9569, 0.4275, 0.2627)],
  14252. [0.9, new Color(0.8353, 0.2431, 0.3098)],
  14253. [1, new Color(0.6196, 0.0039, 0.2588)],
  14254. ],
  14255. PLASMA: [
  14256. [0.0, new Color(0.241, 0.015, 0.61)],
  14257. [0.1, new Color(0.387, 0.001, 0.654)],
  14258. [0.2, new Color(0.524, 0.025, 0.653)],
  14259. [0.3, new Color(0.651, 0.125, 0.596)],
  14260. [0.4, new Color(0.752, 0.227, 0.513)],
  14261. [0.5, new Color(0.837, 0.329, 0.431)],
  14262. [0.6, new Color(0.907, 0.435, 0.353)],
  14263. [0.7, new Color(0.963, 0.554, 0.272)],
  14264. [0.8, new Color(0.992, 0.681, 0.195)],
  14265. [0.9, new Color(0.987, 0.822, 0.144)],
  14266. [1.0, new Color(0.94, 0.975, 0.131)],
  14267. ],
  14268. YELLOW_GREEN: [
  14269. [0, new Color(0.1647, 0.2824, 0.3451)],
  14270. [0.1, new Color(0.1338, 0.3555, 0.4227)],
  14271. [0.2, new Color(0.061, 0.4319, 0.4864)],
  14272. [0.3, new Color(0.0, 0.5099, 0.5319)],
  14273. [0.4, new Color(0.0, 0.5881, 0.5569)],
  14274. [0.5, new Color(0.137, 0.665, 0.5614)],
  14275. [0.6, new Color(0.2906, 0.7395, 0.5477)],
  14276. [0.7, new Color(0.4453, 0.8099, 0.5201)],
  14277. [0.8, new Color(0.6102, 0.8748, 0.485)],
  14278. [0.9, new Color(0.7883, 0.9323, 0.4514)],
  14279. [1, new Color(0.9804, 0.9804, 0.4314)],
  14280. ],
  14281. VIRIDIS: [
  14282. [0.0, new Color(0.267, 0.005, 0.329)],
  14283. [0.1, new Color(0.283, 0.141, 0.458)],
  14284. [0.2, new Color(0.254, 0.265, 0.53)],
  14285. [0.3, new Color(0.207, 0.372, 0.553)],
  14286. [0.4, new Color(0.164, 0.471, 0.558)],
  14287. [0.5, new Color(0.128, 0.567, 0.551)],
  14288. [0.6, new Color(0.135, 0.659, 0.518)],
  14289. [0.7, new Color(0.267, 0.749, 0.441)],
  14290. [0.8, new Color(0.478, 0.821, 0.318)],
  14291. [0.9, new Color(0.741, 0.873, 0.15)],
  14292. [1.0, new Color(0.993, 0.906, 0.144)],
  14293. ],
  14294. INFERNO: [
  14295. [0.0, new Color(0.077, 0.042, 0.206)],
  14296. [0.1, new Color(0.225, 0.036, 0.388)],
  14297. [0.2, new Color(0.373, 0.074, 0.432)],
  14298. [0.3, new Color(0.522, 0.128, 0.42)],
  14299. [0.4, new Color(0.665, 0.182, 0.37)],
  14300. [0.5, new Color(0.797, 0.255, 0.287)],
  14301. [0.6, new Color(0.902, 0.364, 0.184)],
  14302. [0.7, new Color(0.969, 0.516, 0.063)],
  14303. [0.8, new Color(0.988, 0.683, 0.072)],
  14304. [0.9, new Color(0.961, 0.859, 0.298)],
  14305. [1.0, new Color(0.988, 0.998, 0.645)],
  14306. ],
  14307. GRAYSCALE: [
  14308. [0, new Color(0, 0, 0)],
  14309. [1, new Color(1, 1, 1)],
  14310. ],
  14311. // 16 samples of the TURBU color scheme
  14312. // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f
  14313. // original file licensed under Apache-2.0
  14314. TURBO: [
  14315. [0.0, new Color(0.18995, 0.07176, 0.23217)],
  14316. [0.07, new Color(0.25107, 0.25237, 0.63374)],
  14317. [0.13, new Color(0.27628, 0.42118, 0.89123)],
  14318. [0.2, new Color(0.25862, 0.57958, 0.99876)],
  14319. [0.27, new Color(0.15844, 0.73551, 0.92305)],
  14320. [0.33, new Color(0.09267, 0.86554, 0.7623)],
  14321. [0.4, new Color(0.19659, 0.94901, 0.59466)],
  14322. [0.47, new Color(0.42778, 0.99419, 0.38575)],
  14323. [0.53, new Color(0.64362, 0.98999, 0.23356)],
  14324. [0.6, new Color(0.80473, 0.92452, 0.20459)],
  14325. [0.67, new Color(0.93301, 0.81236, 0.22667)],
  14326. [0.73, new Color(0.99314, 0.67408, 0.20348)],
  14327. [0.8, new Color(0.9836, 0.49291, 0.12849)],
  14328. [0.87, new Color(0.92105, 0.31489, 0.05475)],
  14329. [0.93, new Color(0.81608, 0.18462, 0.01809)],
  14330. [1.0, new Color(0.66449, 0.08436, 0.00424)],
  14331. ],
  14332. RAINBOW: [
  14333. [0, new Color(0.278, 0, 0.714)],
  14334. [1 / 6, new Color(0, 0, 1)],
  14335. [2 / 6, new Color(0, 1, 1)],
  14336. [3 / 6, new Color(0, 1, 0)],
  14337. [4 / 6, new Color(1, 1, 0)],
  14338. [5 / 6, new Color(1, 0.64, 0)],
  14339. [1, new Color(1, 0, 0)],
  14340. ],
  14341. CONTOUR: [
  14342. [0.0, new Color(0, 0, 0)],
  14343. [0.03, new Color(0, 0, 0)],
  14344. [0.04, new Color(1, 1, 1)],
  14345. [1.0, new Color(1, 1, 1)],
  14346. ],
  14347. };
  14348. const PointCloudFS = `
  14349. varying vec3 vColor;
  14350. uniform float alpha;
  14351. void main() {
  14352. if (vColor == vec3(0.0, 0.0, 0.0)) {
  14353. discard;
  14354. } else {
  14355. gl_FragColor = vec4( vColor, alpha);
  14356. }
  14357. }
  14358. `;
  14359. const PointCloudVS = `
  14360. varying vec3 vColor;
  14361. uniform sampler2D gradient;
  14362. uniform sampler2D grayscale;
  14363. attribute float intensity;
  14364. attribute float classification;
  14365. uniform vec3 rootCenter;
  14366. uniform vec3 rootNormal;
  14367. uniform vec2 elevationRange;
  14368. uniform int coloring;
  14369. uniform bool hideGround;
  14370. uniform float maxIntensity;
  14371. uniform float intensityContrast;
  14372. uniform float pointSize;
  14373. #ifdef USE_COLOR
  14374. vec3 getRGB() {
  14375. vec3 rgb = color;
  14376. return rgb;
  14377. }
  14378. #endif
  14379. vec3 getElevation(){
  14380. vec4 world = modelMatrix * vec4( position, 1.0 );
  14381. float diff = abs(dot(rootNormal, (vec3(world) - rootCenter)));
  14382. float w = max(diff - elevationRange.x,0.0) / max(elevationRange.y - elevationRange.x,1.0);
  14383. vec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;
  14384. return cElevation;
  14385. }
  14386. vec3 getIntensity(){
  14387. // TODO: real contrast enhancement. Check https://github.com/yuki-koyama/enhancer/blob/master/shaders/enhancer.fs
  14388. float intmod = pow(intensity, intensityContrast);
  14389. vec3 cIntensity = texture2D(grayscale, vec2(intmod / maxIntensity ,1.0-(intmod / maxIntensity))).rgb;
  14390. return cIntensity;
  14391. }
  14392. vec3 getClassification(){
  14393. float classNormalized = classification / 255.0;
  14394. vec3 cClassification = texture2D(gradient, vec2(classNormalized * 5.0,1.0-classNormalized * 5.0)).rgb;
  14395. return cClassification;
  14396. }
  14397. vec3 getColor(){
  14398. vec3 color;
  14399. if (hideGround && classification == 2.0) {
  14400. return vec3(0.0, 0.0, 0.0);
  14401. }
  14402. if (coloring == 1) {
  14403. color = getIntensity();
  14404. }
  14405. else if (coloring == 2) {
  14406. color = getClassification();
  14407. } else if (coloring == 3) {
  14408. color = getElevation();
  14409. }
  14410. #ifdef USE_COLOR
  14411. else if (coloring == 4) {
  14412. color = getRGB();
  14413. }
  14414. #endif
  14415. else {
  14416. color = vec3(1.0, 1.0, 1.0);
  14417. }
  14418. return color;
  14419. }
  14420. void main() {
  14421. vColor = getColor();
  14422. gl_PointSize = pointSize;
  14423. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  14424. }
  14425. `;
  14426. /** Types of coloring used when viewing point cloud tiles */
  14427. var PointCloudColoring;
  14428. (function (PointCloudColoring) {
  14429. PointCloudColoring[PointCloudColoring["Intensity"] = 1] = "Intensity";
  14430. PointCloudColoring[PointCloudColoring["Classification"] = 2] = "Classification";
  14431. PointCloudColoring[PointCloudColoring["Elevation"] = 3] = "Elevation";
  14432. PointCloudColoring[PointCloudColoring["RGB"] = 4] = "RGB";
  14433. PointCloudColoring[PointCloudColoring["White"] = 5] = "White";
  14434. })(PointCloudColoring || (PointCloudColoring = {}));
  14435. /** Types of shading used when viewing b3dm (mesh) tiles */
  14436. var Shading;
  14437. (function (Shading) {
  14438. Shading[Shading["FlatTexture"] = 1] = "FlatTexture";
  14439. Shading[Shading["ShadedTexture"] = 2] = "ShadedTexture";
  14440. Shading[Shading["ShadedNoTexture"] = 3] = "ShadedNoTexture";
  14441. })(Shading || (Shading = {}));
  14442. var GeoTransform;
  14443. (function (GeoTransform) {
  14444. GeoTransform[GeoTransform["Reset"] = 1] = "Reset";
  14445. GeoTransform[GeoTransform["Mercator"] = 2] = "Mercator";
  14446. GeoTransform[GeoTransform["WGS84Cartesian"] = 3] = "WGS84Cartesian";
  14447. })(GeoTransform || (GeoTransform = {}));
  14448. const gradient = Gradients.RAINBOW;
  14449. const gradientTexture = typeof document != 'undefined' ? generateGradientTexture(gradient) : null;
  14450. const grayscale = Gradients.GRAYSCALE;
  14451. const grayscaleTexture = typeof document != 'undefined' ? generateGradientTexture(grayscale) : null;
  14452. const defaultOptions = {
  14453. throttleRequests: true,
  14454. maxRequests: 64,
  14455. updateInterval: 0.1,
  14456. maxConcurrency: 1,
  14457. maximumScreenSpaceError: 16,
  14458. maximumMemoryUsage: 32,
  14459. viewDistanceScale: 1.0,
  14460. skipLevelOfDetail: false,
  14461. updateTransforms: true,
  14462. shading: Shading.FlatTexture,
  14463. transparent: false,
  14464. pointCloudColoring: PointCloudColoring.White,
  14465. pointSize: 1.0,
  14466. worker: true,
  14467. wireframe: false,
  14468. debug: false,
  14469. basisTranscoderPath: null,
  14470. dracoDecoderPath: null,
  14471. material: null,
  14472. computeNormals: false,
  14473. shaderCallback: null,
  14474. geoTransform: GeoTransform.Reset,
  14475. preloadTilesCount: null
  14476. };
  14477. /** 3D Tiles Loader */
  14478. class Loader3DTiles {
  14479. /**
  14480. * Loads a tileset of 3D Tiles according to the given {@link LoaderProps}
  14481. * @public
  14482. *
  14483. * @param props - Properties for this load call {@link LoaderProps}.
  14484. * @returns An object containing the 3D Model to be added to the scene
  14485. * and a runtime engine to be updated every frame.
  14486. */
  14487. static load(props) {
  14488. return __awaiter(this, void 0, void 0, function* () {
  14489. const options = Object.assign(Object.assign({}, defaultOptions), props.options);
  14490. const { url } = props;
  14491. const UPDATE_INTERVAL = options.updateInterval;
  14492. const MAX_DEPTH_FOR_ORIENTATION = 5;
  14493. const loadersGLOptions = {};
  14494. if (options.cesiumIONToken) {
  14495. loadersGLOptions['cesium-ion'] = {
  14496. accessToken: options.cesiumIONToken,
  14497. };
  14498. const metadata = yield CesiumIonLoader.preload(url, loadersGLOptions);
  14499. loadersGLOptions['fetch'] = { headers: metadata.headers };
  14500. }
  14501. if (props.loadingManager) {
  14502. props.loadingManager.itemStart(url);
  14503. }
  14504. const tilesetJson = yield load(url, Tiles3DLoader, Object.assign({}, loadersGLOptions));
  14505. const renderMap = {};
  14506. const boxMap = {};
  14507. const unloadQueue = [];
  14508. const root = new Group();
  14509. const tileBoxes = new Group();
  14510. tileBoxes.matrixAutoUpdate = false//add
  14511. if (!options.debug) {
  14512. tileBoxes.visible = false;
  14513. }else{
  14514. options.parent.add(tileBoxes) //add
  14515. }
  14516. const pointcloudUniforms = {
  14517. pointSize: { type: 'f', value: options.pointSize },
  14518. gradient: { type: 't', value: gradientTexture },
  14519. grayscale: { type: 't', value: grayscaleTexture },
  14520. rootCenter: { type: 'vec3', value: new Vector3$1() },
  14521. rootNormal: { type: 'vec3', value: new Vector3$1() },
  14522. coloring: { type: 'i', value: options.pointCloudColoring },
  14523. hideGround: { type: 'b', value: true },
  14524. elevationRange: { type: 'vec2', value: new Vector2$1(0, 400) },
  14525. maxIntensity: { type: 'f', value: 1.0 },
  14526. intensityContrast: { type: 'f', value: 1.0 },
  14527. alpha: { type: 'f', value: 1.0 },
  14528. };
  14529. const pointcloudMaterial = new ShaderMaterial({
  14530. uniforms: pointcloudUniforms,
  14531. vertexShader: PointCloudVS,
  14532. fragmentShader: PointCloudFS,
  14533. transparent: options.transparent,
  14534. vertexColors: true
  14535. });
  14536. let cameraReference = null;
  14537. let rendererReference = null;
  14538. const gltfLoader = props.gltfLoader || new GLTFLoader$1(); //xzw改
  14539. let ktx2Loader = undefined;
  14540. let dracoLoader = undefined;
  14541. if (options.basisTranscoderPath) {
  14542. ktx2Loader = new KTX2Loader();
  14543. ktx2Loader.detectSupport(props.renderer);
  14544. ktx2Loader.setTranscoderPath(options.basisTranscoderPath + '/');
  14545. ktx2Loader.setWorkerLimit(1);
  14546. gltfLoader.setKTX2Loader(ktx2Loader);
  14547. }
  14548. if (options.dracoDecoderPath) {
  14549. dracoLoader = new DRACOLoader();
  14550. dracoLoader.setDecoderPath(options.dracoDecoderPath + '/');
  14551. dracoLoader.setWorkerLimit(options.maxConcurrency);
  14552. gltfLoader.setDRACOLoader(dracoLoader);
  14553. }
  14554. const unlitMaterial = new MeshBasicMaterial({ transparent: options.transparent });
  14555. const tileOptions = {
  14556. maximumMemoryUsage: options.maximumMemoryUsage,
  14557. maximumScreenSpaceError: options.maximumScreenSpaceError,
  14558. viewDistanceScale: options.viewDistanceScale,
  14559. skipLevelOfDetail: options.skipLevelOfDetail,
  14560. updateTransforms: options.updateTransforms,
  14561. throttleRequests: options.throttleRequests,
  14562. maxRequests: options.maxRequests,
  14563. updateTime: options.updateTime || 0, //add
  14564. //maxDepth: options.maxDepth || 50, // !zeg改
  14565. contentLoader: (tile) => __awaiter(this, void 0, void 0, function* () {
  14566. let tileContent = null;
  14567. switch (tile.type) {
  14568. case TILE_TYPE.POINTCLOUD: {
  14569. tileContent = createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse);
  14570. break;
  14571. }
  14572. case TILE_TYPE.SCENEGRAPH:
  14573. case TILE_TYPE.MESH: {
  14574. tileContent = yield createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse);
  14575. break;
  14576. }
  14577. }
  14578. if (tileContent) {
  14579. tileContent.visible = false;
  14580. renderMap[tile.id] = tileContent;
  14581. tileContent.name = tile.id //add
  14582. tileContent.tile = tile //add
  14583. root.add(renderMap[tile.id]);
  14584. if (options.debug) {
  14585. const box = loadersBoundingBoxToMesh(tile);
  14586. tileBoxes.add(box);
  14587. boxMap[tile.id] = box;
  14588. }
  14589. //xzw :
  14590. tileset.dispatchEvent({type:'tileLoaded',tileContent}) //每一个tile加载完要更改透明度等
  14591. }
  14592. }),
  14593. onTileLoad: (tile) => __awaiter(this, void 0, void 0, function* () {
  14594. if (tileset) {
  14595. if (!orientationDetected && (tile === null || tile === void 0 ? void 0 : tile.depth) <= MAX_DEPTH_FOR_ORIENTATION) {
  14596. detectOrientation(tile);
  14597. }
  14598. tileset._frameNumber++;
  14599. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  14600. }
  14601. }),
  14602. onTileUnload: (tile) => {
  14603. unloadQueue.push(tile);
  14604. },
  14605. onTileError: (tile, message) => {
  14606. console.error('Tile error', tile.id, message);
  14607. },
  14608. };
  14609. const tileset = new Tileset3D(tilesetJson, Object.assign(Object.assign({}, tileOptions), { loadOptions: Object.assign(Object.assign({}, loadersGLOptions), { maxConcurrency: options.maxConcurrency, worker: options.worker, gltf: {
  14610. loadImages: false,
  14611. }, '3d-tiles': {
  14612. loadGLTF: false
  14613. } }) }));
  14614. tileset.boxMap = boxMap //add
  14615. // transformations
  14616. const threeMat = new Matrix4$1();
  14617. const tileTransform = new Matrix4$1();
  14618. const rootCenter = new Vector3$1();
  14619. let orientationDetected = false;
  14620. if (tileset.root.boundingVolume) {
  14621. if (tileset.root.header.boundingVolume.region) {
  14622. // TODO: Handle region type bounding volumes
  14623. // https://github.com/visgl/loaders.gl/issues/1994
  14624. console.warn("Cannot apply a model matrix to bounding volumes of type region. Tileset stays in original geo-coordinates.");
  14625. options.geoTransform = GeoTransform.WGS84Cartesian;
  14626. }
  14627. tileTransform.setPosition(tileset.root.boundingVolume.center[0], tileset.root.boundingVolume.center[1], tileset.root.boundingVolume.center[2]);
  14628. }
  14629. else {
  14630. console.warn("Bounding volume not found, no transformations applied");
  14631. }
  14632. if (options.debug) {
  14633. const box = loadersBoundingBoxToMesh(tileset.root);
  14634. tileBoxes.add(box);
  14635. boxMap[tileset.root.id] = box;
  14636. }
  14637. let disposeFlag = false;
  14638. let loadingEnded = false;
  14639. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  14640. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).normalize());
  14641. // Extra stats
  14642. tileset.stats.get('Loader concurrency').count = options.maxConcurrency;
  14643. tileset.stats.get('Maximum SSE').count = options.maximumScreenSpaceError;
  14644. tileset.stats.get('Maximum mem usage').count = options.maximumMemoryUsage;
  14645. let timer = 0;
  14646. let lastCameraTransform = null;
  14647. let lastCameraAspect = null;
  14648. const lastCameraPosition = new Vector3$1(Infinity, Infinity, Infinity);
  14649. let sseDenominator = null;
  14650. root.updateMatrixWorld(true);
  14651. const lastRootTransform = new Matrix4$1().copy(root.matrixWorld);
  14652. const rootTransformInverse = new Matrix4$1().copy(lastRootTransform).invert();
  14653. tileset.lastRootTransform = lastRootTransform //add
  14654. detectOrientation(tileset.root);
  14655. updateResetTransform();
  14656. if (options.debug) {
  14657. boxMap[tileset.root.id].applyMatrix4(threeMat);
  14658. tileBoxes.matrixWorld.copy(root.matrixWorld);
  14659. }
  14660. if (options.geoTransform == GeoTransform.Mercator) {
  14661. const coords = datumsToSpherical(tileset.cartographicCenter[1], tileset.cartographicCenter[0]);
  14662. rootCenter.set(coords.x, 0, -coords.y);
  14663. root.position.copy(rootCenter);
  14664. root.rotation.set(-Math.PI / 2, 0, 0);
  14665. root.updateMatrixWorld(true);
  14666. }
  14667. else if (options.geoTransform == GeoTransform.WGS84Cartesian) {
  14668. root.applyMatrix4(tileTransform);
  14669. root.updateMatrixWorld(true);
  14670. rootCenter.copy(root.position);
  14671. }
  14672. function detectOrientation(tile) {
  14673. if (!tile.boundingVolume.halfAxes) {
  14674. return;
  14675. }
  14676. const halfAxes = tile.boundingVolume.halfAxes;
  14677. const orientationMatrix = new Matrix4$1()
  14678. .extractRotation(getMatrix4FromHalfAxes(halfAxes))
  14679. .premultiply(new Matrix4$1().extractRotation(rootTransformInverse));
  14680. const rotation = new Euler().setFromRotationMatrix(orientationMatrix);
  14681. if (!rotation.equals(new Euler())) {
  14682. orientationDetected = true;
  14683. const pos = new Vector3$1(tileTransform.elements[12], tileTransform.elements[13], tileTransform.elements[14]);
  14684. tileTransform.extractRotation(orientationMatrix);
  14685. tileTransform.setPosition(pos);
  14686. updateResetTransform();
  14687. }
  14688. }
  14689. function updateResetTransform() {
  14690. if (options.geoTransform != GeoTransform.WGS84Cartesian) {
  14691. // Reset the current model matrix and apply our own transformation
  14692. //threeMat.copy(tileTransform).invert();
  14693. //threeMat.premultiply(lastRootTransform); //xzw删 被下面copy这句覆盖了
  14694. let tileTransInvert = new Matrix4$1().copy(tileTransform).invert()
  14695. threeMat.copy(lastRootTransform).multiply(tileTransInvert);
  14696. tileset.modelMatrix = new Matrix4(threeMat.toArray());
  14697. //console.log('update tileset ModelMatrix', tileset.modelMatrix.elements)
  14698. tileset.tileTransInvert = tileTransInvert.toArray() // add for volumebox
  14699. }
  14700. }
  14701. // 更新瓦片显隐和瓦片迭代更新
  14702. function tilesetUpdate(tileset, renderMap, renderer, camera) {
  14703. if (disposeFlag || options.pauseTilesetUpdate) {// !zeg改 pauseTilesetUpdate
  14704. return
  14705. }
  14706. // Assumes camera fov, near and far are not changing
  14707. if (!sseDenominator || camera.aspect != lastCameraAspect) {
  14708. const loadersFrustum = new PerspectiveFrustum({
  14709. fov: (camera.fov / 180) * Math.PI,
  14710. aspectRatio: camera.aspect,
  14711. near: camera.near,
  14712. far: camera.far,
  14713. });
  14714. sseDenominator = loadersFrustum.sseDenominator;
  14715. lastCameraAspect = camera.aspect;
  14716. if(camera.aspect == 0)return//add
  14717. if (options.debug) {
  14718. console.log('Updated sse denonimator:', sseDenominator);
  14719. }
  14720. }
  14721. const frustum = getCameraFrustum(camera);
  14722. const planes = frustum.planes.map((plane) => new Plane(plane.normal.toArray(), plane.constant));
  14723. const cullingVolume = new CullingVolume(planes);
  14724. const rendererSize = new Vector2$1();
  14725. renderer.getSize(rendererSize);
  14726. const frameState = {
  14727. camera: {
  14728. position: lastCameraPosition.toArray(),
  14729. },
  14730. height: rendererSize.y,
  14731. frameNumber: tileset._frameNumber,
  14732. sseDenominator: sseDenominator,
  14733. cullingVolume: cullingVolume,
  14734. viewport: {
  14735. id: 0,
  14736. },
  14737. };
  14738. tileset._cache.reset();
  14739. tileset._traverser.traverse(tileset.root, frameState, tileset.options);
  14740. for (const tile of tileset.tiles) {
  14741. if (tile.selected) {
  14742. if (!renderMap[tile.id]) {
  14743. console.error('TILE SELECTED BUT NOT LOADED!!', tile.id);
  14744. }
  14745. else {
  14746. // Make sure it's visible
  14747. if(!renderMap[tile.id].visible){
  14748. if(viewer.visiVertexCount<maxVertexVisi){
  14749. renderMap[tile.id].visible = true;
  14750. viewer.visiVertexCount += renderMap[tile.id].vertexCount //xzw add
  14751. options.debug && (boxMap[tile.id].material.opacity = 1 , boxMap[tile.id].children[0].sprite.material.opacity = 1 )
  14752. }else{
  14753. //console.log('超出', visiVertexCount)
  14754. }
  14755. }
  14756. /* if(!renderMap[tile.id].realVisible()){
  14757. console.error('!realVisible')
  14758. } */
  14759. }
  14760. }
  14761. else {
  14762. if (renderMap[tile.id]) {
  14763. if(renderMap[tile.id].visible){
  14764. renderMap[tile.id].visible = false;
  14765. options.debug && (boxMap[tile.id].material.opacity = 0.1, boxMap[tile.id].children[0].sprite.material.opacity = 0.1)
  14766. viewer.visiVertexCount -= renderMap[tile.id].vertexCount //xzw add
  14767. }
  14768. }
  14769. }
  14770. }
  14771. while (unloadQueue.length > 0) {
  14772. const tile = unloadQueue.pop();
  14773. if (renderMap[tile.id] && tile.contentState == TILE_CONTENT_STATE.UNLOADED) {
  14774. //console.log('removevisi', renderMap[tile.id].visible) 如果是true,visiVertexCount要减
  14775. root.remove(renderMap[tile.id]);
  14776. disposeNode(renderMap[tile.id]);
  14777. delete renderMap[tile.id];
  14778. }
  14779. if (boxMap[tile.id]) {
  14780. disposeNode(boxMap[tile.id]);
  14781. tileBoxes.remove(boxMap[tile.id]);
  14782. delete boxMap[tile.id];
  14783. }
  14784. }
  14785. const tilesLoaded = tileset.stats.get('Tiles Loaded').count;
  14786. const tilesLoading = tileset.stats.get('Tiles Loading').count;
  14787. if (props.onProgress) {
  14788. props.onProgress(tilesLoaded, tilesLoaded + tilesLoading);
  14789. }
  14790. if (props.loadingManager && !loadingEnded) {
  14791. if (tilesLoading == 0 &&
  14792. (options.preloadTilesCount == null ||
  14793. tilesLoaded >= options.preloadTilesCount)) {
  14794. loadingEnded = true;
  14795. props.loadingManager.itemEnd(props.url);
  14796. }
  14797. }
  14798. return frameState;
  14799. }
  14800. return {
  14801. model: root,
  14802. runtime: {
  14803. getTileset: () => {
  14804. return tileset;
  14805. },
  14806. getStats: () => {
  14807. return tileset.stats;
  14808. },
  14809. showTiles: (visible) => {
  14810. tileBoxes.visible = visible;
  14811. },
  14812. setWireframe: (wireframe) => {
  14813. options.wireframe = wireframe;
  14814. root.traverse((object) => {
  14815. if (object instanceof Mesh) {
  14816. object.material.wireframe = wireframe;
  14817. }
  14818. });
  14819. },
  14820. setDebug: (debug) => {
  14821. options.debug = debug;
  14822. tileBoxes.visible = debug;
  14823. },
  14824. setShading: (shading) => {
  14825. options.shading = shading;
  14826. },
  14827. getTileBoxes: () => {
  14828. return tileBoxes;
  14829. },
  14830. setViewDistanceScale: (scale) => {
  14831. tileset.options.viewDistanceScale = scale;
  14832. tileset._frameNumber++;
  14833. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  14834. },
  14835. setHideGround: (enabled) => {
  14836. pointcloudUniforms.hideGround.value = enabled;
  14837. },
  14838. setPointCloudColoring: (selection) => {
  14839. pointcloudUniforms.coloring.value = selection;
  14840. },
  14841. setElevationRange: (range) => {
  14842. pointcloudUniforms.elevationRange.value.set(range[0], range[1]);
  14843. },
  14844. setMaxIntensity: (intensity) => {
  14845. pointcloudUniforms.maxIntensity.value = intensity;
  14846. },
  14847. setIntensityContrast: (contrast) => {
  14848. pointcloudUniforms.intensityContrast.value = contrast;
  14849. },
  14850. setPointAlpha: (alpha) => {
  14851. pointcloudUniforms.alpha.value = alpha;
  14852. },
  14853. getLatLongHeightFromPosition: (position) => {
  14854. const cartographicPosition = tileset.ellipsoid.cartesianToCartographic(new Vector3$1().copy(position).applyMatrix4(new Matrix4$1().copy(threeMat).invert()).toArray());
  14855. return {
  14856. lat: cartographicPosition[1],
  14857. long: cartographicPosition[0],
  14858. height: cartographicPosition[2],
  14859. };
  14860. },
  14861. getPositionFromLatLongHeight: (coord) => {
  14862. const cartesianPosition = tileset.ellipsoid.cartographicToCartesian([coord.long, coord.lat, coord.height]);
  14863. return new Vector3$1(...cartesianPosition).applyMatrix4(threeMat);
  14864. },
  14865. getCameraFrustum: (camera) => {
  14866. const frustum = getCameraFrustum(camera);
  14867. const meshes = frustum.planes
  14868. .map((plane) => new Plane(plane.normal.toArray(), plane.constant))
  14869. .map((loadersPlane) => loadersPlaneToMesh(loadersPlane));
  14870. const model = new Group();
  14871. for (const mesh of meshes)
  14872. model.add(mesh);
  14873. return model;
  14874. },
  14875. update: function (dt, renderer, camera, ifForce) {
  14876. cameraReference = camera;
  14877. rendererReference = renderer;
  14878. timer += dt;
  14879. if(!ifForce) ifForce = tileset.nextForceUpdate
  14880. tileset.nextForceUpdate = false
  14881. if(tileset.needRenderNext){//必须在下一帧渲染刷新否则无法显示
  14882. viewer.dispatchEvent('content_changed')
  14883. }
  14884. tileset.needRenderNext = ifForce
  14885. if (tileset && (timer >= UPDATE_INTERVAL || ifForce)) {
  14886. if (!lastRootTransform.equals(root.matrixWorld)) {
  14887. timer = 0;
  14888. lastRootTransform.copy(root.matrixWorld);
  14889. updateResetTransform();
  14890. const rootCenter = new Vector3$1().setFromMatrixPosition(lastRootTransform);
  14891. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  14892. pointcloudUniforms.rootNormal.value.copy(new Vector3$1(0, 0, 1).applyMatrix4(lastRootTransform).normalize());
  14893. rootTransformInverse.copy(lastRootTransform).invert();
  14894. if (options.debug) {
  14895. /* console.log('move', tileset.root.id, boxMap[tileset.root.id].matrix.elements, boxMap[tileset.root.id].matrixWorld.elements)
  14896. boxMap[tileset.root.id].matrix.copy(root.matrixWorld);
  14897. boxMap[tileset.root.id].matrixWorld.copy(root.matrixWorld); */
  14898. //boxMap[tileset.root.id].applyMatrix4(threeMat);
  14899. tileBoxes.matrix.copy(root.matrixWorld);
  14900. //boxMap[tileset.root.id].matrixWorld.copy(threeMat);
  14901. //boxMap[tileset.root.id].applyMatrix4(lastRootTransform);//boxMap[tileset.root.id].applyMatrix4(lastRootTransform);
  14902. //boxMap[tileset.root.id].updateWorldMatrix()
  14903. }
  14904. }
  14905. if (this.lastCameraTransform == null) {
  14906. this.lastCameraTransform = new Matrix4$1().copy(camera.matrixWorld);
  14907. }
  14908. else {
  14909. const cameraChanged = !camera.matrixWorld.equals(this.lastCameraTransform) ||
  14910. !(camera.aspect == lastCameraAspect);
  14911. if (cameraChanged || ifForce) {
  14912. timer = 0;
  14913. tileset._frameNumber++;
  14914. camera.getWorldPosition(lastCameraPosition);
  14915. this.lastCameraTransform.copy(camera.matrixWorld);
  14916. tilesetUpdate(tileset, renderMap, renderer, camera);
  14917. }
  14918. }
  14919. }/* else{
  14920. console.log('11')
  14921. } */
  14922. },
  14923. dispose: function () {
  14924. disposeFlag = true;
  14925. tileset._destroy();
  14926. while (root.children.length > 0) {
  14927. const obj = root.children[0];
  14928. disposeNode(obj);
  14929. root.remove(obj);
  14930. }
  14931. while (tileBoxes.children.length > 0) {
  14932. const obj = tileBoxes.children[0];
  14933. tileBoxes.remove(obj);
  14934. obj.geometry.dispose();
  14935. obj.material.dispose();
  14936. }
  14937. if (ktx2Loader) {
  14938. ktx2Loader.dispose();
  14939. }
  14940. if (dracoLoader) {
  14941. dracoLoader.dispose();
  14942. }
  14943. },
  14944. limit2lowestDepth: isLowest => {//zeg add 设置是否限制为最低精度tile深度
  14945. maxDepth = isLowest ? 1 : 100 //影响到shouldRefine, 检查方法:可以看到当maxDepth降低了之后viewer.objs.children[0].runtime.getTileset().tiles.filter(e=> e.tileContent.visible)变少
  14946. if (cameraReference) {
  14947. tileset._frameNumber++
  14948. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference)
  14949. }
  14950. },
  14951. },
  14952. };
  14953. });
  14954. }
  14955. }
  14956. function createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse) {
  14957. return __awaiter(this, void 0, void 0, function* () {
  14958. return new Promise((resolve, reject) => {
  14959. var _a;
  14960. const rotateX = new Matrix4$1().makeRotationAxis(new Vector3$1(1, 0, 0), Math.PI / 2);
  14961. const shouldRotate = ((_a = tile.tileset.asset) === null || _a === void 0 ? void 0 : _a.gltfUpAxis) !== "Z";
  14962. // The computed trasnform already contains the root's transform, so we have to invert it
  14963. //const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(tileMatrix)//.premultiply(rootTransformInverse); //xzw 删。原先的会造成移动后tiles错乱
  14964. //const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(tile.tileset.modelMatrix).premultiply(rootTransformInverse)
  14965. // 这句同tile.computedTransform左乘tileTransform。 因为tileTransform拿不到所以使用modelMatrix。modelMatrix为tileTransform左乘rootTransform, 所以再左乘rootTransformInverse
  14966. //改动:contentTransform中的computedTransform 去掉左乘 root.modelMatrixWorld , 因为移动过后这个computedTransform没更新
  14967. gltfLoader.parse(
  14968. tile.content.type == 'glTF' ? tile.content.gltf.gltfArrayBuffer : tile.content.gltfArrayBuffer,//tile.content.gltfArrayBuffer,
  14969. tile.contentUrl ? tile.contentUrl.substr(0, tile.contentUrl.lastIndexOf('/') + 1) : '',
  14970. (gltf) => {
  14971. const tileContent = gltf.scenes[0];
  14972. tileContent.vertexCount = 0 //xzw add
  14973. tile.tileContent = tileContent //xzw add
  14974. let needUpdate
  14975. if(tile.rtcCenterState != !!tile.content.rtcCenter){ // 等mesh加载好才知道rtcCenter,每个mesh坐标都不一样
  14976. needUpdate = true
  14977. //console.error('rtcCenter有变化?!')
  14978. }
  14979. tile.rtcCenterState = rtcCenterGlobal = !!tile.content.rtcCenter
  14980. let contentTransform = tile.getContentTransform(needUpdate)
  14981. if(tile.content.rtcCenter){//大部分模型无 rtcCenter
  14982. //console.error('rtcCenter有?!') //似乎bounding中包含这个信息了 所以getContentTransform不含这个
  14983. let tranM = new Matrix4$1()
  14984. tranM.makeTranslation(tile.content.rtcCenter[0], tile.content.rtcCenter[1], tile.content.rtcCenter[2])
  14985. contentTransform.premultiply(tranM)
  14986. }
  14987. if(needUpdate ){
  14988. tile._updateBoundingVolume(tile.header) //add 重新更新
  14989. }
  14990. if (shouldRotate) { //大部分模型 无需 Rotate
  14991. contentTransform.multiply(rotateX); // convert from GLTF Y-up to Z-up
  14992. }
  14993. tileContent.applyMatrix4(contentTransform);
  14994. //'https://testgis.4dage.com/LVBADUI_qp/tileset.json', //村庄 这个案例是 要rotateX 且有rtcCenter的。boundingVolume已经是转换这两者后的值所以getContentTransform不加这个
  14995. //tile总共要左乘的矩阵 rotateX -> tileTransInvert * computedTransform -> 对geometry的tranM修改 -> 整个模型的matrixWorld
  14996. tileContent.traverse((object) => {
  14997. if (object.type == "Mesh") {
  14998. const mesh = object;
  14999. //mesh.tileId = tile.id//add
  15000. const originalMaterial = mesh.material;
  15001. const originalMap = originalMaterial.map;
  15002. if (options.material) {
  15003. mesh.material = options.material.clone();
  15004. originalMaterial.dispose();
  15005. }
  15006. else if (options.shading == Shading.FlatTexture) {
  15007. mesh.material = unlitMaterial.clone();
  15008. originalMaterial.dispose();
  15009. }
  15010. if (options.shading != Shading.ShadedNoTexture) {
  15011. if (mesh.material.type == "ShaderMaterial" && !(mesh.material instanceof MeshBasicMaterial)) {//改
  15012. mesh.material.uniforms.map = { value: originalMap };
  15013. }
  15014. else {
  15015. mesh.material.map = originalMap;
  15016. }
  15017. }
  15018. else {
  15019. if (originalMap) {
  15020. originalMap.dispose();
  15021. }
  15022. mesh.material.map = null;
  15023. }
  15024. if (options.shaderCallback) {
  15025. mesh.onBeforeRender = options.shaderCallback;
  15026. }
  15027. mesh.material.wireframe = options.wireframe;
  15028. if (options.computeNormals) {
  15029. mesh.geometry.computeVertexNormals();
  15030. }
  15031. //xzw add:
  15032. tileContent.vertexCount += mesh.geometry.attributes.position.count
  15033. //------------------add on 2023.1.16----zeg
  15034. //mesh.geometry.applyMatrix4(contentTransform)
  15035. /* if (tile.content.rtcCenter) {
  15036. // 有些b3dm模型会将坐标写在源码的rtcCenter里 如https://testgis.4dage.com/LVBADUI_qp/tileset.json
  15037. mesh.geometry.translate(tile.content.rtcCenter[0], tile.content.rtcCenter[1], tile.content.rtcCenter[2])
  15038. } else {
  15039. mesh.geometry.scale(1, 1, -1) // 调整缩放,对应box也要进行变换(scaleZ对应box[2])
  15040. } */
  15041. //---------------------
  15042. }
  15043. });
  15044. resolve(tileContent);
  15045. },
  15046. (e) => {
  15047. reject(new Error(`error parsing gltf in tile ${tile.id}: ${e}`));
  15048. }
  15049. );
  15050. });
  15051. });
  15052. }
  15053. function createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse) {
  15054. const d = {
  15055. rtc_center: tile.content.rtcCenter,
  15056. points: tile.content.attributes.positions,
  15057. intensities: tile.content.attributes.intensity,
  15058. classifications: tile.content.attributes.classification,
  15059. rgb: null,
  15060. rgba: null,
  15061. };
  15062. const { colors } = tile.content.attributes;
  15063. if (colors && colors.size === 3) {
  15064. d.rgb = colors.value;
  15065. }
  15066. if (colors && colors.size === 4) {
  15067. d.rgba = colors.value;
  15068. }
  15069. const geometry = new BufferGeometry();
  15070. geometry.setAttribute('position', new Float32BufferAttribute(d.points, 3));
  15071. const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(rootTransformInverse);
  15072. if (d.rgba) {
  15073. geometry.setAttribute('color', new Float32BufferAttribute(d.rgba, 4));
  15074. }
  15075. else if (d.rgb) {
  15076. geometry.setAttribute('color', new Uint8BufferAttribute(d.rgb, 3, true));
  15077. }
  15078. if (d.intensities) {
  15079. geometry.setAttribute('intensity',
  15080. // Handles both 16bit or 8bit intensity values
  15081. new BufferAttribute(d.intensities, 1, true));
  15082. }
  15083. if (d.classifications) {
  15084. geometry.setAttribute('classification', new Uint8BufferAttribute(d.classifications, 1, false));
  15085. }
  15086. const tileContent = new Points(geometry, options.material || pointcloudMaterial);
  15087. if (d.rtc_center) {
  15088. const c = d.rtc_center;
  15089. contentTransform.multiply(new Matrix4$1().makeTranslation(c[0], c[1], c[2]));
  15090. }
  15091. tileContent.applyMatrix4(contentTransform);
  15092. return tileContent;
  15093. }
  15094. function disposeMaterial(material) {
  15095. var _a, _b, _c, _d;
  15096. if ((_a = material === null || material === void 0 ? void 0 : material.uniforms) === null || _a === void 0 ? void 0 : _a.map) {
  15097. (_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();
  15098. }
  15099. else if (material.map) {
  15100. (_d = material.map) === null || _d === void 0 ? void 0 : _d.dispose();
  15101. }
  15102. material.dispose();
  15103. }
  15104. function disposeNode(node) {
  15105. node.traverse((object) => {
  15106. if (object.isMesh) {
  15107. object.geometry.dispose();
  15108. if (object.material.isMaterial) {
  15109. disposeMaterial(object.material);
  15110. }
  15111. else {
  15112. // an array of materials
  15113. for (const material of object.material) {
  15114. disposeMaterial(material);
  15115. }
  15116. }
  15117. }
  15118. });
  15119. for (let i = node.children.length - 1; i >= 0; i--) {
  15120. const obj = node.children[i];
  15121. node.remove(obj);
  15122. }
  15123. }
  15124. export { GeoTransform, Loader3DTiles, PointCloudColoring, Shading };
  15125. //# sourceMappingURL=three-loader-3dtiles.esm.js.map
  15126. /*
  15127. 关键搜寻:
  15128. Loader3DTiles : const tileset = new Tileset3D
  15129. tileset.dispatchEvent({type:'tileLoaded',tileContent})
  15130. createGLTFNodes(gltfLoader 创建tile
  15131. executeTraversal(root, frameState) 遍历root
  15132. lastRootTransform rootTransformInverse
  15133. tileset._loadTiles 依次加载tiles
  15134. _getPriority 加载优先级 加了一句
  15135. 笔记:
  15136. 主要类:
  15137. class tileset3D 最外层整体。 获取方法: viewer.objs.children[index].runtime.getTileset()。 .tiles包含所有tiles
  15138. class tileHeader 也就是tileset里面的一个个tile 。 其上有.tileset
  15139. tileset里算的tileTransform之后是不会改变的, tile.transform也是,是json里的。
  15140. tileset.modelMatrix (通常这个值很大) 会随着位移改变
  15141. tile.computedTransform 被我修改了,之前左乘了tileset.modelMatrix,现只包含了transform信息 _updateTransform(parentTransfor 其中有_updateBoundingVolume,这个影响可见性, 在computeVisibilityWithPlaneMask中计算
  15142. tileset._cache.trim(), 然后再update //可以将所有不可见的tiles dispose
  15143. 相机靠近容易缺块的bug暂时修改如下: _visible是由computeVisibilityWithPlaneMask计算得
  15144. get isVisibleAndInRequestVolume() {
  15145. return this._inRequestVolume; //去掉了_visible ||
  15146. }
  15147. 显示所有tile似乎也不会卡顿. 但好像影响了加载顺序从而变慢了。visiVertexCount过量。 怀疑应该还是文件的bound有问题。
  15148. 原本会消失的地方虽然不会消失了但一直是模糊的
  15149. =========
  15150. 访问所有tile:
  15151. viewer.objs.children[0].runtime.getTileset().tiles
  15152. 它的mesh: tile.tileContent
  15153. 或者直接得到所有mesh: viewer.objs.children[0].children
  15154. tile.depth最低为1 , root是0
  15155. */