@spacexr/3d-tiles-runtime 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 (78) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +93 -2
  3. package/dist/chunk-AI6NWGCA.js +316 -0
  4. package/dist/chunk-AI6NWGCA.js.map +1 -0
  5. package/dist/chunk-G7YVZYMR.js +24 -0
  6. package/dist/chunk-G7YVZYMR.js.map +1 -0
  7. package/dist/chunk-PJIVVIOF.js +205 -0
  8. package/dist/chunk-PJIVVIOF.js.map +1 -0
  9. package/dist/chunk-Q2AL6LWU.js +3 -0
  10. package/dist/chunk-Q2AL6LWU.js.map +1 -0
  11. package/dist/chunk-Q35HKP5V.js +249 -0
  12. package/dist/chunk-Q35HKP5V.js.map +1 -0
  13. package/dist/chunk-URZDM4BH.js +488 -0
  14. package/dist/chunk-URZDM4BH.js.map +1 -0
  15. package/dist/implicit/index.d.ts +64 -0
  16. package/dist/implicit/index.js +4 -0
  17. package/dist/implicit/index.js.map +1 -0
  18. package/dist/index-CNnPRQZc.d.ts +350 -0
  19. package/dist/index.d.ts +713 -0
  20. package/dist/index.js +3074 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/metadata/index.d.ts +12 -0
  23. package/dist/metadata/index.js +3 -0
  24. package/dist/metadata/index.js.map +1 -0
  25. package/dist/pipeline/index.d.ts +5 -0
  26. package/dist/pipeline/index.js +3 -0
  27. package/dist/pipeline/index.js.map +1 -0
  28. package/dist/ports/index.d.ts +62 -0
  29. package/dist/ports/index.js +4 -0
  30. package/dist/ports/index.js.map +1 -0
  31. package/dist/resource-DH72MRMN.d.ts +34 -0
  32. package/dist/spatial/index.d.ts +402 -0
  33. package/dist/spatial/index.js +3 -0
  34. package/dist/spatial/index.js.map +1 -0
  35. package/dist/spatial-3IDPbyv4.d.ts +28 -0
  36. package/dist/types-Dn5i8Uqg.d.ts +78 -0
  37. package/dist/types-ri64XfSE.d.ts +237 -0
  38. package/package.json +102 -5
  39. package/src/implicit/availability.ts +55 -0
  40. package/src/implicit/coordinates.ts +193 -0
  41. package/src/implicit/dense-subtree-loader.ts +23 -0
  42. package/src/implicit/index.ts +6 -0
  43. package/src/implicit/standard-subtree-loader.ts +71 -0
  44. package/src/implicit/tile-data-source.ts +120 -0
  45. package/src/implicit/types.ts +156 -0
  46. package/src/index.ts +6 -0
  47. package/src/metadata/index.ts +2 -0
  48. package/src/metadata/metadata-resolver.ts +308 -0
  49. package/src/metadata/types.ts +91 -0
  50. package/src/pipeline/index.ts +4 -0
  51. package/src/pipeline/metadata-store.ts +44 -0
  52. package/src/pipeline/ports.ts +62 -0
  53. package/src/pipeline/states.ts +56 -0
  54. package/src/pipeline/tile-3d.ts +165 -0
  55. package/src/ports/camera.ts +12 -0
  56. package/src/ports/content.ts +71 -0
  57. package/src/ports/glyph.ts +13 -0
  58. package/src/ports/index.ts +32 -0
  59. package/src/ports/resource.ts +54 -0
  60. package/src/ports/spatial.ts +28 -0
  61. package/src/ports/telemetry.ts +44 -0
  62. package/src/runtime/cache.ts +112 -0
  63. package/src/runtime/contracts.ts +77 -0
  64. package/src/runtime/events.ts +57 -0
  65. package/src/runtime/hooks.ts +99 -0
  66. package/src/runtime/index.ts +7 -0
  67. package/src/runtime/instrumentation.ts +163 -0
  68. package/src/runtime/priority-scheduler.ts +88 -0
  69. package/src/runtime/quadtree-balance.ts +215 -0
  70. package/src/runtime/tile-runtime.ts +3508 -0
  71. package/src/spatial/bounding-volumes.ts +159 -0
  72. package/src/spatial/ecef-types.ts +110 -0
  73. package/src/spatial/ecef.ts +196 -0
  74. package/src/spatial/index.ts +6 -0
  75. package/src/spatial/utm-bounds.ts +151 -0
  76. package/src/spatial/utm-types.ts +83 -0
  77. package/src/spatial/vertical-scale.ts +125 -0
  78. package/src/spatial/view-metrics.ts +132 -0
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 [yyyy] [name of copyright owner]
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/README.md CHANGED
@@ -1,3 +1,94 @@
1
- # Temporary Holding Version
1
+ [![CI (Node)](https://github.com/pandaGaume/3d-tiles-core/actions/workflows/ci-node.yml/badge.svg)](https://github.com/pandaGaume/3d-tiles-core/actions/workflows/ci-node.yml)
2
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
2
3
 
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.
4
+ <img src="https://raw.githubusercontent.com/pandaGaume/3d-tiles-core/main/assets/brand/spacexr-component.png" alt="SpaceXR Component" height="56">
5
+
6
+ # @spacexr/3d-tiles-runtime
7
+
8
+ Renderer-neutral traversal and content lifecycle for OGC 3D Tiles.
9
+
10
+ The package owns explicit and implicit tileset traversal, sparse subtree availability, screen-space-error refinement, asynchronous content state, external tileset grafting and metadata resolution. Rendering-engine work is delegated to typed ports for camera events, spatial metrics, glTF or terrain content, glyphs and telemetry.
11
+
12
+ ```ts
13
+ import { TileRuntime } from "@spacexr/3d-tiles-runtime";
14
+
15
+ const runtime = new TileRuntime({
16
+ id: "mine",
17
+ uri: "https://example.test/tileset.json",
18
+ adapter,
19
+ cache: {
20
+ maxContentGpuBytes: 1024 * 1024 * 1024,
21
+ maxSubtreeBytes: 64 * 1024 * 1024,
22
+ unusedRetentionMilliseconds: 60_000,
23
+ },
24
+ });
25
+
26
+ await runtime.start();
27
+
28
+ const stopStatistics = runtime.instrumentation.subscribe((statistics) => {
29
+ console.log(statistics.contents.gpuBytes, statistics.pendingLoads);
30
+ });
31
+
32
+ runtime.instrumentation.setEnabled(false);
33
+ ```
34
+
35
+ Standard JSON and binary subtrees are supported through `StandardImplicitSubtreeLoader`. For dense Web Map or DEM pyramids, `ITileDataSource` owns `ITileMetrics`, the root address, URL templates and source metadata. `ImplicitTilesetDecorator` exposes that source as standard implicit 3D Tiles and derives `availableLevels` from `metrics.minLOD` and `metrics.maxLOD`. `WebMapTileDataSource` of `@spacexr/terrain-tileset` and `WebMercatorTileMetrics` of `@spacexr/tiles` provide the XYZ or TMS implementation. An implicit resolver may also register implicit subtrees with `subtreeAt`: from a tile down, a subtree applies its own tiling, availability, contents, resolver and subtree loader, so an application controls the refinement region by region and supplies its own tiles.
36
+
37
+ The runtime includes a bounded navigation cache for renderable handles, subtree payloads and materialized implicit branches. Content adapters report their CPU, GPU and network footprint in `ContentLoadResult.cost`. Cache evictions are visible through events and hooks. Real-time statistics can be subscribed to or disabled at runtime to remove collection and timer overhead.
38
+
39
+ ## Pipeline API
40
+
41
+ New renderer integrations can replace the legacy combined content adapter with two focused ports:
42
+
43
+ - `ITileActivationAdapter` is notified when camera selection activates or deactivates a tile. Its readiness port returns each prepared resource to the runtime.
44
+ - `ITilePresentationAdapter` presents, hides and releases ready opaque renderer handles.
45
+
46
+ `invalidate(predicate)` marks the loaded contents of the tiles a predicate selects as stale, for example the tiles whose region crosses an area whose data changed, and reloads them while their tile is in the working set. The activation adapter receives them with `refresh: true` and their current `handle`. It reports a new handle, which replaces the old one at the start of the next frame (hide, release, then present, before any render), or the same handle once it refreshed it in place. The stale handle stays presented until then: the view never shows a hole. A failed reload keeps the old handle.
47
+
48
+ `Tile3D` stores selection, readiness, presentation and metadata states as numeric enums. Metadata is addressed with compact numeric handles, with `NO_METADATA = -1`. Applications push immutable camera frames and their frustum with `onCameraChanged`, then call `processFrame`.
49
+
50
+ The implicit geodesic grid example of [3d-tiles-babylon](https://github.com/pandaGaume/3d-tiles-babylon) proves the boundary without using the legacy content adapter. Babylon shares only normalized grid topology, then creates unique ECEF geometry for selected implicit tiles using their geographic regions and WGS84. The same boundary allows a later shader implementation to project instanced topology on the GPU.
51
+
52
+ ## ECEF and geodetic systems
53
+
54
+ The built-in `EcefSpatialMetric` uses `@spacexr/geodesy` for ellipsoid and coordinate-system mathematics. WGS84 is the default, while another oblate body can be selected explicitly:
55
+
56
+ ```ts
57
+ import { Ellipsoid, GeodeticSystem } from "@spacexr/geodesy";
58
+ import { EcefSpatialMetric } from "@spacexr/3d-tiles-runtime";
59
+
60
+ const mars = Ellipsoid.fromAxes("Mars", 3396190, 3376200);
61
+ const spatial = new EcefSpatialMetric({
62
+ geodeticSystem: new GeodeticSystem(mars),
63
+ });
64
+ ```
65
+
66
+ The geodesy package owns ellipsoids, geodetic to ECEF conversion and local ENU or NED frames. `@spacexr/geometry` supplies the vector and 4x4 matrix arithmetic. This runtime owns 3D Tiles transforms, bounding volumes, horizon and frustum culling, visibility, and screen-space error.
67
+
68
+ ## UTM extents
69
+
70
+ A scene shares one `VerticalScale`: pass it to the runtime, and to the metric of objects with `vertical: { scale, frame: radialVerticalFrame(reference) }`. See [Vertical scale](../../../docs/celestial-tiling.md#vertical-scale).
71
+
72
+ `EcefSpatialMetric` places tiles whose bounding volume carries the `SPACEXR_bounding_volume_utm` extension. The UTM extent takes precedence over any standard fallback volume. It is inverted with the `@spacexr/geodesy` transverse Mercator projection on the ellipsoid of its datum, transformed to the metric geodetic system, then converted to ECEF.
73
+
74
+ Every approximation widens the bounds and is reported in `IEcefSpatialState.utmPlacement`:
75
+
76
+ - the datum transformation and its accuracy, by which the bounds are widened (`horizontalMargin`);
77
+ - the vertical origin, and whether orthometric heights used a geoid model or the `GEOID_UNDULATION_MARGIN` of 110 m (`verticalMargin`);
78
+ - the ellipsoidal height interval, including `UNKNOWN_GROUND_HEIGHT_RANGE` when the vertical origin is unknown;
79
+ - `unresolved-projection` or `unresolved-datum` when the extent cannot be placed. The standard volume is then used if present.
80
+
81
+ The default resolver targets WGS 84 with the published null transformations: NAD83 (EPSG:1188, 4 m), NAD83(CSRS) (2 m) and ETRS89 (EPSG:1149, 1 m). An extent without a recognized datum is not placed. Supply a resolver and a geoid model for precise placement:
82
+
83
+ ```ts
84
+ const spatial = new EcefSpatialMetric({
85
+ utm: {
86
+ datumResolver: (projection) => myTransformations.get(projection.epsg),
87
+ geoidUndulation: (latitude, longitude) => myGeoid.undulation(latitude, longitude),
88
+ },
89
+ });
90
+ ```
91
+
92
+ `boundsFromUtm` and `ellipsoidalHeightRange` expose the same computation to adapters, and implicit tiling subdivides UTM extents like regions.
93
+
94
+ See the repository document `docs/runtime-architecture.md` for lifecycle and metadata rules.
@@ -0,0 +1,316 @@
1
+ import { StandardUriResolver } from './chunk-G7YVZYMR.js';
2
+ import { getUtmBoundingVolume, createUtmBoundingVolume, SubtreeCodec } from '@spacexr/3d-tiles-core';
3
+
4
+ function coordinateScale(level) {
5
+ const scale = 2 ** level;
6
+ if (!Number.isSafeInteger(scale)) throw new RangeError(`Implicit level ${level} exceeds the safe coordinate range.`);
7
+ return scale;
8
+ }
9
+ function normalizeLongitude(value) {
10
+ if (value === Math.PI) return value;
11
+ const tau = Math.PI * 2;
12
+ return ((value + Math.PI) % tau + tau) % tau - Math.PI;
13
+ }
14
+ function implicitBranchingFactor(tiling) {
15
+ return tiling.subdivisionScheme === "OCTREE" ? 8 : 4;
16
+ }
17
+ function implicitMortonIndex(coordinates, scheme) {
18
+ const dimensions = scheme === "OCTREE" ? 3 : 2;
19
+ let result = 0;
20
+ for (let bit = 0; bit < coordinates.level; bit++) {
21
+ const divisor = 2 ** bit;
22
+ const x = Math.floor(coordinates.x / divisor) % 2;
23
+ const y = Math.floor(coordinates.y / divisor) % 2;
24
+ const z = scheme === "OCTREE" ? Math.floor((coordinates.z ?? 0) / divisor) % 2 : 0;
25
+ result += x * 2 ** (dimensions * bit) + y * 2 ** (dimensions * bit + 1);
26
+ if (dimensions === 3) result += z * 2 ** (dimensions * bit + 2);
27
+ }
28
+ if (!Number.isSafeInteger(result)) throw new RangeError("The Morton index exceeds the JavaScript safe integer range.");
29
+ return result;
30
+ }
31
+ function implicitLevelOffset(level, branchingFactor) {
32
+ const result = (branchingFactor ** level - 1) / (branchingFactor - 1);
33
+ if (!Number.isSafeInteger(result)) throw new RangeError("The availability level offset exceeds the JavaScript safe integer range.");
34
+ return result;
35
+ }
36
+ function implicitAvailabilityIndex(coordinates, tiling) {
37
+ return implicitLevelOffset(coordinates.level, implicitBranchingFactor(tiling)) + implicitMortonIndex(coordinates, tiling.subdivisionScheme);
38
+ }
39
+ function expandImplicitTemplate(template, coordinates) {
40
+ return template.replaceAll("{level}", String(coordinates.level)).replaceAll("{x}", String(coordinates.x)).replaceAll("{y}", String(coordinates.y)).replaceAll("{z}", String(coordinates.z ?? 0));
41
+ }
42
+ function implicitChildCoordinates(parent, childIndex, scheme) {
43
+ const result = {
44
+ level: parent.level + 1,
45
+ x: parent.x * 2 + (childIndex & 1),
46
+ y: parent.y * 2 + (childIndex >> 1 & 1)
47
+ };
48
+ if (scheme === "OCTREE") result.z = (parent.z ?? 0) * 2 + (childIndex >> 2 & 1);
49
+ return result;
50
+ }
51
+ function implicitLocalCoordinates(global, subtreeRoot) {
52
+ const level = global.level - subtreeRoot.level;
53
+ const scale = coordinateScale(level);
54
+ const result = {
55
+ level,
56
+ x: global.x - subtreeRoot.x * scale,
57
+ y: global.y - subtreeRoot.y * scale
58
+ };
59
+ if (global.z !== void 0 || subtreeRoot.z !== void 0) result.z = (global.z ?? 0) - (subtreeRoot.z ?? 0) * scale;
60
+ return result;
61
+ }
62
+ function subdivideUtmExtent(root, scheme, coordinates, scale) {
63
+ const eastingSize = (root.maxEasting - root.minEasting) / scale;
64
+ const northingSize = (root.maxNorthing - root.minNorthing) / scale;
65
+ const minEasting = root.minEasting + eastingSize * coordinates.x;
66
+ const minNorthing = root.minNorthing + northingSize * coordinates.y;
67
+ let vertical = root.vertical;
68
+ if (scheme === "OCTREE") {
69
+ const verticalSize = (root.vertical.maximum - root.vertical.minimum) / scale;
70
+ const offset = verticalSize * (coordinates.z ?? 0);
71
+ vertical = root.vertical.direction === "DOWN" ? { ...root.vertical, minimum: root.vertical.maximum - offset - verticalSize, maximum: root.vertical.maximum - offset } : { ...root.vertical, minimum: root.vertical.minimum + offset, maximum: root.vertical.minimum + offset + verticalSize };
72
+ }
73
+ return { ...root, minEasting, minNorthing, maxEasting: minEasting + eastingSize, maxNorthing: minNorthing + northingSize, vertical };
74
+ }
75
+ function subdivideImplicitBoundingVolume(root, scheme, coordinates) {
76
+ const scale = coordinateScale(coordinates.level);
77
+ const utm = getUtmBoundingVolume(root);
78
+ if (utm) return createUtmBoundingVolume(subdivideUtmExtent(utm, scheme, coordinates, scale));
79
+ if (root.region) {
80
+ const [west, south, east, north, minimumHeight, maximumHeight] = root.region;
81
+ const unwrappedEast = east < west ? east + Math.PI * 2 : east;
82
+ const longitudeSize = (unwrappedEast - west) / scale;
83
+ const latitudeSize = (north - south) / scale;
84
+ const childWest = west + longitudeSize * coordinates.x;
85
+ const childEast = childWest + longitudeSize;
86
+ let childMinimumHeight = minimumHeight;
87
+ let childMaximumHeight = maximumHeight;
88
+ if (scheme === "OCTREE") {
89
+ const heightSize = (maximumHeight - minimumHeight) / scale;
90
+ childMinimumHeight = minimumHeight + heightSize * (coordinates.z ?? 0);
91
+ childMaximumHeight = childMinimumHeight + heightSize;
92
+ }
93
+ return {
94
+ region: [
95
+ normalizeLongitude(childWest),
96
+ south + latitudeSize * coordinates.y,
97
+ normalizeLongitude(childEast),
98
+ south + latitudeSize * (coordinates.y + 1),
99
+ childMinimumHeight,
100
+ childMaximumHeight
101
+ ]
102
+ };
103
+ }
104
+ if (root.box) {
105
+ const [cx, cy, cz, ...axes] = root.box;
106
+ const xAxis = axes.slice(0, 3);
107
+ const yAxis = axes.slice(3, 6);
108
+ const zAxis = axes.slice(6, 9);
109
+ const xCoefficient = -1 + (2 * coordinates.x + 1) / scale;
110
+ const yCoefficient = -1 + (2 * coordinates.y + 1) / scale;
111
+ const zCoefficient = scheme === "OCTREE" ? -1 + (2 * (coordinates.z ?? 0) + 1) / scale : 0;
112
+ const center = [
113
+ cx + xAxis[0] * xCoefficient + yAxis[0] * yCoefficient + zAxis[0] * zCoefficient,
114
+ cy + xAxis[1] * xCoefficient + yAxis[1] * yCoefficient + zAxis[1] * zCoefficient,
115
+ cz + xAxis[2] * xCoefficient + yAxis[2] * yCoefficient + zAxis[2] * zCoefficient
116
+ ];
117
+ const zScale = scheme === "OCTREE" ? scale : 1;
118
+ return {
119
+ box: [
120
+ center[0],
121
+ center[1],
122
+ center[2],
123
+ xAxis[0] / scale,
124
+ xAxis[1] / scale,
125
+ xAxis[2] / scale,
126
+ yAxis[0] / scale,
127
+ yAxis[1] / scale,
128
+ yAxis[2] / scale,
129
+ zAxis[0] / zScale,
130
+ zAxis[1] / zScale,
131
+ zAxis[2] / zScale
132
+ ]
133
+ };
134
+ }
135
+ throw new Error("Implicit tiling requires a box, region or SPACEXR_bounding_volume_utm bounding volume.");
136
+ }
137
+ function computeImplicitTile(rootTile, tiling, coordinates) {
138
+ const templates = rootTile.contents ? [...rootTile.contents] : rootTile.content ? [rootTile.content] : [];
139
+ return {
140
+ boundingVolume: subdivideImplicitBoundingVolume(rootTile.boundingVolume, tiling.subdivisionScheme, coordinates),
141
+ geometricError: rootTile.geometricError / coordinateScale(coordinates.level),
142
+ contents: templates.map((content) => ({ ...content, uri: expandImplicitTemplate(content.uri, coordinates) }))
143
+ };
144
+ }
145
+
146
+ // src/implicit/availability.ts
147
+ var SubtreeAvailabilityError = class extends Error {
148
+ constructor(message) {
149
+ super(message);
150
+ this.name = "SubtreeAvailabilityError";
151
+ }
152
+ };
153
+ function getBit(bytes, index) {
154
+ const byte = bytes[Math.floor(index / 8)];
155
+ if (byte === void 0) throw new SubtreeAvailabilityError(`Availability bit ${index} is outside the referenced buffer view.`);
156
+ return (byte >> index % 8 & 1) === 1;
157
+ }
158
+ var LoadedSubtreeAvailability = class {
159
+ constructor(loaded, tiling) {
160
+ this.loaded = loaded;
161
+ this.tiling = tiling;
162
+ }
163
+ loaded;
164
+ tiling;
165
+ isTileAvailable(coordinates) {
166
+ return this.read(this.loaded.subtree.tileAvailability, implicitAvailabilityIndex(coordinates, this.tiling));
167
+ }
168
+ isContentAvailable(contentIndex, coordinates) {
169
+ const availability = this.loaded.subtree.contentAvailability?.[contentIndex];
170
+ return availability ? this.read(availability, implicitAvailabilityIndex(coordinates, this.tiling)) : false;
171
+ }
172
+ isChildSubtreeAvailable(coordinates) {
173
+ return this.read(this.loaded.subtree.childSubtreeAvailability, implicitMortonIndex(coordinates, this.tiling.subdivisionScheme));
174
+ }
175
+ read(availability, index) {
176
+ if (availability.constant !== void 0) return availability.constant === 1;
177
+ if (availability.bitstream === void 0)
178
+ throw new SubtreeAvailabilityError("Availability must define either constant or bitstream.");
179
+ const view = this.loaded.subtree.bufferViews?.[availability.bitstream];
180
+ if (!view) throw new SubtreeAvailabilityError(`Availability references missing buffer view ${availability.bitstream}.`);
181
+ return getBit(this.bufferView(view), index);
182
+ }
183
+ bufferView(view) {
184
+ const buffer = this.loaded.buffers?.[view.buffer];
185
+ if (!buffer) throw new SubtreeAvailabilityError(`Buffer view references unloaded buffer ${view.buffer}.`);
186
+ const start = view.byteOffset ?? 0;
187
+ const end = start + view.byteLength;
188
+ if (start < 0 || end > buffer.byteLength) throw new SubtreeAvailabilityError("Buffer view exceeds its loaded buffer.");
189
+ return buffer.subarray(start, end);
190
+ }
191
+ };
192
+
193
+ // src/implicit/dense-subtree-loader.ts
194
+ var DenseImplicitSubtreeLoader = class {
195
+ async load(request) {
196
+ if (request.signal.aborted) throw request.signal.reason;
197
+ const hasChildSubtrees = request.coordinates.level + request.implicitTiling.subtreeLevels < request.implicitTiling.availableLevels;
198
+ const subtree = {
199
+ tileAvailability: { constant: 1 },
200
+ ...request.contentCount > 0 ? {
201
+ contentAvailability: Array.from({ length: request.contentCount }, () => ({ constant: 1 }))
202
+ } : {},
203
+ childSubtreeAvailability: { constant: hasChildSubtrees ? 1 : 0 }
204
+ };
205
+ return { subtree };
206
+ }
207
+ };
208
+ var FetchByteResourceLoader = class {
209
+ constructor(fetcher = globalThis.fetch.bind(globalThis)) {
210
+ this.fetcher = fetcher;
211
+ }
212
+ fetcher;
213
+ async load(request) {
214
+ const response = await this.fetcher(request.uri, { signal: request.signal });
215
+ if (!response.ok) throw new Error(`Resource request failed with HTTP ${response.status} for ${request.uri}.`);
216
+ return new Uint8Array(await response.arrayBuffer());
217
+ }
218
+ };
219
+ var StandardImplicitSubtreeLoader = class {
220
+ resources;
221
+ uri;
222
+ codec = new SubtreeCodec();
223
+ constructor(options) {
224
+ this.resources = options.resources;
225
+ this.uri = options.uri ?? new StandardUriResolver();
226
+ }
227
+ async load(request) {
228
+ const bytes = await this.resources.load({ uri: request.uri, signal: request.signal });
229
+ const decoded = this.codec.decode(bytes);
230
+ const declarations = decoded.subtree.buffers ?? [];
231
+ if (declarations.length === 0) return { subtree: decoded.subtree };
232
+ const baseUri = this.uri.baseOf(request.uri);
233
+ const buffers = await Promise.all(
234
+ declarations.map(async (buffer, index) => {
235
+ let payload;
236
+ if (buffer.uri) {
237
+ payload = await this.resources.load({ uri: this.uri.resolve(buffer.uri, baseUri), signal: request.signal });
238
+ } else if (index === 0 && decoded.binaryChunk) {
239
+ payload = decoded.binaryChunk;
240
+ } else {
241
+ throw new Error(`Subtree buffer ${index} has no URI and no internal binary chunk.`);
242
+ }
243
+ if (payload.byteLength < buffer.byteLength) {
244
+ throw new Error(
245
+ `Subtree buffer ${index} declares ${buffer.byteLength} bytes but only ${payload.byteLength} were loaded.`
246
+ );
247
+ }
248
+ return payload.subarray(0, buffer.byteLength);
249
+ })
250
+ );
251
+ return { subtree: decoded.subtree, buffers };
252
+ }
253
+ };
254
+
255
+ // src/implicit/tile-data-source.ts
256
+ function implicitTemplate(template) {
257
+ return template.replaceAll("{z}", "{level}").replaceAll("{lod}", "{level}");
258
+ }
259
+ var ImplicitTilesetDecorator = class {
260
+ constructor(dataSource, options = {}) {
261
+ this.dataSource = dataSource;
262
+ const { metrics, rootAddress } = dataSource;
263
+ if (rootAddress.lod !== metrics.minLOD)
264
+ throw new RangeError(`The source root LOD ${rootAddress.lod} must equal metrics.minLOD ${metrics.minLOD}.`);
265
+ if (dataSource.urlTemplates.length === 0) throw new RangeError("A tile data source must expose at least one URL template.");
266
+ const subtreeLevels = options.subtreeLevels ?? 4;
267
+ if (!Number.isInteger(subtreeLevels) || subtreeLevels < 1)
268
+ throw new RangeError("Implicit subtreeLevels must be a positive integer.");
269
+ const root = dataSource.resolve({ level: 0, x: 0, y: 0 });
270
+ const templates = dataSource.urlTemplates.map((template, index) => ({
271
+ ...root.contents[index] ?? root.contents[0] ?? {},
272
+ uri: implicitTemplate(template)
273
+ }));
274
+ const contentShape = templates.length === 1 ? { content: templates[0] } : {
275
+ contents: templates
276
+ };
277
+ this.tileset = {
278
+ asset: { version: "1.1" },
279
+ geometricError: root.geometricError,
280
+ root: {
281
+ boundingVolume: root.boundingVolume,
282
+ geometricError: root.geometricError,
283
+ refine: options.refine ?? "REPLACE",
284
+ ...root.metadata ? { metadata: root.metadata } : {},
285
+ ...contentShape,
286
+ implicitTiling: {
287
+ subdivisionScheme: "QUADTREE",
288
+ subtreeLevels,
289
+ availableLevels: metrics.maxLOD - metrics.minLOD + 1,
290
+ subtrees: {
291
+ uri: "virtual-subtrees/{level}/{x}/{y}.subtree"
292
+ }
293
+ }
294
+ }
295
+ };
296
+ }
297
+ dataSource;
298
+ tileset;
299
+ /** Address of the tile in the source pyramid, shared by every decorator of the same pyramid. */
300
+ addressOf(context) {
301
+ return this.dataSource.addressOf(context.coordinates);
302
+ }
303
+ resolve(context) {
304
+ const tile = this.dataSource.resolve(context.coordinates, context.computedContents);
305
+ return {
306
+ boundingVolume: tile.boundingVolume,
307
+ geometricError: tile.geometricError,
308
+ contents: tile.contents,
309
+ ...tile.metadata ? { metadata: tile.metadata } : {}
310
+ };
311
+ }
312
+ };
313
+
314
+ export { DenseImplicitSubtreeLoader, FetchByteResourceLoader, ImplicitTilesetDecorator, LoadedSubtreeAvailability, StandardImplicitSubtreeLoader, SubtreeAvailabilityError, computeImplicitTile, expandImplicitTemplate, implicitAvailabilityIndex, implicitBranchingFactor, implicitChildCoordinates, implicitLevelOffset, implicitLocalCoordinates, implicitMortonIndex, subdivideImplicitBoundingVolume };
315
+ //# sourceMappingURL=chunk-AI6NWGCA.js.map
316
+ //# sourceMappingURL=chunk-AI6NWGCA.js.map