@loaders.gl/tiles
Version:
Common components for different tiles loaders.
4 lines • 184 kB
Source Map (JSON)
{
"version": 3,
"sources": ["../src/index.ts", "../src/tileset/tileset-3d.ts", "../src/utils/doubly-linked-list-node.ts", "../src/utils/doubly-linked-list.ts", "../src/tileset/tileset-cache.ts", "../src/tileset/helpers/transform-utils.ts", "../src/tileset/helpers/frame-state.ts", "../src/tileset/helpers/zoom.ts", "../src/tileset/tile-3d.ts", "../src/constants.ts", "../src/tileset/helpers/bounding-volume.ts", "../src/tileset/helpers/tiles-3d-lod.ts", "../src/tileset/helpers/i3s-lod.ts", "../src/tileset/helpers/3d-tiles-options.ts", "../src/utils/managed-array.ts", "../src/tileset/tileset-traverser.ts", "../src/tileset/format-3d-tiles/tileset-3d-traverser.ts", "../src/tileset/format-i3s/i3s-tileset-traverser.ts", "../src/tileset/format-i3s/i3s-pending-tiles-register.ts", "../src/tileset/format-i3s/i3s-tile-manager.ts"],
"sourcesContent": ["// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport type {Tileset3DProps} from './tileset/tileset-3d';\nexport {Tileset3D} from './tileset/tileset-3d';\nexport {Tile3D} from './tileset/tile-3d';\n\nexport {TilesetTraverser} from './tileset/tileset-traverser';\nexport {TilesetCache} from './tileset/tileset-cache';\n\nexport {createBoundingVolume} from './tileset/helpers/bounding-volume';\nexport {calculateTransformProps} from './tileset/helpers/transform-utils';\n\nexport {getFrameState} from './tileset/helpers/frame-state';\nexport {getLodStatus} from './tileset/helpers/i3s-lod';\n\nexport {\n TILE_CONTENT_STATE,\n TILE_REFINEMENT,\n TILE_TYPE,\n TILESET_TYPE,\n LOD_METRIC_TYPE\n} from './constants';\n", "// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// This file is derived from the Cesium code base under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\nimport {Matrix4, Vector3} from '@math.gl/core';\nimport {Ellipsoid} from '@math.gl/geospatial';\nimport {Stats} from '@probe.gl/stats';\nimport {RequestScheduler, path, LoaderWithParser, LoaderOptions} from '@loaders.gl/loader-utils';\nimport {TilesetCache} from './tileset-cache';\nimport {calculateTransformProps} from './helpers/transform-utils';\nimport {FrameState, getFrameState, limitSelectedTiles} from './helpers/frame-state';\nimport {getZoomFromBoundingVolume, getZoomFromExtent, getZoomFromFullExtent} from './helpers/zoom';\n\nimport type {GeospatialViewport, Viewport} from '../types';\nimport {Tile3D} from './tile-3d';\nimport {TILESET_TYPE} from '../constants';\n\nimport {TilesetTraverser} from './tileset-traverser';\n\n// TODO - these should be moved into their respective modules\nimport {Tileset3DTraverser} from './format-3d-tiles/tileset-3d-traverser';\nimport {I3STilesetTraverser} from './format-i3s/i3s-tileset-traverser';\n\nexport type TilesetJSON = any;\n\n/*\nexport type TilesetJSON = {\n loader;\n // could be 3d tiles, i3s\n type: 'I3S' | '3DTILES';\n /** The url to the top level tileset JSON file. *\n url: string;\n basePath?: string;\n // Geometric error when the tree is not rendered at all\n lodMetricType: string;\n lodMetricValue: number;\n root: {\n refine: string;\n [key: string]: unknown;\n },\n [key: string]: unknown;\n};\n*/\n\nexport type Tileset3DProps = {\n // loading\n throttleRequests?: boolean;\n maxRequests?: number;\n loadOptions?: LoaderOptions;\n loadTiles?: boolean;\n basePath?: string;\n maximumMemoryUsage?: number;\n memoryCacheOverflow?: number;\n maximumTilesSelected?: number;\n debounceTime?: number;\n\n // Metadata\n description?: string;\n attributions?: string[];\n\n // Transforms\n ellipsoid?: object;\n modelMatrix?: Matrix4;\n\n // Traversal\n maximumScreenSpaceError?: number;\n memoryAdjustedScreenSpaceError?: boolean;\n viewportTraversersMap?: any;\n updateTransforms?: boolean;\n viewDistanceScale?: number;\n\n // Callbacks\n onTileLoad?: (tile: Tile3D) => any;\n onTileUnload?: (tile: Tile3D) => any;\n onTileError?: (tile: Tile3D, message: string, url: string) => any;\n contentLoader?: (tile: Tile3D) => Promise<void>;\n onTraversalComplete?: (selectedTiles: Tile3D[]) => Tile3D[];\n onUpdate?: () => void;\n};\n\ntype Props = {\n description: string;\n ellipsoid: object;\n /** A 4x4 transformation matrix this transforms the entire tileset. */\n modelMatrix: Matrix4;\n /** Set to false to disable network request throttling */\n throttleRequests: boolean;\n /** Number of simultaneous requsts, if throttleRequests is true */\n maxRequests: number;\n /* Maximum amount of GPU memory (in MB) that may be used to cache tiles. */\n maximumMemoryUsage: number;\n /* The maximum additional memory (in MB) to allow for cache headroom before adjusting the screen spacer error */\n memoryCacheOverflow: number;\n /** Maximum number limit of tiles selected for show. 0 means no limit */\n maximumTilesSelected: number;\n /** Delay time before the tileset traversal. It prevents traversal requests spam.*/\n debounceTime: number;\n /** Callback. Indicates this a tile's content was loaded */\n onTileLoad: (tile: Tile3D) => void;\n /** Callback. Indicates this a tile's content was unloaded (cache full) */\n onTileUnload: (tile: Tile3D) => void;\n /** Callback. Indicates this a tile's content failed to load */\n onTileError: (tile: Tile3D, message: string, url: string) => void;\n /** Callback. Allows post-process selectedTiles right after traversal. */\n onTraversalComplete: (selectedTiles: Tile3D[]) => Tile3D[];\n /** Callback. Called when the set of selected tiles changes. */\n onUpdate: () => void;\n /** The maximum screen space error used to drive level of detail refinement. */\n maximumScreenSpaceError: number;\n /** Whether to adjust the maximum screen space error to comply with the maximum memory limitation */\n memoryAdjustedScreenSpaceError: boolean;\n viewportTraversersMap: Record<string, any> | null;\n attributions: string[];\n loadTiles: boolean;\n loadOptions: LoaderOptions;\n updateTransforms: boolean;\n /** View distance scale modifier */\n viewDistanceScale: number;\n basePath: string;\n /** Optional async tile content loader */\n contentLoader?: (tile: Tile3D) => Promise<void>;\n /** @todo I3S specific knowledge should be moved to I3S module */\n i3s: Record<string, any>;\n};\n\nconst DEFAULT_PROPS: Props = {\n description: '',\n ellipsoid: Ellipsoid.WGS84,\n modelMatrix: new Matrix4(),\n throttleRequests: true,\n maxRequests: 64,\n /** Default memory values optimized for viewing mesh-based 3D Tiles on both mobile and desktop devices */\n maximumMemoryUsage: 32,\n memoryCacheOverflow: 1,\n maximumTilesSelected: 0,\n debounceTime: 0,\n onTileLoad: () => {},\n onTileUnload: () => {},\n onTileError: () => {},\n onTraversalComplete: (selectedTiles: Tile3D[]) => selectedTiles,\n onUpdate: () => {},\n contentLoader: undefined,\n viewDistanceScale: 1.0,\n maximumScreenSpaceError: 8,\n memoryAdjustedScreenSpaceError: false,\n loadTiles: true,\n updateTransforms: true,\n viewportTraversersMap: null,\n loadOptions: {fetch: {}},\n attributions: [],\n basePath: '',\n i3s: {}\n};\n\n// Tracked Stats\nconst TILES_TOTAL = 'Tiles In Tileset(s)';\nconst TILES_IN_MEMORY = 'Tiles In Memory';\nconst TILES_IN_VIEW = 'Tiles In View';\nconst TILES_RENDERABLE = 'Tiles To Render';\nconst TILES_LOADED = 'Tiles Loaded';\nconst TILES_LOADING = 'Tiles Loading';\nconst TILES_UNLOADED = 'Tiles Unloaded';\nconst TILES_LOAD_FAILED = 'Failed Tile Loads';\nconst POINTS_COUNT = 'Points/Vertices';\nconst TILES_GPU_MEMORY = 'Tile Memory Use';\nconst MAXIMUM_SSE = 'Maximum Screen Space Error';\n\n/**\n * The Tileset loading and rendering flow is as below,\n * A rendered (i.e. deck.gl `Tile3DLayer`) triggers `tileset.update()` after a `tileset` is loaded\n * `tileset` starts traversing the tile tree and update `requestTiles` (tiles of which content need\n * to be fetched) and `selectedTiles` (tiles ready for rendering under the current viewport).\n * `Tile3DLayer` will update rendering based on `selectedTiles`.\n * `Tile3DLayer` also listens to `onTileLoad` callback and trigger another round of `update and then traversal`\n * when new tiles are loaded.\n\n * As I3S tileset have stored `tileHeader` file (metadata) and tile content files (geometry, texture, ...) separately.\n * During each traversal, it issues `tilHeader` requests if that `tileHeader` is not yet fetched,\n * after the tile header is fulfilled, it will resume the traversal starting from the tile just fetched (not root).\n\n * Tile3DLayer\n * |\n * await load(tileset)\n * |\n * tileset.update()\n * | async load tileHeader\n * tileset.traverse() -------------------------- Queued\n * | resume traversal after fetched |\n * |----------------------------------------|\n * |\n * | async load tile content\n * tilset.requestedTiles ----------------------------- RequestScheduler\n * |\n * tilset.selectedTiles (ready for rendering) |\n * | Listen to |\n * Tile3DLayer ----------- onTileLoad ----------------------|\n * | | notify new tile is available\n * updateLayers |\n * tileset.update // trigger another round of update\n*/\nexport class Tileset3D {\n // props: Tileset3DProps;\n options: Props;\n loadOptions: LoaderOptions;\n\n type: TILESET_TYPE;\n tileset: TilesetJSON;\n loader: LoaderWithParser;\n url: string;\n basePath: string;\n modelMatrix: Matrix4;\n ellipsoid: any;\n lodMetricType: string;\n lodMetricValue: number;\n refine: string;\n root: Tile3D | null = null;\n roots: Record<string, Tile3D> = {};\n /** @todo any->unknown */\n asset: Record<string, any> = {};\n\n // Metadata for the entire tileset\n description: string = '';\n properties: any;\n\n extras: any = null;\n attributions: any = {};\n credits: any = {};\n\n stats: Stats;\n\n /** flags that contain information about data types in nested tiles */\n contentFormats = {draco: false, meshopt: false, dds: false, ktx2: false};\n\n // view props\n cartographicCenter: Vector3 | null = null;\n cartesianCenter: Vector3 | null = null;\n zoom: number = 1;\n boundingVolume: any = null;\n\n /** Updated based on the camera position and direction */\n dynamicScreenSpaceErrorComputedDensity: number = 0.0;\n\n // METRICS\n\n /**\n * The maximum amount of GPU memory (in MB) that may be used to cache tiles\n * Tiles not in view are unloaded to enforce private\n */\n maximumMemoryUsage: number = 32;\n\n /** The total amount of GPU memory in bytes used by the tileset. */\n gpuMemoryUsageInBytes: number = 0;\n\n /**\n * If loading the level of detail required by maximumScreenSpaceError\n * results in the memory usage exceeding maximumMemoryUsage (GPU), level of detail refinement\n * will instead use this (larger) adjusted screen space error to achieve the\n * best possible visual quality within the available memory.\n */\n memoryAdjustedScreenSpaceError: number = 0.0;\n\n private _cacheBytes: number = 0;\n private _cacheOverflowBytes: number = 0;\n\n /** Update tracker. increase in each update cycle. */\n _frameNumber: number = 0;\n private _queryParams: Record<string, string> = {};\n private _extensionsUsed: string[] = [];\n private _tiles: Record<string, Tile3D> = {};\n\n /** counter for tracking tiles requests */\n private _pendingCount: number = 0;\n\n /** Hold traversal results */\n selectedTiles: Tile3D[] = [];\n\n // TRAVERSAL\n traverseCounter: number = 0;\n geometricError: number = 0;\n private lastUpdatedVieports: Viewport[] | Viewport | null = null;\n private _requestedTiles: Tile3D[] = [];\n private _emptyTiles: Tile3D[] = [];\n private frameStateData: any = {};\n\n _traverser: TilesetTraverser;\n _cache = new TilesetCache();\n _requestScheduler: RequestScheduler;\n\n /** Tile IDs held visible during transitions until replacements have drawn */\n private _heldTiles: Set<string> = new Set();\n\n // Promise tracking\n private updatePromise: Promise<number> | null = null;\n tilesetInitializationPromise: Promise<void>;\n\n /**\n * Create a new Tileset3D\n * @param json\n * @param props\n */\n // eslint-disable-next-line max-statements\n constructor(tileset: TilesetJSON, options?: Tileset3DProps) {\n // PUBLIC MEMBERS\n this.options = {...DEFAULT_PROPS, ...options};\n // raw data\n this.tileset = tileset;\n this.loader = tileset.loader;\n // could be 3d tiles, i3s\n this.type = tileset.type;\n // The url to a tileset JSON file.\n this.url = tileset.url;\n this.basePath = tileset.basePath || path.dirname(this.url);\n this.modelMatrix = this.options.modelMatrix;\n this.ellipsoid = this.options.ellipsoid;\n\n // Geometric error when the tree is not rendered at all\n this.lodMetricType = tileset.lodMetricType;\n this.lodMetricValue = tileset.lodMetricValue;\n this.refine = tileset.root.refine;\n\n this.loadOptions = this.options.loadOptions || {};\n\n // TRAVERSAL\n this._traverser = this._initializeTraverser();\n this._requestScheduler = new RequestScheduler({\n throttleRequests: this.options.throttleRequests,\n maxRequests: this.options.maxRequests\n });\n\n this.memoryAdjustedScreenSpaceError = this.options.maximumScreenSpaceError;\n this._cacheBytes = this.options.maximumMemoryUsage * 1024 * 1024;\n this._cacheOverflowBytes = this.options.memoryCacheOverflow * 1024 * 1024;\n\n // METRICS\n // The total amount of GPU memory in bytes used by the tileset.\n this.stats = new Stats({id: this.url});\n this._initializeStats();\n\n this.tilesetInitializationPromise = this._initializeTileSet(tileset);\n }\n\n /** Release resources */\n destroy(): void {\n this._destroy();\n }\n\n /** Is the tileset loaded (update needs to have been called at least once) */\n isLoaded(): boolean {\n // Check that `_frameNumber !== 0` which means that update was called at least once\n return this._pendingCount === 0 && this._frameNumber !== 0 && this._requestedTiles.length === 0;\n }\n\n get tiles(): object[] {\n return Object.values(this._tiles);\n }\n\n get frameNumber(): number {\n return this._frameNumber;\n }\n\n get queryParams(): string {\n return new URLSearchParams(this._queryParams).toString();\n }\n\n setProps(props: Tileset3DProps): void {\n this.options = {...this.options, ...props};\n }\n\n /** @deprecated */\n // setOptions(options: Tileset3DProps): void {\n // this.options = {...this.options, ...options};\n // }\n\n /**\n * Return a loadable tile url for a specific tile subpath\n * @param tilePath a tile subpath\n */\n getTileUrl(tilePath: string): string {\n const isDataUrl = tilePath.startsWith('data:');\n if (isDataUrl) {\n return tilePath;\n }\n\n let tileUrl = tilePath;\n if (this.queryParams.length) {\n tileUrl = `${tilePath}${tilePath.includes('?') ? '&' : '?'}${this.queryParams}`;\n }\n return tileUrl;\n }\n\n // TODO CESIUM specific\n hasExtension(extensionName: string): boolean {\n return Boolean(this._extensionsUsed.indexOf(extensionName) > -1);\n }\n\n /**\n * Update visible tiles relying on a list of viewports\n * @param viewports - list of viewports\n * @deprecated\n */\n update(viewports: Viewport[] | Viewport | null = null) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.tilesetInitializationPromise.then(() => {\n if (!viewports && this.lastUpdatedVieports) {\n viewports = this.lastUpdatedVieports;\n } else {\n this.lastUpdatedVieports = viewports;\n }\n if (viewports) {\n this.doUpdate(viewports);\n }\n });\n }\n\n /**\n * Update visible tiles relying on a list of viewports.\n * Do it with debounce delay to prevent update spam\n * @param viewports viewports\n * @returns Promise of new frameNumber\n */\n async selectTiles(viewports: Viewport[] | Viewport | null = null): Promise<number> {\n await this.tilesetInitializationPromise;\n if (viewports) {\n this.lastUpdatedVieports = viewports;\n }\n if (!this.updatePromise) {\n this.updatePromise = new Promise<number>((resolve) => {\n setTimeout(() => {\n if (this.lastUpdatedVieports) {\n this.doUpdate(this.lastUpdatedVieports);\n }\n resolve(this._frameNumber);\n this.updatePromise = null;\n }, this.options.debounceTime);\n });\n }\n return this.updatePromise;\n }\n\n adjustScreenSpaceError(): void {\n if (this.gpuMemoryUsageInBytes < this._cacheBytes) {\n this.memoryAdjustedScreenSpaceError = Math.max(\n this.memoryAdjustedScreenSpaceError / 1.02,\n this.options.maximumScreenSpaceError\n );\n } else if (this.gpuMemoryUsageInBytes > this._cacheBytes + this._cacheOverflowBytes) {\n this.memoryAdjustedScreenSpaceError *= 1.02;\n }\n }\n /**\n * Update visible tiles relying on a list of viewports\n * @param viewports viewports\n */\n // eslint-disable-next-line max-statements, complexity\n private doUpdate(viewports: Viewport[] | Viewport): void {\n if ('loadTiles' in this.options && !this.options.loadTiles) {\n return;\n }\n if (this.traverseCounter > 0) {\n return;\n }\n const preparedViewports = viewports instanceof Array ? viewports : [viewports];\n\n this._cache.reset();\n this._frameNumber++;\n this.traverseCounter = preparedViewports.length;\n const viewportsToTraverse: string[] = [];\n // First loop to decrement traverseCounter\n for (const viewport of preparedViewports) {\n const id = viewport.id;\n if (this._needTraverse(id)) {\n viewportsToTraverse.push(id);\n } else {\n this.traverseCounter--;\n }\n }\n\n // Second loop to traverse\n for (const viewport of preparedViewports) {\n const id = viewport.id;\n if (!this.roots[id]) {\n this.roots[id] = this._initializeTileHeaders(this.tileset, null);\n }\n\n if (!viewportsToTraverse.includes(id)) {\n continue; // eslint-disable-line no-continue\n }\n const frameState = getFrameState(viewport as GeospatialViewport, this._frameNumber);\n this._traverser.traverse(this.roots[id], frameState, this.options);\n }\n }\n\n /**\n * Check if traversal is needed for particular viewport\n * @param {string} viewportId - id of a viewport\n * @return {boolean}\n */\n _needTraverse(viewportId: string): boolean {\n let traverserId = viewportId;\n if (this.options.viewportTraversersMap) {\n traverserId = this.options.viewportTraversersMap[viewportId];\n }\n if (traverserId !== viewportId) {\n return false;\n }\n\n return true;\n }\n\n /**\n * The callback to post-process tiles after traversal procedure\n * @param frameState - frame state for tile culling\n */\n _onTraversalEnd(frameState: FrameState): void {\n const id = frameState.viewport.id;\n if (!this.frameStateData[id]) {\n this.frameStateData[id] = {selectedTiles: [], _requestedTiles: [], _emptyTiles: []};\n }\n const currentFrameStateData = this.frameStateData[id];\n const selectedTiles = Object.values(this._traverser.selectedTiles);\n const [filteredSelectedTiles, unselectedTiles] = limitSelectedTiles(\n selectedTiles,\n frameState,\n this.options.maximumTilesSelected\n );\n currentFrameStateData.selectedTiles = filteredSelectedTiles;\n for (const tile of unselectedTiles) {\n tile.unselect();\n }\n\n currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);\n currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);\n\n this.traverseCounter--;\n if (this.traverseCounter > 0) {\n return;\n }\n\n this._updateTiles();\n }\n\n /**\n * Update tiles relying on data from all traversers\n */\n _updateTiles(): void {\n const previousSelectedTiles = this.selectedTiles;\n this.selectedTiles = [];\n this._requestedTiles = [];\n this._emptyTiles = [];\n\n for (const frameStateKey in this.frameStateData) {\n const frameStateDataValue = this.frameStateData[frameStateKey];\n this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);\n this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);\n this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);\n }\n\n this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);\n\n // Transition hold: keep recently-deselected tiles visible until all their\n // replacements have been drawn by the renderer (e.g. deck.gl).\n // Without this, there are single-frame flashes during REPLACE refinement transitions.\n const selectedIds = new Set(this.selectedTiles.map((t) => t.id));\n const hasUndrawnTiles = this.selectedTiles.some((t) => !t.tileDrawn);\n\n // Keep recently-deselected tiles visible while new tiles haven't drawn yet\n let heldBackCount = 0;\n if (hasUndrawnTiles) {\n for (const tileId of selectedIds) {\n this._heldTiles.add(tileId);\n }\n for (const tileId of this._heldTiles) {\n // Skip tiles that are already selected\n if (selectedIds.has(tileId)) continue; // eslint-disable-line no-continue\n\n // Keep tiles previously drawn selected\n const tile = this._tiles[tileId];\n if (tile && tile.contentAvailable) {\n tile._selectedFrame = this._frameNumber;\n this.selectedTiles.push(tile);\n heldBackCount++;\n } else {\n this._heldTiles.delete(tileId);\n }\n }\n } else {\n // Store current selected ids for next frame\n this._heldTiles = selectedIds;\n }\n\n if (heldBackCount > 0) {\n // Schedule another update so that once all replacement tiles\n // have drawn, the held tiles get released\n setTimeout(() => {\n this.selectTiles();\n }, 0);\n }\n\n for (const tile of this.selectedTiles) {\n this._tiles[tile.id] = tile;\n }\n\n this._loadTiles();\n this._unloadTiles();\n this._updateStats();\n\n if (this._tilesChanged(previousSelectedTiles, this.selectedTiles)) {\n this.options.onUpdate();\n }\n }\n\n _tilesChanged(oldSelectedTiles: Tile3D[], selectedTiles: Tile3D[]): boolean {\n if (oldSelectedTiles.length !== selectedTiles.length) {\n return true;\n }\n const set1 = new Set(oldSelectedTiles.map((t) => t.id));\n const set2 = new Set(selectedTiles.map((t) => t.id));\n let changed = oldSelectedTiles.filter((x) => !set2.has(x.id)).length > 0;\n changed = changed || selectedTiles.filter((x) => !set1.has(x.id)).length > 0;\n return changed;\n }\n\n _loadTiles(): void {\n // Sort requests by priority before making any requests.\n // This makes it less likely this requests will be cancelled after being issued.\n this._requestedTiles.sort((a, b) => a._priority - b._priority);\n for (const tile of this._requestedTiles) {\n if (tile.contentUnloaded) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._loadTile(tile);\n }\n }\n }\n\n _unloadTiles(): void {\n // unload tiles from cache when hit maximumMemoryUsage\n this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));\n }\n\n _updateStats(): void {\n let tilesRenderable = 0;\n let pointsRenderable = 0;\n for (const tile of this.selectedTiles) {\n if (tile.contentAvailable && tile.content) {\n tilesRenderable++;\n if (tile.content.pointCount) {\n pointsRenderable += tile.content.pointCount;\n } else {\n // Calculate vertices for non point cloud tiles.\n pointsRenderable += tile.content.vertexCount;\n }\n }\n }\n\n this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;\n this.stats.get(TILES_RENDERABLE).count = tilesRenderable;\n this.stats.get(POINTS_COUNT).count = pointsRenderable;\n this.stats.get(MAXIMUM_SSE).count = this.memoryAdjustedScreenSpaceError;\n }\n\n async _initializeTileSet(tilesetJson: TilesetJSON): Promise<void> {\n if (this.type === TILESET_TYPE.I3S) {\n this.calculateViewPropsI3S();\n tilesetJson.root = await tilesetJson.root;\n }\n this.root = this._initializeTileHeaders(tilesetJson, null);\n\n if (this.type === TILESET_TYPE.TILES3D) {\n this._initializeTiles3DTileset(tilesetJson);\n this.calculateViewPropsTiles3D();\n }\n\n if (this.type === TILESET_TYPE.I3S) {\n this._initializeI3STileset();\n }\n }\n\n /**\n * Called during initialize Tileset to initialize the tileset's cartographic center (longitude, latitude) and zoom.\n * These metrics help apps center view on tileset\n * For I3S there is extent (<1.8 version) or fullExtent (>=1.8 version) to calculate view props\n * @returns\n */\n private calculateViewPropsI3S(): void {\n // for I3S 1.8 try to calculate with fullExtent\n const fullExtent = this.tileset.fullExtent;\n if (fullExtent) {\n const {xmin, xmax, ymin, ymax, zmin, zmax} = fullExtent;\n this.cartographicCenter = new Vector3(\n xmin + (xmax - xmin) / 2,\n ymin + (ymax - ymin) / 2,\n zmin + (zmax - zmin) / 2\n );\n this.cartesianCenter = new Vector3();\n Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);\n this.zoom = getZoomFromFullExtent(fullExtent, this.cartographicCenter, this.cartesianCenter);\n return;\n }\n // for I3S 1.6-1.7 try to calculate with extent\n const extent = this.tileset.store?.extent;\n if (extent) {\n const [xmin, ymin, xmax, ymax] = extent;\n this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, 0);\n this.cartesianCenter = new Vector3();\n Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);\n this.zoom = getZoomFromExtent(extent, this.cartographicCenter, this.cartesianCenter);\n return;\n }\n // eslint-disable-next-line no-console\n console.warn('Extent is not defined in the tileset header');\n this.cartographicCenter = new Vector3();\n this.zoom = 1;\n return;\n }\n\n /**\n * Called during initialize Tileset to initialize the tileset's cartographic center (longitude, latitude) and zoom.\n * These metrics help apps center view on tileset.\n * For 3DTiles the root tile data is used to calculate view props.\n * @returns\n */\n private calculateViewPropsTiles3D() {\n const root = this.root as Tile3D;\n const {center} = root.boundingVolume;\n // TODO - handle all cases\n if (!center) {\n // eslint-disable-next-line no-console\n console.warn('center was not pre-calculated for the root tile');\n this.cartographicCenter = new Vector3();\n this.zoom = 1;\n return;\n }\n\n // cartographic coordinates are undefined at the center of the ellipsoid\n if (center[0] !== 0 || center[1] !== 0 || center[2] !== 0) {\n this.cartographicCenter = new Vector3();\n Ellipsoid.WGS84.cartesianToCartographic(center, this.cartographicCenter);\n } else {\n this.cartographicCenter = new Vector3(0, 0, -Ellipsoid.WGS84.radii[0]);\n }\n this.cartesianCenter = center;\n this.zoom = getZoomFromBoundingVolume(root.boundingVolume, this.cartographicCenter);\n }\n\n _initializeStats() {\n this.stats.get(TILES_TOTAL);\n this.stats.get(TILES_LOADING);\n this.stats.get(TILES_IN_MEMORY);\n this.stats.get(TILES_IN_VIEW);\n this.stats.get(TILES_RENDERABLE);\n this.stats.get(TILES_LOADED);\n this.stats.get(TILES_UNLOADED);\n this.stats.get(TILES_LOAD_FAILED);\n this.stats.get(POINTS_COUNT);\n this.stats.get(TILES_GPU_MEMORY, 'memory');\n this.stats.get(MAXIMUM_SSE);\n }\n\n // Installs the main tileset JSON file or a tileset JSON file referenced from a tile.\n // eslint-disable-next-line max-statements\n _initializeTileHeaders(tilesetJson: TilesetJSON, parentTileHeader?: any) {\n // A tileset JSON file referenced from a tile may exist in a different directory than the root tileset.\n // Get the basePath relative to the external tileset.\n const rootTile = new Tile3D(this, tilesetJson.root, parentTileHeader); // resource\n\n // If there is a parentTileHeader, add the root of the currently loading tileset\n // to parentTileHeader's children, and update its depth.\n if (parentTileHeader) {\n parentTileHeader.children.push(rootTile);\n rootTile.depth = parentTileHeader.depth + 1;\n }\n\n // 3DTiles knows the hierarchy beforehand\n if (this.type === TILESET_TYPE.TILES3D) {\n const stack: Tile3D[] = [];\n stack.push(rootTile);\n\n while (stack.length > 0) {\n const tile = stack.pop() as Tile3D;\n this.stats.get(TILES_TOTAL).incrementCount();\n const children = tile.header.children || [];\n for (const childHeader of children) {\n const childTile = new Tile3D(this, childHeader, tile);\n\n // Special handling for Google\n // A session key must be used for all tile requests\n if (childTile.contentUrl?.includes('?session=')) {\n const url = new URL(childTile.contentUrl);\n const session = url.searchParams.get('session');\n // eslint-disable-next-line max-depth\n if (session) {\n this._queryParams.session = session;\n }\n }\n\n tile.children.push(childTile);\n childTile.depth = tile.depth + 1;\n stack.push(childTile);\n }\n }\n }\n\n return rootTile;\n }\n\n _initializeTraverser(): TilesetTraverser {\n let TraverserClass;\n const type = this.type;\n switch (type) {\n case TILESET_TYPE.TILES3D:\n TraverserClass = Tileset3DTraverser;\n break;\n case TILESET_TYPE.I3S:\n TraverserClass = I3STilesetTraverser;\n break;\n default:\n TraverserClass = TilesetTraverser;\n }\n\n return new TraverserClass({\n basePath: this.basePath,\n onTraversalEnd: this._onTraversalEnd.bind(this)\n });\n }\n\n _destroyTileHeaders(parentTile: Tile3D): void {\n this._destroySubtree(parentTile);\n }\n\n async _loadTile(tile: Tile3D): Promise<void> {\n let loaded;\n try {\n this._onStartTileLoading();\n loaded = await tile.loadContent();\n } catch (error: unknown) {\n this._onTileLoadError(tile, error instanceof Error ? error : new Error('load failed'));\n } finally {\n this._onEndTileLoading();\n this._onTileLoad(tile, loaded);\n }\n }\n\n _onTileLoadError(tile: Tile3D, error: Error): void {\n this.stats.get(TILES_LOAD_FAILED).incrementCount();\n\n const message = error.message || error.toString();\n const url = tile.url;\n // TODO - Allow for probe log to be injected instead of console?\n console.error(`A 3D tile failed to load: ${tile.url} ${message}`); // eslint-disable-line\n this.options.onTileError(tile, message, url);\n }\n\n _onTileLoad(tile: Tile3D, loaded: boolean): void {\n if (!loaded) {\n return;\n }\n\n if (this.type === TILESET_TYPE.I3S) {\n // We can't calculate tiles total in I3S in advance so we calculate it dynamically.\n const nodesInNodePages = this.tileset?.nodePagesTile?.nodesInNodePages || 0;\n this.stats.get(TILES_TOTAL).reset();\n this.stats.get(TILES_TOTAL).addCount(nodesInNodePages);\n }\n\n // add coordinateOrigin and modelMatrix to tile\n if (tile && tile.content) {\n calculateTransformProps(tile, tile.content);\n }\n\n this.updateContentTypes(tile);\n this._addTileToCache(tile);\n this.options.onTileLoad(tile);\n }\n\n /**\n * Update information about data types in nested tiles\n * @param tile instance of a nested Tile3D\n */\n private updateContentTypes(tile: Tile3D) {\n if (this.type === TILESET_TYPE.I3S) {\n if (tile.header.isDracoGeometry) {\n this.contentFormats.draco = true;\n }\n switch (tile.header.textureFormat) {\n case 'dds':\n this.contentFormats.dds = true;\n break;\n case 'ktx2':\n this.contentFormats.ktx2 = true;\n break;\n default:\n }\n } else if (this.type === TILESET_TYPE.TILES3D) {\n const {extensionsRemoved = []} = tile.content?.gltf || {};\n if (extensionsRemoved.includes('KHR_draco_mesh_compression')) {\n this.contentFormats.draco = true;\n }\n if (extensionsRemoved.includes('EXT_meshopt_compression')) {\n this.contentFormats.meshopt = true;\n }\n if (extensionsRemoved.includes('KHR_texture_basisu')) {\n this.contentFormats.ktx2 = true;\n }\n }\n }\n\n _onStartTileLoading() {\n this._pendingCount++;\n this.stats.get(TILES_LOADING).incrementCount();\n }\n\n _onEndTileLoading() {\n this._pendingCount--;\n this.stats.get(TILES_LOADING).decrementCount();\n }\n\n _addTileToCache(tile: Tile3D) {\n this._cache.add(this, tile, (tileset) => tileset._updateCacheStats(tile));\n }\n\n _updateCacheStats(tile) {\n this.stats.get(TILES_LOADED).incrementCount();\n this.stats.get(TILES_IN_MEMORY).incrementCount();\n\n // TODO: Calculate GPU memory usage statistics for a tile.\n this.gpuMemoryUsageInBytes += tile.gpuMemoryUsageInBytes || 0;\n\n this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;\n\n // Adjust SSE based on cache limits\n if (this.options.memoryAdjustedScreenSpaceError) {\n this.adjustScreenSpaceError();\n }\n }\n\n _unloadTile(tile) {\n this.gpuMemoryUsageInBytes -= tile.gpuMemoryUsageInBytes || 0;\n\n this.stats.get(TILES_IN_MEMORY).decrementCount();\n this.stats.get(TILES_UNLOADED).incrementCount();\n this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;\n\n this.options.onTileUnload(tile);\n tile.unloadContent();\n }\n\n // Traverse the tree and destroy all tiles\n _destroy() {\n const stack: Tile3D[] = [];\n\n if (this.root) {\n stack.push(this.root);\n }\n\n while (stack.length > 0) {\n const tile: Tile3D = stack.pop() as Tile3D;\n\n for (const child of tile.children) {\n stack.push(child);\n }\n\n this._destroyTile(tile);\n }\n this.root = null;\n }\n\n // Traverse the tree and destroy all sub tiles\n _destroySubtree(tile) {\n const root = tile;\n const stack: Tile3D[] = [];\n stack.push(root);\n while (stack.length > 0) {\n tile = stack.pop();\n for (const child of tile.children) {\n stack.push(child);\n }\n if (tile !== root) {\n this._destroyTile(tile);\n }\n }\n root.children = [];\n }\n\n _destroyTile(tile) {\n this._cache.unloadTile(this, tile);\n this._unloadTile(tile);\n tile.destroy();\n }\n\n _initializeTiles3DTileset(tilesetJson) {\n if (tilesetJson.queryString) {\n const searchParams = new URLSearchParams(tilesetJson.queryString);\n const queryParams = Object.fromEntries(searchParams.entries());\n this._queryParams = {...this._queryParams, ...queryParams};\n }\n\n this.asset = tilesetJson.asset;\n if (!this.asset) {\n throw new Error('Tileset must have an asset property.');\n }\n if (\n this.asset.version !== '0.0' &&\n this.asset.version !== '1.0' &&\n this.asset.version !== '1.1'\n ) {\n throw new Error('The tileset must be 3D Tiles version either 0.0 or 1.0 or 1.1.');\n }\n\n // Note: `asset.tilesetVersion` is version of the tileset itself (not the version of the 3D TILES standard)\n // We add this version as a `v=1.0` query param to fetch the right version and not get an older cached version\n if ('tilesetVersion' in this.asset) {\n this._queryParams.v = this.asset.tilesetVersion;\n }\n\n // TODO - ion resources have a credits property we can use for additional attribution.\n this.credits = {\n attributions: this.options.attributions || []\n };\n this.description = this.options.description || '';\n\n // Gets the tileset's properties dictionary object, which contains metadata about per-feature properties.\n this.properties = tilesetJson.properties;\n this.geometricError = tilesetJson.geometricError;\n this._extensionsUsed = tilesetJson.extensionsUsed || [];\n // Returns the extras property at the top of the tileset JSON (application specific metadata).\n this.extras = tilesetJson.extras;\n }\n\n _initializeI3STileset() {\n const i3sOptions = this.loadOptions.i3s;\n if (i3sOptions && typeof i3sOptions === 'object' && 'token' in i3sOptions) {\n this._queryParams.token = (i3sOptions as Record<string, unknown>).token as string;\n }\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// This file is derived from the Cesium code base under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\n/**\n * Doubly linked list node\n * @private\n */\nexport class DoublyLinkedListNode {\n item;\n previous;\n next;\n\n constructor(item, previous, next) {\n this.item = item;\n this.previous = previous;\n this.next = next;\n }\n}\n", "// This file is derived from the Cesium code base under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\nimport {DoublyLinkedListNode} from './doubly-linked-list-node';\n\n/**\n * Doubly linked list\n * @private\n */\nexport class DoublyLinkedList {\n head: DoublyLinkedListNode | null = null;\n tail: DoublyLinkedListNode | null = null;\n _length = 0;\n\n get length() {\n return this._length;\n }\n\n /**\n * Adds the item to the end of the list\n * @param {*} [item]\n * @return {DoublyLinkedListNode}\n */\n add(item) {\n const node = new DoublyLinkedListNode(item, this.tail, null);\n\n if (this.tail) {\n this.tail.next = node;\n this.tail = node;\n } else {\n this.head = node;\n this.tail = node;\n }\n\n ++this._length;\n\n return node;\n }\n\n /**\n * Removes the given node from the list\n * @param {DoublyLinkedListNode} node\n */\n remove(node) {\n if (!node) {\n return;\n }\n\n if (node.previous && node.next) {\n node.previous.next = node.next;\n node.next.previous = node.previous;\n } else if (node.previous) {\n // Remove last node\n node.previous.next = null;\n this.tail = node.previous;\n } else if (node.next) {\n // Remove first node\n node.next.previous = null;\n this.head = node.next;\n } else {\n // Remove last node in the linked list\n this.head = null;\n this.tail = null;\n }\n\n node.next = null;\n node.previous = null;\n\n --this._length;\n }\n\n /**\n * Moves nextNode after node\n * @param {DoublyLinkedListNode} node\n * @param {DoublyLinkedListNode} nextNode\n */\n splice(node, nextNode) {\n if (node === nextNode) {\n return;\n }\n\n // Remove nextNode, then insert after node\n this.remove(nextNode);\n this._insert(node, nextNode);\n }\n\n _insert(node, nextNode) {\n const oldNodeNext = node.next;\n node.next = nextNode;\n\n // nextNode is the new tail\n if (this.tail === node) {\n this.tail = nextNode;\n } else {\n oldNodeNext.previous = nextNode;\n }\n\n nextNode.next = oldNodeNext;\n nextNode.previous = node;\n\n ++this._length;\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// This file is derived from the Cesium code base under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\nimport type {Tileset3D} from './tileset-3d';\nimport type {Tile3D} from './tile-3d';\nimport {DoublyLinkedList} from '../utils/doubly-linked-list';\n\n/**\n * Stores tiles with content loaded.\n * @private\n */\nexport class TilesetCache {\n private _list: DoublyLinkedList;\n private _sentinel: any;\n private _trimTiles: boolean;\n\n constructor() {\n // [head, sentinel) -> tiles that weren't selected this frame and may be removed from the cache\n // (sentinel, tail] -> tiles that were selected this frame\n this._list = new DoublyLinkedList();\n this._sentinel = this._list.add('sentinel');\n this._trimTiles = false;\n }\n\n reset(): void {\n // Move sentinel node to the tail so, at the start of the frame, all tiles\n // may be potentially replaced. Tiles are moved to the right of the sentinel\n // when they are selected so they will not be replaced.\n this._list.splice(this._list.tail, this._sentinel);\n }\n\n touch(tile: Tile3D): void {\n const node = tile._cacheNode;\n if (node) {\n this._list.splice(this._sentinel, node);\n }\n }\n\n add(\n tileset: Tileset3D,\n tile: Tile3D,\n addCallback?: (tileset: Tileset3D, tile: Tile3D) => void\n ): void {\n if (!tile._cacheNode) {\n tile._cacheNode = this._list.add(tile);\n\n if (addCallback) {\n addCallback(tileset, tile);\n }\n }\n }\n\n unloadTile(\n tileset: Tileset3D,\n tile: Tile3D,\n unloadCallback?: (tileset: Tileset3D, tile: Tile3D) => void\n ): void {\n const node = tile._cacheNode;\n if (!node) {\n return;\n }\n\n this._list.remove(node);\n tile._cacheNode = null;\n if (unloadCallback) {\n unloadCallback(tileset, tile);\n }\n }\n\n unloadTiles(tileset, unloadCallback): void {\n const trimTiles = this._trimTiles;\n this._trimTiles = false;\n\n const list = this._list;\n\n const maximumMemoryUsageInBytes = tileset.maximumMemoryUsage * 1024 * 1024;\n\n // Traverse the list only to the sentinel since tiles/nodes to the\n // right of the sentinel were used this frame.\n // The sub-list to the left of the sentinel is ordered from LRU to MRU.\n const sentinel = this._sentinel;\n let node = list.head;\n\n while (\n node !== sentinel &&\n (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)\n ) {\n // @ts-expect-error\n const tile = node.item;\n // @ts-expect-error\n node = node.next;\n this.unloadTile(tileset, tile, unloadCallback);\n }\n }\n\n trim(): void {\n this._trimTiles = true;\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Ellipsoid} from '@math.gl/geospatial';\nimport {Matrix4, Vector3} from '@math.gl/core';\nimport {assert} from '@loaders.gl/loader-utils';\n\nimport {Tile3D} from '../tile-3d';\n\nexport function calculateTransformProps(tileHeader: Tile3D, tile: Tile3D['content']) {\n assert(tileHeader);\n assert(tile);\n\n const {rtcCenter, gltfUpAxis} = tile;\n const {\n computedTransform,\n boundingVolume: {center}\n } = tileHeader;\n\n let modelMatrix = new Matrix4(computedTransform);\n\n // Translate if appropriate\n if (rtcCenter) {\n modelMatrix.translate(rtcCenter);\n }\n\n // glTF models need to be rotated from Y to Z up\n // https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification#y-up-to-z-up\n switch (gltfUpAxis) {\n case 'Z':\n break;\n case 'Y':\n const rotationY = new Matrix4().rotateX(Math.PI / 2);\n modelMatrix = modelMatrix.multiplyRight(rotationY);\n break;\n case 'X':\n const rotationX = new Matrix4().rotateY(-Math.PI / 2);\n modelMatrix = modelMatrix.multiplyRight(rotationX);\n break;\n default:\n break;\n }\n\n // Scale/offset positions if normalized integers\n if (tile.isQuantized) {\n modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale);\n }\n\n // Option 1: Cartesian matrix and origin\n const cartesianOrigin = new Vector3(center);\n\n tile.cartesianModelMatrix = modelMatrix;\n tile.cartesianOrigin = cartesianOrigin;\n\n // Option 2: Cartographic matrix and origin\n const cartographicOrigin = Ellipsoid.WGS84.cartesianToCartographic(\n cartesianOrigin,\n new Vector3()\n );\n const fromFixedFrameMatrix = Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin);\n const toFixedFrameMatrix = fromFixedFrameMatrix.invert();\n\n tile.cartographicModelMatrix = toFixedFrameMatrix.multiplyRight(modelMatrix);\n tile.cartographicOrigin = cartographicOrigin;\n\n // Absorb glTF root node matrix into model matrices for Float32 precision.\n // The glTF root node matrix (applied as sceneModelMatrix in the shader) may contain\n // ECEF-scale translations (~millions of meters). When both cartographicModelMatrix\n // and sceneModelMatrix are applied in the Float32 GPU shader, catastrophic cancellation\n // occurs causing visible seams between adjacent tiles. By combining them here in Float64,\n // the result has small ENU-scale values that preserve precision.\n const rootNode = _getRootNode(tile);\n if (rootNode) {\n tile.cartesianModelMatrix = new Matrix4(modelMatrix).multiplyRight(rootNode.matrix);\n tile.cartographicModelMatrix.multiplyRight(rootNode.matrix);\n rootNode.matrix = Matrix4.IDENTITY;\n }\n\n // Deprecated, drop\n if (!tile.coordinateSystem) {\n tile.modelMatrix = tile.cartographicModelMatrix;\n }\n}\n\nconst TRANSLATION_LIMIT_SQUARED = 10e5 ** 2; // 100km\n\n/**\n * Returns the glTF root node if it has a matrix with earth-scale translations (> 100km).\n * These large translations cause Float32 precision issues when applied in the GPU shader.\n */\nfunction _getRootNode(tile: Tile3D['content']): {matrix: number[]} | null {\n const gltf = tile.gltf;\n if (!gltf) {\n return null;\n }\n\n const sceneIndex = typeof gltf.scene === 'number' ? gltf.scene : 0;\n const scene = gltf.scenes?.[sceneIndex];\n const rootNode = scene?.nodes?.[0];\n if (!rootNode?.matrix) return null;\n\n // Extract translation and compare magnitude (meters) to limit\n const m = rootNode.matrix;\n const translationMagnitude = m[12] * m[12] + m[13] * m[13] + m[14] * m[14];\n if (translationMagnitude <= TRANSLATION_LIMIT_SQUARED) return null;\n\n return rootNode;\n}\n", "import {Tile3D} from '@loaders.gl/tiles';\nimport {Vector3} from '@math.gl/core';\nimport {CullingVolume, Plane} from '@math.gl/culling';\nimport {Ellipsoid} from '@math.gl/geospatial';\nimport {GeospatialViewport, Viewport} from '../../types';\n\nexport type FrameState = {\n camera: {\n position: number[];\n direction: number[];\n up: number[];\n };\n viewport: GeospatialViewport;\n topDownViewport: GeospatialViewport; // Use it to calculate projected radius for a tile\n height: number;\n cullingVolume: CullingVolume;\n frameNumber: number; // TODO: This can be the same between updates, what number is unique for between updates?\n sseDenominator: number; // Assumes fovy = 60 degrees\n};\n\nconst scratchVector = new Vector3();\nconst scratchPosition = new Vector3();\nconst cullingVolume = new CullingVolume([\n new Plane(),\n new Plane(),\n new Plane(),\n new Plane(),\n new Plane(),\n new Plane()\n]);\n\n// Extracts a frame state appropriate for tile culling from a deck.gl viewport\n// TODO - this could likely be generalized and merged back into deck.gl for other culling scenarios\nexport function getFrameState(viewport: GeospatialViewport, frameNumber: number): FrameState {\n // Traverse and and request. Update _selectedTiles so that we know what to render.\n // Traverse and and request. Update _selectedTiles so that we know what to render.\n const {cameraDirection, cameraUp, height} = viewport;\n const {metersPerUnit} = viewport.distanceScales;\n\n // TODO - Ellipsoid.eastNorthUpToFixedFrame() breaks on raw array, create a Vector.\n // TODO - Ellipsoid.eastNorthUpToFixedFrame() takes a cartesian, is that intuitive?\n const viewportCenterCartesian = worldToCartesian(viewport, viewport.center);\n const enuToFixedTransform = Ellipsoid.WGS84.eastNorthUpToFixedFrame(viewportCenterCartesian);\n\n const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);\n const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(\n cameraPositionCartographic,\n new Vector3()\n );\n\n // These should still be normalized as the transform has scale 1 (goes from meters to meters)\n const cameraDirectionCartesian = new Vector3(\n // @ts-ignore\n enuToFixedTransform.transformAsVector(new Vector3(cameraDirection).scale(metersPerUnit))\n ).normalize();\n const cameraUpCartesian = new Vector3(\n // @ts-ignore\n enuToFixedTransform.transformAsVector(new Vector3(cameraUp).scale(metersPerUnit))\n ).normalize();\n\n commonSpacePlanesToWGS84(viewport);\n\n const ViewportClass = viewport.constructor;\n const {longitude, latitude, width, bearing, zoom} = viewport;\n // @ts-ignore\n const topDownViewport = new ViewportClass({\n longitude,\n latitude,\n height,\n width,\n bearing,\n zoom,\n pitch: 0\n });\n\n // TODO: make a file/class for frameState and document what needs to be attached to this so that traversal can function\n return {\n camera: {\n position: cameraPositionCartesian,\n direction: cameraDirectionCartesian,\n up: cameraUpCartesian\n },\n viewport,\