isard 1.2.0 → 1.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.
Files changed (94) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/README.md +44 -39
  3. package/dist/basemap/pmtileslayer.d.ts +33 -0
  4. package/dist/basemap/pmtileslayer.js +97 -0
  5. package/dist/basemap/pmtileslayer.js.map +1 -0
  6. package/dist/basemap/trees.d.ts +26 -0
  7. package/dist/basemap/trees.js +141 -0
  8. package/dist/basemap/trees.js.map +1 -0
  9. package/dist/basemap/vectorstyle.d.ts +10 -0
  10. package/dist/basemap/vectorstyle.js +35 -0
  11. package/dist/basemap/vectorstyle.js.map +1 -1
  12. package/dist/basemap/vectortiles.d.ts +67 -44
  13. package/dist/basemap/vectortiles.js +386 -302
  14. package/dist/basemap/vectortiles.js.map +1 -1
  15. package/dist/basemap/workerpool.d.ts +17 -0
  16. package/dist/basemap/workerpool.js +194 -0
  17. package/dist/basemap/workerpool.js.map +1 -0
  18. package/dist/basemap.worker.js +2 -2
  19. package/dist/basemap.worker.js.map +15 -8
  20. package/dist/decoder.worker.js +4 -4
  21. package/dist/decoder.worker.js.map +3 -3
  22. package/dist/engine-loader.d.ts +5 -1
  23. package/dist/engine-loader.js +11 -1
  24. package/dist/engine-loader.js.map +1 -1
  25. package/dist/geoplateforme.d.ts +16 -0
  26. package/dist/geoplateforme.js +23 -0
  27. package/dist/geoplateforme.js.map +1 -1
  28. package/dist/index.d.ts +11 -4
  29. package/dist/index.js +9 -2
  30. package/dist/index.js.map +1 -1
  31. package/dist/isard_bg.wasm +0 -0
  32. package/dist/isard_core_bg.wasm +0 -0
  33. package/dist/isard_tess_bg.wasm +0 -0
  34. package/dist/layers/layers.js +9 -0
  35. package/dist/layers/layers.js.map +1 -1
  36. package/dist/layers/vectors.d.ts +60 -0
  37. package/dist/layers/vectors.js +130 -0
  38. package/dist/layers/vectors.js.map +1 -0
  39. package/dist/map/frame-loop.d.ts +3 -0
  40. package/dist/map/frame-loop.js +6 -0
  41. package/dist/map/frame-loop.js.map +1 -1
  42. package/dist/map/raster-source.js +1 -1
  43. package/dist/map/raster-source.js.map +1 -1
  44. package/dist/map/workers.d.ts +1 -1
  45. package/dist/map/workers.js +1 -1
  46. package/dist/map/workers.js.map +1 -1
  47. package/dist/map.d.ts +21 -6
  48. package/dist/map.js +65 -11
  49. package/dist/map.js.map +1 -1
  50. package/dist/react/IsardMap.js +1 -0
  51. package/dist/react/IsardMap.js.map +1 -1
  52. package/dist/react/Swipe.d.ts +11 -4
  53. package/dist/react/Swipe.js +26 -15
  54. package/dist/react/Swipe.js.map +1 -1
  55. package/dist/react/VectorGeometry.d.ts +35 -0
  56. package/dist/react/VectorGeometry.js +82 -0
  57. package/dist/react/VectorGeometry.js.map +1 -0
  58. package/dist/react/context.d.ts +2 -1
  59. package/dist/react/context.js.map +1 -1
  60. package/dist/react/index.d.ts +2 -1
  61. package/dist/react/index.js +2 -1
  62. package/dist/react/index.js.map +1 -1
  63. package/dist/types.d.ts +24 -1
  64. package/dist/types.js.map +1 -1
  65. package/dist/ui/minimap.d.ts +25 -0
  66. package/dist/ui/minimap.js +90 -0
  67. package/dist/ui/minimap.js.map +1 -0
  68. package/dist/ui/scale.d.ts +19 -0
  69. package/dist/ui/scale.js +44 -0
  70. package/dist/ui/scale.js.map +1 -0
  71. package/dist/ui/search.d.ts +25 -0
  72. package/dist/ui/search.js +119 -0
  73. package/dist/ui/search.js.map +1 -0
  74. package/dist/ui/style.js +17 -0
  75. package/dist/ui/style.js.map +1 -1
  76. package/dist/util/sun.d.ts +11 -0
  77. package/dist/util/sun.js +26 -0
  78. package/dist/util/sun.js.map +1 -0
  79. package/dist/wasm/isard.d.ts +82 -7
  80. package/dist/wasm/isard.js +229 -8
  81. package/dist/wasm/isard_core.d.ts +82 -7
  82. package/dist/wasm/isard_core.js +229 -8
  83. package/dist/wasm/isard_tess.d.ts +109 -0
  84. package/dist/wasm/isard_tess.js +398 -0
  85. package/dist/workers/basemap/geometry.d.ts +72 -0
  86. package/dist/workers/basemap/labels.d.ts +8 -0
  87. package/dist/workers/basemap/raster.d.ts +10 -0
  88. package/dist/workers/basemap/tiles.d.ts +65 -0
  89. package/dist/workers/basemap/trees.d.ts +19 -0
  90. package/dist/workers/basemap.worker.d.ts +126 -22
  91. package/dist/workers/basemap.worker.js +72 -551
  92. package/dist/workers/basemap.worker.js.map +1 -1
  93. package/package.json +5 -4
  94. package/vite.js +10 -2
@@ -8,8 +8,7 @@
8
8
  * Any subset of the style can be drawn on its own raster layer (`raster({ layers })`), at its own place in the stack:
9
9
  * rivers from the basemap's data over a flood layer, for instance, restyled with `extraLayers`.
10
10
  */
11
- import { headerRules, onHeaderRules, withHeaders } from "../engine/requests.js";
12
- import { assetUrl } from "../engine-loader.js";
11
+ import { withHeaders } from "../engine/requests.js";
13
12
  import { IGN_ATTRIBUTION } from "../geoplateforme.js";
14
13
  import { loadSprites, readPixels } from "../layers/icons.js";
15
14
  import { mercatorX, mercatorY } from "../util/geo.js";
@@ -17,8 +16,9 @@ import { isRecord } from "../util/guards.js";
17
16
  import { Lru } from "../util/lru.js";
18
17
  import { OPENFREEMAP_ATTRIBUTION } from "./basemaps.js";
19
18
  import { pmtiles, pmtilesUrl } from "./pmtiles.js";
20
- import { SOURCE_CACHE } from "./resample.js";
21
- import { isStyle, labelFont, } from "./vectorstyle.js";
19
+ import { isWoodland, TREE_NUMBERS, treeModel, treeSpacing } from "./trees.js";
20
+ import { evaluate, isExpression, isStyle, labelFont, vectorKind, zoomOnly, } from "./vectorstyle.js";
21
+ import { rendererKey, tilePriority } from "./workerpool.js";
22
22
  /** OpenFreeMap's styles: OpenStreetMap data in the OpenMapTiles schema, worldwide, free and without a key */
23
23
  export const OPENFREEMAP_STYLES = {
24
24
  positron: 'https://tiles.openfreemap.org/styles/positron',
@@ -120,193 +120,26 @@ const resolveSource = async (source) => {
120
120
  };
121
121
  /** Pause before the labels of tiles that failed are asked for again, when no move brings an update (ms) */
122
122
  const RETRY_LABELS_MS = 3000;
123
- /** Default size of a basemap worker pool: cores - 1, 1 to 4 */
124
- export const defaultWorkerCount = () => {
125
- return Math.min(4, Math.max(1, (typeof navigator !== 'undefined' ? navigator.hardwareConcurrency || 2 : 2) - 1));
126
- };
127
- /** Default URL of the basemap worker: in the page's assets folder (`isard/vite`), else next to the module */
128
- export const defaultWorkerUrl = (assetsUrl) => {
129
- return assetUrl('basemap.worker.js', undefined, assetsUrl);
130
- };
131
- /** Fetch priority of a raster tile drawn by the workers: 'high' near the center of the view, at the current zoom or
132
- * coarser; 'low' far from it or finer (prefetch); 'auto' between */
133
- export const tilePriority = (z, x, y, camera) => {
134
- // A raster tile of level z covers the map at zoom z - 1
135
- if (z - 1 > camera.zoom + 1)
136
- return 'low';
137
- const n = 2 ** z;
138
- const [lon, lat] = camera.center;
139
- const cx = mercatorX(lon) * n;
140
- const cy = mercatorY(lat) * n;
141
- // Across the antimeridian, the short way
142
- const along = Math.abs(x + 0.5 - cx) % n;
143
- const dx = Math.min(along, n - along);
144
- const d = Math.hypot(dx, y + 0.5 - cy);
145
- if (d <= 1.5)
146
- return 'high';
147
- return d >= 4 ? 'low' : 'auto';
148
- };
149
- /** The worker of a vector tile among `count`: always the same one */
150
- export const workerIndex = (vz, vx, vy, count) => {
151
- // Unsigned: every worker gets its share
152
- return ((Math.imul(vx, 73856093) ^ Math.imul(vy, 19349663) ^ vz) >>> 0) % Math.max(1, count);
153
- };
154
- /** The worker-side key of a renderer: unique across the `VectorTiles` sharing a pool */
155
- export const rendererKey = (namespace, n) => {
156
- return `${namespace}:r${n}`;
157
- };
123
+ /** The style layers of buildings, by default: PLAN IGN's `bati_surf` (not its built-up areas nor its parks), the
124
+ * OpenMapTiles' `building` */
125
+ const isBuildings = (layer) => ['bati_surf', 'building'].includes(layer['source-layer'] ?? '');
158
126
  /**
159
- * @internal Workers drawing vector tiles, shared by the `VectorTiles` of a map: each vector tile always goes to the
160
- * same worker, which keeps it decoded for every style drawn from it. Requests are tracked one by one, with their
161
- * owner, so that one `VectorTiles` going away cancels its own requests only.
127
+ * The tiles of level `z` in view, within a window around the center (a tilted view's bounds reach far), the
128
+ * `maxTiles` nearest to the center first
162
129
  */
163
- export class BasemapWorkers {
164
- count;
165
- url;
166
- workers;
167
- pending = new Map();
168
- next = 1;
169
- namespaces = 0;
170
- terminated = false;
171
- /** Stops following the page's request headers */
172
- unfollow;
173
- constructor(count, url, create = (u) => new Worker(u, { type: 'module' })) {
174
- this.count = count;
175
- this.url = url;
176
- const start = () => {
177
- const worker = create(url);
178
- worker.onmessage = ({ data }) => {
179
- const p = this.pending.get(data.id);
180
- if (!p)
181
- return;
182
- this.pending.delete(data.id);
183
- if ('error' in data)
184
- p.reject(new Error(data.error));
185
- else
186
- p.resolve(data);
187
- };
188
- // A worker that fails to load (a bundler serving it from elsewhere) or to read a message fails its requests
189
- worker.onerror = (event) => {
190
- event.preventDefault();
191
- this.fail(worker, `the vector basemap worker ${url} failed${event.message ? `: ${event.message}` : ''}`);
192
- };
193
- worker.onmessageerror = () => this.fail(worker, `the vector basemap worker ${url} sent an unreadable message`);
194
- const rules = headerRules();
195
- if (rules.length > 0)
196
- worker.postMessage({ type: 'headers', rules });
197
- return worker;
198
- };
199
- this.workers = [start(), ...Array.from({ length: Math.max(1, count) - 1 }, start)];
200
- this.unfollow = onHeaderRules((rules) => {
201
- this.workers.forEach((w) => {
202
- w.postMessage({ type: 'headers', rules });
203
- });
204
- });
205
- }
206
- /** A prefix for the renderer keys of one `VectorTiles` */
207
- namespace() {
208
- return `v${this.namespaces++}`;
209
- }
210
- /** Requests in progress */
211
- get size() {
212
- return this.pending.size;
213
- }
214
- /** Rejects the requests of a failed worker */
215
- fail(worker, message) {
216
- const error = new Error(`isard: ${message}. If a bundler moves the worker, give its URL in the \`basemapWorkerUrl\` option (see "With a bundler" in the guide)`);
217
- this.pending.forEach((p, id) => {
218
- if (p.worker !== worker)
219
- return;
220
- this.pending.delete(id);
221
- p.reject(error);
222
- });
223
- }
224
- /** The worker of a vector tile */
225
- worker(vz, vx, vy) {
226
- return this.workers[workerIndex(vz, vx, vy, this.workers.length)] ?? this.workers[0];
227
- }
228
- /** Sends a message to every worker (a renderer, or its removal) */
229
- broadcast(message) {
230
- if (this.terminated)
231
- return;
232
- // A renderer tells the workers how many they are: they share the decoded tiles' budget
233
- const sent = message.type === 'init' ? { ...message, workers: this.workers.length } : message;
234
- // A sprite image is copied to each worker (structured clone)
235
- this.workers.forEach((w) => {
236
- w.postMessage(sent);
237
- });
238
- }
239
- /** Asks a worker for a tile's image or labels, on behalf of `owner` */
240
- request(worker, work, owner, signal) {
241
- return new Promise((resolve, reject) => {
242
- if (this.terminated)
243
- return reject(new DOMException('isard: vector tiles destroyed', 'AbortError'));
244
- if (signal?.aborted)
245
- return reject(new DOMException('aborted', 'AbortError'));
246
- const id = this.next++;
247
- const abort = () => {
248
- if (!this.pending.delete(id))
249
- return;
250
- worker.postMessage({ type: 'abort', id });
251
- reject(new DOMException('aborted', 'AbortError'));
252
- };
253
- // The listener goes once the request is settled
254
- const settle = () => signal?.removeEventListener('abort', abort);
255
- this.pending.set(id, {
256
- resolve: (r) => {
257
- settle();
258
- resolve(r);
259
- },
260
- reject: (e) => {
261
- settle();
262
- reject(e);
263
- },
264
- worker,
265
- owner,
266
- });
267
- signal?.addEventListener('abort', abort, { once: true });
268
- worker.postMessage({ ...work, id });
269
- });
270
- }
271
- /** The altitudes of a PNG relief tile `z`/`x`/`y` at `url`, decoded by a worker (see `fetchHeights`) */
272
- heights(url, encoding, floor, [z, x, y], signal, owner) {
273
- const work = { type: 'heights', url, encoding, ...(floor === undefined ? {} : { floor }) };
274
- return this.request(this.worker(z, x, y), work, owner, signal).then((r) => ('heights' in r ? r.heights : null));
275
- }
276
- /** Mercator tile `z`/`x`/`y` reprojected by a worker from the source images of its plan (see `resampler`) */
277
- reproject(job, [z, x, y], signal, owner) {
278
- // Blocks of 4 × 4 Mercator tiles go to the same worker: neighbours share source tiles, each worker keeps its share
279
- const worker = this.worker(Math.max(0, z - 2), x >> 2, y >> 2);
280
- const cached = Math.max(16, Math.ceil(SOURCE_CACHE / this.workers.length));
281
- const work = { type: 'reproject', job, cached };
282
- return this.request(worker, work, owner, signal).then((r) => ('image' in r ? r.image : null));
283
- }
284
- /** Cancels the requests of an owner (the workers stop them) */
285
- cancel(owner) {
286
- this.pending.forEach((p, id) => {
287
- if (p.owner !== owner)
288
- return;
289
- this.pending.delete(id);
290
- p.worker.postMessage({ type: 'abort', id });
291
- p.reject(new DOMException('isard: vector tiles destroyed', 'AbortError'));
292
- });
293
- }
294
- /** Stops the workers; their requests fail */
295
- terminate() {
296
- if (this.terminated)
297
- return;
298
- this.terminated = true;
299
- this.unfollow();
300
- this.workers.forEach((w) => {
301
- w.terminate();
302
- });
303
- const pending = [...this.pending.values()];
304
- this.pending.clear();
305
- pending.forEach((p) => {
306
- p.reject(new DOMException('isard: vector tiles destroyed', 'AbortError'));
307
- });
308
- }
309
- }
130
+ const tilesAround = (map, camera, z, maxTiles) => {
131
+ const n = 2 ** z;
132
+ const [west, south, east, north] = map.getBounds();
133
+ const tx = (lon) => Math.floor(mercatorX(lon) * n);
134
+ const ty = (lat) => Math.floor(mercatorY(lat) * n);
135
+ const [cx, cy] = [mercatorX(camera.center[0]) * n, mercatorY(camera.center[1]) * n];
136
+ const reach = Math.ceil(Math.sqrt(maxTiles)) + 2;
137
+ const [x0, x1] = [Math.max(0, tx(west), Math.floor(cx) - reach), Math.min(n - 1, tx(east), Math.floor(cx) + reach)];
138
+ const [y0, y1] = [Math.max(0, ty(north), Math.floor(cy) - reach), Math.min(n - 1, ty(south), Math.floor(cy) + reach)];
139
+ const wanted = Array.from({ length: Math.max(0, y1 - y0 + 1) }, (_, j) => y0 + j).flatMap((y) => Array.from({ length: Math.max(0, x1 - x0 + 1) }, (_, i) => [x0 + i, y]));
140
+ wanted.sort((a, b) => Math.hypot(a[0] + 0.5 - cx, a[1] + 0.5 - cy) - Math.hypot(b[0] + 0.5 - cx, b[1] + 0.5 - cy));
141
+ return wanted.slice(0, maxTiles);
142
+ };
310
143
  /** A tile's label candidates as features, by style layer */
311
144
  export const tileLabels = (candidates) => {
312
145
  const byLayer = new Map();
@@ -425,10 +258,10 @@ export class VectorTiles {
425
258
  return Promise.reject(new DOMException('isard: vector tiles destroyed', 'AbortError'));
426
259
  return this.pool.request(this.pool.worker(vz, vx, vy), work, this, signal);
427
260
  }
428
- /** Sends a renderer of these layers to every worker; returns its key */
429
- async renderer(select, extra) {
261
+ /** Sends a renderer of these layers to every worker (again under `again`, restyled); returns its key */
262
+ async renderer(select, extra, again) {
430
263
  const { style, tiles, maxzoom, rasters } = await this.ready;
431
- const key = rendererKey(this.namespace, this.keys++);
264
+ const key = again ?? rendererKey(this.namespace, this.keys++);
432
265
  const layers = [...style.layers.filter(select), ...extra];
433
266
  const patterns = layers.some((l) => l.paint?.['fill-pattern'] !== undefined);
434
267
  // The images are downloaded once, copied to each worker
@@ -436,8 +269,9 @@ export class VectorTiles {
436
269
  if (this.destroyed)
437
270
  throw new DOMException('isard: vector tiles destroyed', 'AbortError');
438
271
  this.pool.broadcast({ type: 'init', key, tiles, maxzoom, layers, rasters, ...(sprites.length ? { sprites } : {}) });
439
- this.renderers.push(key);
440
- return { key, maxzoom };
272
+ if (!again)
273
+ this.renderers.push(key);
274
+ return { key, maxzoom, layers };
441
275
  }
442
276
  /**
443
277
  * A raster layer drawing the style's fills, lines and circles (or those `layers` keeps, then `extraLayers`, of the
@@ -472,6 +306,310 @@ export class VectorTiles {
472
306
  this.ground ??= layer;
473
307
  return layer;
474
308
  }
309
+ /**
310
+ * An extrusion layer of the polygons of the style's fill layers that `layers` keeps (by default its buildings: the
311
+ * fill or fill-extrusion layers of PLAN IGN's `bati_surf` or OpenMapTiles' `building`), raised by the style
312
+ * given (`height`, `base`, `color`, `ramp`…; the properties of the tiles' features). Its tiles follow the view: at
313
+ * the source's deepest level, the `maxTiles` nearest to the center, from `minZoom` on (15 by default); the tiles
314
+ * leaving the view are dropped.
315
+ */
316
+ extrusions(options = {}) {
317
+ const { layers = isBuildings, minZoom = 15, maxTiles = 36, ...style } = options;
318
+ const extrusions = this.map.addExtrusions(style);
319
+ const renderer = this.renderer((l) => (l.type === 'fill' || l.type === 'fill-extrusion') && layers(l), []);
320
+ renderer.catch(() => undefined);
321
+ this.layers.push(extrusions);
322
+ /** The tiles held or asked for, by key */
323
+ const held = new Map();
324
+ const update = async () => {
325
+ if (this.destroyed)
326
+ return;
327
+ const { key, maxzoom } = await renderer;
328
+ const camera = this.map.getCamera();
329
+ const z = maxzoom;
330
+ const wanted = camera.zoom < minZoom ? [] : tilesAround(this.map, camera, z, maxTiles);
331
+ const keys = new Set(wanted.map(([x, y]) => `${z}/${x}/${y}`));
332
+ // Out of view: dropped, or no longer asked for
333
+ [...held].forEach(([k, controller]) => {
334
+ if (keys.has(k))
335
+ return;
336
+ controller.abort();
337
+ held.delete(k);
338
+ extrusions.removeTile(k);
339
+ });
340
+ wanted.forEach(([x, y], index) => {
341
+ const k = `${z}/${x}/${y}`;
342
+ if (held.has(k))
343
+ return;
344
+ const controller = new AbortController();
345
+ const work = { type: 'polygons', key, z, x, y, priority: index < 4 ? 'auto' : 'low' };
346
+ held.set(k, controller);
347
+ this.request(z, x, y, work, controller.signal).then((r) => {
348
+ if (controller.signal.aborted || !('polygons' in r))
349
+ return;
350
+ const tile = r.polygons;
351
+ // The features' properties as the style reads them
352
+ extrusions.setTile(k, { arrays: tile.arrays, properties: tile.properties });
353
+ }, () => {
354
+ // A failure is asked for again on the next update
355
+ if (held.get(k) === controller)
356
+ held.delete(k);
357
+ });
358
+ });
359
+ };
360
+ this.followView(update, held, update);
361
+ return extrusions;
362
+ }
363
+ /**
364
+ * Trees on the style's woods, forests and grass (or the fill layers `layers` keeps) as 3D models, from street level
365
+ * (`minZoom`, default 15): the workers scatter them over the polygons of the vector tiles around the view, `spacing`
366
+ * metres apart (by style layer: 9 in woods, 25 on grass, by default) on a jittered grid, the same trees whenever a
367
+ * tile comes back; the engine draws them all in one instanced draw, on the relief. A low-poly tree by default (its
368
+ * `colors`), or your own glTF (`url`, `data`, about 10 metres high, standing on its origin). Dense around the
369
+ * view's center, fewer and fewer away from it (as the camera moves too), at most `maxInstances` drawn (default
370
+ * 25000); at most `maxTiles` tiles (default 9) and `maxTrees` trees in each (default 30000). The models load the
371
+ * engine with 3D Tiles.
372
+ */
373
+ trees(options = {}) {
374
+ const { layers = isWoodland, spacing = treeSpacing, minZoom = 15, maxTiles = 9, maxTrees = 30000, maxInstances = 25000, } = options;
375
+ const model = options.url ? { url: options.url } : { data: options.data ?? treeModel(options.colors) };
376
+ const trees = this.map.addModels({
377
+ ...model,
378
+ instances: [],
379
+ ...(options.before ? { before: options.before } : {}),
380
+ });
381
+ const renderer = this.renderer((l) => l.type === 'fill' && layers(l), []);
382
+ renderer.catch(() => undefined);
383
+ this.layers.push(trees);
384
+ /** The tiles held or asked for, by key, and the trees of those that came */
385
+ const held = new Map();
386
+ const found = new Map();
387
+ /** The trees drawn to the engine (longitude, latitude, altitude, heading, pitch, roll, scale each): all of them
388
+ * near the view's center, past `near` metres those of a rank under (near / distance)², at most `maxInstances` */
389
+ const send = () => {
390
+ const { center, zoom } = this.map.getCamera();
391
+ const near = TREES_NEAR_METRES * 2 ** (16 - zoom);
392
+ const metresPerDegree = 111320;
393
+ const cos = Math.cos((center[1] * Math.PI) / 180);
394
+ const chosen = [];
395
+ found.forEach((t) => {
396
+ for (let i = 0; i < t.length / TREE_NUMBERS; i += 1) {
397
+ const dx = ((t[i * TREE_NUMBERS] ?? 0) - center[0]) * metresPerDegree * cos;
398
+ const dy = ((t[i * TREE_NUMBERS + 1] ?? 0) - center[1]) * metresPerDegree;
399
+ const far = (dx * dx + dy * dy) / (near * near);
400
+ const score = (t[i * TREE_NUMBERS + 4] ?? 0) * Math.max(1, far);
401
+ if (score < 1)
402
+ chosen.push([score, t, i]);
403
+ }
404
+ });
405
+ if (chosen.length > maxInstances)
406
+ chosen.sort((a, b) => a[0] - b[0]).splice(maxInstances);
407
+ const out = new Float64Array(chosen.length * 7);
408
+ chosen.forEach(([, t, i], k) => {
409
+ const at = i * TREE_NUMBERS;
410
+ out.set([t[at] ?? 0, t[at + 1] ?? 0, 0, t[at + 3] ?? 0, 0, 0, t[at + 2] ?? 1], k * 7);
411
+ });
412
+ trees.setInstanceNumbers(out);
413
+ };
414
+ const update = async () => {
415
+ if (this.destroyed)
416
+ return;
417
+ const { key, maxzoom, layers: list } = await renderer;
418
+ const camera = this.map.getCamera();
419
+ const z = maxzoom;
420
+ const wanted = camera.zoom < minZoom ? [] : tilesAround(this.map, camera, z, maxTiles);
421
+ const keys = new Set(wanted.map(([x, y]) => `${z}/${x}/${y}`));
422
+ const metres = list.map((l) => (typeof spacing === 'number' ? spacing : spacing(l)));
423
+ const dropped = [...held.keys()].filter((k) => !keys.has(k));
424
+ // Out of view: dropped, or no longer asked for
425
+ dropped.forEach((k) => {
426
+ held.get(k)?.abort();
427
+ held.delete(k);
428
+ found.delete(k);
429
+ });
430
+ // Dense around the new center
431
+ send();
432
+ wanted.forEach(([x, y], index) => {
433
+ const k = `${z}/${x}/${y}`;
434
+ if (held.has(k))
435
+ return;
436
+ const controller = new AbortController();
437
+ const priority = index < 4 ? 'auto' : 'low';
438
+ const work = { type: 'trees', key, z, x, y, spacing: metres, maxTrees, priority };
439
+ held.set(k, controller);
440
+ this.request(z, x, y, work, controller.signal).then((r) => {
441
+ if (controller.signal.aborted || !('trees' in r))
442
+ return;
443
+ found.set(k, r.trees);
444
+ send();
445
+ }, () => {
446
+ // A failure is asked for again on the next update
447
+ if (held.get(k) === controller)
448
+ held.delete(k);
449
+ });
450
+ });
451
+ };
452
+ // While the camera moves, the trees drawn follow its center (dense near it)
453
+ this.followView(update, held, send);
454
+ return trees;
455
+ }
456
+ /**
457
+ * A layer drawing the style's fills, lines and buildings (or those `layers` keeps; backgrounds as fills, the
458
+ * `fill-extrusion` layers raised into buildings by their height and base height) as geometry instead of images: the
459
+ * workers cut the vector tiles in view into polygons and lines, which the engine draws on the globe and the relief,
460
+ * in the style's order, each style layer over its zoom range. Sharp at any zoom
461
+ * and pitch, picked by feature (`pick` gives its properties and style layer), restyled without cutting the tiles
462
+ * again (`setPaintProperty`, `setLayoutProperty`). Its tiles follow the view, while it moves too, coarser far away in a
463
+ * tilted view, and those leaving it stay until the ones replacing them are there; past the source's deepest level,
464
+ * cut again from its tiles down to level 18 (overzoom: their filters and styles those of their level). The fills' outlines are drawn one
465
+ * pixel wide, the lines' ends as their `line-cap` says (their joins round), the colors follow the camera's zoom. The
466
+ * layers drawn with a pattern and the circles are left out (the raster path draws them), as are `line-offset`,
467
+ * `line-blur` and the translations (`fill-translate`, `line-translate`); `raster` stays the lighter path for heavy
468
+ * styles and small devices. At night (`setSun`) the line layers `streets` keeps glow (by default those whose id names
469
+ * a road, not its casing, a railway, a path or a tunnel).
470
+ */
471
+ vectors(options = {}) {
472
+ const { layers = () => true, streets = isStreet, before } = options;
473
+ const vector = this.map.addVectorLayer(before);
474
+ const state = { renderer: this.renderer((l) => vectorKind(l) !== undefined && layers(l), []), update: 0, style: 0 };
475
+ state.renderer.catch(() => undefined);
476
+ this.layers.push(vector);
477
+ const sublayers = (list) => {
478
+ const zoom = this.map.getCamera().zoom;
479
+ return list.map((l) => ({
480
+ id: l.id,
481
+ sourceLayer: l['source-layer'],
482
+ kind: vectorKind(l) ?? 'fill',
483
+ minZoom: l.minzoom ?? 0,
484
+ maxZoom: l.maxzoom ?? 24,
485
+ visible: l.layout?.visibility !== 'none',
486
+ opacity: zoomOnly(l.paint?.[`${l.type}-opacity`], 1) ?? 1,
487
+ cap: lineCap(l.layout?.['line-cap'], zoom),
488
+ lit: l.type === 'line' && streets(l),
489
+ dash: l.type === 'line' ? dashes(l.paint?.['line-dasharray'], zoom) : [0, 0, 0, 0],
490
+ }));
491
+ };
492
+ /** The tiles held or asked for, by `z/x/y` */
493
+ const held = new Map();
494
+ /** A tile's geometry, or its styles alone, asked of the worker of its tile of the source's level (which keeps the
495
+ * decoded tile its deeper tiles are cut from) */
496
+ const ask = ({ key, maxzoom }, [z = 0, x = 0, y = 0], styles, priority, signal) => {
497
+ const d = Math.max(0, z - maxzoom);
498
+ const work = { type: 'vectors', key, z, x, y, deepest: deepestLevel(maxzoom), priority };
499
+ // The geometry made ready for the GPU in the workers, with the prisms the relief needs
500
+ return this.request(z - d, Math.floor(x / 2 ** d), Math.floor(y / 2 ** d), styles ? { ...work, styles } : { ...work, prism: this.map.hasRelief }, signal);
501
+ };
502
+ // The workers tessellate the tiles (the main thread only uploads them), once they know the module
503
+ this.pool.broadcast({ type: 'tess', url: this.map.tessUrl });
504
+ /** The styles of a tile held asked for again, the tile kept as it is */
505
+ const restyleTile = async (renderer, k) => {
506
+ const r = await ask(renderer, k.split('/').map(Number), true, 'auto').catch(() => undefined);
507
+ if (r && 'styles' in r)
508
+ vector.setTileStyles(k, r.styles);
509
+ };
510
+ const update = async () => {
511
+ if (this.destroyed)
512
+ return;
513
+ const generation = ++state.update;
514
+ const { key, maxzoom, layers: list } = await state.renderer;
515
+ vector.setSublayers(sublayers(state.own ?? list));
516
+ const view = this.map.engine.vectorTilesInView(0, deepestLevel(maxzoom));
517
+ const wanted = Array.from({ length: Math.floor(view.length / 3) }, (_, i) => [
518
+ ...view.subarray(i * 3, i * 3 + 3),
519
+ ]);
520
+ const keys = new Set(wanted.map((t) => t.join('/')));
521
+ const loads = wanted.flatMap((t, index) => {
522
+ const k = t.join('/');
523
+ if (held.has(k))
524
+ return [];
525
+ const controller = new AbortController();
526
+ const style = state.style;
527
+ held.set(k, controller);
528
+ return [
529
+ ask({ key, maxzoom }, t, false, index < 4 ? 'high' : 'auto', controller.signal).then(async (r) => {
530
+ if (controller.signal.aborted || !('vectors' in r))
531
+ return;
532
+ vector.setTile(k, r.vectors);
533
+ // Cut under a style changed since: its styles asked for again
534
+ if (style !== state.style)
535
+ await restyleTile(await state.renderer, k);
536
+ }, () => {
537
+ // A failure is asked for again on the next update
538
+ if (held.get(k) === controller)
539
+ held.delete(k);
540
+ }),
541
+ ];
542
+ });
543
+ // Out of view: those still asked for go at once, those drawn once their replacements are there (no hole)
544
+ const drop = (drawn) => {
545
+ const shown = new Set(vector.tileKeys);
546
+ [...held].forEach(([k, controller]) => {
547
+ if (keys.has(k) || shown.has(k) !== drawn)
548
+ return;
549
+ controller.abort();
550
+ held.delete(k);
551
+ vector.removeTile(k);
552
+ });
553
+ };
554
+ drop(false);
555
+ await Promise.all(loads);
556
+ // A later update (the view moved again meanwhile) drops for its own view: these keys are no longer the view
557
+ if (!this.destroyed && generation === state.update)
558
+ drop(true);
559
+ };
560
+ const refresh = () => {
561
+ update().catch(() => undefined);
562
+ };
563
+ /** The style layers changed: the workers' copy, then the styles of the tiles held */
564
+ const restyle = async (list) => {
565
+ state.own = list;
566
+ state.style++;
567
+ state.renderer = state.renderer.then(({ key }) => this.renderer(() => false, list, key));
568
+ const renderer = await state.renderer;
569
+ vector.setSublayers(sublayers(list));
570
+ await Promise.all(vector.tileKeys.map((k) => restyleTile(renderer, k)));
571
+ };
572
+ vector.restyle = (id, group, name, value) => {
573
+ state.renderer
574
+ .then(({ layers: list }) => {
575
+ const next = (state.own ?? list).map((l) => l.id === id ? { ...l, [group]: { ...l[group], [name]: value } } : l);
576
+ // Visibility and dashes are the engine's: the tiles stay as they are
577
+ if ((group === 'layout' && name === 'visibility') || name === 'line-dasharray') {
578
+ state.own = next;
579
+ vector.setSublayers(sublayers(next));
580
+ return undefined;
581
+ }
582
+ // An outline added or taken away: a feature more or less in each tile, cut again
583
+ if (name === 'fill-outline-color' || name === 'fill-antialias') {
584
+ state.own = next;
585
+ state.style++;
586
+ state.renderer = state.renderer.then(({ key }) => this.renderer(() => false, next, key));
587
+ vector.setSublayers(sublayers(next));
588
+ vector.recut?.();
589
+ return undefined;
590
+ }
591
+ return restyle(next);
592
+ })
593
+ .catch(() => undefined);
594
+ };
595
+ vector.recut = () => {
596
+ held.forEach((controller) => {
597
+ controller.abort();
598
+ });
599
+ held.clear();
600
+ refresh();
601
+ };
602
+ vector.styled = state.renderer.then(({ layers: list }) => {
603
+ if (!this.destroyed)
604
+ vector.setSublayers(sublayers(state.own ?? list));
605
+ });
606
+ // Reported by the style's `ready`
607
+ vector.styled.catch(() => undefined);
608
+ // While the camera moves, the tiles follow it (as the labels do: a long drag or flight does not leave the view of
609
+ // its start drawn)
610
+ this.followView(update, held, update);
611
+ return vector;
612
+ }
475
613
  /**
476
614
  * A symbol layer with the labels of the style's symbol layers (or those `layers` keeps), updated as the view
477
615
  * moves: the labels of the vector tiles in view, the higher style layers placed first. With a raster layer of
@@ -565,27 +703,9 @@ export class VectorTiles {
565
703
  }
566
704
  else {
567
705
  const z = Math.min(zoom, maxzoom);
568
- const n = 2 ** z;
569
- const [west, south, east, north] = this.map.getBounds();
570
- const tx = (lon) => Math.floor(mercatorX(lon) * n);
571
- const ty = (lat) => Math.floor(mercatorY(lat) * n);
572
- const [cx, cy] = [mercatorX(camera.center[0]) * n, ty(camera.center[1])];
573
- // The tiles of the bounds, within a window around the center: a tilted view's bounds reach far, and only
574
- // the nearest `maxTiles` are kept anyway
575
- const reach = Math.ceil(Math.sqrt(maxTiles)) + 2;
576
- const [x0, x1] = [
577
- Math.max(0, tx(west), Math.floor(cx) - reach),
578
- Math.min(n - 1, tx(east), Math.floor(cx) + reach),
579
- ];
580
- const [y0, y1] = [
581
- Math.max(0, ty(north), Math.floor(cy) - reach),
582
- Math.min(n - 1, ty(south), Math.floor(cy) + reach),
583
- ];
584
- const wanted = Array.from({ length: y1 - y0 + 1 }, (_, j) => y0 + j).flatMap((y) => Array.from({ length: x1 - x0 + 1 }, (_, i) => [x0 + i, y]));
585
- // Nearest to the center first, at most `maxTiles` (tilted views reach far)
586
- wanted.sort((a, b) => Math.hypot(a[0] + 0.5 - cx, a[1] + 0.5 - cy) - Math.hypot(b[0] + 0.5 - cx, b[1] + 0.5 - cy));
706
+ const wanted = tilesAround(this.map, camera, z, maxTiles);
587
707
  // Past the source's deepest level, its tiles' labels at the zoom of the view (the layers of the deeper zooms)
588
- keys.push(...wanted.slice(0, maxTiles).map(([x, y]) => `${z}/${x}/${y}${zoom > z ? `@${zoom}` : ''}`));
708
+ keys.push(...wanted.map(([x, y]) => `${z}/${x}/${y}${zoom > z ? `@${zoom}` : ''}`));
589
709
  }
590
710
  // The same tiles as the labels shown: nothing to do
591
711
  const set = keys.join(' ');
@@ -653,6 +773,32 @@ export class VectorTiles {
653
773
  refresh();
654
774
  return symbol;
655
775
  }
776
+ /**
777
+ * Makes a layer's tiles follow the view: `update` now and where the camera stops (`moveend`), `moving` every
778
+ * `VECTOR_MOVE_REFRESH_MS` while it moves; the requests `held` aborted when destroyed
779
+ */
780
+ followView(update, held, moving) {
781
+ const refresh = () => {
782
+ update().catch(() => undefined);
783
+ };
784
+ const pace = { timer: 0 };
785
+ const follow = () => {
786
+ if (pace.timer)
787
+ return;
788
+ pace.timer = window.setTimeout(() => {
789
+ pace.timer = 0;
790
+ Promise.resolve(moving()).catch(() => undefined);
791
+ }, VECTOR_MOVE_REFRESH_MS);
792
+ };
793
+ this.cleanup.push(this.map.on('move', follow), this.map.on('moveend', refresh), () => {
794
+ clearTimeout(pace.timer);
795
+ held.forEach((controller) => {
796
+ controller.abort();
797
+ });
798
+ held.clear();
799
+ });
800
+ refresh();
801
+ }
656
802
  /** Stops its workers' work and removes its raster and label layers from the map (those still there) */
657
803
  destroy() {
658
804
  if (this.destroyed)
@@ -690,96 +836,34 @@ export class VectorTiles {
690
836
  this.renderers.length = 0;
691
837
  }
692
838
  }
693
- /** Colors of the layers of `basicStyle`, in turn */
694
- const BASIC_COLORS = ['#2f6fd1', '#d1495b', '#2a9d8f', '#e9a03b', '#7b5ea7', '#5c7a29', '#c8553d', '#3d8eb9'];
695
839
  /**
696
- * A plain style for vector tiles known only by their layers' names (a PMTiles archive's `vector_layers`, an MBTiles'
697
- * metadata): each layer's polygons filled, its lines and outlines stroked and its points as circles, a color per
698
- * layer, the `name` of points as labels. `source` is the style's vector source (`url`: TileJSON or `pmtiles://…`, or
699
- * `tiles`)
840
+ * A `line-dasharray` as the engine takes it: two dashes and gaps in line widths (an odd count repeated, as the
841
+ * canvas's `setLineDash`; past four, the first four), zeros for a solid line
700
842
  */
701
- export const basicStyle = (source, layers) => {
702
- const out = [];
703
- layers.forEach((name, i) => {
704
- const color = BASIC_COLORS[i % BASIC_COLORS.length] ?? '#2f6fd1';
705
- const base = { source: 'data', 'source-layer': name };
706
- out.push({ id: `${name}-fill`, type: 'fill', ...base, paint: { 'fill-color': color, 'fill-opacity': 0.18 } }, { id: `${name}-line`, type: 'line', ...base, paint: { 'line-color': color, 'line-width': 1.2 } }, {
707
- id: `${name}-circle`,
708
- type: 'circle',
709
- ...base,
710
- paint: { 'circle-color': color, 'circle-radius': 3.5, 'circle-stroke-color': '#fff', 'circle-stroke-width': 1 },
711
- });
712
- });
713
- layers.forEach((name) => {
714
- out.push({
715
- id: `${name}-label`,
716
- type: 'symbol',
717
- source: 'data',
718
- 'source-layer': name,
719
- filter: ['all', ['==', ['geometry-type'], 'Point'], ['has', 'name']],
720
- layout: { 'text-field': ['get', 'name'], 'text-size': 12, 'text-offset': [0, 0.9], 'text-anchor': 'top' },
721
- paint: { 'text-color': '#1d2433', 'text-halo-color': '#fff', 'text-halo-width': 1.5 },
722
- });
723
- });
724
- return { version: 8, sources: { data: { type: 'vector', ...source } }, layers: out };
843
+ export const dashes = (value, zoom) => {
844
+ const v = isExpression(value) ? evaluate(value, { zoom, properties: {}, type: 'Unknown' }) : value;
845
+ const list = Array.isArray(v) ? v.map(Number).filter((d) => Number.isFinite(d) && d >= 0) : [];
846
+ const even = list.length % 2 === 1 ? [...list, ...list] : list;
847
+ const [a = 0, b = 0, c = 0, d = 0] = even.length >= 2 && even.some((x) => x > 0) ? even : [];
848
+ return [a, b, c, d];
725
849
  };
726
- /** HTML of a file reduced to its text, escaped: credits from an archive's metadata cannot run in the page */
727
- const plainText = (html) => {
728
- return html
729
- .replace(/<[^>]*>/g, '')
730
- .replace(/&(?!(amp|lt|gt|quot|copy|#\d+);)/g, '&amp;')
731
- .replace(/</g, '&lt;')
732
- .replace(/>/g, '&gt;');
733
- };
734
- /** @internal `GeoMap.addPmtiles`: a raster layer of the archive's images, or vector tiles with their raster layer and
735
- * labels */
736
- export const pmtilesLayer = async (map, url, options) => {
737
- const archiveUrl = pmtilesUrl(url.startsWith('pmtiles://') ? url : `pmtiles://${url}`) ?? url;
738
- const archive = pmtiles(archiveUrl);
739
- const [header, metadata] = await Promise.all([
740
- archive.header(),
741
- archive.metadata().catch(() => ({})),
742
- ]);
743
- const credit = metadata.attribution;
744
- const attribution = options.attribution ?? (typeof credit === 'string' && credit ? plainText(credit) : undefined);
745
- const kind = options.kind ?? (header.tileType === 'mvt' ? 'vector' : 'raster');
746
- const credits = attribution ? { attribution } : {};
747
- if (kind === 'raster') {
748
- return map.addRaster({
749
- url: `pmtiles://${archiveUrl}`,
750
- minZoom: header.minZoom,
751
- maxZoom: Math.max(header.maxZoom, 19),
752
- ...(options.opacity === undefined ? {} : { opacity: options.opacity }),
753
- ...(options.size === undefined ? {} : { size: options.size }),
754
- ...(options.before ? { before: options.before } : {}),
755
- ...credits,
756
- });
757
- }
758
- const layers = metadata.vector_layers;
759
- const names = Array.isArray(layers)
760
- ? layers.map((l) => (isRecord(l) ? l.id : undefined)).filter((id) => typeof id === 'string')
761
- : [];
762
- const style = options.style ?? basicStyle({ url: `pmtiles://${archiveUrl}` }, names);
763
- const tiles = map.vectorTiles({ style, ...credits });
764
- tiles.raster({
765
- ...(options.opacity === undefined ? {} : { opacity: options.opacity }),
766
- ...(options.before ? { before: options.before } : {}),
767
- });
768
- tiles.labels();
769
- return tiles;
770
- };
771
- /** A raster loader reading the tiles of a `pmtiles://` archive URL (images of any size, drawn at `size`); undefined
772
- * for another URL */
773
- export const pmtilesRasterLoader = (url, size) => {
774
- const archiveUrl = pmtilesUrl(url);
775
- if (!archiveUrl)
776
- return undefined;
777
- const archive = pmtiles(archiveUrl);
778
- return async (z, x, y, signal) => {
779
- const bytes = await archive.tile(z, x, y, signal);
780
- if (!bytes)
781
- return null;
782
- return createImageBitmap(new Blob([bytes]), { resizeWidth: size, resizeHeight: size });
783
- };
850
+ /** Metres around the view's center where every tree is drawn at zoom 16 (twice as far a zoom level out) */
851
+ const TREES_NEAR_METRES = 350;
852
+ /** Whether a style layer draws streets, which glow at night: its id names a road (OpenMapTiles' styles, PLAN IGN's),
853
+ * not its casing, a railway, a path or a tunnel */
854
+ const isStreet = (layer) => /road|highway|street|motorway|trunk|primary|secondary|tertiary|minor|routier/i.test(layer.id) &&
855
+ !/casing|outline|rail|path|track|ferry|tunnel|pier|area|pattern|label/i.test(layer.id);
856
+ /** A `line-cap` as the engine draws it, at the camera's zoom (MapLibre's default: butt) */
857
+ const lineCap = (value, zoom) => {
858
+ const v = isExpression(value) ? evaluate(value, { zoom, properties: {}, type: 'Unknown' }) : value;
859
+ return v === 'round' || v === 'square' ? v : 'butt';
784
860
  };
861
+ /** The deepest level `vectors()` cuts its tiles at: past the source's deepest level, its tiles cut again into deeper
862
+ * ones (overzoom, as MapLibre does) down to level 18, their filters and styles those of their level, smaller tiles
863
+ * drawn in a closer view; past it, the tiles of that level stretched */
864
+ const OVERZOOM_LEVEL = 18;
865
+ /** The deepest level of the tiles of `vectors()` over a source whose deepest is `maxzoom` */
866
+ const deepestLevel = (maxzoom) => Math.max(maxzoom, OVERZOOM_LEVEL);
867
+ /** Milliseconds between two updates of the tiles of `vectors()` while the camera moves */
868
+ const VECTOR_MOVE_REFRESH_MS = 250;
785
869
  //# sourceMappingURL=vectortiles.js.map