@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.
- package/LICENSE +21 -0
- package/README.md +93 -2
- package/build/deformation-runtime.js +2143 -0
- package/build/deformation-runtime.js.map +7 -0
- package/build/impostor-runtime-needle-engine.js +42 -0
- package/build/impostor-runtime-needle-engine.js.map +7 -0
- package/build/impostor-runtime.js +1333 -0
- package/build/impostor-runtime.js.map +7 -0
- package/build/internal/deformation/cloth-surface.js +288 -0
- package/build/internal/deformation/cloth-surface.js.map +7 -0
- package/build/internal/deformation/fur-surface.js +130 -0
- package/build/internal/deformation/fur-surface.js.map +7 -0
- package/build/internal/deformation/ik-constraints.js +44 -0
- package/build/internal/deformation/ik-constraints.js.map +7 -0
- package/build/internal/deformation/joints-json.js +197 -0
- package/build/internal/deformation/joints-json.js.map +7 -0
- package/build/internal/deformation/limits.js +16 -0
- package/build/internal/deformation/limits.js.map +7 -0
- package/build/internal/deformation/motion-settings.js +12 -0
- package/build/internal/deformation/motion-settings.js.map +7 -0
- package/build/internal/deformation/pin-cloth.js +196 -0
- package/build/internal/deformation/pin-cloth.js.map +7 -0
- package/build/internal/deformation/pin-ik.js +650 -0
- package/build/internal/deformation/pin-ik.js.map +7 -0
- package/build/internal/deformation/pin-types.js +12 -0
- package/build/internal/deformation/pin-types.js.map +7 -0
- package/build/internal/deformation/pin-wiggle.js +249 -0
- package/build/internal/deformation/pin-wiggle.js.map +7 -0
- package/build/internal/deformation/pose-slots.js +84 -0
- package/build/internal/deformation/pose-slots.js.map +7 -0
- package/build/internal/deformation/pose-timeline.js +210 -0
- package/build/internal/deformation/pose-timeline.js.map +7 -0
- package/build/internal/deformation/rig-drivers.js +48 -0
- package/build/internal/deformation/rig-drivers.js.map +7 -0
- package/build/internal/deformation/rig-extension.js +334 -0
- package/build/internal/deformation/rig-extension.js.map +7 -0
- package/build/internal/deformation/rig-runtime.js +2141 -0
- package/build/internal/deformation/rig-runtime.js.map +7 -0
- package/build/internal/deformation/wind.js +34 -0
- package/build/internal/deformation/wind.js.map +7 -0
- package/build/internal/impostor/impostor-metadata.js +77 -0
- package/build/internal/impostor/impostor-metadata.js.map +7 -0
- package/build/internal/impostor/impostor-node-material.js +1331 -0
- package/build/internal/impostor/impostor-node-material.js.map +7 -0
- package/build/internal/impostor/impostor-runtime-support.js +162 -0
- package/build/internal/impostor/impostor-runtime-support.js.map +7 -0
- package/build/internal/impostor/octahedral.js +232 -0
- package/build/internal/impostor/octahedral.js.map +7 -0
- package/build/internal/pixel-impostor/pixel-impostor-display.js +728 -0
- package/build/internal/pixel-impostor/pixel-impostor-display.js.map +7 -0
- package/build/internal/pixel-impostor/pixel-impostor-metadata.js +71 -0
- package/build/internal/pixel-impostor/pixel-impostor-metadata.js.map +7 -0
- package/build/internal/pixel-impostor/pixel-impostor-runtime.js +150 -0
- package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +7 -0
- package/build/internal/rendering/skin-projection.js +4630 -0
- package/build/internal/rendering/skin-projection.js.map +7 -0
- package/build/internal/rendering/surface-query.js +4519 -0
- package/build/internal/rendering/surface-query.js.map +7 -0
- package/build/internal/rendering/wireframe.js +112 -0
- package/build/internal/rendering/wireframe.js.map +7 -0
- package/build/internal/rendering/wrap-preview-settings.js +126 -0
- package/build/internal/rendering/wrap-preview-settings.js.map +7 -0
- package/build/internal/rendering/wrap-preview.js +5610 -0
- package/build/internal/rendering/wrap-preview.js.map +7 -0
- package/build/internal/rendering/wrap-skin.js +4746 -0
- package/build/internal/rendering/wrap-skin.js.map +7 -0
- package/build/pixel-impostor-runtime.js +876 -0
- package/build/pixel-impostor-runtime.js.map +7 -0
- package/build/types/deformation/cloth-surface.d.ts +39 -0
- package/build/types/deformation/cloth-surface.js +1 -0
- package/build/types/deformation/fur-surface.d.ts +27 -0
- package/build/types/deformation/fur-surface.js +1 -0
- package/build/types/deformation/ik-constraints.d.ts +18 -0
- package/build/types/deformation/ik-constraints.js +1 -0
- package/build/types/deformation/joints-json.d.ts +17 -0
- package/build/types/deformation/joints-json.js +1 -0
- package/build/types/deformation/limits.d.ts +23 -0
- package/build/types/deformation/limits.js +1 -0
- package/build/types/deformation/motion-settings.d.ts +9 -0
- package/build/types/deformation/motion-settings.js +1 -0
- package/build/types/deformation/pin-cloth.d.ts +28 -0
- package/build/types/deformation/pin-cloth.js +1 -0
- package/build/types/deformation/pin-ik.d.ts +37 -0
- package/build/types/deformation/pin-ik.js +1 -0
- package/build/types/deformation/pin-types.d.ts +53 -0
- package/build/types/deformation/pin-types.js +1 -0
- package/build/types/deformation/pin-wiggle.d.ts +16 -0
- package/build/types/deformation/pin-wiggle.js +1 -0
- package/build/types/deformation/pose-slots.d.ts +41 -0
- package/build/types/deformation/pose-slots.js +1 -0
- package/build/types/deformation/pose-timeline.d.ts +65 -0
- package/build/types/deformation/pose-timeline.js +1 -0
- package/build/types/deformation/rig-drivers.d.ts +19 -0
- package/build/types/deformation/rig-drivers.js +1 -0
- package/build/types/deformation/rig-extension.d.ts +33 -0
- package/build/types/deformation/rig-extension.js +1 -0
- package/build/types/deformation/rig-runtime.d.ts +95 -0
- package/build/types/deformation/rig-runtime.js +1 -0
- package/build/types/deformation/wind.d.ts +16 -0
- package/build/types/deformation/wind.js +1 -0
- package/build/types/impostor/impostor-metadata.d.ts +61 -0
- package/build/types/impostor/impostor-metadata.js +1 -0
- package/build/types/impostor/impostor-node-material.d.ts +140 -0
- package/build/types/impostor/impostor-node-material.js +1 -0
- package/build/types/impostor/impostor-runtime-support.d.ts +52 -0
- package/build/types/impostor/impostor-runtime-support.js +1 -0
- package/build/types/impostor/octahedral.d.ts +84 -0
- package/build/types/impostor/octahedral.js +1 -0
- package/build/types/pixel-impostor/pixel-impostor-display.d.ts +48 -0
- package/build/types/pixel-impostor/pixel-impostor-display.js +1 -0
- package/build/types/pixel-impostor/pixel-impostor-metadata.d.ts +34 -0
- package/build/types/pixel-impostor/pixel-impostor-metadata.js +1 -0
- package/build/types/pixel-impostor/pixel-impostor-runtime.d.ts +18 -0
- package/build/types/pixel-impostor/pixel-impostor-runtime.js +1 -0
- package/build/types/public/deformation-runtime.d.ts +3 -0
- package/build/types/public/deformation-runtime.js +1 -0
- package/build/types/public/impostor-runtime-needle-engine.d.ts +31 -0
- package/build/types/public/impostor-runtime-needle-engine.js +1 -0
- package/build/types/public/impostor-runtime.d.ts +6 -0
- package/build/types/public/impostor-runtime.js +1 -0
- package/build/types/public/pixel-impostor-runtime.d.ts +3 -0
- package/build/types/public/pixel-impostor-runtime.js +1 -0
- package/build/types/public/wrap-effects.d.ts +4 -0
- package/build/types/public/wrap-effects.js +1 -0
- package/build/types/rendering/skin-projection.d.ts +44 -0
- package/build/types/rendering/skin-projection.js +1 -0
- package/build/types/rendering/surface-query.d.ts +66 -0
- package/build/types/rendering/surface-query.js +1 -0
- package/build/types/rendering/wireframe.d.ts +25 -0
- package/build/types/rendering/wireframe.js +1 -0
- package/build/types/rendering/wrap-preview-settings.d.ts +22 -0
- package/build/types/rendering/wrap-preview-settings.js +1 -0
- package/build/types/rendering/wrap-preview.d.ts +39 -0
- package/build/types/rendering/wrap-preview.js +1 -0
- package/build/types/rendering/wrap-skin.d.ts +14 -0
- package/build/types/rendering/wrap-skin.js +1 -0
- package/build/wrap-effects.js +5640 -0
- package/build/wrap-effects.js.map +7 -0
- package/package.json +105 -4
- package/src/deformation/cloth-surface.ts +223 -0
- package/src/deformation/fur-surface.ts +129 -0
- package/src/deformation/ik-constraints.ts +37 -0
- package/src/deformation/joints-json.ts +94 -0
- package/src/deformation/limits.ts +25 -0
- package/src/deformation/motion-settings.ts +9 -0
- package/src/deformation/pin-cloth.ts +149 -0
- package/src/deformation/pin-ik.ts +582 -0
- package/src/deformation/pin-types.ts +22 -0
- package/src/deformation/pin-wiggle.ts +119 -0
- package/src/deformation/pose-slots.ts +106 -0
- package/src/deformation/pose-timeline.ts +242 -0
- package/src/deformation/rig-drivers.ts +32 -0
- package/src/deformation/rig-extension.ts +87 -0
- package/src/deformation/rig-runtime.ts +416 -0
- package/src/deformation/wind.ts +36 -0
- package/src/impostor/impostor-metadata.js +137 -0
- package/src/impostor/impostor-node-material.js +1581 -0
- package/src/impostor/impostor-runtime-support.js +139 -0
- package/src/impostor/octahedral.js +280 -0
- package/src/pixel-impostor/pixel-impostor-display.js +794 -0
- package/src/pixel-impostor/pixel-impostor-metadata.js +74 -0
- package/src/pixel-impostor/pixel-impostor-runtime.js +78 -0
- package/src/public/deformation-runtime.ts +3 -0
- package/src/public/impostor-runtime-needle-engine.js +56 -0
- package/src/public/impostor-runtime.js +21 -0
- package/src/public/pixel-impostor-runtime.js +5 -0
- package/src/public/wrap-effects.js +21 -0
- package/src/rendering/skin-projection.js +113 -0
- package/src/rendering/surface-query.js +88 -0
- package/src/rendering/wireframe.js +115 -0
- package/src/rendering/wrap-preview-settings.js +123 -0
- package/src/rendering/wrap-preview.js +645 -0
- package/src/rendering/wrap-skin.js +109 -0
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
import { AnimationMixer, PropertyBinding, Matrix4, Object3D, Quaternion, SkinnedMesh, Vector3, type AnimationClip, type BufferGeometry, type Texture } from 'three';
|
|
2
|
+
import type { GLTF, GLTFLoader, GLTFParser } from 'three/addons/loaders/GLTFLoader.js';
|
|
3
|
+
import type { PinRecord, PinPose } from './pin-types.js';
|
|
4
|
+
import { NEEDLE_DEFORMATION_RIG, parseRigDescriptor, type RigDescriptor } from './rig-extension.js';
|
|
5
|
+
import { definedPoses, restPoseSlot, resolvePose } from './pose-slots.js';
|
|
6
|
+
import { solvePlantedPinIKGoals, solveLocalPinIK, ikChain } from './pin-ik.js';
|
|
7
|
+
import { PinWiggle } from './pin-wiggle.js';
|
|
8
|
+
import { PinCloth, type ClothCollider } from './pin-cloth.js';
|
|
9
|
+
import { ClothSurface, clothSurfaceMotion } from './cloth-surface.js';
|
|
10
|
+
import { driveRig, referencePose, type BoneDriver } from './rig-drivers.js';
|
|
11
|
+
import { FurSurface } from './fur-surface.js';
|
|
12
|
+
|
|
13
|
+
const runtimes = new WeakMap<Object3D, DeformationRigRuntime>();
|
|
14
|
+
const matrix = (pose: PinPose) => new Matrix4().compose(new Vector3().fromArray(pose.position), new Quaternion().fromArray(pose.rotation), new Vector3().fromArray(pose.scale));
|
|
15
|
+
function pose(matrix: Matrix4): PinPose {
|
|
16
|
+
const p = new Vector3(), q = new Quaternion(), s = new Vector3(); matrix.decompose(p, q, s);
|
|
17
|
+
return { position: p.toArray(), rotation: q.normalize().toArray(), scale: s.toArray() };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
type RuntimeClothMesh = { mesh: SkinnedMesh; original: BufferGeometry; positions: Float32Array; surface: ClothSurface; clothIds: string[]; elapsed: number };
|
|
21
|
+
|
|
22
|
+
/** Lightweight articulated runtime. Skinning stays on the renderer's GPU;
|
|
23
|
+
* only the small joint graph is solved on the CPU, with no voxel dependency. */
|
|
24
|
+
export class DeformationRigRuntime {
|
|
25
|
+
/** Stable pin IDs mapped to the glTF bone nodes. Edit a bone for FK. */
|
|
26
|
+
readonly bones = new Map<string, Object3D>();
|
|
27
|
+
/** Scene-local goal objects for IK and secondary controls. Move one before `update()`. */
|
|
28
|
+
readonly targets = new Map<string, Object3D>();
|
|
29
|
+
readonly parents = new Map<string, string>();
|
|
30
|
+
readonly masses = new Map<string, number>();
|
|
31
|
+
readonly helpers: { bone: Object3D; influences: { id: string; weight: number }[] }[] = [];
|
|
32
|
+
private helperReferences = new Map<Object3D, PinPose>();
|
|
33
|
+
private referencePins: readonly PinRecord[] = [];
|
|
34
|
+
private localFrames = new Map<Object3D, number[]>();
|
|
35
|
+
private fittedDrivers:BoneDriver[]=[];
|
|
36
|
+
get drivers(): readonly BoneDriver[] { return this.fittedDrivers; }
|
|
37
|
+
private articulated(pins:readonly PinRecord[]) { const helpers=new Set(this.drivers.map(d=>d.id));return pins.filter(p=>!helpers.has(p.id)); }
|
|
38
|
+
private springs = new PinWiggle();
|
|
39
|
+
private cloth = new PinCloth();
|
|
40
|
+
private clothMeshes: RuntimeClothMesh[] = [];
|
|
41
|
+
readonly furSurface: FurSurface | null;
|
|
42
|
+
private mixer: AnimationMixer;
|
|
43
|
+
private base: readonly PinRecord[];
|
|
44
|
+
private displayed: readonly PinRecord[];
|
|
45
|
+
private disposed = false;
|
|
46
|
+
private dirty = true;
|
|
47
|
+
private targetFrames = new Map<string, string>();
|
|
48
|
+
private editedTargets = new Set<string>();
|
|
49
|
+
private mixedPoseWeights = new Map<number, number>();
|
|
50
|
+
private mixingStaticPoses = false;
|
|
51
|
+
private animationFrames = new Map<Object3D, {position:Vector3;rotation:Quaternion;scale:Vector3;displayedPosition:Vector3;displayedRotation:Quaternion;displayedScale:Vector3}>();
|
|
52
|
+
windStrength:number;
|
|
53
|
+
activePose: number;
|
|
54
|
+
constructor(readonly scene: Object3D, readonly descriptor: RigDescriptor, nodes: readonly Object3D[], readonly clips: readonly AnimationClip[], helperNodes: readonly Object3D[] = []) {
|
|
55
|
+
this.base = descriptor.pins; this.displayed = this.base; this.activePose = descriptor.activePose;this.windStrength=descriptor.windStrength??0;
|
|
56
|
+
descriptor.joints.forEach((joint, i) => {
|
|
57
|
+
const pin = descriptor.pins[i]; this.bones.set(pin.id, nodes[i]); this.masses.set(pin.id, joint.mass);
|
|
58
|
+
if (joint.parent !== null) this.parents.set(pin.id, descriptor.pins[descriptor.joints.findIndex(j => j.node === joint.parent)].id);
|
|
59
|
+
if (pin.ik || pin.wiggle || pin.cloth || pin.fur) { const target = new Object3D(); target.name = `${pin.id} target`; target.visible = false; scene.add(target); this.targets.set(pin.id, target); }
|
|
60
|
+
});
|
|
61
|
+
descriptor.helpers?.forEach((h, i) => this.helpers.push({ bone: helperNodes[i], influences: h.influences.map(w => ({ id: descriptor.pins[descriptor.joints.findIndex(j => j.node === w.node)].id, weight: w.weight })) }));
|
|
62
|
+
if(descriptor.version>=3)this.fittedDrivers=this.helpers.map(h=>({id:[...this.bones].find(([,bone])=>bone===h.bone)![0],influences:h.influences}));
|
|
63
|
+
this.furSurface = descriptor.pins.some(pin => pin.fur) ? new FurSurface(scene, descriptor, nodes, helperNodes) : null;
|
|
64
|
+
this.mixer = new AnimationMixer(scene);
|
|
65
|
+
const bones = [...this.bones.values()];
|
|
66
|
+
const animated = clips.some(clip => clip.tracks.some(track => {
|
|
67
|
+
const node = PropertyBinding.findNode(scene, PropertyBinding.parseTrackName(track.name).nodeName);
|
|
68
|
+
return bones.some(bone => bone === node);
|
|
69
|
+
}));
|
|
70
|
+
if (animated) for (const bone of bones) this.animationFrames.set(bone, this.localFrame(bone));
|
|
71
|
+
this.selectPose(this.activePose);
|
|
72
|
+
if (descriptor.pins.some(pin => pin.cloth)) this.prepareClothMeshes();
|
|
73
|
+
}
|
|
74
|
+
/** Supply a Fur height atlas. The loader calls this for embedded atlases. */
|
|
75
|
+
setFurHeightMap(texture: Texture | null) { this.furSurface?.setHeightMap(texture); }
|
|
76
|
+
/** Keep ordinary glTF materials on renderers without the Fur node shader. */
|
|
77
|
+
setPortableMaterials(portable: boolean) { this.furSurface?.setPortable(portable); }
|
|
78
|
+
/** Joint records in the last displayed frame, including secondary motion. */
|
|
79
|
+
get pins() { return this.displayed; }
|
|
80
|
+
/** Return stable pin IDs from the root of the selected chain to its endpoint. */
|
|
81
|
+
chain(id: string) { return ikChain(this.articulated(this.base), this.parents, id, this.masses).map(p => p.id); }
|
|
82
|
+
/** Clear accumulated spring and Cloth motion after a pose or editor reset. */
|
|
83
|
+
resetSecondary() { this.springs.reset(); this.cloth.reset(); for (const entry of this.clothMeshes) { entry.surface.reset(); entry.elapsed = 0; } }
|
|
84
|
+
|
|
85
|
+
private prepareClothMeshes() {
|
|
86
|
+
this.scene.updateWorldMatrix(true, true);
|
|
87
|
+
const inverse = this.scene.matrixWorld.clone().invert();
|
|
88
|
+
const candidates: { mesh: SkinnedMesh; original: BufferGeometry; positions: Float32Array; rest: Float32Array; indices: ArrayLike<number> }[] = [];
|
|
89
|
+
this.scene.traverse(object => {
|
|
90
|
+
if (!(object instanceof SkinnedMesh)) return;
|
|
91
|
+
const mesh = object, position = mesh.geometry.getAttribute('position');
|
|
92
|
+
if (!position) return;
|
|
93
|
+
const original = mesh.geometry, positions = new Float32Array(position.count * 3), rest = new Float32Array(position.count * 3);
|
|
94
|
+
for (let i = 0; i < position.count; i++) {
|
|
95
|
+
const point = new Vector3().fromBufferAttribute(position, i);
|
|
96
|
+
positions.set(point.toArray(), i * 3);
|
|
97
|
+
rest.set(mesh.applyBoneTransform(i, point).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse).toArray(), i * 3);
|
|
98
|
+
}
|
|
99
|
+
candidates.push({ mesh, original, positions, rest,
|
|
100
|
+
indices: original.index?.array ?? Uint32Array.from({ length: position.count }, (_, i) => i) });
|
|
101
|
+
});
|
|
102
|
+
const assigned = new Map<SkinnedMesh, PinRecord[]>();
|
|
103
|
+
for (const pin of this.descriptor.pins.filter(record => record.cloth && !record.guide)) {
|
|
104
|
+
const point = new Vector3().fromArray(pin.pose.position);
|
|
105
|
+
let best = Infinity, owner: SkinnedMesh | null = null;
|
|
106
|
+
for (const candidate of candidates) for (let i = 0; i < candidate.rest.length; i += 3) {
|
|
107
|
+
const dx = candidate.rest[i] - point.x, dy = candidate.rest[i + 1] - point.y, dz = candidate.rest[i + 2] - point.z;
|
|
108
|
+
const distance = dx * dx + dy * dy + dz * dz;
|
|
109
|
+
if (distance < best) { best = distance; owner = candidate.mesh; }
|
|
110
|
+
}
|
|
111
|
+
if (owner) assigned.set(owner, [...assigned.get(owner) ?? [], pin]);
|
|
112
|
+
}
|
|
113
|
+
for (const candidate of candidates) {
|
|
114
|
+
const cloth = assigned.get(candidate.mesh); if (!cloth?.length) continue;
|
|
115
|
+
const fitted = new Set(this.drivers.map(driver => driver.id));
|
|
116
|
+
const pins = [...this.descriptor.pins.filter(pin => !pin.cloth && !pin.guide && !fitted.has(pin.id)), ...cloth]
|
|
117
|
+
.map(pin => ({ ...pin, rest: pin.pose.position }));
|
|
118
|
+
candidate.mesh.geometry = candidate.original.clone();
|
|
119
|
+
this.clothMeshes.push({ mesh: candidate.mesh, original: candidate.original, positions: candidate.positions,
|
|
120
|
+
surface: new ClothSurface(candidate.rest, candidate.indices, pins), clothIds: cloth.map(pin => pin.id), elapsed: 0 });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private updateClothMeshes(seconds: number, colliders: readonly ClothCollider[]) {
|
|
125
|
+
if (!this.clothMeshes.length) return;
|
|
126
|
+
this.scene.updateWorldMatrix(true, true);
|
|
127
|
+
const sceneInverse = this.scene.matrixWorld.clone().invert();
|
|
128
|
+
for (const entry of this.clothMeshes) {
|
|
129
|
+
// Bones still render every frame; the coarse fabric solve runs at 30 Hz.
|
|
130
|
+
entry.elapsed += Math.max(0, seconds);
|
|
131
|
+
if (entry.elapsed < 1 / 30) continue;
|
|
132
|
+
const step = Math.min(entry.elapsed, .05); entry.elapsed = 0;
|
|
133
|
+
const { mesh, positions, surface } = entry, target = mesh.geometry.getAttribute('position');
|
|
134
|
+
mesh.skeleton.update();
|
|
135
|
+
const base = new Float32Array(positions.length);
|
|
136
|
+
for (let i = 0; i < positions.length / 3; i++) {
|
|
137
|
+
const point = new Vector3().fromArray(positions, i * 3);
|
|
138
|
+
base.set(mesh.applyBoneTransform(i, point).applyMatrix4(mesh.matrixWorld).applyMatrix4(sceneInverse).toArray(), i * 3);
|
|
139
|
+
}
|
|
140
|
+
const moved = surface.step(base, step, this.windStrength, colliders,
|
|
141
|
+
clothSurfaceMotion(this.base.filter(pin => entry.clothIds.includes(pin.id))));
|
|
142
|
+
const skinIndex = mesh.geometry.getAttribute('skinIndex'), skinWeight = mesh.geometry.getAttribute('skinWeight');
|
|
143
|
+
const meshInverse = mesh.matrixWorld.clone().invert().multiply(this.scene.matrixWorld);
|
|
144
|
+
const bone = new Matrix4(), blended = new Matrix4(), skin = new Matrix4();
|
|
145
|
+
for (let i = 0; i < positions.length / 3; i++) {
|
|
146
|
+
const elements = blended.elements; elements.fill(0);
|
|
147
|
+
for (let j = 0; j < 4; j++) {
|
|
148
|
+
const weight = skinWeight.getComponent(i, j); if (!weight) continue;
|
|
149
|
+
bone.fromArray(mesh.skeleton.boneMatrices!, skinIndex.getComponent(i, j) * 16);
|
|
150
|
+
for (let k = 0; k < 16; k++) elements[k] += bone.elements[k] * weight;
|
|
151
|
+
}
|
|
152
|
+
skin.copy(mesh.bindMatrixInverse).multiply(blended).multiply(mesh.bindMatrix).invert();
|
|
153
|
+
const local = new Vector3().fromArray(moved, i * 3).applyMatrix4(meshInverse).applyMatrix4(skin);
|
|
154
|
+
target.setXYZ(i, local.x, local.y, local.z);
|
|
155
|
+
}
|
|
156
|
+
target.needsUpdate = true; mesh.geometry.computeVertexNormals();
|
|
157
|
+
mesh.geometry.computeBoundingSphere(); mesh.frustumCulled = false;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/** Select an exported `Pose N` clip and reset its IK goals and secondary motion. */
|
|
161
|
+
selectPose(slot: number) {
|
|
162
|
+
const stored = slot === 0 ? this.descriptor.poseSlots.find(p=>p.slot===0) ?? (this.descriptor.activePose===0 ? restPoseSlot(this.descriptor.pins) : undefined) : definedPoses(this.descriptor).find(p => p.slot === slot);
|
|
163
|
+
if (!stored) throw new Error(`Pose ${slot} is not included in this GLB.`);
|
|
164
|
+
this.mixer.stopAllAction();
|
|
165
|
+
this.mixingStaticPoses = false;
|
|
166
|
+
const clip = this.clips.find(c => c.name === `Pose ${slot}`);
|
|
167
|
+
if (clip) { this.mixer.clipAction(clip).play(); this.mixer.update(0); }
|
|
168
|
+
this.mixedPoseWeights = new Map([[slot, 1]]);
|
|
169
|
+
this.scene.updateWorldMatrix(true, true);
|
|
170
|
+
const inverse = this.scene.matrixWorld.clone().invert();
|
|
171
|
+
this.referencePins = resolvePose(this.descriptor.pins, stored, this.parents);
|
|
172
|
+
this.helperReferences = new Map(this.helpers.map(h => [h.bone, pose(inverse.clone().multiply(h.bone.matrixWorld))]));
|
|
173
|
+
this.activePose = slot; this.resetSecondary(); this.setPins(resolvePose(this.descriptor.pins, stored, this.parents));
|
|
174
|
+
}
|
|
175
|
+
get poseWeights(): ReadonlyMap<number, number> { return this.mixedPoseWeights; }
|
|
176
|
+
/** Change the editable reference pose without interrupting secondary motion. */
|
|
177
|
+
preparePose(slot: number) {
|
|
178
|
+
const stored = slot === 0 ? this.descriptor.poseSlots.find(p=>p.slot===0) ?? (this.descriptor.activePose===0 ? restPoseSlot(this.descriptor.pins) : undefined) : definedPoses(this.descriptor).find(p => p.slot === slot);
|
|
179
|
+
if (!stored) throw new Error(`Pose ${slot} is not included in this GLB.`);
|
|
180
|
+
this.referencePins = resolvePose(this.descriptor.pins, stored, this.parents);
|
|
181
|
+
this.activePose = slot;
|
|
182
|
+
}
|
|
183
|
+
/** Mix the GLB's standard static pose clips, then simulate on that fitted frame. */
|
|
184
|
+
previewPoseWeights(weights: ReadonlyMap<number, number>, seconds: number) {
|
|
185
|
+
if (this.disposed) return;
|
|
186
|
+
this.mixedPoseWeights = new Map(weights);
|
|
187
|
+
const starting = !this.mixingStaticPoses;
|
|
188
|
+
if (starting) {
|
|
189
|
+
this.mixer.stopAllAction();
|
|
190
|
+
for (const clip of this.clips) if (/^Pose \d+$/.test(clip.name)) this.mixer.clipAction(clip).play();
|
|
191
|
+
this.mixingStaticPoses = true;
|
|
192
|
+
}
|
|
193
|
+
// Secondary motion changed the same bones after the previous mixer tick.
|
|
194
|
+
// PropertyMixer skips an unchanged clip value, so put its last clip-only
|
|
195
|
+
// frame back before evaluating the next one.
|
|
196
|
+
if (!starting) this.apply(this.base, true);
|
|
197
|
+
for (const clip of this.clips) {
|
|
198
|
+
const match = /^Pose (\d+)$/.exec(clip.name);
|
|
199
|
+
if (match) this.mixer.clipAction(clip).setEffectiveWeight(weights.get(Number(match[1])) ?? 0);
|
|
200
|
+
}
|
|
201
|
+
this.mixer.update(0);
|
|
202
|
+
this.scene.updateWorldMatrix(true, true);
|
|
203
|
+
const inverse = this.scene.matrixWorld.clone().invert();
|
|
204
|
+
const fitted = this.base.map(pin => ({ ...pin, pose: pose(inverse.clone().multiply(this.bones.get(pin.id)!.matrixWorld)) }));
|
|
205
|
+
this.base = fitted; this.dirty = false;
|
|
206
|
+
this.rememberAnimationFrame(); this.advanceSecondary(seconds, fitted); this.rememberDisplayedAnimationFrame();
|
|
207
|
+
}
|
|
208
|
+
/** Adapter for editors: authored state stays in the caller's action history. */
|
|
209
|
+
setPins(pins: readonly PinRecord[]) {
|
|
210
|
+
if (pins.length !== this.bones.size || pins.some(p => !this.bones.has(p.id))) throw new Error('Rig layout changed; rebuild the GLB.');
|
|
211
|
+
if (this.mixingStaticPoses) { this.mixer.stopAllAction(); this.mixingStaticPoses = false; }
|
|
212
|
+
// These poses already passed the author's solve. In particular, an
|
|
213
|
+
// unreachable IK goal must not perturb that solve again on load/replay.
|
|
214
|
+
this.base = pins; this.dirty = false; this.editedTargets.clear(); this.mixedPoseWeights = new Map([[this.activePose, 1]]);
|
|
215
|
+
for (const [id, target] of this.targets) if (!pins.some(p => p.id === id && (p.ik || p.wiggle || p.cloth || p.fur) && !p.guide)) { target.removeFromParent(); this.targets.delete(id); this.targetFrames.delete(id); }
|
|
216
|
+
for (const pin of pins) {
|
|
217
|
+
if (pin.guide || (!pin.ik && !pin.wiggle && !pin.cloth && !pin.fur)) continue;
|
|
218
|
+
let target = this.targets.get(pin.id);
|
|
219
|
+
if (!target) { target = new Object3D(); target.name = `${pin.id} target`; target.visible = false; this.scene.add(target); this.targets.set(pin.id, target); }
|
|
220
|
+
target.position.fromArray(pin.ikTarget?.position ?? pin.pose.position); target.quaternion.fromArray(pin.ikTarget?.rotation ?? pin.pose.rotation);
|
|
221
|
+
this.targetFrames.set(pin.id, JSON.stringify([target.position.toArray(), target.quaternion.toArray()]));
|
|
222
|
+
}
|
|
223
|
+
this.apply(pins); this.rememberAnimationFrame();
|
|
224
|
+
}
|
|
225
|
+
/** Display a caller-supplied fitted frame. Workbench playback uses the clips. */
|
|
226
|
+
previewPins(pins: readonly PinRecord[]) {
|
|
227
|
+
if (pins.length !== this.bones.size || pins.some(p => !this.bones.has(p.id))) throw new Error('Rig layout changed; rebuild the GLB.');
|
|
228
|
+
if (this.mixingStaticPoses) { this.mixer.stopAllAction(); this.mixingStaticPoses = false; }
|
|
229
|
+
this.base = pins; this.dirty = false;
|
|
230
|
+
this.apply(pins, true); this.rememberAnimationFrame();
|
|
231
|
+
}
|
|
232
|
+
private localFrame(bone: Object3D) {
|
|
233
|
+
return {position:bone.position.clone(),rotation:bone.quaternion.clone(),scale:bone.scale.clone(),
|
|
234
|
+
displayedPosition:bone.position.clone(),displayedRotation:bone.quaternion.clone(),displayedScale:bone.scale.clone()};
|
|
235
|
+
}
|
|
236
|
+
private rememberAnimationFrame() {
|
|
237
|
+
for (const bone of this.animationFrames.keys()) this.animationFrames.set(bone,this.localFrame(bone));
|
|
238
|
+
}
|
|
239
|
+
/** PropertyMixer skips unchanged values. Recover their clip-only components
|
|
240
|
+
* rather than feeding last frame's secondary motion back into animation. */
|
|
241
|
+
private animationFrame() {
|
|
242
|
+
if (!this.animationFrames.size) return null;
|
|
243
|
+
for (const [bone,frame] of this.animationFrames) {
|
|
244
|
+
if (!bone.position.equals(frame.displayedPosition)) frame.position.copy(bone.position);
|
|
245
|
+
if (!bone.quaternion.equals(frame.displayedRotation)) frame.rotation.copy(bone.quaternion);
|
|
246
|
+
if (!bone.scale.equals(frame.displayedScale)) frame.scale.copy(bone.scale);
|
|
247
|
+
bone.position.copy(frame.position);bone.quaternion.copy(frame.rotation);bone.scale.copy(frame.scale);
|
|
248
|
+
}
|
|
249
|
+
this.scene.updateWorldMatrix(true,true);
|
|
250
|
+
const inverse=this.scene.matrixWorld.clone().invert();
|
|
251
|
+
return this.base.map(pin=>({...pin,pose:pose(inverse.clone().multiply(this.bones.get(pin.id)!.matrixWorld))}));
|
|
252
|
+
}
|
|
253
|
+
private rememberDisplayedAnimationFrame() {
|
|
254
|
+
for (const [bone,frame] of this.animationFrames) {
|
|
255
|
+
frame.displayedPosition.copy(bone.position);frame.displayedRotation.copy(bone.quaternion);frame.displayedScale.copy(bone.scale);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
private apply(pins: readonly PinRecord[], fitted = false) {
|
|
259
|
+
if(this.descriptor.version>=3 && !fitted)pins=driveRig(pins,this.referencePins,this.drivers);
|
|
260
|
+
this.scene.updateWorldMatrix(true, true);
|
|
261
|
+
const desired = new Map(pins.map(p => [this.bones.get(p.id)!, this.scene.matrixWorld.clone().multiply(matrix(p.pose))]));
|
|
262
|
+
// Use desired parent frames, not last frame's bone state (arbitrary order).
|
|
263
|
+
const pending = new Set(desired.keys());
|
|
264
|
+
const apply = (bone: Object3D) => {
|
|
265
|
+
if (!pending.has(bone)) return;
|
|
266
|
+
if (bone.parent && pending.has(bone.parent)) apply(bone.parent);
|
|
267
|
+
bone.parent?.updateWorldMatrix(true, false);
|
|
268
|
+
const local = (bone.parent?.matrixWorld.clone() ?? new Matrix4()).invert().multiply(desired.get(bone)!);
|
|
269
|
+
local.decompose(bone.position, bone.quaternion, bone.scale); bone.updateMatrix(); bone.updateWorldMatrix(false, true); pending.delete(bone);
|
|
270
|
+
};
|
|
271
|
+
for (const bone of desired.keys()) apply(bone);
|
|
272
|
+
// Corrective bones are NOT rigid children of their strongest control.
|
|
273
|
+
// Blend each control's delta using the original harmonic volume binding.
|
|
274
|
+
// Applying a delta to a fitted reference frame preserves the sampled pose
|
|
275
|
+
// exactly, while avoiding hard parent boundaries during new motion.
|
|
276
|
+
const deltas = new Map(this.referencePins.map(reference => {
|
|
277
|
+
const current = pins.find(p => p.id === reference.id)!.pose;
|
|
278
|
+
return [reference.id, { matrix: matrix(current).multiply(matrix(reference.pose).invert()), rotation: new Quaternion().fromArray(current.rotation).multiply(new Quaternion().fromArray(reference.pose.rotation).invert()), scale: new Vector3().fromArray(current.scale).divide(new Vector3().fromArray(reference.pose.scale)) }];
|
|
279
|
+
}));
|
|
280
|
+
for (const helper of this.descriptor.version>=3?[]:this.helpers) {
|
|
281
|
+
const reference = this.helperReferences.get(helper.bone)!;
|
|
282
|
+
const p = new Vector3(), q = new Quaternion(0, 0, 0, 0), s = new Vector3(), ref = new Vector3().fromArray(reference.position);
|
|
283
|
+
const hemisphere = helper.influences.length ? deltas.get(helper.influences[0].id)!.rotation : new Quaternion();
|
|
284
|
+
for (const influence of helper.influences) {
|
|
285
|
+
const delta = deltas.get(influence.id)!, w = influence.weight;
|
|
286
|
+
p.addScaledVector(ref.clone().applyMatrix4(delta.matrix), w); s.addScaledVector(delta.scale, w);
|
|
287
|
+
const sign = hemisphere.dot(delta.rotation) < 0 ? -w : w;
|
|
288
|
+
q.set(q.x + delta.rotation.x*sign, q.y + delta.rotation.y*sign, q.z + delta.rotation.z*sign, q.w + delta.rotation.w*sign);
|
|
289
|
+
}
|
|
290
|
+
if (!helper.influences.length) { p.copy(ref); q.identity(); s.setScalar(1); }
|
|
291
|
+
q.normalize().multiply(new Quaternion().fromArray(reference.rotation)); s.multiply(new Vector3().fromArray(reference.scale));
|
|
292
|
+
const world = this.scene.matrixWorld.clone().multiply(new Matrix4().compose(p, q, s));
|
|
293
|
+
helper.bone.parent?.updateWorldMatrix(true, false);
|
|
294
|
+
const local = (helper.bone.parent?.matrixWorld.clone() ?? new Matrix4()).invert().multiply(world);
|
|
295
|
+
local.decompose(helper.bone.position, helper.bone.quaternion, helper.bone.scale); helper.bone.updateWorldMatrix(false, true);
|
|
296
|
+
}
|
|
297
|
+
this.displayed = pins;
|
|
298
|
+
for(const bone of this.bones.values()){bone.updateMatrix();this.localFrames.set(bone,[...bone.matrix.elements]);}
|
|
299
|
+
}
|
|
300
|
+
/** Call after an external AnimationMixer/TransformControls, before rendering.
|
|
301
|
+
* Targets are scene-local Object3Ds; moving an independent bone never moves them. */
|
|
302
|
+
update(seconds: number) {
|
|
303
|
+
if (this.disposed) return;
|
|
304
|
+
const fitted=this.animationFrame();
|
|
305
|
+
if(fitted){this.base=fitted;this.displayed=fitted;this.dirty=false;}
|
|
306
|
+
else this.furSurface?.update(seconds, this.windStrength);
|
|
307
|
+
this.scene.updateWorldMatrix(true, true);
|
|
308
|
+
const inverse = this.scene.matrixWorld.clone().invert();
|
|
309
|
+
// Accept external bone edits, but never feed our spring output back as input.
|
|
310
|
+
const edited = fitted ? this.base : this.base.map((pin, i) => {
|
|
311
|
+
const driver=this.drivers.find(d=>d.id===pin.id);
|
|
312
|
+
if(driver){
|
|
313
|
+
const bone=this.bones.get(pin.id)!;bone.updateMatrix();
|
|
314
|
+
if(!bone.matrix.elements.some((v,k)=>Math.abs(v-(this.localFrames.get(bone)?.[k]??v))>1e-6))return pin;
|
|
315
|
+
return {...pin,pose:referencePose(pose(inverse.clone().multiply(bone.matrixWorld)),driver,this.base,this.referencePins)};
|
|
316
|
+
}
|
|
317
|
+
const current = pose(inverse.clone().multiply(this.bones.get(pin.id)!.matrixWorld));
|
|
318
|
+
const previous = this.displayed[i].pose;
|
|
319
|
+
const previousMatrix = matrix(previous);
|
|
320
|
+
const changed = matrix(current).elements.some((v, k) => Math.abs(v - previousMatrix.elements[k]) > 1e-6);
|
|
321
|
+
if (changed) this.dirty = true;
|
|
322
|
+
return changed ? { ...pin, pose: current } : pin;
|
|
323
|
+
});
|
|
324
|
+
const bonesEdited=edited.some((p,i)=>p!==this.base[i]);
|
|
325
|
+
if (bonesEdited) this.base = edited;
|
|
326
|
+
const movedTargets = new Set<string>();
|
|
327
|
+
for (const [id, target] of this.targets) {
|
|
328
|
+
const signature = JSON.stringify([target.position.toArray(), target.quaternion.toArray()]);
|
|
329
|
+
if (this.targetFrames.get(id) !== signature) { movedTargets.add(id); this.dirty = true; this.targetFrames.set(id, signature); }
|
|
330
|
+
}
|
|
331
|
+
for (const id of movedTargets) this.editedTargets.add(id);
|
|
332
|
+
const goalTargets = fitted ? this.editedTargets : movedTargets;
|
|
333
|
+
if (fitted && goalTargets.size) this.dirty = true;
|
|
334
|
+
// A secondary root target is a direct hierarchy transform, not a zero-
|
|
335
|
+
// length IK chain. Carry its descendants before solving other fixed goals.
|
|
336
|
+
for (const root of this.base.filter(p => (p.wiggle || p.cloth || p.fur) && goalTargets.has(p.id) && !this.parents.has(p.id))) {
|
|
337
|
+
const target = this.targets.get(root.id)!;
|
|
338
|
+
const delta = matrix({ ...root.pose, position: target.position.toArray(), rotation: target.quaternion.toArray() }).multiply(matrix(root.pose).invert());
|
|
339
|
+
const affected = new Set([root.id]);
|
|
340
|
+
for (let added = true; added;) { added = false; for (const [child, parent] of this.parents) if (affected.has(parent) && !affected.has(child)) { affected.add(child); added = true; } }
|
|
341
|
+
this.base = this.base.map(p => affected.has(p.id) && !this.drivers.some(d=>d.id===p.id) ? { ...p, pose: pose(delta.clone().multiply(matrix(p.pose))) } : p);
|
|
342
|
+
}
|
|
343
|
+
const goals = this.base.filter(p => (p.ik || ((p.wiggle || p.cloth || p.fur) && goalTargets.has(p.id))) && !p.guide && this.chain(p.id).length > 1).map(p => {
|
|
344
|
+
const target = this.targets.get(p.id)!;
|
|
345
|
+
const goal = { id: p.id, position: target.position.toArray(), rotation: target.quaternion.toArray() };
|
|
346
|
+
if (!fitted && (!p.ikTarget || goal.position.some((v, i) => Math.abs(v - p.ikTarget!.position[i]) > 1e-8) || goal.rotation.some((v, i) => Math.abs(v - p.ikTarget!.rotation[i]) > 1e-8))) this.dirty = true;
|
|
347
|
+
return fitted && !goalTargets.has(p.id) ? {id:p.id,position:[...p.pose.position] as PinPose['position'],rotation:[...p.pose.rotation] as PinPose['rotation']} : goal;
|
|
348
|
+
});
|
|
349
|
+
if (this.dirty) {
|
|
350
|
+
const localGoal=!bonesEdited && goalTargets.size===1 ? goals.find(g=>goalTargets.has(g.id)):undefined;
|
|
351
|
+
const articulated=this.articulated(this.base);
|
|
352
|
+
const solved = new Map((localGoal?solveLocalPinIK(articulated,this.parents,localGoal,this.masses):solvePlantedPinIKGoals(articulated, this.parents, goals, this.masses, new Set(articulated.filter(p => p.independent).map(p => p.id)))).map(p => [p.id, p.pose]));
|
|
353
|
+
this.base = this.base.map(p => ({ ...p, pose: solved.get(p.id) ?? p.pose, ikTarget: p.ik ? goals.find(g => g.id === p.id) ?? p.ikTarget : p.ikTarget }));
|
|
354
|
+
this.dirty = false;
|
|
355
|
+
}
|
|
356
|
+
if(fitted && !goalTargets.size && !fitted.some(pin=>pin.wiggle||pin.cloth||pin.fur)) {
|
|
357
|
+
// Ordinary clips already provide exact local TRS, including scaled
|
|
358
|
+
// parent frames which cannot be reconstructed from world TRS alone.
|
|
359
|
+
this.displayed=this.base;
|
|
360
|
+
for(const bone of this.bones.values()){bone.updateMatrix();this.localFrames.set(bone,[...bone.matrix.elements]);}
|
|
361
|
+
} else this.advanceSecondary(seconds,fitted??undefined);
|
|
362
|
+
this.rememberDisplayedAnimationFrame();
|
|
363
|
+
}
|
|
364
|
+
private advanceSecondary(seconds: number, fitted?: readonly PinRecord[]) {
|
|
365
|
+
if (fitted) this.furSurface?.update(seconds, this.windStrength);
|
|
366
|
+
const secondary=this.springs.step(this.articulated(this.base), this.parents, seconds, this.masses, this.windStrength).pins;
|
|
367
|
+
const byId = new Map(secondary.map(p => [p.id, p]));
|
|
368
|
+
const colliders: ClothCollider[] = (this.descriptor.cloth?.colliders ?? []).map(collider => {
|
|
369
|
+
const driver = byId.get(collider.driver!);
|
|
370
|
+
if (!driver) return collider;
|
|
371
|
+
const rest = { position: driver.rest, rotation: [0, 0, 0, 1] as const, scale: [1, 1, 1] as const };
|
|
372
|
+
const position = new Vector3().fromArray(collider.position).applyMatrix4(matrix(driver.pose).multiply(matrix(rest).invert()));
|
|
373
|
+
return { ...collider, position: position.toArray() };
|
|
374
|
+
});
|
|
375
|
+
const cloth = this.cloth.step(secondary, this.parents, seconds, this.descriptor.cloth?.links ?? [], colliders, this.windStrength).pins;
|
|
376
|
+
const displayed=this.base.map(p=>cloth.find(q=>q.id===p.id)??p);
|
|
377
|
+
this.apply(fitted&&this.descriptor.version>=3?driveRig(displayed,fitted,this.drivers):displayed,Boolean(fitted));
|
|
378
|
+
this.updateClothMeshes(seconds, colliders);
|
|
379
|
+
}
|
|
380
|
+
dispose() {
|
|
381
|
+
this.disposed = true; this.mixer.stopAllAction(); this.mixer.uncacheRoot(this.scene); this.resetSecondary();
|
|
382
|
+
this.furSurface?.dispose();
|
|
383
|
+
for (const entry of this.clothMeshes) { entry.mesh.geometry.dispose(); entry.mesh.geometry = entry.original; }
|
|
384
|
+
this.clothMeshes = [];
|
|
385
|
+
for (const target of this.targets.values()) target.removeFromParent(); this.targets.clear(); runtimes.delete(this.scene);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** GLTFLoader plugin that validates a rig extension and binds its scene runtime. */
|
|
390
|
+
export class NeedleDeformationRigLoaderPlugin {
|
|
391
|
+
readonly name = NEEDLE_DEFORMATION_RIG;
|
|
392
|
+
constructor(readonly parser: GLTFParser) {}
|
|
393
|
+
async afterRoot(gltf: GLTF) {
|
|
394
|
+
const json = this.parser.json as { nodes?: unknown[]; textures?: unknown[]; scenes?: { extensions?: Record<string, unknown> }[] };
|
|
395
|
+
for (const [i, scene] of gltf.scenes.entries()) {
|
|
396
|
+
const raw = json.scenes?.[i]?.extensions?.[this.name]; if (!raw) continue;
|
|
397
|
+
const descriptor = parseRigDescriptor(raw, json.nodes?.length ?? 0, json.textures?.length ?? 0);
|
|
398
|
+
const nodes: Object3D[] = await Promise.all(descriptor.joints.map(j => this.parser.getDependency('node', j.node)));
|
|
399
|
+
const helpers: Object3D[] = await Promise.all((descriptor.helpers ?? []).map(h => this.parser.getDependency('node', h.node)));
|
|
400
|
+
for (const node of [...nodes, ...helpers]) { let parent: Object3D | null = node; while (parent && parent !== scene) parent = parent.parent; if (!parent) throw new Error('Rig bone is outside its scene.'); }
|
|
401
|
+
const runtime = new DeformationRigRuntime(scene, descriptor, nodes, gltf.animations, helpers);
|
|
402
|
+
if (descriptor.furSurface) {
|
|
403
|
+
const height = await this.parser.getDependency('texture', descriptor.furSurface.heightTexture);
|
|
404
|
+
height.channel = descriptor.furSurface.texCoord ?? 0;
|
|
405
|
+
runtime.setFurHeightMap(height);
|
|
406
|
+
}
|
|
407
|
+
runtimes.set(scene, runtime);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
/** Register the rig plugin before loading a GLB. Returns the same loader. */
|
|
412
|
+
export function registerNeedleDeformationRigLoader(loader: GLTFLoader) {
|
|
413
|
+
loader.register(parser => new NeedleDeformationRigLoaderPlugin(parser)); return loader;
|
|
414
|
+
}
|
|
415
|
+
/** Return the runtime attached to a loaded glTF scene, if it has the extension. */
|
|
416
|
+
export function getDeformationRig(scene: Object3D) { return runtimes.get(scene); }
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { Vector3 } from 'three';
|
|
2
|
+
|
|
3
|
+
export const MAX_WIND_STRENGTH = 4;
|
|
4
|
+
|
|
5
|
+
/** A single weather control drives pin motion and surface pressure. Sparse pin
|
|
6
|
+
* loads stay bounded; fabric pressure has room to grow through a storm. */
|
|
7
|
+
export function windProfile(strength: number) {
|
|
8
|
+
const level = Math.max(0, Math.min(MAX_WIND_STRENGTH, strength));
|
|
9
|
+
const label = level === 0 ? 'Off' : level < .75 ? 'Breeze' : level < 1.5 ? 'Windy' : level < 2.5 ? 'Strong wind' : level < 3.3 ? 'Gale' : 'Storm';
|
|
10
|
+
return {
|
|
11
|
+
label,
|
|
12
|
+
load: 30 * level * level / (.8 + level * level),
|
|
13
|
+
surfaceLoad: 4 * level * level,
|
|
14
|
+
gust: .14 + .12 * level,
|
|
15
|
+
crosswind: .05 + .07 * level,
|
|
16
|
+
gustRate: .42 + .12 * level,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Deterministic scene-local prevailing wind with slow gusts and spatially
|
|
21
|
+
* varying eddies. Force is an acceleration scaled to the model's size, so a
|
|
22
|
+
* tiny prop and a large character respond comparably at the same setting. */
|
|
23
|
+
export function windAcceleration(seconds: number, strength: number, scale: number, position: readonly number[]) {
|
|
24
|
+
if (strength <= 0) return new Vector3();
|
|
25
|
+
const size = Math.max(1e-4, scale);
|
|
26
|
+
const profile = windProfile(strength);
|
|
27
|
+
// Advect the gust bands along +X. Nearby controls see related wind, while
|
|
28
|
+
// their phase delay keeps a large sheet or branch hierarchy from moving as
|
|
29
|
+
// one perfectly synchronized rigid object.
|
|
30
|
+
const along = position[0] / size, lateral = (position[1] * .67 + position[2] * .33) / size;
|
|
31
|
+
const slow = seconds * profile.gustRate - along * .55;
|
|
32
|
+
const fast = seconds * (profile.gustRate * 2.7) - along * 1.4 + lateral * .4;
|
|
33
|
+
const gust = Math.max(.2, 1 + profile.gust * (.7 * Math.sin(slow) + .3 * Math.sin(fast + 1.3)));
|
|
34
|
+
const cross = profile.crosswind * (.65 * Math.sin(fast + lateral) + .35 * Math.sin(slow * .73 - lateral * .6));
|
|
35
|
+
return new Vector3(1, cross * .35, cross).normalize().multiplyScalar(profile.load * size * gust);
|
|
36
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
/** Primitive extension declaring an explicitly-bound Needle mesh impostor. */
|
|
4
|
+
export const NEEDLE_MESH_IMPOSTOR = 'NEEDLE_mesh_impostor';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @typedef {object} ImpostorDescriptor
|
|
8
|
+
* @property {1} version
|
|
9
|
+
* @property {'hemisphere' | 'full' | 'single'} mapping
|
|
10
|
+
* @property {number} frames
|
|
11
|
+
* @property {readonly [number, number, number]=} captureDirection
|
|
12
|
+
* @property {number} frameResolution
|
|
13
|
+
* @property {number} padding
|
|
14
|
+
* @property {number} radius
|
|
15
|
+
* @property {readonly [number, number, number]} boundsMin
|
|
16
|
+
* @property {readonly [number, number, number]} boundsMax
|
|
17
|
+
* @property {readonly [number, number, number]} center
|
|
18
|
+
* @property {readonly number[]} viewBounds
|
|
19
|
+
* @property {'captured-alpha+sdf-material' | 'sdf-base-alpha'} coverageEncoding
|
|
20
|
+
* @property {number} captureAlphaCutoff
|
|
21
|
+
* @property {number} alphaCutoff
|
|
22
|
+
* @property {number} blendZone
|
|
23
|
+
* @property {number} parallaxSteps
|
|
24
|
+
* @property {boolean} depthDerivedWeights
|
|
25
|
+
* @property {boolean} castShadow
|
|
26
|
+
* @property {boolean} receiveShadow
|
|
27
|
+
* @property {{occlusion: number, roughness: number, metalness: number}} material
|
|
28
|
+
* @property {{version: 4, layout: 'compact-atlas-v4', depthEncoding: 'lossless-geometry10-rgba', materialFrameResolution: number, emissive: boolean}=} compression
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/** @param {unknown} value @returns {ImpostorDescriptor | null} */
|
|
32
|
+
export function parseImpostorDescriptor(value) {
|
|
33
|
+
if (!value || typeof value !== 'object') return null;
|
|
34
|
+
const descriptor = /** @type {Partial<ImpostorDescriptor>} */ (value);
|
|
35
|
+
if (
|
|
36
|
+
descriptor.version !== 1
|
|
37
|
+
|| (descriptor.mapping !== 'hemisphere' && descriptor.mapping !== 'full' && descriptor.mapping !== 'single')
|
|
38
|
+
|| !isPositiveInteger(descriptor.frames)
|
|
39
|
+
|| (descriptor.mapping === 'single'
|
|
40
|
+
? (descriptor.frames !== 1 || !isUnitVec3(descriptor.captureDirection))
|
|
41
|
+
: false)
|
|
42
|
+
|| !isPositiveInteger(descriptor.frameResolution)
|
|
43
|
+
|| !isNonNegativeInteger(descriptor.padding)
|
|
44
|
+
|| !isPositiveFinite(descriptor.radius)
|
|
45
|
+
|| (descriptor.compression !== undefined && (
|
|
46
|
+
descriptor.compression.version !== 4
|
|
47
|
+
|| descriptor.compression.layout !== 'compact-atlas-v4'
|
|
48
|
+
|| descriptor.compression.depthEncoding !== 'lossless-geometry10-rgba'
|
|
49
|
+
|| !isPositiveInteger(descriptor.compression.materialFrameResolution)
|
|
50
|
+
|| typeof descriptor.compression.emissive !== 'boolean'
|
|
51
|
+
))
|
|
52
|
+
|| !isFiniteVec3(descriptor.boundsMin)
|
|
53
|
+
|| !isFiniteVec3(descriptor.boundsMax)
|
|
54
|
+
|| !isFiniteVec3(descriptor.center)
|
|
55
|
+
|| !Array.isArray(descriptor.viewBounds)
|
|
56
|
+
|| descriptor.viewBounds.length !== (descriptor.frames ?? 0) * (descriptor.frames ?? 0) * 4
|
|
57
|
+
|| !descriptor.viewBounds.every(Number.isFinite)
|
|
58
|
+
|| (descriptor.coverageEncoding !== 'captured-alpha+sdf-material'
|
|
59
|
+
&& descriptor.coverageEncoding !== 'sdf-base-alpha')
|
|
60
|
+
|| !isUnitInterval(descriptor.captureAlphaCutoff)
|
|
61
|
+
|| !isUnitInterval(descriptor.alphaCutoff)
|
|
62
|
+
|| !isBlendZone(descriptor.blendZone)
|
|
63
|
+
|| !isNonNegativeInteger(descriptor.parallaxSteps)
|
|
64
|
+
|| typeof descriptor.depthDerivedWeights !== 'boolean'
|
|
65
|
+
|| typeof descriptor.castShadow !== 'boolean'
|
|
66
|
+
|| typeof descriptor.receiveShadow !== 'boolean'
|
|
67
|
+
|| !descriptor.material
|
|
68
|
+
|| !isUnitInterval(descriptor.material.occlusion)
|
|
69
|
+
|| !isUnitInterval(descriptor.material.roughness)
|
|
70
|
+
|| !isUnitInterval(descriptor.material.metalness)
|
|
71
|
+
) return null;
|
|
72
|
+
const valid = /** @type {ImpostorDescriptor} */ (descriptor);
|
|
73
|
+
return {
|
|
74
|
+
version: 1,
|
|
75
|
+
mapping: valid.mapping,
|
|
76
|
+
frames: valid.frames,
|
|
77
|
+
...(valid.mapping === 'single' ? { captureDirection: valid.captureDirection } : {}),
|
|
78
|
+
frameResolution: valid.frameResolution,
|
|
79
|
+
padding: valid.padding,
|
|
80
|
+
radius: valid.radius,
|
|
81
|
+
boundsMin: valid.boundsMin,
|
|
82
|
+
boundsMax: valid.boundsMax,
|
|
83
|
+
center: valid.center,
|
|
84
|
+
viewBounds: valid.viewBounds,
|
|
85
|
+
coverageEncoding: valid.coverageEncoding,
|
|
86
|
+
captureAlphaCutoff: valid.captureAlphaCutoff,
|
|
87
|
+
alphaCutoff: valid.alphaCutoff,
|
|
88
|
+
blendZone: valid.blendZone,
|
|
89
|
+
parallaxSteps: valid.parallaxSteps,
|
|
90
|
+
depthDerivedWeights: valid.depthDerivedWeights,
|
|
91
|
+
castShadow: valid.castShadow,
|
|
92
|
+
receiveShadow: valid.receiveShadow,
|
|
93
|
+
material: valid.material,
|
|
94
|
+
...(valid.compression ? { compression: valid.compression } : {}),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** @param {unknown} value */
|
|
99
|
+
function isFiniteVec3(value) {
|
|
100
|
+
return Array.isArray(value) && value.length === 3 && value.every(Number.isFinite);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** @param {unknown} value */
|
|
104
|
+
function isUnitVec3(value) {
|
|
105
|
+
if (!isFiniteVec3(value)) return false;
|
|
106
|
+
const vector = /** @type {number[]} */ (value);
|
|
107
|
+
return Math.abs(Math.hypot(vector[0], vector[1], vector[2]) - 1) < 1e-4;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** @param {unknown} value */
|
|
111
|
+
function isPositiveInteger(value) {
|
|
112
|
+
return Number.isInteger(value) && /** @type {number} */ (value) > 0;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** @param {unknown} value */
|
|
116
|
+
function isNonNegativeInteger(value) {
|
|
117
|
+
return Number.isInteger(value) && /** @type {number} */ (value) >= 0;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** @param {unknown} value */
|
|
121
|
+
function isPositiveFinite(value) {
|
|
122
|
+
return Number.isFinite(value) && /** @type {number} */ (value) > 0;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** @param {unknown} value */
|
|
126
|
+
function isUnitInterval(value) {
|
|
127
|
+
return Number.isFinite(value)
|
|
128
|
+
&& /** @type {number} */ (value) >= 0
|
|
129
|
+
&& /** @type {number} */ (value) <= 1;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** @param {unknown} value */
|
|
133
|
+
function isBlendZone(value) {
|
|
134
|
+
return Number.isFinite(value)
|
|
135
|
+
&& /** @type {number} */ (value) >= 0.35
|
|
136
|
+
&& /** @type {number} */ (value) <= 1;
|
|
137
|
+
}
|