@vim3d/tiles 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +24 -0
- package/README.md +227 -2
- package/TILESET.md +51 -0
- package/builders.d.ts +28 -0
- package/builders.js +80 -0
- package/elevation-source.d.ts +8 -0
- package/elevation-source.js +48 -0
- package/esm/builders.js +76 -0
- package/esm/elevation-source.js +44 -0
- package/esm/feature-api.js +93 -0
- package/esm/flatgeobuf.js +59 -0
- package/esm/geojson.js +10 -0
- package/esm/index.js +10 -0
- package/esm/loader.js +236 -0
- package/esm/manifest.js +83 -0
- package/esm/package.json +3 -0
- package/esm/pmtiles.js +94 -0
- package/esm/query-tiles.js +140 -0
- package/esm/source-config.js +12 -0
- package/esm/source.js +86 -0
- package/esm/terrarium.js +171 -0
- package/esm/three.js +265 -0
- package/esm/view.js +30 -0
- package/feature-api.d.ts +7 -0
- package/feature-api.js +97 -0
- package/flatgeobuf.d.ts +3 -0
- package/flatgeobuf.js +62 -0
- package/geojson.d.ts +3 -0
- package/geojson.js +13 -0
- package/index.d.ts +19 -0
- package/index.js +27 -0
- package/loader.d.ts +73 -0
- package/loader.js +240 -0
- package/manifest.d.ts +21 -0
- package/manifest.js +86 -0
- package/package.json +45 -4
- package/pmtiles.d.ts +13 -0
- package/pmtiles.js +99 -0
- package/query-tiles.d.ts +23 -0
- package/query-tiles.js +144 -0
- package/source-config.d.ts +26 -0
- package/source-config.js +15 -0
- package/source.d.ts +42 -0
- package/source.js +97 -0
- package/terrarium.d.ts +27 -0
- package/terrarium.js +178 -0
- package/three.d.ts +43 -0
- package/three.js +270 -0
- package/view.d.ts +24 -0
- package/view.js +35 -0
package/esm/view.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export function intersects(bounds, planes) {
|
|
2
|
+
return planes.every(([a, b, c, d]) => a * bounds[a < 0 ? 0 : 3] + b * bounds[b < 0 ? 1 : 4]
|
|
3
|
+
+ c * bounds[c < 0 ? 2 : 5] + d >= 0);
|
|
4
|
+
}
|
|
5
|
+
export function screenSpaceError(tile, projection) {
|
|
6
|
+
if (tile.geometricError === 0)
|
|
7
|
+
return 0;
|
|
8
|
+
if (projection.type === 'orthographic')
|
|
9
|
+
return tile.geometricError * projection.pixelsPerMetre;
|
|
10
|
+
const [x, y, z] = projection.position;
|
|
11
|
+
const [minX, minY, minZ, maxX, maxY, maxZ] = tile.bounds;
|
|
12
|
+
const distance = Math.hypot(Math.max(minX - x, 0, x - maxX), Math.max(minY - y, 0, y - maxY), Math.max(minZ - z, 0, z - maxZ));
|
|
13
|
+
return tile.geometricError * projection.pixelsPerMetreAtUnitDistance / distance;
|
|
14
|
+
}
|
|
15
|
+
export function planView(tile, view, depth = 0) {
|
|
16
|
+
if (!intersects(tile.bounds, view.frustum))
|
|
17
|
+
return undefined;
|
|
18
|
+
const children = [];
|
|
19
|
+
if (tile.children?.length && (!tile.url || screenSpaceError(tile, view.projection) > view.maxScreenSpaceError)) {
|
|
20
|
+
for (const child of tile.children) {
|
|
21
|
+
const visible = planView(child, view, depth + 1);
|
|
22
|
+
if (visible)
|
|
23
|
+
children.push(visible);
|
|
24
|
+
}
|
|
25
|
+
if (children.length === 0)
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
if (tile.url || children.length > 0)
|
|
29
|
+
return { tile, children, depth };
|
|
30
|
+
}
|
package/feature-api.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type FeaturePageOptions, type TileSourceReader } from './source.js';
|
|
2
|
+
export declare function ogcApiFeatures(input: string | URL, options?: FeaturePageOptions): TileSourceReader;
|
|
3
|
+
export interface SocrataOptions extends FeaturePageOptions {
|
|
4
|
+
readonly geomField?: string;
|
|
5
|
+
}
|
|
6
|
+
/** SoQL spatial binding for Socrata .geojson endpoints, including DataSF. */
|
|
7
|
+
export declare function socrataGeoJSON(input: string | URL, options?: SocrataOptions): TileSourceReader;
|
package/feature-api.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ogcApiFeatures = ogcApiFeatures;
|
|
4
|
+
exports.socrataGeoJSON = socrataGeoJSON;
|
|
5
|
+
const source_js_1 = require("./source.js");
|
|
6
|
+
async function readPage(url, { fetch = source_js_1.defaultFetch, signal }) {
|
|
7
|
+
signal.throwIfAborted();
|
|
8
|
+
const response = await fetch(url, {
|
|
9
|
+
headers: { accept: 'application/geo+json, application/json' }, redirect: 'error', signal,
|
|
10
|
+
});
|
|
11
|
+
if (!response.ok)
|
|
12
|
+
throw new Error(`Feature page request failed: ${response.status} (${url})`);
|
|
13
|
+
signal.throwIfAborted();
|
|
14
|
+
const page = await response.json();
|
|
15
|
+
signal.throwIfAborted();
|
|
16
|
+
if (page?.type !== 'FeatureCollection' || !Array.isArray(page.features)) {
|
|
17
|
+
throw new Error(`Not a GeoJSON FeatureCollection: ${url}`);
|
|
18
|
+
}
|
|
19
|
+
return page;
|
|
20
|
+
}
|
|
21
|
+
function pageLimits(options, zoom) {
|
|
22
|
+
const cap = typeof options.maxFeatures === 'function' ? options.maxFeatures(zoom) : options.maxFeatures;
|
|
23
|
+
return {
|
|
24
|
+
pageSize: (0, source_js_1.positiveInteger)(options.pageSize ?? 1000, 'pageSize'),
|
|
25
|
+
max: (0, source_js_1.positiveInteger)(cap ?? 10_000, 'maxFeatures'),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function ogcApiFeatures(input, options = {}) {
|
|
29
|
+
const endpoint = (0, source_js_1.sourceURL)(input);
|
|
30
|
+
return (0, source_js_1.sourceReader)(options, async function* (bbox, context, zoom) {
|
|
31
|
+
const { pageSize, max } = pageLimits(options, zoom);
|
|
32
|
+
const properties = typeof options.properties === 'function' ? options.properties(zoom) : options.properties;
|
|
33
|
+
let count = 0;
|
|
34
|
+
const seen = new Set();
|
|
35
|
+
let next = new URL(endpoint);
|
|
36
|
+
next.searchParams.delete('bbox-crs');
|
|
37
|
+
next.searchParams.delete('crs');
|
|
38
|
+
next.searchParams.set('bbox', bbox.join(','));
|
|
39
|
+
next.searchParams.set('limit', String(Math.min(pageSize, max)));
|
|
40
|
+
if (properties) {
|
|
41
|
+
next.searchParams.set('properties', [...new Set([...properties, ...(options.idField ? [options.idField] : [])])].join(','));
|
|
42
|
+
}
|
|
43
|
+
while (next && count < max) {
|
|
44
|
+
if (next.origin !== endpoint.origin || next.pathname !== endpoint.pathname) {
|
|
45
|
+
throw new Error('OGC pagination must stay on the same collection items endpoint');
|
|
46
|
+
}
|
|
47
|
+
const key = next.href;
|
|
48
|
+
if (seen.has(key))
|
|
49
|
+
throw new Error('Repeated OGC pagination link');
|
|
50
|
+
seen.add(key);
|
|
51
|
+
const page = await readPage(next, context);
|
|
52
|
+
const batch = page.features.slice(0, max - count).map(feature => (0, source_js_1.withId)(feature, options.idField));
|
|
53
|
+
count += batch.length;
|
|
54
|
+
yield batch;
|
|
55
|
+
const link = page.links?.find(({ rel }) => rel === 'next');
|
|
56
|
+
next = count < max && link ? new URL(link.href, next) : undefined;
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
function polygon([west, south, east, north]) {
|
|
61
|
+
return `POLYGON ((${west} ${south},${east} ${south},${east} ${north},${west} ${north},${west} ${south}))`;
|
|
62
|
+
}
|
|
63
|
+
/** SoQL spatial binding for Socrata .geojson endpoints, including DataSF. */
|
|
64
|
+
function socrataGeoJSON(input, options = {}) {
|
|
65
|
+
const endpoint = (0, source_js_1.sourceURL)(input);
|
|
66
|
+
const geometry = options.geomField ?? 'the_geom';
|
|
67
|
+
if (!/^[a-z_][a-z_\d]*$/i.test(geometry))
|
|
68
|
+
throw new TypeError('Invalid Socrata geometry field');
|
|
69
|
+
if (endpoint.searchParams.has('$query') || endpoint.searchParams.has('$$query')) {
|
|
70
|
+
throw new TypeError('Socrata spatial reads do not accept a full query override');
|
|
71
|
+
}
|
|
72
|
+
const where = endpoint.searchParams.get('$where');
|
|
73
|
+
const order = endpoint.searchParams.get('$order');
|
|
74
|
+
return (0, source_js_1.sourceReader)(options, async function* (bbox, context, zoom) {
|
|
75
|
+
const { pageSize, max } = pageLimits(options, zoom);
|
|
76
|
+
const request = new URL(endpoint);
|
|
77
|
+
const intersects = `intersects(${geometry}, '${polygon(bbox)}')`;
|
|
78
|
+
request.searchParams.set('$where', where ? `(${where}) AND ${intersects}` : intersects);
|
|
79
|
+
request.searchParams.set('$order', order ? `${order}, :id` : ':id');
|
|
80
|
+
const properties = typeof options.properties === 'function' ? options.properties(zoom) : options.properties;
|
|
81
|
+
if (properties) {
|
|
82
|
+
request.searchParams.set('$select', [...new Set([geometry, ...properties, ...(options.idField ? [options.idField] : [])])].join(','));
|
|
83
|
+
}
|
|
84
|
+
let offset = 0;
|
|
85
|
+
while (offset < max) {
|
|
86
|
+
const limit = Math.min(pageSize, max - offset);
|
|
87
|
+
request.searchParams.set('$limit', String(limit));
|
|
88
|
+
request.searchParams.set('$offset', String(offset));
|
|
89
|
+
const page = await readPage(new URL(request), context);
|
|
90
|
+
const batch = page.features.slice(0, limit).map(feature => (0, source_js_1.withId)(feature, options.idField));
|
|
91
|
+
offset += batch.length;
|
|
92
|
+
yield batch;
|
|
93
|
+
if (batch.length < limit)
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
}
|
package/flatgeobuf.d.ts
ADDED
package/flatgeobuf.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.flatGeobuf = flatGeobuf;
|
|
4
|
+
const flatbuffers_1 = require("flatbuffers");
|
|
5
|
+
const source_js_1 = require("./source.js");
|
|
6
|
+
async function loadCodec() {
|
|
7
|
+
const { HEADER_MAX_BUFFER_SIZE, magicbytes } = await import('flatgeobuf/lib/mjs/constants.js');
|
|
8
|
+
const { fromByteBuffer } = await import('flatgeobuf/lib/mjs/header-meta.js');
|
|
9
|
+
const { calcTreeSize, streamSearch } = await import('flatgeobuf/lib/mjs/packedrtree.js');
|
|
10
|
+
const { Feature: BinaryFeature } = await import('flatgeobuf/lib/mjs/flat-geobuf/feature.js');
|
|
11
|
+
const { fromFeature } = await import('flatgeobuf/lib/mjs/geojson/feature.js');
|
|
12
|
+
return { HEADER_MAX_BUFFER_SIZE, magicbytes, fromByteBuffer, calcTreeSize, streamSearch, BinaryFeature, fromFeature };
|
|
13
|
+
}
|
|
14
|
+
let codec;
|
|
15
|
+
function isWGS84(crs) {
|
|
16
|
+
if (!crs || !Object.values(crs).some(Boolean) || crs.code === 4326)
|
|
17
|
+
return true;
|
|
18
|
+
if (crs.org?.toUpperCase() === 'OGC' && crs.code_string?.toUpperCase() === 'CRS84')
|
|
19
|
+
return true;
|
|
20
|
+
const wkt = crs.wkt?.trim() ?? '';
|
|
21
|
+
return /^(?:GEOGCS|GEOGCRS|GEODCRS)\s*\[/i.test(wkt)
|
|
22
|
+
&& /,\s*(?:AUTHORITY|ID)\s*\[\s*"OGC"\s*,\s*"CRS84"\s*\]\s*\]$/i.test(wkt);
|
|
23
|
+
}
|
|
24
|
+
/** Read an indexed FlatGeobuf file in WGS84. */
|
|
25
|
+
function flatGeobuf(input, options = {}) {
|
|
26
|
+
const url = (0, source_js_1.sourceURL)(input);
|
|
27
|
+
return (0, source_js_1.sourceReader)(options, async function* (bbox, context) {
|
|
28
|
+
const { HEADER_MAX_BUFFER_SIZE, magicbytes, fromByteBuffer, calcTreeSize, streamSearch, BinaryFeature, fromFeature, } = await (codec ??= loadCodec());
|
|
29
|
+
const bytes = async (offset, length) => (await (0, source_js_1.readRange)(url, offset, length, context)).data;
|
|
30
|
+
const prefixSize = magicbytes.length + 4;
|
|
31
|
+
const prefix = await bytes(0, prefixSize);
|
|
32
|
+
const magic = new Uint8Array(prefix, 0, magicbytes.length);
|
|
33
|
+
if (!magic.subarray(0, -1).every((byte, i) => byte === magicbytes[i]))
|
|
34
|
+
throw new Error('Not a FlatGeobuf file');
|
|
35
|
+
const headerLength = new DataView(prefix).getUint32(magicbytes.length, true);
|
|
36
|
+
if (headerLength < 8 || headerLength > HEADER_MAX_BUFFER_SIZE)
|
|
37
|
+
throw new Error('Invalid FlatGeobuf header size');
|
|
38
|
+
const headerBytes = new Uint8Array(4 + headerLength);
|
|
39
|
+
headerBytes.set(new Uint8Array(prefix, magicbytes.length));
|
|
40
|
+
headerBytes.set(new Uint8Array(await bytes(prefixSize, headerLength)), 4);
|
|
41
|
+
const header = fromByteBuffer(new flatbuffers_1.ByteBuffer(headerBytes));
|
|
42
|
+
if (header.featuresCount === 0)
|
|
43
|
+
return;
|
|
44
|
+
if (!header.indexNodeSize)
|
|
45
|
+
throw new Error('FlatGeobuf bbox queries require a spatial index');
|
|
46
|
+
if (!isWGS84(header.crs))
|
|
47
|
+
throw new Error('FlatGeobuf bbox queries require WGS84 coordinates');
|
|
48
|
+
const treeOffset = prefixSize + headerLength;
|
|
49
|
+
const featureOffset = treeOffset + calcTreeSize(header.featuresCount, header.indexNodeSize);
|
|
50
|
+
const [minX, minY, maxX, maxY] = bbox;
|
|
51
|
+
for await (const [offset, id] of streamSearch(header.featuresCount, header.indexNodeSize, { minX, minY, maxX, maxY }, (start, size) => bytes(treeOffset + start, size))) {
|
|
52
|
+
const start = featureOffset + offset;
|
|
53
|
+
const prefix = await bytes(start, 4);
|
|
54
|
+
const length = new DataView(prefix).getUint32(0, true);
|
|
55
|
+
const featureBytes = new Uint8Array(4 + length);
|
|
56
|
+
featureBytes.set(new Uint8Array(prefix));
|
|
57
|
+
featureBytes.set(new Uint8Array(await bytes(start + 4, length)), 4);
|
|
58
|
+
const binary = BinaryFeature.getSizePrefixedRootAsFeature(new flatbuffers_1.ByteBuffer(featureBytes));
|
|
59
|
+
yield [(0, source_js_1.withId)(fromFeature(id, binary, header), options.idField)];
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
package/geojson.d.ts
ADDED
package/geojson.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.geoJSONDecoder = geoJSONDecoder;
|
|
4
|
+
const geojson_1 = require("@vim3d/geojson");
|
|
5
|
+
function geoJSONDecoder(options = {}) {
|
|
6
|
+
return async (response, { tile }) => {
|
|
7
|
+
const data = await response.json();
|
|
8
|
+
if (data?.type !== 'FeatureCollection' || !Array.isArray(data.features)) {
|
|
9
|
+
throw new Error(`Not a GeoJSON FeatureCollection: ${tile.url}`);
|
|
10
|
+
}
|
|
11
|
+
return (0, geojson_1.resampleGeoJSON)(data, options);
|
|
12
|
+
};
|
|
13
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export { ElevationSources } from './elevation-source.js';
|
|
2
|
+
export type { SocrataOptions } from './feature-api.js';
|
|
3
|
+
export { ogcApiFeatures, socrataGeoJSON } from './feature-api.js';
|
|
4
|
+
export { flatGeobuf } from './flatgeobuf.js';
|
|
5
|
+
export { geoJSONDecoder } from './geojson.js';
|
|
6
|
+
export type { LoadedTile, SourceTileLoaderOptions, TileDecodeContext, TileDecoder, TileLoaderOptions } from './loader.js';
|
|
7
|
+
export { TileLoader } from './loader.js';
|
|
8
|
+
export type { TileBounds, TileNode, TileOrigin, TilesetManifest, Vec3 } from './manifest.js';
|
|
9
|
+
export { parseTilesetManifest } from './manifest.js';
|
|
10
|
+
export type { PMTilesOptions } from './pmtiles.js';
|
|
11
|
+
export { pmTiles, PMTilesTileBudgetError } from './pmtiles.js';
|
|
12
|
+
export type { CreateTileSourceReader, QueryLoaderOptions, QueryTile, QueryTileSourceConfig } from './query-tiles.js';
|
|
13
|
+
export { openQueryTiles, validateTileSource } from './query-tiles.js';
|
|
14
|
+
export type { FeaturePageOptions, SourceBBox, SourceOptions, SourceQuery, SourceReadOptions, TileSourceReader } from './source.js';
|
|
15
|
+
export type { TileSourceConfig } from './source-config.js';
|
|
16
|
+
export { createReader } from './source-config.js';
|
|
17
|
+
export type { ElevationBounds, TerrariumConfig, TerrariumElevation } from './terrarium.js';
|
|
18
|
+
export { readTerrarium, terrariumHeight } from './terrarium.js';
|
|
19
|
+
export type { FrustumPlane, TileProjection, TileView } from './view.js';
|
package/index.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.terrariumHeight = exports.readTerrarium = exports.createReader = exports.validateTileSource = exports.openQueryTiles = exports.PMTilesTileBudgetError = exports.pmTiles = exports.parseTilesetManifest = exports.TileLoader = exports.geoJSONDecoder = exports.flatGeobuf = exports.socrataGeoJSON = exports.ogcApiFeatures = exports.ElevationSources = void 0;
|
|
4
|
+
var elevation_source_js_1 = require("./elevation-source.js");
|
|
5
|
+
Object.defineProperty(exports, "ElevationSources", { enumerable: true, get: function () { return elevation_source_js_1.ElevationSources; } });
|
|
6
|
+
var feature_api_js_1 = require("./feature-api.js");
|
|
7
|
+
Object.defineProperty(exports, "ogcApiFeatures", { enumerable: true, get: function () { return feature_api_js_1.ogcApiFeatures; } });
|
|
8
|
+
Object.defineProperty(exports, "socrataGeoJSON", { enumerable: true, get: function () { return feature_api_js_1.socrataGeoJSON; } });
|
|
9
|
+
var flatgeobuf_js_1 = require("./flatgeobuf.js");
|
|
10
|
+
Object.defineProperty(exports, "flatGeobuf", { enumerable: true, get: function () { return flatgeobuf_js_1.flatGeobuf; } });
|
|
11
|
+
var geojson_js_1 = require("./geojson.js");
|
|
12
|
+
Object.defineProperty(exports, "geoJSONDecoder", { enumerable: true, get: function () { return geojson_js_1.geoJSONDecoder; } });
|
|
13
|
+
var loader_js_1 = require("./loader.js");
|
|
14
|
+
Object.defineProperty(exports, "TileLoader", { enumerable: true, get: function () { return loader_js_1.TileLoader; } });
|
|
15
|
+
var manifest_js_1 = require("./manifest.js");
|
|
16
|
+
Object.defineProperty(exports, "parseTilesetManifest", { enumerable: true, get: function () { return manifest_js_1.parseTilesetManifest; } });
|
|
17
|
+
var pmtiles_js_1 = require("./pmtiles.js");
|
|
18
|
+
Object.defineProperty(exports, "pmTiles", { enumerable: true, get: function () { return pmtiles_js_1.pmTiles; } });
|
|
19
|
+
Object.defineProperty(exports, "PMTilesTileBudgetError", { enumerable: true, get: function () { return pmtiles_js_1.PMTilesTileBudgetError; } });
|
|
20
|
+
var query_tiles_js_1 = require("./query-tiles.js");
|
|
21
|
+
Object.defineProperty(exports, "openQueryTiles", { enumerable: true, get: function () { return query_tiles_js_1.openQueryTiles; } });
|
|
22
|
+
Object.defineProperty(exports, "validateTileSource", { enumerable: true, get: function () { return query_tiles_js_1.validateTileSource; } });
|
|
23
|
+
var source_config_js_1 = require("./source-config.js");
|
|
24
|
+
Object.defineProperty(exports, "createReader", { enumerable: true, get: function () { return source_config_js_1.createReader; } });
|
|
25
|
+
var terrarium_js_1 = require("./terrarium.js");
|
|
26
|
+
Object.defineProperty(exports, "readTerrarium", { enumerable: true, get: function () { return terrarium_js_1.readTerrarium; } });
|
|
27
|
+
Object.defineProperty(exports, "terrariumHeight", { enumerable: true, get: function () { return terrarium_js_1.terrariumHeight; } });
|
package/loader.d.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { FeatureCollection } from '@vim3d/geojson';
|
|
2
|
+
import { type TileNode, type TileOrigin, type TilesetManifest } from './manifest.js';
|
|
3
|
+
import { type SourceQuery, type TileSourceReader } from './source.js';
|
|
4
|
+
import { type TileView } from './view.js';
|
|
5
|
+
export interface TileDecodeContext {
|
|
6
|
+
readonly tile: TileNode;
|
|
7
|
+
readonly manifest: TilesetManifest;
|
|
8
|
+
readonly signal: AbortSignal;
|
|
9
|
+
}
|
|
10
|
+
export type TileDecoder<T> = (response: Response, context: TileDecodeContext) => T | Promise<T>;
|
|
11
|
+
export interface LoadedTile<T> {
|
|
12
|
+
readonly tile: TileNode;
|
|
13
|
+
readonly data: T;
|
|
14
|
+
readonly query?: SourceQuery;
|
|
15
|
+
}
|
|
16
|
+
export interface LoaderOptions<T> {
|
|
17
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
18
|
+
readonly maxConcurrent?: number;
|
|
19
|
+
readonly cacheSize?: number;
|
|
20
|
+
readonly onChange?: (visible: readonly LoadedTile<T>[]) => void;
|
|
21
|
+
readonly onEvict?: (entry: LoadedTile<T>) => void;
|
|
22
|
+
readonly onDispose?: () => void;
|
|
23
|
+
readonly onError?: (error: unknown, tile: TileNode) => void;
|
|
24
|
+
}
|
|
25
|
+
export interface TileLoaderOptions<T> extends LoaderOptions<T> {
|
|
26
|
+
readonly decode: TileDecoder<T>;
|
|
27
|
+
}
|
|
28
|
+
export type SourceTileLoaderOptions = LoaderOptions<FeatureCollection>;
|
|
29
|
+
export declare const sourceMode: unique symbol;
|
|
30
|
+
interface SourceMode<T> extends LoaderOptions<T> {
|
|
31
|
+
readonly origin: TileOrigin;
|
|
32
|
+
readonly root?: TileNode;
|
|
33
|
+
readonly plan?: (view: TileView) => readonly {
|
|
34
|
+
tile: TileNode;
|
|
35
|
+
query: SourceQuery;
|
|
36
|
+
}[];
|
|
37
|
+
readonly read: (query: SourceQuery, options: {
|
|
38
|
+
signal: AbortSignal;
|
|
39
|
+
fetch: typeof globalThis.fetch;
|
|
40
|
+
}) => Promise<T>;
|
|
41
|
+
readonly selectVisible: (visible: readonly LoadedTile<T>[]) => readonly LoadedTile<T>[];
|
|
42
|
+
}
|
|
43
|
+
export declare class TileLoader<T> {
|
|
44
|
+
readonly manifest: TilesetManifest;
|
|
45
|
+
private readonly cache;
|
|
46
|
+
private readonly active;
|
|
47
|
+
private readonly failed;
|
|
48
|
+
private readonly maxConcurrent;
|
|
49
|
+
private readonly cacheSize;
|
|
50
|
+
private readonly fetch;
|
|
51
|
+
private readonly options;
|
|
52
|
+
private readonly decode?;
|
|
53
|
+
private readonly source?;
|
|
54
|
+
private queries;
|
|
55
|
+
private plan?;
|
|
56
|
+
private rawVisible;
|
|
57
|
+
private current;
|
|
58
|
+
private disposed;
|
|
59
|
+
constructor(input: unknown, url: string | URL, options: TileLoaderOptions<T>);
|
|
60
|
+
constructor(input: typeof sourceMode, url: undefined, options: SourceMode<T>);
|
|
61
|
+
static fromSource(reader: TileSourceReader, origin: TileOrigin, options?: SourceTileLoaderOptions): TileLoader<FeatureCollection>;
|
|
62
|
+
static open<T>(url: string | URL, options: TileLoaderOptions<T> & {
|
|
63
|
+
readonly signal?: AbortSignal;
|
|
64
|
+
}): Promise<TileLoader<T>>;
|
|
65
|
+
get visible(): readonly LoadedTile<T>[];
|
|
66
|
+
updateView(view: TileView | undefined): void;
|
|
67
|
+
/** Replace the requested WGS84 view or tile bboxes. An empty list clears the view. */
|
|
68
|
+
updateSourceView(queries: readonly SourceQuery[]): void;
|
|
69
|
+
dispose(): void;
|
|
70
|
+
private refresh;
|
|
71
|
+
private request;
|
|
72
|
+
}
|
|
73
|
+
export {};
|
package/loader.js
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TileLoader = exports.sourceMode = void 0;
|
|
4
|
+
const manifest_js_1 = require("./manifest.js");
|
|
5
|
+
const source_js_1 = require("./source.js");
|
|
6
|
+
const view_js_1 = require("./view.js");
|
|
7
|
+
exports.sourceMode = Symbol('source mode');
|
|
8
|
+
function dedupeVisible(visible) {
|
|
9
|
+
const seen = new Set();
|
|
10
|
+
return visible.map(entry => {
|
|
11
|
+
const features = entry.data.features.filter(feature => {
|
|
12
|
+
if (feature.id === undefined)
|
|
13
|
+
return true;
|
|
14
|
+
const key = (0, source_js_1.featureKey)(feature);
|
|
15
|
+
if (seen.has(key))
|
|
16
|
+
return false;
|
|
17
|
+
seen.add(key);
|
|
18
|
+
return true;
|
|
19
|
+
});
|
|
20
|
+
return features.length === entry.data.features.length ? entry : { ...entry, data: { ...entry.data, features } };
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
function count(value, name, minimum) {
|
|
24
|
+
if (!Number.isSafeInteger(value) || value < minimum)
|
|
25
|
+
throw new RangeError(`${name} must be an integer >= ${minimum}`);
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
28
|
+
class TileLoader {
|
|
29
|
+
manifest;
|
|
30
|
+
cache = new Map();
|
|
31
|
+
active = new Map();
|
|
32
|
+
failed = new Set();
|
|
33
|
+
maxConcurrent;
|
|
34
|
+
cacheSize;
|
|
35
|
+
fetch;
|
|
36
|
+
options;
|
|
37
|
+
decode;
|
|
38
|
+
source;
|
|
39
|
+
queries = new Map();
|
|
40
|
+
plan;
|
|
41
|
+
rawVisible = [];
|
|
42
|
+
current = [];
|
|
43
|
+
disposed = false;
|
|
44
|
+
constructor(input, url, options) {
|
|
45
|
+
if (input === exports.sourceMode && 'read' in options) {
|
|
46
|
+
this.manifest = { version: 1, origin: options.origin, root: options.root ?? { id: 'source', bounds: [0, 0, 0, 0, 0, 0], geometricError: 0 } };
|
|
47
|
+
this.source = options;
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
this.manifest = (0, manifest_js_1.parseTilesetManifest)(input, url);
|
|
51
|
+
this.decode = options.decode;
|
|
52
|
+
}
|
|
53
|
+
this.options = options;
|
|
54
|
+
this.maxConcurrent = count(options.maxConcurrent ?? 4, 'maxConcurrent', 1);
|
|
55
|
+
this.cacheSize = count(options.cacheSize ?? 64, 'cacheSize', 0);
|
|
56
|
+
this.fetch = options.fetch ?? source_js_1.defaultFetch;
|
|
57
|
+
}
|
|
58
|
+
static fromSource(reader, origin, options = {}) {
|
|
59
|
+
return new TileLoader(exports.sourceMode, undefined, {
|
|
60
|
+
...options, origin, selectVisible: dedupeVisible,
|
|
61
|
+
async read({ bbox, zoom }, { fetch, signal }) {
|
|
62
|
+
const features = [];
|
|
63
|
+
for await (const batch of reader.query(bbox, { fetch, signal, zoom })) {
|
|
64
|
+
signal.throwIfAborted();
|
|
65
|
+
for (const feature of batch)
|
|
66
|
+
features.push(feature);
|
|
67
|
+
}
|
|
68
|
+
return { type: 'FeatureCollection', features };
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
static async open(url, options) {
|
|
73
|
+
const fetch = options.fetch ?? source_js_1.defaultFetch;
|
|
74
|
+
const response = await fetch(url, { signal: options.signal, headers: { accept: 'application/json' } });
|
|
75
|
+
if (!response.ok)
|
|
76
|
+
throw new Error(`Tileset request failed: ${response.status} (${url})`);
|
|
77
|
+
return new TileLoader(await response.json(), response.url || url, options);
|
|
78
|
+
}
|
|
79
|
+
get visible() {
|
|
80
|
+
return this.current;
|
|
81
|
+
}
|
|
82
|
+
updateView(view) {
|
|
83
|
+
if (this.disposed)
|
|
84
|
+
throw new Error('Tile loader has been disposed');
|
|
85
|
+
if (this.source) {
|
|
86
|
+
if (!this.source.plan)
|
|
87
|
+
throw new Error('Use updateSourceView for a standard source');
|
|
88
|
+
this.queries = new Map((view ? this.source.plan(view) : []).map(request => [request.tile.id, request]));
|
|
89
|
+
}
|
|
90
|
+
else
|
|
91
|
+
this.plan = view && (0, view_js_1.planView)(this.manifest.root, view);
|
|
92
|
+
this.refresh();
|
|
93
|
+
}
|
|
94
|
+
/** Replace the requested WGS84 view or tile bboxes. An empty list clears the view. */
|
|
95
|
+
updateSourceView(queries) {
|
|
96
|
+
if (this.disposed)
|
|
97
|
+
throw new Error('Tile loader has been disposed');
|
|
98
|
+
if (!this.source || this.source.plan)
|
|
99
|
+
throw new Error('updateSourceView requires a standard source');
|
|
100
|
+
const wanted = new Map();
|
|
101
|
+
for (const query of queries) {
|
|
102
|
+
(0, source_js_1.validateQuery)(query?.bbox, query?.zoom);
|
|
103
|
+
const bbox = [...query.bbox];
|
|
104
|
+
const id = JSON.stringify([bbox, query.zoom]);
|
|
105
|
+
const tile = { id, bounds: [0, 0, 0, 0, 0, 0], geometricError: 0 };
|
|
106
|
+
wanted.set(id, { tile, query: { bbox, zoom: query.zoom } });
|
|
107
|
+
}
|
|
108
|
+
this.queries = wanted;
|
|
109
|
+
this.refresh();
|
|
110
|
+
}
|
|
111
|
+
dispose() {
|
|
112
|
+
if (this.disposed)
|
|
113
|
+
return;
|
|
114
|
+
this.disposed = true;
|
|
115
|
+
this.plan = undefined;
|
|
116
|
+
this.queries.clear();
|
|
117
|
+
for (const controller of this.active.values())
|
|
118
|
+
controller.abort();
|
|
119
|
+
this.active.clear();
|
|
120
|
+
this.failed.clear();
|
|
121
|
+
const entries = [...this.cache.values()];
|
|
122
|
+
this.cache.clear();
|
|
123
|
+
this.current = [];
|
|
124
|
+
this.rawVisible = [];
|
|
125
|
+
for (const entry of entries)
|
|
126
|
+
this.options.onEvict?.(entry);
|
|
127
|
+
this.options.onDispose?.();
|
|
128
|
+
}
|
|
129
|
+
refresh() {
|
|
130
|
+
const wanted = new Map();
|
|
131
|
+
const visible = [];
|
|
132
|
+
const useCached = (id) => {
|
|
133
|
+
const loaded = this.cache.get(id);
|
|
134
|
+
if (loaded) {
|
|
135
|
+
this.cache.delete(id);
|
|
136
|
+
this.cache.set(id, loaded);
|
|
137
|
+
}
|
|
138
|
+
return loaded;
|
|
139
|
+
};
|
|
140
|
+
const resolve = (plan) => {
|
|
141
|
+
const start = visible.length;
|
|
142
|
+
let covered = plan.children.length > 0;
|
|
143
|
+
for (const child of plan.children) {
|
|
144
|
+
if (!resolve(child))
|
|
145
|
+
covered = false;
|
|
146
|
+
}
|
|
147
|
+
if (covered)
|
|
148
|
+
return true;
|
|
149
|
+
const { tile } = plan;
|
|
150
|
+
if (!tile.url)
|
|
151
|
+
return false;
|
|
152
|
+
wanted.set(tile.id, plan);
|
|
153
|
+
const loaded = useCached(tile.id);
|
|
154
|
+
if (!loaded)
|
|
155
|
+
return false;
|
|
156
|
+
visible.length = start;
|
|
157
|
+
visible.push(loaded);
|
|
158
|
+
return true;
|
|
159
|
+
};
|
|
160
|
+
if (this.plan)
|
|
161
|
+
resolve(this.plan);
|
|
162
|
+
for (const [id, request] of this.queries) {
|
|
163
|
+
wanted.set(id, { ...request, depth: 0 });
|
|
164
|
+
const loaded = useCached(id);
|
|
165
|
+
if (loaded)
|
|
166
|
+
visible.push(loaded);
|
|
167
|
+
}
|
|
168
|
+
for (const [id, controller] of this.active) {
|
|
169
|
+
if (!wanted.has(id))
|
|
170
|
+
controller.abort();
|
|
171
|
+
}
|
|
172
|
+
for (const id of this.failed) {
|
|
173
|
+
if (!wanted.has(id))
|
|
174
|
+
this.failed.delete(id);
|
|
175
|
+
}
|
|
176
|
+
const evicted = [];
|
|
177
|
+
if (this.cache.size > this.cacheSize) {
|
|
178
|
+
for (const [id, entry] of this.cache) {
|
|
179
|
+
if (!wanted.has(id)) {
|
|
180
|
+
this.cache.delete(id);
|
|
181
|
+
evicted.push(entry);
|
|
182
|
+
}
|
|
183
|
+
if (this.cache.size <= this.cacheSize)
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (this.active.size < this.maxConcurrent) {
|
|
188
|
+
const queue = [...wanted.values()]
|
|
189
|
+
.filter(({ tile }) => !this.cache.has(tile.id) && !this.active.has(tile.id) && !this.failed.has(tile.id))
|
|
190
|
+
.sort((a, b) => a.depth - b.depth);
|
|
191
|
+
for (const { tile, query } of queue) {
|
|
192
|
+
if (this.active.size >= this.maxConcurrent)
|
|
193
|
+
break;
|
|
194
|
+
const controller = new AbortController();
|
|
195
|
+
this.active.set(tile.id, controller);
|
|
196
|
+
void this.request(tile, controller.signal, query);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (visible.length !== this.rawVisible.length || visible.some((entry, i) => entry !== this.rawVisible[i])) {
|
|
200
|
+
this.rawVisible = visible;
|
|
201
|
+
this.current = this.source?.selectVisible(visible) ?? visible;
|
|
202
|
+
this.options.onChange?.(this.current);
|
|
203
|
+
}
|
|
204
|
+
for (const entry of evicted)
|
|
205
|
+
this.options.onEvict?.(entry);
|
|
206
|
+
}
|
|
207
|
+
async request(tile, signal, query) {
|
|
208
|
+
let failure;
|
|
209
|
+
try {
|
|
210
|
+
await Promise.resolve();
|
|
211
|
+
signal.throwIfAborted();
|
|
212
|
+
let data;
|
|
213
|
+
if (query) {
|
|
214
|
+
data = await this.source.read(query, { signal, fetch: this.fetch });
|
|
215
|
+
}
|
|
216
|
+
else {
|
|
217
|
+
const response = await this.fetch(tile.url, { signal });
|
|
218
|
+
signal.throwIfAborted();
|
|
219
|
+
if (!response.ok)
|
|
220
|
+
throw new Error(`Tile request failed: ${response.status} (${tile.url})`);
|
|
221
|
+
data = await this.decode(response, { tile, manifest: this.manifest, signal });
|
|
222
|
+
}
|
|
223
|
+
signal.throwIfAborted();
|
|
224
|
+
this.cache.set(tile.id, { tile, data, ...(query && { query }) });
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
if (!signal.aborted) {
|
|
228
|
+
this.failed.add(tile.id);
|
|
229
|
+
failure = { error };
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (this.disposed)
|
|
233
|
+
return;
|
|
234
|
+
this.active.delete(tile.id);
|
|
235
|
+
this.refresh();
|
|
236
|
+
if (failure && !this.disposed)
|
|
237
|
+
this.options.onError?.(failure.error, tile);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
exports.TileLoader = TileLoader;
|
package/manifest.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export type Vec3 = readonly [number, number, number];
|
|
2
|
+
export type TileBounds = readonly [number, number, number, number, number, number];
|
|
3
|
+
export interface TileOrigin {
|
|
4
|
+
readonly lat: number;
|
|
5
|
+
readonly lon: number;
|
|
6
|
+
readonly elevation: number;
|
|
7
|
+
}
|
|
8
|
+
export interface TileNode {
|
|
9
|
+
readonly id: string;
|
|
10
|
+
readonly bounds: TileBounds;
|
|
11
|
+
readonly geometricError: number;
|
|
12
|
+
readonly url?: string;
|
|
13
|
+
readonly children?: readonly TileNode[];
|
|
14
|
+
}
|
|
15
|
+
export interface TilesetManifest {
|
|
16
|
+
readonly version: 1;
|
|
17
|
+
readonly origin: TileOrigin;
|
|
18
|
+
readonly root: TileNode;
|
|
19
|
+
}
|
|
20
|
+
/** Validates a v1 manifest and resolves payload URLs against its absolute URL. */
|
|
21
|
+
export declare function parseTilesetManifest(input: unknown, manifestUrl: string | URL): TilesetManifest;
|