@margoengine/tiles 0.0.0-stage → 0.1.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 (54) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +307 -3
  4. package/dist/bounds-CgKJT3Pg.js +161 -0
  5. package/dist/bounds.d.ts +66 -0
  6. package/dist/data-uri-DbGLVHq5.js +132 -0
  7. package/dist/data-uri.d.ts +2 -0
  8. package/dist/errors-D5_2oB8I.js +7 -0
  9. package/dist/fade.d.ts +34 -0
  10. package/dist/fade.js +129 -0
  11. package/dist/feature-texture.d.ts +19 -0
  12. package/dist/features.d.ts +78 -0
  13. package/dist/features.js +401 -0
  14. package/dist/formats-NNuOXg-1.js +390 -0
  15. package/dist/formats.d.ts +124 -0
  16. package/dist/glb-BU81jlYZ.js +25 -0
  17. package/dist/height.d.ts +20 -0
  18. package/dist/height.js +31 -0
  19. package/dist/i3dm.d.ts +16 -0
  20. package/dist/i3dm.js +85 -0
  21. package/dist/imagery.d.ts +108 -0
  22. package/dist/imagery.js +325 -0
  23. package/dist/implicit.d.ts +42 -0
  24. package/dist/index.d.ts +9 -0
  25. package/dist/index.js +849 -0
  26. package/dist/ion.d.ts +106 -0
  27. package/dist/ion.js +152 -0
  28. package/dist/json-BQoirgm5.js +4 -0
  29. package/dist/matrix-DcI5oFrD.js +89 -0
  30. package/dist/matrix.d.ts +32 -0
  31. package/dist/memory.d.ts +44 -0
  32. package/dist/metadata.d.ts +147 -0
  33. package/dist/metadata.js +285 -0
  34. package/dist/properties.d.ts +94 -0
  35. package/dist/properties.js +320 -0
  36. package/dist/queue.d.ts +37 -0
  37. package/dist/raw-accessor.d.ts +4 -0
  38. package/dist/renderer.d.ts +193 -0
  39. package/dist/s2.d.ts +37 -0
  40. package/dist/s2.js +181 -0
  41. package/dist/scene-scope-DufD_3B6.js +42 -0
  42. package/dist/screen-door-CMv5Jko4.js +11 -0
  43. package/dist/shared/screen-door.d.ts +9 -0
  44. package/dist/splats.d.ts +80 -0
  45. package/dist/splats.js +187 -0
  46. package/dist/style.d.ts +61 -0
  47. package/dist/style.js +609 -0
  48. package/dist/terrain.d.ts +96 -0
  49. package/dist/terrain.js +434 -0
  50. package/dist/tileset.d.ts +316 -0
  51. package/dist/uv-transform.d.ts +11 -0
  52. package/dist/wgs84-C5btsGGY.js +18 -0
  53. package/dist/wgs84.d.ts +24 -0
  54. package/package.json +124 -6
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Scott Campbell
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Margo Engine
2
+ Copyright 2026 Scott Campbell
3
+
4
+ This product includes Margo Engine (https://margoengine.com) by Scott Campbell.
package/README.md CHANGED
@@ -1,3 +1,307 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @margoengine/tiles
2
+
3
+ Import `margoengine/tiles` from the `margoengine` package, or `@margoengine/tiles` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ Streaming [OGC 3D Tiles 1.1](https://docs.ogc.org/cs/22-025r4/22-025r4.html) for engineering, GIS and digital-twin scenes: city models, photogrammetry, BIM and scanned sites far bigger than memory. Tiles load by screen-space error as the camera moves, coarse first, from a priority queue with a concurrency limit, and are evicted least recently used past a memory budget. glTF and b3dm tiles are drawn by [`@margoengine/gltf/pbr`](../gltf/README.md), pnts tiles by [`@margoengine/points`](../points/README.md); both are optional peers loaded with `import()` on the first tile that needs them. Core is not changed, and an app that does not import this package ships none of it.
6
+
7
+ ## Quick start
8
+
9
+ ```ts
10
+ import { Engine } from 'margoengine/core';
11
+ import { TilesRenderer } from 'margoengine/tiles';
12
+
13
+ const canvas = document.querySelector('canvas')!;
14
+ const engine = await Engine.create(canvas, { camera: { position: [0, 400, 600], target: [0, 0, 0], far: 50_000 } });
15
+
16
+ // A real sample city (examples/assets/3d-tiles in this repository); give your own tileset's URL.
17
+ // The tileset's centre lands at the world origin, x east, y up, -z north (the default 'enu' frame).
18
+ const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json', {
19
+ maximumScreenSpaceError: 16, // pixels; lower is sharper and loads more
20
+ memoryBudget: 256 * 1024 * 1024, // bytes of tile content kept
21
+ });
22
+ tiles.tileset.on('progress', ({ queued, loading, ready }) => console.log(`${ready} ready, ${loading + queued} to go`));
23
+ tiles.tileset.on('error', ({ error }) => console.warn(error.message)); // MargoError, code 'failed', names the fix
24
+
25
+ // Place a marker by longitude, latitude (degrees) and height (metres).
26
+ console.log(tiles.cartographicToWorld(-75.6, 40.04, 120));
27
+ engine.start();
28
+ ```
29
+
30
+ The renderer updates selection every frame from `engine.camera`. `tiles.dispose()` (or `using tiles = ...`) aborts every request and frees every tile.
31
+
32
+ ## What it reads
33
+
34
+ | Part of the specification | Support |
35
+ | --- | --- |
36
+ | Tileset JSON | `asset`, `geometricError`, `root`, `children`, `transform` (composed in float64), `refine` (inherited), `content` / `contents` (several per tile), `viewerRequestVolume`, `content.boundingVolume`, `properties`, `extensionsRequired` (unknown required extensions fail with code `unsupported`) |
37
+ | Bounding volumes | `box`, `region` (always in EPSG:4979, ignores transforms), `sphere`; S2 cells (`3DTILES_bounding_volume_S2`, explicit and implicit) with `s2` from `margoengine/tiles/s2` |
38
+ | Refinement | `REPLACE` (children drawn only once every visible child is ready, so no holes and no overlap) and `ADD` |
39
+ | Implicit tiling | `QUADTREE` and `OCTREE`, `subtreeLevels`, `availableLevels` (or the 1.0 extension's `maximumLevel`), binary and JSON subtree files, constant and bitstream availability, child subtrees, `{level}` `{x}` `{y}` `{z}` templates |
40
+ | External tilesets | content that is tileset JSON becomes the tile's child; its transforms continue from the tile |
41
+ | Content | glTF and GLB, b3dm (with `RTC_CENTER` and the batch table), pnts (`POSITION`, `POSITION_QUANTIZED`, `RGBA`, `RGB`, `RGB565`, `NORMAL`, `NORMAL_OCT16P`, `BATCH_ID`, `CONSTANT_RGBA`, Draco-compressed with `dracoPoints` from `margoengine/tiles/metadata`), cmpt (nested), i3dm (`POSITION`, `POSITION_QUANTIZED`, `NORMAL_UP` / `NORMAL_RIGHT` and their oct-encoded forms, `SCALE`, `SCALE_NON_UNIFORM`, `EAST_NORTH_UP`, `RTC_CENTER`, embedded or external glTF; drawn with `i3dm` from `margoengine/tiles/i3dm`), glTF with Gaussian splats (`KHR_gaussian_splatting`, SPZ-compressed or not; drawn with `splats` from `margoengine/tiles/splats`) |
42
+ | Metadata | `schema` / `schemaUri`, `metadata` on the tileset, tiles and contents, `groups`; `tileset.properties(entity)` fills in schema defaults; glTF `EXT_structural_metadata` property tables and `EXT_mesh_features` feature IDs with `readStructuralMetadata` from `margoengine/tiles/metadata` |
43
+
44
+ ## Selection
45
+
46
+ Each update measures every visible tile's screen-space error, `geometricError x screenHeight / (2 x distance x tan(fov / 2))` (perspective) or `geometricError x screenHeight / orthographicHeight`, and refines while it is above `maximumScreenSpaceError`. Tiles outside the camera frustum (or a `viewerRequestVolume` the camera is outside) are skipped. An empty tile always refines. Requests are prioritised in two groups: tiles that fill holes (REPLACE parents still standing in for children, ADD parents) first, coarsest first, then the final tiles nearest first. Requests no longer wanted are dropped from the queue or aborted in flight. With `skipLevelOfDetail`, parents whose error is more than `skipScreenSpaceErrorFactor` times the target are not loaded at all, so a close view fills in at full detail sooner.
47
+
48
+ ## Options
49
+
50
+ `TilesRenderer.load(engine, url, options)` and `Tileset.load(url, options)`:
51
+
52
+ | Option | Default | Meaning |
53
+ | --- | --- | --- |
54
+ | `maximumScreenSpaceError` | `16` | Pixels of error allowed before refining. |
55
+ | `maxConcurrentRequests` | `6` | Requests in flight at once. |
56
+ | `memoryBudget` | 512 MiB | Bytes of ready tiles kept: GPU bytes in `TilesRenderer` (see `budget`), file bytes in `Tileset`. Past it, the least recently used tiles outside the view are evicted; if the view alone needs more, only hole-filling loads start (`tileset.overBudget` is then true). |
57
+ | `skipLevelOfDetail` | `false` | Skip loading far-too-coarse parents (see Selection). |
58
+ | `skipScreenSpaceErrorFactor` | `16` | How coarse a parent may be before it is skipped. |
59
+ | `boundingVolumes` | none | Bounding volume extensions to read: `[s2]` from `margoengine/tiles/s2`. A tileset that requires S2 without it fails with code `unsupported`. |
60
+ | `fetch` | `globalThis.fetch` | Your own fetch: auth headers, an offline cache, tests. |
61
+ | `signal` | none | `AbortSignal` for the load and every later request. |
62
+ | `frame` (renderer) | `'enu'` | `'enu'`, `'local'` or a 4x4 matrix; see below. |
63
+ | `origin` (renderer) | none | A floating origin (`FloatingOrigin` from `margoengine/cameras/origin`). |
64
+ | `loadModel` (renderer) | gltf/pbr's `parseGLTFAsync` | Your own glTF loader. |
65
+ | `budget` (renderer) | `'gpu'` | What `memoryBudget` counts: `'gpu'` the GPU memory each tile's model takes (vertex, index and uv buffers, textures with their mip chains or KTX2 levels, i3dm instance rows, point and splat buffers), so the cache limit matches what the device holds; `'content'` the bytes of each tile's file, as `Tileset` alone counts. |
66
+ | `pointBudget` (renderer) | 2,000,000 | Budget of the points plugin made for pnts tiles. |
67
+ | `i3dm` (renderer) | none | The i3dm drawer from `margoengine/tiles/i3dm`; without it an i3dm tile fails with code `unsupported`. |
68
+ | `dracoPoints` (renderer) | none | The Draco pnts decoder from `margoengine/tiles/metadata`; without it a Draco pnts tile fails with code `unsupported`. |
69
+ | `splats` (renderer) | none | The Gaussian splat drawer from `margoengine/tiles/splats`; without it a glTF tile holding `KHR_gaussian_splatting` fails with code `unsupported`. |
70
+
71
+ ## Coordinates and precision
72
+
73
+ 3D Tiles positions are ECEF metres (EPSG:4978): millions of metres from the earth's centre, where float32 keeps only about half a metre. Everything here stays float64 until the last step. The renderer's `frame` maps tileset coordinates to the engine's world: by default the east-north-up frame at the centre of the root volume becomes the world origin, with x east, y up and -z north (glTF's y-up), and glTF tile content gets the specification's y-up to z-up turn first. Each tile model's root mesh gets one float64 matrix, `frame x tile transform x RTC_CENTER x (y-up to z-up)`, split into translation, rotation and scale. A city 50 km across then sits within 25 km of the origin, where float32 still resolves 2 mm.
74
+
75
+ For a continent or the whole globe, add a floating origin: the renderer places every tile root through it, and it rebases the camera and all placed roots together when the camera wanders, so float32 values stay small wherever you are.
76
+
77
+ ```ts
78
+ import { Engine } from 'margoengine/core';
79
+ import { FloatingOrigin } from 'margoengine/cameras/origin';
80
+ import { TilesRenderer } from 'margoengine/tiles';
81
+
82
+ const engine = await Engine.create(document.querySelector('canvas')!);
83
+ const origin = FloatingOrigin.attach(engine);
84
+ const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json', { origin });
85
+ origin.lookAt(tiles.cartographicToWorld(-75.613, 40.038, 300), tiles.cartographicToWorld(-75.613, 40.042, 0));
86
+ ```
87
+
88
+ `toWorld(ecef)`, `toTileset(world)` and `cartographicToWorld(lon, lat, height)` convert points; the WGS84 helpers (`cartographicToEcef`, `ecefToCartographic`, `eastNorthUpToEcef`) are exported too.
89
+
90
+ ## Instanced content (i3dm)
91
+
92
+ Trees, poles and street furniture often come as i3dm: one glTF and a transform per instance. Pass the drawer from `margoengine/tiles/i3dm` and each glTF primitive draws every instance of its tile in one instanced draw (gltf/pbr's `PBRInstances`). Tilesets without i3dm never load this module.
93
+
94
+ ```ts
95
+ import { Engine } from 'margoengine/core';
96
+ import { TilesRenderer } from 'margoengine/tiles';
97
+ import { i3dm } from 'margoengine/tiles/i3dm';
98
+
99
+ const engine = await Engine.create(document.querySelector('canvas')!);
100
+ // 25 trees as i3dm, a real sample (examples/assets/3d-tiles in this repository).
101
+ const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithTreeBillboards/tileset.json', { i3dm });
102
+ engine.start();
103
+ ```
104
+
105
+ Each instance is placed as the specification says: tile transform x `RTC_CENTER` x instance (position, `NORMAL_RIGHT` and `NORMAL_UP` as the x and y axes, or the east-north-up frame at the instance with `EAST_NORTH_UP`, then the scale) x the glTF's y-up to z-up turn. All of it is float64; the model root sits at the mean instance position, so the float32 instance rows stay within the tile's own size. An external glTF (`gltfFormat` 0) is fetched with the tileset's `fetch`, relative to the tile's content URL. `instanceMatrices` and `instanceCenter` are exported for your own renderer.
106
+
107
+ ## Metadata and Draco points
108
+
109
+ `margoengine/tiles/metadata` reads the binary metadata of 3D Tiles 1.1 content and decodes Draco-compressed point clouds. Tilesets without them never load it.
110
+
111
+ ```ts
112
+ import { Engine } from 'margoengine/core';
113
+ import { TilesRenderer } from 'margoengine/tiles';
114
+ import { dracoPoints, readStructuralMetadata } from 'margoengine/tiles/metadata';
115
+
116
+ const engine = await Engine.create(document.querySelector('canvas')!);
117
+ // Draco-compressed pnts (3DTILES_draco_point_compression) decode in workers, with Draco's own decoder, on first use.
118
+ const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json', { dracoPoints });
119
+ engine.start();
120
+
121
+ // Feature properties of a glTF tile (EXT_structural_metadata and EXT_mesh_features); here a real Cesium sample.
122
+ const gltf = await (await fetch('3d-tiles/EXT_structural_metadata/ComplexTypes/ComplexTypes.gltf')).arrayBuffer();
123
+ const metadata = readStructuralMetadata(new Uint8Array(gltf));
124
+ // A picked vertex (mesh 0, primitive 0, vertex 5, say from a raycast hit) leads to its feature and its properties.
125
+ const feature = metadata.feature(0, 0, 5);
126
+ console.log(feature?.id, feature?.properties);
127
+ console.log(metadata.propertyTables[0].get(1, 'example_variable_length_ARRAY_STRING')); // ['One', 'Two']
128
+ ```
129
+
130
+ `readStructuralMetadata(bytes)` takes a GLB, glTF JSON (data URIs, or `buffer: (index, uri) => bytes` for external buffers) or a tile's `content.gltf`. Property tables read every type of the 3D Tiles Metadata binary table format: `SCALAR`, `VECn`, `MATn` (column-major), `STRING`, `BOOLEAN` (bits) and `ENUM` (as the value's name), fixed and variable-length arrays with any offset type, `normalized` integers, then `offset` and `scale` (the table's override first), and `noData` read as the `default`. `table.get(row, name)` and `table.row(row)` read one feature; a row out of range reads as `undefined`. Feature ID sets come per mesh primitive, with their IDs per vertex for attribute and implicit sets. A malformed table throws a `TypeError` or `RangeError` naming it; nothing reads out of bounds.
131
+
132
+ `dracoPoints(content)` turns Draco pnts into ordinary point content: `POSITION`, `RGBA` or `RGB`, `NORMAL` and `BATCH_ID` from the Draco buffer, and the batch table properties the extension names. For your own renderer, call it from the `Tileset` content factory; a third argument takes any decoder with `decode(bytes)`.
133
+
134
+ ## Gaussian splat tiles
135
+
136
+ Photoreal captures are now published as 3D Tiles whose glTF content holds Gaussian splats (`KHR_gaussian_splatting`, often with the SPZ payload of the draft `KHR_gaussian_splatting_compression_spz_2`, declared through `3DTILES_content_gltf`). Pass the drawer from `margoengine/tiles/splats`: gltf/pbr reads each tile's splats and meshes, and [`@margoengine/splats`](../splats/README.md) draws them. Tilesets without splats never load this module.
137
+
138
+ ```ts
139
+ import { Engine } from 'margoengine/core';
140
+ import { TilesRenderer } from 'margoengine/tiles';
141
+ import { splats } from 'margoengine/tiles/splats';
142
+
143
+ const engine = await Engine.create(document.querySelector('canvas')!, { camera: { position: [170, 40, 250], target: [50, -50, 50] } });
144
+ // CesiumJS's real sh_unit_cube: 27 splats with SH degree 3 in an SPZ payload (examples/assets/3d-tiles in this repository).
145
+ const tiles = await TilesRenderer.load(engine, '3d-tiles/GaussianSplats/sh_unit_cube/tileset.json', { splats });
146
+ engine.start();
147
+ ```
148
+
149
+ Every visible tile's splats go into one cloud, so splats of neighbouring and overlapping tiles sort together rather than tile by tile; the cloud is rebuilt after an update that changed which tiles show (one rebuild for a whole REPLACE swap, so no frame shows both levels or neither) and when a floating origin moves. Each primitive is placed by `frame x tile transform x RTC x y-up to z-up x node` in float64: shapes and harmonics are turned by the linear part, and the translation is added in float64 when the cloud is built, so splats keep float32 precision at the tile's own size even at ECEF distances. Tiles with different harmonic degrees merge at the highest one. Past 3,000,000 visible splats a second cloud starts (`SPLATS_PER_CLOUD`), and those two sort apart. `placeSplats`, `mergePlaced` and `TileSplats` are exported for your own renderer.
150
+
151
+ ## S2 cells
152
+
153
+ Global datasets often bound their tiles with S2 cells (`3DTILES_bounding_volume_S2`): a cell of S2's cube-face hierarchy, by its token, extruded along the ellipsoid normals between two heights. Pass `s2` from `margoengine/tiles/s2`; tilesets without S2 never load it.
154
+
155
+ ```ts
156
+ import { Tileset } from 'margoengine/tiles';
157
+ import { parseS2Token, s2, s2Bounds } from 'margoengine/tiles/s2';
158
+
159
+ // The extension's own example: the S2 cell "89c6c7" over Philadelphia's Center City, from the ground to 1 km.
160
+ const volume = { token: '89c6c7', minimumHeight: 0, maximumHeight: 1000 };
161
+ console.log(parseS2Token(volume.token)); // { face: 4, level: 10, i: ..., j: ... }
162
+ console.log(s2Bounds(volume).radius.toFixed(0), 'm bounding radius');
163
+
164
+ const json = { asset: { version: '1.1' }, geometricError: 100, extensionsRequired: ['3DTILES_bounding_volume_S2'],
165
+ root: { geometricError: 0, boundingVolume: { extensions: { '3DTILES_bounding_volume_S2': volume } } } };
166
+ const tileset = await Tileset.load(URL.createObjectURL(new Blob([JSON.stringify(json)])), { boundingVolumes: [s2] });
167
+ console.log(tileset.root.bounds.center);
168
+ ```
169
+
170
+ Each cell becomes an oriented box in ECEF (east, north and up at the cell's centre) around a 17 x 17 grid of points on its bottom and top surfaces, grown by the curvature between those points, so it holds the whole volume; the tile transform is ignored, as the extension says. Tokens, the Hilbert order on each face (odd faces mirrored) and the quadratic projection follow the extension and the S2 cell hierarchy guide. With implicit tiling a quadtree tile (level, x, y) is the S2 cell at (x, y) on its parent's (i, j) grid, and an octree tile also takes its slab of the heights. `parseS2Token`, `s2Token`, `s2LonLat` and `s2CellBounds` are exported.
171
+
172
+ ## Terrain and imagery
173
+
174
+ `margoengine/tiles/terrain` streams quantized-mesh terrain (the format Cesium terrain servers publish) draped with map imagery, so a globe works without a photogrammetry dataset. `terrain(layerUrl)` reads the layer's `layer.json` and returns a tileset URL and a fetch for the renderer: the layer's two geographic root tiles become an implicit quadtree each, and every terrain tile becomes, on request, a b3dm mesh with skirts, RTC-centred in float64, with its imagery tile as an unlit texture. Selection, streaming, the memory budget and a floating origin are then the renderer's own.
175
+
176
+ ```ts
177
+ import { Engine } from 'margoengine/core';
178
+ import { TilesRenderer } from 'margoengine/tiles';
179
+ import { terrain, terrainFrame } from 'margoengine/tiles/terrain';
180
+
181
+ const engine = await Engine.create(document.querySelector('canvas')!, {
182
+ camera: { position: [0, 8_000_000, 22_000_000], target: [0, 0, 0], near: 100_000, far: 100_000_000 },
183
+ });
184
+ // A real two-level quantized-mesh layer from CesiumJS's test data (examples/assets/terrain in this repository).
185
+ // Add imagery: { url: 'https://your.tile.server/{z}/{x}/{y}.png' } to drape XYZ map tiles you may use.
186
+ const source = await terrain('terrain/QuantizedMeshWithOctVertexNormals/layer.json');
187
+ const tiles = await TilesRenderer.load(engine, source.url, { fetch: source.fetch, frame: 'local' });
188
+ engine.start();
189
+ // Close to the ground, centre the world on your area instead: frame: terrainFrame(86.925, 27.988) (degrees).
190
+ console.log(terrainFrame(86.925, 27.988).length); // 16
191
+ ```
192
+
193
+ `parseQuantizedMesh(bytes)` decodes a tile (header, vertices, triangles, edges, oct normals, water mask, metadata); a cut tile throws a `RangeError`. Imagery is `EPSG:3857` with `xyz` rows by default (`projection`, `scheme`, `maximumLevel`, `mimeType` change it); each terrain tile takes the deepest imagery tile that holds it whole, at most one level deeper than the terrain. Without `imagery` the terrain draws lit, in grey, with the tile's normals or ones made from its triangles. Pass `fetch` to `terrain` for headers such as an access token.
194
+
195
+ ## Height under a place: `@margoengine/tiles/height`
196
+
197
+ `tilesHeightQuery(engine, tiles)` returns `(longitude, latitude) => height`: radians in, metres above the WGS84
198
+ ellipsoid out, from a ray straight down the local vertical against the tiles drawn now (the bvh `Raycaster`, an
199
+ optional peer). It reads the current selection on each call, so it follows streaming, and gives undefined where no
200
+ drawn tile lies. Rays start at `top` (9000 m) and look down to `bottom` (12000 m below the ellipsoid). It is the
201
+ `heightAt` the geospatial camera takes for clearance and walking over tiles.
202
+
203
+ ```ts
204
+ import {Engine} from 'margoengine/core';
205
+ import {TilesRenderer} from 'margoengine/tiles';
206
+ import {tilesHeightQuery} from 'margoengine/tiles/height';
207
+ import {GeospatialControls} from 'margoengine/controls/geospatial';
208
+ import {degToRad} from 'margoengine/math/geo';
209
+
210
+ const engine = await Engine.create(document.querySelector('canvas')!);
211
+ const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json');
212
+ const heightAt = tilesHeightQuery(engine, tiles);
213
+ // The camera works in the tileset's frame and keeps clear of the tiles it stands over.
214
+ const camera = new GeospatialControls(engine, undefined, {
215
+ frame: tiles,
216
+ heightAt,
217
+ view: {longitude: degToRad(-75.6), latitude: degToRad(40.04), range: 800, pitch: degToRad(35)},
218
+ });
219
+ console.log(heightAt(degToRad(-75.6), degToRad(40.04))); // undefined until a tile there is drawn
220
+ ```
221
+
222
+ ## Orthographic cameras
223
+
224
+ Maps and plan views use an orthographic camera, such as `CameraProjection` from `margoengine/cameras`. The renderer reads it from `engine.camera.matrix` with no extra call: when the clip w row is constant, the screen-space error becomes `geometricError x screenHeight / orthographicHeight`, the world height the view shows (converted to tileset units through the frame), so zooming in refines and moving the camera along its axis does not.
225
+
226
+ ```ts
227
+ import { Engine } from 'margoengine/core';
228
+ import { CameraProjection } from 'margoengine/cameras';
229
+ import { TilesRenderer } from 'margoengine/tiles';
230
+
231
+ const canvas = document.querySelector('canvas')!;
232
+ const engine = await Engine.create(canvas, { camera: { position: [0, 2000, 0.01], target: [0, 0, 0], far: 50_000 } });
233
+ // A plan view 600 m tall: tiles refine for 600 m on screen, whatever the eye height.
234
+ const projection = CameraProjection.attach(engine, { mode: 'orthographic', height: 600 });
235
+ const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json');
236
+ tiles.tileset.on('progress', ({ ready }) => console.log(`${ready} tiles ready`));
237
+ engine.start();
238
+ // Later, zoom in four times: the next frame's selection refines for 150 m on screen.
239
+ projection.height = 150;
240
+ ```
241
+
242
+ `TilesRenderer.orthographicHeight(matrix)` returns the view height of an orthographic view-projection matrix and undefined for a perspective one (and for core's all-zero matrix before the first frame).
243
+
244
+ ## Hosted tilesets: sign-in and credits
245
+
246
+ `margoengine/tiles/ion` signs in to token-based tile services and lists the credits they require on screen. `ionAsset(id, { accessToken })` asks Cesium ion for the asset's endpoint and returns its URL, a `fetch` that sends the asset's own short-lived token as a bearer header to that host only (asking ion again once when it answers 401) and its attributions. `hostedTileset(url, { query, headers })` signs any other service: Google's photorealistic 3D Tiles take `{ query: { key } }`, and the `session` a tile URL hands out goes on to the tiles it links (`carry`). `TileCredits.follow(tiles, { credits, element })` keeps an element's text to what the view needs: the service's attributions, then the glTF `asset.copyright` of the tiles drawn now, split on semicolons, most frequent first.
247
+
248
+ ```ts
249
+ import { Engine } from 'margoengine/core';
250
+ import { TilesRenderer } from 'margoengine/tiles';
251
+ import { TileCredits, hostedTileset, ionAsset } from 'margoengine/tiles/ion';
252
+
253
+ const engine = await Engine.create(document.querySelector('canvas')!, {
254
+ camera: { position: [0, 400, 600], target: [0, 0, 0], far: 50_000 },
255
+ });
256
+ // Your Cesium ion token and asset ID (from ion's asset page); without one, a keyed stand-in on this page's server.
257
+ const ionToken = '';
258
+ const source = ionToken
259
+ ? await ionAsset(96188, { accessToken: ionToken })
260
+ : hostedTileset(new URL('3d-tiles/TilesetWithRequestVolume/city/tileset.json', location.href), {
261
+ query: { key: 'your-api-key' },
262
+ });
263
+ const tiles = await TilesRenderer.load(engine, source.url, { fetch: source.fetch });
264
+ const credits = TileCredits.follow(tiles, {
265
+ credits: source.credits,
266
+ element: document.body.appendChild(document.createElement('div')),
267
+ });
268
+ engine.start();
269
+ console.log(credits.text()); // the service's attributions, then the drawn tiles' copyright
270
+ ```
271
+
272
+ A terrain asset works the same way: `terrain(source.url, { fetch: source.fetch })`. `credits.text(separator, true)` leaves out what ion marks `collapsible` (it may sit behind a credits button); `credits.html()` gives the service's own HTML (ion's links and logos) as it sent it, with the tiles' copyright escaped, for an app that trusts the service with its markup. Tokens go in headers, never in URLs the signing adds (a `query` you give is yours). An asset ion only points at (`externalType`, such as Bing imagery) throws code `unsupported`; a refused token or a missing asset throws code `failed`, naming the fix.
273
+
274
+ ## Without the engine
275
+
276
+ `Tileset` is engine-free: give it a view each frame and a content factory, and it does the rest. This is how the tests drive it, and how to stream tiles into your own renderer or a server-side job.
277
+
278
+ ```ts
279
+ import { Tileset, type TileRenderable } from 'margoengine/tiles';
280
+
281
+ const tileset = await Tileset.load('3d-tiles/TilesetWithRequestVolume/city/tileset.json', {
282
+ content: (content, tile, signal): TileRenderable => ({ bytes: content.byteLength, visible: false, dispose() {} }),
283
+ });
284
+ const frame = tileset.update({ position: [1_215_000, -4_736_000, 4_081_000], screenHeight: 1080, fov: 60 });
285
+ for (const tile of frame.selected) console.log(tile.id, tile.screenSpaceError.toFixed(1));
286
+ ```
287
+
288
+ `update(view)` returns the tiles drawn this update. Events: `tileload`, `tileunload`, `error`, `progress` (queued, loading, ready, failed, selected, bytes) and `idle` (the view is complete). `tileset.retry()` forgets failed loads after the network or the file is fixed; failed tiles never stop the rest of the tileset, and a REPLACE parent keeps covering a failed child.
289
+
290
+ The content parsers (`parseB3dm`, `parsePnts`, `parseI3dm`, `parseCmpt`, `parseContent`, `parseSubtree`) are exported for tools. Truncated or corrupt input throws a `TypeError` or `RangeError` naming the problem; it never reads out of bounds.
291
+
292
+ ## Limits
293
+
294
+ - i3dm batch tables are read (`content.batchTable`) but per-instance picking and per-instance colours are not wired to them; an i3dm external glTF resolves against the tile's first content URL.
295
+ - S2 boxes are boxes: near a face cell's corners a box holds more than the cell (selection may load a tile slightly early); the pinned CesiumJS ImplicitHeightSemantics standard-data sample expands 21 cells and contains 45,738 independently calculated WGS84 points at its published heights. It has no content meshes. Binary per-tile height metadata does not tighten the inherited root slab (0..10,000 m instead of 1,000..5,000 m here); production-world rendering is unproved. Other faces and octrees retain the specification/generated controls. Fetch required data with `node scripts/reference-rendering/fetch-skip-assets.mjs`, then run `npm test --workspace @margoengine/tiles`.
296
+ - Terrain: only `EPSG:4326` `tms` layers; tile availability from `layer.json` `available` (a layer without it, such as one using `metadataAvailability`, is assumed whole up to `maxzoom`, and a missing tile fails while its parent stays); one imagery tile per terrain tile, so near the poles and for very coarse terrain the imagery is a level coarser than it could be; every region spans -500 to 9,000 m, so selection boxes are taller than the ground; water mask and metadata are read but not drawn.
297
+ - Splat tiles: the visible cloud is rebuilt on the CPU and uploaded again when the visible tiles change, which costs time in proportion to the visible splats (not measured); splats do not write depth or receive lighting (see `@margoengine/splats`); the renderer's `loadModel` is not used for splat tiles; a glTF tile with external buffers is not read.
298
+ - Metadata: feature ID textures are named, not read (sample the texture yourself); property textures, property attributes and a `schemaUri` schema in glTF are not read; 64-bit integers become doubles (exact to 2^53); feature IDs of a Draco-compressed glTF primitive are not read; picking a vertex is yours (a raycast hit), the tables then give its feature.
299
+ - Draco pnts decode with `@margoengine/decoders/draco-points`: in Web Workers in a browser, in the calling thread in Node.
300
+ - A tile whose glTF requires KHR_techniques_webgl (archived GLSL shaders, such as the billboard level of Cesium's TilesetWithTreeBillboards) fails with code `unsupported`, as glTF says a loader must; the rest of the tileset draws.
301
+ - `budget: 'gpu'` counts gltf/pbr models exactly from their arrays and images (Khronos BoomBox: within 0.1% of what the device allocated); points, i3dm rows and splats by their buffer layouts; a custom `loadModel` whose models have no `primitives` is counted by file size. Uniform buffers, pipelines and the engine's own targets are not tile memory and are not counted.
302
+ - Hosted tilesets: an ion token is asked for again only after a 401, once per expiry; requests to other hosts (a tile URL on another server) go unsigned; the credits are counted from glTF `asset.copyright` only (b3dm, i3dm and glTF content), so pnts tiles and imagery name none; nothing here draws a logo.
303
+ - Orthographic cameras are told apart by the clip w row of `camera.matrix`: a projection that mixes the two (clip w that varies only a little with depth) is read as perspective, and before the first frame the renderer selects as perspective.
304
+
305
+ ### Scenes
306
+
307
+ `TilesRenderer.load` remembers the scene that is active when you call it, before its first await, and attaches the renderer there. The tile models, point anchors and instances it makes later (after fetches and imports) belong to the renderer's own scene, not to the default scene that is active again by then.