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(modeling): a hanging part swings as a ring of chains, kept out of the legs, and a pattern presses pleats into it
yhhbb42a2291d35
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5872a3fa5..cf264ecec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,8 @@ published separately; it ships inside the editor.- **Glyphs can be put on the atlas before they are shown.** The first page of a novel is hundreds of new characters, all landing in one frame. `preloadGlyphs(app, label, text, { budgetMs })` makes them ahead of time, a slice a frame, drawn as that `Text` will draw them, and returns `progress`, `done` and `release()`. On a Snapdragon 8 Elite a book's 2992 characters at 28 px took 145 ms over 25 frames with the worst frame at 9.5 ms, after which the first page's frame went from 49 to 11 ms and no page made a new glyph. Preloaded glyphs hold their atlas pages (4 MB each, a few hundred characters at that size) until `release()`.- **Voxel GI lights what the camera does not see, and bounces light more than once.** The cache now reads the sun's shadow map back into the world, so a surface the sun lights behind or beside the camera still sends light into the view. Each surface also gives off again the bounce light it received, so a corner or a floor in shade gets light that took two or more bounces to reach it. A ray now brings what it meets at full strength however far it went (it used to fade with distance, 40% at 4 m with 12 cm voxels). Each voxel is weighed by how much of it a surface covers, so a bright patch no longer lights like the whole voxel around it. Together these keep the result close to a path tracer's whatever the voxel size. In a sunlit test room the whole frame carries 0.95 of Cycles' light at the default size and 0.74 at 12 cm voxels; before, it was 0.54 at the default and darker the finer the grid. With the lit patch behind the camera, the walls went from no bounce light to 25–57%. A closed room the sun only lights from outside stays dark. Two inspector controls tune it: **Off-screen Sun Albedo** (the colour the shadow map cannot give, assumed) and **Multi-bounce**. A fine grid no longer drops every voxel: a count truncated by the cache's ageing had kept them below the two samples a ray asks for. The WebGL2 fallback does the same in its own passes: each voxel asks the sun's map whether a sunlit surface stands in it, and traces two rays through last frame's grid for the light it is given. In the test room it carries 1.00 of Cycles' light at the default size (it was 0.56) and 0.80 at 12 cm; with the lit patch behind the camera 0.20 (it was 0). Its voxel pass costs about 1.3 ms more at 720p on a desktop.+- **An AI building a model can dress it in clothes that swing.** `rig.drape` turns a skirt or a cape into a ring of chains that swing as the game runs, blended so it moves as one sheet, `rig.colliders` keeps it out of the legs, and a `pleats` pattern presses folds into it.+- **An AI building a model can make hair.** A `hair` step grows cards from a scalp, falling around the head, and writes the strand textures and a Hair material. `hairSway` gives them bones that swing as the game runs, and a character's `attach` carries the hair at its head joint, through saving and export.- **An AI building a model can make things see-through.** `material.alpha` is `cutout` for leaves and lace or `blend` for glass and gauze, and a `stain` can set alpha by a pattern or a shape, which a bake keeps on a thin mesh.diff --git a/desktop b/desktopindex 762927009..bf154e330 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 762927009edd921e909433e24832f0ba46dbd025+Subproject commit bf154e330df5d6dbc06495b1da1a70da61189fabdiff --git a/pipeline/src/modeling/displace.ts b/pipeline/src/modeling/displace.tsindex 6d59c5687..ec13ca9bc 100644--- a/pipeline/src/modeling/displace.ts+++ b/pipeline/src/modeling/displace.ts@@ -13,7 +13,7 @@ import { boundsOf, compact, dot, faceArea, faceNormal, normalize, selectFaces, timport { hash3 } from './organic';import { triangulateFace } from './triangulate';-export const DISPLACE_PATTERNS = ['bumps', 'wrinkles', 'cracks', 'scales', 'pores', 'ribs', 'weave', 'scratches'] as const;+export const DISPLACE_PATTERNS = ['bumps', 'wrinkles', 'cracks', 'scales', 'pores', 'ribs', 'weave', 'scratches', 'pleats'] as const;export type DisplacePattern = typeof DISPLACE_PATTERNS[number];export interface DisplaceParams {@@ -34,6 +34,8 @@ export interface DisplaceParams {warp?: number;/** How wide a line or dot is, as a share of a feature: cracks, pores, scratches. */width?: number;+ /** Folds round the y axis through `at`: pleats. Default 24. */+ count?: number;/** The axis ribs run across. Default y. */axis?: 'x' | 'y' | 'z';/** The same pattern on both sides of this axis, as a face wants. */@@ -186,6 +188,9 @@ function patternAt(p: DisplaceParams, x: number, y: number, z: number, n: Vec3):}case 'scratches':return scratches(x, y, z, seed, p.width ?? 0.12, n);+ case 'pleats':+ // A sawtooth softened at its peak: a pressed fold is sharp on one side, where a wave is even on both.+ return Math.pow(((Math.atan2(x, z) / (2 * Math.PI) + 1) * (p.count ?? 24)) % 1, 1.5) * 2 - 1;}}@@ -201,6 +206,7 @@ export function finestShare(p: DisplaceParams): number {case 'ribs': return 1 / 8;case 'weave': return 1 / 6;case 'scratches': return (p.width ?? 0.12) / 2;+ case 'pleats': return 1 / 8;}}diff --git a/pipeline/src/modeling/modelBake.ts b/pipeline/src/modeling/modelBake.tsindex c2bb2296e..ebc4e5dc9 100644--- a/pipeline/src/modeling/modelBake.ts+++ b/pipeline/src/modeling/modelBake.ts@@ -13,7 +13,7 @@ import { generateTangents } from '../assets/meshTangents';import { hairMaps, hairRig, hasCards, type HairMaps } from './hair';import { triangulateFace } from './triangulate';import { faceUvs } from './modelUv';-import { adjustWeights, bindMatrices, computeWeights, resolveJoints, shapeDeltas, type ControllerIk, type RigGoal, type RigJoint, type SkinWeights } from './rig';+import { adjustWeights, bindMatrices, computeWeights, drapeRig, resolveJoints, shapeDeltas, type ControllerIk, type RigGoal, type RigJoint, type RigSpring, type SkinWeights } from './rig';import type { NormalBakeReport } from './normalBake';import { buildPolyMesh, validateModelSource, type ModelSource, type StepReport } from './modelSource';import {@@ -60,7 +60,7 @@ export interface BakedModel {data: MeshData;report: ModelReport;/** Present on a rigged model. */- rig?: { joints: RigJoint[]; skin: SkinWeights; ik?: readonly ControllerIk[]; goals?: readonly RigGoal[] };+ rig?: { joints: RigJoint[]; skin: SkinWeights; ik?: readonly ControllerIk[]; goals?: readonly RigGoal[]; springs?: readonly RigSpring[] };/** Present on a model of hair cards: the textures they read, and where its chains start if it swings. */hair?: { maps: HairMaps; chainRoots?: number[] };/** Present where a source has shapes: three offsets per surface vertex, for each. */@@ -334,7 +334,9 @@ export function bakeModel(raw: unknown): BakedModel {let rig: BakedModel['rig'];if (source.rig) {const joints = resolveJoints(source.rig);- rig = { joints, skin: adjustWeights(mesh, joints, computeWeights(mesh, joints), source.rig.adjust ?? []), ik: source.controller?.ik ?? [], goals: source.rig.goals ?? [] };+ const found = adjustWeights(mesh, joints, computeWeights(mesh, joints), source.rig.adjust ?? []);+ const draped = source.rig.drape ? drapeRig(mesh, joints, found, source.rig.drape) : null;+ rig = { joints: draped?.joints ?? joints, skin: draped?.skin ?? found, ik: source.controller?.ik ?? [], goals: source.rig.goals ?? [], ...(draped ? { springs: draped.springs } : {}) };}const cards = hasCards(mesh);const swing = cards && source.hairSway ? hairRig(mesh, source.hairSway) : null;diff --git a/pipeline/src/modeling/modelSource.ts b/pipeline/src/modeling/modelSource.tsindex e6fbb13cf..97b320f29 100644--- a/pipeline/src/modeling/modelSource.ts+++ b/pipeline/src/modeling/modelSource.ts@@ -139,7 +139,7 @@ export const MODEL_OPS: Record<string, OpSpec> = {slice: { params: { faces: 'faces', axis: 'axis', at: 'number|numbers' }, required: ['axis', 'at'], run: ops.slice as OpSpec['run'], says: 'cuts faces across planes, making the seams a window sits between' },boolean: { params: { operation: 'operation', with: 'faces', from: 'faces', keep: 'boolean', tag: 'string', color: 'color' }, required: ['operation', 'with'], run: booleanOp as unknown as OpSpec['run'], says: 'cuts or joins closed solids: subtract `with` from `from` makes a real hole' },subdivide: { params: { faces: 'faces', levels: 'integer', crease: 'number' }, required: [], run: subdivide as unknown as OpSpec['run'], says: 'rounds whole shells into smooth surfaces, keeping edges sharper than `crease` degrees' },- displace: { params: { faces: 'faces', near: 'near', pattern: 'pattern', amplitude: 'number', scale: 'number', octaves: 'integer', seed: 'integer', stretch: 'vec3', warp: 'number', width: 'number', axis: 'axis', mirror: 'axis', detail: 'number' }, required: ['pattern', 'amplitude', 'scale'], run: ((mesh: PolyMesh, params: never) => displace(mesh, params)) as OpSpec['run'], says: 'pushes fine detail out of the surface along its normal, splitting faces as far as the pattern needs: bumps, wrinkles, cracks, scales, pores, ribs, weave or scratches' },+ displace: { params: { faces: 'faces', near: 'near', pattern: 'pattern', amplitude: 'number', scale: 'number', octaves: 'integer', seed: 'integer', stretch: 'vec3', warp: 'number', width: 'number', count: 'integer', axis: 'axis', mirror: 'axis', detail: 'number' }, required: ['pattern', 'amplitude', 'scale'], run: ((mesh: PolyMesh, params: never) => displace(mesh, params)) as OpSpec['run'], says: 'pushes fine detail out of the surface along its normal, splitting faces as far as the pattern needs: bumps, wrinkles, cracks, scales, pores, ribs, weave, scratches or pleats' },hair: { params: { faces: 'faces', count: 'integer', length: 'number', width: 'number', segments: 'integer', droop: 'number', comb: 'vec3', spread: 'number', uneven: 'number', wave: 'number', taper: 'number', seed: 'integer', color: 'color', tipColor: 'color', tag: 'string' }, required: ['faces', 'length'], run: hair as unknown as OpSpec['run'], says: 'grows cards of hair from these faces, falling around what is there; run it again for another layer, and only the cards are kept' },stain: { params: { faces: 'faces', near: 'near', hard: 'boolean', color: 'color', roughness: 'number', metallic: 'number', alpha: 'number', amount: 'number', pattern: 'pattern', scale: 'number', octaves: 'integer', seed: 'integer', stretch: 'vec3', warp: 'number', width: 'number', axis: 'axis', mirror: 'axis', threshold: 'number', softness: 'number', where: 'where', reach: 'number', facing: 'vec3', detail: 'number' }, required: [], run: ((mesh: PolyMesh, params: never) => stain(mesh, params)) as OpSpec['run'], says: 'lays colour, `roughness`, `metallic` or `alpha` over the surface by a pattern, by shape (`where`: cavity for dirt in what is sunken, edges for wear on what stands out), by which way it faces, or around a spot: pupils, moss, grime' },decimate: { params: { from: 'string', faces: 'faces', ratio: 'number', triangles: 'integer', error: 'number' }, required: [], run: decimate as unknown as OpSpec['run'], says: 'leaves fewer triangles over the same surface: `ratio` to keep or `triangles` to end with, stopping sooner if the surface would move more than `error` (default 0.02) of its size; `from` thins the surface as it stood after that step, before its fine detail' },diff --git a/pipeline/src/modeling/rig.ts b/pipeline/src/modeling/rig.tsindex b13f6cfb5..bfb51c7f9 100644--- a/pipeline/src/modeling/rig.ts+++ b/pipeline/src/modeling/rig.ts@@ -42,6 +42,10 @@ export interface RigGoal {}export interface RigSource {+ /** Hanging parts, as chains that swing. */+ drape?: DrapeSource[];+ /** Shapes on joints that swinging parts stay out of. */+ colliders?: RigCollider[];joints: readonly RigJointSource[];adjust?: readonly WeightAdjust[];goals?: readonly RigGoal[];@@ -287,6 +291,115 @@ export function computeWeights(mesh: PolyMesh, joints: readonly RigJoint[]): Ski}/** @p skin with @p adjusts applied, the rest of each touched vertex rescaled to still sum to one. */+/**+ * A hanging part, as bones: a skirt, a cape, a coat's tail. A ring of chains from its top edge to its hem, shared out by the way+ * round it. Every vertex blends between the two chains either side and the two bones above and below, so the part swings as one sheet.+ */+export interface DrapeSource {+ faces: FaceSelector;+ /** The joint it hangs from. */+ parent: string;+ /** Chains round it. Default 10. */+ chains?: number;+ /** Bones down each. Default 3. */+ bones?: number;+ /** How hard it goes back to where it was, 0..1. Default 0.12. */+ stiffness?: number;+ /** How much speed it loses each frame, 0..1. Default 0.35. */+ drag?: number;+ /** Names from `rig.colliders` it stays out of. */+ colliders?: string[];+}++/** A shape on a joint that swinging parts stay out of: a ball, or with `height` a capsule along the joint's own y. */+export interface RigCollider {+ name: string;+ joint: string;+ /** In the model's own space, where the joint rests. Default where the joint is. */+ at?: Vec3;+ radius: number;+ height?: number;+}++/** A chain that swings: the joint it starts at, which is held, and what moves it. */+export interface RigSpring {+ root: number;+ stiffness: number;+ drag: number;+ colliders: readonly string[];+}++/** Adds each drape's chains to the rig and binds its faces to them, leaving alone any vertex a face outside it also uses. */+export function drapeRig(mesh: PolyMesh, joints: readonly RigJoint[], skin: SkinWeights, drapes: readonly DrapeSource[]): { joints: RigJoint[]; skin: SkinWeights; springs: RigSpring[] } {+ const out: RigJoint[] = joints.map((j) => ({ ...j, children: [...j.children] }));+ const springs: RigSpring[] = [];+ const dominant = [...skin.dominant];+ drapes.forEach((drape, d) => {+ const hit = selectFaces(mesh, drape.faces);+ if (hit.length === 0) throw new Error(`rig.drape ${d}: \`faces\` ${JSON.stringify(drape.faces)} matched no face`);+ const chosen = new Set(hit);+ const held = new Uint8Array(mesh.positions.length);+ mesh.faces.forEach((face, f) => { if (!chosen.has(f)) for (const v of face.v) held[v] = 1; });+ const verts = [...new Set(hit.flatMap((f) => mesh.faces[f]!.v))];+ const parent = out.findIndex((j) => j.name === drape.parent);+ const chains = drape.chains ?? 10;+ const bones = drape.bones ?? 3;+ let [cx, cz, top, bottom] = [0, 0, -Infinity, Infinity];+ for (const v of verts) {+ const p = mesh.positions[v]!;+ cx += p[0]; cz += p[2];+ top = Math.max(top, p[1]); bottom = Math.min(bottom, p[1]);+ }+ cx /= verts.length; cz /= verts.length;+ const tall = Math.max(top - bottom, 1e-6);+ const width = (Math.PI * 2) / chains;+ const angleOf = (p: Vec3): number => (Math.atan2(p[0] - cx, p[2] - cz) + Math.PI * 2) % (Math.PI * 2);+ const firstBones = new Int32Array(chains).fill(-1);+ for (let k = 0; k < chains; k++) {+ const middle = (k + 0.5) * width;+ const mine = verts.filter((v) => {+ const gap = Math.abs(angleOf(mesh.positions[v]!) - middle);+ return Math.min(gap, Math.PI * 2 - gap) < width * 0.75;+ });+ if (mine.length === 0) continue;+ // Where this slice of the part is at each height: a cape has no vertices round the far side, and so no chain there.+ let up = parent;+ firstBones[k] = out.length;+ for (let b = 0; b <= bones; b++) {+ const want = b / bones;+ const near = [...mine].sort((p, q) => Math.abs((top - mesh.positions[p]![1]) / tall - want) - Math.abs((top - mesh.positions[q]![1]) / tall - want)).slice(0, Math.max(3, Math.ceil(mine.length / (bones * 2))));+ let sum: Vec3 = [0, 0, 0];+ for (const v of near) sum = add(sum, mesh.positions[v]!);+ const index = out.length;+ out.push({ name: `drape${d}.${k}.${b}`, at: scale(sum, 1 / near.length), parent: up, children: [] });+ dominant.push(0);+ out[up]!.children.push(index);+ up = index;+ }+ springs.push({ root: firstBones[k]!, stiffness: drape.stiffness ?? 0.12, drag: drape.drag ?? 0.35, colliders: drape.colliders ?? [] });+ }+ for (const v of verts) {+ if (held[v]) continue;+ const p = mesh.positions[v]!;+ const place = angleOf(p) / width - 0.5;+ const k0 = Math.floor(place);+ const blend = place - k0;+ let a = firstBones[(k0 + chains) % chains]!, b = firstBones[(k0 + 1) % chains]!;+ if (a < 0) a = b;+ if (b < 0) b = a;+ const along = Math.min(bones - 1e-6, ((top - p[1]) / tall) * bones);+ const i = Math.floor(along);+ const down = along - i;+ const pairs: [number, number][] = [[a + i, (1 - blend) * (1 - down)], [a + i + 1, (1 - blend) * down], [b + i, blend * (1 - down)], [b + i + 1, blend * down]];+ pairs.forEach(([joint, weight], n) => { skin.joints[v * 4 + n] = joint; skin.weights[v * 4 + n] = weight; });+ const most = pairs.reduce((x, y) => (y[1] > x[1] ? y : x));+ dominant[most[0]]!++;+ }+ });+ if (out.length > MAX_RIG_JOINTS) throw new Error(`rig.drape makes ${out.length} joints, and a rig holds at most ${MAX_RIG_JOINTS}: use fewer chains or bones`);+ return { joints: out, skin: { ...skin, dominant }, springs };+}+export function adjustWeights(mesh: PolyMesh, joints: readonly RigJoint[], skin: SkinWeights, adjusts: readonly WeightAdjust[]): SkinWeights {if (adjusts.length === 0) return skin;const outJoints = skin.joints.slice();@@ -484,7 +597,7 @@ const vec3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.evexport function checkRig(raw: unknown): string | null {const r = raw as { joints?: unknown };if (typeof raw !== 'object' || raw === null || !Array.isArray(r.joints)) return 'rig must be { joints: [{ name, at, parent?, mirror? }] }';- for (const key of Object.keys(raw)) if (!['joints', 'adjust', 'goals'].includes(key)) return `rig has an unknown field "${key}"; it takes joints, adjust, goals`;+ for (const key of Object.keys(raw)) if (!['joints', 'adjust', 'goals', 'drape', 'colliders'].includes(key)) return `rig has an unknown field "${key}"; it takes joints, adjust, goals`;for (const [i, j] of (r.joints as Record<string, unknown>[]).entries()) {if (typeof j !== 'object' || j === null) return `rig joint ${i} must be an object`;for (const key of Object.keys(j)) if (!['name', 'at', 'parent', 'mirror'].includes(key)) return `rig joint ${i} has an unknown field "${key}"; a joint takes name, at, parent, mirror`;@@ -501,6 +614,34 @@ export function checkRig(raw: unknown): string | null {return (e as Error).message;}const rig = raw as RigSource;+ const colliderNames = new Set<string>();+ if (rig.colliders !== undefined) {+ if (!Array.isArray(rig.colliders)) return 'rig.colliders must be an array of { name, joint, radius, at?, height? }';+ for (const c of rig.colliders as unknown as Record<string, unknown>[]) {+ for (const key of Object.keys(c)) if (!['name', 'joint', 'at', 'radius', 'height'].includes(key)) return `rig.colliders has an unknown field "${key}"; it takes name, joint, at, radius, height`;+ if (typeof c.name !== 'string' || !c.name) return 'a rig collider needs a name';+ if (!names.has(c.joint as string)) return `rig collider "${c.name}" names no joint "${String(c.joint)}"`;+ if (!(typeof c.radius === 'number' && c.radius > 0)) return `rig collider "${c.name}": radius must be positive`;+ if (c.height !== undefined && !(typeof c.height === 'number' && c.height >= 0)) return `rig collider "${c.name}": height must be 0 or more`;+ if (c.at !== undefined && !vec3(c.at)) return `rig collider "${c.name}": at must be [x, y, z]`;+ colliderNames.add(c.name);+ }+ }+ if (rig.drape !== undefined) {+ if (!Array.isArray(rig.drape)) return 'rig.drape must be an array of { faces, parent, chains?, bones?, stiffness?, drag?, colliders? }';+ for (const [i, d] of (rig.drape as unknown as Record<string, unknown>[]).entries()) {+ for (const key of Object.keys(d)) if (!['faces', 'parent', 'chains', 'bones', 'stiffness', 'drag', 'colliders'].includes(key)) return `rig.drape ${i} has an unknown field "${key}"; it takes faces, parent, chains, bones, stiffness, drag, colliders`;+ if (d.faces === undefined) return `rig.drape ${i} needs faces`;+ if (!names.has(d.parent as string)) return `rig.drape ${i} names no joint "${String(d.parent)}" as its parent`;+ if (d.chains !== undefined && !(Number.isInteger(d.chains) && (d.chains as number) >= 2 && (d.chains as number) <= 40)) return `rig.drape ${i}: chains must be 2..40`;+ if (d.bones !== undefined && !(Number.isInteger(d.bones) && (d.bones as number) >= 1 && (d.bones as number) <= 6)) return `rig.drape ${i}: bones must be 1..6`;+ for (const key of ['stiffness', 'drag'] as const) if (d[key] !== undefined && !(typeof d[key] === 'number' && (d[key] as number) >= 0 && (d[key] as number) <= 1)) return `rig.drape ${i}: ${key} must be 0..1`;+ if (d.colliders !== undefined) {+ if (!Array.isArray(d.colliders)) return `rig.drape ${i}: colliders must be names from rig.colliders`;+ for (const c of d.colliders) if (!colliderNames.has(c as string)) return `rig.drape ${i}: no collider "${String(c)}" in rig.colliders`;+ }+ }+ }if (rig.adjust !== undefined) {if (!Array.isArray(rig.adjust)) return 'rig.adjust must be an array';for (const a of rig.adjust as unknown as Record<string, unknown>[]) {@@ -932,7 +1073,7 @@ export function timelineOf(animation: AnimationSource, joints: readonly RigJoint*/const SWAY_COLLIDER = 'hairCollider';-export function prefabOf(name: string, meshPath: string, joints: readonly RigJoint[], cullBackfaces: boolean, firstClip: string | null, controller: string | null = null, extra: { goals?: readonly RigGoal[]; shapes?: number; normalMap?: string; texture?: string; material?: string; opaque?: boolean; attach?: readonly { joint: string; prefab: string }[]; sway?: { chainRoots: readonly number[]; stiffness?: number; drag?: number; collider?: { at: Vec3; radius: number } } } = {}): Record<string, unknown> {+export function prefabOf(name: string, meshPath: string, joints: readonly RigJoint[], cullBackfaces: boolean, firstClip: string | null, controller: string | null = null, extra: { goals?: readonly RigGoal[]; shapes?: number; normalMap?: string; texture?: string; material?: string; opaque?: boolean; attach?: readonly { joint: string; prefab: string }[]; springs?: readonly RigSpring[]; colliders?: readonly RigCollider[]; sway?: { chainRoots: readonly number[]; stiffness?: number; drag?: number; collider?: { at: Vec3; radius: number } } } = {}): Record<string, unknown> {const idOf = (i: number): string => `j${i}`;const goals = extra.goals ?? [];const entities: Record<string, unknown>[] = [{@@ -953,7 +1094,7 @@ export function prefabOf(name: string, meshPath: string, joints: readonly RigJoiconst rest = j.parent >= 0 ? sub(j.at, joints[j.parent]!.at) : j.at;entities.push({prefabEntityId: idOf(i), name: j.name, parent: j.parent >= 0 ? idOf(j.parent) : 'root',- children: [...j.children.map(idOf), ...goals.flatMap((g, k) => (g.parent === j.name ? [`g${k}`] : [])), ...(extra.attach ?? []).flatMap((a, k) => (a.joint === j.name ? [`a${k}`] : []))], visible: true,+ children: [...j.children.map(idOf), ...goals.flatMap((g, k) => (g.parent === j.name ? [`g${k}`] : [])), ...(extra.attach ?? []).flatMap((a, k) => (a.joint === j.name ? [`a${k}`] : [])), ...(extra.colliders ?? []).flatMap((c) => (c.joint === j.name ? [`collider:${c.name}`] : []))], visible: true,components: [{ type: 'Transform', data: { position: { x: rest[0], y: rest[1], z: rest[2] } } },// On a chain's first bone, which stays where it is: the ones below it swing.@@ -961,9 +1102,24 @@ export function prefabOf(name: string, meshPath: string, joints: readonly RigJoienabled: true, stiffness: extra.sway.stiffness ?? 0.08, drag: extra.sway.drag ?? 0.3,...(extra.sway.collider ? { colliders: [SWAY_COLLIDER] } : {}),} }] : []),+ ...(extra.springs ?? []).filter((s) => s.root === i).map((s) => ({ type: 'SpringBone', data: {+ enabled: true, stiffness: s.stiffness, drag: s.drag,+ ...(s.colliders.length ? { colliders: s.colliders.map((c) => `collider:${c}`) } : {}),+ } })),],});});+ for (const c of extra.colliders ?? []) {+ const joint = joints.find((j) => j.name === c.joint)!;+ const at = c.at ?? joint.at;+ entities.push({+ prefabEntityId: `collider:${c.name}`, name: c.name, parent: idOf(joints.indexOf(joint)), children: [], visible: true,+ components: [+ { type: 'Transform', data: { position: { x: at[0] - joint.at[0], y: at[1] - joint.at[1], z: at[2] - joint.at[2] } } },+ { type: 'SpringBoneCollider', data: { shape: c.height ? 1 : 0, radius: c.radius, ...(c.height ? { height: c.height } : {}) } },+ ],+ });+ }// Inside the prefab and not beside it in a scene, where a parent inside an instance has no way to be written down. Built in this model's// space, so its root goes back by as far as the joint it hangs from is out.(extra.attach ?? []).forEach((a, k) => {diff --git a/pipeline/tests/modeling-drape.test.ts b/pipeline/tests/modeling-drape.test.tsnew file mode 100644index 000000000..2928d404f--- /dev/null+++ b/pipeline/tests/modeling-drape.test.ts@@ -0,0 +1,130 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/** A hanging part as a ring of chains: where they run, how a vertex is shared between them, and what stays out of the way. */+import { describe, expect, it } from 'vitest';+import { bakeModel, validateModelSource, type BakedModel, type ModelStep } from '../src/modeling';+import { prefabOf } from '../src/modeling/rig';++const skirt: ModelStep = { op: 'lathe', profile: [[0.4, 1], [0.7, 0]], sides: 48, curve: 0, closed: false, tag: 'skirt' };+const body: ModelStep = { op: 'box', size: [0.3, 2, 0.3], at: [0, 1, 0], tag: 'body' };+const rig = { joints: [{ name: 'hips', at: [0, 1, 0] }, { name: 'top', at: [0, 2, 0], parent: 'hips' }, { name: 'thigh', at: [0.2, 0.9, 0], parent: 'hips' }] };+const dressed = (drape: Record<string, unknown> = {}, extra: Record<string, unknown> = {}): BakedModel => bakeModel({+ version: 1, rig: { ...rig, drape: [{ faces: 'skirt', parent: 'hips', chains: 8, bones: 3, ...drape }], ...extra }, steps: [body, skirt, { op: 'slice', faces: 'skirt', axis: 'y', at: [0.25, 0.5, 0.75] }, { op: 'weld' }],+});++describe('rig.drape', () => {+ it('adds a chain of joints per slice round it, hanging from its parent', () => {+ const m = dressed();+ expect(m.rig!.joints).toHaveLength(3 + 8 * 4);+ expect(m.rig!.springs).toHaveLength(8);+ for (const s of m.rig!.springs!) expect(m.rig!.joints[s.root]!.parent).toBe(0);+ });++ it('runs each chain from the top edge to the hem, flaring out as the skirt does', () => {+ const m = dressed();+ for (const s of m.rig!.springs!) {+ const [top, hem] = [m.rig!.joints[s.root]!.at, m.rig!.joints[s.root + 3]!.at];+ expect(top[1]).toBeGreaterThan(0.9);+ expect(hem[1]).toBeLessThan(0.1);+ expect(Math.hypot(hem[0], hem[2])).toBeGreaterThan(Math.hypot(top[0], top[2]) + 0.15);+ }+ });++ it('shares each skirt vertex out to whole weight, and no further than the bones either side', () => {+ const m = dressed();+ const { joints, weights } = m.rig!.skin;+ const first = 3;+ m.poly.positions.forEach((p, v) => {+ if (Math.hypot(p[0], p[2]) < 0.35) return;+ let sum = 0;+ for (let k = 0; k < 4; k++) {+ sum += weights[v * 4 + k]!;+ if (weights[v * 4 + k]! > 1e-4) expect(joints[v * 4 + k]).toBeGreaterThanOrEqual(first);+ }+ expect(sum).toBeCloseTo(1, 5);+ });+ });++ it('blends between neighbouring chains, so no seam opens down the skirt', () => {+ const m = dressed();+ const { joints, weights } = m.rig!.skin;+ let blended = 0;+ m.poly.positions.forEach((p, v) => {+ if (Math.hypot(p[0], p[2]) < 0.35) return;+ const chains = new Set<number>();+ for (let k = 0; k < 4; k++) if (weights[v * 4 + k]! > 0.05) chains.add(Math.floor((joints[v * 4 + k]! - 3) / 4));+ if (chains.size === 2) blended++;+ });+ expect(blended).toBeGreaterThan(m.poly.positions.length * 0.3);+ });++ it('leaves the body bound to the body', () => {+ const m = dressed();+ const { joints, weights } = m.rig!.skin;+ m.poly.positions.forEach((p, v) => {+ if (Math.hypot(p[0], p[2]) > 0.25) return;+ for (let k = 0; k < 4; k++) if (weights[v * 4 + k]! > 1e-4) expect(joints[v * 4 + k]).toBeLessThan(3);+ });+ });++ it('makes no chain where a cape has nothing', () => {+ const cape: ModelStep = { op: 'plane', size: [1, 1.2], at: [0, 1, -0.3], tag: 'cape' };+ const standing: ModelStep = { op: 'transform', faces: 'cape', rotate: [90, 0, 0], pivot: [0, 1, -0.3] };+ const m = bakeModel({ version: 1, rig: { ...rig, drape: [{ faces: 'cape', parent: 'hips', chains: 12 }] }, steps: [body, cape, standing, { op: 'slice', faces: 'cape', axis: 'y', at: [0.8, 1.2] }, { op: 'weld' }] });+ expect(m.rig!.springs!.length).toBeLessThan(12);+ expect(m.rig!.springs!.length).toBeGreaterThan(0);+ });++ it('stops at what a rig can hold', () => {+ expect(() => bakeModel({ version: 1, rig: { ...rig, drape: Array.from({ length: 8 }, () => ({ faces: 'skirt', parent: 'hips', chains: 40, bones: 6 })) }, steps: [body, skirt] })).toThrow(/a rig holds at most 256/);+ });++ it('refuses what cannot be meant', () => {+ const steps = [body, skirt];+ const withDrape = (drape: unknown, more: Record<string, unknown> = {}) => validateModelSource({ steps, rig: { ...rig, drape: [drape], ...more } });+ expect(() => withDrape({ faces: 'skirt' })).toThrow(/names no joint/);+ expect(() => withDrape({ parent: 'hips' })).toThrow(/needs faces/);+ expect(() => withDrape({ faces: 'skirt', parent: 'hips', chains: 1 })).toThrow(/chains must be 2..40/);+ expect(() => withDrape({ faces: 'skirt', parent: 'hips', stiffness: 2 })).toThrow(/stiffness must be 0..1/);+ expect(() => withDrape({ faces: 'skirt', parent: 'hips', colliders: ['leg'] })).toThrow(/no collider "leg"/);+ expect(() => withDrape({ faces: 'skirt', parent: 'hips', swing: 1 })).toThrow(/unknown field "swing"/);+ expect(() => bakeModel({ version: 1, rig: { ...rig, drape: [{ faces: 'nothing', parent: 'hips' }] }, steps })).toThrow(/matched no face/);+ });+});++describe('rig.colliders', () => {+ it('puts them under their joints in the prefab, and a drape names them', () => {+ const colliders = [{ name: 'leg', joint: 'thigh', radius: 0.2, height: 0.8, at: [0.2, 0.5, 0] as [number, number, number] }];+ const m = dressed({ colliders: ['leg'] }, { colliders });+ const prefab = prefabOf('dress', 'dress.esmesh', m.rig!.joints, true, null, null, { springs: m.rig!.springs!, colliders }) as { entities: { prefabEntityId: string; name: string; parent: string; children: string[]; components: { type: string; data: Record<string, unknown> }[] }[] };+ const collider = prefab.entities.find((e) => e.prefabEntityId === 'collider:leg')!;+ const thigh = prefab.entities.find((e) => e.name === 'thigh')!;+ expect(collider.parent).toBe(thigh.prefabEntityId);+ expect(thigh.children).toContain('collider:leg');+ expect(collider.components.find((c) => c.type === 'SpringBoneCollider')!.data).toEqual({ shape: 1, radius: 0.2, height: 0.8 });+ const position = collider.components.find((c) => c.type === 'Transform')!.data.position as { y: number };+ expect(position.y).toBeCloseTo(-0.4, 5);+ const springs = prefab.entities.filter((e) => e.components.some((c) => c.type === 'SpringBone'));+ expect(springs).toHaveLength(8);+ for (const s of springs) expect(s.components.find((c) => c.type === 'SpringBone')!.data.colliders).toEqual(['collider:leg']);+ });++ it('refuses what cannot be meant', () => {+ const withColliders = (c: unknown) => validateModelSource({ steps: [body], rig: { ...rig, colliders: [c] } });+ expect(() => withColliders({ name: 'a', joint: 'nope', radius: 1 })).toThrow(/names no joint "nope"/);+ expect(() => withColliders({ name: 'a', joint: 'thigh', radius: 0 })).toThrow(/radius must be positive/);+ expect(() => withColliders({ joint: 'thigh', radius: 1 })).toThrow(/needs a name/);+ expect(() => withColliders({ name: 'a', joint: 'thigh', radius: 1, size: 2 })).toThrow(/unknown field "size"/);+ });+});++describe('the pleats pattern', () => {+ it('makes as many folds as it is asked for, round the y axis', () => {+ const m = bakeModel({ version: 1, steps: [{ op: 'cylinder', radius: 1, height: 1, sides: 240, tag: 'tube' }, { op: 'delete', faces: { any: ['+y', '-y'] } }, { op: 'displace', pattern: 'pleats', amplitude: 0.05, scale: 1, count: 12, detail: 5 }] });+ const ring = m.poly.positions.filter((p) => p[1] > 0).sort((a, b) => Math.atan2(a[0], a[2]) - Math.atan2(b[0], b[2])).map((p) => Math.hypot(p[0], p[2]));+ let folds = 0;+ for (let i = 1; i < ring.length; i++) if (ring[i - 1]! - ring[i]! > 0.04) folds++;+ expect(folds).toBeGreaterThanOrEqual(11);+ expect(folds).toBeLessThanOrEqual(13);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 390f96023..c5dd3f0c8 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -3884,6 +3884,10 @@ export const NOTED = {{"note":"A material's normal and metal-rough maps are read as data in the editor's Play."},"fix(minigame): no mini-game module needs BigInt64Array, so WeChat DevTools boots the game":{"note":"A WeChat mini-game opens in WeChat DevTools."},+ "feat(modeling): a hanging part swings as a ring of chains, kept out of the legs, and a pattern presses pleats into it":+ {"note":"An AI building a model can dress it in clothes that swing."},+ "feat(mcp): model_write dresses a model in clothes that swing, and a check walks a skirt":+ {"note":"An AI building a model can dress it in clothes that swing."},"feat(modeling): a character wears another model at a joint, through saving and export":{"note":"An AI building a model can make hair."},"fix(mcp): a child added inside a prefab instance is warned about, and a check runs a real package of it all":