@maplibre/mlt-wasm 0.1.41 → 0.1.45

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/pkg/README.md ADDED
@@ -0,0 +1,234 @@
1
+ # mlt-wasm
2
+
3
+ WebAssembly bindings for the [MapLibre Tile (MLT)](https://github.com/maplibre/maplibre-tile-spec) decoder.
4
+
5
+ Compiles `mlt-core` to WASM via [wasm-bindgen](https://github.com/rustwasm/wasm-bindgen) and ships a TypeScript wrapper exposing a `VectorTileLike` API.
6
+
7
+ ## Layout
8
+
9
+ ```
10
+ mlt-wasm/
11
+ ├── src/lib.rs # wasm-bindgen bindings
12
+ ├── js/
13
+ │ ├── index.ts # package entry point
14
+ │ ├── wasm.ts # the one module that imports pkg/
15
+ │ ├── annotate.ts # annotated-dump wire contract
16
+ │ ├── columns.ts # typed-array layers, as decoded
17
+ │ └── vectorTile.ts # VectorTileLike wrapper over columns.ts
18
+ ├── pkg/ # wasm-pack output (gitignored)
19
+ ├── dist/ # tsc output (gitignored)
20
+ ├── Cargo.toml
21
+ ├── package.json
22
+ └── tsconfig.json
23
+ ```
24
+
25
+ ## Build
26
+
27
+ Requires [wasm-pack](https://rustwasm.github.io/wasm-pack/installer/) and Node.js.
28
+
29
+ ```sh
30
+ npm run build
31
+ ```
32
+
33
+ This runs `wasm-pack build --target bundler --out-dir pkg` followed by `tsc`. Both steps are also available individually:
34
+
35
+ ```sh
36
+ npm run build:wasm
37
+ npm run build:ts
38
+ ```
39
+
40
+ The `unstable-v2` feature is on by default, so v2 layers decode. Building with
41
+ `--no-default-features` skips them.
42
+
43
+ ## Usage
44
+
45
+ ```ts
46
+ import { decodeTile } from '@maplibre/mlt-wasm';
47
+
48
+ const data = new Uint8Array(await fetch(tileUrl).then(r => r.arrayBuffer()));
49
+ const tile = decodeTile(data);
50
+
51
+ for (const [name, layer] of Object.entries(tile.layers)) {
52
+ for (let i = 0; i < layer.length; i++) {
53
+ const feature = layer.feature(i);
54
+ console.log(feature.type); // 1 | 2 | 3
55
+ console.log(feature.id); // number | undefined
56
+ console.log(feature.properties); // read from the decoded columns
57
+ console.log(feature.loadGeometry()); // Point[][]
58
+ }
59
+ }
60
+ ```
61
+
62
+ ### Columns
63
+
64
+ `decodeTileColumns` hands each layer over as the typed arrays it decodes to, for consumers that
65
+ build their own buffers, such as a renderer. Nothing per feature crosses the WASM boundary.
66
+
67
+ ```ts
68
+ import { columnValue, decodeTileColumns } from '@maplibre/mlt-wasm';
69
+
70
+ for (const layer of decodeTileColumns(data).layers) {
71
+ const { dimension, vertices, zStep } = layer.geometry;
72
+ // vertices: Int32Array of (x, y) pairs, or (x, y, z) triples when dimension is 3
73
+ // geometryOffsets, partOffsets, ringOffsets: cumulative offsets, left out when not needed
74
+ // triangleOffsets, indexBuffer: present on tessellated layers
75
+ for (const column of layer.properties) {
76
+ // column.values has one slot per feature; a slot without a value holds 0 or ""
77
+ for (let f = 0; f < layer.featureCount; f++) {
78
+ const value = columnValue(column, f); // undefined when feature f has no value
79
+ }
80
+ }
81
+ // v2 vertex-scoped (m-value) and nested columns are not passed on
82
+ }
83
+ ```
84
+
85
+ `decodeTileColumns(data, { layers: ['roads', 'water'] })` decodes only the layers with those names,
86
+ every one that has it, since layer names need not be unique. The other layers are skipped undecoded.
87
+
88
+ Each column is `{ name, type, values, present? }`. `present` is a bitmap with one bit per
89
+ feature, LSB-first, left out when every feature has a value. `bool` comes as `0`/`1`, and
90
+ 64-bit integers, ids included, as `Float64Array`, so values above `Number.MAX_SAFE_INTEGER`
91
+ lose precision.
92
+
93
+ A 3D layer's `zStep` is the power of ten of its z grid's step in metres; `toElevation(z, zStep)`
94
+ converts one z to metres, exactly as `mlt-core` does.
95
+
96
+ ### Features
97
+
98
+ `featureGeometry(layer, i)` reads feature `i` of a column layer without knowing the offset levels.
99
+ Its points, lines and polygon rings are views of the layer's vertices, still in tile coordinates,
100
+ and a polygon's rings come ready for earcut. A `TessPolygonsWithOutlines` layer's triangles come per
101
+ feature, counted from the feature's own vertices. A `TessPolygons` layer stores triangles without
102
+ outlines, so `featureGeometry` rejects it; its `indexBuffer` and `triangleOffsets` are the triangles.
103
+
104
+ ```ts
105
+ import { featureGeometry } from '@maplibre/mlt-wasm';
106
+
107
+ const g = featureGeometry(layer, i);
108
+ if (g.kind === 'polygon') {
109
+ for (const { vertices, holeIndices } of g.polygons) {
110
+ const triangles = earcut(vertices, holeIndices, layer.geometry.dimension);
111
+ }
112
+ }
113
+ ```
114
+
115
+ #### Building GPU buffers
116
+
117
+ `layer.geometry.vertices` can be uploaded as the vertex buffer as it is: `dimension` integers per
118
+ vertex, read as `ivec2` or `ivec3` in the shader. What a renderer adds next to it depends on whether
119
+ its shapes need tessellation on the CPU.
120
+
121
+ Shapes drawn as they are, such as points and lines (thick lines can be extruded in the vertex
122
+ shader), need to know where each line starts, to break lines apart, and which feature it belongs to,
123
+ to style or pick it. `geometryStarts(layer.geometry)` gives both for the whole layer, from the tile's
124
+ own offset levels: where each feature's geometries start, where each geometry's vertices start and, in
125
+ a layer with polygons, where each polygon's rings and each ring's vertices start. The tile stores
126
+ these as counts per level, not per vertex, and the arrays are their running totals. Each has one
127
+ entry more than it has items, and stored offset columns come back as they are. They are resolved once
128
+ per layer and every call returns the same arrays, so don't modify them.
129
+
130
+ In a layer of one geometry kind they are what a renderer takes for a batch, such as deck.gl's binary
131
+ `PathLayer` for lines:
132
+
133
+ ```ts
134
+ import { geometryStarts } from '@maplibre/mlt-wasm';
135
+
136
+ const { featureGeometries, geometryVertices, ringVertices } = geometryStarts(layer.geometry);
137
+ // Lines: line g is vertices geometryVertices[g] .. geometryVertices[g + 1], and feature f's lines
138
+ // are featureGeometries[f] .. featureGeometries[f + 1].
139
+ new PathLayer({
140
+ data: {
141
+ length: geometryVertices.length - 1,
142
+ startIndices: geometryVertices,
143
+ attributes: { getPath: { value: layer.geometry.vertices, size: layer.geometry.dimension } },
144
+ },
145
+ _pathType: 'open',
146
+ });
147
+ // Polygons: geometryVertices starts each polygon, ringVertices each ring (outlines without the
148
+ // closing vertex).
149
+ ```
150
+
151
+ A shader that extrudes lines itself reads one vertex at a time, so it needs the line as a vertex
152
+ attribute instead. That is one fill per line from the same starts, done by the renderer for the id it
153
+ uploads:
154
+
155
+ ```ts
156
+ // A segment is drawn only if both ends are the same line.
157
+ const lineOfVertex = new Uint32Array(geometryVertices[geometryVertices.length - 1]);
158
+ for (let g = 0; g + 1 < geometryVertices.length; g++) {
159
+ lineOfVertex.fill(g, geometryVertices[g], geometryVertices[g + 1]);
160
+ }
161
+ ```
162
+
163
+ A geometry is a point, a line or a polygon, and every kind shares one sequence in feature order, so in
164
+ a layer mixing kinds, `layer.geometry.types` tells which features are which. A `TessPolygons` layer has
165
+ no runs of vertices, only triangles, so `geometryStarts` rejects it.
166
+
167
+ On a 1.3 MB tile of 1,333 line features and 524,482 vertices, `geometryStarts` takes about 0.006 ms
168
+ and the fill above about 0.2 ms, against about 3.8 ms for `decodeTileColumns` (Node, one machine).
169
+
170
+ Shapes that need tessellation on the CPU work one polygon or line at a time:
171
+
172
+ - A tessellation that only adds triangles keeps the vertex buffer: earcut's indices are counted from a
173
+ polygon's view in `featureGeometry`, which comes with its hole indices, so adding its `firstVertex`
174
+ makes them an index buffer over `vertices`. A tessellated layer's triangles are that already.
175
+ - A tessellation that creates vertices, such as ribbons with joins built on the CPU or extruded walls,
176
+ reads each line or ring between its starts, writes a buffer of its own, and tags its output with the
177
+ line or feature it came from.
178
+
179
+ ### 3D
180
+
181
+ `decodeTile3D` reads a tile whose every layer has z coordinates. Its features have the same
182
+ `loadGeometry()` and `loadPolygons()`, with every vertex an `[x, y, z]` array, so the rest of the
183
+ code can assume 3D. It throws when any layer has no z coordinates, for which `decodeTile` reads the
184
+ tile in 2D, and when any layer uses the `TessPolygons` or `TessPolygonsWithOutlines` geometry
185
+ layout. `decodeTileColumns` reads every layout, in 2D and 3D.
186
+
187
+ Like `x` and `y`, `z` is the stored integer: it lies on the layer's `zStep` grid, and
188
+ `toElevation(z, layer.zStep)` gives its elevation in metres.
189
+
190
+ ```ts
191
+ import { decodeTile3D } from '@maplibre/mlt-wasm';
192
+
193
+ const tile = decodeTile3D(data);
194
+ for (const [name, layer] of Object.entries(tile.layers)) {
195
+ for (let i = 0; i < layer.length; i++) {
196
+ const feature = layer.feature(i);
197
+ // exterior ring, then holes; each ring is closed (its first vertex is repeated at the end)
198
+ const polygons = feature.loadPolygons(); // [x, y, z][][][]
199
+ }
200
+ }
201
+ ```
202
+
203
+ ## Annotate
204
+
205
+ `annotateTile` walks a tile into the regions an annotated hexdump is made of: every byte beside
206
+ the meaning of the field that owns it. The crate is built with `unstable-v2`, so v1 and v2 tiles
207
+ both annotate.
208
+
209
+ ```ts
210
+ import { annotateTile } from '@maplibre/mlt-wasm';
211
+
212
+ const tile = annotateTile(data);
213
+ const { bufLen, regions } = tile.tree(); // the whole tile
214
+
215
+ for (const [i, region] of regions.entries()) {
216
+ console.log(region.offset, region.len, region.label, region.value);
217
+ if (region.blob) {
218
+ console.log(tile.decodeBlob(i, 64)); // decoded values, capped
219
+ }
220
+ }
221
+
222
+ console.log(tile.error); // null, or what stopped the walk
223
+ tile.free();
224
+ ```
225
+
226
+ `tree(layerIndex)` narrows to one top-level layer, but `decodeBlob` keeps counting the regions of
227
+ the whole tile.
228
+
229
+ A handle, not a document: the tile bytes stay on the WASM side, `tree()` crosses once per layer
230
+ and is memoized, and payload values are decoded one blob at a time with a cap the caller picks.
231
+
232
+ A malformed tile never throws. The walk hands back the regions it reached, `error` carries the
233
+ failure, and a final `<unannotated>` leaf covers the bytes it never got to, so the leaves still
234
+ partition the buffer.
@@ -0,0 +1,63 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+
4
+ /**
5
+ * A tile annotated as far as the walk got, plus the error that stopped it.
6
+ *
7
+ * The handle keeps the tile bytes and the region list on the WASM side.
8
+ * JS pulls the region list across once per layer and asks for decoded payloads one blob at a
9
+ * time, so a tile with tens of thousands of regions costs one conversion rather than one per
10
+ * value.
11
+ */
12
+ export class AnnotatedTile {
13
+ private constructor();
14
+ free(): void;
15
+ [Symbol.dispose](): void;
16
+ /**
17
+ * Decode the payload of the data blob at `region_index`, keeping at most `max_values` values.
18
+ *
19
+ * `max_values` of `0` keeps all of them, and a bytes payload ignores the cap.
20
+ * The index counts the regions of the whole tile, never those of a filtered [`Self::tree`].
21
+ */
22
+ decodeBlob(region_index: number, max_values: number): any;
23
+ /**
24
+ * The regions of the whole tile, or of one top-level layer, memoized per argument.
25
+ *
26
+ * A tree costs a real conversion, so this is a method rather than a getter.
27
+ */
28
+ tree(layer?: number | null): any;
29
+ /**
30
+ * The walker failure that stopped the annotation, or `null`.
31
+ *
32
+ * When set, the tree ends in an `<unannotated>` leaf covering the bytes the walk never
33
+ * reached.
34
+ */
35
+ readonly error: any;
36
+ }
37
+
38
+ /**
39
+ * Annotate a raw MLT tile blob, region by region.
40
+ *
41
+ * Never throws for a malformed tile: the walk hands back what it annotated and
42
+ * [`AnnotatedTile::error`] carries the failure.
43
+ */
44
+ export function annotateTile(data: Uint8Array): AnnotatedTile;
45
+
46
+ /**
47
+ * Decode the layers of `data` into their columns, in wire order: every layer, or with
48
+ * `names`, only those with one of these names. A layer left out is never decoded.
49
+ *
50
+ * v2 layers are skipped unless the crate is built with the `unstable-v2` feature.
51
+ */
52
+ export function decodeTileColumns(data: Uint8Array, names?: string[] | null): Array<any>;
53
+
54
+ /**
55
+ * Decode a raw MLT tile blob into `GeoJSON`, as the serialized text.
56
+ *
57
+ * Every feature carries `_layer` and `_extent`, and a v2 tile's vertex-scoped columns ride
58
+ * along as `m:`-prefixed arrays, one value per vertex.
59
+ *
60
+ * Text rather than a `JsValue`: building the object graph across the boundary costs a
61
+ * crossing per value, where one string plus `JSON.parse` is a single copy.
62
+ */
63
+ export function tileGeoJson(data: Uint8Array): string;
@@ -0,0 +1,9 @@
1
+ /* @ts-self-types="./mlt_wasm.d.ts" */
2
+ import * as wasm from "./mlt_wasm_bg.wasm";
3
+ import { __wbg_set_wasm } from "./mlt_wasm_bg.js";
4
+
5
+ __wbg_set_wasm(wasm);
6
+ wasm.__wbindgen_start();
7
+ export {
8
+ AnnotatedTile, annotateTile, decodeTileColumns, tileGeoJson
9
+ } from "./mlt_wasm_bg.js";