Skip to content

Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor

Add cloth seams and tiers, tier exaggeration and pelvis twist

shinshin864ac5285a4952
diff --git a/.changeset/cloth-prototype.md b/.changeset/cloth-prototype.md
index 04062b6..25baeb9 100644
--- a/.changeset/cloth-prototype.md
+++ b/.changeset/cloth-prototype.md
@@ -13,3 +13,14 @@ Replace the unreleased cloth row-chain simulation with acceleration-driven colum
Derive cloth pendulum frequencies from source scale, column length and gravity, with optional millimetres-per-pixel `cloth.scale`. Interpret `swing` as a physical frequency multiplier and include vertical pivot acceleration in apparent gravity.
Add optional planted-rig spine stabilization and transfer dip, with delayed chest/head response and default five-second held weight transfers for rigs with `legs` (0.9-second smooth transition and 1.6-second hold per half-cycle, targeting `±0.7`). Replace cloth columns with physically coupled two-link pendulums and add optional `responseGain` for clearly labelled render-only cloth exaggeration. Preserve cloth-free, leg-free deformation and motion.
+
+Add optional source-space cloth `seams` and `tiers` with coupled N-link pendulums,
+length-proportional masses and modal damping. Add render-only relative bending
+exaggeration with `tierGain` and higher-mode damping control with
+`highModeDamping`, both defaulting to 1. Without seams or tiers, retain the existing
+two-link solver. Studio can edit seam and tier lines without rebuilding layers.
+
+Add optional `legs.twist` in degrees for pelvis yaw during weight transfer, partial
+shoulder counterturn and a frontal head with planted feet. Omitted or zero twist
+preserves the existing output; Studio exposes the setting in English, Japanese
+and Chinese.
diff --git a/docs/agent-guide.ja.md b/docs/agent-guide.ja.md
index c119bc6..c1441f8 100644
--- a/docs/agent-guide.ja.md
+++ b/docs/agent-guide.ja.md
@@ -156,6 +156,12 @@ uv run tools/build-sprites.py projects/<name>
```
受け入れた差分を `built/sprites/` に切り出します。もう一度ポーズを描き出すと(ステップ5)、`angry`、`sad`、`surprise` のフレームに表情の目と口が出ます。
+## 任意 — 衣服の縫い目と段
+
+布の `seams` は腰から裾へ、画像の左から右の順に置き、`tiers` は描かれたフリルや段の継ぎ目に沿って列を横切る線にします。各 tier は各列と1回だけ交わり、腰から裾の順に並ぶ必要があります。列を交差させたり、グリッドのセルを反転させたりしないでください。seams または tiers を指定するとNリンクの連成振り子を使い、省略すると従来の2リンクのままです。
+
+Studio の「衣服」で線を追加・削除し、頂点をドラッグして調整できます。辺をダブルクリックすると頂点を追加でき、Altを押しながら頂点をクリックすると削除できます。動きのグリッドの変更にはレイヤーの再構築は不要です。`tierGain` と `highModeDamping` は `1` から始めてください。前者は描画時だけ段の相対的な曲がりを強め、後者は最低次より高いモードの減衰を変えます。調整後は遅れ、行き過ぎ、収束を連続フレームで確認し、下書きを検証して保存してください。項目と検証条件の詳細は [Rig fields](rig-fields.md#optional-garments) を参照してください。
+
## 任意 — 脚の体重移動
`legs` があるリグでは、待機中の体重移動は5秒周期、目標値は `±0.7` です。
@@ -163,6 +169,8 @@ uv run tools/build-sprites.py projects/<name>
`legs` がないリグの出力は従来どおりです。プレビューの体重移動スライダーでは
`-1..1` の全範囲を確認できます。項目の詳細は [Rig fields](rig-fields.md#optional-planted-legs) を参照してください。
+腰のひねりを加える場合は、`twist` を3〜6度から試してください。指定範囲は `0..15` 度です。乗せ替えと保持中に、肩が一部逆向きに回り、頭の正面形状が保たれ、足と衣服の付け根が離れないことを確認してください。省略または `0` なら従来の出力を保ちます。Studio の「脚・体重移動」で調整でき、レイヤーの再構築は不要です。
+
## ステップ7 — 引き渡す
ユーザーに次のことを伝えてください。
diff --git a/docs/agent-guide.md b/docs/agent-guide.md
index 1263be4..bace0c6 100644
--- a/docs/agent-guide.md
+++ b/docs/agent-guide.md
@@ -221,6 +221,17 @@ skirt entry. Depth controls drawing order; parent controls motion, independently
For planted feet, optionally set `body.hip: { "shift": 20, "band": [900, 1400] }`,
adjusting these example coordinates to the illustration. `mesh.clothCell` defaults to 8.
+Optionally trace `seams` from waist to hem in left-to-right order and `tiers`
+across the columns, following the drawn folds and ruffle joins. Every tier must
+cross every column once, in waist-to-hem order, without crossing columns or
+inverting grid cells. Nonempty seams/tiers use coupled N-link pendulums; their
+absence retains the two-link solver. In Studio's **Cloth** inspector, add/delete
+lines and edit vertices (drag, double-click an edge to add, Alt-click a vertex to
+remove). Motion-grid edits do not require rebuilding layers. Start `tierGain` and
+`highModeDamping` at `1`; the former exaggerates relative bending only in the
+rendered grid, while the latter changes damping above the lowest mode. Review
+lag, overshoot and settling after each adjustment.
+
Validate the draft before rebuilding:
```sh
@@ -259,6 +270,12 @@ stay planted, knees must bend smoothly without reversing and the split must not
produce a tear or overlap. The solver preserves bone lengths in 3D, so their
projected lengths can shorten. Also check body sway and head movement together.
+For optional pelvis yaw, start `twist` at 3–6 degrees (allowed range `0..15`).
+Check that the shoulders partly counterturn, the head remains frontal, and feet
+and garment attachments stay connected during transfer and holds. Omitted or
+zero twist preserves the existing output. Studio exposes this under **Legs**;
+it does not require rebuilding layers.
+
In Studio, select **Legs**, align the pelvis and joint handles, and edit the split
vertices (double-click an edge to add a point; Alt-click a vertex to remove
it). Pause idle motion and test the **Weight shift** slider in both directions.
diff --git a/docs/agent-guide.zh.md b/docs/agent-guide.zh.md
index 90ccc86..2f02861 100644
--- a/docs/agent-guide.zh.md
+++ b/docs/agent-guide.zh.md
@@ -156,6 +156,12 @@ uv run tools/build-sprites.py projects/<name>
```
它会把通过检查的差分切成 `built/sprites/`。再次渲染姿态(第 5 步);`angry`、`sad` 和 `surprise` 帧会显示表情眼睛和嘴。
+## 可选 — 衣物纵缝与分层
+
+沿腰到下摆绘制 `seams`,按图像从左到右排列;沿画出的褶皱与层间接缝绘制横跨各列的 `tiers`。每条 tier 必须与每列恰好相交一次,交点按腰到下摆排列。列不能交叉,网格单元不能翻转。非空 seams 或 tiers 使用 N 链节耦合摆;省略时保留原来的双链节求解器。
+
+在 Studio 的“衣物”面板中添加或删除线,拖动顶点调整形状,双击边添加顶点,按住 Alt 点击顶点删除。运动网格的编辑不需要重建图层。`tierGain` 和 `highModeDamping` 从 `1` 开始:前者只在渲染时夸大链节间的相对弯曲,后者改变高于最低阶模态的阻尼。每次调整后逐帧检查滞后、过冲和收敛,验证草稿并保存。字段与验证规则见 [Rig fields](rig-fields.md#optional-garments)。
+
## 可选 — 双腿重心转移
带有 `legs` 的绑定在待机时以5秒为周期转移重心,目标值为 `±0.7`。
@@ -163,6 +169,8 @@ uv run tools/build-sprites.py projects/<name>
不含 `legs` 的绑定保持原来的输出。预览中的重心转移滑块可检查完整的 `-1..1` 范围。
字段说明见 [Rig fields](rig-fields.md#optional-planted-legs)。
+需要骨盆扭转时,可从 `twist` 为3–6度开始,允许范围为 `0..15` 度。检查重心转移与保持期间,肩部部分反向转动、头部保持正面形状、双脚固定且衣物连接处不断开。省略或设为 `0` 保留原输出。Studio 的“双腿”面板可调整此项,无需重建图层。
+
## 第 7 步 —— 交付
告诉用户:
diff --git a/docs/rig-fields.md b/docs/rig-fields.md
index efacac5..2eaeed8 100644
--- a/docs/rig-fields.md
+++ b/docs/rig-fields.md
@@ -162,13 +162,17 @@ Coordinates are source-image pixels, with x increasing right and y increasing do
| `cloth[*].outline` | Cutout polygon, at least three points, enclosing all ruffles and tails belonging to this garment. Changing it requires rebuilding layers. |
| `cloth[*].waist` | Upper attachment polyline, at least two points, from image-left to right. Follows the body or parent garment. |
| `cloth[*].hem` | Lower polyline, at least two points, from image-left to right. Cover the full width of the cloth, including projecting ruffles. |
+| `cloth[*].seams` | Optional waist-to-hem column polylines, ordered image-left to right; empty uses the waist/hem grid. Supply 2–64 lines with at least two points each and strictly increasing y. Nonempty seams override `columns`; lengths follow the source polylines. |
+| `cloth[*].tiers` | Optional array of 0–8 cross-column joint polylines, ordered waist to hem. Each line has at least two points and crosses every column exactly once. With N tiers there are N+1 coupled links; empty uses two links split at half the source length. |
| `cloth[*].scale` | Optional positive image scale, millimetres per source pixel. If omitted, infer 0.8m from mean hip-to-ankle length when `legs` exists; otherwise assume image height represents 1.6m. Supply this for cropped or unusually proportioned art. |
-| `cloth[*].columns`, `rows` | Integer grid node counts, both at least `2`; defaults `8`, `5`. |
+| `cloth[*].columns`, `rows` | Integer grid node counts, both at least `2`; defaults `8`, `5`. With seams/tiers, `rows` is a minimum: the grid includes every tier joint and at least two subdivisions per link. |
| `cloth[*].responseGain` | Positive rendered-response exaggeration; default `1` (physical). `1.6` amplifies cloth angles only. Child solvers use the unexaggerated parent grid, while visible attachments follow the exaggerated grid. |
+| `cloth[*].tierGain` | Positive render-only multiplier on each link's angle relative to the uppermost link; default `1`. Applies only when seams or tiers are nonempty. Changes visible bending without changing physical states, frequencies or child solver input. |
+| `cloth[*].highModeDamping` | Positive damping-ratio multiplier for modes above the lowest-frequency mode; default `1`. Applies only when seams or tiers are nonempty. Below `1` lets higher modes oscillate longer; the lowest mode keeps `0.25 × damping`. |
| `cloth[*].swing` | Positive multiplier on the physical pendulum frequency; default `1`. A value of `1` uses the source scale, column length and gravity. |
-| `cloth[*].stiffness` | Positive restoring-force multiplier; default `1`. Effective angular frequency is `√(g / (0.8L)) × swing × √stiffness`, with g and L in source-pixel units. |
-| `cloth[*].damping` | Positive damping multiplier; default `1`. Effective angular damping ratio is `0.25 × damping`; larger values suppress oscillations. |
-| `cloth[*].follow` | Column rigidity, `0..1`; default `0.85`. At `1` each of the two links is rigid; lower values add up to 10% within-link quadratic bend, without a delayed row chain. |
+| `cloth[*].stiffness` | Positive restoring-force multiplier; default `1`. Modal frequencies scale by `swing × √stiffness`, using effective link lengths of `0.8` times their source lengths. |
+| `cloth[*].damping` | Positive damping multiplier; default `1`. Base small-angle damping ratio is `0.25 × damping`; larger values suppress oscillations. `highModeDamping` can further scale higher modes in the seams/tiers solver. |
+| `cloth[*].follow` | Column rigidity, `0..1`; default `0.85`. At `1` each link is rigid; lower values add up to 10% within-link quadratic bend, without a delayed row chain. |
| `cloth[*].cohesion` | Integer smoothing passes over column angles and angular velocities, `0..8`; default `3`. |
| `cloth[*].wind` | Nonnegative coherent breeze strength as a fraction of `max`; default `0.05`, `0` disables wind. All columns receive the same phase. |
| `cloth[*].max` | Positive soft limit on grid displacement from the body-carried shape, px; default `20`. Limits rotation at the hem and reserves up to 10% for weak vertical bounce. Extrapolated mesh points outside the grid can move farther. |
@@ -178,13 +182,28 @@ Coordinates are source-image pixels, with x increasing right and y increasing do
| `body.hip.band` | Increasing source-y range over which sideways body travel fades to zero. Existing rigs without `hip` keep their original deformation. |
| `mesh.clothCell` | Positive integer garment render-mesh spacing, px; default `8`. Independent of cloth grid node counts. |
-Each column has two equal-length pendulum links, driven by the attachment's
-horizontal acceleration. Gravity is 9.80665m/s², converted to source pixels.
+Without seams or tiers, each column retains its existing two equal-length pendulum
+links. Nonempty seams or tiers use an N-link serial pendulum, with link lengths
+measured along each source column between tier intersections. Without explicit
+seams, columns interpolate the waist and hem. Validation rejects crossed or inverted
+grid cells, columns shorter than 1 source pixel, missing or repeated tier crossings,
+and tier intersections that are not ordered waist to hem. Adjacent intersections,
+including the endpoints, must be separated by at least 0.001 of the column length.
+
+Columns are driven by the attachment's horizontal acceleration, including motion
+from pelvis yaw. Gravity is 9.80665m/s², converted to source pixels.
Each link uses an effective length of 0.8 times its source length, between a uniform rigid strip
(2L/3) and a tip-heavy point mass (L), approximating a ruffled hem.
Upward attachment acceleration increases apparent gravity; source y points down,
so the implementation uses `g - accelerationY`. The angle is relative to the world
-rest shape, so the cloth retains its hanging orientation as the pelvis tilts. The two absolute angles are solved together using the equal-mass double-pendulum mass matrix, gravity and Coriolis forces. Link masses are proportional to their equal half-lengths. Rayleigh damping sets both small-angle modes to `0.25 × damping`; their frequencies follow the link lengths rather than hand-tuned rows. Each rendered link retains its length, with a small within-link bend controlled by `follow`.
+rest shape, so the cloth retains its hanging orientation as the pelvis tilts.
+Absolute link angles are solved together using the pendulum mass matrix, gravity
+and Coriolis forces, with endpoint masses proportional to link lengths. The legacy
+equal-length two-link solver uses Rayleigh damping for both small-angle modes.
+The seams/tiers solver uses modal damping to set every small-angle mode to
+`0.25 × damping`, with `highModeDamping` applied above the lowest mode. Frequencies
+follow link lengths rather than hand-tuned rows. Each rendered link retains its
+length, with a small within-link bend controlled by `follow`.
Each link endpoint retains its distance from that link's pivot; a separate weak, critically damped vertical response can change it slightly during vertical acceleration. Parent
accelerations are evaluated on the parent's unexaggerated physical grid; visible attachments follow its rendered grid. No additional
random samples are used.
@@ -194,6 +213,9 @@ tuning fields above. A `null` name applies to all garments; a string applies onl
that name. Updates take effect on the next simulation step without resetting velocity,
changing the rig or rebuilding layers. Invalid values or an unknown name throw a
`RangeError`. Studio edits update the rig and are included when saving it.
+In Studio's **Cloth** inspector, add or delete seam and tier lines, drag their
+vertices, double-click edges to add vertices, or Alt-click vertices to remove them.
+These motion-grid edits do not require rebuilding image layers; outline edits do.
The element exposes this method through `element.avatar` / `await element.ready`;
React exposes the same element through its ref and the runtime through `onLoad`.
@@ -207,6 +229,7 @@ supports the image-right leg. For rigs with `legs`, idle weight transfer uses a
| --- | --- |
| `legs.spine` | Optional stabilization fraction `0..1`, default `0.7`; the upper torso retains a small opposite pelvic inclination of `1 - spine`, blended through the spine. Chest and head follow serial springs rather than a rigid translating trunk. |
| `legs.bob` | Optional nonnegative extra pelvis dip in source px, default `2`; driven by transfer speed and returning to zero during a hold. Included in the planted-foot IK. |
+| `legs.twist` | Optional pelvis yaw limit in degrees, `0..15`; absent or `0` preserves the existing output. Weight transfer drives yaw, with a small residual during holds. Shoulders partly counterturn according to `spine`, the head stays frontal, and feet stay fixed. |
| `legs.pelvis` | Bone rotation centre `[x,y]` in source pixels. |
| `legs.shift` | Nonnegative sideways travel in px at full weight transfer. |
| `legs.tilt` | Nonnegative pelvic tilt in radians at full transfer; the free side lowers. |
@@ -228,8 +251,8 @@ Vertices at and below the higher ankle stay exactly fixed. Cloth attachments fol
the pelvis through the usual base deformer, with their existing lag.
Studio exposes the pelvis and joint handles, an editable split polyline, and the
-shift, tilt, bend and band fields under **Legs**. These edits recalculate weights
-without marking image layers stale. Pause idle motion to test the **Weight shift**
+shift, tilt, bend, band and optional twist fields under **Legs**. These edits
+recalculate weights without marking image layers stale. Pause idle motion to test the **Weight shift**
slider, then save the rig to persist the geometry and tuning.
`render-poses` adds `weight-left`, `weight-right` at `±0.6`, plus
diff --git a/packages/runtime/src/engine/cloth-grid.js b/packages/runtime/src/engine/cloth-grid.js
new file mode 100644
index 0000000..620928a
--- /dev/null
+++ b/packages/runtime/src/engine/cloth-grid.js
@@ -0,0 +1,56 @@
+/** Shared source-space grid for runtime skinning and Studio overlays. */
+export function sampleLine(line, fraction) {
+ const lengths = [0];
+ for (let i = 1; i < line.length; i++) lengths.push(lengths.at(-1) + Math.hypot(line[i][0] - line[i - 1][0], line[i][1] - line[i - 1][1]));
+ const distance = Math.max(0, Math.min(1, fraction)) * lengths.at(-1);
+ let i = 1; while (i < line.length - 1 && lengths[i] < distance) i++;
+ const t = (distance - lengths[i - 1]) / Math.max(1e-9, lengths[i] - lengths[i - 1]);
+ return line[i - 1].map((v, axis) => v + (line[i][axis] - v) * t);
+}
+export const lineLength = line => line.slice(1).reduce((s, p, i) => s + Math.hypot(p[0] - line[i][0], p[1] - line[i][1]), 0);
+function crossingFraction(seam, tier) {
+ let walked = 0; const total = lineLength(seam), hits = [];
+ for (let i = 1; i < seam.length; i++) {
+ const a = seam[i - 1], b = seam[i], dx = b[0] - a[0], dy = b[1] - a[1], length = Math.hypot(dx, dy);
+ for (let j = 1; j < tier.length; j++) {
+ const c = tier[j - 1], d = tier[j], ex = d[0] - c[0], ey = d[1] - c[1], det = dx * ey - dy * ex;
+ if (Math.abs(det) < 1e-9) continue;
+ const u = ((c[0] - a[0]) * ey - (c[1] - a[1]) * ex) / det;
+ const v = ((c[0] - a[0]) * dy - (c[1] - a[1]) * dx) / det;
+ if (u >= -1e-8 && u <= 1 + 1e-8 && v >= -1e-8 && v <= 1 + 1e-8) hits.push((walked + u * length) / total);
+ }
+ walked += length;
+ }
+ const unique = hits.filter((v, i) => hits.findIndex(w => Math.abs(v - w) < 1e-7) === i);
+ if (unique.length !== 1) throw new RangeError('Each tier must cross every column exactly once');
+ return unique[0];
+}
+export function clothGrid(c) {
+ const custom = !!(c.seams?.length || c.tiers?.length);
+ const cols = c.seams?.length || (c.columns ?? 8);
+ const seams = c.seams?.length ? c.seams : Array.from({ length: cols }, (_, k) => [sampleLine(c.waist, k / (cols - 1)), sampleLine(c.hem, k / (cols - 1))]);
+ if (custom && seams.some(s => lineLength(s) < 1)) throw new RangeError('Columns must have nonzero source length');
+ const joints = seams.map(line => [0, ...(c.tiers?.length ? c.tiers.map(t => crossingFraction(line, t)) : [0.5]), 1]);
+ for (const js of joints) if (js.some((v, i) => i > 0 && v - js[i - 1] < 0.001)) throw new RangeError('Tier intersections must be ordered from waist to hem, with nonzero links');
+ // Include seam bends and exact tier joints in every column's mesh rows.
+ const n = joints[0].length - 1;
+ const subdivisions = custom ? Math.max(2, Math.ceil(((c.rows ?? 5) - 1) / n)) : 0;
+ const rows = custom ? n * subdivisions + 1 : (c.rows ?? 5);
+ const rest = new Float64Array(rows * cols * 2), fractions = [];
+ for (let k = 0; k < cols; k++) {
+ fractions[k] = [];
+ for (let r = 0; r < rows; r++) {
+ const segment = custom ? Math.min(n - 1, Math.floor(r / subdivisions)) : 0;
+ const u = custom ? (r - segment * subdivisions) / subdivisions : r / (rows - 1);
+ const v = custom ? joints[k][segment] + (joints[k][segment + 1] - joints[k][segment]) * u : u;
+ fractions[k].push(v);
+ rest.set(sampleLine(seams[k], v), (r * cols + k) * 2);
+ }
+ }
+ if (custom) for (let r = 0; r < rows - 1; r++) for (let k = 0; k < cols - 1; k++) {
+ const a = (r * cols + k) * 2, b = a + 2, d = a + cols * 2, c = d + 2;
+ const cross = (i, j, l) => (rest[j] - rest[i]) * (rest[l + 1] - rest[i + 1]) - (rest[j + 1] - rest[i + 1]) * (rest[l] - rest[i]);
+ if (cross(a, b, c) <= 1e-6 || cross(a, c, d) <= 1e-6) throw new RangeError('Columns must be ordered left to right without crossing');
+ }
+ return { custom, cols, rows, rest, seams, joints, fractions, lengths: seams.map(lineLength), top: seams.map(s => s[0]) };
+}
diff --git a/packages/runtime/src/engine/cloth-pendulum.js b/packages/runtime/src/engine/cloth-pendulum.js
new file mode 100644
index 0000000..5b6c511
--- /dev/null
+++ b/packages/runtime/src/engine/cloth-pendulum.js
@@ -0,0 +1,62 @@
+// Absolute-angle serial pendulum with endpoint masses proportional to link length.
+// Existing two-link avatars retain their original solver in cloth.js.
+const dot = (a, b) => a.reduce((s, v, i) => s + v * b[i], 0);
+export function solve(matrix, rhs) {
+ const n = rhs.length, l = Array.from({ length: n }, () => Array(n).fill(0));
+ for (let i = 0; i < n; i++) for (let j = 0; j <= i; j++) {
+ let v = matrix[i][j]; for (let k = 0; k < j; k++) v -= l[i][k] * l[j][k];
+ l[i][j] = i === j ? Math.sqrt(Math.max(1e-18, v)) : v / l[j][j];
+ }
+ const y = [], x = [];
+ for (let i = 0; i < n; i++) y[i] = (rhs[i] - dot(l[i].slice(0, i), y)) / l[i][i];
+ for (let i = n - 1; i >= 0; i--) { let v = y[i]; for (let j = i + 1; j < n; j++) v -= l[j][i] * x[j]; x[i] = v / l[i][i]; }
+ return x;
+}
+function eigenSymmetric(input) {
+ const a = input.map(r => [...r]), n = a.length, u = a.map((_, i) => a.map((_, j) => +(i === j)));
+ for (let it = 0; it < 100 * n * n; it++) {
+ let p = 0, q = 1, largest = 0;
+ for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) if (Math.abs(a[i][j]) > largest) { largest = Math.abs(a[i][j]); p = i; q = j; }
+ if (largest < 1e-12) break;
+ const phi = 0.5 * Math.atan2(2 * a[p][q], a[q][q] - a[p][p]), c = Math.cos(phi), s = Math.sin(phi);
+ const app = a[p][p], aqq = a[q][q], apq = a[p][q];
+ for (let k = 0; k < n; k++) if (k !== p && k !== q) { const x = a[k][p], y = a[k][q]; a[k][p] = a[p][k] = c * x - s * y; a[k][q] = a[q][k] = s * x + c * y; }
+ a[p][p] = c*c*app - 2*s*c*apq + s*s*aqq; a[q][q] = s*s*app + 2*s*c*apq + c*c*aqq; a[p][q] = a[q][p] = 0;
+ for (let k = 0; k < n; k++) { const x = u[k][p], y = u[k][q]; u[k][p] = c*x-s*y; u[k][q] = s*x+c*y; }
+ }
+ return { values: a.map((r, i) => r[i]), vectors: u };
+}
+export function pendulumSystem(lengths, gravity, zeta, highModeDamping = 1) {
+ const mass = lengths.map((_, i) => lengths.slice(i).reduce((s, x) => s + x, 0));
+ const coefficient = lengths.map((li, i) => lengths.map((lj, j) => mass[Math.max(i, j)] * li * lj));
+ const stiffness = lengths.map((li, i) => gravity * mass[i] * li);
+ const rootK = stiffness.map(Math.sqrt);
+ const e = eigenSymmetric(coefficient.map((r, i) => r.map((v, j) => v / rootK[i] / rootK[j])));
+ // Modal generalization of Rayleigh: one alpha/beta pair cannot yield identical
+ // zeta at >2 distinct frequencies. This SPD matrix gives every linear mode zeta.
+ const firstMode = e.values.indexOf(Math.max(...e.values));
+ const damping = lengths.map((_, i) => lengths.map((_, j) => rootK[i] * rootK[j] * e.values.reduce((s, v, k) => s + e.vectors[i][k] * e.vectors[j][k] * 2 * zeta * Math.sqrt(v) * (k === firstMode ? 1 : highModeDamping), 0)));
+ return { lengths, mass, coefficient, stiffness, damping, frequencies: e.values.map(v => 1 / Math.sqrt(v) / (2 * Math.PI)).sort((a, b) => a - b), angles: lengths.map(() => 0), velocities: lengths.map(() => 0) };
+}
+export function pendulumEnergy(s, q = s.angles, v = s.velocities) {
+ let energy = s.stiffness.reduce((sum, k, i) => sum + k * (1 - Math.cos(q[i])), 0);
+ for (let i = 0; i < q.length; i++) for (let j = 0; j < q.length; j++) energy += 0.5 * s.coefficient[i][j] * Math.cos(q[i] - q[j]) * v[i] * v[j];
+ return energy;
+}
+export function stepPendulum(s, h, ax = 0, gravityRatio = 1) {
+ const q = s.angles, v = s.velocities;
+ const m = s.coefficient.map((row, i) => row.map((a, j) => a * Math.cos(q[i] - q[j])));
+ const rhs = q.map((angle, i) => dot(m[i], v) + h * (-s.stiffness[i] * gravityRatio * Math.sin(angle) - ax * s.mass[i] * s.lengths[i] * Math.cos(angle)
+ - s.coefficient[i].reduce((sum, a, j) => sum + a * Math.sin(angle - q[j]) * v[j] * v[j], 0)));
+ let nextV = solve(m.map((row, i) => row.map((a, j) => a + h * s.damping[i][j])), rhs);
+ let nextQ = q.map((a, i) => a + h * nextV[i]);
+ if (ax === 0 && gravityRatio === 1) {
+ const old = pendulumEnergy(s), potential = pendulumEnergy(s, nextQ, nextV.map(() => 0)), next = pendulumEnergy(s, nextQ, nextV);
+ // Suppress only numerical energy growth in the unforced system.
+ if (next > old) {
+ if (potential > old) { nextQ = [...q]; nextV = v.map(x => x * 0.999); }
+ else { const scale = Math.sqrt(Math.max(0, (old - potential) / Math.max(1e-30, next - potential))); nextV = nextV.map(x => x * scale); }
+ }
+ }
+ s.angles = nextQ; s.velocities = nextV;
+}
diff --git a/packages/runtime/src/engine/cloth-tuning.js b/packages/runtime/src/engine/cloth-tuning.js
index 900a556..9be4928 100644
--- a/packages/runtime/src/engine/cloth-tuning.js
+++ b/packages/runtime/src/engine/cloth-tuning.js
@@ -3,13 +3,16 @@ export const CLOTH_DEFAULTS = Object.freeze({
responseGain: 1, swing: 1, stiffness: 1, damping: 1, follow: 0.85, cohesion: 3, wind: 0.05, max: 20,
});
+// Optional tuning leaves the existing Studio default field list unchanged.
+export const CLOTH_OPTIONAL_DEFAULTS = Object.freeze({ tierGain: 1, highModeDamping: 1 });
+
/** Validate a partial override before applying it to any garment. */
export function checkClothTuning(tuning) {
if (!tuning || typeof tuning !== 'object' || Array.isArray(tuning)) throw new TypeError('Expected cloth tuning');
for (const [key, value] of Object.entries(tuning)) {
- if (!Object.hasOwn(CLOTH_DEFAULTS, key)) throw new RangeError(`Unknown cloth tuning: ${key}`);
+ if (!Object.hasOwn(CLOTH_DEFAULTS, key) && !Object.hasOwn(CLOTH_OPTIONAL_DEFAULTS, key)) throw new RangeError(`Unknown cloth tuning: ${key}`);
if (typeof value !== 'number' || !Number.isFinite(value)) throw new RangeError(`${key}: expected a finite number`);
- if (['responseGain', 'swing', 'stiffness', 'damping', 'max'].includes(key) && value <= 0) throw new RangeError(`${key}: must be positive`);
+ if (['tierGain', 'highModeDamping', 'responseGain', 'swing', 'stiffness', 'damping', 'max'].includes(key) && value <= 0) throw new RangeError(`${key}: must be positive`);
if (['follow', 'wind'].includes(key) && (value < 0 || (key === 'follow' && value > 1))) throw new RangeError(`${key}: out of range`);
if (key === 'cohesion' && (!Number.isInteger(value) || value < 0 || value > 8)) throw new RangeError('cohesion: expected an integer from 0 to 8');
}
diff --git a/packages/runtime/src/engine/cloth.js b/packages/runtime/src/engine/cloth.js
index f346b09..43cb292 100644
--- a/packages/runtime/src/engine/cloth.js
+++ b/packages/runtime/src/engine/cloth.js
@@ -2,7 +2,9 @@
// Link masses are proportional to their lengths; both halves have the same
// fabric density. Rendered links retain their source lengths.
-import { CLOTH_DEFAULTS, checkClothTuning } from './cloth-tuning.js';
+import { clothGrid, sampleLine } from './cloth-grid.js';
+import { pendulumSystem, stepPendulum } from './cloth-pendulum.js';
+import { CLOTH_DEFAULTS, CLOTH_OPTIONAL_DEFAULTS, checkClothTuning } from './cloth-tuning.js';
/** Evenly spaced points (by arc length) along a polyline. */
function resample(line, n) {
@@ -36,7 +38,8 @@ export function createCloth(engine, rig) {
const inertiaLength = 0.8;
const garments = (rig.cloth ?? []).map(c => {
- const cols = c.columns ?? 8, rows = c.rows ?? 5;
+ const grid = clothGrid(c);
+ const cols = grid.custom ? grid.cols : (c.columns ?? 8), rows = grid.custom ? grid.rows : (c.rows ?? 5);
const top = resample(c.waist, cols), bot = resample(c.hem, cols);
const rest = new Float64Array(rows * cols * 2);
for (let r = 0; r < rows; r++) for (let k = 0; k < cols; k++) {
@@ -44,10 +47,12 @@ export function createCloth(engine, rig) {
rest[i] = top[k][0] + (bot[k][0] - top[k][0]) * v;
rest[i + 1] = top[k][1] + (bot[k][1] - top[k][1]) * v;
}
+ if (grid.custom) rest.set(grid.rest);
return {
+ grid, pendulums: /** @type {ReturnType<typeof pendulumSystem>[]} */ ([]), systemKey: null,
c, gravity: 9.80665 / (c.scale === undefined ? metersPerPixel : c.scale / 1000),
- tuning: Object.fromEntries(Object.entries(CLOTH_DEFAULTS).map(([key, value]) => [key, c[key] ?? value])),
- cols, rows, rest, top, weights: top.map(([x, y]) => baseWeights(x, y, 0)),
+ tuning: Object.fromEntries(Object.entries({ ...CLOTH_DEFAULTS, ...CLOTH_OPTIONAL_DEFAULTS }).map(([key, value]) => [key, c[key] ?? value])),
+ cols, rows, rest, top: grid.custom ? grid.top : top, weights: (grid.custom ? grid.top : top).map(([x, y]) => baseWeights(x, y, 0)),
target: new Float64Array(rest.length), previous: null, pivotVelocity: new Float64Array(cols * 2),
angle: new Float64Array(cols), angularVelocity: new Float64Array(cols),
lowerAngle: new Float64Array(cols), lowerAngularVelocity: new Float64Array(cols),
@@ -75,16 +80,26 @@ export function createCloth(engine, rig) {
s -= (fx * ty - fy * tx) / det;
t -= (sx * fy - sy * fx) / det;
}
- const miss = Math.max(0, -s, s - 1) + Math.max(0, -t, t - 1);
+ let miss = Math.max(0, -s, s - 1) + Math.max(0, -t, t - 1);
+ if (g.grid.custom) {
+ const u = Math.max(0, Math.min(1, s)), v = Math.max(0, Math.min(1, t));
+ const px = ax * (1 - u) * (1 - v) + bx * u * (1 - v) + cx * u * v + dx * (1 - u) * v;
+ const py = ay * (1 - u) * (1 - v) + by * u * (1 - v) + cy * u * v + dy * (1 - u) * v;
+ miss = Math.hypot(px - x, py - y);
+ }
if (!best || miss < best.miss) best = { q, s, t, miss };
}
- best.s = Math.min(4, Math.max(-3, best.s));
- best.t = Math.min(4, Math.max(-3, best.t));
+ best.s = Math.min(g.grid.custom ? 1 : 4, Math.max(g.grid.custom ? 0 : -3, best.s));
+ best.t = Math.min(g.grid.custom ? 1 : 4, Math.max(g.grid.custom ? 0 : -3, best.t));
+ if (g.grid.custom) {
+ const point = [0, 0]; place(g.rest, best, point);
+ best.offset = [x - point[0], y - point[1]];
+ }
return best;
}
function place(p, loc, out) {
const { q, s, t } = loc, w = [(1 - s) * (1 - t), s * (1 - t), s * t, (1 - s) * t];
- out[0] = 0; out[1] = 0;
+ out[0] = loc.offset?.[0] ?? 0; out[1] = loc.offset?.[1] ?? 0;
for (let j = 0; j < 4; j++) { out[0] += p[q[j]] * w[j]; out[1] += p[q[j] + 1] * w[j]; }
return out;
}
@@ -119,7 +134,7 @@ export function createCloth(engine, rig) {
const a = [0, 0];
for (const g of garments) {
const { cols, rows, rest, target, out, angle, angularVelocity, lowerAngle, lowerAngularVelocity, bounce, bounceVelocity } = g;
- const { stiffness, damping, max, swing, follow, cohesion, wind, responseGain } = g.tuning;
+ const { stiffness, damping, max, swing, follow, cohesion, wind, responseGain, tierGain, highModeDamping } = g.tuning;
const gain = this.gain * (responseGain ?? 1);
const pivots = new Float64Array(cols * 2), renderPivots = new Float64Array(cols * 2), acceleration = new Float64Array(cols * 2);
for (let k = 0; k < cols; k++) {
@@ -145,6 +160,63 @@ export function createCloth(engine, rig) {
g.previous = pivots;
const frequencyMultiplier = swing * Math.sqrt(stiffness);
const verticalOmega = 2 * Math.PI * TUNE.bounceHz;
+ if (g.grid.custom) {
+ const key = `${frequencyMultiplier}:${damping}:${highModeDamping}`;
+ if (g.systemKey !== key) {
+ const previous = g.pendulums;
+ g.pendulums = g.grid.lengths.map((length, k) => {
+ const js = g.grid.joints[k];
+ const state = pendulumSystem(js.slice(1).map((v, j) => (v - js[j]) * length * inertiaLength), g.gravity * frequencyMultiplier ** 2, TUNE.zeta * damping, highModeDamping);
+ if (previous[k]) { state.angles = previous[k].angles; state.velocities = previous[k].velocities; }
+ return state;
+ });
+ g.systemKey = key;
+ }
+ // Resolve the highest normal mode as well as the shortest geometric link.
+ const highest = Math.max(...g.pendulums.flatMap(p => p.frequencies));
+ const count = Math.max(sub, Math.ceil(elapsed * highest * 32)), step = elapsed / count;
+ for (let n = 0; n < count; n++) {
+ const t = this.time + (n + 1) * step;
+ const breeze = (Math.sin(t * 1.1) * 0.6 + Math.sin(t * 2.3) * 0.4) * max * wind;
+ for (let k = 0; k < cols; k++) {
+ const ay = acceleration[k * 2 + 1], effectiveGravity = Math.max(g.gravity * 0.1, g.gravity - ay);
+ const ax = Math.max(-8 * g.gravity, Math.min(8 * g.gravity, acceleration[k * 2])) - effectiveGravity * breeze / g.grid.lengths[k];
+ stepPendulum(g.pendulums[k], step, ax, effectiveGravity / g.gravity);
+ bounceVelocity[k] += (-(verticalOmega ** 2) * bounce[k] - 2 * verticalOmega * bounceVelocity[k] - ay * 0.15) * step;
+ bounce[k] += bounceVelocity[k] * step;
+ }
+ }
+ for (let pass = 0; elapsed > 0 && pass < cohesion; pass++) for (const field of ['angles', 'velocities']) {
+ const previous = g.pendulums.map(p => [...p[field]]);
+ g.pendulums.forEach((p, k) => { p[field] = previous[k].map((v, j) => 0.5 * v + 0.25 * (previous[Math.max(0, k - 1)][j] + previous[Math.min(cols - 1, k + 1)][j])); });
+ }
+ const renderCustom = (destination, anchors, renderGain, bendGain = 1) => {
+ for (let k = 0; k < cols; k++) {
+ const js = g.grid.joints[k], seam = g.grid.seams[k], length = g.grid.lengths[k];
+ const vertical = max * 0.1 * Math.tanh(bounce[k] * renderGain / (max * 0.1));
+ const limit = 2 * Math.asin(Math.min(0.95, (max - Math.abs(vertical)) / (2 * length)));
+ const root = g.pendulums[k].angles[0];
+ const angles = g.pendulums[k].angles.map(v => {
+ const displayed = bendGain === 1 ? v : root + (v - root) * bendGain;
+ return limit * Math.tanh(displayed * renderGain / limit);
+ });
+ const joints = [Array.from(anchors.slice(k * 2, k * 2 + 2))];
+ for (let j = 0; j < angles.length; j++) {
+ const a = sampleLine(seam, js[j]), b = sampleLine(seam, js[j + 1]), x = b[0] - a[0], y = b[1] - a[1], theta = angles[j];
+ joints.push([joints[j][0] + x * Math.cos(theta) + y * Math.sin(theta), joints[j][1] - x * Math.sin(theta) + y * Math.cos(theta)]);
+ }
+ for (let r = 0; r < rows; r++) {
+ const v = g.grid.fractions[k][r]; let j = 0; while (j < angles.length - 1 && v > js[j + 1] + 1e-9) j++;
+ const a = sampleLine(seam, js[j]), b = sampleLine(seam, v), u = (v - js[j]) / (js[j + 1] - js[j]);
+ const theta = angles[j] * (1 - 0.1 * (1 - follow) * (1 - u)), x = b[0] - a[0], y = b[1] - a[1], i = (r * cols + k) * 2;
+ destination[i] = joints[j][0] + x * Math.cos(theta) + y * Math.sin(theta);
+ destination[i + 1] = joints[j][1] - x * Math.sin(theta) + y * Math.cos(theta) + vertical * v;
+ }
+ }
+ };
+ renderCustom(g.physicalOut, pivots, 1); renderCustom(out, renderPivots, gain, tierGain);
+ continue;
+ }
for (let n = 0; n < sub; n++) {
const t = this.time + (n + 1) * h;
// One coherent breeze for the whole sheet, never a travelling wave.
diff --git a/packages/runtime/src/engine/legs.js b/packages/runtime/src/engine/legs.js
index de44cab..7d2e00d 100644
--- a/packages/runtime/src/engine/legs.js
+++ b/packages/runtime/src/engine/legs.js
@@ -19,7 +19,7 @@ function boneMatrix(a, b, targetA, targetB) {
const transform = (p, m) => [m[0] * p[0] + m[1] * p[1] + m[4], m[2] * p[0] + m[3] * p[1] + m[5]];
/** Optional planted, two-bone legs. All coordinates are in source pixels. */
-export const LEG_DEFAULTS = Object.freeze({ spine: 0.7, bob: 2 });
+export const LEG_DEFAULTS = Object.freeze({ spine: 0.7, bob: 2, twist: 0 });
/** @param {{pivotX:number, pivotY:number, weightBand:number[]}|null} [head] */
export function createLegs(legs, body, head = null) {
@@ -34,12 +34,24 @@ export function createLegs(legs, body, head = null) {
const cross = dx * (leg.knee[1] - leg.hip[1]) - dy * (leg.knee[0] - leg.hip[0]);
return { ...leg, u, v, depth, lateral: cross / Math.hypot(dx, dy), side: Math.sign(cross) || (i ? 1 : -1) };
});
+ const hasTwist = (legs.twist ?? 0) > 0, maxYaw = (legs.twist ?? 0) * Math.PI / 180;
+ const pelvisRadius = Math.max(1, ...bones.map(b => Math.abs(b.hip[0] - legs.pelvis[0]) * 1.35));
+ const shoulderRadius = Math.max(body.chest.rx, ...body.shoulders.map(s => Math.abs(s.cx - body.chest.cx) + s.rx));
+ const yaw = [0, 0], yawVelocity = [0, 0]; let yawAcceleration = 0;
+ // Smooth front-surface depth: finite slope at the silhouette, unlike a sphere rim.
+ const yawOffset = (x, center, radius, angle) => {
+ const dx = x - center, front = Math.max(0, 1 - (dx / radius) ** 2);
+ return dx * (Math.cos(angle) - 1) + radius * 0.75 * front * front * Math.sin(angle);
+ };
const drive = [0, 0, 0], velocity = [0, 0, 0];
let bob = 0, bobVelocity = 0, lastWeight = 0, version = 0, previousVersion;
function step(P, dt) {
const ws = clamp(P.weightShift ?? 0, -1, 1);
const time = Math.min(Math.max(dt, 0), 0.05);
+ const previousYawVelocity = yawVelocity[0];
+ const targetYaw = hasTwist ? maxYaw * clamp(0.4 * ws + (time ? 0.6 * Math.tanh((ws - lastWeight) / time) : 0), -1, 1) : 0;
if (!time) {
+ if (hasTwist) { yaw.fill(targetYaw); yawVelocity.fill(0); yawAcceleration = 0; }
drive.fill(ws); velocity.fill(0); bob = 0; bobVelocity = 0;
} else {
const targetBob = (legs.bob ?? LEG_DEFAULTS.bob) * Math.min(1, Math.abs(ws - lastWeight) / time / 1.5);
@@ -52,10 +64,16 @@ export function createLegs(legs, body, head = null) {
velocity[i] += (24 * 24 * (target - drive[i]) - 2 * 0.9 * 24 * velocity[i]) * h;
drive[i] += velocity[i] * h;
}
+ if (hasTwist) for (let i = 0; i < 2; i++) {
+ const target = i ? yaw[0] : targetYaw;
+ yawVelocity[i] += (14 * 14 * (target - yaw[i]) - 2 * 0.95 * 14 * yawVelocity[i]) * h;
+ yaw[i] += yawVelocity[i] * h;
+ }
bobVelocity += (24 * 24 * (targetBob - bob) - 2 * 0.9 * 24 * bobVelocity) * h;
bob += bobVelocity * h;
}
}
+ if (hasTwist && time) yawAcceleration = (yawVelocity[0] - previousYawVelocity) / time;
lastWeight = ws; version++;
}
const ankleY = Math.min(...bones.map(b => b.ankle[1]));
@@ -65,7 +83,9 @@ export function createLegs(legs, body, head = null) {
if (ws === previousShift && bx === previousBody && version === previousVersion) return cached;
previousShift = ws; previousBody = bx; previousVersion = version;
const angle = -legs.tilt * ws, shift = legs.shift * ws + bx / 10 * (body.hip?.shift ?? legs.shift);
- const pelvisPoint = p => { const q = rotate(p, legs.pelvis, angle); q[0] += shift; return q; };
+ const pelvisYaw = hasTwist ? (version ? yaw[0] : maxYaw * 0.4 * ws) : 0;
+ const shoulderYaw = hasTwist ? -(1 - (legs.spine ?? LEG_DEFAULTS.spine)) * (version ? yaw[1] : pelvisYaw) : 0;
+ const pelvisPoint = p => { const q = rotate(p, legs.pelvis, angle); if (hasTwist) q[0] += yawOffset(p[0], legs.pelvis[0], pelvisRadius, pelvisYaw); q[0] += shift; return q; };
const hips = bones.map(b => pelvisPoint(b.hip));
// Only the free leg gets an extra inward offset. Quadratic onset keeps the
// neutral derivative continuous; most flexion goes towards the camera (z).
@@ -85,7 +105,7 @@ export function createLegs(legs, body, head = null) {
}
const solved = bones.map((b, i) => {
const hip = [hips[i][0], hips[i][1] + drop], ankle = b.ankle;
- if (!ws && !bx && !bob) return { hip: b.hip, knee: b.knee, ankle,
+ if (!ws && !bx && !bob && !pelvisYaw) return { hip: b.hip, knee: b.knee, ankle,
hip3: [...b.hip, 0], knee3: [...b.knee, b.depth], ankle3: [...ankle, 0],
upper: [1, 0, 0, 1, 0, 0], lower: [1, 0, 0, 1, 0, 0] };
const dx = ankle[0] - hip[0], dy = ankle[1] - hip[1], d = Math.hypot(dx, dy);
@@ -98,6 +118,7 @@ export function createLegs(legs, body, head = null) {
upper: boneMatrix(b.hip, b.knee, hip, knee), lower: boneMatrix(b.knee, b.ankle, knee, ankle) };
});
cached = { ws, bx, angle, shift, drop, bones: solved,
+ ...(hasTwist && { twist: { pelvis: pelvisYaw, shoulder: shoulderYaw, head: 0, acceleration: yawAcceleration } }),
trunk: { spine: drive[0], chest: drive[1], head: drive[2], bob } };
return cached;
}
@@ -120,7 +141,7 @@ export function createLegs(legs, body, head = null) {
}
function apply(p, _x, y, w, P) {
const F = frame(P);
- if (!F.ws && !F.bx && !F.trunk.chest && !F.trunk.head && !bob) return;
+ if (!F.ws && !F.bx && !F.trunk.chest && !F.trunk.head && !bob && !F.twist?.pelvis && !F.twist?.shoulder) return;
const pivot = [legs.pelvis[0] + F.shift, legs.pelvis[1] + F.drop];
const upper = 1 - smooth(Math.min(body.chest.cy, legs.pelvis[1] - 1), legs.pelvis[1], y);
const spineBlend = 1 - smooth(...legs.band, y);
@@ -145,6 +166,15 @@ export function createLegs(legs, body, head = null) {
const q = rotate(counter, center, correction);
counter[0] = q[0] + legs.shift * 1.12 * (F.trunk.head - F.trunk.chest) * weight; counter[1] = q[1];
}
+ if (hasTwist) {
+ const waistY = body.chest.cy + Math.max(40, (legs.pelvis[1] - body.chest.cy) * 0.5);
+ const blend = smooth(body.chest.cy, waistY, y);
+ const angle = F.twist.shoulder + (F.twist.pelvis - F.twist.shoulder) * blend;
+ const center = body.chest.cx + (legs.pelvis[0] - body.chest.cx) * blend;
+ const radius = shoulderRadius + (pelvisRadius - shoulderRadius) * blend;
+ const headRejection = head ? smooth(...head.weightBand, y) : 1;
+ counter[0] += yawOffset(_x, center, radius, angle) * headRejection;
+ }
let dx = 0, dy = 0;
bones.forEach((_b, i) => {
const f = F.bones[i], bw = w.perBone[i];
diff --git a/packages/runtime/src/rig/types.ts b/packages/runtime/src/rig/types.ts
index b534d7d..ad0cb78 100644
--- a/packages/runtime/src/rig/types.ts
+++ b/packages/runtime/src/rig/types.ts
@@ -27,6 +27,10 @@ export interface Accessory {
/** Optional garment that swings with the body (for example a skirt). */
export interface ClothTuning {
responseGain?: number;
+ /** Display-only exaggeration of link angles relative to the uppermost link. */
+ tierGain?: number;
+ /** Damping ratio multiplier for modes above the lowest mode (default 1). */
+ highModeDamping?: number;
swing: number;
stiffness: number;
damping: number;
@@ -42,6 +46,10 @@ export interface Cloth extends Partial<ClothTuning> {
outline: Point[];
waist: Point[];
hem: Point[];
+ /** Ordered waist-to-hem polylines; columns follow their source arc lengths. */
+ seams?: Point[][];
+ /** Ordered cross-column seam lines; each defines a pendulum joint. */
+ tiers?: Point[][];
columns?: number;
rows?: number;
behind?: boolean;
@@ -69,6 +77,8 @@ export interface Leg { hip: Point; knee: Point; ankle: Point }
export interface Legs {
spine?: number;
bob?: number;
+ /** Maximum pelvis yaw in degrees, 0..15; absent/zero preserves the old projection. */
+ twist?: number;
pelvis: Point;
shift: number;
tilt: number;
diff --git a/packages/runtime/src/rig/validate.ts b/packages/runtime/src/rig/validate.ts
index f51659d..280359f 100644
--- a/packages/runtime/src/rig/validate.ts
+++ b/packages/runtime/src/rig/validate.ts
@@ -1,3 +1,4 @@
+import { clothGrid } from '../engine/cloth-grid.js';
import type { Rig } from './types';
type Check = (value: unknown, path: string, errors: string[]) => void;
@@ -79,12 +80,12 @@ const schema = (draft: boolean) => object({
fingerYBand: band, pinBand: band }),
cloth: array(object({ name: string, outline: polygon, waist: line, hem: line,
columns: integer, rows: integer, stiffness: positive, damping: positive, max: positive,
- responseGain: positive, swing: positive, follow: unit, cohesion, wind: nonnegative,
+ tierGain: positive, highModeDamping: positive, responseGain: positive, swing: positive, follow: unit, cohesion, wind: nonnegative,
behind: (v, p, e) => { if (typeof v !== 'boolean') e.push(`${p}: expected a boolean`); },
- parent: string, scale: positive }, ['responseGain', 'columns', 'rows', 'stiffness', 'damping', 'max', 'swing', 'follow', 'cohesion', 'wind', 'behind', 'parent', 'scale'])),
- legs: object({ spine: unit, bob: nonnegative, pelvis: point, shift: nonnegative, tilt: nonnegative, bend: nonnegative,
+ parent: string, scale: positive, seams: array(line, 0, 64), tiers: array(line, 0, 8) }, ['tierGain', 'highModeDamping', 'seams', 'tiers', 'responseGain', 'columns', 'rows', 'stiffness', 'damping', 'max', 'swing', 'follow', 'cohesion', 'wind', 'behind', 'parent', 'scale'])),
+ legs: object({ spine: unit, bob: nonnegative, twist: nonnegative, pelvis: point, shift: nonnegative, tilt: nonnegative, bend: nonnegative,
band, split: line, left: object({ hip: point, knee: point, ankle: point }),
- right: object({ hip: point, knee: point, ankle: point }) }, ['spine', 'bob']),
+ right: object({ hip: point, knee: point, ankle: point }) }, ['spine', 'bob', 'twist']),
mesh: object({ baseCell: integer, fine: object({ x0: wholeNumber, x1: wholeNumber,
y0: wholeNumber, y1: wholeNumber, cell: integer }), handCell: integer,
tasselCell: integer, eyeBallCell: integer, eyeCell: integer, spriteCell: integer,
@@ -124,6 +125,7 @@ export function validateRig(value: unknown, options: { draft?: boolean } = {}):
}
const clothNames = new Set<string>();
if (rig.legs) {
+ if ((rig.legs.twist ?? 0) > 15) errors.push('rig.legs.twist: must be between 0 and 15 degrees');
const legs = rig.legs;
for (const side of ['left', 'right'] as const) {
const b = legs[side];
@@ -140,6 +142,11 @@ export function validateRig(value: unknown, options: { draft?: boolean } = {}):
errors.push(`rig.cloth[${i}].parent: must name an earlier cloth entry`);
if ((cloth.columns ?? 2) < 2 || (cloth.rows ?? 2) < 2)
errors.push(`rig.cloth[${i}]: columns and rows must be at least 2`);
+ if (cloth.seams?.length === 1) errors.push(`rig.cloth[${i}].seams: at least two columns required`);
+ if (cloth.seams?.length || cloth.tiers?.length) {
+ if (cloth.seams?.some(s => s.some((p, j) => j > 0 && p[1] <= s[j - 1][1]))) errors.push(`rig.cloth[${i}].seams: y must increase from waist to hem`);
+ try { clothGrid(cloth); } catch (error) { errors.push(`rig.cloth[${i}]: ${error instanceof Error ? error.message : String(error)}`); }
+ }
clothNames.add(cloth.name);
}
return errors;
diff --git a/src/editor/EditorCanvas.tsx b/src/editor/EditorCanvas.tsx
index a058509..5b83870 100644
--- a/src/editor/EditorCanvas.tsx
+++ b/src/editor/EditorCanvas.tsx
@@ -131,11 +131,14 @@ export function EditorCanvas({ rig, sourceUrl, visible, selected, onSelect, onCh
context.globalAlpha = 1;
}
for (const shape of shapes) {
+ if (shape.grid && (focusGroup !== 'cloth' || (selected !== 'cloth' && selected !== shape.item.replace('.grid', '') && !selected?.startsWith(shape.item.replace('.grid', '.') )))) continue;
if (shape.band && selected?.split('.')[0] !== shape.group) continue;
const active = focusGroup === shape.group;
context.globalAlpha = !focusGroup ? 0.6 : active ? 1 : 0.2;
context.strokeStyle = PART_COLORS[shape.group as PartGroup];
- context.lineWidth = active ? 2.5 : 1;
+ context.lineWidth = shape.grid ? 1 : active ? 2.5 : 1;
+ context.setLineDash(shape.grid ? [3, 4] : []);
+ if (shape.grid) context.strokeStyle = '#159ca3';
context.beginPath();
if (shape.kind === 'ellipse') {
const [x, y] = screen(shape.points[0], view);
@@ -149,6 +152,7 @@ export function EditorCanvas({ rig, sourceUrl, visible, selected, onSelect, onCh
}
context.stroke();
}
+ context.setLineDash([]);
for (const handle of handles) {
const [x, y] = screen(handle.point, view);
const active = focusGroup === handle.group;
diff --git a/src/editor/RigFields.tsx b/src/editor/RigFields.tsx
index 3be9b68..2cdfd1d 100644
--- a/src/editor/RigFields.tsx
+++ b/src/editor/RigFields.tsx
@@ -1,4 +1,5 @@
-import type { Rig } from 'mesh-avatar';
+import { clothGrid, sampleLine } from '../../packages/runtime/src/engine/cloth-grid.js';
+import type { Cloth, Point, Rig } from 'mesh-avatar';
import { getAt } from './model';
import { NumericField } from './NumericField';
import { useI18n } from './i18n';
@@ -6,7 +7,7 @@ import { LEG_DEFAULTS } from '../../packages/runtime/src/engine/legs.js';
import { CLOTH_DEFAULTS } from '../../packages/runtime/src/engine/cloth-tuning.js';
export function RigFields({ rig, path, scope = path, onChange }: {
- rig: Rig; path: string; scope?: string; onChange: (path: string, value: number) => void;
+ rig: Rig; path: string; scope?: string; onChange: (path: string, value: unknown) => void;
}) {
const { t, title } = useI18n();
const label = title(path.startsWith('legs.split') ? path : path === scope ? path.split('.').at(-1)! : path.slice(scope.length + 1));
@@ -24,7 +25,34 @@ export function RigFields({ rig, path, scope = path, onChange }: {
(/^cloth\.\d+$/.test(path) && Object.hasOwn(CLOTH_DEFAULTS, key)) || (path === 'legs' && Object.hasOwn(LEG_DEFAULTS, key))
? <NumericField key={key} path={`${path}.${key}`} label={title(key)} value={child as number} onChange={number => onChange(`${path}.${key}`, number)} />
: <RigFields key={key} rig={rig} path={`${path}.${key}`} scope={scope} onChange={onChange} />);
+
+ if (/^cloth\.\d+$/.test(path)) {
+ const cloth = value as Cloth;
+ const add = (kind: 'seams' | 'tiers') => {
+ if (kind === 'tiers') {
+ const lines = cloth.tiers ?? [];
+ let line: Point[];
+ try {
+ const grid = clothGrid(cloth);
+ line = grid.seams.map((seam: Point[], k: number) => sampleLine(seam, ((lines.length ? grid.joints[k].at(-2)! : 0) + 1) / 2) as Point);
+ } catch { return; }
+ onChange(`${path}.tiers`, [...lines, line]);
+ } else {
+ const lines = cloth.seams?.length ? cloth.seams : [0, 1].map(t => [sampleLine(cloth.waist, t), sampleLine(cloth.hem, t)] as Point[]);
+ if (!cloth.seams?.length) { onChange(`${path}.seams`, lines); return; }
+ let gap = 0; for (let i = 1; i < lines.length - 1; i++) if (lines[i + 1][0][0] - lines[i][0][0] > lines[gap + 1][0][0] - lines[gap][0][0]) gap = i;
+ const line = Array.from({ length: 5 }, (_, j) => { const a = sampleLine(lines[gap], j / 4), b = sampleLine(lines[gap + 1], j / 4); return a.map((v: number, k: number) => (v + b[k]) / 2) as Point; });
+ const next = [...lines]; next.splice(gap + 1, 0, line); onChange(`${path}.seams`, next);
+ }
+ };
+ return <details open><summary>{cloth.name}</summary><div className="fields">{children}
+ <div>{(['seams', 'tiers'] as const).map(kind => <button key={kind} type="button" onClick={() => add(kind)}>{title(kind === 'seams' ? 'addSeam' : 'addTier')}</button>)}</div>
+ </div></details>;
+ }
+ if (/^cloth\.\d+\.(seams|tiers)\.\d+$/.test(path)) {
+ const arrayPath = path.split('.').slice(0, -1).join('.'), lines = getAt(rig, arrayPath) as Point[][];
+ return <details open><summary>{label}</summary><button type="button" onClick={() => { const next = lines.filter((_, i) => i !== Number(path.split('.').at(-1))); onChange(arrayPath, arrayPath.endsWith('seams') && next.length < 2 ? [] : next); }}>{title('deleteLine')}</button><div className="fields">{children}</div></details>;
+ }
if (Array.isArray(value)) return <details open={path === 'eyes' || path === 'strands'}><summary>{label} ({value.length})</summary><div className="fields">{children}</div></details>;
- if (/^cloth\.\d+$/.test(path)) return <details open><summary>{(value as { name: string }).name}</summary><div className="fields">{children}</div></details>;
return <>{children}</>;
}
diff --git a/src/editor/i18n-zh.ts b/src/editor/i18n-zh.ts
index 96923e4..4358ff0 100644
--- a/src/editor/i18n-zh.ts
+++ b/src/editor/i18n-zh.ts
@@ -111,10 +111,11 @@ export const partsZh: Record<PartGroup, [string, string, string]> = {
};
export const fieldsZh: Record<string, string> = {
- spine: '脊柱稳定', bob: '换重心下沉 (px)', responseGain: '布料夸张倍率 (1 = 物理)',
+ twist: '骨盆扭转上限 (度)', spine: '脊柱稳定', bob: '换重心下沉 (px)', responseGain: '布料夸张倍率 (1 = 物理)',
pelvis: '骨盆', left: '图像左腿', right: '图像右腿', hip: '髋关节', knee: '膝盖', ankle: '脚踝',
shift: '横向位移 (px)', tilt: '骨盆倾角 (rad)', bend: '膝盖弯曲量 (px)',
scale: '图像比例 (mm/px)', swing: '频率倍率', stiffness: '刚度倍率', damping: '阻尼倍率', follow: '列刚性', cohesion: '横向平滑次数',
+ seams: '褶皱与缝线', tiers: '层间接缝', addSeam: '添加缝线', addTier: '添加层间接缝', deleteLine: '删除线条',
wind: '风力', waist: '腰线', hem: '下摆线', columns: '列数', rows: '行数', clothCell: '布料网格间距',
image: '原图', width: '宽度', height: '高度', name: '名称',
center: '中心', pivot: '支点', rx: '横向半径', ry: '纵向半径',
diff --git a/src/editor/i18n.tsx b/src/editor/i18n.tsx
index fd930df..f32a6af 100644
--- a/src/editor/i18n.tsx
+++ b/src/editor/i18n.tsx
@@ -146,12 +146,14 @@ const fieldText: Record<string, [string, string]> = {
pelvis: ['Pelvis', '骨盤'], left: ['Image-left leg', '画像左の脚'], right: ['Image-right leg', '画像右の脚'],
hip: ['Hip', '股関節'], knee: ['Knee', '膝'], ankle: ['Ankle', '足首'],
shift: ['Sideways travel (px)', '横の移動量 (px)'], tilt: ['Pelvic tilt (rad)', '骨盤の傾き (rad)'], bend: ['Knee flexion (px)', '膝の曲げ量 (px)'],
+ twist: ['Pelvis twist limit (degrees)', '腰のひねりの上限 (度)'],
spine: ['Spine stabilization', '背骨の安定化'], bob: ['Transfer dip (px)', '乗せ替え時の沈み (px)'],
responseGain: ['Cloth exaggeration (1 = physical)', '布の誇張倍率 (1 = 物理どおり)'],
scale: ['Image scale (mm/px)', '画像の縮尺 (mm/px)'],
swing: ['Frequency multiplier', '周波数の倍率'], stiffness: ['Stiffness multiplier', 'ばねの倍率'],
damping: ['Damping multiplier', '減衰の倍率'], follow: ['Column rigidity', '列の剛性'], cohesion: ['Smoothing passes', '列の平滑化回数'],
wind: ['Wind strength', '風の強さ'], waist: ['Waist line', '腰の線'], hem: ['Hem line', '裾の線'],
+ seams: ['Pleat / seam lines', 'プリーツ・縫い目'], tiers: ['Tier joints', '段の継ぎ目'], addSeam: ['Add seam line', '縫い目の線を追加'], addTier: ['Add tier joint', '段の継ぎ目を追加'], deleteLine: ['Delete line', '線を削除'],
columns: ['Columns', '列数'], rows: ['Rows', '行数'], clothCell: ['Cloth cell size', '布の格子幅'],
image: ['Source image', '元画像'],
center: ['Centre', '中心'], pivot: ['Pivot', '支点'], rx: ['Horizontal radius', '横の半径'], ry: ['Vertical radius', '縦の半径'],
diff --git a/src/editor/model.ts b/src/editor/model.ts
index 48ab913..bd880cd 100644
--- a/src/editor/model.ts
+++ b/src/editor/model.ts
@@ -1,3 +1,4 @@
+import { clothGrid } from '../../packages/runtime/src/engine/cloth-grid.js';
import { editorNumber, isIntegerField } from '../../packages/runtime/src/rig/numeric';
import type { Point, Rig } from 'mesh-avatar';
@@ -20,6 +21,7 @@ export interface Shape {
closed?: boolean;
editable?: boolean;
band?: boolean;
+ grid?: boolean;
radius?: Point;
angle?: number;
}
@@ -100,7 +102,7 @@ export function buildOverlay(rig: Rig): { handles: Handle[]; shapes: Shape[] } {
if (value.length >= 2 && value.every(p => Array.isArray(p) && p.length === 2 && p.every(v => typeof v === 'number'))) {
const points = value as Point[];
const closed = ['opening', 'roi', 'outline', 'background'].includes(key);
- const editable = closed || ['nodes', 'jaw', 'waist', 'hem', ...(group === 'legs' ? ['split'] : [])].includes(key);
+ const editable = /^cloth\.\d+\.(seams|tiers)\.\d+$/.test(path) || closed || ['nodes', 'jaw', 'waist', 'hem', ...(group === 'legs' ? ['split'] : [])].includes(key);
if (group !== 'cheeks') shapes.push({ item: path, group, kind: 'line', points, closed, editable });
points.forEach((point, index) => {
const item = group === 'strands' ? path.split('.').slice(0, 2).join('.') : path;
@@ -172,5 +174,12 @@ export function buildOverlay(rig: Rig): { handles: Handle[]; shapes: Shape[] } {
shapes.push({ item: `legs.${side}`, group: 'legs', kind: 'line', points: [rig.legs.pelvis, leg.hip, leg.knee, leg.ankle] });
}
}
+ rig.cloth?.forEach((c, index) => {
+ try {
+ const g = clothGrid(c), point = (r: number, k: number): Point => [g.rest[(r * g.cols + k) * 2], g.rest[(r * g.cols + k) * 2 + 1]];
+ for (let k = 0; k < g.cols; k++) shapes.push({ item: `cloth.${index}.grid`, group: 'cloth', kind: 'line', grid: true, points: Array.from({ length: g.rows }, (_, r) => point(r, k)) });
+ for (let r = 0; r < g.rows; r++) shapes.push({ item: `cloth.${index}.grid`, group: 'cloth', kind: 'line', grid: true, points: Array.from({ length: g.cols }, (_, k) => point(r, k)) });
+ } catch { /* Invalid in-progress lines retain their editable source handles. */ }
+ });
return { handles, shapes };
}
diff --git a/tests/cloth.test.ts b/tests/cloth.test.ts
index 4f2b21c..0a0b8f4 100644
--- a/tests/cloth.test.ts
+++ b/tests/cloth.test.ts
@@ -39,6 +39,13 @@ test('empty cloth is a no-op and default tuning matches explicit defaults', () =
const a = simulation(), b = simulation({ ...CLOTH_DEFAULTS, wind: 0 });
for (const s of [0, 20, -10, 0]) { a.step(s, 30); b.step(s, 30); }
expect(a.cloth.grids[0].nodes).toEqual(b.cloth.grids[0].nodes);
+ const emptyFields = simulation({}, [{ ...garment(), seams: [], tiers: [] }]);
+ const legacy = simulation(); emptyFields.step(5, 30); legacy.step(5, 30);
+ expect(emptyFields.cloth.grids[0].nodes).toEqual(legacy.cloth.grids[0].nodes);
+ // A short/degenerate legacy column was valid before optional topology existed.
+ const short = garment(); short.hem = structuredClone(short.waist);
+ const old = simulation({}, [short]); expect(validateRig(old.rig)).toEqual([]); old.step();
+ expect(old.garments[0].out.every(Number.isFinite)).toBe(true);
});
test('no-wind cloth converges to rest and is deterministic through motion and release', () => {
@@ -195,3 +202,60 @@ test('parent exaggeration does not feed back into child dynamics', () => {
expect(b.garments[g].physicalOut).toEqual(a.garments[g].physicalOut);
}
});
+
+test('seams follow source polylines; tiers define three unequal physical links', () => {
+ const part = { ...garment(), seams: [[[0, 0], [-5, 40], [0, 100]], [[100, 0], [110, 40], [100, 120]]], tiers: [[[-20, 25], [120, 25]], [[-20, 70], [120, 70]]] } as Cloth;
+ const s = simulation({ wind: 0, cohesion: 0 }, [part]); s.step();
+ const g = s.garments[0]; expect(g.cols).toBe(2); expect(g.pendulums[0].angles).toHaveLength(3);
+ expect(g.grid.lengths[1]).toBeGreaterThan(g.grid.lengths[0]);
+ for (const y of [25, 70]) expect(Math.min(...Array.from({ length: g.rows }, (_, r) => Math.abs(g.rest[(r * g.cols) * 2 + 1] - y)))).toBeLessThan(1e-10);
+ for (let i = 0; i < g.out.length; i++) expect(g.out[i]).toBeCloseTo(g.rest[i], 10);
+ const signature = layerSignature(s.rig); const handle = buildOverlay(s.rig).handles.find(h => h.id === 'cloth.0.tiers.0.0')!;
+ expect(handle.vertex?.closed).toBe(false); expect(layerSignature(moveHandle(s.rig, handle, [-21, 24]))).toBe(signature);
+ expect(validateRig(s.rig)).toEqual([]);
+ s.rig.cloth![0].tiers!.reverse(); expect(validateRig(s.rig).join()).toContain('ordered');
+});
+
+test('N-link modal damping dissipates free energy and resolves short links', async () => {
+ const { pendulumSystem, pendulumEnergy, stepPendulum } = await import('../packages/runtime/src/engine/cloth-pendulum.js');
+ for (const lengths of [[40, 40], [70, 25, 5], [45, 20, 15, 10]]) {
+ const s = pendulumSystem(lengths, 4903.325, 0.25); s.angles = lengths.map((_, i) => 0.12 * (i % 2 ? -1 : 1));
+ let energy = pendulumEnergy(s); const initial = energy;
+ for (let i = 0; i < 2400; i++) { stepPendulum(s, 1 / 480); const next = pendulumEnergy(s); expect(next).toBeLessThanOrEqual(energy + initial * 1e-12); energy = next; }
+ expect(energy).toBeLessThan(initial * 0.001); expect(s.angles.every(Number.isFinite)).toBe(true);
+ }
+ const s = pendulumSystem([40, 40], 4903.325, 0.25);
+ expect(s.frequencies[0]).toBeCloseTo(Math.sqrt(4903.325 / 40 * (2 - Math.SQRT2)) / (2 * Math.PI), 10);
+});
+
+test('curved custom grids keep extrapolated source vertices unchanged at rest', () => {
+ const c = { ...garment(), seams: [[[0, 0], [-10, 50], [0, 100]], [[100, 0], [110, 50], [100, 100]]] } as Cloth;
+ const s = simulation({}, [c]); const mesh = { rest: new Float64Array([-40, -20, 140, 120, 50, 60]), pos: new Float64Array(6) };
+ s.cloth.attach('skirt', mesh); s.step(); s.cloth.deform();
+ for (let i = 0; i < mesh.rest.length; i++) expect(mesh.pos[i]).toBeCloseTo(mesh.rest[i], 10);
+});
+
+test('tier gain exaggerates relative bending only and never changes physical/child states', () => {
+ const parts: Cloth[] = [{ ...garment(), tiers: [[[0, 30], [100, 30]], [[0, 70], [100, 70]]] }, { ...garment(), name: 'tail', parent: 'skirt', waist: [[0, 100], [100, 100]], hem: [[0, 200], [100, 200]] }];
+ const a=simulation({wind:0,cohesion:0},parts), b=simulation({wind:0,cohesion:0,tierGain:3},parts), explicit=simulation({wind:0,cohesion:0,tierGain:1,highModeDamping:1},parts);
+ let difference=0;
+ for(let f=0;f<120;f++) { const x=f<20?0:8; a.step(x);b.step(x);explicit.step(x);
+ for(let i=0;i<2;i++)expect(b.garments[i].physicalOut).toEqual(a.garments[i].physicalOut);
+ expect(explicit.garments[0].out).toEqual(a.garments[0].out);
+ const g=a.garments[0],h=b.garments[0];expect(h.out[2*g.cols]).toBeCloseTo(g.out[2*g.cols],12);
+ difference=Math.max(difference,...h.out.map((v,i)=>Math.abs(v-g.out[i])));
+ }
+ expect(difference).toBeGreaterThan(.1);
+ expect(()=>b.cloth.setTuning(null,{tierGain:0})).toThrow();expect(()=>b.cloth.setTuning(null,{highModeDamping:-1})).toThrow();
+});
+
+test('high-mode damping leaves mode one unchanged and reduces damping of the remaining modes', async () => {
+ const {pendulumSystem,solve}=await import('../packages/runtime/src/engine/cloth-pendulum.js');
+ const a=pendulumSystem([50,30,20],4903.325,.25), b=pendulumSystem([50,30,20],4903.325,.25,.48);
+ expect(b.frequencies).toEqual(a.frequencies);
+ // trace(M^-1 C) is the sum of 2*zeta*omega over all modal damping rates.
+ const rate=(s:typeof a)=>s.damping.reduce((sum:number,_row:number[],i:number)=>sum+solve(s.coefficient,s.damping.map((r:number[])=>r[i]))[i],0);
+ const omega:number[]=a.frequencies.map((f:number)=>f*2*Math.PI);
+ expect(rate(a)).toBeCloseTo(.5*omega.reduce((s,v)=>s+v,0),8);
+ expect(rate(b)).toBeCloseTo(.5*(omega[0]+.48*(omega[1]+omega[2])),8);
+});
diff --git a/tests/legs.test.ts b/tests/legs.test.ts
index 4c14a01..3cced5c 100644
--- a/tests/legs.test.ts
+++ b/tests/legs.test.ts
@@ -201,3 +201,39 @@ test('planted motion uses held transfers without consuming additional random val
expect(Math.max(...values)).toBeLessThan(0.701);
expect(values.slice(300).filter(v => Math.abs(v) > 0.69).length / 600).toBeGreaterThan(0.25);
});
+
+test('optional zero twist preserves every legacy point; yaw counterturns shoulders, stabilizes the head and keeps feet fixed', () => {
+ const body={...fixture.body,chest:{...fixture.body.chest,cy:450}},head={...fixture.head,pivotX:512,pivotY:300,weightBand:[250,320]};
+ const plain=createLegs(legs,body,head)!,zero=createLegs({...legs,twist:0},body,head)!,twisted=createLegs({...legs,twist:6},body,head)!;
+ let maximum=0;
+ for(let f=0;f<600;f++){
+ const P={weightShift:.7*Math.sin(f/60*Math.PI*2/5),bodyAngleX:0};
+ for(const m of [plain,zero,twisted])m.step(P,1/60);
+ const headOffsets:number[][]=[];
+ for(const y of [200,320,450,540,600,680,1000,1235,1400])for(const x of [420,512,600]){
+ const a=[x,y],b=[x,y],c=[x,y];plain.apply(a,x,y,plain.weights(x,y),P);zero.apply(b,x,y,zero.weights(x,y),P);twisted.apply(c,x,y,twisted.weights(x,y),P);expect(b).toEqual(a);if(y===200)headOffsets.push(c.map((v,i)=>v-a[i]));if(y>=1235)expect(c).toEqual([x,y]);
+ }
+ // The head may follow the IK pelvis correction, but yaw must not change its frontal shape.
+ for(const offset of headOffsets)for(let i=0;i<2;i++)expect(offset[i]).toBeCloseTo(headOffsets[0][i],10);
+ maximum=Math.max(maximum,Math.abs(twisted.frame(P).twist!.pelvis));expect(twisted.frame(P).twist!.head).toBe(0);
+ }
+ expect(maximum*180/Math.PI).toBeGreaterThan(3);expect(maximum*180/Math.PI).toBeLessThan(6.1);
+ for(let f=0;f<300;f++)twisted.step({weightShift:.7},1/60);
+ const F=twisted.frame({weightShift:.7});expect(F.twist!.pelvis*180/Math.PI).toBeCloseTo(1.68,2);expect(F.twist!.shoulder*F.twist!.pelvis).toBeLessThan(0);
+ const invalid=rigWithLegs();invalid.legs!.twist=16;expect(validateRig(invalid).join()).toContain('twist');
+});
+
+test('yaw angular acceleration drives a stationary-waist pendulum through projected anchors without an extra travelling-wave force', async () => {
+ const {createCloth}=await import('../packages/runtime/src/engine/cloth.js');
+ const r=rigWithLegs();Object.assign(r.legs!,{shift:0,tilt:0,bend:0,bob:0,twist:6});
+ r.cloth=[{name:'test',outline:[[430,580],[590,580],[600,750],[420,750]],waist:[[450,590],[570,590]],hem:[[430,750],[590,750]],columns:5,rows:5,wind:0,cohesion:0}];
+ const engine=createRig(r),{Cloth,garments}=createCloth(engine,r),cloth=new Cloth();let maximum=0,acceleration=0;
+ for(let f=0;f<600;f++){
+ const P={...defaults,weightShift:f<30?0:.7};engine.stepBody(P,1/60);cloth.step(P,1/60,phys);
+ maximum=Math.max(maximum,...garments[0].angle.map(Math.abs));acceleration=Math.max(acceleration,Math.abs(engine.legs!.frame(P).twist!.acceleration));
+ }
+ expect(acceleration).toBeGreaterThan(.1);expect(maximum).toBeGreaterThan(.0005);
+ expect(Math.max(...garments[0].angle.map(Math.abs))).toBeLessThan(.0001);
+ // Projection is symmetric in source depth; it creates one coherent drive, not column phase offsets.
+ expect(garments[0].angle[0]).toBeCloseTo(garments[0].angle[4],4);
+});