Fixed world clock: no player time controls (ISS-117)
CI / build + unit + e2e (pull_request) Failing after 12m10s
CI / build + unit + e2e (pull_request) Failing after 12m10s
The world always runs at WORLD_TIME_SCALE = 24 (lib/worldClock.ts). A server
background tick (instrumentation.ts -> startBackgroundTick, 1 s interval)
advances the sim with no open browser; idle-pause freezes the clock exactly
while no plane is flying or in repair. Fresh worlds start year 2000
(STARTING_CLOCK_MS in seed.ts).
- Removed: POST /api/sim + OpenAPI entry, applyTimeControls/clampTimeScale,
lib/timeScale.ts, LeftPane pause button + scale slider machinery,
ISS-057 slow-on-landing/resume in flyPlane.
- Snapshot simState is now { clockMs } only; client extrapolates at the fixed
rate between polls and freezes while idle (useSimClock).
- New test-only hook POST /api/test/set-timescale behind FLIGHT_TEST_HOOKS=1
(sibling of set-health); all e2e setScale helpers call it, afterEach restores
the world rate. E2E pause tests replaced by idle-pause assertions; sim.spec.ts
activates the world via set-health + /repair for advance/expiry tests.
This commit is contained in:
@@ -3,6 +3,8 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import initSqlJs from 'sql.js';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { WORLD_TIME_SCALE } from '@/lib/worldClock';
|
||||
import { STARTING_CLOCK_MS } from '@/lib/game/seed';
|
||||
import { openGameDb, persist } from './client';
|
||||
import * as schema from './schema';
|
||||
|
||||
@@ -111,8 +113,9 @@ describe('openGameDb', () => {
|
||||
const account = (await inst.db.select().from(schema.account))[0];
|
||||
expect(account?.cash).toBeGreaterThan(0);
|
||||
const sim = (await inst.db.select().from(schema.simState))[0];
|
||||
expect(sim?.paused).toBe(false);
|
||||
expect(sim?.timeScale).toBe(1);
|
||||
// ISS-117: fresh worlds start at the year-2000 game clock with the fixed world rate.
|
||||
expect(sim?.clockMs).toBe(STARTING_CLOCK_MS);
|
||||
expect(sim?.timeScale).toBe(WORLD_TIME_SCALE);
|
||||
|
||||
// The seed was durably written: the file exists and is non-empty.
|
||||
const st = await fs.stat(file);
|
||||
|
||||
@@ -47,7 +47,7 @@ const basePackage = (id: string): PackageState => ({
|
||||
|
||||
const snapshot = (over: Partial<StateSnapshot> = {}): StateSnapshot => ({
|
||||
account: { cash: 20_000, reputation: 10 },
|
||||
simState: { clockMs: 0, timeScale: 1, paused: false },
|
||||
simState: { clockMs: 0 },
|
||||
planes: [basePlane('plane-starter')],
|
||||
packages: [],
|
||||
catalog: CATALOG,
|
||||
@@ -59,7 +59,7 @@ const snapshot = (over: Partial<StateSnapshot> = {}): StateSnapshot => ({
|
||||
describe('diffSnapshots', () => {
|
||||
it('returns [] for identical snapshots (only clock/cash drift)', () => {
|
||||
const prev = snapshot();
|
||||
const next = snapshot({ account: { cash: 21_000, reputation: 11 }, simState: { clockMs: 60_000, timeScale: 1, paused: false } });
|
||||
const next = snapshot({ account: { cash: 21_000, reputation: 11 }, simState: { clockMs: 60_000 } });
|
||||
expect(diffSnapshots(prev, next)).toEqual([]);
|
||||
});
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
repRate,
|
||||
SELL_FRACTION,
|
||||
} from './catalog';
|
||||
import { HUB_ICAO } from './seed';
|
||||
import { HUB_ICAO, STARTING_CLOCK_MS } from './seed';
|
||||
import {
|
||||
abandonPackage,
|
||||
buyPlane,
|
||||
@@ -173,7 +173,7 @@ describe('flyPlane', () => {
|
||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||
expect(plane.status).toBe('flying');
|
||||
expect(plane.destIcao).toBe('LEMD');
|
||||
expect(plane.departureSimTime).toBe(T0); // seeded clock, no tick in direct calls
|
||||
expect(plane.departureSimTime).toBe(STARTING_CLOCK_MS); // seeded game clock (ISS-117), no tick in direct calls
|
||||
const fc = await loadAirportsGeoJson();
|
||||
const origin = fc.features.find((f) => f.properties.icao === HUB_ICAO)!.properties;
|
||||
expect(plane.lat).toBe(origin.lat);
|
||||
@@ -182,34 +182,6 @@ describe('flyPlane', () => {
|
||||
expect(plane.fuel).toBe(PLANE_TYPES.atr72.maxFuel);
|
||||
});
|
||||
|
||||
it('resumes a manual pause and restores lastSelectedTimeScale when the last grounded plane takes off (ISS-057)', async () => {
|
||||
const inst = await freshDb('fly-resume.db');
|
||||
// A landing slowed the sim to 1×; the player's last manually selected speed was 250.
|
||||
await inst.db.update(schema.simState).set({ paused: true, timeScale: 1, lastSelectedTimeScale: 250 });
|
||||
|
||||
await flyPlane(inst, 'plane-starter', 'LEMD'); // sole grounded plane → airborne
|
||||
|
||||
const sim = (await inst.db.select().from(schema.simState))[0];
|
||||
expect(sim.paused).toBe(false); // dispatch still resumes a manual pause…
|
||||
expect(sim.timeScale).toBe(250); // …and restores the last selected speed
|
||||
});
|
||||
|
||||
it('keeps 1× when another plane is still grounded after dispatch (ISS-057)', async () => {
|
||||
const inst = await freshDb('fly-stayslow.db');
|
||||
await inst.db.update(schema.simState).set({ timeScale: 1, lastSelectedTimeScale: 250 });
|
||||
// A second grounded plane — the starter taking off leaves it on the ground.
|
||||
await inst.db.insert(schema.planes).values({
|
||||
id: 'plane-extra', model: 'atr72', status: 'available', fuel: 100, maxFuel: PLANE_TYPES.atr72.maxFuel,
|
||||
locationIcao: HUB_ICAO, destIcao: null, lat: 50, lon: 8, departureSimTime: null,
|
||||
});
|
||||
|
||||
await flyPlane(inst, 'plane-starter', 'LEMD');
|
||||
|
||||
const sim = (await inst.db.select().from(schema.simState))[0];
|
||||
expect(sim.paused).toBe(false);
|
||||
expect(sim.timeScale).toBe(1); // another plane on ground → stays slowed
|
||||
});
|
||||
|
||||
it('rejects a flying plane with 409', async () => {
|
||||
const inst = await freshDb('fly-flying.db');
|
||||
await inst.db.update(schema.planes)
|
||||
@@ -462,14 +434,14 @@ describe('cancelQueuedLeg (v0.25.0, ISS-043)', () => {
|
||||
});
|
||||
|
||||
describe('abandonPackage', () => {
|
||||
// A loaded package created at T0 with a 10h window; the seeded sim clock is T0.
|
||||
// A loaded package created at the seeded game clock with a 10h window (ISS-117).
|
||||
const REWARD = 1_000;
|
||||
const WINDOW_MS = 10 * 3_600_000;
|
||||
|
||||
async function setupLoaded(name: string, status: 'loaded' | 'expired' = 'loaded') {
|
||||
const inst = await freshDb(name);
|
||||
// Always insert OPEN and load it through the real action…
|
||||
await insertOpenPackage(inst, 'p-ab', { reward: REWARD, createdSimTime: T0, deadlineSimTime: T0 + WINDOW_MS });
|
||||
await insertOpenPackage(inst, 'p-ab', { reward: REWARD, createdSimTime: STARTING_CLOCK_MS, deadlineSimTime: STARTING_CLOCK_MS + WINDOW_MS });
|
||||
await loadPackage(inst, 'p-ab', 'plane-starter');
|
||||
// …then flip to expired in place (what the tick would do once the deadline passes).
|
||||
if (status === 'expired') {
|
||||
@@ -494,7 +466,7 @@ describe('abandonPackage', () => {
|
||||
|
||||
it('scales to exactly 37.5% at the midpoint of the window', async () => {
|
||||
const inst = await setupLoaded('ab-mid.db');
|
||||
await inst.db.update(schema.simState).set({ clockMs: T0 + WINDOW_MS / 2 }); // runAction ticks first in prod
|
||||
await inst.db.update(schema.simState).set({ clockMs: STARTING_CLOCK_MS + WINDOW_MS / 2 }); // runAction ticks first in prod
|
||||
|
||||
const { penalty } = await abandonPackage(inst, 'p-ab');
|
||||
|
||||
@@ -503,8 +475,8 @@ describe('abandonPackage', () => {
|
||||
|
||||
it('caps at exactly 60% at and past the deadline', async () => {
|
||||
for (const [name, clock] of [
|
||||
['ab-deadline.db', T0 + WINDOW_MS],
|
||||
['ab-pastdeadline.db', T0 + WINDOW_MS * 2], // clamped — a not-yet-ticked loaded package past its deadline
|
||||
['ab-deadline.db', STARTING_CLOCK_MS + WINDOW_MS],
|
||||
['ab-pastdeadline.db', STARTING_CLOCK_MS + WINDOW_MS * 2], // clamped — a not-yet-ticked loaded package past its deadline
|
||||
] as const) {
|
||||
const inst = await setupLoaded(name);
|
||||
await inst.db.update(schema.simState).set({ clockMs: clock });
|
||||
@@ -735,7 +707,7 @@ describe('repairPlane (v0.39.0, ISS-069; gradual since v0.45.0, ISS-089)', () =>
|
||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||
expect(plane.status).toBe('repairing');
|
||||
expect(plane.health).toBe(42); // NOT restored yet — the engine's finishRepairs pass heals it gradually…
|
||||
expect(plane.repairUntilSimTime).toBe(T0 + REPAIR_DURATION_MS); // …with the gate set from the seeded clock (no tick in direct calls)
|
||||
expect(plane.repairUntilSimTime).toBe(STARTING_CLOCK_MS + REPAIR_DURATION_MS); // …with the gate set from the seeded game clock (ISS-117; no tick in direct calls)
|
||||
const account = (await inst.db.select().from(schema.account))[0];
|
||||
expect(account.cash).toBeCloseTo(cashBefore - REPAIR_COST, 6);
|
||||
});
|
||||
|
||||
@@ -173,14 +173,6 @@ export async function flyPlane(inst: GameDb, planeId: string, destIcao: string):
|
||||
if (cost > 0) {
|
||||
await inst.db.update(schema.account).set({ cash: Math.round((account.cash - cost) * 100) / 100 });
|
||||
}
|
||||
// ISS-057: dispatch still resumes a MANUALLY paused sim (pause is manual-only now — landings
|
||||
// slow to 1× instead of pausing), and restores the last manually selected speed when this
|
||||
// dispatch took the LAST grounded plane airborne. Runs inside runAction(), so tick + controls
|
||||
// + dispatch are atomic under the sim lock.
|
||||
const sets: Partial<Pick<schema.SimStateRow, 'paused' | 'timeScale'>> = { paused: false };
|
||||
const remaining = await inst.db.select().from(schema.planes).where(eq(schema.planes.status, 'available'));
|
||||
if (remaining.length === 0) sets.timeScale = sim.lastSelectedTimeScale;
|
||||
await inst.db.update(schema.simState).set(sets);
|
||||
await persist(inst);
|
||||
}
|
||||
|
||||
|
||||
+12
-8
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { WORLD_TIME_SCALE } from '@/lib/worldClock';
|
||||
import { haversineKm } from '@/lib/geo';
|
||||
import { PLANE_TYPES, repRate, STARTER_MODEL } from './catalog';
|
||||
import { SPECIALS } from './specials';
|
||||
@@ -18,6 +19,7 @@ import {
|
||||
REWARD_PER_KM,
|
||||
rewardFor,
|
||||
STARTING_CASH,
|
||||
STARTING_CLOCK_MS,
|
||||
STARTING_REPUTATION,
|
||||
type Rng,
|
||||
type SeedAirport,
|
||||
@@ -73,7 +75,7 @@ describe('buildSeed', () => {
|
||||
expect(c.originIcao).not.toBe(c.destIcao);
|
||||
expect(c.status).toBe('open');
|
||||
expect(c.planeId).toBeNull();
|
||||
expect(c.createdSimTime).toBe(NOW);
|
||||
expect(c.createdSimTime).toBe(STARTING_CLOCK_MS); // game-clock origin, not wall time (ISS-117)
|
||||
}
|
||||
expect(new Set(seed.packages.map((c) => c.id)).size).toBe(seed.packages.length);
|
||||
});
|
||||
@@ -101,22 +103,23 @@ describe('buildSeed', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('sets deadlines inside the 6–72h game-time window after now (scaled by any special status)', () => {
|
||||
it('sets deadlines inside the 6–72h game-time window after the game-clock origin (scaled by any special status)', () => {
|
||||
const seed = seedWith(42);
|
||||
for (const c of seed.packages) {
|
||||
// v0.37.0 (ISS-073): a special's deadlineScale tightens the drawn window (e.g. priority → 3–36h).
|
||||
// ISS-117: the window is anchored at STARTING_CLOCK_MS, not wall time.
|
||||
const scale = c.special ? SPECIALS[c.special]?.deadlineScale ?? 1 : 1;
|
||||
expect(c.deadlineSimTime).toBeGreaterThan(NOW + 6 * 3_600_000 * scale - 1);
|
||||
expect(c.deadlineSimTime).toBeLessThanOrEqual(NOW + 72 * 3_600_000 * scale);
|
||||
expect(c.deadlineSimTime).toBeGreaterThan(STARTING_CLOCK_MS + 6 * 3_600_000 * scale - 1);
|
||||
expect(c.deadlineSimTime).toBeLessThanOrEqual(STARTING_CLOCK_MS + 72 * 3_600_000 * scale);
|
||||
}
|
||||
});
|
||||
|
||||
it('seeds the starting account and sim state', () => {
|
||||
const seed = seedWith(42);
|
||||
expect(seed.account).toEqual({ cash: STARTING_CASH, reputation: STARTING_REPUTATION });
|
||||
// lastRealTickMs starts at the seed moment so the first tick-on-read advances ~0;
|
||||
// lastSelectedTimeScale mirrors the seeded speed (v0.30.0, ISS-057).
|
||||
expect(seed.simState).toEqual({ clockMs: NOW, timeScale: 1, paused: false, lastRealTickMs: NOW, lastSelectedTimeScale: 1 });
|
||||
// ISS-117 (v0.52.0): game clock starts at year 2000 with the fixed world rate; lastRealTickMs is
|
||||
// the REAL seed moment so the first tick-on-read advances ~0. paused/lastSelectedTimeScale are legacy columns.
|
||||
expect(seed.simState).toEqual({ clockMs: STARTING_CLOCK_MS, timeScale: WORLD_TIME_SCALE, paused: false, lastRealTickMs: NOW, lastSelectedTimeScale: WORLD_TIME_SCALE });
|
||||
});
|
||||
|
||||
it('is fully deterministic for a fixed RNG and inputs', () => {
|
||||
@@ -186,7 +189,8 @@ describe('generatePackage (shared seed/spawn builder)', () => {
|
||||
const count = PACKAGE_COUNT_MIN + Math.floor(rngA() * (PACKAGE_COUNT_MAX - PACKAGE_COUNT_MIN + 1));
|
||||
const expected: string[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
expected.push(JSON.stringify(generatePackage({ id: `package-${i + 1}`, airports: AIRPORTS, rng: rngA, nowMs: NOW })));
|
||||
// ISS-117: buildSeed anchors packages at the game-clock origin, not the wall-time input.
|
||||
expected.push(JSON.stringify(generatePackage({ id: `package-${i + 1}`, airports: AIRPORTS, rng: rngA, nowMs: STARTING_CLOCK_MS })));
|
||||
}
|
||||
const seed = buildSeed({ airports: AIRPORTS, rng: mulberry32(42), nowMs: NOW });
|
||||
expect(seed.packages.map((c) => JSON.stringify(c))).toEqual(expected);
|
||||
|
||||
+13
-7
@@ -1,4 +1,5 @@
|
||||
import { haversineKm } from '@/lib/geo';
|
||||
import { WORLD_TIME_SCALE } from '@/lib/worldClock';
|
||||
import { PLANE_TYPES, repRate, STARTER_MODEL } from './catalog';
|
||||
import { pickSpecial, SPECIALS } from './specials';
|
||||
|
||||
@@ -75,6 +76,10 @@ export interface SeedData {
|
||||
export const STARTING_CASH = 20_000;
|
||||
export const STARTING_REPUTATION = 10;
|
||||
|
||||
// ISS-117 (v0.52.0): fresh worlds start at the top of year 2000 — a fixed game-time origin so
|
||||
// every new save begins from the same moment. Existing saves keep their own clock (no migration).
|
||||
export const STARTING_CLOCK_MS = Date.UTC(2000, 0, 1);
|
||||
|
||||
// The starter plane grounds at a large central-European hub. If the ICAO is
|
||||
// ever missing from the dataset we fall back to the first airport rather than
|
||||
// failing first run. (EDDF = Frankfurt; EDDM is Munich — don't mix them up.)
|
||||
@@ -291,20 +296,21 @@ export function buildSeed(input: {
|
||||
|
||||
const count = PACKAGE_COUNT_MIN + Math.floor(rng() * (PACKAGE_COUNT_MAX - PACKAGE_COUNT_MIN + 1));
|
||||
// Stable index-based ids for the seed set; runtime-generated entities must use
|
||||
// random UUIDs to avoid colliding with these.
|
||||
// random UUIDs to avoid colliding with these. Deadlines are drawn relative to the GAME clock
|
||||
// origin (ISS-117), not the real wall time, so they stay meaningful at the fixed world rate.
|
||||
const packages: SeedPackage[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
packages.push(generatePackage({ id: `package-${i + 1}`, airports, rng, nowMs }));
|
||||
packages.push(generatePackage({ id: `package-${i + 1}`, airports, rng, nowMs: STARTING_CLOCK_MS }));
|
||||
}
|
||||
|
||||
return {
|
||||
plane,
|
||||
packages,
|
||||
account: { cash: STARTING_CASH, reputation: STARTING_REPUTATION },
|
||||
// lastRealTickMs starts at the seed moment so the first tick-on-read advances
|
||||
// by ~0 instead of treating "time since install" as elapsed play time.
|
||||
// lastSelectedTimeScale (v0.30.0, ISS-057) mirrors the seeded speed — nothing has been
|
||||
// selected manually yet, so resume would restore 1× anyway.
|
||||
simState: { clockMs: nowMs, timeScale: 1, paused: false, lastRealTickMs: nowMs, lastSelectedTimeScale: 1 },
|
||||
// ISS-117 (v0.52.0): the game clock starts at year 2000 with the fixed world rate; lastRealTickMs
|
||||
// is the REAL seed moment so the first tick advances by ~0 instead of treating "time since
|
||||
// install" as elapsed play time. paused/lastSelectedTimeScale are legacy columns kept for schema
|
||||
// stability — no game code reads them anymore.
|
||||
simState: { clockMs: STARTING_CLOCK_MS, timeScale: WORLD_TIME_SCALE, paused: false, lastRealTickMs: nowMs, lastSelectedTimeScale: WORLD_TIME_SCALE },
|
||||
};
|
||||
}
|
||||
|
||||
+4
-2
@@ -73,7 +73,9 @@ export interface PackageState {
|
||||
|
||||
export interface StateSnapshot {
|
||||
account: { cash: number; reputation: number };
|
||||
simState: { clockMs: number; timeScale: number; paused: boolean };
|
||||
// ISS-117 (v0.52.0): the world rate is a fixed constant (WORLD_TIME_SCALE), not per-save state —
|
||||
// only the clock itself is reported here.
|
||||
simState: { clockMs: number };
|
||||
planes: PlaneState[];
|
||||
packages: PackageState[];
|
||||
// Market reference data (v0.10.0) — static per build, sent with every snapshot so
|
||||
@@ -135,7 +137,7 @@ export async function getStateSnapshot(): Promise<StateSnapshot> {
|
||||
|
||||
return {
|
||||
account: { cash: accountRow.cash, reputation: accountRow.reputation },
|
||||
simState: { clockMs: simRow.clockMs, timeScale: simRow.timeScale, paused: simRow.paused },
|
||||
simState: { clockMs: simRow.clockMs },
|
||||
catalog: catalogEntries(),
|
||||
fuelPricePerL: FUEL_PRICE_PER_L,
|
||||
sellFraction: SELL_FRACTION,
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const AIRPORTS = new Map<string, AirportCoord>([
|
||||
function snapshot(overrides: Partial<StateSnapshot> = {}): StateSnapshot {
|
||||
return {
|
||||
account: { cash: 0, reputation: 0 },
|
||||
simState: { clockMs: 0, timeScale: 1, paused: false },
|
||||
simState: { clockMs: 0 },
|
||||
planes: [],
|
||||
packages: [],
|
||||
catalog: [
|
||||
|
||||
+3
-26
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
|
||||
import { openApiSpec } from './openapi';
|
||||
|
||||
describe('OpenAPI spec', () => {
|
||||
it('documents exactly the thirteen public endpoints (4 read + 9 player actions)', () => {
|
||||
it('documents exactly the twelve public endpoints (3 read + 9 player actions)', () => {
|
||||
expect(Object.keys(openApiSpec.paths).sort()).toEqual([
|
||||
'/api/airports',
|
||||
'/api/market/buy-plane',
|
||||
@@ -15,7 +15,6 @@ describe('OpenAPI spec', () => {
|
||||
'/api/planes/{planeId}/queue', // v0.25.0 (ISS-043)
|
||||
'/api/planes/{planeId}/queue/cancel', // v0.25.0 (ISS-043)
|
||||
'/api/planes/{planeId}/repair', // v0.39.0 (ISS-069)
|
||||
'/api/sim',
|
||||
'/api/state',
|
||||
'/api/version',
|
||||
]);
|
||||
@@ -147,36 +146,14 @@ describe('OpenAPI spec', () => {
|
||||
'weightKg', // v0.27.0 (ISS-045) — package weight in kg
|
||||
]);
|
||||
|
||||
// ISS-117 (v0.52.0): the snapshot carries only the game clock — time controls are gone.
|
||||
const sim = openApiSpec.components.schemas.SimState.properties;
|
||||
expect(Object.keys(sim).sort()).toEqual(['clockMs', 'paused', 'timeScale']);
|
||||
expect(Object.keys(sim).sort()).toEqual(['clockMs']);
|
||||
|
||||
const packageStatus = openApiSpec.components.schemas.PackageState.properties.status;
|
||||
expect(packageStatus.enum.sort()).toEqual(['abandoned', 'delivered', 'expired', 'ignored', 'loaded', 'open']); // v0.29.0 (ISS-047 part B)
|
||||
});
|
||||
|
||||
it('describes POST /api/sim as SimControlsRequest → SimState with a 400 error shape', () => {
|
||||
const post = openApiSpec.paths['/api/sim'].post;
|
||||
expect(post.operationId).toBe('setSimControls');
|
||||
|
||||
const requestSchema = post.requestBody.content['application/json'].schema;
|
||||
expect(requestSchema.$ref).toBe('#/components/schemas/SimControlsRequest');
|
||||
|
||||
const ok = post.responses[200].content['application/json'].schema;
|
||||
expect(ok.$ref).toBe('#/components/schemas/SimState');
|
||||
const bad = post.responses[400].content['application/json'].schema;
|
||||
expect(bad.$ref).toBe('#/components/schemas/Error');
|
||||
|
||||
const controls = openApiSpec.components.schemas.SimControlsRequest.properties;
|
||||
expect(Object.keys(controls).sort()).toEqual(['paused', 'timeScale']);
|
||||
expect(controls.timeScale.type).toBe('number');
|
||||
expect(controls.timeScale.minimum).toBe(1);
|
||||
expect(controls.timeScale.maximum).toBe(1000);
|
||||
expect(controls.paused.type).toBe('boolean');
|
||||
|
||||
const error = openApiSpec.components.schemas.Error.properties;
|
||||
expect(Object.keys(error)).toEqual(['error']);
|
||||
});
|
||||
|
||||
it('documents the eight action endpoints: snapshot on 200, Error on their 4xx paths', () => {
|
||||
// The spec object is a literal type; these helpers view it as plain JSON.
|
||||
const post = (p: string) =>
|
||||
|
||||
+3
-52
@@ -37,7 +37,7 @@ export const openApiSpec = {
|
||||
get: {
|
||||
summary: 'Game state snapshot',
|
||||
description:
|
||||
'Full current game state for client polling — account, sim clock, planes and packages, plus the static market reference data (catalog + economy constants) so clients can compute buy/sell previews locally. Tick-on-read: each call first advances the sim clock by (real time since last read) × timeScale (clamped per tick), so expiry/delivery/spawn are always applied before the snapshot is returned.',
|
||||
'Full current game state for client polling — account, sim clock, planes and packages, plus the static market reference data (catalog + economy constants) so clients can compute buy/sell previews locally. The world clock advances on a ~1 s background tick at a fixed rate (v0.52.0, ISS-117: no player-facing time controls), clamped per tick; while no plane is flying or in repair the clock stays frozen. Each call ticks first, so expiry/delivery/spawn are always applied before the snapshot is returned.',
|
||||
operationId: 'getState',
|
||||
responses: {
|
||||
200: {
|
||||
@@ -51,40 +51,6 @@ export const openApiSpec = {
|
||||
},
|
||||
},
|
||||
},
|
||||
'/api/sim': {
|
||||
post: {
|
||||
summary: 'Set sim time controls',
|
||||
description:
|
||||
'Advance the sim clock (tick-on-read) and set the time scale / pause state. The clock is advanced first, so the returned simState already reflects current game time; package expiry, arrival delivery and market spawn run inside that tick.',
|
||||
operationId: 'setSimControls',
|
||||
requestBody: {
|
||||
required: false,
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/SimControlsRequest' },
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
200: {
|
||||
description: 'Updated sim state',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/SimState' },
|
||||
},
|
||||
},
|
||||
},
|
||||
400: {
|
||||
description: 'Invalid body (not an object, unknown field, or wrong types)',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/Error' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
'/api/version': {
|
||||
get: {
|
||||
summary: 'App version',
|
||||
@@ -493,24 +459,9 @@ export const openApiSpec = {
|
||||
SimState: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
clockMs: { type: 'integer', description: 'Sim-clock epoch ms (game time)' },
|
||||
timeScale: { type: 'number', minimum: 1, maximum: 1000 },
|
||||
paused: { type: 'boolean' },
|
||||
},
|
||||
required: ['clockMs', 'timeScale', 'paused'],
|
||||
},
|
||||
SimControlsRequest: {
|
||||
type: 'object',
|
||||
description: 'Partial update — omit a field to leave it unchanged.',
|
||||
properties: {
|
||||
timeScale: {
|
||||
type: 'number',
|
||||
minimum: 1,
|
||||
maximum: 1000,
|
||||
description: 'Game-time multiplier; values outside [1, 1000] are clamped. The UI offers the ladder 1/2/5/10/25/50/100/250/500/1000.',
|
||||
},
|
||||
paused: { type: 'boolean' },
|
||||
clockMs: { type: 'integer', description: 'Sim-clock epoch ms (game time). The world runs at a fixed rate with no player-facing controls (v0.52.0, ISS-117).' },
|
||||
},
|
||||
required: ['clockMs'],
|
||||
},
|
||||
LoadPackageRequest: {
|
||||
type: 'object',
|
||||
|
||||
+71
-143
@@ -10,26 +10,33 @@ import { haversineKm, initialBearingDeg } from '@/lib/geo';
|
||||
import { weatherFor } from '@/lib/weather';
|
||||
import { FUEL_DISCOUNT_PER_REP, FUEL_PRICE_PER_L, MAX_FUEL_DISCOUNT, PLANE_TYPES, REPAIR_DURATION_MS, repRate, WEAR_PER_KM } from '@/lib/game/catalog';
|
||||
import { SPECIALS } from '@/lib/game/specials';
|
||||
import { MARKET_TARGET_OPEN_PACKAGES, mulberry32 } from '@/lib/game/seed';
|
||||
import { MARKET_TARGET_OPEN_PACKAGES, mulberry32, STARTING_CLOCK_MS } from '@/lib/game/seed';
|
||||
import { arrivalTimeFor, fuelAtWeighted, requiredFuelFor, windBurnFactor } from './movement';
|
||||
import {
|
||||
clampTimeScale,
|
||||
deliverPackages,
|
||||
expirePackages,
|
||||
finishRepairs,
|
||||
MAX_TICK_ELAPSED_MS,
|
||||
MAX_TIME_SCALE,
|
||||
MIN_TIME_SCALE,
|
||||
reputationGainFor,
|
||||
shouldAdvanceTime,
|
||||
spawnCoveragePackages,
|
||||
spawnOpenPackages,
|
||||
tickOnce,
|
||||
WORLD_TIME_SCALE,
|
||||
} from './engine';
|
||||
|
||||
// Engine tests run against throwaway DB files (openGameDb) with fake timers so
|
||||
// Date.now() — the only wall-clock input to a tick — is fully controlled. The
|
||||
// public tickNow()/applyTimeControls() wrappers (singleton + lock) are covered
|
||||
// by app/api/sim/route.test.ts and the e2e suite.
|
||||
// public tickNow()/setTestTimeScale() wrappers (singleton + lock) are covered by the e2e suite
|
||||
// (every spec's setScale helper hits /api/test/set-timescale; sim.spec.ts pins its validation).
|
||||
|
||||
// ISS-117: fresh DBs seed a GROUNDED starter, so any test that needs an advancing world must put
|
||||
// a plane in flight first — departureSimTime at the game-clock origin keeps its arrival hours away.
|
||||
async function makeWorldActive(inst: Awaited<ReturnType<typeof openGameDb>>) {
|
||||
await inst.db.update(schema.planes)
|
||||
.set({ status: 'flying', destIcao: 'LEMD', departureSimTime: STARTING_CLOCK_MS })
|
||||
.where(eq(schema.planes.id, 'plane-starter'));
|
||||
}
|
||||
|
||||
let dir: string;
|
||||
const T0 = 1_750_000_000_000; // seed moment / fake "now" at DB open
|
||||
@@ -53,43 +60,46 @@ async function freshDb(name: string) {
|
||||
describe('tickOnce — clock advance', () => {
|
||||
it('advances the clock by elapsed real ms × timeScale', async () => {
|
||||
const inst = await freshDb('scale.db');
|
||||
await makeWorldActive(inst); // a grounded fleet would freeze the world (ISS-117)
|
||||
vi.setSystemTime(T0 + 1_000); // one real second later
|
||||
await inst.db.update(schema.simState).set({ timeScale: 5 });
|
||||
|
||||
const sim = await tickOnce(inst);
|
||||
|
||||
expect(sim.clockMs).toBe(T0 + 5_000); // 1 s × 5
|
||||
expect(sim.clockMs).toBe(STARTING_CLOCK_MS + 5_000); // 1 s × 5
|
||||
expect(sim.lastRealTickMs).toBe(T0 + 1_000);
|
||||
});
|
||||
|
||||
it('freezes the clock while paused but keeps tracking real time', async () => {
|
||||
const inst = await freshDb('pause.db');
|
||||
await inst.db.update(schema.simState).set({ paused: true, timeScale: 60 });
|
||||
it('freezes the clock while the fleet is fully grounded but keeps tracking real time', async () => {
|
||||
const inst = await freshDb('idle.db'); // seeded starter is on the ground → idle (ISS-117)
|
||||
|
||||
vi.setSystemTime(T0 + 3_600_000); // an hour of real pause
|
||||
vi.setSystemTime(T0 + 3_600_000); // an hour of real idleness
|
||||
let sim = await tickOnce(inst);
|
||||
expect(sim.clockMs).toBe(T0); // frozen — no advance at all
|
||||
expect(sim.clockMs).toBe(STARTING_CLOCK_MS); // frozen — no advance at all
|
||||
expect(sim.lastRealTickMs).toBe(T0 + 3_600_000);
|
||||
|
||||
// Unpause: resumes from where it stopped, with NO catch-up for the pause.
|
||||
await inst.db.update(schema.simState).set({ paused: false });
|
||||
// A plane takes off: resumes from where it stopped, with NO catch-up for the idle time.
|
||||
await inst.db.update(schema.simState).set({ timeScale: 60 });
|
||||
await makeWorldActive(inst);
|
||||
vi.setSystemTime(T0 + 3_600_500);
|
||||
sim = await tickOnce(inst);
|
||||
expect(sim.clockMs).toBe(T0 + 500 * 60); // only the 500 ms since unpausing × 60
|
||||
expect(sim.clockMs).toBe(STARTING_CLOCK_MS + 500 * 60); // only the 500 ms since activity × 60
|
||||
});
|
||||
|
||||
it('clamps long absences: a 1-hour gap advances at most MAX_TICK_ELAPSED_MS × scale', async () => {
|
||||
const inst = await freshDb('clamp.db');
|
||||
await makeWorldActive(inst);
|
||||
vi.setSystemTime(T0 + 3_600_000); // server sat idle for an hour
|
||||
|
||||
const sim = await tickOnce(inst); // timeScale is the seeded 1
|
||||
const sim = await tickOnce(inst); // timeScale is the seeded WORLD_TIME_SCALE
|
||||
|
||||
expect(sim.clockMs).toBe(T0 + MAX_TICK_ELAPSED_MS); // exactly one clamped tick, not a fast-forward
|
||||
expect(sim.clockMs).toBe(STARTING_CLOCK_MS + MAX_TICK_ELAPSED_MS * WORLD_TIME_SCALE); // exactly one clamped tick, not a fast-forward
|
||||
vi.setSystemTime(T0); // reset for later tests in this file
|
||||
});
|
||||
|
||||
it('does not advance when two ticks land in the same millisecond', async () => {
|
||||
const inst = await freshDb('same-ms.db');
|
||||
await makeWorldActive(inst);
|
||||
vi.setSystemTime(T0 + 1_000);
|
||||
const a = await tickOnce(inst);
|
||||
const b = await tickOnce(inst); // no real time passed since `a`
|
||||
@@ -100,15 +110,17 @@ describe('tickOnce — clock advance', () => {
|
||||
describe('expirePackages', () => {
|
||||
it('flips open AND loaded packages past their deadline; terminal statuses never expire', async () => {
|
||||
const inst = await freshDb('expiry.db');
|
||||
const clock = T0 + 100_000;
|
||||
// Game-clock anchor just after the seed moment — well inside every seeded package's deadline
|
||||
// window (DEADLINE_MIN_HOURS), so only the rows inserted below can expire.
|
||||
const clock = STARTING_CLOCK_MS + 100_000;
|
||||
|
||||
await inst.db.insert(schema.packages).values([
|
||||
{ id: 'p-open-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'open', planeId: null, createdSimTime: T0 },
|
||||
{ id: 'p-open-future', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock + 1, status: 'open', planeId: null, createdSimTime: T0 },
|
||||
{ id: 'p-loaded-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
||||
{ id: 'p-delivered-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'delivered', planeId: null, createdSimTime: T0 },
|
||||
{ id: 'p-abandoned-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'abandoned', planeId: null, createdSimTime: T0 },
|
||||
{ id: 'p-ignored-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'ignored', planeId: null, createdSimTime: T0 },
|
||||
{ id: 'p-open-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'open', planeId: null, createdSimTime: STARTING_CLOCK_MS },
|
||||
{ id: 'p-open-future', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock + 1, status: 'open', planeId: null, createdSimTime: STARTING_CLOCK_MS },
|
||||
{ id: 'p-loaded-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'loaded', planeId: 'plane-starter', createdSimTime: STARTING_CLOCK_MS },
|
||||
{ id: 'p-delivered-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'delivered', planeId: null, createdSimTime: STARTING_CLOCK_MS },
|
||||
{ id: 'p-abandoned-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'abandoned', planeId: null, createdSimTime: STARTING_CLOCK_MS },
|
||||
{ id: 'p-ignored-past', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: clock - 1, status: 'ignored', planeId: null, createdSimTime: STARTING_CLOCK_MS },
|
||||
]);
|
||||
|
||||
const n = await expirePackages(inst, clock);
|
||||
@@ -127,9 +139,9 @@ describe('expirePackages', () => {
|
||||
const inst = await freshDb('expiry-edge.db');
|
||||
await inst.db.insert(schema.packages).values({
|
||||
id: 'p-edge', originIcao: 'EDDF', destIcao: 'LEMD', reward: 1, cargoType: 'Mail', cargoCount: 1,
|
||||
deadlineSimTime: T0 + 50_000, status: 'open', planeId: null, createdSimTime: T0,
|
||||
deadlineSimTime: STARTING_CLOCK_MS + 50_000, status: 'open', planeId: null, createdSimTime: STARTING_CLOCK_MS,
|
||||
});
|
||||
expect(await expirePackages(inst, T0 + 50_000)).toBe(1); // <= is inclusive
|
||||
expect(await expirePackages(inst, STARTING_CLOCK_MS + 50_000)).toBe(1); // <= is inclusive
|
||||
});
|
||||
});
|
||||
|
||||
@@ -516,11 +528,13 @@ describe('finishRepairs (v0.39.0, ISS-069)', () => {
|
||||
|
||||
it('runs inside tickOnce even when nothing landed: a past gate flips the plane back', async () => {
|
||||
const inst = await freshDb('repair-tick.db');
|
||||
// The repairing plane keeps the world advancing (ISS-117); scale pinned to 1 for clean math.
|
||||
await inst.db.update(schema.simState).set({ timeScale: 1 });
|
||||
await inst.db.update(schema.planes)
|
||||
.set({ status: 'repairing', repairUntilSimTime: T0 + 1_500 })
|
||||
.set({ status: 'repairing', repairUntilSimTime: STARTING_CLOCK_MS + 1_500 })
|
||||
.where(eq(schema.planes.id, 'plane-starter'));
|
||||
|
||||
vi.setSystemTime(T0 + 2_000); // one clamped tick at scale 1 → clock T0+2000 ≥ gate; nothing is flying
|
||||
vi.setSystemTime(T0 + 2_000); // one clamped tick at scale 1 → clock STARTING_CLOCK_MS+2000 ≥ gate
|
||||
await tickOnce(inst);
|
||||
|
||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||
@@ -560,101 +574,35 @@ describe('finishRepairs (v0.39.0, ISS-069)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('slow to 1× when a landing leaves any plane on the ground (ISS-057)', () => {
|
||||
const FROM = 'EDDF';
|
||||
const TO = 'LEMD';
|
||||
describe('idle-pause — the world freezes when nothing is happening (ISS-117)', () => {
|
||||
it('shouldAdvanceTime: grounded/empty fleets are idle; any flying or repairing plane advances', () => {
|
||||
expect(shouldAdvanceTime([])).toEqual({ advance: false, flying: 0, repairing: 0 });
|
||||
expect(shouldAdvanceTime([{ status: 'available' }, { status: 'available' }])).toEqual({ advance: false, flying: 0, repairing: 0 });
|
||||
expect(shouldAdvanceTime([{ status: 'flying' }, { status: 'available' }])).toEqual({ advance: true, flying: 1, repairing: 0 });
|
||||
expect(shouldAdvanceTime([{ status: 'repairing' }])).toEqual({ advance: true, flying: 0, repairing: 1 });
|
||||
expect(shouldAdvanceTime([{ status: 'flying' }, { status: 'repairing' }])).toEqual({ advance: true, flying: 1, repairing: 1 });
|
||||
});
|
||||
|
||||
// Starter flying EDDF→LEMD with departureSimTime set so its arrival is EXACTLY T0 —
|
||||
// any advancing tick past T0 finalizes it. timeScale is the value under test;
|
||||
// lastSelectedTimeScale mirrors what a manual POST /api/sim would have stored.
|
||||
async function setupLanding(name: string, timeScale: number) {
|
||||
const inst = await freshDb(name);
|
||||
const fc = await loadAirportsGeoJson();
|
||||
const from = fc.features.find((f) => f.properties.icao === FROM)!.properties;
|
||||
const to = fc.features.find((f) => f.properties.icao === TO)!.properties;
|
||||
const km = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||
const type = PLANE_TYPES.atr72;
|
||||
it('a fully grounded fleet freezes the clock but keeps tracking real time', async () => {
|
||||
const inst = await freshDb('idle-pause.db'); // seeded starter is on the ground → idle
|
||||
vi.setSystemTime(T0 + 3_600_000);
|
||||
|
||||
await inst.db.update(schema.simState).set({ timeScale, lastSelectedTimeScale: timeScale });
|
||||
const sim = await tickOnce(inst);
|
||||
|
||||
expect(sim.clockMs).toBe(STARTING_CLOCK_MS); // frozen — no advance at all
|
||||
expect(sim.lastRealTickMs).toBe(T0 + 3_600_000); // …but the real-time anchor moved on
|
||||
});
|
||||
|
||||
it('a repairing plane keeps the world advancing', async () => {
|
||||
const inst = await freshDb('idle-repair.db');
|
||||
await inst.db.update(schema.planes)
|
||||
.set({ status: 'flying', destIcao: TO, departureSimTime: T0 - travelMs(km, type.speedKmh), fuel: type.maxFuel })
|
||||
.set({ status: 'repairing', repairUntilSimTime: STARTING_CLOCK_MS + REPAIR_DURATION_MS })
|
||||
.where(eq(schema.planes.id, 'plane-starter'));
|
||||
|
||||
return { inst, from, km, type };
|
||||
}
|
||||
|
||||
it('last plane lands → sim slows to 1× WITHOUT pausing; lastSelectedTimeScale is preserved', async () => {
|
||||
const { inst } = await setupLanding('slow-last.db', 1000);
|
||||
vi.setSystemTime(T0 + 2_000); // one full clamped tick at scale 1000 → clock T0+2e6 ≥ arrival (T0)
|
||||
|
||||
vi.setSystemTime(T0 + 1_000);
|
||||
const sim = await tickOnce(inst);
|
||||
|
||||
expect(sim.paused).toBe(false); // no pause anymore — ISS-057 replaces it with a slow-down…
|
||||
expect((await inst.db.select().from(schema.simState))[0].paused).toBe(false); // …persisted on the row…
|
||||
expect(sim.timeScale).toBe(1); // …slowed to the floor…
|
||||
expect(sim.lastSelectedTimeScale).toBe(1000); // …with the last manual speed kept for resume
|
||||
expect((await inst.db.select().from(schema.planes))[0].status).toBe('available'); // landing itself unchanged
|
||||
});
|
||||
|
||||
it('a landing while another plane is still flying → slows to 1× (any plane on ground)', async () => {
|
||||
const { inst, from, type } = await setupLanding('slow-other.db', 1000);
|
||||
// A second plane on the same route departing at T0 — arrives far after this tick's clock.
|
||||
await inst.db.insert(schema.planes).values({
|
||||
id: 'p-b', model: 'atr72', status: 'flying', fuel: type.maxFuel, maxFuel: type.maxFuel,
|
||||
locationIcao: FROM, destIcao: TO, lat: from.lat, lon: from.lon, departureSimTime: T0,
|
||||
});
|
||||
|
||||
vi.setSystemTime(T0 + 2_000);
|
||||
const sim = await tickOnce(inst);
|
||||
|
||||
expect(sim.paused).toBe(false);
|
||||
expect(sim.timeScale).toBe(1); // the just-landed starter is on ground → slow (literal issue reading)
|
||||
const byId = new Map((await inst.db.select().from(schema.planes)).map((p) => [p.id, p.status]));
|
||||
expect(byId.get('plane-starter')).toBe('available'); // the starter did land…
|
||||
expect(byId.get('p-b')).toBe('flying'); // …but the fleet is not idle — still slowed
|
||||
});
|
||||
|
||||
it('already at 1× → stays 1 (no-op slow)', async () => {
|
||||
const { inst } = await setupLanding('slow-one.db', 1);
|
||||
vi.setSystemTime(T0 + 2_000); // one tick at scale 1 advances 2e3 game ms — past the T0 arrival
|
||||
|
||||
const sim = await tickOnce(inst);
|
||||
|
||||
expect(sim.paused).toBe(false);
|
||||
expect(sim.timeScale).toBe(1);
|
||||
expect((await inst.db.select().from(schema.planes))[0].status).toBe('available');
|
||||
});
|
||||
|
||||
it('a chained plane does NOT slow the sim (nothing is grounded)', async () => {
|
||||
const { inst } = await setupLanding('slow-chain.db', 1000); // full tank, arrival exactly T0
|
||||
// A queued next hop with plenty of fuel → chains on landing instead of grounding.
|
||||
await inst.db.update(schema.planes)
|
||||
.set({ queue: JSON.stringify(['EDDV']) })
|
||||
.where(eq(schema.planes.id, 'plane-starter'));
|
||||
|
||||
vi.setSystemTime(T0 + 2_000); // one full clamped tick at scale 1000 → clock T0+2e6 ≥ arrival (T0)
|
||||
const sim = await tickOnce(inst);
|
||||
|
||||
expect(sim.paused).toBe(false);
|
||||
expect(sim.timeScale).toBe(1000); // still flying after the chain, nothing grounded — no slow…
|
||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||
expect(plane.status).toBe('flying'); // …the fresh select in tickOnce counts it as airborne
|
||||
expect(plane.destIcao).toBe('EDDV');
|
||||
});
|
||||
|
||||
it('manually-paused sim is untouched by ticks (no landing processed while paused)', async () => {
|
||||
const inst = await freshDb('slow-paused.db');
|
||||
// The fleet is fully grounded (the seeded starter) — a paused tick must not touch the
|
||||
// controls even though "any plane on ground" holds: the trigger requires a landing this tick.
|
||||
await inst.db.update(schema.simState).set({ timeScale: 1000, lastSelectedTimeScale: 1000, paused: true });
|
||||
|
||||
vi.setSystemTime(T0 + 5_000);
|
||||
const sim = await tickOnce(inst);
|
||||
|
||||
expect(sim.paused).toBe(true); // no landing processed while paused → trigger never fires
|
||||
expect(sim.timeScale).toBe(1000);
|
||||
expect(sim.lastSelectedTimeScale).toBe(1000);
|
||||
expect((await inst.db.select().from(schema.planes))[0].status).toBe('available');
|
||||
expect(sim.clockMs).toBeGreaterThan(STARTING_CLOCK_MS); // the repair gate is what keeps time moving
|
||||
});
|
||||
});
|
||||
|
||||
@@ -789,7 +737,13 @@ describe('spawnCoveragePackages (v0.8.0 spawn coverage rule)', () => {
|
||||
|
||||
it('runs inside tickOnce: a fresh DB gains an EDDF-origin package after one advancing tick', async () => {
|
||||
const inst = await freshDb('coverage-tick.db');
|
||||
vi.setSystemTime(T0 + 1_000); // one real second → advanceMs > 0 at scale 1
|
||||
// A second, airborne plane keeps the world advancing (ISS-117) while the seeded starter stays
|
||||
// grounded — which is what coverage spawns for. Arrival is hours out, so it never lands here.
|
||||
await inst.db.insert(schema.planes).values({
|
||||
id: 'p-air', model: 'atr72', status: 'flying', fuel: 6300, maxFuel: 6300,
|
||||
locationIcao: 'EDDF', destIcao: 'LEMD', lat: 50.03, lon: 8.57, departureSimTime: STARTING_CLOCK_MS,
|
||||
});
|
||||
vi.setSystemTime(T0 + 1_000); // one real second → advanceMs > 0 at the seeded scale
|
||||
|
||||
await tickOnce(inst);
|
||||
|
||||
@@ -800,32 +754,6 @@ describe('spawnCoveragePackages (v0.8.0 spawn coverage rule)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('clampTimeScale — v0.14.0 ladder bounds [1, 1000]', () => {
|
||||
it('clamps below-minimum values to MIN_TIME_SCALE', () => {
|
||||
expect(clampTimeScale(0)).toBe(MIN_TIME_SCALE);
|
||||
expect(clampTimeScale(-5)).toBe(MIN_TIME_SCALE);
|
||||
expect(clampTimeScale(0.1)).toBe(MIN_TIME_SCALE);
|
||||
});
|
||||
|
||||
it('clamps above-maximum values to MAX_TIME_SCALE', () => {
|
||||
expect(clampTimeScale(1001)).toBe(MAX_TIME_SCALE);
|
||||
expect(clampTimeScale(2000)).toBe(MAX_TIME_SCALE);
|
||||
expect(clampTimeScale(Number.MAX_SAFE_INTEGER)).toBe(MAX_TIME_SCALE);
|
||||
});
|
||||
|
||||
it('passes in-range values through unclamped — ladder and off-ladder alike', () => {
|
||||
for (const s of [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000]) {
|
||||
expect(clampTimeScale(s)).toBe(s); // the full v0.14.0 slider ladder
|
||||
}
|
||||
expect(clampTimeScale(37)).toBe(37); // off-ladder but in range (e.g. a legacy value)
|
||||
});
|
||||
|
||||
it('keeps the endpoints exact', () => {
|
||||
expect(clampTimeScale(MIN_TIME_SCALE)).toBe(MIN_TIME_SCALE);
|
||||
expect(clampTimeScale(MAX_TIME_SCALE)).toBe(MAX_TIME_SCALE);
|
||||
});
|
||||
});
|
||||
|
||||
// Local helper mirroring lib/sim/movement.ts (kept private there on purpose — the
|
||||
// engine composes arrivalTimeFor; tests just need the duration for fixtures).
|
||||
function travelMs(km: number, speedKmh: number): number {
|
||||
|
||||
+48
-61
@@ -18,20 +18,20 @@ import {
|
||||
} from '@/lib/game/seed';
|
||||
import { arrivalTimeFor, fuelAtWeighted, requiredFuelFor, windBurnFactor } from './movement';
|
||||
|
||||
// Server-authoritative sim engine (v0.7.0) — tick-on-read: there is NO background
|
||||
// timer. Every read/action endpoint calls tickNow() first; the clock advances by
|
||||
// (real ms since last tick) × timeScale, clamped per tick so long absences never
|
||||
// fast-forward the game.
|
||||
// Server-authoritative sim engine (v0.7.0). ISS-117 (v0.52.0): the clock advances on a background
|
||||
// tick (~1 s, started at boot from instrumentation.ts) AND on every read/action — both through the
|
||||
// same locked tickOnce path. Each tick advances by (real ms since last tick) × timeScale, clamped
|
||||
// per tick so long absences never fast-forward the game; while no plane is flying or in repair the
|
||||
// clock stays frozen (idle-pause) but lastRealTickMs keeps tracking real time.
|
||||
|
||||
// Clamp constant: max real-time gap counted by a single tick. Chosen at 2000 ms —
|
||||
// comfortably above a normal client poll interval (~1 s), so active play advances
|
||||
// ~real time × scale; small enough that one stale read after an absence moves game
|
||||
// time by at most 2 s × scale (≈ 33 min even at max scale 1000). The sim therefore
|
||||
// only meaningfully progresses while actively polled.
|
||||
// Clamp constant: max real-time gap counted by a single tick. Chosen at 2000 ms — comfortably above
|
||||
// both the client poll interval (~1 s) and the background-tick interval, so active play advances
|
||||
// ~real time × scale; small enough that one stale read after an absence moves game time by at most
|
||||
// 2 s × scale.
|
||||
export const MAX_TICK_ELAPSED_MS = 2_000;
|
||||
|
||||
export const MIN_TIME_SCALE = 1;
|
||||
export const MAX_TIME_SCALE = 1000; // top of the slider ladder (v0.14.0)
|
||||
// ISS-117: the fixed world rate — re-exported here so server code and tests have one familiar home.
|
||||
export { WORLD_TIME_SCALE } from '@/lib/worldClock';
|
||||
|
||||
// Reputation gain per delivered package: BASE + PER_KM × great-circle km, rounded
|
||||
// to 2 decimals (reputation is REAL). A short hop (~300 km) earns ~1.15 rep, a
|
||||
@@ -43,11 +43,6 @@ export function reputationGainFor(km: number): number {
|
||||
return Math.round((REP_BASE + REP_PER_KM * km) * 100) / 100;
|
||||
}
|
||||
|
||||
export interface SimControlsInput {
|
||||
timeScale?: number;
|
||||
paused?: boolean;
|
||||
}
|
||||
|
||||
// Serialize ticks across concurrent requests (Next.js route handlers run in the
|
||||
// same process): each tick re-reads sim_state after the previous one wrote it, so
|
||||
// no advance is ever applied twice.
|
||||
@@ -63,23 +58,36 @@ function withLock<T>(fn: () => Promise<T>): Promise<T> {
|
||||
|
||||
// --- Tick core (takes a GameDb so unit tests can inject their own instance) ---
|
||||
|
||||
// ISS-117: idle-pause decision — pure, so unit tests feed it synthetic fleets. The world clock
|
||||
// advances only while something is happening: at least one plane flying OR in repair. A fully
|
||||
// grounded fleet freezes the clock (and with it expiries/spawns) until a dispatch or repair starts.
|
||||
export function shouldAdvanceTime(planes: Array<{ status: string }>): { advance: boolean; flying: number; repairing: number } {
|
||||
let flying = 0;
|
||||
let repairing = 0;
|
||||
for (const p of planes) {
|
||||
if (p.status === 'flying') flying++;
|
||||
else if (p.status === 'repairing') repairing++;
|
||||
}
|
||||
return { advance: flying > 0 || repairing > 0, flying, repairing };
|
||||
}
|
||||
|
||||
export async function tickOnce(inst: GameDb): Promise<schema.SimStateRow> {
|
||||
const rows = await inst.db.select().from(schema.simState);
|
||||
const sim = rows[0];
|
||||
if (!sim) throw new Error('sim_state row missing');
|
||||
|
||||
const nowMs = Date.now();
|
||||
// ISS-117: frozen while nothing is happening (see shouldAdvanceTime). lastRealTickMs still
|
||||
// tracks real time, so a takeoff resumes cleanly with no catch-up jump for the idle duration.
|
||||
const planeRows = await inst.db.select().from(schema.planes);
|
||||
const { advance } = shouldAdvanceTime(planeRows.map((p) => ({ status: p.status })));
|
||||
const elapsed = Math.max(0, nowMs - sim.lastRealTickMs);
|
||||
// While paused the clock is frozen; lastRealTickMs still tracks real time so
|
||||
// unpausing resumes cleanly with no catch-up jump for the pause duration.
|
||||
const advanceMs = sim.paused ? 0 : Math.min(elapsed, MAX_TICK_ELAPSED_MS) * sim.timeScale;
|
||||
const advanceMs = advance ? Math.min(elapsed, MAX_TICK_ELAPSED_MS) * sim.timeScale : 0;
|
||||
const clockMs = Math.round(sim.clockMs + advanceMs);
|
||||
|
||||
let landedThisTick = 0;
|
||||
if (advanceMs > 0) {
|
||||
await expirePackages(inst, clockMs);
|
||||
// ISS-057: remember the landings so the tick can slow down when a plane is left on ground.
|
||||
landedThisTick = await deliverPackages(inst, clockMs);
|
||||
await deliverPackages(inst, clockMs);
|
||||
// v0.39.0 (ISS-069): repairs whose gate has passed flip back to 'available' — runs even when
|
||||
// nothing landed this tick; BEFORE the spawns so a just-repaired plane gets coverage work too.
|
||||
await finishRepairs(inst, clockMs);
|
||||
@@ -89,25 +97,8 @@ export async function tickOnce(inst: GameDb): Promise<schema.SimStateRow> {
|
||||
await spawnCoveragePackages(inst, clockMs);
|
||||
}
|
||||
|
||||
const sets: Partial<Pick<schema.SimStateRow, 'clockMs' | 'lastRealTickMs' | 'timeScale'>> = {
|
||||
clockMs,
|
||||
lastRealTickMs: nowMs,
|
||||
};
|
||||
// Slow on landing (ISS-057): when ≥1 plane landed this tick and ANY plane is grounded
|
||||
// ('available') afterwards, drop the sim to MIN_TIME_SCALE — a just-landed plane counts, so
|
||||
// any real landing slows. A chained plane stays 'flying' via deliverPackages' auto-chain
|
||||
// branch, so a pure-chain tick with nothing grounded does NOT slow. Pause is manual-only now;
|
||||
// flyPlane restores lastSelectedTimeScale when the last grounded plane takes off. Arrival-
|
||||
// triggered by design: a grounded fleet at high scale is left alone (no idle-enforcement), and
|
||||
// a paused tick never processes landings (advanceMs === 0), so the trigger only fires on an
|
||||
// advancing tick — a manual speed change while planes sit grounded survives until the next landing.
|
||||
if (landedThisTick > 0) {
|
||||
const available = await inst.db.select().from(schema.planes).where(eq(schema.planes.status, 'available'));
|
||||
if (available.length >= 1) sets.timeScale = MIN_TIME_SCALE;
|
||||
}
|
||||
|
||||
// Persist lastRealTickMs even when nothing advanced — it is the tick anchor.
|
||||
await inst.db.update(schema.simState).set(sets);
|
||||
await inst.db.update(schema.simState).set({ clockMs, lastRealTickMs: nowMs });
|
||||
await persist(inst);
|
||||
const updated = (await inst.db.select().from(schema.simState))[0];
|
||||
if (!updated) throw new Error('sim_state row missing after tick');
|
||||
@@ -174,8 +165,7 @@ export async function finishRepairs(inst: GameDb, clockMs: number): Promise<numb
|
||||
// remaining fuel and the queue kept intact for a later dispatch.
|
||||
// Idempotent — a finalized plane either leaves the 'flying' state or starts a NEW
|
||||
// leg whose own arrival is in the future, so it can never be awarded twice.
|
||||
// Returns planes landed. NOTE: runs BEFORE tickOnce's slow-down check on purpose —
|
||||
// a chained plane is already 'flying' again here, so a pure-chain landing never slows the sim.
|
||||
// Returns planes landed.
|
||||
export async function deliverPackages(inst: GameDb, clockMs: number): Promise<number> {
|
||||
const [planeRows, packageRows] = await Promise.all([
|
||||
inst.db.select().from(schema.planes),
|
||||
@@ -423,6 +413,17 @@ export function tickNow(): Promise<schema.SimStateRow> {
|
||||
return withLock(async () => tickOnce(await getGameDb()));
|
||||
}
|
||||
|
||||
// ISS-117: the world clock runs even with nobody polling — a ~1 s interval drives the same locked
|
||||
// tick path as reads/actions. Started once at server boot from instrumentation.ts (Next ≥15); the
|
||||
// guard makes double-starts harmless (dev HMR reloads).
|
||||
let backgroundTimer: ReturnType<typeof setInterval> | null = null;
|
||||
export function startBackgroundTick(intervalMs = 1_000): void {
|
||||
if (backgroundTimer !== null) return;
|
||||
backgroundTimer = setInterval(() => {
|
||||
tickNow().catch((err) => console.error('flight: background tick failed', err));
|
||||
}, intervalMs);
|
||||
}
|
||||
|
||||
// Run a game action atomically with respect to ticks (v0.8.0): the clock is
|
||||
// advanced FIRST so validation and mutation see current game time, then fn runs —
|
||||
// all under the same promise lock as tickNow(), so no concurrent request can
|
||||
@@ -436,31 +437,17 @@ export function runAction<T>(fn: (inst: GameDb) => Promise<T>): Promise<T> {
|
||||
});
|
||||
}
|
||||
|
||||
// Tick first so the returned state reflects current time, then apply the new
|
||||
// controls. timeScale is clamped to [1, 1000]; validation of raw input happens in
|
||||
// the route handler (400 on non-number / non-boolean). ISS-057: posting a timeScale
|
||||
// ALSO records it as lastSelectedTimeScale — the resume target flyPlane restores when
|
||||
// the last grounded plane takes off. A {paused}-only post never touches it, so the
|
||||
// last manual intent wins without an extra flag.
|
||||
export function applyTimeControls(input: SimControlsInput): Promise<schema.SimStateRow> {
|
||||
// Test-hook backing (FLIGHT_TEST_HOOKS=1 only — see app/api/test/set-timescale/route.ts): set the
|
||||
// effective time scale under the same lock as ticks so a background tick can never interleave
|
||||
// between read and write. Input validation happens in the route; this trusts its number.
|
||||
export function setTestTimeScale(scale: number): Promise<schema.SimStateRow> {
|
||||
return withLock(async () => {
|
||||
const inst = await getGameDb();
|
||||
await tickOnce(inst);
|
||||
const sets: Partial<Pick<schema.SimStateRow, 'timeScale' | 'lastSelectedTimeScale' | 'paused'>> = {};
|
||||
if (input.timeScale !== undefined) {
|
||||
const scale = clampTimeScale(input.timeScale);
|
||||
sets.timeScale = scale;
|
||||
sets.lastSelectedTimeScale = scale;
|
||||
}
|
||||
if (input.paused !== undefined) sets.paused = input.paused;
|
||||
if (Object.keys(sets).length > 0) await inst.db.update(schema.simState).set(sets);
|
||||
await inst.db.update(schema.simState).set({ timeScale: scale });
|
||||
await persist(inst);
|
||||
const updated = (await inst.db.select().from(schema.simState))[0];
|
||||
if (!updated) throw new Error('sim_state row missing');
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
export function clampTimeScale(v: number): number {
|
||||
return Math.min(MAX_TIME_SCALE, Math.max(MIN_TIME_SCALE, v));
|
||||
}
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { MAX_SCALE, MIN_SCALE, TIME_SCALES, scaleToSlider, sliderToScale } from './timeScale';
|
||||
|
||||
const STEPS = TIME_SCALES.length - 1; // 9 intervals across the 10 ladder positions (v0.14.0)
|
||||
|
||||
describe('sliderToScale', () => {
|
||||
it('is exact at the endpoints (0 → 1×, 1 → 1000×)', () => {
|
||||
expect(sliderToScale(0)).toBe(MIN_SCALE);
|
||||
expect(sliderToScale(1)).toBe(MAX_SCALE);
|
||||
});
|
||||
|
||||
it('maps each of the 10 positions to the ladder', () => {
|
||||
const expected = [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000];
|
||||
for (let i = 0; i < TIME_SCALES.length; i++) {
|
||||
expect(sliderToScale(i / STEPS)).toBe(expected[i]);
|
||||
}
|
||||
});
|
||||
|
||||
it('is monotonic non-decreasing across the whole range', () => {
|
||||
let prev = sliderToScale(0);
|
||||
for (let i = 1; i <= 2000; i++) {
|
||||
const s = sliderToScale(i / 2000);
|
||||
expect(s).toBeGreaterThanOrEqual(prev);
|
||||
prev = s;
|
||||
}
|
||||
});
|
||||
|
||||
it('only ever returns a ladder value', () => {
|
||||
for (let i = 0; i <= 2000; i++) {
|
||||
expect(TIME_SCALES).toContain(sliderToScale(i / 2000));
|
||||
}
|
||||
});
|
||||
|
||||
it('clamps out-of-range and non-finite input', () => {
|
||||
expect(sliderToScale(-0.5)).toBe(MIN_SCALE);
|
||||
expect(sliderToScale(1.5)).toBe(MAX_SCALE);
|
||||
expect(sliderToScale(NaN)).toBe(MIN_SCALE);
|
||||
});
|
||||
});
|
||||
|
||||
describe('scaleToSlider', () => {
|
||||
it('is exact at the endpoints (1× → 0, 1000× → 1)', () => {
|
||||
expect(scaleToSlider(1)).toBe(0);
|
||||
expect(scaleToSlider(1000)).toBe(1);
|
||||
});
|
||||
|
||||
it('places each ladder value on its own position', () => {
|
||||
for (let i = 0; i < TIME_SCALES.length; i++) {
|
||||
expect(scaleToSlider(TIME_SCALES[i])).toBeCloseTo(i / STEPS, 12);
|
||||
}
|
||||
});
|
||||
|
||||
it('stays within [0, 1] for in-range scales', () => {
|
||||
for (let s = MIN_SCALE; s <= MAX_SCALE; s++) {
|
||||
const t = scaleToSlider(s);
|
||||
expect(t).toBeGreaterThanOrEqual(0);
|
||||
expect(t).toBeLessThanOrEqual(1);
|
||||
}
|
||||
});
|
||||
|
||||
it('clamps out-of-range and non-finite input', () => {
|
||||
expect(scaleToSlider(0)).toBe(0);
|
||||
expect(scaleToSlider(-3)).toBe(0);
|
||||
expect(scaleToSlider(1001)).toBe(1); // above the ladder top → clamped to 1000× → t=1
|
||||
expect(scaleToSlider(NaN)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('round-trip', () => {
|
||||
it('sliderToScale(scaleToSlider(s)) === s for every ladder value', () => {
|
||||
for (const s of TIME_SCALES) {
|
||||
expect(sliderToScale(scaleToSlider(s))).toBe(s);
|
||||
}
|
||||
});
|
||||
|
||||
it('maps off-ladder scales to the nearest ladder step by log distance', () => {
|
||||
expect(sliderToScale(scaleToSlider(3))).toBe(2); // ln 3 ≈ 1.10 → closer to 2 (ln ≈ 0.69) than 5 (ln ≈ 1.61)
|
||||
expect(sliderToScale(scaleToSlider(60))).toBe(50); // legacy max from the v0.9.x era sits between 50 and 100, nearer 50
|
||||
expect(sliderToScale(scaleToSlider(200))).toBe(250); // ln 200 ≈ 5.30 → closer to 250 (ln ≈ 5.52) than 100 (ln ≈ 4.61)
|
||||
});
|
||||
});
|
||||
@@ -1,33 +0,0 @@
|
||||
// Pure mapping helpers for the time-scale slider (v0.9.2, values reworked in v0.14.0) — no
|
||||
// game logic, unit-testable in node. The slider has 10 discrete positions on a mixed
|
||||
// ×2/×2.5 ladder: 1× → 2× → 5× → 10× → 25× → 50× → 100× → 250× → 500× → 1000×, so each
|
||||
// step roughly doubles the speed (matching POST /api/sim's clamp range [1, 1000]).
|
||||
|
||||
export const TIME_SCALES = [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000] as const;
|
||||
export const MIN_SCALE: number = TIME_SCALES[0];
|
||||
export const MAX_SCALE: number = TIME_SCALES[TIME_SCALES.length - 1];
|
||||
|
||||
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
|
||||
|
||||
// t → scale: the position maps to the nearest ladder step. Exact at the endpoints:
|
||||
// sliderToScale(0) === 1, sliderToScale(1) === 1000.
|
||||
export function sliderToScale(t: number): number {
|
||||
const tt = clamp(Number.isFinite(t) ? t : 0, 0, 1);
|
||||
return TIME_SCALES[clamp(Math.round(tt * (TIME_SCALES.length - 1)), 0, TIME_SCALES.length - 1)];
|
||||
}
|
||||
|
||||
// scale → t: the nearest ladder position by log distance. Exact at the endpoints:
|
||||
// scaleToSlider(1) === 0, scaleToSlider(1000) === 1; round-trips every value in TIME_SCALES.
|
||||
export function scaleToSlider(scale: number): number {
|
||||
const s = clamp(Number.isFinite(scale) ? scale : MIN_SCALE, MIN_SCALE, MAX_SCALE);
|
||||
let best = 0;
|
||||
let bestDist = Infinity;
|
||||
for (let i = 0; i < TIME_SCALES.length; i++) {
|
||||
const d = Math.abs(Math.log(s) - Math.log(TIME_SCALES[i]));
|
||||
if (d < bestDist) {
|
||||
bestDist = d;
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
return best / (TIME_SCALES.length - 1);
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { fetchState } from './useGameState';
|
||||
|
||||
const SNAPSHOT = {
|
||||
account: { cash: 20_000, reputation: 10 },
|
||||
simState: { clockMs: 1_750_000_000_000, timeScale: 1, paused: false },
|
||||
simState: { clockMs: 1_750_000_000_000 },
|
||||
planes: [],
|
||||
packages: [],
|
||||
};
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ export async function fetchState(): Promise<StateSnapshot> {
|
||||
(window as unknown as Record<string, unknown>).__flightLastSnapshot = {
|
||||
planeIds: snapshot.planes.map((p) => p.id),
|
||||
cash: snapshot.account.cash,
|
||||
timeScale: snapshot.simState.timeScale,
|
||||
clockMs: snapshot.simState.clockMs,
|
||||
at: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
+14
-18
@@ -1,49 +1,45 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { advanceSimClock, type SimClockAnchor } from './useSimClock';
|
||||
import { WORLD_TIME_SCALE } from './worldClock';
|
||||
|
||||
// ISS-007 (v0.16.1) — the pure extrapolation core of lib/useSimClock.ts. The hook itself is a
|
||||
// thin setInterval + re-sync wrapper covered by e2e (panes.spec.ts "ticks smoothly between polls");
|
||||
// this suite pins the math: game time advances real-time × timeScale, frozen while paused.
|
||||
// this suite pins the math: game time advances real-time × WORLD_TIME_SCALE, frozen while idle.
|
||||
|
||||
const anchor = (over: Partial<SimClockAnchor> = {}): SimClockAnchor => ({
|
||||
clockMs: 1_750_000_000_000,
|
||||
at: 1_000_000,
|
||||
timeScale: 1,
|
||||
paused: false,
|
||||
advancing: true,
|
||||
...over,
|
||||
});
|
||||
|
||||
describe('advanceSimClock', () => {
|
||||
it('advances by exactly elapsed real-time × timeScale while running', () => {
|
||||
expect(advanceSimClock(anchor(), 1_001_000)).toBe(1_750_000_000_000 + 1_000); // scale 1: 1 s real = 1 s game
|
||||
expect(advanceSimClock(anchor({ timeScale: 25 }), 1_002_500)).toBe(1_750_000_000_000 + 62_500);
|
||||
// The e2e scenario: scale 1000, 2.5 s real → 2 500 game seconds.
|
||||
expect(advanceSimClock(anchor({ timeScale: 1000 }), 1_002_500)).toBe(1_750_000_000_000 + 2_500_000);
|
||||
it('advances by exactly elapsed real-time × WORLD_TIME_SCALE while running', () => {
|
||||
expect(advanceSimClock(anchor(), 1_001_000)).toBe(1_750_000_000_000 + 1_000 * WORLD_TIME_SCALE);
|
||||
// The e2e scenario: ~2.6 s real at the fixed world rate.
|
||||
expect(advanceSimClock(anchor(), 1_002_600)).toBe(1_750_000_000_000 + 2_600 * WORLD_TIME_SCALE);
|
||||
});
|
||||
|
||||
it('returns the anchor value exactly at zero elapsed', () => {
|
||||
expect(advanceSimClock(anchor({ timeScale: 1000 }), 1_000_000)).toBe(1_750_000_000_000);
|
||||
expect(advanceSimClock(anchor(), 1_000_000)).toBe(1_750_000_000_000);
|
||||
});
|
||||
|
||||
it('is frozen while paused regardless of elapsed or scale', () => {
|
||||
const a = anchor({ timeScale: 1000, paused: true });
|
||||
it('is frozen while idle regardless of elapsed time', () => {
|
||||
const a = anchor({ advancing: false });
|
||||
expect(advanceSimClock(a, 1_000_000)).toBe(1_750_000_000_000);
|
||||
expect(advanceSimClock(a, 2_000_000)).toBe(1_750_000_000_000); // a full second later — still frozen
|
||||
});
|
||||
|
||||
it('clamps to the anchor value when nowMs is before the anchor (clock skew), never backwards', () => {
|
||||
expect(advanceSimClock(anchor({ timeScale: 1000 }), 999_999)).toBe(1_750_000_000_000);
|
||||
expect(advanceSimClock(anchor({ paused: true }), 999_999)).toBe(1_750_000_000_000);
|
||||
expect(advanceSimClock(anchor(), 999_999)).toBe(1_750_000_000_000);
|
||||
expect(advanceSimClock(anchor({ advancing: false }), 999_999)).toBe(1_750_000_000_000);
|
||||
});
|
||||
|
||||
it('mirrors the server tick model (tickOnce): advance = elapsed × timeScale while actively polled', () => {
|
||||
it('mirrors the server tick model (tickOnce): advance = elapsed × WORLD_TIME_SCALE while actively polled', () => {
|
||||
// lib/sim/engine.ts: clockMs += min(now − lastRealTickMs, MAX_TICK_ELAPSED_MS) × timeScale.
|
||||
// For gaps under the 2 s clamp the client extrapolation is exactly the server's own formula.
|
||||
const scale = 50;
|
||||
for (const gap of [1, 250, 999, 1_999]) {
|
||||
expect(advanceSimClock(anchor({ timeScale: scale }), 1_000_000 + gap)).toBe(
|
||||
1_750_000_000_000 + gap * scale,
|
||||
);
|
||||
expect(advanceSimClock(anchor(), 1_000_000 + gap)).toBe(1_750_000_000_000 + gap * WORLD_TIME_SCALE);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
+19
-25
@@ -2,57 +2,51 @@
|
||||
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { StateSnapshot } from './game/state';
|
||||
import { WORLD_TIME_SCALE } from './worldClock';
|
||||
|
||||
// ISS-007 (v0.16.1): the sim clock ticks smoothly on the CLIENT between polls instead of
|
||||
// jumping once per snapshot. The server's authoritative rate is exactly real-time × timeScale
|
||||
// jumping once per snapshot. The server's authoritative rate is exactly real-time × scale
|
||||
// (tickOnce in lib/sim/engine.ts: advance = min(elapsed, MAX_TICK_ELAPSED_MS) × timeScale), so
|
||||
// client-side extrapolation mirrors the server's own model. Every new snapshot re-anchors to
|
||||
// server truth, bounding any drift by network latency only.
|
||||
// server truth, bounding any drift by network latency only. ISS-117 (v0.52.0): the scale is the
|
||||
// fixed WORLD_TIME_SCALE and the clock freezes while nothing is happening — mirroring the
|
||||
// server's idle-pause instead of a player-controlled pause.
|
||||
|
||||
export interface SimClockAnchor {
|
||||
// Server truth at anchor time — the snapshot's simState.clockMs.
|
||||
clockMs: number;
|
||||
// Date.now() when that snapshot was received.
|
||||
at: number;
|
||||
timeScale: number;
|
||||
paused: boolean;
|
||||
// Whether the world clock is advancing (any plane flying or in repair).
|
||||
advancing: boolean;
|
||||
}
|
||||
|
||||
// Pure core of the extrapolation — mirrors tickOnce: while running, game time advances by
|
||||
// real-time × timeScale; while paused it is frozen (advance 0). nowMs before `at` clamps to
|
||||
// Pure core of the extrapolation — mirrors tickOnce: while advancing, game time advances by
|
||||
// real-time × WORLD_TIME_SCALE; while idle it is frozen (advance 0). nowMs before `at` clamps to
|
||||
// the anchor value instead of going backwards. Unit-testable in node.
|
||||
export function advanceSimClock(anchor: SimClockAnchor, nowMs: number): number {
|
||||
if (anchor.paused) return anchor.clockMs;
|
||||
return anchor.clockMs + Math.max(0, nowMs - anchor.at) * anchor.timeScale;
|
||||
if (!anchor.advancing) return anchor.clockMs;
|
||||
return anchor.clockMs + Math.max(0, nowMs - anchor.at) * WORLD_TIME_SCALE;
|
||||
}
|
||||
|
||||
// ~10 fps display refresh — smooth for a seconds-precision wall clock without busy re-renders.
|
||||
const DISPLAY_TICK_MS = 100;
|
||||
|
||||
export interface SimClockControls {
|
||||
// EFFECTIVE controls (optimistic pending scale / current pause), not the snapshot's:
|
||||
// UI changes take effect on click/drag without waiting for a confirming snapshot.
|
||||
timeScale: number;
|
||||
paused: boolean;
|
||||
}
|
||||
|
||||
// Returns the display clockMs to render, or null until the first snapshot arrives.
|
||||
export function useSimClock(snapshot: StateSnapshot | null, controls: SimClockControls): number | null {
|
||||
export function useSimClock(snapshot: StateSnapshot | null): number | null {
|
||||
const anchorRef = useRef<SimClockAnchor | null>(null);
|
||||
const [displayMs, setDisplayMs] = useState<number | null>(null);
|
||||
|
||||
// Re-sync on every snapshot AND effective-control change: snap to server truth. The snapshot
|
||||
// object is fresh per poll (useGameState), so this runs once per poll cycle as well.
|
||||
// Re-sync on every snapshot: snap to server truth. The snapshot object is fresh per poll
|
||||
// (useGameState), so this runs once per poll cycle as well.
|
||||
useEffect(() => {
|
||||
if (!snapshot) return;
|
||||
anchorRef.current = {
|
||||
clockMs: snapshot.simState.clockMs,
|
||||
at: Date.now(),
|
||||
timeScale: controls.timeScale,
|
||||
paused: controls.paused,
|
||||
};
|
||||
// Mirror of the server's shouldAdvanceTime (lib/sim/engine.ts): frozen while no plane is
|
||||
// flying or in repair. One line on purpose — keep it in sync with that function.
|
||||
const advancing = snapshot.planes.some((p) => p.status === 'flying' || p.status === 'repairing');
|
||||
anchorRef.current = { clockMs: snapshot.simState.clockMs, at: Date.now(), advancing };
|
||||
setDisplayMs(advanceSimClock(anchorRef.current, Date.now()));
|
||||
}, [snapshot, controls.timeScale, controls.paused]);
|
||||
}, [snapshot]);
|
||||
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => {
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// ISS-117 (v0.52.0): the world clock runs at a fixed rate — no player-facing time controls.
|
||||
// Server-side the effective scale lives in the sim_state row (seeded to this value); client-side
|
||||
// lib/useSimClock.ts extrapolates between polls at this same constant, so keep them in sync here.
|
||||
export const WORLD_TIME_SCALE = 24;
|
||||
Reference in New Issue
Block a user