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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(office): Jarvis follows the person as their chosen pet, in 3D
rubenluetke10-beep3e13bf114f7a
diff --git a/docs/agent-society/office-map.md b/docs/agent-society/office-map.mdindex 7d34ecc377..82be990659 100644--- a/docs/agent-society/office-map.md+++ b/docs/agent-society/office-map.md@@ -115,7 +115,8 @@ target runs WebGL.The agent creator still shows the older rigged figures; switching it to thetoy style is the rollout step after the maintainer approves this look.- **Pets**: each agent's symbol (the profile companion) follows it at about a- fifth of its height, reusing `AgentFollower`; the lead gets Gigi.+ fifth of its height, reusing `AgentFollower`; the lead is drawn as the+ person's own pet (see *Jarvis is the person's pet* below).- **Live monitors** (`LiveMonitors.tsx`, `useDeskChats.ts`, `deskChat.ts`): anagent seated at its own desk shows the tail of its chat (user lines, replies,running tools) on its monitor, refreshed by jittered polling of the existing@@ -148,10 +149,29 @@ the floor plan differ.terminal and fittings in each floor's own materials (oak, bronze and a mintglow with the brass ghost downstairs; walnut, brass and amber with a brass`>_` upstairs); two gyroscope rings turn round the floor token.-- **Gigi follows**: on the coding floor Jarvis (Gigi) flies in "follow" mode,- hovering beside and behind the person's head with a smoothed lag and never- inside a wall, including in the elevator. In the agents office Gigi keeps- its lead-office behaviour.+- **Jarvis follows**: on the coding floor Jarvis flies (or walks) in "follow"+ mode beside and behind the person with a smoothed lag and never inside a+ wall, including in the elevator. In the agents office it keeps its+ lead-office behaviour.+- **Jarvis is the person's pet** (2026-10-02): Jarvis appears as the pet+ chosen in Settings → My Pets (`docs/pets.md`), in 3D, not always as Gigi.+ `companion/petCompanions.ts` maps a pet to its companion:+ Gigi keeps its hover model; the six other built-ins have authored Blender+ models (`scripts/art/build_pet_companions.py`, study+ `art/studies/jarvis-pet-companions`, one GLB per pet under+ `assets/society/companions/pets/`) and a gait of their own: Ember the+ dragon flies with beating wings, Miso the cat trots, Bolt the battery+ waddles, Brew the teapot hops with a rattling lid, Mochi bounces and Shelly+ the snail crawls. Pets that fly hover at head height with Gigi's halo and+ sparkles; pets on the floor (`gigiFlight.ts` `ground` mode) walk right+ behind the person's feet, take floor routes (`findPath`) on errands instead+ of flying over desks, and carry their nameplate low. Limbs move by+ `companion/petRig.ts`, phased by ground covered so feet do not slide;+ reduced motion stops every gait. A pet the person drew becomes a voxel+ figure extruded from its own idle frames (`voxelPet.ts`), facing the camera+ and floating low. The stage feeds the choice through+ `companion/companionPetStore.ts`, so a change in My Pets swaps the+ companion live.- **Pane to character** (`codingFloor.ts`): every running coding-agent pane(Claude Code, Codex and the other agent CLIs; not plain shells, not archivedpanes) is one character. Its id is `pane:<workspace>:<history id or key>`,diff --git a/docs/pets.md b/docs/pets.mdindex fa9126030e..b82b175268 100644--- a/docs/pets.md+++ b/docs/pets.md@@ -48,6 +48,11 @@ one click.what was asked, the start of the answer (see *Cards*).- **The pet "None"** (`pet_id = "none"`) shows the control strip and thecards without a figure.+- **In the Jarvis Verse.** The chosen pet is also Jarvis in the office map:+ a 3D version of it walks, crawls, hops or flies behind the person's+ character (`docs/agent-society/office-map.md`, *Jarvis is the person's+ pet*). A pet the person drew becomes a voxel figure cut from its idle+ frames.The pet stays on screen while Jarvis is idle. The global shortcut(`[trigger] hotkey_pet_toggle`, default `alt+win+p`) hides it or brings itdiff --git a/jarvis/ui/web/frontend/src/assets/society/companions/pets/bolt.glb b/jarvis/ui/web/frontend/src/assets/society/companions/pets/bolt.glbnew file mode 100644index 0000000000..1f75ecf0d5Binary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/companions/pets/bolt.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/companions/pets/brew.glb b/jarvis/ui/web/frontend/src/assets/society/companions/pets/brew.glbnew file mode 100644index 0000000000..bb789309fcBinary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/companions/pets/brew.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/companions/pets/ember.glb b/jarvis/ui/web/frontend/src/assets/society/companions/pets/ember.glbnew file mode 100644index 0000000000..d2c14a5b61Binary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/companions/pets/ember.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/companions/pets/miso.glb b/jarvis/ui/web/frontend/src/assets/society/companions/pets/miso.glbnew file mode 100644index 0000000000..c9b6cde8b1Binary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/companions/pets/miso.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/companions/pets/mochi.glb b/jarvis/ui/web/frontend/src/assets/society/companions/pets/mochi.glbnew file mode 100644index 0000000000..00369a8e02Binary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/companions/pets/mochi.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/companions/pets/shelly.glb b/jarvis/ui/web/frontend/src/assets/society/companions/pets/shelly.glbnew file mode 100644index 0000000000..3fdc39d4fdBinary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/companions/pets/shelly.glb differdiff --git a/jarvis/ui/web/frontend/src/components/society/companion/PetModel.tsx b/jarvis/ui/web/frontend/src/components/society/companion/PetModel.tsxnew file mode 100644index 0000000000..a922daac42--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/PetModel.tsx@@ -0,0 +1,175 @@+/**+ * The 3D body of the person's chosen pet in the Jarvis Verse. Built-in pets+ * load their authored GLB and move by `petRig.ts`; a pet the person drew+ * becomes a voxel figure cut from its own idle frames, turned to the camera.+ * Both stand on their origin (bottom centre); the host places and turns them.+ */+import { useEffect, useMemo, useRef, useState } from "react";+import { useGLTF } from "@react-three/drei";+import { useFrame } from "@react-three/fiber";+import {+ BoxGeometry, Color, InstancedMesh, Matrix4, MeshStandardMaterial, Object3D, Quaternion, Vector3, type Group,+} from "three";+import type { CompanionPet } from "./petCompanions";+import { createRigState, rigPose, stepRig, type PartMotion, type PetMood } from "./petRig";+import { voxelFrames, type VoxelFrames } from "./voxelPet";++/** What the host knows each frame: how fast the pet moves over the ground and what Jarvis is doing. */+export interface PetDrive {+ speed: number;+ mood: PetMood;+}++const PET_FILES = import.meta.glob("../../../assets/society/companions/pets/*.glb", {+ query: "?url",+ import: "default",+ eager: true,+}) as Record<string, string>;++export function petModelUrl(id: string): string | null {+ const suffix = `/pets/${id}.glb`;+ for (const [key, url] of Object.entries(PET_FILES)) if (key.endsWith(suffix)) return url;+ return null;+}++interface RiggedPart {+ object: Object3D;+ position: Vector3;+ rotation: [number, number, number];+ scale: Vector3;+}++function applyMotion(part: RiggedPart, motion: PartMotion): void {+ const { object, position, rotation, scale } = part;+ object.position.set(position.x, position.y + motion.dy, position.z);+ object.rotation.set(rotation[0] + motion.rx, rotation[1] + motion.ry, rotation[2] + motion.rz);+ object.scale.set(scale.x * motion.sx, scale.y * motion.sy, scale.z * motion.sz);+}++/** A built-in pet: its authored model, animated part by part. */+export function PetModel({ pet, drive, reduced, paused }: {+ pet: CompanionPet; drive: { current: PetDrive }; reduced: boolean; paused: boolean;+}) {+ const url = petModelUrl(pet.id);+ if (!url) throw new Error(`No 3D model for pet ${pet.id}`);+ const { scene } = useGLTF(url);+ const instance = useMemo(() => {+ const model = scene.clone(true);+ const parts = new Map<string, RiggedPart>();+ model.traverse((object) => {+ if ((object as { isMesh?: boolean }).isMesh) object.castShadow = true;+ const name = typeof object.userData.name === "string" ? object.userData.name : object.name;+ if (name.startsWith(`${pet.id}_`)) {+ parts.set(name, {+ object,+ position: object.position.clone(),+ rotation: [object.rotation.x, object.rotation.y, object.rotation.z],+ scale: object.scale.clone(),+ });+ }+ });+ return { model, parts };+ }, [scene, pet.id]);+ const rig = useRef(createRigState());+ const pose = useMemo(() => new Map<string, PartMotion>(), []);+ useEffect(() => { pose.clear(); }, [pet.id, pose]);+ useFrame((_, dt) => {+ if (paused) return;+ const { speed, mood } = drive.current;+ stepRig(rig.current, pet, { dt, speed, mood, reduced });+ rigPose(pet, rig.current, mood, pose);+ for (const [name, motion] of pose) {+ const part = instance.parts.get(name);+ if (part) applyMotion(part, motion);+ }+ });+ return <primitive object={instance.model} scale={pet.heightM / pet.modelHeightM} dispose={null} />;+}++/** Reads a same-origin sprite sheet into voxel frames; null while loading or when unusable. */+function useVoxelFrames(pet: CompanionPet): VoxelFrames | null {+ const [frames, setFrames] = useState<VoxelFrames | null>(null);+ useEffect(() => {+ setFrames(null);+ if (!pet.sheetUrl || !pet.frameSize || !pet.idle) return;+ let cancelled = false;+ const image = new Image();+ image.onload = () => {+ if (cancelled) return;+ const canvas = document.createElement("canvas");+ canvas.width = image.naturalWidth;+ canvas.height = image.naturalHeight;+ const context = canvas.getContext("2d", { willReadFrequently: true });+ if (!context) return;+ context.drawImage(image, 0, 0);+ const { data } = context.getImageData(0, 0, canvas.width, canvas.height);+ const idle = pet.idle!;+ const result = voxelFrames(data, canvas.width, canvas.height, pet.frameSize!, idle.row, idle.frames);+ if (!result) console.warn("Pet sheet has no usable idle frames for a 3D figure", pet.id);+ setFrames(result);+ };+ image.onerror = () => { if (!cancelled) console.warn("Pet sheet could not load", pet.id); };+ image.src = pet.sheetUrl;+ return () => { cancelled = true; image.onload = null; image.onerror = null; };+ }, [pet.id, pet.sheetUrl, pet.frameSize, pet.idle]);+ return frames;+}++/** Voxel figure of a drawn pet: one instanced cube per opaque pixel, flipping through its idle frames. */+export function VoxelPet({ pet, reduced, paused }: { pet: CompanionPet; reduced: boolean; paused: boolean }) {+ const frames = useVoxelFrames(pet);+ const holder = useRef<Group>(null);+ const shown = useRef(-1);+ const clock = useRef(0);+ const capacity = frames ? Math.max(...frames.frames.map((f) => f.length)) : 0;+ const resources = useMemo(() => {+ if (!frames || capacity === 0) return null;+ const geometry = new BoxGeometry(1, 1, 1);+ const material = new MeshStandardMaterial({ roughness: 0.85 });+ const mesh = new InstancedMesh(geometry, material, capacity);+ mesh.castShadow = true;+ mesh.frustumCulled = false;+ return { mesh, geometry, material };+ }, [frames, capacity]);+ useEffect(() => () => {+ if (!resources) return;+ resources.mesh.dispose(); resources.geometry.dispose(); resources.material.dispose();+ }, [resources]);+ const scratch = useMemo(() => ({ matrix: new Matrix4(), colour: new Color(), parent: new Quaternion(), facing: new Quaternion(), up: new Vector3(0, 1, 0), at: new Vector3() }), []);+ useEffect(() => { shown.current = -1; }, [resources]);++ useFrame(({ camera }, dt) => {+ if (!frames || !resources || !holder.current) return;+ if (!paused && !reduced) clock.current += Math.min(dt, 0.1);+ const index = Math.floor(clock.current * (pet.idle?.fps ?? 6)) % frames.frames.length;+ if (index !== shown.current) {+ shown.current = index;+ const voxel = pet.heightM / (frames.maxY - frames.minY + 1);+ const centreX = (frames.minX + frames.maxX + 1) / 2;+ const { mesh } = resources;+ const list = frames.frames[index];+ for (let i = 0; i < list.length; i++) {+ const v = list[i];+ scratch.matrix.makeScale(voxel, voxel, voxel * 2);+ scratch.matrix.setPosition((v.x + 0.5 - centreX) * voxel, (v.y - frames.minY + 0.5) * voxel, 0);+ mesh.setMatrixAt(i, scratch.matrix);+ mesh.setColorAt(i, scratch.colour.setHex(v.color));+ }+ mesh.count = list.length;+ mesh.instanceMatrix.needsUpdate = true;+ if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;+ }+ // A cut-out reads best face on: keep turning it towards the camera.+ const group = holder.current;+ const parent = group.parent;+ group.getWorldPosition(scratch.at);+ const yaw = Math.atan2(camera.position.x - scratch.at.x, camera.position.z - scratch.at.z);+ scratch.facing.setFromAxisAngle(scratch.up, yaw);+ if (parent) {+ parent.getWorldQuaternion(scratch.parent);+ group.quaternion.copy(scratch.parent.invert().multiply(scratch.facing));+ } else group.quaternion.copy(scratch.facing);+ });++ return <group ref={holder}>{resources && <primitive object={resources.mesh} />}</group>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/companionPetStore.ts b/jarvis/ui/web/frontend/src/components/society/companion/companionPetStore.tsnew file mode 100644index 0000000000..68530cd15e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/companionPetStore.ts@@ -0,0 +1,34 @@+/**+ * The companion the Jarvis Verse draws for Jarvis, shared by every place in+ * the scene that shows it. The office stage feeds it from the pets query+ * (outside the WebGL canvas); the flyer and the lead walker read it inside.+ * The object only changes when the pet does, so a refetch never reloads a+ * model or a sprite sheet.+ */+import { useEffect } from "react";+import { create } from "zustand";+import { useActivePet } from "@/hooks/usePets";+import { companionFor, GIGI_COMPANION, type CompanionPet } from "./petCompanions";++interface CompanionPetState {+ pet: CompanionPet;+ setPet: (pet: CompanionPet) => void;+}++export function sameCompanion(a: CompanionPet, b: CompanionPet): boolean {+ return a.id === b.id && a.kind === b.kind && a.sheetUrl === b.sheetUrl && a.frameSize === b.frameSize+ && a.idle?.row === b.idle?.row && a.idle?.frames === b.idle?.frames && a.idle?.fps === b.idle?.fps;+}++export const useCompanionPet = create<CompanionPetState>((set, get) => ({+ pet: GIGI_COMPANION,+ setPet: (pet) => { if (!sameCompanion(get().pet, pet)) set({ pet }); },+}));++/** Keeps the shared companion in step with the pet chosen in My Pets. */+export function useSyncCompanionPet(): void {+ const active = useActivePet();+ const setPet = useCompanionPet((s) => s.setPet);+ // Until the pets answer arrives the last known companion stays (Gigi on a cold start).+ useEffect(() => { if (active) setPet(companionFor(active)); }, [active, setPet]);+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/petCompanions.test.ts b/jarvis/ui/web/frontend/src/components/society/companion/petCompanions.test.tsnew file mode 100644index 0000000000..db44e5963b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/petCompanions.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest";+import type { Pet } from "@/lib/petsApi";+import { BUILTIN_COMPANIONS, companionFlies, companionFor, GIGI_COMPANION } from "./petCompanions";+import { petModelUrl } from "./PetModel";++function pet(over: Partial<Pet>): Pet {+ return {+ id: "x", name: "X", description: "", builtin: false, frame_size: 48,+ animations: { idle: { row: 0, frames: 4, fps: 6, loop: true } }, sheet_url: "/api/pets/x/sheet.png", ...over,+ };+}++describe("companionFor", () => {+ it("is Gigi with no pet, and for the Gigi pet", () => {+ expect(companionFor(null)).toBe(GIGI_COMPANION);+ expect(companionFor(pet({ id: "gigi", builtin: true }))).toBe(GIGI_COMPANION);+ });++ it("gives every built-in pet its own model and a gait that fits it", () => {+ expect(companionFor(pet({ id: "ember", builtin: true })).gait).toBe("fly");+ expect(companionFor(pet({ id: "miso", builtin: true })).gait).toBe("walk");+ expect(companionFor(pet({ id: "shelly", builtin: true })).gait).toBe("crawl");+ for (const id of Object.keys(BUILTIN_COMPANIONS)) {+ expect(companionFor(pet({ id, builtin: true })).kind).toBe("model");+ expect(petModelUrl(id)).toBeTruthy();+ }+ });++ it("lets only the dragon fly among the built-ins, besides Gigi", () => {+ const flyers = Object.keys(BUILTIN_COMPANIONS).filter((id) => companionFlies(companionFor(pet({ id, builtin: true }))));+ expect(flyers).toEqual(["ember"]);+ expect(companionFlies(GIGI_COMPANION)).toBe(true);+ });++ it("turns a drawn pet into a floating voxel figure from its idle row", () => {+ const companion = companionFor(pet({ id: "u0123456789abcdef", animations: { idle: { row: 2, frames: 6, fps: 8, loop: true } } }));+ expect(companion).toMatchObject({+ kind: "voxel", gait: "float", sheetUrl: "/api/pets/x/sheet.png", frameSize: 48, idle: { row: 2, frames: 6, fps: 8 },+ });+ expect(companionFlies(companion)).toBe(true);+ });++ it("falls back to Gigi for a drawn pet without a usable idle row", () => {+ expect(companionFor(pet({ id: "u0123456789abcdef", animations: {} }))).toBe(GIGI_COMPANION);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/petCompanions.ts b/jarvis/ui/web/frontend/src/components/society/companion/petCompanions.tsnew file mode 100644index 0000000000..c4d85034c5--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/petCompanions.ts@@ -0,0 +1,68 @@+/**+ * Which 3D companion keeps the person company in the Jarvis Verse: the pet+ * chosen in Settings -> My Pets (`docs/pets.md`), Gigi when none is chosen.+ *+ * Built-in pets have an authored Blender model+ * (`art/studies/jarvis-pet-companions`, `scripts/art/build_pet_companions.py`)+ * and a way of moving that fits them: the dragon and Gigi fly, the cat walks,+ * the snail crawls. A pet the person drew themselves has only its sprite+ * sheet, so it becomes a voxel figure extruded from its idle frames and+ * floats low beside them.+ */+import type { Pet } from "@/lib/petsApi";++/** How a companion moves; everything but "fly" and "float" stays on the floor. */+export type PetGait = "fly" | "float" | "walk" | "waddle" | "hop" | "bounce" | "crawl";++export interface CompanionPet {+ id: string;+ /** Gigi keeps its own hover model; built-ins load their GLB; drawn pets become voxels. */+ kind: "gigi" | "model" | "voxel";+ gait: PetGait;+ /** Height of the companion in the office, metres (the toy figures are 1.3 m). */+ heightM: number;+ /** Height of the authored model in its GLB, metres (from the build report). */+ modelHeightM: number;+ /** Ground covered by one full gait cycle at office scale, metres; keeps feet from sliding. */+ strideM: number;+ /** Drawn pets: the sprite sheet and its idle row. */+ sheetUrl?: string;+ frameSize?: number;+ idle?: { row: number; frames: number; fps: number };+}++type BuiltinSpec = Omit<CompanionPet, "id" | "sheetUrl" | "frameSize" | "idle">;++export const GIGI_COMPANION: CompanionPet = { id: "gigi", kind: "gigi", gait: "fly", heightM: 0.5, modelHeightM: 0.4, strideM: 1 };++/** Model heights match `art/studies/jarvis-pet-companions/source/build-report.json`. */+export const BUILTIN_COMPANIONS: Readonly<Record<string, BuiltinSpec>> = {+ ember: { kind: "model", gait: "fly", heightM: 0.5, modelHeightM: 0.534, strideM: 1 },+ miso: { kind: "model", gait: "walk", heightM: 0.44, modelHeightM: 0.519, strideM: 0.42 },+ bolt: { kind: "model", gait: "waddle", heightM: 0.38, modelHeightM: 0.367, strideM: 0.3 },+ brew: { kind: "model", gait: "hop", heightM: 0.34, modelHeightM: 0.341, strideM: 0.5 },+ mochi: { kind: "model", gait: "bounce", heightM: 0.28, modelHeightM: 0.25, strideM: 0.45 },+ shelly: { kind: "model", gait: "crawl", heightM: 0.36, modelHeightM: 0.4, strideM: 0.28 },+};++/** A drawn pet floats at this height (its voxel figure), metres. */+export const VOXEL_HEIGHT_M = 0.42;++/** The companion for the pet the app draws as Jarvis (`pickActivePet`); null means Gigi. */+export function companionFor(pet: Pet | null | undefined): CompanionPet {+ if (!pet || pet.id === GIGI_COMPANION.id) return GIGI_COMPANION;+ const builtin = pet.builtin ? BUILTIN_COMPANIONS[pet.id] : undefined;+ if (builtin) return { id: pet.id, ...builtin };+ const idle = pet.animations?.idle;+ if (!pet.sheet_url || !idle || !(pet.frame_size > 0)) return GIGI_COMPANION;+ return {+ id: pet.id, kind: "voxel", gait: "float", heightM: VOXEL_HEIGHT_M, modelHeightM: VOXEL_HEIGHT_M, strideM: 1,+ sheetUrl: pet.sheet_url, frameSize: pet.frame_size,+ idle: { row: idle.row, frames: Math.max(1, idle.frames), fps: Math.max(1, idle.fps) },+ };+}++/** True for companions that stay in the air (Gigi, the dragon, drawn pets). */+export function companionFlies(pet: CompanionPet): boolean {+ return pet.gait === "fly" || pet.gait === "float";+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/petRig.test.ts b/jarvis/ui/web/frontend/src/components/society/companion/petRig.test.tsnew file mode 100644index 0000000000..3e89858ff1--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/petRig.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it } from "vitest";+import { BUILTIN_COMPANIONS, type CompanionPet } from "./petCompanions";+import { createRigState, rigPose, stepRig, type PetMood } from "./petRig";++const DT = 1 / 60;+const spec = (id: string): CompanionPet => ({ id, ...BUILTIN_COMPANIONS[id] });++describe("pet rig", () => {+ it("advances the gait by ground covered, so the paws never slide", () => {+ const miso = spec("miso");+ const slow = createRigState(), fast = createRigState();+ for (let i = 0; i < 30; i++) {+ stepRig(slow, miso, { dt: DT, speed: 0.5, mood: "idle", reduced: false });+ stepRig(fast, miso, { dt: DT, speed: 1, mood: "idle", reduced: false });+ }+ expect(slow.phase).toBeCloseTo(((0.5 * 30 * DT) / miso.strideM) * Math.PI * 2, 5);+ expect(fast.phase).toBeCloseTo((slow.phase * 2) % (Math.PI * 2), 5);+ });++ it("swings legs while walking and brings them to rest when standing", () => {+ const miso = spec("miso");+ const state = createRigState();+ let maxSwing = 0;+ for (let i = 0; i < 120; i++) {+ stepRig(state, miso, { dt: DT, speed: 1.2, mood: "idle", reduced: false });+ maxSwing = Math.max(maxSwing, Math.abs(rigPose(miso, state, "idle").get("miso_Leg_FL")!.rx));+ }+ expect(maxSwing).toBeGreaterThan(0.3);+ for (let i = 0; i < 240; i++) stepRig(state, miso, { dt: DT, speed: 0, mood: "idle", reduced: false });+ expect(Math.abs(rigPose(miso, state, "idle").get("miso_Leg_FL")!.rx)).toBeLessThan(0.05);+ });++ it("keeps the trot diagonal: front-left moves with back-right", () => {+ const miso = spec("miso");+ const state = createRigState();+ for (let i = 0; i < 40; i++) stepRig(state, miso, { dt: DT, speed: 1, mood: "idle", reduced: false });+ const pose = rigPose(miso, state, "idle");+ expect(pose.get("miso_Leg_FL")!.rx).toBeCloseTo(pose.get("miso_Leg_BR")!.rx);+ expect(pose.get("miso_Leg_FL")!.rx).toBeCloseTo(-pose.get("miso_Leg_FR")!.rx);+ });++ it("beats the dragon's wings in mirror image", () => {+ const ember = spec("ember");+ const state = createRigState();+ for (let i = 0; i < 17; i++) stepRig(state, ember, { dt: DT, speed: 0, mood: "idle", reduced: false });+ const pose = rigPose(ember, state, "idle");+ expect(pose.get("ember_Wing_L")!.rz).toBeCloseTo(-pose.get("ember_Wing_R")!.rz);+ expect(Math.abs(pose.get("ember_Wing_R")!.rz)).toBeGreaterThan(0);+ });++ it("closes the eyes asleep and freezes every gait under reduced motion", () => {+ const moods: PetMood[] = ["idle", "work", "talk", "sleep"];+ for (const id of Object.keys(BUILTIN_COMPANIONS)) {+ const pet = spec(id);+ for (const mood of moods) {+ const state = createRigState();+ for (let i = 0; i < 90; i++) stepRig(state, pet, { dt: DT, speed: 1.5, mood, reduced: true });+ expect(state.stride).toBe(0);+ expect(state.t).toBe(0);+ const pose = rigPose(pet, state, mood);+ for (const motion of pose.values()) {+ for (const value of Object.values(motion)) expect(Number.isFinite(value)).toBe(true);+ }+ const eye = pose.get(`${id}_Eye_L`);+ expect(eye).toBeDefined();+ if (mood === "sleep") expect(eye!.sy).toBeLessThan(0.2);+ }+ }+ });++ it("fills the battery's charge bars one by one while working", () => {+ const bolt = spec("bolt");+ const state = createRigState();+ const levels = new Set<number>();+ for (let i = 0; i < 120; i++) {+ stepRig(state, bolt, { dt: DT, speed: 0, mood: "work", reduced: false });+ const pose = rigPose(bolt, state, "work");+ levels.add([1, 2, 3].filter((n) => pose.get(`bolt_Bar_${n}`)!.sx > 0.5).length);+ }+ expect([...levels].sort()).toEqual([0, 1, 2, 3]);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/petRig.ts b/jarvis/ui/web/frontend/src/components/society/companion/petRig.tsnew file mode 100644index 0000000000..e1432a9505--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/petRig.ts@@ -0,0 +1,224 @@+/**+ * Procedural motion of the authored 3D pets (`petCompanions.ts`). The GLBs+ * carry no animation clips; every animated part hangs under a named pivot+ * (`miso_Leg_FL`, `ember_Wing_L`, …) and this module says how each pivot+ * moves, as an offset from its authored pose.+ *+ * Gait phase advances with ground actually covered (`strideM`), so a cat's+ * paws or a snail's ripple never slide over the floor; standing still settles+ * every gait back to rest. Pure and allocation-free per step when the caller+ * reuses `out`.+ */+import type { CompanionPet } from "./petCompanions";++/** Offset from a part's authored transform: radians, metres and scale factors. */+export interface PartMotion {+ rx: number;+ ry: number;+ rz: number;+ dy: number;+ sx: number;+ sy: number;+ sz: number;+}++export type PetMood = "idle" | "work" | "talk" | "sleep";++export interface RigState {+ /** Gait phase in radians; one full cycle covers `strideM` of ground. */+ phase: number;+ /** 0 standing .. 1 walking, smoothed so starts and stops ease. */+ stride: number;+ /** 0 open .. 1 shut. */+ blink: number;+ t: number;+}++export interface RigInput {+ dt: number;+ /** Ground speed, m/s. */+ speed: number;+ mood: PetMood;+ reduced: boolean;+}++/** Walking pace at which a gait reaches full swing, m/s. */+export const FULL_STRIDE_SPEED = 0.9;+const BLINK_PERIOD_S = 4.3;+const BLINK_S = 0.14;+const TAU = Math.PI * 2;++export function createRigState(): RigState {+ return { phase: 0, stride: 0, blink: 0, t: 0 };+}++export function restMotion(): PartMotion {+ return { rx: 0, ry: 0, rz: 0, dy: 0, sx: 1, sy: 1, sz: 1 };+}++function clamp(value: number, min: number, max: number): number {+ return value < min ? min : value > max ? max : value;+}++/** Advances phase, stride and blink. Reduced motion holds everything at rest. */+export function stepRig(state: RigState, pet: CompanionPet, input: RigInput): void {+ const dt = Number.isFinite(input.dt) ? clamp(input.dt, 0, 0.1) : 0;+ const speed = Number.isFinite(input.speed) ? Math.max(0, input.speed) : 0;+ if (input.reduced) {+ state.stride = 0;+ state.blink = input.mood === "sleep" ? 1 : 0;+ return;+ }+ state.t += dt;+ const target = clamp(speed / FULL_STRIDE_SPEED, 0, 1);+ state.stride += (target - state.stride) * (1 - Math.exp(-8 * dt));+ if (speed > 0.02) state.phase = (state.phase + (speed * dt / Math.max(0.05, pet.strideM)) * TAU) % TAU;+ else if (state.stride < 0.05) {+ // Standing: let the gait run out to a neutral pose instead of freezing mid-step.+ const settle = state.phase % Math.PI;+ if (settle > 0.02 && settle < Math.PI - 0.02) state.phase = (state.phase + dt * 3) % TAU;+ }+ if (input.mood === "sleep") state.blink = 1;+ else state.blink = state.t % BLINK_PERIOD_S < BLINK_S ? 1 : 0;+}++type Parts = Map<string, PartMotion>;++function part(out: Parts, name: string): PartMotion {+ let motion = out.get(name);+ if (!motion) { motion = restMotion(); out.set(name, motion); }+ else { motion.rx = motion.ry = motion.rz = motion.dy = 0; motion.sx = motion.sy = motion.sz = 1; }+ return motion;+}++function eyes(out: Parts, id: string, blink: number): void {+ for (const side of ["L", "R"]) part(out, `${id}_Eye_${side}`).sy = 1 - 0.9 * blink;+}++/**+ * The pose of every animated part for this frame. Parts that are not named+ * stay at their authored transform.+ */+export function rigPose(pet: CompanionPet, state: RigState, mood: PetMood, out: Parts = new Map()): Parts {+ const { phase: p, stride: s, t } = state;+ const talk = mood === "talk" ? 1 : 0;+ const sleep = mood === "sleep" ? 1 : 0;+ const work = mood === "work" ? 1 : 0;+ switch (pet.id) {+ case "miso": {+ // Trot: diagonal pairs swing together.+ const swing = 0.6 * s;+ part(out, "miso_Leg_FL").rx = swing * Math.sin(p);+ part(out, "miso_Leg_BR").rx = swing * Math.sin(p);+ part(out, "miso_Leg_FR").rx = swing * Math.sin(p + Math.PI);+ part(out, "miso_Leg_BL").rx = swing * Math.sin(p + Math.PI);+ const body = part(out, "miso_Body");+ body.dy = 0.01 * s * Math.abs(Math.cos(p)) - 0.03 * sleep;+ body.sy = 1 + 0.02 * Math.sin(t * 1.6) * (1 - s);+ const head = part(out, "miso_Head");+ head.rx = 0.06 * s * Math.sin(2 * p) + 0.12 * sleep;+ head.ry = 0.3 * Math.sin(t * 0.45) * (1 - s) * (1 - sleep);+ head.rz = 0.16 * talk * Math.sin(t * 3.2);+ head.dy = -0.04 * sleep;+ const tail = part(out, "miso_Tail");+ tail.rz = 0.32 * Math.sin(t * 2.1) * (1 - 0.5 * s) + 0.15 * s * Math.sin(p);+ tail.rx = 0.18 * s - 0.25 * sleep;+ // A quick ear flick every few seconds.+ const flick = (t % 5.3) < 0.18 ? Math.sin(((t % 5.3) / 0.18) * Math.PI) : 0;+ part(out, "miso_Ear_L").rz = 0.35 * flick;+ part(out, "miso_Ear_R").rz = -0.12 * flick;+ eyes(out, "miso", state.blink);+ break;+ }+ case "ember": {+ // Wings beat faster in travel; a lazy beat while hovering.+ const beat = Math.sin(t * TAU * (2.2 + 1.6 * s + 1.2 * talk));+ const flap = sleep ? 0.25 : 0.15 + 0.55 * beat;+ part(out, "ember_Wing_R").rz = flap;+ part(out, "ember_Wing_L").rz = -flap;+ const dangle = 0.2 + 0.25 * s + 0.08 * Math.sin(t * TAU * 1.1);+ part(out, "ember_Leg_L").rx = dangle;+ part(out, "ember_Leg_R").rx = dangle;+ part(out, "ember_Arm_L").rx = -0.25 + 0.12 * Math.sin(t * 3 + 1) - 0.5 * talk * Math.abs(Math.sin(t * 5));+ part(out, "ember_Arm_R").rx = -0.25 + 0.12 * Math.sin(t * 3);+ const tail = part(out, "ember_Tail");+ tail.ry = 0.35 * Math.sin(t * 1.8);+ tail.rx = -0.25 * s;+ const head = part(out, "ember_Head");+ head.rx = 0.08 * Math.sin(t * 1.3) + 0.1 * sleep;+ head.rz = 0.12 * talk * Math.sin(t * 3);+ eyes(out, "ember", state.blink);+ break;+ }+ case "bolt": {+ const step = Math.sin(p);+ const left = part(out, "bolt_Foot_L"), right = part(out, "bolt_Foot_R");+ left.rx = 0.5 * s * step; left.dy = 0.03 * s * Math.max(0, step);+ right.rx = -0.5 * s * step; right.dy = 0.03 * s * Math.max(0, -step);+ const body = part(out, "bolt_Body");+ body.rz = 0.1 * s * step + 0.05 * talk * Math.sin(t * 6);+ body.dy = 0.012 * s * Math.abs(step);+ part(out, "bolt_Arm_L").rx = -0.6 * s * step;+ const wave = part(out, "bolt_Arm_R");+ wave.rx = 0.6 * s * step;+ wave.rz = talk * (0.9 + 0.35 * Math.sin(t * 9));+ // Working: the charge bars fill one after another, then start over.+ const level = work ? Math.floor((t * 2.5) % 4) : 3;+ for (let i = 1; i <= 3; i++) {+ const bar = part(out, `bolt_Bar_${i}`);+ bar.sx = i <= level ? 1 : 0.02;+ }+ eyes(out, "bolt", state.blink);+ break;+ }+ case "brew": {+ const air = Math.max(0, Math.sin(p));+ const ground = Math.max(0, -Math.sin(p));+ const body = part(out, "brew_Body");+ body.dy = 0.06 * s * air;+ body.sy = 1 - 0.09 * s * ground + 0.015 * Math.sin(t * 1.7) * (1 - s);+ body.sx = body.sz = 1 + 0.045 * s * ground;+ body.rz = 0.05 * s * Math.sin(p * 0.5);+ // The lid rattles on every landing, and while Brew talks.+ const lid = part(out, "brew_Lid");+ lid.dy = 0.012 * s * ground + 0.012 * talk * Math.abs(Math.sin(t * 17));+ lid.rz = 0.1 * talk * Math.sin(t * 13) + 0.06 * s * Math.sin(p * 2);+ eyes(out, "brew", state.blink);+ break;+ }+ case "mochi": {+ const lift = Math.sin(p);+ const body = part(out, "mochi_Body");+ const jiggle = (0.035 + 0.04 * talk) * Math.sin(t * (2.4 + 6 * talk));+ body.sy = 1 + 0.16 * s * lift + jiggle * (1 - s) - 0.08 * sleep;+ const across = 1 / Math.sqrt(Math.max(0.5, body.sy));+ body.sx = across; body.sz = across;+ body.dy = 0.05 * s * Math.max(0, lift);+ eyes(out, "mochi", state.blink);+ break;+ }+ case "shelly": {+ // The foot ripples front to back; the shell rides the wave.+ const body = part(out, "shelly_Body");+ body.sz = 1 + 0.07 * s * Math.sin(p);+ body.sx = 1 - 0.025 * s * Math.sin(p);+ const shell = part(out, "shelly_Shell");+ shell.dy = 0.006 * s * Math.sin(p + 1) - 0.02 * sleep;+ shell.rz = 0.04 * s * Math.sin(p) + 0.05 * talk * Math.sin(t * 4);+ const head = part(out, "shelly_Head");+ head.ry = 0.25 * Math.sin(t * 0.5) * (1 - s);+ head.rx = 0.1 * talk * Math.sin(t * 5) + 0.3 * sleep;+ for (const [side, offset] of [["L", 0], ["R", 1.7]] as const) {+ const stalk = part(out, `shelly_Stalk_${side}`);+ stalk.rx = 0.16 * Math.sin(t * 1.3 + offset) - 0.15 * s;+ stalk.rz = 0.14 * Math.sin(t * 1.05 + offset * 2);+ stalk.sy = 1 - 0.55 * sleep;+ }+ eyes(out, "shelly", state.blink);+ break;+ }+ default:+ break;+ }+ return out;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/voxelPet.test.ts b/jarvis/ui/web/frontend/src/components/society/companion/voxelPet.test.tsnew file mode 100644index 0000000000..1ef3664d7d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/voxelPet.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from "vitest";+import { MAX_VOXELS_PER_FRAME, voxelFrames } from "./voxelPet";++/** A sheet of `frames` cells of `size` px per row, with the given opaque pixels (frame, x, y from the top). */+function sheet(size: number, frames: number, rows: number, opaque: [number, number, number][]) {+ const width = size * frames, height = size * rows;+ const data = new Uint8ClampedArray(width * height * 4);+ for (const [f, x, y] of opaque) data.set([0x12, 0x34, 0x56, 255], (y * width + f * size + x) * 4);+ return { data, width, height };+}++describe("voxelFrames", () => {+ it("makes one cube per opaque pixel, counted from the bottom edge", () => {+ const { data, width, height } = sheet(4, 2, 1, [[0, 1, 3], [0, 2, 0], [1, 0, 3]]);+ const result = voxelFrames(data, width, height, 4, 0, 2)!;+ expect(result.frames).toHaveLength(2);+ expect(result.frames[0]).toEqual([{ x: 2, y: 3, color: 0x123456 }, { x: 1, y: 0, color: 0x123456 }]);+ expect(result.frames[1]).toEqual([{ x: 0, y: 0, color: 0x123456 }]);+ expect(result).toMatchObject({ minX: 0, maxX: 2, minY: 0, maxY: 3 });+ });++ it("ignores half-transparent pixels like the desktop overlay does", () => {+ const { data, width, height } = sheet(4, 1, 1, [[0, 1, 1]]);+ data[(1 * width + 1) * 4 + 3] = 127;+ expect(voxelFrames(data, width, height, 4, 0, 1)).toBeNull();+ });++ it("refuses rows outside the sheet and oversized frames", () => {+ const small = sheet(4, 1, 1, [[0, 0, 0]]);+ expect(voxelFrames(small.data, small.width, small.height, 4, 1, 1)).toBeNull();+ const size = 66;+ const every: [number, number, number][] = [];+ for (let i = 0; i < size * size; i++) every.push([0, i % size, Math.floor(i / size)]);+ const full = sheet(size, 1, 1, every);+ expect(size * size).toBeGreaterThan(MAX_VOXELS_PER_FRAME);+ expect(voxelFrames(full.data, full.width, full.height, size, 0, 1)).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/voxelPet.ts b/jarvis/ui/web/frontend/src/components/society/companion/voxelPet.tsnew file mode 100644index 0000000000..bc0b427456--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/voxelPet.ts@@ -0,0 +1,58 @@+/**+ * A pet the person drew themselves has no authored model, only its sprite+ * sheet. This turns the idle row into voxel frames: every opaque pixel+ * (alpha >= 128, the same rule the desktop overlay uses) becomes one cube.+ * Pure, so it is tested without a canvas.+ */++export interface Voxel {+ /** Column from the frame's left edge, row from its bottom edge. */+ x: number;+ y: number;+ /** 0xRRGGBB. */+ color: number;+}++export interface VoxelFrames {+ frames: Voxel[][];+ /** Shared bounds over all frames, so the figure never jumps between frames. */+ minX: number;+ maxX: number;+ minY: number;+ maxY: number;+}++/** More cubes than this in one frame and the sheet is treated as unusable. */+export const MAX_VOXELS_PER_FRAME = 4096;++export function voxelFrames(+ data: ArrayLike<number>, sheetWidth: number, sheetHeight: number,+ frameSize: number, row: number, frames: number,+): VoxelFrames | null {+ if (!(frameSize > 0) || row < 0 || frames < 1) return null;+ const top = row * frameSize;+ if (top + frameSize > sheetHeight) return null;+ const out: Voxel[][] = [];+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;+ for (let f = 0; f < frames; f++) {+ const left = f * frameSize;+ if (left + frameSize > sheetWidth) break;+ const voxels: Voxel[] = [];+ for (let py = 0; py < frameSize; py++) {+ for (let px = 0; px < frameSize; px++) {+ const i = ((top + py) * sheetWidth + left + px) * 4;+ if (data[i + 3] < 128) continue;+ const y = frameSize - 1 - py;+ voxels.push({ x: px, y, color: (data[i] << 16) | (data[i + 1] << 8) | data[i + 2] });+ if (px < minX) minX = px;+ if (px > maxX) maxX = px;+ if (y < minY) minY = y;+ if (y > maxY) maxY = y;+ }+ }+ if (voxels.length > MAX_VOXELS_PER_FRAME) return null;+ out.push(voxels);+ }+ if (out.length === 0 || !Number.isFinite(minX)) return null;+ return { frames: out, minX, maxX, minY, maxY };+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/GigiFlyer.tsx b/jarvis/ui/web/frontend/src/components/society/office/GigiFlyer.tsxindex d9052ab19b..b1ee80ba1a 100644--- a/jarvis/ui/web/frontend/src/components/society/office/GigiFlyer.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/GigiFlyer.tsx@@ -1,11 +1,14 @@/**- * The lead agent (Jarvis) as it appears in the office: not a figure but Gigi,- * the mascot, flying at chest/head height above the walker's ground position.+ * The lead agent (Jarvis) as it appears in the office: not a figure but the+ * person's pet from My Pets (Gigi when none is chosen), in 3D. Gigi and the+ * dragon fly at chest/head height above the walker's ground position; a cat,+ * snail, teapot, battery or jelly walks, crawls or hops on the floor+ * (`petCompanions.ts`); a pet the person drew floats as a voxel figure.*- * Motion comes from the pure `gigiFlight.ts`; this component only renders it- * with a few cheap effects: an additive halo behind Gigi, a small glow under- * its hover emitter, a recycled sparkle trail while travelling and a soft- * shadow blob on the floor. Everything is one draw call each, no lights.+ * Motion comes from the pure `gigiFlight.ts` (its `ground` mode for pets on+ * the floor), the pet's own limbs from `petRig.ts`. Flyers get a few cheap+ * effects: an additive halo, a small glow under the body, a recycled sparkle+ * trail while travelling. Every companion casts a soft shadow blob.*/import { Component, Suspense, useEffect, useMemo, useRef, type ReactNode } from "react";import { useFrame } from "@react-three/fiber";@@ -15,6 +18,10 @@ import {} from "three";import { CompanionModel } from "../companion/AgentFollower";import { defaultCompanion } from "../companion/appearance";+import { useCompanionPet } from "../companion/companionPetStore";+import { companionFlies, type CompanionPet } from "../companion/petCompanions";+import { PetModel, VoxelPet, type PetDrive } from "../companion/PetModel";+import type { PetMood } from "../companion/petRig";import { createGigiFlight, createGigiPose, followAnchor, stepGigiFlight, type GigiFlightMode } from "./gigiFlight";import { cameraView } from "./officeStore";@@ -84,11 +91,33 @@ function releaseTextures(): void {cache.shadow.dispose();}-/** A missing or broken GLB hides Gigi's body; the glow still marks the lead. */+/** The pet's mood for its limbs: what Jarvis is doing right now. */+function moodFor(mode: GigiFlightMode, speaking: boolean): PetMood {+ if (speaking || mode === "talk" || mode === "wave") return "talk";+ if (mode === "work") return "work";+ if (mode === "sleep") return "sleep";+ return "idle";+}++/** Lift from the flight point (body centre for flyers, the floor for walkers) to the model's origin. */+function bodyOffset(pet: CompanionPet, ground: boolean): number {+ if (ground) return 0;+ return pet.kind === "gigi" ? MODEL_CENTRE_OFFSET : -pet.heightM / 2;+}++function CompanionBody({ pet, drive, reduced, paused, gigi }: {+ pet: CompanionPet; drive: { current: PetDrive }; reduced: boolean; paused: boolean; gigi: ReactNode;+}) {+ if (pet.kind === "model") return <PetModel pet={pet} drive={drive} reduced={reduced} paused={paused} />;+ if (pet.kind === "voxel") return <VoxelPet pet={pet} reduced={reduced} paused={paused} />;+ return <>{gigi}</>;+}++/** A missing or broken GLB hides the companion's body; the glow still marks the lead. */class ModelBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {state = { failed: false };static getDerivedStateFromError() { return { failed: true }; }- componentDidCatch(error: Error) { console.warn("Gigi model unavailable", error.name); }+ componentDidCatch(error: Error) { console.warn("Companion model unavailable", error.name); }render() { return this.state.failed ? null : this.props.children; }}@@ -125,6 +154,11 @@ export function GigiFlyer({ owner, mode, speaking, paused, reduced, clear }: {const side = useRef<1 | -1>(1);const tint = useMemo(() => new Color(), []);const appearance = useMemo(() => ({ ...defaultCompanion("jarvis"), sizeM: GIGI_OFFICE_SIZE_M }), []);+ const pet = useCompanionPet((s) => s.pet);+ const ground = !companionFlies(pet);+ const groundRef = useRef(ground);+ groundRef.current = ground;+ const drive = useRef<PetDrive>({ speed: 0, mood: "idle" });const textures = useMemo(() => sharedTextures(), []);useEffect(() => { acquireTextures(); return releaseTextures; }, []);@@ -150,17 +184,20 @@ export function GigiFlyer({ owner, mode, speaking, paused, reduced, clear }: {last.current.x = m.x; last.current.z = m.z;let targetX = m.x, targetZ = m.z;if (mode === "follow") {- const anchor = followAnchor(m.x, m.z, m.heading, side.current, clear);+ const anchor = followAnchor(m.x, m.z, m.heading, side.current, clear, groundRef.current);side.current = anchor.side;targetX = anchor.x; targetZ = anchor.z;}+ const onFloor = groundRef.current;stepGigiFlight(flight.current, {- targetX, targetZ, moving, mode, speaking, t: clock.current, dt, heading: m.heading, reduced, clear,+ targetX, targetZ, moving, mode, speaking, t: clock.current, dt, heading: m.heading, reduced, clear, ground: onFloor,}, pose);+ drive.current.speed = pose.speed;+ drive.current.mood = moodFor(mode, speaking);// Gigi hovers at head height beside the person: seated in first person that is right in// front of the eyes, so close by it steps out of the picture until the person stands up.- const hidden = cameraView.firstPerson && Math.hypot(pose.x - cameraView.x, pose.z - cameraView.z) < FIRST_PERSON_CLEARANCE_M;+ const hidden = !onFloor && cameraView.firstPerson && Math.hypot(pose.x - cameraView.x, pose.z - cameraView.z) < FIRST_PERSON_CLEARANCE_M;if (root.current) root.current.visible = !hidden;if (shadow.current) shadow.current.visible = !hidden;if (root.current) root.current.position.set(pose.x, pose.y, pose.z);@@ -198,15 +235,16 @@ export function GigiFlyer({ owner, mode, speaking, paused, reduced, clear }: {});}if (shadow.current) {- const lift = Math.max(0, pose.y - 0.4);+ const lift = onFloor ? 0 : Math.max(0, pose.y - 0.4);(shadow.current.material as MeshBasicMaterial).opacity = Math.max(0.08, 0.34 - lift * 0.22);shadow.current.position.set(pose.x, 0.012, pose.z);- shadow.current.scale.setScalar(0.85 + lift * 0.35);+ // A pet on the floor gets a contact shadow its own size; a flyer's spreads as it rises.+ shadow.current.scale.setScalar(onFloor ? Math.max(0.5, pet.heightM * 1.7) : 0.85 + lift * 0.35);}// Sparkle trail: a fixed pool recycled round-robin, faded by age.const { positions, colours, age, rise } = particles;- if (moving && !reduced && pose.speed > 0.1) {+ if (moving && !reduced && !onFloor && pose.speed > 0.1) {emitDebt.current += dt * TRAIL_RATE;while (emitDebt.current >= 1) {emitDebt.current -= 1;@@ -239,6 +277,7 @@ export function GigiFlyer({ owner, mode, speaking, paused, reduced, clear }: {return (<><group ref={root} position={[owner.current.x, pose.y, owner.current.z]}>+ {!ground && <><sprite ref={halo} scale={0.9} renderOrder={1}><spriteMaterial map={textures.glow} color={GLOW_WARM} transparent opacity={0.35} blending={AdditiveBlending} depthWrite={false} /></sprite>@@ -253,10 +292,14 @@ export function GigiFlyer({ owner, mode, speaking, paused, reduced, clear }: {</sprite>))}</group>+ </>}<group ref={body}>- <group position={[0, MODEL_CENTRE_OFFSET, 0]}>- <ModelBoundary>- <Suspense fallback={null}><CompanionModel appearance={appearance} lead /></Suspense>+ <group position={[0, bodyOffset(pet, ground), 0]}>+ <ModelBoundary key={pet.id}>+ <Suspense fallback={null}>+ <CompanionBody pet={pet} drive={drive} reduced={reduced} paused={paused}+ gigi={<CompanionModel appearance={appearance} lead />} />+ </Suspense></ModelBoundary></group></group>diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsxindex a731a7b9d8..9a158799a7 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx@@ -23,6 +23,8 @@ import { OFFICE } from "./officePalette";import type { DeskSlot, OfficeLayout, Point } from "./officeLayout";import { findPath, isWalkable, type NavGrid } from "./officeNav";import { AgentFollower } from "../companion/AgentFollower";+import { useCompanionPet } from "../companion/companionPetStore";+import { companionFlies } from "../companion/petCompanions";import { resolveCompanion } from "../companion/appearance";import type { TrailPoint } from "../companion/trail";import { stepMover, stepMoverAvoiding, turnToward, WALK_SPEED, type Mover } from "./officeMotion";@@ -47,6 +49,10 @@ const PLAYER_OWNER = { current: player };/** Farther than this from the person's shoulder and Gigi flies back first instead of hovering beside them. */const FOLLOW_CATCH_M = 1;+/** Height of the lead's nameplate: above a flying companion, or low above a pet on the floor. */+const LEAD_PLATE_FLYING_M = 1.75;+const LEAD_PLATE_ON_FLOOR_M = 0.85;+/** Every figure shares one toy scale, so desks and couches read the same everywhere. */export const OFFICE_FIGURE_HEIGHT_M = 1.3;@@ -68,7 +74,7 @@ export function plateScale(distance: number): number {const RING_COLOUR = { working: OFFICE.ringWorking, idle: OFFICE.ringIdle, waiting: OFFICE.ringWaiting, paused: OFFICE.ringPaused } as const;-/** Jarvis is not a person in the office: it is Gigi, flying at chest height. */+/** Jarvis is not a person in the office: it is the person's pet (Gigi by default), flying or on the floor. */function gigiModeFor(pose: Pose | null, travelling: boolean): GigiFlightMode {if (travelling || !pose) return "idle";if (pose === "sit" || pose === "work") return "work";@@ -231,6 +237,11 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,const followingRef = useRef(false);const gigiSide = useRef<1 | -1>(1);const airClear = useMemo(() => (x: number, z: number) => isWalkable(ctx.grid, { x, z }), [ctx.grid]);+ // The lead is drawn as the person's pet; one that walks takes floor routes instead of flying over desks.+ const petOnFloor = useCompanionPet((s) => isGigi && !companionFlies(s.pet));+ const onFloorRef = useRef(petOnFloor);+ onFloorRef.current = petOnFloor;+ const routeGoal = useRef<Point | null>(null);// Leaving the office releases the agent's spot and its registry entry.useEffect(() => () => {@@ -249,6 +260,14 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,const dt = Math.min(rawDt, 0.1);const now = Date.now();const m = mover.current;+ // A flyer heads straight for its goal; a pet on the floor walks a route, re-planned only when the goal moves.+ const headFor = (goal: Point) => {+ if (!onFloorRef.current) { m.path = [goal]; return; }+ const last = routeGoal.current;+ if (last && m.path.length > 0 && Math.hypot(last.x - goal.x, last.z - goal.z) < 0.4) return;+ routeGoal.current = { x: goal.x, z: goal.z };+ m.path = findPath(ctx.grid, m, goal) ?? [goal];+ };// Gigi on an errand: fly straight to the recipient, hover and deliver, then back to its day.const errand = isGigi ? useGigiErrands.getState().current : null;const recipient = errand ? agentPositions.get(errand.to) : undefined;@@ -259,8 +278,12 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,const key = `${errand.id}:${errand.phase}`;if (errand.phase === "fly") {const spot = deliverySpot(recipient, m);- const end = m.path[m.path.length - 1];- if (errandKey.current !== key || !end || Math.hypot(end.x - spot.x, end.z - spot.z) > 0.4) m.path = [spot];+ if (errandKey.current !== key) routeGoal.current = null;+ if (onFloorRef.current) headFor(spot);+ else {+ const end = m.path[m.path.length - 1];+ if (errandKey.current !== key || !end || Math.hypot(end.x - spot.x, end.z - spot.z) > 0.4) m.path = [spot];+ }if (reduced) { m.x = spot.x; m.z = spot.z; m.path = []; }const { arrived } = stepMover(m, ERRAND_SPEED, dt);if (arrived) useGigiErrands.getState().arrive(errand.id);@@ -284,15 +307,15 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,const calledTo = summon && summon.untilMs > now ? summon.target : null;if (isGigi && !calledTo) {// Gigi keeps the person company, as on the coding floor; an errand or a summons still takes it away.- const anchor = followAnchor(player.x, player.z, player.heading, gigiSide.current, airClear);+ const anchor = followAnchor(player.x, player.z, player.heading, gigiSide.current, airClear, onFloorRef.current);gigiSide.current = anchor.side;const far = Math.hypot(anchor.x - m.x, anchor.z - m.z) > FOLLOW_CATCH_M;if (!placed.current || reduced || !far) {m.x = anchor.x; m.z = anchor.z; m.path = [];placed.current = true;} else if (awake) {- // Back from an errand or a meeting: fly over to the person, then fall in beside them.- m.path = [anchor];+ // Back from an errand or a meeting: fly (or run) over to the person, then fall in beside them.+ headFor(anchor);stepMover(m, ERRAND_SPEED, dt);}const nowFollowing = Math.hypot(anchor.x - m.x, anchor.z - m.z) <= FOLLOW_CATCH_M;@@ -340,7 +363,7 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,} else {m.path = findPath(ctx.grid, m, next.target) ?? [];// Gigi flies: after an errand it may hover over a desk, where no floor path starts.- if (m.path.length === 0 && isGigi && Math.hypot(next.target.x - m.x, next.target.z - m.z) > 0.05) m.path = [next.target];+ if (m.path.length === 0 && isGigi && !onFloorRef.current && Math.hypot(next.target.x - m.x, next.target.z - m.z) > 0.05) m.path = [next.target];if (m.path.length === 0) { m.x = next.target.x; m.z = next.target.z; }phase.current = m.path.length > 0 ? "travel" : "dwell";if (phase.current === "dwell") dwellUntil.current = now + next.dwellMs;@@ -380,6 +403,8 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,}});+ // A pet on the floor carries its name low, just above its head; a flyer's sits above its hover height.+ const leadPlate = petOnFloor ? LEAD_PLATE_ON_FLOOR_M : LEAD_PLATE_FLYING_M;return (<><group ref={group} userData={{ agentId: agent.agentId }}>@@ -393,9 +418,9 @@ function Walker({ agent, desk, ctx, arrivesByElevator, awake, reduced, selected,onPointerOut={() => { document.body.style.cursor = ""; }}>{!isGigi && <ToyFigure look={look} drive={drive} paused={!awake} heightM={OFFICE_FIGURE_HEIGHT_M} seatHeight={seatHeight} />}</group>- <Nameplate agent={agent} activity={activity} selected={selected} onSelect={onSelect} height={isGigi ? 1.75 : undefined} />+ <Nameplate agent={agent} activity={activity} selected={selected} onSelect={onSelect} height={isGigi ? leadPlate : undefined} /><AgentBubble agent={agent} lines={lines} selected={selected} onSelect={onSelect}- height={(isGigi ? 1.75 : OFFICE_FIGURE_HEIGHT_M + 0.35) + 0.14} />+ height={(isGigi ? leadPlate : OFFICE_FIGURE_HEIGHT_M + 0.35) + 0.14} /></group>{carrying && <ErrandEnvelope owner={group} />}{isGigidiff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsxindex f31540d6e7..6bbfdb7035 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx@@ -69,7 +69,7 @@ function FloorArrival({ floor, layout, grid, ready }: { floor: OfficeFloor; layoreturn null;}-/** On the coding floor Jarvis is nobody's desk mate: Gigi flies along with the person. */+/** On the coding floor Jarvis is nobody's desk mate: the person's pet (Gigi by default) comes along. */function GigiCompanion({ grid, awake, reduced }: { grid: NavGrid; awake: boolean; reduced: boolean }) {const speaking = useEventStore((s) => s.voiceState === "speaking");const clear = useMemo(() => (x: number, z: number) => isWalkable(grid, { x, z }), [grid]);diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsxindex c1bfe90b26..5813894317 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx@@ -8,6 +8,7 @@*/import { Component, lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { useQueryClient } from "@tanstack/react-query";+import { useSyncCompanionPet } from "../companion/companionPetStore";import { advance, Canvas } from "@react-three/fiber";import { useReducedMotion } from "framer-motion";import { useCanvasAwake } from "@/hooks/useCanvasAwake";@@ -132,6 +133,8 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenconst coding = floor === "coding";const roster = useSocietyRoster();useRosterRefresh(awake && !coding);+ // Jarvis keeps the person company as the pet chosen in My Pets.+ useSyncCompanionPet();const [overview, setOverview] = useState(0);const [mapOpen, setMapOpen] = useState(false);const [profile, setProfile] = useState<PlayerProfile>(loadProfile);diff --git a/jarvis/ui/web/frontend/src/components/society/office/gigiFlight.test.ts b/jarvis/ui/web/frontend/src/components/society/office/gigiFlight.test.tsindex 8f239fac80..1b954277fa 100644--- a/jarvis/ui/web/frontend/src/components/society/office/gigiFlight.test.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/gigiFlight.test.ts@@ -7,6 +7,38 @@ import {const MODES: GigiFlightMode[] = ["idle", "work", "talk", "wave", "sleep", "follow"];const DT = 1 / 60;+describe("a pet on the floor (ground mode)", () => {+ it("lands on the floor, never leans or banks, and hops only while standing happy", () => {+ const state = createGigiFlight(0, 0);+ const pose = createGigiPose();+ let maxStandingY = 0;+ for (let t = 0; t < 20; t += DT) {+ const moving = t > 10;+ stepGigiFlight(state, {+ targetX: moving ? (t - 10) * 1.2 : 0, targetZ: 0, moving, mode: "follow", speaking: !moving, t, dt: DT, ground: true,+ }, pose);+ expect(pose.y).toBeGreaterThanOrEqual(0);+ if (t > 4) {+ expect(pose.pitch).toBeCloseTo(0, 6);+ expect(pose.roll).toBeCloseTo(0, 6);+ }+ if (t > 6 && !moving) maxStandingY = Math.max(maxStandingY, pose.y);+ if (t > 12) expect(pose.y).toBeLessThan(0.02);+ }+ expect(maxStandingY).toBeGreaterThan(0.02);+ expect(maxStandingY).toBeLessThan(0.1);+ });++ it("falls in right behind the person instead of beside the shoulder", () => {+ const air = followAnchor(0, 0, 0, 1);+ const floor = followAnchor(0, 0, 0, 1, undefined, true);+ expect(air.z).toBeCloseTo(-GIGI_FOLLOW_BACK_M);+ expect(floor.z).toBeLessThan(air.z);+ expect(Math.abs(floor.x)).toBeLessThan(Math.abs(air.x));+ expect(Math.abs(air.x)).toBeCloseTo(GIGI_FOLLOW_SIDE_M);+ });+});+describe("gigi flight", () => {it("stays between 0.6 and 1.5 m in every mode, speaking or not, at any frame rate", () => {for (const mode of MODES) {diff --git a/jarvis/ui/web/frontend/src/components/society/office/gigiFlight.ts b/jarvis/ui/web/frontend/src/components/society/office/gigiFlight.tsindex baf90e9e3b..7bf8bedc59 100644--- a/jarvis/ui/web/frontend/src/components/society/office/gigiFlight.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/gigiFlight.ts@@ -4,7 +4,8 @@* and follows the walker's ground position (x, z). In "follow" mode it trails* the person's own character instead, hovering behind-beside its shoulder* (`followAnchor`): always on the coding floor, and on the agents floor- * whenever no errand or summons takes it away.+ * whenever no errand or summons takes it away. When the person's pet is one+ * that walks (`ground`), the same model keeps it on the floor right behind them.** Pure and deterministic: the same state and inputs give the same pose. With* an `out` object a step allocates nothing, so it can run every frame.@@ -31,6 +32,12 @@ export interface GigiFlightInput {reduced?: boolean;/** Is a point free airspace (not inside a wall or solid prop)? Gigi never settles where it is not. */clear?: (x: number, z: number) => boolean;+ /**+ * The companion is a pet that walks, hops or crawls (the person's pet from+ * My Pets): it keeps to the floor, so no hover height, bob, drift or lean;+ * it still turns, hops for joy and settles where it is clear.+ */+ ground?: boolean;}export interface GigiFlightPose {@@ -87,6 +94,11 @@ export const GIGI_FOLLOW_HOVER_M = 1.3;/** The follow anchor sits this far behind and beside the person. */export const GIGI_FOLLOW_BACK_M = 0.45;export const GIGI_FOLLOW_SIDE_M = 0.6;+/** A pet on the floor follows right behind the person, a little to one side. */+export const GROUND_FOLLOW_BACK_M = 0.75;+export const GROUND_FOLLOW_SIDE_M = 0.3;+/** Happy hops of a pet on the floor (speaking, waving), metres. */+const GROUND_HOP_M = 0.06;/** In follow mode Gigi trails the anchor by at most this much (a sprint stretches the spring). */const FOLLOW_MAX_LAG_M = 1.1;const MAX_BANK = 0.35;@@ -151,6 +163,7 @@ export function stepGigiFlight(state: GigiFlightState, input: GigiFlightInput, oconst { targetX, targetZ, mode } = input;const happy = mode === "talk" || mode === "wave" || input.speaking;const moving = input.moving;+ const ground = input.ground === true;// ---- Horizontal follow ------------------------------------------------const px = state.x, pz = state.z;@@ -190,7 +203,8 @@ export function stepGigiFlight(state: GigiFlightState, input: GigiFlightInput, ostate.happyBlend += ((happy ? 1 : 0) - state.happyBlend) * blend;// ---- Height -------------------------------------------------------------- const baseTarget = mode === "sleep" && !input.speaking ? GIGI_SLEEP_HOVER_M : mode === "follow" ? GIGI_FOLLOW_HOVER_M : GIGI_HOVER_M;+ const baseTarget = ground ? 0+ : mode === "sleep" && !input.speaking ? GIGI_SLEEP_HOVER_M : mode === "follow" ? GIGI_FOLLOW_HOVER_M : GIGI_HOVER_M;if (reduced) { state.base = baseTarget; state.vBase = 0; }else if (dt > 0) {springStep(state.base, state.vBase, baseTarget, HEIGHT_OMEGA, dt, scratch);@@ -198,7 +212,11 @@ export function stepGigiFlight(state: GigiFlightState, input: GigiFlightInput, o}let y = state.base;let driftX = 0, driftZ = 0, wiggle = 0;- if (!reduced) {+ if (ground) {+ // On the floor: only hops for joy, and only while standing (a walk has its own gait).+ if (!reduced && !moving) y += Math.abs(Math.sin(t * Math.PI * 1.5)) * GROUND_HOP_M * state.happyBlend;+ y = Math.max(0, y);+ } else if (!reduced) {const calm = 1 - state.sleepBlend;// Gentle hover bob, ~0.06 m at 0.5 Hz; quieter while busy.y += Math.sin(t * Math.PI) * 0.06 * calm * (1 - 0.6 * state.workBlend);@@ -214,7 +232,7 @@ export function stepGigiFlight(state: GigiFlightState, input: GigiFlightInput, odriftZ = Math.sin(2 * w) * 0.05 * state.idleBlend;wiggle = Math.sin(t * 3.2) * 0.22 * state.happyBlend * (mode === "wave" ? 0 : 1);}- y = clamp(y, GIGI_MIN_Y, GIGI_MAX_Y);+ if (!ground) y = clamp(y, GIGI_MIN_Y, GIGI_MAX_Y);// ---- Facing, lean and bank ---------------------------------------------const previousYaw = state.yaw;@@ -225,9 +243,9 @@ export function stepGigiFlight(state: GigiFlightState, input: GigiFlightInput, ostate.yaw = reduced ? wrap(input.heading) : wrap(state.yaw + wrap(input.heading - state.yaw) * approach(5, dt));}const yawRate = dt > 0 ? wrap(state.yaw - previousYaw) / dt : 0;- const leanTarget = reduced ? 0 : GIGI_MAX_LEAN * clamp(speed / LEAN_FULL_SPEED, 0, 1);+ const leanTarget = reduced || ground ? 0 : GIGI_MAX_LEAN * clamp(speed / LEAN_FULL_SPEED, 0, 1);// Turning towards +x (yaw increasing) tips the top towards +x: negative roll.- const bankTarget = reduced ? 0 : clamp(-yawRate * clamp(speed, 0, 2) * 0.12, -MAX_BANK, MAX_BANK);+ const bankTarget = reduced || ground ? 0 : clamp(-yawRate * clamp(speed, 0, 2) * 0.12, -MAX_BANK, MAX_BANK);state.pitch += (leanTarget - state.pitch) * approach(6, dt);state.roll += (bankTarget - state.roll) * approach(6, dt);@@ -270,14 +288,18 @@ export interface FollowAnchor { x: number; z: number; /** +1 or -1: which should* then right above the walker). `clear` tests free airspace; a candidate* counts only when the midpoint to it is clear too, so no wall sits between.*/-export function followAnchor(x: number, z: number, heading: number, side: 1 | -1, clear?: (x: number, z: number) => boolean): FollowAnchor {+export function followAnchor(x: number, z: number, heading: number, side: 1 | -1, clear?: (x: number, z: number) => boolean,+ ground = false): FollowAnchor {const fx = Math.sin(heading), fz = Math.cos(heading);// The walker's right hand (heading 0 faces +z, so its right is -x).const rx = -fz, rz = fx;+ // A flyer hovers behind-beside the shoulder; a pet on the floor walks right behind the feet.+ const back = ground ? GROUND_FOLLOW_BACK_M : GIGI_FOLLOW_BACK_M;+ const lateral = ground ? GROUND_FOLLOW_SIDE_M : GIGI_FOLLOW_SIDE_M;const candidates: [number, number, 1 | -1][] = [- [GIGI_FOLLOW_BACK_M, GIGI_FOLLOW_SIDE_M * side, side],- [GIGI_FOLLOW_BACK_M, -GIGI_FOLLOW_SIDE_M * side, side === 1 ? -1 : 1],- [GIGI_FOLLOW_BACK_M + 0.2, 0, side],+ [back, lateral * side, side],+ [back, -lateral * side, side === 1 ? -1 : 1],+ [back + 0.2, 0, side],[0.25, 0, side],];for (const [back, lateral, keep] of candidates) {diff --git a/scripts/art/build_pet_companions.py b/scripts/art/build_pet_companions.pynew file mode 100644index 0000000000..b94de30942--- /dev/null+++ b/scripts/art/build_pet_companions.py@@ -0,0 +1,783 @@+"""Author the 3D Jarvis pets that follow the person in the Jarvis Verse.++Run in Blender:++ blender --background --factory-startup --disable-autoexec \+ --python scripts/art/build_pet_companions.py [-- --render <dir>]++It saves the editable master to ``art/studies/jarvis-pet-companions/source/pets.blend``+and exports one ``exports/<pet>.glb`` per pet. ``--render`` also writes one review image per pet.++Conventions (see the study brief): metres, Blender Z up, -Y forward (glTF +Z+forward), every pet bottom-centred on its own root ``Pet_<id>``. Parts the+runtime animates hang under pivot empties named ``<id>_<Part>``; names use+underscores because three.js strips dots from glTF node names. Colours come+from the pixel pets in ``scripts/pets/build_pets.py``.+"""++from __future__ import annotations++import json+import math+import sys+from pathlib import Path++import bpy+from mathutils import Vector++ROOT = Path(__file__).resolve().parents[2]+STUDY = ROOT / "art/studies/jarvis-pet-companions"+TAU = 2 * math.pi+COLLECTION = "PetsExport"++_materials: dict[str, bpy.types.Material] = {}+++def hex_rgb(value: str) -> tuple[float, float, float]:+ """sRGB hex to the linear floats Blender stores."""++ def channel(byte: int) -> float:+ c = byte / 255+ return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4++ value = value.lstrip("#")+ return tuple(channel(int(value[i : i + 2], 16)) for i in (0, 2, 4)) # type: ignore[return-value]+++def material(name: str, colour: str, roughness: float = 0.78, emission: float = 0.0):+ if name in _materials:+ return _materials[name]+ rgb = hex_rgb(colour)+ mat = bpy.data.materials.new(name)+ mat.diffuse_color = (*rgb, 1)+ mat.use_nodes = True+ shader = mat.node_tree.nodes.get("Principled BSDF")+ shader.inputs["Base Color"].default_value = (*rgb, 1)+ shader.inputs["Metallic"].default_value = 0.0+ shader.inputs["Roughness"].default_value = roughness+ if emission:+ shader.inputs["Emission Color"].default_value = (*rgb, 1)+ shader.inputs["Emission Strength"].default_value = emission+ _materials[name] = mat+ return mat+++def empty(name: str, location=(0, 0, 0), parent=None):+ obj = bpy.data.objects.new(name, None)+ bpy.context.collection.objects.link(obj)+ obj.parent = parent+ obj.location = location+ obj.empty_display_size = 0.03+ return obj+++def finish(obj, name: str, mat, parent):+ obj.name = name+ obj.data.name = name+ obj.data.materials.clear()+ obj.data.materials.append(mat)+ obj.parent = parent+ for face in obj.data.polygons:+ face.use_smooth = True+ return obj+++def ellipsoid(name, centre, radii, mat, parent, segments=22, rings=11):+ bpy.ops.mesh.primitive_uv_sphere_add(segments=segments, ring_count=rings, location=centre)+ obj = bpy.context.object+ obj.scale = radii+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)+ return finish(obj, name, mat, parent)+++def cone(name, base, tip, radius, mat, parent, vertices=20):+ """A round cone standing on ``base`` and pointing at ``tip``."""+ a, b = Vector(base), Vector(tip)+ axis = b - a+ bpy.ops.mesh.primitive_cone_add(+ vertices=vertices,+ radius1=radius,+ radius2=radius * 0.12,+ depth=axis.length,+ location=(a + b) / 2,+ )+ obj = bpy.context.object+ obj.rotation_euler = axis.to_track_quat("Z", "Y").to_euler()+ bpy.ops.object.transform_apply(location=False, rotation=True, scale=False)+ return finish(obj, name, mat, parent)+++def rounded_box(name, centre, size, radius, mat, parent):+ bpy.ops.mesh.primitive_cube_add(size=1, location=centre)+ obj = bpy.context.object+ obj.scale = size+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)+ bevel = obj.modifiers.new("Soft edge", "BEVEL")+ bevel.width = radius+ bevel.segments = 4+ bevel.limit_method = "NONE"+ bpy.context.view_layer.objects.active = obj+ bpy.ops.object.modifier_apply(modifier=bevel.name)+ return finish(obj, name, mat, parent)+++def tube(name, points, radius, mat, parent, closed=False, taper: float | None = None):+ """A round tube through ``points``; ``taper`` scales the radius at the far end."""+ curve = bpy.data.curves.new(name, "CURVE")+ curve.dimensions = "3D"+ curve.bevel_depth = radius+ curve.bevel_resolution = 2+ curve.use_fill_caps = True+ spline = curve.splines.new("POLY")+ spline.points.add(len(points) - 1)+ count = len(points)+ for index, (point, position) in enumerate(zip(spline.points, points, strict=True)):+ point.co = (*position, 1)+ if taper is not None and count > 1:+ point.radius = 1 + (taper - 1) * index / (count - 1)+ spline.use_cyclic_u = closed+ obj = bpy.data.objects.new(name, curve)+ bpy.context.collection.objects.link(obj)+ obj.parent = parent+ bpy.ops.object.select_all(action="DESELECT")+ bpy.context.view_layer.objects.active = obj+ obj.select_set(True)+ bpy.ops.object.convert(target="MESH")+ obj.select_set(False)+ return finish(obj, name, mat, parent)+++def smooth_points(points, steps=4):+ """Catmull-Rom resample so tubes read as soft curves, not polylines."""+ pts = [Vector(p) for p in points]+ out = []+ for i in range(len(pts) - 1):+ p0 = pts[max(i - 1, 0)]+ p1, p2 = pts[i], pts[i + 1]+ p3 = pts[min(i + 2, len(pts) - 1)]+ for s in range(steps):+ t = s / steps+ t2, t3 = t * t, t * t * t+ out.append(+ 0.5+ * (+ (2 * p1)+ + (-p0 + p2) * t+ + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2+ + (-p0 + 3 * p1 - 3 * p2 + p3) * t3+ )+ )+ out.append(pts[-1])+ return [tuple(v) for v in out]+++def slab(name, outline, thickness, mat, parent):+ """A flat shape in the local XZ plane (outline of (x, z) pairs), ``thickness`` along Y."""+ count = len(outline)+ half = thickness / 2+ vertices = [(x, y, z) for y in (-half, half) for x, z in outline]+ faces = [tuple(range(count))[::-1], tuple(range(count, 2 * count))]+ faces += [(i, (i + 1) % count, (i + 1) % count + count, i + count) for i in range(count)]+ mesh = bpy.data.meshes.new(name)+ mesh.from_pydata(vertices, [], faces)+ mesh.update()+ obj = bpy.data.objects.new(name, mesh)+ bpy.context.collection.objects.link(obj)+ bevel = obj.modifiers.new("Soft edge", "BEVEL")+ bevel.width = min(0.006, half * 0.9)+ bevel.segments = 2+ bpy.ops.object.select_all(action="DESELECT")+ bpy.context.view_layer.objects.active = obj+ bpy.ops.object.modifier_apply(modifier=bevel.name)+ obj = finish(obj, name, mat, parent)+ for face in obj.data.polygons:+ face.use_smooth = False+ return obj+++def dot_eye(prefix, side, pivot_at, parent, radii, iris, pupil=None, glint="#f7f7fb"):+ """A pivot ``<prefix>_Eye_<side>`` (the runtime blinks it by scaling z) with a dot eye."""+ eye = empty(f"{prefix}_Eye_{side}", pivot_at, parent)+ ellipsoid(+ f"{prefix}_Iris_{side}",+ (0, 0, 0),+ radii,+ material(f"{prefix}.Iris", iris, 0.35),+ eye,+ 20,+ 10,+ )+ if pupil:+ ellipsoid(+ f"{prefix}_Pupil_{side}",+ (0, -radii[1] * 0.55, -radii[2] * 0.15),+ (radii[0] * 0.5, radii[1] * 0.5, radii[2] * 0.62),+ material(f"{prefix}.Pupil", pupil, 0.3),+ eye,+ 16,+ 8,+ )+ ellipsoid(+ f"{prefix}_Glint_{side}",+ (radii[0] * 0.32, -radii[1] * 0.9, radii[2] * 0.38),+ (radii[0] * 0.3, radii[1] * 0.3, radii[2] * 0.26),+ material("Pet.Glint", glint, 0.2, 0.4),+ eye,+ 12,+ 6,+ )+ return eye+++def smile(name, centre, width, depth, mat, parent, lift=0.0):+ cx, cy, cz = centre+ points = [+ (cx + width * math.cos(a), cy, cz - depth * math.sin(a) + lift)+ for a in [math.pi * (0.15 + 0.7 * i / 10) for i in range(11)]+ ]+ return tube(name, points, 0.0045, mat, parent)+++# ---------------------------------------------------------------------------+# The pets+# ---------------------------------------------------------------------------++INK = "#1b1622"+BLUSH = "#ff8fa3"+++def build_miso(root):+ fur = material("miso.Fur", "#f2a65a")+ cream = material("miso.Cream", "#fff0d9")+ stripe = material("miso.Stripe", "#c8743a")+ ear = material("miso.Ear", "#ff9fb2")+ nose = material("miso.Nose", "#ff7a8a", 0.5)+ ink = material("Pet.Ink", INK, 0.6)++ body = empty("miso_Body", (0, 0, 0.17), root)+ ellipsoid("miso_Torso", (0, 0.03, 0), (0.105, 0.16, 0.1), fur, body)+ ellipsoid("miso_Belly", (0, 0.0, -0.035), (0.08, 0.13, 0.065), cream, body)+ for i, y in enumerate((0.0, 0.06, 0.12)):+ ellipsoid(f"miso_BackStripe_{i}", (0, y, 0.088), (0.075, 0.013, 0.022), stripe, body, 16, 8)++ head = empty("miso_Head", (0, -0.13, 0.33), root)+ ellipsoid("miso_Skull", (0, 0, 0), (0.15, 0.125, 0.122), fur, head)+ ellipsoid("miso_Muzzle", (0, -0.1, -0.045), (0.065, 0.04, 0.042), cream, head)+ ellipsoid("miso_Nose", (0, -0.138, -0.02), (0.016, 0.01, 0.011), nose, head, 12, 6)+ smile("miso_Mouth", (0, -0.141, -0.042), 0.02, 0.012, ink, head)+ for i, x in enumerate((-0.035, 0.0, 0.035)):+ ellipsoid(+ f"miso_Stripe_{i}", (x, -0.045, 0.105), (0.012, 0.035, 0.016), stripe, head, 12, 6+ )+ for side, sign in (("L", -1), ("R", 1)):+ dot_eye(+ "miso",+ side,+ (sign * 0.058, -0.108, 0.018),+ head,+ (0.024, 0.012, 0.03),+ "#6fcf7f",+ "#123524",+ )+ ellipsoid(+ f"miso_Cheek_{side}",+ (sign * 0.09, -0.098, -0.03),+ (0.022, 0.01, 0.013),+ material("Pet.Blush", BLUSH, 0.7),+ head,+ 12,+ 6,+ )+ pinna = empty(f"miso_Ear_{side}", (sign * 0.085, 0.0, 0.085), head)+ cone(f"miso_EarOuter_{side}", (0, 0, 0), (sign * 0.025, 0.0, 0.1), 0.052, fur, pinna, 16)+ cone(+ f"miso_EarInner_{side}",+ (0, -0.016, 0.004),+ (sign * 0.022, -0.016, 0.085),+ 0.033,+ ear,+ pinna,+ 12,+ )+ for j, dz in enumerate((-0.005, 0.012)):+ tube(+ f"miso_Whisker_{side}_{j}",+ [(sign * 0.06, -0.125, -0.035 + dz), (sign * 0.13, -0.13, -0.03 + dz * 1.8)],+ 0.0022,+ cream,+ head,+ )++ for name, x, y in (+ ("FL", -0.062, -0.085),+ ("FR", 0.062, -0.085),+ ("BL", -0.066, 0.13),+ ("BR", 0.066, 0.13),+ ):+ leg = empty(f"miso_Leg_{name}", (x, y, 0.13), root)+ ellipsoid(f"miso_LegFur_{name}", (0, 0, -0.05), (0.036, 0.038, 0.06), fur, leg, 16, 8)+ ellipsoid(f"miso_Paw_{name}", (0, -0.012, -0.108), (0.04, 0.047, 0.024), cream, leg, 16, 8)++ tail = empty("miso_Tail", (0, 0.185, 0.2), root)+ tube(+ "miso_TailFur",+ smooth_points(+ [(0, 0, 0), (0, 0.07, 0.03), (0, 0.11, 0.11), (0.02, 0.09, 0.2), (0.05, 0.05, 0.24)]+ ),+ 0.023,+ fur,+ tail,+ taper=0.75,+ )+ ellipsoid("miso_TailTip", (0.05, 0.05, 0.24), (0.02, 0.02, 0.02), stripe, tail, 12, 6)+++def build_ember(root):+ scale = material("ember.Scale", "#e8505b")+ light = material("ember.ScaleLight", "#ff8a80")+ dark = material("ember.ScaleDark", "#b0303f")+ belly = material("ember.Belly", "#ffe2ad")+ band = material("ember.BellyBand", "#f0b871")+ wing = material("ember.Wing", "#ffad7a")+ wing_dark = material("ember.WingBone", "#e57a52")+ horn = material("ember.Horn", "#ffd45c", 0.55)+ ink = material("Pet.Ink", INK, 0.6)++ body = empty("ember_Body", (0, 0, 0.17), root)+ ellipsoid("ember_Torso", (0, 0.01, 0), (0.12, 0.11, 0.135), scale, body)+ ellipsoid("ember_BellyPlate", (0, -0.07, -0.005), (0.085, 0.05, 0.105), belly, body)+ for i, z in enumerate((-0.06, -0.015, 0.03)):+ ellipsoid(f"ember_Band_{i}", (0, -0.112, z), (0.07, 0.008, 0.01), band, body, 16, 6)+ for i, z in enumerate((0.09, 0.03, -0.03)):+ cone(f"ember_Spike_{i}", (0, 0.1, z), (0, 0.15, z + 0.03), 0.022, horn, body, 10)++ head = empty("ember_Head", (0, -0.02, 0.36), root)+ ellipsoid("ember_Skull", (0, 0, 0), (0.15, 0.13, 0.12), scale, head)+ ellipsoid("ember_Snout", (0, -0.105, -0.04), (0.085, 0.06, 0.052), light, head)+ for side, sign in (("L", -1), ("R", 1)):+ ellipsoid(+ f"ember_Nostril_{side}",+ (sign * 0.025, -0.16, -0.025),+ (0.009, 0.006, 0.007),+ material("ember.Nostril", "#7a1f2b", 0.6),+ head,+ 10,+ 6,+ )+ dot_eye(+ "ember",+ side,+ (sign * 0.062, -0.1, 0.03),+ head,+ (0.028, 0.013, 0.036),+ "#2a1830",+ None,+ "#ffb347",+ )+ ellipsoid(+ f"ember_Cheek_{side}",+ (sign * 0.098, -0.09, -0.02),+ (0.022, 0.01, 0.013),+ material("Pet.EmberBlush", "#ffb0c0", 0.7),+ head,+ 12,+ 6,+ )+ cone(+ f"ember_Horn_{side}",+ (sign * 0.075, 0.02, 0.085),+ (sign * 0.12, 0.06, 0.17),+ 0.028,+ horn,+ head,+ 14,+ )+ ellipsoid(+ f"ember_Fin_{side}", (sign * 0.145, 0.02, 0.02), (0.02, 0.04, 0.05), wing, head, 12, 6+ )+ for i, (x, z) in enumerate(((-0.025, 0.12), (0.02, 0.125), (0.0, 0.135))):+ ellipsoid(f"ember_Tuft_{i}", (x, -0.01, z), (0.03, 0.03, 0.026), belly, head, 12, 6)+ smile("ember_Mouth", (0, -0.163, -0.06), 0.03, 0.012, ink, head)++ for side, sign in (("L", -1), ("R", 1)):+ # Wings sit on the back, swept back a little; the runtime flaps them about the+ # pivot's local forward axis and keeps this sweep.+ pivot = empty(f"ember_Wing_{side}", (sign * 0.055, 0.085, 0.235), root)+ pivot.rotation_euler.z = sign * math.radians(28)+ outline = [+ (0, 0),+ (0.05, 0.1),+ (0.17, 0.14),+ (0.23, 0.05),+ (0.19, -0.01),+ (0.13, 0.015),+ (0.085, -0.035),+ ]+ slab(f"ember_Membrane_{side}", [(sign * x, z) for x, z in outline], 0.016, wing, pivot)+ tube(+ f"ember_WingBone_{side}",+ smooth_points(+ [(0, 0, 0), (sign * 0.05, 0, 0.1), (sign * 0.17, 0, 0.14), (sign * 0.23, 0, 0.05)],+ 4,+ ),+ 0.011,+ wing_dark,+ pivot,+ )+ arm = empty(f"ember_Arm_{side}", (sign * 0.105, -0.05, 0.22), root)+ ellipsoid(+ f"ember_ArmScale_{side}",+ (sign * 0.012, -0.012, -0.03),+ (0.032, 0.032, 0.05),+ scale,+ arm,+ 14,+ 8,+ )+ leg = empty(f"ember_Leg_{side}", (sign * 0.07, -0.01, 0.085), root)+ ellipsoid(f"ember_Thigh_{side}", (0, 0, -0.025), (0.05, 0.055, 0.055), scale, leg, 16, 8)+ ellipsoid(f"ember_Foot_{side}", (0, -0.03, -0.065), (0.042, 0.05, 0.022), belly, leg, 14, 8)++ tail = empty("ember_Tail", (0, 0.1, 0.1), root)+ tube(+ "ember_TailScale",+ smooth_points([(0, 0, 0), (0, 0.09, -0.04), (0.04, 0.18, -0.02), (0.05, 0.23, 0.05)]),+ 0.036,+ scale,+ tail,+ taper=0.35,+ )+ cone("ember_TailTip", (0.05, 0.23, 0.05), (0.06, 0.26, 0.11), 0.03, dark, tail, 12)+++def build_shelly(root):+ skin = material("shelly.Skin", "#c3de7a")+ skin_light = material("shelly.SkinLight", "#e3f4a9")+ skin_dark = material("shelly.SkinDark", "#8eae4c")+ shell = material("shelly.Shell", "#e08a4f")+ shell_light = material("shelly.ShellLight", "#f5b884")+ spiral = material("shelly.Spiral", "#6b3417")+ white = material("Pet.EyeWhite", "#f7f7fb", 0.4)+ ink = material("Pet.Ink", INK, 0.6)++ body = empty("shelly_Body", (0, 0, 0), root)+ ellipsoid("shelly_Foot", (0, 0.05, 0.058), (0.09, 0.25, 0.058), skin, body)+ ellipsoid("shelly_Sole", (0, 0.05, 0.011), (0.096, 0.252, 0.011), skin_dark, body, 22, 6)+ head = empty("shelly_Head", (0, -0.15, 0.06), body)+ ellipsoid("shelly_Neck", (0, 0, 0.085), (0.085, 0.085, 0.12), skin, head)+ ellipsoid("shelly_Face", (0, -0.035, 0.1), (0.07, 0.06, 0.08), skin_light, head)+ smile("shelly_Mouth", (0, -0.09, 0.07), 0.022, 0.01, ink, head)+ for side, sign in (("L", -1), ("R", 1)):+ ellipsoid(+ f"shelly_Cheek_{side}",+ (sign * 0.05, -0.075, 0.075),+ (0.017, 0.009, 0.011),+ material("Pet.Blush", BLUSH, 0.7),+ head,+ 12,+ 6,+ )+ stalk = empty(f"shelly_Stalk_{side}", (sign * 0.035, -0.02, 0.18), head)+ tube(+ f"shelly_StalkSkin_{side}",+ smooth_points(+ [(0, 0, 0), (sign * 0.012, -0.01, 0.06), (sign * 0.022, -0.012, 0.11)], 4+ ),+ 0.011,+ skin,+ stalk,+ )+ eye = empty(f"shelly_Eye_{side}", (sign * 0.022, -0.012, 0.13), stalk)+ ellipsoid(f"shelly_EyeBall_{side}", (0, 0, 0), (0.03, 0.03, 0.03), white, eye, 18, 10)+ ellipsoid(f"shelly_Pupil_{side}", (0, -0.025, 0), (0.014, 0.008, 0.016), ink, eye, 12, 6)+ ellipsoid(+ f"shelly_Glint_{side}",+ (0.006, -0.032, 0.007),+ (0.004, 0.002, 0.004),+ material("Pet.Glint", "#f7f7fb", 0.2, 0.4),+ eye,+ 8,+ 4,+ )++ house = empty("shelly_Shell", (0, 0.07, 0.1), body)+ centre = Vector((0, 0, 0.13))+ ellipsoid("shelly_ShellCase", tuple(centre), (0.085, 0.15, 0.15), shell, house)+ ellipsoid("shelly_ShellRim", (0, 0, 0.13), (0.07, 0.155, 0.155), shell_light, house)+ for side, sign in (("L", -1), ("R", 1)):+ points = []+ # A spiral that hugs the case: x follows the ellipsoid surface at each radius.+ for i in range(56):+ a = i / 55 * TAU * 2.2+ r = 0.125 * (1 - i / 62)+ points.append(+ (+ sign * (0.085 * math.sqrt(max(0.0, 1 - (r / 0.15) ** 2)) + 0.002),+ centre.y + r * math.cos(a),+ centre.z + r * math.sin(a),+ )+ )+ tube(f"shelly_Spiral_{side}", points, 0.009, spiral, house)+++def build_mochi(root):+ jelly = material("mochi.Jelly", "#ff9fcb", 0.35)+ shine = material("mochi.Shine", "#ffd3e8", 0.2, 0.15)+ blush = material("mochi.Blush", "#ff5f9a", 0.6)+ ink = material("mochi.Ink", "#3b1f2b", 0.5)++ body = empty("mochi_Body", (0, 0, 0), root)+ ellipsoid("mochi_Jelly", (0, 0, 0.125), (0.175, 0.155, 0.125), jelly, body, 30, 15)+ ellipsoid("mochi_Shine", (-0.07, -0.06, 0.215), (0.045, 0.03, 0.02), shine, body, 16, 8)+ ellipsoid("mochi_ShineDot", (-0.02, -0.08, 0.225), (0.014, 0.01, 0.009), shine, body, 10, 5)+ for side, sign in (("L", -1), ("R", 1)):+ dot_eye("mochi", side, (sign * 0.055, -0.143, 0.14), body, (0.016, 0.01, 0.022), "#3b1f2b")+ ellipsoid(+ f"mochi_Cheek_{side}",+ (sign * 0.098, -0.128, 0.11),+ (0.028, 0.01, 0.014),+ blush,+ body,+ 12,+ 6,+ )+ smile("mochi_Mouth", (0, -0.153, 0.118), 0.02, 0.01, ink, body)+++def build_brew(root):+ glaze = material("brew.Glaze", "#6cc7b3", 0.45)+ glaze_light = material("brew.GlazeLight", "#a9ecdc", 0.35)+ rim = material("brew.Rim", "#3e8f80", 0.5)+ gold = material("brew.Gold", "#ffcf45", 0.4)+ ink = material("brew.Ink", "#22303a", 0.5)++ body = empty("brew_Body", (0, 0, 0), root)+ ellipsoid("brew_Pot", (0, 0, 0.14), (0.16, 0.15, 0.13), glaze, body, 30, 15)+ ellipsoid("brew_Base", (0, 0, 0.025), (0.1, 0.095, 0.025), rim, body, 24, 8)+ ellipsoid("brew_Shine", (-0.08, -0.1, 0.2), (0.03, 0.02, 0.045), glaze_light, body, 12, 6)+ ellipsoid("brew_Collar", (0, 0, 0.255), (0.1, 0.095, 0.018), rim, body, 24, 8)+ for side, sign in (("L", -1), ("R", 1)):+ dot_eye("brew", side, (sign * 0.05, -0.14, 0.16), body, (0.015, 0.01, 0.02), "#22303a")+ ellipsoid(+ f"brew_Cheek_{side}",+ (sign * 0.09, -0.125, 0.13),+ (0.022, 0.01, 0.012),+ material("Pet.Blush", BLUSH, 0.7),+ body,+ 12,+ 6,+ )+ smile("brew_Mouth", (0, -0.149, 0.135), 0.02, 0.01, ink, body)+ tube(+ "brew_Spout",+ smooth_points([(0.13, 0, 0.11), (0.2, 0, 0.14), (0.235, 0, 0.21), (0.26, 0, 0.245)], 4),+ 0.026,+ glaze,+ body,+ taper=0.7,+ )+ ellipsoid("brew_SpoutLip", (0.262, 0, 0.248), (0.022, 0.022, 0.01), rim, body, 12, 6)+ tube(+ "brew_Handle",+ smooth_points(+ [+ (-0.13, 0, 0.22),+ (-0.2, 0, 0.22),+ (-0.235, 0, 0.16),+ (-0.2, 0, 0.09),+ (-0.14, 0, 0.08),+ ],+ 5,+ ),+ 0.02,+ glaze,+ body,+ )+ lid = empty("brew_Lid", (0, 0, 0.26), body)+ ellipsoid("brew_LidCap", (0, 0, 0.012), (0.088, 0.083, 0.035), glaze, lid, 24, 10)+ ellipsoid("brew_Knob", (0, 0, 0.055), (0.026, 0.026, 0.026), gold, lid, 16, 8)+++def build_bolt(root):+ casing = material("bolt.Casing", "#3d9be0", 0.5)+ metal = material("bolt.Metal", "#cfd4de", 0.45)+ metal_dark = material("bolt.MetalDark", "#8d95a6", 0.55)+ window = material("bolt.Window", "#1c2733", 0.35)+ green = material("bolt.Charge", "#6ee07a", 0.4, 0.6)+ ink = material("Pet.Ink", INK, 0.6)++ body = empty("bolt_Body", (0, 0, 0.055), root)+ rounded_box("bolt_Case", (0, 0, 0.14), (0.2, 0.15, 0.28), 0.04, casing, body)+ rounded_box("bolt_Cap", (0, 0, 0.29), (0.09, 0.075, 0.04), 0.012, metal, body)+ rounded_box("bolt_Window", (0, -0.072, 0.115), (0.13, 0.012, 0.14), 0.012, window, body)+ for i, z in enumerate((0.07, 0.112, 0.154)):+ rounded_box(f"bolt_Bar_{i + 1}", (0, -0.08, z), (0.1, 0.008, 0.03), 0.004, green, body)+ for side, sign in (("L", -1), ("R", 1)):+ dot_eye("bolt", side, (sign * 0.04, -0.077, 0.235), body, (0.014, 0.008, 0.019), INK)+ arm = empty(f"bolt_Arm_{side}", (sign * 0.1, 0, 0.17), body)+ ellipsoid(+ f"bolt_ArmNub_{side}", (sign * 0.02, 0, -0.02), (0.026, 0.03, 0.036), metal, arm, 14, 8+ )+ foot = empty(f"bolt_Foot_{side}", (sign * 0.05, 0, 0.0), root)+ ellipsoid(+ f"bolt_FootShoe_{side}",+ (0, -0.012, 0.024),+ (0.04, 0.052, 0.026),+ metal_dark,+ foot,+ 14,+ 8,+ )+ smile("bolt_Mouth", (0, -0.078, 0.214), 0.018, 0.009, ink, body)+++PETS = {+ "miso": build_miso,+ "ember": build_ember,+ "shelly": build_shelly,+ "mochi": build_mochi,+ "brew": build_brew,+ "bolt": build_bolt,+}+++def measure(root) -> dict:+ lo = Vector((math.inf,) * 3)+ hi = Vector((-math.inf,) * 3)+ triangles = 0+ for obj in root.children_recursive:+ if obj.type != "MESH":+ continue+ for corner in obj.bound_box:+ world = obj.matrix_world @ Vector(corner)+ lo = Vector(map(min, lo, world))+ hi = Vector(map(max, hi, world))+ triangles += sum(len(p.vertices) - 2 for p in obj.data.polygons)+ return {+ "height_m": round(hi.z - lo.z, 3),+ "bottom_m": round(lo.z, 3),+ "width_m": round(hi.x - lo.x, 3),+ "length_m": round(hi.y - lo.y, 3),+ "triangles": triangles,+ }+++def render_reviews(target: Path, roots: dict) -> None:+ scene = bpy.context.scene+ bpy.context.view_layer.active_layer_collection = bpy.context.view_layer.layer_collection+ world = bpy.data.worlds.new("Pet review studio")+ world.use_nodes = True+ world.node_tree.nodes["Background"].inputs[0].default_value = (0.55, 0.6, 0.68, 1)+ world.node_tree.nodes["Background"].inputs[1].default_value = 0.9+ scene.world = world+ bpy.ops.object.light_add(type="SUN", location=(1, -1, 2))+ sun = bpy.context.object+ sun.data.energy = 3.2+ sun.rotation_euler = (math.radians(50), 0, math.radians(35))+ bpy.ops.mesh.primitive_plane_add(size=6, location=(0, 0, 0))+ floor = bpy.context.object+ floor.data.materials.append(material("Review.Floor", "#e9e4da", 0.9))+ bpy.ops.object.camera_add()+ camera = bpy.context.object+ camera.data.type = "ORTHO"+ scene.camera = camera+ scene.render.engine = "CYCLES"+ scene.cycles.samples = 32+ scene.cycles.device = "CPU"+ scene.render.resolution_x = scene.render.resolution_y = 520+ scene.view_settings.view_transform = "Standard"+ target.mkdir(parents=True, exist_ok=True)+ for pet_id, root in roots.items():+ for other in roots.values():+ hide = other is not root+ for obj in [other, *other.children_recursive]:+ obj.hide_render = hide+ size = measure(root)+ focus = Vector((0, 0, size["height_m"] * 0.5))+ for view, (azimuth, elevation) in {"front": (-35, 22), "side": (-100, 12)}.items():+ a, e = math.radians(azimuth), math.radians(elevation)+ direction = Vector((math.sin(a) * math.cos(e), -math.cos(a) * math.cos(e), math.sin(e)))+ camera.location = focus + direction * 2+ camera.rotation_euler = (focus - camera.location).to_track_quat("-Z", "Y").to_euler()+ camera.data.ortho_scale = (+ max(size["height_m"], size["length_m"], size["width_m"]) * 1.45+ )+ scene.render.filepath = str(target / f"{pet_id}-{view}.png")+ bpy.ops.render.render(write_still=True)+++def main() -> None:+ argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []+ render_dir = Path(argv[argv.index("--render") + 1]) if "--render" in argv else None++ bpy.ops.object.select_all(action="SELECT")+ bpy.ops.object.delete(use_global=False)+ scene = bpy.context.scene+ scene.unit_settings.system = "METRIC"+ scene.unit_settings.scale_length = 1+ collection = bpy.data.collections.new(COLLECTION)+ scene.collection.children.link(collection)+ bpy.context.view_layer.active_layer_collection = (+ bpy.context.view_layer.layer_collection.children[COLLECTION]+ )++ roots = {}+ report = {+ "blender": bpy.app.version_string,+ "forward": "glTF +Z",+ "pivot": "bottom centre",+ "pets": {},+ }+ for pet_id, build in PETS.items():+ # One collection per pet, so `scripts/art/export_study.py` can re-export a single pet.+ own = bpy.data.collections.new(f"Pet_{pet_id}")+ collection.children.link(own)+ bpy.context.view_layer.active_layer_collection = (+ bpy.context.view_layer.layer_collection.children[COLLECTION].children[own.name]+ )+ root = empty(f"Pet_{pet_id}")+ root["pet_id"] = pet_id+ build(root)+ roots[pet_id] = root+ bpy.context.view_layer.update()+ for pet_id, root in roots.items():+ report["pets"][pet_id] = measure(root)++ source = STUDY / "source/pets.blend"+ source.parent.mkdir(parents=True, exist_ok=True)+ bpy.context.preferences.filepaths.save_version = 0+ scene["production_recipe"] = "scripts/art/build_pet_companions.py"+ bpy.ops.wm.save_as_mainfile(+ filepath=str(source), check_existing=False, relative_remap=False, compress=False+ )++ # One GLB per pet: the runtime loads only the pet the person picked.+ exports = STUDY / "exports"+ exports.mkdir(parents=True, exist_ok=True)+ for pet_id, root in roots.items():+ export = exports / f"{pet_id}.glb"+ bpy.ops.object.select_all(action="DESELECT")+ for obj in [root, *root.children_recursive]:+ obj.select_set(True)+ bpy.ops.export_scene.gltf(+ filepath=str(export),+ export_format="GLB",+ use_selection=True,+ export_yup=True,+ export_extras=True,+ export_texcoords=False,+ export_animations=False,+ export_materials="EXPORT",+ )+ report["pets"][pet_id]["glb_bytes"] = export.stat().st_size+ (STUDY / "source/build-report.json").write_text(+ json.dumps(report, indent=2) + "\n", encoding="utf-8"+ )+ print("PET_REPORT", json.dumps(report))++ if render_dir is not None:+ render_reviews(render_dir, roots)+++if __name__ == "__main__":+ main()