@threenative/core 0.3.4 → 0.3.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 (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Bj8G1wmD.d.ts} +102 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12423 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +47 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2390 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +564 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +839 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { createHash } from "node:crypto";
2
3
  import { existsSync } from "node:fs";
3
4
  import { readFile, writeFile } from "node:fs/promises";
4
5
  import { createRequire } from "node:module";
@@ -7,6 +8,7 @@ import { fileURLToPath } from "node:url";
7
8
 
8
9
  const THREE_VERSION = "0.185.1";
9
10
  const PATCH_NAME = `three@${THREE_VERSION}.patch`;
11
+ const UPGRADE_PATCH_NAME = `three@${THREE_VERSION}-prd269-upgrade.patch`;
10
12
 
11
13
  /** Apply the package-owned Three.js patch to the dependency resolved for the consumer. */
12
14
  export async function applyThreePatch(options = {}) {
@@ -29,7 +31,11 @@ export async function applyThreePatch(options = {}) {
29
31
 
30
32
  const patchPath = path.join(packageRoot, "patches", PATCH_NAME);
31
33
  const patch = parsePatch(await readFile(patchPath, "utf8"), patchPath);
32
- const plans = await planPatch(threeRoot, patch);
34
+ const upgradePath = path.join(packageRoot, "patches", UPGRADE_PATCH_NAME);
35
+ const upgrades = existsSync(upgradePath)
36
+ ? parsePatch(await readFile(upgradePath, "utf8"), upgradePath)
37
+ : [];
38
+ const plans = await planPatch(threeRoot, patch, upgrades);
33
39
  // `planPatch` refuses any file it does not fully recognise, so every plan that is not already
34
40
  // `patched` is safe to write — including the files an older release of this patch already
35
41
  // touched, which is the state a project upgrading from the previous `latest` is in.
@@ -139,6 +145,12 @@ function parsePatchFiles(text, patchPath) {
139
145
  }
140
146
 
141
147
  function parsePatchLine(line, current, hunk, patchPath) {
148
+ const blobs = /^index ([a-f0-9]{40})\.\.([a-f0-9]{40}) /u.exec(line);
149
+ if (blobs !== null) {
150
+ current.oldBlob = blobs[1];
151
+ current.newBlob = blobs[2];
152
+ return hunk;
153
+ }
142
154
  if (line.startsWith("--- ")) {
143
155
  current.oldPath = patchPathFromHeader(line.slice(4), patchPath);
144
156
  return hunk;
@@ -205,7 +217,7 @@ function patchPathFromHeader(header, patchPath) {
205
217
  return relative;
206
218
  }
207
219
 
208
- async function planPatch(threeRoot, files) {
220
+ async function planPatch(threeRoot, files, upgrades) {
209
221
  const plans = [];
210
222
  for (const file of files) {
211
223
  const target = path.resolve(threeRoot, file.oldPath);
@@ -215,7 +227,8 @@ async function planPatch(threeRoot, files) {
215
227
  );
216
228
  }
217
229
  const original = await readFile(target, "utf8");
218
- const lines = original.replaceAll("\r\n", "\n").split("\n");
230
+ const recognised = upgradeKnownFile(original, file.oldPath, upgrades);
231
+ const lines = recognised.replaceAll("\r\n", "\n").split("\n");
219
232
  const states = classifyFile(lines, file.hunks);
220
233
  const unknown = states.findIndex((state) => state === "unknown");
221
234
  if (unknown !== -1) {
@@ -228,8 +241,13 @@ async function planPatch(threeRoot, files) {
228
241
  : states.some((state) => state === "patched")
229
242
  ? "extended"
230
243
  : "stock";
244
+ assertKnownExtension(status, recognised === original, file.oldPath, upgrades);
231
245
  if (status === "patched") {
232
- plans.push({ contents: original, file: target, status });
246
+ plans.push({
247
+ contents: recognised,
248
+ file: target,
249
+ status: recognised === original ? status : "extended",
250
+ });
233
251
  continue;
234
252
  }
235
253
  plans.push({
@@ -241,6 +259,46 @@ async function planPatch(threeRoot, files) {
241
259
  return plans;
242
260
  }
243
261
 
262
+ /** Registered migration files must not fall through to permissive hunk-only upgrades. */
263
+ function assertKnownExtension(status, unchanged, file, upgrades) {
264
+ if (
265
+ status === "extended" &&
266
+ unchanged &&
267
+ upgrades.some((candidate) => candidate.oldPath === file)
268
+ ) {
269
+ throw new Error(
270
+ `TN_THREE_PATCH_PARTIAL: ${file} is partly patched but does not match an exact supported predecessor; refusing an unrecognised installation.`,
271
+ );
272
+ }
273
+ }
274
+
275
+ /** Upgrade only exact known prior blobs; a custom edit never enters this migration. */
276
+ function upgradeKnownFile(original, file, upgrades, seen = new Set()) {
277
+ const normalized = original.replaceAll("\r\n", "\n");
278
+ const upgrade = upgrades.find(
279
+ (candidate) => candidate.oldPath === file && candidate.oldBlob === blobHash(normalized),
280
+ );
281
+ if (upgrade === undefined) return original;
282
+ if (seen.has(upgrade.oldBlob))
283
+ throw new Error(`TN_THREE_PATCH_INVALID: cyclic known upgrade for ${file}.`);
284
+ seen.add(upgrade.oldBlob);
285
+ const lines = normalized.split("\n");
286
+ const states = classifyFile(lines, upgrade.hunks);
287
+ if (states.some((state) => state !== "stock"))
288
+ throw new Error(`TN_THREE_PATCH_INVALID: known upgrade hunks do not match ${file}.`);
289
+ const contents = applyFile(lines, upgrade.hunks, states, file).join("\n");
290
+ if (blobHash(contents) !== upgrade.newBlob)
291
+ throw new Error(`TN_THREE_PATCH_INVALID: known upgrade output does not match ${file}.`);
292
+ return upgradeKnownFile(contents, file, upgrades, seen);
293
+ }
294
+
295
+ function blobHash(contents) {
296
+ return createHash("sha1")
297
+ .update(`blob ${Buffer.byteLength(contents)}\0`)
298
+ .update(contents)
299
+ .digest("hex");
300
+ }
301
+
244
302
  /**
245
303
  * Every hunk's state in this file, in patch order: `"stock"`, `"patched"` or `"unknown"`.
246
304
  *
@@ -0,0 +1,264 @@
1
+ /*!
2
+ * Selectively adapted from GGEZ packages/anim-runtime/src/runtime/helpers.ts
3
+ * (findBlend1DChildren, computeTriangleBarycentricWeights, findBlend2DEdgeWeights)
4
+ * at 45ed541cb163ef98694467758f60d5533373ac60. Replaced graph children with
5
+ * validated fixed sample indices, initialization-only sorting and reusable output.
6
+ * MIT License
7
+ * Copyright (c) 2026 @alightinastorm (x.com/alightinastorm)
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ * of this software and associated documentation files (the "Software"), to deal
10
+ * in the Software without restriction, including without limitation the rights
11
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ * copies of the Software, and to permit persons to whom the Software is
13
+ * furnished to do so, subject to the following conditions:
14
+ * The above copyright notice and this permission notice shall be included in all
15
+ * copies or substantial portions of the Software.
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ interface IBlendThreshold {
26
+ readonly value: number;
27
+ readonly index: number;
28
+ }
29
+
30
+ type Point = readonly [number, number];
31
+ type Triangle = readonly [number, number, number];
32
+ const EPSILON = 1e-10;
33
+
34
+ export function animationFinite(value: number, name: string): number {
35
+ if (!Number.isFinite(value)) throw new Error(`AnimationComposer: ${name} must be finite.`);
36
+ return value;
37
+ }
38
+
39
+ export class BlendSpace1D {
40
+ readonly weights: Float64Array;
41
+ readonly #samples: readonly IBlendThreshold[];
42
+
43
+ constructor(thresholds: readonly number[]) {
44
+ if (thresholds.length === 0) throw new Error("BlendSpace1D requires samples.");
45
+ this.#samples = thresholds
46
+ .map((value, index) => ({ value: animationFinite(value, `threshold[${index}]`), index }))
47
+ .sort((a, b) => a.value - b.value);
48
+ for (let i = 1; i < this.#samples.length; i += 1) {
49
+ const distance =
50
+ (this.#samples[i] as IBlendThreshold).value -
51
+ (this.#samples[i - 1] as IBlendThreshold).value;
52
+ if (distance === 0) throw new Error("BlendSpace1D: duplicate threshold.");
53
+ animationFinite(distance, "threshold interval");
54
+ }
55
+ this.weights = new Float64Array(thresholds.length);
56
+ }
57
+
58
+ sample(value: number): Float64Array {
59
+ animationFinite(value, "1D query");
60
+ const weights = this.weights;
61
+ weights.fill(0);
62
+ const first = this.#samples[0] as IBlendThreshold;
63
+ const last = this.#samples[this.#samples.length - 1] as IBlendThreshold;
64
+ if (value <= first.value) weights[first.index] = 1;
65
+ else if (value >= last.value) weights[last.index] = 1;
66
+ else {
67
+ for (let i = 1; i < this.#samples.length; i += 1) {
68
+ const b = this.#samples[i] as IBlendThreshold;
69
+ if (value > b.value) continue;
70
+ const a = this.#samples[i - 1] as IBlendThreshold;
71
+ const t = (value - a.value) / (b.value - a.value);
72
+ weights[a.index] = 1 - t;
73
+ weights[b.index] = t;
74
+ break;
75
+ }
76
+ }
77
+ return weights;
78
+ }
79
+ }
80
+
81
+ function cross(a: Point, b: Point, c: Point): number {
82
+ return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
83
+ }
84
+
85
+ function hull(points: readonly Point[]): number[] {
86
+ const sorted = points
87
+ .map((_, i) => i)
88
+ .sort(
89
+ (a, b) =>
90
+ (points[a] as Point)[0] - (points[b] as Point)[0] ||
91
+ (points[a] as Point)[1] - (points[b] as Point)[1],
92
+ );
93
+ const half = (indices: number[]) => {
94
+ const result: number[] = [];
95
+ for (const i of indices) {
96
+ while (
97
+ result.length > 1 &&
98
+ cross(
99
+ points[result[result.length - 2] as number] as Point,
100
+ points[result[result.length - 1] as number] as Point,
101
+ points[i] as Point,
102
+ ) <= 0
103
+ )
104
+ result.pop();
105
+ result.push(i);
106
+ }
107
+ return result.slice(0, -1);
108
+ };
109
+ return [...half(sorted), ...half([...sorted].reverse())];
110
+ }
111
+
112
+ /** Fixed complete convex-hull triangulation. Collinear triangles and overlapping tiles fail at load. */
113
+ export class BlendSpace2D {
114
+ readonly weights: Float64Array;
115
+ readonly #points: readonly Point[];
116
+ readonly #triangles: readonly Triangle[];
117
+ readonly #hull: readonly number[];
118
+ readonly #boundary: readonly (readonly [number, number])[];
119
+
120
+ constructor(points: readonly Point[], triangles: readonly Triangle[]) {
121
+ if (points.length < 3 || triangles.length === 0)
122
+ throw new Error("BlendSpace2D requires a triangulation of at least three samples.");
123
+ this.#points = points.map((p, i) => {
124
+ if (p.length !== 2) throw new Error(`BlendSpace2D: sample[${i}] must have two coordinates.`);
125
+ return [animationFinite(p[0], `sample[${i}].x`), animationFinite(p[1], `sample[${i}].y`)];
126
+ });
127
+ for (let a = 0; a < points.length; a += 1)
128
+ for (let b = a + 1; b < points.length; b += 1)
129
+ if (
130
+ (points[a] as Point)[0] === (points[b] as Point)[0] &&
131
+ (points[a] as Point)[1] === (points[b] as Point)[1]
132
+ )
133
+ throw new Error("BlendSpace2D: duplicate sample.");
134
+ this.#hull = hull(this.#points);
135
+ this.weights = new Float64Array(points.length);
136
+ const used = new Set<number>();
137
+ const seen = new Set<string>();
138
+ const edges = new Map<string, { a: number; b: number; count: number }>();
139
+ let area = 0;
140
+ this.#triangles = triangles.map((triangle) => {
141
+ if (
142
+ triangle.length !== 3 ||
143
+ triangle.some((i) => !Number.isInteger(i) || i < 0 || i >= points.length)
144
+ )
145
+ throw new Error("BlendSpace2D: invalid triangle index.");
146
+ const key = [...triangle].sort((a, b) => a - b).join(",");
147
+ if (seen.has(key)) throw new Error("BlendSpace2D: duplicate triangle.");
148
+ seen.add(key);
149
+ let [a, b, c] = triangle;
150
+ const signed = animationFinite(
151
+ cross(points[a] as Point, points[b] as Point, points[c] as Point),
152
+ "triangle area",
153
+ );
154
+ if (signed === 0) throw new Error("BlendSpace2D: collinear triangle.");
155
+ if (signed < 0) [b, c] = [c, b];
156
+ area += Math.abs(signed);
157
+ for (const index of triangle) used.add(index);
158
+ for (const [u, v] of [
159
+ [a, b],
160
+ [b, c],
161
+ [c, a],
162
+ ]) {
163
+ const key = [u, v].sort((a, b) => (a as number) - (b as number)).join(",");
164
+ const edge = edges.get(key);
165
+ if (edge !== undefined) {
166
+ if (edge.count !== 1 || edge.a !== v)
167
+ throw new Error("BlendSpace2D: overlapping/nonmanifold triangulation.");
168
+ edge.count += 1;
169
+ } else edges.set(key, { a: u as number, b: v as number, count: 1 });
170
+ }
171
+ return [a, b, c];
172
+ });
173
+ if (used.size !== points.length) throw new Error("BlendSpace2D: unused sample.");
174
+ const origin = points[this.#hull[0] as number] as Point;
175
+ let hullArea = 0;
176
+ for (let i = 1; i + 1 < this.#hull.length; i += 1)
177
+ hullArea += cross(
178
+ origin,
179
+ points[this.#hull[i] as number] as Point,
180
+ points[this.#hull[i + 1] as number] as Point,
181
+ );
182
+ if (!Number.isFinite(area) || Math.abs(area - hullArea) > EPSILON * hullArea)
183
+ throw new Error("BlendSpace2D: triangulation must cover the convex hull exactly.");
184
+ for (const edge of edges.values()) {
185
+ if (edge.count !== 1) continue;
186
+ const onHull = this.#hull.some((a, i) => {
187
+ const b = this.#hull[(i + 1) % this.#hull.length] as number;
188
+ return (
189
+ cross(points[a] as Point, points[b] as Point, points[edge.a] as Point) === 0 &&
190
+ cross(points[a] as Point, points[b] as Point, points[edge.b] as Point) === 0
191
+ );
192
+ });
193
+ if (!onHull) throw new Error("BlendSpace2D: triangulation has an interior boundary.");
194
+ }
195
+ this.#boundary = [...edges.values()]
196
+ .filter((edge) => edge.count === 1)
197
+ .map((edge) => [edge.a, edge.b]);
198
+ for (let i = 0; i < this.#triangles.length; i += 1) {
199
+ const a = this.#triangles[i] as Triangle;
200
+ for (let j = i + 1; j < this.#triangles.length; j += 1) {
201
+ const b = this.#triangles[j] as Triangle;
202
+ for (let u = 0; u < 3; u += 1)
203
+ for (let v = 0; v < 3; v += 1) {
204
+ const p = points[a[u] as number] as Point;
205
+ const q = points[a[(u + 1) % 3] as number] as Point;
206
+ const r = points[b[v] as number] as Point;
207
+ const s = points[b[(v + 1) % 3] as number] as Point;
208
+ if (cross(p, q, r) * cross(p, q, s) < 0 && cross(r, s, p) * cross(r, s, q) < 0)
209
+ throw new Error("BlendSpace2D: crossing triangle edges.");
210
+ }
211
+ }
212
+ }
213
+ }
214
+
215
+ sample(x: number, y: number): Float64Array {
216
+ animationFinite(x, "2D query.x");
217
+ animationFinite(y, "2D query.y");
218
+ this.weights.fill(0);
219
+ for (const [a, b, c] of this.#triangles) {
220
+ const p = this.#points[a] as Point;
221
+ const q = this.#points[b] as Point;
222
+ const r = this.#points[c] as Point;
223
+ const denominator = cross(p, q, r);
224
+ const wa = ((q[1] - r[1]) * (x - r[0]) + (r[0] - q[0]) * (y - r[1])) / denominator;
225
+ const wb = ((r[1] - p[1]) * (x - r[0]) + (p[0] - r[0]) * (y - r[1])) / denominator;
226
+ const wc = 1 - wa - wb;
227
+ if (Math.min(wa, wb, wc) < -EPSILON) continue;
228
+ animationFinite(wa + wb + wc, "barycentric query");
229
+ this.weights[a] = Math.max(0, wa);
230
+ this.weights[b] = Math.max(0, wb);
231
+ this.weights[c] = Math.max(0, wc);
232
+ const sum =
233
+ (this.weights[a] as number) + (this.weights[b] as number) + (this.weights[c] as number);
234
+ this.weights[a] = (this.weights[a] as number) / sum;
235
+ this.weights[b] = (this.weights[b] as number) / sum;
236
+ this.weights[c] = (this.weights[c] as number) / sum;
237
+ return this.weights;
238
+ }
239
+ let best = Number.POSITIVE_INFINITY;
240
+ let bestA = 0;
241
+ let bestB = 0;
242
+ let bestT = 0;
243
+ for (const [a, b] of this.#boundary) {
244
+ const p = this.#points[a] as Point;
245
+ const q = this.#points[b] as Point;
246
+ const dx = q[0] - p[0];
247
+ const dy = q[1] - p[1];
248
+ const t = Math.max(0, Math.min(1, ((x - p[0]) * dx + (y - p[1]) * dy) / (dx * dx + dy * dy)));
249
+ const distance = animationFinite(
250
+ (x - p[0] - dx * t) ** 2 + (y - p[1] - dy * t) ** 2,
251
+ "hull projection",
252
+ );
253
+ if (distance < best) {
254
+ best = distance;
255
+ bestA = a;
256
+ bestB = b;
257
+ bestT = t;
258
+ }
259
+ }
260
+ this.weights[bestA] = 1 - bestT;
261
+ this.weights[bestB] = bestT;
262
+ return this.weights;
263
+ }
264
+ }