@math.gl/geometry 5.0.0-beta.3 → 5.0.0-beta.5

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 (96) hide show
  1. package/README.md +58 -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 +1225 -699
  60. package/dist/index.cjs.map +3 -3
  61. package/dist/index.d.ts +6 -1
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.js +3 -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/package.json +15 -3
  80. package/src/color/color-lut-types.ts +19 -0
  81. package/src/color/index.ts +6 -0
  82. package/src/color/sample-lut.ts +175 -0
  83. package/src/culling/bounds.ts +152 -0
  84. package/src/culling/frustum-planes.ts +41 -0
  85. package/src/culling/geometric-queries.ts +299 -0
  86. package/src/culling/index.ts +37 -1
  87. package/src/culling/lib/bounding-volumes/axis-aligned-bounding-box.ts +26 -8
  88. package/src/culling/lib/culling-volume.ts +9 -1
  89. package/src/culling/lib/ray.ts +21 -0
  90. package/src/curves/adaptive-sampling.ts +85 -0
  91. package/src/curves/index.ts +4 -0
  92. package/src/curves/parallel-transport.ts +104 -0
  93. package/src/index.ts +35 -0
  94. package/src/lighting/index.ts +10 -0
  95. package/src/lighting/lighting-types.ts +20 -0
  96. package/src/lighting/photometry.ts +264 -0
@@ -0,0 +1,175 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import type {ColorLUT} from './color-lut-types';
5
+
6
+ /** Reusable RGB sampler; inputs use the authored domain and outputs retain signed/HDR values. */
7
+ export type ColorLUTSampler = (
8
+ red: number,
9
+ green: number,
10
+ blue: number
11
+ ) => [number, number, number];
12
+
13
+ /** Options for interleaved floating-point RGB or RGBA buffers. */
14
+ export type ApplyColorLUTOptions = {
15
+ /** Number of interleaved components; default 3. Alpha is copied at float32 precision. */
16
+ components?: 3 | 4;
17
+ };
18
+
19
+ /** Creates a snapshot sampler with per-channel 1D linear or red-fastest 3D trilinear interpolation. */
20
+ export function createColorLUTSampler(lut: ColorLUT): ColorLUTSampler {
21
+ const writeSample = createColorLUTWriter(lut);
22
+ return (red, green, blue) => {
23
+ const result: [number, number, number] = [0, 0, 0];
24
+ writeSample(red, green, blue, result, 0);
25
+ return result;
26
+ };
27
+ }
28
+
29
+ /** Creates a validated snapshot writer with reusable per-sampler scratch storage. */
30
+ function createColorLUTWriter(lut: ColorLUT) {
31
+ const {dimension, size} = lut;
32
+ if (
33
+ ![1, 3].includes(dimension) ||
34
+ !Number.isSafeInteger(size) ||
35
+ size < 2 ||
36
+ !Number.isSafeInteger(size ** dimension * 3) ||
37
+ lut.data.length !== size ** dimension * 3 ||
38
+ lut.domainMinimum.length !== 3 ||
39
+ lut.domainMaximum.length !== 3
40
+ ) {
41
+ throw new Error('LUT: invalid calculation table');
42
+ }
43
+ const minimum = Array.from(lut.domainMinimum);
44
+ const maximum = Array.from(lut.domainMaximum);
45
+ for (let channel = 0; channel < 3; channel++) {
46
+ if (
47
+ !Number.isFinite(minimum[channel]) ||
48
+ !Number.isFinite(maximum[channel]) ||
49
+ !Number.isFinite(maximum[channel] - minimum[channel]) ||
50
+ maximum[channel] <= minimum[channel]
51
+ )
52
+ throw new Error('LUT: invalid calculation domain');
53
+ }
54
+ if (!lut.data.every(Number.isFinite)) throw new Error('LUT: invalid calculation samples');
55
+ const data = lut.data.slice();
56
+ const grid = lut.inputGrid?.slice();
57
+ if (
58
+ grid &&
59
+ (grid.length !== size ||
60
+ grid[0] !== 0 ||
61
+ grid[size - 1] !== 1 ||
62
+ grid.some(
63
+ (value, index) => !Number.isFinite(value) || (index > 0 && value <= grid[index - 1])
64
+ ))
65
+ ) {
66
+ throw new Error('LUT: invalid nonuniform input grid');
67
+ }
68
+ const coordinates = [0, 0, 0];
69
+ const indices = [0, 0, 0];
70
+ const weights = [0, 0, 0];
71
+ const accumulated = [0, 0, 0];
72
+ return (
73
+ red: number,
74
+ green: number,
75
+ blue: number,
76
+ result: [number, number, number] | Float32Array,
77
+ resultOffset: number
78
+ ): void => {
79
+ coordinates[0] = red;
80
+ coordinates[1] = green;
81
+ coordinates[2] = blue;
82
+ for (let channel = 0; channel < 3; channel++) {
83
+ const value = coordinates[channel];
84
+ if (!Number.isFinite(value)) throw new Error('LUT: input colors must be finite');
85
+ const normalized =
86
+ value <= minimum[channel]
87
+ ? 0
88
+ : value >= maximum[channel]
89
+ ? 1
90
+ : (value - minimum[channel]) / (maximum[channel] - minimum[channel]);
91
+ writeLUTInterval(normalized, size, grid, indices, weights, channel);
92
+ }
93
+ accumulated[0] = 0;
94
+ accumulated[1] = 0;
95
+ accumulated[2] = 0;
96
+ if (dimension === 1) {
97
+ for (let channel = 0; channel < 3; channel++) {
98
+ const offset = indices[channel] * 3 + channel;
99
+ accumulated[channel] =
100
+ data[offset] * (1 - weights[channel]) + data[offset + 3] * weights[channel];
101
+ }
102
+ } else {
103
+ for (let blueCorner = 0; blueCorner < 2; blueCorner++) {
104
+ for (let greenCorner = 0; greenCorner < 2; greenCorner++) {
105
+ for (let redCorner = 0; redCorner < 2; redCorner++) {
106
+ const weight =
107
+ (redCorner ? weights[0] : 1 - weights[0]) *
108
+ (greenCorner ? weights[1] : 1 - weights[1]) *
109
+ (blueCorner ? weights[2] : 1 - weights[2]);
110
+ const offset =
111
+ (((indices[2] + blueCorner) * size + indices[1] + greenCorner) * size +
112
+ indices[0] +
113
+ redCorner) *
114
+ 3;
115
+ for (let channel = 0; channel < 3; channel++)
116
+ accumulated[channel] += data[offset + channel] * weight;
117
+ }
118
+ }
119
+ }
120
+ }
121
+ for (let channel = 0; channel < 3; channel++)
122
+ result[resultOffset + channel] = accumulated[channel];
123
+ };
124
+ }
125
+
126
+ /** Applies a LUT to floating-point pixels without changing the source or applying transfer functions. */
127
+ export function applyColorLUT(
128
+ lut: ColorLUT,
129
+ colors: Float32Array | Float64Array,
130
+ options: ApplyColorLUTOptions = {}
131
+ ): Float32Array {
132
+ const {components = 3} = options;
133
+ if (![3, 4].includes(components) || colors.length % components !== 0)
134
+ throw new Error('LUT: invalid pixel component count');
135
+ const writeSample = createColorLUTWriter(lut);
136
+ const result = new Float32Array(colors.length);
137
+ for (let offset = 0; offset < colors.length; offset += components) {
138
+ writeSample(colors[offset], colors[offset + 1], colors[offset + 2], result, offset);
139
+ if (components === 4) {
140
+ const alpha = colors[offset + 3];
141
+ result[offset + 3] = alpha;
142
+ if (!Number.isFinite(alpha) || !Number.isFinite(result[offset + 3]))
143
+ throw new Error('LUT: alpha cannot be represented as float32');
144
+ }
145
+ }
146
+ return result;
147
+ }
148
+
149
+ /** Finds normalized uniform/nonuniform knots, retaining the final endpoint in the last interval. */
150
+ function writeLUTInterval(
151
+ value: number,
152
+ size: number,
153
+ grid: Float64Array | undefined,
154
+ indices: number[],
155
+ weights: number[],
156
+ channel: number
157
+ ): void {
158
+ if (!grid) {
159
+ const coordinate = value * (size - 1);
160
+ const lower = Math.min(Math.floor(coordinate), size - 2);
161
+ indices[channel] = lower;
162
+ weights[channel] = coordinate - lower;
163
+ return;
164
+ }
165
+ let lower = 0;
166
+ let upper = size - 1;
167
+ while (upper - lower > 1) {
168
+ const midpoint = Math.floor((lower + upper) / 2);
169
+ if (value < grid[midpoint]) upper = midpoint;
170
+ else lower = midpoint;
171
+ }
172
+ lower = Math.min(lower, size - 2);
173
+ indices[channel] = lower;
174
+ weights[channel] = (value - grid[lower]) / (grid[lower + 1] - grid[lower]);
175
+ }
@@ -0,0 +1,152 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import type {Bounds, Bounds2D, Bounds3D, NumericArray} from '@math.gl/core';
5
+
6
+ type ReadonlyBounds = readonly [ArrayLike<number>, ArrayLike<number>];
7
+ function dimension(bounds: ReadonlyBounds): number {
8
+ const n = bounds[0].length;
9
+ if (
10
+ (n !== 2 && n !== 3) ||
11
+ bounds[1].length !== n ||
12
+ [...Array.from(bounds[0]), ...Array.from(bounds[1])].some(Number.isNaN)
13
+ ) {
14
+ throw new RangeError('Expected 2D or 3D bounds without NaN');
15
+ }
16
+ const empty = Array.from({length: n}, (_, i) => bounds[0][i] > bounds[1][i]).some(Boolean);
17
+ if (
18
+ !empty &&
19
+ [...Array.from(bounds[0]), ...Array.from(bounds[1])].some(x => !Number.isFinite(x))
20
+ ) {
21
+ throw new RangeError('Nonempty bounds must be finite');
22
+ }
23
+ return n;
24
+ }
25
+ function pair(a: ReadonlyBounds, b: ReadonlyBounds): number {
26
+ const n = dimension(a);
27
+ if (dimension(b) !== n) throw new RangeError('Bounds dimensions must match');
28
+ return n;
29
+ }
30
+ function point(p: ArrayLike<number>, n: number): void {
31
+ if (p.length !== n || Array.from(p).some(x => !Number.isFinite(x)))
32
+ throw new RangeError('Expected a finite point of matching dimension');
33
+ }
34
+ export function createEmptyBounds(dimension: 2): Bounds2D;
35
+ export function createEmptyBounds(dimension: 3): Bounds3D;
36
+ export function createEmptyBounds(dimension: 2 | 3): Bounds;
37
+ export function createEmptyBounds(dimension: 2 | 3): Bounds {
38
+ if (dimension !== 2 && dimension !== 3) throw new RangeError('Expected dimension 2 or 3');
39
+ return [new Array(dimension).fill(Infinity), new Array(dimension).fill(-Infinity)] as Bounds;
40
+ }
41
+ /** Any inverted axis denotes empty bounds. Equal endpoints describe a nonempty point. */
42
+ export function isEmptyBounds(bounds: ReadonlyBounds): boolean {
43
+ return Array.from({length: dimension(bounds)}, (_, i) => bounds[0][i] > bounds[1][i]).some(
44
+ Boolean
45
+ );
46
+ }
47
+ export function boundsContainsPoint(bounds: ReadonlyBounds, p: ArrayLike<number>): boolean {
48
+ point(p, dimension(bounds));
49
+ return (
50
+ !isEmptyBounds(bounds) && Array.from(p).every((x, i) => x >= bounds[0][i] && x <= bounds[1][i])
51
+ );
52
+ }
53
+ export function boundsContainsBounds(a: ReadonlyBounds, b: ReadonlyBounds): boolean {
54
+ const n = pair(a, b);
55
+ return (
56
+ isEmptyBounds(b) ||
57
+ (!isEmptyBounds(a) &&
58
+ Array.from({length: n}, (_, i) => a[0][i] <= b[0][i] && a[1][i] >= b[1][i]).every(Boolean))
59
+ );
60
+ }
61
+ export function boundsIntersect(a: ReadonlyBounds, b: ReadonlyBounds): boolean {
62
+ const n = pair(a, b);
63
+ return (
64
+ !isEmptyBounds(a) &&
65
+ !isEmptyBounds(b) &&
66
+ Array.from({length: n}, (_, i) => a[0][i] <= b[1][i] && b[0][i] <= a[1][i]).every(Boolean)
67
+ );
68
+ }
69
+ function store(values: Bounds, out: Bounds = createEmptyBounds(values[0].length as 2 | 3)): Bounds {
70
+ if (out[0].length !== values[0].length || out[1].length !== values[0].length) {
71
+ throw new RangeError('Output bounds dimensions must match');
72
+ }
73
+ for (let j = 0; j < 2; j++) for (let i = 0; i < values[j].length; i++) out[j][i] = values[j][i];
74
+ return out;
75
+ }
76
+ export function unionBounds(a: ReadonlyBounds, b: ReadonlyBounds, out?: Bounds): Bounds {
77
+ const n = pair(a, b);
78
+ const values = createEmptyBounds(n as 2 | 3);
79
+ const ea = isEmptyBounds(a),
80
+ eb = isEmptyBounds(b);
81
+ for (let i = 0; i < n; i++) {
82
+ values[0][i] = Math.min(ea ? Infinity : a[0][i], eb ? Infinity : b[0][i]);
83
+ values[1][i] = Math.max(ea ? -Infinity : a[1][i], eb ? -Infinity : b[1][i]);
84
+ }
85
+ return store(values, out);
86
+ }
87
+ export function intersectBounds(a: ReadonlyBounds, b: ReadonlyBounds, out?: Bounds): Bounds {
88
+ const n = pair(a, b),
89
+ values = createEmptyBounds(n as 2 | 3);
90
+ if (boundsIntersect(a, b))
91
+ for (let i = 0; i < n; i++) {
92
+ values[0][i] = Math.max(a[0][i], b[0][i]);
93
+ values[1][i] = Math.min(a[1][i], b[1][i]);
94
+ }
95
+ return store(values, out);
96
+ }
97
+ export function expandBoundsByPoint(
98
+ bounds: ReadonlyBounds,
99
+ p: ArrayLike<number>,
100
+ out?: Bounds
101
+ ): Bounds {
102
+ point(p, dimension(bounds));
103
+ return unionBounds(bounds, [p, p], out);
104
+ }
105
+ /** Negative padding shrinks bounds; an inverted result becomes canonical empty bounds. */
106
+ export function expandBounds(bounds: ReadonlyBounds, padding: number, out?: Bounds): Bounds {
107
+ if (!Number.isFinite(padding)) throw new RangeError('Padding must be finite');
108
+ const n = dimension(bounds),
109
+ values = createEmptyBounds(n as 2 | 3);
110
+ if (!isEmptyBounds(bounds))
111
+ for (let i = 0; i < n; i++) {
112
+ values[0][i] = bounds[0][i] - padding;
113
+ values[1][i] = bounds[1][i] + padding;
114
+ }
115
+ return store(isEmptyBounds(values) ? createEmptyBounds(n as 2 | 3) : values, out);
116
+ }
117
+ export function clampPointToBounds(
118
+ bounds: ReadonlyBounds,
119
+ p: ArrayLike<number>,
120
+ out: NumericArray = new Array(p.length)
121
+ ): NumericArray | null {
122
+ point(p, dimension(bounds));
123
+ if (out.length < p.length) throw new RangeError('Result buffer is too short');
124
+ if (isEmptyBounds(bounds)) return null;
125
+ const result = Array.from(p, (x, i) => Math.max(bounds[0][i], Math.min(bounds[1][i], x)));
126
+ for (let i = 0; i < result.length; i++) out[i] = result[i];
127
+ return out;
128
+ }
129
+ function radius(r: number): void {
130
+ if (!Number.isFinite(r) || r < 0) throw new RangeError('Radius must be finite and nonnegative');
131
+ }
132
+ export function spheresIntersect(
133
+ a: ArrayLike<number>,
134
+ ar: number,
135
+ b: ArrayLike<number>,
136
+ br: number
137
+ ): boolean {
138
+ point(a, 3);
139
+ point(b, 3);
140
+ radius(ar);
141
+ radius(br);
142
+ return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]) <= ar + br;
143
+ }
144
+ export function boundsIntersectSphere(
145
+ bounds: ReadonlyBounds,
146
+ center: ArrayLike<number>,
147
+ r: number
148
+ ): boolean {
149
+ radius(r);
150
+ const closest = clampPointToBounds(bounds, center);
151
+ return closest !== null && Math.hypot(...Array.from(center, (x, i) => x - closest[i])) <= r;
152
+ }
@@ -0,0 +1,41 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import {getProjectionDepthRange, type ProjectionDepthOptions} from '@math.gl/core';
5
+ import {Plane} from './lib/plane';
6
+
7
+ /** Inward planes: left, right, bottom, top, near, far. An infinite far plane is omitted. */
8
+ export function extractFrustumPlanes(
9
+ matrix: ArrayLike<number>,
10
+ options: ProjectionDepthOptions = {}
11
+ ): Plane[] {
12
+ if (matrix.length !== 16 || Array.from(matrix).some(x => !Number.isFinite(x)))
13
+ throw new RangeError('Expected a finite view-projection matrix');
14
+ const [near, far] = getProjectionDepthRange(options);
15
+ const low = Math.min(near, far),
16
+ high = Math.max(near, far);
17
+ const row = (i: number) => [matrix[i], matrix[i + 4], matrix[i + 8], matrix[i + 12]];
18
+ const x = row(0),
19
+ y = row(1),
20
+ z = row(2),
21
+ w = row(3);
22
+ const combine = (a: number[], b: number[], factor: number) => a.map((v, i) => v + factor * b[i]);
23
+ const lo = combine(z, w, -low),
24
+ hi = w.map((v, i) => high * v - z[i]);
25
+ const coefficients = [
26
+ combine(w, x, 1),
27
+ combine(w, x, -1),
28
+ combine(w, y, 1),
29
+ combine(w, y, -1),
30
+ ...(options.reversedDepth ? [hi, lo] : [lo, hi])
31
+ ];
32
+ const planes: Plane[] = [];
33
+ for (const [a, b, c, d] of coefficients) {
34
+ const length = Math.hypot(a, b, c);
35
+ if (length === 0) {
36
+ if (d < 0) throw new RangeError('Empty clipping volume');
37
+ } else planes.push(new Plane([a / length, b / length, c / length], d / length));
38
+ }
39
+ if (planes.length < 4) throw new RangeError('Degenerate clipping volume');
40
+ return planes;
41
+ }
@@ -0,0 +1,299 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import type {NumericArray} from '@math.gl/core';
5
+ import {validateQueryPoint, normalizeQueryDirection, type QueryPoint} from './queries';
6
+
7
+ type V = [number, number, number];
8
+ const sub = (a: QueryPoint, b: QueryPoint): V => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
9
+ const dot = (a: QueryPoint, b: QueryPoint) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
10
+ const cross = (a: QueryPoint, b: QueryPoint): V => [
11
+ a[1] * b[2] - a[2] * b[1],
12
+ a[2] * b[0] - a[0] * b[2],
13
+ a[0] * b[1] - a[1] * b[0]
14
+ ];
15
+ const check = (...points: QueryPoint[]) => {
16
+ for (const p of points) validateQueryPoint(p, 3);
17
+ };
18
+ function output<T extends NumericArray>(out: T, values: QueryPoint): T {
19
+ if (out.length < values.length) throw new RangeError('Result buffer is too short');
20
+ const copy = Array.from(values);
21
+ for (let i = 0; i < copy.length; i++) out[i] = copy[i];
22
+ return out;
23
+ }
24
+ function direction(d: QueryPoint): void {
25
+ check(d);
26
+ if (Math.hypot(d[0], d[1], d[2]) === 0) throw new RangeError('Ray direction must be nonzero');
27
+ }
28
+ export function getRayPoint(
29
+ origin: QueryPoint,
30
+ dir: QueryPoint,
31
+ t: number,
32
+ out: NumericArray = [0, 0, 0]
33
+ ): NumericArray {
34
+ check(origin);
35
+ direction(dir);
36
+ if (!Number.isFinite(t) || t < 0)
37
+ throw new RangeError('Ray parameter must be finite and nonnegative');
38
+ return output(out, [origin[0] + t * dir[0], origin[1] + t * dir[1], origin[2] + t * dir[2]]);
39
+ }
40
+ export function getClosestPointOnRay(
41
+ point: QueryPoint,
42
+ origin: QueryPoint,
43
+ dir: QueryPoint,
44
+ out: NumericArray = [0, 0, 0]
45
+ ): NumericArray {
46
+ check(point, origin);
47
+ direction(dir);
48
+ const unit = normalizeQueryDirection(dir, 3);
49
+ const distance = Math.max(0, dot(sub(point, origin), unit));
50
+ return output(
51
+ out,
52
+ [0, 1, 2].map(i => origin[i] + distance * unit[i])
53
+ );
54
+ }
55
+ export function distanceToRay(point: QueryPoint, origin: QueryPoint, dir: QueryPoint): number {
56
+ const p = getClosestPointOnRay(point, origin, dir);
57
+ return Math.hypot(...sub(point, p));
58
+ }
59
+ export type RaySegmentClosestPoints = {
60
+ rayPoint: V;
61
+ segmentPoint: V;
62
+ rayParameter: number;
63
+ segmentFraction: number;
64
+ distance: number;
65
+ };
66
+ export function getClosestPointsRaySegment(
67
+ origin: QueryPoint,
68
+ dir: QueryPoint,
69
+ a: QueryPoint,
70
+ b: QueryPoint
71
+ ): RaySegmentClosestPoints {
72
+ check(origin, a, b);
73
+ direction(dir);
74
+ const unit = normalizeQueryDirection(dir, 3);
75
+ const directionLength = Math.hypot(dir[0], dir[1], dir[2]);
76
+ const edge = sub(b, a),
77
+ offset = sub(origin, a);
78
+ const segmentLength = Math.hypot(...edge);
79
+ const segmentUnit = edge.map(x => (segmentLength ? x / segmentLength : 0));
80
+ const bb = dot(unit, segmentUnit),
81
+ dd = dot(unit, offset),
82
+ ee = dot(segmentUnit, offset);
83
+ const candidates: [number, number][] = [
84
+ [0, Math.max(0, Math.min(segmentLength, ee))],
85
+ [Math.max(0, -dd), 0],
86
+ [Math.max(0, bb * segmentLength - dd), segmentLength]
87
+ ];
88
+ // Cross products retain the angle when nearly parallel dot products round to one.
89
+ const normal = cross(unit, segmentUnit);
90
+ const sine = Math.hypot(...normal);
91
+ if (segmentLength > 0 && sine > 0) {
92
+ const normalUnit = normal.map(value => value / sine);
93
+ const separation = sub(a, origin);
94
+ const t = dot(cross(separation, segmentUnit), normalUnit) / sine;
95
+ const u = dot(cross(separation, unit), normalUnit) / sine;
96
+ if (t >= 0 && u >= 0 && u <= segmentLength) candidates.push([t, u]);
97
+ }
98
+ let best: RaySegmentClosestPoints | undefined;
99
+ for (const [t, u] of candidates) {
100
+ const rayPoint = [
101
+ origin[0] + t * unit[0],
102
+ origin[1] + t * unit[1],
103
+ origin[2] + t * unit[2]
104
+ ] as V;
105
+ const segmentPoint = [
106
+ a[0] + u * segmentUnit[0],
107
+ a[1] + u * segmentUnit[1],
108
+ a[2] + u * segmentUnit[2]
109
+ ] as V;
110
+ const distance = Math.hypot(...sub(rayPoint, segmentPoint));
111
+ if (!best || distance < best.distance)
112
+ best = {
113
+ rayPoint,
114
+ segmentPoint,
115
+ rayParameter: t / directionLength,
116
+ segmentFraction: segmentLength ? u / segmentLength : 0,
117
+ distance
118
+ };
119
+ }
120
+ return best!;
121
+ }
122
+ /** Finite affine transforms only. The unnormalized output direction preserves the ray parameter. */
123
+ export function transformRay(
124
+ origin: QueryPoint,
125
+ dir: QueryPoint,
126
+ matrix: QueryPoint
127
+ ): {origin: V; direction: V} {
128
+ check(origin);
129
+ direction(dir);
130
+ if (
131
+ matrix.length !== 16 ||
132
+ Array.from(matrix).some(x => !Number.isFinite(x)) ||
133
+ matrix[3] !== 0 ||
134
+ matrix[7] !== 0 ||
135
+ matrix[11] !== 0 ||
136
+ matrix[15] !== 1
137
+ )
138
+ throw new RangeError('Expected a finite affine matrix');
139
+ const apply = (p: QueryPoint, w: number): V =>
140
+ [0, 1, 2].map(
141
+ i => matrix[i] * p[0] + matrix[i + 4] * p[1] + matrix[i + 8] * p[2] + w * matrix[i + 12]
142
+ ) as V;
143
+ const transformed = {origin: apply(origin, 1), direction: apply(dir, 0)};
144
+ check(transformed.origin);
145
+ direction(transformed.direction);
146
+ return transformed;
147
+ }
148
+ function triangle(a: QueryPoint, b: QueryPoint, c: QueryPoint) {
149
+ check(a, b, c);
150
+ const ab = sub(b, a),
151
+ ac = sub(c, a);
152
+ const scale = Math.max(Math.hypot(...ab), Math.hypot(...ac));
153
+ const u = ab.map(x => (scale ? x / scale : 0)) as V,
154
+ v = ac.map(x => (scale ? x / scale : 0)) as V;
155
+ return {u, v, scale, normal: cross(u, v)};
156
+ }
157
+ /** Barycentrics of the point's orthogonal projection; null for a degenerate triangle. */
158
+ export function getTriangleBarycentric(
159
+ point: QueryPoint,
160
+ a: QueryPoint,
161
+ b: QueryPoint,
162
+ c: QueryPoint,
163
+ out: NumericArray = [0, 0, 0]
164
+ ): NumericArray | null {
165
+ check(point);
166
+ const {u, v, scale, normal} = triangle(a, b, c),
167
+ denominator = dot(normal, normal);
168
+ if (denominator === 0) return null;
169
+ const p = sub(point, a).map(x => x / scale);
170
+ const second = dot(cross(p, v), normal) / denominator;
171
+ const third = dot(cross(u, p), normal) / denominator;
172
+ return output(out, [1 - second - third, second, third]);
173
+ }
174
+ export function getTriangleArea(a: QueryPoint, b: QueryPoint, c: QueryPoint): number {
175
+ const {normal, scale} = triangle(a, b, c);
176
+ return (Math.hypot(...normal) * scale * scale) / 2;
177
+ }
178
+ export function getTriangleNormal(
179
+ a: QueryPoint,
180
+ b: QueryPoint,
181
+ c: QueryPoint,
182
+ out: NumericArray = [0, 0, 0]
183
+ ): NumericArray {
184
+ const {normal} = triangle(a, b, c),
185
+ length = Math.hypot(...normal);
186
+ return output(
187
+ out,
188
+ normal.map(x => (length ? x / length : 0))
189
+ );
190
+ }
191
+ /** Front-facing means the oriented normal points against the viewing/ray direction. */
192
+ export function isTriangleFrontFacing(
193
+ a: QueryPoint,
194
+ b: QueryPoint,
195
+ c: QueryPoint,
196
+ dir: QueryPoint
197
+ ): boolean {
198
+ direction(dir);
199
+ return dot(triangle(a, b, c).normal, dir) < 0;
200
+ }
201
+ /** Relative tolerance: plane distance is scaled by the longest edge from a. */
202
+ export function triangleContainsPoint(
203
+ point: QueryPoint,
204
+ a: QueryPoint,
205
+ b: QueryPoint,
206
+ c: QueryPoint,
207
+ tolerance = 1e-10
208
+ ): boolean {
209
+ if (!Number.isFinite(tolerance) || tolerance < 0) throw new RangeError('Invalid tolerance');
210
+ const weights = getTriangleBarycentric(point, a, b, c);
211
+ if (!weights) return false;
212
+ const {normal, scale} = triangle(a, b, c);
213
+ const distance =
214
+ Math.abs(
215
+ dot(
216
+ sub(point, a).map(x => x / scale),
217
+ normal
218
+ )
219
+ ) / Math.hypot(...normal);
220
+ return (
221
+ distance <= tolerance && Array.from(weights).every(x => x >= -tolerance && x <= 1 + tolerance)
222
+ );
223
+ }
224
+ export function interpolateTriangleAttribute(
225
+ weights: QueryPoint,
226
+ a: QueryPoint,
227
+ b: QueryPoint,
228
+ c: QueryPoint,
229
+ out: NumericArray = new Array(a.length)
230
+ ): NumericArray {
231
+ check(weights);
232
+ if (
233
+ !a.length ||
234
+ a.length !== b.length ||
235
+ a.length !== c.length ||
236
+ [a, b, c].some(p => Array.from(p).some(x => !Number.isFinite(x)))
237
+ )
238
+ throw new RangeError('Expected matching finite attributes');
239
+ return output(
240
+ out,
241
+ Array.from(a, (x, i) => weights[0] * x + weights[1] * b[i] + weights[2] * c[i])
242
+ );
243
+ }
244
+ /** Closed segment; a coplanar segment returns its start, a disjoint segment returns null. */
245
+ export function intersectPlaneSegment(
246
+ normal: QueryPoint,
247
+ constant: number,
248
+ start: QueryPoint,
249
+ end: QueryPoint,
250
+ out: NumericArray = [0, 0, 0]
251
+ ): NumericArray | null {
252
+ check(start, end);
253
+ direction(normal);
254
+ if (!Number.isFinite(constant)) throw new RangeError('Plane constant must be finite');
255
+ const a = dot(normal, start) + constant,
256
+ b = dot(normal, end) + constant;
257
+ if (a === 0) return output(out, start);
258
+ if (b === 0) return output(out, end);
259
+ if (a > 0 === b > 0) return null;
260
+ const t = a / (a - b);
261
+ return output(
262
+ out,
263
+ [0, 1, 2].map(i => start[i] + t * (end[i] - start[i]))
264
+ );
265
+ }
266
+ /** Separating-axis test for a closed AABB. Degenerate triangles reduce to segments/points. */
267
+ export function triangleIntersectsBounds(
268
+ a: QueryPoint,
269
+ b: QueryPoint,
270
+ c: QueryPoint,
271
+ minimum: QueryPoint,
272
+ maximum: QueryPoint
273
+ ): boolean {
274
+ check(a, b, c, minimum, maximum);
275
+ if ([0, 1, 2].some(i => minimum[i] > maximum[i])) return false;
276
+ const center = [0, 1, 2].map(i => minimum[i] / 2 + maximum[i] / 2);
277
+ const extent = [0, 1, 2].map(i => maximum[i] / 2 - minimum[i] / 2);
278
+ const vertices = [a, b, c].map(p => sub(p, center));
279
+ const edges = [sub(b, a), sub(c, b), sub(a, c)];
280
+ const basis: V[] = [
281
+ [1, 0, 0],
282
+ [0, 1, 0],
283
+ [0, 0, 1]
284
+ ];
285
+ const axes = [
286
+ ...basis,
287
+ cross(edges[0], edges[1]),
288
+ ...edges.flatMap(e => basis.map(axis => cross(e, axis)))
289
+ ];
290
+ for (const axis of axes) {
291
+ const length = Math.hypot(...axis);
292
+ if (!length) continue;
293
+ const unit = axis.map(x => x / length);
294
+ const projections = vertices.map(v => dot(v, unit));
295
+ const radius = extent.reduce((sum, x, i) => sum + x * Math.abs(unit[i]), 0);
296
+ if (Math.min(...projections) > radius || Math.max(...projections) < -radius) return false;
297
+ }
298
+ return true;
299
+ }