@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
@@ -0,0 +1,159 @@
1
+ import type { Box, Region, Sphere } from "@spacexr/3d-tiles-core";
2
+ import type { GeodeticSystem } from "@spacexr/geodesy";
3
+ import { cartesian3, matrix4 } from "@spacexr/geometry";
4
+
5
+ import type { IAxisAlignedBox, IBoundingSphere3, IEcefSpatialState, IVector3 } from "./ecef-types";
6
+
7
+ export type EcefBounds = Pick<IEcefSpatialState, "boundingBox" | "boundingSphere">;
8
+
9
+ export function boundsFromBox(box: Box, matrix: Float64Array): EcefBounds {
10
+ const center = matrix4.transformPoint(matrix, { x: box[0], y: box[1], z: box[2] });
11
+ const axes = [
12
+ matrix4.transformDirection(matrix, { x: box[3], y: box[4], z: box[5] }),
13
+ matrix4.transformDirection(matrix, { x: box[6], y: box[7], z: box[8] }),
14
+ matrix4.transformDirection(matrix, { x: box[9], y: box[10], z: box[11] }),
15
+ ];
16
+ const extent = {
17
+ x: Math.abs(axes[0]!.x) + Math.abs(axes[1]!.x) + Math.abs(axes[2]!.x),
18
+ y: Math.abs(axes[0]!.y) + Math.abs(axes[1]!.y) + Math.abs(axes[2]!.y),
19
+ z: Math.abs(axes[0]!.z) + Math.abs(axes[1]!.z) + Math.abs(axes[2]!.z),
20
+ };
21
+ let radius = 0;
22
+ for (const xSign of [-1, 1]) {
23
+ for (const ySign of [-1, 1]) {
24
+ for (const zSign of [-1, 1]) {
25
+ radius = Math.max(
26
+ radius,
27
+ cartesian3.length({
28
+ x: xSign * axes[0]!.x + ySign * axes[1]!.x + zSign * axes[2]!.x,
29
+ y: xSign * axes[0]!.y + ySign * axes[1]!.y + zSign * axes[2]!.y,
30
+ z: xSign * axes[0]!.z + ySign * axes[1]!.z + zSign * axes[2]!.z,
31
+ }),
32
+ );
33
+ }
34
+ }
35
+ }
36
+ return {
37
+ boundingBox: {
38
+ min: { x: center.x - extent.x, y: center.y - extent.y, z: center.z - extent.z },
39
+ max: { x: center.x + extent.x, y: center.y + extent.y, z: center.z + extent.z },
40
+ },
41
+ boundingSphere: { center, radius },
42
+ };
43
+ }
44
+
45
+ export function boundsFromSphere(sphere: Sphere, matrix: Float64Array): EcefBounds {
46
+ const center = matrix4.transformPoint(matrix, { x: sphere[0], y: sphere[1], z: sphere[2] });
47
+ const radius = sphere[3] * matrix4.maximumScale(matrix);
48
+ return {
49
+ boundingSphere: { center, radius },
50
+ boundingBox: {
51
+ min: { x: center.x - radius, y: center.y - radius, z: center.z - radius },
52
+ max: { x: center.x + radius, y: center.y + radius, z: center.z + radius },
53
+ },
54
+ };
55
+ }
56
+
57
+ function angleWithin(angle: number, west: number, east: number): boolean {
58
+ const fullTurn = Math.PI * 2;
59
+ const normalized = ((angle % fullTurn) + fullTurn) % fullTurn;
60
+ const normalizedWest = ((west % fullTurn) + fullTurn) % fullTurn;
61
+ let normalizedEast = ((east % fullTurn) + fullTurn) % fullTurn;
62
+ if (normalizedEast < normalizedWest) normalizedEast += fullTurn;
63
+ const candidate = normalized < normalizedWest ? normalized + fullTurn : normalized;
64
+ return candidate >= normalizedWest && candidate <= normalizedEast;
65
+ }
66
+
67
+ function regionSamples(region: Region): Array<readonly [number, number, number]> {
68
+ const [west, south, east, north, minimumHeight, maximumHeight] = region;
69
+ const longitudes = new Set([west, east, (west + (east < west ? east + Math.PI * 2 : east)) / 2]);
70
+ for (const candidate of [-Math.PI, -Math.PI / 2, 0, Math.PI / 2, Math.PI]) {
71
+ if (angleWithin(candidate, west, east)) longitudes.add(candidate);
72
+ }
73
+ const latitudes = new Set([south, north, (south + north) / 2]);
74
+ if (south <= 0 && north >= 0) latitudes.add(0);
75
+ const samples: Array<readonly [number, number, number]> = [];
76
+ for (const longitude of longitudes) {
77
+ for (const latitude of latitudes) {
78
+ samples.push([longitude, latitude, minimumHeight], [longitude, latitude, maximumHeight]);
79
+ }
80
+ }
81
+ return samples;
82
+ }
83
+
84
+ export function boundsFromRegion(region: Region, system: GeodeticSystem): EcefBounds {
85
+ return boundsFromPoints(
86
+ regionSamples(region).map(([longitude, latitude, height]) => system.geodeticRadiansToEcef(latitude, longitude, height)),
87
+ );
88
+ }
89
+
90
+ /** Axis-aligned box and enclosing sphere of a set of ECEF sample points. */
91
+ export function boundsFromPoints(points: readonly IVector3[]): EcefBounds {
92
+ const min = { x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY, z: Number.POSITIVE_INFINITY };
93
+ const max = { x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY, z: Number.NEGATIVE_INFINITY };
94
+ for (const point of points) {
95
+ min.x = Math.min(min.x, point.x);
96
+ min.y = Math.min(min.y, point.y);
97
+ min.z = Math.min(min.z, point.z);
98
+ max.x = Math.max(max.x, point.x);
99
+ max.y = Math.max(max.y, point.y);
100
+ max.z = Math.max(max.z, point.z);
101
+ }
102
+ const center = { x: (min.x + max.x) / 2, y: (min.y + max.y) / 2, z: (min.z + max.z) / 2 };
103
+ const radius = points.reduce((current, point) => Math.max(current, cartesian3.distance(point, center)), 0);
104
+ return { boundingBox: { min, max }, boundingSphere: { center, radius } };
105
+ }
106
+
107
+ export function boxesIntersect(left: IAxisAlignedBox, right: IAxisAlignedBox): boolean {
108
+ return !(
109
+ left.max.x < right.min.x ||
110
+ left.min.x > right.max.x ||
111
+ left.max.y < right.min.y ||
112
+ left.min.y > right.max.y ||
113
+ left.max.z < right.min.z ||
114
+ left.min.z > right.max.z
115
+ );
116
+ }
117
+
118
+ export function sphereOutsidePlane(sphere: IBoundingSphere3, plane: { x: number; y: number; z: number; w: number }): boolean {
119
+ return cartesian3.dot(plane, sphere.center) + plane.w < -sphere.radius;
120
+ }
121
+
122
+ /**
123
+ * Whether a tile lies beyond the horizon of a spherical body, from the true formula: a point at distance `p` from the
124
+ * centre is hidden from a camera at distance `c` by a sphere of radius `r` when their angle exceeds
125
+ * `acos(r / c) + acos(r / p)`, the horizons of the camera and of the point. The test takes the highest point of the tile.
126
+ *
127
+ * The sphere must be solid: a sight line may pass over any basin between the camera and the tile, so it lies below the
128
+ * lowest terrain of the body, not only of the tile. A tile without known heights uses the extent of its bounding sphere.
129
+ *
130
+ * @param bodyRadius - Radius of the reference surface of the body, in metres.
131
+ * @param lowestHeight - Lowest terrain of the body over that surface, in metres.
132
+ * @param heightRange - Lowest and highest heights of the tile over that surface, in metres.
133
+ */
134
+ export function isSphereBeyondHorizon(
135
+ sphere: IBoundingSphere3,
136
+ cameraPosition: IVector3,
137
+ bodyRadius: number,
138
+ lowestHeight: number,
139
+ heightRange?: readonly [number, number],
140
+ ): boolean {
141
+ const centreDistance = cartesian3.length(sphere.center);
142
+ if (sphere.radius >= centreDistance) return false;
143
+ const cameraDistance = cartesian3.length(cameraPosition);
144
+ const lowest = heightRange ? bodyRadius + heightRange[0] : centreDistance - sphere.radius;
145
+ const highest = heightRange ? bodyRadius + heightRange[1] : centreDistance + sphere.radius;
146
+ const occluder = Math.min(bodyRadius + Math.min(0, lowestHeight), lowest);
147
+ if (occluder <= 0 || cameraDistance <= occluder) return false;
148
+ const cosine = cartesian3.dot(sphere.center, cameraPosition) / (centreDistance * cameraDistance);
149
+ const angle = Math.acos(Math.max(-1, Math.min(1, cosine)));
150
+ const extent = Math.asin(sphere.radius / centreDistance);
151
+ return angle - extent > Math.acos(occluder / cameraDistance) + Math.acos(occluder / Math.max(occluder, highest));
152
+ }
153
+
154
+ export function isSphereBelowConservativeHorizon(sphere: IBoundingSphere3, cameraPosition: IVector3, occluderRadius: number): boolean {
155
+ const cameraDistance = cartesian3.length(cameraPosition);
156
+ if (cameraDistance <= occluderRadius) return false;
157
+ const centreDotCamera = cartesian3.dot(sphere.center, cameraPosition);
158
+ return centreDotCamera + sphere.radius * cameraDistance < occluderRadius * occluderRadius;
159
+ }
@@ -0,0 +1,110 @@
1
+ import type { GeodeticSystem } from "@spacexr/geodesy";
2
+ import type { ICartesian3 } from "@spacexr/geometry";
3
+
4
+ import type { IUtmPlacement, IUtmPlacementOptions } from "./utm-types";
5
+ import type { IVerticalPlacement } from "./vertical-scale";
6
+
7
+ /** Mutable three-dimensional vector, the `ICartesian3` of `@spacexr/geometry`. ECEF values are expressed in metres. */
8
+ export type IVector3 = ICartesian3;
9
+
10
+ /** Plane equation `ax + by + cz + d = 0`. */
11
+ export interface IPlane {
12
+ /** Plane-normal X component. */
13
+ x: number;
14
+ /** Plane-normal Y component. */
15
+ y: number;
16
+ /** Plane-normal Z component. */
17
+ z: number;
18
+ /** Signed plane offset. */
19
+ w: number;
20
+ }
21
+
22
+ /** Axis-aligned ECEF bounding box. */
23
+ export interface IAxisAlignedBox {
24
+ /** Minimum corner in ECEF metres. */
25
+ min: IVector3;
26
+ /** Maximum corner in ECEF metres. */
27
+ max: IVector3;
28
+ }
29
+
30
+ /** Bounding sphere expressed in ECEF metres. */
31
+ export interface IBoundingSphere3 {
32
+ /** Sphere centre. */
33
+ center: IVector3;
34
+ /** Sphere radius in metres. */
35
+ radius: number;
36
+ }
37
+
38
+ /** Camera state consumed by {@link EcefSpatialMetric}. */
39
+ export interface IEcefCameraFrame {
40
+ /** Optional application camera identifier. */
41
+ id?: string;
42
+ /** Camera position in ECEF metres. */
43
+ position: IVector3;
44
+ /** Viewport height in physical pixels. */
45
+ viewportHeight: number;
46
+ /** Vertical field of view in radians. */
47
+ verticalFovRadians?: number;
48
+ /** Precomputed tangent of half the vertical field of view. */
49
+ tanHalfVerticalFov?: number;
50
+ /** Optional unit direction of the view in ECEF, for orientation and scale displays. Selection does not read it. */
51
+ forward?: IVector3;
52
+ /** Optional normalized ECEF frustum planes. */
53
+ frustumPlanes?: readonly IPlane[];
54
+ /** Optional wider ECEF planes around the view: a tile between them and {@link frustumPlanes} is in the periphery. */
55
+ peripheryFrustumPlanes?: readonly IPlane[];
56
+ /** Optional coarse ECEF clipping box. */
57
+ clipBounds?: IAxisAlignedBox;
58
+ /** Optional source timestamp in milliseconds. */
59
+ timestamp?: number;
60
+ }
61
+
62
+ /** Derived renderer-neutral spatial state for one runtime tile. */
63
+ export interface IEcefSpatialState {
64
+ /** Column-major local-to-ECEF transform. */
65
+ worldTransform: Float64Array;
66
+ /** Optional enclosing ECEF sphere. */
67
+ boundingSphere?: IBoundingSphere3;
68
+ /** Optional enclosing ECEF axis-aligned box. */
69
+ boundingBox?: IAxisAlignedBox;
70
+ /** Lowest and highest heights of the terrain of the tile over the reference surface, in metres, when known. */
71
+ heightRange?: readonly [number, number];
72
+ /** World-space geometric error in metres. */
73
+ geometricError: number;
74
+ /** Report of the conversions and approximations applied, for tiles located by `SPACEXR_bounding_volume_utm`. */
75
+ utmPlacement?: IUtmPlacement;
76
+ /** Point whose height moves the tile with the vertical scale, when the metric has a vertical placement. */
77
+ verticalAnchor?: IVector3;
78
+ /** Origin of the object the tile belongs to; its descendants move with it. */
79
+ verticalObject?: IVector3;
80
+ }
81
+
82
+ /** Configuration for the renderer-neutral ECEF spatial metric. */
83
+ export interface IEcefSpatialMetricOptions {
84
+ /** Geodetic reference system used by region volumes and horizon culling. Supplied explicitly by the caller. */
85
+ geodeticSystem: GeodeticSystem;
86
+ /** Enables conservative ellipsoid horizon culling. Defaults to `true`. */
87
+ horizonCulling?: boolean;
88
+ /**
89
+ * Test of the horizon.
90
+ *
91
+ * - `plane`, the default: tiles behind the plane of the horizon of the smallest sphere of the ellipsoid. It suits oblate
92
+ * bodies, where that sphere lies below the surface. It culls a summit that still shows above the horizon, and on a
93
+ * sphere what lies deeper below the reference surface than the camera is above it.
94
+ * - `tile-heights`: the horizons of the camera and of the highest point of the tile, from the radius of the body and the
95
+ * heights of the tile. The hiding sphere lies below the lowest terrain measured so far, since a sight line may pass over
96
+ * any basin on its way. For spherical bodies.
97
+ */
98
+ horizon?: "plane" | "tile-heights";
99
+ /** Viewport height fallback in pixels. Defaults to 1080. */
100
+ defaultViewportHeight?: number;
101
+ /** Vertical field-of-view fallback in radians. Defaults to 60 degrees. */
102
+ defaultVerticalFovRadians?: number;
103
+ /** Datum transformation and geoid model used to place `SPACEXR_bounding_volume_utm` extents. */
104
+ utm?: IUtmPlacementOptions;
105
+ /**
106
+ * Moves the bounds of objects with the vertical scale of the scene. Not for terrain tiles, whose volumes already hold
107
+ * their scaled heights.
108
+ */
109
+ vertical?: IVerticalPlacement;
110
+ }
@@ -0,0 +1,196 @@
1
+ import { getUtmBoundingVolume } from "@spacexr/3d-tiles-core";
2
+ import type { GeodeticSystem } from "@spacexr/geodesy";
3
+ import { cartesian3, matrix4 } from "@spacexr/geometry";
4
+
5
+ import type { IScreenSpaceErrorContext, ISpatialDerivationContext, ISpatialMetric } from "../ports/spatial";
6
+ import {
7
+ boundsFromBox,
8
+ boundsFromRegion,
9
+ boundsFromSphere,
10
+ boxesIntersect,
11
+ isSphereBelowConservativeHorizon,
12
+ isSphereBeyondHorizon,
13
+ sphereOutsidePlane,
14
+ } from "./bounding-volumes";
15
+ import type { IEcefCameraFrame, IEcefSpatialMetricOptions, IEcefSpatialState } from "./ecef-types";
16
+ import { boundsFromUtm } from "./utm-bounds";
17
+ import type { IUtmPlacementOptions } from "./utm-types";
18
+ import { placeVertically, type IVerticalPlacement } from "./vertical-scale";
19
+ import { metresPerPixel, type IProjectionFallback } from "./view-metrics";
20
+
21
+ const DEFAULT_VIEWPORT_HEIGHT = 1080;
22
+ const DEFAULT_VERTICAL_FOV_RADIANS = Math.PI / 3;
23
+
24
+ /**
25
+ * Renderer-neutral 3D Tiles spatial metric operating in ECEF metres.
26
+ *
27
+ * The class owns 3D Tiles concerns such as transform composition, bounding
28
+ * volume derivation, visibility and screen-space error. Ellipsoid and
29
+ * coordinate-system mathematics are delegated to `@spacexr/geodesy`.
30
+ */
31
+ export class EcefSpatialMetric implements ISpatialMetric<IEcefCameraFrame, IEcefSpatialState> {
32
+ private readonly system: GeodeticSystem;
33
+ private readonly horizonCulling: boolean;
34
+ private readonly horizon: "plane" | "tile-heights";
35
+ /** Lowest terrain measured on any tile so far, over the reference surface, in metres. */
36
+ /** Lowest terrain measured, without the vertical scale, which may change later. */
37
+ private lowestUnscaledHeight = 0;
38
+ private readonly defaultViewportHeight: number;
39
+ private readonly defaultVerticalFovRadians: number;
40
+ /** Viewport height and field of view used when a camera frame does not give them. */
41
+ public readonly projectionFallback: Readonly<IProjectionFallback>;
42
+ private readonly utmOptions: IUtmPlacementOptions;
43
+ private readonly vertical: IVerticalPlacement | undefined;
44
+
45
+ /**
46
+ * Creates an ECEF spatial metric.
47
+ *
48
+ * @param options - Geodetic system and camera fallbacks.
49
+ */
50
+ public constructor(options: IEcefSpatialMetricOptions) {
51
+ if (!options?.geodeticSystem) throw new TypeError("An explicit geodetic system is required.");
52
+ this.system = options.geodeticSystem;
53
+ this.horizonCulling = options.horizonCulling ?? true;
54
+ this.horizon = options.horizon ?? "plane";
55
+ this.defaultViewportHeight = options.defaultViewportHeight ?? DEFAULT_VIEWPORT_HEIGHT;
56
+ this.defaultVerticalFovRadians = options.defaultVerticalFovRadians ?? DEFAULT_VERTICAL_FOV_RADIANS;
57
+ this.utmOptions = options.utm ?? {};
58
+ this.vertical = options.vertical;
59
+ this.projectionFallback = { viewportHeight: this.defaultViewportHeight, verticalFovRadians: this.defaultVerticalFovRadians };
60
+
61
+ if (!Number.isFinite(this.defaultViewportHeight) || this.defaultViewportHeight <= 0) {
62
+ throw new RangeError("The default viewport height must be a positive finite number.");
63
+ }
64
+ if (
65
+ !Number.isFinite(this.defaultVerticalFovRadians) ||
66
+ this.defaultVerticalFovRadians <= 0 ||
67
+ this.defaultVerticalFovRadians >= Math.PI
68
+ ) {
69
+ throw new RangeError("The default vertical field of view must be in the interval (0, PI).");
70
+ }
71
+ }
72
+
73
+ /** Geodetic reference system used for regions and horizon culling. */
74
+ public get geodeticSystem(): GeodeticSystem {
75
+ return this.system;
76
+ }
77
+
78
+ /**
79
+ * Derives world-space state for a tile.
80
+ *
81
+ * Box and sphere volumes receive the accumulated tile transform. A region
82
+ * is already expressed in the tileset geodetic reference system and is not
83
+ * transformed, as required by 3D Tiles. A `SPACEXR_bounding_volume_utm`
84
+ * extent is likewise absolute: it takes precedence over any standard
85
+ * fallback volume and ignores the tile transform. Its datum
86
+ * transformation, geoid handling and margins are reported in
87
+ * `utmPlacement`. When it cannot be placed, the standard volume is used
88
+ * if present; otherwise the state has no bounds and the tile is never culled.
89
+ *
90
+ * @param context - Source tile and optional parent spatial state.
91
+ * @returns Spatial state expressed in ECEF metres.
92
+ */
93
+ public derive(context: ISpatialDerivationContext<IEcefSpatialState>): IEcefSpatialState {
94
+ const unscaled = this.deriveUnscaled(context);
95
+ const state = context.heightRange ? { ...unscaled, heightRange: context.heightRange } : unscaled;
96
+ if (context.heightRange) {
97
+ const scale = this.vertical?.scale.value ?? 1;
98
+ if (scale > 0) this.lowestUnscaledHeight = Math.min(this.lowestUnscaledHeight, context.heightRange[0] / scale);
99
+ }
100
+ return this.vertical ? placeVertically(state, this.vertical, context.parent) : state;
101
+ }
102
+
103
+ private deriveUnscaled(context: ISpatialDerivationContext<IEcefSpatialState>): IEcefSpatialState {
104
+ const worldTransform = matrix4.create();
105
+ matrix4.from(context.tile.transform, worldTransform);
106
+ if (context.parent) matrix4.multiply(context.parent.worldTransform, worldTransform, worldTransform);
107
+ const scale = matrix4.maximumScale(worldTransform);
108
+ const volume = context.tile.boundingVolume;
109
+ const utm = getUtmBoundingVolume(volume);
110
+ const utmBounds = utm ? boundsFromUtm(utm, this.system, this.utmOptions) : undefined;
111
+ const standardBounds = volume.box
112
+ ? boundsFromBox(volume.box, worldTransform)
113
+ : volume.sphere
114
+ ? boundsFromSphere(volume.sphere, worldTransform)
115
+ : volume.region
116
+ ? boundsFromRegion(volume.region, this.system)
117
+ : {};
118
+
119
+ if (utmBounds) {
120
+ const { placement, ...placedBounds } = utmBounds;
121
+ // An extent that cannot be placed falls back to the standard volume, if any; the report states why.
122
+ const bounds = placement.status === "placed" ? placedBounds : standardBounds;
123
+ return { worldTransform, ...bounds, geometricError: context.tile.geometricError * scale, utmPlacement: placement };
124
+ }
125
+ return {
126
+ worldTransform,
127
+ ...standardBounds,
128
+ geometricError: context.tile.geometricError * scale,
129
+ };
130
+ }
131
+
132
+ /**
133
+ * Evaluates coarse clip bounds, conservative horizon culling and frustum planes.
134
+ *
135
+ * @param spatial - Derived tile state.
136
+ * @param camera - Camera expressed in ECEF metres.
137
+ * @returns `true` when the tile may contribute to the current view.
138
+ */
139
+ public isVisible(spatial: IEcefSpatialState, camera: IEcefCameraFrame): boolean {
140
+ return this.isInside(spatial, camera, camera.frustumPlanes);
141
+ }
142
+
143
+ /**
144
+ * Whether a tile is inside the wider planes around the view, with the same bounds and horizon as {@link isVisible}.
145
+ *
146
+ * @param spatial - Derived tile state.
147
+ * @param camera - Camera expressed in ECEF metres.
148
+ * @returns `true` when the camera has such planes and the tile may lie inside them.
149
+ */
150
+ public isInPeriphery(spatial: IEcefSpatialState, camera: IEcefCameraFrame): boolean {
151
+ return camera.peripheryFrustumPlanes !== undefined && this.isInside(spatial, camera, camera.peripheryFrustumPlanes);
152
+ }
153
+
154
+ private isInside(spatial: IEcefSpatialState, camera: IEcefCameraFrame, planes: IEcefCameraFrame["frustumPlanes"]): boolean {
155
+ if (camera.clipBounds && spatial.boundingBox && !boxesIntersect(spatial.boundingBox, camera.clipBounds)) return false;
156
+ if (!spatial.boundingSphere) return true;
157
+ if (this.horizonCulling) {
158
+ const radius = this.system.ellipsoid.minimumRadius;
159
+ const hidden =
160
+ this.horizon === "tile-heights"
161
+ ? isSphereBeyondHorizon(
162
+ spatial.boundingSphere,
163
+ camera.position,
164
+ radius,
165
+ this.lowestUnscaledHeight * (this.vertical?.scale.value ?? 1),
166
+ spatial.heightRange,
167
+ )
168
+ : isSphereBelowConservativeHorizon(spatial.boundingSphere, camera.position, radius);
169
+ if (hidden) return false;
170
+ }
171
+ if (planes?.some((plane) => sphereOutsidePlane(spatial.boundingSphere!, plane))) return false;
172
+ return true;
173
+ }
174
+
175
+ /**
176
+ * Computes projected geometric error in physical pixels.
177
+ *
178
+ * Distance is measured from the camera to the enclosing sphere surface,
179
+ * not merely to its centre. This prevents premature refinement changes
180
+ * near large tiles.
181
+ *
182
+ * @param context - Camera, tile and derived spatial state.
183
+ * @returns Screen-space error in physical pixels.
184
+ */
185
+ public screenSpaceError(context: IScreenSpaceErrorContext<IEcefCameraFrame, IEcefSpatialState>): number {
186
+ if (context.spatial.geometricError <= 0) return 0;
187
+ const camera = context.camera;
188
+ const sphere = context.spatial.boundingSphere;
189
+ const distance = sphere
190
+ ? Math.max(cartesian3.distance(camera.position, sphere.center) - sphere.radius, Number.EPSILON)
191
+ : Math.max(cartesian3.length(camera.position), Number.EPSILON);
192
+ const perPixel = metresPerPixel(camera, distance, this.projectionFallback);
193
+ if (!(perPixel > 0)) return Number.POSITIVE_INFINITY;
194
+ return context.spatial.geometricError / perPixel;
195
+ }
196
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./ecef";
2
+ export * from "./ecef-types";
3
+ export * from "./utm-bounds";
4
+ export * from "./utm-types";
5
+ export * from "./vertical-scale";
6
+ export * from "./view-metrics";
@@ -0,0 +1,151 @@
1
+ import { resolveUtmProjection, type IUtmBoundingVolume, type IUtmProjection, type IVerticalExtent } from "@spacexr/3d-tiles-core";
2
+ import { UtmProjection, type GeodeticSystem } from "@spacexr/geodesy";
3
+
4
+ import { boundsFromPoints, type EcefBounds } from "./bounding-volumes";
5
+ import type { IVector3 } from "./ecef-types";
6
+ import type { IHorizontalDatumTransformation, IUtmPlacement, IUtmPlacementOptions, UtmVerticalOrigin } from "./utm-types";
7
+
8
+ /** Horizontal sample count per axis. */
9
+ const SAMPLES_PER_AXIS = 3;
10
+
11
+ /** No datum transformation is assumed without an application policy. */
12
+ export function defaultHorizontalDatumResolver(_projection: IUtmProjection): IHorizontalDatumTransformation | undefined {
13
+ return undefined;
14
+ }
15
+
16
+ function explicitGeoidMargin(options: IUtmPlacementOptions): number {
17
+ const margin = options.geoidUndulationMargin;
18
+ if (margin === undefined || !Number.isFinite(margin) || margin < 0)
19
+ throw new RangeError("An explicit nonnegative geoid margin or geoid model is required.");
20
+ return margin;
21
+ }
22
+
23
+ interface IVerticalModel {
24
+ origin: UtmVerticalOrigin;
25
+ /** Height interval in metres, ellipsoidal or orthometric depending on `orthometric`. */
26
+ range: [number, number];
27
+ orthometric: boolean;
28
+ }
29
+
30
+ /** Converts signed vertical values to an interval measured upward from the vertical origin. */
31
+ function upwardInterval(vertical: IVerticalExtent): [number, number] {
32
+ return vertical.direction === "DOWN" ? [-vertical.maximum, -vertical.minimum] : [vertical.minimum, vertical.maximum];
33
+ }
34
+
35
+ function verticalModel(vertical: IVerticalExtent, options: IUtmPlacementOptions): IVerticalModel {
36
+ const [lower, upper] = upwardInterval(vertical);
37
+ switch (vertical.reference) {
38
+ case "ELLIPSOID":
39
+ return { origin: "ellipsoid", range: [lower, upper], orthometric: false };
40
+ case "GEOID":
41
+ return { origin: "geoid", range: [lower, upper], orthometric: true };
42
+ case "GROUND":
43
+ if (vertical.groundElevation !== undefined) {
44
+ return {
45
+ origin: "ground-elevation",
46
+ range: [vertical.groundElevation + lower, vertical.groundElevation + upper],
47
+ orthometric: true,
48
+ };
49
+ }
50
+ break;
51
+ }
52
+ return {
53
+ origin: "assumed-terrain",
54
+ range: (() => {
55
+ const range = options.unknownGroundHeightRange;
56
+ if (!range || !range.every(Number.isFinite) || range[0] > range[1])
57
+ throw new RangeError("An explicit valid terrain height envelope is required.");
58
+ return [range[0] + lower, range[1] + upper];
59
+ })(),
60
+ orthometric: false,
61
+ };
62
+ }
63
+
64
+ /**
65
+ * Derives the ellipsoidal height interval of a vertical extent without a geoid model.
66
+ *
67
+ * Orthometric and ground-anchored values use the caller-supplied margin. Ground values
68
+ * without `groundElevation` and `LOCAL` values require an explicit height envelope.
69
+ *
70
+ * @param vertical - Vertical extent of a UTM bounding volume.
71
+ * @returns Minimum and maximum ellipsoidal heights in metres.
72
+ */
73
+ export function ellipsoidalHeightRange(vertical: IVerticalExtent, options: IUtmPlacementOptions): [number, number] {
74
+ const model = verticalModel(vertical, options);
75
+ return model.orthometric ? [model.range[0] - explicitGeoidMargin(options), model.range[1] + explicitGeoidMargin(options)] : model.range;
76
+ }
77
+
78
+ /** ECEF bounds of a UTM extent together with the report of how they were derived. */
79
+ export interface IUtmBounds extends EcefBounds {
80
+ placement: IUtmPlacement;
81
+ }
82
+
83
+ function widen(bounds: EcefBounds, margin: number): EcefBounds {
84
+ if (margin <= 0 || !bounds.boundingBox || !bounds.boundingSphere) return bounds;
85
+ const { min, max } = bounds.boundingBox;
86
+ return {
87
+ boundingBox: {
88
+ min: { x: min.x - margin, y: min.y - margin, z: min.z - margin },
89
+ max: { x: max.x + margin, y: max.y + margin, z: max.z + margin },
90
+ },
91
+ boundingSphere: { center: bounds.boundingSphere.center, radius: bounds.boundingSphere.radius + margin },
92
+ };
93
+ }
94
+
95
+ /**
96
+ * Derives ECEF bounds from a `SPACEXR_bounding_volume_utm` extent.
97
+ *
98
+ * 1. The zone, hemisphere and datum are resolved from the EPSG code or the explicit zone.
99
+ * 2. The UTM grid is inverted on the ellipsoid of the datum.
100
+ * 3. The datum transformation is applied, and the bounds are widened by its accuracy.
101
+ * 4. Heights are converted to ellipsoidal heights with the geoid model, or widened by a geoid margin.
102
+ * 5. A 3 x 3 grid of the extent at both heights is converted to ECEF with `system`.
103
+ *
104
+ * Every step is reported in `placement`. When the projection or the datum cannot be resolved, no bounds are derived.
105
+ *
106
+ * @param extent - UTM extent.
107
+ * @param system - Geodetic system of the ECEF frame.
108
+ * @param options - Datum resolver and geoid model.
109
+ * @returns ECEF bounds and the placement report.
110
+ */
111
+ export function boundsFromUtm(extent: IUtmBoundingVolume, system: GeodeticSystem, options: IUtmPlacementOptions = {}): IUtmBounds {
112
+ const projection = resolveUtmProjection(extent);
113
+ if (!projection) return { placement: { status: "unresolved-projection", horizontalMargin: 0, verticalMargin: 0 } };
114
+
115
+ const datumTransformation = (options.datumResolver ?? defaultHorizontalDatumResolver)(projection);
116
+ if (!datumTransformation) return { placement: { status: "unresolved-datum", projection, horizontalMargin: 0, verticalMargin: 0 } };
117
+
118
+ const vertical = verticalModel(extent.vertical, options);
119
+ const geoid = vertical.orthometric ? (options.geoidUndulation ? "model" : "margin") : undefined;
120
+ const verticalMargin = geoid === "margin" ? explicitGeoidMargin(options) : 0;
121
+ const minimumHeight = vertical.range[0] - verticalMargin;
122
+ const maximumHeight = vertical.range[1] + verticalMargin;
123
+
124
+ const ellipsoid = datumTransformation.sourceEllipsoid ?? system.ellipsoid;
125
+ const utm = new UtmProjection(projection.zone, projection.hemisphere, ellipsoid);
126
+ const points: IVector3[] = [];
127
+ const geodetic = { latitude: 0, longitude: 0, height: 0 };
128
+ for (let i = 0; i < SAMPLES_PER_AXIS; i++) {
129
+ const easting = extent.minEasting + ((extent.maxEasting - extent.minEasting) * i) / (SAMPLES_PER_AXIS - 1);
130
+ for (let j = 0; j < SAMPLES_PER_AXIS; j++) {
131
+ const northing = extent.minNorthing + ((extent.maxNorthing - extent.minNorthing) * j) / (SAMPLES_PER_AXIS - 1);
132
+ utm.projectedToGeodeticRadians(easting, northing, 0, geodetic);
133
+ datumTransformation.transform?.(geodetic);
134
+ const undulation = geoid === "model" ? options.geoidUndulation!(geodetic.latitude, geodetic.longitude) : 0;
135
+ points.push(system.geodeticRadiansToEcef(geodetic.latitude, geodetic.longitude, minimumHeight + undulation));
136
+ points.push(system.geodeticRadiansToEcef(geodetic.latitude, geodetic.longitude, maximumHeight + undulation));
137
+ }
138
+ }
139
+
140
+ const placement: IUtmPlacement = {
141
+ status: "placed",
142
+ projection,
143
+ datumTransformation: { name: datumTransformation.name, accuracy: datumTransformation.accuracy },
144
+ horizontalMargin: datumTransformation.accuracy,
145
+ verticalOrigin: vertical.origin,
146
+ verticalMargin,
147
+ heightRange: [minimumHeight, maximumHeight],
148
+ };
149
+ if (geoid) placement.geoid = geoid;
150
+ return { ...widen(boundsFromPoints(points), datumTransformation.accuracy), placement };
151
+ }