@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
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { defaultFetch, positiveInteger, sourceReader, sourceURL, withId, } from './source.js';
|
|
2
|
+
async function readPage(url, { fetch = defaultFetch, signal }) {
|
|
3
|
+
signal.throwIfAborted();
|
|
4
|
+
const response = await fetch(url, {
|
|
5
|
+
headers: { accept: 'application/geo+json, application/json' }, redirect: 'error', signal,
|
|
6
|
+
});
|
|
7
|
+
if (!response.ok)
|
|
8
|
+
throw new Error(`Feature page request failed: ${response.status} (${url})`);
|
|
9
|
+
signal.throwIfAborted();
|
|
10
|
+
const page = await response.json();
|
|
11
|
+
signal.throwIfAborted();
|
|
12
|
+
if (page?.type !== 'FeatureCollection' || !Array.isArray(page.features)) {
|
|
13
|
+
throw new Error(`Not a GeoJSON FeatureCollection: ${url}`);
|
|
14
|
+
}
|
|
15
|
+
return page;
|
|
16
|
+
}
|
|
17
|
+
function pageLimits(options, zoom) {
|
|
18
|
+
const cap = typeof options.maxFeatures === 'function' ? options.maxFeatures(zoom) : options.maxFeatures;
|
|
19
|
+
return {
|
|
20
|
+
pageSize: positiveInteger(options.pageSize ?? 1000, 'pageSize'),
|
|
21
|
+
max: positiveInteger(cap ?? 10_000, 'maxFeatures'),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export function ogcApiFeatures(input, options = {}) {
|
|
25
|
+
const endpoint = sourceURL(input);
|
|
26
|
+
return sourceReader(options, async function* (bbox, context, zoom) {
|
|
27
|
+
const { pageSize, max } = pageLimits(options, zoom);
|
|
28
|
+
const properties = typeof options.properties === 'function' ? options.properties(zoom) : options.properties;
|
|
29
|
+
let count = 0;
|
|
30
|
+
const seen = new Set();
|
|
31
|
+
let next = new URL(endpoint);
|
|
32
|
+
next.searchParams.delete('bbox-crs');
|
|
33
|
+
next.searchParams.delete('crs');
|
|
34
|
+
next.searchParams.set('bbox', bbox.join(','));
|
|
35
|
+
next.searchParams.set('limit', String(Math.min(pageSize, max)));
|
|
36
|
+
if (properties) {
|
|
37
|
+
next.searchParams.set('properties', [...new Set([...properties, ...(options.idField ? [options.idField] : [])])].join(','));
|
|
38
|
+
}
|
|
39
|
+
while (next && count < max) {
|
|
40
|
+
if (next.origin !== endpoint.origin || next.pathname !== endpoint.pathname) {
|
|
41
|
+
throw new Error('OGC pagination must stay on the same collection items endpoint');
|
|
42
|
+
}
|
|
43
|
+
const key = next.href;
|
|
44
|
+
if (seen.has(key))
|
|
45
|
+
throw new Error('Repeated OGC pagination link');
|
|
46
|
+
seen.add(key);
|
|
47
|
+
const page = await readPage(next, context);
|
|
48
|
+
const batch = page.features.slice(0, max - count).map(feature => withId(feature, options.idField));
|
|
49
|
+
count += batch.length;
|
|
50
|
+
yield batch;
|
|
51
|
+
const link = page.links?.find(({ rel }) => rel === 'next');
|
|
52
|
+
next = count < max && link ? new URL(link.href, next) : undefined;
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
function polygon([west, south, east, north]) {
|
|
57
|
+
return `POLYGON ((${west} ${south},${east} ${south},${east} ${north},${west} ${north},${west} ${south}))`;
|
|
58
|
+
}
|
|
59
|
+
/** SoQL spatial binding for Socrata .geojson endpoints, including DataSF. */
|
|
60
|
+
export function socrataGeoJSON(input, options = {}) {
|
|
61
|
+
const endpoint = sourceURL(input);
|
|
62
|
+
const geometry = options.geomField ?? 'the_geom';
|
|
63
|
+
if (!/^[a-z_][a-z_\d]*$/i.test(geometry))
|
|
64
|
+
throw new TypeError('Invalid Socrata geometry field');
|
|
65
|
+
if (endpoint.searchParams.has('$query') || endpoint.searchParams.has('$$query')) {
|
|
66
|
+
throw new TypeError('Socrata spatial reads do not accept a full query override');
|
|
67
|
+
}
|
|
68
|
+
const where = endpoint.searchParams.get('$where');
|
|
69
|
+
const order = endpoint.searchParams.get('$order');
|
|
70
|
+
return sourceReader(options, async function* (bbox, context, zoom) {
|
|
71
|
+
const { pageSize, max } = pageLimits(options, zoom);
|
|
72
|
+
const request = new URL(endpoint);
|
|
73
|
+
const intersects = `intersects(${geometry}, '${polygon(bbox)}')`;
|
|
74
|
+
request.searchParams.set('$where', where ? `(${where}) AND ${intersects}` : intersects);
|
|
75
|
+
request.searchParams.set('$order', order ? `${order}, :id` : ':id');
|
|
76
|
+
const properties = typeof options.properties === 'function' ? options.properties(zoom) : options.properties;
|
|
77
|
+
if (properties) {
|
|
78
|
+
request.searchParams.set('$select', [...new Set([geometry, ...properties, ...(options.idField ? [options.idField] : [])])].join(','));
|
|
79
|
+
}
|
|
80
|
+
let offset = 0;
|
|
81
|
+
while (offset < max) {
|
|
82
|
+
const limit = Math.min(pageSize, max - offset);
|
|
83
|
+
request.searchParams.set('$limit', String(limit));
|
|
84
|
+
request.searchParams.set('$offset', String(offset));
|
|
85
|
+
const page = await readPage(new URL(request), context);
|
|
86
|
+
const batch = page.features.slice(0, limit).map(feature => withId(feature, options.idField));
|
|
87
|
+
offset += batch.length;
|
|
88
|
+
yield batch;
|
|
89
|
+
if (batch.length < limit)
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { ByteBuffer } from 'flatbuffers';
|
|
2
|
+
import { readRange, sourceReader, sourceURL, withId } from './source.js';
|
|
3
|
+
async function loadCodec() {
|
|
4
|
+
const { HEADER_MAX_BUFFER_SIZE, magicbytes } = await import('flatgeobuf/lib/mjs/constants.js');
|
|
5
|
+
const { fromByteBuffer } = await import('flatgeobuf/lib/mjs/header-meta.js');
|
|
6
|
+
const { calcTreeSize, streamSearch } = await import('flatgeobuf/lib/mjs/packedrtree.js');
|
|
7
|
+
const { Feature: BinaryFeature } = await import('flatgeobuf/lib/mjs/flat-geobuf/feature.js');
|
|
8
|
+
const { fromFeature } = await import('flatgeobuf/lib/mjs/geojson/feature.js');
|
|
9
|
+
return { HEADER_MAX_BUFFER_SIZE, magicbytes, fromByteBuffer, calcTreeSize, streamSearch, BinaryFeature, fromFeature };
|
|
10
|
+
}
|
|
11
|
+
let codec;
|
|
12
|
+
function isWGS84(crs) {
|
|
13
|
+
if (!crs || !Object.values(crs).some(Boolean) || crs.code === 4326)
|
|
14
|
+
return true;
|
|
15
|
+
if (crs.org?.toUpperCase() === 'OGC' && crs.code_string?.toUpperCase() === 'CRS84')
|
|
16
|
+
return true;
|
|
17
|
+
const wkt = crs.wkt?.trim() ?? '';
|
|
18
|
+
return /^(?:GEOGCS|GEOGCRS|GEODCRS)\s*\[/i.test(wkt)
|
|
19
|
+
&& /,\s*(?:AUTHORITY|ID)\s*\[\s*"OGC"\s*,\s*"CRS84"\s*\]\s*\]$/i.test(wkt);
|
|
20
|
+
}
|
|
21
|
+
/** Read an indexed FlatGeobuf file in WGS84. */
|
|
22
|
+
export function flatGeobuf(input, options = {}) {
|
|
23
|
+
const url = sourceURL(input);
|
|
24
|
+
return sourceReader(options, async function* (bbox, context) {
|
|
25
|
+
const { HEADER_MAX_BUFFER_SIZE, magicbytes, fromByteBuffer, calcTreeSize, streamSearch, BinaryFeature, fromFeature, } = await (codec ??= loadCodec());
|
|
26
|
+
const bytes = async (offset, length) => (await readRange(url, offset, length, context)).data;
|
|
27
|
+
const prefixSize = magicbytes.length + 4;
|
|
28
|
+
const prefix = await bytes(0, prefixSize);
|
|
29
|
+
const magic = new Uint8Array(prefix, 0, magicbytes.length);
|
|
30
|
+
if (!magic.subarray(0, -1).every((byte, i) => byte === magicbytes[i]))
|
|
31
|
+
throw new Error('Not a FlatGeobuf file');
|
|
32
|
+
const headerLength = new DataView(prefix).getUint32(magicbytes.length, true);
|
|
33
|
+
if (headerLength < 8 || headerLength > HEADER_MAX_BUFFER_SIZE)
|
|
34
|
+
throw new Error('Invalid FlatGeobuf header size');
|
|
35
|
+
const headerBytes = new Uint8Array(4 + headerLength);
|
|
36
|
+
headerBytes.set(new Uint8Array(prefix, magicbytes.length));
|
|
37
|
+
headerBytes.set(new Uint8Array(await bytes(prefixSize, headerLength)), 4);
|
|
38
|
+
const header = fromByteBuffer(new ByteBuffer(headerBytes));
|
|
39
|
+
if (header.featuresCount === 0)
|
|
40
|
+
return;
|
|
41
|
+
if (!header.indexNodeSize)
|
|
42
|
+
throw new Error('FlatGeobuf bbox queries require a spatial index');
|
|
43
|
+
if (!isWGS84(header.crs))
|
|
44
|
+
throw new Error('FlatGeobuf bbox queries require WGS84 coordinates');
|
|
45
|
+
const treeOffset = prefixSize + headerLength;
|
|
46
|
+
const featureOffset = treeOffset + calcTreeSize(header.featuresCount, header.indexNodeSize);
|
|
47
|
+
const [minX, minY, maxX, maxY] = bbox;
|
|
48
|
+
for await (const [offset, id] of streamSearch(header.featuresCount, header.indexNodeSize, { minX, minY, maxX, maxY }, (start, size) => bytes(treeOffset + start, size))) {
|
|
49
|
+
const start = featureOffset + offset;
|
|
50
|
+
const prefix = await bytes(start, 4);
|
|
51
|
+
const length = new DataView(prefix).getUint32(0, true);
|
|
52
|
+
const featureBytes = new Uint8Array(4 + length);
|
|
53
|
+
featureBytes.set(new Uint8Array(prefix));
|
|
54
|
+
featureBytes.set(new Uint8Array(await bytes(start + 4, length)), 4);
|
|
55
|
+
const binary = BinaryFeature.getSizePrefixedRootAsFeature(new ByteBuffer(featureBytes));
|
|
56
|
+
yield [withId(fromFeature(id, binary, header), options.idField)];
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
}
|
package/esm/geojson.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { resampleGeoJSON } from '@vim3d/geojson';
|
|
2
|
+
export function geoJSONDecoder(options = {}) {
|
|
3
|
+
return async (response, { tile }) => {
|
|
4
|
+
const data = await response.json();
|
|
5
|
+
if (data?.type !== 'FeatureCollection' || !Array.isArray(data.features)) {
|
|
6
|
+
throw new Error(`Not a GeoJSON FeatureCollection: ${tile.url}`);
|
|
7
|
+
}
|
|
8
|
+
return resampleGeoJSON(data, options);
|
|
9
|
+
};
|
|
10
|
+
}
|
package/esm/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { ElevationSources } from './elevation-source.js';
|
|
2
|
+
export { ogcApiFeatures, socrataGeoJSON } from './feature-api.js';
|
|
3
|
+
export { flatGeobuf } from './flatgeobuf.js';
|
|
4
|
+
export { geoJSONDecoder } from './geojson.js';
|
|
5
|
+
export { TileLoader } from './loader.js';
|
|
6
|
+
export { parseTilesetManifest } from './manifest.js';
|
|
7
|
+
export { pmTiles, PMTilesTileBudgetError } from './pmtiles.js';
|
|
8
|
+
export { openQueryTiles, validateTileSource } from './query-tiles.js';
|
|
9
|
+
export { createReader } from './source-config.js';
|
|
10
|
+
export { readTerrarium, terrariumHeight } from './terrarium.js';
|
package/esm/loader.js
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { parseTilesetManifest } from './manifest.js';
|
|
2
|
+
import { defaultFetch, featureKey, validateQuery } from './source.js';
|
|
3
|
+
import { planView } from './view.js';
|
|
4
|
+
export const sourceMode = Symbol('source mode');
|
|
5
|
+
function dedupeVisible(visible) {
|
|
6
|
+
const seen = new Set();
|
|
7
|
+
return visible.map(entry => {
|
|
8
|
+
const features = entry.data.features.filter(feature => {
|
|
9
|
+
if (feature.id === undefined)
|
|
10
|
+
return true;
|
|
11
|
+
const key = featureKey(feature);
|
|
12
|
+
if (seen.has(key))
|
|
13
|
+
return false;
|
|
14
|
+
seen.add(key);
|
|
15
|
+
return true;
|
|
16
|
+
});
|
|
17
|
+
return features.length === entry.data.features.length ? entry : { ...entry, data: { ...entry.data, features } };
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
function count(value, name, minimum) {
|
|
21
|
+
if (!Number.isSafeInteger(value) || value < minimum)
|
|
22
|
+
throw new RangeError(`${name} must be an integer >= ${minimum}`);
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
export class TileLoader {
|
|
26
|
+
manifest;
|
|
27
|
+
cache = new Map();
|
|
28
|
+
active = new Map();
|
|
29
|
+
failed = new Set();
|
|
30
|
+
maxConcurrent;
|
|
31
|
+
cacheSize;
|
|
32
|
+
fetch;
|
|
33
|
+
options;
|
|
34
|
+
decode;
|
|
35
|
+
source;
|
|
36
|
+
queries = new Map();
|
|
37
|
+
plan;
|
|
38
|
+
rawVisible = [];
|
|
39
|
+
current = [];
|
|
40
|
+
disposed = false;
|
|
41
|
+
constructor(input, url, options) {
|
|
42
|
+
if (input === sourceMode && 'read' in options) {
|
|
43
|
+
this.manifest = { version: 1, origin: options.origin, root: options.root ?? { id: 'source', bounds: [0, 0, 0, 0, 0, 0], geometricError: 0 } };
|
|
44
|
+
this.source = options;
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
this.manifest = parseTilesetManifest(input, url);
|
|
48
|
+
this.decode = options.decode;
|
|
49
|
+
}
|
|
50
|
+
this.options = options;
|
|
51
|
+
this.maxConcurrent = count(options.maxConcurrent ?? 4, 'maxConcurrent', 1);
|
|
52
|
+
this.cacheSize = count(options.cacheSize ?? 64, 'cacheSize', 0);
|
|
53
|
+
this.fetch = options.fetch ?? defaultFetch;
|
|
54
|
+
}
|
|
55
|
+
static fromSource(reader, origin, options = {}) {
|
|
56
|
+
return new TileLoader(sourceMode, undefined, {
|
|
57
|
+
...options, origin, selectVisible: dedupeVisible,
|
|
58
|
+
async read({ bbox, zoom }, { fetch, signal }) {
|
|
59
|
+
const features = [];
|
|
60
|
+
for await (const batch of reader.query(bbox, { fetch, signal, zoom })) {
|
|
61
|
+
signal.throwIfAborted();
|
|
62
|
+
for (const feature of batch)
|
|
63
|
+
features.push(feature);
|
|
64
|
+
}
|
|
65
|
+
return { type: 'FeatureCollection', features };
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
static async open(url, options) {
|
|
70
|
+
const fetch = options.fetch ?? defaultFetch;
|
|
71
|
+
const response = await fetch(url, { signal: options.signal, headers: { accept: 'application/json' } });
|
|
72
|
+
if (!response.ok)
|
|
73
|
+
throw new Error(`Tileset request failed: ${response.status} (${url})`);
|
|
74
|
+
return new TileLoader(await response.json(), response.url || url, options);
|
|
75
|
+
}
|
|
76
|
+
get visible() {
|
|
77
|
+
return this.current;
|
|
78
|
+
}
|
|
79
|
+
updateView(view) {
|
|
80
|
+
if (this.disposed)
|
|
81
|
+
throw new Error('Tile loader has been disposed');
|
|
82
|
+
if (this.source) {
|
|
83
|
+
if (!this.source.plan)
|
|
84
|
+
throw new Error('Use updateSourceView for a standard source');
|
|
85
|
+
this.queries = new Map((view ? this.source.plan(view) : []).map(request => [request.tile.id, request]));
|
|
86
|
+
}
|
|
87
|
+
else
|
|
88
|
+
this.plan = view && planView(this.manifest.root, view);
|
|
89
|
+
this.refresh();
|
|
90
|
+
}
|
|
91
|
+
/** Replace the requested WGS84 view or tile bboxes. An empty list clears the view. */
|
|
92
|
+
updateSourceView(queries) {
|
|
93
|
+
if (this.disposed)
|
|
94
|
+
throw new Error('Tile loader has been disposed');
|
|
95
|
+
if (!this.source || this.source.plan)
|
|
96
|
+
throw new Error('updateSourceView requires a standard source');
|
|
97
|
+
const wanted = new Map();
|
|
98
|
+
for (const query of queries) {
|
|
99
|
+
validateQuery(query?.bbox, query?.zoom);
|
|
100
|
+
const bbox = [...query.bbox];
|
|
101
|
+
const id = JSON.stringify([bbox, query.zoom]);
|
|
102
|
+
const tile = { id, bounds: [0, 0, 0, 0, 0, 0], geometricError: 0 };
|
|
103
|
+
wanted.set(id, { tile, query: { bbox, zoom: query.zoom } });
|
|
104
|
+
}
|
|
105
|
+
this.queries = wanted;
|
|
106
|
+
this.refresh();
|
|
107
|
+
}
|
|
108
|
+
dispose() {
|
|
109
|
+
if (this.disposed)
|
|
110
|
+
return;
|
|
111
|
+
this.disposed = true;
|
|
112
|
+
this.plan = undefined;
|
|
113
|
+
this.queries.clear();
|
|
114
|
+
for (const controller of this.active.values())
|
|
115
|
+
controller.abort();
|
|
116
|
+
this.active.clear();
|
|
117
|
+
this.failed.clear();
|
|
118
|
+
const entries = [...this.cache.values()];
|
|
119
|
+
this.cache.clear();
|
|
120
|
+
this.current = [];
|
|
121
|
+
this.rawVisible = [];
|
|
122
|
+
for (const entry of entries)
|
|
123
|
+
this.options.onEvict?.(entry);
|
|
124
|
+
this.options.onDispose?.();
|
|
125
|
+
}
|
|
126
|
+
refresh() {
|
|
127
|
+
const wanted = new Map();
|
|
128
|
+
const visible = [];
|
|
129
|
+
const useCached = (id) => {
|
|
130
|
+
const loaded = this.cache.get(id);
|
|
131
|
+
if (loaded) {
|
|
132
|
+
this.cache.delete(id);
|
|
133
|
+
this.cache.set(id, loaded);
|
|
134
|
+
}
|
|
135
|
+
return loaded;
|
|
136
|
+
};
|
|
137
|
+
const resolve = (plan) => {
|
|
138
|
+
const start = visible.length;
|
|
139
|
+
let covered = plan.children.length > 0;
|
|
140
|
+
for (const child of plan.children) {
|
|
141
|
+
if (!resolve(child))
|
|
142
|
+
covered = false;
|
|
143
|
+
}
|
|
144
|
+
if (covered)
|
|
145
|
+
return true;
|
|
146
|
+
const { tile } = plan;
|
|
147
|
+
if (!tile.url)
|
|
148
|
+
return false;
|
|
149
|
+
wanted.set(tile.id, plan);
|
|
150
|
+
const loaded = useCached(tile.id);
|
|
151
|
+
if (!loaded)
|
|
152
|
+
return false;
|
|
153
|
+
visible.length = start;
|
|
154
|
+
visible.push(loaded);
|
|
155
|
+
return true;
|
|
156
|
+
};
|
|
157
|
+
if (this.plan)
|
|
158
|
+
resolve(this.plan);
|
|
159
|
+
for (const [id, request] of this.queries) {
|
|
160
|
+
wanted.set(id, { ...request, depth: 0 });
|
|
161
|
+
const loaded = useCached(id);
|
|
162
|
+
if (loaded)
|
|
163
|
+
visible.push(loaded);
|
|
164
|
+
}
|
|
165
|
+
for (const [id, controller] of this.active) {
|
|
166
|
+
if (!wanted.has(id))
|
|
167
|
+
controller.abort();
|
|
168
|
+
}
|
|
169
|
+
for (const id of this.failed) {
|
|
170
|
+
if (!wanted.has(id))
|
|
171
|
+
this.failed.delete(id);
|
|
172
|
+
}
|
|
173
|
+
const evicted = [];
|
|
174
|
+
if (this.cache.size > this.cacheSize) {
|
|
175
|
+
for (const [id, entry] of this.cache) {
|
|
176
|
+
if (!wanted.has(id)) {
|
|
177
|
+
this.cache.delete(id);
|
|
178
|
+
evicted.push(entry);
|
|
179
|
+
}
|
|
180
|
+
if (this.cache.size <= this.cacheSize)
|
|
181
|
+
break;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (this.active.size < this.maxConcurrent) {
|
|
185
|
+
const queue = [...wanted.values()]
|
|
186
|
+
.filter(({ tile }) => !this.cache.has(tile.id) && !this.active.has(tile.id) && !this.failed.has(tile.id))
|
|
187
|
+
.sort((a, b) => a.depth - b.depth);
|
|
188
|
+
for (const { tile, query } of queue) {
|
|
189
|
+
if (this.active.size >= this.maxConcurrent)
|
|
190
|
+
break;
|
|
191
|
+
const controller = new AbortController();
|
|
192
|
+
this.active.set(tile.id, controller);
|
|
193
|
+
void this.request(tile, controller.signal, query);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (visible.length !== this.rawVisible.length || visible.some((entry, i) => entry !== this.rawVisible[i])) {
|
|
197
|
+
this.rawVisible = visible;
|
|
198
|
+
this.current = this.source?.selectVisible(visible) ?? visible;
|
|
199
|
+
this.options.onChange?.(this.current);
|
|
200
|
+
}
|
|
201
|
+
for (const entry of evicted)
|
|
202
|
+
this.options.onEvict?.(entry);
|
|
203
|
+
}
|
|
204
|
+
async request(tile, signal, query) {
|
|
205
|
+
let failure;
|
|
206
|
+
try {
|
|
207
|
+
await Promise.resolve();
|
|
208
|
+
signal.throwIfAborted();
|
|
209
|
+
let data;
|
|
210
|
+
if (query) {
|
|
211
|
+
data = await this.source.read(query, { signal, fetch: this.fetch });
|
|
212
|
+
}
|
|
213
|
+
else {
|
|
214
|
+
const response = await this.fetch(tile.url, { signal });
|
|
215
|
+
signal.throwIfAborted();
|
|
216
|
+
if (!response.ok)
|
|
217
|
+
throw new Error(`Tile request failed: ${response.status} (${tile.url})`);
|
|
218
|
+
data = await this.decode(response, { tile, manifest: this.manifest, signal });
|
|
219
|
+
}
|
|
220
|
+
signal.throwIfAborted();
|
|
221
|
+
this.cache.set(tile.id, { tile, data, ...(query && { query }) });
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
if (!signal.aborted) {
|
|
225
|
+
this.failed.add(tile.id);
|
|
226
|
+
failure = { error };
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
if (this.disposed)
|
|
230
|
+
return;
|
|
231
|
+
this.active.delete(tile.id);
|
|
232
|
+
this.refresh();
|
|
233
|
+
if (failure && !this.disposed)
|
|
234
|
+
this.options.onError?.(failure.error, tile);
|
|
235
|
+
}
|
|
236
|
+
}
|
package/esm/manifest.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
function fail(path, reason) {
|
|
2
|
+
throw new TypeError(`Invalid tileset manifest at ${path}: ${reason}`);
|
|
3
|
+
}
|
|
4
|
+
function record(value, path) {
|
|
5
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
6
|
+
fail(path, 'expected an object');
|
|
7
|
+
return value;
|
|
8
|
+
}
|
|
9
|
+
function number(value, path) {
|
|
10
|
+
if (typeof value !== 'number' || !Number.isFinite(value))
|
|
11
|
+
fail(path, 'expected a finite number');
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
function httpURL(value, path, base) {
|
|
15
|
+
let url;
|
|
16
|
+
try {
|
|
17
|
+
url = new URL(value, base);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
fail(path, 'expected a valid URL');
|
|
21
|
+
}
|
|
22
|
+
if (url.protocol !== 'https:' && url.protocol !== 'http:')
|
|
23
|
+
fail(path, 'expected an HTTP(S) URL');
|
|
24
|
+
return url;
|
|
25
|
+
}
|
|
26
|
+
/** Validates a v1 manifest and resolves payload URLs against its absolute URL. */
|
|
27
|
+
export function parseTilesetManifest(input, manifestUrl) {
|
|
28
|
+
const base = httpURL(String(manifestUrl), 'manifest URL');
|
|
29
|
+
const manifest = record(input, '$');
|
|
30
|
+
if (manifest.version !== 1)
|
|
31
|
+
fail('version', 'expected 1');
|
|
32
|
+
const origin = record(manifest.origin, 'origin');
|
|
33
|
+
const lat = number(origin.lat, 'origin.lat');
|
|
34
|
+
const lon = number(origin.lon, 'origin.lon');
|
|
35
|
+
const elevation = number(origin.elevation, 'origin.elevation');
|
|
36
|
+
if (Math.abs(lat) > 90)
|
|
37
|
+
fail('origin.lat', 'expected latitude in [-90, 90]');
|
|
38
|
+
if (Math.abs(lon) > 180)
|
|
39
|
+
fail('origin.lon', 'expected longitude in [-180, 180]');
|
|
40
|
+
const ids = new Set();
|
|
41
|
+
function readTile(value, path, parent) {
|
|
42
|
+
const node = record(value, path);
|
|
43
|
+
const { id } = node;
|
|
44
|
+
if (typeof id !== 'string' || !id.trim())
|
|
45
|
+
fail(`${path}.id`, 'expected a nonempty string');
|
|
46
|
+
if (ids.has(id))
|
|
47
|
+
fail(`${path}.id`, `duplicate tile ID ${id}`);
|
|
48
|
+
ids.add(id);
|
|
49
|
+
const raw = node.bounds;
|
|
50
|
+
if (!Array.isArray(raw) || raw.length !== 6)
|
|
51
|
+
fail(`${path}.bounds`, 'expected six coordinates');
|
|
52
|
+
const coords = Array.from(raw, (coord, i) => number(coord, `${path}.bounds[${i}]`));
|
|
53
|
+
const bounds = [coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]];
|
|
54
|
+
for (let axis = 0; axis < 3; axis++) {
|
|
55
|
+
if (bounds[axis] > bounds[axis + 3])
|
|
56
|
+
fail(`${path}.bounds`, 'minimum exceeds maximum');
|
|
57
|
+
if (parent && (bounds[axis] < parent.bounds[axis] || bounds[axis + 3] > parent.bounds[axis + 3])) {
|
|
58
|
+
fail(`${path}.bounds`, 'child bounds must fit inside parent bounds');
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const geometricError = number(node.geometricError, `${path}.geometricError`);
|
|
62
|
+
if (geometricError < 0 || (parent && geometricError > parent.geometricError)) {
|
|
63
|
+
fail(`${path}.geometricError`, 'must be nonnegative and no greater than the parent error');
|
|
64
|
+
}
|
|
65
|
+
let url;
|
|
66
|
+
if (node.url !== undefined) {
|
|
67
|
+
if (typeof node.url !== 'string' || !node.url.trim())
|
|
68
|
+
fail(`${path}.url`, 'expected a nonempty string');
|
|
69
|
+
url = httpURL(node.url, `${path}.url`, base).href;
|
|
70
|
+
}
|
|
71
|
+
const tile = { id, bounds, geometricError, ...(url && { url }) };
|
|
72
|
+
const { children } = node;
|
|
73
|
+
if (children === undefined || (Array.isArray(children) && children.length === 0)) {
|
|
74
|
+
if (!url)
|
|
75
|
+
fail(path, 'a leaf must have a payload URL');
|
|
76
|
+
return tile;
|
|
77
|
+
}
|
|
78
|
+
if (!Array.isArray(children) || children.length > 4)
|
|
79
|
+
fail(`${path}.children`, 'expected up to four children');
|
|
80
|
+
return { ...tile, children: Array.from(children, (child, i) => readTile(child, `${path}.children[${i}]`, tile)) };
|
|
81
|
+
}
|
|
82
|
+
return { version: 1, origin: { lat, lon, elevation }, root: readTile(manifest.root, 'root') };
|
|
83
|
+
}
|
package/esm/package.json
ADDED
package/esm/pmtiles.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { bytesToHeader, EtagMismatch, PMTiles, TileType } from 'pmtiles';
|
|
2
|
+
import { featureKey, positiveInteger, readRange, sourceReader, sourceURL, withId, } from './source.js';
|
|
3
|
+
export class PMTilesTileBudgetError extends RangeError {
|
|
4
|
+
constructor() {
|
|
5
|
+
super('PMTiles query exceeds maxTiles');
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
function tileY(lat, size) {
|
|
9
|
+
const clamped = Math.max(-85.0511287798066, Math.min(85.0511287798066, lat));
|
|
10
|
+
return size * (1 - Math.asinh(Math.tan(clamped * Math.PI / 180)) / Math.PI) / 2;
|
|
11
|
+
}
|
|
12
|
+
function bboxZoom([west, south, east, north]) {
|
|
13
|
+
return Math.floor(-Math.log2(Math.max((east - west) / 360, tileY(south, 1) - tileY(north, 1))));
|
|
14
|
+
}
|
|
15
|
+
/** Read the MVT tiles overlapping a WGS84 bbox in a PMTiles v3 archive. */
|
|
16
|
+
export function pmTiles(input, options = {}) {
|
|
17
|
+
const url = sourceURL(input);
|
|
18
|
+
const maxTiles = positiveInteger(options.maxTiles ?? 64, 'maxTiles');
|
|
19
|
+
return sourceReader(options, async function* (bbox, context, requestedZoom) {
|
|
20
|
+
const source = {
|
|
21
|
+
getKey: () => url.href,
|
|
22
|
+
getBytes: async (offset, length, _signal, etag) => {
|
|
23
|
+
// The library asks for a 16 KiB bootstrap, which can include tile payloads.
|
|
24
|
+
// Supply just the header and root directory within that bootstrap instead.
|
|
25
|
+
if (offset === 0 && length === 16_384) {
|
|
26
|
+
const header = await readRange(url, 0, 127, context);
|
|
27
|
+
const { specVersion, rootDirectoryOffset: start, rootDirectoryLength: size, } = bytesToHeader(header.data, header.etag);
|
|
28
|
+
if (specVersion !== 3)
|
|
29
|
+
throw new Error('Expected a PMTiles v3 archive');
|
|
30
|
+
if (start < 127 || size < 1 || start + size > length)
|
|
31
|
+
throw new Error('Invalid PMTiles root directory span');
|
|
32
|
+
const root = await readRange(url, start, size, context);
|
|
33
|
+
if (root.etag !== header.etag)
|
|
34
|
+
throw new EtagMismatch();
|
|
35
|
+
const bytes = new Uint8Array(start + size);
|
|
36
|
+
bytes.set(new Uint8Array(header.data));
|
|
37
|
+
bytes.set(new Uint8Array(root.data), start);
|
|
38
|
+
return { data: bytes.buffer, etag: header.etag };
|
|
39
|
+
}
|
|
40
|
+
const range = await readRange(url, offset, length, context);
|
|
41
|
+
if (etag !== undefined && range.etag !== etag)
|
|
42
|
+
throw new EtagMismatch();
|
|
43
|
+
return range;
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
const archive = new PMTiles(source);
|
|
47
|
+
const header = await archive.getHeader();
|
|
48
|
+
if (header.tileType !== TileType.Mvt)
|
|
49
|
+
throw new Error('PMTiles source must contain MVT vector tiles');
|
|
50
|
+
if (header.minZoom > header.maxZoom || header.maxZoom > 26)
|
|
51
|
+
throw new Error('Invalid PMTiles zoom range');
|
|
52
|
+
const zoom = Math.max(header.minZoom, Math.min(header.maxZoom, Math.floor(requestedZoom)));
|
|
53
|
+
const size = 2 ** zoom;
|
|
54
|
+
const [west, south, east, north] = bbox;
|
|
55
|
+
const clip = (i) => Math.max(0, Math.min(size - 1, i));
|
|
56
|
+
if (south >= 85.0511287798066 || north <= -85.0511287798066)
|
|
57
|
+
return;
|
|
58
|
+
const x0 = clip(Math.floor((west + 180) / 360 * size));
|
|
59
|
+
const x1 = clip(Math.ceil((east + 180) / 360 * size) - 1);
|
|
60
|
+
const y0 = clip(Math.floor(tileY(north, size)));
|
|
61
|
+
const y1 = clip(Math.ceil(tileY(south, size)) - 1);
|
|
62
|
+
if ((x1 - x0 + 1) * (y1 - y0 + 1) > maxTiles)
|
|
63
|
+
throw new PMTilesTileBudgetError();
|
|
64
|
+
const layers = typeof options.layers === 'function' ? options.layers(zoom) : options.layers;
|
|
65
|
+
const [{ VectorTile }, { default: Pbf }] = await Promise.all([import('@mapbox/vector-tile'), import('pbf')]);
|
|
66
|
+
const seen = new Set();
|
|
67
|
+
for (let x = x0; x <= x1; x++) {
|
|
68
|
+
for (let y = y0; y <= y1; y++) {
|
|
69
|
+
const response = await archive.getZxy(zoom, x, y, context.signal);
|
|
70
|
+
context.signal.throwIfAborted();
|
|
71
|
+
if (!response)
|
|
72
|
+
continue;
|
|
73
|
+
const tile = new VectorTile(new Pbf(response.data));
|
|
74
|
+
const features = [];
|
|
75
|
+
for (const [name, layer] of Object.entries(tile.layers)) {
|
|
76
|
+
if (layers && !layers.includes(name))
|
|
77
|
+
continue;
|
|
78
|
+
for (let i = 0; i < layer.length; i++) {
|
|
79
|
+
const feature = withId(layer.feature(i).toGeoJSON(x, y, zoom), options.idField);
|
|
80
|
+
feature.id = JSON.stringify([name, feature.id]);
|
|
81
|
+
if (!options.keepTileFragments) {
|
|
82
|
+
const key = featureKey(feature);
|
|
83
|
+
if (seen.has(key))
|
|
84
|
+
continue;
|
|
85
|
+
seen.add(key);
|
|
86
|
+
}
|
|
87
|
+
features.push(feature);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
yield features;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}, bboxZoom);
|
|
94
|
+
}
|