Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 130 additions & 0 deletions apps/web/e2e/units.e2e.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// End-to-end test of the sprite layers: zoomed out the map shows overlays only; zoomed in, resource
// objects, roads, a hall at each capital and the walking villagers are drawn, and the villagers move
// while time runs. Screenshots (E2E_SHOTS=<directory>) are for a human to look at.
//
// pnpm --filter @sovereign/web e2e:units
//
// It starts the Vite dev server itself and needs Chromium. The world is 2000 x 2000, so this takes a
// few minutes in software GL.
import { chromium } from 'playwright'
import {
SOFTWARE_GL,
centerOn,
firstNationPoint,
readCamera,
startDevServer,
withTimeout
} from './support.mjs'

const PORT = 5198
const SEED = 1337
const viewport = { width: 1280, height: 800 }

const stats = (page) =>
page.$eval('canvas', (c) => ({
sprites: c.dataset.sprites,
roads: Number(c.dataset.spriteRoads),
resources: Number(c.dataset.spriteResources),
halls: Number(c.dataset.spriteHalls),
units: Number(c.dataset.spriteUnits)
}))

async function main() {
const problems = []
const fail = (message) => problems.push(message)
const nation = firstNationPoint(SEED)
const { url, stop } = await startDevServer(PORT)
const browser = await chromium.launch({ args: SOFTWARE_GL })
try {
const page = await browser.newPage({ viewport })
page.on('pageerror', (error) => fail(`pageerror: ${error.message}`))
page.on('console', (message) => {
if (message.type() === 'error') fail(`console.error: ${message.text()}`)
})
await withTimeout(page.goto(url), 30_000, 'load the page')
await page.fill('#seed-input', String(SEED))
await page.click('text=New World')
await withTimeout(
page.waitForFunction(() => document.querySelector('.time-controls') !== null, null, {
timeout: 240_000
}),
245_000,
'the world and its time controls'
)
await page.waitForTimeout(800)

// far out: overlays only
let s = await stats(page)
if (s.sprites !== 'off') fail(`zoomed out, sprites should be off, got ${s.sprites}`)
if (s.units !== 0 || s.resources !== 0) fail('zoomed out, no sprites should be made')

// centre the first nation, then zoom in with the + button
const drag = async (dx, dy) => {
const x = viewport.width / 2
const y = viewport.height / 2
await page.mouse.move(x, y)
await page.mouse.down()
await page.mouse.move(x + dx / 2, y + dy / 2, { steps: 4 })
await page.mouse.move(x + dx, y + dy, { steps: 4 })
await page.mouse.up()
await page.waitForTimeout(100)
}
if (!(await centerOn(page, nation, drag, viewport, 2)))
fail('could not centre the first nation')
for (let i = 0; i < 12 && (await readCamera(page)).zoom < 5; i += 1) {
await page.click('button[aria-label="Zoom in"]')
await page.waitForTimeout(150)
}
await centerOn(page, nation, drag, viewport, 2)
await page.waitForTimeout(600)
const zoom = (await readCamera(page)).zoom
if (zoom < 2.5) fail(`could not zoom in far enough (zoom ${zoom})`)

s = await stats(page)
if (s.sprites !== 'on') fail(`zoomed in, sprites should be on, got ${s.sprites}`)
if (!(s.units > 0)) fail('zoomed in on a capital, there should be villagers')
if (!(s.halls >= 1)) fail('zoomed in on a capital, its hall should be drawn')
if (!(s.resources > 0)) fail('zoomed in on land, there should be resource objects')
if (process.env.E2E_SHOTS)
await page.screenshot({ path: `${process.env.E2E_SHOTS}/units-still.png` })

// time runs, and the villagers walk: the picture changes
const before = await page.screenshot({ clip: { x: 340, y: 150, width: 600, height: 500 } })
await page.click('.time-controls__play')
await page.waitForTimeout(3000)
const after = await page.screenshot({ clip: { x: 340, y: 150, width: 600, height: 500 } })
if (before.equals(after))
fail('the picture did not change while time ran: villagers did not move')
if (process.env.E2E_SHOTS)
await page.screenshot({ path: `${process.env.E2E_SHOTS}/units-running.png` })

// zooming back out takes the sprites away
for (let i = 0; i < 14 && (await readCamera(page)).zoom > 1; i += 1) {
await page.click('button[aria-label="Zoom out"]')
await page.waitForTimeout(100)
}
s = await stats(page)
if (s.sprites !== 'off') fail('zoomed back out, sprites should be off again')
await withTimeout(
page.evaluate(() => document.title),
5_000,
'the page being alive'
)
await page.close()
} finally {
await browser.close()
stop()
}
if (problems.length > 0) {
console.error(`FAIL\n${problems.map((p) => ` - ${p}`).join('\n')}`)
process.exit(1)
}
console.log(
'PASS: sprites gate on zoom, draw resources, halls and villagers, and the villagers move'
)
}

main().catch((error) => {
console.error(error)
process.exit(1)
})
3 changes: 2 additions & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"test": "vitest run --passWithNoTests",
"e2e": "node e2e/strict-mode.e2e.mjs",
"e2e:mobile": "node e2e/mobile.e2e.mjs",
"e2e:time": "node e2e/time.e2e.mjs"
"e2e:time": "node e2e/time.e2e.mjs",
"e2e:units": "node e2e/units.e2e.mjs"
},
"dependencies": {
"@sovereign/config": "workspace:*",
Expand Down
11 changes: 11 additions & 0 deletions apps/web/src/MapView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,16 @@ const MapView: React.FC = () => {

for (const name of LAYER_NAMES) renderer.setLayer(name, ready.layers[name], width, height)

renderer.setNationColors(ready.snapshot.nations.map((n) => n.color))
renderer.setSpriteWorld({
width,
height,
resources: ready.fields.resources,
roads: ready.roads,
halls: ready.snapshot.nations.map((n) => ({ tile: n.capital, color: n.color }))
})
renderer.setUnits(ready.units)

mapSizeRef.current = { width, height, tileSize }
biomeIdsRef.current = ready.fields.biomeIds
baseLayerRef.current = ready.layers.biome
Expand Down Expand Up @@ -443,6 +453,7 @@ const MapView: React.FC = () => {
timestep: store.timestep,
saturated: ticked.saturated
})
rendererRef.current?.setUnits(ticked.units)
if (ticked.claims > 0) {
nationsRef.current = ticked.nations
store.setNations(ticked.nations)
Expand Down
7 changes: 7 additions & 0 deletions apps/web/src/host/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type {
NationSnapshot,
ResourceSlots,
StrategicPoint,
UnitSnapshot,
WorldSnapshot
} from '@sovereign/contracts'
import type { LayerName } from '@sovereign/renderer'
Expand Down Expand Up @@ -46,6 +47,10 @@ export interface WorldReady {
/** Every overlay as RGBA pixels, `width * height * 4` bytes. */
layers: Record<LayerName, Uint8ClampedArray>
fields: WorldFields
/** One byte per tile for the road sprites: 0 for none, else `16 | sides` (see `roadMaskFromRoutes`). */
roads: Uint8Array
/** Where every unit is. */
units: UnitSnapshot
}

/** The world after some ticks. */
Expand All @@ -64,6 +69,8 @@ export interface WorldTicked {
ownership?: Uint8Array
/** The political overlay as RGBA pixels, when it was asked for and is out of date. */
political?: Uint8ClampedArray
/** Where every unit is now (sent every time: they walk). */
units: UnitSnapshot
}

export type WorldResponse =
Expand Down
18 changes: 15 additions & 3 deletions apps/web/src/host/readyMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ import {
humidityRgba,
politicalRgba,
resourceRgba,
roadMaskFromRoutes,
strategicRgba,
temperatureRgba,
type LayerName,
type PoliticalStyle
} from '@sovereign/renderer'
import type { ResourceSlot } from '@sovereign/contracts'
import type { ResourceSlot, UnitSnapshot } from '@sovereign/contracts'
import type { World } from '@sovereign/simulation'
import type { WorldFields, WorldReady } from './protocol'

Expand All @@ -36,6 +37,11 @@ function slotArrays(slot: ResourceSlot): Uint8Array[] {
return [slot.type, slot.richness, slot.stock]
}

/** The buffers of a unit snapshot, for a transfer list. */
export function unitBuffers(units: UnitSnapshot): ArrayBuffer[] {
return [units.id, units.kind, units.owner, units.x, units.y].map((a) => a.buffer as ArrayBuffer)
}

export function buildReady(world: World, style: PoliticalStyle): Built {
const t = world.terrain
const { width, height } = t
Expand Down Expand Up @@ -72,20 +78,26 @@ export function buildReady(world: World, style: PoliticalStyle): Built {
ownership: world.map.ownership.slice()
}

const roads = roadMaskFromRoutes(t.routes, width, height)
const units = world.unitPositions()
const { resources, ...flat } = fields
const transfer = [
...Object.values(layers),
...Object.values(flat),
...slotArrays(resources.surface),
...slotArrays(resources.ground)
...slotArrays(resources.ground),
roads
].map((array) => array.buffer as ArrayBuffer)
transfer.push(...unitBuffers(units))
return {
message: {
type: 'ready',
snapshot: world.snapshot(),
strategicPoints: t.strategicPoints.map((p) => ({ ...p })),
layers,
fields
fields,
roads,
units
},
transfer
}
Expand Down
6 changes: 4 additions & 2 deletions apps/web/src/host/tickRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import { biomeRgba, politicalRgba, type PoliticalStyle } from '@sovereign/renderer'
import type { World } from '@sovereign/simulation'
import type { RunOptions, WorldTicked } from './protocol'
import { unitBuffers } from './readyMessage'

export interface Ticked {
message: WorldTicked
Expand Down Expand Up @@ -62,9 +63,10 @@ export class TickRunner {
time: world.clock.time,
claims,
saturated: world.saturated,
nations: world.snapshot().nations
nations: world.snapshot().nations,
units: world.unitPositions()
}
const transfer: ArrayBuffer[] = []
const transfer: ArrayBuffer[] = unitBuffers(message.units)

const due =
options.flush === true || world.saturated || this.now() - this.lastSent >= this.minOverlayMs
Expand Down
3 changes: 2 additions & 1 deletion apps/web/src/state/persistence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ const DB_NAME = 'sovereign'
// 4: engine save format 3 (every tile has two resource slots with richness and stock); older records are dropped.
// 5: engine save format 4 (a route network, and the profile of each nation's land); older records are dropped.
// 6: engine save format 5 (nations own provinces, with expansion points); older records are dropped.
const DB_VERSION = 6
// 7: engine save format 6 (the world has units: the entity store is saved); older records are dropped.
const DB_VERSION = 7
const STORE_NAME = 'saves'

/* ------------------------------------------------------------------ */
Expand Down
38 changes: 34 additions & 4 deletions apps/web/tests/readyMessage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ import {
humidityRgba,
politicalRgba,
resourceRgba,
roadMaskFromRoutes,
strategicRgba,
temperatureRgba
} from '@sovereign/renderer'
import { World } from '@sovereign/simulation'
import type { ResourceSlot } from '@sovereign/contracts'
import type { ResourceSlot, UnitSnapshot } from '@sovereign/contracts'
import { buildReady } from '../src/host/readyMessage'
import type { WorldFields } from '../src/host/protocol'

Expand Down Expand Up @@ -46,6 +47,14 @@ function fieldArrays(fields: WorldFields): Array<Float32Array | Uint8Array> {
]
}

const unitArrays = (u: UnitSnapshot): Array<Uint32Array | Uint8Array | Float32Array> => [
u.id,
u.kind,
u.owner,
u.x,
u.y
]

const make = (): World => World.create({ seed: 21, config: SMALL })

describe('buildReady', () => {
Expand Down Expand Up @@ -134,10 +143,31 @@ describe('buildReady', () => {
for (const array of fieldArrays(message.fields)) expect(own.has(array.buffer)).toBe(false)
})

it('carries the units as the world places them, in tiles', () => {
expect(message.units).toEqual(world.unitPositions())
expect(message.units.count).toBeGreaterThan(0)
})

it('carries a road byte per tile, made from the routes', () => {
expect(message.roads).toEqual(roadMaskFromRoutes(world.terrain.routes, width, height))
expect(message.roads.length).toBe(width * height)
expect(message.roads.some((v) => v !== 0)).toBe(true)
})

it("sends the units' own copies, never the engine's arrays", () => {
const again = world.unitPositions()
for (const key of ['id', 'kind', 'owner', 'x', 'y'] as const) {
expect(message.units[key].buffer).not.toBe(again[key].buffer)
}
})

it('lists every buffer to transfer exactly once, and nothing else', () => {
const buffers = [...Object.values(message.layers), ...fieldArrays(message.fields)].map(
(a) => a.buffer
)
const buffers = [
...Object.values(message.layers),
...fieldArrays(message.fields),
message.roads,
...unitArrays(message.units)
].map((a) => a.buffer)
expect(transfer.length).toBe(buffers.length)
expect(new Set(transfer).size).toBe(transfer.length)
for (const b of buffers) expect(transfer).toContain(b)
Expand Down
11 changes: 10 additions & 1 deletion apps/web/tests/simulationHost.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,16 @@ const TICKED: WorldTicked = {
time: 10,
claims: 2,
saturated: false,
nations: []
nations: [],
units: {
tick: 10,
count: 0,
id: new Uint32Array(0),
kind: new Uint8Array(0),
owner: new Uint8Array(0),
x: new Float32Array(0),
y: new Float32Array(0)
}
}

const setup = (): { host: SimulationHost; worker: FakeWorker } => {
Expand Down
Loading
Loading