Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(society): make 3D agent shapes livelier (#643)

Ruben Lütke448e2dbabba7
diff --git a/jarvis/ui/web/frontend/src/components/society/agentSymbol.css b/jarvis/ui/web/frontend/src/components/society/agentSymbol.css
index 9366fb9ab7..3b1795614f 100644
--- a/jarvis/ui/web/frontend/src/components/society/agentSymbol.css
+++ b/jarvis/ui/web/frontend/src/components/society/agentSymbol.css
@@ -113,32 +113,57 @@
display: inline-block;
flex-shrink: 0;
}
-/* Everything that belongs to the body moves as one: it breathes from the ground up, a little out of step
- with every other figure (--agent-figure-delay), and gives a small hop when the pointer finds it. */
+/* Everything that belongs to the body moves as one, a little out of step with every other figure
+ (--agent-figure-delay). One loop: two breaths, a hop with squash and stretch, a wobble about the base.
+ The pointer brings a hop at once. */
.society-agent-figure > .agent-figure-body {
position: relative;
display: block;
width: 100%;
height: 100%;
transform-origin: 50% 88%;
- animation: agent-figure-breathe 4.2s ease-in-out infinite;
+ animation: agent-figure-idle 7.2s ease-in-out infinite;
animation-delay: var(--agent-figure-delay, 0ms);
}
-@keyframes agent-figure-breathe {
- 0%, 100% { transform: translateY(0) scale(1, 1); }
- 50% { transform: translateY(-1.2%) scale(1.014, 0.984); }
+@keyframes agent-figure-idle {
+ 0%, 20%, 40% { transform: translateY(0) rotate(0deg) scale(1, 1); }
+ 10%, 30% { transform: translateY(-2.4%) rotate(0deg) scale(0.985, 1.03); }
+ 46% { transform: translateY(1.6%) rotate(0deg) scale(1.08, 0.9); }
+ 54% { transform: translateY(-15%) rotate(0deg) scale(0.94, 1.09); }
+ 61% { transform: translateY(0) rotate(0deg) scale(1.07, 0.92); }
+ 67% { transform: translateY(0) rotate(0deg) scale(1, 1); }
+ 74% { transform: translateY(0) rotate(-6deg) scale(1, 1); }
+ 82% { transform: translateY(0) rotate(6deg) scale(1, 1); }
+ 89% { transform: translateY(0) rotate(-3deg) scale(1, 1); }
+ 95%, 100% { transform: translateY(0) rotate(0deg) scale(1, 1); }
}
:is(button, a, [role="button"], [role="tab"], li):hover > .society-agent-figure > .agent-figure-body,
:is(button, a, [role="button"], [role="tab"], li):hover :is(span, div) > .society-agent-figure > .agent-figure-body,
.society-agent-figure:hover > .agent-figure-body {
- animation: agent-figure-hop 0.55s cubic-bezier(0.3, 0.7, 0.4, 1), agent-figure-breathe 4.2s ease-in-out 0.55s infinite;
+ animation: agent-figure-hop 0.6s cubic-bezier(0.3, 0.7, 0.4, 1), agent-figure-idle 7.2s ease-in-out 0.6s infinite;
}
@keyframes agent-figure-hop {
- 0% { transform: translateY(0) scale(1, 1); }
- 22% { transform: translateY(1.5%) scale(1.06, 0.92); }
- 52% { transform: translateY(-9%) scale(0.97, 1.05); }
- 78% { transform: translateY(0) scale(1.03, 0.96); }
- 100% { transform: translateY(0) scale(1, 1); }
+ 0% { transform: translateY(0) rotate(0deg) scale(1, 1); }
+ 20% { transform: translateY(2%) rotate(0deg) scale(1.1, 0.88); }
+ 50% { transform: translateY(-18%) rotate(-4deg) scale(0.93, 1.1); }
+ 78% { transform: translateY(0) rotate(3deg) scale(1.08, 0.92); }
+ 100% { transform: translateY(0) rotate(0deg) scale(1, 1); }
+}
+/* The shadow stays on the ground: it shrinks and pales while the body is in the air. */
+.society-agent-figure > .agent-figure-ground {
+ position: absolute;
+ display: block;
+ border-radius: 50%;
+ background: radial-gradient(closest-side, rgb(0 0 0 / 0.3) 22%, rgb(0 0 0 / 0.16) 60%, transparent 100%);
+ pointer-events: none;
+ opacity: 0;
+ animation: agent-figure-ground 7.2s ease-in-out infinite;
+ animation-delay: var(--agent-figure-delay, 0ms);
+}
+.society-agent-figure[data-ready="true"] > .agent-figure-ground { opacity: 1; }
+@keyframes agent-figure-ground {
+ 0%, 46%, 61%, 100% { transform: scale(1); filter: opacity(1); }
+ 54% { transform: scale(0.74); filter: opacity(0.55); }
}
/* The picture and what is blended onto it: flowing colours meet the picture only, never the page behind. */
.agent-figure-body > .agent-figure-picture {
@@ -168,16 +193,22 @@
pointer-events: none;
}
-/* Living eyes: the pair glances about now and then, each eye blinks. Lengths in em of one symbol unit. */
+/* Living eyes: the pair glances about, each eye blinks; near the pointer the pair follows it instead
+ (figureGaze.ts sets the two lengths). Lengths in em of one symbol unit. */
.agent-figure-body > .agent-figure-eyes {
position: absolute;
inset: 0;
pointer-events: none;
opacity: 0;
- animation: agent-figure-glance 11s ease-in-out infinite;
+ animation: agent-figure-glance 6.4s ease-in-out infinite;
animation-delay: var(--agent-figure-delay, 0ms);
}
.society-agent-figure[data-ready="true"] .agent-figure-eyes { opacity: 1; }
+.agent-figure-body > .agent-figure-eyes[data-following="true"] {
+ animation: none;
+ transform: translate(var(--agent-look-x, 0), var(--agent-look-y, 0));
+ transition: transform 0.14s ease-out;
+}
.agent-figure-eyes > i {
position: absolute;
display: block;
@@ -186,28 +217,29 @@
position: absolute;
inset: 0;
border-radius: 50%;
- animation: agent-figure-blink 5.4s ease-in-out infinite;
+ animation: agent-figure-blink 3.8s ease-in-out infinite;
animation-delay: var(--agent-figure-delay, 0ms);
}
@keyframes agent-figure-glance {
- 0%, 18%, 30%, 56%, 70%, 100% { transform: translate(0, 0); }
- 21%, 27% { transform: translate(-1em, 0.15em); }
- 59%, 66% { transform: translate(0.9em, -0.35em); }
+ 0%, 10%, 26%, 44%, 60%, 78%, 100% { transform: translate(0, 0); }
+ 13%, 22% { transform: translate(-1.35em, 0.2em); }
+ 47%, 56% { transform: translate(1.25em, -0.45em); }
+ 81%, 92% { transform: translate(0.3em, -0.8em); }
}
@keyframes agent-figure-blink {
- 0%, 44%, 50%, 90%, 94.5%, 97%, 100% { transform: scaleY(1); }
- 47% { transform: scaleY(0.08); }
- 92% { transform: scaleY(0.08); }
- 95.8% { transform: scaleY(0.08); }
+ 0%, 40%, 48%, 84%, 90.5%, 94%, 100% { transform: scaleY(1); }
+ 44% { transform: scaleY(0.08); }
+ 87% { transform: scaleY(0.08); }
+ 92.2% { transform: scaleY(0.08); }
}
/* The pointer has found it: wide eyes for the hop. */
:is(button, a, [role="button"], [role="tab"], li):hover .agent-figure-eyes > i > b,
.society-agent-figure:hover .agent-figure-eyes > i > b {
- animation: agent-figure-wide 0.55s ease-out, agent-figure-blink 5.4s ease-in-out 0.55s infinite;
+ animation: agent-figure-wide 0.6s ease-out, agent-figure-blink 3.8s ease-in-out 0.6s infinite;
}
@keyframes agent-figure-wide {
0%, 100% { transform: scale(1); }
- 40% { transform: scale(1.18, 1.22); }
+ 40% { transform: scale(1.25, 1.3); }
}
/* A glowing design: a soft halo of its brightest colour breathes behind the figure. */
@@ -290,6 +322,7 @@
@media (prefers-reduced-motion: reduce) {
.agent-figure-body > .agent-figure-picture { transition: none; }
.society-agent-figure > .agent-figure-body,
+ .society-agent-figure > .agent-figure-ground,
.agent-figure-body > .agent-figure-eyes,
.agent-figure-eyes > i > b,
.society-agent-figure > .agent-figure-halo,
diff --git a/jarvis/ui/web/frontend/src/components/society/companion/AgentFollower.tsx b/jarvis/ui/web/frontend/src/components/society/companion/AgentFollower.tsx
index 297ff67101..eba3aa5c62 100644
--- a/jarvis/ui/web/frontend/src/components/society/companion/AgentFollower.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/companion/AgentFollower.tsx
@@ -91,11 +91,31 @@ function ShapeModel({ appearance, lead = false }: { appearance: CompanionAppeara
mesh.material = name.includes("Body") ? body : name.includes("Highlight") ? shine : eyes;
});
}
- return { model, materials };
+ // The eyes that show, with the height of their middle: a blink squeezes them about it.
+ const eyes: { mesh: Mesh; middle: number }[] = [];
+ if (!lead) model.traverse(object => {
+ const mesh = object as Mesh;
+ if (!mesh.isMesh || !mesh.visible || !(mesh.name.includes("Dots") || mesh.name.includes("Lines"))) return;
+ if (!mesh.geometry.boundingBox) mesh.geometry.computeBoundingBox();
+ const box = mesh.geometry.boundingBox;
+ if (box) eyes.push({ mesh, middle: (box.min.y + box.max.y) / 2 });
+ });
+ return { model, materials, eyes };
// eslint-disable-next-line react-hooks/exhaustive-deps -- appearance.skin is read through skinKey
}, [scene, lead, appearance.shape, appearance.color, appearance.eyes, skinKey]);
useEffect(() => () => { instance.materials.forEach(material => material.dispose()); }, [instance]);
- useFrame((_, delta) => { if (!reduced && skinKey) advanceSkin(instance.materials[0]!, delta); });
+ // Each companion blinks on its own beat; only frames that are drawn anyway move the lids.
+ const blink = useRef(Math.random() * BLINK_EVERY_S);
+ useFrame((_, delta) => {
+ if (reduced) return;
+ if (skinKey) advanceSkin(instance.materials[0]!, delta);
+ blink.current = (blink.current + Math.min(delta, 0.1)) % BLINK_EVERY_S;
+ const open = blink.current < BLINK_S || (blink.current > BLINK_S * 2.4 && blink.current < BLINK_S * 3.4) ? 0.1 : 1;
+ for (const eye of instance.eyes) {
+ eye.mesh.scale.y = open;
+ eye.mesh.position.y = eye.middle * (1 - open);
+ }
+ });
const wearing = !lead && wornAccessories(appearance.accessories).length > 0;
// Gigi's authored body is 0.4 m; the symbol master is exactly 1 m.
return <group scale={appearance.sizeM / (lead ? 0.4 : 1)}>
@@ -105,6 +125,9 @@ function ShapeModel({ appearance, lead = false }: { appearance: CompanionAppeara
</group>;
}
+/** A shape companion blinks twice in quick succession this often, and one blink takes this long, seconds. */
+const BLINK_EVERY_S = 3.6, BLINK_S = 0.13;
+
const PUFFS = 7;
const PUFF_GEOMETRY = new SphereGeometry(1, 12, 8);
diff --git a/jarvis/ui/web/frontend/src/components/society/companion/CompanionPreview.tsx b/jarvis/ui/web/frontend/src/components/society/companion/CompanionPreview.tsx
index 19066a69b0..1f785c6d6c 100644
--- a/jarvis/ui/web/frontend/src/components/society/companion/CompanionPreview.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/companion/CompanionPreview.tsx
@@ -80,19 +80,29 @@ function Frame({ framing }: { framing: Framing }) {
}
/**
- * A shape at rest on the table: it sways a little to each side and breathes,
- * so the preview shows its volume without being turned by hand. A pet brings
+ * A shape at rest on the table: it sways to each side, breathes, leans and
+ * hops every few seconds, so the preview shows its volume and its character
+ * without being turned by hand. A pet brings
* its own life (PetModel) and is left alone.
*/
-function Idle({ enabled, children }: { enabled: boolean; children: ReactNode }) {
+/** The preview's shape hops this often, and one hop takes this long, seconds. */
+const HOP_EVERY_S = 3.4, HOP_S = 0.7;
+
+function Idle({ enabled, heightM, children }: { enabled: boolean; heightM: number; children: ReactNode }) {
const group = useRef<Group>(null);
useFrame(({ clock }) => {
const node = group.current;
if (!node || !enabled) return;
const t = clock.getElapsedTime();
- const breath = Math.sin(t * 1.5) * 0.012;
- node.rotation.y = Math.sin(t * 0.6) * 0.3;
- node.scale.set(1 + breath, 1 - breath, 1 + breath);
+ const breath = Math.sin(t * 1.9) * 0.02;
+ // Every few seconds a hop: down into a squash, up, and a soft landing.
+ const beat = (t % HOP_EVERY_S) / HOP_S;
+ const air = beat < 1 ? Math.sin(beat * Math.PI) : 0;
+ const squash = beat < 1 ? Math.sin(beat * Math.PI * 2) * -0.07 : 0;
+ node.rotation.y = Math.sin(t * 0.8) * 0.5;
+ node.rotation.z = Math.sin(t * 1.3) * 0.05;
+ node.position.y = air * heightM * 0.22;
+ node.scale.set(1 + breath - squash, 1 - breath + squash, 1 + breath - squash);
});
return <group ref={group}>{children}</group>;
}
@@ -118,7 +128,7 @@ export function CompanionPreview({ appearance, lead = false }: { appearance: Com
camera={{ position: framing.position, fov: FOV, near: 0.02, far: 20 }} gl={{ alpha: true, antialias: true }}>
<Studio />
<Frame framing={framing} />
- <Suspense fallback={null}><Idle enabled={live && !pet}><CompanionModel appearance={appearance} lead={lead} /></Idle></Suspense>
+ <Suspense fallback={null}><Idle enabled={live && !pet} heightM={appearance.sizeM}><CompanionModel appearance={appearance} lead={lead} /></Idle></Suspense>
<ContactShadows position={[0, 0.001, 0]} opacity={0.5} scale={Math.max(1, framing.target[1] * 6)} blur={2.6} far={1} resolution={512} frames={live ? Infinity : 1} />
<OrbitControls makeDefault target={framing.target} enablePan={false} enableZoom={false} autoRotate={turning} autoRotateSpeed={0.9}
minPolarAngle={0.25} maxPolarAngle={Math.PI * 0.55} />
diff --git a/jarvis/ui/web/frontend/src/components/society/companion/ShapeFigure.tsx b/jarvis/ui/web/frontend/src/components/society/companion/ShapeFigure.tsx
index f243b50104..f1a1e15d55 100644
--- a/jarvis/ui/web/frontend/src/components/society/companion/ShapeFigure.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/companion/ShapeFigure.tsx
@@ -1,4 +1,5 @@
-import { useCallback, useLayoutEffect, useRef, useState, useSyncExternalStore, type CSSProperties, type ReactNode } from "react";
+import { useCallback, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type CSSProperties, type ReactNode } from "react";
+import { followPointer } from "./figureGaze";
import { figureKey, type FigureLook, type FigureSmoke } from "./figureScene";
import { WorkingBadge } from "./WorkingBadge";
import { FIGURE_BROKEN, figuresSupported, readFigure, watchFigure, watchFigureSupport, type Figure } from "./figureStore";
@@ -53,9 +54,10 @@ const EYE_HALF = { lines: [1.35, 3.15], dots: [2.15, 2.3] } as const;
/**
* The eyes of a figure as two plain elements at the place the picture's own
- * projection gives them: a wrapper that glances, and in it each eye, leaning
- * with the turned face, that blinks. Lengths are in `em` of one symbol
- * unit, so the motion scales with the face.
+ * projection gives them: a wrapper that glances (or follows the pointer
+ * while it is near, see figureGaze.ts), and in it each eye, leaning with the
+ * turned face, that blinks. Lengths are in `em` of one symbol unit, so the
+ * motion scales with the face.
*/
function LivingEyes({ figure, size, eyes }: { figure: Figure; size: number; eyes: { kind: "dots" | "lines"; y: number; color: string } }) {
const [a, b, c, d, e, f] = figure.face;
@@ -64,7 +66,9 @@ function LivingEyes({ figure, size, eyes }: { figure: Figure; size: number; eyes
const across = Math.hypot(a, b) * scale, down = Math.hypot(c, d) * scale;
const [halfX, halfY] = EYE_HALF[eyes.kind];
const lean = Math.atan2(b, a) * 180 / Math.PI;
- return <span aria-hidden className="agent-figure-eyes" data-figure-eyes={eyes.kind} style={{ fontSize: down }}>
+ const pair = useRef<HTMLSpanElement>(null);
+ useEffect(() => pair.current ? followPointer(pair.current) : undefined, []);
+ return <span ref={pair} aria-hidden className="agent-figure-eyes" data-figure-eyes={eyes.kind} style={{ fontSize: down }}>
{EYE_X.map(x => <i key={x} style={{
left: (a * x + c * eyes.y + e) * scale - halfX * across, top: (b * x + d * eyes.y + f) * scale - halfY * down,
width: halfX * across * 2, height: halfY * down * 2, transform: `skewY(${lean.toFixed(2)}deg)`,
@@ -84,8 +88,9 @@ function LivingEyes({ figure, size, eyes }: { figure: Figure; size: number; eyes
* colours of a flowing design (multiplied onto a white body), the shine of a
* shimmering one, both cut to the body's outline, and the smoke of a cigar.
*
- * The figure is alive at rest: it breathes, and with `eyes` it blinks and
- * glances about. Those eyes are plain elements moved by transforms only, so
+ * The figure is alive at rest: it breathes, hops and wobbles over a shadow
+ * that stays on the ground, and with `eyes` it blinks, glances about and
+ * follows the pointer. Those eyes are plain elements moved by transforms only, so
* a roster of faces costs the UI thread nothing while it idles; each figure
* runs a little out of step with the others.
*/
@@ -151,6 +156,10 @@ export function ShapeFigure({ look, size, shape, behind, children, overlay, fall
const pace = { "--agent-figure-delay": `${-beat}ms` } as CSSProperties;
return <span className="society-agent-figure" data-agent-figure={shape} data-ready={ready ? "true" : undefined} data-working={working ? "true" : undefined} style={{ width: size, height: size, ...pace }}>
{behind}
+ {shown?.ground && <i aria-hidden className="agent-figure-ground" style={{
+ left: (shown.ground.x - shown.ground.rx) * size / shown.pixels, top: (shown.ground.y - shown.ground.ry) * size / shown.pixels,
+ width: shown.ground.rx * 2 * size / shown.pixels, height: shown.ground.ry * 2 * size / shown.pixels,
+ }} />}
<span className="agent-figure-body">
<span className="agent-figure-picture" style={flow ? masked(current?.whole) : undefined}>
<canvas ref={canvas} aria-hidden />
diff --git a/jarvis/ui/web/frontend/src/components/society/companion/figure.worker.ts b/jarvis/ui/web/frontend/src/components/society/companion/figure.worker.ts
index 3ec45436fc..86ef8d4ba4 100644
--- a/jarvis/ui/web/frontend/src/components/society/companion/figure.worker.ts
+++ b/jarvis/ui/web/frontend/src/components/society/companion/figure.worker.ts
@@ -5,7 +5,7 @@
* the cheap half of the work. Terminating the worker releases everything.
*/
import { meshesByName, readGlb, type FigureMesh } from "./figureGlb";
-import { figureCover, shadeFigure, traceFigure, type FigureTrace } from "./figureRender";
+import { figureCover, figureGround, shadeFigure, traceFigure, type FigureGround, type FigureTrace } from "./figureRender";
import {
bodyEffectMoves, figureFaceMatrix, figureParts, figureSmoke, figureTraceKey, wearsAccessories, type FigureLook, type FigureSmoke,
} from "./figureScene";
@@ -26,6 +26,8 @@ export type FigureResponse =
/** How much of each pixel is body, one byte per pixel: only for a look whose effect moves across the body. */
body?: ArrayBuffer;
smoke: FigureSmoke[];
+ /** The shadow the figure stands on; the face draws it under the picture. */
+ ground?: FigureGround;
}
| { id: number; ok: false };
@@ -80,7 +82,7 @@ async function draw(request: FigureRequest): Promise<FigureResponse> {
return {
id: request.id, ok: true, pixels, data: image.data.buffer as ArrayBuffer, face: figureFaceMatrix(look, bodies, image.frame),
body: bodyEffectMoves(look) ? figureCover(trace, parts.map(part => !!part.body)).buffer : undefined,
- smoke: figureSmoke(look, image.frame),
+ smoke: figureSmoke(look, image.frame), ground: figureGround(trace),
};
}
diff --git a/jarvis/ui/web/frontend/src/components/society/companion/figureGaze.ts b/jarvis/ui/web/frontend/src/components/society/companion/figureGaze.ts
new file mode 100644
index 0000000000..4afa75a7bc
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/companion/figureGaze.ts
@@ -0,0 +1,72 @@
+/**
+ * Eyes that follow the pointer. Every living pair of eyes on screen (see
+ * ShapeFigure) registers its wrapper here; one passive listener for the
+ * whole window turns the pointer's place into two CSS lengths per pair, at
+ * most once a frame and only while the pointer moves. Out of reach, a pair
+ * goes back to glancing about by itself.
+ */
+
+/** A pair looks at the pointer while it is this close, CSS pixels. */
+const REACH_PX = 380;
+/** The eyes are fully turned once the pointer is this far away. */
+const FULL_PX = 110;
+/** How far the pair moves across and up or down, in symbol units (`em` on the wrapper). */
+const TURN_X = 1.35, TURN_Y = 0.85;
+
+const pairs = new Set<HTMLElement>();
+let pointerX = 0, pointerY = 0;
+let scheduled = false;
+
+function rest(pair: HTMLElement): void {
+ if (!pair.dataset.following) return;
+ delete pair.dataset.following;
+ pair.style.removeProperty("--agent-look-x");
+ pair.style.removeProperty("--agent-look-y");
+}
+
+function look(): void {
+ scheduled = false;
+ // Measure every pair first, then write: no layout is forced between two writes.
+ const measured = [...pairs].map(pair => ({ pair, box: pair.getBoundingClientRect() }));
+ for (const { pair, box } of measured) {
+ const dx = pointerX - (box.left + box.width / 2), dy = pointerY - (box.top + box.height / 2);
+ const distance = Math.hypot(dx, dy);
+ if (!box.width || distance > REACH_PX) { rest(pair); continue; }
+ const pull = Math.min(1, distance / FULL_PX) / (distance || 1);
+ pair.style.setProperty("--agent-look-x", `${(dx * pull * TURN_X).toFixed(2)}em`);
+ pair.style.setProperty("--agent-look-y", `${(dy * pull * TURN_Y).toFixed(2)}em`);
+ pair.dataset.following = "true";
+ }
+}
+
+function onMove(event: PointerEvent): void {
+ pointerX = event.clientX;
+ pointerY = event.clientY;
+ if (scheduled) return;
+ scheduled = true;
+ requestAnimationFrame(look);
+}
+
+function onLeave(): void {
+ pairs.forEach(rest);
+}
+
+/**
+ * Lets a pair of eyes follow the pointer until the returned function is
+ * called. With reduced motion (or without a window) nothing is registered.
+ */
+export function followPointer(pair: HTMLElement): () => void {
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return () => {};
+ if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return () => {};
+ pairs.add(pair);
+ if (pairs.size === 1) {
+ window.addEventListener("pointermove", onMove, { passive: true });
+ document.documentElement.addEventListener("pointerleave", onLeave);
+ }
+ return () => {
+ pairs.delete(pair);
+ if (pairs.size) return;
+ window.removeEventListener("pointermove", onMove);
+ document.documentElement.removeEventListener("pointerleave", onLeave);
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/companion/figureRender.test.ts b/jarvis/ui/web/frontend/src/components/society/companion/figureRender.test.ts
index 8bca8bbf57..b88b309e45 100644
--- a/jarvis/ui/web/frontend/src/components/society/companion/figureRender.test.ts
+++ b/jarvis/ui/web/frontend/src/components/society/companion/figureRender.test.ts
@@ -5,7 +5,7 @@ import { describe, expect, it } from "vitest";
import { ACCESSORY_CATALOG, ACCESSORY_ITEMS } from "./accessories";
import { COMPANION_SHAPES } from "./appearance";
import { meshesByName, readGlb } from "./figureGlb";
-import { figureCover, renderFigure, shadeFigure, traceFigure } from "./figureRender";
+import { figureCover, figureGround, renderFigure, shadeFigure, traceFigure } from "./figureRender";
import { bodyEffectMoves, EFFECT_FLOW, EFFECT_STARS, figureFaceMatrix, figureKey, figureParts, figureSmoke, figureTraceKey, type FigureLook } from "./figureScene";
const ASSETS = path.resolve(__dirname, "../../../assets/society/companions");
@@ -46,7 +46,7 @@ describe("3D profile faces", () => {
for (let y = 0; y < 48; y++) for (let x = 0; x < 48; x++) {
const [, , , alpha] = pixel(image, x, y);
if (alpha > 200) solid++;
- // The figure never touches the edge; only its faint shadow may reach it.
+ // The figure never touches the edge.
if (x === 0 || y === 0 || x === 47 || y === 47) expect(alpha).toBeLessThan(120);
}
expect(solid).toBeGreaterThan(48 * 48 * 0.2);
@@ -142,6 +142,22 @@ describe("3D profile faces", () => {
expect(figureSmoke(look(), image.frame)).toHaveLength(0);
});
+ it("leaves the ground shadow out of the picture and says where it lies", () => {
+ const parts = figureParts(look({ shape: "circle" }), bodies);
+ const trace = traceFigure(parts, 64);
+ const image = shadeFigure(trace, parts);
+ const ground = figureGround(trace)!;
+ // Under the body, inside the picture, wider than tall (a circle on the ground seen from above the horizon).
+ expect(ground.x).toBeGreaterThan(16);
+ expect(ground.x).toBeLessThan(48);
+ expect(ground.y).toBeGreaterThan(40);
+ expect(ground.y + ground.ry).toBeLessThanOrEqual(66);
+ expect(ground.rx).toBeGreaterThan(ground.ry * 2);
+ // Beside the body, on the shadow's own height, the picture itself is empty.
+ expect(pixel(image, Math.min(63, Math.round(ground.x + ground.rx * 0.95)), Math.min(63, Math.round(ground.y + ground.ry * 0.6)))[3]).toBe(0);
+ expect(figureGround(traceFigure([], 16))).toBeUndefined();
+ });
+
it("draws nothing for an empty figure", () => {
expect(renderFigure([], 16).data.every(value => value === 0)).toBe(true);
});
diff --git a/jarvis/ui/web/frontend/src/components/society/companion/figureRender.ts b/jarvis/ui/web/frontend/src/components/society/companion/figureRender.ts
index 561d3a6305..a49dfd77ce 100644
--- a/jarvis/ui/web/frontend/src/components/society/companion/figureRender.ts
+++ b/jarvis/ui/web/frontend/src/components/society/companion/figureRender.ts
@@ -1,7 +1,9 @@
/**
* Draws an agent's shape as a small 3D figure on the CPU: the same meshes
- * the map uses, turned a little to the side, lit from the upper left and
- * set on a soft ground shadow. The result is a plain RGBA image, so a profile
+ * the map uses, turned a little to the side and lit from the upper left.
+ * The shadow it stands on is not part of the picture: the face draws it as
+ * a layer of its own (`figureGround` says where), so the figure can hop
+ * off it. The result is a plain RGBA image, so a profile
* face is real 3D without a WebGL context. Everything here is pure; the
* worker (figure.worker.ts) calls it off the UI thread.
*
@@ -104,7 +106,6 @@ const FILL_COLOR: LinearRgb = [0.1, 0.12, 0.15];
/** The share of the image left free around the figure and its shadow. */
const PAD = 0.03;
-const SHADOW_ALPHA = 0.3;
/** The shadow reaches this far past the footprint, in footprint radii. */
const SHADOW_REACH = 1.18;
/** It lies a little away from the light: this far along x and z, in footprint radii. */
@@ -353,7 +354,7 @@ export function traceFigure(parts: readonly Pick<FigurePart, "mesh" | "offset" |
/** The colours of a traced figure: one coat per part, in the order the parts were traced. */
export function shadeFigure(trace: FigureTrace, coats: readonly FigureCoat[]): FigureImage {
- const { size, samples, depth, normal, owner, light, open, box, foot } = trace;
+ const { size, samples, depth, normal, owner, light, open, box } = trace;
const { k, ox, oy, yaw, pitch } = trace.frame;
const cy = Math.cos(yaw), sy = Math.sin(yaw), cp = Math.cos(pitch), sp = Math.sin(pitch);
const width = size * samples;
@@ -409,19 +410,10 @@ export function shadeFigure(trace: FigureTrace, coats: readonly FigureCoat[]): F
sumR += shoulder(r); sumG += shoulder(g); sumB += shoulder(b); hits++;
}
}
- const cover = hits / (samples * samples);
- let ground = 0;
- if (foot && cover < 1) {
- // Where this pixel's view ray meets the ground (model y = 0).
- const xv = ((oxPixel + 0.5) * samples - ox) / k, z1 = -((oy - (oyPixel + 0.5) * samples) / k) / sp;
- const qx = (xv * cy - z1 * sy - foot.x) / foot.rx, qz = (xv * sy + z1 * cy - foot.z) / foot.rz;
- ground = SHADOW_ALPHA * smooth(SHADOW_REACH, 0.3, Math.hypot(qx, qz)) * (1 - cover);
- }
- const alpha = cover + ground;
- if (alpha <= 0) continue;
+ if (!hits) continue;
const out = (oyPixel * size + oxPixel) * 4;
- // The samples carry the figure's light; the shadow under it adds only darkness.
- const weight = 1 / (samples * samples * alpha);
+ const weight = 1 / hits;
+ const alpha = hits / (samples * samples);
data[out] = TO_SRGB[Math.round(Math.max(0, Math.min(1, sumR * weight)) * 4096)]!;
data[out + 1] = TO_SRGB[Math.round(Math.max(0, Math.min(1, sumG * weight)) * 4096)]!;
data[out + 2] = TO_SRGB[Math.round(Math.max(0, Math.min(1, sumB * weight)) * 4096)]!;
@@ -431,6 +423,25 @@ export function shadeFigure(trace: FigureTrace, coats: readonly FigureCoat[]): F
return { size, data, frame: { k: k / samples, ox: ox / samples, oy: oy / samples, yaw, pitch } };
}
+/** The shadow a figure stands on, as an ellipse on the picture: centre and radii, pixels. */
+export interface FigureGround { x: number; y: number; rx: number; ry: number }
+
+/** Where the ground shadow of a traced figure lies, or nothing when it does not stand on the ground. */
+export function figureGround(trace: FigureTrace): FigureGround | undefined {
+ const { foot, samples } = trace;
+ if (!foot) return undefined;
+ const { k, yaw, pitch } = trace.frame;
+ const cy = Math.cos(yaw), sy = Math.sin(yaw), sp = Math.sin(pitch);
+ const frame: FigureFrame = { ...trace.frame, k: k / samples, ox: trace.frame.ox / samples, oy: trace.frame.oy / samples };
+ const [x, y] = projectFigure(frame, foot.x, 0, foot.z);
+ // The footprint's ellipse on the ground, seen through the turn and the tilt.
+ return {
+ x, y,
+ rx: Math.hypot(foot.rx * cy, foot.rz * sy) * SHADOW_REACH * frame.k,
+ ry: Math.hypot(foot.rx * sy, foot.rz * cy) * sp * SHADOW_REACH * frame.k,
+ };
+}
+
/**
* How much of each pixel shows the chosen parts, 0 to 255: the outline a
* moving effect is cut to (a shine that sweeps the body must not cross the
diff --git a/jarvis/ui/web/frontend/src/components/society/companion/figureStore.ts b/jarvis/ui/web/frontend/src/components/society/companion/figureStore.ts
index a5322912fc..3f6d1e0f63 100644
--- a/jarvis/ui/web/frontend/src/components/society/companion/figureStore.ts
+++ b/jarvis/ui/web/frontend/src/components/society/companion/figureStore.ts
@@ -8,6 +8,7 @@
import accessoryModels from "@/assets/society/companions/accessories.glb";
import companionModels from "@/assets/society/companions/companions.glb";
import type { FigureRequest, FigureResponse } from "./figure.worker";
+import type { FigureGround } from "./figureRender";
import { figureKey, type FigureLook, type FigureSmoke } from "./figureScene";
export interface Figure {
@@ -21,6 +22,8 @@ export interface Figure {
body?: Uint8ClampedArray<ArrayBuffer>;
/** Where worn items smoke, in picture pixels. */
smoke: FigureSmoke[];
+ /** The shadow the figure stands on, in picture pixels. */
+ ground?: FigureGround;
}
/** The most picture memory kept, bytes. */
@@ -125,7 +128,7 @@ function answer(message: FigureResponse): void {
workerFailures = 0;
keep(key, {
pixels: message.pixels, data: new Uint8ClampedArray(message.data), face: message.face,
- body: message.body && new Uint8ClampedArray(message.body), smoke: message.smoke,
+ body: message.body && new Uint8ClampedArray(message.body), smoke: message.smoke, ground: message.ground,
});
const entry = wanted.get(key);
wanted.delete(key);