Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: extract the duplicated rigged-GLB fit-to-height math into fitModelToHeight (#4119)

[._.]/ Adam Eivy489c0d331a1b
diff --git a/.changelog/next/changed-issue-4119.md b/.changelog/next/changed-issue-4119.md
new file mode 100644
index 0000000000..d598ad2bb8
--- /dev/null
+++ b/.changelog/next/changed-issue-4119.md
@@ -0,0 +1 @@
+- Extracted the duplicated rigged-GLB fit-to-height math out of the Cyber Muse, mini-character, and CyberCity player avatars into a shared fitModelToHeight helper
diff --git a/client/src/components/city/PlayerAvatar.jsx b/client/src/components/city/PlayerAvatar.jsx
index 52ae16fb12..ab9552ecf3 100644
--- a/client/src/components/city/PlayerAvatar.jsx
+++ b/client/src/components/city/PlayerAvatar.jsx
@@ -5,6 +5,7 @@ import * as THREE from 'three';
import { useCityPalette } from './CityPaletteContext';
import { dampFactor, EYE_HEIGHT } from '../../utils/cityPlayerRig';
import { withInPlaceClips, inPlaceClipName } from '../../utils/animationClips';
+import { fitModelToHeight } from '../../utils/modelFit';
import useClonedGltf, { GltfPrimitive } from '../../hooks/useClonedGltf';
// The root-motion clip set + treadmill suffix are model-level facts about the bundled
// RobotExpressive GLB, so import the single source of truth rather than redeclaring it —
@@ -74,18 +75,7 @@ export default function PlayerAvatar({ rigRef }) {
obj.castShadow = false;
obj.receiveShadow = false;
});
- // Reset to the source transform before measuring so this is idempotent: under
- // StrictMode the mount effect runs twice on the same scene, and measuring an
- // already-fitted scene would compute scale≈1 and blow the model back up to source size.
- scene.scale.setScalar(1);
- scene.position.set(0, 0, 0);
- scene.updateMatrixWorld(true);
- const box = new THREE.Box3().setFromObject(scene);
- const size = box.getSize(new THREE.Vector3());
- const center = box.getCenter(new THREE.Vector3());
- const scale = TARGET_HEIGHT / Math.max(size.y, 1e-3);
- scene.scale.setScalar(scale);
- scene.position.set(-center.x * scale, -box.min.y * scale, -center.z * scale);
+ fitModelToHeight(scene, { targetHeight: TARGET_HEIGHT, feetOnGround: true });
}, [scene]);
// Precompute each rig.state → the concrete clip present on the loaded GLB (root-motion →
diff --git a/client/src/components/cos/MiniCharacterCoSAvatar.jsx b/client/src/components/cos/MiniCharacterCoSAvatar.jsx
index 9a61cd9ac9..8b446c8bb3 100644
--- a/client/src/components/cos/MiniCharacterCoSAvatar.jsx
+++ b/client/src/components/cos/MiniCharacterCoSAvatar.jsx
@@ -1,11 +1,11 @@
import { useRef, useMemo, useEffect, useState, Suspense } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
-import * as THREE from 'three';
import { AGENT_STATES } from './constants';
import CoSAvatarOrbitControls from './CoSAvatarOrbitControls';
import CoSBackgroundCamera from './CoSBackgroundCamera';
import CoSCanvasGuard from './CoSCanvasGuard';
import useClonedGltf, { GltfPrimitive } from '../../hooks/useClonedGltf';
+import { fitModelToHeight } from '../../utils/modelFit';
// Kenney Mini Characters (CC0) ship 32 named clips. We map the CoS agent
// states onto the most evocative ones. Each entry has a clip name plus a
@@ -26,6 +26,10 @@ const FALLBACK = { clip: 'idle', rot: 0.2, timeScale: 1.0 };
// the whole avatar down in frame (~210px per world unit at this camera).
const GROUND_Y = -1.4;
+// Kenney mini-characters are authored ~1.7 units tall already, but we normalize
+// so any dropped-in model fills the frame the same way.
+const TARGET_HEIGHT = 2.6;
+
// Variants shipped in data.reference/avatar/ and seeded into data/avatar/ by
// `npm run setup:data`. For these the "missing model" case means the seed
// hasn't run yet — not that the user must supply their own GLB.
@@ -41,23 +45,11 @@ function MiniCharacter({ state, speaking, variant }) {
const { scene, actions, names } = useClonedGltf(url);
// Fit the character into a consistent height regardless of source scale.
- // Kenney mini-characters are authored ~1.7 units tall already, but we
- // normalize so any dropped-in model fills the frame the same way.
+ // Recenter horizontally; rest the feet on the shared ground plane (GROUND_Y)
+ // rather than centering vertically so the character stands in frame with its
+ // feet on the shadow disc.
useEffect(() => {
- const box = new THREE.Box3().setFromObject(scene);
- const size = box.getSize(new THREE.Vector3());
- const center = box.getCenter(new THREE.Vector3());
- const targetHeight = 2.6;
- const scale = targetHeight / Math.max(size.y, 1e-3);
- scene.scale.setScalar(scale);
- // Recenter horizontally; rest the feet on the shared ground plane
- // (GROUND_Y) rather than centering vertically so the character stands
- // in frame with its feet on the shadow disc.
- scene.position.set(
- -center.x * scale,
- -box.min.y * scale + GROUND_Y,
- -center.z * scale,
- );
+ fitModelToHeight(scene, { targetHeight: TARGET_HEIGHT, feetOnGround: true, yOffset: GROUND_Y });
}, [scene]);
// Resolve the active clip for this state, falling back gracefully.
diff --git a/client/src/components/cos/MuseCoSAvatar.jsx b/client/src/components/cos/MuseCoSAvatar.jsx
index 5fb913b0c6..d7a1d5da1e 100644
--- a/client/src/components/cos/MuseCoSAvatar.jsx
+++ b/client/src/components/cos/MuseCoSAvatar.jsx
@@ -13,9 +13,12 @@ import CoSAvatarOrbitControls from './CoSAvatarOrbitControls';
import CoSBackgroundCamera from './CoSBackgroundCamera';
import CoSCanvasGuard from './CoSCanvasGuard';
import { withInPlaceClips } from '../../utils/animationClips';
+import { fitModelToHeight } from '../../utils/modelFit';
import useClonedGltf, { GltfPrimitive } from '../../hooks/useClonedGltf';
const MODEL_URL = '/api/avatar/model.glb';
+const TARGET_HEIGHT = 1.9; // world units — fills the fixed portrait frame
+const VERTICAL_LIFT = 0.05; // small upward nudge off the exact frame center
const FADE = 0.35; // crossfade seconds between state loops
const buildMuseAnimations = (animations) => (
withInPlaceClips(animations, MUSE_ROOT_MOTION_CLIPS, MUSE_IN_PLACE_SUFFIX)
@@ -51,18 +54,11 @@ function GLBAvatar({ state, speaking }) {
obj.frustumCulled = false;
});
- // Fit bounding box into a fixed height so different models render consistently.
- const box = new THREE.Box3().setFromObject(scene);
- const size = box.getSize(new THREE.Vector3());
- const center = box.getCenter(new THREE.Vector3());
- const targetHeight = 1.9;
- const scale = targetHeight / Math.max(size.y, 1e-3);
- scene.scale.setScalar(scale);
- scene.position.set(
- -center.x * scale,
- -center.y * scale + 0.05,
- -center.z * scale
- );
+ // Fit into a fixed height so different models render consistently. Centered
+ // vertically rather than resting its feet on the ground glow (the way the
+ // mini-character and CyberCity player do): this is a fixed portrait frame,
+ // so the body reads best balanced on the camera's look-at point.
+ fitModelToHeight(scene, { targetHeight: TARGET_HEIGHT, yOffset: VERTICAL_LIFT });
}, [scene]);
// --- Animation driving -------------------------------------------------
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 72574fb59e..9396ee637b 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -36,6 +36,7 @@ grep -i "what you want to do" client/src/utils/README.md
| `coalesce` | Trailing-edge coalescer: wraps a function so rapid calls collapse into one deferred invocation. |
| `easing` | `smoothstep` interpolation easing curve. |
| `hashString` | Deterministic string → 32-bit hash (stable colors, keys, seeds). |
+| `modelFit` | `fitModelToHeight(object, { targetHeight, feetOnGround, yOffset })` — normalize a loaded GLB to a fixed on-screen height and anchor it vertically, either by bounding-box center (portrait framing) or by its lowest point (a figure standing on a ground plane). Recenters x/z, guards a zero-height model against an infinite scale, skips a geometry-less object entirely, and resets to identity before measuring so a repeat call (StrictMode's double mount effect) converges instead of blowing the model back up. Call from an effect, never during render — a skinned mesh measures wrong before `useAnimations` binds the skeleton. |
| `sleep` | `sleep(ms)` — promise-returning `setTimeout` for retry backoffs and race timeouts. Use instead of re-declaring a local `delay`. |
| `urlNormalize` | `isUrl` detection, `normalizeUrl` (optional git/`requireDot` modes), `isHttpUrl` (explicit http(s) only — safe-href check), and `tiktokVideoId` / `tiktokEmbedSrc` (host-anchored TikTok video-id extraction + its Embed Player URL, so a reference embeds without loading TikTok's embed.js). |
| `platform` | `isMac` detection and `modKey` (⌘/Ctrl) for keyboard-shortcut display. |
diff --git a/client/src/utils/index.js b/client/src/utils/index.js
index 1c8fdc4d1f..6e804411f7 100644
--- a/client/src/utils/index.js
+++ b/client/src/utils/index.js
@@ -21,6 +21,7 @@ export * from './animationClips.js';
export * from './coalesce.js';
export * from './easing.js';
export * from './hashString.js';
+export * from './modelFit.js';
export * from './sleep.js';
export * from './urlNormalize.js';
export * from './platform.js';
diff --git a/client/src/utils/modelFit.js b/client/src/utils/modelFit.js
new file mode 100644
index 0000000000..855e740eef
--- /dev/null
+++ b/client/src/utils/modelFit.js
@@ -0,0 +1,44 @@
+import * as THREE from 'three';
+
+// Normalize a loaded model to a fixed on-screen height so different source GLBs
+// (authored at wildly different scales) frame identically.
+//
+// The two vertical anchorings the avatars need are made explicit rather than
+// left implicit per consumer:
+// feetOnGround: false → the model's bounding-box CENTER lands at `yOffset`
+// (a bust/portrait framing — the Cyber Muse avatar).
+// feetOnGround: true → the model's LOWEST point lands at `yOffset`
+// (a standing figure on a ground plane / shadow disc).
+// `x`/`z` are always recentered on the bounding-box center.
+//
+// Call this from an effect, never during render: the bounding box is only
+// correct after `useAnimations` has bound the skeleton/mixer — measuring a
+// skinned mesh during render sees an unposed rig and yields a wildly wrong size.
+//
+// The transform is absolute, and the object is reset to identity before
+// measuring, so repeat calls on the same object converge on the same result
+// (StrictMode runs mount effects twice; without the reset the second pass would
+// measure an already-fitted model, compute scale ≈ 1, and blow it back up to
+// source size). GLTFLoader's scene root is a plain identity-transform Group, so
+// resetting it discards nothing the model authored.
+export function fitModelToHeight(object, { targetHeight, feetOnGround = false, yOffset = 0 } = {}) {
+ object.scale.setScalar(1);
+ object.position.set(0, 0, 0);
+ object.updateMatrixWorld(true);
+
+ const box = new THREE.Box3().setFromObject(object);
+ // An object carrying no renderable geometry measures as an EMPTY box, whose
+ // `min` is +Infinity — fitting it would fling the object to -Infinity and
+ // take any sibling content in the group with it. Leave it at identity.
+ if (box.isEmpty()) return;
+
+ const size = box.getSize(new THREE.Vector3());
+ const center = box.getCenter(new THREE.Vector3());
+ // Guard the divide so a flat (zero-height) model yields a finite scale instead
+ // of Infinity, which would drop the whole object out of the scene graph.
+ const scale = targetHeight / Math.max(size.y, 1e-3);
+
+ object.scale.setScalar(scale);
+ const anchorY = feetOnGround ? -box.min.y : -center.y;
+ object.position.set(-center.x * scale, anchorY * scale + yOffset, -center.z * scale);
+}
diff --git a/client/src/utils/modelFit.test.js b/client/src/utils/modelFit.test.js
new file mode 100644
index 0000000000..1b9ead0952
--- /dev/null
+++ b/client/src/utils/modelFit.test.js
@@ -0,0 +1,100 @@
+import { describe, it, expect } from 'vitest';
+import * as THREE from 'three';
+import { fitModelToHeight } from './modelFit.js';
+
+// Build a scene-root Group (what GLTFLoader hands back) holding one box mesh of
+// the given dimensions, offset so the box sits at an arbitrary place in space.
+// Assertions below check where the box lands in WORLD space, not the formula.
+function makeModel({ width = 1, height = 4, depth = 1, offset = [0, 0, 0] } = {}) {
+ const root = new THREE.Group();
+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(width, height, depth));
+ mesh.position.set(...offset);
+ root.add(mesh);
+ return root;
+}
+
+// Where the model's bounding box actually ends up once the fit is applied.
+function worldBox(object) {
+ object.updateMatrixWorld(true);
+ return new THREE.Box3().setFromObject(object);
+}
+
+describe('fitModelToHeight', () => {
+ it('scales the model so its rendered height matches targetHeight', () => {
+ const model = makeModel({ height: 8 });
+ fitModelToHeight(model, { targetHeight: 2 });
+ const box = worldBox(model);
+ expect(box.getSize(new THREE.Vector3()).y).toBeCloseTo(2, 5);
+ });
+
+ it('scales uniformly, preserving the source aspect ratio', () => {
+ const model = makeModel({ width: 3, height: 6, depth: 1.5 });
+ fitModelToHeight(model, { targetHeight: 3 });
+ const size = worldBox(model).getSize(new THREE.Vector3());
+ expect(size.x / size.y).toBeCloseTo(3 / 6, 5);
+ expect(size.z / size.y).toBeCloseTo(1.5 / 6, 5);
+ });
+
+ it('centers the model vertically by default', () => {
+ const model = makeModel({ height: 4, offset: [7, 12, -3] });
+ fitModelToHeight(model, { targetHeight: 2 });
+ const center = worldBox(model).getCenter(new THREE.Vector3());
+ expect(center.x).toBeCloseTo(0, 5);
+ expect(center.y).toBeCloseTo(0, 5);
+ expect(center.z).toBeCloseTo(0, 5);
+ });
+
+ it('rests the lowest point on y=0 with feetOnGround, still recentering x/z', () => {
+ const model = makeModel({ height: 4, offset: [7, 12, -3] });
+ fitModelToHeight(model, { targetHeight: 2, feetOnGround: true });
+ const box = worldBox(model);
+ expect(box.min.y).toBeCloseTo(0, 5);
+ const center = box.getCenter(new THREE.Vector3());
+ expect(center.x).toBeCloseTo(0, 5);
+ expect(center.z).toBeCloseTo(0, 5);
+ });
+
+ it('lifts the anchor by yOffset — the centered anchor moves the center', () => {
+ const model = makeModel({ height: 4 });
+ fitModelToHeight(model, { targetHeight: 2, yOffset: 0.05 });
+ expect(worldBox(model).getCenter(new THREE.Vector3()).y).toBeCloseTo(0.05, 5);
+ });
+
+ it('lifts the anchor by yOffset — the feet anchor moves the ground plane', () => {
+ const model = makeModel({ height: 4 });
+ fitModelToHeight(model, { targetHeight: 2.6, feetOnGround: true, yOffset: -1.4 });
+ expect(worldBox(model).min.y).toBeCloseTo(-1.4, 5);
+ });
+
+ // Measuring an already-fitted object would compute scale ≈ 1 and blow the
+ // model back up to source size, so every extra call must land in the same
+ // place — including the second call StrictMode makes on the same scene.
+ // Checked at each of the first four calls: a fit that merely oscillates
+ // between two placements would pass a check made only on an odd call count.
+ it.each([2, 3, 4])('lands in the same place on call %i as on the first', (calls) => {
+ const model = makeModel({ height: 8, offset: [2, 5, 1] });
+ fitModelToHeight(model, { targetHeight: 1.9, feetOnGround: true });
+ const first = worldBox(model).clone();
+ for (let i = 1; i < calls; i += 1) {
+ fitModelToHeight(model, { targetHeight: 1.9, feetOnGround: true });
+ }
+ const after = worldBox(model);
+ expect(after.min.toArray()).toEqual(first.min.toArray().map((v) => expect.closeTo(v, 5)));
+ expect(after.max.toArray()).toEqual(first.max.toArray().map((v) => expect.closeTo(v, 5)));
+ });
+
+ it('keeps a zero-height model finite instead of scaling it to Infinity', () => {
+ const model = makeModel({ height: 0 });
+ fitModelToHeight(model, { targetHeight: 2 });
+ expect(Number.isFinite(model.scale.x)).toBe(true);
+ expect(model.position.toArray().every(Number.isFinite)).toBe(true);
+ });
+
+ it('leaves a geometry-less object at identity rather than flinging it to -Infinity', () => {
+ const empty = new THREE.Group();
+ empty.add(new THREE.Group());
+ fitModelToHeight(empty, { targetHeight: 2, feetOnGround: true });
+ expect(empty.position.toArray()).toEqual([0, 0, 0]);
+ expect(empty.scale.toArray()).toEqual([1, 1, 1]);
+ });
+});