@math.gl/geometry 5.0.0-beta.4 → 5.0.0-beta.6

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 (106) hide show
  1. package/README.md +61 -0
  2. package/THIRD-PARTY-NOTICES.md +1 -1
  3. package/dist/color/color-lut-types.d.ts +16 -0
  4. package/dist/color/color-lut-types.d.ts.map +1 -0
  5. package/dist/color/color-lut-types.js +5 -0
  6. package/dist/color/color-lut-types.js.map +1 -0
  7. package/dist/color/index.cjs +132 -0
  8. package/dist/color/index.cjs.map +6 -0
  9. package/dist/color/index.d.ts +4 -0
  10. package/dist/color/index.d.ts.map +1 -0
  11. package/dist/color/index.js +5 -0
  12. package/dist/color/index.js.map +1 -0
  13. package/dist/color/sample-lut.d.ts +13 -0
  14. package/dist/color/sample-lut.d.ts.map +1 -0
  15. package/dist/color/sample-lut.js +132 -0
  16. package/dist/color/sample-lut.js.map +1 -0
  17. package/dist/culling/bounds.d.ts +20 -0
  18. package/dist/culling/bounds.d.ts.map +1 -0
  19. package/dist/culling/bounds.js +121 -0
  20. package/dist/culling/bounds.js.map +1 -0
  21. package/dist/culling/frustum-planes.d.ts +5 -0
  22. package/dist/culling/frustum-planes.d.ts.map +1 -0
  23. package/dist/culling/frustum-planes.js +37 -0
  24. package/dist/culling/frustum-planes.js.map +1 -0
  25. package/dist/culling/geometric-queries.d.ts +34 -0
  26. package/dist/culling/geometric-queries.d.ts.map +1 -0
  27. package/dist/culling/geometric-queries.js +208 -0
  28. package/dist/culling/geometric-queries.js.map +1 -0
  29. package/dist/culling/index.cjs +917 -514
  30. package/dist/culling/index.cjs.map +3 -3
  31. package/dist/culling/index.d.ts +5 -1
  32. package/dist/culling/index.d.ts.map +1 -1
  33. package/dist/culling/index.js +3 -0
  34. package/dist/culling/index.js.map +1 -1
  35. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.d.ts +3 -3
  36. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.d.ts.map +1 -1
  37. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.js +25 -8
  38. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.js.map +1 -1
  39. package/dist/culling/lib/culling-volume.d.ts +3 -0
  40. package/dist/culling/lib/culling-volume.d.ts.map +1 -1
  41. package/dist/culling/lib/culling-volume.js +7 -0
  42. package/dist/culling/lib/culling-volume.js.map +1 -1
  43. package/dist/culling/lib/ray.d.ts +5 -0
  44. package/dist/culling/lib/ray.d.ts.map +1 -1
  45. package/dist/culling/lib/ray.js +21 -0
  46. package/dist/culling/lib/ray.js.map +1 -1
  47. package/dist/curves/adaptive-sampling.d.ts +16 -0
  48. package/dist/curves/adaptive-sampling.d.ts.map +1 -0
  49. package/dist/curves/adaptive-sampling.js +59 -0
  50. package/dist/curves/adaptive-sampling.js.map +1 -0
  51. package/dist/curves/index.d.ts +4 -0
  52. package/dist/curves/index.d.ts.map +1 -1
  53. package/dist/curves/index.js +2 -0
  54. package/dist/curves/index.js.map +1 -1
  55. package/dist/curves/parallel-transport.d.ts +12 -0
  56. package/dist/curves/parallel-transport.d.ts.map +1 -0
  57. package/dist/curves/parallel-transport.js +83 -0
  58. package/dist/curves/parallel-transport.js.map +1 -0
  59. package/dist/index.cjs +1336 -699
  60. package/dist/index.cjs.map +3 -3
  61. package/dist/index.d.ts +10 -1
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.js +5 -0
  64. package/dist/index.js.map +1 -1
  65. package/dist/lighting/index.cjs +175 -0
  66. package/dist/lighting/index.cjs.map +6 -0
  67. package/dist/lighting/index.d.ts +4 -0
  68. package/dist/lighting/index.d.ts.map +1 -0
  69. package/dist/lighting/index.js +5 -0
  70. package/dist/lighting/index.js.map +1 -0
  71. package/dist/lighting/lighting-types.d.ts +16 -0
  72. package/dist/lighting/lighting-types.d.ts.map +1 -0
  73. package/dist/lighting/lighting-types.js +5 -0
  74. package/dist/lighting/lighting-types.js.map +1 -0
  75. package/dist/lighting/photometry.d.ts +36 -0
  76. package/dist/lighting/photometry.d.ts.map +1 -0
  77. package/dist/lighting/photometry.js +181 -0
  78. package/dist/lighting/photometry.js.map +1 -0
  79. package/dist/utils/project-bounds.d.ts +44 -0
  80. package/dist/utils/project-bounds.d.ts.map +1 -0
  81. package/dist/utils/project-bounds.js +93 -0
  82. package/dist/utils/project-bounds.js.map +1 -0
  83. package/dist/utils/project-texture-coordinates.d.ts +19 -0
  84. package/dist/utils/project-texture-coordinates.d.ts.map +1 -0
  85. package/dist/utils/project-texture-coordinates.js +49 -0
  86. package/dist/utils/project-texture-coordinates.js.map +1 -0
  87. package/package.json +15 -3
  88. package/src/color/color-lut-types.ts +19 -0
  89. package/src/color/index.ts +6 -0
  90. package/src/color/sample-lut.ts +175 -0
  91. package/src/culling/bounds.ts +152 -0
  92. package/src/culling/frustum-planes.ts +41 -0
  93. package/src/culling/geometric-queries.ts +299 -0
  94. package/src/culling/index.ts +37 -1
  95. package/src/culling/lib/bounding-volumes/axis-aligned-bounding-box.ts +26 -8
  96. package/src/culling/lib/culling-volume.ts +9 -1
  97. package/src/culling/lib/ray.ts +21 -0
  98. package/src/curves/adaptive-sampling.ts +85 -0
  99. package/src/curves/index.ts +4 -0
  100. package/src/curves/parallel-transport.ts +104 -0
  101. package/src/index.ts +44 -0
  102. package/src/lighting/index.ts +10 -0
  103. package/src/lighting/lighting-types.ts +20 -0
  104. package/src/lighting/photometry.ts +264 -0
  105. package/src/utils/project-bounds.ts +154 -0
  106. package/src/utils/project-texture-coordinates.ts +67 -0
package/src/index.ts CHANGED
@@ -154,6 +154,7 @@ export {
154
154
  export type {
155
155
  CullingResult,
156
156
  ImplicitShape,
157
+ Shape,
157
158
  RayIntersection,
158
159
  BoxShapeProps,
159
160
  CapsuleShapeProps,
@@ -204,3 +205,46 @@ export type {
204
205
  export {composeAttributeProvenance} from './utils/compose-attribute-provenance';
205
206
  export {qualifySurfaceTransition} from './utils/qualify-surface-transition';
206
207
  export type {SurfaceTransitionQualification} from './utils/qualify-surface-transition';
208
+
209
+ export {
210
+ extractFrustumPlanes,
211
+ createEmptyBounds,
212
+ isEmptyBounds,
213
+ boundsContainsPoint,
214
+ boundsContainsBounds,
215
+ boundsIntersect,
216
+ unionBounds,
217
+ intersectBounds,
218
+ expandBoundsByPoint,
219
+ expandBounds,
220
+ clampPointToBounds,
221
+ spheresIntersect,
222
+ boundsIntersectSphere
223
+ } from './culling/index';
224
+ export {
225
+ getRayPoint,
226
+ getClosestPointOnRay,
227
+ distanceToRay,
228
+ getClosestPointsRaySegment,
229
+ transformRay,
230
+ getTriangleBarycentric,
231
+ getTriangleArea,
232
+ getTriangleNormal,
233
+ isTriangleFrontFacing,
234
+ triangleContainsPoint,
235
+ interpolateTriangleAttribute,
236
+ intersectPlaneSegment,
237
+ triangleIntersectsBounds
238
+ } from './culling/geometric-queries';
239
+ export type {RaySegmentClosestPoints} from './culling/geometric-queries';
240
+ export {sampleCurveAdaptive, computeParallelTransportFrames} from './curves/index';
241
+ export type {AdaptiveCurveOptions, AdaptiveCurveSamples, CurveFrames} from './curves/index';
242
+
243
+ export {projectBounds} from './utils/project-bounds';
244
+ export type {
245
+ ProjectionSourceBounds,
246
+ ProjectBoundsOptions,
247
+ ProjectedBoundsResult
248
+ } from './utils/project-bounds';
249
+ export {projectTextureCoordinates} from './utils/project-texture-coordinates';
250
+ export type {ProjectTextureCoordinatesOptions} from './utils/project-texture-coordinates';
@@ -0,0 +1,10 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ export {
5
+ createPhotometricSampler,
6
+ integrateLuminousFlux,
7
+ resamplePhotometricProfile
8
+ } from './photometry';
9
+ export type {PhotometricSampler, PhotometricGrid, PhotometricResampleOptions} from './photometry';
10
+ export type {PhotometricProfile, PhotometricSymmetry} from './lighting-types';
@@ -0,0 +1,20 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ /** Explicit azimuth extension rule; never inferred from a file or its metadata. */
6
+ export type PhotometricSymmetry = 'rotational' | 'quadrant' | 'bilateral' | 'none';
7
+
8
+ /** Format-independent polar/azimuth intensity measurements in degrees and candela. */
9
+ export type PhotometricProfile = {
10
+ /** Ordered polar angles in [0, 180], measured from an application-chosen pole. */
11
+ verticalAngles: ArrayLike<number>;
12
+ /** Ordered azimuth angles in [0, 360], relative to an application-chosen origin. */
13
+ horizontalAngles: ArrayLike<number>;
14
+ /** Candela samples, vertical angle varying fastest. */
15
+ intensities: ArrayLike<number>;
16
+ /** Uniform intensity multiplier; default 1. No lamp, ballast or file metadata is read. */
17
+ intensityScale?: number;
18
+ /** Explicit rotational, quadrant, bilateral or full-circle interpretation. */
19
+ symmetry: PhotometricSymmetry;
20
+ };
@@ -0,0 +1,264 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import type {PhotometricProfile} from './lighting-types';
5
+
6
+ /** Samples a snapshotted polar/azimuth distribution in candela, using angles in degrees. */
7
+ export type PhotometricSampler = (verticalAngle: number, horizontalAngle: number) => number;
8
+
9
+ /** Options for a regular, renderer-independent angular grid. */
10
+ export type PhotometricResampleOptions = {
11
+ /** Samples from vertical 0 through 180 degrees, including both endpoints; default 181. */
12
+ verticalCount?: number;
13
+ /** Horizontal samples around [0, 360), excluding the duplicate seam; default 360. */
14
+ horizontalCount?: number;
15
+ /** Preserve candela or divide by the measured peak; default none. */
16
+ normalization?: 'none' | 'peak';
17
+ };
18
+
19
+ /** Regular angular samples without texture objects or renderer coordinate transforms. */
20
+ export type PhotometricGrid = {
21
+ /** Vertical samples per row. */
22
+ readonly width: number;
23
+ /** Horizontal rows. */
24
+ readonly height: number;
25
+ /** Row-major intensity samples, vertical angle varying fastest. */
26
+ readonly data: Float64Array;
27
+ /** Vertical sample coordinates in degrees. */
28
+ readonly verticalAngles: Float64Array;
29
+ /** Horizontal sample coordinates in degrees. */
30
+ readonly horizontalAngles: Float64Array;
31
+ /** Physical candela or peak-relative values. */
32
+ readonly unit: 'candela' | 'relative';
33
+ /** Measured peak in candela, before optional normalization. */
34
+ readonly peakCandela: number;
35
+ };
36
+
37
+ /** Internal immutable snapshot of the measured distribution. */
38
+ type PreparedPhotometricProfile = {
39
+ /** Measured vertical angles. */
40
+ verticalAngles: Float64Array;
41
+ /** Measured horizontal angles. */
42
+ horizontalAngles: Float64Array;
43
+ /** Scaled candela values. */
44
+ values: Float64Array;
45
+ /** Measured horizontal extent, or zero for rotational symmetry. */
46
+ horizontalSpan: number;
47
+ /** Largest scaled intensity. */
48
+ peak: number;
49
+ };
50
+ const DEGREES_TO_RADIANS = Math.PI / 180;
51
+ const MAX_GRID_SAMPLES = 4_194_304;
52
+
53
+ /** Creates a reusable bilinear sampler; later mutations of the source profile have no effect. */
54
+ export function createPhotometricSampler(profile: PhotometricProfile): PhotometricSampler {
55
+ const prepared = preparePhotometricProfile(profile);
56
+ return (verticalAngle, horizontalAngle) => {
57
+ if (
58
+ !Number.isFinite(verticalAngle) ||
59
+ verticalAngle < 0 ||
60
+ verticalAngle > 180 ||
61
+ !Number.isFinite(horizontalAngle)
62
+ ) {
63
+ throw new Error(
64
+ 'Photometry: sampling requires a vertical angle in [0, 180] and finite horizontal angle'
65
+ );
66
+ }
67
+ return samplePreparedProfile(prepared, verticalAngle, horizontalAngle);
68
+ };
69
+ }
70
+
71
+ /** Integrates the piecewise bilinear angular distribution over solid angle, returning lumens. */
72
+ export function integrateLuminousFlux(profile: PhotometricProfile): number {
73
+ const prepared = preparePhotometricProfile(profile);
74
+ const {verticalAngles, horizontalAngles, values, horizontalSpan} = prepared;
75
+ const rows = new Float64Array(horizontalAngles.length);
76
+ for (let horizontalIndex = 0; horizontalIndex < rows.length; horizontalIndex++) {
77
+ for (let verticalIndex = 0; verticalIndex < verticalAngles.length - 1; verticalIndex++) {
78
+ const lowerAngle = verticalAngles[verticalIndex];
79
+ const upperAngle = verticalAngles[verticalIndex + 1];
80
+ const reflected = lowerAngle + upperAngle > 180;
81
+ const lower = reflected ? 180 - upperAngle : lowerAngle;
82
+ const upper = reflected ? 180 - lowerAngle : upperAngle;
83
+ const midpoint = ((lower + upper) / 2) * DEGREES_TO_RADIANS;
84
+ const halfWidth = ((upper - lower) / 2) * DEGREES_TO_RADIANS;
85
+ // Stable cos(h) - sin(h)/h, including very narrow angular intervals.
86
+ const squaredWidth = halfWidth * halfWidth;
87
+ const difference =
88
+ halfWidth < 0.001
89
+ ? squaredWidth * (-1 / 3 + squaredWidth * (1 / 30 - squaredWidth / 840))
90
+ : Math.cos(halfWidth) - Math.sin(halfWidth) / halfWidth;
91
+ const sharedWeight = Math.sin(midpoint) * Math.sin(halfWidth);
92
+ const offsetWeight = Math.cos(midpoint) * difference;
93
+ const lowerWeight = Math.max(0, sharedWeight + offsetWeight);
94
+ const upperWeight = Math.max(0, sharedWeight - offsetWeight);
95
+ const offset = horizontalIndex * verticalAngles.length + verticalIndex;
96
+ rows[horizontalIndex] +=
97
+ values[offset] * (reflected ? upperWeight : lowerWeight) +
98
+ values[offset + 1] * (reflected ? lowerWeight : upperWeight);
99
+ }
100
+ }
101
+ let flux = 0;
102
+ if (horizontalSpan === 0) flux = rows[0] * 2 * Math.PI;
103
+ else {
104
+ for (let index = 0; index < rows.length - 1; index++) {
105
+ const angularWidth =
106
+ (horizontalAngles[index + 1] - horizontalAngles[index]) * DEGREES_TO_RADIANS;
107
+ flux += (rows[index] / 2 + rows[index + 1] / 2) * angularWidth;
108
+ }
109
+ flux *= 360 / horizontalSpan;
110
+ }
111
+ if (!Number.isFinite(flux)) throw new Error('Photometry: luminous flux overflow');
112
+ return flux;
113
+ }
114
+
115
+ /** Resamples photometry; no image decoding, world-axis conversion or GPU allocation occurs. */
116
+ export function resamplePhotometricProfile(
117
+ profile: PhotometricProfile,
118
+ options: PhotometricResampleOptions = {}
119
+ ): PhotometricGrid {
120
+ const {verticalCount = 181, horizontalCount = 360, normalization = 'none'} = options;
121
+ if (
122
+ !Number.isSafeInteger(verticalCount) ||
123
+ verticalCount < 2 ||
124
+ !Number.isSafeInteger(horizontalCount) ||
125
+ horizontalCount < 1 ||
126
+ verticalCount * horizontalCount > MAX_GRID_SAMPLES ||
127
+ !['none', 'peak'].includes(normalization)
128
+ ) {
129
+ throw new Error('Photometry: invalid resampling dimensions or normalization');
130
+ }
131
+ const prepared = preparePhotometricProfile(profile);
132
+ const verticalAngles = Float64Array.from(
133
+ {length: verticalCount},
134
+ (_, index) => (index * 180) / (verticalCount - 1)
135
+ );
136
+ const horizontalAngles = Float64Array.from(
137
+ {length: horizontalCount},
138
+ (_, index) => (index * 360) / horizontalCount
139
+ );
140
+ const data = new Float64Array(verticalCount * horizontalCount);
141
+ for (let horizontalIndex = 0; horizontalIndex < horizontalCount; horizontalIndex++) {
142
+ for (let verticalIndex = 0; verticalIndex < verticalCount; verticalIndex++) {
143
+ const intensity = samplePreparedProfile(
144
+ prepared,
145
+ verticalAngles[verticalIndex],
146
+ horizontalAngles[horizontalIndex]
147
+ );
148
+ data[horizontalIndex * verticalCount + verticalIndex] =
149
+ normalization === 'peak' ? (prepared.peak > 0 ? intensity / prepared.peak : 0) : intensity;
150
+ }
151
+ }
152
+ return {
153
+ width: verticalCount,
154
+ height: horizontalCount,
155
+ data,
156
+ verticalAngles,
157
+ horizontalAngles,
158
+ unit: normalization === 'peak' ? 'relative' : 'candela',
159
+ peakCandela: prepared.peak
160
+ };
161
+ }
162
+
163
+ /** Validates and snapshots only the angular and intensity fields used by the calculations. */
164
+ function preparePhotometricProfile(profile: PhotometricProfile): PreparedPhotometricProfile {
165
+ const {verticalAngles, horizontalAngles, intensities, intensityScale = 1, symmetry} = profile;
166
+ if (
167
+ verticalAngles.length < 2 ||
168
+ horizontalAngles.length < 1 ||
169
+ intensities.length !== verticalAngles.length * horizontalAngles.length ||
170
+ !Number.isFinite(intensityScale) ||
171
+ intensityScale < 0
172
+ ) {
173
+ throw new Error('Photometry: invalid calculation profile');
174
+ }
175
+ for (const [angles, maximum] of [
176
+ [verticalAngles, 180],
177
+ [horizontalAngles, 360]
178
+ ] as const) {
179
+ for (let index = 0; index < angles.length; index++) {
180
+ if (
181
+ !Number.isFinite(angles[index]) ||
182
+ angles[index] < 0 ||
183
+ angles[index] > maximum ||
184
+ (index > 0 && angles[index] <= angles[index - 1])
185
+ )
186
+ throw new Error('Photometry: invalid calculation angles');
187
+ }
188
+ }
189
+ const first = horizontalAngles[0];
190
+ const last = horizontalAngles[horizontalAngles.length - 1];
191
+ const horizontalSpan = last - first;
192
+ const validSymmetry =
193
+ (symmetry === 'rotational' && horizontalAngles.length === 1) ||
194
+ (symmetry === 'quadrant' && horizontalAngles.length > 1 && first === 0 && last === 90) ||
195
+ (symmetry === 'bilateral' && horizontalAngles.length > 1 && horizontalSpan === 180) ||
196
+ (symmetry === 'none' && horizontalAngles.length > 1 && first === 0 && last === 360);
197
+ if (!validSymmetry) throw new Error('Photometry: symmetry does not match horizontal coverage');
198
+ let peak = 0;
199
+ const values = new Float64Array(intensities.length);
200
+ for (let index = 0; index < values.length; index++) {
201
+ const value = intensities[index];
202
+ const scaled = value * intensityScale;
203
+ if (!Number.isFinite(value) || value < 0 || !Number.isFinite(scaled))
204
+ throw new Error('Photometry: invalid calculation intensity');
205
+ values[index] = scaled;
206
+ peak = Math.max(peak, scaled);
207
+ }
208
+ return {
209
+ verticalAngles: Float64Array.from(verticalAngles),
210
+ horizontalAngles: Float64Array.from(horizontalAngles),
211
+ values,
212
+ horizontalSpan,
213
+ peak
214
+ };
215
+ }
216
+
217
+ /** Samples a validated snapshot, returning zero outside its measured vertical extent. */
218
+ function samplePreparedProfile(
219
+ profile: PreparedPhotometricProfile,
220
+ verticalAngle: number,
221
+ horizontalAngle: number
222
+ ): number {
223
+ const {verticalAngles, horizontalAngles, values, horizontalSpan} = profile;
224
+ if (
225
+ verticalAngle < verticalAngles[0] ||
226
+ verticalAngle > verticalAngles[verticalAngles.length - 1]
227
+ )
228
+ return 0;
229
+ const verticalIndex = findLowerAngle(verticalAngles, verticalAngle);
230
+ const verticalWeight =
231
+ (verticalAngle - verticalAngles[verticalIndex]) /
232
+ (verticalAngles[verticalIndex + 1] - verticalAngles[verticalIndex]);
233
+ let horizontalIndex = 0;
234
+ let horizontalWeight = 0;
235
+ if (horizontalSpan > 0) {
236
+ const period = horizontalSpan === 360 ? 360 : horizontalSpan * 2;
237
+ let folded = (((horizontalAngle - horizontalAngles[0]) % period) + period) % period;
238
+ if (folded > horizontalSpan) folded = period - folded;
239
+ const measuredAngle = horizontalAngles[0] + folded;
240
+ horizontalIndex = findLowerAngle(horizontalAngles, measuredAngle);
241
+ horizontalWeight =
242
+ (measuredAngle - horizontalAngles[horizontalIndex]) /
243
+ (horizontalAngles[horizontalIndex + 1] - horizontalAngles[horizontalIndex]);
244
+ }
245
+ const lowerOffset = horizontalIndex * verticalAngles.length + verticalIndex;
246
+ const upperOffset = horizontalSpan === 0 ? lowerOffset : lowerOffset + verticalAngles.length;
247
+ const lowerValue =
248
+ values[lowerOffset] + (values[lowerOffset + 1] - values[lowerOffset]) * verticalWeight;
249
+ const upperValue =
250
+ values[upperOffset] + (values[upperOffset + 1] - values[upperOffset]) * verticalWeight;
251
+ return lowerValue + (upperValue - lowerValue) * horizontalWeight;
252
+ }
253
+
254
+ /** Finds the lower knot, keeping the final coordinate in the last interval. */
255
+ function findLowerAngle(angles: Float64Array, angle: number): number {
256
+ let lower = 0;
257
+ let upper = angles.length - 1;
258
+ while (upper - lower > 1) {
259
+ const midpoint = Math.floor((lower + upper) / 2);
260
+ if (angle < angles[midpoint]) upper = midpoint;
261
+ else lower = midpoint;
262
+ }
263
+ return Math.min(lower, angles.length - 2);
264
+ }
@@ -0,0 +1,154 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ /** A finite, continuous source box with ordered minimum and maximum coordinates. */
6
+ export type ProjectionSourceBounds = readonly [ArrayLike<number>, ArrayLike<number>];
7
+
8
+ /** Controls bounded sampling of a prepared synchronous coordinate transform. */
9
+ export type ProjectBoundsOptions = {
10
+ /** Receives a fresh source array. Null/nonfinite output rejects the whole result.
11
+ * Exceptions propagate unchanged; no projection engine is imported by this helper.
12
+ */
13
+ transform: (position: readonly number[]) => ArrayLike<number> | null;
14
+ /** Output dimension, 2 or 3. Defaults to the source dimension. */
15
+ targetSize?: 2 | 3;
16
+ /** Equal subdivisions on each nonzero source axis. Positive integer; default 8. */
17
+ subdivisions?: number;
18
+ /** Maximum transform calls. Positive safe integer; default 262144. */
19
+ maxSamples?: number;
20
+ /** Optional caller-qualified global Lipschitz constant for EACH output component,
21
+ * measured against Euclidean source distance over the ENTIRE source box.
22
+ * Requires a finite continuous transform throughout the box, not merely at samples.
23
+ * This contract cannot be inferred or verified from point samples.
24
+ */
25
+ lipschitz?: readonly number[];
26
+ };
27
+
28
+ /** Detached bounds plus an explicit qualification; invalid results never expose partial bounds. */
29
+ export type ProjectedBoundsResult =
30
+ | {
31
+ /** 'sampled' is for approximate fitting only; 'conservative' requires the supplied contract. */
32
+ status: 'sampled' | 'conservative';
33
+ /** Output minimum and maximum vectors; safe for culling only in conservative mode. */
34
+ bounds: [number[], number[]];
35
+ /** Number of transform calls. */
36
+ sampleCount: number;
37
+ }
38
+ | {
39
+ /** A null/nonfinite transform sample or unrepresentable enclosure was encountered. */
40
+ status: 'invalid';
41
+ /** No partial result is safe to use. */
42
+ bounds: null;
43
+ /** Number of transform calls, including an invalid sample if applicable. */
44
+ sampleCount: number;
45
+ };
46
+
47
+ /** Projects a lattice covering corners, edges, faces and the interior of a 2D/3D box.
48
+ * Sampling alone cannot establish an enclosure for a nonlinear transform. When qualified
49
+ * global Lipschitz constants are supplied, inflate by the lattice covering radius instead
50
+ * of claiming corner/sample extrema are conservative. Split seams and domains beforehand.
51
+ */
52
+ export function projectBounds(
53
+ sourceBounds: ProjectionSourceBounds,
54
+ options: ProjectBoundsOptions
55
+ ): ProjectedBoundsResult {
56
+ const [minimum, maximum] = sourceBounds;
57
+ const size = minimum.length;
58
+ const {transform, targetSize = size, subdivisions = 8, maxSamples = 262144, lipschitz} = options;
59
+ if (
60
+ (size !== 2 && size !== 3) ||
61
+ maximum.length !== size ||
62
+ (targetSize !== 2 && targetSize !== 3)
63
+ ) {
64
+ throw new RangeError('Bounds and target dimension must be 2 or 3');
65
+ }
66
+ if (
67
+ !Number.isSafeInteger(subdivisions) ||
68
+ subdivisions < 1 ||
69
+ !Number.isSafeInteger(maxSamples) ||
70
+ maxSamples < 1
71
+ ) {
72
+ throw new RangeError('Subdivision and sample budgets must be positive safe integers');
73
+ }
74
+ if (
75
+ lipschitz &&
76
+ (lipschitz.length !== targetSize ||
77
+ !Array.from(lipschitz).every(value => Number.isFinite(value) && value >= 0))
78
+ ) {
79
+ throw new RangeError('Lipschitz constants must be finite, nonnegative and match target size');
80
+ }
81
+ const widths: number[] = [];
82
+ const counts: number[] = [];
83
+ let count = 1;
84
+ for (let axis = 0; axis < size; axis++) {
85
+ const width = maximum[axis] - minimum[axis];
86
+ if (
87
+ !Number.isFinite(minimum[axis]) ||
88
+ !Number.isFinite(maximum[axis]) ||
89
+ !Number.isFinite(width) ||
90
+ width < 0
91
+ ) {
92
+ throw new RangeError('Source bounds must have finite ordered coordinates and extents');
93
+ }
94
+ widths.push(width);
95
+ counts.push(width === 0 ? 1 : subdivisions + 1);
96
+ count *= counts[axis];
97
+ if (!Number.isSafeInteger(count) || count > maxSamples) {
98
+ throw new RangeError('Projected bounds exceed the sample budget');
99
+ }
100
+ }
101
+ const lower = new Array<number>(targetSize).fill(Infinity);
102
+ const upper = new Array<number>(targetSize).fill(-Infinity);
103
+ for (let index = 0; index < count; index++) {
104
+ let remaining = index;
105
+ const source: number[] = [];
106
+ for (let axis = 0; axis < size; axis++) {
107
+ const step = remaining % counts[axis];
108
+ remaining = Math.floor(remaining / counts[axis]);
109
+ source.push(
110
+ step === 0
111
+ ? minimum[axis]
112
+ : step === subdivisions
113
+ ? maximum[axis]
114
+ : minimum[axis] + widths[axis] * (step / subdivisions)
115
+ );
116
+ }
117
+ const projected = transform(source);
118
+ if (!projected || projected.length < targetSize) {
119
+ return {status: 'invalid', bounds: null, sampleCount: index + 1};
120
+ }
121
+ for (let axis = 0; axis < targetSize; axis++) {
122
+ if (!Number.isFinite(projected[axis]))
123
+ return {status: 'invalid', bounds: null, sampleCount: index + 1};
124
+ lower[axis] = Math.min(lower[axis], projected[axis]);
125
+ upper[axis] = Math.max(upper[axis], projected[axis]);
126
+ }
127
+ }
128
+ if (lipschitz) {
129
+ const radius = Math.hypot(
130
+ ...widths.map(
131
+ (width, axis) =>
132
+ width / subdivisions / 2 +
133
+ 4 * Number.EPSILON * Math.max(Math.abs(minimum[axis]), Math.abs(maximum[axis]))
134
+ )
135
+ );
136
+ for (let axis = 0; axis < targetSize; axis++) {
137
+ const displacement = lipschitz[axis] * radius;
138
+ const roundoff =
139
+ 8 *
140
+ Number.EPSILON *
141
+ Math.max(1, Math.abs(lower[axis]), Math.abs(upper[axis]), displacement);
142
+ lower[axis] -= displacement + roundoff;
143
+ upper[axis] += displacement + roundoff;
144
+ if (!Number.isFinite(lower[axis]) || !Number.isFinite(upper[axis])) {
145
+ return {status: 'invalid', bounds: null, sampleCount: count};
146
+ }
147
+ }
148
+ }
149
+ return {
150
+ status: lipschitz ? 'conservative' : 'sampled',
151
+ bounds: [lower, upper],
152
+ sampleCount: count
153
+ };
154
+ }
@@ -0,0 +1,67 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ /** Projects packed source vertices into an explicitly located image rectangle. */
6
+ export type ProjectTextureCoordinatesOptions = {
7
+ /** Prepared synchronous source-to-image transform. Receives a fresh source array.
8
+ * Null or nonfinite XY rejects the operation; exceptions propagate unchanged.
9
+ */
10
+ transform: (position: readonly number[]) => ArrayLike<number> | null;
11
+ /** Image rectangle [left, bottom, right, top], in the transform's output coordinates. */
12
+ bounds: readonly [number, number, number, number];
13
+ /** Number of packed source components per vertex. Default 3. */
14
+ size?: 2 | 3;
15
+ /** Texture origin. Default 'top-left'; bottom-left makes V increase with image Y. */
16
+ origin?: 'top-left' | 'bottom-left';
17
+ };
18
+
19
+ /** Generates detached float64 UVs without changing positions, indices or vertex order.
20
+ * Outside-image coordinates remain outside [0, 1]. This performs no subdivision,
21
+ * seam inference, domain clipping, GPU readback, or asynchronous preparation.
22
+ */
23
+ export function projectTextureCoordinates(
24
+ positions: ArrayLike<number>,
25
+ options: ProjectTextureCoordinatesOptions
26
+ ): Float64Array {
27
+ const {transform, bounds, size = 3, origin = 'top-left'} = options;
28
+ if (size !== 2 && size !== 3) throw new RangeError('Source size must be 2 or 3');
29
+ if (!Number.isSafeInteger(positions.length) || positions.length < 0 || positions.length % size) {
30
+ throw new RangeError('Positions must contain complete packed vertices');
31
+ }
32
+ if (origin !== 'top-left' && origin !== 'bottom-left') {
33
+ throw new RangeError('Invalid texture origin');
34
+ }
35
+ if (bounds.length !== 4 || !bounds.every(Number.isFinite)) {
36
+ throw new RangeError('Image bounds must contain four finite values');
37
+ }
38
+ const [left, bottom, right, top] = bounds;
39
+ const width = right - left;
40
+ const height = top - bottom;
41
+ if (!(width > 0) || !(height > 0) || !Number.isFinite(width) || !Number.isFinite(height)) {
42
+ throw new RangeError('Image bounds must have finite positive extents');
43
+ }
44
+ const count = positions.length / size;
45
+ const result = new Float64Array(count * 2);
46
+ for (let index = 0; index < count; index++) {
47
+ const source = Array.from({length: size}, (_, axis) => positions[index * size + axis]);
48
+ if (!source.every(Number.isFinite)) throw new RangeError(`Invalid source vertex ${index}`);
49
+ const projected = transform(source);
50
+ if (
51
+ !projected ||
52
+ projected.length < 2 ||
53
+ !Number.isFinite(projected[0]) ||
54
+ !Number.isFinite(projected[1])
55
+ ) {
56
+ throw new RangeError(`Invalid projected vertex ${index}`);
57
+ }
58
+ const u = (projected[0] - left) / width;
59
+ const v =
60
+ origin === 'top-left' ? (top - projected[1]) / height : (projected[1] - bottom) / height;
61
+ if (!Number.isFinite(u) || !Number.isFinite(v))
62
+ throw new RangeError(`Invalid UV at vertex ${index}`);
63
+ result[index * 2] = u;
64
+ result[index * 2 + 1] = v;
65
+ }
66
+ return result;
67
+ }