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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(pipeline): a model's Spring Bones import setting builds hair chains and colliders from bone names
yhhf8a353bebaeb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 00bd204f6..ed2891c73 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 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.- **Spring-bone authoring.** Spring bones can be authored in the editor: Details groups a chain's fields into Motion, Chain and Collision and counts the bones below it (or warns that there are none), the viewport draws a selected chain (the bones as posed, a ring at each joint, the tips) with the colliders it keeps out of, or a selected collider on its own, behind a Spring bones entry in the Gizmo menu, and View · Preview FX simulates the chain in the edit viewport, drawn solid over its dashed pose. Ending the preview gives the bones back as the scene has them.- **Spring bones.** Spring bones give a skeleton secondary motion: a `SpringBone` on the root of a chain of bones (hair, a tail, a cord) makes everything below it a spring that lags the animation, falls with gravity, is pulled back to its animated pose, never stretches, and is kept out of `SpringBoneCollider` spheres and capsules. It runs in C++ in the engine, so it costs the same on every target: 300 chains of six bones step in 0.28 ms. Only the bones' rotations are written, and switching it off gives the animation's own back.diff --git a/desktop b/desktopindex 64cb4c582..07bf324e2 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 64cb4c582dcdf453d5700186e2a0fb74334d0ef3+Subproject commit 07bf324e238ecbd8d72aa6fef6e6b2d7faf532badiff --git a/pipeline/bin/estella.mjs b/pipeline/bin/estella.mjsindex 429fe8b5d..d07ececa8 100644--- a/pipeline/bin/estella.mjs+++ b/pipeline/bin/estella.mjs@@ -740,13 +740,16 @@ if (opts.command === 'import-model' || opts.command === 'import-gltf') {const root = opts.project ?? findProjectRoot(sourceDir);const projectRef = (abs) => path.relative(root, abs).split(path.sep).join('/');let characters = false;+ let springBones = false;try {- characters = JSON.parse(readFileSync(`${opts.source}.meta`, 'utf8')).importer?.characterMaterials === 'auto';+ const importerMeta = JSON.parse(readFileSync(`${opts.source}.meta`, 'utf8')).importer;+ characters = importerMeta?.characterMaterials === 'auto';+ springBones = importerMeta?.springBones === 'auto';} catch { /* no meta: the schema's default */ }const refs = root? { prefix: projectRef(dir) ? `${projectRef(dir)}/` : '',- external: (uri) => projectRef(path.resolve(sourceDir, uri)), characters }- : { characters };+ external: (uri) => projectRef(path.resolve(sourceDir, uri)), characters, springBones }+ : { characters, springBones };const { meshes, textures, nodes, animations, warnings } = await reader.readModelSource(new Uint8Array(readFileSync(opts.source)), stem,diff --git a/pipeline/src/assets/modelImport.ts b/pipeline/src/assets/modelImport.tsindex 13ac3ac5a..04cec07c2 100644--- a/pipeline/src/assets/modelImport.ts+++ b/pipeline/src/assets/modelImport.ts@@ -524,6 +524,8 @@ export interface ProductRefs {external?: (uri: string) => string;/** Give a skin, hair or eye material the engine's character shader instead of the Model shader (see {@link characterShading}). */characters?: boolean;+ /** Turn the bones a model names as hair chains, and the empties it names as colliders, into SpringBone and SpringBoneCollider (see {@link springBoneComponents}). */+ springBones?: boolean;}/** How the products go together. */@@ -895,6 +897,54 @@ function entity(id: string, name: string, parent: string | null,return { prefabEntityId: id, name, parent, children: [], visible: true, components };}+/** 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. */+const SPRING_COLLIDER = /^SBC_(Sphere|Capsule)_(.+?)_r(\d+)(?:_h(\d+))?$/;++/** How loose each kind of strand hangs. A fringe is held close, a ponytail swings; the numbers are the starting point an artist adjusts in Details, not a claim about hair. */+const HAIR_FEEL: Record<string, { stiffness: number; drag: number }> = {+ Ponytail: { stiffness: 0.06, drag: 0.35 },+ Temple: { stiffness: 0.12, drag: 0.4 },+ Fringe: { stiffness: 0.2, drag: 0.45 },+ Crest: { stiffness: 0.15, drag: 0.3 },+ Crown: { stiffness: 0.2, drag: 0.5 },+};++/**+ * Builds hair motion from names: a `Hair_<region>_<chain>_00` bone with a child is a SpringBone, an `SBC_` node a SpringBoneCollider,+ * and every chain is kept out of every collider the model has. Sizes are the model's metres times the import scale; gravity is Earth's.+ * Returns the counts it made.+ */+export function springBoneComponents(entities: PrefabEntityData[], scale = 1): { chains: number; colliders: number } {+ const colliders: string[] = [];+ for (const e of entities) {+ const m = SPRING_COLLIDER.exec(e.name);+ if (!m) continue;+ const radius = Number(m[3]) / 100;+ const capsule = m[1] === 'Capsule';+ if (capsule && m[4] === undefined) continue;+ e.components.push({ type: 'SpringBoneCollider', data: {+ shape: capsule ? 1 : 0, radius, ...(capsule ? { height: Number(m[4]) / 100 } : {}),+ } });+ colliders.push(e.prefabEntityId);+ }+ let chains = 0;+ for (const e of entities) {+ const m = HAIR_CHAIN_ROOT.exec(e.name);+ if (!m || e.children.length === 0) 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,+ gravity: { x: 0, y: -9.8 * scale, z: 0 },+ endLength: 0.04 * scale, radius: 0.005 * scale,+ colliders: [...colliders],+ } });+ chains++;+ }+ return { chains, colliders: colliders.length };+}+/*** The import's assembly: where each piece of geometry sits, and which image and* tint it is drawn with. The products are separate files and nothing else@@ -954,6 +1004,7 @@ export function assembleModelPrefab(name: string, meshes: ImportedMesh[],...lodComponent(mesh, refs)]));});}+ if (refs.springBones) springBoneComponents(entities, options.scale ?? 1);// The player rides the root, which is the entity a clip's childPaths are// resolved from — the same root the tracks were addressed against.if (options.timeline && entities[0]) {diff --git a/pipeline/src/project/importSettings.ts b/pipeline/src/project/importSettings.tsindex 895c4901e..830692927 100644--- a/pipeline/src/project/importSettings.ts+++ b/pipeline/src/project/importSettings.ts@@ -239,6 +239,15 @@ const MODEL: ImporterFieldSpec[] = [+ 'shaders instead of the Model shader, with the normal and occlusion/roughness maps bound to them, and hair '+ 'cut out and feathered by its alpha. A name is a convention, so check what it chose.',},+ {+ 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.',+ },{key: 'specularMap', label: 'Specular Map', type: 'enum', default: 'color',category: 'Import', advanced: true,diff --git a/pipeline/tests/spring-bone-import.test.ts b/pipeline/tests/spring-bone-import.test.tsnew file mode 100644index 000000000..e469f5113--- /dev/null+++ b/pipeline/tests/spring-bone-import.test.ts@@ -0,0 +1,83 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file spring-bone-import — hair chains and colliders found by the names a model already carries.+ *+ * A bone `Hair_<region>_<chain>_00` becomes a SpringBone, an empty `SBC_Sphere_...` / `SBC_Capsule_...` a SpringBoneCollider, and every chain+ * is wired to every collider the model has. Off, nothing is touched.+ */+import { describe, it, expect } from 'vitest';+import { assembleModelPrefab, type ImportedNode } from '../src/assets/modelImport';++let next = 0;+function node(name: string, children: ImportedNode[] = []): ImportedNode {+ return { index: next++, name, translation: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1], meshes: [], children };+}++/** A strand: Hair_<region>_<chain>_00 down through `joints` bones. */+function strand(region: string, chain: string, joints: number): ImportedNode {+ let below: ImportedNode[] = [];+ for (let j = joints - 1; j >= 0; j--) below = [node(`Hair_${region}_${chain}_${String(j).padStart(2, '0')}`, below)];+ return below[0]!;+}++function character(): ImportedNode[] {+ next = 0;+ return [node('Hips', [node('Spine', [node('Neck', [+ node('Head', [node('Hair_Root', [strand('Ponytail', '00', 5), strand('Temple_L', '01', 3), strand('Fringe', '02', 1)]),+ node('SBC_Sphere_Head_r9')]),+ node('SBC_Capsule_Neck_r5_h10'),+ node('SBC_Capsule_Broken_r5'),+ ])])])];+}++const springs = (nodes: ImportedNode[], on: boolean, scale?: number) => {+ const prefab = assembleModelPrefab('girl', [], { nodes, refs: { springBones: on }, ...(scale ? { scale } : {}) });+ const of = (type: string) => prefab.entities.filter(e => e.components.some(c => c.type === type));+ return { prefab, chains: of('SpringBone'), colliders: of('SpringBoneCollider') };+};++describe('spring bones from names', () => {+ it('does nothing when the setting is off', () => {+ const { chains, colliders } = springs(character(), false);+ expect(chains).toHaveLength(0);+ expect(colliders).toHaveLength(0);+ });++ it('makes a SpringBone at the root of each chain that has bones below it, and nowhere else', () => {+ const { chains } = springs(character(), true);+ expect(chains.map(e => e.name)).toEqual(['Hair_Ponytail_00_00', 'Hair_Temple_L_01_00']);+ });++ it('reads a collider name into a shape and a size in metres, and skips a capsule with no length', () => {+ const { colliders } = springs(character(), true);+ expect(colliders.map(e => e.name)).toEqual(['SBC_Sphere_Head_r9', 'SBC_Capsule_Neck_r5_h10']);+ const [head, neck] = colliders.map(e => e.components.find(c => c.type === 'SpringBoneCollider')!.data);+ expect(head).toEqual({ shape: 0, radius: 0.09 });+ expect(neck).toEqual({ shape: 1, radius: 0.05, height: 0.1 });+ });++ it('keeps every chain out of every collider, by the prefab ids the instance remaps', () => {+ const { chains, colliders } = springs(character(), true);+ const ids = colliders.map(e => e.prefabEntityId);+ for (const chain of chains) {+ const data = chain.components.find(c => c.type === 'SpringBone')!.data;+ expect(data.colliders).toEqual(ids);+ expect(ids.every(id => typeof id === 'string')).toBe(true);+ }+ });++ it('hangs a ponytail looser than a fringe would, and takes the model\'s metres into the import scale', () => {+ const { chains } = springs(character(), true, 100);+ const data = chains[0]!.components.find(c => c.type === 'SpringBone')!.data;+ expect(data.stiffness).toBeLessThan(0.1);+ expect((data.gravity as { y: number }).y).toBeCloseTo(-980);+ expect(data.endLength).toBeCloseTo(4);+ });++ it('does not take the Hair_Root bone or a non-root joint for a chain', () => {+ next = 0;+ const odd = [node('Head', [node('Hair_Root', [node('Hair_Ponytail_00_01', [node('Hair_Ponytail_00_02')])])])];+ expect(springs(odd, true).chains).toHaveLength(0);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex ea2d2f37d..69c837a74 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): a model's Spring Bones import setting builds hair chains and colliders from bone names":+ {"note":"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."},"feat(animation): a spring-bone chain takes a wind, with gusts that ripple down the strand":{"note":"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."},"feat(editor): a selected spring-bone chain and its colliders are drawn in the viewport, Details groups and counts them, and Preview FX simulates the chain":