diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..53efbd7 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +.git +.local +.tools +node_modules +client/dist +assets +test-results +playwright-report +*.log +*.exe diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..caba36f --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +* text=auto eol=lf +*.ps1 text eol=crlf +*.glb binary +*.blend binary +*.png binary +*.exe binary diff --git a/.gitea/workflows/build.yaml b/.gitea/workflows/build.yaml new file mode 100644 index 0000000..6d904a4 --- /dev/null +++ b/.gitea/workflows/build.yaml @@ -0,0 +1,82 @@ +name: Verify, publish, and promote +on: + push: + branches: [master, main] + pull_request: + +jobs: + verify: + runs-on: ubuntu-latest + services: + postgres: + image: postgres:17-alpine + env: + POSTGRES_USER: aeternalis + POSTGRES_PASSWORD: ci-test-only + POSTGRES_DB: aeternalis_test + options: >- + --health-cmd "pg_isready -U aeternalis -d aeternalis_test" + --health-interval 5s --health-timeout 5s --health-retries 10 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: { node-version: "24", cache: npm } + - uses: actions/setup-go@v5 + with: { go-version-file: server/go.mod, cache-dependency-path: server/go.sum } + - run: npm ci --no-fund + - run: npm run test:contracts && npm run check && npm run build + - name: Go tests, race detector, and PostgreSQL integration + working-directory: server + env: + TEST_DATABASE_URL: postgres://aeternalis:ci-test-only@postgres:5432/aeternalis_test?sslmode=disable + run: go test -race -count=1 ./... + - name: Go static analysis + working-directory: server + run: go vet ./... + - run: npx playwright install --with-deps chromium + - run: npm run test:e2e + - uses: azure/setup-helm@v4.3.0 + - run: helm lint deploy/chart && helm template aeternalis deploy/chart > /tmp/aeternalis.yaml + + publish: + if: gitea.event_name == 'push' + needs: verify + runs-on: ubuntu-latest + outputs: + digest: ${{ steps.build.outputs.digest }} + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ vars.HARBOR_HOST }} + username: ${{ secrets.HARBOR_USERNAME }} + password: ${{ secrets.HARBOR_PASSWORD }} + - uses: docker/build-push-action@v6 + id: build + with: + context: . + push: true + tags: ${{ vars.HARBOR_HOST }}/${{ vars.HARBOR_PROJECT }}/aeternalis:${{ gitea.sha }} + provenance: true + sbom: true + + promote: + if: gitea.event_name == 'push' && vars.GITOPS_REPOSITORY != '' + needs: publish + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: { node-version: "24" } + - run: npm ci --no-fund + - name: Update GitOps image digest + env: + GITOPS_REPOSITORY: ${{ vars.GITOPS_REPOSITORY }} + GITOPS_BRANCH: ${{ vars.GITOPS_BRANCH }} + GITOPS_VALUES_FILE: ${{ vars.GITOPS_VALUES_FILE }} + GITOPS_USERNAME: ${{ secrets.GITOPS_USERNAME }} + GITOPS_TOKEN: ${{ secrets.GITOPS_TOKEN }} + IMAGE_REPOSITORY: ${{ vars.HARBOR_HOST }}/${{ vars.HARBOR_PROJECT }}/aeternalis + IMAGE_DIGEST: ${{ needs.publish.outputs.digest }} + run: node tools/promote-gitops.mjs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9ccefd4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +node_modules/ +client/dist/ +.local/ +.tools/ +*.exe +*.log +test-results/ +playwright-report/ +.env +!*.example diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..9c64a1a --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,10 @@ +# Aeternalis + +Read `planning/VISION.md` and `docs/ARCHITECTURE.md` before changing systems. +Go owns gameplay; the browser sends intents only. One process owns one world. +Never weaken permanent-death, daily-time-limit, or survivor-transfer invariants. +Protocol bindings are generated from `schemas/protocol.json` with `npm run generate`. +Game tuning lives in `server/content/balance.yaml`. Tests must cover lifecycle changes. +Run `npm run check`, `npm run build`, and `go test ./...` in `server`. +Production must require PostgreSQL and OIDC. Development auth is loopback-only. +Do not increase the documented tested capacity without a representative load test. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..1650f71 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +FROM node:24-bookworm-slim AS client +WORKDIR /src +COPY package*.json ./ +RUN npm ci --no-fund +COPY schemas ./schemas +COPY tools/generate-protocol.mjs ./tools/generate-protocol.mjs +COPY client ./client +COPY server/internal/protocol ./server/internal/protocol +RUN npm run test:contracts && npm run check && npm run build + +FROM golang:1.27.1-bookworm AS server +WORKDIR /src +COPY server/go.mod server/go.sum ./ +RUN go mod download +COPY server ./ +RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /world ./cmd/world + +FROM gcr.io/distroless/static-debian12:nonroot +COPY --from=server /world /world +COPY --from=client /src/client/dist /client +ENV APP_ENV=production LISTEN_ADDR=0.0.0.0:8080 CLIENT_DIR=/client +USER 65532:65532 +EXPOSE 8080 +ENTRYPOINT ["/world"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..f068fc1 --- /dev/null +++ b/README.md @@ -0,0 +1,113 @@ +# Aeternalis + +A playable browser survival RPG foundation: an authoritative Go world server, +Three.js terrain and GLB models, persistent one-life characters, and weekly worlds. + +**Status: local prototype, not a production MMO or a verified 2,000-player server.** +The review, architecture, deployment instructions, and remaining work are in +`docs/ARCHITECTURE.md`, `docs/DEPLOYMENT.md`, and `docs/ROADMAP.md`. + +## Run locally + +Requirements: Node.js 24 and Go 1.26+ (tested with Go 1.27.1). +On Windows without Go, `powershell -File tools/bootstrap-go.ps1` downloads a +checksum-verified, project-local toolchain. + +```sh +npm ci +npm run build +node tools/dev-server.mjs +``` + +Open **http://127.0.0.1:18080**. Guest authentication is available only in +development, on an explicit loopback listen address. Production fails closed +without PostgreSQL and an HTTPS OIDC configuration. + +The delivered Windows build can also be started without installing Go: + +```powershell +powershell -File tools/start-local.ps1 -UseExisting +``` + +That command starts a hidden background process and prints its PID. Stop your +specific local process with `Stop-Process -Id `. Local state lives in +`.local/aeternalis.db`; restarting preserves characters, world age, and death. +Deleting this development database is an explicit reset, not part of startup. + +## Play + +- Move with WASD/arrows, click the terrain, or use touch direction controls. +- Click resources/enemies to approach and gather/attack. The toolbar also chooses + the nearest suitable target. E gathers, Space attacks, I opens inventory. +- Gather wood, ore, and herbs. Craft a spear or bandages in inventory. +- The Harbinger appears after seven days. In loopback development, Display + settings includes **Awaken Harbinger** for testing the event immediately. +- During the boss event the safe world radius shrinks toward the center. The + boundary deals damage; complete collapse kills remaining characters, including + offline and daily-capped characters. Killing the boss freezes survivor eligibility. +- Survivors sign into a different configured world with the same identity, then + choose **Continue as ...**. An atomic passage redemption preserves identity, + inventory, skills, kills, and daily play-time usage. + +PvP, damage-priority corpse looting, body-part damage, full skills/stats, +leaderboards, and an admin center are not implemented. Corpse looting currently +has no priority lock because PvP is not enabled. + +## Multiple local worlds + +Start independent worlds against the same SQLite database. Every process needs a +unique world ID and port. A completed world ID must never be recycled for a new +season. Seeds and balance are stored when a world is first created. + +```powershell +$env:WORLD_DIRECTORY = '[{"id":"world-001","url":"http://127.0.0.1:18080"},{"id":"world-002","url":"http://127.0.0.1:18081"}]' +powershell -File tools/start-local.ps1 -WorldId world-001 -Port 18080 +powershell -File tools/start-local.ps1 -WorldId world-002 -Port 18081 -Seed 829312 +``` + +Loopback cookies are shared across these two ports, so the same local guest can +redeem a passage. Production worlds use OIDC issuer + subject for stable identity +and separate secure host cookies. Never use dev identity for public servers. + +## Validate + +```sh +npm run test:contracts +npm run check +npm run build +# In server/: +go test ./... +go vet ./... +# At the repository root: +npx playwright install chromium +npm run test:e2e +helm lint deploy/chart +helm template aeternalis deploy/chart +``` + +When Go is local, use `.tools/go/bin/go.exe` from the root or +`../.tools/go/bin/go.exe` from `server/`. Go tests use a temporary SQLite database. +Set `TEST_DATABASE_URL` to an expendable PostgreSQL test database to run the same +storage suite on PostgreSQL; CI provides one. Linux CI also runs `go test -race`. +The browser suite starts and stops its own server on port 18089 with a fresh DB. +On Windows, `PLAYWRIGHT_CHANNEL=msedge` can use installed Edge without downloading +Chromium. Screenshots and traces are written to `test-results/`. + +For client hot reload, run the server with `PUBLIC_URL=http://127.0.0.1:5175`, +then run `npm run dev` and open port 5175. Origin checking intentionally rejects +requests from other origins. + +## Layout + +| Path | Responsibility | +|---|---| +| `planning/VISION.md` | Original user vision; new boss rule in `IMPLEMENTATION-NOTES.md` | +| `server/internal/game` | Terrain, authoritative simulation, lifecycle | +| `server/internal/store` | World ownership, snapshots, sessions, atomic passages | +| `server/internal/transport` | HTTP, OIDC, origin checks, WebSocket intent validation | +| `schemas/protocol.json` | Generated Go/TypeScript wire contracts | +| `server/content/balance.yaml` | Validated balance and recipe data | +| `client/` | Full-screen browser game and mobile controls | +| `tools/create-models.py` | Original temporary Blender models | +| `deploy/chart/` | Five independent world deployments, services, TLS ingress | +| `.gitea/workflows/build.yaml` | Tests, Harbor image publication, optional GitOps promotion | diff --git a/assets/README.md b/assets/README.md new file mode 100644 index 0000000..588a1c2 --- /dev/null +++ b/assets/README.md @@ -0,0 +1,7 @@ +# Temporary art + +All six GLB models are original procedural placeholder models generated with +Blender by `tools/create-models.py`. No third-party model or texture inputs. +Rebuild with Blender 4.3+: `blender --background --python tools/create-models.py`. +The final Harbinger scene is preserved in `harbinger.blend`. +These are rigid meshes; production rigs, animations, LODs, and material art remain. diff --git a/assets/harbinger.blend b/assets/harbinger.blend new file mode 100644 index 0000000..22e0d0f Binary files /dev/null and b/assets/harbinger.blend differ diff --git a/client/AGENTS.md b/client/AGENTS.md new file mode 100644 index 0000000..7a8849c --- /dev/null +++ b/client/AGENTS.md @@ -0,0 +1,5 @@ +# Browser client + +Three.js presentation and intent input only. Do not decide damage, inventory, +death, transfer eligibility, or play-time limits here. Consume generated contracts. +Dispose chunk GPU resources on eviction. Keep the world full-screen on mobile. diff --git a/client/index.html b/client/index.html new file mode 100644 index 0000000..3cbb3f7 --- /dev/null +++ b/client/index.html @@ -0,0 +1,35 @@ + + + + + + + Aeternalis + + + + +
+
+
A
AETERNALISThe First Reach
+
WNWNNEE
+
Connecting
+
+
THE GATHERING7d 00h
Until the Harbinger
+ + + + + +
+
Traveler100 / 100
2h left today0 kills
+ +
0, 09 chunks
+
+ +
+
THE FIRST REACH

Aeternalis

One life. A world on borrowed time.

+
JOURNEY ENDED

Your story remains.

+ + + diff --git a/client/public/models/boss.glb b/client/public/models/boss.glb new file mode 100644 index 0000000..757996c Binary files /dev/null and b/client/public/models/boss.glb differ diff --git a/client/public/models/herb.glb b/client/public/models/herb.glb new file mode 100644 index 0000000..e599b04 Binary files /dev/null and b/client/public/models/herb.glb differ diff --git a/client/public/models/ore.glb b/client/public/models/ore.glb new file mode 100644 index 0000000..66c497f Binary files /dev/null and b/client/public/models/ore.glb differ diff --git a/client/public/models/player.glb b/client/public/models/player.glb new file mode 100644 index 0000000..25518a1 Binary files /dev/null and b/client/public/models/player.glb differ diff --git a/client/public/models/sentinel.glb b/client/public/models/sentinel.glb new file mode 100644 index 0000000..e8b6426 Binary files /dev/null and b/client/public/models/sentinel.glb differ diff --git a/client/public/models/tree.glb b/client/public/models/tree.glb new file mode 100644 index 0000000..ba94f3c Binary files /dev/null and b/client/public/models/tree.glb differ diff --git a/client/src/generated.ts b/client/src/generated.ts new file mode 100644 index 0000000..e6175e4 --- /dev/null +++ b/client/src/generated.ts @@ -0,0 +1,79 @@ +// Code generated from schemas/protocol.json. DO NOT EDIT. +export interface Protocol { + intent: Intent; + snapshot: Snapshot; +} + +export interface Intent { + op: string; + seq: number; + target: string; + x: number; + z: number; +} + +export interface Snapshot { + chunkKeys: string[]; + chunks: Chunk[]; + entities: Entity[]; + message: string; + self: Character; + tick: number; + type: string; + unavailableResources: string[]; + version: number; + world: WorldInfo; +} + +export interface Chunk { + biome: string; + heights: number[]; + key: string; + resolution: number; + resources: Entity[]; + size: number; + x: number; + z: number; +} + +export interface Entity { + hp: number; + id: string; + kind: string; + maxHp: number; + name: string; + position: Vec3; + state: string; +} + +export interface Vec3 { + x: number; + y: number; + z: number; +} + +export interface Character { + ack: number; + entity: Entity; + hasKeystone: boolean; + inventory: { [key: string]: number }; + kills: number; + playedSeconds: number; + remainingSeconds: number; + skills: { [key: string]: number }; +} + +export interface WorldInfo { + ageSeconds: number; + bossHp: number; + bossInSeconds: number; + bossMaxHp: number; + capacity: number; + collapseInSeconds: number; + id: string; + online: number; + phase: string; + radius: number; + safeRadius: number; + seed: number; +} diff --git a/client/src/main.ts b/client/src/main.ts new file mode 100644 index 0000000..7eb4f33 --- /dev/null +++ b/client/src/main.ts @@ -0,0 +1,223 @@ +import './style.css'; +import { createIcons, Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } from 'lucide'; +import { WorldView } from './world-view'; +import type { Character, Chunk, Entity, Intent, Snapshot } from './generated'; + +type Recipe = { Inputs: Record; Outputs: Record }; +type Config = { worldId: string; development: boolean; worlds: { id: string; url: string }[]; recipes: Record; playerSpeed: number; gatherRange: number; attackRange: number }; +const $ = (id: string) => document.getElementById(id) as T; +const visible = (id: string, show: boolean) => { $(id).hidden = !show; }; +const pretty = (s: string) => s.replaceAll('_', ' ').replace(/^./, c => c.toUpperCase()); +const time = (seconds: number) => seconds >= 86400 ? `${Math.floor(seconds / 86400)}d ${Math.floor(seconds % 86400 / 3600)}h` : seconds >= 3600 ? `${Math.floor(seconds / 3600)}h ${Math.floor(seconds % 3600 / 60)}m` : `${Math.floor(seconds / 60)}m ${Math.floor(seconds % 60)}s`; +let config: Config; +let snapshot: Snapshot | undefined; +let ws: WebSocket | undefined; +let sequence = 0; +let lastNotice = ''; +let noticeTimer: ReturnType; +let inputElapsed = 0; +let walkTo: { x: number; z: number } | undefined; +let pendingAction: { op: string; target: string } | undefined; +let requestedClose = false; +const keys = new Set(); +let view: WorldView; + +async function api(path: string, body?: unknown): Promise { + const response = await fetch(path, { method: body === undefined ? 'GET' : 'POST', credentials: 'same-origin', headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) }); + const result = await response.json(); + if (!response.ok) throw new Error(result.error ?? `Request failed (${response.status})`); + return result as T; +} +function notice(message: string) { $('notice').textContent = message; visible('notice', true); clearTimeout(noticeTimer); noticeTimer = setTimeout(() => visible('notice', false), 3500); } +function send(op: string, target = '', x = 0, z = 0) { + if (ws?.readyState !== WebSocket.OPEN || !snapshot || snapshot.self.entity.state !== 'alive') return; + const intent: Intent = { op, target, x, z, seq: ++sequence }; + ws.send(JSON.stringify(intent)); +} +function selection(entity?: Entity) { + view.selected = entity; visible('target', !!entity); + if (entity) { $('target-name').textContent = entity.name; $('target-health').textContent = ['boss', 'sentinel', 'player'].includes(entity.kind) ? `${Math.ceil(entity.hp)} / ${Math.ceil(entity.maxHp)}` : pretty(entity.kind); } +} +function action(op: string) { + if (!snapshot) return; + const kinds = op === 'attack' ? ['boss', 'sentinel'] : ['tree', 'ore', 'herb', 'corpse']; + let target = view.selected; + if (!target || !kinds.includes(target.kind)) { + const p = snapshot.self.entity.position; + target = snapshot.entities.filter(e => kinds.includes(e.kind)).sort((a, b) => Math.hypot(a.position.x - p.x, a.position.z - p.z) - Math.hypot(b.position.x - p.x, b.position.z - p.z))[0]; + } + if (!target) { notice('No target nearby.'); return; } + selection(target); + pendingAction = { op: target.kind === 'corpse' ? 'loot' : op, target: target.id }; + walkTo = target.position; +} +function connect() { + requestedClose = false; sequence = 0; + const ending = $('ending'); ending.close(); + ws = new WebSocket(`${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.host}/ws`); + ws.onopen = () => { $('connection-status').textContent = 'Connected'; $('connection-dot').parentElement!.classList.remove('offline'); }; + ws.onmessage = event => { + const value = JSON.parse(event.data) as Snapshot; + if (value.type !== 'snapshot' || value.version !== 1) { ws?.close(); notice('Client and server versions do not match.'); return; } + snapshot = value; view.update(value); updateHUD(value); + const state = value.self.entity.state; + if (state === 'dead') showEnding('A life, remembered.', 'This character is permanently dead. Their belongings remain in this world.', false); + else if (state === 'eligible') showEnding('A passage forward.', 'The Harbinger has fallen. Your character and belongings can continue to a new world.', true); + else if (value.self.remainingSeconds <= 0) showEnding('Rest until tomorrow.', 'Your daily play time is complete. Your keystone will return you to your previous location after 00:00 UTC.', false); + }; + ws.onclose = async () => { + $('connection-status').textContent = 'Disconnected'; $('connection-dot').parentElement!.classList.add('offline'); keys.clear(); walkTo = undefined; + if (requestedClose || $('ending').open) return; + let detail = 'The connection ended. Your character state is held by the server.'; + try { const me = await api<{ character?: Character }>('/api/me'); if (me.character?.entity.state === 'dead') { showEnding('A life, remembered.', 'This character is permanently dead.', false); return; } if (me.character?.remainingSeconds === 0) detail = 'Daily play time is complete. Return after 00:00 UTC.'; } catch { detail = 'Your session ended. Sign in again to continue.'; } + showEnding('Connection interrupted.', detail, false); visible('reconnect', true); + }; +} +function showEnding(title: string, detail: string, survivor: boolean) { + keys.clear(); walkTo = undefined; pendingAction = undefined; + $('ending-title').textContent = title; $('ending-detail').textContent = detail; + $('ending-eyebrow').textContent = survivor ? 'WORLD SURVIVED' : 'JOURNEY PAUSED'; + if (snapshot?.self.entity.state === 'dead') $('ending-eyebrow').textContent = 'JOURNEY ENDED'; + const destinations = $('destinations'); destinations.replaceChildren(); + if (survivor) for (const destination of config.worlds.filter(w => w.id !== config.worldId)) { + const link = document.createElement('a'); link.href = destination.url; link.textContent = `Travel to ${destination.id}`; link.rel = 'noopener'; destinations.append(link); + } + if (survivor && destinations.children.length === 0) { const p = document.createElement('p'); p.textContent = 'Your passage is saved. No destination world is open yet.'; destinations.append(p); } + visible('reconnect', false); + $('ending').show(); +} +function inventory(c: Character) { + const parent = $('inventory-items'); parent.replaceChildren(); + for (const [item, count] of Object.entries(c.inventory).filter(([, n]) => n > 0)) { + const div = document.createElement('div'); div.className = 'item'; + const text = document.createElement('span'); text.textContent = pretty(item); + const quantity = document.createElement('b'); quantity.textContent = String(count); + div.append(text, quantity); parent.append(div); + } + const recipes = $('recipes'); recipes.replaceChildren(); + for (const [name, recipe] of Object.entries(config.recipes)) { + const row = document.createElement('div'); row.className = 'recipe'; + const label = document.createElement('div'), title = document.createElement('strong'), cost = document.createElement('small'); + title.textContent = pretty(name); cost.textContent = Object.entries(recipe.Inputs).map(([k, n]) => `${n} ${pretty(k)}`).join(' + '); label.append(title, cost); + const button = document.createElement('button'); button.textContent = 'Craft'; button.title = `Craft ${name}`; button.disabled = Object.entries(recipe.Inputs).some(([item, count]) => (c.inventory[item] ?? 0) < count); button.onclick = () => send('craft', name); + row.append(label, button); recipes.append(row); + } + const skills = $('skills'); skills.replaceChildren(); + for (const skill of ['gathering', 'crafting', 'combat']) { const label = document.createElement('span'); label.textContent = pretty(skill); const amount = document.createElement('b'); amount.textContent = `${c.skills[skill] ?? 0} XP`; label.append(amount); skills.append(label); } +} +function minimap(s: Snapshot) { + const canvas = $('minimap'), ctx = canvas.getContext('2d')!; + const p = s.self.entity.position, radius = s.world.radius; + ctx.clearRect(0, 0, 140, 140); ctx.save(); ctx.beginPath(); ctx.arc(70, 70, 66, 0, Math.PI * 2); ctx.clip(); + ctx.fillStyle = '#263c30'; ctx.fillRect(0, 0, 140, 140); + ctx.strokeStyle = '#77916a50'; ctx.lineWidth = 1; + for (let i = 6; i < 140; i += 16) { ctx.beginPath(); ctx.moveTo(i, 0); ctx.lineTo(i, 140); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0, i); ctx.lineTo(140, i); ctx.stroke(); } + ctx.strokeStyle = s.world.phase === 'cataclysm' ? '#e18a8a' : '#aebc92'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(70, 70, 62 * s.world.safeRadius / radius, 0, Math.PI * 2); ctx.stroke(); + if (s.world.phase === 'cataclysm') { ctx.fillStyle = '#ed7963'; ctx.fillRect(67, 67, 6, 6); } + ctx.fillStyle = '#ecedbd'; ctx.beginPath(); ctx.arc(70 + p.x / radius * 62, 70 + p.z / radius * 62, 3, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#d4debf'; ctx.font = '9px sans-serif'; ctx.fillText('N', 67, 15); ctx.restore(); +} +function updateHUD(s: Snapshot) { + const c = s.self, w = s.world; + visible('game-controls', true); visible('movement', c.entity.state === 'alive' && $('inventory').hidden && $('settings').hidden); + $('character-name').textContent = c.entity.name; + $('health-number').textContent = `${Math.max(0, Math.ceil(c.entity.hp))} / ${Math.ceil(c.entity.maxHp)}`; + $('health-fill').style.width = `${Math.max(0, c.entity.hp / c.entity.maxHp * 100)}%`; + $('play-time').textContent = `${time(c.remainingSeconds)} left today`; + $('kills').textContent = `${c.kills} kills`; + $('bandage-count').textContent = String(c.inventory.bandage ?? 0); + $('heal').disabled = !c.inventory.bandage || c.entity.hp >= c.entity.maxHp; + $('keystone').disabled = !c.hasKeystone; + $('world-name').textContent = `${w.id} / ${w.online} online`; + $('phase-label').textContent = w.phase === 'gathering' ? 'THE GATHERING' : w.phase === 'cataclysm' ? 'THE UNRAVELING' : w.phase === 'won' ? 'WORLD SURVIVED' : 'WORLD LOST'; + $('season-clock').textContent = time(w.phase === 'gathering' ? w.bossInSeconds : w.collapseInSeconds); + $('season-detail').textContent = w.phase === 'gathering' ? 'Until the Harbinger' : `${Math.round(w.safeRadius)}m of world remaining`; + $('season-progress').style.width = `${w.safeRadius / w.radius * 100}%`; + visible('boss-bar', w.phase === 'cataclysm'); $('boss-health').style.width = `${w.bossHp / w.bossMaxHp * 100}%`; $('boss-count').textContent = `${Math.ceil(w.bossHp)} / ${Math.ceil(w.bossMaxHp)}`; + $('coordinates').textContent = `${Math.round(c.entity.position.x)}, ${Math.round(c.entity.position.z)}`; + $('chunk-count').textContent = `${view.chunks.size} chunks`; + if (!$('inventory').hidden) inventory(c); + selection(view.selected); minimap(s); + if (s.message && s.message !== lastNotice) { notice(s.message); lastNotice = s.message; } +} +async function boot() { + createIcons({ icons: { Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } }); + view = new WorldView($('world')); + view.start(dt => { + inputElapsed += dt; + if (!snapshot || ws?.readyState !== WebSocket.OPEN || $('ending').open) return; + let x = Number(keys.has('d') || keys.has('arrowright')) - Number(keys.has('a') || keys.has('arrowleft')); + let z = Number(keys.has('s') || keys.has('arrowdown')) - Number(keys.has('w') || keys.has('arrowup')); + if (x || z) { walkTo = undefined; pendingAction = undefined; } + if (walkTo) { + const p = snapshot.self.entity.position, dx = walkTo.x - p.x, dz = walkTo.z - p.z, distance = Math.hypot(dx, dz); + const target = snapshot.entities.find(e => e.id === pendingAction?.target); + const range = pendingAction ? pendingAction.op === 'attack' ? config.attackRange + (target?.kind === 'boss' ? 3 : -0.5) : config.gatherRange - 0.5 : 0.8; + if (distance <= range) { if (pendingAction) send(pendingAction.op, pendingAction.target); walkTo = undefined; pendingAction = undefined; } + else { x = dx / distance; z = dz / distance; } + } + view.moving = !!(x || z); + if (inputElapsed >= 0.05) { send('move', '', x, z); inputElapsed = 0; } + }); + const [loadedConfig, chunks] = await Promise.all([api('/api/config'), api('/api/preview'), view.load()]); + config = loadedConfig; + $('zoom').value = String(view.distance); + view.addChunks(chunks); view.updateEntities(chunks.flatMap(c => c.resources)); + $('connection-status').textContent = 'World online'; + visible('dev-boss', config.development); + let me: { character: Character | null } | undefined; + try { me = await api('/api/me'); } catch { if (config.development) { await api('/auth/dev', {}); me = await api('/api/me'); } } + if (!me && !config.development) { visible('join-form', false); visible('login', true); } + else if (me?.character) { + $('arrival').close(); + if (me.character.entity.state === 'dead') showEnding('A life, remembered.', 'This character is permanently dead. A fresh world is a new beginning.', false); + else if (me.character.entity.state === 'eligible') showEnding('A passage forward.', 'Your survivor passage is saved.', true); + else connect(); + } else { + const passages = await api<{ characterId: string; sourceWorld: string; name: string }[]>('/api/passages').catch(() => []); + for (const passage of passages.filter(p => p.sourceWorld !== config.worldId)) { + const button = document.createElement('button'); button.textContent = `Continue as ${passage.name}`; + button.onclick = async () => { try { await api('/api/join', { name: '', passage: passage.characterId }); $('arrival').close(); connect(); } catch (e) { $('arrival-error').textContent = String((e as Error).message); } }; + $('passages').append(button); + } + } + $('join-form').onsubmit = async event => { + event.preventDefault(); const button = $('join'); button.disabled = true; + try { await api('/api/join', { name: $('name').value, passage: '' }); $('arrival').close(); connect(); } + catch (e) { $('arrival-error').textContent = (e as Error).message; } + finally { button.disabled = false; } + }; + for (const id of ['inventory', 'settings']) { $(`${id}-toggle`).onclick = () => { visible(id, $(id).hidden); visible('movement', $('inventory').hidden && $('settings').hidden && !!snapshot); if (id === 'inventory' && snapshot) inventory(snapshot.self); }; } + document.querySelectorAll('[data-close]').forEach(button => button.onclick = () => visible(button.dataset.close!, false)); + $('attack').onclick = () => action('attack'); $('gather').onclick = () => action('gather'); $('heal').onclick = () => send('heal'); $('keystone').onclick = () => send('return'); + $('target-boss').onclick = () => { selection(snapshot?.entities.find(e => e.id === 'boss')); walkTo = { x: 0, z: 0 }; pendingAction = { op: 'attack', target: 'boss' }; }; + $('dev-boss').onclick = () => void api('/api/dev/boss', {}).catch(e => notice(e.message)); + $('reconnect').onclick = () => location.reload(); + $('logout').onclick = async () => { requestedClose = true; await api('/auth/logout', {}); ws?.close(); location.reload(); }; + $('quality').onchange = event => view.quality((event.target as HTMLSelectElement).value === 'high'); + $('zoom').oninput = event => { view.distance = Number((event.target as HTMLInputElement).value); view.resize(); }; + window.addEventListener('keydown', event => { + if ((event.target as HTMLElement).matches('input,select,textarea') || $('arrival').open) return; + const key = event.key.toLowerCase(); + if (['w', 'a', 's', 'd', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright', ' '].includes(key)) event.preventDefault(); + keys.add(key); if (event.repeat) return; + if (key === 'e') action('gather'); if (key === ' ') action('attack'); if (key === 'i') $('inventory-toggle').click(); if (key === 'escape') { visible('inventory', false); visible('settings', false); selection(); walkTo = undefined; } + }); + window.addEventListener('keyup', event => keys.delete(event.key.toLowerCase())); + window.addEventListener('blur', () => { keys.clear(); walkTo = undefined; send('move'); }); + document.addEventListener('visibilitychange', () => { if (document.hidden) { keys.clear(); walkTo = undefined; send('move'); } }); + const movements: Record = { up: 'w', down: 's', left: 'a', right: 'd' }; + document.querySelectorAll('[data-move]').forEach(button => { + const key = movements[button.dataset.move!]; + button.onpointerdown = event => { button.setPointerCapture(event.pointerId); keys.add(key); }; + button.onpointerup = button.onpointercancel = () => keys.delete(key); + }); + view.canvas.addEventListener('pointerdown', event => { + if (!snapshot || $('ending').open || event.button !== 0) return; + const hit = view.pick(event.clientX, event.clientY); + if (hit.entity) { selection(hit.entity); action(['boss', 'sentinel'].includes(hit.entity.kind) ? 'attack' : 'gather'); } + else if (hit.point) { selection(); walkTo = hit.point; pendingAction = undefined; } + }); + Object.defineProperty(window, '__aeternalis', { value: { diagnostics: () => view.diagnostics(), get snapshot() { return snapshot; } }, configurable: true }); +} +boot().catch(error => { console.error(error); $('arrival-error').textContent = `Unable to enter the world: ${error.message}`; $('connection-status').textContent = 'Unavailable'; }); diff --git a/client/src/style.css b/client/src/style.css new file mode 100644 index 0000000..baf3868 --- /dev/null +++ b/client/src/style.css @@ -0,0 +1,6 @@ +:root{font-family:Inter,"Segoe UI",sans-serif;color:#f0f4ee;background:#9bbabc;font-synthesis:none;font-size:14px;letter-spacing:0;color-scheme:dark}*{box-sizing:border-box}body{margin:0;overflow:hidden}button,input,select{font:inherit}button,a.command{cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:9px;min-height:42px;color:#edf3ed;background:#293b36;border:1px solid #6c82706b;border-radius:4px;padding:9px 14px;text-decoration:none}button:hover,a.command:hover{background:#41574a;border-color:#a6bd9c}button:disabled{opacity:.4;cursor:default}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid #d1e3a4;outline-offset:3px}svg{width:20px;height:20px;flex-shrink:0}input,select{width:100%;min-height:42px;border:1px solid #77867b;background:#14201e;color:#f4f4ec;padding:8px 10px;border-radius:3px}input[type=range]{padding:0;accent-color:#b9cf8b}label{display:block;color:#c4cdc4;font-size:12px;margin-bottom:7px}h1,h2,h3,p{margin:0}h1{font-family:Georgia,serif;font-size:42px;font-weight:400;margin:12px 0 16px}h2{font-size:17px;font-weight:500}h3{font-size:12px;font-weight:500;text-transform:uppercase;color:#b4c3ae;margin:24px 0 12px}.icon{width:36px;height:36px;min-height:36px;padding:8px;background:transparent;border-color:transparent}[hidden]{display:none!important}#world{position:fixed;inset:0;width:100%;height:100%;display:block;touch-action:none}#hud{position:fixed;inset:0;pointer-events:none}#hud button,#hud input,#hud select,.panel{pointer-events:auto}.topbar{position:absolute;top:0;left:0;width:100%;display:flex;align-items:center;justify-content:space-between;padding:24px 30px;background:linear-gradient(#122521a6,transparent);text-shadow:0 2px 7px #12251c80}.brand{display:flex;align-items:center;gap:13px}.brand-mark{font:36px Georgia,serif;border:1px solid #e7edce99;padding:0 10px;color:#d9e6b5}.brand strong{display:block;font:21px Georgia,serif}.brand span:not(.brand-mark){display:block;font-size:11px;color:#cfdfc9;margin-top:6px}.compass{display:flex;align-items:center;gap:32px;font-size:11px;color:#e2eddfb3}.compass b{color:#edf5d8;font-size:15px;border-bottom:2px solid #dce7af;padding-bottom:7px}.connection{display:flex;gap:8px;align-items:center;font-size:11px}.connection>i{height:6px;width:6px;border-radius:50%;background:#a4c478}.connection.offline>i{background:#d37569}.season{position:absolute;top:115px;left:30px;width:210px;text-shadow:0 2px 5px #142119}.season>div:first-child{display:flex;align-items:center;justify-content:space-between;gap:12px}.season span{font-size:10px;color:#dce4d3}.season strong{font-size:17px;font-weight:500}.season>span{display:block;font-size:11px;margin:9px 0 12px}.thin-track{height:2px;background:#d9e5d14d}.thin-track i{display:block;width:100%;height:100%;background:#c9da99}.panel{position:absolute;background:#192722f2;border:1px solid #7b887469;border-radius:6px;box-shadow:0 10px 35px #10251d40;padding:20px;backdrop-filter:blur(12px);width:310px;max-height:calc(100dvh - 210px);overflow:auto}.panel-title{display:flex;align-items:center;justify-content:space-between;margin-bottom:18px}.inventory{right:30px;bottom:155px}.inventory-items{display:grid;grid-template-columns:1fr 1fr;gap:8px}.item{background:#e6eeca0a;border:1px solid #87927938;padding:11px 9px;display:flex;align-items:center;gap:8px;min-height:55px}.item span{font-size:11px;overflow-wrap:anywhere;flex:1}.item b{font-size:13px;font-weight:500;color:#d6e4b6}.recipe{display:flex;gap:10px;justify-content:space-between;align-items:center;border-top:1px solid #ffffff12;padding:10px 0}.recipe strong{font-size:12px;font-weight:500}.recipe small{display:block;font-size:10px;color:#9dab9c;margin-top:5px}.recipe button{padding:8px;min-height:34px}.skills{display:flex;gap:18px}.skills span{font-size:11px;color:#c1d0bd}.skills b{display:block;margin-top:5px;color:#f0f5e8}.settings{right:30px;top:95px}.settings label{margin:18px 0;display:grid;gap:8px}.settings>button{width:100%;margin-top:8px}.bottom{position:absolute;left:30px;right:30px;bottom:24px;display:flex;align-items:flex-end;justify-content:space-between;gap:20px}.vitals{width:250px;padding:18px;background:#172a23e8;border:1px solid #b2c3a24a;border-radius:4px}.vitals>div:first-child{display:flex;justify-content:space-between;gap:10px;font-size:11px}.vitals strong{font-size:13px;max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.bar{height:6px;background:#ffffff20;margin:12px 0;overflow:hidden}.bar>i{display:block;width:100%;height:100%;background:#b3ce82;transition:width .18s}.vital-detail{display:flex;justify-content:space-between;gap:8px;color:#b8c9b2;font-size:10px}.vital-detail>span:first-child{display:flex;align-items:center;gap:5px}.vital-detail svg{width:12px;height:12px}.actions{display:flex;gap:7px;align-items:center;background:#172720df;padding:9px;border:1px solid #a8b99a50;border-radius:5px}.actions button{position:relative;width:48px;height:48px;padding:10px;background:#29382fe6}.actions button:first-child{background:#773f36}.actions>span{height:25px;width:1px;background:#a5b78b4a;margin:0 2px}.actions small{position:absolute;bottom:3px;right:5px;font-size:9px}.location{display:flex;flex-direction:column;align-items:center;gap:5px;width:150px;font-size:10px;color:#e2e8d8;text-shadow:0 1px 3px #000}.location canvas{width:122px;height:122px;border:1px solid #c9d4b99c;border-radius:50%;background:#263d30b3}.location small{color:#d0debc;font-size:9px}.target{position:absolute;left:50%;top:26%;transform:translateX(-50%);background:#13261ee3;border:1px solid #aabb9277;padding:8px 14px;border-radius:3px;font-size:12px;text-align:center}.target span+span{display:block;font-size:10px;color:#aebf99;margin-top:4px}.notice{position:absolute;left:50%;bottom:120px;transform:translateX(-50%);max-width:90%;background:#18241feb;border:1px solid #94a77755;border-radius:3px;padding:10px 18px;text-align:center;font-size:12px}.boss-bar{position:absolute;left:50%;top:100px;transform:translateX(-50%);width:350px;max-width:50%;text-align:center}.boss-bar>span{font:18px Georgia,serif;color:#ffe3d5;text-shadow:0 2px 5px #000}.boss-bar .bar{height:5px}.boss-bar .bar>i{background:#c9685b}.boss-bar small{font-size:10px}.movement{display:none}dialog{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);margin:0;width:360px;max-width:calc(100% - 36px);padding:30px;background:#172722f2;color:#eef2e6;border:1px solid #a2b2946b;border-radius:6px;box-shadow:0 20px 90px #132c1d44;backdrop-filter:blur(15px)}dialog .eyebrow{font-size:10px;color:#bed399}dialog p{font-size:13px;color:#bec9bd;line-height:1.6;margin-bottom:22px}dialog form{display:flex;flex-direction:column;gap:7px}dialog form button{margin-top:12px;background:#c1d095;color:#19261d;border-color:#d0ddb1;font-weight:600}dialog input{background:#101e18a6}dialog .error{font-size:12px;color:#edaa94;margin:14px 0 0}dialog a.command{width:100%;margin-top:10px}dialog #passages button{width:100%;margin-top:10px}#destinations a{display:flex;color:#d0e9a7;margin:12px 0;align-items:center;gap:10px}#ending h1{font-size:32px}#reconnect{width:100%} +@media(max-width:800px){.compass{display:none}.topbar{padding:18px}.brand strong{font-size:18px}.brand-mark{font-size:30px}.connection>span{max-width:95px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.season{left:18px;top:95px;width:170px}.bottom{left:18px;right:18px;bottom:18px;flex-wrap:wrap;justify-content:space-between;gap:10px}.vitals{width:210px;padding:12px}.location{width:90px}.location canvas{width:78px;height:78px}.location small{display:none}.actions{order:3;margin:0 auto;padding:6px}.actions button{width:42px;height:42px}.inventory{right:18px;bottom:165px;width:290px;max-height:calc(100dvh - 250px)}.settings{right:18px;top:85px}.boss-bar{top:165px;max-width:75%;width:290px}.movement:not([hidden]){display:grid;position:absolute;left:18px;bottom:182px;grid-template-columns:repeat(3,38px);grid-template-rows:repeat(2,38px);gap:3px}.movement button{min-height:38px;padding:7px;background:#1b3026ae;touch-action:none}.movement button:first-child{grid-column:2}.movement button:nth-child(2){grid-row:2;grid-column:1}.movement button:nth-child(3){grid-row:2;grid-column:2}.movement button:nth-child(4){grid-row:2;grid-column:3}.notice{bottom:315px;width:max-content;max-width:85%}.target{top:36%}h1{font-size:36px}} +.panel{z-index:4} +.boss-bar>button{background:transparent;border:0;padding:0;min-height:28px;font:18px Georgia,serif;color:#ffe3d5;text-shadow:0 2px 5px #000} +@media(max-width:800px){.inventory{bottom:190px;max-height:calc(100dvh - 285px)}} +@media(max-height:520px){.season{top:85px}.bottom{bottom:10px;flex-wrap:nowrap}.location{display:none}.movement:not([hidden]){display:grid;position:absolute;grid-template-columns:repeat(4,38px);gap:3px;bottom:110px;left:18px}.movement button{padding:6px}.boss-bar{top:80px}.inventory,.settings{top:70px;bottom:auto;max-height:calc(100dvh - 90px)}dialog{max-height:calc(100dvh - 24px);overflow:auto;padding:20px}.notice{bottom:90px}} diff --git a/client/src/world-view.ts b/client/src/world-view.ts new file mode 100644 index 0000000..dbfec04 --- /dev/null +++ b/client/src/world-view.ts @@ -0,0 +1,234 @@ +import * as T from 'three'; +import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; +import type { Chunk, Entity, Snapshot, Vec3 } from './generated'; + +type Batch = { parts: T.InstancedMesh[]; entities: Entity[] }; +export class WorldView { + readonly renderer: T.WebGLRenderer; + readonly scene = new T.Scene(); + readonly camera = new T.OrthographicCamera(-60, 60, 40, -40, 0.1, 1400); + readonly chunks = new Map(); + readonly batches = new Map(); + readonly focus = new T.Vector3(0, 0, 0); + readonly position = new T.Vector3(); + readonly aim = new T.Vector3(); + readonly ring: T.Mesh; + readonly selection: T.Mesh; + readonly storm: T.Mesh; + readonly sun: T.DirectionalLight; + readonly models = new Map(); + player?: T.Group; + snapshot?: Snapshot; + selected?: Entity; + distance = 46; + frames = 0; + moving = false; + private highQuality = true; + private initialized = false; + private clock = new T.Clock(); + private matrix = new T.Matrix4(); + private dummy = new T.Object3D(); + private ray = new T.Raycaster(); + private onFrame: (dt: number) => void = () => {}; + constructor(readonly canvas: HTMLCanvasElement) { + this.renderer = new T.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' }); + this.renderer.setPixelRatio(Math.min(devicePixelRatio, 1.5)); + this.renderer.shadowMap.enabled = true; + this.renderer.shadowMap.type = T.PCFSoftShadowMap; + this.renderer.toneMapping = T.ACESFilmicToneMapping; + this.renderer.toneMappingExposure = 1.0; + this.scene.background = new T.Color('#b9ccd0'); + this.scene.fog = new T.Fog('#b9ccd0', 200, 650); + this.scene.add(new T.HemisphereLight('#e9f4f2', '#475c3d', 1.35)); + this.sun = new T.DirectionalLight('#fff0d8', 2.3); + this.sun.position.set(-60, 100, 45); + this.sun.castShadow = true; + this.sun.shadow.mapSize.set(2048, 2048); + Object.assign(this.sun.shadow.camera, { left: -100, right: 100, top: 100, bottom: -100, near: 1, far: 300 }); + this.sun.shadow.bias = -0.0003; + this.sun.shadow.normalBias = 0.15; + this.scene.add(this.sun, this.sun.target); + this.ring = new T.Mesh(new T.RingGeometry(1.35, 1.5, 48), new T.MeshBasicMaterial({ color: '#ebefc1', side: T.DoubleSide, depthWrite: false })); + this.ring.rotation.x = -Math.PI / 2; + this.scene.add(this.ring); + this.selection = new T.Mesh(new T.RingGeometry(2.1, 2.24, 40), new T.MeshBasicMaterial({ color: '#f1d595', side: T.DoubleSide, depthWrite: false })); + this.selection.rotation.x = -Math.PI / 2; + this.selection.visible = false; + this.scene.add(this.selection); + this.storm = new T.Mesh(new T.CylinderGeometry(1, 1, 36, 160, 1, true), new T.MeshBasicMaterial({ color: '#ce4f65', transparent: true, opacity: 0.27, side: T.DoubleSide, depthWrite: false })); + this.storm.visible = false; + this.scene.add(this.storm); + window.addEventListener('resize', () => this.resize()); + this.resize(); + } + async load() { + const loader = new GLTFLoader(); + await Promise.all(['tree', 'ore', 'herb', 'player', 'sentinel', 'boss'].map(async kind => { + const gltf = await loader.loadAsync(`/models/${kind}.glb`); + gltf.scene.updateMatrixWorld(true); + this.models.set(kind, gltf.scene); + if (kind === 'player') return; + const batch: Batch = { parts: [], entities: [] }; + gltf.scene.traverse(child => { + if (!(child instanceof T.Mesh)) return; + const geometry = child.geometry.clone().applyMatrix4(child.matrixWorld); + const mesh = new T.InstancedMesh(geometry, child.material, kind === 'boss' ? 1 : 2048); + mesh.count = 0; + mesh.instanceMatrix.setUsage(T.DynamicDrawUsage); + mesh.castShadow = true; + mesh.receiveShadow = true; + mesh.userData.kind = kind; + this.scene.add(mesh); + batch.parts.push(mesh); + }); + this.batches.set(kind, batch); + })); + this.player = this.models.get('player')!.clone(true); + this.player.traverse(o => { if (o instanceof T.Mesh) { o.castShadow = true; o.receiveShadow = true; } }); + this.scene.add(this.player); + // Players share rigid placeholder geometry until animated LOD assets are available. + const template = this.models.get('player')!; + const peers: Batch = { parts: [], entities: [] }; + template.traverse(child => { + if (!(child instanceof T.Mesh)) return; + const mesh = new T.InstancedMesh(child.geometry.clone().applyMatrix4(child.matrixWorld), child.material, 2048); + mesh.count = 0; mesh.castShadow = true; mesh.userData.kind = 'player'; + this.scene.add(mesh); peers.parts.push(mesh); + }); + this.batches.set('player', peers); + const corpseMesh = new T.InstancedMesh(new T.BoxGeometry(1.1, 0.45, 2.1), new T.MeshStandardMaterial({ color: '#77766d' }), 2048); + corpseMesh.count = 0; corpseMesh.userData.kind = 'corpse'; this.scene.add(corpseMesh); + this.batches.set('corpse', { parts: [corpseMesh], entities: [] }); + } + resize() { + const width = innerWidth, height = innerHeight, aspect = width / height; + this.renderer.setSize(width, height, false); + const size = this.distance * (width < 800 ? 0.7 : 0.65); + this.camera.left = -size * aspect; this.camera.right = size * aspect; + this.camera.top = size; this.camera.bottom = -size; + this.camera.updateProjectionMatrix(); + } + quality(high: boolean) { + this.highQuality = high; this.renderer.shadowMap.enabled = high; + this.renderer.setPixelRatio(Math.min(devicePixelRatio, high ? 1.5 : 1)); + this.resize(); + } + addChunks(chunks: Chunk[], keys?: string[]) { + const keep = new Set(keys ?? chunks.map(c => c.key)); + for (const [key, chunk] of this.chunks) { + if (keep.has(key)) continue; + this.scene.remove(chunk.mesh); chunk.mesh.geometry.dispose(); + (chunk.mesh.material as T.Material).dispose(); this.chunks.delete(key); + } + for (const chunk of chunks) { + if (this.chunks.has(chunk.key)) continue; + const n = chunk.resolution, step = chunk.size / n; + const positions: number[] = [], colors: number[] = [], indices: number[] = []; + const green = new T.Color('#425e3e'), light = new T.Color('#748058'), stone = new T.Color('#829092'); + for (let z = 0; z <= n; z++) for (let x = 0; x <= n; x++) { + const wx = chunk.x * chunk.size + x * step, wz = chunk.z * chunk.size + z * step; + const h = chunk.heights[z * (n + 1) + x]; + positions.push(wx, h, wz); + const noise = (Math.sin(wx * 0.072) * Math.cos(wz * 0.052) + 1) / 2; + const patch = Math.max(0, Math.sin(wx * 0.018 + wz * 0.012) * Math.cos(wz * 0.025) - 0.22); + const color = green.clone().lerp(light, noise * 0.6).lerp(stone, Math.min(0.9, Math.max(0, (h - 5) / 10) + patch)); + if (Math.hypot(wx, wz) < 16) color.lerp(new T.Color('#97a07d'), 0.5); + colors.push(color.r, color.g, color.b); + } + for (let z = 0; z < n; z++) for (let x = 0; x < n; x++) { + const a = z * (n + 1) + x, b = a + 1, c = a + n + 1, d = c + 1; + indices.push(a, c, b, b, c, d); + } + const geometry = new T.BufferGeometry(); + geometry.setAttribute('position', new T.Float32BufferAttribute(positions, 3)); + geometry.setAttribute('color', new T.Float32BufferAttribute(colors, 3)); + geometry.setIndex(indices); geometry.computeVertexNormals(); + const mesh = new T.Mesh(geometry, new T.MeshStandardMaterial({ vertexColors: true, roughness: 1, flatShading: true })); + mesh.receiveShadow = true; + this.scene.add(mesh); this.chunks.set(chunk.key, { data: chunk, mesh }); + } + } + height(x: number, z: number) { + const chunk = this.chunks.get(`${Math.floor(x / 128)}:${Math.floor(z / 128)}`)?.data; + if (!chunk) return this.position.y; + const gx = (x - chunk.x * chunk.size) / chunk.size * chunk.resolution; + const gz = (z - chunk.z * chunk.size) / chunk.size * chunk.resolution; + const ix = Math.min(chunk.resolution - 1, Math.floor(gx)), iz = Math.min(chunk.resolution - 1, Math.floor(gz)); + const fx = gx - ix, fz = gz - iz, n = chunk.resolution + 1, i = iz * n + ix; + const [a, b, c, d] = [chunk.heights[i], chunk.heights[i + 1], chunk.heights[i + n], chunk.heights[i + n + 1]]; + return fx + fz <= 1 ? a + (b - a) * fx + (c - a) * fz : d + (c - d) * (1 - fx) + (b - d) * (1 - fz); + } + updateEntities(entities: Entity[]) { + for (const batch of this.batches.values()) batch.entities = []; + for (const entity of entities) this.batches.get(entity.kind)?.entities.push(entity); + for (const batch of this.batches.values()) { + const count = Math.min(2048, batch.entities.length); + for (let i = 0; i < count; i++) { + const e = batch.entities[i]; + this.dummy.position.set(e.position.x, e.position.y, e.position.z); + const variation = e.id.split('').reduce((n, c) => n + c.charCodeAt(0), 0); + this.dummy.rotation.set(0, e.kind === 'tree' || e.kind === 'ore' ? variation : 0, 0); + const scale = e.kind === 'tree' ? 0.85 + (variation % 6) * 0.07 : 1; + this.dummy.scale.setScalar(scale); this.dummy.updateMatrix(); + for (const mesh of batch.parts) mesh.setMatrixAt(i, this.dummy.matrix); + } + for (const mesh of batch.parts) { mesh.count = count; mesh.instanceMatrix.needsUpdate = true; mesh.computeBoundingSphere(); } + } + } + update(snapshot: Snapshot) { + this.snapshot = snapshot; + this.addChunks(snapshot.chunks, snapshot.chunkKeys); + const unavailable = new Set(snapshot.unavailableResources); + const resources = [...this.chunks.values()].flatMap(c => c.data.resources).filter(r => !unavailable.has(r.id)); + snapshot.entities = [...snapshot.entities, ...resources]; + this.updateEntities(snapshot.entities); + const p = snapshot.self.entity.position; + this.aim.set(p.x, p.y, p.z); + if (!this.initialized || this.position.distanceTo(this.aim) > 20) { this.position.copy(this.aim); this.focus.copy(this.aim); this.initialized = true; } + this.storm.visible = snapshot.world.phase === 'cataclysm'; + this.storm.scale.set(snapshot.world.safeRadius, 1, snapshot.world.safeRadius); + const danger = snapshot.world.phase === 'cataclysm'; + (this.scene.background as T.Color).set(danger ? '#c19f9e' : '#b9ccd0'); + (this.scene.fog as T.Fog).color.copy(this.scene.background as T.Color); + if (this.selected) this.selected = snapshot.entities.find(e => e.id === this.selected!.id); + } + pick(clientX: number, clientY: number): { entity?: Entity; point?: T.Vector3 } { + const rect = this.canvas.getBoundingClientRect(); + this.ray.setFromCamera(new T.Vector2((clientX - rect.left) / rect.width * 2 - 1, -(clientY - rect.top) / rect.height * 2 + 1), this.camera); + const objects: T.Object3D[] = []; + for (const batch of this.batches.values()) objects.push(...batch.parts); + const hit = this.ray.intersectObjects(objects, false)[0]; + if (hit?.instanceId !== undefined) { + const batch = this.batches.get(hit.object.userData.kind); + return { entity: batch?.entities[hit.instanceId] }; + } + return { point: this.ray.intersectObjects([...this.chunks.values()].map(c => c.mesh), false)[0]?.point }; + } + start(onFrame: (dt: number) => void) { + this.onFrame = onFrame; + this.renderer.setAnimationLoop(() => { + const dt = Math.min(this.clock.getDelta(), 0.05); + this.onFrame(dt); + // Presentation interpolation follows server positions; it never changes authoritative movement. + this.position.lerp(this.aim, 1 - Math.exp(-14 * dt)); + this.focus.lerp(this.position, 1 - Math.exp(-8 * dt)); + this.camera.position.copy(this.focus).add(new T.Vector3(0, 85, 80)); + this.camera.lookAt(this.focus); + if (this.player) { + this.player.position.copy(this.position); + const direction = this.aim.clone().sub(this.position); + if (direction.lengthSq() > 0.002) this.player.rotation.y = Math.atan2(-direction.x, -direction.z); + this.player.position.y += this.moving ? Math.sin(this.clock.elapsedTime * 15) * 0.09 : 0; + } + this.ring.position.copy(this.position); this.ring.position.y += 0.08; + this.selection.visible = !!this.selected; + if (this.selected) this.selection.position.set(this.selected.position.x, this.selected.position.y + 0.1, this.selected.position.z); + if (this.highQuality) { + this.sun.position.copy(this.focus).add(new T.Vector3(-60, 100, 45)); + this.sun.target.position.copy(this.focus); + } + this.renderer.render(this.scene, this.camera); this.frames++; + }); + } + diagnostics() { return { frames: this.frames, chunks: this.chunks.size, drawCalls: this.renderer.info.render.calls, triangles: this.renderer.info.render.triangles, models: this.models.size, position: this.position.toArray() }; } +} diff --git a/client/tsconfig.json b/client/tsconfig.json new file mode 100644 index 0000000..47fb677 --- /dev/null +++ b/client/tsconfig.json @@ -0,0 +1,9 @@ +{ + "compilerOptions": { + "target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM", "DOM.Iterable"], "strict": true, + "noEmit": true, "skipLibCheck": true, "allowImportingTsExtensions": true, + "types": ["vite/client"] + }, + "include": ["src"] +} diff --git a/client/vite.config.ts b/client/vite.config.ts new file mode 100644 index 0000000..cdb2361 --- /dev/null +++ b/client/vite.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'vite'; + +export default defineConfig({ + root: 'client', + build: { outDir: 'dist', target: 'es2022', chunkSizeWarningLimit: 650 }, + server: { + port: 5175, strictPort: true, + proxy: { '/api': 'http://127.0.0.1:18080', '/auth': 'http://127.0.0.1:18080', '/ws': { target: 'ws://127.0.0.1:18080', ws: true } }, + }, +}); diff --git a/deploy/argocd-application.example.yaml b/deploy/argocd-application.example.yaml new file mode 100644 index 0000000..10d7649 --- /dev/null +++ b/deploy/argocd-application.example.yaml @@ -0,0 +1,22 @@ +apiVersion: argoproj.io/v1alpha1 +kind: Application +metadata: + name: aeternalis + namespace: argocd +spec: + project: default + sources: + - repoURL: https://gitea.example.invalid/games/aeternalis.git + targetRevision: master + path: deploy/chart + helm: + valueFiles: [$values/apps/aeternalis/values.yaml] + - repoURL: https://gitea.example.invalid/infra/gitops.git + targetRevision: main + ref: values + destination: + server: https://kubernetes.default.svc + namespace: aeternalis + syncPolicy: + automated: { prune: false, selfHeal: true } + syncOptions: [CreateNamespace=true] diff --git a/deploy/chart/Chart.yaml b/deploy/chart/Chart.yaml new file mode 100644 index 0000000..0b57a80 --- /dev/null +++ b/deploy/chart/Chart.yaml @@ -0,0 +1,6 @@ +apiVersion: v2 +name: aeternalis +description: Independent authoritative Aeternalis worlds +type: application +version: 0.1.0 +appVersion: 0.1.0 diff --git a/deploy/chart/templates/network-policy.yaml b/deploy/chart/templates/network-policy.yaml new file mode 100644 index 0000000..e9cb0be --- /dev/null +++ b/deploy/chart/templates/network-policy.yaml @@ -0,0 +1,28 @@ +{{- if .Values.networkPolicy.enabled }} +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ .Release.Name }}-worlds +spec: + podSelector: + matchLabels: { app.kubernetes.io/name: aeternalis, app.kubernetes.io/instance: {{ .Release.Name | quote }} } + policyTypes: [Ingress, Egress] + ingress: + - from: + - namespaceSelector: + matchLabels: { kubernetes.io/metadata.name: {{ .Values.networkPolicy.ingressNamespace | quote }} } + ports: [{ protocol: TCP, port: 8080 }] + egress: + - to: + - namespaceSelector: + matchLabels: { kubernetes.io/metadata.name: {{ .Values.networkPolicy.dnsNamespace | quote }} } + ports: [{ protocol: UDP, port: 53 }, { protocol: TCP, port: 53 }] + {{- range .Values.networkPolicy.databaseCIDRs }} + - to: [{ ipBlock: { cidr: {{ . | quote }} } }] + ports: [{ protocol: TCP, port: 5432 }] + {{- end }} + {{- range .Values.networkPolicy.identityCIDRs }} + - to: [{ ipBlock: { cidr: {{ . | quote }} } }] + ports: [{ protocol: TCP, port: 443 }] + {{- end }} +{{- end }} diff --git a/deploy/chart/templates/worlds.yaml b/deploy/chart/templates/worlds.yaml new file mode 100644 index 0000000..69f8b05 --- /dev/null +++ b/deploy/chart/templates/worlds.yaml @@ -0,0 +1,83 @@ +{{- $root := . -}} +{{- $directory := list -}} +{{- range .Values.worlds -}} +{{- $directory = append $directory (dict "id" .id "url" (printf "https://%s" .host)) -}} +{{- end -}} +{{- range .Values.worlds }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ $root.Release.Name }}-{{ .id }} + labels: { app.kubernetes.io/name: aeternalis, app.kubernetes.io/instance: {{ $root.Release.Name | quote }}, aeternalis.world: {{ .id | quote }} } +spec: + replicas: 1 + strategy: { type: Recreate } + revisionHistoryLimit: 3 + selector: + matchLabels: { app.kubernetes.io/instance: {{ $root.Release.Name | quote }}, aeternalis.world: {{ .id | quote }} } + template: + metadata: + labels: { app.kubernetes.io/name: aeternalis, app.kubernetes.io/instance: {{ $root.Release.Name | quote }}, aeternalis.world: {{ .id | quote }} } + spec: + automountServiceAccountToken: false + terminationGracePeriodSeconds: 30 + imagePullSecrets: {{ $root.Values.imagePullSecrets | toJson }} + securityContext: + runAsNonRoot: true + runAsUser: 65532 + runAsGroup: 65532 + seccompProfile: { type: RuntimeDefault } + containers: + - name: world + image: {{ if $root.Values.image.digest }}{{ printf "%s@%s" $root.Values.image.repository $root.Values.image.digest | quote }}{{ else }}{{ printf "%s:%s" $root.Values.image.repository $root.Values.image.tag | quote }}{{ end }} + imagePullPolicy: IfNotPresent + ports: [{ name: http, containerPort: 8080 }] + securityContext: + readOnlyRootFilesystem: true + allowPrivilegeEscalation: false + capabilities: { drop: [ALL] } + env: + - { name: APP_ENV, value: production } + - { name: LISTEN_ADDR, value: "0.0.0.0:8080" } + - { name: WORLD_ID, value: {{ .id | quote }} } + - { name: WORLD_SEED, value: {{ .seed | quote }} } + - { name: PUBLIC_URL, value: {{ printf "https://%s" .host | quote }} } + - { name: WORLD_DIRECTORY, value: {{ $directory | toJson | quote }} } + envFrom: + - secretRef: { name: {{ $root.Values.existingSecret | quote }} } + resources: {{ $root.Values.resources | toJson }} + startupProbe: { httpGet: { path: /readyz, port: http }, periodSeconds: 5, failureThreshold: 24 } + readinessProbe: { httpGet: { path: /readyz, port: http }, periodSeconds: 3, failureThreshold: 2 } + livenessProbe: { httpGet: { path: /healthz, port: http }, periodSeconds: 10, failureThreshold: 3 } +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ $root.Release.Name }}-{{ .id }} +spec: + selector: { app.kubernetes.io/instance: {{ $root.Release.Name | quote }}, aeternalis.world: {{ .id | quote }} } + ports: [{ name: http, port: 8080, targetPort: http }] +--- +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: {{ $root.Release.Name }}-{{ .id }} + annotations: + nginx.ingress.kubernetes.io/proxy-read-timeout: "3600" + nginx.ingress.kubernetes.io/proxy-send-timeout: "3600" + nginx.ingress.kubernetes.io/proxy-body-size: "8k" + nginx.ingress.kubernetes.io/limit-rps: "10" + nginx.ingress.kubernetes.io/ssl-redirect: "true" +spec: + ingressClassName: {{ $root.Values.ingress.className | quote }} + tls: [{ hosts: [{{ .host | quote }}], secretName: {{ $root.Values.ingress.tlsSecret | quote }} }] + rules: + - host: {{ .host | quote }} + http: + paths: + - path: / + pathType: Prefix + backend: + service: { name: {{ $root.Release.Name }}-{{ .id }}, port: { name: http } } +{{- end }} diff --git a/deploy/chart/values.schema.json b/deploy/chart/values.schema.json new file mode 100644 index 0000000..3e868db --- /dev/null +++ b/deploy/chart/values.schema.json @@ -0,0 +1,10 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["worlds", "existingSecret", "image"], + "properties": { + "worlds": {"type": "array", "minItems": 1, "items": {"type": "object", "required": ["id", "seed", "host"], "properties": {"id": {"type": "string", "pattern": "^[a-z][a-z0-9-]{0,30}$"}, "seed": {"type": "string", "pattern": "^[0-9]{1,15}$"}, "host": {"type": "string", "minLength": 1}}}}, + "existingSecret": {"type": "string", "minLength": 1}, + "image": {"type": "object", "required": ["repository", "tag", "digest"], "properties": {"repository": {"type": "string", "minLength": 1}, "tag": {"type": "string", "minLength": 1}, "digest": {"type": "string", "pattern": "^(sha256:[a-f0-9]{64})?$"}}} + } +} diff --git a/deploy/chart/values.yaml b/deploy/chart/values.yaml new file mode 100644 index 0000000..adefe07 --- /dev/null +++ b/deploy/chart/values.yaml @@ -0,0 +1,37 @@ +image: + repository: harbor.example.invalid/games/aeternalis + tag: bootstrap + digest: "" +imagePullSecrets: + - name: harbor-pull +existingSecret: aeternalis-runtime +ingress: + className: nginx + tlsSecret: aeternalis-tls +worlds: + - id: world-001 + seed: "734291" + host: world-001.aeternalis.example.invalid + - id: world-002 + seed: "829312" + host: world-002.aeternalis.example.invalid + - id: world-003 + seed: "942731" + host: world-003.aeternalis.example.invalid + - id: world-004 + seed: "1037412" + host: world-004.aeternalis.example.invalid + - id: world-005 + seed: "1123491" + host: world-005.aeternalis.example.invalid +resources: + requests: { cpu: "500m", memory: "256Mi" } + limits: { cpu: "2", memory: "1Gi" } +networkPolicy: + enabled: true + ingressNamespace: ingress-nginx + # Explicitly set actual database and OIDC provider IP ranges before deployment. + databaseCIDRs: [] + identityCIDRs: [] + # Kube-dns defaults; adjust for clusters using NodeLocal DNSCache. + dnsNamespace: kube-system diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..3a38791 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,116 @@ +# Architecture and vision review + +Reviewed 2026-09-05 against `C:/Dev/aeternalis/planning/VISION.md` and the earlier +RPGTheory design notes. The new weekly boss rule is authoritative over the older +uncertain session-ending description. + +## Assessment + +The vision has a coherent distinguishing loop: players invest in a single life, +cooperate against a closing deadline, and earn passage to a new world. The browser +is a reasonable first client. Chunk subscriptions and GPU instancing address some +client costs, but do not prove that thousands of players can gather around one boss. +Changing to a native client would not remove simulation, bandwidth, or persistence +bottlenecks. Measure before changing platforms. + +The highest-risk requirements are: + +1. **Death and transfers must remain correct after retries, crashes, and redeploys.** + A duplicated survivor or resurrected character undermines the one-life premise. +2. **One world is explicitly one server instance.** Kubernetes adds world capacity + by adding independent owners; replicating the same world deployment does not + share its simulation. A crowded final boss bypasses the benefit of small AOIs. +3. **Nine 128-unit chunks are a subscription rule, not a complete scaling plan.** + Entity density, bytes/update, allocation rate, AI work, and client draw cost need + separate budgets and load measurements. +4. **Two hours per day and a destructive weekly event interact.** The prototype + protects a capped character from enemies in a central safe zone, but does not + exempt it from final world collapse or grant passage before the boss dies. + Offline-world survival is an explicit provisional rule requiring playtesting. +5. **Five worlds opened together also reach their deadlines together.** Operators + need to open fresh destinations before survivors transfer. There is no automatic + Kubernetes world allocator in this slice. + +## Implemented boundaries + +One Go process owns one world, with a serial simulation protected by one lock. +Clients submit bounded intents. The server determines speed, terrain height, +range, cooldown, inventory changes, damage, death, play-time, and passage eligibility. +Movement is interpolated on the client; full prediction/reconciliation is deferred. +No rigid-body physics is claimed: this is heightfield movement in open terrain. + +The simulation ticks at 20 Hz; snapshots are sent at 5 Hz. Coordinates use X/Z +chunk indices and Y height. Terrain has a vertical coordinate but is a 2.5D +heightfield, **not** a volumetric 128x128x128 voxel world. Overhangs, caves, stacked +chunks, and fully destructible voxel terrain require another generator/version. +Destruction currently means a shrinking hazardous boundary, not terrain deformation. + +OpenSimplex supplies seeded noise. A versioned generator produces chunk meshes and +resources only as needed. Mesh height and server collision height share a triangle +split. A connection subscribes to current chunk + eight neighbors. Unchanged +terrain and static resource transforms are not resent; resource availability IDs +and dynamic entities are filtered by this area. GPU terrain is disposed +on eviction. Repeated GLB meshes use instancing; camera frustum culling is separate +from network interest. The server retains mutation deltas across chunk eviction. + +The finite circular world, 48-unit spawn separation, 100-character capacity, +combat numbers, terrain details, mob scaling, and respawn periods are provisional +defaults. They are not newly confirmed design decisions. Balance is validated and +persisted with the world; editing YAML affects newly created world IDs only. + +## Durability and ownership + +Development uses SQLite WAL. Production requires PostgreSQL with TLS certificate +verification. Both use the same storage tests and transaction behavior. + +The `worlds` row has an expiring owner token and a monotonically increasing +revision. Every save atomically checks owner, lease expiry using database time, +and expected revision. A competing process cannot acquire an unexpired lease, +and a previous owner cannot write after replacement. Lease renewal accompanies +regular saves; a stopped/crashed process releases or expires after 30 seconds. + +World snapshots are saved every second and on material gameplay changes before +the next client snapshot. Victory creates survivor passage records in that same +transaction. A destination saves its imported character and marks the passage +redeemed in one transaction. Later victories can issue a new passage for the same +character ID; old source servers cannot overwrite it. Account identity is checked +at redemption, and the destination rejects duplicate accounts/characters. + +On storage failure the process freezes and fails readiness/liveness, closes its +sockets, and must restart/reload durable state. This avoids continuing after an +ambiguous commit. Default shutdown allows 10 seconds to save and release ownership. +Treat backup/restore as an explicit administrative operation: restoring an old +database can reverse deaths and transfers, so production needs a restoration policy. + +**Prototype durability limit:** an abrupt crash can roll back up to one second of +position and daily play usage. Gameplay mutations are acknowledged after a save; +unacknowledged inputs can disappear. Whole-world JSON checkpoints occur under the +simulation lock and are deliberately a simple first implementation. Before public +permadeath or large worlds, replace this with a durable event log, asynchronous +checkpoints, versioned migrations, and crash/latency fault injection. + +## Security scope + +- Production login: OIDC verification (issuer, audience, signature, expiry), PKCE, + state and nonce binding, and opaque server-side sessions. +- Secure, HttpOnly, SameSite cookies. No client-controlled identity or progression. +- Explicit same-origin checks on mutations and WebSockets; no permissive CORS. +- Strict JSON parsing, small input limits, sequence checks, HTTP/WS rate limits, + action validation, movement timeout, and bounded slow-consumer queues. +- CSP, no framing, MIME sniff protection, HSTS in production, and no token logging. +- A non-root, read-only runtime container with all capabilities dropped, no service + account token, health probes, TLS ingress, and limited network egress. + +The application limiter uses the real TCP peer address, **not untrusted forwarded +headers**. Behind ingress this may group many users into one bucket. Configure +trusted-proxy-aware rate limiting before public load; the chart's ingress rate +limit is an additional layer. OIDC provider callbacks and JWKS refresh, TLS, network +policies, actual ingress behavior, backups, secret rotation, and dependency scanning +must be tested on the real cluster. This code is not a completed security audit. + +## Source references + +- [Three.js instanced rendering](https://threejs.org/docs/pages/InstancedMesh.html) +- [Three.js object-count optimization](https://threejs.org/manual/en/optimize-lots-of-objects.html) +- [Kubernetes security contexts](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) +- [Gitea Actions runner setup](https://docs.gitea.com/usage/actions/quickstart/) diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md new file mode 100644 index 0000000..1474784 --- /dev/null +++ b/docs/DEPLOYMENT.md @@ -0,0 +1,106 @@ +# Kubernetes and Gitea deployment + +The chart and workflow are provided for configuration and cluster validation. +No image has been published, no GitOps repository has been modified, and no +cluster resources have been applied by this implementation session. + +## Runtime prerequisites + +- PostgreSQL database shared by all worlds, with verified TLS. The runtime needs + table/index creation for initial bootstrap, then reads and writes in its own + database. A separate migration job and reduced DDL privileges are follow-up work. +- An OIDC provider/client with exact callbacks for each world: + `https:///auth/callback`. Use one client accepting these registered + callbacks or extend the chart to use per-world credentials. Never use wildcards. +- Harbor registry project and a pull-only robot credential for Kubernetes. +- An ingress controller that supports WebSocket upgrades and preserves Host, + certificates covering all world hosts, working DNS, and NetworkPolicy enforcement. +- ArgoCD with read access to the application and GitOps repositories. + +Create the runtime secret through your existing secret manager (e.g. External +Secrets or sealed secrets). Do not put actual secret values into this repository. +The named secret `aeternalis-runtime` must contain: + +| Key | Value | +|---|---| +| `DATABASE_URL` | `postgres://user:password@db.example/db?sslmode=verify-full` | +| `OIDC_ISSUER` | Exact HTTPS issuer URL | +| `OIDC_CLIENT_ID` | Registered client ID | +| `OIDC_CLIENT_SECRET` | Client secret, if required by your provider | + +Certificates from the image's system CA bundle are trusted. Mount a custom CA and +configure the PostgreSQL/HTTPS clients if your infrastructure uses a private CA; +that mounting is site-specific and not included in the sample chart. + +Configure `deploy/chart/values.yaml` (prefer an external GitOps values file): + +1. Set image repository, pull secret, runtime secret, TLS secret, and actual hosts. +2. Set `networkPolicy.databaseCIDRs` and `identityCIDRs` to the actual permitted + destinations. Empty lists deny these connections, so the server will not start + until the allowlists match. Adjust DNS rules for NodeLocal DNSCache if used. +3. Adjust requests/limits after measuring on cluster hardware. Defaults are initial + allocations, not a capacity guarantee. +4. Render and inspect with `helm lint` and `helm template`; validate against the + target cluster version using your normal dry-run pipeline. + +## Gitea setup + +Enable Actions in the repository. Use a runner with the `ubuntu-latest` label, +Node/Go setup support, service-container networking, and Docker build capability. +The publication runner should be trusted; do not expose a privileged Docker socket +to untrusted pull-request jobs. The verify job has no deployment credentials. +Action references use upstream version tags; mirror/pin these to reviewed commits +under your organization's supply-chain policy before production use. + +Set repository variables: + +| Variable | Example | +|---|---| +| `HARBOR_HOST` | `harbor.your-domain` (no scheme) | +| `HARBOR_PROJECT` | `games` | +| `GITOPS_REPOSITORY` | `https://gitea.your-domain/infra/gitops.git` | +| `GITOPS_BRANCH` | `main` | +| `GITOPS_VALUES_FILE` | `apps/aeternalis/values.yaml` | + +Set repository secrets `HARBOR_USERNAME`, `HARBOR_PASSWORD`, `GITOPS_USERNAME`, +and `GITOPS_TOKEN`. Use a Harbor project-scoped push robot and a token restricted +to the intended GitOps repository. An empty `GITOPS_REPOSITORY` skips promotion. +Harbor publication still requires its own variables/secrets. + +On a push to `master` or `main`, CI verifies generated contracts, TypeScript, +production client build, Go tests with the race detector, real PostgreSQL storage +integration, browser tests, Go vet, and Helm rendering. It builds/publishes an image +tagged with the commit SHA, then updates the GitOps values to the image's immutable +digest. ArgoCD reconciles that change. No kubeconfig is handed to CI. + +Copy and configure `deploy/argocd-application.example.yaml`. It uses ArgoCD's +multiple-source Application support: chart from the app repository, values from +the GitOps repository. Pruning is disabled in the example to avoid silently +deleting worlds when editing the list. Monitor promotion failures; concurrent +GitOps commits are rejected by a normal non-force push and must be retried. + +## Add worlds and retire seasons + +Each world gets a distinct Deployment, Service, hostname, ID, seed, and database +row. `replicas: 1` and `Recreate` are intentional. An expiring DB lease also fences +duplicate processes. Increasing replicas does not increase one world's capacity. + +To add capacity, append a world entry with a never-used ID and fresh seed, register +its OIDC callback and DNS/TLS, and sync ArgoCD. Open destination worlds before the +current cohort wins; five worlds launched together have the same deadline. +The world directory is supplied to every client, and passages are visible to the +same account after signing into a destination. + +Retire a finished world's workload only after confirming its persisted outcome and +passages. Keep its database row and passage history. Never reuse its ID: restarted +IDs restore their old state. Rolling the code back does not roll the database back. +Balance/seed changes do not mutate a running saved world's rules. + +## Before public access + +Run a real OIDC login and cross-host survivor transfer, restart/kill a pod during +combat and victory, simulate database failure, validate NetworkPolicy and TLS, +and test peak boss crowding. Add observability and alerting, versioned migrations, +durable event recording, abuse controls, account-level cap policy if chosen, and +an operational backup/restore procedure. The current prototype is suitable for +controlled development playtests after deployment validation. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md new file mode 100644 index 0000000..aa3efca --- /dev/null +++ b/docs/ROADMAP.md @@ -0,0 +1,64 @@ +# Implementation status and next work + +## Playable in this slice + +- Browser 3D scene, original Blender placeholder GLBs, instanced resource meshes, + desktop/touch controls, target selection, inventory, recipes, skills display. +- Seeded streamed heightfield chunks, negative coordinates, seamless borders, + server-authoritative terrain height, 3x3 subscriptions, client chunk eviction. +- Persistent character identity and starting kit; gathering, spear/bandage crafting, + XP counters, basic melee, healing, roaming/respawning zone-confined enemies. +- Seven-day boss deadline, development trigger, shrinking danger boundary, + permanent death, corpses, frozen victory, account-bound atomic survivor passages. +- Two-hour daily character cap, safe relocation, HP floor, logout, next-day keystone. +- SQLite local persistence, PostgreSQL production adapter, exclusive world leases, + strict intents, OIDC, secure cookies, origin checks, bounded sockets/rate limits. +- Gitea verification/publication/GitOps workflow, Dockerfile, five-world Helm chart, + TLS ingress, probes, pod security, network policy, ArgoCD example. + +## Deliberate gaps + +- **2,000 players in one world:** unverified. Default is 100 admitted characters per + world. Current snapshot construction and enemy searches scan world collections; + whole-world persistence can stall ticks. Do not raise capacity based on unit tests. +- **Procedural volume/destruction:** current terrain is a heightfield. The storm + destroys playable space; it does not erode individual terrain cells or structures. +- **Permadeath durability:** last second of movement/time can roll back on abrupt + crash; public permadeath needs event persistence and failure injection. +- **PvP and corpse priority:** disabled/unimplemented. Corpse items can currently be + looted by nearby living players. The highest-damage-attacker lock and close-to- + release rule must ship together with PvP, not be inferred from PvE behavior. +- **Stats/body parts/dynamic skills:** XP counters exist, not the complete formula, + emergent-skill, multi-limb damage, or level/stat allocation systems. +- **Progression:** gathering/crafting content is intentionally small. Fishing, + alchemy stations, smithing, buildable structures, loot tables, and hunger are absent. +- **Operations:** no admin center, chat/moderation, leaderboards, account management, + automatic world provisioning, observability dashboard, or migration framework. +- **Art:** rigid placeholders; no rigged locomotion, attack telegraphs, audio, or LODs. +- **Networking:** interpolated movement without prediction; full entity snapshots + at 5 Hz, not packed/delta entity replication; no proven large-crowd behavior. + +## Next milestones + +1. Playtest the small loop and decide offline/capped survival during the final boss, + return timing, boss telegraphs, and whether peers cooperate or can attack each other. +2. Add a durable event log, versioned database migrations, transfer race/failure + stress tests, and restart recovery. Prove PostgreSQL and OIDC on the real cluster. +3. Add chunk-indexed entity lookups, network byte/tick/allocation telemetry, and + incremental entity replication. Load-test spread populations and a concentrated + boss arena at 50, 100, 250, 500, and then higher only as measurements allow. +4. Build proper enemy telegraphs, animation/LOD pipeline, collision/navigation, and + client prediction. Compare browser frame time on actual target hardware. +5. Implement the full progression and PvP/loot rules with focused tests. Add admin + inspection, leaderboard persistence, account controls, and moderation. +6. Automate lifecycle-aware world provisioning once transfers and retirement are + proven operationally. Keep world creation out of untrusted client requests. + +## Open design questions retained + +The original unresolved good-karma source, exact spawn separation, node dimensions, +full starting gear, and mob scaling policy remain open. This build uses configurable +placeholders (world-age mob scaling resets with each new world). New clarification: +the boss spawns after seven days and slowly destroys the world until defeated or +until no survivors remain. Collapse duration, damage behavior, offline safety, +and the fresh-world opening cadence still need design approval through playtesting. diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md new file mode 100644 index 0000000..bf0e952 --- /dev/null +++ b/docs/VERIFICATION.md @@ -0,0 +1,61 @@ +# Verification performed + +Local checks on Windows, 2026-09-05. Node 24.13.0, Go 1.27.1, Blender 4.3.2, +Helm 3.18.6, and headless Microsoft Edge driven by Playwright. + +## Passing checks + +- Generated Go/TypeScript contract drift check, TypeScript strict checking, and + production Vite build. Main JavaScript: 600.22 KB, 156.65 KB gzip estimate. +- Go tests: deterministic terrain and seams, movement bounds/replay rejection, + chunk interest, gathering/crafting, permanent death across restart, daily cap, + real wall-time accounting under lag, keystone safety, boss victory/collapse, + offline survivors, transfer progress preservation, resource replication. +- Storage tests: exclusive ownership, stale-owner rejection, durable passages, + cross-account denial, duplicate redemption rejection, simultaneous redemption + at two destinations, later-world passages, session revocation. +- HTTP/WebSocket tests: origin rejection, HttpOnly sessions, unknown JSON fields, + initial chunk delivery, private identity exclusion, malformed socket input. +- `go vet ./...`. +- Four Playwright tests: desktop rendering/movement/gather/reconnect; mobile + portrait and landscape controls/layout; HTTP security behavior; boss rendering + and actual server-authoritative boss damage. Canvas pixel variation, loaded + models, triangle counts, and progressing render frames were checked. +- Desktop, mobile, landscape, and boss screenshots visually inspected. +- Helm lint and rendering: five distinct Deployments/Services/Ingresses plus a + NetworkPolicy. No cluster resources were applied. + +## Initial concurrency measurement + +`go run ./cmd/load -url http://127.0.0.1:18090 -clients 20 -duration 15s` + +Twenty authenticated WebSocket clients on an isolated local development world, +with periodic movement/idle intents and snapshot reads. Join setup is excluded +from the throughput window. This is a short connection/replication smoke test, +not a long-duration soak, active combat workload, mobile hardware benchmark, or +large final-boss crowd test. + +| Measurement | Before static-resource optimization | After | +|---|---:|---:| +| Concurrent clients | 20 | 20 | +| Measurement duration | 15 seconds | 15 seconds | +| Delivered snapshots | 1,500 | 1,500 | +| Outgoing application payload | 7,548.5 KiB/s | 560.3 KiB/s | +| p95 interval between snapshots | 206.9 ms | 203.0 ms | +| Unexpected disconnections | 0 | 0 | + +The target snapshot interval is 200 ms. Sending static resource transforms once +per chunk reduced measured outgoing payload by about 92.6%. Figures exclude TCP, +WebSocket, and TLS framing. CPU/RAM/GPU saturation and 2,000 players remain unproven. + +## Not executed locally + +- Docker image build/runtime: Docker Desktop's Linux daemon was not running. +- PostgreSQL-backed tests: no test database was configured locally; the workflow + provides a PostgreSQL service and runs the same storage lifecycle suite there. +- Go race detector: no local C toolchain was available; the Linux CI job runs it. +- Real OIDC-provider login, cross-host production transfer, TLS ingress, network + policy enforcement, image publication, ArgoCD sync, and Kubernetes rollout. + +The Playwright Chromium download timed out; all browser tests ran successfully +using installed Edge instead. CI is configured to install Chromium. diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..c9e05d7 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1629 @@ +{ + "name": "aeternalis", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "aeternalis", + "dependencies": { + "lucide": "^0.468.0", + "three": "^0.180.0" + }, + "devDependencies": { + "@playwright/test": "^1.55.0", + "@types/three": "^0.180.0", + "quicktype-core": "^23.2.6", + "typescript": "^5.9.2", + "vite": "^7.1.0", + "yaml": "^2.8.1" + } + }, + "node_modules/@dimforge/rapier3d-compat": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz", + "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@glideapps/ts-necessities": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/@glideapps/ts-necessities/-/ts-necessities-2.2.3.tgz", + "integrity": "sha512-gXi0awOZLHk3TbW55GZLCPP6O+y/b5X1pBXKBVckFONSwF1z1E5ND2BGJsghQFah+pW7pkkyFb2VhUQI2qhL5w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@playwright/test": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz", + "integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.63.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.63.1.tgz", + "integrity": "sha512-UZ8sUxPTiHWYX9QNdJedb1kDZSpS1t/VPWBWGSgqHNi9w3Cu6IXvu2mzbhiTiPvtrqgTQJ+zqiAq2iPIPilpaQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.63.1.tgz", + "integrity": "sha512-cQ4nFQABN5cDvDpbvJ7bMStCpnaVxynZrRMfUJYgxcIk9Sh54FIO1vtfkg0B69REjER77ioZ/ov+eAApx/KmLQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.63.1.tgz", + "integrity": "sha512-FQNqd1lRy/0QhDk3xeRIkSBiCpXCiDnZO3YLVdcDKN1UBiKToNftCzcXYNLshmPDUMlu2TdeS8tGcsU6f3YF1Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.63.1.tgz", + "integrity": "sha512-pvD16V939D3CloK0+qikpGaxiPrDUXTe7Y5cWOMkMSy7m1cawa8EGy/kXYi/G/cKAC4HDAbSnzCIk1WmsoOKXg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.63.1.tgz", + "integrity": "sha512-pcFGeL2345VwdTnJhA6zLbew+YgWB0qBG2+dMtXjCicf6+rm6kO6cOoh5VnTe0ZMrMRgRyuHmCJxZWrIdzYuOw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.63.1.tgz", + "integrity": "sha512-mRJlqSRulVzcKq/LKA6ICSIc3K/l4fzlVn/gePn2nXIHy8seRi5z/eeRE0d/XMBxcMldiXtQTSpRj0tkkC3g8Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.63.1.tgz", + "integrity": "sha512-YDUNvVM85TI3g/1OpnqKP1h4NeW/j64DfWMf+G3M809xNk1bJSnpFp4sh83NpmVE5DXnkh8ULor4LTVZKoYLHw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.63.1.tgz", + "integrity": "sha512-7Mcn71p9ZuQFAj+h+dhQXy/yeLePRS2yKRnmW1DijA9thKO5qap0GNOIQK4yQ6iP3SU0Mrb/yWo8h8vgRba8lw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.63.1.tgz", + "integrity": "sha512-4YiLQTX6U4CSl0L9cluep9A9W6UmTfqBDc2/CH6wlu54pl4E7Jn3cOD8oxzvBDEGk/JMKgJ47C8g+radF7mwvg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.63.1.tgz", + "integrity": "sha512-2ra8F7w8OquwZN9z2/fKFnli69wa8PLwaVzRMIPGb13ByMJwC28Fbp8YcVGoUhlYMTt7j5j9bNgpysrN2UM+vw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.63.1.tgz", + "integrity": "sha512-Sy20ncyhjmBP0Ml+UvQbimjlk6VFgjW5uNP+qqwHB00mTE8Bl2C1TuHTlRwK2YoXeZbee5lP2XevBWVkAQAtSQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.63.1.tgz", + "integrity": "sha512-noITLp8oNjYliPnGWmLyelIHwULGqbHloQHGw1rtxbWhTuWooRpnZarZQJ1y9EUC4szuCusCc+HEpUtxpIwYvA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.63.1.tgz", + "integrity": "sha512-hlxxXd+F1mWiAcaFR7Sv9ZQT6m6UfI8+Vy/kFJzztq2pDMU/0wZ9sish0iszNZvsQDo8Gc0i5yuFEOz5dDf6fA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.63.1.tgz", + "integrity": "sha512-EF7OpqQTQ/BvGqLzUi4rEHuagCV9MugAUXSHemwPW5vxZ75RR+jxO/2j95Ph2dalMpFHSVECjRoioHZgA9zOYA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.63.1.tgz", + "integrity": "sha512-wQO3JesW9PRkwlabQ27y7sPfVOOTLRG73I4F2UYHG5PXun3J9U3y+b7ezVKSYbsvSKGQ1k1cq8Qlun4C9kLt3w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.63.1.tgz", + "integrity": "sha512-ouAGwhO6wHRXdnOVCOsB0tRFkA7nhNB2Nwax6oECXN0YiN8EYUTBAOudADOB1PI+yDL61TeNx/u7MVCzksNbkQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.63.1.tgz", + "integrity": "sha512-q2R38Sn+1J8RxhfJ+T54wSWmyKXWec+9jgDfqO2AtArEqHO5R2aeayp5H5OYLr5UYDVGsVaZPEFUooMhYCdz5A==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.63.1.tgz", + "integrity": "sha512-gfI5T24WLLuFfSKw7Go/zDXjAAV0fny0swTaDv+WjK7vqcw4cRhFfdsyKL1n+ukI+ooBxn3bVQnyrn06WpI50w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.63.1.tgz", + "integrity": "sha512-4h6XqthmB4Hspji84wvgk+ElodTsGj+dbZqHJHHtKxj4mYq0ANSEEPX9ys3moJueqsRjwpaJYH7874Itwnj2ow==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.63.1.tgz", + "integrity": "sha512-dlfCOa87o1VAYegLQ9EKilx2JCeRofiyPGhTCmqnuXZ6bMPiycO1rq1+sKoulAp7pGLIsTIw+1x5R+zgh5LhhA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.63.1.tgz", + "integrity": "sha512-cjkLbOlfcm3QGhMM1J5zaZjsw1GggbN6rw9UTSSRrPrR1KkcXnN7Uq9rPw34xImQ9VOY9GN+6u2Zj80B9ptkcw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.63.1.tgz", + "integrity": "sha512-Li1KdUnWGE4N3e1F/B4RTB1ms+nG4WBgjByO46pkeBVX/2UBsY53xf5vK9WygVmnH3RwncIST7lkSdLSY6P9lg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.63.1.tgz", + "integrity": "sha512-t4ZYOSoLTgwhuFMrmTMLx/+i1DQVK7HYqMc6kY46EApwi8X0nIVphzdNoThU3xt6n+N5urG1/gxBdCaKDLavfg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.63.1.tgz", + "integrity": "sha512-RgroPfMmKlD1RzSDxvwgcPiy2HNQKoYV7OmwIXDsk73uKW5t6B/V8KIy27SMv/FNXFo/oSBtWc9J0X7t91ezZg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.63.1.tgz", + "integrity": "sha512-at8QVep6S3h5Y6gSbdGU06bRY5WJkf6WUduM9YtvYMbYhB1MOFfUgc6kehitQXzOtMSaT70q7f9ydPhpqu821w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@tweenjs/tween.js": { + "version": "23.1.3", + "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz", + "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/stats.js": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz", + "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/three": { + "version": "0.180.0", + "resolved": "https://registry.npmjs.org/@types/three/-/three-0.180.0.tgz", + "integrity": "sha512-ykFtgCqNnY0IPvDro7h+9ZeLY+qjgUWv+qEvUt84grhenO60Hqd4hScHE7VTB9nOQ/3QM8lkbNE+4vKjEpUxKg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@dimforge/rapier3d-compat": "~0.12.0", + "@tweenjs/tween.js": "~23.1.3", + "@types/stats.js": "*", + "@types/webxr": "*", + "@webgpu/types": "*", + "fflate": "~0.8.2", + "meshoptimizer": "~0.22.0" + } + }, + "node_modules/@types/webxr": { + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz", + "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webgpu/types": { + "version": "0.1.72", + "resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.72.tgz", + "integrity": "sha512-0cF7RFM2edNoiIS1ODJp0/Gzv4/xSXhwoR0YCza+OWpJWtn4wmo9DvK91aLlH9+uUnwIriP7ZiC3WitmyhuzBw==", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "dev": true, + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/browser-or-node": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/browser-or-node/-/browser-or-node-3.0.0.tgz", + "integrity": "sha512-iczIdVJzGEYhP5DqQxYM9Hh7Ztpqqi+CXZpSmX8ALFs9ecXkQIeqRyM6TfxEfMVpwhl3dSuDvxdzzo9sUOIVBQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/collection-utils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/collection-utils/-/collection-utils-1.0.1.tgz", + "integrity": "sha512-LA2YTIlR7biSpXkKYwwuzGjwL5rjWEZVOSnvdUc7gObvWe4WkjxOpfrdhoP7Hs09YWDVfg0Mal9BpAqLfVEzQg==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/cross-fetch": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-4.1.0.tgz", + "integrity": "sha512-uKm5PU+MHTootlWEY+mZ4vvXoCn4fLQxT9dSc1sXVMSFkINTJVN8cAQROpwcKm8bJ/c7rgZVIBWzH5T78sNZZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "node-fetch": "^2.7.0" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "dev": true, + "license": "MIT" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/is-url": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/is-url/-/is-url-1.2.4.tgz", + "integrity": "sha512-ITvGim8FhRiYe4IQ5uHSkj7pVaPDrCTkNd3yq3cV7iZAcJdHTUMPMEHcqSOy9xZ9qFenQCvi+2wjH9a1nXqHww==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-base64": { + "version": "3.9.3", + "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-3.9.3.tgz", + "integrity": "sha512-uwYQp+VJ38FVvtim6qNbit6e9uT6dwWQ4Y1+H9TxhW5hcHjpHwoxlR0nMpqUmIFOmu4VqMxwdJA88gIVuZJQ/g==", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/lucide": { + "version": "0.468.0", + "resolved": "https://registry.npmjs.org/lucide/-/lucide-0.468.0.tgz", + "integrity": "sha512-UFbgwji/ZnAV7iTTE4jujyTV7J95AILKyATDUrqOJrMcUGfXvGjw3c1mcuHZUX2oJfkrAGU9KoxkrLQk2jjtiA==", + "license": "ISC" + }, + "node_modules/meshoptimizer": { + "version": "0.22.0", + "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-0.22.0.tgz", + "integrity": "sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.18", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz", + "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "dev": true, + "license": "(MIT AND Zlib)" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/playwright": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz", + "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.63.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz", + "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/pluralize": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-8.0.0.tgz", + "integrity": "sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss": { + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/quicktype-core": { + "version": "23.3.25", + "resolved": "https://registry.npmjs.org/quicktype-core/-/quicktype-core-23.3.25.tgz", + "integrity": "sha512-WOKJw/DemC1pO8CD0tgZ/Fn8FzWvWIeLPrbfpwfNbnPoXnehNgDRFesPYpgrNlF0Pce98aUBqqT55fsidaJGVQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@glideapps/ts-necessities": "2.2.3", + "browser-or-node": "^3.0.0", + "collection-utils": "^1.0.1", + "cross-fetch": "^4.0.0", + "is-url": "^1.2.4", + "js-base64": "^3.7.7", + "lodash": "^4.18.1", + "pako": "^1.0.6", + "pluralize": "^8.0.0", + "readable-stream": "4.5.2", + "unicode-properties": "^1.4.1", + "urijs": "^1.19.1", + "wordwrap": "^1.0.0", + "yaml": "^2.8.3" + } + }, + "node_modules/readable-stream": { + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.5.2.tgz", + "integrity": "sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/rollup": { + "version": "4.63.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.1.tgz", + "integrity": "sha512-3Df9jsstwhccuEfmAMi9l8XUh/GOkVObmFTU7CCVBysEbcOZLl84jCtaAZMcPiMz2EGKsATzQcU+Xr3n/wU6cg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.63.1", + "@rollup/rollup-android-arm64": "4.63.1", + "@rollup/rollup-darwin-arm64": "4.63.1", + "@rollup/rollup-darwin-x64": "4.63.1", + "@rollup/rollup-freebsd-arm64": "4.63.1", + "@rollup/rollup-freebsd-x64": "4.63.1", + "@rollup/rollup-linux-arm-gnueabihf": "4.63.1", + "@rollup/rollup-linux-arm-musleabihf": "4.63.1", + "@rollup/rollup-linux-arm64-gnu": "4.63.1", + "@rollup/rollup-linux-arm64-musl": "4.63.1", + "@rollup/rollup-linux-loong64-gnu": "4.63.1", + "@rollup/rollup-linux-loong64-musl": "4.63.1", + "@rollup/rollup-linux-ppc64-gnu": "4.63.1", + "@rollup/rollup-linux-ppc64-musl": "4.63.1", + "@rollup/rollup-linux-riscv64-gnu": "4.63.1", + "@rollup/rollup-linux-riscv64-musl": "4.63.1", + "@rollup/rollup-linux-s390x-gnu": "4.63.1", + "@rollup/rollup-linux-x64-gnu": "4.63.1", + "@rollup/rollup-linux-x64-musl": "4.63.1", + "@rollup/rollup-openbsd-x64": "4.63.1", + "@rollup/rollup-openharmony-arm64": "4.63.1", + "@rollup/rollup-win32-arm64-msvc": "4.63.1", + "@rollup/rollup-win32-ia32-msvc": "4.63.1", + "@rollup/rollup-win32-x64-gnu": "4.63.1", + "@rollup/rollup-win32-x64-msvc": "4.63.1", + "fsevents": "~2.3.2" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/three": { + "version": "0.180.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.180.0.tgz", + "integrity": "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w==", + "license": "MIT" + }, + "node_modules/tiny-inflate": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz", + "integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "dev": true, + "license": "MIT" + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/unicode-properties": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz", + "integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.0", + "unicode-trie": "^2.0.0" + } + }, + "node_modules/unicode-trie": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz", + "integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "pako": "^0.2.5", + "tiny-inflate": "^1.0.0" + } + }, + "node_modules/unicode-trie/node_modules/pako": { + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz", + "integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==", + "dev": true, + "license": "MIT" + }, + "node_modules/urijs": { + "version": "1.19.11", + "resolved": "https://registry.npmjs.org/urijs/-/urijs-1.19.11.tgz", + "integrity": "sha512-HXgFDgDommxn5/bIv0cnQZsPhHDA90NPHD6+c/v21U5+Sx5hoP8+dP9IZXBU1gIfvdRfhG8cel9QNPeionfcCQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "7.3.6", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz", + "integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.27.0 || ^0.28.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/yaml": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", + "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", + "dev": true, + "license": "ISC", + "peer": true, + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..b53c164 --- /dev/null +++ b/package.json @@ -0,0 +1,25 @@ +{ + "name": "aeternalis", + "private": true, + "type": "module", + "scripts": { + "generate": "node tools/generate-protocol.mjs", + "check": "tsc --noEmit -p client/tsconfig.json", + "build": "vite build --config client/vite.config.ts", + "dev": "vite --config client/vite.config.ts --host 127.0.0.1", + "test:e2e": "playwright test", + "test:contracts": "node tools/generate-protocol.mjs --check" + }, + "dependencies": { + "three": "^0.180.0", + "lucide": "^0.468.0" + }, + "devDependencies": { + "@playwright/test": "^1.55.0", + "@types/three": "^0.180.0", + "typescript": "^5.9.2", + "vite": "^7.1.0", + "quicktype-core": "^23.2.6", + "yaml": "^2.8.1" + } +} diff --git a/planning/IMPLEMENTATION-NOTES.md b/planning/IMPLEMENTATION-NOTES.md new file mode 100644 index 0000000..b4d0001 --- /dev/null +++ b/planning/IMPLEMENTATION-NOTES.md @@ -0,0 +1,29 @@ +# September 2026 implementation notes + +The original `VISION.md` remains the user-authored planning source. This addendum +records the new explicit requirement and the boundary of the first implementation. + +## Confirmed addition + +After one real-world week, a boss spawns and slowly destroys the world. When the +boss dies, living characters may move to a new server/world. A dead character is +permanently finished. Production deployment should run on Kubernetes and use a +Gitea workflow compatible with Harbor and ArgoCD. The client is browser-first, +with platform changes considered only after real performance measurements. + +## Implemented interpretation for playtesting + +The deadline is seven days by default. A shrinking circular hazard represents +world destruction over a configurable period. Victory grants persistent passage +to eligible survivors; complete collapse kills everyone still assigned to the +world. A character and its inventory/skills retain identity across successful +passages. A passage is bound to its account and can be redeemed only once per +successful world. Daily play usage carries forward with the character. + +These choices remain provisional: 30-minute destruction duration, hazard damage, +offline exposure, safe-zone behavior during the event, finite world radius, +48-unit spawn separation, and mob scaling. The current generated chunks are +heightfields; volumetric terrain and terrain deformation are not implemented. + +The full assessment, delivered scope, and follow-up work are documented under +`docs/`. No 2,000-player, security-audit, or live Kubernetes deployment claim is made. diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 0000000..bbc8753 --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from '@playwright/test'; + +export default defineConfig({ + testDir: './tests', timeout: 45000, workers: 1, fullyParallel: false, + use: { baseURL: 'http://127.0.0.1:18089', browserName: 'chromium', channel: process.env.PLAYWRIGHT_CHANNEL || undefined, headless: true, screenshot: 'only-on-failure', trace: 'retain-on-failure', launchOptions: { args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] } }, + webServer: { + command: 'node tools/dev-server.mjs', url: 'http://127.0.0.1:18089/readyz', + timeout: 180000, reuseExistingServer: false, + env: { PORT: '18089', E2E: 'true', WORLD_ID: 'e2e', DEV_SEASON_SECONDS: '3600' }, + }, +}); diff --git a/schemas/AGENTS.md b/schemas/AGENTS.md new file mode 100644 index 0000000..344038c --- /dev/null +++ b/schemas/AGENTS.md @@ -0,0 +1,4 @@ +# Shared contracts + +Edit protocol.json, then run `npm run generate`. Generated Go and TypeScript must +be committed together. Inputs additionally need semantic validation on the server. diff --git a/schemas/protocol.json b/schemas/protocol.json new file mode 100644 index 0000000..d0b3f9b --- /dev/null +++ b/schemas/protocol.json @@ -0,0 +1,82 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Protocol", + "type": "object", + "additionalProperties": false, + "properties": { + "intent": {"$ref": "#/definitions/Intent"}, + "snapshot": {"$ref": "#/definitions/Snapshot"} + }, + "required": ["intent", "snapshot"], + "definitions": { + "Vec3": { + "type": "object", "additionalProperties": false, + "properties": {"x": {"type": "number"}, "y": {"type": "number"}, "z": {"type": "number"}}, + "required": ["x", "y", "z"] + }, + "Intent": { + "type": "object", "additionalProperties": false, + "properties": { + "op": {"type": "string"}, "seq": {"type": "integer"}, + "x": {"type": "number"}, "z": {"type": "number"}, "target": {"type": "string"} + }, + "required": ["op", "seq", "x", "z", "target"] + }, + "Entity": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, "kind": {"type": "string"}, "name": {"type": "string"}, + "position": {"$ref": "#/definitions/Vec3"}, + "hp": {"type": "number"}, "maxHp": {"type": "number"}, + "state": {"type": "string"} + }, + "required": ["id", "kind", "name", "position", "hp", "maxHp", "state"] + }, + "Character": { + "type": "object", "additionalProperties": false, + "properties": { + "entity": {"$ref": "#/definitions/Entity"}, + "inventory": {"type": "object", "additionalProperties": {"type": "integer"}}, + "skills": {"type": "object", "additionalProperties": {"type": "integer"}}, + "playedSeconds": {"type": "number"}, "remainingSeconds": {"type": "number"}, + "kills": {"type": "integer"}, "ack": {"type": "integer"}, + "hasKeystone": {"type": "boolean"} + }, + "required": ["entity", "inventory", "skills", "playedSeconds", "remainingSeconds", "kills", "ack", "hasKeystone"] + }, + "Chunk": { + "type": "object", "additionalProperties": false, + "properties": { + "key": {"type": "string"}, "x": {"type": "integer"}, "z": {"type": "integer"}, + "size": {"type": "number"}, "resolution": {"type": "integer"}, + "heights": {"type": "array", "items": {"type": "number"}}, + "biome": {"type": "string"}, "resources": {"type": "array", "items": {"$ref": "#/definitions/Entity"}} + }, + "required": ["key", "x", "z", "size", "resolution", "heights", "biome", "resources"] + }, + "WorldInfo": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, "seed": {"type": "integer"}, "phase": {"type": "string"}, + "ageSeconds": {"type": "number"}, "bossInSeconds": {"type": "number"}, + "collapseInSeconds": {"type": "number"}, "safeRadius": {"type": "number"}, + "radius": {"type": "number"}, "online": {"type": "integer"}, "capacity": {"type": "integer"}, + "bossHp": {"type": "number"}, "bossMaxHp": {"type": "number"} + }, + "required": ["id", "seed", "phase", "ageSeconds", "bossInSeconds", "collapseInSeconds", "safeRadius", "radius", "online", "capacity", "bossHp", "bossMaxHp"] + }, + "Snapshot": { + "type": "object", "additionalProperties": false, + "properties": { + "type": {"type": "string"}, "version": {"type": "integer"}, "tick": {"type": "integer"}, + "world": {"$ref": "#/definitions/WorldInfo"}, "self": {"$ref": "#/definitions/Character"}, + "entities": {"type": "array", "items": {"$ref": "#/definitions/Entity"}}, + "chunks": {"type": "array", "items": {"$ref": "#/definitions/Chunk"}}, + "chunkKeys": {"type": "array", "items": {"type": "string"}}, + "unavailableResources": {"type": "array", "items": {"type": "string"}}, + "message": {"type": "string"} + }, + "required": ["type", "version", "tick", "world", "self", "entities", "chunks", "chunkKeys", "unavailableResources", "message"] + } + } +} diff --git a/server/AGENTS.md b/server/AGENTS.md new file mode 100644 index 0000000..d22f3aa --- /dev/null +++ b/server/AGENTS.md @@ -0,0 +1,6 @@ +# Authoritative server + +`internal/game` is deterministic simulation, with no HTTP or database dependency. +`internal/store` owns durable snapshots, exclusive ownership, and atomic transfers. +`internal/transport` authenticates and validates requests before intents reach game. +Keep all balance values in `content/balance.yaml`. Test lifecycle and auth boundaries. diff --git a/server/cmd/load/main.go b/server/cmd/load/main.go new file mode 100644 index 0000000..90a3055 --- /dev/null +++ b/server/cmd/load/main.go @@ -0,0 +1,143 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "flag" + "fmt" + "io" + "net" + "net/http" + "net/url" + "sort" + "strings" + "sync" + "sync/atomic" + "time" + + p "aeternalis/server/internal/protocol" + "github.com/coder/websocket" +) + +func main() { + base := flag.String("url", "http://127.0.0.1:18080", "loopback development world") + clients := flag.Int("clients", 20, "concurrent clients (1-100)") + duration := flag.Duration("duration", 20*time.Second, "measurement duration after connections") + flag.Parse() + u, err := url.Parse(*base) + if err != nil || net.ParseIP(u.Hostname()) == nil || !net.ParseIP(u.Hostname()).IsLoopback() { + panic("load tool only targets explicit loopback development servers") + } + if *clients < 1 || *clients > 100 { + panic("clients must be 1-100") + } + var received, frames, failures atomic.Int64 + var mu sync.Mutex + intervals := []float64{} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var readers, writers sync.WaitGroup + client := &http.Client{Timeout: 5 * time.Second} + post := func(path, body string, cookie *http.Cookie) (*http.Response, error) { + req, _ := http.NewRequestWithContext(ctx, "POST", *base+path, strings.NewReader(body)) + req.Header.Set("Origin", *base) + req.Header.Set("Content-Type", "application/json") + if cookie != nil { + req.AddCookie(cookie) + } + return client.Do(req) + } + for i := 0; i < *clients; i++ { + r, err := post("/auth/dev", "{}", nil) + if err != nil { + panic(err) + } + cookies := r.Cookies() + io.Copy(io.Discard, r.Body) + r.Body.Close() + if r.StatusCode != 200 || len(cookies) == 0 { + panic(fmt.Sprintf("auth status %d", r.StatusCode)) + } + r, err = post("/api/join", fmt.Sprintf(`{"name":"Load %d","passage":""}`, i), cookies[0]) + if err != nil { + panic(err) + } + data, _ := io.ReadAll(r.Body) + r.Body.Close() + if r.StatusCode != 200 { + panic(fmt.Sprintf("join %d %s", r.StatusCode, data)) + } + conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(*base, "http")+"/ws", &websocket.DialOptions{HTTPHeader: http.Header{"Origin": []string{*base}, "Cookie": []string{cookies[0].String()}}}) + if err != nil { + panic(err) + } + conn.SetReadLimit(4 << 20) + readers.Add(1) + go func() { + defer readers.Done() + defer conn.CloseNow() + last := time.Time{} + for { + _, data, err := conn.Read(ctx) + if err != nil { + if ctx.Err() == nil { + failures.Add(1) + } + return + } + now := time.Now() + if !last.IsZero() { + mu.Lock() + intervals = append(intervals, now.Sub(last).Seconds()*1000) + mu.Unlock() + } + last = now + received.Add(int64(len(data))) + frames.Add(1) + if !bytes.Contains(data, []byte(`"type":"snapshot"`)) { + failures.Add(1) + } + } + }() + writers.Add(1) + go func() { + defer writers.Done() + ticker := time.NewTicker(50 * time.Millisecond) + defer ticker.Stop() + seq := int64(0) + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + seq++ + data, _ := json.Marshal(p.Intent{Op: "move", Seq: seq}) + writeCtx, stop := context.WithTimeout(ctx, time.Second) + err := conn.Write(writeCtx, websocket.MessageText, data) + stop() + if err != nil { + return + } + } + } + }() + time.Sleep(400 * time.Millisecond) + } + baselineBytes, baselineFrames := received.Load(), frames.Load() + start := time.Now() + time.Sleep(*duration) + elapsed := time.Since(start).Seconds() + cancel() + readers.Wait() + writers.Wait() + sort.Float64s(intervals) + p95 := float64(0) + if len(intervals) > 0 { + p95 = intervals[int(float64(len(intervals)-1)*.95)] + } + fmt.Printf("clients=%d duration=%.1fs snapshots=%d payload_KiB_per_second=%.1f p95_snapshot_interval_ms=%.1f disconnects=%d\n", *clients, elapsed, frames.Load()-baselineFrames, float64(received.Load()-baselineBytes)/1024/elapsed, p95, failures.Load()) + if failures.Load() > 0 { + panic("unexpected client disconnects") + } +} diff --git a/server/cmd/world/main.go b/server/cmd/world/main.go new file mode 100644 index 0000000..e956444 --- /dev/null +++ b/server/cmd/world/main.go @@ -0,0 +1,167 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net" + "net/http" + "net/url" + "os" + "os/signal" + "path/filepath" + "strconv" + "strings" + "syscall" + "time" + + "aeternalis/server/content" + "aeternalis/server/internal/game" + "aeternalis/server/internal/store" + "aeternalis/server/internal/transport" +) + +func env(k, def string) string { + if v := os.Getenv(k); v != "" { + return v + } + return def +} +func run() error { + dev := env("APP_ENV", "production") == "development" + listen := env("LISTEN_ADDR", "127.0.0.1:18080") + base := env("PUBLIC_URL", "http://127.0.0.1:18080") + if dev { + host, _, err := net.SplitHostPort(listen) + if err != nil || net.ParseIP(host) == nil || !net.ParseIP(host).IsLoopback() { + return errors.New("development auth requires an explicit loopback listen address") + } + u, err := url.Parse(base) + if err != nil || net.ParseIP(u.Hostname()) == nil || !net.ParseIP(u.Hostname()).IsLoopback() { + return errors.New("development PUBLIC_URL must be loopback") + } + } + if !dev && os.Getenv("DATABASE_URL") == "" { + return errors.New("production requires DATABASE_URL") + } + dsn := env("DATABASE_URL", "file:../.local/aeternalis.db") + if !dev && !(strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://")) { + return errors.New("production requires PostgreSQL") + } + if !dev { + u, err := url.Parse(dsn) + if err != nil || u.Query().Get("sslmode") != "verify-full" { + return errors.New("production DATABASE_URL requires sslmode=verify-full") + } + } + if dev && strings.HasPrefix(dsn, "file:") { + path := strings.Split(strings.TrimPrefix(dsn, "file:"), "?")[0] + if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + return err + } + } + b, err := content.Load() + if err != nil { + return err + } + if dev { + for key, dest := range map[string]*float64{"DEV_SEASON_SECONDS": &b.SeasonSeconds, "DEV_COLLAPSE_SECONDS": &b.CollapseSeconds, "DEV_DAILY_SECONDS": &b.DailyPlaySeconds} { + if raw := os.Getenv(key); raw != "" { + value, err := strconv.ParseFloat(raw, 64) + if err != nil { + return err + } + *dest = value + } + } + } + if err = b.Validate(); err != nil { + return err + } + seed, err := strconv.ParseInt(env("WORLD_SEED", "734291"), 10, 64) + if err != nil { + return err + } + id := env("WORLD_ID", "world-001") + if len(id) > 64 || strings.ContainsAny(id, "/\\ \t\n") { + return errors.New("invalid WORLD_ID") + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + db, err := store.Open(ctx, dsn) + if err != nil { + return err + } + defer db.Close() + w := game.New(id, seed, time.Now().UTC(), b) + lease, raw, err := db.Acquire(ctx, w) + if err != nil { + return fmt.Errorf("acquire world: %w", err) + } + released := false + defer func() { + if !released { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = lease.Release(ctx) + } + }() + if err = json.Unmarshal(raw, w); err != nil { + return err + } + if err = w.Restore(time.Now().UTC()); err != nil { + return err + } + auth, err := transport.NewAuth(ctx, db, dev, base, os.Getenv("OIDC_ISSUER"), os.Getenv("OIDC_CLIENT_ID"), os.Getenv("OIDC_CLIENT_SECRET")) + if err != nil { + return err + } + worlds := []transport.Destination{} + if raw := os.Getenv("WORLD_DIRECTORY"); raw != "" { + if err = json.Unmarshal([]byte(raw), &worlds); err != nil { + return err + } + for _, dest := range worlds { + u, err := url.Parse(dest.URL) + if err != nil || u.Host == "" || (!dev && u.Scheme != "https") || u.User != nil { + return errors.New("invalid WORLD_DIRECTORY URL") + } + } + } + svc := transport.NewService(w, lease) + handler := transport.NewHTTP(svc, auth, env("CLIENT_DIR", "../client/dist"), worlds).Handler() + server := &http.Server{Addr: listen, Handler: handler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16384} + runtimeCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + go svc.Run(runtimeCtx) + errorsCh := make(chan error, 1) + go func() { + slog.Info("world listening", "url", base, "world", id, "development", dev) + errorsCh <- server.ListenAndServe() + }() + select { + case <-runtimeCtx.Done(): + case err = <-errorsCh: + if !errors.Is(err, http.ErrServerClosed) { + return err + } + } + stop() + shutdown, cancelShutdown := context.WithTimeout(context.Background(), 10*time.Second) + defer cancelShutdown() + err = svc.Stop(shutdown) + released = true + httpErr := server.Shutdown(shutdown) + if err != nil { + return err + } + return httpErr +} +func main() { + if err := run(); err != nil { + slog.Error("world stopped", "error", err) + os.Exit(1) + } +} diff --git a/server/content/balance.yaml b/server/content/balance.yaml new file mode 100644 index 0000000..17dca40 --- /dev/null +++ b/server/content/balance.yaml @@ -0,0 +1,48 @@ +version: 1 +tickHz: 20 +snapshotHz: 5 +chunkSize: 128 +terrainResolution: 16 +worldRadius: 1024 +maxPlayers: 100 +spawnSeparation: 48 +seasonSeconds: 604800 +collapseSeconds: 1800 +dailyPlaySeconds: 7200 +playerHp: 100 +playerSpeed: 12 +attackRange: 6 +attackCooldown: 0.7 +playerDamage: 18 +spearDamage: 32 +gatherRange: 7 +gatherCooldown: 0.6 +bossHp: 1200 +bossDamage: 18 +bossRange: 12 +bossCooldown: 2 +stormDamagePerSecond: 15 +mobHp: 54 +mobDamage: 6 +mobSpeed: 4 +mobAggroRange: 24 +mobAttackRange: 3 +mobCooldown: 1.8 +mobRespawnSeconds: 40 +mobScalePerDay: 0.1 +resourcesPerChunk: 48 +resourceRespawnSeconds: 120 +skillXpPerAction: 1 +startingKit: + knife: 1 + axe: 1 + flint_and_steel: 1 + fishing_pole: 1 +recipes: + spear: + inputs: { wood: 3, ore: 2 } + outputs: { spear: 1 } + bandage: + inputs: { herb: 2 } + outputs: { bandage: 1 } +bandageHealing: 35 diff --git a/server/content/content.go b/server/content/content.go new file mode 100644 index 0000000..1a7e915 --- /dev/null +++ b/server/content/content.go @@ -0,0 +1,117 @@ +package content + +import ( + "bytes" + _ "embed" + "fmt" + "math" + "reflect" + + "go.yaml.in/yaml/v3" +) + +//go:embed balance.yaml +var balance []byte + +type Recipe struct { + Inputs map[string]int64 `yaml:"inputs"` + Outputs map[string]int64 `yaml:"outputs"` +} + +type Balance struct { + Version int `yaml:"version"` + TickHz int `yaml:"tickHz"` + SnapshotHz int `yaml:"snapshotHz"` + ChunkSize float64 `yaml:"chunkSize"` + TerrainResolution int `yaml:"terrainResolution"` + WorldRadius float64 `yaml:"worldRadius"` + MaxPlayers int `yaml:"maxPlayers"` + SpawnSeparation float64 `yaml:"spawnSeparation"` + SeasonSeconds float64 `yaml:"seasonSeconds"` + CollapseSeconds float64 `yaml:"collapseSeconds"` + DailyPlaySeconds float64 `yaml:"dailyPlaySeconds"` + PlayerHp float64 `yaml:"playerHp"` + PlayerSpeed float64 `yaml:"playerSpeed"` + AttackRange float64 `yaml:"attackRange"` + AttackCooldown float64 `yaml:"attackCooldown"` + PlayerDamage float64 `yaml:"playerDamage"` + SpearDamage float64 `yaml:"spearDamage"` + GatherRange float64 `yaml:"gatherRange"` + GatherCooldown float64 `yaml:"gatherCooldown"` + BossHp float64 `yaml:"bossHp"` + BossDamage float64 `yaml:"bossDamage"` + BossRange float64 `yaml:"bossRange"` + BossCooldown float64 `yaml:"bossCooldown"` + StormDamagePerSecond float64 `yaml:"stormDamagePerSecond"` + MobHp float64 `yaml:"mobHp"` + MobDamage float64 `yaml:"mobDamage"` + MobSpeed float64 `yaml:"mobSpeed"` + MobAggroRange float64 `yaml:"mobAggroRange"` + MobAttackRange float64 `yaml:"mobAttackRange"` + MobCooldown float64 `yaml:"mobCooldown"` + MobRespawnSeconds float64 `yaml:"mobRespawnSeconds"` + MobScalePerDay float64 `yaml:"mobScalePerDay"` + ResourcesPerChunk int `yaml:"resourcesPerChunk"` + ResourceRespawnSeconds float64 `yaml:"resourceRespawnSeconds"` + SkillXpPerAction int64 `yaml:"skillXpPerAction"` + StartingKit map[string]int64 `yaml:"startingKit"` + Recipes map[string]Recipe `yaml:"recipes"` + BandageHealing float64 `yaml:"bandageHealing"` +} + +func Load() (Balance, error) { return Parse(balance) } +func Parse(data []byte) (Balance, error) { + var b Balance + d := yaml.NewDecoder(bytes.NewReader(data)) + d.KnownFields(true) + if err := d.Decode(&b); err != nil { + return b, err + } + return b, b.Validate() +} +func (b Balance) Validate() error { + v := reflect.ValueOf(b) + for i := 0; i < v.NumField(); i++ { + f := v.Field(i) + n := float64(1) + switch f.Kind() { + case reflect.Int, reflect.Int64: + n = float64(f.Int()) + case reflect.Float64: + n = f.Float() + } + if n <= 0 || math.IsNaN(n) || math.IsInf(n, 0) { + return fmt.Errorf("%s must be finite and positive", v.Type().Field(i).Name) + } + } + if b.TickHz > 60 || b.SnapshotHz > b.TickHz || b.TickHz%b.SnapshotHz != 0 || b.TerrainResolution > 64 || b.ResourcesPerChunk > 128 || b.MaxPlayers > 2000 || b.WorldRadius < b.ChunkSize*2 { + return fmt.Errorf("invalid capacity, terrain, or tick configuration") + } + known := map[string]bool{"knife": true, "axe": true, "flint_and_steel": true, "fishing_pole": true, "wood": true, "ore": true, "herb": true, "spear": true, "bandage": true} + check := func(items map[string]int64) error { + if len(items) == 0 { + return fmt.Errorf("empty item list") + } + for k, n := range items { + if !known[k] || n < 1 || n > 1000 { + return fmt.Errorf("invalid item %q quantity %d", k, n) + } + } + return nil + } + if err := check(b.StartingKit); err != nil { + return err + } + for name, r := range b.Recipes { + if !known[name] { + return fmt.Errorf("unknown recipe %q", name) + } + if err := check(r.Inputs); err != nil { + return err + } + if err := check(r.Outputs); err != nil { + return err + } + } + return nil +} diff --git a/server/content/content_test.go b/server/content/content_test.go new file mode 100644 index 0000000..6b6cc21 --- /dev/null +++ b/server/content/content_test.go @@ -0,0 +1,17 @@ +package content + +import "testing" + +func TestBalanceValidation(t *testing.T) { + b, err := Load() + if err != nil { + t.Fatal(err) + } + b.PlayerSpeed = -1 + if b.Validate() == nil { + t.Fatal("negative speed accepted") + } + if _, err = Parse([]byte("unexpected: 1")); err == nil { + t.Fatal("unknown content key accepted") + } +} diff --git a/server/go.mod b/server/go.mod new file mode 100644 index 0000000..2857079 --- /dev/null +++ b/server/go.mod @@ -0,0 +1,31 @@ +module aeternalis/server + +go 1.26.0 + +require ( + github.com/coder/websocket v1.8.15 + github.com/coreos/go-oidc/v3 v3.21.0 + github.com/jackc/pgx/v5 v5.10.0 + github.com/ojrac/opensimplex-go v1.0.2 + go.yaml.in/yaml/v3 v3.0.5 + golang.org/x/oauth2 v0.36.0 + modernc.org/sqlite v1.58.0 +) + +require ( + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/go-jose/go-jose/v4 v4.1.4 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect + github.com/ncruces/go-strftime v1.0.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/sync v0.22.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.29.0 // indirect + modernc.org/libc v1.75.6 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.12.1 // indirect +) diff --git a/server/go.sum b/server/go.sum new file mode 100644 index 0000000..12cd30f --- /dev/null +++ b/server/go.sum @@ -0,0 +1,86 @@ +github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA= +github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= +github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM= +github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= +github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo= +github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0= +github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= +github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/ojrac/opensimplex-go v1.0.2 h1:l4vs0D+JCakcu5OV0kJ99oEaWJfggSc9jiLpxaWvSzs= +github.com/ojrac/opensimplex-go v1.0.2/go.mod h1:NwbXFFbXcdGgIFdiA7/REME+7n/lOf1TuEbLiZYOWnM= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= +golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= +golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= +golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= +golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE= +golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.29.2 h1:h6+9ciCnPKutf4I03CvheAvDLX7+IHlqR6Iy6J+cgd8= +modernc.org/cc/v4 v4.29.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.35.0 h1:F+TUsmw09QxLzmi3aeYYGxjAXarmZaKgj3mKQHNaA8w= +modernc.org/ccgo/v4 v4.35.0/go.mod h1:qrVGs9S3Sr2Ztcg9ve+kTAYMp5a3YvWjo+SoN06kJ5I= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc= +modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.75.6 h1:yKk8qo+Di4gkmvRboK8ocCqH22FiUCR6jRy2OwtCRus= +modernc.org/libc v1.75.6/go.mod h1:bO5o2ztHxBb2rjz0PgdHN0sSMw57CgxGFLZ3Qd/QpVQ= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= +modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= +modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.58.0 h1:38u40/bwkfM7f0Myhosl+SEMltSDxnGdQf8o6Kjmys0= +modernc.org/sqlite v1.58.0/go.mod h1:rsD2CckafgObKC4DhBlGBf+RiHxkc3hINGt1Xw32tVY= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/server/internal/game/terrain.go b/server/internal/game/terrain.go new file mode 100644 index 0000000..79cd634 --- /dev/null +++ b/server/internal/game/terrain.go @@ -0,0 +1,69 @@ +package game + +import ( + "fmt" + "math" + "math/rand/v2" + + "aeternalis/server/content" + p "aeternalis/server/internal/protocol" + "github.com/ojrac/opensimplex-go" +) + +const GeneratorVersion = 1 + +type Terrain struct { + Seed int64 + B content.Balance + noise opensimplex.Noise +} + +func NewTerrain(seed int64, b content.Balance) *Terrain { + return &Terrain{seed, b, opensimplex.New(seed)} +} +func (t *Terrain) rawHeight(x, z float64) float64 { + // A low, flat arrival clearing blends into broad hills and fine detail. + d := math.Min(1, math.Hypot(x, z)/55) + return (t.noise.Eval2(x/220, z/220)*17 + t.noise.Eval2(x/55, z/55)*3) * d +} +func ChunkCoord(v, size float64) int { return int(math.Floor(v / size)) } +func Key(x, z int) string { return fmt.Sprintf("%d:%d", x, z) } + +// Height uses the same triangle split as the transmitted terrain mesh. +func (t *Terrain) Height(x, z float64) float64 { + step := t.B.ChunkSize / float64(t.B.TerrainResolution) + ix, iz := math.Floor(x/step), math.Floor(z/step) + fx, fz := x/step-ix, z/step-iz + a, b := t.rawHeight(ix*step, iz*step), t.rawHeight((ix+1)*step, iz*step) + c, d := t.rawHeight(ix*step, (iz+1)*step), t.rawHeight((ix+1)*step, (iz+1)*step) + if fx+fz <= 1 { + return a + (b-a)*fx + (c-a)*fz + } + return d + (c-d)*(1-fx) + (b-d)*(1-fz) +} +func (t *Terrain) Position(x, z float64) p.Vec3 { return p.Vec3{X: x, Y: t.Height(x, z), Z: z} } +func (t *Terrain) Chunk(x, z int) p.Chunk { + c := p.Chunk{Key: Key(x, z), X: int64(x), Z: int64(z), Size: t.B.ChunkSize, Resolution: int64(t.B.TerrainResolution), Biome: "highlands", Heights: []float64{}, Resources: []p.Entity{}} + for iz := 0; iz <= t.B.TerrainResolution; iz++ { + for ix := 0; ix <= t.B.TerrainResolution; ix++ { + c.Heights = append(c.Heights, t.rawHeight(float64(x)*c.Size+float64(ix)*c.Size/float64(c.Resolution), float64(z)*c.Size+float64(iz)*c.Size/float64(c.Resolution))) + } + } + rng := rand.New(rand.NewPCG(uint64(t.Seed)^uint64(int64(x)*73856093), uint64(int64(z)*19349663)^0xa341316c)) + kinds := []string{"tree", "ore", "herb"} + for i := 0; i < t.B.ResourcesPerChunk; i++ { + px, pz := (float64(x)+0.08+rng.Float64()*0.84)*c.Size, (float64(z)+0.08+rng.Float64()*0.84)*c.Size + if math.Hypot(px, pz) > t.B.WorldRadius || math.Hypot(px, pz) < 10 { + continue + } + kind := kinds[i%len(kinds)] + c.Resources = append(c.Resources, p.Entity{ID: fmt.Sprintf("r:%d:%d:%d", x, z, i), Kind: kind, Name: kind, Position: t.Position(px, pz), HP: 1, MaxHP: 1, State: "available"}) + } + // Arrival resources make the first crafting loop reachable without aimless travel. + if x == 0 && z == 0 { + for i, k := range kinds { + c.Resources = append(c.Resources, p.Entity{ID: "arrival:" + k, Kind: k, Name: k, Position: t.Position(12+float64(i)*5, 12), HP: 1, MaxHP: 1, State: "available"}) + } + } + return c +} diff --git a/server/internal/game/world.go b/server/internal/game/world.go new file mode 100644 index 0000000..b861856 --- /dev/null +++ b/server/internal/game/world.go @@ -0,0 +1,648 @@ +package game + +import ( + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "math" + "sort" + "time" + + "aeternalis/server/content" + p "aeternalis/server/internal/protocol" +) + +type Character struct { + View p.Character `json:"view"` + Account string `json:"account"` + Day string `json:"day"` + DailySeconds float64 `json:"dailySeconds"` + ReturnPosition *p.Vec3 `json:"returnPosition,omitempty"` + Sheltered bool `json:"sheltered"` + LastAttack float64 `json:"lastAttack"` + LastGather float64 `json:"lastGather"` + Online bool `json:"-"` + MoveX float64 `json:"-"` + MoveZ float64 `json:"-"` + LastMove time.Time `json:"-"` + Message string `json:"-"` +} +type Corpse struct { + Entity p.Entity `json:"entity"` + Inventory map[string]int64 `json:"inventory"` +} +type Mob struct { + Entity p.Entity `json:"entity"` + HomeX int `json:"homeX"` + HomeZ int `json:"homeZ"` + LastAttack float64 `json:"lastAttack"` + RespawnAt float64 `json:"respawnAt"` +} +type World struct { + Version int `json:"version"` + ID string `json:"id"` + Seed int64 `json:"seed"` + CreatedAt time.Time `json:"createdAt"` + EndedAt *time.Time `json:"endedAt,omitempty"` + Phase string `json:"phase"` + Tick int64 `json:"tick"` + BossHP float64 `json:"bossHp"` + BossLastAttack float64 `json:"bossLastAttack"` + Characters map[string]*Character `json:"characters"` + Corpses map[string]*Corpse `json:"corpses"` + Depleted map[string]float64 `json:"depleted"` + Mobs map[string]*Mob `json:"mobs"` + Balance content.Balance `json:"balance"` + terrain *Terrain + chunks map[string]p.Chunk + now time.Time + dirty bool +} + +func ID() string { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + panic(err) + } + return hex.EncodeToString(b[:]) +} +func New(id string, seed int64, now time.Time, b content.Balance) *World { + w := &World{Version: GeneratorVersion, ID: id, Seed: seed, CreatedAt: now, Phase: "gathering", BossHP: b.BossHp, Characters: map[string]*Character{}, Corpses: map[string]*Corpse{}, Depleted: map[string]float64{}, Mobs: map[string]*Mob{}, Balance: b} + _ = w.Restore(now) + return w +} +func (w *World) Restore(now time.Time) error { + if w.Version != GeneratorVersion { + return errors.New("unsupported persisted generator version") + } + if err := w.Balance.Validate(); err != nil { + return err + } + if w.Characters == nil || w.Mobs == nil || w.Corpses == nil || w.Depleted == nil { + return errors.New("invalid world snapshot") + } + w.terrain = NewTerrain(w.Seed, w.Balance) + w.chunks = map[string]p.Chunk{} + w.now = now + for _, c := range w.Characters { + c.Online = false + c.MoveX = 0 + c.MoveZ = 0 + c.View.ACK = 0 + } + return nil +} +func (w *World) Age() float64 { + now := w.now + if w.EndedAt != nil { + now = *w.EndedAt + } + return math.Max(0, now.Sub(w.CreatedAt).Seconds()) +} +func (w *World) Dirty() bool { return w.dirty } +func (w *World) Saved() { w.dirty = false } +func (w *World) SafeRadius() float64 { + if w.Phase == "gathering" { + return w.Balance.WorldRadius + } + if w.Phase == "lost" { + return 0 + } + return math.Max(0, w.Balance.WorldRadius*(1-(w.Age()-w.Balance.SeasonSeconds)/w.Balance.CollapseSeconds)) +} +func (w *World) Info() p.WorldInfo { + online := int64(0) + for _, c := range w.Characters { + if c.Online { + online++ + } + } + return p.WorldInfo{ID: w.ID, Seed: w.Seed, Phase: w.Phase, AgeSeconds: w.Age(), BossInSeconds: math.Max(0, w.Balance.SeasonSeconds-w.Age()), CollapseInSeconds: math.Max(0, w.Balance.SeasonSeconds+w.Balance.CollapseSeconds-w.Age()), SafeRadius: w.SafeRadius(), Radius: w.Balance.WorldRadius, Online: online, Capacity: int64(w.Balance.MaxPlayers), BossHP: w.BossHP, BossMaxHP: w.Balance.BossHp} +} +func (w *World) ForAccount(account string) *Character { + for _, c := range w.Characters { + if c.Account == account { + return c + } + } + return nil +} +func (w *World) spawn(exclude string) (p.Vec3, error) { + for i := 0; i < 4096; i++ { + radius := math.Sqrt(float64(i)) * w.Balance.SpawnSeparation * 0.6 + angle := float64(i) * 2.399963229728653 + pos := w.terrain.Position(math.Cos(angle)*radius, math.Sin(angle)*radius) + if radius > w.Balance.WorldRadius-32 { + break + } + clear := true + for id, c := range w.Characters { + if id != exclude && c.View.Entity.State != "dead" && distance(pos, c.View.Entity.Position) < w.Balance.SpawnSeparation { + clear = false + break + } + } + if clear { + return pos, nil + } + } + return p.Vec3{}, errors.New("no separated spawn available") +} +func (w *World) Join(account, name string) (*Character, error) { + if c := w.ForAccount(account); c != nil { + return c, nil + } + if w.Phase != "gathering" { + return nil, errors.New("this world is closed to new arrivals") + } + if len(w.Characters) >= w.Balance.MaxPlayers { + return nil, errors.New("world capacity reached") + } + pos, err := w.spawn("") + if err != nil { + return nil, err + } + c := &Character{Account: account, Day: w.now.UTC().Format(time.DateOnly), View: p.Character{Entity: p.Entity{ID: ID(), Kind: "player", Name: name, Position: pos, HP: w.Balance.PlayerHp, MaxHP: w.Balance.PlayerHp, State: "alive"}, Inventory: map[string]int64{}, Skills: map[string]int64{}, RemainingSeconds: w.Balance.DailyPlaySeconds}} + for k, v := range w.Balance.StartingKit { + c.View.Inventory[k] = v + } + w.Characters[c.View.Entity.ID] = c + w.dirty = true + return c, nil +} +func (w *World) Import(c *Character) error { + if w.Phase != "gathering" || w.ForAccount(c.Account) != nil || len(w.Characters) >= w.Balance.MaxPlayers { + return errors.New("destination cannot accept character") + } + if c.View.Entity.State != "eligible" || c.View.Entity.HP <= 0 { + return errors.New("character is not a living survivor") + } + pos, err := w.spawn("") + if err != nil { + return err + } + c.View.Entity.Position = pos + c.View.Entity.State = "alive" + c.Online = false + c.MoveX = 0 + c.MoveZ = 0 + c.View.ACK = 0 + c.LastAttack = 0 + c.LastGather = 0 + c.ReturnPosition = nil + c.Sheltered = false + c.View.HasKeystone = false + w.resetDay(c) + w.Characters[c.View.Entity.ID] = c + w.dirty = true + return nil +} +func (w *World) resetDay(c *Character) { + day := w.now.UTC().Format(time.DateOnly) + if c.Day != day { + c.Day = day + c.DailySeconds = 0 + w.dirty = true + } + c.View.RemainingSeconds = math.Max(0, w.Balance.DailyPlaySeconds-c.DailySeconds) +} +func (w *World) Connect(id string) error { + c := w.Characters[id] + if c == nil { + return errors.New("character not found") + } + w.resetDay(c) + if c.View.Entity.State == "dead" { + return errors.New("this character has died permanently") + } + if c.View.RemainingSeconds <= 0 { + return errors.New("daily play limit reached; resets at 00:00 UTC") + } + if c.Online { + return errors.New("character already connected") + } + c.Online = true + c.View.ACK = 0 + c.MoveX = 0 + c.MoveZ = 0 + return nil +} +func (w *World) Disconnect(id string) { + if c := w.Characters[id]; c != nil { + c.Online = false + c.MoveX = 0 + c.MoveZ = 0 + } +} +func distance(a, b p.Vec3) float64 { return math.Hypot(a.X-b.X, a.Z-b.Z) } +func (w *World) chunk(x, z int) p.Chunk { + key := Key(x, z) + if c, ok := w.chunks[key]; ok { + return c + } + c := w.terrain.Chunk(x, z) + w.chunks[key] = c + return c +} +func (w *World) neighbors(pos p.Vec3) []p.Chunk { + x, z := ChunkCoord(pos.X, w.Balance.ChunkSize), ChunkCoord(pos.Z, w.Balance.ChunkSize) + chunks := make([]p.Chunk, 0, 9) + for dz := -1; dz <= 1; dz++ { + for dx := -1; dx <= 1; dx++ { + chunks = append(chunks, w.chunk(x+dx, z+dz)) + } + } + return chunks +} +func (w *World) Intent(id string, i p.Intent) error { + c := w.Characters[id] + if c == nil || !c.Online || c.View.Entity.State != "alive" || w.Phase == "won" || w.Phase == "lost" { + return errors.New("character cannot act") + } + if i.Seq <= c.View.ACK || i.Seq > c.View.ACK+10000 { + return errors.New("invalid input sequence") + } + if math.IsNaN(i.X) || math.IsNaN(i.Z) || math.IsInf(i.X, 0) || math.IsInf(i.Z, 0) || math.Abs(i.X) > 1 || math.Abs(i.Z) > 1 || len(i.Target) > 100 { + return errors.New("invalid intent") + } + c.View.ACK = i.Seq + if c.Sheltered && ((i.Op == "move" && (i.X != 0 || i.Z != 0)) || (i.Op != "move" && i.Op != "heal")) { + c.Sheltered = false + w.dirty = true + } + switch i.Op { + case "move": + n := math.Max(1, math.Hypot(i.X, i.Z)) + c.MoveX = i.X / n + c.MoveZ = i.Z / n + c.LastMove = w.now + return nil + case "gather": + return w.gather(c, i.Target) + case "craft": + return w.craft(c, i.Target) + case "attack": + return w.attack(c, i.Target) + case "heal": + if c.View.Inventory["bandage"] < 1 || c.View.Entity.HP >= c.View.Entity.MaxHP { + return errors.New("no bandage needed or available") + } + c.View.Inventory["bandage"]-- + c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+w.Balance.BandageHealing) + w.dirty = true + case "return": + if c.ReturnPosition == nil { + return errors.New("no keystone destination") + } + if math.Hypot(c.ReturnPosition.X, c.ReturnPosition.Z) > w.SafeRadius() { + return errors.New("keystone destination has been destroyed") + } + c.View.Entity.Position = *c.ReturnPosition + c.ReturnPosition = nil + c.View.HasKeystone = false + w.dirty = true + case "loot": + corpse := w.Corpses[i.Target] + if corpse == nil || distance(c.View.Entity.Position, corpse.Entity.Position) > w.Balance.GatherRange { + return errors.New("corpse out of reach") + } + for k, v := range corpse.Inventory { + c.View.Inventory[k] += v + } + delete(w.Corpses, i.Target) + w.dirty = true + default: + return errors.New("unknown intent") + } + return nil +} +func (w *World) gather(c *Character, target string) error { + if w.Age()-c.LastGather < w.Balance.GatherCooldown { + return errors.New("gathering cooldown") + } + if until := w.Depleted[target]; until > w.Age() { + return errors.New("resource depleted") + } + for _, chunk := range w.neighbors(c.View.Entity.Position) { + for _, r := range chunk.Resources { + if r.ID != target { + continue + } + if distance(c.View.Entity.Position, r.Position) > w.Balance.GatherRange { + return errors.New("resource out of reach") + } + item := map[string]string{"tree": "wood", "ore": "ore", "herb": "herb"}[r.Kind] + if item == "" { + return errors.New("not gatherable") + } + c.View.Inventory[item]++ + c.View.Skills["gathering"] += w.Balance.SkillXpPerAction + c.LastGather = w.Age() + w.Depleted[target] = w.Age() + w.Balance.ResourceRespawnSeconds + w.dirty = true + c.Message = "Gathered " + item + return nil + } + } + return errors.New("unknown resource") +} +func (w *World) craft(c *Character, name string) error { + r, ok := w.Balance.Recipes[name] + if !ok { + return errors.New("unknown recipe") + } + for k, v := range r.Inputs { + if c.View.Inventory[k] < v { + return errors.New("missing crafting materials") + } + } + for k, v := range r.Inputs { + c.View.Inventory[k] -= v + } + for k, v := range r.Outputs { + c.View.Inventory[k] += v + } + c.View.Skills["crafting"] += w.Balance.SkillXpPerAction + c.Message = "Crafted " + name + w.dirty = true + return nil +} +func (w *World) attack(c *Character, target string) error { + if w.Age()-c.LastAttack < w.Balance.AttackCooldown { + return errors.New("attack cooldown") + } + damage := w.Balance.PlayerDamage + if c.View.Inventory["spear"] > 0 { + damage = w.Balance.SpearDamage + } + if target == "boss" { + if w.Phase != "cataclysm" || distance(c.View.Entity.Position, w.terrain.Position(0, 0)) > w.Balance.AttackRange+4 { + return errors.New("boss out of reach") + } + w.BossHP = math.Max(0, w.BossHP-damage) + if w.BossHP == 0 { + w.Phase = "won" + ended := w.now + w.EndedAt = &ended + for _, survivor := range w.Characters { + if survivor.View.Entity.State == "alive" { + survivor.View.Entity.State = "eligible" + survivor.MoveX = 0 + survivor.MoveZ = 0 + survivor.Message = "The world is saved. Passage is open." + } + } + } + } else { + m := w.Mobs[target] + if m == nil || m.Entity.HP <= 0 || distance(c.View.Entity.Position, m.Entity.Position) > w.Balance.AttackRange { + return errors.New("target out of reach") + } + m.Entity.HP = math.Max(0, m.Entity.HP-damage) + if m.Entity.HP == 0 { + m.Entity.State = "dead" + m.RespawnAt = w.Age() + w.Balance.MobRespawnSeconds + c.View.Kills++ + c.View.Inventory["herb"]++ + } + } + c.LastAttack = w.Age() + c.View.Skills["combat"] += w.Balance.SkillXpPerAction + w.dirty = true + return nil +} +func (w *World) kill(c *Character, reason string) { + if c.View.Entity.State != "alive" { + return + } + e := c.View.Entity + e.ID = "corpse:" + e.ID + e.Kind = "corpse" + e.State = "dead" + e.HP = 0 + w.Corpses[e.ID] = &Corpse{Entity: e, Inventory: c.View.Inventory} + c.View.Inventory = map[string]int64{} + c.View.Entity.HP = 0 + c.View.Entity.State = "dead" + c.MoveX = 0 + c.MoveZ = 0 + c.ReturnPosition = nil + c.View.HasKeystone = false + c.Message = reason + w.dirty = true +} +func (w *World) Advance(now time.Time, dt float64) { + playedDT := math.Max(0, dt) + w.now = now + w.Tick++ + dt = math.Max(0, math.Min(dt, 0.25)) + if w.Phase == "won" || w.Phase == "lost" { + return + } + if w.Phase == "gathering" && w.Age() >= w.Balance.SeasonSeconds { + w.Phase = "cataclysm" + w.dirty = true + } + active := map[string]bool{} + for _, c := range w.Characters { + if c.View.Entity.State != "alive" { + continue + } + w.resetDay(c) + if c.Online { + midnight := time.Date(now.UTC().Year(), now.UTC().Month(), now.UTC().Day(), 0, 0, 0, 0, time.UTC) + c.DailySeconds += math.Min(playedDT, now.Sub(midnight).Seconds()) + c.View.PlayedSeconds += playedDT + c.View.RemainingSeconds = math.Max(0, w.Balance.DailyPlaySeconds-c.DailySeconds) + if c.View.RemainingSeconds <= 0 { + pos := c.View.Entity.Position + c.ReturnPosition = &pos + c.Sheltered = true + c.View.HasKeystone = true + c.View.Entity.Position = w.terrain.Position(0, 0) + c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, math.Max(50, c.View.Entity.HP)) + c.Online = false + c.MoveX = 0 + c.MoveZ = 0 + c.Message = "Daily limit reached. Your keystone is ready for tomorrow." + w.dirty = true + } + } + if c.Online { + if now.Sub(c.LastMove) > 250*time.Millisecond { + c.MoveX = 0 + c.MoveZ = 0 + } + pos := c.View.Entity.Position + nx, nz := pos.X+c.MoveX*w.Balance.PlayerSpeed*dt, pos.Z+c.MoveZ*w.Balance.PlayerSpeed*dt + if math.Hypot(nx, nz) < w.Balance.WorldRadius { + c.View.Entity.Position = w.terrain.Position(nx, nz) + } + for _, ch := range w.neighbors(c.View.Entity.Position) { + active[ch.Key] = true + w.ensureMob(ch) + } + } + if w.Phase == "cataclysm" && math.Hypot(c.View.Entity.Position.X, c.View.Entity.Position.Z) > w.SafeRadius() { + c.View.Entity.HP -= w.Balance.StormDamagePerSecond * dt + w.dirty = true + } + if c.View.Entity.HP <= 0 { + w.kill(c, "The encroaching ruin claimed this character.") + } + } + w.updateMobs(active, dt) + if w.Phase == "cataclysm" { + if w.Age()-w.BossLastAttack >= w.Balance.BossCooldown { + for _, c := range w.Characters { + if c.Online && !c.Sheltered && c.View.Entity.State == "alive" && distance(c.View.Entity.Position, w.terrain.Position(0, 0)) <= w.Balance.BossRange { + c.View.Entity.HP -= w.Balance.BossDamage + w.dirty = true + if c.View.Entity.HP <= 0 { + w.kill(c, "The Harbinger ended this character's journey.") + } + } + } + w.BossLastAttack = w.Age() + } + alive := 0 + for _, c := range w.Characters { + if c.View.Entity.State == "alive" { + alive++ + } + } + if w.SafeRadius() <= 0 || (len(w.Characters) > 0 && alive == 0) { + for _, c := range w.Characters { + w.kill(c, "The world has been destroyed.") + } + w.Phase = "lost" + ended := w.now + w.EndedAt = &ended + w.dirty = true + } + } + // Keep CPU/GPU working sets bounded to subscribed chunks. Persistent deltas survive eviction. + for key := range w.chunks { + if !active[key] { + delete(w.chunks, key) + } + } + for key, until := range w.Depleted { + if until <= w.Age() { + delete(w.Depleted, key) + } + } +} +func (w *World) ensureMob(ch p.Chunk) { + id := "m:" + ch.Key + if _, ok := w.Mobs[id]; ok { + return + } + x, z := (float64(ch.X)+0.55)*ch.Size, (float64(ch.Z)+0.55)*ch.Size + if math.Hypot(x, z) > w.Balance.WorldRadius { + return + } + hp := w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay) + w.Mobs[id] = &Mob{Entity: p.Entity{ID: id, Kind: "sentinel", Name: "Ash sentinel", Position: w.terrain.Position(x, z), HP: hp, MaxHP: hp, State: "alive"}, HomeX: int(ch.X), HomeZ: int(ch.Z)} +} +func (w *World) updateMobs(active map[string]bool, dt float64) { + for id, m := range w.Mobs { + key := Key(m.HomeX, m.HomeZ) + if !active[key] { + if m.Entity.HP == m.Entity.MaxHP || (m.Entity.HP <= 0 && w.Age() >= m.RespawnAt) { + delete(w.Mobs, id) + } + continue + } + if m.Entity.HP <= 0 { + if w.Age() >= m.RespawnAt { + m.Entity.HP = w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay) + m.Entity.MaxHP = m.Entity.HP + m.Entity.State = "alive" + } + continue + } + var target *Character + nearest := w.Balance.MobAggroRange + for _, c := range w.Characters { + if !c.Online || c.View.Entity.State != "alive" || c.Sheltered { + continue + } + d := distance(c.View.Entity.Position, m.Entity.Position) + if d < nearest { + nearest = d + target = c + } + } + if target == nil { + continue + } + if nearest <= w.Balance.MobAttackRange { + if w.Age()-m.LastAttack >= w.Balance.MobCooldown { + target.View.Entity.HP -= w.Balance.MobDamage * (1 + w.Age()/86400*w.Balance.MobScalePerDay) + m.LastAttack = w.Age() + w.dirty = true + if target.View.Entity.HP <= 0 { + w.kill(target, "An ash sentinel ended this character's journey.") + } + } + } else { + pos, to := m.Entity.Position, target.View.Entity.Position + step := math.Min(nearest, w.Balance.MobSpeed*dt) + x, z := pos.X+(to.X-pos.X)/nearest*step, pos.Z+(to.Z-pos.Z)/nearest*step + if ChunkCoord(x, w.Balance.ChunkSize) == m.HomeX && ChunkCoord(z, w.Balance.ChunkSize) == m.HomeZ { + m.Entity.Position = w.terrain.Position(x, z) + } + } + } +} +func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot { + c := w.Characters[id] + s := p.Snapshot{Type: "snapshot", Version: 1, Tick: w.Tick, World: w.Info(), Self: c.View, Message: c.Message, Entities: []p.Entity{}, Chunks: []p.Chunk{}, ChunkKeys: []string{}, UnavailableResources: []string{}} + allowed := map[string]bool{} + for _, ch := range w.neighbors(c.View.Entity.Position) { + allowed[ch.Key] = true + s.ChunkKeys = append(s.ChunkKeys, ch.Key) + if !known[ch.Key] { + s.Chunks = append(s.Chunks, ch) + } + for _, r := range ch.Resources { + if w.Depleted[r.ID] > w.Age() { + s.UnavailableResources = append(s.UnavailableResources, r.ID) + } + } + } + visible := func(pos p.Vec3) bool { + return allowed[Key(ChunkCoord(pos.X, w.Balance.ChunkSize), ChunkCoord(pos.Z, w.Balance.ChunkSize))] + } + for _, other := range w.Characters { + if other.View.Entity.ID != id && other.Online && other.View.Entity.State != "dead" && visible(other.View.Entity.Position) { + s.Entities = append(s.Entities, other.View.Entity) + } + } + for _, m := range w.Mobs { + if m.Entity.HP > 0 && visible(m.Entity.Position) { + s.Entities = append(s.Entities, m.Entity) + } + } + for _, corpse := range w.Corpses { + if visible(corpse.Entity.Position) { + s.Entities = append(s.Entities, corpse.Entity) + } + } + if w.Phase == "cataclysm" && visible(w.terrain.Position(0, 0)) { + s.Entities = append(s.Entities, p.Entity{ID: "boss", Kind: "boss", Name: "The Harbinger", HP: w.BossHP, MaxHP: w.Balance.BossHp, Position: w.terrain.Position(0, 0), State: "alive"}) + } + sort.Slice(s.Entities, func(i, j int) bool { return s.Entities[i].ID < s.Entities[j].ID }) + return s +} +func (w *World) TriggerBoss() error { + if w.Phase != "gathering" { + return fmt.Errorf("boss event already started") + } + w.CreatedAt = w.now.Add(-time.Duration(w.Balance.SeasonSeconds * float64(time.Second))) + w.Phase = "cataclysm" + w.dirty = true + return nil +} diff --git a/server/internal/game/world_test.go b/server/internal/game/world_test.go new file mode 100644 index 0000000..83d679f --- /dev/null +++ b/server/internal/game/world_test.go @@ -0,0 +1,305 @@ +package game + +import ( + "encoding/json" + "math" + "reflect" + "testing" + "time" + + "aeternalis/server/content" + p "aeternalis/server/internal/protocol" +) + +func fixture(t *testing.T) (*World, *Character) { + t.Helper() + b, err := content.Load() + if err != nil { + t.Fatal(err) + } + w := New("test", 123, time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC), b) + c, err := w.Join("account", "Traveler") + if err != nil { + t.Fatal(err) + } + if err = w.Connect(c.View.Entity.ID); err != nil { + t.Fatal(err) + } + return w, c +} +func TestTerrainDeterministicAndSeamless(t *testing.T) { + b, _ := content.Load() + a := NewTerrain(123, b) + other := NewTerrain(456, b) + if !reflect.DeepEqual(a.Chunk(-1, 0), NewTerrain(123, b).Chunk(-1, 0)) { + t.Fatal("same seed changed") + } + if reflect.DeepEqual(a.Chunk(0, 0), other.Chunk(0, 0)) { + t.Fatal("different seeds identical") + } + left, right := a.Chunk(-1, 0), a.Chunk(0, 0) + n := b.TerrainResolution + 1 + for z := 0; z < n; z++ { + if left.Heights[z*n+n-1] != right.Heights[z*n] { + t.Fatal("chunk seam") + } + } + if ChunkCoord(-0.1, 128) != -1 || ChunkCoord(-128, 128) != -1 { + t.Fatal("negative coordinates") + } + for _, r := range left.Resources { + if math.Abs(r.Position.Y-a.Height(r.Position.X, r.Position.Z)) > 1e-8 { + t.Fatal("floating resource") + } + } +} +func TestMovementAuthorityAndInterest(t *testing.T) { + w, c := fixture(t) + id := c.View.Entity.ID + w.now = w.now.Add(time.Second) + for _, intent := range []p.Intent{{Op: "move", Seq: 1, X: 2}, {Op: "move", Seq: 1, X: math.NaN()}, {Op: "move", Seq: 1, Z: math.Inf(1)}} { + if w.Intent(id, intent) == nil { + t.Fatal("invalid movement accepted") + } + } + if err := w.Intent(id, p.Intent{Op: "move", Seq: 1, X: 1, Z: 1}); err != nil { + t.Fatal(err) + } + before := c.View.Entity.Position + w.Advance(w.now.Add(50*time.Millisecond), 0.05) + if got := distance(before, c.View.Entity.Position); math.Abs(got-w.Balance.PlayerSpeed*0.05) > 1e-8 { + t.Fatalf("diagonal speed: %v", got) + } + if w.Intent(id, p.Intent{Op: "move", Seq: 1}) == nil { + t.Fatal("replayed sequence") + } + s := w.Snapshot(id, map[string]bool{}) + if len(s.Chunks) != 9 || len(s.ChunkKeys) != 9 { + t.Fatal("interest area not 3x3") + } + known := map[string]bool{} + for _, key := range s.ChunkKeys { + known[key] = true + } + if len(w.Snapshot(id, known).Chunks) != 0 { + t.Fatal("resent known terrain") + } + far, _ := w.Join("far", "Far") + far.View.Entity.Position = w.terrain.Position(700, 700) + far.Online = true + for _, e := range w.Snapshot(id, known).Entities { + if e.ID == far.View.Entity.ID { + t.Fatal("remote entity leaked outside interest") + } + } + w.Advance(w.now.Add(time.Second), 0.05) + if c.MoveX != 0 || c.MoveZ != 0 { + t.Fatal("stale input did not stop") + } +} +func TestGatherCraftAndPermanentDeath(t *testing.T) { + w, c := fixture(t) + id := c.View.Entity.ID + w.now = w.now.Add(2 * time.Second) + if w.Intent(id, p.Intent{Op: "gather", Seq: 1, Target: "arrival:ore"}) == nil { + t.Fatal("remote gather accepted") + } + c.View.Entity.Position = w.terrain.Position(17, 12) + if err := w.Intent(id, p.Intent{Op: "gather", Seq: 2, Target: "arrival:ore"}); err != nil { + t.Fatal(err) + } + if c.View.Inventory["ore"] != 1 { + t.Fatal("gather failed") + } + if w.Intent(id, p.Intent{Op: "gather", Seq: 3, Target: "arrival:ore"}) == nil { + t.Fatal("double gather") + } + if w.Intent(id, p.Intent{Op: "craft", Seq: 4, Target: "spear"}) == nil { + t.Fatal("free craft") + } + c.View.Inventory["wood"] = 3 + c.View.Inventory["ore"] = 2 + if err := w.Intent(id, p.Intent{Op: "craft", Seq: 5, Target: "spear"}); err != nil { + t.Fatal(err) + } + if c.View.Inventory["spear"] != 1 || c.View.Inventory["wood"] != 0 || c.View.Inventory["ore"] != 0 { + t.Fatal("recipe not atomic") + } + w.kill(c, "test death") + w.Disconnect(id) + if w.Connect(id) == nil { + t.Fatal("dead character reconnected") + } + same, err := w.Join(c.Account, "Replacement") + if err != nil || same.View.Entity.ID != id || same.View.Entity.State != "dead" { + t.Fatal("death bypass by rejoining") + } + if len(c.View.Inventory) != 0 || w.Corpses["corpse:"+id].Inventory["spear"] != 1 { + t.Fatal("corpse inventory") + } + raw, _ := json.Marshal(w) + var restored World + if err = json.Unmarshal(raw, &restored); err != nil { + t.Fatal(err) + } + if err = restored.Restore(w.now); err != nil { + t.Fatal(err) + } + if restored.Connect(id) == nil { + t.Fatal("restart resurrected character") + } +} + +func TestStaticResourcesAreNotReplicatedEverySnapshot(t *testing.T) { + w, c := fixture(t) + w.Depleted["arrival:ore"] = w.Age() + 60 + s := w.Snapshot(c.View.Entity.ID, map[string]bool{}) + if len(s.UnavailableResources) != 1 || s.UnavailableResources[0] != "arrival:ore" { + t.Fatal("missing authoritative resource availability") + } + for _, e := range s.Entities { + if e.Kind == "tree" || e.Kind == "ore" || e.Kind == "herb" { + t.Fatal("static resource repeated in dynamic entity snapshot") + } + } + resources := 0 + for _, ch := range s.Chunks { + resources += len(ch.Resources) + } + if resources == 0 { + t.Fatal("initial chunk does not carry resources") + } +} +func TestDailyLimitAndKeystone(t *testing.T) { + w, c := fixture(t) + w.Balance.DailyPlaySeconds = 1 + c.DailySeconds = .9 + c.View.Entity.HP = 20 + c.View.Entity.Position = w.terrain.Position(40, 40) + w.Advance(w.now.Add(200*time.Millisecond), .2) + if c.Online || c.ReturnPosition == nil || !c.View.HasKeystone || c.View.Entity.HP != 50 || distance(c.View.Entity.Position, p.Vec3{}) != 0 { + t.Fatalf("cap not enforced: %+v", c) + } + if w.Connect(c.View.Entity.ID) == nil { + t.Fatal("same-day cap bypass") + } + w.now = w.now.Add(24 * time.Hour) + if err := w.Connect(c.View.Entity.ID); err != nil { + t.Fatal(err) + } + if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "return", Seq: 1}); err != nil { + t.Fatal(err) + } + if c.View.Entity.Position.X != 40 || c.ReturnPosition != nil || c.View.HasKeystone { + t.Fatal("keystone failed") + } +} + +func TestDailyBudgetUsesWallTimeDuringLag(t *testing.T) { + w, c := fixture(t) + w.Balance.DailyPlaySeconds = 2 + w.Advance(w.now.Add(3*time.Second), 3) + if c.Online || c.View.RemainingSeconds != 0 { + t.Fatal("simulation lag bypassed wall-clock play cap") + } +} + +func TestKeystoneCannotGrantRoamingInvulnerability(t *testing.T) { + w, c := fixture(t) + c.Sheltered = true + c.ReturnPosition = &p.Vec3{X: 40, Z: 40} + if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 1, X: 1}); err != nil { + t.Fatal(err) + } + if c.Sheltered || c.ReturnPosition == nil { + t.Fatal("leaving sanctuary must remove protection while preserving keystone") + } +} +func TestBossVictoryAndCollapse(t *testing.T) { + t.Run("victory includes offline survivors and excludes dead", func(t *testing.T) { + w, c := fixture(t) + dead, _ := w.Join("dead", "Dead") + w.kill(dead, "test") + offline, _ := w.Join("offline", "Offline") + w.now = w.now.Add(time.Second) + _ = w.TriggerBoss() + w.BossHP = 1 + if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 1, Target: "boss"}); err != nil { + t.Fatal(err) + } + if w.Phase != "won" || c.View.Entity.State != "eligible" || offline.View.Entity.State != "eligible" || dead.View.Entity.State != "dead" { + t.Fatal("incorrect survivor selection") + } + radius := w.SafeRadius() + w.Advance(w.now.Add(20*24*time.Hour), .05) + if w.SafeRadius() != radius { + t.Fatal("world kept collapsing after boss death") + } + if c.View.Entity.State != "eligible" { + t.Fatal("victory not terminal") + } + if w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 2, X: 1}) == nil { + t.Fatal("survivor mutated frozen world") + } + }) + t.Run("collapse kills offline and capped characters", func(t *testing.T) { + w, c := fixture(t) + c.Online = false + c.ReturnPosition = &p.Vec3{X: 40} + w.Advance(w.CreatedAt.Add(time.Duration((w.Balance.SeasonSeconds+w.Balance.CollapseSeconds+1)*float64(time.Second))), .05) + if w.Phase != "lost" || c.View.Entity.State != "dead" { + t.Fatal("world destruction bypass") + } + }) + t.Run("boss schedule survives downtime", func(t *testing.T) { + w, _ := fixture(t) + w.Advance(w.CreatedAt.Add(7*24*time.Hour+5*time.Minute), .05) + if w.Phase != "cataclysm" || w.SafeRadius() >= w.Balance.WorldRadius { + t.Fatal("deadline did not advance") + } + }) +} +func TestSpawnAndTransferPreserveBudget(t *testing.T) { + w, c := fixture(t) + other, _ := w.Join("other", "Other") + if distance(c.View.Entity.Position, other.View.Entity.Position) < w.Balance.SpawnSeparation { + t.Fatal("spawns overlap") + } + c.View.Entity.State = "eligible" + c.DailySeconds = 123 + c.View.PlayedSeconds = 456 + c.View.Skills["combat"] = 9 + c.View.Inventory["spear"] = 1 + next := New("next", 999, w.now, w.Balance) + if err := next.Import(c); err != nil { + t.Fatal(err) + } + if c.DailySeconds != 123 || c.View.PlayedSeconds != 456 || c.View.Skills["combat"] != 9 || c.View.Inventory["spear"] != 1 { + t.Fatal("transfer changed progress or budget") + } + if err := next.Import(c); err == nil { + t.Fatal("duplicate import") + } +} +func BenchmarkSnapshot100Players(b *testing.B) { + balance, _ := content.Load() + w := New("bench", 123, time.Now(), balance) + ids := []string{} + for i := 0; i < 100; i++ { + c, err := w.Join(ID(), "Traveler") + if err != nil { + b.Fatal(err) + } + c.Online = true + ids = append(ids, c.View.Entity.ID) + } + w.Advance(time.Now(), .05) + known := map[string]bool{} + b.ResetTimer() + for i := 0; i < b.N; i++ { + s := w.Snapshot(ids[i%len(ids)], known) + if _, err := json.Marshal(s); err != nil { + b.Fatal(err) + } + } +} diff --git a/server/internal/protocol/generated.go b/server/internal/protocol/generated.go new file mode 100644 index 0000000..a4ae431 --- /dev/null +++ b/server/internal/protocol/generated.go @@ -0,0 +1,81 @@ +// Code generated from schemas/protocol.json. DO NOT EDIT. +package protocol + +type Protocol struct { + Intent Intent `json:"intent"` + Snapshot Snapshot `json:"snapshot"` +} + +type Intent struct { + Op string `json:"op"` + Seq int64 `json:"seq"` + Target string `json:"target"` + X float64 `json:"x"` + Z float64 `json:"z"` +} + +type Snapshot struct { + ChunkKeys []string `json:"chunkKeys"` + Chunks []Chunk `json:"chunks"` + Entities []Entity `json:"entities"` + Message string `json:"message"` + Self Character `json:"self"` + Tick int64 `json:"tick"` + Type string `json:"type"` + UnavailableResources []string `json:"unavailableResources"` + Version int64 `json:"version"` + World WorldInfo `json:"world"` +} + +type Chunk struct { + Biome string `json:"biome"` + Heights []float64 `json:"heights"` + Key string `json:"key"` + Resolution int64 `json:"resolution"` + Resources []Entity `json:"resources"` + Size float64 `json:"size"` + X int64 `json:"x"` + Z int64 `json:"z"` +} + +type Entity struct { + HP float64 `json:"hp"` + ID string `json:"id"` + Kind string `json:"kind"` + MaxHP float64 `json:"maxHp"` + Name string `json:"name"` + Position Vec3 `json:"position"` + State string `json:"state"` +} + +type Vec3 struct { + X float64 `json:"x"` + Y float64 `json:"y"` + Z float64 `json:"z"` +} + +type Character struct { + ACK int64 `json:"ack"` + Entity Entity `json:"entity"` + HasKeystone bool `json:"hasKeystone"` + Inventory map[string]int64 `json:"inventory"` + Kills int64 `json:"kills"` + PlayedSeconds float64 `json:"playedSeconds"` + RemainingSeconds float64 `json:"remainingSeconds"` + Skills map[string]int64 `json:"skills"` +} + +type WorldInfo struct { + AgeSeconds float64 `json:"ageSeconds"` + BossHP float64 `json:"bossHp"` + BossInSeconds float64 `json:"bossInSeconds"` + BossMaxHP float64 `json:"bossMaxHp"` + Capacity int64 `json:"capacity"` + CollapseInSeconds float64 `json:"collapseInSeconds"` + ID string `json:"id"` + Online int64 `json:"online"` + Phase string `json:"phase"` + Radius float64 `json:"radius"` + SafeRadius float64 `json:"safeRadius"` + Seed int64 `json:"seed"` +} diff --git a/server/internal/store/store.go b/server/internal/store/store.go new file mode 100644 index 0000000..923172c --- /dev/null +++ b/server/internal/store/store.go @@ -0,0 +1,245 @@ +package store + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "strings" + + "aeternalis/server/internal/game" + _ "github.com/jackc/pgx/v5/stdlib" + _ "modernc.org/sqlite" +) + +var ErrOwnership = errors.New("world ownership or revision lost") + +type DB struct { + sql *sql.DB + postgres bool +} +type Lease struct { + DB *DB + WorldID string + Owner string + Revision int64 +} +type Passage struct { + CharacterID string `json:"characterId"` + SourceWorld string `json:"sourceWorld"` + Name string `json:"name"` +} + +func Open(ctx context.Context, dsn string) (*DB, error) { + postgres := strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") + driver := "sqlite" + if postgres { + driver = "pgx" + } + conn, err := sql.Open(driver, dsn) + if err != nil { + return nil, err + } + conn.SetMaxOpenConns(8) + if !postgres { + conn.SetMaxOpenConns(1) + } + db := &DB{conn, postgres} + if err = conn.PingContext(ctx); err != nil { + conn.Close() + return nil, err + } + if !postgres { + if _, err = conn.ExecContext(ctx, "PRAGMA journal_mode=WAL"); err != nil { + conn.Close() + return nil, err + } + _, _ = conn.ExecContext(ctx, "PRAGMA busy_timeout=5000") + } + for _, stmt := range []string{ + `CREATE TABLE IF NOT EXISTS worlds(id TEXT PRIMARY KEY, owner TEXT NOT NULL, lease_until BIGINT NOT NULL, revision BIGINT NOT NULL, snapshot TEXT NOT NULL)`, + `CREATE TABLE IF NOT EXISTS passages(character_id TEXT PRIMARY KEY, account_id TEXT NOT NULL, source_world TEXT NOT NULL, character TEXT NOT NULL, claimed_world TEXT)`, + `CREATE INDEX IF NOT EXISTS passages_account ON passages(account_id)`, + `CREATE TABLE IF NOT EXISTS sessions(token_hash TEXT PRIMARY KEY, account_id TEXT NOT NULL, expires BIGINT NOT NULL)`, + `CREATE INDEX IF NOT EXISTS sessions_expiry ON sessions(expires)`, + } { + if _, err = conn.ExecContext(ctx, stmt); err != nil { + conn.Close() + return nil, err + } + } + return db, nil +} +func (d *DB) Close() error { return d.sql.Close() } +func (d *DB) q(query string) string { + if !d.postgres { + return query + } + i := 0 + var b strings.Builder + for _, c := range query { + if c == '?' { + i++ + fmt.Fprintf(&b, "$%d", i) + } else { + b.WriteRune(c) + } + } + return b.String() +} +func (d *DB) now() string { + if d.postgres { + return "CAST(EXTRACT(EPOCH FROM clock_timestamp()) AS BIGINT)" + } + return "unixepoch()" +} +func (d *DB) Acquire(ctx context.Context, w *game.World) (*Lease, []byte, error) { + data, err := json.Marshal(w) + if err != nil { + return nil, nil, err + } + tx, err := d.sql.BeginTx(ctx, nil) + if err != nil { + return nil, nil, err + } + defer tx.Rollback() + _, err = tx.ExecContext(ctx, d.q(`INSERT INTO worlds(id,owner,lease_until,revision,snapshot) VALUES(?,'',0,0,?) ON CONFLICT(id) DO NOTHING`), w.ID, string(data)) + if err != nil { + return nil, nil, err + } + owner := game.ID() + result, err := tx.ExecContext(ctx, d.q(`UPDATE worlds SET owner=?,lease_until=`+d.now()+`+30 WHERE id=? AND (owner='' OR lease_until<`+d.now()+`)`), owner, w.ID) + if err != nil { + return nil, nil, err + } + n, _ := result.RowsAffected() + if n != 1 { + return nil, nil, ErrOwnership + } + var snapshot string + var revision int64 + if err = tx.QueryRowContext(ctx, d.q(`SELECT revision,snapshot FROM worlds WHERE id=?`), w.ID).Scan(&revision, &snapshot); err != nil { + return nil, nil, err + } + if err = tx.Commit(); err != nil { + return nil, nil, err + } + return &Lease{d, w.ID, owner, revision}, []byte(snapshot), nil +} +func (l *Lease) Save(ctx context.Context, w *game.World, claimID string) error { + data, err := json.Marshal(w) + if err != nil { + return err + } + d := l.DB + tx, err := d.sql.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + result, err := tx.ExecContext(ctx, d.q(`UPDATE worlds SET snapshot=?,revision=revision+1,lease_until=`+d.now()+`+30 WHERE id=? AND owner=? AND revision=? AND lease_until>=`+d.now()), string(data), l.WorldID, l.Owner, l.Revision) + if err != nil { + return err + } + n, _ := result.RowsAffected() + if n != 1 { + return ErrOwnership + } + if claimID != "" { + c := w.Characters[claimID] + if c == nil { + return errors.New("claimed character absent from target") + } + result, err = tx.ExecContext(ctx, d.q(`UPDATE passages SET claimed_world=? WHERE character_id=? AND account_id=? AND claimed_world IS NULL AND source_world<>?`), w.ID, claimID, c.Account, w.ID) + if err != nil { + return err + } + n, _ = result.RowsAffected() + if n != 1 { + return errors.New("passage already redeemed or unavailable") + } + } + if w.Phase == "won" { + for _, c := range w.Characters { + if c.View.Entity.State != "eligible" { + continue + } + encoded, err := json.Marshal(c) + if err != nil { + return err + } + _, err = tx.ExecContext(ctx, d.q(`INSERT INTO passages(character_id,account_id,source_world,character) VALUES(?,?,?,?) ON CONFLICT(character_id) DO UPDATE SET source_world=excluded.source_world,character=excluded.character,claimed_world=NULL WHERE passages.claimed_world=excluded.source_world`), c.View.Entity.ID, c.Account, w.ID, string(encoded)) + if err != nil { + return err + } + } + } + if err = tx.Commit(); err != nil { + return err + } + l.Revision++ + w.Saved() + return nil +} +func (l *Lease) Release(ctx context.Context) error { + _, err := l.DB.sql.ExecContext(ctx, l.DB.q(`UPDATE worlds SET owner='',lease_until=0 WHERE id=? AND owner=?`), l.WorldID, l.Owner) + return err +} +func (d *DB) Passages(ctx context.Context, account string) ([]Passage, error) { + rows, err := d.sql.QueryContext(ctx, d.q(`SELECT character_id,source_world,character FROM passages WHERE account_id=? AND claimed_world IS NULL`), account) + if err != nil { + return nil, err + } + defer rows.Close() + out := []Passage{} + for rows.Next() { + var p Passage + var raw string + if err = rows.Scan(&p.CharacterID, &p.SourceWorld, &raw); err != nil { + return nil, err + } + var c game.Character + if err = json.Unmarshal([]byte(raw), &c); err != nil { + return nil, err + } + p.Name = c.View.Entity.Name + out = append(out, p) + } + return out, rows.Err() +} +func (d *DB) ReadPassage(ctx context.Context, id, account string) (*game.Character, error) { + var raw string + err := d.sql.QueryRowContext(ctx, d.q(`SELECT character FROM passages WHERE character_id=? AND account_id=? AND claimed_world IS NULL`), id, account).Scan(&raw) + if err != nil { + return nil, err + } + var c game.Character + if err = json.Unmarshal([]byte(raw), &c); err != nil { + return nil, err + } + return &c, nil +} +func (d *DB) CreateSession(ctx context.Context, hash, account string) error { + tx, err := d.sql.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err = tx.ExecContext(ctx, `DELETE FROM sessions WHERE expires<`+d.now()); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, d.q(`INSERT INTO sessions(token_hash,account_id,expires) VALUES(?,?,`+d.now()+`+86400)`), hash, account); err != nil { + return err + } + return tx.Commit() +} +func (d *DB) Session(ctx context.Context, hash string) (string, error) { + var account string + err := d.sql.QueryRowContext(ctx, d.q(`SELECT account_id FROM sessions WHERE token_hash=? AND expires>`+d.now()), hash).Scan(&account) + return account, err +} +func (d *DB) DeleteSession(ctx context.Context, hash string) error { + _, err := d.sql.ExecContext(ctx, d.q(`DELETE FROM sessions WHERE token_hash=?`), hash) + return err +} diff --git a/server/internal/store/store_test.go b/server/internal/store/store_test.go new file mode 100644 index 0000000..325029a --- /dev/null +++ b/server/internal/store/store_test.go @@ -0,0 +1,210 @@ +package store + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "sync" + "testing" + "time" + + "aeternalis/server/content" + "aeternalis/server/internal/game" +) + +func TestStoreLifecycle(t *testing.T) { + runStoreTests(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "world.db"))) +} + +func TestConcurrentPassageRedemption(t *testing.T) { + ctx := context.Background() + db, err := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "race.db"))) + if err != nil { + t.Fatal(err) + } + defer db.Close() + b, _ := content.Load() + now := time.Now().UTC() + source := game.New("source", 1, now, b) + lease, _, err := db.Acquire(ctx, source) + if err != nil { + t.Fatal(err) + } + c, _ := source.Join("account", "Survivor") + c.View.Entity.State = "eligible" + source.Phase = "won" + if err = lease.Save(ctx, source, ""); err != nil { + t.Fatal(err) + } + targets := []*game.World{game.New("target-a", 2, now, b), game.New("target-b", 3, now, b)} + leases := make([]*Lease, 2) + for i, w := range targets { + leases[i], _, err = db.Acquire(ctx, w) + if err != nil { + t.Fatal(err) + } + copy, err := db.ReadPassage(ctx, c.View.Entity.ID, c.Account) + if err != nil { + t.Fatal(err) + } + if err = w.Import(copy); err != nil { + t.Fatal(err) + } + } + var wg sync.WaitGroup + results := make(chan error, 2) + for i := range targets { + wg.Add(1) + go func(i int) { defer wg.Done(); results <- leases[i].Save(ctx, targets[i], c.View.Entity.ID) }(i) + } + wg.Wait() + close(results) + successes := 0 + for err := range results { + if err == nil { + successes++ + } + } + if successes != 1 { + t.Fatalf("expected one successful redemption, got %d", successes) + } + durableCopies := 0 + for _, w := range targets { + var raw string + if err := db.sql.QueryRowContext(ctx, db.q("SELECT snapshot FROM worlds WHERE id=?"), w.ID).Scan(&raw); err != nil { + t.Fatal(err) + } + var restored game.World + if err := json.Unmarshal([]byte(raw), &restored); err != nil { + t.Fatal(err) + } + if restored.Characters[c.View.Entity.ID] != nil { + durableCopies++ + } + } + if durableCopies != 1 { + t.Fatal("failed redemption left a durable duplicate") + } +} +func TestPostgresLifecycle(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not configured") + } + runStoreTests(t, dsn) +} +func runStoreTests(t *testing.T, dsn string) { + ctx := context.Background() + db, err := Open(ctx, dsn) + if err != nil { + t.Fatal(err) + } + defer db.Close() + balance, _ := content.Load() + prefix := game.ID() + now := time.Now().UTC() + source := game.New(prefix+"-source", 123, now, balance) + lease, _, err := db.Acquire(ctx, source) + if err != nil { + t.Fatal(err) + } + if _, _, err = db.Acquire(ctx, source); err == nil { + t.Fatal("two simultaneous world owners") + } + c, _ := source.Join("account:"+prefix, "Traveler") + c.View.Inventory["spear"] = 1 + c.DailySeconds = 123 + c.View.Entity.State = "eligible" + source.Phase = "won" + if err = lease.Save(ctx, source, ""); err != nil { + t.Fatal(err) + } + if err = lease.Save(ctx, source, ""); err != nil { + t.Fatal(err) + } + passages, err := db.Passages(ctx, c.Account) + if err != nil || len(passages) != 1 { + t.Fatalf("idempotent survivor grant %v %v", passages, err) + } + if _, err = db.ReadPassage(ctx, c.View.Entity.ID, "attacker"); err == nil { + t.Fatal("another account stole transfer") + } + target := game.New(prefix+"-target", 456, now, balance) + targetLease, _, err := db.Acquire(ctx, target) + if err != nil { + t.Fatal(err) + } + survivor, err := db.ReadPassage(ctx, c.View.Entity.ID, c.Account) + if err != nil { + t.Fatal(err) + } + if err = target.Import(survivor); err != nil { + t.Fatal(err) + } + if err = targetLease.Save(ctx, target, c.View.Entity.ID); err != nil { + t.Fatal(err) + } + if _, err = db.ReadPassage(ctx, c.View.Entity.ID, c.Account); err == nil { + t.Fatal("passage can be redeemed twice") + } + third := game.New(prefix+"-third", 789, now, balance) + thirdLease, _, err := db.Acquire(ctx, third) + if err != nil { + t.Fatal(err) + } + copy := *survivor + copy.View.Entity.State = "eligible" + if err = third.Import(©); err != nil { + t.Fatal(err) + } + if err = thirdLease.Save(ctx, third, c.View.Entity.ID); err == nil { + t.Fatal("duplicate transfer committed") + } + if err = targetLease.Release(ctx); err != nil { + t.Fatal(err) + } + freshLease, raw, err := db.Acquire(ctx, target) + if err != nil { + t.Fatal(err) + } + var restored game.World + if err = json.Unmarshal(raw, &restored); err != nil { + t.Fatal(err) + } + loaded := restored.Characters[c.View.Entity.ID] + if loaded == nil || loaded.DailySeconds != 123 || loaded.View.Inventory["spear"] != 1 { + t.Fatal("transfer not durable") + } + if err = targetLease.Save(ctx, target, ""); err == nil { + t.Fatal("stale owner wrote state") + } + // A subsequent victory grants a fresh passage for the same permanent character ID. + loaded.View.Entity.State = "eligible" + restored.Phase = "won" + if err = freshLease.Save(ctx, &restored, ""); err != nil { + t.Fatal(err) + } + if err = lease.Save(ctx, source, ""); err != nil { + t.Fatal(err) + } + passages, err = db.Passages(ctx, c.Account) + if err != nil || len(passages) != 1 || passages[0].SourceWorld != target.ID { + t.Fatal("old world overwrote next passage") + } + if err = db.CreateSession(ctx, "hash:"+prefix, c.Account); err != nil { + t.Fatal(err) + } + if account, err := db.Session(ctx, "hash:"+prefix); err != nil || account != c.Account { + t.Fatal("session roundtrip") + } + if err = db.DeleteSession(ctx, "hash:"+prefix); err != nil { + t.Fatal(err) + } + if _, err = db.Session(ctx, "hash:"+prefix); err == nil { + t.Fatal("revoked session remains valid") + } + _ = lease.Release(ctx) + _ = freshLease.Release(ctx) + _ = thirdLease.Release(ctx) +} diff --git a/server/internal/transport/auth.go b/server/internal/transport/auth.go new file mode 100644 index 0000000..ffe6173 --- /dev/null +++ b/server/internal/transport/auth.go @@ -0,0 +1,149 @@ +package transport + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "net/http" + "net/url" + "strings" + "sync" + "time" + + "aeternalis/server/internal/game" + "aeternalis/server/internal/store" + "github.com/coreos/go-oidc/v3/oidc" + "golang.org/x/oauth2" +) + +type Auth struct { + db *store.DB + dev bool + base string + oauth *oauth2.Config + verifier *oidc.IDTokenVerifier + mu sync.Mutex + flows map[string]flow +} +type flow struct { + verifier string + expires time.Time +} + +func NewAuth(ctx context.Context, db *store.DB, dev bool, base, issuer, client, secret string) (*Auth, error) { + a := &Auth{db: db, dev: dev, base: base, flows: map[string]flow{}} + if dev { + return a, nil + } + if !strings.HasPrefix(base, "https://") || !strings.HasPrefix(issuer, "https://") || client == "" { + return nil, errors.New("production requires HTTPS PUBLIC_URL, OIDC_ISSUER, and OIDC_CLIENT_ID") + } + provider, err := oidc.NewProvider(ctx, issuer) + if err != nil { + return nil, err + } + a.oauth = &oauth2.Config{ClientID: client, ClientSecret: secret, Endpoint: provider.Endpoint(), RedirectURL: base + "/auth/callback", Scopes: []string{oidc.ScopeOpenID}} + a.verifier = provider.Verifier(&oidc.Config{ClientID: client}) + return a, nil +} +func hash(s string) string { b := sha256.Sum256([]byte(s)); return hex.EncodeToString(b[:]) } +func (a *Auth) cookieName() string { + if a.dev { + return "aeternalis_session" + } + return "__Host-aeternalis_session" +} +func (a *Auth) account(r *http.Request) (string, error) { + c, err := r.Cookie(a.cookieName()) + if err != nil || len(c.Value) != 64 { + return "", errors.New("not authenticated") + } + return a.db.Session(r.Context(), hash(c.Value)) +} +func (a *Auth) session(w http.ResponseWriter, r *http.Request, account string) error { + token := game.ID() + game.ID() + if err := a.db.CreateSession(r.Context(), hash(token), account); err != nil { + return err + } + http.SetCookie(w, &http.Cookie{Name: a.cookieName(), Value: token, Path: "/", HttpOnly: true, Secure: !a.dev, SameSite: http.SameSiteLaxMode, MaxAge: 86400}) + return nil +} +func (a *Auth) login(w http.ResponseWriter, r *http.Request) { + if a.dev { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } + state := game.ID() + game.ID() + v := oauth2.GenerateVerifier() + a.mu.Lock() + for key, f := range a.flows { + if time.Now().After(f.expires) { + delete(a.flows, key) + } + } + if len(a.flows) >= 4096 { + a.mu.Unlock() + fail(w, 503, "login capacity reached") + return + } + a.flows[state] = flow{v, time.Now().Add(10 * time.Minute)} + a.mu.Unlock() + http.SetCookie(w, &http.Cookie{Name: "__Host-aeternalis_login", Value: state, Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: 600}) + http.Redirect(w, r, a.oauth.AuthCodeURL(state, oauth2.S256ChallengeOption(v), oidc.Nonce(state)), http.StatusSeeOther) +} +func (a *Auth) callback(w http.ResponseWriter, r *http.Request) { + if a.dev { + fail(w, 404, "not enabled") + return + } + state := r.URL.Query().Get("state") + cookie, err := r.Cookie("__Host-aeternalis_login") + if err != nil || state == "" || cookie.Value != state { + fail(w, 400, "invalid login state") + return + } + a.mu.Lock() + f, ok := a.flows[state] + delete(a.flows, state) + a.mu.Unlock() + if !ok || time.Now().After(f.expires) { + fail(w, 400, "login expired") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + token, err := a.oauth.Exchange(ctx, r.URL.Query().Get("code"), oauth2.VerifierOption(f.verifier)) + if err != nil { + fail(w, 401, "login exchange failed") + return + } + raw, ok := token.Extra("id_token").(string) + if !ok { + fail(w, 401, "identity token missing") + return + } + identity, err := a.verifier.Verify(ctx, raw) + if err != nil || identity.Nonce != state { + fail(w, 401, "invalid identity token") + return + } + if err = a.session(w, r, hash(identity.Issuer+"\x00"+identity.Subject)); err != nil { + fail(w, 503, "session unavailable") + return + } + http.SetCookie(w, &http.Cookie{Name: "__Host-aeternalis_login", Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: -1}) + http.Redirect(w, r, "/", http.StatusSeeOther) +} +func validOrigin(r *http.Request, base string) bool { + origin := r.Header.Get("Origin") + if origin == "" { + return false + } + expected, err := url.Parse(base) + if err != nil { + return false + } + actual, err := url.Parse(origin) + return err == nil && actual.Scheme == expected.Scheme && actual.Host == expected.Host && actual.Path == "" && actual.RawQuery == "" && actual.User == nil +} diff --git a/server/internal/transport/http.go b/server/internal/transport/http.go new file mode 100644 index 0000000..a3848ea --- /dev/null +++ b/server/internal/transport/http.go @@ -0,0 +1,408 @@ +package transport + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net" + "net/http" + "os" + "path/filepath" + "regexp" + "strings" + "sync" + "time" + + "aeternalis/server/internal/game" + p "aeternalis/server/internal/protocol" + "github.com/coder/websocket" +) + +type Destination struct { + ID string `json:"id"` + URL string `json:"url"` +} +type HTTP struct { + s *Service + auth *Auth + assets string + worlds []Destination + mu sync.Mutex + rates map[string]*bucket +} +type bucket struct { + tokens float64 + updated time.Time +} + +func NewHTTP(s *Service, a *Auth, assets string, worlds []Destination) *HTTP { + return &HTTP{s: s, auth: a, assets: assets, worlds: worlds, rates: map[string]*bucket{}} +} +func respond(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} +func fail(w http.ResponseWriter, status int, msg string) { + respond(w, status, map[string]string{"error": msg}) +} +func decode(w http.ResponseWriter, r *http.Request, v any) error { + r.Body = http.MaxBytesReader(w, r.Body, 4096) + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if err := d.Decode(v); err != nil { + return err + } + var extra any + if err := d.Decode(&extra); err != io.EOF { + return io.ErrUnexpectedEOF + } + return nil +} +func (h *HTTP) allow(r *http.Request) bool { + // RemoteAddr is authoritative here. Proxy headers are deliberately not trusted. + key, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + key = r.RemoteAddr + } + h.mu.Lock() + defer h.mu.Unlock() + now := time.Now() + b := h.rates[key] + if b == nil { + if len(h.rates) >= 4096 { + for k, v := range h.rates { + if now.Sub(v.updated) > time.Minute { + delete(h.rates, k) + } + } + if len(h.rates) >= 4096 { + return false + } + } + b = &bucket{60, now} + h.rates[key] = b + } + b.tokens = min(60, b.tokens+now.Sub(b.updated).Seconds()*5) + b.updated = now + if b.tokens < 1 { + return false + } + b.tokens-- + return true +} +func (h *HTTP) Handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { + if !h.s.ready.Load() { + fail(w, 503, "world frozen") + return + } + respond(w, 200, map[string]string{"status": "alive"}) + }) + mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, r *http.Request) { + if !h.s.ready.Load() { + fail(w, 503, "world unavailable") + return + } + respond(w, 200, map[string]string{"status": "ready"}) + }) + mux.HandleFunc("GET /auth/login", h.auth.login) + mux.HandleFunc("GET /auth/callback", h.auth.callback) + mux.HandleFunc("POST /auth/dev", func(w http.ResponseWriter, r *http.Request) { + if !h.auth.dev { + fail(w, 404, "not enabled") + return + } + if account, err := h.auth.account(r); err == nil { + respond(w, 200, map[string]bool{"authenticated": account != ""}) + return + } + if err := h.auth.session(w, r, "dev:"+game.ID()); err != nil { + fail(w, 503, "session unavailable") + return + } + respond(w, 200, map[string]bool{"authenticated": true}) + }) + mux.HandleFunc("POST /auth/logout", func(w http.ResponseWriter, r *http.Request) { + account, _ := h.auth.account(r) + if cookie, err := r.Cookie(h.auth.cookieName()); err == nil { + _ = h.auth.db.DeleteSession(r.Context(), hash(cookie.Value)) + } + h.s.mu.Lock() + if c := h.s.world.ForAccount(account); c != nil { + if p := h.s.peers[c.View.Entity.ID]; p != nil { + p.close() + } + } + h.s.mu.Unlock() + http.SetCookie(w, &http.Cookie{Name: h.auth.cookieName(), Path: "/", HttpOnly: true, Secure: !h.auth.dev, SameSite: http.SameSiteLaxMode, MaxAge: -1}) + respond(w, 200, map[string]bool{"ok": true}) + }) + mux.HandleFunc("GET /api/config", func(w http.ResponseWriter, r *http.Request) { + h.s.mu.Lock() + defer h.s.mu.Unlock() + b := h.s.world.Balance + respond(w, 200, map[string]any{"worldId": h.s.world.ID, "development": h.auth.dev, "worlds": h.worlds, "chunkSize": b.ChunkSize, "playerSpeed": b.PlayerSpeed, "attackRange": b.AttackRange, "gatherRange": b.GatherRange, "recipes": b.Recipes, "tickHz": b.TickHz}) + }) + mux.HandleFunc("GET /api/preview", func(w http.ResponseWriter, r *http.Request) { + h.s.mu.Lock() + defer h.s.mu.Unlock() + t := game.NewTerrain(h.s.world.Seed, h.s.world.Balance) + chunks := []p.Chunk{} + for z := -1; z <= 1; z++ { + for x := -1; x <= 1; x++ { + chunks = append(chunks, t.Chunk(x, z)) + } + } + respond(w, 200, chunks) + }) + mux.HandleFunc("GET /api/me", func(w http.ResponseWriter, r *http.Request) { + account, err := h.auth.account(r) + if err != nil { + fail(w, 401, "sign in required") + return + } + h.s.mu.Lock() + defer h.s.mu.Unlock() + if c := h.s.world.ForAccount(account); c != nil { + respond(w, 200, map[string]any{"character": c.View, "world": h.s.world.Info()}) + return + } + respond(w, 200, map[string]any{"character": nil, "world": h.s.world.Info()}) + }) + mux.HandleFunc("POST /api/join", func(w http.ResponseWriter, r *http.Request) { + account, err := h.auth.account(r) + if err != nil { + fail(w, 401, "sign in required") + return + } + var req struct { + Name string `json:"name"` + Passage string `json:"passage"` + } + if decode(w, r, &req) != nil { + fail(w, 400, "invalid request") + return + } + req.Name = strings.TrimSpace(req.Name) + if req.Passage == "" && !regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9 _-]{1,23}$`).MatchString(req.Name) { + fail(w, 400, "Name must be 2-24 letters, numbers, spaces, or hyphens.") + return + } + c, err := h.s.join(r.Context(), account, req.Name, req.Passage) + if err != nil { + fail(w, 409, err.Error()) + return + } + respond(w, 200, c) + }) + mux.HandleFunc("GET /api/passages", func(w http.ResponseWriter, r *http.Request) { + account, err := h.auth.account(r) + if err != nil { + fail(w, 401, "sign in required") + return + } + passages, err := h.auth.db.Passages(r.Context(), account) + if err != nil { + fail(w, 503, "passages unavailable") + return + } + respond(w, 200, passages) + }) + mux.HandleFunc("POST /api/dev/boss", func(w http.ResponseWriter, r *http.Request) { + if !h.auth.dev { + fail(w, 404, "not enabled") + return + } + if _, err := h.auth.account(r); err != nil { + fail(w, 401, "sign in required") + return + } + h.s.mu.Lock() + defer h.s.mu.Unlock() + if !h.s.ready.Load() { + fail(w, 503, "world unavailable") + return + } + if err := h.s.world.TriggerBoss(); err != nil { + fail(w, 409, err.Error()) + return + } + if err := h.s.persist(r.Context(), ""); err != nil { + fail(w, 503, "save failed") + return + } + respond(w, 200, map[string]bool{"ok": true}) + }) + mux.HandleFunc("GET /ws", h.socket) + files := http.FileServer(http.Dir(h.assets)) + mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { + clean := filepath.Clean(filepath.FromSlash(r.URL.Path)) + if strings.HasPrefix(r.URL.Path, "/api/") { + fail(w, 404, "not found") + return + } + if r.URL.Path == "/" { + w.Header().Set("Cache-Control", "no-cache") + } + if strings.Contains(clean, ".env") || strings.HasPrefix(r.URL.Path, "/.") { + fail(w, 404, "not found") + return + } + if _, err := os.Stat(filepath.Join(h.assets, strings.TrimPrefix(clean, string(filepath.Separator)))); err != nil { + http.NotFound(w, r) + return + } + files.ServeHTTP(w, r) + }) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("Referrer-Policy", "no-referrer") + w.Header().Set("X-Frame-Options", "DENY") + w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()") + w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'") + if !h.auth.dev { + w.Header().Set("Strict-Transport-Security", "max-age=31536000") + } + if strings.HasPrefix(r.URL.Path, "/api/") || strings.HasPrefix(r.URL.Path, "/auth/") { + w.Header().Set("Cache-Control", "no-store") + if !h.allow(r) { + fail(w, 429, "too many requests") + return + } + } + if r.Method == "POST" && !validOrigin(r, h.auth.base) { + fail(w, 403, "origin rejected") + return + } + mux.ServeHTTP(w, r) + }) +} +func (h *HTTP) socket(w http.ResponseWriter, r *http.Request) { + if !validOrigin(r, h.auth.base) { + fail(w, 403, "origin rejected") + return + } + if !h.allow(r) { + fail(w, 429, "too many connections") + return + } + account, err := h.auth.account(r) + if err != nil { + fail(w, 401, "sign in required") + return + } + h.s.mu.Lock() + if !h.s.ready.Load() { + h.s.mu.Unlock() + fail(w, 503, "world unavailable") + return + } + c := h.s.world.ForAccount(account) + if c == nil { + h.s.mu.Unlock() + fail(w, 403, "create a character first") + return + } + id := c.View.Entity.ID + if h.s.peers[id] != nil { + h.s.mu.Unlock() + fail(w, 409, "character already connected") + return + } + if err = h.s.world.Connect(id); err != nil { + h.s.mu.Unlock() + fail(w, 403, err.Error()) + return + } + conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionDisabled}) + if err != nil { + h.s.world.Disconnect(id) + h.s.mu.Unlock() + return + } + conn.SetReadLimit(1024) + ctx, cancel := context.WithCancel(r.Context()) + peer := &peer{character: id, out: make(chan []byte, 2), known: map[string]bool{}, close: func() { cancel(); _ = conn.CloseNow() }} + h.s.peers[id] = peer + h.s.mu.Unlock() + defer func() { + cancel() + _ = conn.CloseNow() + h.s.mu.Lock() + delete(h.s.peers, id) + h.s.world.Disconnect(id) + h.s.mu.Unlock() + }() + go func() { + for { + select { + case <-ctx.Done(): + return + case data := <-peer.out: + writeCtx, stop := context.WithTimeout(ctx, 3*time.Second) + err := conn.Write(writeCtx, websocket.MessageText, data) + stop() + if err != nil { + peer.close() + return + } + var snap p.Snapshot + if json.Unmarshal(data, &snap) == nil && snap.Self.RemainingSeconds <= 0 { + _ = conn.Close(websocket.StatusPolicyViolation, "daily play limit reached") + peer.close() + return + } + } + } + }() + tokens := float64(40) + last := time.Now() + lastSessionCheck := last + for { + readCtx, stop := context.WithTimeout(ctx, 45*time.Second) + kind, data, err := conn.Read(readCtx) + stop() + if err != nil { + return + } + now := time.Now() + tokens = min(40, tokens+now.Sub(last).Seconds()*30) + last = now + if tokens < 1 { + _ = conn.Close(websocket.StatusPolicyViolation, "input rate exceeded") + return + } + tokens-- + if now.Sub(lastSessionCheck) > time.Minute { + if _, err = h.auth.account(r); err != nil { + return + } + lastSessionCheck = now + } + if kind != websocket.MessageText { + return + } + var intent p.Intent + d := json.NewDecoder(bytes.NewReader(data)) + d.DisallowUnknownFields() + if d.Decode(&intent) != nil { + return + } + var extra any + if d.Decode(&extra) != io.EOF { + return + } + h.s.mu.Lock() + if !h.s.ready.Load() { + h.s.mu.Unlock() + return + } + if err = h.s.world.Intent(id, intent); err != nil { + c.Message = err.Error() + } + h.s.mu.Unlock() + } +} diff --git a/server/internal/transport/http_test.go b/server/internal/transport/http_test.go new file mode 100644 index 0000000..c85c981 --- /dev/null +++ b/server/internal/transport/http_test.go @@ -0,0 +1,139 @@ +package transport + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "aeternalis/server/content" + "aeternalis/server/internal/game" + p "aeternalis/server/internal/protocol" + "aeternalis/server/internal/store" + "github.com/coder/websocket" +) + +func TestHTTPAndSocketSecurity(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + db, err := store.Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "http.db"))) + if err != nil { + t.Fatal(err) + } + defer db.Close() + b, _ := content.Load() + w := game.New("test", 123, time.Now(), b) + lease, _, err := db.Acquire(ctx, w) + if err != nil { + t.Fatal(err) + } + svc := NewService(w, lease) + auth, _ := NewAuth(ctx, db, true, "http://127.0.0.1", "", "", "") + server := httptest.NewServer(NewHTTP(svc, auth, t.TempDir(), nil).Handler()) + defer server.Close() + auth.base = server.URL + go svc.Run(ctx) + defer func() { cancel(); <-svc.done; _ = svc.Stop(context.Background()) }() + request := func(path, origin, body string, cookie *http.Cookie) *http.Response { + t.Helper() + req, _ := http.NewRequest(http.MethodPost, server.URL+path, strings.NewReader(body)) + if origin != "" { + req.Header.Set("Origin", origin) + } + req.Header.Set("Content-Type", "application/json") + if cookie != nil { + req.AddCookie(cookie) + } + response, err := server.Client().Do(req) + if err != nil { + t.Fatal(err) + } + return response + } + for _, origin := range []string{"", "https://evil.example", "null", server.URL + ".evil"} { + r := request("/auth/dev", origin, "{}", nil) + r.Body.Close() + if r.StatusCode != 403 { + t.Fatalf("accepted origin %q", origin) + } + } + r := request("/auth/dev", server.URL, "{}", nil) + cookies := r.Cookies() + r.Body.Close() + if len(cookies) != 1 || !cookies[0].HttpOnly { + t.Fatal("missing HttpOnly session") + } + cookie := cookies[0] + r = request("/api/join", server.URL, `{"name":"Traveler","passage":"","hp":999}`, cookie) + r.Body.Close() + if r.StatusCode != 400 { + t.Fatal("unknown join field accepted") + } + r = request("/api/join", server.URL, `{"name":"Traveler","passage":""}`, cookie) + raw, _ := io.ReadAll(r.Body) + r.Body.Close() + if r.StatusCode != 200 { + t.Fatalf("join %d %s", r.StatusCode, raw) + } + var character p.Character + if err = json.Unmarshal(raw, &character); err != nil { + t.Fatal(err) + } + wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws" + badCtx, stop := context.WithTimeout(ctx, time.Second) + _, response, err := websocket.Dial(badCtx, wsURL, &websocket.DialOptions{HTTPHeader: http.Header{"Origin": []string{"https://evil.example"}, "Cookie": []string{cookie.String()}}}) + stop() + if err == nil || response.StatusCode != 403 { + t.Fatal("cross-origin websocket accepted") + } + socketCtx, stopSocket := context.WithTimeout(ctx, 5*time.Second) + defer stopSocket() + conn, _, err := websocket.Dial(socketCtx, wsURL, &websocket.DialOptions{HTTPHeader: http.Header{"Origin": []string{server.URL}, "Cookie": []string{cookie.String()}}}) + if err != nil { + t.Fatal(err) + } + defer conn.CloseNow() + conn.SetReadLimit(2 << 20) + _, data, err := conn.Read(socketCtx) + if err != nil { + t.Fatal(err) + } + var s p.Snapshot + if err = json.Unmarshal(data, &s); err != nil { + t.Fatal(err) + } + if len(s.Chunks) != 9 { + t.Fatal("missing chunk snapshot") + } + if bytes.Contains(data, []byte(`"account"`)) { + t.Fatal("account identity leaked") + } + intent := p.Intent{Op: "move", Seq: 1, X: 1} + payload, _ := json.Marshal(intent) + if err = conn.Write(socketCtx, websocket.MessageText, payload); err != nil { + t.Fatal(err) + } + if err = conn.Write(socketCtx, websocket.MessageText, []byte(`{"op":"move","seq":2,"x":1,"z":0,"target":"","hp":999}`)); err != nil { + t.Fatal(err) + } + for { + _, _, err = conn.Read(socketCtx) + if err != nil { + break + } + } + if err == nil { + t.Fatal("malformed intent was not disconnected") + } +} +func TestProductionAuthRequiresOIDC(t *testing.T) { + if _, err := NewAuth(context.Background(), nil, false, "http://insecure", "", "", ""); err == nil { + t.Fatal("insecure production auth accepted") + } +} diff --git a/server/internal/transport/service.go b/server/internal/transport/service.go new file mode 100644 index 0000000..78e6091 --- /dev/null +++ b/server/internal/transport/service.go @@ -0,0 +1,149 @@ +package transport + +import ( + "context" + "encoding/json" + "errors" + "log/slog" + "maps" + "sync" + "sync/atomic" + "time" + + "aeternalis/server/internal/game" + p "aeternalis/server/internal/protocol" + "aeternalis/server/internal/store" +) + +type peer struct { + character string + out chan []byte + known map[string]bool + close func() +} +type Service struct { + mu sync.Mutex + world *game.World + lease *store.Lease + peers map[string]*peer + ready atomic.Bool + lastSave time.Time + done chan struct{} +} + +func NewService(w *game.World, l *store.Lease) *Service { + s := &Service{world: w, lease: l, peers: map[string]*peer{}, lastSave: time.Now(), done: make(chan struct{})} + s.ready.Store(true) + return s +} +func (s *Service) persist(ctx context.Context, claim string) error { + err := s.lease.Save(ctx, s.world, claim) + if err != nil { + s.ready.Store(false) + slog.Error("world frozen: persistence failed", "error", err) + for _, p := range s.peers { + p.close() + } + return err + } + s.lastSave = time.Now() + return nil +} +func (s *Service) Run(ctx context.Context) { + defer close(s.done) + ticker := time.NewTicker(time.Second / time.Duration(s.world.Balance.TickHz)) + defer ticker.Stop() + last := time.Now() + for { + select { + case <-ctx.Done(): + return + case now := <-ticker.C: + s.mu.Lock() + if !s.ready.Load() { + s.mu.Unlock() + return + } + s.world.Advance(now, now.Sub(last).Seconds()) + last = now + if s.world.Dirty() || now.Sub(s.lastSave) >= time.Second { + saveCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + err := s.persist(saveCtx, "") + cancel() + if err != nil { + s.mu.Unlock() + return + } + } + if s.world.Tick%int64(s.world.Balance.TickHz/s.world.Balance.SnapshotHz) == 0 { + for id, p := range s.peers { + snapshot := s.world.Snapshot(id, p.known) + data, err := json.Marshal(snapshot) + if err != nil { + slog.Error("snapshot encoding failed", "error", err) + p.close() + continue + } + select { + case p.out <- data: + for key := range p.known { + delete(p.known, key) + } + for _, key := range snapshot.ChunkKeys { + p.known[key] = true + } + default: + p.close() + } + } + } + s.mu.Unlock() + } + } +} +func (s *Service) Stop(ctx context.Context) error { + s.mu.Lock() + defer s.mu.Unlock() + wasReady := s.ready.Swap(false) + for id, p := range s.peers { + s.world.Disconnect(id) + p.close() + } + if !wasReady { + return errors.New("world already frozen; lease will expire") + } + if err := s.lease.Save(ctx, s.world, ""); err != nil { + return err + } + return s.lease.Release(ctx) +} +func (s *Service) join(ctx context.Context, account, name, claim string) (p.Character, error) { + s.mu.Lock() + defer s.mu.Unlock() + if !s.ready.Load() { + return p.Character{}, errors.New("world unavailable") + } + var c *game.Character + var err error + if claim != "" { + c, err = s.lease.DB.ReadPassage(ctx, claim, account) + if err != nil { + return p.Character{}, errors.New("passage unavailable") + } + if err = s.world.Import(c); err != nil { + return p.Character{}, err + } + } else { + c, err = s.world.Join(account, name) + if err != nil { + return p.Character{}, err + } + } + if err = s.persist(ctx, claim); err != nil { + return p.Character{}, errors.New("world persistence unavailable") + } + view := c.View + view.Inventory = maps.Clone(view.Inventory) + view.Skills = maps.Clone(view.Skills) + return view, nil +} diff --git a/tests/game.spec.ts b/tests/game.spec.ts new file mode 100644 index 0000000..a6d6492 --- /dev/null +++ b/tests/game.spec.ts @@ -0,0 +1,88 @@ +import { test, expect } from '@playwright/test'; + +async function enter(page, name = 'Wayfarer') { + await page.goto('/'); + await expect(page.locator('#connection-status')).toHaveText('World online'); + await page.getByLabel('Character name').fill(name); + await page.getByRole('button', { name: 'Enter world' }).click(); + await expect(page.locator('#connection-status')).toHaveText('Connected'); + await expect(page.locator('#game-controls')).toBeVisible(); + await expect.poll(() => page.evaluate(() => (window as any).__aeternalis?.diagnostics().chunks)).toBe(9); +} + +test('desktop renders models, moves authoritatively, gathers, and reconnects', async ({ page }) => { + const errors: string[] = []; + page.on('pageerror', error => errors.push(error.message)); + await page.setViewportSize({ width: 1440, height: 900 }); + await enter(page); + const before = await page.evaluate(() => (window as any).__aeternalis.snapshot.self.entity.position); + await page.keyboard.down('d'); await page.waitForTimeout(1000); await page.keyboard.up('d'); + await expect.poll(() => page.evaluate(() => (window as any).__aeternalis.snapshot.self.entity.position.x)).toBeGreaterThan(before.x + 3); + await page.getByRole('button', { name: 'Gather', exact: true }).click(); + await expect.poll(() => page.evaluate(() => Object.values((window as any).__aeternalis.snapshot.self.skills).reduce((sum: number, n: any) => sum + n, 0)), { timeout: 15000 }).toBeGreaterThan(0); + await page.getByRole('button', { name: 'Inventory and crafting' }).click(); + await expect(page.locator('#inventory')).toBeVisible(); + await expect(page.locator('#inventory-items')).toContainText('Knife'); + await page.getByRole('button', { name: 'Close inventory', exact: true }).click(); + const id = await page.evaluate(() => (window as any).__aeternalis.snapshot.self.entity.id); + await page.screenshot({ path: 'test-results/desktop.png' }); + const pixels = await page.evaluate(async () => { + const canvas = document.getElementById('world') as HTMLCanvasElement; + // Read in the animation frame immediately after rendering; avoid a cleared backbuffer. + return new Promise(resolve => requestAnimationFrame(() => { + const gl = canvas.getContext('webgl2')!; + const data = new Uint8Array(64 * 64 * 4); + gl.readPixels(Math.floor(canvas.width / 2) - 32, Math.floor(canvas.height / 2) - 32, 64, 64, gl.RGBA, gl.UNSIGNED_BYTE, data); + const colors = new Set(); for (let i = 0; i < data.length; i += 4) colors.add(`${data[i]},${data[i+1]},${data[i+2]}`); + resolve(colors.size); + })); + }); + expect(pixels).toBeGreaterThan(8); + const diagnostics = await page.evaluate(() => (window as any).__aeternalis.diagnostics()); + expect(diagnostics.models).toBe(6); expect(diagnostics.frames).toBeGreaterThan(10); expect(diagnostics.triangles).toBeGreaterThan(1000); + await page.reload(); + await expect(page.locator('#connection-status')).toHaveText('Connected'); + await expect.poll(() => page.evaluate(() => (window as any).__aeternalis?.snapshot?.self.entity.id)).toBe(id); + expect(errors).toEqual([]); +}); + +test('mobile controls fit and move the character', async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + await enter(page, 'Mobile'); + await expect(page.getByRole('button', { name: 'Move north' })).toBeVisible(); + const before = await page.evaluate(() => (window as any).__aeternalis.snapshot.self.entity.position.z); + const button = page.getByRole('button', { name: 'Move north' }); + await button.dispatchEvent('pointerdown', { pointerId: 1 }); await page.waitForTimeout(650); await button.dispatchEvent('pointerup', { pointerId: 1 }); + await expect.poll(() => page.evaluate(() => (window as any).__aeternalis.snapshot.self.entity.position.z)).toBeLessThan(before - 2); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); + await page.getByRole('button', { name: 'Inventory and crafting' }).click(); + const box = await page.locator('#inventory').boundingBox(); + expect(box!.x).toBeGreaterThanOrEqual(0); expect(box!.x + box!.width).toBeLessThanOrEqual(390); + await page.screenshot({ path: 'test-results/mobile.png' }); + await page.getByRole('button', { name: 'Close inventory', exact: true }).click(); + await page.setViewportSize({ width: 844, height: 390 }); + await page.screenshot({ path: 'test-results/mobile-landscape.png' }); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); +}); + +test('unauthenticated API and hostile origins cannot mutate state', async ({ request }) => { + expect((await request.post('/api/join', { data: { name: 'Intruder' }, headers: { Origin: 'https://evil.example' } })).status()).toBe(403); + expect((await request.get('/api/me')).status()).toBe(401); + const response = await request.get('/api/config'); + expect(response.headers()['content-security-policy']).toContain("frame-ancestors 'none'"); + expect(response.headers()['x-content-type-options']).toBe('nosniff'); +}); + +test('boss event is visible and accepts server-authoritative combat', async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 900 }); + await enter(page, 'Boss witness'); + await page.getByRole('button', { name: 'Display settings' }).click(); + await page.getByRole('button', { name: 'Awaken Harbinger' }).click(); + await expect(page.locator('#phase-label')).toHaveText('THE UNRAVELING'); + await page.getByRole('button', { name: 'Close display settings' }).click(); + const hp = await page.evaluate(() => (window as any).__aeternalis.snapshot.world.bossHp); + await page.getByRole('button', { name: 'Target Harbinger', exact: true }).click(); + await expect.poll(() => page.evaluate(() => (window as any).__aeternalis.snapshot.world.bossHp), { timeout: 15000 }).toBeLessThan(hp); + await expect(page.locator('#boss-bar')).toBeVisible(); + await page.screenshot({ path: 'test-results/boss.png' }); +}); diff --git a/tools/bootstrap-go.ps1 b/tools/bootstrap-go.ps1 new file mode 100644 index 0000000..482435b --- /dev/null +++ b/tools/bootstrap-go.ps1 @@ -0,0 +1,12 @@ +$ErrorActionPreference = 'Stop' +$toolsDir = Join-Path $PSScriptRoot '..\.tools' +New-Item -ItemType Directory -Force -Path $toolsDir | Out-Null +$releases = Invoke-RestMethod 'https://go.dev/dl/?mode=json' +$release = $releases | Where-Object stable | Select-Object -First 1 +$archive = $release.files | Where-Object { $_.os -eq 'windows' -and $_.arch -eq 'amd64' -and $_.kind -eq 'archive' } | Select-Object -First 1 +if (-not $archive) { throw 'No stable Windows Go archive found.' } +$destination = Join-Path $toolsDir $archive.filename +Invoke-WebRequest ('https://go.dev/dl/' + $archive.filename) -OutFile $destination +if ((Get-FileHash $destination -Algorithm SHA256).Hash.ToLowerInvariant() -ne $archive.sha256) { throw 'Go checksum mismatch.' } +Expand-Archive -LiteralPath $destination -DestinationPath $toolsDir -Force +& (Join-Path $toolsDir 'go\bin\go.exe') version diff --git a/tools/bootstrap-helm.ps1 b/tools/bootstrap-helm.ps1 new file mode 100644 index 0000000..fe6f6e4 --- /dev/null +++ b/tools/bootstrap-helm.ps1 @@ -0,0 +1,13 @@ +$ErrorActionPreference = 'Stop' +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$toolsDir = Join-Path $PSScriptRoot '..\.tools' +New-Item -ItemType Directory -Force -Path $toolsDir | Out-Null +$name = 'helm-v3.18.6-windows-amd64.zip' +$destination = Join-Path $toolsDir $name +$checksumResponse = (Invoke-WebRequest ('https://get.helm.sh/' + $name + '.sha256sum') -UseBasicParsing).Content +$checksumText = if ($checksumResponse -is [byte[]]) { [Text.Encoding]::ASCII.GetString($checksumResponse) } else { [string]$checksumResponse } +$expected = ($checksumText.Trim() -split '\s+')[0] +Invoke-WebRequest ('https://get.helm.sh/' + $name) -UseBasicParsing -OutFile $destination +if ((Get-FileHash $destination -Algorithm SHA256).Hash.ToLowerInvariant() -ne $expected) { throw 'Helm checksum mismatch.' } +Expand-Archive -LiteralPath $destination -DestinationPath $toolsDir -Force +& (Join-Path $toolsDir 'windows-amd64\helm.exe') version --short diff --git a/tools/copy-to-aeternalis.ps1 b/tools/copy-to-aeternalis.ps1 new file mode 100644 index 0000000..c56b867 --- /dev/null +++ b/tools/copy-to-aeternalis.ps1 @@ -0,0 +1,36 @@ +$ErrorActionPreference = 'Stop' +$source = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')).TrimEnd('\') +$target = 'C:\Dev\aeternalis' +if ($source -ne 'C:\Dev\RPGTheory\aeternalis-build') { throw 'Unexpected source workspace.' } +if (-not (Test-Path -LiteralPath (Join-Path $target 'planning\VISION.md'))) { throw 'Original target planning document not found.' } +$visionHash = (Get-FileHash -LiteralPath (Join-Path $target 'planning\VISION.md') -Algorithm SHA256).Hash +$excluded = @('.git', '.tools', '.local', 'node_modules', 'test-results', 'playwright-report') +$copied = 0 +foreach ($entry in Get-ChildItem -Force -LiteralPath $source) { + if ($entry.Name -in $excluded) { continue } + if ($entry.PSIsContainer) { + foreach ($file in Get-ChildItem -File -Recurse -Force -LiteralPath $entry.FullName) { + $relative = $file.FullName.Substring($source.Length + 1) + if ($relative -eq 'planning\VISION.md') { continue } + $destination = [IO.Path]::GetFullPath((Join-Path $target $relative)) + if (-not $destination.StartsWith($target + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'Copy escaped destination.' } + New-Item -ItemType Directory -Force -Path (Split-Path -Parent $destination) | Out-Null + Copy-Item -LiteralPath $file.FullName -Destination $destination -Force + if ((Get-FileHash -LiteralPath $destination -Algorithm SHA256).Hash -ne (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash) { throw "Copy mismatch: $relative" } + $copied++ + } + } else { + Copy-Item -LiteralPath $entry.FullName -Destination (Join-Path $target $entry.Name) -Force + $copied++ + } +} +if ((Get-FileHash -LiteralPath (Join-Path $target 'planning\VISION.md') -Algorithm SHA256).Hash -ne $visionHash) { throw 'Original vision changed unexpectedly.' } +$binary = Join-Path $source '.local\world-001.exe' +if (Test-Path -LiteralPath $binary) { + New-Item -ItemType Directory -Force -Path (Join-Path $target '.local') | Out-Null + $binaryDestination = Join-Path $target '.local\world-001.exe' + Copy-Item -LiteralPath $binary -Destination $binaryDestination -Force + if ((Get-FileHash -LiteralPath $binaryDestination -Algorithm SHA256).Hash -ne (Get-FileHash -LiteralPath $binary -Algorithm SHA256).Hash) { throw 'Server binary copy mismatch.' } + $copied++ +} +Write-Output "Copied $copied files into $target. Original vision and .git preserved." diff --git a/tools/create-models.py b/tools/create-models.py new file mode 100644 index 0000000..86fe865 --- /dev/null +++ b/tools/create-models.py @@ -0,0 +1,119 @@ +"""Rebuild original placeholder meshes: blender --background --python tools/create-models.py.""" +import bpy +import math +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +OUT = ROOT / "client" / "public" / "models" +OUT.mkdir(parents=True, exist_ok=True) + +def material(name, color, metallic=0): + mat = bpy.data.materials.new(name) + mat.diffuse_color = (*color, 1) + mat.use_nodes = True + node = mat.node_tree.nodes.get("Principled BSDF") + node.inputs["Base Color"].default_value = (*color, 1) + node.inputs["Roughness"].default_value = 0.85 + node.inputs["Metallic"].default_value = metallic + return mat + +pine = material("pine needles", (0.15, 0.34, 0.25)) +tips = material("fresh needles", (0.28, 0.48, 0.3)) +bark = material("bark", (0.24, 0.22, 0.2)) +rock = material("stone", (0.42, 0.47, 0.48)) +iron = material("iron", (0.23, 0.29, 0.3), 0.4) +cloth = material("traveler green", (0.24, 0.45, 0.41)) +linen = material("linen", (0.73, 0.76, 0.71)) +skin = material("skin", (0.7, 0.49, 0.34)) +ember = material("ember", (0.88, 0.16, 0.16)) +leaf = material("sage", (0.41, 0.64, 0.3)) +flower = material("flowers", (0.89, 0.75, 0.29)) + +def clear(): + bpy.ops.object.select_all(action="SELECT") + bpy.ops.object.delete(use_global=False) + +def cone(name, pos, radius, depth, mat, top=0, vertices=7): + bpy.ops.mesh.primitive_cone_add(vertices=vertices, radius1=radius, radius2=top, depth=depth, location=pos) + obj = bpy.context.object + obj.name = name + obj.data.materials.append(mat) + return obj + +def cube(name, pos, scale, mat): + bpy.ops.mesh.primitive_cube_add(size=1, location=pos) + obj = bpy.context.object + obj.name = name + obj.scale = scale + obj.data.materials.append(mat) + bevel = obj.modifiers.new("worn edges", "BEVEL") + bevel.width = 0.09 + bevel.segments = 1 + bpy.ops.object.transform_apply(location=False, rotation=False, scale=True) + return obj + +def ico(name, pos, scale, mat): + bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=1, radius=1, location=pos) + obj = bpy.context.object + obj.name = name + obj.scale = scale + obj.data.materials.append(mat) + return obj + +def export(name): + bpy.ops.export_scene.gltf(filepath=str(OUT / (name + ".glb")), export_format="GLB", export_yup=True) + +clear() +cone("trunk", (0,0,3.7), 0.6, 7.4, bark, 0.22) +for z,r in [(5,3.8),(7.5,3),(9.5,2.2)]: + cone("canopy", (0,0,z), r, 5.2, pine if z<9 else tips) +export("tree") + +clear() +ico("boulder", (0,0,1), (2.3,1.7,1.5), rock) +for x,y in [(-0.8,0.3),(0.6,-0.7),(1,0.6)]: + cone("iron vein", (x,y,1.7), 0.35, 1.8, iron, 0.1, 5) +export("ore") + +clear() +for i in range(6): + a = i*math.tau/6 + x,y = math.cos(a)*0.6,math.sin(a)*0.6 + cone("stem",(x,y,0.6),0.09,1.2,leaf,0.04,5) + ico("leaf",(x,y,0.9),(0.6,0.3,0.2),leaf) + ico("flower",(x,y,1.4),(0.3,0.3,0.25),flower) +export("herb") + +def humanoid(boss=False): + body_mat = iron if boss else cloth + cube("torso", (0,0,1.7), (0.9,0.5,1.1), body_mat) + cube("belt", (0,0,1.22), (1,0.6,0.2), bark) + ico("head", (0,0,2.55), (0.37,0.34,0.43), rock if boss else skin) + cone("hood", (0,0.05,2.83), 0.46, 0.5, body_mat, 0.18) + for sign in [-1,1]: + cube("leg", (sign*0.24,0,0.65), (0.32,0.34,1.2), iron if boss else linen) + cube("boot", (sign*0.24,-0.12,0.15), (0.37,0.58,0.3), bark) + cube("arm", (sign*0.64,0,1.67), (0.3,0.35,1), body_mat) + ico("hand", (sign*0.64,0,1.03), (0.18,0.18,0.2), rock if boss else skin) + if boss: + for sign in [-1,1]: + horn=cone("crown", (sign*0.4,0,3.2),0.2,1.2,ember,0,5) + horn.rotation_euler[1] = sign*0.4 + cube("heart", (0,-0.28,1.9), (0.3,0.12,0.5),ember) + else: + cube("pack", (0,0.38,1.8), (0.72,0.4,0.85),bark) + cone("knife", (0.7,-0.05,0.75),0.13,0.6,iron,0,4) + +clear() +humanoid() +export("player") +clear() +humanoid(True) +export("sentinel") +clear() +humanoid(True) +for obj in bpy.context.scene.objects: + obj.location *= 4 + obj.scale *= 4 +export("boss") +bpy.ops.wm.save_as_mainfile(filepath=str(ROOT / "assets" / "harbinger.blend")) diff --git a/tools/dev-server.mjs b/tools/dev-server.mjs new file mode 100644 index 0000000..af64481 --- /dev/null +++ b/tools/dev-server.mjs @@ -0,0 +1,23 @@ +import { existsSync, mkdirSync } from 'node:fs'; +import { spawn, spawnSync } from 'node:child_process'; +import { resolve } from 'node:path'; + +const localGo = resolve('.tools/go/bin/go.exe'); +const go = process.env.GO_EXE || (existsSync(localGo) ? localGo : 'go'); +mkdirSync('.local', { recursive: true }); +const executable = resolve(`.local/world${process.platform === 'win32' ? '.exe' : ''}`); +const environment = { ...process.env, GOCACHE: resolve('.local/go-cache') }; +const result = spawnSync(go, ['build', '-o', executable, './cmd/world'], { cwd: resolve('server'), env: environment, stdio: 'inherit' }); +if (result.status !== 0) process.exit(result.status || 1); +const port = process.env.PORT || '18080'; +const child = spawn(executable, [], { + cwd: resolve('server'), stdio: 'inherit', + env: { + ...environment, APP_ENV: 'development', LISTEN_ADDR: `127.0.0.1:${port}`, + PUBLIC_URL: process.env.PUBLIC_URL || `http://127.0.0.1:${port}`, CLIENT_DIR: resolve('client/dist'), + DATABASE_URL: process.env.DATABASE_URL || `file:${resolve('.local', process.env.E2E ? `e2e-${Date.now()}.db` : 'aeternalis.db')}`, + WORLD_ID: process.env.WORLD_ID || 'world-001', + }, +}); +for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { child.kill('SIGTERM'); }); +child.on('exit', code => process.exit(code || 0)); diff --git a/tools/generate-protocol.mjs b/tools/generate-protocol.mjs new file mode 100644 index 0000000..21ffcbd --- /dev/null +++ b/tools/generate-protocol.mjs @@ -0,0 +1,22 @@ +import { readFile, writeFile, mkdir } from 'node:fs/promises'; +import { quicktype, InputData, JSONSchemaInput, FetchingJSONSchemaStore } from 'quicktype-core'; + +const schema = await readFile(new URL('../schemas/protocol.json', import.meta.url), 'utf8'); +const input = new JSONSchemaInput(new FetchingJSONSchemaStore()); +await input.addSource({ name: 'Protocol', schema }); +const inputData = new InputData(); +inputData.addInput(input); +for (const [lang, path, rendererOptions] of [ + ['go', '../server/internal/protocol/generated.go', { package: 'protocol', 'just-types': 'true' }], + ['typescript', '../client/src/generated.ts', { 'just-types': 'true' }], +]) { + const result = await quicktype({ inputData, lang, rendererOptions, alphabetizeProperties: true }); + const output = '// Code generated from schemas/protocol.json. DO NOT EDIT.\n' + (lang === 'go' ? 'package protocol\n\n' : '') + result.lines.join('\n').trimEnd() + '\n'; + const url = new URL(path, import.meta.url); + if (process.argv.includes('--check')) { + if (await readFile(url, 'utf8') !== output) throw new Error(`Stale generated contract: ${path}`); + } else { + await mkdir(new URL('.', url), { recursive: true }); + await writeFile(url, output); + } +} diff --git a/tools/promote-gitops.mjs b/tools/promote-gitops.mjs new file mode 100644 index 0000000..415a9f0 --- /dev/null +++ b/tools/promote-gitops.mjs @@ -0,0 +1,34 @@ +import { spawnSync } from 'node:child_process'; +import { mkdir, readFile, writeFile } from 'node:fs/promises'; +import { resolve, relative, isAbsolute } from 'node:path'; +import YAML from 'yaml'; + +const env = process.env; +for (const key of ['GITOPS_REPOSITORY', 'GITOPS_USERNAME', 'GITOPS_TOKEN', 'IMAGE_REPOSITORY', 'IMAGE_DIGEST']) if (!env[key]) throw new Error(`Missing ${key}`); +if (!/^sha256:[a-f0-9]{64}$/.test(env.IMAGE_DIGEST)) throw new Error('Invalid image digest'); +const repository = new URL(env.GITOPS_REPOSITORY); +if (repository.protocol !== 'https:' || repository.username || repository.password) throw new Error('GITOPS_REPOSITORY must be HTTPS without credentials'); +const root = resolve('.local/gitops'); +const askpass = resolve('.local/git-askpass.cjs'); +await mkdir(resolve('.local'), { recursive: true }); +await writeFile(askpass, '#!/usr/bin/env node\nprocess.stdout.write(process.argv[2].toLowerCase().includes("username") ? process.env.GITOPS_USERNAME : process.env.GITOPS_TOKEN);\n', { mode: 0o700 }); +function git(args, cwd = process.cwd()) { + const result = spawnSync('git', args, { cwd, env: { ...env, GIT_ASKPASS: askpass, GIT_TERMINAL_PROMPT: '0' }, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); + if (result.status !== 0) throw new Error(`Git operation failed (${args[0]}): ${result.stderr.replaceAll(env.GITOPS_TOKEN, '[redacted]')}`); + return result.stdout; +} +git(['clone', '--branch', env.GITOPS_BRANCH || 'main', '--depth', '1', '--', repository.href, root]); +const file = resolve(root, env.GITOPS_VALUES_FILE || 'apps/aeternalis/values.yaml'); +const local = relative(root, file); +if (local.startsWith('..') || isAbsolute(local) || !/\.ya?ml$/.test(local)) throw new Error('Values file must stay inside the GitOps checkout'); +const document = YAML.parseDocument(await readFile(file, 'utf8')); +document.setIn(['image', 'repository'], env.IMAGE_REPOSITORY); +document.setIn(['image', 'digest'], env.IMAGE_DIGEST); +await writeFile(file, document.toString()); +git(['config', 'user.name', 'Aeternalis CI'], root); +git(['config', 'user.email', 'aeternalis-ci@localhost'], root); +git(['add', '--', local], root); +if (git(['diff', '--cached', '--name-only'], root).trim()) { + git(['commit', '-m', `Deploy Aeternalis ${env.IMAGE_DIGEST.slice(0,19)}`], root); + git(['push', 'origin', `HEAD:${env.GITOPS_BRANCH || 'main'}`], root); +} diff --git a/tools/start-local.ps1 b/tools/start-local.ps1 new file mode 100644 index 0000000..dd669d9 --- /dev/null +++ b/tools/start-local.ps1 @@ -0,0 +1,26 @@ +param([int]$Port = 18080, [string]$WorldId = 'world-001', [int]$Seed = 734291, [switch]$UseExisting) +$ErrorActionPreference = 'Stop' +$root = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +if ($WorldId -notmatch '^[a-z][a-z0-9-]{0,30}$') { throw 'Invalid world ID.' } +if (-not (Test-Path -LiteralPath (Join-Path $root 'client\dist\index.html'))) { throw 'Run npm ci and npm run build first.' } +$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, $Port) +try { $listener.Start() } finally { $listener.Stop() } +New-Item -ItemType Directory -Force -Path (Join-Path $root '.local') | Out-Null +$exe = Join-Path $root ".local\$WorldId.exe" +$env:GOCACHE = Join-Path $root '.local\go-cache' +if (-not $UseExisting) { + $go = Join-Path $root '.tools\go\bin\go.exe' + if (-not (Test-Path -LiteralPath $go)) { $go = (Get-Command go -ErrorAction Stop).Source } + Push-Location (Join-Path $root 'server') + try { & $go build -o $exe ./cmd/world; if ($LASTEXITCODE -ne 0) { throw 'Go build failed.' } } finally { Pop-Location } +} +if (-not (Test-Path -LiteralPath $exe)) { throw "Missing server binary: $exe" } +$env:APP_ENV = 'development' +$env:LISTEN_ADDR = "127.0.0.1:$Port" +$env:PUBLIC_URL = "http://127.0.0.1:$Port" +$env:CLIENT_DIR = Join-Path $root 'client\dist' +$env:DATABASE_URL = 'file:' + ((Join-Path $root '.local\aeternalis.db') -replace '\\','/') +$env:WORLD_ID = $WorldId +$env:WORLD_SEED = "$Seed" +$process = Start-Process -FilePath $exe -WorkingDirectory (Join-Path $root 'server') -WindowStyle Hidden -PassThru -RedirectStandardOutput (Join-Path $root ".local\$WorldId.stdout.log") -RedirectStandardError (Join-Path $root ".local\$WorldId.stderr.log") +Write-Output "World ${WorldId}: http://127.0.0.1:$Port (PID $($process.Id))"