Skip to content

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

feat(world): the island can be looked at from any side

rubenluetke10-beep7e22c7538502
diff --git a/docs/agent-society/world-masterplan-v2.md b/docs/agent-society/world-masterplan-v2.md
index 01e66e2d07..0ef689fd03 100644
--- a/docs/agent-society/world-masterplan-v2.md
+++ b/docs/agent-society/world-masterplan-v2.md
@@ -52,8 +52,14 @@ north-east, where the camera looks from), sky-blue ambient from above, green bou
Emissives (glass, lamps, holograms, the beacon) get a small bloom. Evening mode later shifts the
sun to orange and turns the lamps on — the same scene, two moods.
-**Camera:** unchanged — 50° pitch, 45° yaw, orthographic, three zoom steps. This is the CoC
-camera within a few degrees; it is what makes shadows and rooflines read.
+**Camera:** 50° pitch, 45° yaw, orthographic, five zoom steps — the CoC camera within a few
+degrees, and what makes shadows and rooflines read. Those two angles are the **starting** view,
+not the only one: a right-button drag orbits the island (yaw all the way round, so any building
+can be seen from behind; pitch between 20° and 80°), Q / E step a quarter turn, and the HUD
+compass points at north and clicks back to the designed view. Nothing about the island moves
+with it — the houses keep the headings the layout designed, the sun keeps shining from the
+south-west, and only the picture turns. The view is not persisted; `?world=x,z,zoom,yaw,pitch`
+carries one when it is worth sharing.
**Surface at 1:1:** no visible pixel grain by default. A `grain` setting keeps the V1 look as an
option (0 = off, 2 = V1, 3 = coarse); the pixel pass then also becomes the cheap-GPU fallback.
diff --git a/jarvis/ui/web/frontend/src/components/society/world/Minimap.tsx b/jarvis/ui/web/frontend/src/components/society/world/Minimap.tsx
index 2d48bd7832..2df3ac70d9 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/Minimap.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/world/Minimap.tsx
@@ -9,6 +9,7 @@ import { useEffect, useMemo, useRef } from "react";
import { useT } from "@/i18n";
import { useCameraStore } from "./cameraStore";
import { ISLAND_HALF_M, PLATEAU_LEVEL, TILE_M, TileKind, buildIsland } from "./islandLayout";
+import { viewAngles } from "./viewAngles";
import { walkerPins } from "./walkerRegistry";
import { ZOOM_WIDTHS_M, visibleGroundCorners } from "./worldCamera";
import { LABEL, WATER, minimapColor, shadeHex } from "./worldPalette";
@@ -71,9 +72,11 @@ export function Minimap({ awake }: { awake: boolean }) {
ctx.fillStyle = pin.color;
ctx.fillRect(Math.round(px) - 1, Math.round(pz) - 1, 3, 3);
}
- // The viewport as a rotated rectangle.
+ // The viewport as a rotated rectangle. The map itself stays north-up —
+ // the rectangle turning inside it is what shows which way the view faces.
const { target, zoom, aspect } = useCameraStore.getState();
- const corners = visibleGroundCorners(target, ZOOM_WIDTHS_M[zoom], aspect);
+ const { yaw, pitch } = viewAngles();
+ const corners = visibleGroundCorners(target, ZOOM_WIDTHS_M[zoom], aspect, pitch, yaw);
ctx.beginPath();
corners.forEach(([x, z], i) => {
const [px, pz] = worldToMap(x, z);
diff --git a/jarvis/ui/web/frontend/src/components/society/world/SunRig.tsx b/jarvis/ui/web/frontend/src/components/society/world/SunRig.tsx
index 9c1fcc02cf..6c494275fa 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/SunRig.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/world/SunRig.tsx
@@ -9,6 +9,7 @@ import { useFrame, useThree } from "@react-three/fiber";
import { DirectionalLight, Vector3 } from "three";
import { useCameraStore } from "./cameraStore";
+import { viewAngles } from "./viewAngles";
import { ZOOM_WIDTHS_M, orthoHalfExtents } from "./worldCamera";
import { SKY } from "./worldPalette";
import { useWorldSettings } from "./worldSettings";
@@ -42,7 +43,9 @@ export function SunRig() {
const aspect = size.width / Math.max(1, size.height);
const width = ZOOM_WIDTHS_M[zoom] * COVER;
const { halfW, halfH } = orthoHalfExtents(width, aspect);
- const reach = Math.max(halfW, halfH / Math.sin((50 * Math.PI) / 180));
+ // A flatter view sees far deeper into the island, so the shadow frustum
+ // has to grow with the tilt or shadows cut off at the top of the screen.
+ const reach = Math.max(halfW, halfH / Math.sin((viewAngles().pitch * Math.PI) / 180));
l.target.position.set(target[0], 0, target[1]);
l.target.updateMatrixWorld();
l.position.set(
diff --git a/jarvis/ui/web/frontend/src/components/society/world/Terrain.tsx b/jarvis/ui/web/frontend/src/components/society/world/Terrain.tsx
index 7beb01c932..4f86a120a6 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/Terrain.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/world/Terrain.tsx
@@ -30,6 +30,7 @@ import {
import { ISLAND_HALF_M, LEVEL_Y, TILE_M, TileKind, buildIsland, type IslandMap } from "./islandLayout";
import { buildTerrainGeometry } from "./terrainGeometry";
+import { viewAngles } from "./viewAngles";
import { SKY, WATER } from "./worldPalette";
import { cameraOffset } from "./worldCamera";
@@ -352,7 +353,8 @@ export function Water({ paused }: { paused: boolean }) {
halfSize: { value: ISLAND_HALF_M },
reachM: { value: SHORE_REACH_M },
sunDir: { value: SUN_DIR },
- viewDir: { value: VIEW_DIR },
+ // Cloned: the frame loop turns this one with the orbit.
+ viewDir: { value: VIEW_DIR.clone() },
abyss: { value: new Color(WATER.abyss) },
deep: { value: new Color(WATER.deep) },
surface: { value: new Color(WATER.surface) },
@@ -395,6 +397,11 @@ export function Water({ paused }: { paused: boolean }) {
);
useFrame(({ clock }) => {
+ // The sun's glint is a mirror of the view direction, so it has to follow
+ // the orbit even when the water itself is frozen (reduced motion).
+ const { yaw, pitch } = viewAngles();
+ const [vx, vy, vz] = cameraOffset(pitch, yaw);
+ material.uniforms.viewDir.value.set(vx, vy, vz).normalize();
if (paused) return;
const t = clock.getElapsedTime();
material.uniforms.time.value = t;
diff --git a/jarvis/ui/web/frontend/src/components/society/world/WorldCameraRig.tsx b/jarvis/ui/web/frontend/src/components/society/world/WorldCameraRig.tsx
index 8a0afb2abe..fa8b18ba61 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/WorldCameraRig.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/world/WorldCameraRig.tsx
@@ -1,58 +1,76 @@
/**
* Drives the Canvas's orthographic camera from the camera store: follows the
- * target with an exponential ease, applies the zoom step to the frustum, and
+ * target with an exponential ease, applies the zoom step to the frustum,
+ * carries the orbit angles (yaw / pitch) the viewer turns the island by, and
* turns held keys into a steady pan. Inside the Canvas; the DOM controls live
* in `useWorldControls`.
+ *
+ * Everything screen-relative is derived from the SMOOTHED angles, not the
+ * store's: a keyboard pan during a turn then follows the picture the viewer
+ * actually sees rather than the angle they are easing toward.
*/
import { useEffect, useRef } from "react";
import { useFrame, useThree } from "@react-three/fiber";
import type { OrthographicCamera } from "three";
import { keyPanVector, useCameraStore } from "./cameraStore";
+import { setViewAngles } from "./viewAngles";
import {
+ CAMERA_FAR_M,
KEY_PAN_PER_S,
ZOOM_WIDTHS_M,
cameraOffset,
followAlpha,
groundBasis,
orthoHalfExtents,
+ shortestYawDelta,
} from "./worldCamera";
/** How quickly the camera settles on a new target / zoom, per second. */
const FOLLOW_RATE = 7;
-
-const OFFSET = cameraOffset();
-const BASIS = groundBasis();
+/** A stepped quarter turn should read as a swing, so the angles ease slower. */
+const TURN_RATE = 5;
export function WorldCameraRig() {
const camera = useThree((s) => s.camera) as OrthographicCamera;
const size = useThree((s) => s.size);
const invalidate = useThree((s) => s.invalidate);
const setAspect = useCameraStore((s) => s.setAspect);
- const current = useRef<{ x: number; z: number; width: number }>({
+ const current = useRef<{ x: number; z: number; width: number; yaw: number; pitch: number }>({
x: useCameraStore.getState().target[0],
z: useCameraStore.getState().target[1],
width: ZOOM_WIDTHS_M[useCameraStore.getState().zoom],
+ yaw: useCameraStore.getState().yaw,
+ pitch: useCameraStore.getState().pitch,
});
useEffect(() => {
setAspect(size.width / Math.max(1, size.height));
}, [size.width, size.height, setAspect]);
+ // A deep-linked or already-turned view must reach the minimap and the sun
+ // before the first frame, not one frame late.
+ useEffect(() => {
+ setViewAngles(current.current.yaw, current.current.pitch);
+ }, []);
+
// A store change must wake a demand-driven loop (reduced motion).
useEffect(() => useCameraStore.subscribe(() => invalidate()), [invalidate]);
useFrame((_, dt) => {
const state = useCameraStore.getState();
const step = Math.min(dt, 0.1);
+ const cur = current.current;
- // Keyboard pan: constant speed as a fraction of the visible width.
+ // Keyboard pan: constant speed as a fraction of the visible width, along
+ // the ground axes of the picture on screen right now.
const [kr, ku] = keyPanVector(state.heldKeys);
if (kr !== 0 || ku !== 0) {
- const speed = current.current.width * KEY_PAN_PER_S * step;
+ const basis = groundBasis(cur.yaw);
+ const speed = cur.width * KEY_PAN_PER_S * step;
const len = Math.hypot(kr, ku);
- const dx = ((kr * BASIS.right[0] + ku * BASIS.forward[0]) / len) * speed;
- const dz = ((kr * BASIS.right[1] + ku * BASIS.forward[1]) / len) * speed;
+ const dx = ((kr * basis.right[0] + ku * basis.forward[0]) / len) * speed;
+ const dz = ((kr * basis.right[1] + ku * basis.forward[1]) / len) * speed;
state.panBy(dx, dz);
invalidate();
}
@@ -60,7 +78,6 @@ export function WorldCameraRig() {
const [tx, tz] = useCameraStore.getState().target;
const targetWidth = ZOOM_WIDTHS_M[state.zoom];
const a = followAlpha(step, FOLLOW_RATE);
- const cur = current.current;
// While dragging the world must stick to the pointer: no easing.
if (state.dragging) {
cur.x = tx;
@@ -72,20 +89,44 @@ export function WorldCameraRig() {
cur.width += (targetWidth - cur.width) * a;
if (Math.abs(targetWidth - cur.width) < 0.01) cur.width = targetWidth;
+ // The orbit: while the pointer turns the island it must stick to it, so
+ // only a stepped turn (keyboard, compass) is eased. Yaw takes the short
+ // way round, or a turn past north would swing all the way back.
+ const turn = followAlpha(step, TURN_RATE);
+ const dYaw = shortestYawDelta(cur.yaw, state.yaw);
+ if (state.orbiting) {
+ cur.yaw = state.yaw;
+ cur.pitch = state.pitch;
+ } else {
+ cur.yaw += dYaw * turn;
+ cur.pitch += (state.pitch - cur.pitch) * turn;
+ if (Math.abs(shortestYawDelta(cur.yaw, state.yaw)) < 0.01) cur.yaw = state.yaw;
+ if (Math.abs(state.pitch - cur.pitch) < 0.01) cur.pitch = state.pitch;
+ }
+
+ setViewAngles(cur.yaw, cur.pitch);
+
const aspect = size.width / Math.max(1, size.height);
const { halfW, halfH } = orthoHalfExtents(cur.width, aspect);
+ const offset = cameraOffset(cur.pitch, cur.yaw);
camera.left = -halfW;
camera.right = halfW;
camera.top = halfH;
camera.bottom = -halfH;
camera.near = 1;
- camera.far = 1200;
- camera.position.set(cur.x + OFFSET[0], OFFSET[1], cur.z + OFFSET[2]);
+ camera.far = CAMERA_FAR_M;
+ camera.position.set(cur.x + offset[0], offset[1], cur.z + offset[2]);
camera.lookAt(cur.x, 0, cur.z);
camera.updateProjectionMatrix();
- // Keep the loop alive until the ease has settled.
- if (Math.abs(tx - cur.x) > 0.005 || Math.abs(tz - cur.z) > 0.005 || cur.width !== targetWidth) {
+ // Keep the loop alive until every ease has settled.
+ if (
+ Math.abs(tx - cur.x) > 0.005 ||
+ Math.abs(tz - cur.z) > 0.005 ||
+ cur.width !== targetWidth ||
+ cur.yaw !== state.yaw ||
+ cur.pitch !== state.pitch
+ ) {
invalidate();
}
}, 0);
diff --git a/jarvis/ui/web/frontend/src/components/society/world/WorldCompass.tsx b/jarvis/ui/web/frontend/src/components/society/world/WorldCompass.tsx
new file mode 100644
index 0000000000..231b277a37
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/world/WorldCompass.tsx
@@ -0,0 +1,95 @@
+/**
+ * The compass beside the zoom: which way the island is being looked at, and
+ * the three ways to change it without a mouse drag — a quarter turn each way
+ * and a click on the dial for the designed bird's-eye view.
+ *
+ * The needle is written straight into the DOM from a store subscription: a
+ * pointer turn changes the yaw on every move event, and that must never
+ * become a React render (`useWorldControls` keeps the whole move path out of
+ * React for the same reason). While the pointer turns the island the needle
+ * tracks it exactly; a stepped quarter turn glides, matching the camera rig's
+ * own ease instead of snapping ahead of the picture.
+ */
+import { useEffect, useRef } from "react";
+import { RotateCcw, RotateCw } from "lucide-react";
+
+import { useT } from "@/i18n";
+import { useCameraStore } from "./cameraStore";
+import { isDesignedView, northScreenAngle, shortestYawDelta } from "./worldCamera";
+
+export function WorldCompass() {
+ const t = useT();
+ const dial = useRef<SVGGElement>(null);
+ const root = useRef<HTMLDivElement>(null);
+ const turnYaw = useCameraStore((s) => s.turnYaw);
+ const resetView = useCameraStore((s) => s.resetView);
+
+ useEffect(() => {
+ // The angle actually written out: kept unwrapped, so a turn from 350° to
+ // 10° eases 20° forward instead of 340° back — the same short way the
+ // camera rig takes.
+ let shown = northScreenAngle(useCameraStore.getState().yaw);
+ const paint = (yaw: number, pitch: number, orbiting: boolean) => {
+ shown += shortestYawDelta(shown, northScreenAngle(yaw));
+ if (dial.current) {
+ // Glide with the rig's ease, except while a drag is turning the island:
+ // there the needle must sit exactly under the pointer, not 160 ms behind.
+ dial.current.style.transition = orbiting ? "none" : "transform 160ms ease-out";
+ dial.current.style.transform = `rotate(${shown.toFixed(1)}deg)`;
+ }
+ if (root.current) {
+ // An empty string would still set the attribute, and the highlight
+ // would never go away — the marker has to be deleted instead.
+ if (isDesignedView(yaw, pitch)) delete root.current.dataset.turned;
+ else root.current.dataset.turned = "yes";
+ }
+ };
+ const s = useCameraStore.getState();
+ paint(s.yaw, s.pitch, s.orbiting);
+ return useCameraStore.subscribe((next) => paint(next.yaw, next.pitch, next.orbiting));
+ }, []);
+
+ return (
+ <div ref={root} className="sw-compass" role="group" aria-label={t("society.world.compass_label")}>
+ <button
+ type="button"
+ className="sw-zoom-btn"
+ onClick={() => turnYaw(-1)}
+ aria-label={t("society.world.turn_left")}
+ title={t("society.world.turn_left")}
+ >
+ <RotateCcw size={14} />
+ </button>
+ <button
+ type="button"
+ className="sw-compass-dial"
+ onClick={resetView}
+ aria-label={t("society.world.view_reset")}
+ title={t("society.world.view_reset")}
+ >
+ {/*
+ The viewBox starts at 0,0 on purpose: with a negative origin Chromium
+ turns `transform-box: view-box` about the box's corner rather than the
+ user-space centre, and the needle orbits the rim instead of spinning.
+ */}
+ <svg viewBox="0 0 32 32" width="26" height="26" aria-hidden focusable="false">
+ <circle cx="16" cy="16" r="14" className="sw-compass-face" />
+ <g ref={dial}>
+ {/* north half, then the south half in ink */}
+ <polygon points="16,5 20,17 12,17" className="sw-compass-north" />
+ <polygon points="16,27 20,17 12,17" className="sw-compass-south" />
+ </g>
+ </svg>
+ </button>
+ <button
+ type="button"
+ className="sw-zoom-btn"
+ onClick={() => turnYaw(1)}
+ aria-label={t("society.world.turn_right")}
+ title={t("society.world.turn_right")}
+ >
+ <RotateCw size={14} />
+ </button>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/world/WorldHud.tsx b/jarvis/ui/web/frontend/src/components/society/world/WorldHud.tsx
index f5205caf6a..c7f01e4ec1 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/WorldHud.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/world/WorldHud.tsx
@@ -12,6 +12,7 @@ import type { SocietyAgent } from "../data";
import { useBuildingPoses, useTurnedCount } from "./buildingPoses";
import { useCameraStore } from "./cameraStore";
import { Minimap } from "./Minimap";
+import { WorldCompass } from "./WorldCompass";
import { ZOOM_WIDTHS_M } from "./worldCamera";
interface Props {
@@ -116,6 +117,7 @@ export function WorldHud({
<Minus size={14} />
</button>
</div>
+ <WorldCompass />
<Minimap awake={awake} />
</div>
</div>
diff --git a/jarvis/ui/web/frontend/src/components/society/world/WorldStage.tsx b/jarvis/ui/web/frontend/src/components/society/world/WorldStage.tsx
index 471cca3eb5..c75a2d3c17 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/WorldStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/world/WorldStage.tsx
@@ -60,7 +60,7 @@ function asHub(place: PlaceId): KitPlace | null {
// Not "is it in the house ring" — the foundry crowns the mountain instead.
return isKitPlace(place) ? place : null;
}
-import { cameraOffset } from "./worldCamera";
+import { CAMERA_FAR_M, cameraOffset } from "./worldCamera";
import { SKY } from "./worldPalette";
import { useWorldSettings } from "./worldSettings";
@@ -168,7 +168,7 @@ export function WorldStage({ topRight, onOpenLedger, onSelectAgent, onSelectPlac
<Canvas
key={generation}
orthographic
- camera={{ position: CAMERA_START, near: 1, far: 1200, zoom: 1 }}
+ camera={{ position: CAMERA_START, near: 1, far: CAMERA_FAR_M, zoom: 1 }}
dpr={1}
flat
shadows={shadows ? "soft" : false}
diff --git a/jarvis/ui/web/frontend/src/components/society/world/cameraStore.ts b/jarvis/ui/web/frontend/src/components/society/world/cameraStore.ts
index 572112d9fe..a318dd6461 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/cameraStore.ts
+++ b/jarvis/ui/web/frontend/src/components/society/world/cameraStore.ts
@@ -1,19 +1,37 @@
/**
- * Where the viewer is looking: the camera target on the ground and the zoom
- * step. One store per page — the stage, the minimap and the HUD all read it,
- * the controls write it. Pixels are the client's business (MASTERPLAN §2.7),
- * so nothing here is ever persisted or synced.
+ * Where the viewer is looking: the camera target on the ground, the zoom step
+ * and the two orbit angles. One store per page — the stage, the minimap, the
+ * sun and the HUD all read it, the controls write it. Pixels are the client's
+ * business (MASTERPLAN §2.7), so nothing here is ever persisted or synced;
+ * a view worth keeping travels as a `?world=` link instead.
*/
import { create } from "zustand";
-import { DEFAULT_ZOOM, MAX_ZOOM, clampTarget, stepZoom, type ZoomLevel } from "./worldCamera";
+import {
+ CAMERA_PITCH_DEG,
+ CAMERA_YAW_DEG,
+ DEFAULT_ZOOM,
+ MAX_ZOOM,
+ clampPitch,
+ clampTarget,
+ normalizeYaw,
+ stepYaw,
+ stepZoom,
+ type ZoomLevel,
+} from "./worldCamera";
export interface CameraState {
/** Ground point the camera looks at, world metres. */
target: [number, number];
zoom: ZoomLevel;
+ /** Compass direction the camera stands in, degrees in [0, 360). */
+ yaw: number;
+ /** Angle below the horizon, degrees between MIN_PITCH_DEG and MAX_PITCH_DEG. */
+ pitch: number;
/** True while the pointer drags the world — figures ignore clicks then. */
dragging: boolean;
+ /** True while the pointer orbits the view — the angles then track it with no ease. */
+ orbiting: boolean;
/** Keys currently held for keyboard panning (`ArrowUp`, `KeyW`, …). */
heldKeys: Set<string>;
/** Bumped when the viewport size or aspect changes — the minimap re-reads. */
@@ -23,7 +41,14 @@ export interface CameraState {
/** Look at a spot at a chosen zoom — the world's "show me this". */
focusOn: (x: number, z: number, zoom: ZoomLevel) => void;
zoomStep: (direction: 1 | -1) => void;
+ /** Turn the view by a pointer drag: yaw wraps, pitch is clamped. */
+ orbitBy: (dYaw: number, dPitch: number) => void;
+ /** One quarter turn left (−1) or right (+1) — the keyboard and the compass. */
+ turnYaw: (direction: 1 | -1) => void;
+ /** Back to the designed bird's-eye view; the target and the zoom stay put. */
+ resetView: () => void;
setDragging: (dragging: boolean) => void;
+ setOrbiting: (orbiting: boolean) => void;
setAspect: (aspect: number) => void;
keyDown: (code: string) => void;
keyUp: (code: string) => void;
@@ -31,11 +56,14 @@ export interface CameraState {
}
/**
- * `?world=x,z[,zoom]` deep-links a spot on the island (metres from the centre,
- * zoom step 0–4) — for "show me the harbor" from voice or a shared link, and
- * for screenshots. Anything malformed falls back to the square.
+ * `?world=x,z[,zoom[,yaw[,pitch]]]` deep-links a view of the island (metres
+ * from the centre, zoom step 0–4, then the two orbit angles in degrees) — for
+ * "show me the harbor" from voice or a shared link, and for screenshots that
+ * need a building's back. Anything malformed falls back to the designed view.
*/
-export function focusFromSearch(search: string): { target: [number, number]; zoom: ZoomLevel } | null {
+export function focusFromSearch(
+ search: string,
+): { target: [number, number]; zoom: ZoomLevel; yaw: number; pitch: number } | null {
const raw = new URLSearchParams(search).get("world");
if (!raw) return null;
const parts = raw.split(",").map((v) => Number(v));
@@ -45,7 +73,9 @@ export function focusFromSearch(search: string): { target: [number, number]; zoo
parts.length > 2 && Number.isInteger(parts[2]) && parts[2] >= 0 && parts[2] <= MAX_ZOOM
? (parts[2] as ZoomLevel)
: DEFAULT_ZOOM;
- return { target, zoom: z };
+ const yaw = parts.length > 3 ? normalizeYaw(parts[3]) : CAMERA_YAW_DEG;
+ const pitch = parts.length > 4 ? clampPitch(parts[4]) : CAMERA_PITCH_DEG;
+ return { target, zoom: z, yaw, pitch };
}
const initialFocus =
@@ -54,7 +84,10 @@ const initialFocus =
export const useCameraStore = create<CameraState>((set, get) => ({
target: initialFocus?.target ?? [0, 0],
zoom: initialFocus?.zoom ?? DEFAULT_ZOOM,
+ yaw: initialFocus?.yaw ?? CAMERA_YAW_DEG,
+ pitch: initialFocus?.pitch ?? CAMERA_PITCH_DEG,
dragging: false,
+ orbiting: false,
heldKeys: new Set<string>(),
aspect: 16 / 9,
panBy: (dx, dz) => {
@@ -64,7 +97,12 @@ export const useCameraStore = create<CameraState>((set, get) => ({
jumpTo: (x, z) => set({ target: clampTarget(x, z) }),
focusOn: (x, z, zoom) => set({ target: clampTarget(x, z), zoom }),
zoomStep: (direction) => set((s) => ({ zoom: stepZoom(s.zoom, direction) })),
+ orbitBy: (dYaw, dPitch) =>
+ set((s) => ({ yaw: normalizeYaw(s.yaw + dYaw), pitch: clampPitch(s.pitch + dPitch) })),
+ turnYaw: (direction) => set((s) => ({ yaw: stepYaw(s.yaw, direction) })),
+ resetView: () => set({ yaw: CAMERA_YAW_DEG, pitch: CAMERA_PITCH_DEG }),
setDragging: (dragging) => set({ dragging }),
+ setOrbiting: (orbiting) => set({ orbiting }),
setAspect: (aspect) => set({ aspect }),
keyDown: (code) => {
const keys = get().heldKeys;
diff --git a/jarvis/ui/web/frontend/src/components/society/world/useWorldControls.ts b/jarvis/ui/web/frontend/src/components/society/world/useWorldControls.ts
index b6fb0da9c3..a6be49af83 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/useWorldControls.ts
+++ b/jarvis/ui/web/frontend/src/components/society/world/useWorldControls.ts
@@ -1,13 +1,20 @@
/**
- * Pointer and keyboard navigation over the island: drag to pan, wheel to step
- * the zoom, arrow keys / WASD to glide. Plain DOM listeners on the stage
- * host — never through React state on the move path, and never through R3F's
- * pointer events (those belong to the figures).
+ * Pointer and keyboard navigation over the island: drag to pan, drag with the
+ * RIGHT (or middle) button to orbit, wheel to step the zoom, arrow keys / WASD
+ * to glide, Q / E for a quarter turn and R for the designed view. Plain DOM
+ * listeners on the stage host — never through React state on the move path,
+ * and never through R3F's pointer events (those belong to the figures).
+ *
+ * Why the right button for the turn: the left one is spoken for three times
+ * over (pan, pick a figure, drag a building's rotate handle), so a turn on it
+ * would need a modifier no one discovers. The right button is free — the stage
+ * has no context menu of its own — and it is what every city builder uses.
*/
import { useEffect, type RefObject } from "react";
import { useCameraStore } from "./cameraStore";
-import { ZOOM_WIDTHS_M, dragToPan } from "./worldCamera";
+import { viewAngles } from "./viewAngles";
+import { ZOOM_WIDTHS_M, dragToOrbit, dragToPan } from "./worldCamera";
/** Pointer travel below this is a click, not a drag. */
const DRAG_THRESHOLD_PX = 4;
@@ -23,6 +30,8 @@ export function useWorldControls(hostRef: RefObject<HTMLElement | null>, enabled
const store = useCameraStore;
let pointerId: number | null = null;
+ /** What the held button does: pan the ground, or orbit around it. */
+ let mode: "pan" | "orbit" = "pan";
let lastX = 0;
let lastY = 0;
let travelled = 0;
@@ -46,7 +55,12 @@ export function useWorldControls(hostRef: RefObject<HTMLElement | null>, enabled
const allowSelectStart = () => document.removeEventListener("selectstart", blockSelectStart);
const onPointerDown = (e: PointerEvent) => {
- if (e.button !== 0) return;
+ // 0 = left (pan), 2 = right and 1 = middle (orbit). Anything else is
+ // someone's fourth mouse button and belongs to the browser.
+ if (e.button !== 0 && e.button !== 1 && e.button !== 2) return;
+ mode = e.button === 0 ? "pan" : "orbit";
+ // The middle button would otherwise start Chromium's autoscroll.
+ if (e.button === 1) e.preventDefault();
pointerId = e.pointerId;
lastX = e.clientX;
lastY = e.clientY;
@@ -64,15 +78,28 @@ export function useWorldControls(hostRef: RefObject<HTMLElement | null>, enabled
travelled += Math.abs(dx) + Math.abs(dy);
if (travelled < DRAG_THRESHOLD_PX) return;
if (!store.getState().dragging) {
+ // `dragging` stands every click guard down, whichever button it is:
+ // a turn must not select a figure either.
store.getState().setDragging(true);
+ if (mode === "orbit") {
+ store.getState().setOrbiting(true);
+ host.dataset.orbiting = "yes"; // the stage swaps its grab cursor
+ }
try {
host.setPointerCapture(e.pointerId);
} catch {
/* a synthetic pointer without capture support still pans */
}
}
+ if (mode === "orbit") {
+ const [dYaw, dPitch] = dragToOrbit(dx, dy, host.clientWidth || 1, host.clientHeight || 1);
+ store.getState().orbitBy(dYaw, dPitch);
+ return;
+ }
+ // Pan along the ground axes of the picture on screen, not the designed ones.
const width = ZOOM_WIDTHS_M[store.getState().zoom];
- const [px, pz] = dragToPan(dx, dy, width, host.clientWidth || 1);
+ const { yaw, pitch } = viewAngles();
+ const [px, pz] = dragToPan(dx, dy, width, host.clientWidth || 1, pitch, yaw);
store.getState().panBy(px, pz);
};
@@ -80,6 +107,8 @@ export function useWorldControls(hostRef: RefObject<HTMLElement | null>, enabled
if (pointerId !== e.pointerId) return;
pointerId = null;
allowSelectStart();
+ delete host.dataset.orbiting;
+ if (store.getState().orbiting) store.getState().setOrbiting(false);
if (store.getState().dragging) {
// Let the click that ends a drag pass first, then re-enable figure clicks.
window.setTimeout(() => store.getState().setDragging(false), 0);
@@ -102,8 +131,17 @@ export function useWorldControls(hostRef: RefObject<HTMLElement | null>, enabled
store.getState().zoomStep(-1);
} else if (e.code === "Minus" || e.code === "NumpadSubtract") {
store.getState().zoomStep(1);
+ } else if (e.code === "KeyQ") {
+ store.getState().turnYaw(-1);
+ } else if (e.code === "KeyE") {
+ store.getState().turnYaw(1);
+ } else if (e.code === "KeyR") {
+ store.getState().resetView();
}
};
+
+ // The stage has no context menu of its own, and the right button turns it.
+ const onContextMenu = (e: MouseEvent) => e.preventDefault();
const onKeyUp = (e: KeyboardEvent) => {
if (PAN_KEYS.has(e.code)) store.getState().keyUp(e.code);
};
@@ -117,6 +155,7 @@ export function useWorldControls(hostRef: RefObject<HTMLElement | null>, enabled
host.addEventListener("keydown", onKeyDown);
host.addEventListener("keyup", onKeyUp);
host.addEventListener("blur", onBlur);
+ host.addEventListener("contextmenu", onContextMenu);
return () => {
host.removeEventListener("pointerdown", onPointerDown);
host.removeEventListener("pointermove", onPointerMove);
@@ -126,9 +165,12 @@ export function useWorldControls(hostRef: RefObject<HTMLElement | null>, enabled
host.removeEventListener("keydown", onKeyDown);
host.removeEventListener("keyup", onKeyUp);
host.removeEventListener("blur", onBlur);
+ host.removeEventListener("contextmenu", onContextMenu);
allowSelectStart();
+ delete host.dataset.orbiting;
store.getState().clearKeys();
store.getState().setDragging(false);
+ store.getState().setOrbiting(false);
};
}, [hostRef, enabled]);
}
diff --git a/jarvis/ui/web/frontend/src/components/society/world/viewAngles.ts b/jarvis/ui/web/frontend/src/components/society/world/viewAngles.ts
new file mode 100644
index 0000000000..6649abf38c
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/world/viewAngles.ts
@@ -0,0 +1,31 @@
+/**
+ * The angles the island is being DRAWN at this frame — the camera rig's eased
+ * yaw and pitch, one step behind the store while a turn swings into place.
+ *
+ * Anything that has to line up with the picture on screen reads these, not the
+ * store: the minimap's viewport rectangle, the sun's shadow frustum and the
+ * water's glint. Going through the store instead would make them lead the
+ * camera during the ease, and reading them per frame through zustand would
+ * cost a subscription where a plain mutable record does.
+ */
+import { CAMERA_PITCH_DEG, CAMERA_YAW_DEG } from "./worldCamera";
+
+export interface ViewAngles {
+ /** Compass direction the camera stands in, degrees. */
+ yaw: number;
+ /** Angle below the horizon, degrees. */
+ pitch: number;
+}
+
+const live: ViewAngles = { yaw: CAMERA_YAW_DEG, pitch: CAMERA_PITCH_DEG };
+
+/** Written once per frame by `WorldCameraRig`; nothing else may write it. */
+export function setViewAngles(yaw: number, pitch: number): void {
+ live.yaw = yaw;
+ live.pitch = pitch;
+}
+
+/** The shared record — read `.yaw` / `.pitch`, never hold on to the object. */
+export function viewAngles(): Readonly<ViewAngles> {
+ return live;
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/world/world.css b/jarvis/ui/web/frontend/src/components/society/world/world.css
index b634988483..4bc8bafa61 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/world.css
+++ b/jarvis/ui/web/frontend/src/components/society/world/world.css
@@ -23,6 +23,10 @@
.sw-stage:active {
cursor: grabbing;
}
+/* A right-button drag turns the island instead of sliding it. */
+.sw-stage[data-orbiting] {
+ cursor: all-scroll;
+}
.sw-stage canvas {
display: block;
}
@@ -480,6 +484,58 @@
font-size: 12px;
color: #1f2a3a;
}
+
+/* The compass: a quarter turn each way, and the dial back to the designed view. */
+.sw-compass {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ padding: 3px;
+ background: rgba(255, 252, 245, 0.9);
+ border: 1px solid rgba(31, 42, 58, 0.2);
+ border-radius: 6px;
+ box-shadow: 0 2px 0 rgba(31, 42, 58, 0.25);
+}
+.sw-compass[data-turned] {
+ background: #fff8dc;
+ border-color: rgba(31, 42, 58, 0.45);
+}
+.sw-compass-dial {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 30px;
+ height: 30px;
+ padding: 0;
+ border: 0;
+ border-radius: 50%;
+ background: transparent;
+ cursor: pointer;
+}
+.sw-compass-dial:hover {
+ background: rgba(31, 42, 58, 0.1);
+}
+.sw-compass-dial g {
+ /* Turn about the middle of the viewBox, not about its top-left corner. */
+ transform-box: view-box;
+ transform-origin: center;
+}
+.sw-compass-face {
+ fill: rgba(31, 42, 58, 0.07);
+ stroke: rgba(31, 42, 58, 0.35);
+ stroke-width: 1.5;
+}
+.sw-compass-north {
+ fill: #b4453c;
+}
+.sw-compass-south {
+ fill: rgba(31, 42, 58, 0.55);
+}
+@media (prefers-reduced-motion: reduce) {
+ .sw-compass-dial g {
+ transition: none !important;
+ }
+}
.sw-minimap {
width: 168px;
height: 168px;
diff --git a/jarvis/ui/web/frontend/src/components/society/world/worldCamera.test.ts b/jarvis/ui/web/frontend/src/components/society/world/worldCamera.test.ts
index c6fa3150d6..e2a36d4d28 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/worldCamera.test.ts
+++ b/jarvis/ui/web/frontend/src/components/society/world/worldCamera.test.ts
@@ -3,16 +3,29 @@ import { describe, expect, it } from "vitest";
import { focusFromSearch } from "./cameraStore";
import { CAMERA_FROM, ISLAND_HALF_M, facesCamera } from "./islandLayout";
import {
+ CAMERA_DISTANCE_M,
+ CAMERA_FAR_M,
CAMERA_PITCH_DEG,
CAMERA_YAW_DEG,
DEFAULT_ZOOM,
+ MAX_PITCH_DEG,
MAX_ZOOM,
+ MIN_PITCH_DEG,
+ ORBIT_YAW_PER_WIDTH_DEG,
+ YAW_STEP_DEG,
ZOOM_WIDTHS_M,
cameraOffset,
+ clampPitch,
clampTarget,
+ dragToOrbit,
dragToPan,
groundBasis,
+ isDesignedView,
+ normalizeYaw,
+ northScreenAngle,
orthoHalfExtents,
+ shortestYawDelta,
+ stepYaw,
stepZoom,
visibleGroundCorners,
} from "./worldCamera";
@@ -100,11 +113,132 @@ describe("worldCamera", () => {
});
it("reads a ?world=x,z,zoom deep link and ignores garbage", () => {
- expect(focusFromSearch("?view=agents&world=12,-30,0")).toEqual({ target: [12, -30], zoom: 0 });
- expect(focusFromSearch("?world=5,5")).toEqual({ target: [5, 5], zoom: 1 });
- expect(focusFromSearch("?world=9999,0,7")).toEqual({ target: [ISLAND_HALF_M, 0], zoom: 1 });
+ const designed = { yaw: CAMERA_YAW_DEG, pitch: CAMERA_PITCH_DEG };
+ expect(focusFromSearch("?view=agents&world=12,-30,0")).toEqual({
+ target: [12, -30],
+ zoom: 0,
+ ...designed,
+ });
+ expect(focusFromSearch("?world=5,5")).toEqual({ target: [5, 5], zoom: 1, ...designed });
+ expect(focusFromSearch("?world=9999,0,7")).toEqual({
+ target: [ISLAND_HALF_M, 0],
+ zoom: 1,
+ ...designed,
+ });
expect(focusFromSearch("?world=0,0,4")?.zoom).toBe(4);
expect(focusFromSearch("?world=abc")).toBeNull();
expect(focusFromSearch("?view=agents")).toBeNull();
});
+
+ it("deep-links the orbit too, clamped and wrapped", () => {
+ expect(focusFromSearch("?world=0,0,2,225")?.yaw).toBe(225);
+ expect(focusFromSearch("?world=0,0,2,-45")?.yaw).toBe(315);
+ expect(focusFromSearch("?world=0,0,2,225,70")?.pitch).toBe(70);
+ // Past the limits the view is clamped, not refused.
+ expect(focusFromSearch("?world=0,0,2,0,5")?.pitch).toBe(MIN_PITCH_DEG);
+ expect(focusFromSearch("?world=0,0,2,0,120")?.pitch).toBe(MAX_PITCH_DEG);
+ expect(focusFromSearch("?world=0,0,2,abc")?.yaw).toBe(CAMERA_YAW_DEG);
+ });
+});
+
+describe("the orbit", () => {
+ it("wraps the yaw and clamps the pitch", () => {
+ expect(normalizeYaw(45)).toBe(45);
+ expect(normalizeYaw(-90)).toBe(270);
+ expect(normalizeYaw(725)).toBe(5);
+ expect(normalizeYaw(Number.NaN)).toBe(CAMERA_YAW_DEG);
+ expect(clampPitch(50)).toBe(50);
+ expect(clampPitch(0)).toBe(MIN_PITCH_DEG);
+ expect(clampPitch(90)).toBe(MAX_PITCH_DEG);
+ expect(clampPitch(Number.NaN)).toBe(CAMERA_PITCH_DEG);
+ // The designed view is inside the range, not on its edge.
+ expect(CAMERA_PITCH_DEG).toBeGreaterThan(MIN_PITCH_DEG);
+ expect(CAMERA_PITCH_DEG).toBeLessThan(MAX_PITCH_DEG);
+ });
+
+ it("stands clear of the island at every allowed tilt", () => {
+ // The whole island has to sit between the near and the far plane from any
+ // angle — at the flattest tilt the far side is nearly a full island length
+ // further along the view axis, and the target may sit at either end of it.
+ const span = 2 * ISLAND_HALF_M;
+ for (const pitch of [MIN_PITCH_DEG, CAMERA_PITCH_DEG, MAX_PITCH_DEG]) {
+ const reach = span * Math.cos((pitch * Math.PI) / 180);
+ expect(CAMERA_DISTANCE_M - reach).toBeGreaterThan(1); // nothing behind the camera
+ expect(CAMERA_DISTANCE_M + reach).toBeLessThan(CAMERA_FAR_M); // nothing past the far plane
+ }
+ });
+
+ it("turns a full revolution across the stage width, and the island follows the pointer", () => {
+ const [yawFull] = dragToOrbit(1000, 0, 1000, 600);
+ expect(yawFull).toBe(ORBIT_YAW_PER_WIDTH_DEG);
+ // Dragging right turns the island right, dragging down tips more of its
+ // roofs into view — the same grab metaphor the pan uses.
+ expect(dragToOrbit(50, 0, 1000, 600)[0]).toBeGreaterThan(0);
+ expect(dragToOrbit(0, 50, 1000, 600)[1]).toBeGreaterThan(0);
+ expect(dragToOrbit(10, 10, 0, 0)).toEqual([0, 0]);
+ });
+
+ it("steps the yaw onto the quarter-turn grid", () => {
+ expect(stepYaw(CAMERA_YAW_DEG, 1)).toBe(90);
+ expect(stepYaw(CAMERA_YAW_DEG, -1)).toBe(0);
+ // Off the grid a step lands on the next stop, not 45° further on.
+ expect(stepYaw(50, 1)).toBe(90);
+ expect(stepYaw(50, -1)).toBe(45);
+ // Four steps from the designed view come back to it.
+ let yaw = CAMERA_YAW_DEG;
+ for (let i = 0; i < 360 / YAW_STEP_DEG; i++) yaw = stepYaw(yaw, 1);
+ expect(yaw).toBe(CAMERA_YAW_DEG);
+ expect(stepYaw(0, -1)).toBe(360 - YAW_STEP_DEG);
+ });
+
+ it("eases a turn the short way round", () => {
+ expect(shortestYawDelta(350, 10)).toBe(20);
+ expect(shortestYawDelta(10, 350)).toBe(-20);
+ expect(shortestYawDelta(0, 180)).toBe(180);
+ expect(shortestYawDelta(45, 45)).toBe(0);
+ });
+
+ it("shows the same picture from a turned camera, only rotated", () => {
+ // Half a turn from the designed view: the camera stands on the other side,
+ // the ground basis flips, and a house front now shows its back.
+ const [x, , z] = cameraOffset(CAMERA_PITCH_DEG, CAMERA_YAW_DEG + 180);
+ const [x0, , z0] = cameraOffset();
+ expect(x).toBeCloseTo(-x0, 3);
+ expect(z).toBeCloseTo(-z0, 3);
+ const back = groundBasis(CAMERA_YAW_DEG + 180);
+ const front = groundBasis();
+ expect(back.forward[0]).toBeCloseTo(-front.forward[0], 5);
+ expect(back.forward[1]).toBeCloseTo(-front.forward[1], 5);
+ expect(facesCamera(Math.atan2(CAMERA_FROM[0], CAMERA_FROM[1]))).toBe(true);
+ });
+
+ it("pans and frames along the turned axes", () => {
+ const yaw = 135;
+ const { right } = groundBasis(yaw);
+ const [dx, dz] = dragToPan(200, 0, 64, 1280, CAMERA_PITCH_DEG, yaw);
+ expect(dx).toBeCloseTo(-10 * right[0], 4);
+ expect(dz).toBeCloseTo(-10 * right[1], 4);
+ // A flatter view looks further into the island, so the frame runs deeper.
+ const steep = visibleGroundCorners([0, 0], 64, 16 / 9, 70, yaw);
+ const flat = visibleGroundCorners([0, 0], 64, 16 / 9, 25, yaw);
+ const depth = (c: Array<[number, number]>) => Math.hypot(c[3][0] - c[0][0], c[3][1] - c[0][1]);
+ expect(depth(flat)).toBeGreaterThan(depth(steep));
+ });
+
+ it("points the needle where north actually is on screen", () => {
+ // North is (0, −1) on the ground; read through the basis it lands at
+ // (sin yaw, cos yaw) on screen — straight up only when the camera is due south.
+ for (const yaw of [0, 45, 135, 270]) {
+ const { right, forward } = groundBasis(yaw);
+ const screenX = -right[1];
+ const screenUp = -forward[1];
+ const rad = (northScreenAngle(yaw) * Math.PI) / 180;
+ expect(screenX).toBeCloseTo(Math.sin(rad), 5);
+ expect(screenUp).toBeCloseTo(Math.cos(rad), 5);
+ }
+ expect(isDesignedView(CAMERA_YAW_DEG, CAMERA_PITCH_DEG)).toBe(true);
+ expect(isDesignedView(CAMERA_YAW_DEG + 360, CAMERA_PITCH_DEG)).toBe(true);
+ expect(isDesignedView(CAMERA_YAW_DEG + 90, CAMERA_PITCH_DEG)).toBe(false);
+ expect(isDesignedView(CAMERA_YAW_DEG, CAMERA_PITCH_DEG + 10)).toBe(false);
+ });
});
diff --git a/jarvis/ui/web/frontend/src/components/society/world/worldCamera.ts b/jarvis/ui/web/frontend/src/components/society/world/worldCamera.ts
index c57f372352..4c6e12920f 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/worldCamera.ts
+++ b/jarvis/ui/web/frontend/src/components/society/world/worldCamera.ts
@@ -9,13 +9,51 @@
* is five fixed steps (one field, four fields, the market district, a quarter
* of the island, the whole island), never continuous: with an integer pixel
* size every step stays crisp, and the widest step is the postcard view.
+ *
+ * Decision (maintainer, 2026-09-03): those two angles are the STARTING view,
+ * not the only one. The viewer orbits the island — yaw all the way round, so
+ * every building can be looked at from behind, and pitch between a low
+ * street-level slant and a near-vertical map view. Both stay free (no snapping
+ * mid-drag); the keyboard and the HUD compass step yaw in quarter turns so
+ * getting back to the designed view is one click.
*/
import { ISLAND_HALF_M } from "./islandLayout";
export const CAMERA_PITCH_DEG = 50;
export const CAMERA_YAW_DEG = 45;
-/** Far enough that nothing on the island reaches behind the camera. */
-export const CAMERA_DISTANCE_M = 420;
+/**
+ * Far enough that nothing on the island reaches behind the camera. An
+ * orthographic camera draws the same picture from any distance, so this only
+ * has to clear the clipping planes — and the flattest allowed view is what
+ * decides it: looking along the ground from 20°, the far side of the island
+ * lies 2 · ISLAND_HALF_M · cos(20°) ≈ 481 m further along the view axis than
+ * the near side, and the target may sit at either end. `CAMERA_FAR_M` then
+ * has to hold the whole of that span on the other side.
+ */
+export const CAMERA_DISTANCE_M = 640;
+export const CAMERA_FAR_M = 1500;
+
+/**
+ * How far the view may be tilted. Flatter than `MIN` and the island hides
+ * behind its own hills while a pointer drag pans absurdly far (the pan
+ * stretches by 1 / sin(pitch)); steeper than `MAX` and the houses lose their
+ * fronts and the world reads as a flat map.
+ */
+export const MIN_PITCH_DEG = 20;
+export const MAX_PITCH_DEG = 80;
+
+/** Yaw the compass and the keyboard step in — a quarter turn per press. */
+export const YAW_STEP_DEG = 45;
+
+/**
+ * Orbit speed: dragging across the full stage width turns a whole revolution,
+ * and across its full height sweeps the tilt twice from end to end — so half
+ * a stage of travel covers the whole tilt range, and a short drag still
+ * changes it noticeably. Relative to the stage, so a small pane turns as fast
+ * as a large one.
+ */
+export const ORBIT_YAW_PER_WIDTH_DEG = 360;
+export const ORBIT_PITCH_PER_HEIGHT_DEG = 120;
/** Ground width the orthographic frustum shows per zoom step, in metres. */
export const ZOOM_WIDTHS_M = [32, 64, 128, 256, 512] as const;
@@ -102,6 +140,75 @@ export function stepZoom(level: ZoomLevel, direction: 1 | -1): ZoomLevel {
return next as ZoomLevel;
}
+/** Wrap a yaw into [0, 360) — the store never holds a wound-up angle. */
+export function normalizeYaw(deg: number): number {
+ if (!Number.isFinite(deg)) return CAMERA_YAW_DEG;
+ return round(((deg % 360) + 360) % 360);
+}
+
+/** Keep the tilt inside the range the island still reads in. */
+export function clampPitch(deg: number): number {
+ if (!Number.isFinite(deg)) return CAMERA_PITCH_DEG;
+ return round(Math.min(MAX_PITCH_DEG, Math.max(MIN_PITCH_DEG, deg)));
+}
+
+/**
+ * How much a pointer drag of (dx, dy) pixels turns the view, as
+ * [yaw, pitch] degrees. The island follows the pointer, the same grab
+ * metaphor the pan uses: drag right and the island spins right, drag down and
+ * it tips forward so more of its roofs come into view.
+ */
+export function dragToOrbit(
+ dxPx: number,
+ dyPx: number,
+ stageWidthPx: number,
+ stageHeightPx: number,
+): [number, number] {
+ const dYaw = stageWidthPx > 0 ? (dxPx / stageWidthPx) * ORBIT_YAW_PER_WIDTH_DEG : 0;
+ const dPitch = stageHeightPx > 0 ? (dyPx / stageHeightPx) * ORBIT_PITCH_PER_HEIGHT_DEG : 0;
+ return [round(dYaw), round(dPitch)];
+}
+
+/**
+ * The next quarter-turn stop from `yawDeg` in `direction`. Already on a stop
+ * (within a degree) it moves a full step; off one it lands on the next stop,
+ * so a stepped turn always ends on the grid the island was designed for.
+ */
+export function stepYaw(yawDeg: number, direction: 1 | -1): number {
+ const cur = normalizeYaw(yawDeg) / YAW_STEP_DEG;
+ // Half a degree of slack: an angle that close to a stop counts as being on
+ // it, so a press there moves on instead of snapping back to where it is.
+ const eps = 0.5 / YAW_STEP_DEG;
+ const next = direction > 0 ? Math.floor(cur + eps) + 1 : Math.ceil(cur - eps) - 1;
+ return normalizeYaw(next * YAW_STEP_DEG);
+}
+
+/**
+ * Whether the view still stands where the island was designed to be seen
+ * from. The compass marks itself while it does not, so a viewer who turned
+ * the island by accident can see why the fronts are facing away.
+ */
+export function isDesignedView(yawDeg: number, pitchDeg: number): boolean {
+ return Math.abs(shortestYawDelta(yawDeg, CAMERA_YAW_DEG)) < 0.5 && Math.abs(pitchDeg - CAMERA_PITCH_DEG) < 0.5;
+}
+
+/**
+ * Where north points on screen, as an SVG rotation in degrees: the ground
+ * vector (0, −1) read through `groundBasis` lands at (sin yaw, cos yaw) on
+ * screen, which is a clockwise rotation by the yaw itself.
+ */
+export function northScreenAngle(yawDeg: number): number {
+ return normalizeYaw(yawDeg);
+}
+
+/** Signed shortest way from `fromDeg` to `toDeg`, in (−180, 180]. */
+export function shortestYawDelta(fromDeg: number, toDeg: number): number {
+ let d = (toDeg - fromDeg) % 360;
+ if (d > 180) d -= 360;
+ if (d <= -180) d += 360;
+ return round(d);
+}
+
/**
* The four ground corners the viewport covers around `target`, in screen
* order (top-left, top-right, bottom-right, bottom-left). Used by the minimap