@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,140 @@
|
|
|
1
|
+
import { geodeticToScene } from '@vim3d/core';
|
|
2
|
+
import { sourceMode, TileLoader } from './loader.js';
|
|
3
|
+
import { featureKey, withId } from './source.js';
|
|
4
|
+
import { intersects, screenSpaceError } from './view.js';
|
|
5
|
+
const radians = Math.PI / 180;
|
|
6
|
+
function boundedInteger(value, name, min, max = Number.MAX_SAFE_INTEGER) {
|
|
7
|
+
if (!Number.isSafeInteger(value) || value < min || value > max)
|
|
8
|
+
throw new RangeError(`Invalid ${name}`);
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
11
|
+
export function validateTileSource(config) {
|
|
12
|
+
const candidate = config;
|
|
13
|
+
if (!candidate || !['flatgeobuf', 'pmtiles', 'ogc-features', 'socrata'].includes(candidate.kind)) {
|
|
14
|
+
throw new TypeError('Invalid tile source kind');
|
|
15
|
+
}
|
|
16
|
+
if (typeof candidate.url !== 'string' || !['http:', 'https:'].includes(new URL(candidate.url).protocol)) {
|
|
17
|
+
throw new TypeError('Expected an HTTP(S) tile source URL');
|
|
18
|
+
}
|
|
19
|
+
const { bounds, origin, elevationBounds } = candidate;
|
|
20
|
+
const minZoom = boundedInteger(candidate.minZoom ?? 1, 'minZoom', 1, 24);
|
|
21
|
+
boundedInteger(candidate.maxZoom ?? 16, 'maxZoom', minZoom, 24);
|
|
22
|
+
const [w, s, e, n] = Array.isArray(bounds) ? bounds : [];
|
|
23
|
+
if (!Array.isArray(bounds) || bounds.length !== 4 || !bounds.every(Number.isFinite) ||
|
|
24
|
+
w < -180 || e > 180 || s < -90 || n > 90 || w >= e || s >= n)
|
|
25
|
+
throw new RangeError('Invalid tile source bounds');
|
|
26
|
+
if (!origin || ![origin.lat, origin.lon, origin.elevation].every(Number.isFinite) ||
|
|
27
|
+
Math.abs(origin.lat) > 90 || Math.abs(origin.lon) > 180)
|
|
28
|
+
throw new RangeError('Invalid tile source origin');
|
|
29
|
+
if (elevationBounds !== undefined && (!Array.isArray(elevationBounds) || elevationBounds.length !== 2 ||
|
|
30
|
+
!elevationBounds.every(Number.isFinite) || elevationBounds[0] > elevationBounds[1])) {
|
|
31
|
+
throw new RangeError('Invalid tile source elevationBounds');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export function openQueryTiles(config, reader, options = {}) {
|
|
35
|
+
validateTileSource(config);
|
|
36
|
+
const minZoom = boundedInteger(config.minZoom ?? 1, 'minZoom', 1, 24);
|
|
37
|
+
const maxZoom = boundedInteger(config.maxZoom ?? 16, 'maxZoom', minZoom, 24);
|
|
38
|
+
const maxTiles = boundedInteger(options.maxVisibleTiles ?? 64, 'maxVisibleTiles', 1);
|
|
39
|
+
const maxFeatures = boundedInteger(options.maxFeaturesPerTile ?? 10_000, 'maxFeaturesPerTile', 1);
|
|
40
|
+
const { origin } = config;
|
|
41
|
+
const [minElevation, maxElevation] = config.elevationBounds ?? [origin.elevation - 100, origin.elevation + 1000];
|
|
42
|
+
const sourceId = config.url;
|
|
43
|
+
const attribution = config.attribution ?? reader.attribution;
|
|
44
|
+
function cell(bbox, id, zoom) {
|
|
45
|
+
const [w, s, e, n] = bbox;
|
|
46
|
+
const lonMid = (w + e) / 2, latMid = (s + n) / 2;
|
|
47
|
+
const samples = [[w, s], [w, n], [e, s], [e, n],
|
|
48
|
+
[lonMid, s], [lonMid, n], [w, latMid], [e, latMid]];
|
|
49
|
+
const points = samples.flatMap(([lon, lat]) => [
|
|
50
|
+
geodeticToScene(origin, lat, lon, minElevation),
|
|
51
|
+
geodeticToScene(origin, lat, lon, maxElevation),
|
|
52
|
+
]);
|
|
53
|
+
// Bound curvature between projected samples.
|
|
54
|
+
const span = radians * Math.hypot(e - w, n - s);
|
|
55
|
+
const padding = (7_000_000 + Math.max(Math.abs(minElevation), Math.abs(maxElevation))) * span * span / 4;
|
|
56
|
+
const [xs, ys, zs] = [0, 1, 2].map(axis => points.map(point => point[axis]));
|
|
57
|
+
const bounds = [Math.min(...xs) - padding, Math.min(...ys) - padding, Math.min(...zs) - padding,
|
|
58
|
+
Math.max(...xs) + padding, Math.max(...ys) + padding, Math.max(...zs) + padding];
|
|
59
|
+
return { id, bbox, zoom, bounds, geometricError: span * 6_378_137 / 8 };
|
|
60
|
+
}
|
|
61
|
+
const [west, south, east, north] = config.bounds;
|
|
62
|
+
const baseZoom = Math.max(0, Math.min(maxZoom - 1, Math.floor(Math.log2(360 / Math.max(east - west, north - south)))));
|
|
63
|
+
const root = cell(config.bounds, 'r', baseZoom);
|
|
64
|
+
function plan(view) {
|
|
65
|
+
const bounds = root.bounds;
|
|
66
|
+
const coversExtent = view.frustum.every(([a, b, c, d]) => a * bounds[a < 0 ? 3 : 0] + b * bounds[b < 0 ? 4 : 1] + c * bounds[c < 0 ? 5 : 2] + d >= 0);
|
|
67
|
+
if (coversExtent || screenSpaceError(root, view.projection) <= view.maxScreenSpaceError)
|
|
68
|
+
return [];
|
|
69
|
+
const firstQueryZoom = Math.max(minZoom, baseZoom + 1);
|
|
70
|
+
for (let zoomLimit = maxZoom; zoomLimit >= firstQueryZoom; zoomLimit--) {
|
|
71
|
+
const selected = [];
|
|
72
|
+
let visited = 0;
|
|
73
|
+
let overBudget = false;
|
|
74
|
+
function visit(tile) {
|
|
75
|
+
if (overBudget || !intersects(tile.bounds, view.frustum))
|
|
76
|
+
return;
|
|
77
|
+
if (++visited > maxTiles * (zoomLimit - baseZoom + 1) * 4) {
|
|
78
|
+
overBudget = true;
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const error = screenSpaceError(tile, view.projection);
|
|
82
|
+
const refine = error > view.maxScreenSpaceError;
|
|
83
|
+
if (tile.zoom <= firstQueryZoom && error < view.maxScreenSpaceError)
|
|
84
|
+
return;
|
|
85
|
+
if (tile.zoom >= firstQueryZoom && (!refine || tile.zoom === zoomLimit)) {
|
|
86
|
+
if (selected.length === maxTiles)
|
|
87
|
+
overBudget = true;
|
|
88
|
+
else
|
|
89
|
+
selected.push(tile);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
const [w, s, e, n] = tile.bbox;
|
|
93
|
+
const x = (w + e) / 2, y = (s + n) / 2;
|
|
94
|
+
if (x === w || x === e || y === s || y === n)
|
|
95
|
+
return;
|
|
96
|
+
const boxes = [[w, s, x, y], [x, s, e, y], [w, y, x, n], [x, y, e, n]];
|
|
97
|
+
for (const [i, box] of boxes.entries())
|
|
98
|
+
visit(cell(box, tile.id + i, tile.zoom + 1));
|
|
99
|
+
}
|
|
100
|
+
visit(root);
|
|
101
|
+
if (!overBudget)
|
|
102
|
+
return selected;
|
|
103
|
+
}
|
|
104
|
+
return [];
|
|
105
|
+
}
|
|
106
|
+
return new TileLoader(sourceMode, undefined, {
|
|
107
|
+
...options, origin, root,
|
|
108
|
+
plan: view => plan(view).map(tile => ({ tile, query: { bbox: tile.bbox, zoom: tile.zoom } })),
|
|
109
|
+
selectVisible: visible => visible,
|
|
110
|
+
async read({ bbox, zoom = minZoom }, { signal, fetch }) {
|
|
111
|
+
const features = [];
|
|
112
|
+
const seen = new Set();
|
|
113
|
+
let count = 0;
|
|
114
|
+
for await (const page of reader.query(bbox, { signal, zoom, fetch })) {
|
|
115
|
+
signal.throwIfAborted();
|
|
116
|
+
for (const feature of page) {
|
|
117
|
+
count++;
|
|
118
|
+
const propertyId = config.idField ? feature.properties?.[config.idField] : undefined;
|
|
119
|
+
const identified = feature.id === undefined
|
|
120
|
+
&& ((typeof propertyId === 'string' && propertyId.trim()) || Number.isFinite(propertyId))
|
|
121
|
+
? withId(feature, config.idField) : feature;
|
|
122
|
+
if (identified.id !== undefined) {
|
|
123
|
+
const key = featureKey(identified);
|
|
124
|
+
if (!seen.has(key)) {
|
|
125
|
+
seen.add(key);
|
|
126
|
+
features.push(identified);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
else
|
|
130
|
+
features.push(identified);
|
|
131
|
+
if (count === maxFeatures)
|
|
132
|
+
break;
|
|
133
|
+
}
|
|
134
|
+
if (count === maxFeatures)
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
return { type: 'FeatureCollection', features, bbox, zoom, sourceId, attribution };
|
|
138
|
+
},
|
|
139
|
+
});
|
|
140
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ogcApiFeatures, socrataGeoJSON } from './feature-api.js';
|
|
2
|
+
import { flatGeobuf } from './flatgeobuf.js';
|
|
3
|
+
import { pmTiles } from './pmtiles.js';
|
|
4
|
+
export function createReader(config) {
|
|
5
|
+
switch (config.kind) {
|
|
6
|
+
case 'flatgeobuf': return flatGeobuf(config.url, config);
|
|
7
|
+
case 'pmtiles': return pmTiles(config.url, config);
|
|
8
|
+
case 'ogc-features': return ogcApiFeatures(config.url, config);
|
|
9
|
+
case 'socrata': return socrataGeoJSON(config.url, config);
|
|
10
|
+
default: throw new TypeError('Unknown tile source kind');
|
|
11
|
+
}
|
|
12
|
+
}
|
package/esm/source.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { createFetch, isLocalhostSubdomain } from '@constructive-io/fetch';
|
|
2
|
+
export const defaultFetch = (input, init) => {
|
|
3
|
+
// The Node localhost shim buffers the body before exposing the status.
|
|
4
|
+
if (input instanceof URL && isLocalhostSubdomain(input.hostname) && new Headers(init?.headers).has('range')) {
|
|
5
|
+
return globalThis.fetch(input, init);
|
|
6
|
+
}
|
|
7
|
+
return createFetch()(input, init);
|
|
8
|
+
};
|
|
9
|
+
export function sourceURL(input) {
|
|
10
|
+
const url = new URL(input);
|
|
11
|
+
if (!['http:', 'https:'].includes(url.protocol))
|
|
12
|
+
throw new TypeError('Expected an HTTP(S) source URL');
|
|
13
|
+
return url;
|
|
14
|
+
}
|
|
15
|
+
export function validateQuery(bbox, zoom) {
|
|
16
|
+
if (!Array.isArray(bbox) || bbox.length !== 4 || !Array.from(bbox).every(Number.isFinite)
|
|
17
|
+
|| bbox[0] < -180 || bbox[2] > 180 || bbox[1] < -90 || bbox[3] > 90
|
|
18
|
+
|| bbox[0] >= bbox[2] || bbox[1] >= bbox[3]) {
|
|
19
|
+
throw new RangeError('Expected a nonempty WGS84 bbox');
|
|
20
|
+
}
|
|
21
|
+
if (zoom !== undefined && !Number.isFinite(zoom))
|
|
22
|
+
throw new RangeError('Expected a finite source zoom');
|
|
23
|
+
}
|
|
24
|
+
export function positiveInteger(value, name) {
|
|
25
|
+
if (!Number.isSafeInteger(value) || value < 1)
|
|
26
|
+
throw new RangeError(`${name} must be a positive integer`);
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
function isFeatureId(value) {
|
|
30
|
+
return (typeof value === 'string' && value.trim().length > 0)
|
|
31
|
+
|| (typeof value === 'number' && Number.isFinite(value));
|
|
32
|
+
}
|
|
33
|
+
const propertyIds = new WeakSet();
|
|
34
|
+
export function withId(feature, field) {
|
|
35
|
+
const preferred = field === undefined ? undefined : feature.properties?.[field];
|
|
36
|
+
const usesProperty = isFeatureId(preferred);
|
|
37
|
+
const id = usesProperty ? preferred : feature.id;
|
|
38
|
+
if (!isFeatureId(id)) {
|
|
39
|
+
throw new Error('Feature has no stable ID; configure idField or use a source with feature IDs');
|
|
40
|
+
}
|
|
41
|
+
const identified = { ...feature, id };
|
|
42
|
+
if (usesProperty)
|
|
43
|
+
propertyIds.add(identified);
|
|
44
|
+
return identified;
|
|
45
|
+
}
|
|
46
|
+
export function featureKey(feature) {
|
|
47
|
+
return JSON.stringify([propertyIds.has(feature) ? 'property' : 'feature', feature.id]);
|
|
48
|
+
}
|
|
49
|
+
export function sourceReader(options, read, defaultZoom = () => 0) {
|
|
50
|
+
const { attribution, minZoom = 0, maxZoom = Infinity } = options;
|
|
51
|
+
if (!Number.isSafeInteger(minZoom) || minZoom < 0
|
|
52
|
+
|| (options.maxZoom !== undefined && (!Number.isSafeInteger(maxZoom) || maxZoom < minZoom))) {
|
|
53
|
+
throw new RangeError('Invalid source zoom range');
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
attribution,
|
|
57
|
+
async *query(bbox, context) {
|
|
58
|
+
validateQuery(bbox, context.zoom);
|
|
59
|
+
context.signal.throwIfAborted();
|
|
60
|
+
const zoom = Math.max(minZoom, Math.min(maxZoom, context.zoom ?? defaultZoom(bbox)));
|
|
61
|
+
yield* read(bbox, context, zoom);
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
export async function readRange(url, offset, length, { fetch = defaultFetch, signal }) {
|
|
66
|
+
const end = offset + length - 1;
|
|
67
|
+
if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(end) || length < 1) {
|
|
68
|
+
throw new RangeError('Invalid source byte range');
|
|
69
|
+
}
|
|
70
|
+
signal.throwIfAborted();
|
|
71
|
+
const response = await fetch(url, {
|
|
72
|
+
headers: { range: `bytes=${offset}-${end}` }, redirect: 'error', signal,
|
|
73
|
+
});
|
|
74
|
+
const range = /^bytes (\d+)-(\d+)\/(\d+)$/i.exec(response.headers.get('content-range') ?? '');
|
|
75
|
+
if (response.status !== 206 || !range || Number(range[1]) !== offset || Number(range[2]) !== end
|
|
76
|
+
|| !Number.isSafeInteger(Number(range[3])) || end >= Number(range[3]) || (offset === 0 && end + 1 === Number(range[3]))) {
|
|
77
|
+
void response.body?.cancel().catch(() => { });
|
|
78
|
+
throw new Error(`Source requires a partial HTTP byte range: ${url} (${response.status})`);
|
|
79
|
+
}
|
|
80
|
+
signal.throwIfAborted();
|
|
81
|
+
const data = await response.arrayBuffer();
|
|
82
|
+
signal.throwIfAborted();
|
|
83
|
+
if (data.byteLength !== length)
|
|
84
|
+
throw new Error('Source byte range has the wrong length');
|
|
85
|
+
return { data, etag: response.headers.get('etag') ?? undefined };
|
|
86
|
+
}
|
package/esm/terrarium.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { geodeticToScene, Heightfield, sceneToGeodetic } from '@vim3d/core';
|
|
2
|
+
import { Buffer } from 'buffer';
|
|
3
|
+
import png from 'pngjs/browser.js';
|
|
4
|
+
import { positiveInteger } from './source.js';
|
|
5
|
+
const rad = Math.PI / 180;
|
|
6
|
+
const size = 256;
|
|
7
|
+
const maxTileBytes = 1024 * 1024;
|
|
8
|
+
const pngSignature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
|
9
|
+
export function terrariumHeight(r, g, b) {
|
|
10
|
+
return r * 256 + g + b / 256 - 32768;
|
|
11
|
+
}
|
|
12
|
+
function pixel(lat, lon, tiles) {
|
|
13
|
+
return [(lon + 180) / 360 * tiles * size - 0.5,
|
|
14
|
+
(1 - Math.asinh(Math.tan(lat * rad)) / Math.PI) / 2 * tiles * size - 0.5];
|
|
15
|
+
}
|
|
16
|
+
async function readTerrariumPng(response) {
|
|
17
|
+
const reader = response.body?.getReader();
|
|
18
|
+
if (!reader)
|
|
19
|
+
throw new Error('Terrarium tile has no response body');
|
|
20
|
+
const chunks = [];
|
|
21
|
+
let length = 0;
|
|
22
|
+
try {
|
|
23
|
+
if (Number(response.headers.get('content-length')) > maxTileBytes)
|
|
24
|
+
throw new Error('Terrarium tile exceeds 1 MiB');
|
|
25
|
+
for (;;) {
|
|
26
|
+
const chunk = await reader.read();
|
|
27
|
+
if (chunk.done)
|
|
28
|
+
break;
|
|
29
|
+
length += chunk.value.byteLength;
|
|
30
|
+
if (length > maxTileBytes)
|
|
31
|
+
throw new Error('Terrarium tile exceeds 1 MiB');
|
|
32
|
+
chunks.push(chunk.value);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
await reader.cancel().catch(() => { });
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
reader.releaseLock();
|
|
41
|
+
}
|
|
42
|
+
const bytes = Buffer.concat(chunks, length);
|
|
43
|
+
if (length < 33 || !bytes.subarray(0, 8).equals(pngSignature) || bytes.readUInt32BE(8) !== 13 ||
|
|
44
|
+
bytes.toString('ascii', 12, 16) !== 'IHDR' || bytes.readUInt32BE(16) !== size ||
|
|
45
|
+
bytes.readUInt32BE(20) !== size || bytes[28] !== 0) {
|
|
46
|
+
throw new Error('Expected non-interlaced 256x256 Terrarium PNG tiles');
|
|
47
|
+
}
|
|
48
|
+
for (let offset = 33; offset <= length - 12;) {
|
|
49
|
+
const chunkLength = bytes.readUInt32BE(offset);
|
|
50
|
+
const kind = bytes.toString('ascii', offset + 4, offset + 8);
|
|
51
|
+
if (kind === 'IHDR' || chunkLength > length - offset - 12)
|
|
52
|
+
throw new Error('Invalid Terrarium PNG chunk');
|
|
53
|
+
if (kind === 'IEND') {
|
|
54
|
+
if (chunkLength !== 0 || offset + 12 !== length)
|
|
55
|
+
throw new Error('Invalid Terrarium PNG chunk');
|
|
56
|
+
return png.PNG.sync.read(bytes).data;
|
|
57
|
+
}
|
|
58
|
+
offset += chunkLength + 12;
|
|
59
|
+
}
|
|
60
|
+
throw new Error('Invalid Terrarium PNG chunk');
|
|
61
|
+
}
|
|
62
|
+
function rectangle(bounds) {
|
|
63
|
+
return Array.isArray(bounds) && bounds.length === 4 && Array.from(bounds).every(Number.isFinite) &&
|
|
64
|
+
bounds[0] < bounds[2] && bounds[1] < bounds[3];
|
|
65
|
+
}
|
|
66
|
+
function projectBounds(origin, [west, south, east, north]) {
|
|
67
|
+
const longitudes = [west, east];
|
|
68
|
+
// East and north are proportional to sin and cos of the longitude offset, respectively.
|
|
69
|
+
for (let lon = origin.lon + Math.ceil((west - origin.lon) / 90) * 90; lon < east; lon += 90) {
|
|
70
|
+
if (lon > west)
|
|
71
|
+
longitudes.push(lon);
|
|
72
|
+
}
|
|
73
|
+
const points = longitudes.flatMap(lon => {
|
|
74
|
+
const latitudes = [south, north];
|
|
75
|
+
if (south < 0 && north > 0)
|
|
76
|
+
latitudes.push(0);
|
|
77
|
+
const stationary = Math.atan2(-Math.cos(origin.lat * rad), Math.sin(origin.lat * rad) * Math.cos((lon - origin.lon) * rad)) / rad;
|
|
78
|
+
const lat = stationary + Math.ceil((south - stationary) / 180) * 180;
|
|
79
|
+
if (lat > south && lat < north)
|
|
80
|
+
latitudes.push(lat);
|
|
81
|
+
return latitudes.map(latitude => geodeticToScene(origin, latitude, lon));
|
|
82
|
+
});
|
|
83
|
+
return [Math.min(...points.map(p => p[0])), Math.min(...points.map(p => p[2])),
|
|
84
|
+
Math.max(...points.map(p => p[0])), Math.max(...points.map(p => p[2]))];
|
|
85
|
+
}
|
|
86
|
+
/** Read a bounded Terrarium XYZ view and sample its triangulated height grid. */
|
|
87
|
+
export async function readTerrarium(config, { signal, fetch: fetchTile = globalThis.fetch, }) {
|
|
88
|
+
const { url: template, bbox, sceneBounds, origin, zoom, spacing = 40, maxTiles = 24 } = config;
|
|
89
|
+
const maxLatitude = 85.0511287798066;
|
|
90
|
+
if (typeof template !== 'string' || !template.startsWith('https://') || !['{x}', '{y}', '{z}'].every(token => template.includes(token))) {
|
|
91
|
+
throw new Error('Terrain URL must be an HTTPS Terrarium template with {z}, {x}, and {y}');
|
|
92
|
+
}
|
|
93
|
+
if (!Number.isSafeInteger(zoom) || zoom < 0 || zoom > 24)
|
|
94
|
+
throw new RangeError('Expected a Terrarium zoom from 0 to 24');
|
|
95
|
+
if (!origin || ![origin.lat, origin.lon, origin.elevation].every(Number.isFinite) ||
|
|
96
|
+
Math.abs(origin.lat) > maxLatitude || Math.abs(origin.lon) > 180)
|
|
97
|
+
throw new RangeError('Invalid Terrarium scene origin');
|
|
98
|
+
if (!Number.isFinite(spacing) || spacing <= 0)
|
|
99
|
+
throw new RangeError('Invalid Terrarium grid spacing');
|
|
100
|
+
positiveInteger(maxTiles, 'maxTiles');
|
|
101
|
+
if (maxTiles > 24)
|
|
102
|
+
throw new RangeError('Terrarium maxTiles cannot exceed 24');
|
|
103
|
+
let bounds;
|
|
104
|
+
if (sceneBounds !== undefined) {
|
|
105
|
+
if (bbox !== undefined || !rectangle(sceneBounds))
|
|
106
|
+
throw new RangeError('Expected nonempty metric Terrarium bounds');
|
|
107
|
+
bounds = [...sceneBounds];
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
if (!rectangle(bbox) || bbox[0] < -180 || bbox[2] > 180 || bbox[1] < -maxLatitude || bbox[3] > maxLatitude) {
|
|
111
|
+
throw new RangeError('Expected nonempty WGS84 Terrarium bounds within Web Mercator');
|
|
112
|
+
}
|
|
113
|
+
bounds = projectBounds(origin, bbox);
|
|
114
|
+
}
|
|
115
|
+
if (!rectangle(bounds))
|
|
116
|
+
throw new RangeError('Terrarium bounds cannot form a local scene grid');
|
|
117
|
+
const [minX, minZ, maxX, maxZ] = bounds;
|
|
118
|
+
signal.throwIfAborted();
|
|
119
|
+
const tiles = 2 ** zoom;
|
|
120
|
+
const columns = Math.max(2, Math.ceil((maxX - minX) / spacing) + 1);
|
|
121
|
+
const rows = Math.max(2, Math.ceil((maxZ - minZ) / spacing) + 1);
|
|
122
|
+
if (columns * rows > 1_000_000)
|
|
123
|
+
throw new RangeError('Terrarium grid exceeds 1,000,000 samples');
|
|
124
|
+
const dx = (maxX - minX) / (columns - 1), dz = (maxZ - minZ) / (rows - 1);
|
|
125
|
+
const samples = Array.from({ length: columns * rows }, (_, i) => {
|
|
126
|
+
const col = i % columns, row = Math.floor(i / columns);
|
|
127
|
+
const x = col === columns - 1 ? maxX : minX + col * dx;
|
|
128
|
+
const z = row === rows - 1 ? maxZ : minZ + row * dz;
|
|
129
|
+
const loc = sceneToGeodetic(origin, [x, 0, z]);
|
|
130
|
+
return pixel(loc.lat, loc.lon, tiles);
|
|
131
|
+
});
|
|
132
|
+
const reference = pixel(origin.lat, origin.lon, tiles);
|
|
133
|
+
const indices = new Map();
|
|
134
|
+
const tileIndex = (x, y) => [
|
|
135
|
+
((Math.floor(x / size) % tiles) + tiles) % tiles, Math.max(0, Math.min(tiles - 1, Math.floor(y / size))),
|
|
136
|
+
];
|
|
137
|
+
const include = ([x, y]) => {
|
|
138
|
+
for (const i of [Math.floor(x), Math.floor(x) + 1])
|
|
139
|
+
for (const j of [Math.floor(y), Math.floor(y) + 1]) {
|
|
140
|
+
const index = tileIndex(i, j);
|
|
141
|
+
indices.set(index.join('/'), index);
|
|
142
|
+
}
|
|
143
|
+
if (indices.size > maxTiles)
|
|
144
|
+
throw new Error(`Terrain view exceeds the ${maxTiles}-tile budget`);
|
|
145
|
+
};
|
|
146
|
+
for (const coords of samples)
|
|
147
|
+
include(coords);
|
|
148
|
+
include(reference);
|
|
149
|
+
const sources = new Map(await Promise.all([...indices.entries()].map(async ([key, [x, y]]) => {
|
|
150
|
+
const url = template.replaceAll('{z}', String(zoom)).replaceAll('{x}', String(x)).replaceAll('{y}', String(y));
|
|
151
|
+
const response = await fetchTile(url, { signal, redirect: 'error' });
|
|
152
|
+
if (!response.ok)
|
|
153
|
+
throw new Error('Terrarium tile request failed: ' + response.status + ' ' + key);
|
|
154
|
+
return [key, await readTerrariumPng(response)];
|
|
155
|
+
})));
|
|
156
|
+
const value = (x, y) => {
|
|
157
|
+
const rgba = sources.get(tileIndex(x, y).join('/'));
|
|
158
|
+
const i = (((y % size + size) % size) * size + (x % size + size) % size) * 4;
|
|
159
|
+
return terrariumHeight(rgba[i], rgba[i + 1], rgba[i + 2]);
|
|
160
|
+
};
|
|
161
|
+
const height = ([px, py]) => {
|
|
162
|
+
const x = Math.floor(px), y = Math.floor(py), u = px - x, v = py - y;
|
|
163
|
+
return (value(x, y) * (1 - u) + value(x + 1, y) * u) * (1 - v) +
|
|
164
|
+
(value(x, y + 1) * (1 - u) + value(x + 1, y + 1) * u) * v;
|
|
165
|
+
};
|
|
166
|
+
const datum = height(reference);
|
|
167
|
+
const grid = { columns, rows, extent: bounds,
|
|
168
|
+
heights: samples.map(p => Math.round((height(p) - datum) * 100) / 100) };
|
|
169
|
+
const field = new Heightfield(grid);
|
|
170
|
+
return { bounds, grid, height: (x, z) => field.sampleHeight(x, z), datum, tileCount: indices.size };
|
|
171
|
+
}
|
package/esm/three.js
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { EventDispatcher, Frustum, Group, Matrix4, Vector2, Vector3, } from 'three';
|
|
2
|
+
import { TileLoader } from './loader.js';
|
|
3
|
+
import { openQueryTiles, validateTileSource } from './query-tiles.js';
|
|
4
|
+
import { createReader } from './source-config.js';
|
|
5
|
+
export function attachTileBuilders(player, scene, builders, options = {}) {
|
|
6
|
+
const attachments = [];
|
|
7
|
+
const dispose = () => {
|
|
8
|
+
for (const attachment of attachments.splice(0))
|
|
9
|
+
attachment.dispose();
|
|
10
|
+
};
|
|
11
|
+
try {
|
|
12
|
+
for (const { config, props, build } of builders.bindings(scene)) {
|
|
13
|
+
validateTileSource(config);
|
|
14
|
+
const reader = createReader(config);
|
|
15
|
+
attachments.push(attachThreeQueryTiles(player, config, reader, {
|
|
16
|
+
...options,
|
|
17
|
+
createGroup({ tile, data }, origin) {
|
|
18
|
+
const result = build({ id: tile.id, source: data.sourceId, features: data.features }, { origin, props });
|
|
19
|
+
const wrap = (object) => {
|
|
20
|
+
const group = new Group();
|
|
21
|
+
group.name = tile.id;
|
|
22
|
+
group.add(object);
|
|
23
|
+
return group;
|
|
24
|
+
};
|
|
25
|
+
return 'then' in result ? Promise.resolve(result).then(wrap) : wrap(result);
|
|
26
|
+
},
|
|
27
|
+
}));
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
dispose();
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
return dispose;
|
|
35
|
+
}
|
|
36
|
+
function visitResources(object, visit) {
|
|
37
|
+
// Sprites share a Three.js-owned quad.
|
|
38
|
+
if (object.geometry && !object.isSprite)
|
|
39
|
+
visit(object.geometry);
|
|
40
|
+
if (object.isInstancedMesh && object.morphTexture)
|
|
41
|
+
visit(object.morphTexture);
|
|
42
|
+
if (object.isBatchedMesh) {
|
|
43
|
+
for (const texture of [object._matricesTexture, object._indirectTexture, object._colorsTexture]) {
|
|
44
|
+
if (texture)
|
|
45
|
+
visit(texture);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const visitTextures = (value) => {
|
|
49
|
+
if (Array.isArray(value)) {
|
|
50
|
+
for (const item of value) {
|
|
51
|
+
if (item?.isTexture === true)
|
|
52
|
+
visit(item);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
else if (value && typeof value === 'object' && 'isTexture' in value && value.isTexture === true) {
|
|
56
|
+
visit(value);
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
if (!object.material)
|
|
60
|
+
return;
|
|
61
|
+
for (const material of Array.isArray(object.material) ? object.material : [object.material]) {
|
|
62
|
+
visit(material);
|
|
63
|
+
for (const value of Object.values(material))
|
|
64
|
+
visitTextures(value);
|
|
65
|
+
if ('uniforms' in material) {
|
|
66
|
+
for (const uniform of Object.values(material.uniforms)) {
|
|
67
|
+
visitTextures(uniform.value);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
class TileResources {
|
|
73
|
+
references = new Map();
|
|
74
|
+
track(group) {
|
|
75
|
+
const resources = new Set();
|
|
76
|
+
const instances = [];
|
|
77
|
+
group.traverse(node => {
|
|
78
|
+
const object = node;
|
|
79
|
+
visitResources(object, resource => resources.add(resource));
|
|
80
|
+
if (object.isInstancedMesh)
|
|
81
|
+
instances.push(object);
|
|
82
|
+
});
|
|
83
|
+
for (const resource of resources) {
|
|
84
|
+
this.references.set(resource, (this.references.get(resource) ?? 0) + 1);
|
|
85
|
+
}
|
|
86
|
+
return () => {
|
|
87
|
+
// The renderer frees per-instance attributes in response to this event.
|
|
88
|
+
for (const instance of instances)
|
|
89
|
+
EventDispatcher.prototype.dispatchEvent.call(instance, { type: 'dispose' });
|
|
90
|
+
for (const resource of resources) {
|
|
91
|
+
const count = this.references.get(resource);
|
|
92
|
+
if (count > 1)
|
|
93
|
+
this.references.set(resource, count - 1);
|
|
94
|
+
else {
|
|
95
|
+
this.references.delete(resource);
|
|
96
|
+
resource.dispose();
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/** Streams tiles into a Vim3DPlayer without adding Three.js to the main tiles entry. */
|
|
103
|
+
export async function attachThreeTiles(player, manifestUrl, options) {
|
|
104
|
+
const start = prepareAttachment(player, options, options.onError);
|
|
105
|
+
return start(await TileLoader.open(manifestUrl, { ...options, ...start.callbacks }));
|
|
106
|
+
}
|
|
107
|
+
export function attachThreeQueryTiles(player, config, reader, options) {
|
|
108
|
+
const start = prepareAttachment(player, options, options.onError);
|
|
109
|
+
return start(openQueryTiles(config, reader, { ...options, ...start.callbacks }));
|
|
110
|
+
}
|
|
111
|
+
function prepareAttachment(player, options, onError) {
|
|
112
|
+
const maxScreenSpaceError = options.maxScreenSpaceError ?? 16;
|
|
113
|
+
if (!Number.isFinite(maxScreenSpaceError) || maxScreenSpaceError < 0) {
|
|
114
|
+
throw new RangeError('maxScreenSpaceError must be finite and nonnegative');
|
|
115
|
+
}
|
|
116
|
+
const root = new Group();
|
|
117
|
+
root.name = '@tiles';
|
|
118
|
+
const groups = new Map();
|
|
119
|
+
let visible = new Set();
|
|
120
|
+
const resources = new TileResources();
|
|
121
|
+
let disposed = false;
|
|
122
|
+
let redrawQueued = false;
|
|
123
|
+
let loader;
|
|
124
|
+
const requestRedraw = () => {
|
|
125
|
+
player.adapter.refitShadows();
|
|
126
|
+
if (!redrawQueued) {
|
|
127
|
+
redrawQueued = true;
|
|
128
|
+
queueMicrotask(() => {
|
|
129
|
+
redrawQueued = false;
|
|
130
|
+
if (!disposed)
|
|
131
|
+
player.redraw();
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
const callbacks = {
|
|
136
|
+
onChange: entries => {
|
|
137
|
+
for (const entry of visible) {
|
|
138
|
+
if (!entries.includes(entry))
|
|
139
|
+
groups.get(entry)?.group?.removeFromParent();
|
|
140
|
+
}
|
|
141
|
+
visible = new Set(entries);
|
|
142
|
+
for (const entry of entries) {
|
|
143
|
+
const tracked = groups.get(entry);
|
|
144
|
+
if (!tracked) {
|
|
145
|
+
const pending = {};
|
|
146
|
+
groups.set(entry, pending);
|
|
147
|
+
const accept = (group) => {
|
|
148
|
+
const release = resources.track(group);
|
|
149
|
+
if (disposed || groups.get(entry) !== pending) {
|
|
150
|
+
release();
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
pending.group = group;
|
|
154
|
+
pending.release = release;
|
|
155
|
+
if (visible.has(entry))
|
|
156
|
+
root.add(group);
|
|
157
|
+
};
|
|
158
|
+
const fail = (error) => {
|
|
159
|
+
if (disposed || groups.get(entry) !== pending)
|
|
160
|
+
return;
|
|
161
|
+
groups.delete(entry);
|
|
162
|
+
onError?.(error, entry.tile);
|
|
163
|
+
};
|
|
164
|
+
try {
|
|
165
|
+
const result = options.createGroup(entry, loader.manifest.origin);
|
|
166
|
+
if ('then' in result)
|
|
167
|
+
void Promise.resolve(result).then(group => {
|
|
168
|
+
accept(group);
|
|
169
|
+
if (!disposed && visible.has(entry))
|
|
170
|
+
requestRedraw();
|
|
171
|
+
}).catch(fail);
|
|
172
|
+
else
|
|
173
|
+
accept(result);
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
fail(error);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
else if (tracked.group && tracked.group.parent !== root)
|
|
180
|
+
root.add(tracked.group);
|
|
181
|
+
}
|
|
182
|
+
requestRedraw();
|
|
183
|
+
},
|
|
184
|
+
onEvict: entry => {
|
|
185
|
+
const tracked = groups.get(entry);
|
|
186
|
+
if (!tracked)
|
|
187
|
+
return;
|
|
188
|
+
groups.delete(entry);
|
|
189
|
+
tracked.group?.removeFromParent();
|
|
190
|
+
tracked.release?.();
|
|
191
|
+
},
|
|
192
|
+
onDispose: () => detach(true),
|
|
193
|
+
};
|
|
194
|
+
const size = new Vector2();
|
|
195
|
+
const viewProjection = new Matrix4();
|
|
196
|
+
const lastProjection = new Matrix4();
|
|
197
|
+
const lastWorld = new Matrix4();
|
|
198
|
+
const frustum = new Frustum();
|
|
199
|
+
let lastCamera;
|
|
200
|
+
let lastHeight;
|
|
201
|
+
const beforeRender = () => {
|
|
202
|
+
const camera = player.getRenderCamera();
|
|
203
|
+
const height = options.getViewportHeight?.() ?? player.renderer.getSize?.(size).y;
|
|
204
|
+
const perspective = camera && 'isPerspectiveCamera' in camera && camera.isPerspectiveCamera === true;
|
|
205
|
+
const orthographic = camera && 'isOrthographicCamera' in camera && camera.isOrthographicCamera === true;
|
|
206
|
+
if (!camera?.isCamera || !(perspective || orthographic) ||
|
|
207
|
+
!Number.isFinite(height) || height <= 0) {
|
|
208
|
+
if (lastCamera)
|
|
209
|
+
loader.updateView(undefined);
|
|
210
|
+
lastCamera = undefined;
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
camera.updateWorldMatrix(true, false);
|
|
214
|
+
if (camera === lastCamera && height === lastHeight && lastProjection.equals(camera.projectionMatrix)
|
|
215
|
+
&& lastWorld.equals(camera.matrixWorld))
|
|
216
|
+
return;
|
|
217
|
+
lastCamera = camera;
|
|
218
|
+
lastHeight = height;
|
|
219
|
+
lastProjection.copy(camera.projectionMatrix);
|
|
220
|
+
lastWorld.copy(camera.matrixWorld);
|
|
221
|
+
frustum.setFromProjectionMatrix(viewProjection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse), camera.coordinateSystem, camera.reversedDepth);
|
|
222
|
+
const pixels = height * Math.abs(camera.projectionMatrix.elements[5]) * 0.5;
|
|
223
|
+
loader.updateView({
|
|
224
|
+
frustum: frustum.planes.map(({ normal: { x, y, z }, constant }) => [x, y, z, constant]),
|
|
225
|
+
projection: perspective
|
|
226
|
+
? { type: 'perspective', position: new Vector3().setFromMatrixPosition(camera.matrixWorld).toArray(), pixelsPerMetreAtUnitDistance: pixels }
|
|
227
|
+
: { type: 'orthographic', pixelsPerMetre: pixels },
|
|
228
|
+
maxScreenSpaceError,
|
|
229
|
+
});
|
|
230
|
+
};
|
|
231
|
+
let removeHook;
|
|
232
|
+
let removeBounds;
|
|
233
|
+
const detach = (redraw) => {
|
|
234
|
+
if (disposed)
|
|
235
|
+
return;
|
|
236
|
+
disposed = true;
|
|
237
|
+
options.signal?.removeEventListener('abort', abort);
|
|
238
|
+
removeHook?.();
|
|
239
|
+
removeBounds?.();
|
|
240
|
+
root.removeFromParent();
|
|
241
|
+
visible.clear();
|
|
242
|
+
loader.dispose();
|
|
243
|
+
if (redraw) {
|
|
244
|
+
player.adapter.refitShadows();
|
|
245
|
+
player.redraw();
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
const abort = () => detach(true);
|
|
249
|
+
return Object.assign((value) => {
|
|
250
|
+
loader = value;
|
|
251
|
+
try {
|
|
252
|
+
options.signal?.throwIfAborted();
|
|
253
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
254
|
+
removeHook = player.addRenderHook({ beforeRender, dispose: () => detach(false) });
|
|
255
|
+
player.adapter.scene.add(root);
|
|
256
|
+
removeBounds = player.adapter.addBoundsObject(root);
|
|
257
|
+
player.redraw();
|
|
258
|
+
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
detach(false);
|
|
261
|
+
throw error;
|
|
262
|
+
}
|
|
263
|
+
return { loader, dispose: () => detach(true) };
|
|
264
|
+
}, { callbacks });
|
|
265
|
+
}
|