Skip to content

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

refactor(city): share rig constants, return resolved boom point, dedupe settings segments

[._.]/ Adam Eivyac0cfffffbec
diff --git a/client/src/components/city/CitySettingsPanel.jsx b/client/src/components/city/CitySettingsPanel.jsx
index 1cbe2341f4..b8acf15247 100644
--- a/client/src/components/city/CitySettingsPanel.jsx
+++ b/client/src/components/city/CitySettingsPanel.jsx
@@ -61,6 +61,33 @@ function SettingSlider({ label, value, onChange, min = 0, max = 1, step = 0.05,
);
}
+// Segmented enum picker — one glowing button per option, with an optional hint line.
+// `isActive` defaults to strict equality; pass a predicate for legacy-value mapping.
+function SettingSegment({ label, options, value, onChange, hint, isActive }) {
+ const activeFor = isActive ?? ((key) => value === key);
+ return (
+ <div className="py-1.5">
+ {label && <div className="font-pixel text-[10px] text-gray-400 tracking-wide mb-2">{label}</div>}
+ <div className={`grid gap-1.5 ${options.length === 2 ? 'grid-cols-2' : 'grid-cols-3'}`}>
+ {options.map(({ key, label: optionLabel }) => (
+ <button
+ key={key}
+ onClick={() => onChange(key)}
+ className={`font-pixel text-[9px] py-2 rounded border transition-all tracking-wide ${
+ activeFor(key)
+ ? 'bg-cyan-500/20 border-cyan-500/50 text-cyan-400 shadow-[0_0_8px_rgba(6,182,212,0.2)]'
+ : 'bg-gray-800/40 border-gray-700/40 text-gray-500 hover:border-gray-600 hover:text-gray-400'
+ }`}
+ >
+ {optionLabel}
+ </button>
+ ))}
+ </div>
+ {hint && <div className="font-pixel text-[8px] text-gray-600 tracking-wide mt-1.5">{hint}</div>}
+ </div>
+ );
+}
+
function SectionHeader({ title, subtitle }) {
return (
<div className="mb-2">
@@ -216,35 +243,21 @@ export default function CitySettingsPanel() {
format={(v) => `${v.toFixed(1)}x`}
description="Brightness of neon lights and building glow"
/>
- <div className="py-1.5">
- <div className="font-pixel text-[10px] text-gray-400 tracking-wide mb-2">TIME OF DAY</div>
- <div className="grid grid-cols-3 gap-1.5">
- {[
- { key: 'auto', label: 'AUTO' },
- { key: 'day', label: 'DAY' },
- { key: 'night', label: 'NIGHT' },
- ].map(({ key, label }) => {
- // Legacy presets (sunrise/noon/sunset/midnight) read as Auto now.
- const active = (settings.timeOfDay === 'day' || settings.timeOfDay === 'night')
- ? settings.timeOfDay === key
- : key === 'auto';
- return (
- <button
- key={key}
- onClick={() => updateSetting('timeOfDay', key)}
- className={`font-pixel text-[9px] py-2 rounded border transition-all tracking-wide ${
- active
- ? 'bg-cyan-500/20 border-cyan-500/50 text-cyan-400 shadow-[0_0_8px_rgba(6,182,212,0.2)]'
- : 'bg-gray-800/40 border-gray-700/40 text-gray-500 hover:border-gray-600 hover:text-gray-400'
- }`}
- >
- {label}
- </button>
- );
- })}
- </div>
- <div className="font-pixel text-[8px] text-gray-600 tracking-wide mt-1.5">AUTO FOLLOWS YOUR THEME (DAY / NIGHT)</div>
- </div>
+ <SettingSegment
+ label="TIME OF DAY"
+ options={[
+ { key: 'auto', label: 'AUTO' },
+ { key: 'day', label: 'DAY' },
+ { key: 'night', label: 'NIGHT' },
+ ]}
+ value={settings.timeOfDay}
+ onChange={(key) => updateSetting('timeOfDay', key)}
+ hint="AUTO FOLLOWS YOUR THEME (DAY / NIGHT)"
+ // Legacy presets (sunrise/noon/sunset/midnight) read as Auto now.
+ isActive={(key) => (settings.timeOfDay === 'day' || settings.timeOfDay === 'night')
+ ? settings.timeOfDay === key
+ : key === 'auto'}
+ />
</div>
<div className="border-t border-cyan-500/10" />
@@ -258,30 +271,15 @@ export default function CitySettingsPanel() {
onChange={(v) => updateSetting('explorationMode', v)}
description="Toggle street-level exploration (Tab)"
/>
- <div className="mt-2">
- <div className="grid grid-cols-2 gap-1.5">
- {[
- { key: 'third', label: 'CHARACTER' },
- { key: 'first', label: 'FIRST PERSON' },
- ].map(({ key, label }) => {
- const active = (settings.cameraView ?? 'third') === key;
- return (
- <button
- key={key}
- onClick={() => updateSetting('cameraView', key)}
- className={`font-pixel text-[9px] py-2 rounded border transition-all tracking-wide ${
- active
- ? 'bg-cyan-500/20 border-cyan-500/50 text-cyan-400 shadow-[0_0_8px_rgba(6,182,212,0.2)]'
- : 'bg-gray-800/40 border-gray-700/40 text-gray-500 hover:border-gray-600 hover:text-gray-400'
- }`}
- >
- {label}
- </button>
- );
- })}
- </div>
- <div className="font-pixel text-[8px] text-gray-600 tracking-wide mt-1.5">CAMERA WHILE EXPLORING (V SWAPS IN-WORLD)</div>
- </div>
+ <SettingSegment
+ options={[
+ { key: 'third', label: 'CHARACTER' },
+ { key: 'first', label: 'FIRST PERSON' },
+ ]}
+ value={settings.cameraView ?? 'third'}
+ onChange={(key) => updateSetting('cameraView', key)}
+ hint="CAMERA WHILE EXPLORING (V SWAPS IN-WORLD)"
+ />
</div>
<div className="border-t border-cyan-500/10" />
diff --git a/client/src/components/city/PlayerAvatar.jsx b/client/src/components/city/PlayerAvatar.jsx
index f633cbf7d9..26c01a1ce8 100644
--- a/client/src/components/city/PlayerAvatar.jsx
+++ b/client/src/components/city/PlayerAvatar.jsx
@@ -2,7 +2,7 @@ import { useRef, useMemo, useEffect } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import { useCityPalette } from './CityPaletteContext';
-import { dampFactor, dampAngle } from '../../utils/cityPlayerRig';
+import { dampFactor, dampAngle, EYE_HEIGHT } from '../../utils/cityPlayerRig';
// The exploration-mode cyber-runner: a stylized articulated character (~1.7 units tall)
// rendered in third person. Reads the PlayerController's mutable rig every frame — no
@@ -42,7 +42,7 @@ GEO.helmet.computeVertexNormals();
const HIP_Y = 0.76;
const SHOULDER_Y = 1.3;
-export default function PlayerAvatar({ rigRef, eyeHeight = 1.6 }) {
+export default function PlayerAvatar({ rigRef }) {
const { accent, buildingBody, tintStructure } = useCityPalette();
// Theme-tinted materials. Trim/visor glow the accent; the animated ones (visor, vents,
@@ -86,7 +86,7 @@ export default function PlayerAvatar({ rigRef, eyeHeight = 1.6 }) {
const elbowL = useRef();
const elbowR = useRef();
const phaseRef = useRef(0);
- const groundOffsetRef = useRef(-eyeHeight);
+ const groundOffsetRef = useRef(-EYE_HEIGHT);
useFrame(({ clock }, delta) => {
const root = rootRef.current;
@@ -101,7 +101,7 @@ export default function PlayerAvatar({ rigRef, eyeHeight = 1.6 }) {
// Root follows the rig: feet on the ground normally; in hover the body floats
// closer to the camera anchor with legs tucked.
- const targetOffset = hovering ? -1.05 : -eyeHeight;
+ const targetOffset = hovering ? -1.05 : -EYE_HEIGHT;
groundOffsetRef.current += (targetOffset - groundOffsetRef.current) * f;
const bob = state === 'idle' ? Math.sin(t * 1.6) * 0.03 : hovering ? Math.sin(t * 2.2) * 0.06 : 0;
root.position.set(rig.position.x, rig.position.y + groundOffsetRef.current + bob, rig.position.z);
diff --git a/client/src/components/city/PlayerController.jsx b/client/src/components/city/PlayerController.jsx
index 39a8592acf..2bddf3e557 100644
--- a/client/src/components/city/PlayerController.jsx
+++ b/client/src/components/city/PlayerController.jsx
@@ -1,27 +1,30 @@
-import { useRef, useEffect, useCallback } from 'react';
+import { useRef, useEffect, useCallback, useMemo } from 'react';
import { useThree, useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import PlayerAvatar from './PlayerAvatar';
import {
- THIRD_PERSON, thirdPersonCamera, resolveBoomT,
+ THIRD_PERSON, EYE_HEIGHT, BUILDING_COLLISION_RADIUS,
+ thirdPersonCamera, resolveBoom,
dampFactor, dampAngle, moveFacing, avatarState, bankAngle,
} from '../../utils/cityPlayerRig';
-import { isWalkable } from '../../utils/cityPlan';
+import { isWalkable, WORLD } from '../../utils/cityPlan';
const WALK_SPEED = 10;
const SPRINT_SPEED = 20;
const VERTICAL_SPEED = 8;
-const BUILDING_EXCLUSION_RADIUS = 3.5;
const PROXIMITY_DISTANCE = 6;
-const WORLD_BOUND = 180;
-const EYE_HEIGHT = 1.6;
const MAX_CAMERA_HEIGHT = 160;
const BUILDING_FLYOVER_HEIGHT = 12; // above this the player clears rooftops, so skip collision
const AIRBORNE_HEIGHT = EYE_HEIGHT + 0.6; // above this the avatar reads as flying (hover state)
const MOUSE_SENSITIVITY = 0.002;
const PITCH_LIMIT = Math.PI / 2 - 0.02;
-// Frame-loop scratch vectors (module scope — no per-frame allocation on the camera path).
+// Frame-loop scratch vectors (module scope — no per-frame allocation in useFrame).
+const _forward = new THREE.Vector3();
+const _right = new THREE.Vector3();
+const _moveDir = new THREE.Vector3();
+const _nextPos = new THREE.Vector3();
+const _lookDir = new THREE.Vector3();
const _camTarget = new THREE.Vector3();
const _lookTarget = new THREE.Vector3();
@@ -50,13 +53,13 @@ export default function PlayerController({
position: new THREE.Vector3(0, EYE_HEIGHT, 0),
yaw: 0, // camera heading; forward is (-sin yaw, 0, -cos yaw)
pitch: 0,
- moving: false,
- sprinting: false,
- airborne: false,
facing: 0, // the character's body heading (damped toward movement direction)
bank: 0, // lean into turns
state: 'idle',
});
+ // Stable array view of the positions Map for the per-frame boom collision test —
+ // re-collected only when the layout itself changes, never per frame.
+ const buildingList = useMemo(() => (positions ? [...positions.values()] : []), [positions]);
const lastSpawnRef = useRef(null);
const pointerLockedRef = useRef(false);
const proximityAppRef = useRef(null);
@@ -158,14 +161,14 @@ export default function PlayerController({
const verticalSpeed = (isSprinting ? SPRINT_SPEED : VERTICAL_SPEED) * delta;
// Movement direction relative to camera yaw
- const forward = new THREE.Vector3(-Math.sin(rig.yaw), 0, -Math.cos(rig.yaw));
- const right = new THREE.Vector3(-forward.z, 0, forward.x);
+ const forward = _forward.set(-Math.sin(rig.yaw), 0, -Math.cos(rig.yaw));
+ const right = _right.set(-forward.z, 0, forward.x);
const forwardInput = (keys.has('w') || keys.has('arrowup') ? 1 : 0)
- (keys.has('s') || keys.has('arrowdown') ? 1 : 0);
const strafeInput = (keys.has('d') || keys.has('arrowright') ? 1 : 0)
- (keys.has('a') || keys.has('arrowleft') ? 1 : 0);
- const moveDir = new THREE.Vector3(0, 0, 0)
+ const moveDir = _moveDir.set(0, 0, 0)
.addScaledVector(forward, forwardInput)
.addScaledVector(right, strafeInput);
@@ -175,7 +178,7 @@ export default function PlayerController({
if (moving) {
if (hasHorizontal) moveDir.normalize().multiplyScalar(speed);
- const nextPos = rig.position.clone().add(moveDir);
+ const nextPos = _nextPos.copy(rig.position).add(moveDir);
nextPos.y += verticalDir * verticalSpeed;
// Collision detection with buildings — skipped above rooftop height so the
@@ -186,7 +189,7 @@ export default function PlayerController({
const dx = nextPos.x - pos.x;
const dz = nextPos.z - pos.z;
const dist = Math.sqrt(dx * dx + dz * dz);
- if (dist < BUILDING_EXCLUSION_RADIUS) {
+ if (dist < BUILDING_COLLISION_RADIUS) {
// Slide along boundary tangent
const nx = dx / dist;
const nz = dz / dist;
@@ -198,7 +201,7 @@ export default function PlayerController({
// Re-check distance after slide
const dx2 = nextPos.x - pos.x;
const dz2 = nextPos.z - pos.z;
- if (Math.sqrt(dx2 * dx2 + dz2 * dz2) < BUILDING_EXCLUSION_RADIUS) {
+ if (Math.sqrt(dx2 * dx2 + dz2 * dz2) < BUILDING_COLLISION_RADIUS) {
blocked = true;
}
}
@@ -211,18 +214,19 @@ export default function PlayerController({
if (!blocked) {
// World bounds
- nextPos.x = Math.max(-WORLD_BOUND, Math.min(WORLD_BOUND, nextPos.x));
+ nextPos.x = Math.max(-WORLD.bound, Math.min(WORLD.bound, nextPos.x));
nextPos.y = Math.max(EYE_HEIGHT, Math.min(MAX_CAMERA_HEIGHT, nextPos.y));
- nextPos.z = Math.max(-WORLD_BOUND, Math.min(WORLD_BOUND, nextPos.z));
+ nextPos.z = Math.max(-WORLD.bound, Math.min(WORLD.bound, nextPos.z));
rig.position.copy(nextPos);
}
}
// Pose classification for the avatar + facing/banking toward movement.
- rig.moving = moving;
- rig.sprinting = isSprinting && moving;
- rig.airborne = rig.position.y > AIRBORNE_HEIGHT;
- rig.state = avatarState(rig);
+ rig.state = avatarState({
+ moving,
+ sprinting: isSprinting && moving,
+ airborne: rig.position.y > AIRBORNE_HEIGHT,
+ });
if (hasHorizontal) {
const target = moveFacing(rig.yaw, { forward: forwardInput, strafe: strafeInput });
const prevFacing = rig.facing;
@@ -259,12 +263,12 @@ export default function PlayerController({
if (cameraView === 'first') {
camera.position.copy(rig.position);
- const lookDir = new THREE.Vector3(
+ const lookDir = _lookDir.set(
-Math.sin(rig.yaw) * Math.cos(rig.pitch),
Math.sin(rig.pitch),
-Math.cos(rig.yaw) * Math.cos(rig.pitch),
);
- camera.lookAt(rig.position.clone().add(lookDir));
+ camera.lookAt(_lookTarget.copy(rig.position).add(lookDir));
return;
}
@@ -272,10 +276,7 @@ export default function PlayerController({
// damped so the camera glides while the aim stays tight.
const desired = thirdPersonCamera({ pos: rig.position, yaw: rig.yaw, pitch: rig.pitch });
const anchor = { x: rig.position.x, y: rig.position.y + THIRD_PERSON.lookHeight, z: rig.position.z };
- const t = resolveBoomT({ anchor, camera: desired.camera, buildings: positions?.values() });
- const camX = anchor.x + (desired.camera.x - anchor.x) * t;
- const camY = Math.max(THIRD_PERSON.minCamY, anchor.y + (desired.camera.y - anchor.y) * t);
- const camZ = anchor.z + (desired.camera.z - anchor.z) * t;
+ const { point: resolvedCam } = resolveBoom({ anchor, camera: desired.camera, buildings: buildingList });
if (!lookInitRef.current) {
// First third-person frame (mode entry): aim snaps so the camera doesn't swing
@@ -285,7 +286,7 @@ export default function PlayerController({
}
const posFactor = dampFactor(THIRD_PERSON.camDampRate, delta);
const lookFactor = dampFactor(THIRD_PERSON.lookDampRate, delta);
- camera.position.lerp(_camTarget.set(camX, camY, camZ), posFactor);
+ camera.position.lerp(_camTarget.set(resolvedCam.x, resolvedCam.y, resolvedCam.z), posFactor);
lookRef.current.lerp(_lookTarget.set(desired.lookAt.x, desired.lookAt.y, desired.lookAt.z), lookFactor);
camera.lookAt(lookRef.current);
});
@@ -294,5 +295,5 @@ export default function PlayerController({
// The visible character exists only in third person — first person stays the
// classic invisible camera (and can't self-clip).
- return cameraView === 'third' ? <PlayerAvatar rigRef={rigRef} eyeHeight={EYE_HEIGHT} /> : null;
+ return cameraView === 'third' ? <PlayerAvatar rigRef={rigRef} /> : null;
}
diff --git a/client/src/utils/cityPlayerRig.js b/client/src/utils/cityPlayerRig.js
index 327d037e0e..6bef729fee 100644
--- a/client/src/utils/cityPlayerRig.js
+++ b/client/src/utils/cityPlayerRig.js
@@ -7,6 +7,11 @@
// Convention (matches PlayerController): forward at yaw is (-sin(yaw), 0, -cos(yaw));
// the camera hangs BEHIND the character at (+sin(yaw), 0, +cos(yaw)) scaled by the boom.
+// Shared rig dimensions — the controller, the avatar, and the boom collision all read
+// these (restating them at call sites is how walk collision and camera collision drift).
+export const EYE_HEIGHT = 1.6;
+export const BUILDING_COLLISION_RADIUS = 3.5;
+
export const THIRD_PERSON = {
boom: 6.5, // camera distance behind the character
shoulder: 0.6, // lateral over-the-shoulder offset (positive = right)
@@ -54,22 +59,25 @@ const insideBuilding = (point, building, radius) =>
point.y < (building.height ?? 4) + 0.5
&& Math.hypot(point.x - building.x, point.z - building.z) < radius;
-// Boom-shortening fraction in (0, 1]: walk the camera in toward the aim anchor until it
-// clears every building cylinder. "Collision-aware enough" — a sampled pull-in, not a
-// raycast. `buildings` is any iterable of { x, z, height }.
-export function resolveBoomT({ anchor, camera, buildings, radius = 3.5 }) {
- const list = buildings ? [...buildings] : [];
- if (list.length === 0) return 1;
+// Walk the camera in toward the aim anchor until it clears every building cylinder,
+// returning `{ t, point }` — the boom fraction and the resolved camera position (so the
+// caller never re-derives the lerp). "Collision-aware enough" — a sampled pull-in, not a
+// raycast. `buildings` is an array or any iterable of { x, z, height }; pass a memoized
+// array on hot paths (an iterable is re-collected per call).
+export function resolveBoom({ anchor, camera, buildings, radius = BUILDING_COLLISION_RADIUS }) {
+ const list = Array.isArray(buildings) ? buildings : buildings ? [...buildings] : [];
+ const at = (t) => ({
+ x: anchor.x + (camera.x - anchor.x) * t,
+ y: anchor.y + (camera.y - anchor.y) * t,
+ z: anchor.z + (camera.z - anchor.z) * t,
+ });
+ if (list.length === 0) return { t: 1, point: at(1) };
const steps = [1, 0.85, 0.7, 0.55, 0.4, 0.3];
for (const t of steps) {
- const point = {
- x: anchor.x + (camera.x - anchor.x) * t,
- y: anchor.y + (camera.y - anchor.y) * t,
- z: anchor.z + (camera.z - anchor.z) * t,
- };
- if (!list.some((b) => insideBuilding(point, b, radius))) return t;
+ const point = at(t);
+ if (!list.some((b) => insideBuilding(point, b, radius))) return { t, point };
}
- return 0.25;
+ return { t: 0.25, point: at(0.25) };
}
// Frame-rate-independent damping factor: lerp by this each frame and the closure rate
diff --git a/client/src/utils/cityPlayerRig.test.js b/client/src/utils/cityPlayerRig.test.js
index 6fbdcdb2c7..2eec5f60f0 100644
--- a/client/src/utils/cityPlayerRig.test.js
+++ b/client/src/utils/cityPlayerRig.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest';
import {
- THIRD_PERSON, clampPitch, thirdPersonCamera, resolveBoomT,
+ THIRD_PERSON, clampPitch, thirdPersonCamera, resolveBoom,
dampFactor, dampAngle, moveFacing, avatarState, bankAngle,
} from './cityPlayerRig';
@@ -40,32 +40,32 @@ describe('thirdPersonCamera', () => {
});
});
-describe('resolveBoomT', () => {
+describe('resolveBoom', () => {
const anchor = { x: 0, y: 2, z: 0 };
it('keeps the full boom with no obstructions', () => {
- expect(resolveBoomT({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings: [] })).toBe(1);
- expect(resolveBoomT({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings: null })).toBe(1);
+ const clear = resolveBoom({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings: [] });
+ expect(clear.t).toBe(1);
+ expect(clear.point).toEqual({ x: 0, y: 3, z: 7 });
+ expect(resolveBoom({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings: null }).t).toBe(1);
});
it('shortens the boom when the camera lands inside a building cylinder', () => {
const buildings = [{ x: 0, z: 7, height: 10 }];
- const t = resolveBoomT({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings });
+ const { t, point } = resolveBoom({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings });
expect(t).toBeLessThan(1);
// The resolved point actually clears the cylinder.
- const z = anchor.z + (7 - anchor.z) * t;
- expect(Math.abs(z - 7)).toBeGreaterThanOrEqual(3.5);
+ expect(Math.abs(point.z - 7)).toBeGreaterThanOrEqual(3.5);
});
it('ignores buildings the camera clears above (flyover)', () => {
const buildings = [{ x: 0, z: 7, height: 4 }];
- const t = resolveBoomT({ anchor, camera: { x: 0, y: 12, z: 7 }, buildings });
- expect(t).toBe(1);
+ expect(resolveBoom({ anchor, camera: { x: 0, y: 12, z: 7 }, buildings }).t).toBe(1);
});
it('accepts any iterable (e.g. Map.values())', () => {
const map = new Map([['a', { x: 0, z: 7, height: 10 }]]);
- const t = resolveBoomT({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings: map.values() });
+ const { t } = resolveBoom({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings: map.values() });
expect(t).toBeLessThan(1);
});
});