Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(pipeline): spring-bone import reads VRM spring bones and node properties before it looks at names

yhh609fb0b7554a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9c7f1605f..a32aeab03 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,7 @@ published separately; it ships inside the editor.
- **Contact shadows and screen-space bounce light.** Contact Shadows and Screen Space GI effects add small sharp shadows at contacts and one bounce of colour between surfaces, and the weather softens the sun's shadows. `contactShadows` marches a short ray toward the scene's sun in the depth buffer; `ssgi` gathers eight rays a pixel over the G-buffer's normals at half size into a float target and averages the neighbours on the same surface before laying the light, times the receiver's colour, over the picture. The Weather component raises the sun's `sourceAngle` and lowers its `shadowStrength` as the sky clouds over.
- **Terrain and Foliage.** A Terrain component makes ground from a heightmap or noise, paints it with grass, dirt, snow and rock layers and draws it in chunks that coarsen with distance; a Foliage component scatters grass or a mesh over it, swaying in the wind and thinning out with distance.
- **Separate material maps packed on import.** Importing an FBX with separate metalness, roughness and occlusion images now packs them into the one map the Model shader samples, instead of dropping them. Occlusion goes in red, roughness in green and metal in blue, each from its image's red channel (a glossiness map is inverted); a channel with no image stays at full so the material's own value speaks. Only PNG and DDS can be read.
+- **Spring-bone data in the file.** The Spring Bones import setting now reads what a model states before it looks at names: the VRM spring-bone extension (VRMC_springBone, with its stiffness and gravity converted to units the engine uses) and a node's own extras.estella.springBone and springCollider properties, which carry exact sizes from a Blender custom property. Names fill in whatever those leave out, a chain with no collider list is kept out of every collider in the model, and springs that cannot be used are reported in the import warnings.
- **Spring-bone collider handles.** A selected spring-bone collider carries six square handles in the viewport: on a sphere any of them sets the radius, on a capsule the four round its middle set the radius and the two on its ends set the height. The ones on the far side of the shape are faded, the value shows beside the pointer while one is dragged, a drag is one undo step, and with Preview FX on the strands follow it live.
- **Spring-bone import.** A model's new Spring Bones import setting (By Bone Name) builds hair motion from names the file already carries: a bone called Hair_<region>_<chain>_00 becomes a SpringBone with the bones below it as the strand, and an empty called SBC_Sphere_<name>_r<cm> or SBC_Capsule_<name>_r<cm>_h<cm> becomes a collider every chain is kept out of. The region sets a starting stiffness and drag, sizes follow the model's metres and the import scale, and the result is ordinary components to adjust in Details.
- **Spring-bone wind.** A spring-bone chain takes a wind: `wind` is a steady acceleration on the chain, `windGust` swings its strength from calm to twice as strong, and `windFrequency` sets how often. Each bone meets a gust a moment after the one above, so a strand ripples rather than swaying as one, and a chain's gusts depend only on its own clock, so the same scene moves the same way twice. The wind is a field on each chain; there is no scene-wide wind source yet.
diff --git a/docs/astro/src/content/docs/animation/spring-bones.mdx b/docs/astro/src/content/docs/animation/spring-bones.mdx
index b50270900..d927e9702 100644
--- a/docs/astro/src/content/docs/animation/spring-bones.mdx
+++ b/docs/astro/src/content/docs/animation/spring-bones.mdx
@@ -34,7 +34,11 @@ and shoulders bones so hair does not pass through the body.
## From a model
-Set a model's **Spring Bones** import setting to **By Bone Name** and the importer builds the chains from names the file already carries, so nobody sets up forty strands by hand:
+Set a model's **Spring Bones** import setting to **From File Data and Names** and the importer builds the chains from what the file already says, so nobody sets up forty strands by hand. It looks, in this order, at:
+
+1. **`VRMC_springBone`**, the VRM 1.0 extension: springs, colliders and collider groups with their numbers. A spring becomes a `SpringBone` on its first joint (that bone is held, the ones below it move), and its stiffness (per second in VRM) and gravity power are converted to the engine's per-frame and acceleration units. Springs that name fewer than two joints, or that would move bones they do not name, are reported in the import warnings.
+2. **A node's own properties**, `extras.estella.springBone` (`stiffness`, `drag`, `gravity`, `radius`, `endLength`) on a chain root and `extras.estella.springCollider` (`shape`, `radius`, `height`, `offset`) on a collider node, which is how a Blender custom property reaches the engine with exact sizes. These win over VRM for the node they are on.
+3. **Names**, for whatever those leave unsaid:
| Name | Becomes |
| --- | --- |
diff --git a/docs/astro/src/content/docs/zh-cn/animation/spring-bones.mdx b/docs/astro/src/content/docs/zh-cn/animation/spring-bones.mdx
index f1100f462..34699564c 100644
--- a/docs/astro/src/content/docs/zh-cn/animation/spring-bones.mdx
+++ b/docs/astro/src/content/docs/zh-cn/animation/spring-bones.mdx
@@ -29,7 +29,11 @@ description: 骨骼链的次级运动(头发、尾巴、绳索):放在链根上
## 从模型导入
-把模型的 **Spring Bones** 导入设置改成 **By Bone Name**,导入器就按文件里已有的名字建链,不用手动设置几十根发丝:
+把模型的 **Spring Bones** 导入设置改成 **From File Data and Names**,导入器就按文件里已有的信息建链,不用手动设置几十根发丝。它按下面的顺序查找:
+
+1. **`VRMC_springBone`**(VRM 1.0 扩展):弹簧、碰撞体、碰撞体组和它们的数值。一条弹簧变成它第一个关节上的 `SpringBone`(这根骨头固定,它下面的骨头会动),VRM 里按秒的刚度和重力强度会换算成引擎按帧的刚度和加速度。关节少于两个、或会带动它没有列出的骨头的弹簧,会在导入警告里报告。
+2. **节点自己的属性**:链根上的 `extras.estella.springBone`(`stiffness`、`drag`、`gravity`、`radius`、`endLength`)和碰撞体节点上的 `extras.estella.springCollider`(`shape`、`radius`、`height`、`offset`)。Blender 的自定义属性就是这样带着精确尺寸进到引擎里的。在同一个节点上,它优先于 VRM。
+3. **名字**,补全前两者没说的部分:
| 名字 | 变成 |
| --- | --- |
diff --git a/pipeline/src/assets/gltfImport.ts b/pipeline/src/assets/gltfImport.ts
index 808b6f775..32136bf24 100644
--- a/pipeline/src/assets/gltfImport.ts
+++ b/pipeline/src/assets/gltfImport.ts
@@ -15,6 +15,7 @@ import { MESH_MAX_BONES, MeshChannel, MeshChannelType, packChannels,
type MeshMorphTargets } from 'esengine';
import { MeshoptDecoder } from 'meshoptimizer/decoder';
import { generateTangents } from './meshTangents';
+import { readSpringBones } from './springBoneSource';
import {
ANIMATED_PATHS, alignQuaternionSigns, animationProductName, disambiguateNodes,
nodeChildPaths, nodeNameFor, samplerKeyframes, timelineDocument,
@@ -153,13 +154,14 @@ interface GltfJson {
weights?: number[];
camera?: number;
extensions?: { KHR_lights_punctual?: { light?: number } };
+ extras?: unknown;
}[];
cameras?: {
type: string;
perspective?: { yfov: number; znear: number; zfar?: number; aspectRatio?: number };
orthographic?: { xmag: number; ymag: number; znear: number; zfar: number };
}[];
- extensions?: { KHR_lights_punctual?: { lights?: GltfLight[] } };
+ extensions?: { KHR_lights_punctual?: { lights?: GltfLight[] } } & Record<string, unknown>;
skins?: { name?: string; joints: number[]; inverseBindMatrices?: number; skeleton?: number }[];
animations?: {
name?: string;
@@ -780,6 +782,7 @@ function readNodes(json: GltfJson, meshIndexOf: Map<string, number>,
const roots = json.scenes?.[json.scene ?? 0]?.nodes
?? source.map((_, i) => i).filter(i => !source.some(n => n.children?.includes(i)));
+ const spring = readSpringBones(json, warnings);
const visiting = new Set<number>();
const build = (index: number): ImportedNode | null => {
const node = source[index];
@@ -804,7 +807,7 @@ function readNodes(json: GltfJson, meshIndexOf: Map<string, number>,
: readLight(json.extensions?.KHR_lights_punctual?.lights?.[lightIndex], warnings, name);
const camera = node.camera === undefined ? undefined : readCamera(json.cameras?.[node.camera]);
return { index, name, ...nodeTrs(node), meshes, children,
- ...(light ? { light } : {}), ...(camera ? { camera } : {}) };
+ ...(light ? { light } : {}), ...(camera ? { camera } : {}), ...(spring.get(index) ?? {}) };
};
const built = roots.map(build).filter((n): n is ImportedNode => n !== null);
diff --git a/pipeline/src/assets/modelImport.ts b/pipeline/src/assets/modelImport.ts
index 04cec07c2..1ae5282fa 100644
--- a/pipeline/src/assets/modelImport.ts
+++ b/pipeline/src/assets/modelImport.ts
@@ -162,6 +162,30 @@ export interface ImportedNode {
light?: ImportedLight;
/** A camera the node carries, looking along its local -Z with +Y up. */
camera?: ImportedCamera;
+ /** This node is the root of a spring chain: the bones below it are the strand. Lengths are the model's metres. */
+ springBone?: ImportedSpringBone;
+ /** Colliders this node hosts, each an entity of its own below it so one bone can carry several. */
+ springColliders?: ImportedSpringCollider[];
+}
+
+/** What a source states about a spring chain; a field it leaves out keeps the component's default (or the name rule's, for a chain found by name). */
+export interface ImportedSpringBone {
+ stiffness?: number;
+ drag?: number;
+ gravity?: [number, number, number];
+ radius?: number;
+ endLength?: number;
+ /** Prefab entity ids of the colliders the chain is kept out of; left out, every collider in the model. */
+ colliders?: string[];
+}
+
+/** A sphere (`shape` 0) or capsule (1) placed relative to its host node: `offset` and `rotation` (x, y, z, w) put its centre and its Y axis. */
+export interface ImportedSpringCollider {
+ shape: 0 | 1;
+ radius: number;
+ height?: number;
+ offset?: [number, number, number];
+ rotation?: [number, number, number, number];
}
/**
@@ -897,6 +921,33 @@ function entity(id: string, name: string, parent: string | null,
return { prefabEntityId: id, name, parent, children: [], visible: true, components };
}
+/** The spring data a source stated for this node: a SpringBone on it, and an entity below it for each collider it hosts. Lengths are the model's metres times the import scale. */
+function addExplicitSpringBones(node: ImportedNode, self: PrefabEntityData, entities: PrefabEntityData[], scale: number): void {
+ (node.springColliders ?? []).forEach((c, i) => {
+ const id = `${self.prefabEntityId}_sbc${i}`;
+ const [x, y, z] = c.offset ?? [0, 0, 0];
+ const [rx, ry, rz, rw] = c.rotation ?? [0, 0, 0, 1];
+ self.children.push(id);
+ entities.push(entity(id, `${node.name}_collider${i}`, self.prefabEntityId, [
+ { type: 'Transform', data: {
+ ...(x || y || z ? { position: { x, y, z } } : {}),
+ ...(rx || ry || rz || rw !== 1 ? { rotation: { w: rw, x: rx, y: ry, z: rz } } : {}),
+ } },
+ { type: 'SpringBoneCollider', data: { shape: c.shape, radius: c.radius, ...(c.shape === 1 ? { height: c.height ?? 0 } : {}) } },
+ ]));
+ });
+ const s = node.springBone;
+ if (!s) return;
+ self.components.push({ type: 'SpringBone', data: {
+ ...(s.stiffness !== undefined ? { stiffness: s.stiffness } : {}),
+ ...(s.drag !== undefined ? { drag: s.drag } : {}),
+ ...(s.gravity ? { gravity: { x: s.gravity[0] * scale, y: s.gravity[1] * scale, z: s.gravity[2] * scale } } : {}),
+ ...(s.radius !== undefined ? { radius: s.radius * scale } : {}),
+ ...(s.endLength !== undefined ? { endLength: s.endLength * scale } : {}),
+ ...(s.colliders ? { colliders: [...s.colliders] } : {}),
+ } });
+}
+
/** A hair chain's root bone: `Hair_<region>_<chain>_00`, the joint the body or the animation drives and the chain hangs from. */
const HAIR_CHAIN_ROOT = /^Hair_([A-Za-z]+(?:_[A-Za-z]+)*)_(\d{2})_00$/;
/** A collider an artist left in the model: `SBC_Sphere_<name>_r<cm>` or `SBC_Capsule_<name>_r<cm>_h<cm>`; the node's own transform places it, a capsule runs along its local +Y. */
@@ -917,8 +968,16 @@ const HAIR_FEEL: Record<string, { stiffness: number; drag: number }> = {
* Returns the counts it made.
*/
export function springBoneComponents(entities: PrefabEntityData[], scale = 1): { chains: number; colliders: number } {
- const colliders: string[] = [];
+ const has = (e: PrefabEntityData, type: string): boolean => e.components.some(c => c.type === type);
+ // What the file stated outright is already on the entities; names only fill in what it did not.
+ const colliders: string[] = entities.filter(e => has(e, 'SpringBoneCollider')).map(e => e.prefabEntityId);
+ for (const e of entities) {
+ for (const c of e.components) {
+ if (c.type === 'SpringBone' && c.data.colliders === undefined) c.data.colliders = [...colliders];
+ }
+ }
for (const e of entities) {
+ if (has(e, 'SpringBoneCollider')) continue;
const m = SPRING_COLLIDER.exec(e.name);
if (!m) continue;
const radius = Number(m[3]) / 100;
@@ -932,7 +991,7 @@ export function springBoneComponents(entities: PrefabEntityData[], scale = 1): {
let chains = 0;
for (const e of entities) {
const m = HAIR_CHAIN_ROOT.exec(e.name);
- if (!m || e.children.length === 0) continue;
+ if (!m || e.children.length === 0 || has(e, 'SpringBone')) continue;
const feel = HAIR_FEEL[m[1]!.split('_')[0]!] ?? { stiffness: 0.1, drag: 0.5 };
e.components.push({ type: 'SpringBone', data: {
stiffness: feel.stiffness, drag: feel.drag,
@@ -971,6 +1030,7 @@ export function assembleModelPrefab(name: string, meshes: ImportedMesh[],
...(node.camera ? [cameraComponent(node.camera)] : []),
]);
entities.push(self);
+ if (refs.springBones) addExplicitSpringBones(node, self, entities, options.scale ?? 1);
if (own.length === 0) {
drawn.forEach((mesh, i) => {
const childId = `${id}_p${i}`;
diff --git a/pipeline/src/assets/springBoneSource.ts b/pipeline/src/assets/springBoneSource.ts
new file mode 100644
index 000000000..5bc8617bc
--- /dev/null
+++ b/pipeline/src/assets/springBoneSource.ts
@@ -0,0 +1,170 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file springBoneSource.ts
+ * @brief The spring-bone data a glTF states outright, as per-node facts the prefab assembly turns into components.
+ *
+ * Two sources, in the order they are trusted. `VRMC_springBone` (the VRM 1.0 extension) lists springs and colliders with their numbers; a node's own
+ * `extras.estella` can carry the same for one chain root (`springBone`) or one collider (`springCollider`), which is how a Blender custom property gets in
+ * without a name to parse. Names (`Hair_...`, `SBC_...`) are the fallback, handled by the assembly for whatever these leave unsaid.
+ *
+ * Sizes stay in the model's metres here; the assembly applies the import scale. A VRM spring becomes a SpringBone on its FIRST joint's node (that bone is
+ * held, the ones below it are simulated), since several springs may start under one parent and a bone holds only one SpringBone.
+ */
+import type { ImportedSpringBone, ImportedSpringCollider } from './modelImport';
+
+type Vec3 = [number, number, number];
+
+interface GltfNodeLike { name?: string; children?: number[]; extras?: unknown }
+
+export interface SpringNodeData {
+ springBone?: ImportedSpringBone;
+ springColliders?: ImportedSpringCollider[];
+}
+
+/** VRM stiffness is per second and ours is per 60 Hz frame; VRM drag is already a per-step share. */
+const REFERENCE_RATE = 60;
+
+const num = (v: unknown, fallback: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : fallback);
+const vec3 = (v: unknown, fallback: Vec3): Vec3 =>
+ Array.isArray(v) && v.length >= 3 ? [num(v[0], fallback[0]), num(v[1], fallback[1]), num(v[2], fallback[2])] : fallback;
+const record = (v: unknown): Record<string, unknown> | undefined =>
+ typeof v === 'object' && v !== null && !Array.isArray(v) ? v as Record<string, unknown> : undefined;
+
+/** The shortest rotation (x, y, z, w) that turns +Y onto `dir`. */
+export function rotationFromY(dir: Vec3): [number, number, number, number] {
+ const len = Math.hypot(dir[0], dir[1], dir[2]);
+ if (len < 1e-9) return [0, 0, 0, 1];
+ const d: Vec3 = [dir[0] / len, dir[1] / len, dir[2] / len];
+ // cross(Y, d) = (d.z, 0, -d.x); dot(Y, d) = d.y
+ if (d[1] < -0.999999) return [1, 0, 0, 0];
+ const w = 1 + d[1];
+ const n = Math.hypot(d[2], w, d[0]);
+ return [d[2] / n, 0, -d[0] / n, w / n];
+}
+
+function readExtras(index: number, node: GltfNodeLike, out: Map<number, SpringNodeData>): void {
+ const estella = record(record(node.extras)?.estella);
+ if (!estella) return;
+ const spring = record(estella.springBone);
+ const collider = record(estella.springCollider);
+ const slot = out.get(index) ?? {};
+ if (spring) {
+ const g = spring.gravity;
+ slot.springBone = {
+ ...(typeof spring.stiffness === 'number' ? { stiffness: spring.stiffness } : {}),
+ ...(typeof spring.drag === 'number' ? { drag: spring.drag } : {}),
+ ...(Array.isArray(g) ? { gravity: vec3(g, [0, -9.8, 0]) } : {}),
+ ...(typeof spring.radius === 'number' ? { radius: spring.radius } : {}),
+ ...(typeof spring.endLength === 'number' ? { endLength: spring.endLength } : {}),
+ };
+ }
+ if (collider) {
+ const capsule = collider.shape === 'capsule' || collider.shape === 1;
+ (slot.springColliders ??= []).push({
+ shape: capsule ? 1 : 0, radius: num(collider.radius, 0.05),
+ ...(capsule ? { height: num(collider.height, 0.1) } : {}),
+ ...(Array.isArray(collider.offset) ? { offset: vec3(collider.offset, [0, 0, 0]) } : {}),
+ });
+ }
+ out.set(index, slot);
+}
+
+/** Every node of the subtree below `root` (not counting it). */
+function below(nodes: ReadonlyArray<GltfNodeLike>, root: number): Set<number> {
+ const out = new Set<number>();
+ const stack = [...(nodes[root]?.children ?? [])];
+ while (stack.length > 0 && out.size < 4096) {
+ const i = stack.pop()!;
+ if (out.has(i)) continue;
+ out.add(i);
+ stack.push(...(nodes[i]?.children ?? []));
+ }
+ return out;
+}
+
+function readVrm(nodes: ReadonlyArray<GltfNodeLike>, ext: Record<string, unknown>, out: Map<number, SpringNodeData>, warnings: string[]): void {
+ const colliderDefs = Array.isArray(ext.colliders) ? ext.colliders : [];
+ // The id each collider will have: its host node's own list position, which is the order they are pushed in here.
+ const idOf: Array<string | null> = [];
+ colliderDefs.forEach((raw) => {
+ const c = record(raw);
+ const node = c ? c.node : undefined;
+ const shape = record(c?.shape);
+ const sphere = record(shape?.sphere), capsule = record(shape?.capsule);
+ if (!c || typeof node !== 'number' || !nodes[node] || (!sphere && !capsule)) {
+ warnings.push('a VRMC_springBone collider names no node or no shape — skipped');
+ idOf.push(null);
+ return;
+ }
+ const slot = out.get(node) ?? {};
+ const list = slot.springColliders ??= [];
+ if (sphere) {
+ list.push({ shape: 0, radius: num(sphere.radius, 0), offset: vec3(sphere.offset, [0, 0, 0]) });
+ } else if (capsule) {
+ const head = vec3(capsule.offset, [0, 0, 0]), tail = vec3(capsule.tail, [0, 0, 0]);
+ const axis: Vec3 = [tail[0] - head[0], tail[1] - head[1], tail[2] - head[2]];
+ list.push({
+ shape: 1, radius: num(capsule.radius, 0), height: Math.hypot(axis[0], axis[1], axis[2]),
+ offset: [(head[0] + tail[0]) / 2, (head[1] + tail[1]) / 2, (head[2] + tail[2]) / 2], rotation: rotationFromY(axis),
+ });
+ }
+ out.set(node, slot);
+ idOf.push(`n${node}_sbc${list.length - 1}`);
+ });
+ const groups = Array.isArray(ext.colliderGroups) ? ext.colliderGroups : [];
+ const springs = Array.isArray(ext.springs) ? ext.springs : [];
+ for (const raw of springs) {
+ const spring = record(raw);
+ const joints = (Array.isArray(spring?.joints) ? spring!.joints as unknown[] : []).map(record).filter((j): j is Record<string, unknown> => !!j);
+ const first = joints[0];
+ const rootNode = first ? first.node : undefined;
+ const label = typeof spring?.name === 'string' ? spring.name : 'a spring';
+ if (typeof rootNode !== 'number' || !nodes[rootNode] || joints.length < 2) {
+ warnings.push(`VRMC_springBone: ${label} has fewer than two joints — skipped`);
+ continue;
+ }
+ const slot = out.get(rootNode) ?? {};
+ if (slot.springBone) {
+ warnings.push(`VRMC_springBone: ${label} starts on a bone another spring already holds — skipped`);
+ continue;
+ }
+ const mean = (read: (j: Record<string, unknown>) => number): number => joints.reduce((a, j) => a + read(j), 0) / joints.length;
+ const gravity: Vec3 = [0, 0, 0];
+ for (const j of joints) {
+ const dir = vec3(j.gravityDir, [0, -1, 0]);
+ const power = num(j.gravityPower, 0);
+ for (let k = 0; k < 3; k++) gravity[k]! += (dir[k]! * power * REFERENCE_RATE) / joints.length;
+ }
+ const colliders: string[] = [];
+ for (const g of Array.isArray(spring?.colliderGroups) ? spring!.colliderGroups as unknown[] : []) {
+ const group = record(typeof g === 'number' ? groups[g] : undefined);
+ for (const c of Array.isArray(group?.colliders) ? group!.colliders as unknown[] : []) {
+ const id = typeof c === 'number' ? idOf[c] : null;
+ if (id && !colliders.includes(id)) colliders.push(id);
+ }
+ }
+ slot.springBone = {
+ stiffness: Math.min(1, Math.max(0, mean((j) => num(j.stiffness, 1)) / REFERENCE_RATE)),
+ drag: Math.min(1, Math.max(0, mean((j) => num(j.dragForce, 0.5)))),
+ gravity,
+ radius: mean((j) => num(j.hitRadius, 0)),
+ colliders,
+ };
+ out.set(rootNode, slot);
+ // A SpringBone simulates everything below its bone; a VRM spring names exactly which bones.
+ const named = new Set(joints.map((j) => j.node as number));
+ const extra = [...below(nodes, rootNode)].filter((i) => !named.has(i)).length;
+ if (extra > 0) warnings.push(`VRMC_springBone: ${label} also moves ${extra} bone(s) below its first joint that it does not name`);
+ }
+}
+
+/** The per-node spring-bone facts a glTF's own data gives: VRM first, then each node's `extras.estella`. */
+export function readSpringBones(json: { nodes?: ReadonlyArray<GltfNodeLike>; extensions?: Record<string, unknown> }, warnings: string[]): Map<number, SpringNodeData> {
+ const out = new Map<number, SpringNodeData>();
+ const nodes = json.nodes ?? [];
+ const vrm = record(json.extensions?.VRMC_springBone);
+ if (vrm) readVrm(nodes, vrm, out, warnings);
+ nodes.forEach((node, i) => readExtras(i, node, out));
+ return out;
+}
diff --git a/pipeline/src/project/importSettings.ts b/pipeline/src/project/importSettings.ts
index 830692927..795279c07 100644
--- a/pipeline/src/project/importSettings.ts
+++ b/pipeline/src/project/importSettings.ts
@@ -242,11 +242,11 @@ const MODEL: ImporterFieldSpec[] = [
{
key: 'springBones', label: 'Spring Bones', type: 'enum', default: 'off',
category: 'Import', advanced: true,
- options: [{ label: 'Off', value: 'off' }, { label: 'By Bone Name', value: 'auto' }],
- tooltip: 'Give hair its secondary motion from names the model already carries: a bone called Hair_<region>_<chain>_00 '
- + 'becomes a SpringBone and everything below it the strand, and an empty called SBC_Sphere_<name>_r<cm> or '
- + 'SBC_Capsule_<name>_r<cm>_h<cm> becomes a collider the strands are kept out of. Sizes are in metres, as the model has them. '
- + 'A name is a convention, so check what it found.',
+ options: [{ label: 'Off', value: 'off' }, { label: 'From File Data and Names', value: 'auto' }],
+ tooltip: 'Give hair its secondary motion from what the model already says. A VRM spring-bone extension or a node custom '
+ + 'property (extras.estella.springBone / springCollider) is used as stated; for what they leave out, a bone called '
+ + 'Hair_<region>_<chain>_00 becomes a SpringBone and an empty called SBC_Sphere_<name>_r<cm> or '
+ + 'SBC_Capsule_<name>_r<cm>_h<cm> a collider. Sizes are in metres, as the model has them. A name is a convention, so check what it found.',
},
{
key: 'specularMap', label: 'Specular Map', type: 'enum', default: 'color',
diff --git a/pipeline/tests/spring-bone-source.test.ts b/pipeline/tests/spring-bone-source.test.ts
new file mode 100644
index 000000000..e6369a387
--- /dev/null
+++ b/pipeline/tests/spring-bone-source.test.ts
@@ -0,0 +1,130 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spring-bone-source — spring bones a glTF states outright: the VRM 1.0 extension and a node's own extras, and how they meet the name rule.
+ */
+import { describe, it, expect } from 'vitest';
+import { readSpringBones, rotationFromY } from '../src/assets/springBoneSource';
+import { assembleModelPrefab, type ImportedNode } from '../src/assets/modelImport';
+
+const nodes = [
+ { name: 'Head', children: [1, 4] },
+ { name: 'Hair_A', children: [2] },
+ { name: 'Hair_A1', children: [3] },
+ { name: 'Hair_A2' },
+ { name: 'Hair_B', children: [5] },
+ { name: 'Hair_B1' },
+ { name: 'Neck' },
+];
+
+const vrm = {
+ colliders: [
+ { node: 0, shape: { sphere: { offset: [0, 0.1, 0], radius: 0.08 } } },
+ { node: 6, shape: { capsule: { offset: [0, 0, 0], radius: 0.04, tail: [0, 0.1, 0] } } },
+ ],
+ colliderGroups: [{ colliders: [0, 1] }],
+ springs: [
+ { name: 'hairA', joints: [{ node: 1, stiffness: 0.6, dragForce: 0.4, gravityPower: 0.1, hitRadius: 0.01 }, { node: 2 }, { node: 3 }], colliderGroups: [0] },
+ { name: 'hairB', joints: [{ node: 4 }, { node: 5 }] },
+ ],
+};
+
+describe('rotationFromY', () => {
+ it('turns +Y onto the direction it is given, and handles straight up and straight down', () => {
+ const turn = (q: number[], v: number[]): number[] => {
+ const [x, y, z, w] = q as [number, number, number, number];
+ const tx = 2 * (y * v[2]! - z * v[1]!), ty = 2 * (z * v[0]! - x * v[2]!), tz = 2 * (x * v[1]! - y * v[0]!);
+ return [v[0]! + w * tx + (y * tz - z * ty), v[1]! + w * ty + (z * tx - x * tz), v[2]! + w * tz + (x * ty - y * tx)];
+ };
+ for (const d of [[1, 0, 0], [0, 0, 1], [1, 1, 0], [0, 1, 0], [0, -1, 0]]) {
+ const len = Math.hypot(d[0]!, d[1]!, d[2]!);
+ const out = turn(rotationFromY(d as [number, number, number]), [0, 1, 0]);
+ expect(out[0]).toBeCloseTo(d[0]! / len);
+ expect(out[1]).toBeCloseTo(d[1]! / len);
+ expect(out[2]).toBeCloseTo(d[2]! / len);
+ }
+ });
+});
+
+describe('VRMC_springBone', () => {
+ it('puts a SpringBone on the first joint, in the units the engine uses', () => {
+ const out = readSpringBones({ nodes, extensions: { VRMC_springBone: vrm } }, []);
+ const a = out.get(1)!.springBone!;
+ // Per second becomes per 60 Hz frame, and gravity power times 60 is the acceleration the solver adds each step.
+ expect(a.stiffness).toBeCloseTo((0.6 + 1 + 1) / 3 / 60);
+ expect(a.drag).toBeCloseTo((0.4 + 0.5 + 0.5) / 3);
+ expect(a.gravity![1]).toBeCloseTo(-(0.1 * 60) / 3);
+ expect(a.radius).toBeCloseTo(0.01 / 3);
+ expect(out.get(4)!.springBone).toBeDefined();
+ });
+
+ it('turns colliders into entities hosted on their node, a capsule centred and turned along its tail', () => {
+ const out = readSpringBones({ nodes, extensions: { VRMC_springBone: vrm } }, []);
+ expect(out.get(0)!.springColliders).toEqual([{ shape: 0, radius: 0.08, offset: [0, 0.1, 0] }]);
+ const neck = out.get(6)!.springColliders![0]!;
+ expect(neck.shape).toBe(1);
+ expect(neck.height).toBeCloseTo(0.1);
+ expect(neck.offset).toEqual([0, 0.05, 0]);
+ expect(neck.rotation![3]).toBeCloseTo(1);
+ // A spring names its groups; a spring that names none gets none.
+ expect(out.get(1)!.springBone!.colliders).toEqual(['n0_sbc0', 'n6_sbc0']);
+ expect(out.get(4)!.springBone!.colliders).toEqual([]);
+ });
+
+ it('says so when a spring is not usable, or moves bones it does not name', () => {
+ const warnings: string[] = [];
+ readSpringBones({ nodes, extensions: { VRMC_springBone: { springs: [{ name: 'short', joints: [{ node: 1 }] }, { name: 'partial', joints: [{ node: 1 }, { node: 2 }] }] } } }, warnings);
+ expect(warnings.some(w => /short.*fewer than two joints/.test(w))).toBe(true);
+ expect(warnings.some(w => /partial.*1 bone/.test(w))).toBe(true);
+ });
+});
+
+describe('extras.estella', () => {
+ const withExtras = nodes.map((n, i) => i === 1
+ ? { ...n, extras: { estella: { springBone: { stiffness: 0.3, gravity: [0, -5, 0], endLength: 0.02 } } } }
+ : i === 6 ? { ...n, extras: { estella: { springCollider: { shape: 'capsule', radius: 0.04, height: 0.09, offset: [0, 0.02, 0] } } } } : n);
+
+ it('reads a chain and a collider from a node\'s own properties, with exact sizes', () => {
+ const out = readSpringBones({ nodes: withExtras }, []);
+ expect(out.get(1)!.springBone).toEqual({ stiffness: 0.3, gravity: [0, -5, 0], endLength: 0.02 });
+ expect(out.get(6)!.springColliders).toEqual([{ shape: 1, radius: 0.04, height: 0.09, offset: [0, 0.02, 0] }]);
+ });
+
+ it('wins over the VRM data for the node it is on', () => {
+ const out = readSpringBones({ nodes: withExtras, extensions: { VRMC_springBone: vrm } }, []);
+ expect(out.get(1)!.springBone!.stiffness).toBe(0.3);
+ });
+});
+
+describe('assembly of stated data', () => {
+ let next = 0;
+ const node = (name: string, extra: Partial<ImportedNode> = {}, children: ImportedNode[] = []): ImportedNode =>
+ ({ index: next++, name, translation: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1], meshes: [], children, ...extra });
+
+ it('makes the components, scales the lengths, and gives a chain with no list every collider in the model', () => {
+ next = 0;
+ const tree = [node('Head', { springColliders: [{ shape: 0, radius: 0.08 }] }, [
+ node('Strand', { springBone: { stiffness: 0.2, gravity: [0, -10, 0], endLength: 0.02 } }, [node('Tip')]),
+ node('Hair_Ponytail_00_00', {}, [node('Hair_Ponytail_00_01')]),
+ ])];
+ const prefab = assembleModelPrefab('rig', [], { nodes: tree, refs: { springBones: true }, scale: 100 });
+ const by = (name: string) => prefab.entities.find(e => e.name === name)!;
+ const strand = by('Strand').components.find(c => c.type === 'SpringBone')!.data;
+ expect(strand.stiffness).toBe(0.2);
+ expect((strand.gravity as { y: number }).y).toBeCloseTo(-1000);
+ expect(strand.endLength).toBeCloseTo(2);
+ const hosted = `${by('Head').prefabEntityId}_sbc0`;
+ expect(strand.colliders).toEqual([hosted]);
+ // The collider is an entity below its host, and a chain found by name is wired to it as well.
+ const collider = by('Head_collider0');
+ expect(collider.parent).toBe(by('Head').prefabEntityId);
+ expect(by('Hair_Ponytail_00_00').components.find(c => c.type === 'SpringBone')!.data.colliders).toEqual([hosted]);
+ });
+
+ it('leaves a model alone when the setting is off', () => {
+ next = 0;
+ const tree = [node('Head', { springColliders: [{ shape: 0, radius: 0.08 }] }, [node('Strand', { springBone: {} }, [node('Tip')])])];
+ const prefab = assembleModelPrefab('rig', [], { nodes: tree, refs: {} });
+ expect(prefab.entities.some(e => e.components.some(c => c.type === 'SpringBone' || c.type === 'SpringBoneCollider'))).toBe(false);
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 7d0f64a4d..dc759fa78 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2567,6 +2567,8 @@ export const NOTED = {
{"note":"Water holds things up. A Floating component on an entity with a RigidBody3D floats it: a buoyant force against gravity (`buoyancy` is the water's density against the body's, so 2 floats it half under) and a drag against its velocity relative to the water, which brings it to rest in a lake and carries it with a river's current, applied at a few points of the body so waves tip it. It works from the CPU's own water surface, so it needs no renderer, and it needs the 3D physics module, which gains force and mass queries."},
"feat(water): a camera under the surface sees through the water, fogged and tinted by what it has crossed":
{"note":"A camera under water sees through it. Whenever the active camera is below a water body's surface an Underwater effect is added to the post-process volumes: the light of each pixel is taken out colour by colour (red first) by the distance it crossed, with the same absorption and density the surface's material draws with, and the water gives back its own colour, dimmer the deeper the camera is. The surface seen from below turns over and, past the critical angle, reflects whole (Snell's window)."},
+ "feat(pipeline): spring-bone import reads VRM spring bones and node properties before it looks at names":
+ {"note":"The Spring Bones import setting now reads what a model states before it looks at names: the VRM spring-bone extension (VRMC_springBone, with its stiffness and gravity converted to units the engine uses) and a node's own extras.estella.springBone and springCollider properties, which carry exact sizes from a Blender custom property. Names fill in whatever those leave out, a chain with no collider list is kept out of every collider in the model, and springs that cannot be used are reported in the import warnings."},
"feat(editor): a selected spring-bone collider has six handles in the viewport that drag its radius and height":
{"note":"A selected spring-bone collider carries six square handles in the viewport: on a sphere any of them sets the radius, on a capsule the four round its middle set the radius and the two on its ends set the height. The ones on the far side of the shape are faded, the value shows beside the pointer while one is dragged, a drag is one undo step, and with Preview FX on the strands follow it live."},
"feat(pipeline): a model's Spring Bones import setting builds hair chains and colliders from bone names":