@needle-tools/three-mesh-effects 0.0.0-stage → 0.1.0-alpha.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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +93 -2
  3. package/build/deformation-runtime.js +2143 -0
  4. package/build/deformation-runtime.js.map +7 -0
  5. package/build/impostor-runtime-needle-engine.js +42 -0
  6. package/build/impostor-runtime-needle-engine.js.map +7 -0
  7. package/build/impostor-runtime.js +1333 -0
  8. package/build/impostor-runtime.js.map +7 -0
  9. package/build/internal/deformation/cloth-surface.js +288 -0
  10. package/build/internal/deformation/cloth-surface.js.map +7 -0
  11. package/build/internal/deformation/fur-surface.js +130 -0
  12. package/build/internal/deformation/fur-surface.js.map +7 -0
  13. package/build/internal/deformation/ik-constraints.js +44 -0
  14. package/build/internal/deformation/ik-constraints.js.map +7 -0
  15. package/build/internal/deformation/joints-json.js +197 -0
  16. package/build/internal/deformation/joints-json.js.map +7 -0
  17. package/build/internal/deformation/limits.js +16 -0
  18. package/build/internal/deformation/limits.js.map +7 -0
  19. package/build/internal/deformation/motion-settings.js +12 -0
  20. package/build/internal/deformation/motion-settings.js.map +7 -0
  21. package/build/internal/deformation/pin-cloth.js +196 -0
  22. package/build/internal/deformation/pin-cloth.js.map +7 -0
  23. package/build/internal/deformation/pin-ik.js +650 -0
  24. package/build/internal/deformation/pin-ik.js.map +7 -0
  25. package/build/internal/deformation/pin-types.js +12 -0
  26. package/build/internal/deformation/pin-types.js.map +7 -0
  27. package/build/internal/deformation/pin-wiggle.js +249 -0
  28. package/build/internal/deformation/pin-wiggle.js.map +7 -0
  29. package/build/internal/deformation/pose-slots.js +84 -0
  30. package/build/internal/deformation/pose-slots.js.map +7 -0
  31. package/build/internal/deformation/pose-timeline.js +210 -0
  32. package/build/internal/deformation/pose-timeline.js.map +7 -0
  33. package/build/internal/deformation/rig-drivers.js +48 -0
  34. package/build/internal/deformation/rig-drivers.js.map +7 -0
  35. package/build/internal/deformation/rig-extension.js +334 -0
  36. package/build/internal/deformation/rig-extension.js.map +7 -0
  37. package/build/internal/deformation/rig-runtime.js +2141 -0
  38. package/build/internal/deformation/rig-runtime.js.map +7 -0
  39. package/build/internal/deformation/wind.js +34 -0
  40. package/build/internal/deformation/wind.js.map +7 -0
  41. package/build/internal/impostor/impostor-metadata.js +77 -0
  42. package/build/internal/impostor/impostor-metadata.js.map +7 -0
  43. package/build/internal/impostor/impostor-node-material.js +1331 -0
  44. package/build/internal/impostor/impostor-node-material.js.map +7 -0
  45. package/build/internal/impostor/impostor-runtime-support.js +162 -0
  46. package/build/internal/impostor/impostor-runtime-support.js.map +7 -0
  47. package/build/internal/impostor/octahedral.js +232 -0
  48. package/build/internal/impostor/octahedral.js.map +7 -0
  49. package/build/internal/pixel-impostor/pixel-impostor-display.js +728 -0
  50. package/build/internal/pixel-impostor/pixel-impostor-display.js.map +7 -0
  51. package/build/internal/pixel-impostor/pixel-impostor-metadata.js +71 -0
  52. package/build/internal/pixel-impostor/pixel-impostor-metadata.js.map +7 -0
  53. package/build/internal/pixel-impostor/pixel-impostor-runtime.js +150 -0
  54. package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +7 -0
  55. package/build/internal/rendering/skin-projection.js +4630 -0
  56. package/build/internal/rendering/skin-projection.js.map +7 -0
  57. package/build/internal/rendering/surface-query.js +4519 -0
  58. package/build/internal/rendering/surface-query.js.map +7 -0
  59. package/build/internal/rendering/wireframe.js +112 -0
  60. package/build/internal/rendering/wireframe.js.map +7 -0
  61. package/build/internal/rendering/wrap-preview-settings.js +126 -0
  62. package/build/internal/rendering/wrap-preview-settings.js.map +7 -0
  63. package/build/internal/rendering/wrap-preview.js +5610 -0
  64. package/build/internal/rendering/wrap-preview.js.map +7 -0
  65. package/build/internal/rendering/wrap-skin.js +4746 -0
  66. package/build/internal/rendering/wrap-skin.js.map +7 -0
  67. package/build/pixel-impostor-runtime.js +876 -0
  68. package/build/pixel-impostor-runtime.js.map +7 -0
  69. package/build/types/deformation/cloth-surface.d.ts +39 -0
  70. package/build/types/deformation/cloth-surface.js +1 -0
  71. package/build/types/deformation/fur-surface.d.ts +27 -0
  72. package/build/types/deformation/fur-surface.js +1 -0
  73. package/build/types/deformation/ik-constraints.d.ts +18 -0
  74. package/build/types/deformation/ik-constraints.js +1 -0
  75. package/build/types/deformation/joints-json.d.ts +17 -0
  76. package/build/types/deformation/joints-json.js +1 -0
  77. package/build/types/deformation/limits.d.ts +23 -0
  78. package/build/types/deformation/limits.js +1 -0
  79. package/build/types/deformation/motion-settings.d.ts +9 -0
  80. package/build/types/deformation/motion-settings.js +1 -0
  81. package/build/types/deformation/pin-cloth.d.ts +28 -0
  82. package/build/types/deformation/pin-cloth.js +1 -0
  83. package/build/types/deformation/pin-ik.d.ts +37 -0
  84. package/build/types/deformation/pin-ik.js +1 -0
  85. package/build/types/deformation/pin-types.d.ts +53 -0
  86. package/build/types/deformation/pin-types.js +1 -0
  87. package/build/types/deformation/pin-wiggle.d.ts +16 -0
  88. package/build/types/deformation/pin-wiggle.js +1 -0
  89. package/build/types/deformation/pose-slots.d.ts +41 -0
  90. package/build/types/deformation/pose-slots.js +1 -0
  91. package/build/types/deformation/pose-timeline.d.ts +65 -0
  92. package/build/types/deformation/pose-timeline.js +1 -0
  93. package/build/types/deformation/rig-drivers.d.ts +19 -0
  94. package/build/types/deformation/rig-drivers.js +1 -0
  95. package/build/types/deformation/rig-extension.d.ts +33 -0
  96. package/build/types/deformation/rig-extension.js +1 -0
  97. package/build/types/deformation/rig-runtime.d.ts +95 -0
  98. package/build/types/deformation/rig-runtime.js +1 -0
  99. package/build/types/deformation/wind.d.ts +16 -0
  100. package/build/types/deformation/wind.js +1 -0
  101. package/build/types/impostor/impostor-metadata.d.ts +61 -0
  102. package/build/types/impostor/impostor-metadata.js +1 -0
  103. package/build/types/impostor/impostor-node-material.d.ts +140 -0
  104. package/build/types/impostor/impostor-node-material.js +1 -0
  105. package/build/types/impostor/impostor-runtime-support.d.ts +52 -0
  106. package/build/types/impostor/impostor-runtime-support.js +1 -0
  107. package/build/types/impostor/octahedral.d.ts +84 -0
  108. package/build/types/impostor/octahedral.js +1 -0
  109. package/build/types/pixel-impostor/pixel-impostor-display.d.ts +48 -0
  110. package/build/types/pixel-impostor/pixel-impostor-display.js +1 -0
  111. package/build/types/pixel-impostor/pixel-impostor-metadata.d.ts +34 -0
  112. package/build/types/pixel-impostor/pixel-impostor-metadata.js +1 -0
  113. package/build/types/pixel-impostor/pixel-impostor-runtime.d.ts +18 -0
  114. package/build/types/pixel-impostor/pixel-impostor-runtime.js +1 -0
  115. package/build/types/public/deformation-runtime.d.ts +3 -0
  116. package/build/types/public/deformation-runtime.js +1 -0
  117. package/build/types/public/impostor-runtime-needle-engine.d.ts +31 -0
  118. package/build/types/public/impostor-runtime-needle-engine.js +1 -0
  119. package/build/types/public/impostor-runtime.d.ts +6 -0
  120. package/build/types/public/impostor-runtime.js +1 -0
  121. package/build/types/public/pixel-impostor-runtime.d.ts +3 -0
  122. package/build/types/public/pixel-impostor-runtime.js +1 -0
  123. package/build/types/public/wrap-effects.d.ts +4 -0
  124. package/build/types/public/wrap-effects.js +1 -0
  125. package/build/types/rendering/skin-projection.d.ts +44 -0
  126. package/build/types/rendering/skin-projection.js +1 -0
  127. package/build/types/rendering/surface-query.d.ts +66 -0
  128. package/build/types/rendering/surface-query.js +1 -0
  129. package/build/types/rendering/wireframe.d.ts +25 -0
  130. package/build/types/rendering/wireframe.js +1 -0
  131. package/build/types/rendering/wrap-preview-settings.d.ts +22 -0
  132. package/build/types/rendering/wrap-preview-settings.js +1 -0
  133. package/build/types/rendering/wrap-preview.d.ts +39 -0
  134. package/build/types/rendering/wrap-preview.js +1 -0
  135. package/build/types/rendering/wrap-skin.d.ts +14 -0
  136. package/build/types/rendering/wrap-skin.js +1 -0
  137. package/build/wrap-effects.js +5640 -0
  138. package/build/wrap-effects.js.map +7 -0
  139. package/package.json +105 -4
  140. package/src/deformation/cloth-surface.ts +223 -0
  141. package/src/deformation/fur-surface.ts +129 -0
  142. package/src/deformation/ik-constraints.ts +37 -0
  143. package/src/deformation/joints-json.ts +94 -0
  144. package/src/deformation/limits.ts +25 -0
  145. package/src/deformation/motion-settings.ts +9 -0
  146. package/src/deformation/pin-cloth.ts +149 -0
  147. package/src/deformation/pin-ik.ts +582 -0
  148. package/src/deformation/pin-types.ts +22 -0
  149. package/src/deformation/pin-wiggle.ts +119 -0
  150. package/src/deformation/pose-slots.ts +106 -0
  151. package/src/deformation/pose-timeline.ts +242 -0
  152. package/src/deformation/rig-drivers.ts +32 -0
  153. package/src/deformation/rig-extension.ts +87 -0
  154. package/src/deformation/rig-runtime.ts +416 -0
  155. package/src/deformation/wind.ts +36 -0
  156. package/src/impostor/impostor-metadata.js +137 -0
  157. package/src/impostor/impostor-node-material.js +1581 -0
  158. package/src/impostor/impostor-runtime-support.js +139 -0
  159. package/src/impostor/octahedral.js +280 -0
  160. package/src/pixel-impostor/pixel-impostor-display.js +794 -0
  161. package/src/pixel-impostor/pixel-impostor-metadata.js +74 -0
  162. package/src/pixel-impostor/pixel-impostor-runtime.js +78 -0
  163. package/src/public/deformation-runtime.ts +3 -0
  164. package/src/public/impostor-runtime-needle-engine.js +56 -0
  165. package/src/public/impostor-runtime.js +21 -0
  166. package/src/public/pixel-impostor-runtime.js +5 -0
  167. package/src/public/wrap-effects.js +21 -0
  168. package/src/rendering/skin-projection.js +113 -0
  169. package/src/rendering/surface-query.js +88 -0
  170. package/src/rendering/wireframe.js +115 -0
  171. package/src/rendering/wrap-preview-settings.js +123 -0
  172. package/src/rendering/wrap-preview.js +645 -0
  173. package/src/rendering/wrap-skin.js +109 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/deformation/cloth-surface.ts", "../../../src/deformation/motion-settings.ts", "../../../src/deformation/wind.ts"],
4
+ "sourcesContent": ["import { Vector3 } from 'three';\nimport type { PinRecord, Point } from './pin-types.js';\nimport type { ClothCollider } from './pin-cloth.js';\nimport { DEFAULT_MOTION, type MotionSettings } from './motion-settings.js';\nimport { windAcceleration, windProfile } from './wind.js';\n\ntype Edge = { a: number; b: number; length: number; bend: boolean };\ntype Triangle = { a: number; b: number; c: number };\ntype Particle = { position: Vector3; previous: Vector3; base: Vector3; share: number; anchor: number };\n\nexport function clothSurfaceMotion(pins: readonly PinRecord[]): MotionSettings {\n if (!pins.length) return { ...DEFAULT_MOTION };\n const values = pins.map(pin => pin.motion ?? DEFAULT_MOTION);\n return { ...DEFAULT_MOTION,\n damping: values.reduce((sum, motion) => sum + motion.damping, 0) / values.length,\n strength: values.reduce((sum, motion) => sum + motion.strength, 0) / values.length };\n}\n\nfunction distances(graph: readonly { to: number; length: number }[][], seeds: readonly number[]) {\n const distance = new Float64Array(graph.length).fill(Infinity);\n const heap: { node: number; distance: number }[] = [];\n const push = (node: number, value: number) => {\n let i = heap.length; heap.push({ node, distance: value });\n while (i) { const parent = (i - 1) >> 1; if (heap[parent].distance <= value) break; heap[i] = heap[parent]; i = parent; }\n heap[i] = { node, distance: value };\n };\n const pop = () => {\n const top = heap[0], last = heap.pop()!;\n if (heap.length) {\n let i = 0;\n for (;;) {\n let child = i * 2 + 1; if (child >= heap.length) break;\n if (child + 1 < heap.length && heap[child + 1].distance < heap[child].distance) child++;\n if (last.distance <= heap[child].distance) break;\n heap[i] = heap[child]; i = child;\n }\n heap[i] = last;\n }\n return top;\n };\n for (const seed of seeds) if (distance[seed] > 0) { distance[seed] = 0; push(seed, 0); }\n while (heap.length) {\n const next = pop(); if (next.distance !== distance[next.node]) continue;\n for (const edge of graph[next.node]) {\n const value = next.distance + edge.length;\n if (value < distance[edge.to]) { distance[edge.to] = value; push(edge.to, value); }\n }\n }\n return distance;\n}\n\n/** A topology-connected fabric layer over the portable skinned/voxel result.\n * Vertices at UV seams share one particle; all other vertices keep the source\n * triangle topology. Body controls attach the sheet, cloth controls release it. */\nexport class ClothSurface {\n readonly particles: Particle[];\n readonly vertexParticle: Uint32Array;\n readonly triangles: Triangle[];\n readonly edges: Edge[];\n readonly scale: number;\n private time = 0;\n\n constructor(restVertices: Float32Array, indices: ArrayLike<number>, pins: readonly PinRecord[]) {\n const vertexCount = restVertices.length / 3;\n const min = new Vector3(Infinity, Infinity, Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity);\n for (let i = 0; i < vertexCount; i++) {\n const p = new Vector3().fromArray(restVertices, i * 3); min.min(p); max.max(p);\n }\n this.scale = Math.max(1e-4, max.clone().sub(min).length());\n const tolerance = this.scale * 1e-6;\n const welded = new Map<string, number>(), particles: Particle[] = [];\n this.vertexParticle = new Uint32Array(vertexCount);\n for (let i = 0; i < vertexCount; i++) {\n const p = new Vector3().fromArray(restVertices, i * 3);\n const key = p.toArray().map(value => Math.round(value / tolerance)).join(',');\n let node = welded.get(key);\n if (node === undefined) {\n node = particles.length; welded.set(key, node);\n particles.push({ position: p.clone(), previous: p.clone(), base: p, share: 0, anchor: 0 });\n }\n this.vertexParticle[i] = node;\n }\n const edgeMap = new Map<string, { a: number; b: number; opposites: number[] }>();\n const graph: { to: number; length: number }[][] = particles.map(() => []);\n const triangles: Triangle[] = [];\n const edge = (a: number, b: number, opposite: number) => {\n if (a === b) return;\n const key = a < b ? `${a}:${b}` : `${b}:${a}`;\n const existing = edgeMap.get(key);\n if (existing) existing.opposites.push(opposite);\n else edgeMap.set(key, { a, b, opposites: [opposite] });\n };\n for (let i = 0; i + 2 < indices.length; i += 3) {\n const a = this.vertexParticle[indices[i]], b = this.vertexParticle[indices[i + 1]], c = this.vertexParticle[indices[i + 2]];\n if (a === b || b === c || c === a) continue;\n triangles.push({ a, b, c }); edge(a, b, c); edge(b, c, a); edge(c, a, b);\n }\n this.triangles = triangles;\n const edges: Edge[] = [];\n for (const value of edgeMap.values()) {\n const length = particles[value.a].base.distanceTo(particles[value.b].base);\n edges.push({ a: value.a, b: value.b, length, bend: false });\n graph[value.a].push({ to: value.b, length }); graph[value.b].push({ to: value.a, length });\n if (value.opposites.length === 2 && value.opposites[0] !== value.opposites[1]) {\n const a = value.opposites[0], b = value.opposites[1];\n edges.push({ a, b, length: particles[a].base.distanceTo(particles[b].base), bend: true });\n }\n }\n this.edges = edges;\n const nearest = (point: Point) => {\n const p = new Vector3().fromArray(point); let found = 0, best = Infinity;\n for (let i = 0; i < particles.length; i++) {\n const d = particles[i].base.distanceToSquared(p); if (d < best) { best = d; found = i; }\n }\n return found;\n };\n const cloth = pins.filter(pin => pin.cloth && !pin.guide).map(pin => nearest(pin.rest));\n const body = pins.filter(pin => !pin.cloth && !pin.guide).map(pin => nearest(pin.rest));\n const clothDistance = distances(graph, cloth), bodyDistance = distances(graph, body);\n for (let i = 0; i < particles.length; i++) {\n const a = clothDistance[i], b = bodyDistance[i];\n particles[i].share = Number.isFinite(a) && Number.isFinite(b) ? b / Math.max(1e-6, a + b) : Number.isFinite(a) ? 1 : 0;\n particles[i].anchor = Number.isFinite(b) ? Math.exp(-b / (.12 * this.scale)) : 0;\n }\n this.particles = particles;\n }\n\n get movableCount() { return this.particles.filter(p => p.share > .25).length; }\n\n reset() {\n this.time = 0;\n for (const particle of this.particles) particle.position.copy(particle.base), particle.previous.copy(particle.base);\n }\n\n step(baseVertices: Float32Array, seconds: number, windStrength: number, colliders: readonly ClothCollider[] = [], motion: Readonly<MotionSettings> = DEFAULT_MOTION) {\n const count = this.particles.length, base = Array.from({ length: count }, () => new Vector3()), samples = new Uint32Array(count);\n for (let i = 0; i < this.vertexParticle.length; i++) {\n const node = this.vertexParticle[i]; base[node].add(new Vector3().fromArray(baseVertices, i * 3)); samples[node]++;\n }\n for (let i = 0; i < count; i++) {\n base[i].divideScalar(samples[i] || 1);\n const particle = this.particles[i], delta = base[i].clone().sub(particle.base);\n particle.position.add(delta); particle.previous.add(delta); particle.base.copy(base[i]);\n }\n const dt = Math.min(Math.max(seconds, 0), .05), steps = Math.max(1, Math.ceil(dt * 60)), h = dt / steps;\n const profile = windProfile(windStrength), pressureScale = profile.load ? .025 * profile.surfaceLoad / profile.load : 0;\n const radius = Math.max(1e-4, ...colliders.map(collider => collider.radius));\n const cell = radius * 2;\n const bins = new Map<number, ClothCollider[]>();\n // Hash collisions only add candidates; the distance test below remains exact.\n const key = (x: number, y: number, z: number) => (Math.imul(x, 73856093) ^ Math.imul(y, 19349663) ^ Math.imul(z, 83492791)) | 0;\n for (const collider of colliders) {\n const p = collider.position, id = key(Math.floor(p[0] / cell), Math.floor(p[1] / cell), Math.floor(p[2] / cell));\n const bin = bins.get(id) ?? []; bin.push(collider); bins.set(id, bin);\n }\n for (let step = 0; step < steps && h > 0; step++) {\n this.time += h;\n const force = Array.from({ length: count }, () => new Vector3());\n const area = new Float32Array(count);\n if (pressureScale && motion.strength) for (const triangle of this.triangles) {\n const a = this.particles[triangle.a].position, b = this.particles[triangle.b].position, c = this.particles[triangle.c].position;\n const normal = b.clone().sub(a).cross(c.clone().sub(a));\n const surface = normal.length(); if (surface < 1e-10) continue;\n normal.divideScalar(surface);\n const center = a.clone().add(b).add(c).divideScalar(3);\n const wind = windAcceleration(this.time, windStrength, this.scale, center.toArray());\n // Normal pressure bends the sheet; a small tangential drag carries\n // near-parallel fabric rather than letting it ignore the wind entirely.\n const pressure = normal.multiplyScalar(wind.dot(normal)).addScaledVector(wind, .12)\n .multiplyScalar(pressureScale);\n for (const node of [triangle.a, triangle.b, triangle.c]) { force[node].addScaledVector(pressure, surface); area[node] += surface; }\n }\n for (let i = 0; i < count; i++) {\n const particle = this.particles[i], share = particle.share;\n if (share < 1e-4) { particle.position.copy(particle.base); particle.previous.copy(particle.base); continue; }\n const velocity = particle.position.clone().sub(particle.previous).multiplyScalar(Math.exp(-motion.damping * 3 * h));\n particle.previous.copy(particle.position);\n particle.position.add(velocity).y -= 2.5 * this.scale * share * h * h;\n if (area[i]) particle.position.addScaledVector(force[i], motion.strength * share * h * h / area[i]);\n const anchor = 1 - Math.exp(-(1.5 + 60 * particle.anchor ** 2) * h);\n particle.position.lerp(particle.base, anchor);\n }\n for (let iteration = 0; iteration < 5; iteration++) {\n for (const edge of this.edges) {\n const a = this.particles[edge.a], b = this.particles[edge.b];\n const difference = b.position.clone().sub(a.position), length = difference.length();\n if (length < 1e-8) continue;\n const wa = a.share * a.share, wb = b.share * b.share, total = wa + wb;\n if (total < 1e-8) continue;\n const strength = edge.bend ? .14 : .72;\n difference.multiplyScalar((length - edge.length) * strength / (length * total));\n a.position.addScaledVector(difference, wa); b.position.addScaledVector(difference, -wb);\n }\n }\n if (colliders.length) for (const particle of this.particles) {\n if (particle.share < .35) continue;\n const p = particle.position, px = p.x / cell, py = p.y / cell, pz = p.z / cell;\n const x = Math.floor(px), y = Math.floor(py), z = Math.floor(pz);\n const sx = px - x < .5 ? -1 : 1, sy = py - y < .5 ? -1 : 1, sz = pz - z < .5 ? -1 : 1;\n let chosen: ClothCollider | undefined, penetration = 0;\n // Cell width is twice the largest radius, so only the nearest neighbor\n // on each axis can contain a sphere reaching this particle.\n for (let iz = 0; iz < 2; iz++) for (let iy = 0; iy < 2; iy++) for (let ix = 0; ix < 2; ix++) {\n for (const collider of bins.get(key(x + ix * sx, y + iy * sy, z + iz * sz)) ?? []) {\n const center = collider.position, bx = particle.base.x - center[0], by = particle.base.y - center[1], bz = particle.base.z - center[2];\n if (bx * bx + by * by + bz * bz < collider.radius * collider.radius * 1.04) continue;\n const vx = p.x - center[0], vy = p.y - center[1], vz = p.z - center[2];\n const depth = collider.radius - Math.hypot(vx, vy, vz);\n if (depth > penetration) { penetration = depth; chosen = collider; }\n }\n }\n if (chosen) {\n const center = chosen.position, delta = p.clone().sub(new Vector3().fromArray(center));\n if (delta.lengthSq() < 1e-12) delta.copy(particle.base).sub(new Vector3().fromArray(center));\n p.copy(new Vector3().fromArray(center).add(delta.setLength(chosen.radius)));\n }\n }\n }\n const result = new Float32Array(baseVertices.length);\n for (let i = 0; i < this.vertexParticle.length; i++) result.set(this.particles[this.vertexParticle[i]].position.toArray(), i * 3);\n return result;\n }\n}\n", "export type MotionSettings = { reach: number; frequency: number; damping: number; massInfluence:number; strength:number };\nexport const DEFAULT_MOTION: Readonly<MotionSettings> = { reach: .5, frequency: 14 / (2*Math.PI), damping: .28, massInfluence:1,strength:1 };\nexport function validateMotionSettings(value: MotionSettings) {\n if (!value || !Number.isFinite(value.reach) || value.reach < 0 || value.reach > 1\n || !Number.isFinite(value.frequency) || value.frequency < .25 || value.frequency > 8\n || !Number.isFinite(value.damping) || value.damping < .05 || value.damping > 1\n || !Number.isFinite(value.massInfluence) || value.massInfluence<0 || value.massInfluence>2\n || !Number.isFinite(value.strength) || value.strength<0 || value.strength>3) throw new Error('Invalid motion settings.');\n}\n", "import { Vector3 } from 'three';\n\nexport const MAX_WIND_STRENGTH = 4;\n\n/** A single weather control drives pin motion and surface pressure. Sparse pin\n * loads stay bounded; fabric pressure has room to grow through a storm. */\nexport function windProfile(strength: number) {\n const level = Math.max(0, Math.min(MAX_WIND_STRENGTH, strength));\n const label = level === 0 ? 'Off' : level < .75 ? 'Breeze' : level < 1.5 ? 'Windy' : level < 2.5 ? 'Strong wind' : level < 3.3 ? 'Gale' : 'Storm';\n return {\n label,\n load: 30 * level * level / (.8 + level * level),\n surfaceLoad: 4 * level * level,\n gust: .14 + .12 * level,\n crosswind: .05 + .07 * level,\n gustRate: .42 + .12 * level,\n };\n}\n\n/** Deterministic scene-local prevailing wind with slow gusts and spatially\n * varying eddies. Force is an acceleration scaled to the model's size, so a\n * tiny prop and a large character respond comparably at the same setting. */\nexport function windAcceleration(seconds: number, strength: number, scale: number, position: readonly number[]) {\n if (strength <= 0) return new Vector3();\n const size = Math.max(1e-4, scale);\n const profile = windProfile(strength);\n // Advect the gust bands along +X. Nearby controls see related wind, while\n // their phase delay keeps a large sheet or branch hierarchy from moving as\n // one perfectly synchronized rigid object.\n const along = position[0] / size, lateral = (position[1] * .67 + position[2] * .33) / size;\n const slow = seconds * profile.gustRate - along * .55;\n const fast = seconds * (profile.gustRate * 2.7) - along * 1.4 + lateral * .4;\n const gust = Math.max(.2, 1 + profile.gust * (.7 * Math.sin(slow) + .3 * Math.sin(fast + 1.3)));\n const cross = profile.crosswind * (.65 * Math.sin(fast + lateral) + .35 * Math.sin(slow * .73 - lateral * .6));\n return new Vector3(1, cross * .35, cross).normalize().multiplyScalar(profile.load * size * gust);\n}\n"],
5
+ "mappings": ";;;AAAA,SAAS,WAAAA,gBAAe;;;ACCjB,IAAM,iBAA2C,EAAE,OAAO,KAAI,WAAW,MAAM,IAAE,KAAK,KAAK,SAAS,MAAK,eAAc,GAAE,UAAS,EAAE;;;ACD3I,SAAS,eAAe;AAEjB,IAAM,oBAAoB;AAI1B,SAAS,YAAY,UAAkB;AAC5C,QAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,IAAI,mBAAmB,QAAQ,CAAC;AAC/D,QAAM,QAAQ,UAAU,IAAI,QAAQ,QAAQ,OAAM,WAAW,QAAQ,MAAM,UAAU,QAAQ,MAAM,gBAAgB,QAAQ,MAAM,SAAS;AAC1I,SAAO;AAAA,IACL;AAAA,IACA,MAAM,KAAK,QAAQ,SAAS,MAAK,QAAQ;AAAA,IACzC,aAAa,IAAI,QAAQ;AAAA,IACzB,MAAM,OAAM,OAAM;AAAA,IAClB,WAAW,OAAM,OAAM;AAAA,IACvB,UAAU,OAAM,OAAM;AAAA,EACxB;AACF;AAKO,SAAS,iBAAiB,SAAiB,UAAkB,OAAe,UAA6B;AAC9G,MAAI,YAAY,EAAG,QAAO,IAAI,QAAQ;AACtC,QAAM,OAAO,KAAK,IAAI,MAAM,KAAK;AACjC,QAAM,UAAU,YAAY,QAAQ;AAIpC,QAAM,QAAQ,SAAS,CAAC,IAAI,MAAM,WAAW,SAAS,CAAC,IAAI,OAAM,SAAS,CAAC,IAAI,QAAO;AACtF,QAAM,OAAO,UAAU,QAAQ,WAAW,QAAQ;AAClD,QAAM,OAAO,WAAW,QAAQ,WAAW,OAAO,QAAQ,MAAM,UAAU;AAC1E,QAAM,OAAO,KAAK,IAAI,KAAI,IAAI,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E,IAAI,IAAIA,SAAQ,EAAE,UAAU,MAAM,CAAC;AAC3F,YAAE,KAAK,IAAIA,SAAQ,EAAE,UAAU,MAAM,EAAE,IAAI,MAAM,UAAU,OAAO,MAAM,CAAC,CAAC;AAAA,QAC5E;AAAA,MACF;AAAA,IACF;AACA,UAAM,SAAS,IAAI,aAAa,aAAa,MAAM;AACnD,aAAS,IAAI,GAAG,IAAI,KAAK,eAAe,QAAQ,IAAK,QAAO,IAAI,KAAK,UAAU,KAAK,eAAe,CAAC,CAAC,EAAE,SAAS,QAAQ,GAAG,IAAI,CAAC;AAChI,WAAO;AAAA,EACT;AACF;",
6
+ "names": ["Vector3", "Vector3"]
7
+ }
@@ -0,0 +1,130 @@
1
+ // @ts-nocheck
2
+
3
+ // src/deformation/fur-surface.ts
4
+ import { BufferAttribute, MeshPhysicalMaterial, MeshStandardMaterial, SkinnedMesh } from "three";
5
+ import { MeshPhysicalNodeMaterial, MeshStandardNodeMaterial } from "three/webgpu";
6
+ import { attribute, float, mix, normalMap, positionLocal, texture, uniform, uv, varying, vec2, vec3, vec4 } from "three/tsl";
7
+ var FurSurface = class {
8
+ surfaces = [];
9
+ height = null;
10
+ clock = uniform(0);
11
+ wind = uniform(0);
12
+ constructor(scene, descriptor, nodes, helpers) {
13
+ const depth = /* @__PURE__ */ new Map();
14
+ descriptor.pins.forEach((pin, i) => depth.set(nodes[i], pin.fur ? pin.furDepth ?? 0.1 : 0));
15
+ descriptor.helpers?.forEach((helper, i) => depth.set(helpers[i], helper.influences.reduce((sum, influence) => {
16
+ const index = descriptor.joints.findIndex((joint) => joint.node === influence.node);
17
+ const pin = descriptor.pins[index];
18
+ return sum + (pin?.fur ? (pin.furDepth ?? 0.1) * influence.weight : 0);
19
+ }, 0)));
20
+ scene.traverse((object) => {
21
+ if (!(object instanceof SkinnedMesh)) return;
22
+ const geometry = object.geometry, indices = geometry.getAttribute("skinIndex"), weights = geometry.getAttribute("skinWeight");
23
+ if (!indices || !weights || !geometry.getAttribute("uv") || !geometry.getAttribute("normal")) return;
24
+ if ((Array.isArray(object.material) ? object.material : [object.material]).some((material) => !(material instanceof MeshStandardMaterial))) return;
25
+ const values = new Float32Array(indices.count);
26
+ for (let v = 0; v < values.length; v++) for (let lane = 0; lane < 4; lane++) {
27
+ values[v] += (depth.get(object.skeleton.bones[indices.getComponent(v, lane)]) ?? 0) * weights.getComponent(v, lane);
28
+ }
29
+ if (!values.some((value) => value > 1e-5)) return;
30
+ const modified = geometry.clone();
31
+ modified.setAttribute("furDepth", new BufferAttribute(values, 1));
32
+ const surface = { mesh: object, geometry, modified, material: object.material, variants: [] };
33
+ object.geometry = modified;
34
+ this.surfaces.push(surface);
35
+ });
36
+ this.rebuild();
37
+ }
38
+ setHeightMap(height) {
39
+ if (this.height !== height) {
40
+ this.height = height;
41
+ this.rebuild();
42
+ }
43
+ }
44
+ update(seconds, windStrength) {
45
+ this.clock.value += Math.max(0, Math.min(seconds, 0.1));
46
+ this.wind.value = windStrength;
47
+ }
48
+ /** GLTFExporter must only see standard portable materials and attributes. */
49
+ setPortable(portable) {
50
+ for (const surface of this.surfaces) {
51
+ surface.mesh.geometry = portable ? surface.geometry : surface.modified;
52
+ surface.mesh.material = portable ? surface.material : Array.isArray(surface.material) ? surface.variants : surface.variants[0];
53
+ }
54
+ }
55
+ dispose() {
56
+ this.setPortable(true);
57
+ for (const surface of this.surfaces) {
58
+ surface.modified.dispose();
59
+ surface.mesh.geometry = surface.geometry;
60
+ for (const variant of surface.variants) variant.dispose();
61
+ }
62
+ this.surfaces.length = 0;
63
+ }
64
+ rebuild() {
65
+ for (const surface of this.surfaces) {
66
+ const sources = Array.isArray(surface.material) ? surface.material : [surface.material];
67
+ const variants = sources.map((source) => this.material(source));
68
+ this.setPortable(true);
69
+ for (const old of surface.variants) old.dispose();
70
+ surface.variants = variants;
71
+ }
72
+ this.setPortable(false);
73
+ }
74
+ material(source) {
75
+ const material = source instanceof MeshPhysicalMaterial ? new MeshPhysicalNodeMaterial() : new MeshStandardNodeMaterial();
76
+ material.copy(source);
77
+ material.name = `${source.name || "Material"} \xB7 Fur texture motion`;
78
+ const coordinates = uv();
79
+ const signal = source.map ?? source.normalMap ?? source.roughnessMap ?? source.metalnessMap ?? source.emissiveMap ?? source.aoMap ?? source.alphaMap ?? this.height;
80
+ if (!signal) return material;
81
+ const depth = attribute("furDepth", "float").mul(5).clamp(0, 1);
82
+ const skinnedDelta = varying(positionLocal.sub(attribute("position", "vec3")), "furSkinDelta");
83
+ const dimensions = signal.image;
84
+ const pixel = vec2(1 / Math.max(1, dimensions?.width ?? 1024), 1 / Math.max(1, dimensions?.height ?? 1024));
85
+ const movement = projectMotionToUv(skinnedDelta, coordinates).clamp(pixel.mul(-1.5), pixel.mul(1.5));
86
+ const height = this.height ? texture(this.height, uv(this.height.channel)).r : float(0.5);
87
+ const raised = mix(0.65, 1.35, height);
88
+ const phase = coordinates.dot(vec2(31, 43)).add(height.sub(0.5).mul(2.4)).add(this.clock.mul(this.wind).mul(1.7));
89
+ const gust = vec2(phase.sin(), phase.mul(1.31).cos()).mul(pixel).mul(this.wind.mul(0.65));
90
+ const shift = movement.add(gust).mul(depth).mul(raised).clamp(pixel.mul(-2), pixel.mul(2)).toVar("furTextureShift");
91
+ const sample = (map) => {
92
+ const node = texture(map, uv(map.channel).add(shift));
93
+ node.updateMatrix = true;
94
+ return node;
95
+ };
96
+ const base = source.map ? sample(source.map) : vec4(1);
97
+ material.colorNode = base.mul(vec4(source.color.r, source.color.g, source.color.b, 1));
98
+ if (source.alphaMap) material.opacityNode = sample(source.alphaMap).g;
99
+ if (source.normalMap) material.normalNode = normalMap(
100
+ sample(source.normalMap).xyz,
101
+ vec2(source.normalScale.x, source.normalScale.y)
102
+ );
103
+ material.roughnessNode = source.roughnessMap ? sample(source.roughnessMap).g.mul(source.roughness) : float(source.roughness);
104
+ material.metalnessNode = source.metalnessMap ? sample(source.metalnessMap).b.mul(source.metalness) : float(source.metalness);
105
+ if (source.aoMap) material.aoNode = float(1).sub(float(1).sub(sample(source.aoMap).r).mul(source.aoMapIntensity));
106
+ if (source.emissiveMap) material.emissiveNode = sample(source.emissiveMap).rgb.mul(vec3(
107
+ source.emissive.r * source.emissiveIntensity,
108
+ source.emissive.g * source.emissiveIntensity,
109
+ source.emissive.b * source.emissiveIntensity
110
+ ));
111
+ material.userData.furSurface = { heightMapped: Boolean(this.height), motionMapped: true };
112
+ return material;
113
+ }
114
+ };
115
+ function projectMotionToUv(movement, coordinates) {
116
+ const dUvDx = coordinates.dFdx(), dUvDy = coordinates.dFdy();
117
+ const dPosDx = positionLocal.dFdx(), dPosDy = positionLocal.dFdy();
118
+ const determinant = dUvDx.x.mul(dUvDy.y).sub(dUvDx.y.mul(dUvDy.x));
119
+ const safe = determinant.abs().max(1e-10).mul(determinant.lessThan(0).select(-1, 1));
120
+ const dPosDu = dPosDx.mul(dUvDy.y).sub(dPosDy.mul(dUvDx.y)).div(safe);
121
+ const dPosDv = dPosDy.mul(dUvDx.x).sub(dPosDx.mul(dUvDx.y)).div(safe);
122
+ const uu = dPosDu.dot(dPosDu), vv = dPosDv.dot(dPosDv), uvMetric = dPosDu.dot(dPosDv);
123
+ const metric = uu.mul(vv).sub(uvMetric.mul(uvMetric)).max(1e-12);
124
+ const u = movement.dot(dPosDu), v = movement.dot(dPosDv);
125
+ return vec2(vv.mul(u).sub(uvMetric.mul(v)).div(metric), uu.mul(v).sub(uvMetric.mul(u)).div(metric));
126
+ }
127
+ export {
128
+ FurSurface
129
+ };
130
+ //# sourceMappingURL=fur-surface.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/deformation/fur-surface.ts"],
4
+ "sourcesContent": ["import { BufferAttribute, MeshPhysicalMaterial, MeshStandardMaterial, SkinnedMesh, type BufferGeometry, type Material, type Object3D, type Texture } from 'three';\nimport { MeshPhysicalNodeMaterial, MeshStandardNodeMaterial, type Node } from 'three/webgpu';\nimport { attribute, float, mix, normalMap, positionLocal, texture, uniform, uv, varying, vec2, vec3, vec4 } from 'three/tsl';\nimport type { RigDescriptor } from './rig-extension.js';\n\ninterface Surface { mesh: SkinnedMesh; geometry: BufferGeometry; modified: BufferGeometry; material: Material | Material[]; variants: MeshStandardNodeMaterial[] }\n\n/** Optional GPU detail for a portable skinned GLB. Nothing is written into its\n * fallback material or geometry, and the variant is absent without Fur pins. */\nexport class FurSurface {\n readonly surfaces: Surface[] = [];\n private height: Texture | null = null;\n private clock = uniform(0);\n private wind = uniform(0);\n\n constructor(scene: Object3D, descriptor: RigDescriptor, nodes: readonly Object3D[], helpers: readonly Object3D[]) {\n const depth = new Map<Object3D, number>();\n descriptor.pins.forEach((pin, i) => depth.set(nodes[i], pin.fur ? (pin.furDepth ?? .1) : 0));\n descriptor.helpers?.forEach((helper, i) => depth.set(helpers[i], helper.influences.reduce((sum, influence) => {\n const index = descriptor.joints.findIndex(joint => joint.node === influence.node);\n const pin = descriptor.pins[index];\n return sum + (pin?.fur ? (pin.furDepth ?? .1) * influence.weight : 0);\n }, 0)));\n scene.traverse(object => {\n if (!(object instanceof SkinnedMesh)) return;\n const geometry = object.geometry, indices = geometry.getAttribute('skinIndex'), weights = geometry.getAttribute('skinWeight');\n if (!indices || !weights || !geometry.getAttribute('uv') || !geometry.getAttribute('normal')) return;\n if ((Array.isArray(object.material) ? object.material : [object.material]).some(material => !(material instanceof MeshStandardMaterial))) return;\n const values = new Float32Array(indices.count);\n for (let v = 0; v < values.length; v++) for (let lane = 0; lane < 4; lane++) {\n values[v] += (depth.get(object.skeleton.bones[indices.getComponent(v, lane)]) ?? 0) * weights.getComponent(v, lane);\n }\n if (!values.some(value => value > 1e-5)) return;\n const modified = geometry.clone();\n modified.setAttribute('furDepth', new BufferAttribute(values, 1));\n const surface: Surface = { mesh: object, geometry, modified, material: object.material, variants: [] };\n object.geometry = modified;\n this.surfaces.push(surface);\n });\n this.rebuild();\n }\n\n setHeightMap(height: Texture | null) { if (this.height !== height) { this.height = height; this.rebuild(); } }\n update(seconds: number, windStrength: number) {\n this.clock.value += Math.max(0, Math.min(seconds, .1));\n this.wind.value = windStrength;\n }\n /** GLTFExporter must only see standard portable materials and attributes. */\n setPortable(portable: boolean) {\n for (const surface of this.surfaces) {\n surface.mesh.geometry = portable ? surface.geometry : surface.modified;\n surface.mesh.material = portable ? surface.material : Array.isArray(surface.material) ? surface.variants : surface.variants[0];\n }\n }\n dispose() {\n this.setPortable(true);\n for (const surface of this.surfaces) {\n surface.modified.dispose(); surface.mesh.geometry = surface.geometry;\n for (const variant of surface.variants) variant.dispose();\n }\n this.surfaces.length = 0;\n }\n private rebuild() {\n for (const surface of this.surfaces) {\n const sources = Array.isArray(surface.material) ? surface.material : [surface.material];\n const variants = sources.map(source => this.material(source as MeshStandardMaterial));\n this.setPortable(true);\n for (const old of surface.variants) old.dispose();\n surface.variants = variants;\n }\n this.setPortable(false);\n }\n private material(source: MeshStandardMaterial) {\n const material = source instanceof MeshPhysicalMaterial ? new MeshPhysicalNodeMaterial() : new MeshStandardNodeMaterial();\n material.copy(source);\n material.name = `${source.name || 'Material'} \u00B7 Fur texture motion`;\n const coordinates = uv();\n const signal = source.map ?? source.normalMap ?? source.roughnessMap ?? source.metalnessMap ?? source.emissiveMap ?? source.aoMap ?? source.alphaMap ?? this.height;\n if (!signal) return material;\n const depth = attribute('furDepth', 'float' as const).mul(5).clamp(0, 1);\n const skinnedDelta = varying(positionLocal.sub(attribute('position', 'vec3' as const)), 'furSkinDelta') as Node<'vec3'>;\n const dimensions = signal.image as { width?: number; height?: number } | undefined;\n const pixel = vec2(1 / Math.max(1, dimensions?.width ?? 1024), 1 / Math.max(1, dimensions?.height ?? 1024));\n const movement = projectMotionToUv(skinnedDelta, coordinates).clamp(pixel.mul(-1.5), pixel.mul(1.5));\n const height = this.height ? texture(this.height, uv(this.height.channel)).r : float(.5);\n const raised = mix(.65, 1.35, height);\n const phase = coordinates.dot(vec2(31, 43)).add(height.sub(.5).mul(2.4)).add(this.clock.mul(this.wind).mul(1.7));\n const gust = vec2(phase.sin(), phase.mul(1.31).cos()).mul(pixel).mul(this.wind.mul(.65));\n // A shared subpixel-to-two-pixel UV flow keeps color, normal, ORM, AO and\n // opacity aligned. The field follows the skinned surface and can shimmer\n // with wind; height modulates movement rather than drawing synthetic hair.\n const shift = movement.add(gust).mul(depth).mul(raised)\n .clamp(pixel.mul(-2), pixel.mul(2)).toVar('furTextureShift');\n const sample = (map: Texture) => {\n const node = texture(map, uv(map.channel).add(shift));\n node.updateMatrix = true;\n return node;\n };\n const base = source.map ? sample(source.map) : vec4(1);\n material.colorNode = base.mul(vec4(source.color.r, source.color.g, source.color.b, 1));\n if (source.alphaMap) material.opacityNode = sample(source.alphaMap).g;\n if (source.normalMap) material.normalNode = normalMap(sample(source.normalMap).xyz,\n vec2(source.normalScale.x, source.normalScale.y));\n material.roughnessNode = source.roughnessMap ? sample(source.roughnessMap).g.mul(source.roughness) : float(source.roughness);\n material.metalnessNode = source.metalnessMap ? sample(source.metalnessMap).b.mul(source.metalness) : float(source.metalness);\n if (source.aoMap) material.aoNode = float(1).sub(float(1).sub(sample(source.aoMap).r).mul(source.aoMapIntensity));\n if (source.emissiveMap) material.emissiveNode = sample(source.emissiveMap).rgb.mul(vec3(\n source.emissive.r * source.emissiveIntensity,\n source.emissive.g * source.emissiveIntensity,\n source.emissive.b * source.emissiveIntensity));\n material.userData.furSurface = { heightMapped: Boolean(this.height), motionMapped: true };\n return material;\n }\n}\n\n/** Convert the current skin displacement into a local UV offset. The metric\n * inversion avoids assuming that U/V align with world X/Y or have equal scale. */\nfunction projectMotionToUv(movement: Node<'vec3'>, coordinates: Node<'vec2'>) {\n const dUvDx = coordinates.dFdx(), dUvDy = coordinates.dFdy();\n const dPosDx = positionLocal.dFdx(), dPosDy = positionLocal.dFdy();\n const determinant = dUvDx.x.mul(dUvDy.y).sub(dUvDx.y.mul(dUvDy.x));\n const safe = determinant.abs().max(1e-10).mul(determinant.lessThan(0).select(-1, 1));\n const dPosDu = dPosDx.mul(dUvDy.y).sub(dPosDy.mul(dUvDx.y)).div(safe);\n const dPosDv = dPosDy.mul(dUvDx.x).sub(dPosDx.mul(dUvDx.y)).div(safe);\n const uu = dPosDu.dot(dPosDu), vv = dPosDv.dot(dPosDv), uvMetric = dPosDu.dot(dPosDv);\n const metric = uu.mul(vv).sub(uvMetric.mul(uvMetric)).max(1e-12);\n const u = movement.dot(dPosDu), v = movement.dot(dPosDv);\n return vec2(vv.mul(u).sub(uvMetric.mul(v)).div(metric), uu.mul(v).sub(uvMetric.mul(u)).div(metric));\n}\n"],
5
+ "mappings": ";;;AAAA,SAAS,iBAAiB,sBAAsB,sBAAsB,mBAAoF;AAC1J,SAAS,0BAA0B,gCAA2C;AAC9E,SAAS,WAAW,OAAO,KAAK,WAAW,eAAe,SAAS,SAAS,IAAI,SAAS,MAAM,MAAM,YAAY;AAO1G,IAAM,aAAN,MAAiB;AAAA,EACb,WAAsB,CAAC;AAAA,EACxB,SAAyB;AAAA,EACzB,QAAQ,QAAQ,CAAC;AAAA,EACjB,OAAO,QAAQ,CAAC;AAAA,EAExB,YAAY,OAAiB,YAA2B,OAA4B,SAA8B;AAChH,UAAM,QAAQ,oBAAI,IAAsB;AACxC,eAAW,KAAK,QAAQ,CAAC,KAAK,MAAM,MAAM,IAAI,MAAM,CAAC,GAAG,IAAI,MAAO,IAAI,YAAY,MAAM,CAAC,CAAC;AAC3F,eAAW,SAAS,QAAQ,CAAC,QAAQ,MAAM,MAAM,IAAI,QAAQ,CAAC,GAAG,OAAO,WAAW,OAAO,CAAC,KAAK,cAAc;AAC5G,YAAM,QAAQ,WAAW,OAAO,UAAU,WAAS,MAAM,SAAS,UAAU,IAAI;AAChF,YAAM,MAAM,WAAW,KAAK,KAAK;AACjC,aAAO,OAAO,KAAK,OAAO,IAAI,YAAY,OAAM,UAAU,SAAS;AAAA,IACrE,GAAG,CAAC,CAAC,CAAC;AACN,UAAM,SAAS,YAAU;AACvB,UAAI,EAAE,kBAAkB,aAAc;AACtC,YAA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AAC,EAAE,IAAI,IAAI;AACpE,QAAM,SAAS,OAAO,IAAI,MAAM,CAAC,EAAE,IAAI,OAAO,IAAI,MAAM,CAAC,CAAC,EAAE,IAAI,IAAI;AACpE,QAAM,KAAK,OAAO,IAAI,MAAM,GAAG,KAAK,OAAO,IAAI,MAAM,GAAG,WAAW,OAAO,IAAI,MAAM;AACpF,QAAM,SAAS,GAAG,IAAI,EAAE,EAAE,IAAI,SAAS,IAAI,QAAQ,CAAC,EAAE,IAAI,KAAK;AAC/D,QAAM,IAAI,SAAS,IAAI,MAAM,GAAG,IAAI,SAAS,IAAI,MAAM;AACvD,SAAO,KAAK,GAAG,IAAI,CAAC,EAAE,IAAI,SAAS,IAAI,CAAC,CAAC,EAAE,IAAI,MAAM,GAAG,GAAG,IAAI,CAAC,EAAE,IAAI,SAAS,IAAI,CAAC,CAAC,EAAE,IAAI,MAAM,CAAC;AACpG;",
6
+ "names": []
7
+ }
@@ -0,0 +1,44 @@
1
+ // @ts-nocheck
2
+
3
+ // src/deformation/ik-constraints.ts
4
+ import { Quaternion, Vector3 } from "three";
5
+ var DEFAULT_IK_CONSTRAINT = { mode: "free", axis: "auto", min: -120, max: 120 };
6
+ function validateIKConstraint(value) {
7
+ if (value?.maxY !== void 0 && (!Number.isFinite(value.maxY) || value.maxY < 0 || value.maxY > 180)) throw new Error("Invalid IK cone aperture.");
8
+ if (value?.orientation !== void 0 && (!Array.isArray(value.orientation) || value.orientation.length !== 4 || !value.orientation.every(Number.isFinite) || Math.abs(Math.hypot(...value.orientation) - 1) > 1e-4)) throw new Error("Invalid IK cone orientation.");
9
+ if (!value || !["free", "cone", "hinge", "locked"].includes(value.mode) || !["auto", "x", "y", "z"].includes(value.axis) || !Number.isFinite(value.min) || !Number.isFinite(value.max) || value.min < -180 || value.max > 180 || value.min > value.max || value.mode === "cone" && value.max < 0) throw new Error("Invalid IK joint constraint.");
10
+ }
11
+ function coneFrame(axis, constraint) {
12
+ return new Quaternion().fromArray(constraint.orientation ?? [0, 0, 0, 1]).multiply(new Quaternion().setFromUnitVectors(new Vector3(0, 0, 1), axis.clone().normalize()));
13
+ }
14
+ function coneAngle(constraint, azimuth) {
15
+ const x = (constraint.mode === "cone" ? constraint.max : 90) * Math.PI / 180, y = (constraint.mode === "cone" ? constraint.maxY ?? constraint.max : 90) * Math.PI / 180;
16
+ const c = Math.cos(azimuth), s = Math.sin(azimuth);
17
+ if (x === 0 && Math.abs(c) > 1e-8 || y === 0 && Math.abs(s) > 1e-8) return 0;
18
+ return 1 / Math.sqrt((Math.abs(c) < 1e-8 ? 0 : c / Math.max(x, 1e-12)) ** 2 + (Math.abs(s) < 1e-8 ? 0 : s / Math.max(y, 1e-12)) ** 2);
19
+ }
20
+ function constrainCone(rotation, axis, constraint, movingAxis = axis) {
21
+ const frame = coneFrame(axis, constraint), direction = movingAxis.clone().normalize().applyQuaternion(rotation);
22
+ const local = direction.clone().applyQuaternion(frame.clone().invert()), azimuth = Math.atan2(local.y, local.x);
23
+ const angle = Math.atan2(Math.hypot(local.x, local.y), local.z), limit = coneAngle(constraint, azimuth);
24
+ if (angle <= limit + 1e-8) return rotation.clone();
25
+ const target = new Vector3(Math.sin(limit) * Math.cos(azimuth), Math.sin(limit) * Math.sin(azimuth), Math.cos(limit)).applyQuaternion(frame);
26
+ return new Quaternion().setFromUnitVectors(direction, target).multiply(rotation).normalize();
27
+ }
28
+ function constrainSwing(rotation, axis, degrees) {
29
+ const direction = axis.clone().normalize(), rotated = direction.clone().applyQuaternion(rotation);
30
+ const angle = direction.angleTo(rotated), limit = degrees * Math.PI / 180;
31
+ if (angle <= limit + 1e-8) return rotation.clone();
32
+ const normal = new Vector3().crossVectors(direction, rotated);
33
+ if (normal.lengthSq() < 1e-12) normal.crossVectors(direction, Math.abs(direction.x) < 0.8 ? new Vector3(1, 0, 0) : new Vector3(0, 1, 0));
34
+ return new Quaternion().setFromAxisAngle(normal.normalize(), limit - angle).multiply(rotation).normalize();
35
+ }
36
+ export {
37
+ DEFAULT_IK_CONSTRAINT,
38
+ coneAngle,
39
+ coneFrame,
40
+ constrainCone,
41
+ constrainSwing,
42
+ validateIKConstraint
43
+ };
44
+ //# sourceMappingURL=ik-constraints.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/deformation/ik-constraints.ts"],
4
+ "sourcesContent": ["import { Quaternion, Vector3 } from 'three';\nexport type IKConstraint = { mode:'free'|'cone'|'hinge'|'locked'; axis:'auto'|'x'|'y'|'z'; min:number; max:number; orientation?:[number,number,number,number]; maxY?:number };\nexport const DEFAULT_IK_CONSTRAINT:Readonly<IKConstraint> = {mode:'free',axis:'auto',min:-120,max:120};\nexport function validateIKConstraint(value:IKConstraint) {\n if(value?.maxY!==undefined && (!Number.isFinite(value.maxY)||value.maxY<0||value.maxY>180))throw new Error('Invalid IK cone aperture.');\n if(value?.orientation!==undefined && (!Array.isArray(value.orientation)||value.orientation.length!==4||!value.orientation.every(Number.isFinite)||Math.abs(Math.hypot(...value.orientation)-1)>1e-4))throw new Error('Invalid IK cone orientation.');\n if (!value || !['free','cone','hinge','locked'].includes(value.mode) || !['auto','x','y','z'].includes(value.axis)\n || !Number.isFinite(value.min) || !Number.isFinite(value.max) || value.min < -180 || value.max > 180 || value.min > value.max || (value.mode==='cone' && value.max<0)) throw new Error('Invalid IK joint constraint.');\n}\n/** Stable parent-local cone frame. Z follows the rest bone; X/Y are aperture axes. */\nexport function coneFrame(axis:Vector3,constraint:Readonly<IKConstraint>){\n return new Quaternion().fromArray(constraint.orientation??[0,0,0,1]).multiply(new Quaternion().setFromUnitVectors(new Vector3(0,0,1),axis.clone().normalize()));\n}\n/** Angular ellipse (also valid beyond 90 degrees), rather than a tangent-plane box. */\nexport function coneAngle(constraint:Readonly<IKConstraint>,azimuth:number){\n const x=(constraint.mode==='cone'?constraint.max:90)*Math.PI/180,y=(constraint.mode==='cone'?(constraint.maxY??constraint.max):90)*Math.PI/180;\n const c=Math.cos(azimuth),s=Math.sin(azimuth);\n if((x===0&&Math.abs(c)>1e-8)||(y===0&&Math.abs(s)>1e-8))return 0;\n return 1/Math.sqrt((Math.abs(c)<1e-8?0:c/Math.max(x,1e-12))**2+(Math.abs(s)<1e-8?0:s/Math.max(y,1e-12))**2);\n}\nexport function constrainCone(rotation:Quaternion,axis:Vector3,constraint:Readonly<IKConstraint>,movingAxis:Vector3=axis){\n const frame=coneFrame(axis,constraint),direction=movingAxis.clone().normalize().applyQuaternion(rotation);\n const local=direction.clone().applyQuaternion(frame.clone().invert()),azimuth=Math.atan2(local.y,local.x);\n const angle=Math.atan2(Math.hypot(local.x,local.y),local.z),limit=coneAngle(constraint,azimuth);\n if(angle<=limit+1e-8)return rotation.clone();\n const target=new Vector3(Math.sin(limit)*Math.cos(azimuth),Math.sin(limit)*Math.sin(azimuth),Math.cos(limit)).applyQuaternion(frame);\n return new Quaternion().setFromUnitVectors(direction,target).multiply(rotation).normalize();\n}\n/** Circular swing cone, not an Euler-angle box. Twist remains free. */\nexport function constrainSwing(rotation: Quaternion, axis: Vector3, degrees: number) {\n const direction=axis.clone().normalize(), rotated=direction.clone().applyQuaternion(rotation);\n const angle=direction.angleTo(rotated), limit=degrees*Math.PI/180;\n if(angle<=limit+1e-8)return rotation.clone();\n const normal=new Vector3().crossVectors(direction,rotated);\n if(normal.lengthSq()<1e-12)normal.crossVectors(direction,Math.abs(direction.x)<.8?new Vector3(1,0,0):new Vector3(0,1,0));\n return new Quaternion().setFromAxisAngle(normal.normalize(),limit-angle).multiply(rotation).normalize();\n}\n"],
5
+ "mappings": ";;;AAAA,SAAS,YAAY,eAAe;AAE7B,IAAM,wBAA+C,EAAC,MAAK,QAAO,MAAK,QAAO,KAAI,MAAK,KAAI,IAAG;AAC9F,SAAS,qBAAqB,OAAoB;AACvD,MAAG,OAAO,SAAO,WAAc,CAAC,OAAO,SAAS,MAAM,IAAI,KAAG,MAAM,OAAK,KAAG,MAAM,OAAK,KAAK,OAAM,IAAI,MAAM,2BAA2B;AACtI,M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AAE,CAAC,IAAE,IAAI,QAAQ,GAAE,GAAE,CAAC,CAAC;AACvH,SAAO,IAAI,WAAW,EAAE,iBAAiB,OAAO,UAAU,GAAE,QAAM,KAAK,EAAE,SAAS,QAAQ,EAAE,UAAU;AACxG;",
6
+ "names": []
7
+ }
@@ -0,0 +1,197 @@
1
+ // @ts-nocheck
2
+
3
+ // src/deformation/pin-types.ts
4
+ var MAX_FUR_DEPTH = 0.5;
5
+ var IK_CHAIN_KINDS = ["leg", "arm", "head", "tail", "wing", "fin", "tentacle", "spine"];
6
+
7
+ // src/deformation/limits.ts
8
+ var MAX_DEFORMATION_PINS = 128;
9
+
10
+ // src/deformation/motion-settings.ts
11
+ var DEFAULT_MOTION = { reach: 0.5, frequency: 14 / (2 * Math.PI), damping: 0.28, massInfluence: 1, strength: 1 };
12
+ function validateMotionSettings(value) {
13
+ if (!value || !Number.isFinite(value.reach) || value.reach < 0 || value.reach > 1 || !Number.isFinite(value.frequency) || value.frequency < 0.25 || value.frequency > 8 || !Number.isFinite(value.damping) || value.damping < 0.05 || value.damping > 1 || !Number.isFinite(value.massInfluence) || value.massInfluence < 0 || value.massInfluence > 2 || !Number.isFinite(value.strength) || value.strength < 0 || value.strength > 3) throw new Error("Invalid motion settings.");
14
+ }
15
+
16
+ // src/deformation/ik-constraints.ts
17
+ import { Quaternion, Vector3 } from "three";
18
+ function validateIKConstraint(value) {
19
+ if (value?.maxY !== void 0 && (!Number.isFinite(value.maxY) || value.maxY < 0 || value.maxY > 180)) throw new Error("Invalid IK cone aperture.");
20
+ if (value?.orientation !== void 0 && (!Array.isArray(value.orientation) || value.orientation.length !== 4 || !value.orientation.every(Number.isFinite) || Math.abs(Math.hypot(...value.orientation) - 1) > 1e-4)) throw new Error("Invalid IK cone orientation.");
21
+ if (!value || !["free", "cone", "hinge", "locked"].includes(value.mode) || !["auto", "x", "y", "z"].includes(value.axis) || !Number.isFinite(value.min) || !Number.isFinite(value.max) || value.min < -180 || value.max > 180 || value.min > value.max || value.mode === "cone" && value.max < 0) throw new Error("Invalid IK joint constraint.");
22
+ }
23
+
24
+ // src/deformation/pose-slots.ts
25
+ var POSE_SLOTS = 9;
26
+ function capturePose(pins) {
27
+ return pins.map((pin) => ({ id: pin.id, pose: pin.pose, ...pin.authored ? { authored: true } : {}, ...pin.ikTarget ? { ikTarget: pin.ikTarget } : {} }));
28
+ }
29
+ var restPoseOf = (rest) => ({ position: [rest[0], rest[1], rest[2]], rotation: [0, 0, 0, 1], scale: [1, 1, 1] });
30
+ function carriedPose(rest, parentRest, parent) {
31
+ const [qx, qy, qz, qw] = parent.rotation;
32
+ const x = (rest[0] - parentRest[0]) * parent.scale[0], y = (rest[1] - parentRest[1]) * parent.scale[1], z = (rest[2] - parentRest[2]) * parent.scale[2];
33
+ const tx = 2 * (qy * z - qz * y), ty = 2 * (qz * x - qx * z), tz = 2 * (qx * y - qy * x);
34
+ const position = [parent.position[0] + x + qw * tx + (qy * tz - qz * ty), parent.position[1] + y + qw * ty + (qz * tx - qx * tz), parent.position[2] + z + qw * tz + (qx * ty - qy * tx)];
35
+ const rotation = [qx, qy, qz, qw], scale = [parent.scale[0], parent.scale[1], parent.scale[2]];
36
+ return { position, rotation, scale };
37
+ }
38
+ function resolvePose(pins, slot, parents = /* @__PURE__ */ new Map()) {
39
+ const saved = new Map(slot.poses.map((p) => [p.id, p]));
40
+ const byId = new Map(pins.map((pin) => [pin.id, pin]));
41
+ const memo = /* @__PURE__ */ new Map(), visiting = /* @__PURE__ */ new Set();
42
+ const poseOf = (pin) => {
43
+ const cached = memo.get(pin.id);
44
+ if (cached) return cached;
45
+ const stored = saved.get(pin.id);
46
+ let pose;
47
+ if (stored) pose = stored.pose;
48
+ else {
49
+ const parentId = parents.get(pin.id);
50
+ const parent = parentId && !visiting.has(parentId) ? byId.get(parentId) : void 0;
51
+ if (!parent) pose = restPoseOf(pin.rest);
52
+ else {
53
+ visiting.add(pin.id);
54
+ pose = carriedPose(pin.rest, parent.rest, poseOf(parent));
55
+ visiting.delete(pin.id);
56
+ }
57
+ }
58
+ memo.set(pin.id, pose);
59
+ return pose;
60
+ };
61
+ const resolved = pins.map((pin) => {
62
+ const stored = saved.get(pin.id), { ikTarget: _target, authored: _authored, ...base } = pin;
63
+ return { ...base, pose: poseOf(pin), ...stored?.authored ? { authored: true } : {}, ...stored?.ikTarget ? { ikTarget: stored.ikTarget } : {} };
64
+ });
65
+ return resolved.map((pin) => {
66
+ if (!pin.rigidGroup) return pin;
67
+ const anchor = resolved.find((p) => p.rigidGroup === pin.rigidGroup);
68
+ return { ...pin, pose: { ...pin.pose, rotation: anchor.pose.rotation, scale: [anchor.pose.scale[0], anchor.pose.scale[0], anchor.pose.scale[0]] } };
69
+ });
70
+ }
71
+
72
+ // src/deformation/pose-timeline.ts
73
+ var MIN_POSE_SECONDS = 0.05;
74
+ var MAX_POSE_SECONDS = 60;
75
+
76
+ // src/deformation/wind.ts
77
+ import { Vector3 as Vector32 } from "three";
78
+ var MAX_WIND_STRENGTH = 4;
79
+
80
+ // src/deformation/joints-json.ts
81
+ function record(value) {
82
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid joints JSON object.");
83
+ return value;
84
+ }
85
+ function numbers(value, length) {
86
+ if (!Array.isArray(value) || value.length !== length || !value.every((v) => typeof v === "number" && Number.isFinite(v))) throw new Error("Invalid joint coordinates.");
87
+ return [...value];
88
+ }
89
+ function point(value) {
90
+ const v = numbers(value, 3);
91
+ return [v[0], v[1], v[2]];
92
+ }
93
+ function quaternion(value) {
94
+ const v = numbers(value, 4);
95
+ return [v[0], v[1], v[2], v[3]];
96
+ }
97
+ function validateJoints(value, maximum = MAX_DEFORMATION_PINS) {
98
+ if (!Array.isArray(value) || value.length > maximum) throw new Error(`Joints JSON must contain at most ${maximum} joints.`);
99
+ const ids = /* @__PURE__ */ new Set();
100
+ const pins = value.map((item) => {
101
+ const pin = record(item), pose = record(pin.pose);
102
+ if (typeof pin.id !== "string" || !pin.id || ids.has(pin.id)) throw new Error("Joint IDs must be unique non-empty strings.");
103
+ ids.add(pin.id);
104
+ if (typeof pin.independent !== "boolean" || pin.rigidGroup !== null && (typeof pin.rigidGroup !== "string" || !pin.rigidGroup)) throw new Error("Invalid joint membership.");
105
+ if (pin.guide !== void 0 && typeof pin.guide !== "boolean") throw new Error("Invalid guide flag.");
106
+ if (pin.authored !== void 0 && typeof pin.authored !== "boolean") throw new Error("Invalid authored flag.");
107
+ if (pin.ik !== void 0 && typeof pin.ik !== "boolean") throw new Error("Invalid IK flag.");
108
+ if (pin.wiggle !== void 0 && typeof pin.wiggle !== "boolean") throw new Error("Invalid Wiggle flag.");
109
+ if (pin.cloth !== void 0 && typeof pin.cloth !== "boolean") throw new Error("Invalid Cloth flag.");
110
+ if (pin.fur !== void 0 && typeof pin.fur !== "boolean") throw new Error("Invalid Fur flag.");
111
+ if (pin.furDepth !== void 0 && (typeof pin.furDepth !== "number" || !Number.isFinite(pin.furDepth) || pin.furDepth < 0 || pin.furDepth > MAX_FUR_DEPTH)) throw new Error("Invalid Fur depth.");
112
+ const chainRole = pin.chainRole === void 0 ? void 0 : (() => {
113
+ const value2 = record(pin.chainRole);
114
+ if (!IK_CHAIN_KINDS.includes(value2.kind) || !["center", "left", "right"].includes(value2.side) || value2.position !== void 0 && !["front", "hind"].includes(value2.position)) throw new Error("Invalid IK chain role.");
115
+ return { kind: value2.kind, side: value2.side, ...value2.position ? { position: value2.position } : {} };
116
+ })();
117
+ if (Number(Boolean(pin.ik)) + Number(Boolean(pin.wiggle)) + Number(Boolean(pin.cloth)) + Number(Boolean(pin.fur)) > 1) throw new Error("Choose IK, Wiggle, Cloth or Fur.");
118
+ const motion = pin.motion === void 0 ? void 0 : (() => {
119
+ const raw = record(pin.motion), result = { reach: Number(raw.reach), frequency: Number(raw.frequency), damping: Number(raw.damping), massInfluence: raw.massInfluence === void 0 ? DEFAULT_MOTION.massInfluence : Number(raw.massInfluence), strength: raw.strength === void 0 ? DEFAULT_MOTION.strength : Number(raw.strength) };
120
+ for (const key of ["massInfluence", "strength"]) if (raw[key] !== void 0 && typeof raw[key] !== "number") throw new Error("Invalid motion settings.");
121
+ if (typeof raw.reach !== "number" || typeof raw.frequency !== "number" || typeof raw.damping !== "number") throw new Error("Invalid motion settings.");
122
+ validateMotionSettings(result);
123
+ return result;
124
+ })();
125
+ const ikConstraint = pin.ikConstraint === void 0 ? void 0 : (() => {
126
+ const raw = record(pin.ikConstraint);
127
+ const value2 = { mode: raw.mode, axis: raw.axis, min: raw.min, max: raw.max, ...raw.orientation !== void 0 ? { orientation: quaternion(raw.orientation) } : {}, ...raw.maxY !== void 0 ? { maxY: raw.maxY } : {} };
128
+ validateIKConstraint(value2);
129
+ return value2;
130
+ })();
131
+ const ikTarget = pin.ikTarget === void 0 ? void 0 : (() => {
132
+ const raw = record(pin.ikTarget), rotation2 = quaternion(raw.rotation);
133
+ if (Math.abs(Math.hypot(...rotation2) - 1) > 1e-4) throw new Error("Invalid IK target rotation.");
134
+ return { position: point(raw.position), rotation: rotation2 };
135
+ })();
136
+ if (pin.guide && (pin.rigidGroup || pin.independent)) throw new Error("Guides cannot be rigid members or roots.");
137
+ const scale = point(pose.scale), rotation = quaternion(pose.rotation);
138
+ if (scale.some((v) => v < 0.01 || v > 100) || Math.abs(Math.hypot(...rotation) - 1) > 1e-4) throw new Error("Invalid joint rotation or scale.");
139
+ return {
140
+ id: pin.id,
141
+ independent: pin.independent,
142
+ rigidGroup: pin.rigidGroup,
143
+ ...pin.authored === true ? { authored: true } : {},
144
+ ...typeof pin.guide === "boolean" ? { guide: pin.guide } : {},
145
+ ...typeof pin.ik === "boolean" ? { ik: pin.ik } : {},
146
+ ...ikConstraint ? { ikConstraint } : {},
147
+ ...chainRole ? { chainRole } : {},
148
+ ...motion ? { motion } : {},
149
+ ...ikTarget ? { ikTarget } : {},
150
+ ...typeof pin.wiggle === "boolean" ? { wiggle: pin.wiggle } : {},
151
+ ...typeof pin.cloth === "boolean" ? { cloth: pin.cloth } : {},
152
+ ...typeof pin.fur === "boolean" ? { fur: pin.fur } : {},
153
+ ...pin.furDepth !== void 0 ? { furDepth: pin.furDepth } : {},
154
+ rest: point(pin.rest),
155
+ pose: { position: point(pose.position), rotation, scale }
156
+ };
157
+ });
158
+ for (const pin of pins) if (pin.rigidGroup) {
159
+ const anchor = pins.find((other) => other.rigidGroup === pin.rigidGroup);
160
+ const dot = pin.pose.rotation.reduce((sum, v, i) => sum + v * anchor.pose.rotation[i], 0);
161
+ if (pin.pose.scale.some((v) => Math.abs(v - anchor.pose.scale[0]) > 1e-5) || 1 - Math.abs(dot) > 1e-5) throw new Error("Rigid joints must share rotation and uniform scale.");
162
+ }
163
+ return pins;
164
+ }
165
+ function validatePoseTimes(value) {
166
+ if (!Array.isArray(value) || value.length > POSE_SLOTS) throw new Error("Invalid pose times.");
167
+ const slots = /* @__PURE__ */ new Set();
168
+ return value.map((item) => {
169
+ const entry = record(item);
170
+ if (!Number.isInteger(entry.slot) || entry.slot < 0 || entry.slot > POSE_SLOTS || slots.has(entry.slot)) throw new Error("Invalid pose time slot.");
171
+ slots.add(entry.slot);
172
+ if (typeof entry.seconds !== "number" || !Number.isFinite(entry.seconds) || entry.seconds < MIN_POSE_SECONDS || entry.seconds > MAX_POSE_SECONDS) throw new Error("Invalid pose time.");
173
+ return { slot: entry.slot, seconds: entry.seconds };
174
+ }).sort((a, b) => a.slot - b.slot);
175
+ }
176
+ function validateRig(value, maximum = MAX_DEFORMATION_PINS, parents = /* @__PURE__ */ new Map()) {
177
+ const pins = validateJoints(value.pins, maximum);
178
+ if (value.windStrength !== void 0 && (!Number.isFinite(value.windStrength) || value.windStrength < 0 || value.windStrength > MAX_WIND_STRENGTH)) throw new Error("Invalid wind strength.");
179
+ if (!Number.isInteger(value.activePose) || value.activePose < 0 || value.activePose > POSE_SLOTS || !Array.isArray(value.poseSlots) || value.poseSlots.length > POSE_SLOTS) throw new Error("Invalid pose slots.");
180
+ const slots = /* @__PURE__ */ new Set(), ids = new Set(pins.map((p) => p.id));
181
+ const poseSlots = value.poseSlots.map((slot) => {
182
+ if (!slot || !Number.isInteger(slot.slot) || slot.slot < 1 || slot.slot > POSE_SLOTS || slots.has(slot.slot) || !Array.isArray(slot.poses)) throw new Error("Invalid pose slot.");
183
+ slots.add(slot.slot);
184
+ const pinIds = /* @__PURE__ */ new Set();
185
+ for (const p of slot.poses) {
186
+ if (!p || !ids.has(p.id) || pinIds.has(p.id)) throw new Error("Invalid pose pin.");
187
+ pinIds.add(p.id);
188
+ }
189
+ return { slot: slot.slot, poses: capturePose(validateJoints(resolvePose(pins, slot, parents), maximum)) };
190
+ }).filter((slot) => slot.slot !== value.activePose);
191
+ return { pins, activePose: value.activePose, poseSlots, poseTimes: validatePoseTimes(value.poseTimes ?? []), ...value.windStrength !== void 0 ? { windStrength: value.windStrength } : {} };
192
+ }
193
+ export {
194
+ validateJoints,
195
+ validateRig
196
+ };
197
+ //# sourceMappingURL=joints-json.js.map