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

fix(openworld): tighten exploration collisions and rover handling (#4671)

[._.]/ Adam Eivye7e7a844571e
diff --git a/client/src/components/openworld/OpenWorldGrass.jsx b/client/src/components/openworld/OpenWorldGrass.jsx
new file mode 100644
index 0000000000..fea98da296
--- /dev/null
+++ b/client/src/components/openworld/OpenWorldGrass.jsx
@@ -0,0 +1,100 @@
+import { useMemo, useLayoutEffect, useRef } from 'react';
+import { useFrame } from '@react-three/fiber';
+import * as THREE from 'three';
+import { mixHex, openWorldShowDetail, seededRand } from './openWorldConstants';
+import { useOpenWorldPalette } from './OpenWorldPaletteContext';
+import { NATURE_PATCHES } from './OpenWorldNature';
+import { WORLD } from '../../utils/openWorldPlan';
+
+// Grass is placed in small readable meadows rather than across every square metre. That
+// keeps the low-poly look intentional, protects the road silhouettes, and gives the rover
+// a visual reason to leave the paved arrival lane and explore the edges of town.
+const GRASS_FIELDS = [
+ { id: 'arrival-west', position: [-24, 0, 44], radius: 8.5 },
+ { id: 'arrival-east', position: [24, 0, 44], radius: 8.5 },
+ { id: 'west-greenway', position: [-45, 0, 20], radius: 7.5 },
+ { id: 'east-greenway', position: [45, 0, 20], radius: 7.5 },
+ { id: 'memory-edge', position: [-54, 0, -31], radius: 6.5 },
+ { id: 'goal-edge', position: [52, 0, -39], radius: 7 },
+ { id: 'shoreline-west', position: [-31, 0, -51], radius: 6 },
+ { id: 'shoreline-east', position: [31, 0, -51], radius: 6 },
+ ...NATURE_PATCHES.map((patch) => ({
+ id: patch.id,
+ position: patch.position,
+ radius: 2.4 + patch.scale * 1.7,
+ })),
+];
+
+const dummy = new THREE.Object3D();
+const GRASS_BASE_Y = WORLD.groundY + 0.08;
+
+function grassCount(settings) {
+ // Keep a small signature patch on the low tier. Adaptive quality may downshift on
+ // integrated GPUs, but the Vibes world should still read as a windy meadow rather
+ // than a bare debug plane.
+ if (settings?.effectiveTier === 'low') return 140;
+ if (!openWorldShowDetail(settings)) return 0;
+ if (settings?.effectiveTier === 'ultra') return 680;
+ if (settings?.effectiveTier === 'medium') return 320;
+ return 520;
+}
+
+function createBlades(count) {
+ const rand = seededRand(9117);
+ return Array.from({ length: count }, (_, index) => {
+ const field = GRASS_FIELDS[index % GRASS_FIELDS.length];
+ const angle = rand() * Math.PI * 2;
+ const radius = Math.sqrt(rand()) * field.radius;
+ return {
+ x: field.position[0] + Math.cos(angle) * radius,
+ z: field.position[2] + Math.sin(angle) * radius,
+ height: 0.42 + rand() * 0.5,
+ width: 0.7 + rand() * 0.42,
+ yaw: rand() * Math.PI * 2,
+ phase: rand() * Math.PI * 2,
+ };
+ });
+}
+
+function writeMatrices(ref, blades, time = 0) {
+ if (!ref.current) return;
+ blades.forEach((blade, index) => {
+ const gust = Math.sin(time * 0.62 + blade.x * 0.045 + blade.z * 0.032 + blade.phase) * 0.22
+ + Math.sin(time * 1.45 + blade.phase * 0.7) * 0.07;
+ const height = blade.height * (1 + Math.sin(blade.phase * 1.3) * 0.08);
+ dummy.position.set(blade.x, GRASS_BASE_Y + height * 0.5, blade.z);
+ // A triangular blade leans in two axes so the field reads as a moving volume, not
+ // as one synchronized sheet. The phase is deterministic, but the wind is shared.
+ dummy.rotation.set(gust * 0.36, blade.yaw, gust * 0.58);
+ dummy.scale.set(blade.width, height, blade.width);
+ dummy.updateMatrix();
+ ref.current.setMatrixAt(index, dummy.matrix);
+ });
+ ref.current.instanceMatrix.needsUpdate = true;
+}
+
+export default function OpenWorldGrass({ settings }) {
+ const { accent, surface, lowPoly } = useOpenWorldPalette();
+ const count = grassCount(settings);
+ const blades = useMemo(() => createBlades(count), [count]);
+ const ref = useRef();
+ const grassColor = mixHex('#4f8a5d', accent, 0.16);
+
+ useLayoutEffect(() => {
+ writeMatrices(ref, blades);
+ if (ref.current) ref.current.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
+ }, [blades]);
+
+ useFrame(({ clock }) => {
+ if (lowPoly && blades.length > 0) writeMatrices(ref, blades, clock.getElapsedTime());
+ });
+
+ if (!lowPoly || blades.length === 0) return null;
+
+ return (
+ <instancedMesh key={blades.length} ref={ref} args={[undefined, undefined, blades.length]} frustumCulled={false}>
+ <coneGeometry args={[0.12, 1, 3]} />
+ <meshStandardMaterial {...surface} color={grassColor} roughness={1} metalness={0} />
+ </instancedMesh>
+ );
+}
diff --git a/client/src/components/openworld/OpenWorldHud.jsx b/client/src/components/openworld/OpenWorldHud.jsx
index f2d56b1a0d..8c4fd8331c 100644
--- a/client/src/components/openworld/OpenWorldHud.jsx
+++ b/client/src/components/openworld/OpenWorldHud.jsx
@@ -43,7 +43,7 @@ function ControlsHint({ visible, isDesktop }) {
))}
</div>
<div className="font-pixel text-[8px] tracking-wide text-[rgb(var(--port-text-muted))]">
- WASD MOVE <span className="mx-1 opacity-50">·</span> SHIFT BOOST <span className="mx-1 opacity-50">·</span> SPACE JUMP <span className="mx-1 opacity-50">·</span> M MAP
+ WASD DRIVE <span className="mx-1 opacity-50">·</span> SHIFT BOOST <span className="mx-1 opacity-50">·</span> CTRL BRAKE <span className="mx-1 opacity-50">·</span> SPACE JUMP <span className="mx-1 opacity-50">·</span> M MAP
</div>
</div>
</div>
diff --git a/client/src/components/openworld/OpenWorldScene.jsx b/client/src/components/openworld/OpenWorldScene.jsx
index 7cd6838610..f0a007b6f0 100644
--- a/client/src/components/openworld/OpenWorldScene.jsx
+++ b/client/src/components/openworld/OpenWorldScene.jsx
@@ -38,6 +38,7 @@ import OpenWorldSky from './OpenWorldSky';
import OpenWorldGalaxySky from './OpenWorldGalaxySky';
import OpenWorldLandscape from './OpenWorldLandscape';
import OpenWorldNature from './OpenWorldNature';
+import OpenWorldGrass from './OpenWorldGrass';
import OpenWorldWater from './OpenWorldWater';
import OpenWorldStreets from './OpenWorldStreets';
import OpenWorldStreetProps from './OpenWorldStreetProps';
@@ -320,6 +321,7 @@ export default function OpenWorldScene({ apps, agentMap, onBuildingClick, onTogg
<OpenWorldLights settings={renderSettings} lightingTier={settings?.effectiveTier} />
<OpenWorldLandscape settings={renderSettings} />
<OpenWorldNature settings={renderSettings} />
+ <OpenWorldGrass settings={renderSettings} />
<OpenWorldWater settings={renderSettings} />
<OpenWorldEnergyOverlay chronotype={chronotype} settings={renderSettings} />
{neonLayers && <OpenWorldStarfield settings={renderSettings} />}
diff --git a/client/src/components/openworld/OpenWorldSettingsDrawer.jsx b/client/src/components/openworld/OpenWorldSettingsDrawer.jsx
index 3e2eb4d725..507d07315e 100644
--- a/client/src/components/openworld/OpenWorldSettingsDrawer.jsx
+++ b/client/src/components/openworld/OpenWorldSettingsDrawer.jsx
@@ -309,6 +309,7 @@ export default function OpenWorldSettingsDrawer({ open, onClose }) {
<div className="rounded-xl border border-gray-700/35 bg-black/10 px-3">
<ControlRow keys={['W', 'A', 'S', 'D']} label="Move" hint="Arrow keys also work" />
<ControlRow keys={['SHIFT']} label="Boost" />
+ <ControlRow keys={['CTRL']} label="Brake" hint="Hold while steering for a tighter turn" />
<ControlRow keys={['SPACE']} label="Jump" />
<ControlRow keys={['E', 'Q']} label="Fly up / down" hint="Free-fly vertical movement" />
<ControlRow keys={['F']} label="Interact" hint="Buildings and warp pads" />
diff --git a/client/src/components/openworld/OpenWorldStreetProps.jsx b/client/src/components/openworld/OpenWorldStreetProps.jsx
index 6821acb504..5d55fc2295 100644
--- a/client/src/components/openworld/OpenWorldStreetProps.jsx
+++ b/client/src/components/openworld/OpenWorldStreetProps.jsx
@@ -1,15 +1,16 @@
import { useMemo, useLayoutEffect, useRef } from 'react';
+import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import { openWorldDayMix, openWorldShowDetail, mixHex } from './openWorldConstants';
import { useOpenWorldPalette } from './OpenWorldPaletteContext';
import { computeStreets, computeStreetProps } from '../../utils/openWorldPlan';
// Street furniture from the master plan: lamp posts pooling light along every street and
-// planting trees ringing the AI Core plaza. Everything is instanced — five draw calls cover
-// the whole town regardless of lamp count. Lamp light pools are faked with emissive heads
-// + additive ground discs (the city's established no-real-point-lights pattern).
-// Adaptive-quality gated: lamps and their light pools are detail-only, while the plaza grove
-// remains at every tier because it is part of the city's navigation and sense of place.
+// planting trees ringing the AI Core plaza. Everything is instanced, so lamp count does not
+// multiply the scene's draw calls. Lamp light pools are faked with emissive heads + additive
+// ground discs (the city's established no-real-point-lights pattern).
+// The Vibes silhouettes remain on the low tier; Cyber keeps the older detail gate because its
+// neon dressing is much heavier and the grove is already enough orientation at that tier.
const dummy = new THREE.Object3D();
@@ -17,6 +18,8 @@ const dummy = new THREE.Object3D();
// runs only when placements actually change, not on every parent re-render.
const POLE_POS = [0, 1.7, 0];
const HEAD_POS = [0, 3.45, 0];
+const HEAD_CORE_POS = [0, 3.45, 0];
+const HEAD_CAP_POS = [0, 3.75, 0];
const POOL_POS = [0, 0.035, 0];
const TRUNK_POS = [0, 0.55, 0];
const CANOPY_POS = [0, 1.55, 0];
@@ -24,20 +27,34 @@ const CANOPY_TOP_POS = [0, 2.12, 0, 0.72];
// One instanced mesh whose matrices are written once from `placements`. `flat` lays the
// geometry into the ground plane (used by the light-pool discs).
-function Instances({ placements, geometry, geometryArgs, position, flat = false, children }) {
+function writeMatrices(ref, placements, position, flat, sway, time = 0) {
+ if (!ref.current) return;
+ const scaleMultiplier = position[3] ?? 1;
+ placements.forEach((p, i) => {
+ const phase = p.seed ?? i;
+ const gust = sway
+ ? Math.sin(time * 0.72 + phase * 1.7 + p.x * 0.04 + p.z * 0.03) * 0.035
+ + Math.sin(time * 1.21 + phase * 0.63) * 0.016
+ : 0;
+ dummy.position.set(p.x + position[0], position[1], p.z + position[2]);
+ dummy.rotation.set(flat ? -Math.PI / 2 : gust * 0.6, !flat && p.seed != null ? (p.seed * 1.7) % (Math.PI * 2) : 0, flat ? 0 : gust);
+ dummy.scale.setScalar((p.scale ?? 1) * scaleMultiplier);
+ dummy.updateMatrix();
+ ref.current.setMatrixAt(i, dummy.matrix);
+ });
+ ref.current.instanceMatrix.needsUpdate = true;
+}
+
+function Instances({ placements, geometry, geometryArgs, position, flat = false, sway = false, children }) {
const ref = useRef();
useLayoutEffect(() => {
- if (!ref.current) return;
- const scaleMultiplier = position[3] ?? 1;
- placements.forEach((p, i) => {
- dummy.position.set(p.x + position[0], position[1], p.z + position[2]);
- dummy.rotation.set(flat ? -Math.PI / 2 : 0, !flat && p.seed != null ? (p.seed * 1.7) % (Math.PI * 2) : 0, 0);
- dummy.scale.setScalar((p.scale ?? 1) * scaleMultiplier);
- dummy.updateMatrix();
- ref.current.setMatrixAt(i, dummy.matrix);
- });
- ref.current.instanceMatrix.needsUpdate = true;
- }, [placements, position, flat]);
+ writeMatrices(ref, placements, position, flat, sway);
+ if (sway && ref.current) ref.current.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
+ }, [placements, position, flat, sway]);
+
+ useFrame(({ clock }) => {
+ if (sway) writeMatrices(ref, placements, position, flat, true, clock.getElapsedTime());
+ });
return (
<instancedMesh ref={ref} args={[undefined, undefined, placements.length]} frustumCulled={false}>
@@ -45,6 +62,7 @@ function Instances({ placements, geometry, geometryArgs, position, flat = false,
{geometry === 'sphere' && <sphereGeometry args={geometryArgs} />}
{geometry === 'circle' && <circleGeometry args={geometryArgs} />}
{geometry === 'icosahedron' && <icosahedronGeometry args={geometryArgs} />}
+ {geometry === 'box' && <boxGeometry args={geometryArgs} />}
{children}
</instancedMesh>
);
@@ -62,7 +80,7 @@ export default function OpenWorldStreetProps({ settings }) {
// Keep the plaza grove even on the low tier: it is cheap, anchors the center of the map,
// and gives the bright world a sense of scale. Lamps and their additive pools remain detail-only.
- const showLamps = openWorldShowDetail(settings);
+ const showLamps = lowPoly || openWorldShowDetail(settings);
if (!showLamps && props.trees.length === 0) return null;
const lampGlow = mixHex(accent, '#ffe2a6', 0.58);
@@ -81,10 +99,17 @@ export default function OpenWorldStreetProps({ settings }) {
<Instances placements={props.lamps} geometry="cylinder" geometryArgs={[0.05, 0.08, 3.4, 6]} position={POLE_POS}>
<meshStandardMaterial {...surface} color={structureColor} roughness={0.7} metalness={lowPoly ? 0 : 0.45} />
</Instances>
- {/* Lamp heads — emissive spheres standing in for point lights */}
- <Instances placements={props.lamps} geometry="sphere" geometryArgs={[0.16, 10, 10]} position={HEAD_POS}>
+ {/* Faceted lantern housings + warm cores: a stronger silhouette than a bare orb,
+ while still keeping the city's no-point-light performance budget. */}
+ <Instances placements={props.lamps} geometry="box" geometryArgs={[0.48, 0.5, 0.48]} position={HEAD_POS}>
+ <meshStandardMaterial {...surface} color={structureColor} roughness={0.65} metalness={lowPoly ? 0 : 0.35} />
+ </Instances>
+ <Instances placements={props.lamps} geometry="box" geometryArgs={[0.29, 0.31, 0.29]} position={HEAD_CORE_POS}>
<meshBasicMaterial color={lampGlow} transparent opacity={headOpacity} toneMapped={false} />
</Instances>
+ <Instances placements={props.lamps} geometry="box" geometryArgs={[0.58, 0.07, 0.58]} position={HEAD_CAP_POS}>
+ <meshStandardMaterial {...surface} color={structureColor} roughness={0.7} metalness={lowPoly ? 0 : 0.4} />
+ </Instances>
{/* Faked light pools on the pavement */}
{poolOpacity > 0.005 && (
<Instances placements={props.lamps} geometry="circle" geometryArgs={[1.7, 16]} position={POOL_POS} flat>
@@ -107,15 +132,15 @@ export default function OpenWorldStreetProps({ settings }) {
floating gems; Cyber keeps the established wireframe treatment. */}
{lowPoly ? (
<>
- <Instances placements={props.trees} geometry="sphere" geometryArgs={[0.9, 8, 5]} position={CANOPY_POS}>
+ <Instances placements={props.trees} geometry="sphere" geometryArgs={[0.9, 8, 5]} position={CANOPY_POS} sway>
<meshStandardMaterial {...surface} color={foliageColor} roughness={0.98} />
</Instances>
- <Instances placements={props.trees} geometry="sphere" geometryArgs={[0.68, 8, 5]} position={CANOPY_TOP_POS}>
+ <Instances placements={props.trees} geometry="sphere" geometryArgs={[0.68, 8, 5]} position={CANOPY_TOP_POS} sway>
<meshStandardMaterial {...surface} color={mixHex(foliageColor, '#d5e7a4', 0.28)} roughness={0.98} />
</Instances>
</>
) : (
- <Instances placements={props.trees} geometry="icosahedron" geometryArgs={[0.8, 1]} position={CANOPY_POS}>
+ <Instances placements={props.trees} geometry="icosahedron" geometryArgs={[0.8, 1]} position={CANOPY_POS} sway>
<meshBasicMaterial
color={mixHex(accent, '#22c55e', 0.45)}
wireframe
diff --git a/client/src/components/openworld/PlayerAvatar.jsx b/client/src/components/openworld/PlayerAvatar.jsx
index d9b1246254..4e9824fc8d 100644
--- a/client/src/components/openworld/PlayerAvatar.jsx
+++ b/client/src/components/openworld/PlayerAvatar.jsx
@@ -2,15 +2,15 @@ import { useRef } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import { useOpenWorldPalette } from './OpenWorldPaletteContext';
-import { dampFactor, EYE_HEIGHT } from '../../utils/openWorldPlayerRig';
+import { dampFactor, EYE_HEIGHT, VEHICLE } from '../../utils/openWorldPlayerRig';
import { mixHex } from './openWorldConstants';
// A small, procedural low-poly rover keeps the third-person actor local to OpenWorld.
// It is intentionally made from primitives instead of another downloaded GLB: the car
// inherits the active theme, loads instantly, and stays readable while sprinting, jumping,
// or flying above the city.
-const CAR_LENGTH = 1.85;
-const CAR_WIDTH = 1.06;
+const CAR_LENGTH = VEHICLE.bodyLength;
+const CAR_WIDTH = VEHICLE.bodyWidth;
const WHEEL_RADIUS = 0.24;
const WHEEL_X = CAR_WIDTH * 0.57;
const WHEEL_Z = CAR_LENGTH * 0.31;
@@ -41,21 +41,27 @@ export default function PlayerAvatar({ rigRef }) {
const running = rig.state === 'run';
const follow = dampFactor(10, delta);
const targetY = rig.position.y - EYE_HEIGHT + (hovering ? 0.25 : 0);
+ const speed = rig.speed || 0;
+ const speedRatio = Math.min(1, Math.abs(speed) / 38);
root.position.lerp(_rootTarget.set(rig.position.x, targetY, rig.position.z), follow);
root.rotation.y = rig.facing;
- root.rotation.z = rig.bank * 0.38;
+ root.rotation.z = rig.bank * 0.58;
- const bob = hovering ? 0.2 + Math.sin(t * 2.4) * 0.07 : 0;
+ const bob = hovering
+ ? 0.2 + Math.sin(t * 2.4) * 0.07
+ : Math.sin(t * (7 + speedRatio * 8)) * 0.018 * speedRatio;
body.position.y += (bob - body.position.y) * follow;
- body.rotation.x = hovering ? Math.sin(t * 2.1) * 0.045 : 0;
- body.rotation.z = rig.bank * 0.32;
+ body.rotation.x = hovering ? Math.sin(t * 2.1) * 0.045 : -speedRatio * 0.018;
+ body.rotation.z = rig.bank * 0.34;
- const wheelSpeed = running ? 15 : moving ? 8 : 0;
- wheelRefs.current.forEach((wheel) => {
+ const wheelSpeed = speed !== 0 ? speed / WHEEL_RADIUS : running ? 15 : moving ? 8 : 0;
+ wheelRefs.current.forEach((wheel, index) => {
if (!wheel) return;
wheel.rotation.x -= wheelSpeed * delta;
- wheel.rotation.y = hovering ? Math.sin(t * 2) * 0.08 : 0;
+ // The front axle follows the damped steering angle. Rear wheels stay planted while
+ // the whole rover banks, which makes steering readable even at low speed.
+ wheel.rotation.y = index >= 2 ? (rig.wheelAngle || 0) : 0;
});
if (hoverRingRef.current) {
diff --git a/client/src/components/openworld/PlayerController.jsx b/client/src/components/openworld/PlayerController.jsx
index 2d10b369ab..d4aef2d659 100644
--- a/client/src/components/openworld/PlayerController.jsx
+++ b/client/src/components/openworld/PlayerController.jsx
@@ -4,11 +4,13 @@ import * as THREE from 'three';
import PlayerAvatar from './PlayerAvatar';
import ErrorBoundary from '../ErrorBoundary';
import {
- THIRD_PERSON, EYE_HEIGHT, DEFAULT_SPAWN_Z, BUILDING_COLLISION_RADIUS,
+ THIRD_PERSON, EYE_HEIGHT, DEFAULT_SPAWN_Z,
thirdPersonCamera, resolveBoom,
- dampFactor, dampAngle, moveFacing, avatarState, bankAngle,
+ dampFactor, dampAngle, moveFacing, avatarState, bankAngle, stepVehicle,
+ moveWithCollisions, PLAYER_COLLISION_RADIUS, VEHICLE_COLLISION,
} from '../../utils/openWorldPlayerRig';
import { isWalkable, WORLD } from '../../utils/openWorldPlan';
+import { BOROUGH_PARAMS, BUILDING_PARAMS, PROCESS_BUILDING_PARAMS } from './openWorldConstants';
import { regionWarpPadPosition } from '../../utils/openWorldRegions';
const WALK_SPEED = 10;
@@ -34,13 +36,13 @@ const _lookTarget = new THREE.Vector3();
// Exploration-mode player rig. One mutable rig object is the single source of truth for
// the player's pose; both camera modes (and the third-person avatar) read from it:
-// - 'third' (default): a damped follow camera behind a visible low-poly rover, with
-// building-aware boom shortening (openWorldPlayerRig.js owns all the math).
+// - 'third' (default): a damped follow camera behind a visible low-poly rover with
+// arcade vehicle handling, building-aware boom shortening, and speed-weighted steering.
// - 'first' (V to toggle): the classic invisible first-person camera.
-// All original behavior is preserved: WASD/arrows, shift boost, E/Q vertical, F interact,
-// R respawn, pointer-lock mouselook, per-building cylinder collision below flyover height,
-// world bounds, and spawn persistence. Ground movement can't enter the bay (the harbor piers
-// stay walkable — see isWalkable in openWorldPlan.js).
+// WASD/arrows, shift boost, E/Q vertical, F interact, R respawn, pointer-lock mouselook,
+// shape-aware building/pylon collision below flyover height, world bounds, and spawn
+// persistence remain available. Ground movement can't enter the bay (the harbor piers stay
+// walkable — see isWalkable in openWorldPlan.js).
export default function PlayerController({
keysRef,
positions,
@@ -62,9 +64,13 @@ export default function PlayerController({
const rigRef = useRef({
position: new THREE.Vector3(0, EYE_HEIGHT, 0),
yaw: THIRD_PERSON.isometricYaw, // camera heading; forward is (-sin yaw, 0, -cos yaw)
+ heading: THIRD_PERSON.isometricYaw, // rover heading; camera orbit can look independently
pitch: 0,
facing: THIRD_PERSON.isometricYaw, // the character's body heading (damped toward movement direction)
bank: 0, // lean into turns
+ speed: 0, // signed rover speed; positive forward, negative reverse
+ wheelAngle: 0,
+ skid: 0,
vy: 0, // vertical velocity for the Space jump arc (E/Q free-fly zeroes it)
jumping: false, // an active Space jump arc — gates gravity so E/Q free-fly holds altitude
state: 'idle',
@@ -72,6 +78,38 @@ export default function PlayerController({
// 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]);
+ // Movement colliders mirror the rendered footprint: app buildings are boxes and
+ // process pylons are round. The boom keeps its own larger camera-only padding above.
+ const collisionShapes = useMemo(() => {
+ if (!positions) return [];
+ const appById = new Map((apps || []).map((app) => [app.id, app]));
+ const shapes = [];
+
+ positions.forEach((pos, appId) => {
+ shapes.push({
+ shape: 'box',
+ x: pos.x,
+ z: pos.z,
+ halfWidth: BUILDING_PARAMS.width / 2,
+ halfDepth: BUILDING_PARAMS.depth / 2,
+ });
+
+ const app = appById.get(appId);
+ const processCount = app?.archived || !Array.isArray(app?.processes) ? 0 : app.processes.length;
+ const processRadius = Math.max(PROCESS_BUILDING_PARAMS.width, PROCESS_BUILDING_PARAMS.depth) * 0.58;
+ for (let index = 0; index < processCount; index += 1) {
+ const angle = (index / processCount) * Math.PI * 2;
+ shapes.push({
+ shape: 'circle',
+ x: pos.x + Math.cos(angle) * BOROUGH_PARAMS.processRingRadius,
+ z: pos.z + Math.sin(angle) * BOROUGH_PARAMS.processRingRadius,
+ radius: processRadius,
+ });
+ }
+ });
+
+ return shapes;
+ }, [apps, positions]);
const warpPadList = useMemo(
() => warpPads.map((region) => ({ region, position: regionWarpPadPosition(region) })).filter((entry) => entry.position),
[warpPads],
@@ -86,12 +124,31 @@ export default function PlayerController({
// Re-snap the aim whenever the camera mode flips (V) so the lerp never starts
// from a stale aim point left by the previous third-person stint.
- useEffect(() => { lookInitRef.current = false; }, [cameraView]);
+ useEffect(() => {
+ const rig = rigRef.current;
+ // A camera-mode change is also a clean handoff: first person inherits the current
+ // rover heading, and returning to the rover starts with the camera's current aim.
+ rig.heading = rig.yaw;
+ rig.facing = rig.yaw;
+ rig.speed = 0;
+ rig.wheelAngle = 0;
+ rig.skid = 0;
+ lookInitRef.current = false;
+ }, [cameraView]);
// Initialize spawn position
useEffect(() => {
- if (!active) return;
const rig = rigRef.current;
+ if (!active) {
+ // Orbital mode pauses the frame loop. Clear a partially applied throttle so
+ // dropping back into the street never resumes with stale momentum.
+ rig.speed = 0;
+ rig.wheelAngle = 0;
+ rig.skid = 0;
+ rig.vy = 0;
+ rig.jumping = false;
+ return;
+ }
if (lastSpawnRef.current) {
rig.position.copy(lastSpawnRef.current);
} else {
@@ -106,8 +163,12 @@ export default function PlayerController({
// playable streets and landmarks before the player drives toward downtown.
rig.position.set(0, EYE_HEIGHT, Math.max(maxZ + 8, DEFAULT_SPAWN_Z));
rig.yaw = THIRD_PERSON.isometricYaw;
+ rig.heading = THIRD_PERSON.isometricYaw;
rig.pitch = 0;
rig.facing = THIRD_PERSON.isometricYaw;
+ rig.speed = 0;
+ rig.wheelAngle = 0;
+ rig.skid = 0;
lastSpawnRef.current = rig.position.clone();
}
lookInitRef.current = false;
@@ -124,8 +185,12 @@ export default function PlayerController({
rig.position.set(teleport.x, EYE_HEIGHT, teleport.z);
// Face the destination from the same diagonal heading as the default isometric view.
rig.yaw = THIRD_PERSON.isometricYaw;
+ rig.heading = THIRD_PERSON.isometricYaw;
rig.pitch = 0;
rig.facing = THIRD_PERSON.isometricYaw;
+ rig.speed = 0;
+ rig.wheelAngle = 0;
+ rig.skid = 0;
rig.vy = 0;
rig.jumping = false;
lastSpawnRef.current = rig.position.clone();
@@ -200,8 +265,12 @@ export default function PlayerController({
} else if (key === 'r' && lastSpawnRef.current) {
rigRef.current.position.copy(lastSpawnRef.current);
rigRef.current.yaw = THIRD_PERSON.isometricYaw;
+ rigRef.current.heading = THIRD_PERSON.isometricYaw;
rigRef.current.pitch = 0;
rigRef.current.facing = THIRD_PERSON.isometricYaw;
+ rigRef.current.speed = 0;
+ rigRef.current.wheelAngle = 0;
+ rigRef.current.skid = 0;
rigRef.current.vy = 0;
rigRef.current.jumping = false;
lookInitRef.current = false;
@@ -267,24 +336,52 @@ export default function PlayerController({
rig.pitch = Math.max(-PITCH_LIMIT, Math.min(PITCH_LIMIT, rig.pitch - lookDeltaY * MOUSE_SENSITIVITY));
}
+ const isVehicle = cameraView === 'third';
const isSprinting = keys.has('shift') || Boolean(mobileInput?.boost);
const speed = (isSprinting ? SPRINT_SPEED : WALK_SPEED) * delta;
const verticalSpeed = (isSprinting ? SPRINT_SPEED : VERTICAL_SPEED) * delta;
-
- // Movement direction relative to camera yaw
- const forward = _forward.set(-Math.sin(rig.yaw), 0, -Math.cos(rig.yaw));
- const right = _right.set(-forward.z, 0, forward.x);
-
const keyboardForward = (keys.has('w') || keys.has('arrowup') ? 1 : 0)
- (keys.has('s') || keys.has('arrowdown') ? 1 : 0);
const keyboardStrafe = (keys.has('d') || keys.has('arrowright') ? 1 : 0)
- (keys.has('a') || keys.has('arrowleft') ? 1 : 0);
const forwardInput = THREE.MathUtils.clamp(keyboardForward - (mobileInput?.moveY || 0), -1, 1);
const strafeInput = THREE.MathUtils.clamp(keyboardStrafe + (mobileInput?.moveX || 0), -1, 1);
- const moveDir = _moveDir.set(0, 0, 0)
- .addScaledVector(forward, forwardInput)
- .addScaledVector(right, strafeInput);
-
+ const brake = keys.has('control') || keys.has('x');
+ const previousHeading = rig.heading;
+ const moveDir = _moveDir.set(0, 0, 0);
+ if (isVehicle) {
+ // Third-person is a rover: left/right steer the nose, while the analog stick's
+ // horizontal axis remains the same steering input on touch devices. The camera yaw
+ // stays independent so a player can look around while carrying speed.
+ const drive = stepVehicle({
+ speed: rig.speed,
+ heading: rig.heading,
+ wheelAngle: rig.wheelAngle,
+ throttle: forwardInput,
+ steer: strafeInput,
+ boost: isSprinting,
+ brake,
+ delta,
+ });
+ rig.speed = drive.speed;
+ rig.heading = drive.heading;
+ rig.wheelAngle = drive.wheelAngle;
+ rig.skid = drive.skid;
+ moveDir.set(drive.displacement.x, 0, drive.displacement.z);
+ } else {
+ // First person remains the useful free-roam inspection mode: movement stays relative
+ // to the mouse aim and keeps the original walk/fly behavior.
+ const forward = _forward.set(-Math.sin(rig.yaw), 0, -Math.cos(rig.yaw));
+ const right = _right.set(-forward.z, 0, forward.x);
+ moveDir
+ .addScaledVector(forward, forwardInput)
+ .addScaledVector(right, strafeInput);
+ if (moveDir.lengthSq() > 0) moveDir.normalize().multiplyScalar(speed);
+ rig.heading = rig.yaw;
+ rig.speed = 0;
+ rig.wheelAngle = 0;
+ rig.skid = 0;
+ }
const hasHorizontal = moveDir.lengthSq() > 0;
// Vertical: E/Q is direct free-fly and takes precedence — it cancels any jump and
@@ -306,52 +403,49 @@ export default function PlayerController({
dy = rig.vy * delta;
}
}
- const moving = hasHorizontal || dy !== 0;
+ const hasMotionIntent = hasHorizontal || dy !== 0;
+ let movedHorizontally = false;
- if (moving) {
- if (hasHorizontal) moveDir.normalize().multiplyScalar(speed);
+ if (hasMotionIntent) {
+ const startX = rig.position.x;
+ const startZ = rig.position.z;
const nextPos = _nextPos.copy(rig.position).add(moveDir);
nextPos.y += dy;
- // Collision detection with buildings — skipped above rooftop height so the
- // player can fly over the city.
+ // Collision detection is skipped above rooftop height so the player can fly over
+ // the city. The resolver stops at the actual facade/pylon contact and preserves
+ // the free axis for a stable wall slide.
let blocked = false;
if (hasHorizontal && nextPos.y < BUILDING_FLYOVER_HEIGHT) {
- positions?.forEach((pos) => {
- const dx = nextPos.x - pos.x;
- const dz = nextPos.z - pos.z;
- const dist = Math.sqrt(dx * dx + dz * dz);
- if (dist < BUILDING_COLLISION_RADIUS) {
- // Slide along boundary tangent
- const nx = dx / dist;
- const nz = dz / dist;
- const dot = moveDir.x * nx + moveDir.z * nz;
- if (dot < 0) {
- // Moving toward building - project movement onto tangent
- nextPos.x = rig.position.x + (moveDir.x - dot * nx) * 0.8;
- nextPos.z = rig.position.z + (moveDir.z - dot * nz) * 0.8;
- // 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_COLLISION_RADIUS) {
- blocked = true;
- }
- }
- }
+ const collision = moveWithCollisions({
+ position: rig.position,
+ displacement: { x: moveDir.x, z: moveDir.z },
+ colliders: collisionShapes,
+ body: isVehicle
+ ? { type: 'vehicle', heading: rig.heading, ...VEHICLE_COLLISION }
+ : { type: 'circle', radius: PLAYER_COLLISION_RADIUS },
});
+ nextPos.x = collision.x;
+ nextPos.z = collision.z;
+ blocked = collision.blocked;
// The bay is not walkable (the harbor piers are) — a grounded player stops
// at the shoreline instead of strolling onto open water.
- if (!isWalkable(nextPos.x, nextPos.z)) blocked = true;
+ if (!isWalkable(nextPos.x, nextPos.z)) {
+ blocked = true;
+ // Water is a hard terrain boundary rather than a wall: undo the whole
+ // attempted move so the player cannot slide diagonally onto the bay.
+ nextPos.x = rig.position.x;
+ nextPos.z = rig.position.z;
+ }
}
// Vertical (jump/gravity) is independent of horizontal collision: a wall only
- // stops x/z, never the jump arc. Pinning x/z back to the current position when
- // blocked — instead of skipping the whole write — lets the hop still rise, fall,
- // and land (resetting rig.vy) rather than freezing mid-air while vy keeps
- // integrating downward and then yanking the player down when they turn away.
+ // stops horizontal progress, never the jump arc. The resolver has already placed
+ // the player at the contact point (and kept any tangent slide); terrain boundaries
+ // were reset above. In either case the hop still rises, falls, and lands rather
+ // than freezing mid-air while vy keeps integrating downward.
if (blocked) {
- nextPos.x = rig.position.x;
- nextPos.z = rig.position.z;
+ if (isVehicle) rig.speed = 0;
}
// World bounds
nextPos.x = Math.max(-WORLD.bound, Math.min(WORLD.bound, nextPos.x));
@@ -363,16 +457,27 @@ export default function PlayerController({
rig.vy = 0;
rig.jumping = false;
}
+ movedHorizontally = Math.abs(nextPos.x - startX) > 1e-5 || Math.abs(nextPos.z - startZ) > 1e-5;
rig.position.copy(nextPos);
}
// Pose classification for the avatar + facing/banking toward movement.
+ const moving = movedHorizontally || dy !== 0;
rig.state = avatarState({
moving,
- sprinting: isSprinting && moving,
+ sprinting: isVehicle ? Math.abs(rig.speed) > 16 || (isSprinting && moving) : isSprinting && moving,
airborne: rig.position.y > AIRBORNE_HEIGHT,
});
- if (hasHorizontal) {
+ if (isVehicle) {
+ const prevFacing = rig.facing;
+ rig.facing = dampAngle(rig.facing, rig.heading, dampFactor(14, delta));
+ const headingStep = delta > 0 ? (dampAngle(previousHeading, rig.heading, 1) - previousHeading) / delta : 0;
+ const turnBank = bankAngle(headingStep, 0.24, 0.045) + rig.wheelAngle * rig.skid * 0.08;
+ rig.bank += (turnBank - rig.bank) * dampFactor(8, delta);
+ // Keep the facing value live even while coasting to a stop; the visual rover should
+ // settle into the same heading as the steering math rather than snap at zero speed.
+ if (!movedHorizontally && Math.abs(prevFacing - rig.heading) < 0.001) rig.facing = rig.heading;
+ } else if (movedHorizontally) {
const target = moveFacing(rig.yaw, { forward: forwardInput, strafe: strafeInput });
const prevFacing = rig.facing;
rig.facing = dampAngle(rig.facing, target, dampFactor(10, delta));
diff --git a/client/src/utils/openWorldPlayerRig.js b/client/src/utils/openWorldPlayerRig.js
index d647acde34..1b84ef63c3 100644
--- a/client/src/utils/openWorldPlayerRig.js
+++ b/client/src/utils/openWorldPlayerRig.js
@@ -10,7 +10,10 @@
// 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;
+// Camera boom padding stays deliberately generous so the view does not clip into a
+// facade. Player movement uses the shape-aware colliders below instead of this radius.
export const BUILDING_COLLISION_RADIUS = 3.5;
+export const PLAYER_COLLISION_RADIUS = 0.55;
export const DEFAULT_SPAWN_Z = 52;
export const THIRD_PERSON = {
@@ -29,6 +32,33 @@ export const THIRD_PERSON = {
lookDampRate: 12, // aim smoothing (tighter than position so aim stays crisp)
};
+// Arcade vehicle tuning for the default rover. It deliberately stops short of a full
+// rigid-body simulation: OpenWorld needs a dependable, low-latency toy-car feel on a
+// dashboard canvas, while still borrowing the important reference-game cues — ramped
+// acceleration, a real brake, reverse, speed-weighted steering, and a little drift.
+export const VEHICLE = {
+ bodyLength: 1.85,
+ bodyWidth: 1.06,
+ maxSpeed: 24,
+ boostMaxSpeed: 38,
+ reverseMaxSpeed: 10,
+ acceleration: 22,
+ boostAcceleration: 31,
+ coastDeceleration: 5.5,
+ brakeDeceleration: 34,
+ turnRate: 2.8,
+ maxWheelAngle: 0.62,
+ steeringResponse: 9,
+};
+
+// The visible wheels extend a little beyond the body box. Keep that small envelope in
+// one place so the rover cannot visually overlap a wall without bringing back the old
+// multi-unit empty cushion around every building.
+export const VEHICLE_COLLISION = {
+ halfWidth: 0.7,
+ halfLength: 0.98,
+};
+
export const clampPitch = (pitch) =>
Math.min(THIRD_PERSON.maxPitch, Math.max(THIRD_PERSON.minPitch, pitch));
@@ -62,14 +92,13 @@ export function thirdPersonCamera({
};
}
-// True when a camera point lands inside a building cylinder (the same cylinder model
-// PlayerController uses for walking collision). Above a building's roof the point is
-// clear — flyover camera angles stay unclipped.
+// True when a camera point lands inside a building safety cylinder. The camera keeps a
+// simpler generous envelope than the movement solver so the boom does not clip a facade.
const insideBuilding = (point, building, radius) =>
point.y < (building.height ?? 4) + 0.5
&& Math.hypot(point.x - building.x, point.z - building.z) < radius;
-// Walk the camera in toward the aim anchor until it clears every building cylinder,
+// Walk the camera in toward the aim anchor until it clears every building safety 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
@@ -90,10 +119,195 @@ export function resolveBoom({ anchor, camera, buildings, radius = BUILDING_COLLI
return { t: 0.25, point: at(0.25) };
}
+const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
+
+const circleIntersectsBox = (point, collider, radius) => {
+ const halfWidth = Math.max(0, collider.halfWidth ?? 0);
+ const halfDepth = Math.max(0, collider.halfDepth ?? 0);
+ const closestX = clamp(point.x, collider.x - halfWidth, collider.x + halfWidth);
+ const closestZ = clamp(point.z, collider.z - halfDepth, collider.z + halfDepth);
+ const dx = point.x - closestX;
+ const dz = point.z - closestZ;
+ return dx * dx + dz * dz < radius * radius;
+};
+
+const vehicleAxes = (heading) => ({
+ right: { x: Math.cos(heading), z: -Math.sin(heading) },
+ forward: { x: -Math.sin(heading), z: -Math.cos(heading) },
+});
+
+const vehicleIntersectsCircle = (point, collider, body) => {
+ const { right, forward } = vehicleAxes(body.heading ?? 0);
+ const dx = collider.x - point.x;
+ const dz = collider.z - point.z;
+ const localX = dx * right.x + dz * right.z;
+ const localZ = dx * forward.x + dz * forward.z;
+ const closestX = clamp(localX, -body.halfWidth, body.halfWidth);
+ const closestZ = clamp(localZ, -body.halfLength, body.halfLength);
+ const offsetX = localX - closestX;
+ const offsetZ = localZ - closestZ;
+ return offsetX * offsetX + offsetZ * offsetZ < (collider.radius ?? 0) ** 2;
+};
+
+const vehicleIntersectsBox = (point, collider, body) => {
+ const { right, forward } = vehicleAxes(body.heading ?? 0);
+ const axes = [
+ { x: 1, z: 0 },
+ { x: 0, z: 1 },
+ right,
+ forward,
+ ];
+ const dx = collider.x - point.x;
+ const dz = collider.z - point.z;
+ const halfWidth = Math.max(0, collider.halfWidth ?? 0);
+ const halfDepth = Math.max(0, collider.halfDepth ?? 0);
+
+ return axes.every((axis) => {
+ const distance = Math.abs(dx * axis.x + dz * axis.z);
+ const vehicleProjection = Math.abs(axis.x * right.x + axis.z * right.z) * body.halfWidth
+ + Math.abs(axis.x * forward.x + axis.z * forward.z) * body.halfLength;
+ const colliderProjection = Math.abs(axis.x) * halfWidth + Math.abs(axis.z) * halfDepth;
+ return distance < vehicleProjection + colliderProjection;
+ });
+};
+
+const bodyIntersects = (point, colliders, body) => {
+ const bodyType = body?.type || 'circle';
+ if (bodyType === 'vehicle') {
+ return colliders.some((collider) => {
+ if (!Number.isFinite(collider?.x) || !Number.isFinite(collider?.z)) return false;
+ return collider.shape === 'circle'
+ ? vehicleIntersectsCircle(point, collider, body)
+ : vehicleIntersectsBox(point, collider, body);
+ });
+ }
+
+ const radius = Math.max(0, body?.radius ?? PLAYER_COLLISION_RADIUS);
+ return colliders.some((collider) => {
+ if (!Number.isFinite(collider?.x) || !Number.isFinite(collider?.z)) return false;
+ if (collider.shape === 'circle') {
+ const combinedRadius = radius + Math.max(0, collider.radius ?? 0);
+ const dx = point.x - collider.x;
+ const dz = point.z - collider.z;
+ return dx * dx + dz * dz < combinedRadius * combinedRadius;
+ }
+ return circleIntersectsBox(point, collider, radius);
+ });
+};
+
+// Move a player body through static 2D colliders. Each world axis is swept in small
+// increments, then the first colliding increment is binary-searched to the contact
+// point. Resolving X and Z independently gives the familiar arcade-game wall slide,
+// while the sweep prevents a fast rover frame from tunneling through a pylon.
+export function moveWithCollisions({
+ position,
+ displacement,
+ colliders = [],
+ body = { type: 'circle', radius: PLAYER_COLLISION_RADIUS },
+ maxSampleDistance = 0.25,
+}) {
+ const current = { x: position?.x ?? 0, z: position?.z ?? 0 };
+ const shapes = Array.isArray(colliders) ? colliders : [];
+ const stepDistance = Math.max(0.01, Number.isFinite(maxSampleDistance) ? maxSampleDistance : 0.25);
+ const blockedAxes = { x: false, z: false };
+ let blocked = false;
+
+ const moveAxis = (axis, amount) => {
+ if (!Number.isFinite(amount) || amount === 0) return;
+ const sampleCount = Math.max(1, Math.ceil(Math.abs(amount) / stepDistance));
+ const sample = amount / sampleCount;
+
+ for (let index = 0; index < sampleCount; index += 1) {
+ const start = current[axis];
+ const end = start + sample;
+ const candidate = { x: current.x, z: current.z };
+ candidate[axis] = end;
+ if (!bodyIntersects(candidate, shapes, body)) {
+ current[axis] = end;
+ continue;
+ }
+
+ let safe = 0;
+ let contact = 1;
+ for (let iteration = 0; iteration < 10; iteration += 1) {
+ const midpoint = (safe + contact) * 0.5;
+ const probe = { x: current.x, z: current.z };
+ probe[axis] = start + sample * midpoint;
+ if (bodyIntersects(probe, shapes, body)) contact = midpoint;
+ else safe = midpoint;
+ }
+ current[axis] = start + sample * safe;
+ blocked = true;
+ blockedAxes[axis] = true;
+ return;
+ }
+ };
+
+ moveAxis('x', displacement?.x ?? 0);
+ moveAxis('z', displacement?.z ?? 0);
+
+ return { ...current, blocked, blockedAxes };
+}
+
// Frame-rate-independent damping factor: lerp by this each frame and the closure rate
// stays constant whether the frame took 4ms or 40ms.
export const dampFactor = (rate, delta) => 1 - Math.exp(-rate * Math.max(0, delta));
+const approach = (value, target, distance) => {
+ if (value < target) return Math.min(target, value + distance);
+ if (value > target) return Math.max(target, value - distance);
+ return target;
+};
+
+// Advance the rover by one frame. Keeping this pure makes the handling tunable without
+// tying the math to React or Three.js, and gives the controller one stable contract for
+// keyboard, touch, and future gamepad inputs.
+export function stepVehicle({
+ speed = 0,
+ heading = 0,
+ wheelAngle = 0,
+ throttle = 0,
+ steer = 0,
+ boost = false,
+ brake = false,
+ delta = 0.016,
+}) {
+ const dt = Math.min(0.05, Math.max(0, delta));
+ const gas = Math.max(-1, Math.min(1, throttle));
+ const steering = Math.max(-1, Math.min(1, steer));
+ const targetLimit = gas < 0
+ ? VEHICLE.reverseMaxSpeed
+ : boost ? VEHICLE.boostMaxSpeed : VEHICLE.maxSpeed;
+ const targetSpeed = brake ? 0 : gas * targetLimit;
+ const changingDirection = speed !== 0 && targetSpeed !== 0 && Math.sign(speed) !== Math.sign(targetSpeed);
+ const response = brake || changingDirection
+ ? VEHICLE.brakeDeceleration
+ : Math.abs(gas) > 0.01 ? (boost && gas > 0 ? VEHICLE.boostAcceleration : VEHICLE.acceleration) : VEHICLE.coastDeceleration;
+ const nextSpeed = approach(speed, targetSpeed, response * dt);
+ const targetWheelAngle = steering * VEHICLE.maxWheelAngle;
+ const nextWheelAngle = wheelAngle + (targetWheelAngle - wheelAngle) * dampFactor(VEHICLE.steeringResponse, dt);
+ const speedRatio = Math.min(1, Math.abs(nextSpeed) / VEHICLE.boostMaxSpeed);
+ const reverseFactor = nextSpeed < -0.05 ? -1 : 1;
+ const nextHeading = heading - nextWheelAngle * speedRatio * VEHICLE.turnRate * dt * reverseFactor;
+ const forwardX = -Math.sin(nextHeading);
+ const forwardZ = -Math.cos(nextHeading);
+
+ return {
+ speed: nextSpeed,
+ heading: nextHeading,
+ wheelAngle: nextWheelAngle,
+ speedRatio,
+ // `skid` is intentionally a visual signal, not a second physics state. It lets the
+ // rover lean into a hard turn and gives the player feedback before a full tire-trail
+ // system exists.
+ skid: Math.min(1, Math.abs(nextWheelAngle / VEHICLE.maxWheelAngle) * speedRatio),
+ displacement: {
+ x: forwardX * nextSpeed * dt,
+ z: forwardZ * nextSpeed * dt,
+ },
+ };
+}
+
// Shortest-arc angular lerp — never spins the long way around ±π.
export function dampAngle(current, target, factor) {
let diff = (target - current) % (Math.PI * 2);
diff --git a/client/src/utils/openWorldPlayerRig.test.js b/client/src/utils/openWorldPlayerRig.test.js
index 5ed2d6671a..9d2d772055 100644
--- a/client/src/utils/openWorldPlayerRig.test.js
+++ b/client/src/utils/openWorldPlayerRig.test.js
@@ -1,7 +1,8 @@
import { describe, it, expect } from 'vitest';
import {
THIRD_PERSON, clampPitch, thirdPersonCamera, resolveBoom,
- dampFactor, dampAngle, moveFacing, avatarState, bankAngle,
+ dampFactor, dampAngle, moveFacing, avatarState, bankAngle, stepVehicle,
+ moveWithCollisions, VEHICLE_COLLISION,
} from './openWorldPlayerRig';
const pos = { x: 0, y: 1.6, z: 0 };
@@ -82,6 +83,62 @@ describe('resolveBoom', () => {
});
});
+describe('moveWithCollisions', () => {
+ const box = { shape: 'box', x: 0, z: 0, halfWidth: 1, halfDepth: 1 };
+
+ it('stops at a box facade instead of using a large center radius', () => {
+ const result = moveWithCollisions({
+ position: { x: -4, z: 0 },
+ displacement: { x: 4, z: 0 },
+ colliders: [box],
+ body: { type: 'circle', radius: 0.5 },
+ });
+
+ expect(result.blocked).toBe(true);
+ expect(result.x).toBeCloseTo(-1.5, 2);
+ expect(result.z).toBe(0);
+ expect(Number.isFinite(result.x)).toBe(true);
+ });
+
+ it('slides along a wall while preserving movement on the open axis', () => {
+ const result = moveWithCollisions({
+ position: { x: -3, z: 0 },
+ displacement: { x: 3, z: 0.8 },
+ colliders: [box],
+ body: { type: 'circle', radius: 0.5 },
+ });
+
+ expect(result.blockedAxes.x).toBe(true);
+ expect(result.blockedAxes.z).toBe(false);
+ expect(result.x).toBeCloseTo(-1.5, 2);
+ expect(result.z).toBeCloseTo(0.8, 2);
+ });
+
+ it('uses the rover footprint and heading for box contact', () => {
+ const result = moveWithCollisions({
+ position: { x: -4, z: 0 },
+ displacement: { x: 4, z: 0 },
+ colliders: [box],
+ body: { type: 'vehicle', heading: 0, ...VEHICLE_COLLISION },
+ });
+
+ expect(result.blocked).toBe(true);
+ expect(result.x).toBeCloseTo(-1 - VEHICLE_COLLISION.halfWidth, 2);
+ });
+
+ it('treats round process pylons as their actual small footprint', () => {
+ const result = moveWithCollisions({
+ position: { x: -3, z: 0 },
+ displacement: { x: 3, z: 0 },
+ colliders: [{ shape: 'circle', x: 0, z: 0, radius: 0.46 }],
+ body: { type: 'circle', radius: 0.5 },
+ });
+
+ expect(result.blocked).toBe(true);
+ expect(result.x).toBeCloseTo(-0.96, 2);
+ });
+});
+
describe('dampFactor', () => {
it('is monotonic in delta and bounded to [0, 1)', () => {
const a = dampFactor(8, 0.004);
@@ -115,6 +172,30 @@ describe('dampAngle', () => {
});
});
+describe('stepVehicle', () => {
+ it('ramps speed instead of teleporting to the target velocity', () => {
+ const first = stepVehicle({ throttle: 1, delta: 0.016 });
+ expect(first.speed).toBeGreaterThan(0);
+ expect(first.speed).toBeLessThan(24);
+ expect(first.displacement.z).toBeLessThan(0);
+ });
+
+ it('coasts down and brakes faster', () => {
+ const coasting = stepVehicle({ speed: 12, delta: 0.016 });
+ const braking = stepVehicle({ speed: 12, throttle: 1, brake: true, delta: 0.016 });
+ expect(coasting.speed).toBeLessThan(12);
+ expect(braking.speed).toBeLessThan(coasting.speed);
+ });
+
+ it('steers more as speed builds and reverses the turn in reverse', () => {
+ const forward = stepVehicle({ speed: 18, heading: 0, steer: 1, delta: 0.016 });
+ const reverse = stepVehicle({ speed: -8, heading: 0, steer: 1, delta: 0.016 });
+ expect(forward.heading).toBeLessThan(0);
+ expect(reverse.heading).toBeGreaterThan(0);
+ expect(forward.wheelAngle).toBeGreaterThan(0);
+ });
+});
+
describe('moveFacing', () => {
it('faces the camera yaw when moving forward', () => {
expect(moveFacing(0.3, { forward: 1, strafe: 0 })).toBeCloseTo(0.3, 6);
diff --git a/server/services/threejsModels/prompt.test.js b/server/services/threejsModels/prompt.test.js
index 92a0d29aef..255f5c1cf0 100644
--- a/server/services/threejsModels/prompt.test.js
+++ b/server/services/threejsModels/prompt.test.js
@@ -42,6 +42,13 @@ describe('buildThreejsGenerationPrompt', () => {
expect(prompt).toContain('must not have every identity part flat along one axis');
});
+ it('teaches the intentional open-shell declaration without weakening the depth gate', () => {
+ const prompt = build();
+ expect(prompt).toContain('"side":"front" | "double"');
+ expect(prompt).toContain('needs a material with "side":"double" or it disappears from behind');
+ expect(prompt).toContain('must not be used to dodge giving a solid part a real cross-section');
+ });
+
it('carries the reference path, name, and direction into the prompt', () => {
const prompt = build({ prompt: 'Match the brass finish.' });
expect(prompt).toContain('/tmp/reference.png');