diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8efca279b..79917e1aa 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,6 +10,7 @@ concurrency: cancel-in-progress: true jobs: build: + timeout-minutes: 5 env: POLYWORLD_DEPS: ${{ github.workspace }}/.. strategy: @@ -20,50 +21,14 @@ jobs: steps: - uses: actions/checkout@v5 - uses: treeform/setup-nim-action@v6 - - name: Install native HTTP library on Windows - if: runner.os == 'Windows' - shell: pwsh - run: | - vcpkg install curl:x64-windows - "$env:VCPKG_INSTALLATION_ROOT/installed/x64-windows/bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append - name: Install dependencies shell: bash run: | cd .. nimby create nimby sync "${{ github.event.repository.name }}/nimby.lock" - - name: Build relay without game sources - run: python tests/test_server_boundary.py - - name: Run release tests and all-game determinism - run: nim r -d:release -d:audioTest -d:bassyNativeStrict -d:replayEvents tests/all.nim - - name: Test Cards and Casters - run: nim r -d:release -d:audioTest -d:bassyNativeStrict games/cac/tests/tests.nim - - name: Test display settings - run: nim r -d:release tests/test_displays.nim - - name: Test lockstep training API - run: nim r -d:release -d:headless -d:bassyNativeStrict games/gods_of_the_arena/tests/test_lockstep.nim - - name: Test presentation audio without an output device - shell: bash - run: | - nim r -d:release -d:audioTest tests/test_sound_startup.nim - nim r -d:release -d:audioTest -d:nimAllocStats tests/test_sounds.nim - nim r -d:release -d:audioTest -d:nimAllocStats games/gods_of_the_arena/tests/test_audio.nim - nim r -d:release -d:audioTest -d:nimAllocStats games/light_vs_dark/tests/test_battle_sounds.nim - - name: Test browser launch arguments - run: | - node tests/test_webinputs.js - node tests/test_replay_audio.js - - name: Test Voice Lab browser transport and local server - run: | - node experiments/voice/tests/test_browser_transport.mjs - nim r experiments/voice/tests/test_web_server.nim - - name: Test Voice Lab signing selection - if: runner.os != 'Windows' - run: nim r experiments/voice/tests/test_signings.nim - - name: Test browser relay protocol + - name: Check and run unit tests shell: bash run: | - nim c -r --hints:off --nimcache:"$RUNNER_TEMP/room-wire-cache" -o:"$RUNNER_TEMP/room-wire-fixture" tests/room_protocol_fixture.nim > "$RUNNER_TEMP/room-wire.json" - node tests/test_room_protocol.cjs "$RUNNER_TEMP/room-wire.json" - - name: Check neural converters - run: python games/gods_of_the_arena/tests/test_neural_converters.py + nim check -d:release tests/unit_tests.nim + nim r -d:release tests/unit_tests.nim diff --git a/docs/command-line.md b/docs/command-line.md new file mode 100644 index 000000000..5819b9434 --- /dev/null +++ b/docs/command-line.md @@ -0,0 +1,108 @@ +# Game command lines + +Polyworld games share one parser for options that have the same meaning. +Run a game's `--help` for its supported options and game-specific setup. +An unsupported option produces an error rather than being silently ignored. + +All valued options accept the same three forms: + +```sh +./game --replay "replays/my match.replay" +./game --replay="replays/my match.replay" +./game --replay:"replays/my match.replay" +``` + +Paths are relative to the directory where the game was launched, including +clients that change their working directory to find assets. Quote paths or +names containing spaces. Repeated scalar options use their last value; +`--player` may appear only once and bot options accumulate. + +| Option | Shared meaning | +| --- | --- | +| `--record PATH` | Save the current match's replay to this file, creating missing parent directories. | +| `--replay PATH` | Load and play this recording instead of running bots. | +| `--bot PATH[:N]` | Add N instances of a bot program, defaulting to one. Repeat to use different programs. | +| `--bots PATH[:N]` | Identical alias of `--bot`, including repetition and counts. | +| `--player [N]` | Reserve one human-controlled slot, numbered from one. Bare `--player` selects slot one. | +| `--name TEXT` | Set the local human's display name, or the multiplayer identity where supported. | +| `--seed N` | Set the new match's signed 32-bit random seed. | +| `--ticks N` | Set the new match's maximum simulation ticks. | +| `--seconds N`, `--minutes N` | Set the new match's duration using that game's simulation tick rate. | +| `--play [BOOL]` | Start local simulation or replay playback playing or paused; default true. | +| `--speed N` | Use this positive integer local simulation or playback multiplier; default one. | +| `--windowSize WIDTHxHEIGHT` | Set the graphical window dimensions. | +| `--vsync [BOOL]` | Enable or disable display synchronization; default true. | +| `--mute [BOOL]` | Override saved audio settings for this launch; bare `--mute` disables sound. | +| `--unmute [BOOL]` | Enable launch audio; false mutes it. This does not enable microphone input. | +| `--verbose [BOOL]` | Enable diagnostic output; default false. | +| `--headless-tick-rate N` | Pace headless simulation at N ticks per wall-clock second; zero is unlimited. | +| `--llm-mode async\|barrier` | Advance asynchronously or wait for the current batch of bot LLM requests, where supported. | +| `--server URL` | Select the multiplayer relay. | +| `--room CODE` | Select a multiplayer room. `--join CODE` is an identical alias. | +| `--screenshot PATH` | Capture one native rendered frame, save it, and exit. | +| `--frames N` | Select the screenshot's rendered frame, defaulting to 30. | + +Booleans accept `true/false`, `on/off`, `yes/no`, and `1/0`. Explicit command-line +choices take precedence over saved window and audio preferences. + +## Bots and human slots + +An explicit bot roster fills every nonhuman slot exactly. Bot programs expand +in argument order and skip the reserved human slot. There is no implicit cycling +or padding of an explicitly supplied roster. Games can offer bundled bots when +no bot programs are specified, and their fixed or configurable roster sizes +remain game-specific. + +For a four-player game, these commands select the same roster: + +```sh +./game --player 2 --bot players/base.bas:3 +./game --player=2 --bots=players/base.bas:3 +./game --player:2 --bot:players/base.bas:3 +``` + +Two different programs can fill the three bot slots: + +```sh +./game --player 2 --name "Local player" \ + --bot players/first.bas --bot players/second.bas:2 +``` + +Use `--name` for a display name. `--player Alice` is an error. A headless build +cannot host a human controller. + +## Recording and playback + +`--record` selects a destination. In a client that opens a menu, the choice +persists into the match started from that menu; the flag alone does not select +a game setup. `--bot`, `--player`, or a game's explicit start option can launch +a configured match directly. Explicit replay files remain separate from optional +automatic desktop replay-library saving. + +`--replay` cannot be combined with bots, a human controller, recording, an +explicit seed, or explicit duration flags. A replay carries its original setup; +game-specific seek options control which recorded position to display. Replay +format/version validation is unchanged, with no conversion of older recordings. + +Local playback speed does not change simulation rules or a multiplayer server's +tick rate. A live network controller follows the authoritative match clock. +Games report when that prevents a requested pause or playback speed. GotA's +draft remains interactive before its battle simulation starts; `--play=false` +pauses the battle when the draft finishes. + +## Game-specific capabilities + +GotA, Light vs Dark, Cards and Casters, Call to Adventure, Heartleaf, Crewrift, +Galcon, Pudge Wars, Generals, and Mini Diplomacy use the shared replay and bot +vocabulary where their clients support those capabilities. Monster has no BASIC +roster or action-replay implementation and rejects those options. Its microphone +conversation mode is selected explicitly with `--conversation`. + +Map generation, heroes, decks, tutorials, roles, calendar dates, and coaching +controls remain game-specific. Turn-based clients need not support a duration +in seconds. Graphical transport and window flags require a graphical build; +LLM barrier mode requires a client that implements LLM requests. + +See [screenshot capture](screenshots.md) for capture behavior and +[testing](testing.md) for the unit-only CI policy. Parser, roster, and path +regressions are unit tests; CI does not open windows or simulate full games. diff --git a/docs/crewrift.md b/docs/crewrift.md index 47ab69a0f..78bd60e59 100644 --- a/docs/crewrift.md +++ b/docs/crewrift.md @@ -4,16 +4,17 @@ Run from the Polyworld repository root, with the usual dependencies and sibling `polyworld_art` checkout: ```sh -nim r games/crewrift/crewrift.nim +nim r games/crewrift/crewrift.nim --player ``` -The default match has eight players, with one human and seven local Bassy BASIC -bots. Roles are random. To choose a role or watch the bots: +The default match has eight local Bassy BASIC bots. `--player` reserves slot one +for a human, and `--player N` selects another one-based slot. Roles are random. +To choose a role or watch the bots: ```sh -nim r games/crewrift/crewrift.nim --role:imp -nim r games/crewrift/crewrift.nim --role:crew -nim r games/crewrift/crewrift.nim --spectate --seed:17 +nim r games/crewrift/crewrift.nim --player --role imp +nim r games/crewrift/crewrift.nim --player --role crew +nim r games/crewrift/crewrift.nim --seed 17 ``` | Control | Action | @@ -52,8 +53,12 @@ and remaining task count, imposter kill count, or dead status. Scroll to see mor crew. Click a visible living crew member's portrait to follow them. The top-left **Room names** button shows or hides the large white room labels. Room labels start visible and retain their setting while seeking or looping. -Use `--name:"Andre von Houck"` to name your human-controlled slot. Local bots -are labeled `base.bas`, or the filename supplied with `--bot PATH[:N]`. See the +Use `--player --name "Andre von Houck"` to name your human-controlled slot. +`--name` requires `--player`; bot identities come from their program files. +Local bots are labeled `base.bas`, or the filename supplied with the repeatable +`--bot PATH[:N]` option (`--bots` has the same meaning). Supplied groups must +fill every non-human slot in order. If no bot option is supplied, those slots +use the bundled program. See the [BASIC bot guide](../games/crewrift/docs/bots.md) for custom policies and the host API. New replays retain the names for each slot. Older recordings without identities show `Unknown`. @@ -124,18 +129,38 @@ faces, and boxes fully enclosed by solid meshes before auditing the ship. Input recordings can be viewed graphically or verified without graphics: ```sh -nim r games/crewrift/crewrift.nim --record:tmp/crewrift.json -nim r games/crewrift/crewrift.nim --replay:tmp/crewrift.json -nim r -d:headless games/crewrift/crewrift.nim --record:tmp/crewrift.json -nim r -d:headless games/crewrift/crewrift.nim --replay:tmp/crewrift.json +nim r games/crewrift/crewrift.nim --player --record tmp/crewrift.json +nim r games/crewrift/crewrift.nim --replay tmp/crewrift.json +nim r -d:headless games/crewrift/crewrift.nim --record tmp/crewrift.json +nim r -d:headless games/crewrift/crewrift.nim --replay tmp/crewrift.json nim r -d:headless games/crewrift/tests/test_sim.nim ``` -`--players:8` through `--players:16` set the roster. `--ticks:N` bounds active -simulation ticks. `--windowSize:1440x900` changes the window. `--screenshot:PATH` -captures a frame and exits. `--capture-ticks:N` selects the simulation tick to -capture. Replays store input buttons, votes, and chat with a fingerprint for -every tick. Playback reports the first mismatch. +`--players 8` through `--players 16` set the roster. `--ticks N` bounds active +simulation ticks; `--seconds N` and `--minutes N` express the same limit in +time. `--play false` starts the viewer paused, `--speed N` selects its playback +speed, and `--vsync off` disables display synchronization. Headless runs accept +`--headless-tick-rate N` for wall-clock pacing; zero runs without waiting. +Graphical builds reject this headless-only pacing option. +Replay playback cannot be combined with bots, a human player, or recording. +Explicit `--seed N` values are deterministic signed 32-bit integers, including +negative values and `-1`. The exact seed is retained in recordings and rewinds. +Crewrift has no network-room or LLM request interface, so those options are +rejected. All value flags accept space, `=`, or `:` separators. + +Screenshot capture uses the shared native arguments: + +```sh +nim r games/crewrift/crewrift.nim --screenshot output/crewrift.png --frames 30 --windowSize 1280x720 +``` + +The same flags accept space, `=`, or `:` separators. Capture uses a hidden, +muted window, writes the PNG after 30 rendered frames by default, and exits. +Parent output folders are created automatically. No special build is needed; +headless and browser builds cannot capture native screenshots. +`--capture-ticks:N` optionally advances N simulation ticks before the capture +frames; its default is zero. Replays store input buttons, votes, and chat with +a fingerprint for every tick. Playback reports the first mismatch. This example is a local playable port. The original Bitworld websocket server, league clients, pixel renderer, and `.bitreplay` format are not connected to it. diff --git a/docs/mailboxes.md b/docs/mailboxes.md index 4f5ae3824..ddba99bc7 100644 --- a/docs/mailboxes.md +++ b/docs/mailboxes.md @@ -4,7 +4,8 @@ Each player has one inbox with 100 message slots. A message is an integer ID and a string, limited to 1024 bytes. Sending to a full inbox does nothing; unread messages remain until the player pulls them. -Each game defines `sendChat` and its BASIC callbacks in its own `bots.nim`. +The BASIC host passes the sender’s roster slot, the destination, and the +message bytes to the game’s `sendChat`. The [BASIC mailbox example](../examples/mailboxes/chat.bas) uses these routing rules: @@ -17,10 +18,9 @@ rules: Broadcasts include the sender. CTA uses its existing Chebyshev tile distance: the difference along each tile axis must be at most 16. Range and level are checked when sending; moving afterward does not remove queued messages. -Each game owns this routing loop. There is no shared routing policy or -routing callback framework. +Each game selects recipients before writing to their inboxes. -`sendChat` returns the number of inboxes that accepted a copy. Empty or +In a local game, `sendChat` returns the number of inboxes that accepted a copy. Empty or oversized messages and unsupported or invalid destinations return zero. A broadcast can reach some players even when another player's inbox is full. @@ -30,8 +30,9 @@ global, `-1` for team, or the sender's player ID for a DM. An empty pull sets that ID to `-3`. There is no separate sender, channel name, or timestamp. `mailboxCount()` counts unread messages, `mailboxSelf()` returns the caller's -roster ID, and `mailboxPlayers()` gives the roster size. GotA uses IDs 0 to 9, -CTA uses 0 to 3, and Light vs Dark uses 0 to 1. +roster ID, and `mailboxPlayers()` gives the roster size. Addresses run from +0 through `mailboxPlayers() - 1` in all three games. CTA has four party +slots. GotA uses the hero roster and LvD uses the configured player count. ```basic sendChat(-2, "Hello everyone.") @@ -46,15 +47,53 @@ while message$ <> "" wend ``` -Delivery follows script execution order. A later player can read a message +Local delivery follows script execution order. A later player can read a message in the same tick. Players can send and pull multiple times per decision, within their normal BASIC instruction and string limits. Inboxes persist across decisions and are replaced when policies are loaded for a new run. Recorded matches store chat in the same ordered command stream as gameplay actions. Replay playback consumes those commands without rerunning the bots. -`mailboxes.nim` is only a bounded inbox: an array of IDs, an array of reserved -strings, and read/count fields. It has no BASIC dependency. Each game owns -one inbox per player and copies message text through Bassy's public API. -Bassy owns its string storage and reclaims temporary strings on `restart()`. -Polyworld does not inspect or manage BASIC's private storage. +## From submission to inbox + +- **GotA** resolves the hero entity to a roster slot. Local policy chat goes + through `deliverChat` to `deliverPolicyChat`. In multiplayer, `sendChat` + returns 1 when it queues a submission. Each client receives the submission in an + authoritative tick packet. The game decodes category 1, checks hero/seat + ownership and destination, and applies an `ActionPolicyChat` with the sender + hero, target and text. Human chat uses category 2 and its own transcript. + See the [packet layout](../games/gods_of_the_arena/packets.md). +- **LvD** uses the player slot directly. Local sends call `deliverChat`. + Multiplayer queues a submission and returns 1 on acceptance. The client + decodes the packet’s chat payload (tag 0, player, target, byte-counted text), + checks ownership and destination, then applies nonempty chat at the packet + tick. The public HUD reads broadcast actions from the transcript. Reading + the HUD leaves BASIC inboxes untouched. +- **CTA** converts the hero ID to its party slot and selects nearby players + with room in their inboxes. When recording, it saves the accepted recipient + mask, target and text before pushing the broadcast to those same slots. + +In each host, `pullMailbox$()` uses Bassy’s public string API to copy the front +message into the calling player’s runtime before popping the entry. The pop updates +`mailboxId()`. An inbox can fill between network submission and delivery. + +## Local contract check + +With the dependencies from `nimby.lock` available to `config.nims`, run this +from the repository root in a POSIX shell. Set `POLYWORLD_DEPS` if the pinned +dependencies live outside the checkout’s parent directory. This checks FIFO +wraparound, exercises all three BASIC hosts for 300 decisions, measures inbox +allocations, and checks LvD authoritative packet delivery and replay. The +tests run serially with one compiler worker. + +```sh +( + scratch=$(mktemp -d) || exit 1 + trap 'rm -rf "$scratch"' EXIT + for test in tests/test_mailboxes.nim tests/test_mailbox_allocations.nim \ + games/light_vs_dark/tests/test_replay_chat.nim; do + nim c -r -d:headless -d:nimAllocStats --parallelBuild:1 \ + --nimcache:"$scratch/cache" -o:"$scratch/check" "$test" || exit 1 + done +) +``` diff --git a/docs/replays.md b/docs/replays.md new file mode 100644 index 000000000..8329fbbb1 --- /dev/null +++ b/docs/replays.md @@ -0,0 +1,58 @@ +# Desktop replay libraries + +GotA, Light vs Dark, Cards and Casters, and Galcon use the same desktop replay +library components. Game setup defaults to **Save replay** enabled. The choice +belongs to the local player and is stored separately from multiplayer match settings. +The replay menu, import dialog, folder button, and save controls are excluded +from browser builds. + +## Shared responsibilities + +- `polyworld/replaylibraries.nim` owns user folders, bounded reads, version + checks, newest-first listing, imports, and unique atomic file writes. Each + game supplies a `ReplayLibrary` descriptor and its payload validator. +- `polyworld/replaymenus.nim` owns the replay list, selection, scrolling, + disabled incompatible entries, and browser actions. Games handle launching + and leaving their own playback sessions. Galcon supplies its space background, + original fonts, flat widgets, and green highlights to the shared renderer. +- `polyworld/replaysettings.nim` owns the recording preference format and + persistence. Game wrappers supply their existing configuration namespace. +- `polyworld/replaysaves.nim` owns save deduplication, completion attempts, + outstanding save requests, and retrying retained recordings. + +Games retain their own recording and playback logic, including deterministic +state checks and ordered chat actions. GotA and LvD display elapsed time; CaC +displays action counts because its replay advances by accepted game actions. +Galcon supplies an opaque-payload descriptor because its existing recording +format uses only the outer Polyworld version header. Its decoder still +validates the complete payload before a replay becomes playable. + +## Save behavior + +For matches launched through the desktop menus, automatic saving writes the +recording at completion and when leaving a partial match. Repeated saves of +the same recorded prefix reuse its file. Further actions or chat create a new +snapshot, and deleting a saved file allows it to be recreated. + +Manual saving remains available when automatic saving is disabled. A failed +manual request is retried on exit. Failed exit saves remain in memory for the +menu's **Retry saving replay** button; a failed retry does not discard them. +Completion failures are not retried every frame. Pending recordings are not +durable across process termination. Watching a replay never records another +replay. + +## Compatibility + +Recordings live under the user's application data folder in +`Polyworld//Replays`. Each game defines its versioned recording +format. Galcon accepts only its matching format and has no historical simulation +modes; older recordings require the corresponding archived game build. +Imports copy the source file. Old game +or replay versions remain visible but disabled, and selecting a playable +entry revalidates it before playback. + +Shared behavior tests live in `tests/test_replaysettings.nim`, +`tests/test_replaysaves.nim`, `tests/test_replaylibraries.nim`, and +`tests/test_replay_browser.nim`. +Each game's tests retain coverage of its actual +recording, save/load, replay hashes, and native menu rendering. diff --git a/docs/screenshots.md b/docs/screenshots.md new file mode 100644 index 000000000..56ea73140 --- /dev/null +++ b/docs/screenshots.md @@ -0,0 +1,72 @@ +# Screenshot capture + +Every native game uses the same runtime arguments: + +```sh +./game --screenshot output/shot.png --frames 30 --windowSize 1280x720 +``` + +Use an ordinary graphical build. Capture opens a hidden window, renders without +display pacing or sound, saves the image, and exits through normal cleanup. +Parent directories are created automatically. Relative output paths are resolved +from the launch directory, even when a game changes its working directory. + +| Argument | Meaning | +| --- | --- | +| `--screenshot PATH` | Save one image to this path and exit. | +| `--frames N` | Capture the Nth rendered content frame; default 30. | +| `--windowSize WIDTHxHEIGHT` | Request the window dimensions used for rendering. | + +All three arguments accept separate, equals, or colon values: + +```sh +./game --screenshot output/shot.png --frames 3 --windowSize 1280x720 +./game --screenshot=output/shot.png --frames=3 --windowSize=1280x720 +./game --screenshot:output/shot.png --frames:3 --windowSize:1280x720 +``` + +Quote paths containing spaces. Frame counts and dimensions must be positive +integers. `--frames` counts rendered frames, not simulation ticks or seconds. +Games retain their own menu, replay, pause, and match-start arguments. A capture +does not automatically start a match in a game that normally opens its menu. +Call to Adventure and Heartleaf supply bundled bots for an otherwise unspecified +capture launch because those clients open directly into a match. + +Screenshot runs do not create automatic replay-library saves. An explicit +`--record` request still writes its replay. Monster's ordinary capture does not +invoke AI, listen to the microphone, or modify saved world/conversation data; +an explicit `--prompt` retains its separate wait-for-actions behavior. + +Capture requires a native graphical client. Headless builds and browser clients +reject screenshot requests. It is not a headless simulation or browser download +feature. + +## Clients + +The shared arguments are used by GotA, Light vs Dark, Cards and Casters, Call to +Adventure, Heartleaf, Crewrift, and Monster in this repository, and by the native +Galcon, Pudge Wars, Generals, and Mini Diplomacy clients in their own repositories. + +For example: + +```sh +nim r games/gods_of_the_arena/gota.nim --screenshot output/gota.png --frames 3 +nim r games/light_vs_dark/lvd.nim --screenshot output/lvd.png --frames 3 +nim r games/cac/cac.nim --screenshot output/cac.png --frames 3 +``` + +Game-specific scene setup remains separate. For example, Crewrift's explicit +`--capture-ticks` advances its simulation before rendering, Generals' `--at` +selects a position, and a replay argument opens the supplied recording. + +## Shared implementation and checks + +`polyworld/screenshots.nim` owns the graphics-free options, parsing, validation, +and capture state. `polyworld/cli.nim` exposes those options as +`GameOptions.capture`. `polyworld/viewers.nim` supplies the hidden framebuffer, +pixel writer, fixed capture clock, and one-shot completion helper. Games choose +their scene and perform their normal shutdown after a successful capture. + +Some specialized developer fixtures still use `-d:takeScreenshot` and environment +variables. Runtime screenshot arguments take precedence and do not require that +build define. Parser and state tests run in CI; rendering checks are local only. diff --git a/docs/stats.md b/docs/stats.md index 7923a6741..23d4d8368 100644 --- a/docs/stats.md +++ b/docs/stats.md @@ -68,8 +68,8 @@ APM uses reconstructed history when seeking, and revisiting a completed tick does not count commands again. Histories and decoded CPU samples have explicit size limits. -For viewer screenshots, build with `-d:takeScreenshot` and set -`SHOW_STATS=1` to include the overlay. Normal builds use TAB and the button. +For viewer screenshots, use `--screenshot PATH` and set `SHOW_STATS=1` to +include the overlay. Interactive play uses TAB and the button. ## GotA replay events diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 000000000..19be88ab9 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,30 @@ +# Testing + +CI runs one bounded unit suite on Linux, macOS, and Windows: + +```sh +nim check -d:release tests/unit_tests.nim +nim r -d:release tests/unit_tests.nim +``` + +Use the pinned dependencies in `nimby.lock`. Each CI job has a five-minute +limit, including setup and compilation. New pushes cancel older runs for the +same branch. + +The suite covers command-line and screenshot-option parsing, hashes, random +streams, mailboxes, replay serialization and save recovery, policy packages, +and in-memory room and client state. Screenshot tests check arguments and +capture state only. Tests do not create windows, render images, initialize +audio, start network servers, or simulate full games. The suite intentionally +keeps native command-line semantics, so do not add `-d:headless`. + +Full game, integration, rendering, audio, and browser checks remain local and +manual. For the existing combined suite, run: + +```sh +nim r -d:release -d:audioTest -d:bassyNativeStrict -d:replayEvents tests/all.nim +``` + +Run the relevant game's tests or standalone `tests/test_*.nim` and +`tests/manual_*.nim` fixtures locally when changing those systems. Those checks +may need the game's assets and native libraries; they are not CI prerequisites. diff --git a/games/cac/README.md b/games/cac/README.md index 84fa07933..185a5dd78 100644 --- a/games/cac/README.md +++ b/games/cac/README.md @@ -15,7 +15,7 @@ repository root: cd games/cac nim c cac.nim # builds ./cac ./cac --cards:warrior # print a class's cards -./cac --human --bot players/warrior.bas # play against a bot +./cac --player --bot players/warrior.bas # play against a bot nim c -d:headless -o:build/cac-headless cac.nim ./build/cac-headless --bot my.bas --bot players/mage.bas --seed 7 ``` @@ -364,8 +364,8 @@ RETURN ./build/cac-headless --bot my.bas:4 --bot players/mage.bas --record m.replay ./build/cac-headless --replay m.replay # check it replays exactly ./cac --replay m.replay # watch it -./cac --bot my.bas # watch it play itself -./cac --human --bot my.bas # play against it +./cac --bot my.bas:2 # watch it play itself +./cac --player --bot my.bas # play against it ``` Headless flags: `--bot PATH[:COUNT]` once per group of seats (2 to 7 seats @@ -397,22 +397,29 @@ P/T: 3/1 ## Playing ```sh -./cac # two reference bots -./cac --human # you pick a class on screen and play its precon -./cac --human players/mage.bas # you play that script's class and deck -./cac --players 4 --human # you and 3 bots around the ring +./cac # main menu; --direct watches bundled bots +./cac --player # you pick a class on screen and play its precon +./cac --player --deck players/mage.bas # you play that script's class and deck +./cac --players 4 --player # you and 3 bots around the ring ``` | Flag | Meaning | |---|---| -| `--human [PATH.bas]` | You play seat 0 (shown as player 1) | -| `--bot PATH` | Bot script, up to 2; one plays both duel seats, and with `--human` it is your opponent. Default: the reference bots in `players/` (a human faces one at random) | +| `--player [N]` | Control one-based seat N; bare --player selects seat 1 | +| `--deck PATH.bas` | With --player, use the class and deck from this bot setup script | +| `--bot PATH[:N]`, `--bots PATH[:N]` | Add N bot seats, repeatable; supplied bots must fill every nonhuman seat. With no explicit bots, use bundled defaults | | `--players N` | 2 is a duel; 3 to 7 play the ring (last one standing wins) | | `--seed N` | Fixed deal; without it every game takes a new seed and prints it | | `--replay PATH` | Watch a recorded match | +| `--record PATH` | Save the current match to this exact path, including on exit | +| `--name TEXT` | Set the human display name | +| `--play BOOL`, `--speed N` | Start playing or paused, with a positive integer speed | +| `--ticks N` | Cap a native local match after N accepted actions | | `--cards`, `--cards:CLASS`, `--card:NAME` | Print cards and exit | | `-h`, `--help` | Print the options and exit | +Common values accept separate, equals, and colon forms. See [CLI details](cli.md). + ## Coworld Cards and Casters runs on Coworld like Polyworld's other games: each seat is one uploaded @@ -466,9 +473,9 @@ the optional art and fonts available. `test_courtyard_render.nim` needs a GPU. writes the bundle to `emscripten/`. `./tools/serve.sh` builds and serves on port 8080 (`CAC_SKIP_WEB_BUILD=1` serves the existing build; `./tools/build_web.sh` -only builds). URL parameters mirror the flags: `human=1`, `players=N`, +only builds). URL parameters mirror the flags: `player=1`, `players=N`, `seed=N`, `bot=URL` (repeatable), `replay=URL`, e.g. -`cac.html?players=4&human=1`. Card art is staged cropped to the 546 × 417 +`cac.html?players=4&player=1`. Card art is staged cropped to the 546 × 417 art window, so the download stays near 31 MB. The replay viewer: `CAC_WEB_DIR=emscripten/replay ./tools/build_web.sh -d:replayViewer`, then `cac.html?replay=URL`. With Playwright, `node tests/test_hero_select.cjs` diff --git a/games/cac/app.nim b/games/cac/app.nim index 0c6847c3b..f05f1a5d5 100644 --- a/games/cac/app.nim +++ b/games/cac/app.nim @@ -3,12 +3,17 @@ ## with these. import std/[options, os] import chroma, opengl, pixie, silky, vmath, windy -import core/sim, core/sessions, ui/cardfaces, scene/cardrenderer, +import core/sim, core/sessions, core/bots, ui/cardfaces, scene/cardrenderer, vfx/vfxrenderer, scene/post, scene/table, scene/courtyard, scene/heroes, ui/hud, ui/heroselect, ui/frontendassets, scene/heroselectstage, paths, replayer, net/multiplayer import polyworld/[assets, characters, chargen, connections, menus, viewers] +from polyworld/cli import CliError, DurationFlags + +when not defined(emscripten): + import polyworld/replaysaves, core/replays, replaylibraries, replaysettings + export replaysettings when PostPanelControls: import polyworld/common @@ -39,10 +44,9 @@ type returnToMenu*: bool battlefieldPlayers: int captureFramebuffer*: GLuint - captureTexture, captureDepth: GLuint - captureSize: IVec2 + captureTarget: ScreenshotTarget humanSeat*: Option[Seat] - ## The class and deck the human brought with `--human PATH.bas`; + ## The class and deck the human brought with `--deck PATH.bas`; ## without one they choose a class and play its precon. appDir*: string ## The project folder: players/, the atlas, screenshots. window*: Window @@ -58,6 +62,13 @@ type idleClips*: array[HeroSeats, array[HeroClass, int]] deathClips*: array[HeroSeats, array[HeroClass, int]] replay*: Replayer ## Set when watching a recorded match. + when not defined(emscripten): + replayPreferences*: ReplayPreferences + replaySaveError*: string + unsavedReplays*: seq[ReplayData] + recording*: ReplayRecorder + replaySaving: ReplaySaveState + explicitReplaySaved: bool const DefaultBots* = ["archer.bas", "warrior.bas", "mage.bas", "archer_warrior.bas"] @@ -70,6 +81,26 @@ proc defaultBotSources*(appDir: string): seq[string] = if fileExists(path): result.add readFile(path) +proc launchBotPrinter*(options: SessionOptions): PrintProc = + ## Routes script output to the terminal only for a verbose launch. + if options.common.verbose: + result = proc(event: PrintEvent) = + ## Writes each BASIC print fragment without changing simulation state. + case event.kind + of TextPrint: stdout.write(event.text) + of ValuePrint: stdout.write(event.value) + of FixedPrint: stdout.write(event.fixedValue) + of NewlinePrint: stdout.write("\n") + +proc validateNetworkLaunch*(app: App) = + ## Keeps room-authoritative timing separate from local launch controls. + if app.options.common.specifiedFlags * DurationFlags != {}: + raise newException(CliError, + "--ticks, --seconds, and --minutes are not supported for network matches") + if app.options.common.pauseOnStart or app.options.common.speed != 1: + echo "Network matches follow room timing; --play and --speed apply " & + "to local games and replays." + proc polyworldRoot*(): string = var candidates: seq[string] let configured = getEnv("POLYWORLD_REPO") @@ -128,6 +159,9 @@ proc buildUiAtlas*(cardAssets: string): AtlasBuilder = proc initApp*(sessionOptions: SessionOptions): App = ## Opens the window and loads everything the modes draw with. + configureCapture(sessionOptions.capture, "cac.png") + if captureActive(): + configureSoundLaunch(true) when defined(emscripten): let appDir = "/" setCurrentDir("/") @@ -156,8 +190,10 @@ proc initApp*(sessionOptions: SessionOptions): App = (window, sk) = initGameWindow( WindowTitle, atlasPath, - ivec2(3200, 2000), - vsync = true + (if sessionOptions.windowWidth > 0: + ivec2(sessionOptions.windowWidth, sessionOptions.windowHeight) + else: ivec2(3200, 2000)), + vsync = sessionOptions.common.vsync ) var @@ -196,8 +232,135 @@ proc initApp*(sessionOptions: SessionOptions): App = except MenusError, IOError, OSError: result.preferenceError = getCurrentExceptionMsg() result.preferences = Preferences() + if sessionOptions.common.playerName.len > 0: + result.preferences.name = sessionOptions.common.playerName + if sessionOptions.human: + for index in 0 ..< sessionOptions.playerCount: + result.playerNames.add( + if index == max(sessionOptions.common.playerSlot.int - 1, 0) and + result.preferences.name.len > 0: + result.preferences.name + else: + "Player " & $(index + 1)) + when not defined(emscripten): + result.replayPreferences = ReplayPreferences() + try: + result.replayPreferences = readReplayPreferences() + except MenusError, IOError, OSError: + result.replaySaveError = getCurrentExceptionMsg() result.preferences.applyPreferences(window, - configureDisplay = not defined(takeScreenshot)) + configureDisplay = not captureActive() and sessionOptions.windowWidth == 0) + +when not defined(emscripten): + proc replaySavedPath*(app: App): string = + ## Returns the last successfully saved prefix of the current match. + app.replaySaving.savedPath + + proc useReplayRecording*(app: App, recorder: ReplayRecorder = nil) = + ## Starts a fresh recording session without discarding failed prior saves. + app.recording = if app.replay == nil: recorder else: nil + app.replaySaveError = "" + app.replaySaving.resetReplaySave() + app.explicitReplaySaved = false + + proc beginReplayRecording*(app: App, seats: openArray[Seat], + seed: int64, messages: openArray[ReplayAction] = []): ReplayRecorder = + ## Records the exact decks and public names used to start a local match. + app.useReplayRecording() + if app.replay != nil: + return + if seed < low(int32).int64 or seed > high(int32).int64: + app.replaySaveError = "This seed is outside the replay format's range." + return + let maximumTicks = + if app.options.common.maximumTicks > 0: + app.options.common.maximumTicks + else: + MaxReplayHashes.int32 + var config = GameConfig(seed: seed.int32, maxTicks: maximumTicks) + for index in 0 ..< seats.len: + config.players.add PlayerConfig(name: + if index < app.playerNames.len: app.playerNames[index] + else: "Player " & $(index + 1)) + result = initReplayRecorder( + matchSetup(seats, seed.int32, maximumTicks.uint32), config) + for message in messages: + result.record(message) + app.recording = result + + proc saveCurrentReplay*(app: App): string = + ## Saves a completed action prefix once, sharing manual and automatic saves. + if app.replay != nil or app.recording == nil: + raise newException(ReplayError, "There is no live match replay to save.") + app.replaySaving.requestReplaySave() + let data = app.recording.data + result = app.replaySaving.saveReplaySnapshot(data, + proc(data: ReplayData): string = + ## Writes a validated CaC recording to its desktop library. + saveLibraryReplay(data) + ) + app.replaySaveError = "" + + proc updateReplaySaving*(app: App, completed: bool) = + ## Saves a completed match before the player leaves its result screen. + if app.options.common.recordPath.len > 0: + if completed and app.replay == nil and app.recording != nil and + not app.explicitReplaySaved: + saveReplay(app.options.common.recordPath, app.recording.data) + app.explicitReplaySaved = true + return + if app.replay == nil and app.recording != nil and + app.replaySaving.beginAutomaticReplaySave( + app.replayPreferences.saveReplay and not captureActive(), completed): + try: + discard app.saveCurrentReplay() + except CatchableError as error: + app.replaySaveError = "Cannot save replay: " & error.msg + + proc finishReplayRecording*(app: App) = + ## Preserves failed exit saves for retry after the renderer has cleaned up. + if app.options.common.recordPath.len > 0: + if app.replay == nil and app.recording != nil and + not app.explicitReplaySaved: + saveReplay(app.options.common.recordPath, app.recording.data) + app.explicitReplaySaved = true + return + if app.replay != nil or app.recording == nil or + not app.replaySaving.shouldSaveReplayOnExit( + app.replayPreferences.saveReplay and not captureActive()): + return + try: + discard app.saveCurrentReplay() + except CatchableError as error: + app.replaySaveError = "Cannot save replay: " & error.msg + if app.window != nil and not captureActive(): + app.window.closeRequested = false + try: + app.recording.data.validate() + app.unsavedReplays.add(app.recording.data) + except ReplayError: + discard + + proc retryPendingReplays*(app: App) = + ## Removes retained recordings only after their library writes succeed. + try: + app.unsavedReplays.retryReplaySaves( + proc(data: ReplayData): string = + ## Writes a retained CaC recording to its desktop library. + saveLibraryReplay(data) + ) + app.replaySaveError = "" + except CatchableError as error: + app.replaySaveError = "Cannot save replay: " & error.msg + +proc atLaunchTickLimit*(app: App): bool = + ## Stops a native local match after its requested number of accepted actions. + when not defined(emscripten): + app.network == nil and app.replay == nil and app.recording != nil and + app.options.common.maximumTicks > 0 and + app.recording.data.hashes.len >= app.options.common.maximumTicks + else: + false proc setBattlefield*(app: App, playerCount: int) = ## Uses Tower Arena for two players and the ring for larger matches. @@ -211,47 +374,16 @@ proc setBattlefield*(app: App, playerCount: int) = proc closeCapture*(app: App) = ## Releases the hidden capture target while the window context is alive. - if app.captureFramebuffer == 0: - return - glBindFramebuffer(GL_FRAMEBUFFER, 0) - glDeleteFramebuffers(1, app.captureFramebuffer.addr) - glDeleteTextures(1, app.captureTexture.addr) - glDeleteRenderbuffers(1, app.captureDepth.addr) + app.captureTarget.releaseScreenshotTarget() app.captureFramebuffer = 0 - app.captureTexture = 0 - app.captureDepth = 0 - app.captureSize = ivec2(0) proc beginCaptureFrame*(app: App) = ## Renders screenshots offscreen without depending on a visible Cocoa drawable. - when defined(takeScreenshot): + if captureActive(): when not defined(emscripten): doAssert not app.window.visible, "Capture windows must stay hidden" - let size = app.window.size - if app.captureFramebuffer == 0 or app.captureSize != size: - app.closeCapture() - glGenFramebuffers(1, app.captureFramebuffer.addr) - glBindFramebuffer(GL_FRAMEBUFFER, app.captureFramebuffer) - glGenTextures(1, app.captureTexture.addr) - glBindTexture(GL_TEXTURE_2D, app.captureTexture) - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8.GLint, size.x, size.y, - 0, GL_RGBA, GL_UNSIGNED_BYTE, nil) - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST.GLint) - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST.GLint) - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, - GL_TEXTURE_2D, app.captureTexture, 0) - glGenRenderbuffers(1, app.captureDepth.addr) - glBindRenderbuffer(GL_RENDERBUFFER, app.captureDepth) - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, - size.x, size.y) - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, - GL_RENDERBUFFER, app.captureDepth) - if glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE: - app.closeCapture() - raise newException(IOError, "Unable to allocate screenshot target") - app.captureSize = size - glBindFramebuffer(GL_FRAMEBUFFER, app.captureFramebuffer) - glViewport(0, 0, size.x, size.y) + app.captureFramebuffer = + app.captureTarget.beginScreenshotFrame(app.window) proc heroClip*(app: App, model: int, heroClass: HeroClass, dying, idleTime: float32): tuple[clip: int, time: float32] = diff --git a/games/cac/cac.nim b/games/cac/cac.nim index 579c0e29b..903e3f0e4 100644 --- a/games/cac/cac.nim +++ b/games/cac/cac.nim @@ -5,9 +5,9 @@ import core/[sim, cardlist] export sim when not defined(headless): - import std/[options, strutils] + import std/options import windy - import polyworld/[connections, menus, sounds] + import polyworld/[cli, connections, menus, screenshots, sounds] import core/[sessions, replays, bots], app, replayer, scene/post, modes/duel, modes/multiplayer, frontend, paths @@ -25,42 +25,26 @@ when not defined(headless): echo Rule proc printHelp() = - echo "Cards and Casters\n" & - "Options (--key value or --key=value):\n" & - " --menu Open the main menu (default without match flags)\n" & - " --direct Launch a match without the menus\n" & - " --server URL Set the relay used after choosing Multiplayer\n" & - " --room CODE Join this room after choosing Multiplayer\n" & - " --players N Player count (2). 2 plays a duel; 3 to 7 play a\n" & - " multiplayer match: the last player alive wins.\n" & - " --seed INTEGER Set the battle seed\n" & - " --bot PATH Bot program (.bas), repeatable up to " & $PlayerCount & - " times.\n" & - " Duel: one bot plays both seats; with --human it\n" & - " plays the opponent. Multiplayer: the bots take\n" & - " every seat but yours, in turn.\n" & - " Defaults to the reference bots in players/.\n" & - " --human [PATH] Play seat 0 yourself instead of watching bots.\n" & - " With a bot program (.bas), play the class and deck\n" & - " it lists; otherwise choose a class on screen and\n" & - " play its precon.\n" & - " --replay PATH Watch a recorded match (see --record in the\n" & - " headless build)\n" & - " --mute Mute this launch; otherwise use saved settings\n" & - " --unmute Enable sound for this launch (--mute=false)\n" & - " --cards List every card and exit\n" & - " --cards:CLASS List one class's cards (archer, warrior or mage)\n" & - " and exit\n" & - " --card:NAME Show one card and exit; case, spaces and hyphens\n" & - " don't matter (--card:hail-of-arrows)\n" & - " -h, --help Show this help and exit" + ## Lists shared launch arguments and CaC-specific setup choices. + echo "Cards and Casters" + echo commonUsageFor(SessionFlags) + echo " --menu Open the main menu (default without match flags)" + echo " --direct Launch a match without the menus" + echo " --players N Set 2 to 7 seats (defaults to supplied roster or 2)" + echo " --deck PATH Read the human class/deck from a bot setup script" + echo " Requires --player; only the setup program runs" + echo " --cards List every card and exit" + echo " --cards:CLASS List archer, warrior, or mage cards and exit" + echo " --card:NAME Show one card and exit" + echo " -h, --help Show this help and exit" + echo "Supply one bot per nonhuman seat; absent bots use bundled defaults." - proc readHumanSeat(path: string, seats: int, seed: int64): Seat = + proc readHumanSeat(path: string, seats: int, seed: int64, player: int32): Seat = ## The class and deck a bot script lists, for the human to play. Only ## its setup runs. An illegal deck is reported and seats them with none. try: resetInboxes(seats) - let vm = loadBot(readFile(path), 0) + let vm = loadBot(readFile(path), player) result = vm.setupSeat(seats, seed) for problem in vm.deckProblems: stderr.writeLine "Your deck in ", path, " is illegal: ", problem @@ -76,22 +60,19 @@ when not defined(headless): if printCardReference(commandLineParams()): return var options = parseSessionOptions(commandLineParams()) - var soundExplicit = false - for argument in commandLineParams(): - if argument == "--unmute" or argument.startsWith("--mute"): - soundExplicit = true - configureSoundLaunch(options.soundMuted, soundExplicit) + options.resolveSessionPaths() + configureCapture(options.capture, "cac.png") + configureSoundLaunch(options.soundMuted or captureActive(), + options.common.soundOverride or captureActive()) when defined(takeScreenshot): options.menu = "--menu" in commandLineParams() when defined(replayViewer): options.menu = false - # Before initApp, which moves to the Polyworld folder. - for path in options.botPaths.mitems: - path = absolutePath(path) var humanSeat: Option[Seat] if options.humanDeckPath.len > 0: humanSeat = some(readHumanSeat(options.humanDeckPath, - max(options.playerCount, PlayerCount), options.seed)) + max(options.playerCount, PlayerCount), options.seed, + options.common.playerSlot - 1)) var replay: Replayer if options.replayPath.len > 0: # Before initApp, which moves to the Polyworld folder. @@ -111,7 +92,8 @@ when not defined(headless): app.returnToMenu = false if directLaunch: directLaunch = false - if app.options.playerCount > PlayerCount: + if app.options.playerCount > PlayerCount or + app.options.common.playerSlot > 1: app.runMultiplayer() else: app.runDuel() @@ -121,6 +103,36 @@ when not defined(headless): let selected = app.runFrontend(connection, returnToLobby) if selected.kind == ExitFrontend: break + when not defined(emscripten): + if selected.kind == ReplayFrontend: + let previousOptions = app.options + try: + app.network = nil + app.connection = nil + app.configuredSeats = @[] + app.configuredBotSources = @[] + app.configuredHumanSeat = -1 + app.playerNames = @[] + app.replay = newReplayer(loadReplay(selected.replayPath)) + app.options.replayPath = selected.replayPath + app.options.botPaths = @[] + app.options.humanDeckPath = "" + app.options.human = false + app.options.playerCount = app.replay.classes.len + if app.options.playerCount > PlayerCount: + app.runMultiplayer() + else: + app.runDuel() + except CatchableError as problem: + app.preferenceError = problem.msg + app.window.closeRequested = false + finally: + app.window.onFrame = nil + app.window.onButtonPress = nil + app.options = previousOptions + app.replay = nil + returnToLobby = false + continue app.connection = connection app.network = selected.network app.configuredSeats = selected.seats diff --git a/games/cac/cli.md b/games/cac/cli.md new file mode 100644 index 000000000..39a9f46ca --- /dev/null +++ b/games/cac/cli.md @@ -0,0 +1,49 @@ +# Command-line options + +Cards and Casters uses Polyworld's shared argument parser in both native and +headless builds. Values accept `--flag VALUE`, `--flag=VALUE`, and +`--flag:VALUE`. `--help` lists the options supported by that build. + +```sh +./cac --player 2 --bot players/archer.bas --name Ada +./cac --bot players/mage.bas:4 --seed 7 --record output/match.replay +./cac --replay output/match.replay --play false --speed 3 +./build/cac-headless --bots players/warrior.bas:3 --ticks 500 --record output/match.replay +``` + +`--bot PATH[:N]` adds N seats in order, skipping the one-based human slot from +`--player [N]`. `--bots` is an identical alias. A bare `--player` selects slot +1. `--name TEXT` sets the display name; it does not select a slot. When bot +programs are supplied, they must fill every nonhuman seat exactly. If +`--players N` is omitted, the explicit roster determines the seat count. +Without bot arguments, the native menus and direct launch use bundled bots. + +The CaC-specific `--deck PATH` runs a bot script's setup to choose the human's +class and deck. It requires `--player`. It replaces the old overloaded +`--human PATH` option and uses a direct launch. The menu provides its own deck +selection, so `--menu` cannot be combined with `--deck`. + +`--replay PATH` loads a recording and excludes live bot, human, seed, duration, +and recording-output arguments. `--record PATH` writes the live match to that +exact path on completion or exit. Parent directories are created. Paths are +relative to the launch directory, including when asset setup changes the +working directory. Setting a record destination alone leaves the main menu +open; it applies to the subsequent live match. + +`--play BOOL` chooses the initial pause state and `--speed N` selects a positive +integer speed for local gameplay and replay playback. Online clients follow +the authoritative room timing and reject local duration caps. `--server` and +`--room` configure the multiplayer menu and cannot be combined with direct +bot, human, or replay inputs. `--windowSize`, `--vsync`, `--mute`, `--unmute`, +`--screenshot`, and `--frames` use the shared graphical behavior. + +One CaC tick is one accepted gameplay action. Native `--ticks N` limits that +count; `--seconds N` and `--minutes N` convert using Polyworld's 24-tick time +scale. The headless runner supports `--headless-tick-rate N` to pace those +actions in wall-clock time; zero runs without pacing. Its `--players N` +validates the supplied roster, and `--classes archer,mage,...` overrides each +seat's selected class and deck with that class's precon. + +Unsupported options fail explicitly. CaC bots do not implement the shared LLM +request modes. Headless builds reject graphical controls and menu connection +settings. Browser builds do not offer replay output or local duration caps. diff --git a/games/cac/core/sessions.nim b/games/cac/core/sessions.nim index f78ddce6d..8f08a64ff 100644 --- a/games/cac/core/sessions.nim +++ b/games/cac/core/sessions.nim @@ -1,30 +1,36 @@ ## Shared browser/server session options, deterministic bots and snapshot codec. ## Card programs stay in the base set; the wire format contains stable card IDs. -import std/[algorithm, json, options, sets, strutils] -from polyworld/cli import takeSoundFlag +import std/[algorithm, json, options, os, sets, strutils] +import polyworld/cli import sim -from battlesetup import MaxBattlePlayers +from battlesetup import BattleSetup, MaxBattlePlayers, defaultBattleSetup export sim const DefaultSessionSeed* = 20260910'i64 SnapshotSchemaVersion* = 20 + SessionFlags* = AllCommonFlags - {HeadlessTickRateFlag, LlmModeFlag} - + (when defined(emscripten): DurationFlags + {RecordFlag} else: {}) type SessionOptions* = object + common*: GameOptions + ## Canonical launch arguments shared with every Polyworld game. seed*: int64 seedGiven*: bool ## --seed was passed; otherwise games may pick their own. playerCount*: int ## Number of seats for a direct local match. human*: bool - soundMuted*: bool = true + soundMuted*: bool ## Launch audio preference, separate from deterministic match state. humanDeckPath*: string - ## `--human PATH.bas`: a bot script whose class and deck the human + ## `--deck PATH.bas`: a bot script whose class and deck the human ## plays. Only its setup runs. botPaths*: seq[string] replayPath*: string ## A recorded match to watch instead of playing. menu*: bool = true serverAddress*, roomCode*: string + capture*: ScreenshotOptions + windowWidth*, windowHeight*: int32 BotActionKind* = enum PlayCardAction, EndTurnAction, ResolveTriggerAction, TossAction @@ -53,88 +59,102 @@ proc classId(heroClass: HeroClass): string = heroClass.className().toLowerAscii() proc parseSessionOptions*(args: openArray[string]): SessionOptions = - ## Accept both --key=value and --key value, including negative numeric seeds. - ## --human is a flag: --human, --human=true, --human true all work, and - ## --human PATH.bas plays the deck that script lists. + ## Shares common flags and validates the local roster before opening a window. result = SessionOptions(seed: DefaultSessionSeed, playerCount: PlayerCount, - human: false) + common: GameOptions(seed: DefaultSessionSeed.int32, speed: 1)) + let arguments = @args var index = 0 directLaunch = false + playersGiven = false menuChoice: Option[bool] - while index < args.len: - if result.soundMuted.takeSoundFlag(args[index]): - inc index - continue - let separator = args[index].find('=') - let key = if separator >= 0: args[index][0 ..< separator] else: args[index] - if key in ["--menu", "--direct"]: - if separator >= 0: - raise newException(ValueError, key & " does not take a value") - menuChoice = some(key == "--menu") - inc index - continue - if key notin ["--seed", "--players", "--bot", "--human", "--replay", - "--server", "--room"]: - raise newException(ValueError, "Unknown session option: " & key) - if key in ["--players", "--bot", "--human", "--replay"]: - directLaunch = true - if key == "--human": - var value = "true" - if separator >= 0: - value = args[index][separator + 1 .. ^1] - elif index + 1 < args.len and not args[index + 1].startsWith("--"): - inc index - value = args[index] - if value.toLowerAscii().endsWith(".bas"): - result.human = true - result.humanDeckPath = value - else: - result.human = value.toLowerAscii() in ["true", "1", "yes", ""] - inc index - continue - var value: string - if separator >= 0: - value = args[index][separator + 1 .. ^1] + while index < arguments.len: + let + argument = arguments[index] + flag = splitFlag(argument) + if result.common.takeCommonFlag(arguments, index, argument): + if flag.name in ["--bot", "--bots", "--player", "--replay"]: + directLaunch = true else: - inc index - if index >= args.len or args[index].startsWith("--"): - raise newException(ValueError, "Missing value for " & key) - value = args[index] - if value.len == 0: - raise newException(ValueError, "Missing value for " & key) - case key - of "--seed": - try: - result.seed = parseBiggestInt(value).int64 - except ValueError: - raise newException(ValueError, "Invalid integer seed: " & value) - result.seedGiven = true - of "--players": - try: - result.playerCount = parseInt(value) - except ValueError: - raise newException(ValueError, "Invalid integer player count: " & value) - if result.playerCount < PlayerCount: - raise newException(ValueError, "Player count must be at least " & - $PlayerCount) - if result.playerCount > MaxBattlePlayers: - raise newException(ValueError, "Player count must be at most " & - $MaxBattlePlayers) - of "--bot": - if result.botPaths.len >= PlayerCount: - raise newException(ValueError, "Too many --bot arguments (max " & - $PlayerCount & ")") - result.botPaths.add value - of "--replay": result.replayPath = value - of "--server": result.serverAddress = value - of "--room": result.roomCode = value - else: discard + case flag.name + of "--menu", "--direct": + if flag.attached: + raise newException(ValueError, flag.name & " does not take a value") + menuChoice = some(flag.name == "--menu") + of "--players": + result.playerCount = parsePositiveInt32( + flagValue(arguments, index, argument), flag.name).int + playersGiven = true + directLaunch = true + of "--deck": + result.humanDeckPath = flagValue(arguments, index, argument) + else: + raise newException(ValueError, "Unknown session option: " & flag.name) inc index + result.common.rejectUnsupportedFlags(SessionFlags) + result.common.validateGameOptions(0, "") + result.seed = result.common.seed.int64 + result.seedGiven = SeedFlag in result.common.specifiedFlags + result.human = result.common.playerSlot > 0 + result.soundMuted = result.common.soundMuted + result.replayPath = result.common.replayPath + result.serverAddress = result.common.serverUrl + result.roomCode = result.common.roomCode + result.capture = result.common.capture + result.windowWidth = result.common.windowWidth + result.windowHeight = result.common.windowHeight + if not playersGiven and result.common.botGroups.len > 0: + result.playerCount = result.common.botGroups.botCount + ord(result.human) + if result.playerCount notin PlayerCount .. MaxBattlePlayers: + raise newException(ValueError, "--players must be between " & + $PlayerCount & " and " & $MaxBattlePlayers) + if result.common.playerSlot > result.playerCount: + raise newException(ValueError, "--player must be between 1 and " & + $result.playerCount) + if result.common.botGroups.len > 0: + result.common.validateGameOptions(result.playerCount, + "supply one bot per nonhuman seat") + for group in result.common.botGroups: + for _ in 0 ..< group.count: + result.botPaths.add group.path + if result.humanDeckPath.len > 0 and not result.human: + raise newException(ValueError, "--deck requires --player") + if result.serverAddress.len > 0 or result.roomCode.len > 0: + if result.common.botGroups.len > 0 or result.human or + result.replayPath.len > 0: + raise newException(ValueError, + "--server and --room cannot be combined with --bot, --player, or --replay") result.menu = menuChoice.get(not directLaunch or result.serverAddress.len > 0 or result.roomCode.len > 0) if result.replayPath.len > 0: result.menu = false + if result.menu and result.humanDeckPath.len > 0: + raise newException(ValueError, "--deck requires a direct local launch") + +proc initialBattleSetup*(options: SessionOptions): BattleSetup = + ## Preserves the signed launch seed when the player enters local setup. + result = defaultBattleSetup(options.playerCount) + result.seed = options.seed.int32 + +proc initialMenuHumanSeat*(options: SessionOptions): int = + ## Applies explicit roster choices while keeping the menu's default human. + if options.human: + options.common.playerSlot.int - 1 + elif options.common.botGroups.len > 0: + -1 + else: + 0 + +proc resolveSessionPaths*(options: var SessionOptions) = + ## Keeps user file arguments relative to the original launch directory. + options.common.resolveGamePaths() + options.replayPath = options.common.replayPath + options.botPaths.setLen(0) + for group in options.common.botGroups: + for _ in 0 ..< group.count: + options.botPaths.add group.path + if options.humanDeckPath.len > 0: + options.humanDeckPath = absolutePath(options.humanDeckPath) proc botPick(game: GameState, choices: seq[Choice], player: int, helps: bool): Choice = diff --git a/games/cac/frontend.nim b/games/cac/frontend.nim index 757592abf..a553e293e 100644 --- a/games/cac/frontend.nim +++ b/games/cac/frontend.nim @@ -2,18 +2,19 @@ import std/[os, strutils, tables, uri], bumpy, chroma, opengl, pixie, silky, vmath, windy, - polyworld/[chrome, connections, gameuis, homes, lobbies, menus, policies, + polyworld/[chrome, connections, homes, lobbies, menus, policies, roomclients, rooms, sounds, viewers], - app, core/[battlesetup, sim], net/[multiplayer, web], ui/controls + app, core/[battlesetup, sessions, sim], net/[multiplayer, web], ui/controls, + homes as cacHomes when not defined(emscripten): - import polyworld/displays + import polyworld/displays, replaylibraries, replaymenus, replaysettings const ClassChoices = [Archer, Warrior, Mage] type FrontendKind* = enum - ExitFrontend, LocalFrontend, NetworkFrontend + ExitFrontend, LocalFrontend, NetworkFrontend, ReplayFrontend FrontendResult* = object kind*: FrontendKind seats*: seq[sim.Seat] @@ -21,6 +22,7 @@ type network*: NetworkMatch botSources*, playerNames*: seq[string] seed*: int64 + replayPath*: string FrontendState = object initialized: bool setup: BattleSetup @@ -29,6 +31,9 @@ type roomName, roomNameDefault: string pendingInvite: string publicRoom: bool + browsingReplays: bool + when not defined(emscripten): + replayBrowser: ReplayBrowserState var frontendState: FrontendState @@ -73,58 +78,6 @@ proc localSelection(name: string): FrontendResult = continue result.seats.add precon(heroClass) -proc drawCacHome(sk: Silky, window: Window, focus: var int): HomeAction = - ## Draws illustrated CaC buttons with pointer and keyboard navigation. - sk.uiScale = selectedUiScale(max(0.1'f, min( - window.size.x.float32 / 760, window.size.y.float32 / 940)), - 1080.0'f / 940) - sk.beginUi(window, window.size) - sk.textStyle = "LobbyBody" - sk.drawHomeBackground(window) - let - view = window.size.vec2 / sk.uiScale - center = view * 0.5'f - at = center - vec2(270, 280) - labels = ["Single Player", "Multiplayer", "Settings", "Exit"] - count = when defined(emscripten): 3 else: 4 - sk.drawSprite("home-shade", center - vec2(500, 440), vec2(1000, 880)) - sk.drawLabel("CARDS AND CASTERS", at - vec2(80, 21), vec2(700, 80), - rgbx(8, 16, 25, 230), "HomeTitle", CenterAlign) - sk.drawLabel("CARDS AND CASTERS", at - vec2(80, 24), vec2(700, 80), - rgbx(245, 225, 181, 255), "HomeTitle", CenterAlign) - if window.buttonPressed[KeyUp]: - focus = (focus + count - 1) mod count - playSound(SelectSound) - if window.buttonPressed[KeyDown] or window.buttonPressed[KeyTab]: - focus = (focus + 1) mod count - playSound(SelectSound) - for index in 0 ..< count: - let - point = at + vec2(30, 142 + index.float32 * 80) - size = vec2(480, 76) - interaction = sk.interact(rect(point, size), true) - hovered = interaction in {Hovered, Pressed, Held, Released} - if hovered and window.mouseDelta != ivec2(0): - focus = index - sk.hoverSound(GameUiPanel(origin: point, size: size)) - let - active = hovered or focus == index - pressed = interaction in {Pressed, Held} - tint = if pressed: 205'u8 elif active: 255'u8 else: 218'u8 - inset = if pressed: vec2(2, 1) else: vec2(0) - ink = if active: rgbx(255, 240, 202, 255) - else: rgbx(225, 221, 200, 255) - skin = if index == 0: "home-button-primary" else: "home-button-secondary" - sk.drawSprite(skin, point + inset, size - inset * 2, - rgbx(tint, tint, tint, 255)) - sk.drawLabel(labels[index], point + vec2(0, 2), size, - rgbx(6, 15, 20, 235), "HomeButton", CenterAlign) - sk.drawLabel(labels[index], point, size, ink, "HomeButton", CenterAlign) - if interaction == Released or - (focus == index and window.buttonPressed[KeyEnter]): - result = HomeAction(index + 1) - playSound(ClickSound) - proc removePlayerPicker(sk: Silky, window: Window, ui: var LobbyUi): SlotChoice = ## Lets the host release any guest slot without removing their other seats. @@ -181,14 +134,23 @@ proc runFrontend*(app: App, connection: var Connection, template preferences: untyped = app.preferences if not frontendState.initialized: frontendState = FrontendState(initialized: true, - setup: defaultBattleSetup(clamp(app.options.playerCount, 2, 7)), - humanSeat: 0, publicRoom: true) - frontendState.setup.seed = int32(app.options.seed and 0x7fffffff) + setup: app.options.initialBattleSetup(), + humanSeat: app.options.initialMenuHumanSeat(), publicRoom: true) frontendState.roomNameDefault = defaultRoomName(preferences.name) frontendState.roomName = frontendState.roomNameDefault + when not defined(emscripten): + frontendState.replayBrowser = initReplayBrowser(Library) frontendState.localPolicies.setLen(frontendState.setup.classes.len) - for index in 1 ..< frontendState.localPolicies.len: - if bots.len > 0: + var botIndex = 0 + for index in 0 ..< frontendState.localPolicies.len: + if index == frontendState.humanSeat: + continue + if botIndex < app.options.botPaths.len: + let path = app.options.botPaths[botIndex] + frontendState.localPolicies[index] = LocalPolicy( + name: path.extractFilename(), bytes: readPolicyBytes(path)) + inc botIndex + elif bots.len > 0: frontendState.localPolicies[index] = bots[index mod bots.len] var activeConnection = connection @@ -207,7 +169,24 @@ proc runFrontend*(app: App, connection: var Connection, playerName = preferences.name editingPlayer, localLaunchRequested: bool launchLocal, launchNetwork: bool + launchReplay: bool selection: FrontendResult + when not defined(emscripten): + template replayBrowser: untyped = frontendState.replayBrowser + var + replayAction: ReplayBrowserResult + retryReplaySave: bool + replayBrowser.message = if app.replaySaveError.len > 0: + app.replaySaveError else: error + replayBrowser.refreshRequested = frontendState.browsingReplays + + proc drawReplayRetry() = + ## Keeps failed exports available without discarding the completed match. + if sk.drawReplaySaveRetry(app.unsavedReplays.len > 0): + retryReplaySave = true + + if app.replaySaveError.len > 0: + error = app.replaySaveError app.preferenceError = "" if initialEntry and not returnToLobby: let inviteServer = inviteParameter("server") @@ -225,8 +204,8 @@ proc runFrontend*(app: App, connection: var Connection, client.snapshot.phase in {rooms.Ended, Desynced}: client.send(RoomMessage(kind: ReturnLobby)) client.error = "" + var screenshotFrame: int when defined(takeScreenshot): - var screenshotFrame: int # Capture fixtures change memory only; saved preferences remain untouched. preferences.name = "Player One" connectRequested = false @@ -236,6 +215,12 @@ proc runFrontend*(app: App, connection: var Connection, of "single": page = SingleMenu of "settings": page = SettingsMenu of "multiplayer": page = MultiplayerMenu + of "replays": + when defined(emscripten): + raise newException(MenusError, "The replay library is desktop-only") + else: + frontendState.browsingReplays = true + replayBrowser.refreshRequested = true of "name": page = MultiplayerMenu preferences.name = "" @@ -244,16 +229,20 @@ proc runFrontend*(app: App, connection: var Connection, raise newException(MenusError, "Unknown CAC_CAPTURE_PAGE") template presentMenuFrame() = ## Capture the rendered back buffer before swapping the hidden window. - when defined(takeScreenshot): - when not defined(emscripten): - doAssert not window.visible, "Capture windows must stay hidden" - captureScreenshot(window, screenshotFrame, - max(1, parseInt(getEnv("CAC_CAPTURE_FRAME", "20"))), - app.appDir / "cac_menu.png") - window.presentFrame(framePaceHz) - while not window.closeRequested and not launchLocal and not launchNetwork: + if captureFrame(window, screenshotFrame, + (when defined(takeScreenshot): + max(1, parseInt(getEnv("CAC_CAPTURE_FRAME", "20"))) + else: 30), app.appDir / "cac_menu.png"): + when not defined(emscripten): + window.closeRequested = true + else: + window.presentFrame(framePaceHz) + while not window.closeRequested and not launchLocal and not launchNetwork and + not launchReplay: when not defined(emscripten): window.updateWindowSettings() + replayAction = ReplayBrowserResult() + retryReplaySave = false let roomNameDefault = defaultRoomName(preferences.name) if frontendState.roomName == frontendState.roomNameDefault: frontendState.roomName = roomNameDefault @@ -433,16 +422,22 @@ proc runFrontend*(app: App, connection: var Connection, sk.endUi() presentMenuFrame() return + when not defined(emscripten): + if frontendState.browsingReplays: + replayAction = sk.drawReplayBrowser(window, replayBrowser) + sk.endUi() + presentMenuFrame() + return if page == HomeMenu: case sk.drawCacHome(window, homeFocus) - of StayHome: discard - of PlaySingle: + of CacStayHome: discard + of CacPlaySingle: page = SingleMenu frontendState.localPolicies.setLen(frontendState.setup.classes.len) if frontendState.humanSeat >= frontendState.setup.classes.len: frontendState.humanSeat = -1 lobbyUi = LobbyUi() - of PlayMultiplayer: + of CacPlayMultiplayer: page = MultiplayerMenu connectRequested = preferences.server.strip().len > 0 and (activeConnection == nil or not activeConnection.client.connected) @@ -451,8 +446,13 @@ proc runFrontend*(app: App, connection: var Connection, joinRequested = true autoClaim = true lobbyUi = LobbyUi() - of OpenSettings: page = SettingsMenu - of ExitGame: + of CacOpenReplays: + when not defined(emscripten): + frontendState.browsingReplays = true + replayBrowser.refreshRequested = true + replayBrowser.message = "" + of CacOpenSettings: page = SettingsMenu + of CacExitGame: when not defined(emscripten): window.closeRequested = true if sk.playerButton(window, preferences.name): @@ -460,6 +460,8 @@ proc runFrontend*(app: App, connection: var Connection, editingPlayer = true if error.len > 0: sk.menuLabel(error, vec2(24, 24), color = LobbyRed) + when not defined(emscripten): + drawReplayRetry() sk.endUi() presentMenuFrame() return @@ -761,6 +763,12 @@ proc runFrontend*(app: App, connection: var Connection, sk.lobbyLabel(if online: "Ready is optional. The host can start anytime." else: "Clear your human slot to watch the bots.", options + vec2(0, 462), width, tint = LobbyMuted) + when not defined(emscripten): + if sk.drawReplaySaveOption( + window, options + vec2(0, 510), + app.replayPreferences.saveReplay, not modal, width + ): + app.replayPreferences.saveReplayPreferences() if online: configDirty = frontendState.setup.encodeBattleSetup() != snapshot.payload or matchName != snapshot.name @@ -896,11 +904,30 @@ proc runFrontend*(app: App, connection: var Connection, editingPlayer = true if error.len > 0: sk.lobbyLabel(error, vec2(24, 0), 1400, tint = LobbyRed) + when not defined(emscripten): + drawReplayRetry() sk.textStyle = "Default" sk.endUi() presentMenuFrame() pollEvents() waitForDisplay() + when not defined(emscripten): + if retryReplaySave: + app.retryPendingReplays() + error = app.replaySaveError + replayBrowser.refreshRequested = true + if frontendState.browsingReplays: + let selected = replayBrowser.updateReplayBrowser(Library, replayAction) + case selected.action + of BackFromReplays: + frontendState.browsingReplays = false + sk.resetInteractions() + of PlayReplay: + selection = FrontendResult(kind: ReplayFrontend, + replayPath: selected.path) + launchReplay = true + else: + discard window.onFrame = nil window.onButtonPress = nil if launchLocal: diff --git a/games/cac/homes.nim b/games/cac/homes.nim new file mode 100644 index 000000000..bc7b9da12 --- /dev/null +++ b/games/cac/homes.nim @@ -0,0 +1,67 @@ +import + bumpy, chroma, pixie, silky, vmath, windy, + polyworld/[chrome, gameuis, homes, sounds] + +type CacHomeAction* = enum + CacStayHome, CacPlaySingle, CacPlayMultiplayer, CacOpenReplays, + CacOpenSettings, CacExitGame + +proc drawCacHome*(sk: Silky, window: Window, focus: var int): CacHomeAction = + ## Draws CaC's illustrated menu with a desktop-only replay library entry. + sk.uiScale = selectedUiScale(max(0.1'f, min( + window.size.x.float32 / 760, window.size.y.float32 / 940 + )), 1080.0'f / 940) + sk.beginUi(window, window.size) + sk.textStyle = "LobbyBody" + sk.drawHomeBackground(window) + let + view = window.size.vec2 / sk.uiScale + center = view * 0.5'f + at = center - vec2(270, 280) + labels = + when defined(emscripten): + ["Single Player", "Multiplayer", "Settings"] + else: + ["Single Player", "Multiplayer", "Replays", "Settings", "Exit"] + count = labels.len + sk.drawSprite("home-shade", center - vec2(500, 440), vec2(1000, 880)) + sk.drawLabel("CARDS AND CASTERS", at - vec2(80, 21), vec2(700, 80), + rgbx(8, 16, 25, 230), "HomeTitle", CenterAlign) + sk.drawLabel("CARDS AND CASTERS", at - vec2(80, 24), vec2(700, 80), + rgbx(245, 225, 181, 255), "HomeTitle", CenterAlign) + focus = clamp(focus, 0, count - 1) + if window.buttonPressed[KeyUp]: + focus = (focus + count - 1) mod count + playSound(SelectSound) + if window.buttonPressed[KeyDown] or window.buttonPressed[KeyTab]: + focus = (focus + 1) mod count + playSound(SelectSound) + for index in 0 ..< count: + let + point = at + vec2(30, 142 + index.float32 * 80) + size = vec2(480, 76) + interaction = sk.interact(rect(point, size), true) + hovered = interaction in {Hovered, Pressed, Held, Released} + if hovered and window.mouseDelta != ivec2(0): + focus = index + sk.hoverSound(GameUiPanel(origin: point, size: size)) + let + active = hovered or focus == index + pressed = interaction in {Pressed, Held} + tint = if pressed: 205'u8 elif active: 255'u8 else: 218'u8 + inset = if pressed: vec2(2, 1) else: vec2(0) + ink = if active: rgbx(255, 240, 202, 255) + else: rgbx(225, 221, 200, 255) + skin = if index == 0: "home-button-primary" else: "home-button-secondary" + sk.drawSprite(skin, point + inset, size - inset * 2, + rgbx(tint, tint, tint, 255)) + sk.drawLabel(labels[index], point + vec2(0, 2), size, + rgbx(6, 15, 20, 235), "HomeButton", CenterAlign) + sk.drawLabel(labels[index], point, size, ink, "HomeButton", CenterAlign) + if interaction == Released or + (focus == index and window.buttonPressed[KeyEnter]): + when defined(emscripten): + result = [CacPlaySingle, CacPlayMultiplayer, CacOpenSettings][index] + else: + result = CacHomeAction(index + 1) + playSound(ClickSound) diff --git a/games/cac/modes/duel.nim b/games/cac/modes/duel.nim index dfc3be411..6c8c4182e 100644 --- a/games/cac/modes/duel.nim +++ b/games/cac/modes/duel.nim @@ -3,6 +3,7 @@ import std/[math, options, os, random, strformat, times] when defined(takeScreenshot): import std/strutils +when not defined(emscripten) or defined(takeScreenshot): import ../core/replays import opengl, pixie, silky, vmath, windy import ../core/sim, ../core/sessions, ../core/bots, ../core/eventtext @@ -10,7 +11,7 @@ import ../app, ../bench, ../ui/hud, ../scene/table, ../play, ../scene/cardrenderer, ../vfx/vfxrenderer, ../scene/post, ../scene/courtyard, ../scene/towerarena, ../ui/tuning, ../ui/matchmenu, ../ui/controls, ../replayer, ../audios -import polyworld/[characters, chrome, menus, sounds, viewers] +import polyworld/[characters, chrome, menus, player, sounds, viewers] when defined(emscripten): import ../net/web else: @@ -82,17 +83,25 @@ proc drawCardReadingView( proc runDuel*(app: App) = ## Presents a duel using public replay names when they are available. bindApp(app) + when not defined(emscripten): + app.useReplayRecording() app.setBattlefield(2) - let names = if app.replay != nil: app.replay.playerNames() else: @[] + let names = if app.replay != nil: app.replay.playerNames() + else: app.playerNames var phase = ChooseClasses game: GameState - menu: MatchMenu + menu = MatchMenu(paused: app.replay == nil and + sessionOptions.common.pauseOnStart) # Captures can replay a cast from its visual seed. - play = when defined(takeScreenshot): - initTablePlay(parseBiggestInt(getEnv("CAC_VFX_SEED", "20260909"))) - else: - initTablePlay() + play = + if captureActive(): + when defined(takeScreenshot): + initTablePlay(parseBiggestInt(getEnv("CAC_VFX_SEED", "20260909"))) + else: + initTablePlay(20260909) + else: + initTablePlay() animationTime = 0.0'f32 hudTime = 0.0'f lastFrameTime = epochTime() @@ -105,6 +114,8 @@ proc runDuel*(app: App) = uiCapturesMouse = false ## The pointer is over a tuning window. battleInputEnabled = true chooseCanceled = false ## The choose screen's button, clicked last frame. + when not defined(emscripten): + var setupMessages: seq[ReplayAction] template gamePressed(button: Button): bool = ## A press the board should react to (not one meant for a window). @@ -113,13 +124,10 @@ proc runDuel*(app: App) = proc gameSeed(): int64 = ## --seed replays one deal; otherwise every game gets a fresh one. - when defined(takeScreenshot): - result = sessionOptions.seed - else: - if sessionOptions.seedGiven: - return sessionOptions.seed - result = seedRng.rand(high(int)).int64 - echo "CaC seed ", result, " (replay with --seed ", result, ")" + if sessionOptions.seedGiven or captureActive(): + return sessionOptions.seed + result = seedRng.rand(high(int32)).int64 + echo "CaC seed ", result, " (replay with --seed ", result, ")" proc cameraPlayer(): int = if sessionOptions.human or phase == ChooseClasses: 0 @@ -157,16 +165,37 @@ proc runDuel*(app: App) = else: sources[1] = defaults[seedRng.rand(defaults.high)] botVms = loadBots(sources) + for bot in botVms: + if bot != nil: + bot.output = sessionOptions.launchBotPrinter() proc botSeat(player: int, seed: int64): Seat = ## A bot's own class and deck; an illegal deck is reported and seats ## it with none. + when not defined(emscripten): + let previous = botVms[player].onSendChat + botVms[player].onSendChat = proc(sender, target: int, + text: openArray[char]): int32 = + ## Retains admitted setup messages until the exact decks are known. + result = sendChat(sender, target, text) + if result > 0: + var message = "" + for character in text: + message.add character + setupMessages.add ReplayAction(kind: ActionMailbox, + playerId: sender.int32, target: target.int32, text: message) + defer: + botVms[player].onSendChat = previous result = botVms[player].setupSeat(PlayerCount, seed) for problem in botVms[player].deckProblems: stderr.writeLine "Player ", player + 1, " has an illegal deck: ", problem proc startDuel(seats: openArray[Seat], seed: int64) = + ## Deals the exact setup that the local replay will reproduce. game = newGame(seats, seed, recordEvents = true) + when not defined(emscripten): + play.recorder = app.beginReplayRecording(seats, seed, setupMessages) + setupMessages.setLen(0) play.resetTable() phase = PlayGame play.addOpeningHands(game, duelLayout) @@ -188,12 +217,9 @@ proc runDuel*(app: App) = phase = ChooseClasses play.statusMessage = "Bots are choosing classes..." - when defined(takeScreenshot): - var screenshotFrame = 0 + var screenshotFrame = 0 if getEnv("CAC_AUTOSTART") == "1": - game = newGame(Archer, Mage, 20260904) - phase = PlayGame - play.addOpeningHands(game, duelLayout) + startDuel([precon(Archer), precon(Mage)], 20260904) play.statusMessage = &"Player {game.currentPlayer + 1} begins." if app.replay != nil: @@ -203,6 +229,8 @@ proc runDuel*(app: App) = play.addOpeningHands(game, duelLayout) play.statusMessage = app.replay.playerName(game.currentPlayer) & " begins." + app.replay.transport.playing = not sessionOptions.common.pauseOnStart + app.replay.transport.setPlaybackSpeed(max(sessionOptions.common.speed, 1)) when defined(takeScreenshot): if getEnv("CAC_DEMO_BOARD") == "1": play.animations.setLen(0) @@ -595,8 +623,12 @@ proc runDuel*(app: App) = menu.handleEscape(window, play.pendingTargeting or play.selectedAttacker != 0) battleInputEnabled = not menuWasVisible and not menu.visible + if app.atLaunchTickLimit(): + menu.paused = true + battleInputEnabled = false + play.statusMessage = "Tick limit reached." let audible = window.focused and - not defined(takeScreenshot) and not menu.visible and not menu.paused and + not captureActive() and not menu.visible and not menu.paused and (app.replay == nil or (app.replay.transport.playing and app.replay.timeScale == 1 and app.replay.transport.targetTick < 0 and app.replay.transport.restoreTick < 0)) @@ -609,6 +641,8 @@ proc runDuel*(app: App) = dt = 0 if app.replay != nil: dt *= app.replay.timeScale + else: + dt *= max(sessionOptions.common.speed, 1).float32 when defined(cacLayoutTuning): # Provisional controls for dialing in the camera and the hands. tuner.tune(window, dt, duelTuningTargets()) @@ -643,6 +677,10 @@ proc runDuel*(app: App) = elif not menu.paused: discard play.updateBots(game, duelLayout, botVms, botClock, humanActs, dt) + if app.atLaunchTickLimit(): + menu.paused = true + battleInputEnabled = false + play.statusMessage = "Tick limit reached." for event in terminalLog.readNew(game): echo event.describe() @@ -953,7 +991,12 @@ proc runDuel*(app: App) = else: "END TURN"), canFinish): play.audio.queueSound(ClickSound) play.selectedAttacker = 0 + when not defined(emscripten): + let player = game.currentPlayer game.finishTurn() + when not defined(emscripten): + play.recordAccepted(game, ReplayAction( + kind: ActionEndTurn, playerId: player.int32)) botClock.wait = 1.2'f32 play.statusMessage = "Your opponent is thinking..." play.pendingTargeting = false @@ -1011,11 +1054,15 @@ proc runDuel*(app: App) = play.presentationIdle(game) and not play.attackActive) for cue in play.audio.takeSounds(): playSound(cue) + when not defined(emscripten): + if phase == PlayGame: + app.updateReplaySaving(game.gameOver or app.atLaunchTickLimit()) menu.draw(app) sk.endUi() sk.drawHudFaces() benchStop(Ui) benchEndFrame("duel") + var screenshotComplete = false when defined(takeScreenshot): if existsEnv("CAC_CAPTURE_SEQUENCE"): inc screenshotFrame @@ -1031,13 +1078,20 @@ proc runDuel*(app: App) = if screenshotFrame >= max(2, parseInt(getEnv("CAC_CAPTURE_FRAME", "120"))): quit(0) else: - captureScreenshot( + screenshotComplete = captureFrame( window, screenshotFrame, (if existsEnv("CAC_CAPTURE_FRAME"): max(1, parseInt(getEnv("CAC_CAPTURE_FRAME"))) elif getEnv("CAC_CAPTURE_SETTLED") == "1": 80 else: 20), appDir / "cac_shot.png" ) + else: + screenshotComplete = captureFrame( + window, screenshotFrame, 30, appDir / "cac_shot.png") + if screenshotComplete: + when not defined(emscripten): + window.closeRequested = true + return window.presentFrame(framePaceHz) if app.replay != nil: app.replay.reportFrame() @@ -1051,3 +1105,5 @@ proc runDuel*(app: App) = window.onFrame = nil window.onButtonPress = nil duelLayout = TableLayout() + when not defined(emscripten): + app.finishReplayRecording() diff --git a/games/cac/modes/headless.nim b/games/cac/modes/headless.nim index 1b37c8f6e..cd91ae24f 100644 --- a/games/cac/modes/headless.nim +++ b/games/cac/modes/headless.nim @@ -3,7 +3,7 @@ ## publishes their results and replay like the other Polyworld games. import std/[os, strutils] import jsony -import polyworld/cli +import polyworld/[cli, timings] import ../core/[sim, sessions, bots, match, replays] when defined(coworld): @@ -12,11 +12,15 @@ when defined(coworld): type HeadlessArgs* = object options*: GameOptions + playerCount*: int classNames*: seq[string] ## `--classes`, one per seat; empty without it. ConfigClasses = object classes: seq[string] +const HeadlessFlags* = {BotFlag, ReplayFlag, RecordFlag, SeedFlag, + SecondsFlag, MinutesFlag, TicksFlag, HeadlessTickRateFlag, VerboseFlag} + proc seatClasses*(names: openArray[string], seats: int): seq[Seat] = ## Parses an explicit class override with one entry per seat. Each seat ## plays its class's precon, whatever deck its script lists. @@ -58,26 +62,44 @@ proc parseHeadlessArgs*(arguments: seq[string]): HeadlessArgs = ## `--bot PATH[:COUNT]` once per group of seats (2 to 7 seats), `--seed`, ## `--ticks` (or `--seconds`, `--minutes`), `--classes archer,mage,...` ## and `--record PATH`; or `--replay PATH` to verify a recording. The - ## shared flags parse as in every Polyworld game; an error quits. + ## Shared argument errors remain catchable by callers and tests. result.options = GameOptions(seed: DefaultSessionSeed.int32, maximumTicks: DefaultDurationTicks) var index = 0 while index < arguments.len: - let argument = arguments[index] + let + argument = arguments[index] + flag = splitFlag(argument) if result.options.takeCommonFlag(arguments, index, argument): discard - elif argument == "--classes": - result.classNames = arguments.argumentValue(index, argument).split(',') - elif argument.startsWith("--classes="): - result.classNames = argument["--classes=".len .. ^1].split(',') else: - fail("unknown argument: " & argument) + case flag.name + of "--classes": + result.classNames = flagValue(arguments, index, argument).split(',') + of "--players": + result.playerCount = parsePositiveInt32( + flagValue(arguments, index, argument), flag.name).int + if result.playerCount notin PlayerCount .. MaxPlayers: + raise newException(CliError, "--players must be between " & + $PlayerCount & " and " & $MaxPlayers) + else: + raise newException(CliError, "unknown argument: " & argument) inc index + result.options.rejectUnsupportedFlags(HeadlessFlags) # No window: --player is refused, and --replay takes no bots or record. result.options.validateGameOptions(0, "") + if result.playerCount > 0 and result.options.replayPath.len == 0: + result.options.validateGameOptions(result.playerCount, + "supply one bot per seat") proc runHeadless*() = ## Plays and optionally records one bot match, or verifies a replay. + if "--help" in commandLineParams() or "-h" in commandLineParams(): + echo "Cards and Casters, headless" + echo commonUsageFor(HeadlessFlags) + echo " --players N Require N bot seats (otherwise inferred)" + echo " --classes NAMES Comma-separated class overrides, one per seat" + return let parsed = parseHeadlessArgs(commandLineParams()) options = parsed.options @@ -100,15 +122,27 @@ proc runHeadless*() = for _ in 0 ..< group.count: sources.add readFile(group.path) players.add PlayerConfig(name: group.path.extractFilename) + let bots = loadBots(sources) + if options.verbose: + echo "CaC headless seed ", options.seed, ", ", seats, + " players, maximum ", options.maximumTicks, " ticks" + for bot in bots: + bot.output = proc(event: PrintEvent) = + ## Shows BASIC output only for explicitly verbose launches. + case event.kind + of TextPrint: stdout.write(event.text) + of ValuePrint: stdout.write(event.value) + of FixedPrint: stdout.write(event.fixedValue) + of NewlinePrint: stdout.write("\n") let - bots = loadBots(sources) seated = if classOverride.len > 0: classOverride else: setupBotSeats(bots, options.seed.int64) recorder = initReplayRecorder( matchSetup(seated, options.seed, options.maximumTicks.uint32), GameConfig(players: players, seed: options.seed, - maxTicks: options.maximumTicks)) + maxTicks: options.maximumTicks, + headlessTickRate: options.headlessTickRate)) for player, bot in bots: for problem in bot.deckProblems: echo "player ", player, " illegal deck: ", problem @@ -116,7 +150,9 @@ proc runHeadless*() = options.maximumTicks.uint32, recorder) played.scriptError = proc(player: int, message: string) = echo "player ", player, " BASIC error: ", message - played.run() + var pacer = initTickPacer(options.headlessTickRate) + while played.step(): + pacer.pace() if options.recordPath.len > 0: saveReplay(options.recordPath, recorder.data) echo "Match ", played.outcomeLabel, " after ", played.tick, " ticks, ", diff --git a/games/cac/modes/multiplayer.nim b/games/cac/modes/multiplayer.nim index 6127b467a..2c7f45a7f 100644 --- a/games/cac/modes/multiplayer.nim +++ b/games/cac/modes/multiplayer.nim @@ -1,6 +1,6 @@ ## Local and network matches share Tower Arena or the multiplayer ring. import std/math -import ../core/sim, ../core/bots, ../core/eventtext, ../scene/ring +import ../core/sim, ../core/bots, ../core/eventtext, ../core/replays, ../scene/ring export ring const @@ -14,6 +14,10 @@ const type MultiplayerMatch* = object game*: GameState + initialSeats*: seq[Seat] + seed*: int64 + when not defined(emscripten): + setupMessages*: seq[ReplayAction] humanSeat*: int ## -1 when every seat is a bot and we spectate. bots*: seq[BotVm] ## One per seat; nil for the human's. @@ -29,7 +33,7 @@ proc turnNumber*(match: MultiplayerMatch): int = proc newMultiplayerMatch*(seats: openArray[Seat], humanSeat: int, seed: int64, botSources: openArray[string] = [], - botsChoose = false): MultiplayerMatch = + botsChoose = false, output: PrintProc = nil): MultiplayerMatch = ## The seats dealt by the core. The last seat standing wins. Every seat ## but the human's runs a bot script, taken from `botSources` in turn ## (repeating); with none, those seats don't act. With `botsChoose`, each @@ -43,16 +47,41 @@ proc newMultiplayerMatch*(seats: openArray[Seat], humanSeat: int, sources[seat] = botSources[next mod botSources.len] inc next result.bots = loadBots(sources) + for bot in result.bots: + if bot != nil: + bot.output = output var selected = @seats + when not defined(emscripten): + var setupMessages: seq[ReplayAction] if botsChoose: for seat in 0 ..< selected.len: if seat != humanSeat and result.bots[seat] != nil: + when not defined(emscripten): + let + bot = result.bots[seat] + previous = bot.onSendChat + bot.onSendChat = proc(sender, target: int, + text: openArray[char]): int32 = + ## Retains setup admissions until the selected decks are recorded. + result = sendChat(sender, target, text) + if result > 0: + var message = "" + for character in text: + message.add character + setupMessages.add ReplayAction(kind: ActionMailbox, + playerId: sender.int32, target: target.int32, text: message) + defer: + bot.onSendChat = previous selected[seat] = result.bots[seat].setupSeat(selected.len, seed) for problem in result.bots[seat].deckProblems: stderr.writeLine "Player ", seat + 1, " has an illegal deck: ", problem for bot in result.bots: bot.ensureSeed(seed) + result.initialSeats = selected + result.seed = seed + when not defined(emscripten): + result.setupMessages = setupMessages result.game = newGame(selected, seed, recordEvents = true) proc newMultiplayerMatch*(classes: openArray[HeroClass], humanSeat: int, @@ -130,10 +159,9 @@ when not defined(headless): ../vfx/vfxrenderer, ../scene/post, ../scene/courtyard, ../scene/towerarena, ../scene/heroes, ../ui/tuning, ../ui/matchmenu, ../ui/controls, ../audios, ../net/multiplayer as networkplay - import polyworld/[characters, chrome, connections, menus, + import polyworld/[characters, chrome, connections, menus, player, roomclients, sounds, viewers] import polyworld/rooms except Seat - import ../core/replays import ../replayer when defined(emscripten): import ../net/web @@ -230,6 +258,10 @@ when not defined(headless): ## Presents two players in Tower Arena and larger matches on the ring. ## Each human faces their own seat; spectators follow the active seat. bindApp(app) + if app.network != nil: + app.validateNetworkLaunch() + when not defined(emscripten): + app.useReplayRecording() let online = app.network != nil playerCount = @@ -248,11 +280,12 @@ when not defined(headless): previewLastFrame = epochTime() terminalLog: LogReader ## Where the terminal's printout of events is. seatRng = - if sessionOptions.seedGiven or defined(takeScreenshot): + if sessionOptions.seedGiven or captureActive(): initRand(sessionOptions.seed) else: initRand() match: MultiplayerMatch - menu: MatchMenu + menu = MatchMenu(paused: not online and app.replay == nil and + sessionOptions.common.pauseOnStart) play = initTablePlay() networkTable: TableLayout networkBlocked = false @@ -279,12 +312,18 @@ when not defined(headless): for seat in seats.mitems: seat = precon(Archer) if human.isSome: - seats[0] = human.get + seats[max(sessionOptions.common.playerSlot.int - 1, 0)] = human.get choosingClasses = false match = newMultiplayerMatch(seats, - humanSeat = if human.isSome: 0 else: -1, - seed = seatRng.rand(high(int)).int64, botSources = botSources, - botsChoose = true) + humanSeat = if human.isSome: + max(sessionOptions.common.playerSlot.int - 1, 0) else: -1, + seed = if sessionOptions.seedGiven: sessionOptions.seed + else: seatRng.rand(high(int32)).int64, + botSources = botSources, botsChoose = true, + output = sessionOptions.launchBotPrinter()) + when not defined(emscripten): + play.recorder = app.beginReplayRecording( + match.initialSeats, match.seed, match.setupMessages) botClock = initBotClock() orbit = initSeatOrbit(layout.balconies[match.viewedSeat].yaw) play.resetTable() @@ -300,6 +339,11 @@ when not defined(headless): if botSources.len == 0: botSources = defaultBotSources(appDir) if online: + for bot in app.network.bots: + if bot != nil: + bot.output = sessionOptions.launchBotPrinter() + when not defined(emscripten): + app.useReplayRecording(app.network.recorder) app.network.automaticBots = false choosingClasses = false match = MultiplayerMatch(game: app.network.game, @@ -332,12 +376,18 @@ when not defined(headless): elif app.configuredSeats.len > 0: choosingClasses = false let seed = if sessionOptions.seedGiven: sessionOptions.seed - else: seatRng.rand(high(int)).int64 + else: seatRng.rand(high(int32)).int64 match = MultiplayerMatch( game: newGame(app.configuredSeats, seed, recordEvents = true), + initialSeats: app.configuredSeats, + seed: seed, humanSeat: app.configuredHumanSeat, bots: loadBots(app.configuredBotSources)) + when not defined(emscripten): + play.recorder = app.beginReplayRecording(match.initialSeats, seed) for bot in match.bots: + if bot != nil: + bot.output = sessionOptions.launchBotPrinter() bot.ensureSeed(seed) orbit = initSeatOrbit(layout.balconies[match.viewedSeat].yaw) play.statusMessage = match.turnStatus(names) @@ -358,9 +408,10 @@ when not defined(headless): play.resetTable() play.statusMessage = app.replay.playerName(match.current) & " begins." + app.replay.transport.playing = not sessionOptions.common.pauseOnStart + app.replay.transport.setPlaybackSpeed(max(sessionOptions.common.speed, 1)) openingDraw = true - when defined(takeScreenshot): - var previewScreenshotFrame = 0 + var previewScreenshotFrame = 0 when defined(cacLayoutTuning): # The duel's layout keys: the viewed seat's hand is the player's one # and every other balcony's is an opponent's. Enter prints a row. @@ -394,7 +445,11 @@ when not defined(headless): menu.handleEscape(window, play.pendingTargeting or play.selectedAttacker != 0) battleInputEnabled = not menuWasVisible and not menu.visible - let audible = window.focused and not defined(takeScreenshot) and + if app.atLaunchTickLimit(): + menu.paused = true + battleInputEnabled = false + play.statusMessage = "Tick limit reached." + let audible = window.focused and not captureActive() and not menu.visible and not menu.paused and (app.replay == nil or (app.replay.transport.playing and app.replay.timeScale == 1 and app.replay.transport.targetTick < 0 and @@ -412,6 +467,8 @@ when not defined(headless): previewDt = 0 if app.replay != nil: previewDt *= app.replay.timeScale + elif not online: + previewDt *= max(sessionOptions.common.speed, 1).float32 previewTime += previewDt play.animations.advanceAnimations(previewDt) play.discardFlights.advanceAnimations(previewDt) @@ -530,9 +587,22 @@ when not defined(headless): turnPassed() if botClock.scriptFailed: play.statusMessage = message - if play.presentationIdle(match.game) and not play.attackActive and - match.skipDeadTurn(): - turnPassed() + if app.atLaunchTickLimit(): + menu.paused = true + battleInputEnabled = false + play.statusMessage = "Tick limit reached." + if not menu.paused and play.presentationIdle(match.game) and + not play.attackActive and + not match.game.gameOver and not match.game.waitingChoice and + match.game.dead(match.current): + when not defined(emscripten): + let player = match.current + let passed = match.skipDeadTurn() + when not defined(emscripten): + play.recordAccepted(match.game, ReplayAction( + kind: ActionEndTurn, playerId: player.int32)) + if passed: + turnPassed() for event in terminalLog.readNew(match.game): echo event.describe(names) orbit.advance(previewDt) @@ -933,8 +1003,15 @@ when not defined(headless): if online: discard app.network.submitAction(ReplayAction( kind: ActionEndTurn, playerId: match.humanSeat.int32)) - elif match.endTurn(): - turnPassed() + else: + when not defined(emscripten): + let player = match.current + let passed = match.endTurn() + when not defined(emscripten): + play.recordAccepted(match.game, ReplayAction( + kind: ActionEndTurn, playerId: player.int32)) + if passed: + turnPassed() when defined(emscripten): # The same summary as the duel's, one line per seat. var summary = &"Multiplayer match: {layout.playerCount} players. " & @@ -975,15 +1052,22 @@ when not defined(headless): play.presentationIdle(match.game) and not play.attackActive) for cue in play.audio.takeSounds(): playSound(cue) + when not defined(emscripten): + if not choosingClasses: + app.updateReplaySaving(match.game.gameOver or app.atLaunchTickLimit() or + (online and app.network.finished)) menu.draw(app) sk.endUi() sk.drawHudFaces() benchStop(Ui) benchEndFrame("multiplayer " & $layout.playerCount) - when defined(takeScreenshot): - captureScreenshot(window, previewScreenshotFrame, - max(1, parseInt(getEnv("CAC_CAPTURE_FRAME", "20"))), - appDir / &"cac_multiplayer_{layout.playerCount}.png") + if captureFrame(window, previewScreenshotFrame, + (when defined(takeScreenshot): + max(1, parseInt(getEnv("CAC_CAPTURE_FRAME", "20"))) + else: 30), appDir / ("cac_multiplayer_" & $layout.playerCount & ".png")): + when not defined(emscripten): + window.closeRequested = true + return window.presentFrame(framePaceHz) if app.replay != nil: app.replay.reportFrame() @@ -999,3 +1083,5 @@ when not defined(headless): if online: app.network.onAction = nil networkTable = TableLayout() + when not defined(emscripten): + app.finishReplayRecording() diff --git a/games/cac/play.md b/games/cac/play.md index b1d401513..ca0e4c56f 100644 --- a/games/cac/play.md +++ b/games/cac/play.md @@ -71,7 +71,7 @@ Give these to your human; they open a window: ```sh nim c cac.nim -./cac --human --bot my.bas # play against the bot +./cac --player --bot my.bas # play against the bot ./cac --replay m.replay # watch a recorded match ``` diff --git a/games/cac/play.nim b/games/cac/play.nim index 621b64bac..fab332f83 100644 --- a/games/cac/play.nim +++ b/games/cac/play.nim @@ -76,6 +76,10 @@ type submitAction*: proc(action: ReplayAction): bool ## Queues a human action for a network match instead of changing its ## confirmed game state. Nil keeps local play immediate. + recorder*: ReplayRecorder + ## Captures completed local actions; network and replay tables leave it nil. + pendingReplayAction: ReplayAction + ## Keeps a permanent's original hand index until its targets are settled. pendingTargeting*: bool pendingCardIndex*: int pendingSourceId*: int @@ -182,6 +186,20 @@ proc initTablePlay*(): TablePlay = TablePlay(pendingCardIndex: -1, attackTarget: Canceled, attackForward: true, visualRng: initRand()) +proc recordAccepted*(play: var TablePlay, game: GameState, + action: ReplayAction) = + ## Records one completed local action and its resulting canonical state. + if play.recorder == nil: + return + if play.recorder.data.hashes.len >= MaxReplayHashes or + play.recorder.data.actions.len >= MaxReplayActions: + raise newException(ReplayError, "The replay recording is full.") + var recorded = action + recorded.tick = play.recorder.data.hashes.len.uint32 + 1 + let hash = game.stateHash() + play.recorder.record(recorded) + play.recorder.recordHash(hash) + proc silenceAudioThrough*(play: var TablePlay, game: GameState) = ## Silences queued history without discarding its visual presentation. play.silentThroughBeat = max(play.silentThroughBeat, game.visualBeat) @@ -583,6 +601,7 @@ proc resetTable*(play: var TablePlay) = play = TablePlay( audio: TableAudio(silent: play.audio.silent), submitAction: play.submitAction, + recorder: play.recorder, pendingCardIndex: -1, attackTarget: Canceled, attackForward: true, @@ -708,6 +727,7 @@ proc playHandCard*( ## all targets are chosen. True when the play was accepted, so the hand ## stops hovering that card while its action is being resolved. let + actingPlayer = game.currentPlayer player = game.players[game.currentPlayer] card = player.hand[handIndex] if game.playCost(game.currentPlayer, card) > player.energy: @@ -790,6 +810,8 @@ proc playHandCard*( ) play.pendingCard = card play.pendingCardIndex = -1 + play.pendingReplayAction = ReplayAction(kind: ActionPlayCard, + playerId: actingPlayer.int32, handIndex: handIndex.int32) play.pendingSourceId = minionId play.pendingPicks.setLen(0) play.pendingChoices = game.availableChoices(card) @@ -807,6 +829,8 @@ proc playHandCard*( else: play.pendingCard = card play.pendingCardIndex = handIndex + play.pendingReplayAction = ReplayAction(kind: ActionPlayCard, + playerId: actingPlayer.int32, handIndex: handIndex.int32) play.pendingSourceId = 0 play.pendingPicks.setLen(0) play.pendingChoices = game.availableChoices(handIndex) @@ -855,6 +879,10 @@ proc playHandCard*( game.currentPlayer, sourcePose) play.statusMessage = &"{card.name} resolves." result = true + if result and play.submitAction == nil and not play.pendingTargeting: + play.recordAccepted(game, ReplayAction(kind: ActionPlayCard, + playerId: actingPlayer.int32, handIndex: handIndex.int32, + choices: @[NoTarget].toReplay)) proc updateTossPicking*( play: var TablePlay, @@ -891,8 +919,15 @@ proc updateTossPicking*( if submitted: &"{pending.source}: discard submitted." else: "Those discards could not be submitted." else: + let accepted = game.resolvePendingToss(picks) + if accepted: + var indices: seq[int32] + for index in picks: + indices.add index.int32 + play.recordAccepted(game, ReplayAction(kind: ActionToss, + playerId: pending.player.int32, indices: indices)) play.statusMessage = - if game.resolvePendingToss(picks): &"{pending.source}: discarded." + if accepted: &"{pending.source}: discarded." else: "Those cards can't be discarded." proc pendingRules(play: TablePlay, game: GameState): Rules = @@ -981,6 +1016,7 @@ proc takePick*( )[play.pendingCardIndex] let triggerName = game.waitingTriggerName() + actingPlayer = game.actingPlayer() resolved = if play.pendingTrigger: game.resolvePendingTrigger(picks) @@ -993,6 +1029,16 @@ proc takePick*( play.holdCastSpell(layout, card.pickedFace(picks, board), spellClass, game.currentPlayer, spellSourcePose) if resolved: + var action = + if play.pendingTrigger: + ReplayAction(kind: ActionResolveTrigger, playerId: actingPlayer.int32) + elif play.pendingReplayAction.kind == ActionPlayCard: + play.pendingReplayAction + else: + ReplayAction(kind: ActionPlayCard, playerId: actingPlayer.int32, + handIndex: play.pendingCardIndex.int32) + action.choices = picks.toReplay + play.recordAccepted(game, action) play.statusMessage = if play.pendingTrigger: &"{triggerName} resolves." @@ -1006,6 +1052,7 @@ proc takePick*( else: play.statusMessage = &"{card.name} could not resolve." play.pendingTargeting = false + play.pendingReplayAction = ReplayAction() play.pendingTrigger = false play.pendingCardIndex = -1 play.pendingPreview = none(GameState) @@ -1039,8 +1086,14 @@ proc updateChoosing*( return if cancel: play.audio.queueSound(CancelSound) + if play.pendingCard.kind != Spell and play.submitAction == nil: + if game.finishPlay(play.pendingCard, @[NoTarget], play.pendingSourceId): + var action = play.pendingReplayAction + action.choices = @[NoTarget].toReplay + play.recordAccepted(game, action) play.statusMessage = &"{play.pendingCard.name} canceled." play.pendingTargeting = false + play.pendingReplayAction = ReplayAction() play.pendingCardIndex = -1 play.pendingPreview = none(GameState) play.pendingPicks.setLen(0) @@ -1086,12 +1139,16 @@ proc updateTargeting*( if submitted: &"{card.name} submitted without a target." else: &"{card.name} could not be submitted." else: - discard game.finishPlay(card, @[NoTarget], play.pendingSourceId) + if game.finishPlay(card, @[NoTarget], play.pendingSourceId): + var action = play.pendingReplayAction + action.choices = @[NoTarget].toReplay + play.recordAccepted(game, action) play.statusMessage = &"{card.name}'s rule finishes without a target." else: play.statusMessage = &"{card.name} canceled." play.pendingTargeting = false + play.pendingReplayAction = ReplayAction() play.pendingCardIndex = -1 play.pendingPreview = none(GameState) play.pendingPicks.setLen(0) @@ -1109,6 +1166,7 @@ proc updateTargeting*( proc stopTargeting*(play: var TablePlay) = play.pendingTargeting = false + play.pendingReplayAction = ReplayAction() play.pendingCardIndex = -1 play.pendingPreview = none(GameState) play.choosePicked = none(int) @@ -1171,8 +1229,13 @@ proc advanceAttack*(play: var TablePlay, game: var GameState, if play.attackForward: if play.attackElapsed >= AttackLungeDuration: if not play.attackDamageApplied: - discard game.attack(play.attackSteps[play.attackIndex], - play.attackTarget) + let + player = game.currentPlayer + attacker = play.attackSteps[play.attackIndex] + if game.attack(attacker, play.attackTarget): + play.recordAccepted(game, ReplayAction(kind: ActionAttack, + playerId: player.int32, attacker: attacker.int32, + choices: @[play.attackTarget].toReplay)) play.attackDamageApplied = true play.attackForward = false play.attackElapsed = 0 @@ -2023,7 +2086,22 @@ proc updateBots*( let name = if botName.isNil: "Bot" else: botName(player) let before = game.copyGameState() clock.scriptFailed = false - let decision = vm.runDecision(game, apply = false) + let + previousChat = vm.onSendChat + recorder = play.recorder + if recorder != nil: + vm.onSendChat = proc(sender, target: int, + text: openArray[char]): int32 = + ## Records local mailbox admission before the selected action. + result = sendChat(sender, target, text) + if result > 0: + recorder.recordMailbox(recorder.data.hashes.len.uint32, + sender, target, text) + var decision: BotDecision + try: + decision = vm.runDecision(game, apply = false) + finally: + vm.onSendChat = previousChat case decision of BotAttacked: play.startAttack(game, layout, @[vm.action.attacker.int], @@ -2031,6 +2109,7 @@ proc updateBots*( play.statusMessage = name & " is attacking..." of BotPlayedCard, BotResolvedTrigger, BotTossed, BotEndedTurn: if game.applyAction(vm.action): + play.recordAccepted(game, vm.action) play.addActionArrows(layout, before, game, vm.action) play.animateTransition(layout, before, game, vm.action.choices.toChoices) diff --git a/games/cac/replaylibraries.nim b/games/cac/replaylibraries.nim new file mode 100644 index 000000000..85c5bf6db --- /dev/null +++ b/games/cac/replaylibraries.nim @@ -0,0 +1,46 @@ +import polyworld/replaylibraries as sharedLibraries +import core/replays + +export sharedLibraries.ReplayEntry + +proc replayTicks(bytes: string): int = + ## Validates this game's complete payload before marking a file playable. + decodeReplay(bytes).hashes.len + +const Library* = ReplayLibrary( + gameFolder: "Cards and Casters", + gamePrefix: "CaC", + format: ReplayLibraryFormat( + game: ReplayGame, + gameVersion: ReplayGameVersion, + tapeVersion: ReplayFormatVersion, + maxBytes: DefaultMaxReplayBytes + ), + inspect: replayTicks +) + +proc replayDirectory*(): string = + ## Returns this game's replay folder in the current user's application data. + sharedLibraries.replayDirectory(Library) + +proc ensureReplayDirectory*(directory = replayDirectory()): string = + ## Creates and returns the library directory without relying on the game path. + sharedLibraries.ensureReplayDirectory(Library, directory) + +proc inspectReplay*(path: string): ReplayEntry = + ## Describes a valid, incompatible, or unreadable CaC recording. + sharedLibraries.inspectReplay(Library, path) + +proc listReplays*(directory = replayDirectory()): seq[ReplayEntry] = + ## Lists this game's recordings with newest files first. + sharedLibraries.listReplays(Library, directory) + +proc saveLibraryReplay*( + data: ReplayData, directory = replayDirectory() +): string = + ## Validates and saves the complete match under a unique library filename. + sharedLibraries.saveLibraryReplay(Library, encodeReplay(data), directory) + +proc importReplay*(source: string, directory = replayDirectory()): string = + ## Copies a CaC recording, preserving unsupported versions and the source. + sharedLibraries.importReplay(Library, source, directory) diff --git a/games/cac/replaymenus.nim b/games/cac/replaymenus.nim new file mode 100644 index 000000000..e2003e1aa --- /dev/null +++ b/games/cac/replaymenus.nim @@ -0,0 +1,24 @@ +import + silky, windy, + polyworld/replaymenus as sharedReplayMenus, + core/replays, replaylibraries + +export sharedReplayMenus except drawReplayBrowser + +proc drawReplayBrowser*( + sk: Silky, window: Window, ui: var ReplayBrowserUi, + entries: openArray[ReplayEntry], folder: string, message = "" +): ReplayBrowserResult = + ## Shows CaC recordings by accepted action count rather than elapsed time. + sharedReplayMenus.drawReplayBrowser( + sk, window, ui, entries, folder, ReplayGameVersion, 1, message, + lengthDisplay = ReplayActionCount + ) + +proc drawReplayBrowser*( + sk: Silky, window: Window, browser: var ReplayBrowserState +): ReplayBrowserResult = + ## Supplies CaC's action-count metadata to the shared library controller. + sharedReplayMenus.drawReplayBrowser( + sk, window, browser, ReplayGameVersion, 1, ReplayActionCount + ) diff --git a/games/cac/replaysettings.nim b/games/cac/replaysettings.nim new file mode 100644 index 000000000..e0139e6c5 --- /dev/null +++ b/games/cac/replaysettings.nim @@ -0,0 +1,11 @@ +import polyworld/replaysettings as sharedSettings + +export sharedSettings.ReplayPreferences + +proc readReplayPreferences*(): ReplayPreferences = + ## Reads CaC's recording choice from its existing device configuration. + sharedSettings.readReplayPreferences("Polyworld CaC") + +proc saveReplayPreferences*(preferences: ReplayPreferences) = + ## Saves CaC's recording choice separately from shared match settings. + sharedSettings.saveReplayPreferences(preferences, "Polyworld CaC") diff --git a/games/cac/tests/test_base.nim b/games/cac/tests/test_base.nim index 652bbe7b4..bcedac55c 100644 --- a/games/cac/tests/test_base.nim +++ b/games/cac/tests/test_base.nim @@ -40,12 +40,17 @@ block: echo "The reference players play alike and differ only in their setup" block: - proc play(source: string): string = - ## The script without its title and its setup. + proc play(source: string): seq[string] = + ## Compare the script lines outside the title and opening setup block. let - start = source.find("IF selectingClass THEN") - finish = source.find("END IF\n", start) + "END IF\n".len - source[source.find("'\n") ..< start] & source[finish .. ^1] + lines = source.splitLines() + titleEnd = lines.find("'") + start = lines.find("IF selectingClass THEN") + finish = lines.find("END IF") + doAssert titleEnd > 0, "Missing separator after reference bot title" + doAssert start > titleEnd, "Missing reference bot setup after the title" + doAssert finish > start, "Missing END IF for reference bot setup" + lines[titleEnd ..< start] & lines[finish + 1 .. ^1] for bot in ReferenceBots: doAssert bot.play == ArcherBot.play diff --git a/games/cac/tests/test_coworld.nim b/games/cac/tests/test_coworld.nim index 170df4b54..10abc2ccf 100644 --- a/games/cac/tests/test_coworld.nim +++ b/games/cac/tests/test_coworld.nim @@ -186,6 +186,21 @@ suite "headless runner flags": @["archer", "mage"] check parseHeadlessArgs(@["--classes=warrior,mage,archer"]).classNames == @["warrior", "mage", "archer"] + check parseHeadlessArgs(@["--classes:warrior,mage"]).classNames == + @["warrior", "mage"] + + test "explicit roster size, pacing, and unsupported flags are validated": + let parsed = parseHeadlessArgs(@[ + "--bots=a.bas:3", "--players:3", "--headless-tick-rate", "24"]) + check parsed.playerCount == 3 + check parsed.options.botGroups.botCount == 3 + check parsed.options.headlessTickRate == 24 + for args in [@["--players=3", "--bot=a.bas:2"], + @["--player"], @["--speed=2"], @["--play=false"], + @["--windowSize=800x600"], @["--llm-mode=barrier"], + @["--server=ws://localhost:9911/ws"]]: + expect ValueError: + discard parseHeadlessArgs(args) test "--record and --replay": let recorded = parseHeadlessArgs(@["--bot", "a.bas:2", "--record", @@ -204,17 +219,17 @@ suite "browser and replay viewer flags": "/episode.replay" check parseSessionOptions([]).replayPath == "" - test "the browser's URL parameters become session flags": - # webinputs.js: replay=URL, bot=URL, seed=N; web/inputs.js: human=1, - # players=N. - let options = parseSessionOptions(["--replay", "/web/replay.replay", - "--bot", "/web/bot0/archer.bas", "--bot", "/web/bot1/mage.bas", - "--seed", "-42", "--human", "true", "--players", "4"]) - check options.replayPath == "/web/replay.replay" - check options.botPaths == @["/web/bot0/archer.bas", "/web/bot1/mage.bas"] + test "the browser's URL parameters become canonical session flags": + # Replay input is a separate launch from seed and bot configuration. + let options = parseSessionOptions([ + "--bot", "/web/bot0/archer.bas:2", "--bot", "/web/bot1/mage.bas", + "--seed", "-42", "--players", "3"]) + check options.replayPath == "" + check options.botPaths == @["/web/bot0/archer.bas", + "/web/bot0/archer.bas", "/web/bot1/mage.bas"] check options.seed == -42 - check options.human - check options.playerCount == 4 + check not options.human + check options.playerCount == 3 let inputs = readFile(currentSourcePath().parentDir.parentDir / "web/inputs.js") check "\"class\"" notin inputs diff --git a/games/cac/tests/test_hero_select.cjs b/games/cac/tests/test_hero_select.cjs index fcf25ea68..71c7f225f 100644 --- a/games/cac/tests/test_hero_select.cjs +++ b/games/cac/tests/test_hero_select.cjs @@ -115,7 +115,7 @@ function choicePoint(viewport, index, target = 'hero') { async function humanChoice({name, index, target = 'hero', players = 2, viewport = {width: 1440, height: 900}, density = 1, outside = false, animate = false}) { const page = await createPage(viewport, density); - await page.goto(`${base}/cac.html?human=1&players=${players}&seed=42`, {waitUntil: 'domcontentloaded'}); + await page.goto(`${base}/cac.html?player=1&players=${players}&seed=42`, {waitUntil: 'domcontentloaded'}); await waitStatus(page, /Choose your (class|hero)/); await page.locator('#loading').waitFor({state: 'hidden', timeout: 30000}); assert.match(await status(page), /Human player/); diff --git a/games/cac/tests/test_multiplayer.nim b/games/cac/tests/test_multiplayer.nim index e2ab43731..b04e39dfc 100644 --- a/games/cac/tests/test_multiplayer.nim +++ b/games/cac/tests/test_multiplayer.nim @@ -1014,3 +1014,27 @@ block: doAssert (match.game.players[seat].hand & match.game.players[seat].deck). countIt(it.name == "Bear") == 4 doAssert match.bots[0] == nil + +echo "Selected human slots preserve bot order and verbose setup output" +block: + var output = "" + let match = newMultiplayerMatch( + @[precon(Warrior), precon(Warrior), precon(Warrior)], + humanSeat = 1, + seed = 90210, + botSources = @[ + "if selectingClass then\nprint \"first\"\npickClass(0)\n" & + "deckCard(\"Archer\", 40)\nend\nend if\nendTurn()", + "if selectingClass then\nprint \"last\"\npickClass(2)\n" & + "deckCard(\"Mage\", 40)\nend\nend if\nendTurn()"], + botsChoose = true, + output = proc(event: PrintEvent) = + ## Retains setup output without initializing a terminal or viewer. + if event.kind == TextPrint: + output.add event.text) + doAssert match.seed == 90210 + doAssert match.humanSeat == 1 and match.bots[1] == nil + doAssert match.game.players[0].heroClass == Archer + doAssert match.game.players[1].heroClass == Warrior + doAssert match.game.players[2].heroClass == Mage + doAssert output == "firstlast" diff --git a/games/cac/tests/test_recording_library.nim b/games/cac/tests/test_recording_library.nim new file mode 100644 index 000000000..2cd225478 --- /dev/null +++ b/games/cac/tests/test_recording_library.nim @@ -0,0 +1,216 @@ +import + std/[os, strutils, tempfiles], + ../app, ../core/[replays, sim], ../modes/multiplayer, ../replaylibraries +from polyworld/cli import CliError, TicksFlag + +proc verify(data: ReplayData) = + ## Replays every saved action and requires its canonical fingerprint. + data.validate() + var + game = newGame(data.header.setup) + cursor = initReplayCursor(data) + tick = 0'u32 + data.applyReplayMailboxes(cursor, tick) + while tick < data.hashes.len.uint32: + var action: ReplayAction + doAssert data.takeReplayAction(cursor, tick, action) + doAssert game.applyAction(action) + tick = action.tick + doAssert game.stateHash() == data.hashes[tick.int - 1] + data.applyReplayMailboxes(cursor, tick) + +proc testLibraryRecording() = + ## Checks real saves, deduplication, opt-out, and failed-save recovery. + const DataVariable = when defined(windows): "APPDATA" else: "XDG_DATA_HOME" + let + directory = createTempDir("cac-recording-library-", "") + hadData = existsEnv(DataVariable) + previousData = getEnv(DataVariable) + putEnv(DataVariable, directory) + defer: + if hadData: + putEnv(DataVariable, previousData) + else: + delEnv(DataVariable) + removeDir(directory) + let + library = replayDirectory() + app = App(replayPreferences: ReplayPreferences(saveReplay: true), + playerNames: @["Alice", "Bob"]) + seats = @[precon(Archer), precon(Mage)] + recorder = app.beginReplayRecording(seats, 2026) + doAssert library.startsWith(directory) + doAssert recorder != nil + doAssert recorder.data.config.players[0].name == "Alice" + var game = newGame(seats, 2026) + for tick in 1'u32 .. 3'u32: + let action = ReplayAction(kind: ActionEndTurn, tick: tick, + playerId: game.currentPlayer.int32) + doAssert game.applyAction(action) + recorder.record(action) + recorder.recordHash(game.stateHash()) + app.updateReplaySaving(completed = true) + doAssert app.replaySaveError.len == 0 + let entries = listReplays() + doAssert entries.len == 1 and entries[0].playable + let completed = loadReplay(entries[0].path) + completed.verify() + doAssert completed.hashes.len == 3 + app.finishReplayRecording() + doAssert listReplays().len == 1, + "Completion and exit must not duplicate the same recording." + discard app.saveCurrentReplay() + doAssert listReplays().len == 1 + + discard app.beginReplayRecording(seats, 77) + app.finishReplayRecording() + doAssert listReplays().len == 2, + "Leaving a live match must save its completed action prefix." + + app.replayPreferences.saveReplay = false + discard app.beginReplayRecording(seats, 78) + app.updateReplaySaving(completed = true) + app.finishReplayRecording() + doAssert listReplays().len == 2 + discard app.saveCurrentReplay() + doAssert listReplays().len == 3, + "Manual saves remain available when automatic saving is disabled." + + let blocked = directory / "blocked" + writeFile(blocked, "Not a directory") + putEnv(DataVariable, blocked) + app.replayPreferences.saveReplay = true + discard app.beginReplayRecording(seats, 79) + app.finishReplayRecording() + doAssert app.replaySaveError.len > 0 + doAssert app.unsavedReplays.len == 1 + app.unsavedReplays[0].verify() + app.retryPendingReplays() + doAssert app.unsavedReplays.len == 1, + "A failed retry must keep its original recording." + putEnv(DataVariable, directory) + app.retryPendingReplays() + doAssert app.unsavedReplays.len == 0 + doAssert app.replaySaveError.len == 0 + doAssert listReplays().len == 4 + + doAssert app.beginReplayRecording(seats, high(int64)) == nil + doAssert "seed" in app.replaySaveError.toLowerAscii() + doAssert listReplays().len == 4, + "Unsupported seeds must never produce a divergent recording." + + const SetupChat = """ +IF selectingClass THEN + sent = sendChat(-2, "Setup message") + pickClass(0) + deckCard("Archer", 40) + END +END IF +endTurn() +END +""" + let prepared = newMultiplayerMatch(seats, -1, 80, @[SetupChat], + botsChoose = true) + doAssert prepared.setupMessages.len == 2 + let setupRecorder = app.beginReplayRecording( + prepared.initialSeats, prepared.seed, prepared.setupMessages) + doAssert setupRecorder.data.hashes.len == 0 + doAssert setupRecorder.data.actions.len == 2 + doAssert setupRecorder.data.actions[0].tick == 0 + doAssert setupRecorder.data.actions[0].playerId == 0 + doAssert setupRecorder.data.actions[1].playerId == 1 + setupRecorder.data.encodeReplay().decodeReplay().verify() + +proc testManualSaveRecovery() = + ## Retains a failed manual save when the automatic-save preference is off. + const DataVariable = when defined(windows): "APPDATA" else: "XDG_DATA_HOME" + let + directory = createTempDir("cac-manual-replay-", "") + hadData = existsEnv(DataVariable) + previousData = getEnv(DataVariable) + blocked = directory / "blocked" + app = App(replayPreferences: ReplayPreferences(saveReplay: false)) + defer: + if hadData: + putEnv(DataVariable, previousData) + else: + delEnv(DataVariable) + removeDir(directory) + writeFile(blocked, "Not a directory") + putEnv(DataVariable, blocked) + discard app.beginReplayRecording(@[precon(Archer), precon(Mage)], 91) + var rejected = false + try: + discard app.saveCurrentReplay() + except ReplayError: + rejected = true + doAssert rejected + app.finishReplayRecording() + doAssert app.unsavedReplays.len == 1, + "A failed manual save must survive leaving a match with autosave off." + putEnv(DataVariable, directory) + app.retryPendingReplays() + doAssert app.unsavedReplays.len == 0 + doAssert app.replaySaveError.len == 0 + doAssert listReplays().len == 1 + +proc testExplicitRecording() = + ## Writes the requested file even with autosave off and honors its action cap. + let + directory = createTempDir("cac-explicit-replay-", "") + target = directory / "chosen replay.cacreplay" + app = App(replayPreferences: ReplayPreferences(saveReplay: false), + playerNames: @["Alice", "Bob"]) + seats = @[precon(Archer), precon(Mage)] + defer: + removeDir(directory) + app.options.common.recordPath = target + app.options.common.maximumTicks = 1 + let recorder = app.beginReplayRecording(seats, 2026) + doAssert recorder.data.header.setup.maximumTicks == 1 + doAssert recorder.data.config.maxTicks == 1 + doAssert not app.atLaunchTickLimit() + var game = newGame(seats, 2026) + let action = ReplayAction(kind: ActionEndTurn, tick: 1, + playerId: game.currentPlayer.int32) + doAssert game.applyAction(action) + recorder.record(action) + recorder.recordHash(game.stateHash()) + doAssert app.atLaunchTickLimit() + app.updateReplaySaving(completed = true) + doAssert fileExists(target) + let saved = readFile(target) + saved.decodeReplay().verify() + app.finishReplayRecording() + doAssert readFile(target) == saved + discard app.beginReplayRecording(seats, 77) + app.finishReplayRecording() + doAssert loadReplay(target).config.seed == 77 + app.options.common.recordPath = target / "replay.cacreplay" + discard app.beginReplayRecording(seats, 78) + var rejected = false + try: + app.finishReplayRecording() + except CatchableError: + rejected = true + doAssert rejected, "An explicit CLI save must report a failed write." + +proc testNetworkLaunchControls() = + ## Refuses local duration limits before a room-backed match starts. + let app = App() + app.options.common.speed = 1 + app.validateNetworkLaunch() + app.options.common.maximumTicks = 5 + app.options.common.specifiedFlags.incl TicksFlag + var rejected = false + try: + app.validateNetworkLaunch() + except CliError: + rejected = true + doAssert rejected + +testLibraryRecording() +testManualSaveRecovery() +testExplicitRecording() +testNetworkLaunchControls() +echo "CaC library save, deduplication, opt-out, and recovery tests passed." diff --git a/games/cac/tests/test_recording_play.nim b/games/cac/tests/test_recording_play.nim new file mode 100644 index 000000000..363b3aaed --- /dev/null +++ b/games/cac/tests/test_recording_play.nim @@ -0,0 +1,237 @@ +import + std/[options, sequtils], + vmath, + ../play, ../core/[bots, replays, sim], ../scene/table + +proc poses(player, count: int): seq[CardPose] = + ## Supplies a neutral table for exercising input without a renderer. + for _ in 0 ..< count: + result.add CardPose() + +proc origin(player: int): CardPose = + ## Places every single-card anchor at the test table's origin. + CardPose() + +proc feet(player: int): Vec3 = + ## Keeps opposing hero targets distinct for attack presentation. + vec3(player.float32 * 5, 0, 0) + +proc shown(player: int): bool = + ## Makes every test seat's hand visible. + true + +proc flatTable(): TableLayout = + ## Provides the public table interface without a graphics context. + TableLayout(handPoses: poses, boardPoses: poses, deckPose: origin, + discardPose: origin, spellPose: origin, heroPosition: feet, + handVisible: shown) + +proc fixture(card: string, heroClass: HeroClass, + players = 2): tuple[play: TablePlay, game: GameState] = + ## Deals repeatable base-card decks so actions remain legal on replay. + var seats: seq[Seat] + for player in 0 ..< players: + seats.add Seat(heroClass: heroClass, + deck: @[(card, 30)]) + result.game = newGame(seats, 35, recordEvents = true) + result.play = initTablePlay(1) + result.play.recorder = initReplayRecorder(matchSetup(seats, 35, 1000), + GameConfig(seed: 35, maxTicks: 1000, players: unnamedPlayers(players))) + +proc endTurn(play: var TablePlay, game: var GameState) = + ## Records the same direct end-turn operation used by graphical modes. + let player = game.currentPlayer + doAssert not game.waitingChoice and not game.gameOver + game.finishTurn() + play.recordAccepted(game, + ReplayAction(kind: ActionEndTurn, playerId: player.int32)) + +proc readyFor(play: var TablePlay, game: var GameState, cost: int, + player = 0) = + ## Waits through legal recorded turns until a seat can play its card. + while game.currentPlayer != player or game.players[player].energy < cost: + doAssert game.turnNumber < 30 + play.endTurn(game) + +proc verify(play: TablePlay, expected: GameState) = + ## Decodes and replays every admitted command, checking each state hash. + let data = play.recorder.data.encodeReplay().decodeReplay() + var + replay = newGame(data.header.setup) + cursor = data.initReplayCursor() + action: ReplayAction + tick = 0'u32 + while data.takeReplayAction(cursor, tick, action): + doAssert replay.applyAction(action), "Recorded action must remain legal." + discard replay.takeVisualEvents() + doAssert replay.stateHash() == data.hashes[action.tick.int - 1], + "Replay diverged at action " & $action.tick + tick = action.tick + doAssert cursor.actionIndex == data.actions.len + doAssert replay.stateHash() == expected.stateHash() + +proc testLocalActions() = + ## Covers human cards, pending targeting, and delayed attack admission. + for players in [2, 7]: + var (play, game) = fixture("Sharpshooter", Archer, players) + play.readyFor(game, 3) + let before = play.recorder.data.hashes.len + doAssert play.playHandCard(game, flatTable(), 0) + doAssert play.pendingTargeting + doAssert play.recorder.data.hashes.len == before, + "A permanent is recorded only after its pending choices finish." + discard play.recorder.data.encodeReplay() + play.takePick(game, flatTable(), heroChoice(1)) + doAssert play.recorder.data.hashes.len == before + 1 + doAssert play.recorder.data.actions[^1].handIndex == 0 + play.verify(game) + + let attacker = game.players[0].board[0].id + play.endTurn(game) + play.readyFor(game, 0) + let attackTick = play.recorder.data.hashes.len + play.startAttack(game, flatTable(), @[attacker], heroChoice(1)) + doAssert play.recorder.data.hashes.len == attackTick + discard play.advanceAttack(game, AttackLungeDuration * 0.5'f) + doAssert play.recorder.data.hashes.len == attackTick + discard play.advanceAttack(game, AttackLungeDuration) + doAssert play.recorder.data.hashes.len == attackTick + 1 + doAssert play.recorder.data.actions[^1].kind == ActionAttack + discard play.advanceAttack(game, AttackReturnDuration * 2) + doAssert play.recorder.data.hashes.len == attackTick + 1 + play.verify(game) + + block: + var (play, game) = fixture("Sniper", Archer) + play.readyFor(game, 2) + doAssert play.playHandCard(game, flatTable(), 0) + doAssert not play.pendingTargeting + play.verify(game) + + block: + var (play, game) = fixture("Bolt", Archer) + play.readyFor(game, 1) + discard play.playHandCard(game, flatTable(), 0) + doAssert play.pendingTargeting + play.takePick(game, flatTable(), heroChoice(1)) + doAssert play.recorder.data.actions[^1].kind == ActionPlayCard + play.verify(game) + + block: + var (play, game) = fixture("Study", Mage) + play.readyFor(game, 2) + doAssert play.playHandCard(game, flatTable(), 0) + doAssert game.waitingToss + play.startTossPicking(game) + play.updateTossPicking(game, 0, pick = true, clear = false) + doAssert not game.waitingToss + doAssert play.recorder.data.actions[^1].kind == ActionToss + play.verify(game) + + block: + var (play, game) = fixture("Morphosis Chamber", Mage) + play.readyFor(game, 3) + doAssert play.playHandCard(game, flatTable(), 0) + play.endTurn(game) + play.readyFor(game, 0) + doAssert game.waitingTrigger + play.startTriggerTargeting(game) + play.updateChoosing(game, flatTable(), -1, + pick = false, cancel = true, time = 0) + doAssert not game.waitingTrigger + doAssert play.recorder.data.actions[^1].kind == ActionResolveTrigger + play.verify(game) + + block: + var (play, game) = fixture("Burnout", Mage, 3) + let + player = game.currentPlayer + turn = game.turnNumber + doAssert play.playHandCard(game, flatTable(), 0) + play.endTurn(game) + doAssert game.waitingToss + doAssert game.currentPlayer == player and game.turnNumber == turn + doAssert play.recorder.data.actions[^1].kind == ActionEndTurn, + "An accepted turn end is recorded even while its trigger awaits input." + play.startTossPicking(game) + play.updateTossPicking(game, 0, pick = true, clear = false) + doAssert game.currentPlayer != player and game.turnNumber > turn + doAssert play.recorder.data.actions[^1].kind == ActionToss + play.verify(game) + echo "CaC local human actions, delayed attacks, and choices replay exactly." + +proc testBotMail() = + ## Records repeated mailbox messages before the bot's accepted action. + const Talking = """ +sent = sendChat(enemyPlayer, "same message") +sent = sendChat(enemyPlayer, "same message") +endTurn() +end +""" + for players in [2, 7]: + var + fixture = fixture("Footsoldier", Warrior, players) + clock = initBotClock() + let bots = loadBots(newSeqWith(players, Talking)) + for _ in 0 ..< 5: + fixture.play.resetTable() + discard fixture.game.takeVisualEvents() + clock.wait = 0 + discard fixture.play.updateBots(fixture.game, flatTable(), bots, clock, + proc(): bool = false, 0) + let data = fixture.play.recorder.data + doAssert data.hashes.len == 5 + doAssert data.actions.len == 15 + for tick in 0 ..< 5: + doAssert data.actions[tick * 3].kind == ActionMailbox + doAssert data.actions[tick * 3 + 1].kind == ActionMailbox + doAssert data.actions[tick * 3].tick == tick.uint32 + doAssert data.actions[tick * 3 + 2].kind == ActionEndTurn + doAssert data.actions[tick * 3 + 2].tick == tick.uint32 + 1 + fixture.play.verify(fixture.game) + echo "CaC local bot actions and repeated mailbox messages retain order." + +proc testPermanentChoiceCancel() = + ## Declining a permanent's branch matches core play, including its watchers. + let + card = Card(name: "Branching guard", energyCost: 0, + class: some(Archer), kind: Minion, power: 1, toughness: 2, + rules: rules( + choose(rules(draw(1)), rules(damage(1, You))), + draw(1))) + watcher = Card(name: "Watcher", energyCost: 0, + class: some(Archer), kind: Trinket, + rules: rules(on(played(You, {kind: {Minion}}), damage(2, You)))) + var (play, game) = fixture("Sniper", Archer) + play.recorder = nil + let player = game.currentPlayer + game.players[player].hand = @[card] + game.players[player].board = @[MinionState(id: 1, owner: player, + card: watcher, enteredTurn: game.turnNumber)] + game.nextMinionId = 2 + var expected = game.copyGameState() + let action = ReplayAction(kind: ActionPlayCard, playerId: player.int32, + handIndex: 0, choices: @[NoTarget].toReplay) + doAssert expected.applyAction(action) + doAssert play.playHandCard(game, flatTable(), 0) + doAssert play.choosing + play.updateChoosing(game, flatTable(), -1, + pick = false, cancel = true, time = 0) + doAssert not play.pendingTargeting + doAssert game.players[player].hand.len == 1, + "The remaining draw must run exactly once after declining the branch." + doAssert game.players[player].life == StartingLife - 2, + "The played-card watcher must fire exactly once." + # Snapshots only support base-set cards. Replace the same fixture cards + # in both completed states before comparing the rest of their snapshots. + for state in [addr game, addr expected]: + for seat in state[].players.mitems: + for minion in seat.board.mitems: + if minion.card.name in [card.name, watcher.name]: + minion.card = baseCardNamed("Sniper") + doAssert game.stateHash() == expected.stateHash() + echo "CaC permanent choice cancellation matches canonical play exactly." + +testLocalActions() +testBotMail() +testPermanentChoiceCancel() diff --git a/games/cac/tests/test_replay_library.nim b/games/cac/tests/test_replay_library.nim new file mode 100644 index 000000000..9488cc7cf --- /dev/null +++ b/games/cac/tests/test_replay_library.nim @@ -0,0 +1,214 @@ +import + std/[os, strutils, tempfiles, times], + polyworld/tapes, + ../core/[replays, sim], ../replaylibraries + +const RecordedTicks = 3 + +proc sampleReplay(): ReplayData = + ## Records accepted game actions and repeated messages with canonical hashes. + let + seated = [precon(Archer), precon(Mage)] + recorder = initReplayRecorder( + matchSetup(seated, 23, RecordedTicks), + GameConfig(seed: 23, maxTicks: RecordedTicks, + players: unnamedPlayers(seated.len)) + ) + var game = newGame(seated, 23, recordEvents = true) + recorder.recordMailbox(0, 0, -2, "Opening message") + for tick in 1 .. RecordedTicks: + let action = ReplayAction(kind: ActionEndTurn, tick: tick.uint32, + playerId: game.currentPlayer.int32) + doAssert game.applyAction(action) + recorder.record(action) + recorder.recordHash(game.stateHash()) + if tick == 1: + recorder.recordMailbox(tick.uint32, 1, 0, "Same message") + recorder.recordMailbox(tick.uint32, 1, 0, "Same message") + recorder.data + +proc verifyReplay(data: ReplayData) = + ## Replays saved actions without policy execution and checks every hash. + var + game = newGame(data.header.setup) + cursor = data.initReplayCursor() + action: ReplayAction + tick = 0'u32 + while data.takeReplayAction(cursor, tick, action): + doAssert game.applyAction(action) + tick = action.tick + doAssert game.stateHash() == data.hashes[tick.int - 1] + doAssert tick == RecordedTicks + doAssert cursor.actionIndex == data.actions.len + doAssert data.actions[0].kind == ActionMailbox + doAssert data.actions[2].text == data.actions[3].text + doAssert data.actions[2].tick == data.actions[3].tick + +proc changeVersion(bytes: var string, offset: int, version: uint16) = + ## Rewrites a header field without interpreting an obsolete game payload. + bytes[offset] = char(version and 0xff) + bytes[offset + 1] = char(version shr 8) + +proc rejectsImport(path, directory: string) = + ## Requires malformed imports to leave their source and library unchanged. + let + source = readFile(path) + before = listReplays(directory).len + var rejected = false + try: + discard importReplay(path, directory) + except ReplayError: + rejected = true + doAssert rejected + doAssert readFile(path) == source + doAssert listReplays(directory).len == before + +proc testLibrary() = + ## Exercises saves, old versions, malformed files, and non-destructive imports. + let + root = createTempDir("cac-replay-library-", "") + library = root / "library with spaces" + data = sampleReplay() + bytes = encodeReplay(data) + payloadOffset = ReplayMagic.len + 6 + ReplayGame.len + defer: + removeDir(root) + + echo "Testing user library locations and empty libraries" + doAssert replayDirectory().isAbsolute() + doAssert replayDirectory().endsWith( + "Polyworld" / "Cards and Casters" / "Replays" + ) + doAssert listReplays(library).len == 0 + doAssert not dirExists(library) + doAssert ensureReplayDirectory(library) == library + + echo "Testing uniquely named atomic replay saves" + let + first = saveLibraryReplay(data, library) + second = saveLibraryReplay(data, library) + doAssert first != second + doAssert first.parentDir == library + doAssert first.splitFile().ext == ".replay" + doAssert readFile(first) == bytes + doAssert readFile(second) == bytes + doAssert loadReplay(first).actions == data.actions + doAssert first.splitFile().name.startsWith("CaC-") + verifyReplay(loadReplay(first)) + let entry = inspectReplay(first) + doAssert entry.playable + doAssert entry.problem.len == 0 + doAssert entry.ticks == RecordedTicks + doAssert entry.fileVersion == ReplayFileVersion + doAssert entry.gameVersion == ReplayGameVersion + doAssert entry.tapeVersion == ReplayFormatVersion + doAssert entry.size == bytes.len + doAssert entry.path == first + doAssert entry.name == first.splitFile().name + for kind, path in walkDir(library): + doAssert kind == pcFile + doAssert path.endsWith(".replay") + + echo "Testing newest-first ordering and unrelated-file filtering" + setLastModificationTime(first, fromUnix(100)) + setLastModificationTime(second, fromUnix(200)) + writeFile(library / "unfinished.partial", bytes) + writeFile(library / "notes.txt", "not a replay") + createDir(library / "directory.replay") + let ordered = listReplays(library) + doAssert ordered.len == 2 + doAssert ordered[0].path == second + doAssert ordered[1].path == first + + echo "Testing import copies, repeated names, and importing library files" + let source = root / "A match with spaces.REPLAY" + writeFile(source, bytes) + let + imported = importReplay(source, library) + importedAgain = importReplay(source, library) + doAssert imported != importedAgain + doAssert readFile(source) == bytes + doAssert readFile(imported) == bytes + doAssert imported.splitFile().name.startsWith("Imported-A-match-with-spaces-") + let count = listReplays(library).len + doAssert importReplay(imported, library) == imported + doAssert listReplays(library).len == count + + echo "Testing incompatible versions remain visible and import unchanged" + for kind in 0 ..< 4: + var old = bytes + case kind + of 0: + old.changeVersion(ReplayMagic.len + 2, ReplayGameVersion - 1) + old.setLen(payloadOffset) + old.add("old payload whose layout is intentionally unknown") + of 1: + old.changeVersion(ReplayMagic.len, ReplayFileVersion + 1) + old.setLen(payloadOffset) + of 2: + old.changeVersion(payloadOffset, ReplayFormatVersion - 1) + old.setLen(payloadOffset + 4) + else: + old.changeVersion(payloadOffset + 2, ReplayGameVersion + 1) + old.setLen(payloadOffset + 4) + let path = root / ("older-" & $kind & ".replay") + writeFile(path, old) + let + copied = importReplay(path, library) + incompatible = inspectReplay(copied) + doAssert not incompatible.playable + doAssert incompatible.problem.len > 0 + doAssert readFile(copied) == old + doAssert readFile(path) == old + + echo "Testing invalid, truncated, and foreign replays are contained" + for i, bad in [ + "not a replay", + ReplayMagic, + bytes[0 ..< payloadOffset + 4], + encodeReplayFile("gods_of_the_arena", 84, 1'u32) + ]: + let path = root / ("invalid-" & $i & ".replay") + writeFile(path, bad) + let invalid = inspectReplay(path) + doAssert not invalid.playable + doAssert invalid.problem.len > 0 + rejectsImport(path, library) + let broken = library / "broken.replay" + writeFile(broken, "not a replay") + var foundBroken = false + for item in listReplays(library): + if item.path == broken: + foundBroken = true + doAssert not item.playable + doAssert item.problem.len > 0 + doAssert foundBroken + + echo "Testing oversized replays and failed saves" + let oversized = root / "oversized.replay" + block: + let file = open(oversized, fmWrite) + defer: + file.close() + file.setFilePos(DefaultMaxReplayBytes) + file.write('x') + doAssert not inspectReplay(oversized).playable + doAssert "64 MiB" in inspectReplay(oversized).problem + var rejected = false + try: + discard importReplay(oversized, library) + except ReplayError: + rejected = true + doAssert rejected + let occupied = root / "occupied" + writeFile(occupied, "keep this file") + rejected = false + try: + discard saveLibraryReplay(data, occupied) + except ReplayError: + rejected = true + doAssert rejected + doAssert readFile(occupied) == "keep this file" + +testLibrary() +echo "CaC replay library checks passed without touching the user library." diff --git a/games/cac/tests/test_replay_menu_render.nim b/games/cac/tests/test_replay_menu_render.nim new file mode 100644 index 000000000..da75c396b --- /dev/null +++ b/games/cac/tests/test_replay_menu_render.nim @@ -0,0 +1,172 @@ +import + std/[importutils, os, times], + opengl, pixie, silky, vmath, windy/internal, + polyworld/[chrome, viewers], + ../[homes, replaylibraries, replaymenus], ../core/replays, + ../ui/frontendassets + +privateAccess(Window) + +proc verifyReplayMenu(size: IVec2, screenshot: string, zoom = 0) = + ## Exercises production replay controls with real UI input and rendering. + let + savedMode = uiScaleMode + savedPercent = uiScalePercent + if zoom > 0: + uiScaleMode = CustomUiScale + uiScalePercent = zoom + defer: + uiScaleMode = savedMode + uiScalePercent = savedPercent + let window = newWindow("CaC replay browser test", size, visible = false) + defer: + window.close() + window.makeContextCurrent() + loadExtensions() + let builder = newHudAtlas(4096) + builder.addDefaultFonts() + builder.addFrontendAssets() + let sk = newSilky(window, builder.atlasImage, builder.atlas) + sk.applyThemePatches() + var + browser = ReplayBrowserUi() + entries: seq[ReplayEntry] + framebuffer, texture: GLuint + for index in 0 ..< 12: + entries.add ReplayEntry( + path: "/test/cac-" & $index & ".replay", + name: "CaC match " & $(index + 1), + modified: fromUnix(1795200000 - int64(index * 3600)), + gameVersion: ReplayGameVersion, + ticks: 120 + index * 12, + playable: true + ) + entries[1].playable = false + entries[1].gameVersion = ReplayGameVersion - 1 + entries[1].problem = "Game version " & $entries[1].gameVersion & + " (requires " & $ReplayGameVersion & ")" + entries[3].ticks = 1 + entries[2].playable = false + entries[2].problem = "The replay file is incomplete." + glGenFramebuffers(1, framebuffer.addr) + glGenTextures(1, texture.addr) + glBindTexture(GL_TEXTURE_2D, texture) + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8.GLint, size.x.GLsizei, size.y.GLsizei, + 0, GL_RGBA, GL_UNSIGNED_BYTE, nil) + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer) + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, texture, 0) + doAssert glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE + defer: + glBindFramebuffer(GL_FRAMEBUFFER, 0) + glDeleteTextures(1, texture.addr) + glDeleteFramebuffers(1, framebuffer.addr) + + proc input(point = vec2(-100), pressed = false, released = false, + key = ButtonUnknown) = + ## Updates only the transient events consumed by the real menu widgets. + window.state.perFrame = PerFrame() + window.state.buttonDown = {} + window.state.mousePos = (point * sk.uiScale).ivec2 + window.state.mousePrevPos = window.state.mousePos + if pressed: + window.state.perFrame.buttonPressed.incl MouseLeft + window.state.buttonDown.incl MouseLeft + if released: + window.state.perFrame.buttonReleased.incl MouseLeft + if key != ButtonUnknown: + window.state.perFrame.buttonPressed.incl key + + proc render(point = vec2(-100), pressed = false, released = false, + key = ButtonUnknown): ReplayBrowserResult = + ## Renders the browser without performing its returned filesystem actions. + input(point, pressed, released, key) + result = sk.drawReplayBrowser(window, browser, entries, + "User folder / Polyworld / Cards and Casters / Replays") + sk.endUi() + + proc click(point: Vec2): ReplayBrowserResult = + ## Sends a complete mouse press and release through the renderer. + discard render(point, pressed = true) + render(point, released = true) + + discard render() + let layout = replayBrowserLayout(window.size.vec2 / sk.uiScale) + doAssert layout.back.y + layout.back.h < window.size.y.float32 / sk.uiScale + doAssert layout.folderButton.x + layout.folderButton.w < layout.refresh.x + doAssert layout.panel.y + layout.panel.h < layout.back.y + let watch = layout.rows.xy + vec2(layout.rows.w - 96, 48) + let live = click(watch) + doAssert live.action == PlayReplay and live.path == entries[0].path + doAssert click(watch + vec2(0, ReplayRowHeight)).action == StayReplayBrowser + doAssert click(watch + vec2(0, ReplayRowHeight * 2)).action == StayReplayBrowser + discard render(key = KeyDown) + doAssert browser.selectedPath == entries[0].path + discard render(key = KeyDown) + doAssert browser.selectedPath == entries[3].path + doAssert render(key = KeyEnter).path == entries[3].path + for index in 0 ..< 10: + discard render(key = KeyDown) + doAssert browser.selectedPath == entries[^1].path + doAssert browser.scroll.scrollPos.y > 0 + doAssert render(key = KeyEnter).path == entries[^1].path + doAssert click(layout.importButton.xy + vec2(60, 20)).action == ImportReplayFile + doAssert click(layout.folderButton.xy + vec2(70, 20)).action == OpenReplayFolder + doAssert click(layout.refresh.xy + vec2(70, 20)).action == RefreshReplays + doAssert click(layout.back.xy + vec2(70, 20)).action == BackFromReplays + doAssert render(key = KeyEscape).action == BackFromReplays + browser = ReplayBrowserUi() + discard render() + if screenshot.len > 0: + let image = newImage(size.x, size.y) + glReadPixels(0, 0, size.x.GLsizei, size.y.GLsizei, + GL_RGBA, GL_UNSIGNED_BYTE, image.data[0].addr) + image.flipVertical() + createDir(screenshot.parentDir) + image.writeFile(screenshot) + entries.setLen(0) + browser.selectedPath = "/test/no-longer-present.replay" + doAssert render(key = KeyEnter).action == StayReplayBrowser + doAssert browser.selectedPath.len == 0 + doAssert click(layout.importButton.xy + vec2(60, 20)).action == ImportReplayFile + var focus = 2 + input(key = KeyEnter) + doAssert sk.drawCacHome(window, focus) == CacOpenReplays + sk.endUi() + input(key = KeyDown) + doAssert sk.drawCacHome(window, focus) == CacStayHome + doAssert focus == 3 + sk.endUi() + input(key = KeyEnter) + doAssert sk.drawCacHome(window, focus) == CacOpenSettings + sk.endUi() + var saveReplay = false + + proc renderSaveOption(pressed = false, released = false, + enabled = true): bool = + ## Sends real pointer input through the shared recording preference. + input(vec2(90, 90), pressed, released) + sk.beginUi(window, window.size) + sk.textStyle = "LobbyBody" + result = sk.drawReplaySaveOption(window, vec2(80, 80), saveReplay, enabled) + sk.endUi() + + sk.resetInteractions() + discard renderSaveOption() + doAssert not renderSaveOption(pressed = true) + doAssert renderSaveOption(released = true) + doAssert saveReplay + discard renderSaveOption(enabled = false) + doAssert not renderSaveOption(pressed = true, enabled = false) + doAssert not renderSaveOption(released = true, enabled = false) + doAssert saveReplay + discard renderSaveOption() + doAssert not renderSaveOption(pressed = true) + doAssert renderSaveOption(released = true) + doAssert not saveReplay + +verifyReplayMenu(ivec2(1280, 900), + getEnv("CAC_REPLAY_MENU_SCREENSHOT", "/tmp/cac-replay-browser.png")) +verifyReplayMenu(ivec2(800, 600), "") +verifyReplayMenu(ivec2(800, 600), "", zoom = 300) +echo "Replay browser mouse, keyboard, disabled versions, and scrolling passed." diff --git a/games/cac/tests/test_sessions.nim b/games/cac/tests/test_sessions.nim index 67c3edcbb..e1b7c3102 100644 --- a/games/cac/tests/test_sessions.nim +++ b/games/cac/tests/test_sessions.nim @@ -1,113 +1,191 @@ -import std/[json, options, strutils, unittest] +import std/[json, options, os, strutils, unittest] +import polyworld/screenshots import ../core/sessions suite "session options": - test "defaults": + test "defaults preserve the menu and saved sound choice": let options = parseSessionOptions([]) check options.seed == DefaultSessionSeed check not options.seedGiven check options.playerCount == 2 - check options.human == false - check options.soundMuted + check not options.human + check not options.soundMuted + check not options.common.soundOverride + check options.common.speed == 1 + check options.common.vsync check options.menu - test "menus are the default and direct launches remain available": + test "shared screenshot and window flags accept every common spelling": + for args in [ + @["--screenshot", "captures/menu view.png", "--frames", "3", + "--windowSize", "800x600"], + @["--screenshot=captures/menu view.png", "--frames=3", + "--windowSize=800x600"], + @["--screenshot:captures/menu view.png", "--frames:3", + "--windowSize:800x600"] + ]: + when defined(headless) or defined(emscripten): + expect CatchableError: + discard parseSessionOptions(args) + else: + let options = parseSessionOptions(args) + check options.capture.path == "captures/menu view.png" + check options.capture.frames == 3 + check options.windowWidth == 800 and options.windowHeight == 600 + check options.menu + when not defined(headless): + let sized = parseSessionOptions(["--windowSize", "1280x900"]) + check sized.windowWidth == 1280 and sized.windowHeight == 900 + + test "menus stay available for destination and connection presets": check parseSessionOptions(["--seed=42"]).menu check not parseSessionOptions(["--direct"]).menu - check not parseSessionOptions(["--human"]).menu check not parseSessionOptions(["--players=5"]).menu check parseSessionOptions(["--menu", "--players=5"]).menu check not parseSessionOptions(["--menu", "--replay=a.replay"]).menu + when not defined(emscripten): + check parseSessionOptions(["--record", "match.replay"]).menu let network = parseSessionOptions([ - "--players=5", "--server=127.0.0.1:8090", "--room", "abc"]) + "--players=5", "--server:ws://localhost:9911/ws", "--room", "abc"]) check network.menu - check network.serverAddress == "127.0.0.1:8090" + check network.serverAddress == "ws://localhost:9911/ws" check network.roomCode == "abc" for args in [@["--server"], @["--room="], @["--menu=false"], @["--direct=true"], @["--players=8"]]: expect ValueError: discard parseSessionOptions(args) - test "audio flags preserve session arguments and the last choice wins": - check SessionOptions().soundMuted + test "common playback values have one spelling across input forms": + for args in [ + @["--play", "false", "--speed", "3", + "--vsync", "off", "--name", "Ada", "--replay", "m.replay"], + @["--play=false", "--speed=3", "--vsync=off", + "--name=Ada", "--replay=m.replay"], + @["--play:false", "--speed:3", "--vsync:off", + "--name:Ada", "--replay:m.replay"] + ]: + when defined(headless): + expect ValueError: + discard parseSessionOptions(args) + else: + let options = parseSessionOptions(args) + check options.common.pauseOnStart + check options.common.speed == 3 + check not options.common.vsync + check options.common.playerName == "Ada" + check options.replayPath == "m.replay" + for args in [@["--seed", "-123"], @["--seed=-123"], @["--seed:-123"]]: + let options = parseSessionOptions(args) + check options.seed == -123 and options.seedGiven + + test "menu setup preserves signed seeds and explicit bot occupancy": + for seed in [int32.low, -42, 0, int32.high]: + let options = parseSessionOptions(["--menu", "--seed=" & $seed]) + check options.initialBattleSetup().seed == seed + let bots = parseSessionOptions(["--menu", "--bots", "a.bas:3"]) + check bots.initialMenuHumanSeat() == -1 + check bots.initialBattleSetup().classes.len == 3 + when not defined(headless): + let human = parseSessionOptions([ + "--menu", "--player", "2", "--bot", "a.bas"]) + check human.initialMenuHumanSeat() == 1 + check parseSessionOptions([]).initialMenuHumanSeat() == 0 + + test "connection options cannot discard a requested local roster": + for args in [@["--server=ws://localhost:9911/ws", "--bot=a.bas:2"], + @["--room=abc", "--replay=m.replay"], + @["--server=ws://localhost:9911/ws", "--player"], + @["--menu", "--player", "--deck=a.bas"]]: + expect ValueError: + discard parseSessionOptions(args) + + test "audio uses common override state and the last choice wins": check parseSessionOptions(["--mute"]).soundMuted check not parseSessionOptions(["--unmute"]).soundMuted for argument in ["--mute=false", "--mute:off", "--mute=0"]: - let options = parseSessionOptions([ - "--human", argument, "--seed", "42", "--replay", "m.replay" - ]) + let options = parseSessionOptions([argument, "--seed", "42"]) check not options.soundMuted - check options.human + check options.common.soundOverride check options.seed == 42 - check options.replayPath == "m.replay" check parseSessionOptions(["--unmute", "--mute=true"]).soundMuted check not parseSessionOptions(["--mute", "--unmute"]).soundMuted - for argument in ["--mute=", "--mute=maybe"]: - expect ValueError: - discard parseSessionOptions([argument]) - - test "URL argument forms and negative seeds": - let options = parseSessionOptions([ - "--seed", "-123", "--players=3", "--replay", "m.replay"]) - check options.seed == -123 - check options.seedGiven - check options.playerCount == 3 - check options.replayPath == "m.replay" - - test "bots are paths, at most one per duel seat": - check parseSessionOptions(["--bot", "a.bas", "--bot=b.bas"]).botPaths == - @["a.bas", "b.bas"] - expect ValueError: - discard parseSessionOptions(["--bot=a.bas", "--bot=b.bas", "--bot=c.bas"]) - - test "human flag forms": - check parseSessionOptions(["--human"]).human == true - check parseSessionOptions(["--human", "true"]).human == true - check parseSessionOptions(["--human=1"]).human == true - check parseSessionOptions(["--human=yes"]).human == true - check parseSessionOptions(["--human", "false"]).human == false - check parseSessionOptions(["--human", "--seed", "1"]).human == true - - test "a human may bring a bot script's deck": - for args in [@["--human", "players/archer.bas"], - @["--human=players/archer.bas"]]: + + test "bot specifications expand in order without implicit repetition": + for args in [ + @["--bot", "a.bas:2", "--bots", "b.bas"], + @["--bot=a.bas:2", "--bots=b.bas"], + @["--bot:a.bas:2", "--bots:b.bas"] + ]: let options = parseSessionOptions(args) - check options.human - check options.humanDeckPath == "players/archer.bas" - check parseSessionOptions(["--human"]).humanDeckPath == "" - - test "player count selects a scene without changing duel options": - check parseSessionOptions(["--players=2"]).playerCount == 2 - check parseSessionOptions(["--players=3"]).playerCount == 3 - let options = parseSessionOptions([ - "--players", "6", "--human", "--seed=42"]) - check options.playerCount == 6 - check options.human - check options.seed == 42 - check options.seedGiven - - test "invalid and missing player counts fail clearly": - for args in [@["--players"], @["--players="], - @["--players", "--seed=42"], @["--players=many"], - @["--players=3.5"], @["--players=0"], @["--players=1"], - @["--players=-3"], @["--players=9223372036854775808"]]: + check options.botPaths == @["a.bas", "a.bas", "b.bas"] + check options.playerCount == 3 + check not options.menu + check parseSessionOptions(["--bots", "C:/bots/a.bas:2"]).botPaths == + @["C:/bots/a.bas", "C:/bots/a.bas"] + for args in [@["--bot", "a.bas"], + @["--players=4", "--bot", "a.bas:2"], + @["--bot", "a.bas:8"], @["--bot", "a.bas:0"]]: expect ValueError: discard parseSessionOptions(args) - test "invalid and incomplete options fail clearly": - for args in [@["--seed=none"], @["--seed"], @["--seed="], - @["--unknown=value"], @["local"], @["--seed=9223372036854775808"]]: + when not defined(headless): + test "player is a one-based human slot and deck selection is separate": + for args in [@["--player", "2", "--bot", "a.bas"], + @["--player=2", "--bot=a.bas"], + @["--player:2", "--bot:a.bas"]]: + let options = parseSessionOptions(args) + check options.human + check options.common.playerSlot == 2 + check options.playerCount == 2 + check options.botPaths == @["a.bas"] + check parseSessionOptions(["--player"]).common.playerSlot == 1 + let deck = parseSessionOptions([ + "--player", "--deck", "players/archer.bas"]) + check deck.humanDeckPath == "players/archer.bas" + check not deck.menu + for args in [@["--player=0"], @["--player=3"], + @["--player", "Ada"], @["--human"], + @["--deck", "players/archer.bas"]]: + expect ValueError: + discard parseSessionOptions(args) + + test "replay input excludes live bots, human control, and output": + for args in [@["--replay=m.replay", "--bot=a.bas:2"], + @["--replay=m.replay", "--player"], + @["--replay=m.replay", "--record=copy.replay"]]: + expect ValueError: + discard parseSessionOptions(args) + + test "native action caps and exact replay destination share common options": + when not defined(emscripten): + for args in [@["--record", "out/match.replay", "--ticks", "50"], + @["--record=out/match.replay", "--ticks=50"], + @["--record:out/match.replay", "--ticks:50"]]: + let options = parseSessionOptions(args) + check options.common.recordPath == "out/match.replay" + check options.common.maximumTicks == 50 + check parseSessionOptions(["--seconds:2"]).common.maximumTicks == 48 + for args in [@["--llm-mode=barrier"], @["--headless-tick-rate=24"]]: expect ValueError: discard parseSessionOptions(args) - test "--class and --opponent are gone": - for args in [@["--class=warrior"], @["--class", "warrior"], - @["--opponent=mage"], @["--opponent", "mage"]]: - try: + test "relative input and output paths survive a later working directory change": + when not defined(emscripten): + var options = parseSessionOptions([ + "--bot", "bots/a.bas:2", "--record", "out/match.replay"]) + options.resolveSessionPaths() + check options.common.recordPath == absolutePath("out/match.replay") + check options.botPaths == @[absolutePath("bots/a.bas"), + absolutePath("bots/a.bas")] + + test "invalid options and unsupported aliases fail clearly": + for args in [@["--seed=none"], @["--seed"], @["--seed="], + @["--seed=2147483648"], @["--players=many"], @["--players=1"], + @["--players=0"], @["--players=-3"], @["--players=3.5"], + @["--class=warrior"], @["--opponent=mage"], + @["--unknown=value"], @["local"]]: + expect ValueError: discard parseSessionOptions(args) - check false - except ValueError as error: - check error.msg.startsWith("Unknown session option: --") suite "deterministic session bots": test "Bolt targets the enemy hero and never an ally": diff --git a/games/cac/tests/tests.nim b/games/cac/tests/tests.nim index 7fe4419a1..9b573b103 100644 --- a/games/cac/tests/tests.nim +++ b/games/cac/tests/tests.nim @@ -20,6 +20,9 @@ import test_pile_hover, test_play, test_replayer, + test_replay_library, + test_recording_library, + test_recording_play, test_sessions, test_towerarena diff --git a/games/cac/ui/matchmenu.nim b/games/cac/ui/matchmenu.nim index a5207c75e..48e53a792 100644 --- a/games/cac/ui/matchmenu.nim +++ b/games/cac/ui/matchmenu.nim @@ -6,7 +6,9 @@ import ../app, ../net/multiplayer, controls const - BattleMenuSize = vec2(520, 560) + BattleMenuSize = + when defined(emscripten): vec2(520, 560) + else: vec2(520, 620) BattleMenuInset = vec2(32) BattleMenuWidth = 456'f BattleMenuGold = rgbx(215, 181, 112, 255) @@ -138,7 +140,16 @@ proc draw*(menu: var MatchMenu, app: App) = if sk.lobbyButton("Settings", origin + vec2(32, 262), BattleMenuWidth, "settings", enabled = not menu.waitingToLeave, height = 48): menu.page = MenuSettings - sk.drawRect(origin + vec2(32, 326), vec2(BattleMenuWidth, 1), + when not defined(emscripten): + if sk.lobbyButton("Save replay", origin + vec2(32, 322), BattleMenuWidth, + enabled = not menu.waitingToLeave and app.replay == nil and + app.recording != nil, height = 48): + try: + discard app.saveCurrentReplay() + except CatchableError as error: + app.replaySaveError = "Cannot save replay: " & error.msg + let replayRow = when defined(emscripten): 0.0'f else: 60.0'f + sk.drawRect(origin + vec2(32, 326 + replayRow), vec2(BattleMenuWidth, 1), rgbx(215, 181, 112, 60)) let leaveText = if not online: "Return to main menu" @@ -147,7 +158,7 @@ proc draw*(menu: var MatchMenu, app: App) = elif network.client.snapshot.participant == network.client.participant: "Return room to lobby" else: "Back to multiplayer" - if sk.lobbyButton(leaveText, origin + vec2(32, 338), BattleMenuWidth, + if sk.lobbyButton(leaveText, origin + vec2(32, 338 + replayRow), BattleMenuWidth, "arrow_left", enabled = not menu.waitingToLeave, height = 48, tint = rgbx(218, 220, 220, 255)): if online: @@ -168,8 +179,15 @@ proc draw*(menu: var MatchMenu, app: App) = elif online and not active: "Return to the lobby to set up another battle." elif paused: "Resume when you are ready to continue." else: "Use Pause battle to stop the game.", - origin + vec2(32, 410), vec2(BattleMenuWidth, 28), + origin + vec2(32, 410 + replayRow), vec2(BattleMenuWidth, 28), BattleMenuMuted, "Default", CenterAlign) sk.drawLabel(menuShortcut() & " closes this menu", - origin + vec2(32, 482), vec2(BattleMenuWidth, 24), + origin + vec2(32, 482 + replayRow), vec2(BattleMenuWidth, 24), BattleMenuGold, "Small", CenterAlign) + when not defined(emscripten): + let message = + if app.replaySaveError.len > 0: app.replaySaveError + elif app.replaySavedPath.len > 0: "Replay saved to your library." + else: "" + sk.menuLabel(sk.fittedLabel(message, BattleMenuWidth, "Default"), + origin + vec2(32, 574), BattleMenuWidth, BattleMenuGold) diff --git a/games/cac/web/inputs.js b/games/cac/web/inputs.js index 06b3b68f8..7ee897981 100644 --- a/games/cac/web/inputs.js +++ b/games/cac/web/inputs.js @@ -7,10 +7,6 @@ var parameters = new URLSearchParams(window.location.search); var args = Module["arguments"] || []; - if (parameters.get("human") === "true" || parameters.get("human") === "1") { - args.push("--human", "true"); - } - parameters.getAll("players").forEach(function (value) { args.push("--players", value); }); diff --git a/games/call_to_adventure/bots.nim b/games/call_to_adventure/bots.nim index c3900793b..9ebffff21 100644 --- a/games/call_to_adventure/bots.nim +++ b/games/call_to_adventure/bots.nim @@ -161,15 +161,8 @@ proc buildHeroHost(heroId: int32, llm: LlmClient = nil, policySlot = -1): Host = result = activeGame.sendChat(player, int(args[0].asInt), text) let pullMailboxProc: NumericHostProc = proc(args: openArray[Value]): Value = ## Copies the oldest message into BASIC and consumes it on success. - let - player = int(heroId - 100) - inbox = activeGame.inboxes[player] - var runtime = activeGame.heroVms[player].runtime - if inbox.count == 0: - result = runtime.putString("") - else: - result = runtime.putString(inbox.messages[inbox.first]) - discard inbox.pop() + let player = int(heroId - 100) + activeGame.heroVms[player].runtime.pullMailboxString(activeGame.inboxes[player]) let mailboxIdProc: HostProc = proc(args: openArray[int32]): int32 = ## Returns the channel or DM sender of the last pulled message. activeGame.inboxes[int(heroId - 100)].lastId diff --git a/games/call_to_adventure/content.nim b/games/call_to_adventure/content.nim index 28c535b02..6e4778f63 100644 --- a/games/call_to_adventure/content.nim +++ b/games/call_to_adventure/content.nim @@ -16,6 +16,8 @@ import const LevelCount* = 6 ## surface, pyramid, rooms, caves, lava hall, vault PartySize* = 4 + ArenaMonsterLimit* = 24 + ## Six arena columns, leaving a gap before the heroes' column. InventorySlots* = 2 ChatLines* = 16 ## ring buffer of recent party chatter TilesPerLevel* = GridTiles * GridTiles diff --git a/games/call_to_adventure/game.nim b/games/call_to_adventure/game.nim index e8f5cdd11..633d3c579 100644 --- a/games/call_to_adventure/game.nim +++ b/games/call_to_adventure/game.nim @@ -5,184 +5,23 @@ ## replaying. import - std/[os, strformat, strutils, times], + std/[strformat, strutils, times], polyworld/[cli, controllers, metrics, profiles, tapes, timings], content, maps, sim, bots, controls, - replays + replays, + options as launchoptions + +export launchoptions when defined(coworld): import polyworld/coworld -proc usage() = - ## Prints the shared Polyworld game command surface. - echo "Call to Adventure" - echo " --bot:PATH Fill one of the four hero slots." - echo " --bot:PATH:N Fill N slots with that BASIC program." - echo " --bot PATH[:N] The equivalent two-argument form." - echo " --player Control the first hero; supply 3 bots." - echo " --player:N Control hero N (1-4); supply 3 bots." - echo " --replay PATH Play recorded actions instead of bots." - echo " --record PATH Record bot actions to a replay." - echo " --seed NUMBER Live dungeon seed." - echo " --seconds NUMBER Duration in seconds (default 1200)." - echo " --minutes NUMBER Duration in minutes (default 20)." - echo " --ticks NUMBER Duration in ticks (default 28800)." - echo " --headless-tick-rate N Wall-clock ticks per second, 0 is unlimited." - echo " --llm-mode:async|barrier Wait for all requests between headless ticks." - echo " --speed NUMBER Graphical start speed: 1, 2, 4, or 16." - echo " --play=false Start the graphical transport paused." - echo " --windowSize WxH Graphical window, such as 800x400." - echo " --vsync:off Unlock the frame rate (default on)." - echo " --mute[=true|false] Override saved sound levels for this launch." - echo " --unmute Enable sound for this launch." - echo " --verbose Print periodic headless summaries." - echo " --arena Debug fight in one 10x10 room." - echo " --hero:CLASS[,CLASS] Arena party: wizard (the mage), rogue (the" - echo " archer), fighter, cleric (the druid); default" - echo " mage,fighter." - echo " --monster:NAME[,NAME] Arena monsters, cycled: dustling (default)..." - echo " --monsters:N Arena monster count, 1 to 24 (default 10)." - echo "Compile with -d:headless for command-line simulation." - echo "Compile with -d:emscripten for the web backend." - -type ArenaOptions* = object - ## The debug fight that replaces the dungeon when enabled. - enabled*: bool - heroes*: seq[HeroClass] - species*: seq[Species] - count*: int - -var arenaOptions* = ArenaOptions( - heroes: @[WizardClass, FighterClass], - species: @[DustlingSpecies], - count: 10 -) - -proc squashed(name: string): string = - ## Lowercases a name and drops spaces, dashes and underscores. - for ch in name: - if ch.isAlphaNumeric: - result.add ch.toLowerAscii - -proc heroName*(class: HeroClass): string = - ## A class's plain name, such as Fighter. - ($class)[0 ..< ($class).len - "Class".len] - -proc parseArenaHero(name: string): HeroClass = - ## Reads a hero class by its plain name, in any case. The rogue, who - ## carries the bow, also answers to archer and ranger, the wizard to mage - ## and arcanist, and the cleric to druid. - if name.squashed in ["archer", "ranger"]: - return RogueClass - if name.squashed in ["mage", "arcanist"]: - return WizardClass - if name.squashed == "druid": - return ClericClass - for class in HeroClass: - if class.heroName.squashed == name.squashed: - return class - fail("unknown --hero " & name & "; use mage, archer, fighter or druid") - -proc parseArenaMonster(name: string): Species = - ## Reads a species by its display name, ignoring case, spaces and dashes. - for species in Species: - if SpeciesNames[species].squashed == name.squashed: - return species - var names: seq[string] - for species in Species: - names.add SpeciesNames[species].toLowerAscii.replace(' ', '_') - fail("unknown --monster " & name & "; use one of " & names.join(", ")) - -proc parseArenaHeroes(names: string): seq[HeroClass] = - ## Reads a comma-separated party, each class at most once. - for name in names.split(','): - let class = parseArenaHero(name) - if class in result: - fail("--hero names the " & class.heroName & " twice") - result.add class - -proc parseArenaCount(value: string): int = - ## Reads how many monsters the arena spawns. - try: - result = parseInt(value) - except ValueError: - fail("--monsters takes a count; pick species with --monster:" & value) - if result notin 1 .. ArenaMonsterLimit: - fail("--monsters takes 1 to " & $ArenaMonsterLimit) - -proc arenaMonsters*(): seq[Species] = - ## The arena's monsters, cycling through the chosen species. - for index in 0 ..< arenaOptions.count: - result.add arenaOptions.species[index mod arenaOptions.species.len] - -proc takeArenaFlag( - arguments: seq[string], - index: var int, - argument: string -): bool = - ## Handles the debug arena flags. Picking heroes or monsters implies it. - if argument == "--arena": - arenaOptions.enabled = true - return true - for flag in ["--hero", "--monsters", "--monster"]: - var value = "" - if argument == flag: - value = arguments.argumentValue(index, argument) - elif argument.startsWith(flag & ":") or argument.startsWith(flag & "="): - value = argument[flag.len + 1 .. ^1] - else: - continue - arenaOptions.enabled = true - case flag - of "--hero": - arenaOptions.heroes = parseArenaHeroes(value) - of "--monsters": - arenaOptions.count = parseArenaCount(value) - else: - arenaOptions.species = @[] - for name in value.split(','): - arenaOptions.species.add parseArenaMonster(name) - return true - -proc parseGameOptions(): GameOptions = - ## Parses runtime game, bot, replay, and renderer configuration. - result = GameOptions( - seed: 2026, - seconds: DefaultMinutes * 60, - maximumTicks: DefaultDurationTicks, - speed: 1 - ) - let arguments = commandLineParams() - var index = 0 - while index < arguments.len: - let argument = arguments[index] - if result.takeCommonFlag(arguments, index, argument): - discard - elif takeArenaFlag(arguments, index, argument): - discard - else: - case argument - of "--verbose": - result.verbose = true - of "--help", "-h": - usage() - quit(0) - else: - fail("unknown argument: " & argument) - inc index - result.validateGameOptions( - PartySize, - "a live expedition requires exactly four bots" - ) - if arenaOptions.enabled and - (result.recordPath.len > 0 or result.replayPath.len > 0): - fail("--arena is a debug fight and cannot record or replay") - var + arenaOptions* = defaultArenaOptions() options*: GameOptions run*: Game @@ -278,7 +117,7 @@ proc arenaMatchup(): string = for class in arenaOptions.heroes: heroes.add class.heroName var counts: array[Species, int] - for species in arenaMonsters(): + for species in arenaOptions.arenaMonsters(): inc counts[species] var monsters: seq[string] for species in arenaOptions.species: @@ -385,7 +224,12 @@ proc runHeadless*() = when defined(coworld): options = coworldOptions(4) else: - options = parseGameOptions() + try: + let parsed = parseGameOptions() + options = parsed.options + arenaOptions = parsed.arena + except CliError as error: + fail(error.msg) startGameProfile() if options.replayPath.len > 0: @@ -416,7 +260,7 @@ else: options.seed, options.maximumTicks, arenaOptions.heroes, - arenaMonsters() + arenaOptions.arenaMonsters() ) else: newGame(options.seed, options.maximumTicks) diff --git a/games/call_to_adventure/graphics.nim b/games/call_to_adventure/graphics.nim index 7daff26b8..a8731922f 100644 --- a/games/call_to_adventure/graphics.nim +++ b/games/call_to_adventure/graphics.nim @@ -349,6 +349,7 @@ proc addAbilityIcons(builder: AtlasBuilder) = proc runGraphics*() = ## Runs the native or Emscripten graphical expedition viewer. + configureCapture(options.capture, "games/call_to_adventure/shot.png") startGameProfile() profileBlock "atlas": let builder = newHudAtlas(4096) @@ -375,6 +376,8 @@ proc runGraphics*() = msaa = msaa4x ) let splash = startSplash(sk, window) + var screenshotTarget: ScreenshotTarget + defer: screenshotTarget.releaseScreenshotTarget() # The stack spans about 45 tiles top to bottom; the shading uses amplitude # as its height scale, so a value near the whole span keeps every level # readable instead of clipping the deep ones to black. @@ -1850,9 +1853,9 @@ proc runGraphics*() = 160 ) + var screenshotFrame = 0 + applyScreenshotCamera(cameraDistance) when defined(takeScreenshot): - var screenshotFrame = 0 - applyScreenshotCamera(cameraDistance) if existsEnv("PBR"): scene.shading = PbrCharacters if existsEnv("SIM_TICKS"): @@ -2344,6 +2347,7 @@ proc runGraphics*() = drawWorldActors() scene.sunDepthPass = false + discard screenshotTarget.beginScreenshotFrame(window) glViewport(0, 0, window.size.x.GLsizei, window.size.y.GLsizei) when not defined(emscripten): glEnable(GL_MULTISAMPLE) @@ -2365,14 +2369,16 @@ proc runGraphics*() = # Bodies drawn after the ground copy cast contact shadows but keep # their own colors. - occlusion.captureGround(window.size) + occlusion.captureGround(window.size, screenshotTarget.framebuffer) beginCharacters(scene, window, view, projection, eye) drawWorldActors() finishCharacters(scene) # Only the opaque world is occluded: gizmos, particles, bars, # outlines and the HUD draw after it at full brightness. profileBlock "ambient occlusion": - occlusion.applyScreenOcclusion(window.size, projection) + occlusion.applyScreenOcclusion( + window.size, projection, screenshotTarget.framebuffer + ) # Walls stay whole: what they hide of a body shows through them on # a screen-door pattern, after the occlusion so it stays clean. profileBlock "xray bodies": @@ -2449,13 +2455,10 @@ proc runGraphics*() = ) sk.endUi() drawStatsOverlay(sk, window) - when defined(takeScreenshot): - captureScreenshot( - window, - screenshotFrame, - 8, - "games/call_to_adventure/shot.png" - ) + if captureFrame(window, screenshotFrame): + when not defined(emscripten): + window.closeRequested = true + return profileBlock "present": window.presentFrame(framePaceHz) reportDirectorFrame( diff --git a/games/call_to_adventure/options.nim b/games/call_to_adventure/options.nim new file mode 100644 index 000000000..1451b5204 --- /dev/null +++ b/games/call_to_adventure/options.nim @@ -0,0 +1,176 @@ +## Pure command-line configuration for Call to Adventure. + +import + std/[os, strutils], + polyworld/cli, + content + +const SupportedFlags = + when defined(headless): + AllCommonFlags - {ServerFlag, RoomFlag} + else: + AllCommonFlags - {ServerFlag, RoomFlag, LlmModeFlag, HeadlessTickRateFlag} + +proc fail(message: string) {.noreturn.} = + ## Reports invalid launch options without starting a game. + raise newException(CliError, message) + +proc usage() = + ## Prints shared options and Call to Adventure's arena extensions. + echo "Call to Adventure" + echo commonUsageFor(SupportedFlags) + echo "Live expeditions have four slots; --player occupies one of them." + echo " --arena Debug fight in one 10x10 room." + echo " --hero CLASS[,CLASS] Arena party; default mage,fighter." + echo " --monster NAME[,NAME] Arena species, cycled; default dustling." + echo " --monsters N Arena monster count, 1 to 24; default 10." + echo "Screenshot captures use bundled bots when no roster is supplied." + echo "Audio flags are accepted; this client currently has no audio output." + +type ArenaOptions* = object + ## The debug fight that replaces the dungeon when enabled. + enabled*: bool + heroes*: seq[HeroClass] + species*: seq[Species] + count*: int + +proc defaultArenaOptions*(): ArenaOptions = + ## Returns a fresh arena configuration for one command-line parse. + ArenaOptions( + heroes: @[WizardClass, FighterClass], + species: @[DustlingSpecies], + count: 10 + ) + +proc squashed(name: string): string = + ## Lowercases a name and drops spaces, dashes and underscores. + for ch in name: + if ch.isAlphaNumeric: + result.add ch.toLowerAscii + +proc heroName*(class: HeroClass): string = + ## A class's plain name, such as Fighter. + ($class)[0 ..< ($class).len - "Class".len] + +proc parseArenaHero(name: string): HeroClass = + ## Reads a hero class by its plain name, in any case. The rogue, who + ## carries the bow, also answers to archer and ranger, the wizard to mage + ## and arcanist, and the cleric to druid. + if name.squashed in ["archer", "ranger"]: + return RogueClass + if name.squashed in ["mage", "arcanist"]: + return WizardClass + if name.squashed == "druid": + return ClericClass + for class in HeroClass: + if class.heroName.squashed == name.squashed: + return class + fail("unknown --hero " & name & "; use mage, archer, fighter or druid") + +proc parseArenaMonster(name: string): Species = + ## Reads a species by its display name, ignoring case, spaces and dashes. + for species in Species: + if SpeciesNames[species].squashed == name.squashed: + return species + var names: seq[string] + for species in Species: + names.add SpeciesNames[species].toLowerAscii.replace(' ', '_') + fail("unknown --monster " & name & "; use one of " & names.join(", ")) + +proc parseArenaHeroes(names: string): seq[HeroClass] = + ## Reads a comma-separated party, each class at most once. + for name in names.split(','): + let class = parseArenaHero(name) + if class in result: + fail("--hero names the " & class.heroName & " twice") + result.add class + +proc parseArenaCount(value: string): int = + ## Reads how many monsters the arena spawns. + try: + result = parseInt(value) + except ValueError: + fail("--monsters takes a count; pick species with --monster:" & value) + if result notin 1 .. ArenaMonsterLimit: + fail("--monsters takes 1 to " & $ArenaMonsterLimit) + +proc arenaMonsters*(arenaOptions: ArenaOptions): seq[Species] = + ## The arena's monsters, cycling through the chosen species. + for index in 0 ..< arenaOptions.count: + result.add arenaOptions.species[index mod arenaOptions.species.len] + +proc takeArenaFlag( + arenaOptions: var ArenaOptions, + arguments: seq[string], + index: var int, + argument: string +): bool = + ## Handles the debug arena flags. Picking heroes or monsters implies it. + if argument == "--arena": + arenaOptions.enabled = true + return true + for flag in ["--hero", "--monsters", "--monster"]: + var value = "" + if argument == flag: + value = arguments.argumentValue(index, argument) + elif argument.startsWith(flag & ":") or argument.startsWith(flag & "="): + value = argument[flag.len + 1 .. ^1] + else: + continue + arenaOptions.enabled = true + case flag + of "--hero": + arenaOptions.heroes = parseArenaHeroes(value) + of "--monsters": + arenaOptions.count = parseArenaCount(value) + else: + arenaOptions.species = @[] + for name in value.split(','): + arenaOptions.species.add parseArenaMonster(name) + return true + +proc parseGameOptions*( + arguments = commandLineParams() +): tuple[options: GameOptions, arena: ArenaOptions] = + ## Parses runtime game, bot, replay, and renderer configuration. + var options = GameOptions( + seed: 2026, + seconds: DefaultMinutes * 60, + maximumTicks: DefaultDurationTicks, + speed: 1 + ) + var arenaOptions = defaultArenaOptions() + var index = 0 + while index < arguments.len: + let argument = arguments[index] + if options.takeCommonFlag(arguments, index, argument): + discard + elif arenaOptions.takeArenaFlag(arguments, index, argument): + discard + else: + case argument + of "--help", "-h": + usage() + quit(0) + else: + fail("unknown argument: " & argument) + inc index + when not defined(headless) and not defined(emscripten): + if options.capture.path.len > 0 and options.botGroups.len == 0 and + options.replayPath.len == 0 and options.playerSlot == 0: + options.botGroups.add BotGroup( + path: currentSourcePath().parentDir / "players" / "base.bas", + count: PartySize + ) + options.rejectUnsupportedFlags(SupportedFlags) + options.resolveGamePaths() + if options.playerName.len > 0 and options.playerSlot == 0: + fail("--name requires --player in Call to Adventure") + options.validateGameOptions( + PartySize, + "a live expedition requires exactly four bots" + ) + if arenaOptions.enabled and + (options.recordPath.len > 0 or options.replayPath.len > 0): + fail("--arena is a debug fight and cannot record or replay") + (options, arenaOptions) diff --git a/games/call_to_adventure/sim.nim b/games/call_to_adventure/sim.nim index d558f50c7..051a8ac98 100644 --- a/games/call_to_adventure/sim.nim +++ b/games/call_to_adventure/sim.nim @@ -115,8 +115,6 @@ const ## for heroes and monsters alike. ArenaRanks = 4'i32 ## Monsters per arena column, every other row and clear of both walls. - ArenaMonsterLimit* = 24 - ## Six arena columns, leaving a gap before the heroes' column. ActorBodyRadius = 0.33'fx BodyTurnRate = 0.35'fx PathArrive = 0.35'fx diff --git a/games/call_to_adventure/tests/test_options.nim b/games/call_to_adventure/tests/test_options.nim new file mode 100644 index 000000000..bd99a626a --- /dev/null +++ b/games/call_to_adventure/tests/test_options.nim @@ -0,0 +1,156 @@ +import + std/os, + polyworld/cli, + ../options, ../content + +proc rejects(arguments: seq[string]): bool = + ## Checks invalid launch options without creating a game or renderer. + try: + discard parseGameOptions(arguments) + except CliError: + return true + +echo "Testing Call to Adventure common argument forms" +block: + for arguments in [ + @["--bots", "bots/base.bas:4", "--record", "replays/match.replay", + "--seed", "17", "--ticks", "48"], + @["--bots=bots/base.bas:4", "--record=replays/match.replay", "--seed=17", + "--ticks=48"], + @["--bots:bots/base.bas:4", "--record:replays/match.replay", "--seed:17", + "--ticks:48"] + ]: + let launch = parseGameOptions(arguments) + doAssert launch.options.botGroups.botCount == PartySize + doAssert launch.options.botGroups[0].path == absolutePath("bots/base.bas") + doAssert launch.options.recordPath == absolutePath("replays/match.replay") + doAssert launch.options.seed == 17 + doAssert launch.options.maximumTicks == 48 + doAssert not launch.arena.enabled + +echo "Testing Call to Adventure graphical playback options" +block: + for visual in [ + @["--speed", "4", "--play", "false"], + @["--speed=4", "--play=false"], + @["--speed:4", "--play:false"] + ]: + let arguments = @["--bot", "base.bas:4"] & visual + when defined(headless): + doAssert rejects(arguments) + else: + let launch = parseGameOptions(arguments) + doAssert launch.options.speed == 4 + doAssert launch.options.pauseOnStart + +echo "Testing Call to Adventure human and bot slot selection" +block: + when not defined(headless): + for arguments in [ + @["--player", "2", "--name", "Ada", "--bot", "base.bas:3"], + @["--player=2", "--name=Ada", "--bot=base.bas:3"], + @["--player:2", "--name:Ada", "--bot:base.bas:3"] + ]: + let launch = parseGameOptions(arguments) + doAssert launch.options.playerSlot == 2 + doAssert launch.options.playerName == "Ada" + doAssert launch.options.botGroups.botCount == 3 + let first = parseGameOptions(@["--player", "--bot", "base.bas:3"]) + doAssert first.options.playerSlot == 1 + else: + doAssert rejects(@["--player", "--bot", "base.bas:3"]) + +echo "Testing Call to Adventure replay input and portable launch settings" +block: + for arguments in [ + @["--replay", "replays/saved.replay"], + @["--replay=replays/saved.replay"], + @["--replay:replays/saved.replay"] + ]: + let launch = parseGameOptions(arguments) + doAssert launch.options.replayPath == absolutePath("replays/saved.replay") + doAssert launch.options.botGroups.len == 0 + let launch = parseGameOptions(@[ + "--bot", "one.bas", "--bots", "two.bas:3", "--minutes:2", + "--mute", "--verbose=true" + ]) + doAssert launch.options.botGroups.len == 2 + doAssert launch.options.maximumTicks == 2 * 60 * SharedTickRate + doAssert launch.options.soundMuted + doAssert launch.options.soundOverride + doAssert launch.options.verbose + doAssert launch.options.headlessTickRate == 0 + doAssert not launch.options.waitForLlm + let windowArguments = @[ + "--bot", "base.bas:4", "--windowSize=960x720", "--vsync", "off" + ] + when defined(headless): + doAssert rejects(windowArguments) + else: + let window = parseGameOptions(windowArguments).options + doAssert window.windowWidth == 960 + doAssert window.windowHeight == 720 + doAssert not window.vsync + +echo "Testing tick pacing requires the headless runner" +block: + for flags in [ + @["--headless-tick-rate", "24"], + @["--headless-tick-rate=24"], + @["--headless-tick-rate:24"], + @["--headless-tick-rate", "0"] + ]: + let arguments = @["--bot", "base.bas:4"] & flags + when defined(headless): + let launch = parseGameOptions(arguments) + doAssert launch.options.headlessTickRate == + (if flags[^1] == "0": 0 else: 24) + else: + doAssert rejects(arguments) + +echo "Testing LLM mode requires the headless request barrier" +block: + for flags in [ + @["--llm-mode", "barrier"], + @["--llm-mode=barrier"], + @["--llm-mode:barrier"], + @["--llm-mode", "async"] + ]: + let arguments = @["--bot", "base.bas:4"] & flags + when defined(headless): + let launch = parseGameOptions(arguments) + doAssert launch.options.waitForLlm == (flags[^1] != "async") + else: + doAssert rejects(arguments) + +echo "Testing Call to Adventure arena configuration stays local to a parse" +block: + let arena = parseGameOptions(@[ + "--bot", "base.bas:4", "--arena", "--hero", "fighter", + "--monster=dustling", "--monsters:3" + ]) + doAssert arena.arena.enabled + doAssert arena.arena.heroes == @[FighterClass] + doAssert arena.arena.arenaMonsters().len == 3 + let ordinary = parseGameOptions(@["--bot", "base.bas:4"]) + doAssert not ordinary.arena.enabled + doAssert ordinary.arena.count == 10 + +echo "Testing Call to Adventure rejects conflicting and unsupported options" +block: + for arguments in [ + @["--bot", "base.bas:3"], + @["--bot", "base.bas:4", "--name", "Ada"], + @["--bot", "base.bas:4", "--server", "ws://localhost:9911/ws"], + @["--bot", "base.bas:4", "--room", "ABCD"], + @["--replay", "saved.replay", "--record", "copy.replay"], + @["--replay", "saved.replay", "--bots", "base.bas:4"], + @["--replay", "saved.replay", "--ticks", "3"], + @["--replay", "saved.replay", "--seed", "17"], + @["--arena", "--bot", "base.bas:4", "--record", "arena.replay"], + @["--bot", "base.bas:4", "--player", "Ada"], + @["--bot", "base.bas:4", "--speed", "0"] + ]: + doAssert rejects(arguments) + +echo "Call to Adventure command-line tests passed" diff --git a/games/call_to_adventure/tests/tests.nim b/games/call_to_adventure/tests/tests.nim index 0febc81af..bb8afeb6e 100644 --- a/games/call_to_adventure/tests/tests.nim +++ b/games/call_to_adventure/tests/tests.nim @@ -2,6 +2,7 @@ {.warning[UnusedImport]: off.} import + test_options, test_maps, test_nav, test_replays, diff --git a/games/crewrift/game.nim b/games/crewrift/game.nim index aa6e77714..0aeddbdde 100644 --- a/games/crewrift/game.nim +++ b/games/crewrift/game.nim @@ -3,16 +3,20 @@ import std/[os, strutils], bassy, - polyworld/[cli, policies], + polyworld/[cli, policies, screenshots, timings], sim, maps, bots, replays type Options* = object seed*, players*, ticks*, player*: int - speed*: float32 - soundMuted*: bool = true - role*, name*, record*, replay*, screenshot*: string - width*, height*, captureTicks*: int + speed*: int32 + soundMuted*, pauseOnStart*, verbose*, seedSpecified*: bool + vsync*: bool = true + headlessTickRate*: int32 + role*, name*, record*, replay*: string + width*, height*: int32 + captureTicks*: int + capture*: ScreenshotOptions botGroups*: seq[BotGroup] Game* = ref object world*: SimServer @@ -31,49 +35,41 @@ type proc usage() = ## Prints the controls and native or headless launch options. echo "Crewrift in Polyworld" - echo " WASD: move or select vote. E / Space: use, kill, vote." - echo " Arrows / middle / right drag: pan. Wheel: zoom. C: action camera." - echo " Click / shift-click / box select: follow crew. Ctrl+A: select all." - echo " Q: vent. Enter: meeting chat. Tab: map. R: new match." - echo " --player:N Control slot N (1-16, default 1)." - echo " --name:NAME Human player's name in the roster and replay." - echo " --spectate Let local bots play every slot." + when not defined(headless): + echo " WASD: move or select vote. E / Space: use, kill, vote." + echo " Arrows / middle / right drag: pan. Wheel: zoom. C: action camera." + echo " Click / shift-click / box select: follow crew. Ctrl+A: select all." + echo " Q: vent. Enter: meeting chat. Tab: map. R: new match." + echo " --player [N] Control slot N (1-16, bare flag selects 1)." + echo " --name NAME Human player's name in the roster and replay." + echo " --spectate Let local bots play every slot (the default)." echo " --bot PATH[:N] Use a BASIC program for N bot slots (default 1)." - echo " --bot:PATH[:N] Equivalent compact form; other slots use base.bas." - echo " --role:crew|imp Choose your role, or omit for random roles." - echo " --players:N Roster size (8-16, default 8)." - echo " --seed:N Match seed (default 2026)." - echo " --ticks:N Maximum active ticks (default 10000)." - echo " --speed:N Simulation speed (default 1)." - echo " --record:PATH Save an input replay with tick fingerprints." - echo " --replay:PATH Play and verify a saved input replay." - echo " --windowSize:WxH Window size (default 1440x900)." - echo " --screenshot:PATH Save a frame and exit." - echo " --mute[=BOOL] Start muted (default true)." + echo " --bots PATH[:N] Same as --bot; explicit bots must fill the roster." + echo " Without bot options, every bot uses base.bas." + when not defined(headless): + echo " --role crew|imp Choose your human role, or omit for random roles." + echo " --players N Roster size (8-16, default 8)." + echo " --seed N Match seed (default 2026)." + echo " --ticks N Maximum active ticks (default 10000)." + echo " --seconds N Same duration in seconds; --minutes N also works." + when not defined(headless): + echo " --speed N Simulation speed (default 1)." + echo " --play BOOL Start the viewer playing or paused." + echo " --record PATH Save an input replay with tick fingerprints." + echo " --replay PATH Play and verify a saved input replay." + when not defined(headless): + echo " --windowSize WxH Window size (default 1440x900)." + echo " --screenshot PATH Save a PNG and exit after --frames N (default 30)." + echo " --capture-ticks:N Advance N ticks before capture frames (default 0)." + echo " --vsync BOOL Enable display synchronization (default true)." + echo " --mute[=BOOL] Request muted audio." echo " --unmute Start with sound enabled." + echo " --verbose Print the resolved match setup." + when defined(headless): + echo " --headless-tick-rate N Pace headless ticks (default 0: unlimited)." + echo "All value flags accept spaces, =, or : separators." echo "Compile with -d:headless to run and verify without graphics." -proc addBotOption(groups: var seq[BotGroup], specification: string) = - ## Validates the shared bot syntax using Crewrift's error boundary. - var path = specification - let separator = specification.rfind(':') - if separator >= 0 and separator < specification.high: - let suffix = specification[separator + 1 .. ^1] - var numeric = true - for character in suffix: - if character notin {'0' .. '9'}: - numeric = false - break - if numeric: - path = specification[0 ..< separator] - let count = parseBiggestInt(suffix) - if count < 1 or count > MaxPlayers: - raise newException(CrewriftError, - "Bot count must be between 1 and " & $MaxPlayers & ".") - if path.len == 0: - raise newException(CrewriftError, "--bot requires a BASIC source path.") - groups.addBotSpec(specification) - proc validateBots(options: Options) = ## Rejects bot groups that cannot fit the live roster before reading files. if options.replay.len > 0: @@ -87,78 +83,92 @@ proc validateBots(options: Options) = raise newException(CrewriftError, "Too many bots for " & $available & " available slots.") count += group.count + if options.botGroups.len > 0 and count != available: + raise newException(CrewriftError, + "Explicit bots must fill " & $available & " slots; configured " & + $count & ".") proc parseOptions*(arguments = commandLineParams()): Options = ## Parses the shared native and headless command surface. - result = Options( - seed: 2026, players: MinPlayers, ticks: MaxTicks, - player: 0, speed: 1, width: 1440, height: 900, - captureTicks: RoleRevealTicks + 12 - ) - when defined(headless): - result.player = -1 - var index = 0 - while index < arguments.len: - let argument = arguments[index] - inc index - let - parts = argument.split(':', 1) - flag = parts[0] - value = if parts.len > 1: parts[1] else: "" - try: - if result.soundMuted.takeSoundFlag(argument): - continue - if argument == "--bot": - if index >= arguments.len: - raise newException(CrewriftError, - "--bot requires a BASIC source path.") - result.botGroups.addBotOption(arguments[index]) - inc index - continue - if argument.startsWith("--bot="): - result.botGroups.addBotOption(argument[6 .. ^1]) - continue - case flag - of "--bot": result.botGroups.addBotOption(value) - of "--seed": result.seed = parseInt(value) - of "--players": result.players = parseInt(value) - of "--ticks": result.ticks = parseInt(value) - of "--player": result.player = parseInt(value) - 1 - of "--name": result.name = value.strip() - of "--spectate": result.player = -1 - of "--speed": result.speed = parseFloat(value).float32 - of "--role": result.role = value - of "--record": result.record = value - of "--replay": result.replay = value - of "--screenshot": result.screenshot = value - of "--capture-ticks": result.captureTicks = parseInt(value) - of "--windowSize": - let size = value.toLowerAscii().split('x') - if size.len != 2: - raise newException(CrewriftError, "Expected --windowSize:WxH.") - result.width = parseInt(size[0]) - result.height = parseInt(size[1]) - of "--help", "-h": - usage() - quit(0) + result.players = MinPlayers + var + common = GameOptions(seed: 2026, maximumTicks: MaxTicks, + speed: 1, windowWidth: 1440, windowHeight: 900) + index = 0 + spectate = false + try: + while index < arguments.len: + let + argument = arguments[index] + flag = argument.splitFlag().name + if common.takeCommonFlag(arguments, index, argument): + discard else: - raise newException(CrewriftError, "Unknown argument: " & argument) - except ValueError as error: - raise newException(CrewriftError, "Invalid option: " & error.msg) - if result.seed < RandomSeedSentinel or - result.players < MinPlayers or result.players > MaxPlayers or + case flag + of "--players", "--role", "--capture-ticks": + let value = arguments.flagValue(index, argument) + case flag + of "--players": result.players = parsePositiveInt32(value, flag).int + of "--role": result.role = value + of "--capture-ticks": + result.captureTicks = parseInt32(value, flag).int + else: discard + of "--spectate": + if argument != flag: + raise newException(CrewriftError, "--spectate takes no value.") + spectate = true + of "--help", "-h": + usage() + quit(0) + else: + raise newException(CrewriftError, "Unknown argument: " & argument) + inc index + if spectate and common.playerSlot != 0: + raise newException(CrewriftError, "--spectate cannot be used with --player.") + var supported = AllCommonFlags - {LlmModeFlag, ServerFlag, RoomFlag} + when not defined(headless): + supported.excl HeadlessTickRateFlag + common.rejectUnsupportedFlags(supported) + common.validateGameOptions(0, "") + if NameFlag in common.specifiedFlags and common.playerSlot == 0: + raise newException(CrewriftError, "--name requires --player.") + except ValueError as error: + raise newException(CrewriftError, "Invalid option: " & error.msg) + result.seed = common.seed + result.seedSpecified = SeedFlag in common.specifiedFlags + result.ticks = common.maximumTicks + result.player = common.playerSlot.int - 1 + result.speed = common.speed + result.soundMuted = common.soundMuted + result.name = common.playerName + result.record = common.recordPath + result.replay = common.replayPath + result.width = common.windowWidth + result.height = common.windowHeight + result.capture = common.capture + result.botGroups = common.botGroups + result.pauseOnStart = common.pauseOnStart + result.vsync = common.vsync + result.verbose = common.verbose + result.headlessTickRate = common.headlessTickRate + if result.players < MinPlayers or result.players > MaxPlayers or result.player < -1 or result.player >= result.players or result.ticks < 1 or result.ticks > 1_000_000 or result.captureTicks < 0 or result.captureTicks > 1_000_000 or - not (result.speed > 0 and result.speed <= 16) or - result.width < 800 or result.height < 600: + result.speed <= 0 or result.width <= 0 or result.height <= 0: raise newException(CrewriftError, "Invalid roster, time, or window size.") if result.role notin ["", "crew", "imp"]: raise newException(CrewriftError, "Role must be crew or imp.") - if result.record.len > 0 and result.replay.len > 0: - raise newException(CrewriftError, "Choose recording or replay playback.") + if result.role.len > 0 and result.player < 0: + raise newException(CrewriftError, "--role requires --player.") if result.name.len > 128 or result.name != cleanChatMessage(result.name): raise newException(CrewriftError, "Player name must be printable text.") + try: + result.capture.validateCapture() + except ScreenshotError as error: + raise newException(CrewriftError, error.msg) + if result.capture.captureRequested(): + result.soundMuted = true result.validateBots() proc loadBotSources(game: Game, options: Options) = @@ -201,7 +211,7 @@ proc rewind*(game: Game) = ## Restores the resolved match setup while retaining the input tape. var config = game.recording.config config.minPlayers = game.recording.players - game.world = initSimServer(config) + game.world = initSimServer(config, resolveSeed = false) game.world.fitStations() game.world.gameEventLoggingEnabled = false for i in 0 ..< config.minPlayers: @@ -238,6 +248,8 @@ proc newGame*(options: Options): Game = result.recording = loadReplay(options.replay) result.playback = true else: + if not options.seedSpecified: + config.resolveRandomSeed() result.recording = ReplayData( version: ReplayVersion, config: config, players: config.minPlayers @@ -245,6 +257,10 @@ proc newGame*(options: Options): Game = result.loadBotSources(options) result.rewind() result.recording.config = result.world.config + if options.verbose: + echo "Crewrift setup: ", result.world.players.len, " players, seed ", + result.world.config.seed, ", human slot ", options.player + 1, + ", replay ", result.playback proc rosterName*(game: Game, slot: int): string = ## Labels each crew color with its recorded human or policy identity. @@ -334,8 +350,10 @@ proc advance*(game: Game, player = -1, record = false) = proc runHeadless*(options: Options) = ## Runs local policies or verifies all recorded simulation ticks. let game = newGame(options) + var pacer = initTickPacer(options.headlessTickRate) while not game.finished(): game.advance(record = options.record.len > 0) + pacer.pace() saveReplay(options.record, game.recording) let outcome = if game.world.phase != GameOver: "partial replay" diff --git a/games/crewrift/graphics.nim b/games/crewrift/graphics.nim index 22a9ed2e8..f0b7ffe92 100644 --- a/games/crewrift/graphics.nim +++ b/games/crewrift/graphics.nim @@ -715,6 +715,7 @@ proc drawReplayControls( proc runGraphics*(initial: Options) = ## Runs the playable native or browser viewer with fixed simulation ticks. + configureCapture(initial.capture, "crewrift.png") var options = initial game = newGame(options) @@ -728,6 +729,7 @@ proc runGraphics*(initial: Options) = durationTicks = (game.world.config.maxTicks + game.world.config.roleRevealTicks).int32, speed = options.speed.int32, + playing = not options.pauseOnStart, repeating = game.playback ) actionCam = initActionCam( @@ -738,6 +740,7 @@ proc runGraphics*(initial: Options) = mapSpan = MapColumns.float32 ) clock: ViewingClock + renderedFrames = 0 captureFrames = 0 if existsEnv("SHOW_TILES"): try: @@ -809,7 +812,7 @@ proc runGraphics*(initial: Options) = "Crewrift / Polyworld", AtlasPath, ivec2(options.width.int32, options.height.int32), - true + options.vsync ) sk.builder = builder defer: @@ -819,7 +822,9 @@ proc runGraphics*(initial: Options) = terrain = loadShipSkin() markers = initShapeRenderer() starField = initStarField() + captureTarget: ScreenshotTarget defer: + captureTarget.releaseScreenshotTarget() terrain.clearFromGpu() markers.closeShapeRenderer() starField.close() @@ -947,7 +952,7 @@ proc runGraphics*(initial: Options) = state.typing = false state.text.setLen(0) syncTransport() - if options.screenshot.len > 0 and captureFrames == 0: + if captureActive() and renderedFrames == 0: for i in 0 ..< options.captureTicks: game.advance(slot, record = true) syncTransport() @@ -973,7 +978,7 @@ proc runGraphics*(initial: Options) = state.camera.distance ) state.camera.overview = false - if captureFrames == 0: + if renderedFrames == 0: state.camera.target = if slot < 0: worldPoint(MapWidth div 2 - 48, MapHeight div 2) @@ -1022,6 +1027,7 @@ proc runGraphics*(initial: Options) = blocked = mouseOverDebugMenu(window.mousePos.vec2) ) scene.beginCharacters(window, view, projection, eye) + discard captureTarget.beginScreenshotFrame(window) scene.renderer.clearScreen(color(0.025, 0.045, 0.085, 1)) starField.draw( vp, @@ -1106,7 +1112,7 @@ proc runGraphics*(initial: Options) = elif moving: CrewClips[1] else: CrewClips[0] visuals[i].position = mix(visuals[i].position, position, damping(20, dt)) - if captureFrames == 0 or restoreTick >= 0 or + if renderedFrames == 0 or restoreTick >= 0 or game.world.phase != Playing or length(visuals[i].position - position) > 5: visuals[i].position = position @@ -1134,15 +1140,8 @@ proc runGraphics*(initial: Options) = ) sk.drawDebugMenu(window) sk.endUi() - inc captureFrames - if options.screenshot.len > 0 and captureFrames >= 3: - let screenshot = newImage(window.size.x, window.size.y) - glReadPixels( - 0, 0, window.size.x, window.size.y, GL_RGBA, GL_UNSIGNED_BYTE, - screenshot.data[0].addr - ) - screenshot.flipVertical() - screenshot.writeFile(options.screenshot) + inc renderedFrames + if captureFrame(window, captureFrames): break window.swapBuffers() waitForDisplay() diff --git a/games/crewrift/sim.nim b/games/crewrift/sim.nim index 3dc095909..9917c5a9e 100644 --- a/games/crewrift/sim.nim +++ b/games/crewrift/sim.nim @@ -711,11 +711,6 @@ proc validate(config: GameConfig) = CrewriftError, "Config field frictionDen must be positive." ) - if config.seed < RandomSeedSentinel: - raise newException( - CrewriftError, - "Config field seed must be -1 or greater." - ) if config.minPlayers < 1: raise newException( CrewriftError, @@ -893,7 +888,7 @@ proc update*(config: var GameConfig, jsonText: string) = proc timeGameSeed*(): int = ## Returns a positive game seed derived from wall-clock time. - result = int(epochTime() * 1000) mod RandomSeedMod + result = int(int64(epochTime() * 1000) mod RandomSeedMod.int64) if result < 0: result += RandomSeedMod @@ -3024,11 +3019,12 @@ proc loadCrewriftMap*(path = ""): CrewriftMap = except ValueError as error: raise newException(CrewriftError, "Invalid map metadata: " & error.msg) -proc initSimServer*(config: GameConfig): SimServer = +proc initSimServer*(config: GameConfig, resolveSeed = true): SimServer = ## Creates fixed-tick rules with collision derived from the selected floor. config.validate() var resolvedConfig = config - resolvedConfig.resolveRandomSeed() + if resolveSeed: + resolvedConfig.resolveRandomSeed() result.config = resolvedConfig result.rng = initRand(resolvedConfig.seed) result.gameMap = loadCrewriftMap(config.mapPath) diff --git a/games/crewrift/tests/test_bots.nim b/games/crewrift/tests/test_bots.nim index 737bcb4dc..e6a8a8504 100644 --- a/games/crewrift/tests/test_bots.nim +++ b/games/crewrift/tests/test_bots.nim @@ -52,17 +52,23 @@ block: let directory = createTempDir("crewrift-bots-", "") defer: removeDir(directory) - let path = directory / "move.bas" + let + path = directory / "move.bas" + defaultPath = directory / "base.bas" writeFile(path, MoveSource) + writeFile(defaultPath, DefaultBotSource) for arguments in [ - @["--spectate", "--bot", path & ":2"], - @["--spectate", "--bot:" & path & ":2"], - @["--spectate", "--bot=" & path & ":2"] + @["--spectate", "--bot", path & ":8"], + @["--spectate", "--bot:" & path & ":8"], + @["--spectate", "--bot=" & path & ":8"] ]: let parsed = parseOptions(arguments) - doAssert parsed.botGroups == @[BotGroup(path: path, count: 2)] + doAssert parsed.botGroups == @[BotGroup(path: path, count: 8)] var options = botOptions() - options.botGroups = @[BotGroup(path: path, count: 2)] + options.botGroups = @[ + BotGroup(path: path, count: 2), + BotGroup(path: defaultPath, count: MinPlayers - 2) + ] let game = newGame(options) game.enterPlaying() let start = game.world.players[0].x @@ -80,6 +86,7 @@ block: options.player = 2 options.name = "Human" options.botGroups[0].count = 3 + options.botGroups[1].count = MinPlayers - 4 let human = newGame(options) doAssert human.bots[2].runtime == nil doAssert human.rosterName(2).endsWith("(Human)") @@ -93,7 +100,7 @@ block: removeDir(directory) let path = directory / "broken.bas" var options = botOptions() - options.botGroups = @[BotGroup(path: path, count: 1)] + options.botGroups = @[BotGroup(path: path, count: MinPlayers)] for source in ["", "if then"]: if source.len > 0: writeFile(path, source) diff --git a/games/crewrift/tests/test_capture_options.nim b/games/crewrift/tests/test_capture_options.nim new file mode 100644 index 000000000..228a68e8f --- /dev/null +++ b/games/crewrift/tests/test_capture_options.nim @@ -0,0 +1,59 @@ +import + std/strutils, + ../[game, sim] + +echo "Testing shared Crewrift capture arguments" +block: + let options = parseOptions(@[]) + doAssert options.capture.path.len == 0 + doAssert options.capture.frames == 30 + doAssert options.captureTicks == 0 + doAssert options.width == 1440 and options.height == 900 + +for arguments in [ + @["--screenshot", "output/crew shot.png", "--frames", "2", + "--windowSize", "1280x720", "--seed:19"], + @["--screenshot=output/crew shot.png", "--frames=2", + "--windowSize=1280x720", "--seed:19"], + @["--screenshot:output/crew shot.png", "--frames:2", + "--windowSize:1280x720", "--seed:19"] +]: + when defined(headless) or defined(emscripten): + var rejected = false + try: + discard parseOptions(arguments) + except CrewriftError as error: + rejected = "graphical" in error.msg or "native" in error.msg + doAssert rejected, "Capture needs a native graphical client." + else: + let options = parseOptions(arguments) + doAssert options.capture.path == "output/crew shot.png" + doAssert options.capture.frames == 2 + doAssert options.capture.framesSpecified + doAssert options.width == 1280 and options.height == 720 + doAssert options.seed == 19 + doAssert options.soundMuted + doAssert options.captureTicks == 0 + +for arguments in [ + @["--screenshot"], @["--screenshot="], @["--frames"], + @["--frames:0"], @["--frames=-1"], @["--frames=bad"], + @["--windowSize"], @["--windowSize=0x720"], + @["--windowSize=bad"] +]: + var rejected = false + try: + discard parseOptions(arguments) + except CrewriftError: + rejected = true + doAssert rejected, "Invalid capture arguments must fail: " & $arguments + +when not defined(headless) and not defined(emscripten): + let options = parseOptions(@[ + "--unmute", "--screenshot", "output/crew.png", "--capture-ticks:12" + ]) + doAssert options.soundMuted + doAssert options.capture.frames == 30 + doAssert options.captureTicks == 12 + +echo "Crewrift capture argument checks passed" diff --git a/games/crewrift/tests/test_cli.nim b/games/crewrift/tests/test_cli.nim new file mode 100644 index 000000000..1d57d0a4d --- /dev/null +++ b/games/crewrift/tests/test_cli.nim @@ -0,0 +1,150 @@ +import ../[game, sim] + +when defined(headless): + import std/strutils + +echo "Testing Crewrift shared command-line options" +block: + let options = parseOptions(@[]) + doAssert options.player == -1 + doAssert options.speed == 1 + doAssert options.vsync + doAssert not options.pauseOnStart + doAssert not options.soundMuted + doAssert not options.seedSpecified + +for arguments in [ + @["--seed", "-1"], @["--seed=-1"], @["--seed:-1"] +]: + let options = parseOptions(arguments) + doAssert options.seed == -1 and options.seedSpecified +doAssert parseOptions(@["--seed", "-2147483648"]).seed == int32.low.int + +for arguments in [ + @["--seed", "17", "--bot", "first.bas:2", "--bots", "second.bas:6", + "--record", "output/crew replay.json", "--ticks", "240", + "--verbose"], + @["--seed=17", "--bot=first.bas:2", "--bots=second.bas:6", + "--record=output/crew replay.json", "--ticks=240", + "--verbose=true"], + @["--seed:17", "--bot:first.bas:2", "--bots:second.bas:6", + "--record:output/crew replay.json", "--ticks:240", + "--verbose:true"] +]: + let options = parseOptions(arguments) + doAssert options.seed == 17 + doAssert options.seedSpecified + doAssert options.botGroups.len == 2 + doAssert options.botGroups[0].path == "first.bas" + doAssert options.botGroups[0].count == 2 + doAssert options.botGroups[1].path == "second.bas" + doAssert options.botGroups[1].count == 6 + doAssert options.player == -1 + doAssert options.record == "output/crew replay.json" + doAssert options.ticks == 240 + doAssert options.headlessTickRate == 0 + doAssert options.name.len == 0 + doAssert options.verbose + +for arguments in [ + @["--headless-tick-rate", "24"], @["--headless-tick-rate=24"], + @["--headless-tick-rate:24"] +]: + when defined(headless): + doAssert parseOptions(arguments).headlessTickRate == 24 + else: + var rejected = false + try: + discard parseOptions(arguments) + except CrewriftError: + rejected = true + doAssert rejected + +for arguments in [ + @["--speed", "4", "--play", "false", "--vsync", "off"], + @["--speed=4", "--play=false", "--vsync=off"], + @["--speed:4", "--play:false", "--vsync:off"] +]: + when defined(headless): + var rejected = false + try: + discard parseOptions(arguments) + except CrewriftError: + rejected = true + doAssert rejected + else: + let options = parseOptions(arguments) + doAssert options.speed == 4 + doAssert options.pauseOnStart and not options.vsync + +for arguments in [ + @["--replay", "C:\\recordings\\crew replay.json"], + @["--replay=C:\\recordings\\crew replay.json"], + @["--replay:C:\\recordings\\crew replay.json"] +]: + let options = parseOptions(arguments) + doAssert options.replay == "C:\\recordings\\crew replay.json" + doAssert options.player == -1 + +block: + doAssert parseOptions(@["--seconds", "10"]).ticks == 240 + doAssert parseOptions(@["--minutes=2"]).ticks == 2880 + doAssert parseOptions(@["--minutes:2", "--ticks", "12"]).ticks == 12 + doAssert parseOptions(@["--players", "12"]).players == 12 + doAssert parseOptions(@["--players=12"]).players == 12 + doAssert parseOptions(@["--players:12"]).players == 12 + doAssert parseOptions(@["--capture-ticks", "0"]).captureTicks == 0 + +when not defined(headless): + for arguments in [ + @["--player", "2"], @["--player=2"], @["--player:2"] + ]: + doAssert parseOptions(arguments).player == 1 + doAssert parseOptions(@["--player"]).player == 0 + let named = parseOptions(@["--player", "--name", "Pilot", "--role", "crew"]) + doAssert named.player == 0 and named.name == "Pilot" + doAssert named.role == "crew" + let human = parseOptions(@["--player", "2", "--bots", "base.bas:7"]) + doAssert human.player == 1 + doAssert human.botGroups[0].count == 7 + for arguments in [ + @["--player", "2", "--name", "Crew Name"], + @["--player=2", "--name=Crew Name"], + @["--player:2", "--name:Crew Name"] + ]: + let named = parseOptions(arguments) + doAssert named.player == 1 and named.name == "Crew Name" + +for arguments in [ + @["--record"], @["--record", "--seed", "9"], @["--replay="], + @["--replay", "old.json", "--record", "new.json"], + @["--replay", "old.json", "--bots", "base.bas"], + @["--replay", "old.json", "--player"], + @["--player", "Pilot"], @["--player", "17"], + @["--spectate", "--player"], @["--role", "crew"], + @["--name", "Crew Name"], @["--name=Crew Name"], + @["--name:Crew Name"], @["--spectate", "--name", "Crew Name"], + @["--bots", "base.bas:8", "--name", "Crew Name"], + @["--bot", "base.bas:17"], @["--bots=base.bas:0"], + @["--bot", "base.bas:2"], + @["--player", "--bot", "base.bas:6"], + @["--bot", "base.bas:999999999999999999999999"], + @["--llm-mode", "async"], @["--server", "ws://localhost:9911/ws"], + @["--room", "ABCD"], @["--players", "--ticks", "20"] +]: + var rejected = false + try: + discard parseOptions(arguments) + except CrewriftError as error: + rejected = error.msg.len > 0 + doAssert rejected, "Invalid launch must fail: " & $arguments + +when defined(headless): + var rejected = false + try: + discard parseOptions(@["--player"]) + except CrewriftError as error: + rejected = "graphical" in error.msg + doAssert rejected + +echo "Crewrift shared CLI checks passed" diff --git a/games/crewrift/tests/test_seeds.nim b/games/crewrift/tests/test_seeds.nim new file mode 100644 index 000000000..ef860dd56 --- /dev/null +++ b/games/crewrift/tests/test_seeds.nim @@ -0,0 +1,52 @@ +import + std/[os, tempfiles], + ../[game, replays, sim] + +echo "Testing explicit negative Crewrift seeds remain deterministic" +block: + let directory = createTempDir("crewrift-negative-seeds-", "") + defer: removeDir(directory) + for seed in [-1, -17, int32.low.int]: + let + options = parseOptions(@["--seed", $seed]) + first = newGame(options) + second = newGame(options) + doAssert first.world.config.seed == seed + doAssert first.recording.config.seed == seed + doAssert first.world.gameHash() == second.world.gameHash() + for tick in 0 ..< 16: + first.advance(record = true) + second.advance(record = true) + doAssert first.recording.frames == second.recording.frames + doAssert first.world.rng == second.world.rng + let + expected = first.world.gameHash() + path = directory / ($seed & ".json") + saveReplay(path, first.recording) + first.rewind() + doAssert first.world.config.seed == seed + for tick in 0 ..< 16: + first.advance(record = true) + doAssert first.world.gameHash() == expected + let playback = newGame(parseOptions(@["--replay", path])) + doAssert playback.world.config.seed == seed + for tick in 0 ..< 16: + playback.advance() + doAssert playback.world.gameHash() == expected + +echo "Testing implicit random seed resolution remains recorded" +block: + var options = parseOptions(@[]) + options.seed = RandomSeedSentinel + let game = newGame(options) + doAssert game.world.config.seed >= 0 + doAssert game.recording.config.seed == game.world.config.seed + let expected = game.world.gameHash() + game.rewind() + doAssert game.world.gameHash() == expected + var config = defaultGameConfig() + doAssert config.seed == RandomSeedSentinel + config.resolveRandomSeed() + doAssert config.seed >= 0 + +echo "Crewrift seed checks passed" diff --git a/games/crewrift/tests/test_sim.nim b/games/crewrift/tests/test_sim.nim index 0c4cf3976..4dfe62299 100644 --- a/games/crewrift/tests/test_sim.nim +++ b/games/crewrift/tests/test_sim.nim @@ -604,7 +604,7 @@ block: echo "Testing muted launch options" block: - doAssert parseOptions(@[]).soundMuted + doAssert not parseOptions(@[]).soundMuted doAssert parseOptions(@["--mute"]).soundMuted doAssert not parseOptions(@["--unmute"]).soundMuted doAssert not parseOptions(@["--mute=false"]).soundMuted diff --git a/games/crewrift/tests/tests.nim b/games/crewrift/tests/tests.nim index 0a446ab54..7b867dffc 100644 --- a/games/crewrift/tests/tests.nim +++ b/games/crewrift/tests/tests.nim @@ -2,6 +2,9 @@ {.warning[UnusedImport]: off.} import + test_cli, + test_seeds, + test_capture_options, test_sim, test_bots, test_skins diff --git a/games/gods_of_the_arena/bots.nim b/games/gods_of_the_arena/bots.nim index f3da001e4..3bf906669 100644 --- a/games/gods_of_the_arena/bots.nim +++ b/games/gods_of_the_arena/bots.nim @@ -509,15 +509,8 @@ proc initHeroHost( result = activeGame.sendChat(player, int(args[0].asInt), text) let pullMailboxProc: NumericHostProc = proc(args: openArray[Value]): Value = ## Copies the oldest message into BASIC and consumes it on success. - let - player = activeGame.world.heroIndex(heroId) - inbox = activeGame.inboxes[player] - var runtime = activeGame.heroVms[player].runtime - if inbox.count == 0: - result = runtime.putString("") - else: - result = runtime.putString(inbox.messages[inbox.first]) - discard inbox.pop() + let player = activeGame.world.heroIndex(heroId) + activeGame.heroVms[player].runtime.pullMailboxString(activeGame.inboxes[player]) let mailboxIdProc: HostProc = proc(args: openArray[int32]): int32 = ## Returns the channel or DM sender of the last pulled message. activeGame.inboxes[activeGame.world.heroIndex(heroId)].lastId diff --git a/games/gods_of_the_arena/docs/command-line.md b/games/gods_of_the_arena/docs/command-line.md new file mode 100644 index 000000000..727d4d91b --- /dev/null +++ b/games/gods_of_the_arena/docs/command-line.md @@ -0,0 +1,38 @@ +# Command-line options + +GotA uses the [shared game arguments](../../../docs/command-line.md) for bot +rosters, human slots, replay files, playback, and display settings. All shared +value flags accept separate, equals, and colon forms. + +```sh +./gota --bots players/base.bas:10 --record replays/match.replay --seed 7 +./gota --player 2 --bot players/base.bas:9 --name Alice +./gota --replay replays/match.replay --play false --speed 3 +./gota --server ws://localhost:9911/ws --room ABC123 --name Alice +``` + +Paths are relative to the directory from which the game was launched. Bot paths +refer to actual files; the examples above assume a launch from the game folder. +`--player` selects a one-based human slot and defaults to slot one. Display names +use `--name`, including names made entirely of digits. + +Direct local matches require ten total slots: ten bots, or nine bots and one +human. Explicit bot or human arguments launch the match directly. With no roster +or replay, the menu opens. Explicit `--server` or `--room` opens Multiplayer; +choose human and bot seats there. + +`--record PATH` also applies to live matches started from the menus. The explicit +playback and window choices are preserved when entering a match. Saved fullscreen +preferences do not replace an explicit `--windowSize`. + +Live multiplayer controllers follow the server clock. `--play` and `--speed` +control local games, file replays, and spectator playback, and do not change the +server's match speed. + +`--headless-tick-rate` and `--llm-mode` belong to the headless runner. Graphical +builds reject those options, and headless builds reject graphical controls. + +GotA's draft has deadlines and always advances. `--play false` pauses when the +battle begins; it does not stop draft deadlines. Duration flags count battle time, +with drafting separate from that limit. `--seed` controls the match randomness; +the game-specific `--map-seed` changes the arena. diff --git a/games/gods_of_the_arena/frontend.nim b/games/gods_of_the_arena/frontend.nim index 7527abec8..5e2e49f49 100644 --- a/games/gods_of_the_arena/frontend.nim +++ b/games/gods_of_the_arena/frontend.nim @@ -2,10 +2,16 @@ import std/[os, random, strutils, uri], bumpy, chroma, jsony, silky, vmath, windy, polyworld/[displays, chrome, connections, menus, roomclients, rooms, policies, - sounds, viewers], + sounds, tapes, viewers], content, controls, game, graphics, homes, lobbies, multiplayer, playernames, pointers, presets, replays, settings, joiningseats +from polyworld/cli import BotFlag, DurationFlags, PlayerFlag, RecordFlag, + RoomFlag, SeedFlag, ServerFlag, WindowSizeFlag + +when not defined(emscripten): + import polyworld/replaysaves, replaylibraries, replaymenus + const AppName = "Polyworld GotA" proc bundledBot(name, file: string): LocalPolicy = @@ -26,7 +32,9 @@ proc runFrontend*() = error: string roomName: string matchName: string - invite = inviteParameter("room") + invite = + if options.roomCode.len > 0: options.roomCode + else: inviteParameter("room") joinRequested = invite.len > 0 connection: Connection joiningSeat: JoiningSeat @@ -51,12 +59,40 @@ proc runFrontend*() = editingPlayer: bool connectRequested: bool localLaunchRequested: bool + replayPreferences = ReplayPreferences() + when not defined(emscripten): + var + browsingReplays = false + replayBrowser = initReplayBrowser(Library) + replayAction: ReplayBrowserResult + unsavedReplays: seq[ReplayData] + retryReplaySave: bool + + proc retainUnsavedReplay(problem: ref CatchableError) = + ## Keeps failed automatic and manual saves available on the menu. + window.closeRequested = false + if shouldRetainReplay(replayPreferences.saveReplay, problem) and + run != nil and + run.recorder != nil and not run.replayMode: + try: + unsavedReplays.add(recordingData()) + except ReplayError: + discard + + proc drawReplayRetry() = + ## Offers a retry without losing the recording when the disk is full. + if sk.drawReplaySaveRetry(unsavedReplays.len > 0): + retryReplaySave = true try: preferences = readGotaPreferences() + when not defined(emscripten): + replayPreferences = readReplayPreferences() except MenusError, IOError, OSError: error = getCurrentExceptionMsg() roomName = defaultGameName(preferences.name) - preferences.applyPreferences(window) + preferences.applyPreferences(window, + configureDisplay = not captureActive() and + WindowSizeFlag notin options.specifiedFlags) window.updateCursorConfinement(preferences.edgeScrolling) let bots = @[ bundledBot("Base bot", "base"), @@ -87,9 +123,13 @@ proc runFrontend*() = while not window.closeRequested: when not defined(emscripten): - window.updateWindowSettings() + if not captureActive(): + window.updateWindowSettings() launchLocal = false launchNetwork = false + when not defined(emscripten): + replayAction = ReplayBrowserResult() + retryReplaySave = false if connectRequested and eligiblePlayerName(preferences.name): connectRequested = false try: @@ -174,10 +214,17 @@ proc runFrontend*() = prepared.humanHeroIndex() + 1 ) options.replayPath = "" - options.recordPath = "" - options.pauseOnStart = false - options.speed = 1 - let quitToMenu = runGraphics(prepared, connection) + var + quitToMenu = false + matchError: string + try: + quitToMenu = runGraphics(prepared, connection, + autoSaveReplay = replayPreferences.saveReplay) + except CatchableError as problem: + matchError = problem.msg + quitToMenu = connection.client.snapshot.room.len == 0 + when not defined(emscripten): + retainUnsavedReplay(problem) for i in 0 ..< min(networkPolicies.len, prepared.sources.len): networkPolicies[i].bytes = prepared.sources[i] if i < connection.client.snapshot.seats.len: @@ -207,6 +254,8 @@ proc runFrontend*() = preparedRevision = 0 clearPlayerCommands() run = nil + if matchError.len > 0: + error = matchError continue window.onButtonPress = proc(button: Button) = @@ -217,6 +266,7 @@ proc runFrontend*() = ) window.onFrame = proc() = ## Draws this lifecycle state without constructing a hidden match. + beginGotaFrame() updateSounds() window.updateCursorConfinement(preferences.edgeScrolling) let needsPlayerName = not eligiblePlayerName(preferences.name) @@ -271,31 +321,45 @@ proc runFrontend*() = if error.len > 0: sk.menuLabel(error, at + vec2(0, 272), color = LobbyRed) sk.endUi() - window.presentFrame(framePaceHz) + presentGotaFrame() + reportReplayFrame(0, 0) + return + when not defined(emscripten): + if browsingReplays: + replayAction = sk.drawReplayBrowser(window, replayBrowser) + sk.endUi() + presentGotaFrame() reportReplayFrame(0, 0) return if page == HomeMenu: - case sk.drawHome(window, homeFocus) - of StayHome: discard - of PlaySingle: + case sk.drawGotaHome(window, homeFocus) + of GotaStayHome: discard + of GotaPlaySingle: page = SingleMenu lobbyUi.scroll = 0 lobbyUi.selectedSeat = -1 - of PlayMultiplayer: + of GotaPlayMultiplayer: page = MultiplayerMenu connectRequested = preferences.server.strip().len > 0 and not connection.connecting() and (connection == nil or not connection.client.connected) lobbyUi.scroll = 0 lobbyUi.selectedSeat = -1 - of OpenSettings: page = SettingsMenu - of ExitGame: + of GotaOpenReplays: + when not defined(emscripten): + browsingReplays = true + replayBrowser.refreshRequested = true + replayBrowser.message = "" + of GotaOpenSettings: page = SettingsMenu + of GotaExitGame: when not defined(emscripten): window.closeRequested = true if error.len > 0: sk.menuLabel(error, vec2(24, 24), color = rgbx(245, 151, 139, 255)) + when not defined(emscripten): + drawReplayRetry() sk.endUi() - window.presentFrame(framePaceHz) + presentGotaFrame() reportReplayFrame(0, 0) return var layout: LobbyLayout @@ -652,6 +716,12 @@ proc runFrontend*() = sk.lobbyLabel(if humanSeat < 0: "Spectating bots" else: "Playing seat " & $(humanSeat + 1), layout.left + vec2(22, layout.panelHeight - 74), 800, tint = LobbyMuted) + when not defined(emscripten): + if sk.drawReplaySaveOption( + window, layout.left + vec2(22, layout.panelHeight - 38), + replayPreferences.saveReplay, not modal + ): + replayPreferences.saveReplayPreferences() let selectedSeat = lobbyUi.selectedSeat let choice = if lobbyUi.selectedSeat >= 0: sk.seatPicker(window, lobbyUi, bots) @@ -719,12 +789,60 @@ proc runFrontend*() = editingPlayer = true if error.len > 0: sk.lobbyLabel(error, vec2(24, 0), 1400, tint = rgbx(245, 151, 139, 255)) + when not defined(emscripten): + drawReplayRetry() sk.textStyle = "Default" sk.endUi() - window.presentFrame(framePaceHz) + presentGotaFrame() reportReplayFrame(0, 0) pollEvents() waitForDisplay() + when not defined(emscripten): + if retryReplaySave: + try: + unsavedReplays.retryReplaySaves( + proc(data: ReplayData): string = + ## Writes a retained game recording to its desktop library. + saveLibraryReplay(data) + ) + error = "" + replayBrowser.refreshRequested = true + except CatchableError as problem: + error = "Cannot save replay: " & problem.msg + if browsingReplays: + try: + let selected = replayBrowser.updateReplayBrowser(Library, replayAction) + case selected.action + of BackFromReplays: + browsingReplays = false + sk.resetInteractions() + of PlayReplay: + let previousOptions = options + try: + window.onFrame = nil + options.replayPath = selected.path + options.recordPath = "" + options.playerSlot = 0 + options.botGroups.setLen(0) + options.serverUrl = "" + options.roomCode = "" + options.specifiedFlags = options.specifiedFlags - + {BotFlag, PlayerFlag, RecordFlag, SeedFlag, ServerFlag, RoomFlag} - + DurationFlags + initializeMatch() + runGraphics() + preferences = readGotaPreferences() + replayBrowser.message = "" + finally: + options = previousOptions + clearPlayerCommands() + run = nil + replayBrowser.refreshRequested = true + else: + discard + except CatchableError as problem: + replayBrowser.message = problem.msg + continue if launchLocal: connection.close() connection = nil @@ -740,10 +858,12 @@ proc runFrontend*() = config.players[i].name = policy.name try: initializeLocalMatch(config, sources, humanSeat) - runGraphics() + runGraphics(autoSaveReplay = replayPreferences.saveReplay) preferences = readGotaPreferences() except CatchableError as problem: error = problem.msg + when not defined(emscripten): + retainUnsavedReplay(problem) page = HomeMenu run = nil window.onFrame = nil diff --git a/games/gods_of_the_arena/game.nim b/games/gods_of_the_arena/game.nim index 8020fd423..dfec7dfed 100644 --- a/games/gods_of_the_arena/game.nim +++ b/games/gods_of_the_arena/game.nim @@ -6,7 +6,7 @@ import std/[math, os, strformat, strutils, times], - polyworld/[cli, controllers, metrics, profiles, rooms, tapes, timings], + polyworld/[cli, controllers, metrics, profiles, tapes, timings], content, maps, sim, @@ -17,6 +17,12 @@ import when defined(coworld): import polyworld/coworld +const SupportedFlags = + when defined(headless): + AllCommonFlags - GraphicalFlags - {NameFlag, ServerFlag, RoomFlag} + else: + AllCommonFlags - {HeadlessTickRateFlag, LlmModeFlag} + var matchConfig* = GotaConfig(seed: ArenaSeed) serverAddress*: string @@ -26,40 +32,24 @@ var proc usage() = ## Prints the command-line and compile-time configuration surface. echo "Gods of the Arena" - echo " --server URL Open Multiplayer and connect to a ws/wss server." - echo " --bot:PATH Fill one of the 10 hero slots." - echo " --bot:PATH:N Fill N of the 10 slots with that file." - echo " --bot PATH[:N] The equivalent two-argument form." - echo " --player Control the first hero; supply 9 bots." - echo " --player:N Control hero N (1-10); supply 9 bots." - echo " --player NAME Save a nonnumeric player display name." - echo " --replay PATH Play an action replay instead of bots." - echo " --record PATH Record bot actions to a replay." - echo " --seconds NUMBER Battle seconds (default 1200)." - echo " --minutes NUMBER Battle minutes (default 20)." - echo " --ticks NUMBER Battle ticks (default 28800)." + echo commonUsageFor(SupportedFlags) + echo "Live matches use ten slots; a human takes one slot, leaving nine bots." + echo "The duration covers battle time (default 1200 seconds)." echo "Drafting allows 10 seconds per pick, separate from battle time." - echo " --seed NUMBER Match seed for draft order, bot turn order," - echo " and combat randomness; the arena stays fixed." + echo "Draft deadlines always advance; --play=false pauses after the draft." + echo "The match seed controls draft order, bots, and combat; the arena stays fixed." echo " --map-seed NUMBER Regenerate the arena from another seed (the" echo " league always plays the preset's own seed)." echo " --draft-mode MODE unique (default), team, or open." echo " --config PATH JSON match settings, including mapPreset." - echo " --headless-tick-rate N Wall-clock ticks per second, 0 is unlimited." - echo " --llm-mode:async|barrier Wait for all requests between headless ticks." echo " --spawn-interval NUMBER Seconds between waves." - echo " --play=false Start the graphical transport paused." - echo " --speed NUMBER Graphical start speed: 1, 2, 4, or 16." - echo " --windowSize WxH Graphical window, such as 1024x576." - echo " --vsync:off Unlock the frame rate (default on)." - echo " --mute[=true|false] Override saved sound levels for this launch." - echo " --unmute Enable sound for this launch." echo "Compile with -d:headless for command-line simulation." echo "Compile with -d:emscripten for the web backend." -proc parseGameOptions(validateMatch: bool): GameOptions = +proc parseGameOptions*( + arguments: seq[string], validateMatch = false +): GameOptions = ## Parses runtime game, bot, replay, and simulation configuration. - let arguments = commandLineParams() var index = 0 while index < arguments.len: if arguments[index] == "--config": @@ -77,25 +67,11 @@ proc parseGameOptions(validateMatch: bool): GameOptions = ) index = 0 while index < arguments.len: - var argument = arguments[index] - if argument == "--player" and index + 1 < arguments.len and - not arguments[index + 1].startsWith("--"): - argument = "--player=" & arguments.argumentValue(index, "--player") - if argument.startsWith("--player=") and - not argument[9 .. ^1].allCharsInSet({'0' .. '9'}): - let name = argument[9 .. ^1].strip() - if name.len > 64 or not name.validName: - fail("--player requires a nonempty display name of at most 64 bytes") - playerNameOverride = name - elif result.takeCommonFlag(arguments, index, argument): + let argument = arguments[index] + if result.takeCommonFlag(arguments, index, argument): discard else: case argument - of "--server": - serverAddress = arguments.argumentValue(index, "--server") - if not serverAddress.startsWith("ws://") and - not serverAddress.startsWith("wss://"): - fail("--server requires a ws:// or wss:// URL") of "--config": discard arguments.argumentValue(index, "--config") of "--draft-mode": @@ -130,17 +106,25 @@ proc parseGameOptions(validateMatch: bool): GameOptions = else: fail("unknown argument: " & argument) inc index - if serverAddress.len > 0: + result.rejectUnsupportedFlags(SupportedFlags) + result.resolveGamePaths() + serverAddress = result.serverUrl + playerNameOverride = result.playerName + if serverAddress.len > 0 or result.roomCode.len > 0: when defined(headless): - fail("--server requires the graphical client") - if result.botGroups.len > 0 or result.replayPath.len > 0 or - result.playerSlot > 0: - fail("--server uses lobby seats; select players and bots in the lobby") - if validateMatch or result.botGroups.len > 0 or result.replayPath.len > 0: - result.validateGameOptions( - HeroClassCount, - "live games require exactly 10 bots" - ) + fail("--server and --room require the graphical client") + else: + if result.botGroups.len > 0 or result.replayPath.len > 0 or + result.playerSlot > 0: + fail("--server and --room use lobby seats; " & + "select players and bots in the lobby") + result.validateGameOptions( + if validateMatch or result.botGroups.len > 0 or result.playerSlot > 0: + HeroClassCount + else: + 0, + "live games require exactly 10 slots" + ) var options*: GameOptions @@ -152,7 +136,12 @@ proc initializeOptions*() = options = coworldOptions(10) matchConfig = parseConfig(readLocal(getEnv("COGAME_CONFIG_URI"))) else: - options = parseGameOptions(defined(headless)) + options = parseGameOptions(commandLineParams(), defined(headless)) + if options.verbose: + echo "GotA launch: seed=", options.seed, + " bots=", options.botGroups.botCount, + " player=", options.playerSlot, + " replay=", options.replayPath proc initializeMatch*() = ## Creates a fresh local or replay session from explicit startup settings. @@ -291,14 +280,22 @@ proc startReplayRecording*(maximumTicks: uint32) = run.recorder.data.config = config run.replayPlayer = ReplayPlayer(data: run.recorder.data) +proc recordingData*(): ReplayData = + ## Captures the complete recorded timeline even when viewing an earlier tick. + if run == nil or run.recorder == nil or run.replayMode: + raise newException(ReplayError, "There is no live match replay to save.") + if run.recordingError.len > 0: + raise newException(ReplayError, run.recordingError) + if run.world.tick == run.recorder.data.hashes.len: + run.sampleMetrics(true) + result = run.recorder.data + result.metrics = run.history.replayMetrics() + proc saveRecording*(path = options.recordPath) = ## Finalizes and saves a requested action replay. if run.recorder == nil or path.len == 0: return - if run.world.tick == run.recorder.data.hashes.len: - run.sampleMetrics(true) - run.recorder.data.metrics = run.history.replayMetrics() - saveReplay(path, run.recorder.data) + saveReplay(path, recordingData()) echo &"replay saved: {path} " & &"({run.recorder.data.actions.len} actions)" @@ -400,9 +397,6 @@ proc initializeLocalMatch*( options.spawnIntervalTicks = config.spawnIntervalTicks options.playerSlot = int32(humanSeat + 1) options.replayPath = "" - options.recordPath = "" - options.pauseOnStart = false - options.speed = 1 clearPlayerCommands() var activeSeats: seq[int] var packedSources: seq[string] diff --git a/games/gods_of_the_arena/gota.nim b/games/gods_of_the_arena/gota.nim index 69782218b..54e11b3bd 100644 --- a/games/gods_of_the_arena/gota.nim +++ b/games/gods_of_the_arena/gota.nim @@ -16,26 +16,31 @@ when defined(headless): ), run.world.totalXp()) else: import - windy, polyworld/[menus, sounds], + windy, polyworld/[menus, sounds, viewers], assets, game, graphics, frontend, pointers, settings initializeOptions() - configureSoundLaunch(options.soundMuted, options.soundOverride) + configureCapture(options.capture, "games/gods_of_the_arena/gota_shot.png") + configureSoundLaunch(captureActive() or options.soundMuted, + captureActive() or options.soundOverride) try: var preferences = readGotaPreferences() configureSounds( false, preferences.mainVolume, preferences.fxVolume, preferences.uiVolume, preferences.musicVolume ) - initSounds(GotaMusicPath) + if not captureActive(): + initSounds(GotaMusicPath) if playerNameOverride.len > 0: preferences.name = playerNameOverride preferences.savePreferences("Polyworld GotA") localPlayerName = preferences.name - if options.botGroups.len > 0 or options.replayPath.len > 0: - initializeMatch() - runGraphics() + if options.botGroups.len > 0 or options.replayPath.len > 0 or + options.playerSlot > 0: + initializeMatch() + runGraphics() if window == nil or not window.closeRequested: runFrontend() finally: releaseCursorConfinement() + releaseGotaCapture() closeSounds() diff --git a/games/gods_of_the_arena/graphics.nim b/games/gods_of_the_arena/graphics.nim index 95c20a584..927375296 100644 --- a/games/gods_of_the_arena/graphics.nim +++ b/games/gods_of_the_arena/graphics.nim @@ -1,7 +1,7 @@ ## Window, terrain rendering, characters, camera, and HUD for the arena. import - std/[math, strutils, tables, times], + std/[math, os, strutils, tables, times], bumpy, chroma, opengl, pixie, silky, vmath, assets, brushes, content, groves, landscapes, sim, game, maps, replays, ui, walls, aiming, cameras, controls, faces, lighting, spelleffects, multiplayer, homes, lobbies, cursors, pointers, @@ -10,7 +10,7 @@ import polyworld/actioncam, polyworld/assets, polyworld/characters, polyworld/clickmarks, polyworld/fxshapes, polyworld/weapontrails, polyworld/chargen, polyworld/common, polyworld/pathing, - polyworld/tapes, polyworld/toon, polyworld/metrics, + polyworld/tapes, polyworld/toon, polyworld/particles, polyworld/particleshaders, polyworld/player, polyworld/profiles, polyworld/sounds, polyworld/quadterrain, @@ -21,9 +21,8 @@ import when defined(emscripten): {.emit: "#include ".} - -when defined(takeScreenshot): - import std/os +else: + import polyworld/replaysaves, replaylibraries const GotaLakeWater = block: ## The arena's lakes: the engine's lake preset, tuned for the arena. @@ -239,6 +238,9 @@ proc addHudIcons(builder: AtlasBuilder) = var window*: Window sk*: Silky + screenshotTarget: ScreenshotTarget + screenshotFrame: int + runtimeScreenshot: bool terrainReady: bool sharedScene: CharacterScene towerPacks: array[Team, PropPack] @@ -259,10 +261,34 @@ var godEyes: array[Team, DeathEyes] heroEyes: array[HeroClass, DeathEyes] +proc beginGotaFrame*() = + ## Selects the shared offscreen target for a hidden application frame. + discard beginScreenshotFrame(screenshotTarget, window) + +proc presentGotaFrame*() = + ## Saves the requested frame before presenting and ending the normal loop. + when not defined(emscripten): + when ActiveTracePath.len == 0: + if captureFrame(window, screenshotFrame, 30, + "games/gods_of_the_arena/gota_shot.png"): + window.closeRequested = true + else: + if runtimeScreenshot and captureFrame(window, screenshotFrame, 30, + "games/gods_of_the_arena/gota_shot.png"): + window.closeRequested = true + window.presentFrame(framePaceHz) + +proc releaseGotaCapture*() = + ## Releases the application's offscreen target while its context is alive. + if window != nil: + releaseScreenshotTarget(screenshotTarget) + proc initializeGraphics*() = ## Creates the application window and shared atlas exactly once. if window != nil: return + runtimeScreenshot = options.capture.path.len > 0 + configureCapture(options.capture, "games/gods_of_the_arena/gota_shot.png") when ProfileWarmupFrames > 0: finishGameProfile() else: @@ -313,10 +339,16 @@ proc initializeGraphics*() = ## Restores the pointer before closing the game window. releaseCursorConfinement() proc runGraphics*( - network: NetworkMatch = nil, connection: Connection = nil + network: NetworkMatch = nil, connection: Connection = nil, + autoSaveReplay = false ): bool {.discardable.} = ## Runs one match on the existing window and releases match-owned resources. + if network != nil and not network.isSpectator and + (options.pauseOnStart or options.speed != 1): + echo "Live multiplayer follows the server clock; --play and --speed " & + "apply to local games, replays, and spectators." initializeGraphics() + let saveAutomatically = autoSaveReplay and not captureActive() stopSounds() defer: stopSounds() clearHudTooltip() @@ -339,6 +371,18 @@ proc runGraphics*( preferences = Preferences() saveError: string chat: ChatEditor + when not defined(emscripten): + var replaySaving: ReplaySaveState + + proc saveToLibrary() = + ## Saves each recorded state once, sharing manual and automatic saves. + replaySaving.requestReplaySave() + let data = recordingData() + discard replaySaving.saveReplaySnapshot(data, + proc(snapshot: ReplayData): string = + ## Writes one validated game snapshot to its replay library. + saveLibraryReplay(snapshot)) + saveError = "" let chatHooks = window.installChatInput(addr chat) defer: window.restoreChatInput(chatHooks) try: @@ -1324,11 +1368,13 @@ proc runGraphics*( holdSeconds = 2.8, mapSpan = mapHalfSize() * 2 ) + pauseAfterDraft = options.pauseOnStart and run.world.phase == Drafting and + (network == nil or network.isSpectator) transport = initPlayer( live = not run.replayMode, durationTicks = run.durationTicks(), - playing = run.world.phase == Drafting or network.isSpectator or not options.pauseOnStart, - speed = if network.isSpectator: 1'i32 else: options.speed, + playing = run.world.phase == Drafting or not options.pauseOnStart, + speed = options.speed, repeating = run.replayMode and not network.isSpectator ) spectatorStream = if network.isSpectator: newSpectatorStream(network) else: nil @@ -1340,6 +1386,12 @@ proc runGraphics*( ## Holds every completed live match until the player leaves its results. if run.replayMode or not run.finished(): return + when not defined(emscripten): + if replaySaving.beginAutomaticReplaySave(saveAutomatically, true): + try: + saveToLibrary() + except CatchableError as error: + saveError = "Cannot save replay: " & error.msg transport.repeating = false transport.pause() transport.restoreTick = -1 @@ -2564,6 +2616,7 @@ proc runGraphics*( spectatorStream.advance() else: network.applyPacket(packet) + run.world.applyStartupPause(transport, pauseAfterDraft) for i, hero in run.world.heroes: if oldPortalEnds[i] > 0 and hero.portalEnds == 0: let @@ -2647,16 +2700,8 @@ proc runGraphics*( startReplayRecording(uint32(options.maximumTicks)) replayCheckpoints = @[captureCheckpoint()] - let cleanScreenshot = - when defined(takeScreenshot): existsEnv("CLEAN_SCREENSHOT") - else: false - when defined(takeScreenshot): - var screenshotFrame = 0 - let screenshotPath = - if existsEnv("SCREENSHOT_PATH"): - getEnv("SCREENSHOT_PATH") - else: - "games/gods_of_the_arena/gota_shot.png" + let cleanScreenshot = captureActive() and existsEnv("CLEAN_SCREENSHOT") + if captureActive(): applyScreenshotCamera(cameraDistance) if existsEnv("CAM_X"): cameraTarget.x = getEnv("CAM_X").parseFloat.float32 if existsEnv("CAM_Z"): cameraTarget.z = getEnv("CAM_Z").parseFloat.float32 @@ -2673,6 +2718,7 @@ proc runGraphics*( advanceGame() if options.pauseOnStart and run.world.phase != Drafting: transport.pause() + pauseAfterDraft = false if existsEnv("PARTICLE_DEMO"): let origin = cameraTarget + vec3(-2.5'f32, 4.0'f32, 0) @@ -2688,25 +2734,26 @@ proc runGraphics*( HealingAura, cameraTarget + vec3(0, 3.5'f32, 0) ) - if not playerMode(): - for hero in run.world.heroes: - if hero.class == Arcanist and hero.state != Dying: - primaryId = hero.id - selectedIds = @[hero.id] - followSelection = true - break - if primaryId == 0: + when defined(takeScreenshot): + if not playerMode(): for hero in run.world.heroes: - if hero.state != Dying: + if hero.class == Arcanist and hero.state != Dying: primaryId = hero.id selectedIds = @[hero.id] followSelection = true break - else: - primaryId = playerHeroId() - selectedIds = @[primaryId] - followSelection = false - cameraTarget = playerHeroFrame() + if primaryId == 0: + for hero in run.world.heroes: + if hero.state != Dying: + primaryId = hero.id + selectedIds = @[hero.id] + followSelection = true + break + else: + primaryId = playerHeroId() + selectedIds = @[primaryId] + followSelection = false + cameraTarget = playerHeroFrame() if existsEnv("SELECT_ID"): selectEntity(getEnv("SELECT_ID").parseInt.int32) @@ -2754,8 +2801,8 @@ proc runGraphics*( let dt = frameDelta(lastFrameTime) viewingDt = viewingClock.viewingDelta(window) viewingSeeking = transport.targetTick >= 0 or transport.restoreTick >= 0 - let audible = window.focused and not viewingSeeking and - transport.playing and transport.speedIndex == 0 and + let audible = not captureActive() and window.focused and + not viewingSeeking and transport.playing and transport.speed == 1 and matchMenu == HiddenMatchMenu if audioEnabled and not audible and (not run.world.gameOver or not window.focused or @@ -2796,9 +2843,10 @@ proc runGraphics*( if run.world.tick == spectatorStream.receivedEnd: spectatorStream = nil network.promoteController() + pauseAfterDraft = false networkSpectator = false transport.streamed = false - transport.speedIndex = 0 + transport.setSpeed(0) transport.playing = true transport.accumulator = 0 run.historyPlayback = false @@ -2832,7 +2880,7 @@ proc runGraphics*( leaveRequested = true transport.playing = not network.finished and network.client.snapshot.phase == rooms.Playing - transport.speedIndex = 0 + transport.setSpeed(0) run.historyPlayback = false networkElapsed += dt try: @@ -3079,6 +3127,7 @@ proc runGraphics*( drawWorldCharacters(scene, worldCharacters, worldCharacterCount) scene.sunDepthPass = false profileBlock "Main pass": + beginGotaFrame() when not defined(emscripten): glEnable(GL_MULTISAMPLE) glClearColor(0.05, 0.06, 0.09, 1.0) @@ -3175,7 +3224,10 @@ proc runGraphics*( ) drawWorldCharacters(scene, worldCharacters, worldCharacterCount) finishCharacters(scene) - glBindFramebuffer(GL_FRAMEBUFFER, 0) + if captureActive(): + beginGotaFrame() + else: + glBindFramebuffer(GL_FRAMEBUFFER, 0) glViewport(0, 0, window.size.x, window.size.y) drawWaterBody( lake, @@ -3471,6 +3523,11 @@ proc runGraphics*( else: network.client.snapshot.flag activeMatch = network == nil or network.client.snapshot.phase in {rooms.Playing, Waiting} + exitY = + when defined(emscripten): + if network == nil: 256.0'f else: 312.0'f + else: + 312.0'f var controller = network == nil if network != nil: for seat in network.client.snapshot.seats: @@ -3496,21 +3553,23 @@ proc runGraphics*( )) if sk.lobbyButton("Settings", origin + vec2(0, 200), 416): matchMenu = MatchSettings - if network != nil and sk.lobbyButton("Players", - origin + vec2(218, 256), 198): - matchMenu = MatchPlayers - if sk.lobbyButton("Save replay", origin + vec2(0, 256), - (if network != nil: 204.0'f else: 416.0'f), - enabled = run.recorder != nil and - run.world.tick == run.recorder.data.hashes.len): - run.sampleMetrics(true) - run.recorder.data.metrics = run.history.replayMetrics() - saveReplayFile(run.recorder.data.encodeReplay()) - saveError = "" + when defined(emscripten): + if network != nil and sk.lobbyButton("Players", + origin + vec2(0, 256), 416): + matchMenu = MatchPlayers + else: + if network != nil and sk.lobbyButton("Players", + origin + vec2(218, 256), 198): + matchMenu = MatchPlayers + if sk.lobbyButton("Save replay", origin + vec2(0, 256), + (if network != nil: 204.0'f else: 416.0'f), + enabled = run.recorder != nil and not run.replayMode): + saveToLibrary() + saveError = "" if sk.lobbyButton( if network == nil: "Return to menu" elif not activeMatch: "Return to lobby" else: "Leave match", - origin + vec2(0, 312), 416, + origin + vec2(0, exitY), 416, enabled = network == nil or not controller or not activeMatch): if network == nil or not activeMatch: leaveMatch = true @@ -3518,7 +3577,7 @@ proc runGraphics*( network.client.send(RoomMessage(kind: LeaveRoom)) quitToMenu = true if sk.lobbyButton("Quit to main menu", - origin + vec2(0, 368), 416): + origin + vec2(0, exitY + 56), 416): quitToMenu = true if network == nil: leaveMatch = true @@ -3533,17 +3592,22 @@ proc runGraphics*( "Quitting ends the match for everyone." else: "Playback controls affect only your view.", - origin + vec2(0, 432), 416, sk.theme.disabledTextColor) + origin + vec2(0, exitY + 120), 416, sk.theme.disabledTextColor) sk.menuLabel(network.client.status, - origin + vec2(0, 464), 416, sk.theme.disabledTextColor) + origin + vec2(0, exitY + 152), 416, sk.theme.disabledTextColor) else: sk.menuLabel(if run.world.phase == Drafting: "Drafting cannot be paused." else: "Use Pause match to stop the game.", - origin + vec2(0, 432), 416, sk.theme.disabledTextColor) + origin + vec2(0, exitY + 120), 416, sk.theme.disabledTextColor) except CatchableError as error: saveError = error.msg if saveError.len > 0: sk.menuLabel(saveError, origin + vec2(0, 528), 416, MenuAccent) + else: + when not defined(emscripten): + if replaySaving.savedPath.len > 0: + sk.menuLabel("Replay saved to your library.", + origin + vec2(0, 528), 416, MenuAccent) if matchMenu == HiddenMatchMenu: sk.drawHumanChat(window.size.vec2 / sk.uiScale, chat, (if network != nil: network.visibleHumanChat() @@ -3574,15 +3638,16 @@ proc runGraphics*( if not window.buttonDown[MouseLeft] and not window.buttonPressed[MouseLeft]: resultsInputReady = true - when defined(takeScreenshot) and ActiveTracePath.len == 0: - captureScreenshot( - window, - screenshotFrame, - 30, - screenshotPath - ) + when not defined(emscripten): + if saveAutomatically: + sk.beginUi(window, window.size) + sk.menuLabel(if saveError.len > 0: saveError + elif replaySaving.savedPath.len > 0: + "Replay saved to your library." else: "", + vec2(24, 24), 1000, MenuAccent) + sk.endUi() profileBlock "present": - window.presentFrame(framePaceHz) + presentGotaFrame() reportDirectorFrame( actionCam, transport, cameraDistance, int32(run.hashCheck.mismatches) ) @@ -3609,15 +3674,28 @@ proc runGraphics*( break pollEvents() when not defined(emscripten): - window.updateWindowSettings() + if not captureActive(): + window.updateWindowSettings() waitForDisplay() window.cursor = Cursor(kind: ArrowCursor) window.onFrame = nil window.onButtonPress = nil clearPlayerCommands() + var recordingFailure: string + when not defined(emscripten): + var libraryFailure: string if not run.replayMode: - saveRecording() + try: + saveRecording() + except CatchableError as error: + recordingFailure = "Cannot save replay: " & error.msg + when not defined(emscripten): + if replaySaving.shouldSaveReplayOnExit(saveAutomatically): + try: + saveToLibrary() + except CatchableError as error: + libraryFailure = "Cannot save replay: " & error.msg occlusion.closeScreenOcclusion() clickMarks.closeClickMarks() attackMarks.closeClickMarks() @@ -3633,4 +3711,12 @@ proc runGraphics*( clearSceneProps() grove.trees.closePropPack() grove.rocks.closePropPack() + when not defined(emscripten): + if libraryFailure.len > 0: + raise newException(ReplaySaveError, libraryFailure) + if recordingFailure.len > 0: + when defined(emscripten): + raise newException(MenusError, recordingFailure) + else: + raise newException(ReplayExportError, recordingFailure) result = quitToMenu diff --git a/games/gods_of_the_arena/homes.nim b/games/gods_of_the_arena/homes.nim index 92403ce1a..2c288c37d 100644 --- a/games/gods_of_the_arena/homes.nim +++ b/games/gods_of_the_arena/homes.nim @@ -1,9 +1,76 @@ -import silky +import + chroma, pixie, silky, vmath, windy, + polyworld/[chrome, gameuis, sounds] import polyworld/homes as sharedHomes import assets export sharedHomes except MenuImages +const + HomeSize = vec2(1672, 941) + DesktopLabels = ["Single Player", "Multiplayer", "Replays", "Settings", "Exit"] + DesktopImages = [ + "button-single-player", "button-multiplayer", "button-settings", + "button-settings", "button-exit" + ] + +type GotaHomeAction* = enum + GotaStayHome, GotaPlaySingle, GotaPlayMultiplayer, GotaOpenReplays, + GotaOpenSettings, GotaExitGame + proc addHomeAssets*(builder: AtlasBuilder) = ## Keeps GotA asset selection behind its existing frontend API. sharedHomes.addHomeAssets(builder, MenuRoot, assets.MenuImages) + +proc drawGotaHome*(sk: Silky, window: Window, focus: var int): GotaHomeAction = + ## Adds the desktop replay library while preserving the shared browser menu. + when defined(emscripten): + case sharedHomes.drawHome(sk, window, focus) + of StayHome: GotaStayHome + of PlaySingle: GotaPlaySingle + of PlayMultiplayer: GotaPlayMultiplayer + of OpenSettings: GotaOpenSettings + of ExitGame: GotaExitGame + else: + sk.uiScale = selectedUiScale(max(0.1'f, min( + window.size.x.float32 / 720, + window.size.y.float32 / HomeSize.y + )), 1080.0'f / HomeSize.y) + sk.beginUi(window, window.size) + sk.mousePos = window.mousePos.vec2 / sk.uiScale + let + view = window.size.vec2 / sk.uiScale + origin = (view - HomeSize) * 0.5'f + sk.drawHomeBackground(window) + sk.drawSprite("home-shade", origin + vec2(386, 95), vec2(900, 850)) + sk.drawSprite("home-logo", origin + vec2(536, 30), vec2(600, 400)) + sk.drawLabel("Polyworld", origin + vec2(536, 437), vec2(600, 36), + rgbx(222, 222, 218, 255), "Bold", CenterAlign) + focus = clamp(focus, 0, DesktopLabels.high) + if window.buttonPressed[KeyUp]: + focus = (focus + DesktopLabels.len - 1) mod DesktopLabels.len + playSound(SelectSound) + if window.buttonPressed[KeyDown] or window.buttonPressed[KeyTab]: + focus = (focus + 1) mod DesktopLabels.len + playSound(SelectSound) + for index, label in DesktopLabels: + let + at = origin + vec2(596, 490 + index.float32 * 80) + size = vec2(480, 70) + panel = GameUiPanel(origin: at, size: size) + hovered = panel.contains(sk.mousePos) + if hovered and window.mouseDelta != ivec2(0): + focus = index + sk.hoverSound(panel) + let + tint = if hovered or focus == index: 255'u8 else: 226'u8 + ink = + if index == 0: rgbx(39, 24, 10, 255) + else: rgbx(255, 242, 213, 255) + sk.drawSprite("home-" & DesktopImages[index], at, size, + rgbx(tint, tint, tint, 255)) + sk.drawLabel(label, at, size, ink, "H1", CenterAlign) + if (hovered and window.buttonReleased[MouseLeft]) or + (focus == index and window.buttonPressed[KeyEnter]): + result = GotaHomeAction(index + 1) + playSound(ClickSound) diff --git a/games/gods_of_the_arena/replaylibraries.nim b/games/gods_of_the_arena/replaylibraries.nim new file mode 100644 index 000000000..4d9041d1d --- /dev/null +++ b/games/gods_of_the_arena/replaylibraries.nim @@ -0,0 +1,46 @@ +import polyworld/replaylibraries as sharedLibraries +import replays + +export sharedLibraries.ReplayEntry + +proc replayTicks(bytes: string): int = + ## Validates this game's complete payload before marking a file playable. + decodeReplay(bytes).hashes.len + +const Library* = ReplayLibrary( + gameFolder: "Gods of the Arena", + gamePrefix: "GotA", + format: ReplayLibraryFormat( + game: ReplayGame, + gameVersion: ReplayGameVersion, + tapeVersion: ReplayFormatVersion, + maxBytes: MaxReplayBytes + ), + inspect: replayTicks +) + +proc replayDirectory*(): string = + ## Returns this game's replay folder in the current user's application data. + sharedLibraries.replayDirectory(Library) + +proc ensureReplayDirectory*(directory = replayDirectory()): string = + ## Creates and returns the library directory without relying on the game path. + sharedLibraries.ensureReplayDirectory(Library, directory) + +proc inspectReplay*(path: string): ReplayEntry = + ## Describes a valid, incompatible, or unreadable GotA recording. + sharedLibraries.inspectReplay(Library, path) + +proc listReplays*(directory = replayDirectory()): seq[ReplayEntry] = + ## Lists this game's recordings with newest files first. + sharedLibraries.listReplays(Library, directory) + +proc saveLibraryReplay*( + data: ReplayData, directory = replayDirectory() +): string = + ## Validates and saves the complete match under a unique library filename. + sharedLibraries.saveLibraryReplay(Library, encodeReplay(data), directory) + +proc importReplay*(source: string, directory = replayDirectory()): string = + ## Copies a GotA recording, preserving unsupported versions and the source. + sharedLibraries.importReplay(Library, source, directory) diff --git a/games/gods_of_the_arena/replaymenus.nim b/games/gods_of_the_arena/replaymenus.nim new file mode 100644 index 000000000..9e27df7c4 --- /dev/null +++ b/games/gods_of_the_arena/replaymenus.nim @@ -0,0 +1,23 @@ +import + silky, windy, + polyworld/replaymenus as sharedReplayMenus, + content, replaylibraries, replays + +export sharedReplayMenus except drawReplayBrowser + +proc drawReplayBrowser*( + sk: Silky, window: Window, ui: var ReplayBrowserUi, + entries: openArray[ReplayEntry], folder: string, message = "" +): ReplayBrowserResult = + ## Supplies GotA's replay version and clock to the shared desktop browser. + sharedReplayMenus.drawReplayBrowser( + sk, window, ui, entries, folder, ReplayGameVersion, TickRate, message + ) + +proc drawReplayBrowser*( + sk: Silky, window: Window, browser: var ReplayBrowserState +): ReplayBrowserResult = + ## Supplies GotA's replay metadata to the shared library controller. + sharedReplayMenus.drawReplayBrowser( + sk, window, browser, ReplayGameVersion, TickRate + ) diff --git a/games/gods_of_the_arena/replaysettings.nim b/games/gods_of_the_arena/replaysettings.nim new file mode 100644 index 000000000..010a0bad0 --- /dev/null +++ b/games/gods_of_the_arena/replaysettings.nim @@ -0,0 +1,11 @@ +import polyworld/replaysettings as sharedSettings + +export sharedSettings.ReplayPreferences + +proc readReplayPreferences*(): ReplayPreferences = + ## Reads GotA's recording choice from its existing device configuration. + sharedSettings.readReplayPreferences("Polyworld GotA") + +proc saveReplayPreferences*(preferences: ReplayPreferences) = + ## Saves GotA's recording choice separately from shared match settings. + sharedSettings.saveReplayPreferences(preferences, "Polyworld GotA") diff --git a/games/gods_of_the_arena/settings.nim b/games/gods_of_the_arena/settings.nim index 24e9c0b1f..2febd8efa 100644 --- a/games/gods_of_the_arena/settings.nim +++ b/games/gods_of_the_arena/settings.nim @@ -2,7 +2,10 @@ import jsony, windy, - polyworld/[inputs, menus] + polyworld/[inputs, menus], + replaysettings + +export replaysettings const GotaControlProfile* = block: diff --git a/games/gods_of_the_arena/sim.nim b/games/gods_of_the_arena/sim.nim index c4a66422c..1c2ea7cfd 100644 --- a/games/gods_of_the_arena/sim.nim +++ b/games/gods_of_the_arena/sim.nim @@ -5564,7 +5564,7 @@ proc deliverPolicyChat*( if game.inboxes.len == 0: for hero in game.world.heroes: game.inboxes.add newMailbox() - let id = int32(if target < 0: target else: sender) + let id = receivedChatId(sender, target) for recipient in 0 ..< game.inboxes.len: case target of -2: diff --git a/games/gods_of_the_arena/tests/test_cli.nim b/games/gods_of_the_arena/tests/test_cli.nim new file mode 100644 index 000000000..a5ad21bdb --- /dev/null +++ b/games/gods_of_the_arena/tests/test_cli.nim @@ -0,0 +1,117 @@ +import + std/os, + polyworld/cli, + ../[game, presets] + +proc parsed(arguments: seq[string]): GameOptions = + ## Parses a launch without constructing a game or retaining test overrides. + let + previousConfig = matchConfig + previousServer = serverAddress + previousName = playerNameOverride + defer: + matchConfig = previousConfig + serverAddress = previousServer + playerNameOverride = previousName + matchConfig = GotaConfig(seed: previousConfig.seed) + result = parseGameOptions(arguments) + doAssert serverAddress == result.serverUrl + doAssert playerNameOverride == result.playerName + +echo "Testing GotA shared command-line forms without starting a match" +let previousRun = run +for commonArguments in [ + @["--bots", "base.bas:10", "--record", "shots/match.replay", + "--seed", "7", "--ticks", "24", "--verbose"], + @["--bots=base.bas:10", "--record=shots/match.replay", "--seed=7", + "--ticks=24", "--verbose"], + @["--bots:base.bas:10", "--record:shots/match.replay", "--seed:7", + "--ticks:24", "--verbose"] +]: + var arguments = commonArguments + when not defined(headless): + arguments.add @["--name", "123"] + let options = parsed(arguments) + doAssert options.botGroups.botCount == 10 + doAssert options.botGroups[0].path == absolutePath("base.bas") + doAssert options.recordPath == absolutePath("shots/match.replay") + doAssert options.seed == 7 + doAssert options.maximumTicks == 24 + when not defined(headless): + doAssert options.playerName == "123" + doAssert not options.pauseOnStart and options.speed == 1 + doAssert options.verbose + doAssert run == previousRun + +echo "Testing GotA replay and menu recording paths" +block: + let replay = parsed(@["--replay=shots/match.replay"]) + doAssert replay.replayPath == absolutePath("shots/match.replay") + let menu = parsed(@["--record:shots/menu.replay"]) + doAssert menu.recordPath == absolutePath("shots/menu.replay") + doAssert menu.botGroups.len == 0 + +when not defined(headless): + echo "Testing GotA refuses headless pacing and barriers in graphical builds" + for arguments in [@["--llm-mode", "barrier"], + @["--headless-tick-rate", "24"]]: + var rejected = false + try: + discard parsed(arguments) + except CliError: + rejected = true + doAssert rejected + echo "Testing GotA retains menu playback and window choices" + for arguments in [ + @["--play", "false", "--speed", "3", "--windowSize", "960x640"], + @["--play=false", "--speed=3", "--windowSize=960x640"], + @["--play:false", "--speed:3", "--windowSize:960x640"] + ]: + let options = parsed(arguments) + doAssert options.pauseOnStart and options.speed == 3 + doAssert options.windowWidth == 960 and options.windowHeight == 640 + echo "Testing GotA human slot and multiplayer arguments" + for arguments in [ + @["--player", "2", "--bot", "base.bas:9", "--name", "Alice"], + @["--player=2", "--bot=base.bas:9", "--name=Alice"], + @["--player:2", "--bot:base.bas:9", "--name:Alice"] + ]: + let options = parsed(arguments) + doAssert options.playerSlot == 2 + doAssert options.playerName == "Alice" + doAssert options.botGroups.botCount == 9 + for arguments in [ + @["--server", "ws://localhost:9911/ws", "--room", "ABC123"], + @["--server=ws://localhost:9911/ws", "--room=ABC123"], + @["--server:ws://localhost:9911/ws", "--join:ABC123"] + ]: + let options = parsed(arguments) + doAssert options.serverUrl == "ws://localhost:9911/ws" + doAssert options.roomCode == "ABC123" +else: + echo "Testing GotA headless pacing and request barriers" + let headless = parsed(@["--bot", "base.bas:10", "--llm-mode", "barrier", + "--headless-tick-rate", "24"]) + doAssert headless.waitForLlm and headless.headlessTickRate == 24 + var rejected = false + try: + discard parsed(@["--name", "Alice"]) + except CliError: + rejected = true + doAssert rejected + +echo "Testing GotA rejects ambiguous names and incomplete direct rosters" +for arguments in [ + @["--player", "Alice"], + @["--player", "--record", "shots/match.replay"], + @["--replay", "shots/match.replay", "--bot", "base.bas:10"], + @["--replay", "shots/match.replay", "--record", "shots/other.replay"] +]: + var rejected = false + try: + discard parsed(arguments) + except CliError: + rejected = true + doAssert rejected + +echo "GotA command-line tests passed" diff --git a/games/gods_of_the_arena/tests/test_draft_pause.nim b/games/gods_of_the_arena/tests/test_draft_pause.nim index 30fd0c7fa..16433342d 100644 --- a/games/gods_of_the_arena/tests/test_draft_pause.nim +++ b/games/gods_of_the_arena/tests/test_draft_pause.nim @@ -31,6 +31,19 @@ for live in [false, true]: run.world.phase = Playing run.networked = false doAssert transportAvailable(), "Local battle transport remains available" +block: + var + transport = initPlayer(live = true, durationTicks = 2000) + pending = true + run.world.phase = Drafting + run.world.applyStartupPause(transport, pending) + doAssert pending and transport.playing + run.world.phase = Playing + run.world.applyStartupPause(transport, pending) + doAssert not pending and not transport.playing + transport.playing = true + run.world.applyStartupPause(transport, pending) + doAssert transport.playing, "The launch pause must only apply once" run.networked = true networkSpectator = true doAssert transportAvailable(), "Spectator battle transport remains available" diff --git a/games/gods_of_the_arena/tests/test_recording_library.nim b/games/gods_of_the_arena/tests/test_recording_library.nim new file mode 100644 index 000000000..3c0895890 --- /dev/null +++ b/games/gods_of_the_arena/tests/test_recording_library.nim @@ -0,0 +1,114 @@ +import + std/[os, strutils, tempfiles], + polyworld/tapes, + ../[content, controls, game, replaylibraries, replays, sim] + +proc testRecordingLibrary() = + ## Saves a real sparse match and preserves its full tape after rewinding. + let + directory = createTempDir("gota-recording-library-", "") + library = directory / "Replays" + previousRun = run + previousOptions = options + previousConfig = matchConfig + previousPlayerName = localPlayerName + defer: + clearPlayerCommands() + run = previousRun + options = previousOptions + matchConfig = previousConfig + localPlayerName = previousPlayerName + removeDir(directory) + var sources: array[HeroClassCount, string] + let config = parseConfig("""{ + "maxTicks":31,"draftMode":"open","mapPreset":{"mapSize":64} + }""") + initializeLocalMatch(config, sources, 8) + let heroId = run.world.heroes[0].id + queueDraft(heroId, VanguardKnight.ord.int32) + var checkpoint: World + while run.world.tick < 60: + if run.world.tick == 40: + queueStop(heroId) + advanceGame() + if run.world.tick == 24: + checkpoint = run.world.clone() + doAssert checkpoint != nil + doAssert not run.finished() + let partialPath = directory / "partial.replay" + saveRecording(partialPath) + let partial = loadReplay(partialPath) + doAssert partial.hashes.len == 60 + doAssert partial.metrics.frames[^1].tick == 60 + doAssert partial.header.setup.heroes.len == 1 + doAssert partial.metrics.final.len == 1, + "Sparse matches must save telemetry for occupied heroes only." + + while not run.finished(): + if run.world.tick mod 100 == 0: + queueStop(heroId) + advanceGame() + doAssert run.world.tick < 1200, + "The short match must finish without waiting for empty seats." + let + completed = recordingData() + liveHash = run.stateHash() + path = saveLibraryReplay(completed, library) + loaded = loadReplay(path) + doAssert completed.hashes.len == run.world.tick + doAssert completed.actions[^1].tick > checkpoint.tick.uint32 + doAssert loaded.actions == completed.actions + doAssert loaded.hashes == completed.hashes + doAssert loaded.metrics == completed.metrics + doAssert loaded.metrics.frames[^1].tick == run.world.tick + let entries = listReplays(library) + doAssert entries.len == 1 + doAssert entries[0].path == path + doAssert entries[0].playable and entries[0].problem.len == 0 + doAssert entries[0].ticks == completed.hashes.len + + let replay = newGame( + run.map, loaded.config.spawnIntervalTicks, 0, true, loaded + ) + replay.historyPlayback = true + replay.replayPlayer = initReplayPlayer(loaded) + for tick in 0 ..< loaded.hashes.len: + replay.tickWorld(nil) + doAssert replay.hashCheck.mismatches == 0 + doAssert replay.replayPlayer.finished + doAssert replay.stateHash() == liveHash + + run.world.restore(checkpoint) + run.historyPlayback = true + let rewound = recordingData() + doAssert rewound.hashes == completed.hashes, + "Saving while rewound must retain the complete recorded duration." + doAssert rewound.actions == completed.actions, + "Saving while rewound must retain actions after the current playhead." + doAssert rewound.metrics == completed.metrics, + "Saving while rewound must retain original late-match telemetry." + let rewoundPath = saveLibraryReplay(rewound, library) + doAssert loadReplay(rewoundPath).hashes == completed.hashes + doAssert listReplays(library).len == 2 + + run.recordingError = "Interrupted recording for the integration test" + var rejected = false + try: + discard saveLibraryReplay(recordingData(), library) + except ReplayError as error: + rejected = true + doAssert "Interrupted recording" in error.msg + doAssert rejected, "An interrupted recorder must not create a replay file." + doAssert listReplays(library).len == 2 + doAssert loadReplay(path).hashes == completed.hashes + run.recordingError = "" + run.recorder = nil + rejected = false + try: + discard recordingData() + except ReplayError: + rejected = true + doAssert rejected, "A missing recorder must be reported before saving." + +testRecordingLibrary() +echo "Match recording, library playback, rewind retention, and errors passed." diff --git a/games/gods_of_the_arena/tests/test_replay_library.nim b/games/gods_of_the_arena/tests/test_replay_library.nim new file mode 100644 index 000000000..437b99baa --- /dev/null +++ b/games/gods_of_the_arena/tests/test_replay_library.nim @@ -0,0 +1,191 @@ +import + std/[os, strutils, tempfiles, times], + polyworld/tapes, + ../content, ../replays, ../replaylibraries + +proc sampleReplay(): ReplayData = + ## Builds a tiny valid tape without creating a world or user files. + let recorder = initReplayRecorder(Setup( + mapSeed: 2026, + mapHash: 0x123456789ABCDEF0'u64, + tickRate: uint16(TickRate), + gridTiles: 116, + spawnIntervalTicks: uint32(TickRate) * 10, + maximumTicks: 20, + heroes: @[ + ReplayHero(id: 100, team: 0, slot: 0, lane: 0), + ReplayHero(id: 105, team: 1, slot: 0, lane: 0) + ] + )) + recorder.recordWalkTo(1, 100, 64, 42) + recorder.recordAttackTarget(3, 105, 100) + for tick in 1'u64 .. 3'u64: + recorder.recordHash(tick) + recorder.data + +proc changeVersion(bytes: var string, offset: int, version: uint16) = + ## Rewrites a header field without interpreting an obsolete game payload. + bytes[offset] = char(version and 0xff) + bytes[offset + 1] = char(version shr 8) + +proc rejectsImport(path, directory: string) = + ## Requires malformed imports to leave their source and library unchanged. + let + source = readFile(path) + before = listReplays(directory).len + var rejected = false + try: + discard importReplay(path, directory) + except ReplayError: + rejected = true + doAssert rejected + doAssert readFile(path) == source + doAssert listReplays(directory).len == before + +proc testLibrary() = + ## Exercises saves, old versions, malformed files, and non-destructive imports. + let + root = createTempDir("gota-replay-library-", "") + library = root / "library with spaces" + data = sampleReplay() + bytes = encodeReplay(data) + payloadOffset = ReplayMagic.len + 6 + ReplayGame.len + defer: + removeDir(root) + + echo "Testing user library locations and empty libraries" + doAssert replayDirectory().isAbsolute() + doAssert replayDirectory().endsWith( + "Polyworld" / "Gods of the Arena" / "Replays" + ) + doAssert listReplays(library).len == 0 + doAssert not dirExists(library) + doAssert ensureReplayDirectory(library) == library + + echo "Testing uniquely named atomic replay saves" + let + first = saveLibraryReplay(data, library) + second = saveLibraryReplay(data, library) + doAssert first != second + doAssert first.parentDir == library + doAssert first.splitFile().ext == ".replay" + doAssert readFile(first) == bytes + doAssert readFile(second) == bytes + doAssert loadReplay(first).actions == data.actions + let entry = inspectReplay(first) + doAssert entry.playable + doAssert entry.problem.len == 0 + doAssert entry.ticks == 3 + doAssert entry.fileVersion == ReplayFileVersion + doAssert entry.gameVersion == ReplayGameVersion + doAssert entry.tapeVersion == ReplayFormatVersion + doAssert entry.size == bytes.len + doAssert entry.path == first + doAssert entry.name == first.splitFile().name + for kind, path in walkDir(library): + doAssert kind == pcFile + doAssert path.endsWith(".replay") + + echo "Testing newest-first ordering and unrelated-file filtering" + setLastModificationTime(first, fromUnix(100)) + setLastModificationTime(second, fromUnix(200)) + writeFile(library / "unfinished.partial", bytes) + writeFile(library / "notes.txt", "not a replay") + createDir(library / "directory.replay") + let ordered = listReplays(library) + doAssert ordered.len == 2 + doAssert ordered[0].path == second + doAssert ordered[1].path == first + + echo "Testing import copies, repeated names, and importing library files" + let source = root / "A match with spaces.REPLAY" + writeFile(source, bytes) + let + imported = importReplay(source, library) + importedAgain = importReplay(source, library) + doAssert imported != importedAgain + doAssert readFile(source) == bytes + doAssert readFile(imported) == bytes + doAssert imported.splitFile().name.startsWith("Imported-A-match-with-spaces-") + let count = listReplays(library).len + doAssert importReplay(imported, library) == imported + doAssert listReplays(library).len == count + + echo "Testing incompatible versions remain visible and import unchanged" + for kind in 0 ..< 4: + var old = bytes + case kind + of 0: + old.changeVersion(ReplayMagic.len + 2, ReplayGameVersion - 1) + old.setLen(payloadOffset) + old.add("old payload whose layout is intentionally unknown") + of 1: + old.changeVersion(ReplayMagic.len, ReplayFileVersion + 1) + old.setLen(payloadOffset) + of 2: + old.changeVersion(payloadOffset, ReplayFormatVersion - 1) + old.setLen(payloadOffset + 4) + else: + old.changeVersion(payloadOffset + 2, ReplayGameVersion + 1) + old.setLen(payloadOffset + 4) + let path = root / ("older-" & $kind & ".replay") + writeFile(path, old) + let + copied = importReplay(path, library) + incompatible = inspectReplay(copied) + doAssert not incompatible.playable + doAssert incompatible.problem.len > 0 + doAssert readFile(copied) == old + doAssert readFile(path) == old + + echo "Testing invalid, truncated, and foreign replays are contained" + for i, bad in [ + "not a replay", + ReplayMagic, + bytes[0 ..< payloadOffset + 4], + encodeReplayFile("galcon", 1, 1'u32) + ]: + let path = root / ("invalid-" & $i & ".replay") + writeFile(path, bad) + let invalid = inspectReplay(path) + doAssert not invalid.playable + doAssert invalid.problem.len > 0 + rejectsImport(path, library) + let broken = library / "broken.replay" + writeFile(broken, "not a replay") + var foundBroken = false + for item in listReplays(library): + if item.path == broken: + foundBroken = true + doAssert not item.playable + doAssert item.problem.len > 0 + doAssert foundBroken + + echo "Testing oversized replays and failed saves" + let oversized = root / "oversized.replay" + block: + let file = open(oversized, fmWrite) + defer: + file.close() + file.setFilePos(MaxReplayBytes) + file.write('x') + doAssert not inspectReplay(oversized).playable + doAssert "64 MiB" in inspectReplay(oversized).problem + var rejected = false + try: + discard importReplay(oversized, library) + except ReplayError: + rejected = true + doAssert rejected + let occupied = root / "occupied" + writeFile(occupied, "keep this file") + rejected = false + try: + discard saveLibraryReplay(data, occupied) + except ReplayError: + rejected = true + doAssert rejected + doAssert readFile(occupied) == "keep this file" + +testLibrary() +echo "Replay library checks passed without touching the user library." diff --git a/games/gods_of_the_arena/tests/test_replay_menu_render.nim b/games/gods_of_the_arena/tests/test_replay_menu_render.nim new file mode 100644 index 000000000..8ae3a29ee --- /dev/null +++ b/games/gods_of_the_arena/tests/test_replay_menu_render.nim @@ -0,0 +1,147 @@ +import + std/[importutils, os, times], + opengl, pixie, silky, vmath, windy/internal, + polyworld/[chrome, lobbies, viewers], + ../[content, homes, replaylibraries, replaymenus, replays] + +privateAccess(Window) + +proc verifyReplayMenu(size: IVec2, screenshot: string, zoom = 0) = + ## Exercises production replay controls with real UI input and rendering. + let + savedMode = uiScaleMode + savedPercent = uiScalePercent + if zoom > 0: + uiScaleMode = CustomUiScale + uiScalePercent = zoom + defer: + uiScaleMode = savedMode + uiScalePercent = savedPercent + let window = newWindow("GotA replay browser test", size, visible = false) + defer: + window.close() + window.makeContextCurrent() + loadExtensions() + let builder = newHudAtlas(4096) + builder.addDefaultFonts() + builder.addLobbyFonts() + builder.addHomeAssets() + let sk = newSilky(window, builder.atlasImage, builder.atlas) + sk.applyThemePatches() + var + browser = ReplayBrowserUi() + entries: seq[ReplayEntry] + framebuffer, texture: GLuint + for index in 0 ..< 12: + entries.add ReplayEntry( + path: "/test/arena-" & $index & ".replay", + name: "Arena match " & $(index + 1) & ".replay", + modified: fromUnix(1795200000 - int64(index * 3600)), + gameVersion: ReplayGameVersion, + ticks: TickRate * 60 * 12, + playable: true + ) + entries[1].playable = false + entries[1].gameVersion = ReplayGameVersion - 1 + entries[1].problem = "Game version " & $entries[1].gameVersion & + " (requires " & $ReplayGameVersion & ")" + entries[2].playable = false + entries[2].problem = "The replay file is incomplete." + glGenFramebuffers(1, framebuffer.addr) + glGenTextures(1, texture.addr) + glBindTexture(GL_TEXTURE_2D, texture) + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8.GLint, size.x.GLsizei, size.y.GLsizei, + 0, GL_RGBA, GL_UNSIGNED_BYTE, nil) + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer) + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, texture, 0) + doAssert glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE + defer: + glBindFramebuffer(GL_FRAMEBUFFER, 0) + glDeleteTextures(1, texture.addr) + glDeleteFramebuffers(1, framebuffer.addr) + + proc input(point = vec2(-100), pressed = false, released = false, + key = ButtonUnknown) = + ## Updates only the transient events consumed by the real menu widgets. + window.state.perFrame = PerFrame() + window.state.buttonDown = {} + window.state.mousePos = (point * sk.uiScale).ivec2 + window.state.mousePrevPos = window.state.mousePos + if pressed: + window.state.perFrame.buttonPressed.incl MouseLeft + window.state.buttonDown.incl MouseLeft + if released: + window.state.perFrame.buttonReleased.incl MouseLeft + if key != ButtonUnknown: + window.state.perFrame.buttonPressed.incl key + + proc render(point = vec2(-100), pressed = false, released = false, + key = ButtonUnknown): ReplayBrowserResult = + ## Renders the browser without performing its returned filesystem actions. + input(point, pressed, released, key) + result = sk.drawReplayBrowser(window, browser, entries, + "User folder / Polyworld / Gods of the Arena / Replays") + sk.endUi() + + proc click(point: Vec2): ReplayBrowserResult = + ## Sends a complete mouse press and release through the renderer. + discard render(point, pressed = true) + render(point, released = true) + + discard render() + let layout = replayBrowserLayout(window.size.vec2 / sk.uiScale) + doAssert layout.back.y + layout.back.h < window.size.y.float32 / sk.uiScale + doAssert layout.folderButton.x + layout.folderButton.w < layout.refresh.x + doAssert layout.panel.y + layout.panel.h < layout.back.y + let watch = layout.rows.xy + vec2(layout.rows.w - 96, 48) + let live = click(watch) + doAssert live.action == PlayReplay and live.path == entries[0].path + doAssert click(watch + vec2(0, ReplayRowHeight)).action == StayReplayBrowser + doAssert click(watch + vec2(0, ReplayRowHeight * 2)).action == StayReplayBrowser + discard render(key = KeyDown) + doAssert browser.selectedPath == entries[0].path + discard render(key = KeyDown) + doAssert browser.selectedPath == entries[3].path + doAssert render(key = KeyEnter).path == entries[3].path + for index in 0 ..< 10: + discard render(key = KeyDown) + doAssert browser.selectedPath == entries[^1].path + doAssert browser.scroll.scrollPos.y > 0 + doAssert render(key = KeyEnter).path == entries[^1].path + doAssert click(layout.importButton.xy + vec2(60, 20)).action == ImportReplayFile + doAssert click(layout.folderButton.xy + vec2(70, 20)).action == OpenReplayFolder + doAssert click(layout.refresh.xy + vec2(70, 20)).action == RefreshReplays + doAssert click(layout.back.xy + vec2(70, 20)).action == BackFromReplays + doAssert render(key = KeyEscape).action == BackFromReplays + browser = ReplayBrowserUi() + discard render() + if screenshot.len > 0: + let image = newImage(size.x, size.y) + glReadPixels(0, 0, size.x.GLsizei, size.y.GLsizei, + GL_RGBA, GL_UNSIGNED_BYTE, image.data[0].addr) + image.flipVertical() + createDir(screenshot.parentDir) + image.writeFile(screenshot) + entries.setLen(0) + browser.selectedPath = "/test/no-longer-present.replay" + doAssert render(key = KeyEnter).action == StayReplayBrowser + doAssert browser.selectedPath.len == 0 + doAssert click(layout.importButton.xy + vec2(60, 20)).action == ImportReplayFile + var focus = 2 + input(key = KeyEnter) + doAssert sk.drawGotaHome(window, focus) == GotaOpenReplays + sk.endUi() + input(key = KeyDown) + doAssert sk.drawGotaHome(window, focus) == GotaStayHome + doAssert focus == 3 + sk.endUi() + input(key = KeyEnter) + doAssert sk.drawGotaHome(window, focus) == GotaOpenSettings + sk.endUi() + +verifyReplayMenu(ivec2(1280, 900), + getEnv("GOTA_REPLAY_MENU_SCREENSHOT", "/tmp/gota-replay-browser.png")) +verifyReplayMenu(ivec2(800, 600), "") +verifyReplayMenu(ivec2(800, 600), "", zoom = 300) +echo "Replay browser mouse, keyboard, disabled versions, and scrolling passed." diff --git a/games/gods_of_the_arena/tests/test_sparse_local.nim b/games/gods_of_the_arena/tests/test_sparse_local.nim index bfe0e5f16..84eb206eb 100644 --- a/games/gods_of_the_arena/tests/test_sparse_local.nim +++ b/games/gods_of_the_arena/tests/test_sparse_local.nim @@ -1,10 +1,18 @@ import ../[game, sim, replays] +let previousOptions = options +options.recordPath = "menu-match.replay" +options.pauseOnStart = true +options.speed = 3 let config = parseConfig("{\"maxTicks\":24,\"draftMode\":\"open\"}") var sources: array[10, string] initializeLocalMatch(config, sources, 8) doAssert run.world.heroes.len == 1, "Local empty slots must not spawn" doAssert run.world.heroes[0].id == FirstHeroId + 8 doAssert options.playerSlot == 1 +doAssert options.recordPath == "menu-match.replay" +doAssert options.pauseOnStart +doAssert options.speed == 3 for vm in run.heroVms: doAssert vm == nil +options = previousOptions echo "Local sparse human preserved without ghost policies" diff --git a/games/gods_of_the_arena/tests/tests.nim b/games/gods_of_the_arena/tests/tests.nim index e1099e08f..100a721ff 100644 --- a/games/gods_of_the_arena/tests/tests.nim +++ b/games/gods_of_the_arena/tests/tests.nim @@ -12,6 +12,7 @@ import test_cameras, test_camps, test_content, + test_cli, test_cogas, test_tooltips, test_controls, @@ -58,6 +59,8 @@ import test_presets, test_progression, test_replays, + test_replay_library, + test_recording_library, test_replay_chat, test_policy_chat_replay, test_rotations, diff --git a/games/gods_of_the_arena/ui.nim b/games/gods_of_the_arena/ui.nim index 3b5a18049..d10359b84 100644 --- a/games/gods_of_the_arena/ui.nim +++ b/games/gods_of_the_arena/ui.nim @@ -161,6 +161,14 @@ proc keepDraftPlaying*(world: World, transport: var Player) = if world.phase == Drafting: transport.playing = true +proc applyStartupPause*( + world: World, transport: var Player, pending: var bool +) = + ## Applies one requested launch pause after mandatory drafting has finished. + if pending and world.phase != Drafting: + pending = false + transport.pause() + proc currentLayout*(window: Window): GameUiLayout = ## Reserves timeline space only when the transport controls are visible. initGameUiLayout( diff --git a/games/heartleaf/ASSETS.md b/games/heartleaf/ASSETS.md index 40ded1cf7..84a5a28ac 100644 --- a/games/heartleaf/ASSETS.md +++ b/games/heartleaf/ASSETS.md @@ -11,16 +11,17 @@ Adventure. The opening overview shows all nine cottages. Screenshots run in a hidden window and exit after writing their PNG: ```sh -SCREENSHOT_PATH=tmp/heartleaf.png nim r -d:takeScreenshot \ - games/heartleaf/heartleaf.nim \ - --bot games/heartleaf/players/base.bas:9 \ +nim r games/heartleaf/heartleaf.nim \ + --screenshot tmp/heartleaf.png --frames 30 \ --seek-tick 1500 --play=false ``` Use `--seek-event day:1:dinner` for a named event, or `--replay PATH` for a saved run. `CAM_DIST`, `CAM_X` and `CAM_Z` override the screenshot camera. The latter two use simulation tile coordinates. `--windowSize WIDTHxHEIGHT` overrides the -shared window dimensions. +shared window dimensions. With no roster or replay, screenshot capture uses +the bundled villager bots. The standard capture flags also accept `=VALUE` +and `:VALUE` forms. ## Reference layer captures @@ -48,12 +49,12 @@ and props have transparent backgrounds. The assembled comparison excludes HUD, gnomes and crop placeholders. Normal gameplay retains them. To capture one layer, set `HEARTLEAF_LAYER` to `ground`, `buildings`, -`vegetation`, `props` or `all` and compile with both capture flags: +`vegetation`, `props` or `all` and compile with the scene-only capture flag: ```sh -HEARTLEAF_LAYER=buildings SCREENSHOT_PATH=tmp/buildings.png \ - nim r -d:takeScreenshot -d:sceneCapture games/heartleaf/heartleaf.nim \ - --bot games/heartleaf/players/base.bas:9 \ +HEARTLEAF_LAYER=buildings \ + nim r -d:sceneCapture games/heartleaf/heartleaf.nim \ + --screenshot tmp/buildings.png --frames 30 \ --seek-tick 1500 --play=false --windowSize 1122x1402 ``` diff --git a/games/heartleaf/docs/cli.md b/games/heartleaf/docs/cli.md new file mode 100644 index 000000000..f4bc654eb --- /dev/null +++ b/games/heartleaf/docs/cli.md @@ -0,0 +1,38 @@ +# Command-line options + +Heartleaf uses the shared Polyworld launch options. Values accept separate, +equals, or colon forms, such as `--replay match.replay`, +`--replay=match.replay`, and `--replay:match.replay`. + +```sh +./heartleaf --bot players/base.bas:9 --record saved/week.replay +./heartleaf --player 2 --bots players/base.bas:8 +./heartleaf --replay saved/week.replay --play false --speed 4 +``` + +`--bot PATH[:N]` and `--bots PATH[:N]` both add N instances of one program; +repeat either option for a mixed roster. `--player [N]` controls one human +slot, numbered 1 through 9, and defaults to slot 1 when N is omitted. Bots +fill the other slots in order. Human control requires a graphical build. + +`--record PATH` saves this match. `--replay PATH` loads a recording and cannot +be combined with bots, a human controller, or another recording destination. +Replay and bot paths resolve from the launch directory. Recording creates +the destination's parent directories. + +`--days N` sets the village calendar, from 1 to 28 days, and defaults to 7. +`--ticks N`, `--seconds N`, and `--minutes N` stop execution earlier without +changing that calendar. A partial saved replay keeps its original calendar +setup and plays only its recorded ticks. Duration options configure new +matches and cannot be combined with `--replay`. + +`--headless-tick-rate N` paces a headless run in wall-clock ticks per second; +zero runs without pacing. `--verbose` prints progress every 30 simulated +seconds. The fixed villager names cannot be replaced with `--name`. +Heartleaf's BASIC bindings do not provide LLM requests, so `--llm-mode` is +unavailable. Audio flags are accepted for portable launch scripts; Heartleaf +has no audio output. + +`--seek-tick N` or `--seek-event day:N:morning|dinner|scorecard` selects a +starting position. Only one seek target can be supplied. Pair it with +`--play false` to inspect that point without advancing further. diff --git a/games/heartleaf/game.nim b/games/heartleaf/game.nim index 35173f53d..dcc71dfa0 100644 --- a/games/heartleaf/game.nim +++ b/games/heartleaf/game.nim @@ -7,88 +7,48 @@ import std/[os, strformat, times], - polyworld/[cli, controllers, profiles, tapes], + polyworld/[cli, controllers, profiles, tapes, timings], content, maps as mapgen, sim, bots, controls, - replays, seeking - -var startupTarget*: SeekTarget + replays, seeking, + options as launches proc usage() = ## Prints the command-line and compile-time configuration surface. + echo "Heartleaf, a village dinner-party week between nine BASIC villagers." + echo commonUsageFor(HeartleafCommonFlags) echo """ -Heartleaf, a village dinner-party week between nine BASIC villagers. - - --bot PATH[:N] Fill N of the nine villager slots with one program. - --player Control villager one; supply eight bots. - --player:N Control villager N (1 .. 9); supply eight bots. - --replay PATH Play a recorded game instead of running bots. - --record PATH Record this game to a replay file. --days N Days in the week (default 7). - --seed N Map seed (default 2026). --seek-tick N Fast-forward to an absolute tick (zero is initial state). --seek-event S Fast-forward to day:N:morning|dinner|scorecard. - --play=false Start the graphical transport paused. - --speed N Graphical start speed: 1, 2, 4, or 16. - --windowSize WxH Graphical window, such as 800x400. - --vsync:off Unlock the frame rate (default on). - --mute[=true|false] Override saved sound levels for this launch. - --unmute Enable sound for this launch. --help Show this message. +Supply nine bots, or one human in slot 1 .. 9 and eight bots. +--days sets the calendar; shared duration options can end a new match earlier. +Heartleaf has fixed villager names, no LLM requests, and no audio output. Compile with -d:headless for a command-line game. Compile with -d:emscripten for the web backend. -Compile with -d:takeScreenshot to save a PNG without showing a window. -Set SCREENSHOT_PATH for the output (default heartleaf.png). +Screenshot captures use the bundled bots when no roster is supplied. Use --seek-tick or --seek-event with --play=false to capture that state.""" -proc parseGameOptions(): (GameOptions, int32) = - ## Reads the command line into a validated game description. - var options = GameOptions( - seed: DefaultSeed, - speed: 1 - ) - var dayCount = DefaultDayCount - let arguments = commandLineParams() - var index = 0 - while index < arguments.len: - let argument = arguments[index] - if options.takeCommonFlag(arguments, index, argument): - discard - else: - case argument - of "--seek-tick", "--seek-event": - if startupTarget.kind != NoSeek: - fail("only one startup seek target is allowed") - startupTarget = parseSeekTarget(argument, - arguments.argumentValue(index, argument)) - of "--days": - dayCount = parsePositiveInt32( - arguments.argumentValue(index, "--days"), "--days") - if dayCount > MaxDayCount: - fail("--days must be at most " & $MaxDayCount) - of "--help", "-h": - usage() - quit(0) - else: - fail("unknown argument: " & argument) - inc index - options.setMaximumTicks(gameLengthTicks(dayCount)) - options.validateGameOptions( - VillagerCount, - "a live game requires exactly nine bots" - ) - if startupTarget.kind != NoSeek and options.playerSlot > 0: - fail("startup seeking requires a replay or nine scripted bots") - (options, dayCount) +proc readLaunchOptions(): LaunchOptions = + ## Reports command-line errors without initializing the game world. + try: + result = parseLaunchOptions(commandLineParams()) + except ValueError as error: + fail(error.msg) let - parsed = parseGameOptions() - options* = parsed[0] - optionDays = parsed[1] + parsed = readLaunchOptions() + options* = parsed.common + startupTarget* = parsed.startupTarget + +if parsed.showHelp: + usage() + quit(0) var run*: Game @@ -96,7 +56,7 @@ block: startGameProfile() var mapSeed = options.seed - dayCount = optionDays + dayCount = parsed.dayCount if options.replayPath.len > 0: var replayData: ReplayData profileBlock "replay": @@ -125,6 +85,7 @@ block: gameMap = generateMap(mapSeed) gameMap.validateMap() run = newGame(gameMap, dayCount) + run.maximumTicks = parsed.executionTicks(run.maximumTicks) let kinds = controllerKinds(VillagerCount, options.playerSlot) expanded = options.botGroups.expandBotSources(kinds) @@ -141,6 +102,7 @@ block: )) run.recorder.data.config = localGameConfig(options, VillagerCount) run.recorder.data.config.dayCount = dayCount + run.recorder.data.config.maxTicks = gameLengthTicks(dayCount) run.replayPlayer = ReplayPlayer(data: run.recorder.data) startupTarget.validate(run.world.dayCount, run.maximumTicks) @@ -177,6 +139,7 @@ proc advanceGame*() = run.recorder.recordHash(run.stateHash()) proc seekStartup*(afterTick: proc() {.closure.} = nil) = + ## Advances to the requested scene without changing the recorded setup. if startupTarget.kind == NoSeek: return while not startupTarget.reached(run.world): @@ -224,12 +187,17 @@ proc runHeadless*() = defer: finishGameProfile() let started = epochTime() - seekStartup() + var pacer = initTickPacer(options.headlessTickRate) + seekStartup(proc() = pacer.pace()) while startupTarget.kind == NoSeek and run.world.tick < run.maximumTicks and not run.world.over: advanceGame() + pacer.pace() if profileShouldDump(run.world.tick): finishGameProfile() + if options.verbose and run.world.tick mod (TickRate * 30) == 0: + echo &"tick {run.world.tick}/{run.maximumTicks}, " & + &"day {run.world.day}, {run.world.phase}" let elapsed = max(epochTime() - started, 0.000001) simulated = run.world.tick.float64 / TickRate.float64 diff --git a/games/heartleaf/graphics.nim b/games/heartleaf/graphics.nim index 93ced3eaa..dd60449a6 100644 --- a/games/heartleaf/graphics.nim +++ b/games/heartleaf/graphics.nim @@ -5,7 +5,7 @@ ## that can flow back into `World`. import - std/[math, times], + std/[math, os, strutils, times], fixxy, opengl, pixie, vmath, windy, silky, polyworld/[actioncam, assets, characters, chargen, chrome, clickmarks, common, gameuis, inputs, occlusions, pathing, player, profiles, quadterrain, rtscameras, @@ -25,9 +25,6 @@ import democamera, scorecard -when defined(takeScreenshot): - import std/[os, strutils] - const WindowTitle = "Heartleaf" AtlasPath = TmpRoot & "/heartleaf.atlas.png" @@ -120,6 +117,7 @@ proc renderTime(ticks: int32): float32 = proc runGraphics*() = ## Runs the native or Emscripten spectator. + configureCapture(options.capture, "heartleaf.png") startGameProfile() profileBlock "atlas": let builder = newHudAtlas(4096) @@ -133,9 +131,12 @@ proc runGraphics*() = gameWindowSize(options.windowWidth, options.windowHeight), options.vsync ) + var screenshotTarget: ScreenshotTarget + defer: releaseScreenshotTarget(screenshotTarget) + discard beginScreenshotFrame(screenshotTarget, window) let splash = startSplash(sk, window) var captureLayer = AllLayer - when defined(takeScreenshot): + if captureActive(): case getEnv("HEARTLEAF_LAYER") of "ground": captureLayer = GroundLayer of "buildings": captureLayer = BuildingsLayer @@ -538,7 +539,9 @@ proc runGraphics*() = ## Frame - var lastFrameTime = epochTime() + var + lastFrameTime = epochTime() + screenshotFrame = 0 const Step = 1.0'f32 / float32(TickRate) proc advanceRenderedGame() = @@ -547,7 +550,7 @@ proc runGraphics*() = advanceGame() captureCheckpoint() - when defined(takeScreenshot): + if captureActive(): if existsEnv("HEARTLEAF_LAYER"): cameraDistance = 1402'f * 0.044'f / 2 / TownCameraScale cameraTarget = TownCameraTarget @@ -561,11 +564,10 @@ proc runGraphics*() = while run.world.tick < wanted and run.world.tick < run.maximumTicks and not run.world.over: advanceGame() - var screenshotFrame = 0 - holdSplash(sk, window, splash) window.onFrame = proc() = profileBlock "frame": + discard beginScreenshotFrame(screenshotTarget, window) let dt = frameDelta(lastFrameTime, Step) let recorded = if run.recorder != nil: int32(run.recorder.data.hashes.len) @@ -658,6 +660,7 @@ proc runGraphics*() = if captureLayer == AllLayer: drawWorldVillagers() scene.sunDepthPass = false + discard beginScreenshotFrame(screenshotTarget, window) if captureLayer in {BuildingsLayer, VegetationLayer, PropsLayer}: glClearColor(0, 0, 0, 0) else: @@ -758,15 +761,12 @@ proc runGraphics*() = if speedClicked: snapFollowCamera() sk.endUi() - when defined(takeScreenshot): - captureScreenshot( - window, - screenshotFrame, - 3, - "heartleaf.png" - ) - profileBlock "present": - window.presentFrame(framePaceHz) + if captureFrame(window, screenshotFrame, 30, "heartleaf.png"): + when not defined(emscripten): + window.closeRequested = true + else: + profileBlock "present": + window.presentFrame(framePaceHz) if noteProfileFrame(): when not defined(emscripten): window.closeRequested = true diff --git a/games/heartleaf/options.nim b/games/heartleaf/options.nim new file mode 100644 index 000000000..4ac6421db --- /dev/null +++ b/games/heartleaf/options.nim @@ -0,0 +1,83 @@ +## Heartleaf launch options without creating a world or loading bots. + +import + polyworld/cli, + content, seeking + +when not defined(headless) and not defined(emscripten): + import std/os + +type LaunchOptions* = object + common*: GameOptions + dayCount*: int32 + startupTarget*: SeekTarget + durationLimited*: bool + showHelp*: bool + +const HeartleafCommonFlags* = + when defined(headless): + AllCommonFlags - {NameFlag, ServerFlag, RoomFlag, LlmModeFlag} + else: + AllCommonFlags - { + NameFlag, ServerFlag, RoomFlag, LlmModeFlag, HeadlessTickRateFlag + } + +proc parseLaunchOptions*(arguments: seq[string]): LaunchOptions = + ## Parses the shared launch contract and Heartleaf's calendar and seek flags. + result.common = GameOptions(seed: DefaultSeed, speed: 1) + result.dayCount = DefaultDayCount + var index = 0 + while index < arguments.len: + let argument = arguments[index] + if result.common.takeCommonFlag(arguments, index, argument): + discard + elif argument in ["--help", "-h"]: + result.showHelp = true + return + else: + let flag = splitFlag(argument).name + if flag notin ["--days", "--seek-tick", "--seek-event"]: + raise newException(CliError, "unknown argument: " & argument) + let value = arguments.flagValue(index, argument) + if flag == "--days": + result.dayCount = parsePositiveInt32(value, flag) + if result.dayCount > MaxDayCount: + raise newException(CliError, + "--days must be at most " & $MaxDayCount) + else: + if result.startupTarget.kind != NoSeek: + raise newException(CliError, + "only one startup seek target is allowed") + result.startupTarget = parseSeekTarget(flag, value) + inc index + result.common.rejectUnsupportedFlags(HeartleafCommonFlags) + result.durationLimited = (result.common.specifiedFlags * DurationFlags) != {} + if not result.durationLimited: + result.common.setMaximumTicks(gameLengthTicks(result.dayCount)) + else: + result.common.setMaximumTicks(min( + result.common.maximumTicks, gameLengthTicks(result.dayCount) + )) + when not defined(headless) and not defined(emscripten): + if result.common.capture.path.len > 0 and + result.common.botGroups.len == 0 and + result.common.replayPath.len == 0 and result.common.playerSlot == 0: + result.common.botGroups.add BotGroup( + path: currentSourcePath().parentDir / "players" / "base.bas", + count: VillagerCount + ) + result.common.validateGameOptions( + VillagerCount, + "a live game requires exactly nine bots" + ) + if result.startupTarget.kind != NoSeek and result.common.playerSlot > 0: + raise newException(CliError, + "startup seeking requires a replay or nine scripted bots") + result.common.resolveGamePaths() + +proc executionTicks*(options: LaunchOptions, available: int32): int32 = + ## Applies an explicit duration without changing the recorded calendar setup. + if options.durationLimited: + min(options.common.maximumTicks, available) + else: + available diff --git a/games/heartleaf/tests/test_options.nim b/games/heartleaf/tests/test_options.nim new file mode 100644 index 000000000..5a340f14b --- /dev/null +++ b/games/heartleaf/tests/test_options.nim @@ -0,0 +1,140 @@ +import + std/os, + polyworld/cli, + ../[content, options, seeking] + +proc rejects(arguments: seq[string]): bool = + ## Reports argument errors without loading a map, bot, or replay. + try: + discard parseLaunchOptions(arguments) + except ValueError: + return true + +echo "Testing Heartleaf's shared command-line options" +block: + for arguments in [ + @["--bots", "base.bas:9", "--seed", "7", "--record", "match.replay"], + @["--bots=base.bas:9", "--seed=7", "--record=match.replay"], + @["--bots:base.bas:9", "--seed:7", "--record:match.replay"] + ]: + let launch = parseLaunchOptions(arguments) + doAssert launch.common.seed == 7 + doAssert launch.common.botGroups.botCount == VillagerCount + doAssert launch.common.botGroups[0].path == absolutePath("base.bas") + doAssert launch.common.recordPath == absolutePath("match.replay") + doAssert launch.common.maximumTicks == gameLengthTicks(DefaultDayCount) + doAssert not launch.durationLimited + +echo "Testing calendar setup stays independent of the execution limit" +block: + for arguments in [ + @["--bot", "base.bas:9", "--days", "2", "--ticks", "48"], + @["--bot=base.bas:9", "--seconds=2", "--days=2"], + @["--bot:base.bas:9", "--days:2", "--ticks:48"] + ]: + let launch = parseLaunchOptions(arguments) + doAssert launch.dayCount == 2 + doAssert launch.durationLimited + doAssert launch.common.maximumTicks == 48 + doAssert launch.executionTicks(gameLengthTicks(2)) == 48 + doAssert launch.executionTicks(12) == 12 + let long = parseLaunchOptions(@[ + "--bot", "base.bas:9", "--days", "1", "--minutes", "20" + ]) + doAssert long.common.maximumTicks == gameLengthTicks(1) + +echo "Testing replay playback, seek options, and common presentation flags" +block: + for arguments in [ + @["--replay", "match.replay", "--seek-tick", "12"], + @["--replay=match.replay", "--seek-tick=12"], + @["--replay:match.replay", "--seek-tick:12"] + ]: + let launch = parseLaunchOptions(arguments) + doAssert launch.common.replayPath == absolutePath("match.replay") + doAssert launch.startupTarget == SeekTarget(kind: TickSeek, value: 12) + doAssert launch.executionTicks(100) == 100 + let replay = parseLaunchOptions(@["--replay", "long.replay"]) + doAssert replay.executionTicks(gameLengthTicks(28)) == gameLengthTicks(28) + let launch = parseLaunchOptions(@[ + "--replay", "match.replay", "--seek-event:day:2:dinner", + "--mute", "--verbose" + ]) + doAssert launch.startupTarget == SeekTarget(kind: DinnerSeek, value: 2) + doAssert launch.common.soundMuted + doAssert launch.common.verbose + doAssert launch.common.headlessTickRate == 0 + for arguments in [ + @["--replay", "match.replay", "--play", "false", "--speed", "4", + "--windowSize", "800x600", "--vsync", "off"], + @["--replay=match.replay", "--play=false", "--speed=4", + "--windowSize=800x600", "--vsync=off"], + @["--replay:match.replay", "--play:false", "--speed:4", + "--windowSize:800x600", "--vsync:off"] + ]: + when defined(headless): + doAssert rejects(arguments) + else: + let launch = parseLaunchOptions(arguments) + doAssert launch.common.pauseOnStart + doAssert launch.common.speed == 4 + doAssert launch.common.windowWidth == 800 + doAssert launch.common.windowHeight == 600 + doAssert not launch.common.vsync + +echo "Testing tick pacing requires the headless runner" +block: + for flags in [ + @["--headless-tick-rate", "48"], + @["--headless-tick-rate=48"], + @["--headless-tick-rate:48"], + @["--headless-tick-rate", "0"] + ]: + let arguments = @["--replay", "match.replay"] & flags + when defined(headless): + let launch = parseLaunchOptions(arguments) + doAssert launch.common.headlessTickRate == + (if flags[^1] == "0": 0 else: 48) + else: + doAssert rejects(arguments) + +echo "Testing human slots have the same one-based meaning" +block: + for arguments in [ + @["--player", "2", "--bot", "base.bas:8"], + @["--player=2", "--bot=base.bas:8"], + @["--player:2", "--bot:base.bas:8"] + ]: + when defined(headless): + doAssert rejects(arguments) + else: + let launch = parseLaunchOptions(arguments) + doAssert launch.common.playerSlot == 2 + doAssert launch.common.botGroups.botCount == 8 + when not defined(headless): + doAssert parseLaunchOptions(@[ + "--player", "--bot", "base.bas:8" + ]).common.playerSlot == 1 + +echo "Testing invalid or unsupported launches are rejected" +block: + for arguments in [ + @["--bot", "base.bas:8"], + @["--bot", "base.bas:10"], + @["--replay", "match.replay", "--record", "copy.replay"], + @["--replay", "match.replay", "--bot", "base.bas:9"], + @["--replay", "match.replay", "--name", "Visitor"], + @["--replay", "match.replay", "--llm-mode", "barrier"], + @["--replay", "match.replay", "--server", "ws://localhost:9911/ws"], + @["--replay", "match.replay", "--room", "ABCD"], + @["--replay", "match.replay", "--ticks", "24"], + @["--replay", "match.replay", "--days=0"], + @["--replay", "match.replay", "--days=29"], + @["--replay", "match.replay", "--ticks=0"], + @["--replay", "match.replay", "--seek-tick=0", "--seek-tick=1"], + @["--replay", "match.replay", "--unknown"] + ]: + doAssert rejects(arguments), $arguments + doAssert parseLaunchOptions(@["--help"]).showHelp + +echo "Heartleaf command-line tests passed" diff --git a/games/heartleaf/tests/tests.nim b/games/heartleaf/tests/tests.nim index 12ea53203..a35270d68 100644 --- a/games/heartleaf/tests/tests.nim +++ b/games/heartleaf/tests/tests.nim @@ -2,6 +2,7 @@ {.warning[UnusedImport]: off.} import + test_options, test_content, test_maps, test_replays, diff --git a/games/light_vs_dark/bots.nim b/games/light_vs_dark/bots.nim index 2db5dcc9c..325bf7422 100644 --- a/games/light_vs_dark/bots.nim +++ b/games/light_vs_dark/bots.nim @@ -331,7 +331,7 @@ proc deliverChat*( target < -2 or target == -1 or target >= game.inboxes.len or text.len == 0 or text.len > MaxChatBytes: return 0 - let id = int32(if target < 0: target else: sender) + let id = receivedChatId(sender, target) for recipient in 0 ..< game.inboxes.len: if (target == -2 or recipient == target) and game.inboxes[recipient].count < MaxMailboxMessages: @@ -392,15 +392,8 @@ proc buildOverlordHost*(playerId: int32, llm: LlmClient = nil, policySlot = -1): result = activeGame.sendChat(player, int(args[0].asInt), text) let pullMailboxProc: NumericHostProc = proc(args: openArray[Value]): Value = ## Copies the oldest message into BASIC and consumes it on success. - let - player = int(playerId) - inbox = activeGame.inboxes[player] - var runtime = activeGame.brains[player].runtime - if inbox.count == 0: - result = runtime.putString("") - else: - result = runtime.putString(inbox.messages[inbox.first]) - discard inbox.pop() + let player = int(playerId) + activeGame.brains[player].runtime.pullMailboxString(activeGame.inboxes[player]) let mailboxIdProc: HostProc = proc(args: openArray[int32]): int32 = ## Returns the channel or DM sender of the last pulled message. activeGame.inboxes[int(playerId)].lastId diff --git a/games/light_vs_dark/docs/menu.md b/games/light_vs_dark/docs/menu.md index b57ae561a..e73259e97 100644 --- a/games/light_vs_dark/docs/menu.md +++ b/games/light_vs_dark/docs/menu.md @@ -2,6 +2,24 @@ Run `nim c -r games/light_vs_dark/lvd.nim` from the Polyworld root to open the main menu. Explicit `--bot` or `--replay` arguments retain direct match/replay startup; headless builds retain the command-line runner. +The [shared command-line options](../../../docs/command-line.md) apply to LvD. Use +`--player N` for the one-based human slot and `--name Alice` for a display name. +For example, `--player 2 --bot games/light_vs_dark/players/base.bas --record out/match.replay` +starts a two-player match from the repository root and saves its replay. +Repeat `--bot PATH[:N]` (or its +`--bots` alias) to fill additional slots. Replay and bot paths are relative to +the directory from which the game was launched. `--replay PATH` plays a recording. + +Native `--server URL` opens Multiplayer and connects; `--room CODE` also joins +that room. A bare `--record PATH` retains the destination for a match started +from the menu. Explicit playback speed, pause, and window-size choices also +survive local menu startup. +Live multiplayer follows the authoritative relay at normal speed; its pause +action affects the shared match. `--play` and `--speed` control local games and +file replays. +`--headless-tick-rate` and `--llm-mode` belong to headless builds; graphical +clients reject them instead of accepting settings they do not execute. + ## Shared versus game-specific code - `src/polyworld/homes.nim`: centered main menu layout, keyboard navigation, atlas packing, and backdrop drawing. diff --git a/games/light_vs_dark/frontend.nim b/games/light_vs_dark/frontend.nim index 99483a7c1..187084744 100644 --- a/games/light_vs_dark/frontend.nim +++ b/games/light_vs_dark/frontend.nim @@ -6,6 +6,13 @@ import content, controls, game, graphics, homes, lobbies, multiplayer, presets, rosterstate, participantcontext, lobbyreadiness, joiningseats +from polyworld/cli import WindowSizeFlag, BotFlag, PlayerFlag, RecordFlag, + SeedFlag, DurationFlags, ServerFlag, RoomFlag + +when not defined(emscripten): + import polyworld/[replaysaves, tapes], replaylibraries, replaymenus, replays, + replaysettings + const AppName = "Polyworld LvD" proc bundledBot(name, file: string): LocalPolicy = @@ -20,6 +27,19 @@ proc bundledBot(name, file: string): LocalPolicy = proc runFrontend*() = ## Owns menu, lobby, match and return transitions on the same window. initializeGraphics() + var + captureTarget: ScreenshotTarget + screenshotFrame = 0 + defer: releaseScreenshotTarget(captureTarget) + + proc presentMenu() = + ## Captures every menu path before presentation and leaves normal cleanup active. + when not defined(emscripten): + if captureFrame(window, screenshotFrame, 30, "light_vs_dark.png"): + window.closeRequested = true + window.presentFrame(if captureActive(): 0 else: framePaceHz) + reportReplayFrame(0, 0) + let inviteServer = inviteParameter("server") var preferences = Preferences() @@ -27,7 +47,8 @@ proc runFrontend*() = error: string roomName: string matchName, namedRoom, publishedName: string - invite = inviteParameter("room") + invite = if options.roomCode.len > 0: options.roomCode + else: inviteParameter("room") joinRequested = invite.len > 0 connection: Connection prepared: NetworkMatch @@ -54,12 +75,45 @@ proc runFrontend*() = playerName: string editingPlayer: bool connectRequested: bool + when not defined(emscripten): + var + replayPreferences = ReplayPreferences() + browsingReplays = false + replayBrowser = initReplayBrowser(Library) + replayAction: ReplayBrowserResult + unsavedReplays: seq[ReplayData] + retryReplaySave: bool + + proc retainUnsavedReplay(problem: ref CatchableError) = + ## Keeps failed automatic and manual saves available on the menu. + window.closeRequested = false + if shouldRetainReplay(replayPreferences.saveReplay, problem) and + run != nil and + run.recorder != nil and not run.replayMode: + try: + unsavedReplays.add(recordingData()) + except ReplayError: + discard + + proc drawReplayRetry() = + ## Offers a retry without losing the recording when the disk is full. + if sk.drawReplaySaveRetry(unsavedReplays.len > 0): + retryReplaySave = true + + template automaticReplaySave(): bool = + ## Enables automatic recording only for desktop games. + when defined(emscripten): false + else: replayPreferences.saveReplay and not captureActive() + try: preferences = readLvdPreferences() + when not defined(emscripten): + replayPreferences = readReplayPreferences() except MenusError, IOError, OSError: error = getCurrentExceptionMsg() - preferences = effectivePreferences(preferences, inviteServer, serverAddress) - preferences.applyPreferences(window) + preferences = effectivePreferences(preferences, inviteServer, options.serverUrl) + preferences.applyPreferences(window, configureDisplay = + not captureActive() and WindowSizeFlag notin options.specifiedFlags) window.updateCursorConfinement(preferences.edgeScrolling) roomName = defaultGameName(preferences.name) let bots = @[ @@ -72,15 +126,19 @@ proc runFrontend*() = config.maxTicks = options.maximumTicks config.mapSettings = mapSettings config.diplomacySettings = diplomacySettings - if opensMultiplayer(invite): + if opensMultiplayer(invite, options.serverUrl): page = MultiplayerMenu connectRequested = true while not window.closeRequested: when not defined(emscripten): - window.updateWindowSettings() + if not captureActive(): + window.updateWindowSettings() launchLocal = false launchNetwork = false + when not defined(emscripten): + replayAction = ReplayBrowserResult() + retryReplaySave = false if connectRequested and not editingPlayer and confirmedPlayerName(preferences.name): connectRequested = false @@ -170,12 +228,19 @@ proc runFrontend*() = prepared.humanPlayerFor(connection.client.participant) + 1 ) options.replayPath = "" - options.recordPath = "" - options.pauseOnStart = false - options.speed = 1 - let quitToMenu = runGraphics(prepared, connection) + var + quitToMenu = false + matchError: string + try: + quitToMenu = runGraphics(prepared, connection, + autoSaveReplay = automaticReplaySave()) + except CatchableError as problem: + matchError = problem.msg + quitToMenu = connection.client.snapshot.room.len == 0 + when not defined(emscripten): + retainUnsavedReplay(problem) preferences = effectivePreferences( - readLvdPreferences(), inviteServer, serverAddress + readLvdPreferences(), inviteServer, options.serverUrl ) if quitToMenu: connection.close() @@ -191,6 +256,8 @@ proc runFrontend*() = preparedRevision = 0 clearPlayerCommands() run = nil + if matchError.len > 0: + error = matchError continue window.onButtonPress = proc(button: Button) = @@ -201,6 +268,7 @@ proc runFrontend*() = ) window.onFrame = proc() = ## Draws this lifecycle state without constructing a hidden match. + discard beginScreenshotFrame(captureTarget, window) updateSounds() window.updateCursorConfinement(preferences.edgeScrolling) var contextInputBlocked = false @@ -261,13 +329,18 @@ proc runFrontend*() = if error.len > 0: sk.menuLabel(error, at + vec2(0, 272), color = LobbyRed) sk.endUi() - window.presentFrame(framePaceHz) - reportReplayFrame(0, 0) + presentMenu() + return + when not defined(emscripten): + if browsingReplays: + replayAction = sk.drawReplayBrowser(window, replayBrowser) + sk.endUi() + presentMenu() return if page == HomeMenu: case sk.drawLvdHome(window, homeFocus) - of StayHome: discard - of PlaySingle: + of LvdStayHome: discard + of LvdPlaySingle: roster = RosterState() localPolicies.setLen(config.playerCount) if humanSeat >= config.playerCount: humanSeat = -1 @@ -276,7 +349,7 @@ proc runFrontend*() = lobbyUi.scroll = 0 lobbyUi.selectedSeat = -1 rosterScroll.scrollPos = vec2(0) - of PlayMultiplayer: + of LvdPlayMultiplayer: config.playerSlot = 0 page = MultiplayerMenu connectRequested = preferences.server.strip().len > 0 and @@ -284,15 +357,21 @@ proc runFrontend*() = (connection == nil or not connection.client.connected) lobbyUi.scroll = 0 lobbyUi.selectedSeat = -1 - of OpenSettings: page = SettingsMenu - of ExitGame: + of LvdOpenReplays: + when not defined(emscripten): + browsingReplays = true + replayBrowser.refreshRequested = true + replayBrowser.message = "" + of LvdOpenSettings: page = SettingsMenu + of LvdExitGame: when not defined(emscripten): window.closeRequested = true if error.len > 0: sk.menuLabel(error, vec2(24, 24), color = rgbx(245, 151, 139, 255)) + when not defined(emscripten): + drawReplayRetry() sk.endUi() - window.presentFrame(framePaceHz) - reportReplayFrame(0, 0) + presentMenu() return var layout: LobbyLayout let origin = @@ -670,6 +749,12 @@ proc runFrontend*() = sk.lobbyLabel(if humanSeat < 0: "Spectating bots" else: "Playing seat " & $(humanSeat + 1), layout.left + vec2(22, layout.panelHeight - 74), 800, tint = LobbyMuted) + when not defined(emscripten): + if sk.drawReplaySaveOption( + window, layout.left + vec2(22, layout.panelHeight - 38), + replayPreferences.saveReplay, not modal + ): + replayPreferences.saveReplayPreferences() let selectedSeat = lobbyUi.selectedSeat let choice = if modal and not contextBlocked and lobbyUi.selectedSeat >= 0: @@ -731,7 +816,8 @@ proc runFrontend*() = window, preferences, AppName, origin, "", height ): page = HomeMenu - preferences = effectivePreferences(preferences, inviteServer, serverAddress) + preferences = effectivePreferences(preferences, inviteServer, + options.serverUrl) except CatchableError as problem: error = problem.msg if page in {MultiplayerMenu, LobbyMenu, SettingsMenu} and @@ -744,12 +830,62 @@ proc runFrontend*() = editingPlayer = true if error.len > 0: sk.lobbyLabel(error, vec2(24, 0), 1400, tint = rgbx(245, 151, 139, 255)) + when not defined(emscripten): + drawReplayRetry() sk.textStyle = "Default" sk.endUi() - window.presentFrame(framePaceHz) - reportReplayFrame(0, 0) + presentMenu() pollEvents() waitForDisplay() + when not defined(emscripten): + if retryReplaySave: + try: + unsavedReplays.retryReplaySaves( + proc(data: ReplayData): string = + ## Writes a retained game recording to its desktop library. + saveLibraryReplay(data) + ) + error = "" + replayBrowser.refreshRequested = true + except CatchableError as problem: + error = "Cannot save replay: " & problem.msg + if browsingReplays: + try: + let selected = replayBrowser.updateReplayBrowser(Library, replayAction) + case selected.action + of BackFromReplays: + browsingReplays = false + sk.resetInteractions() + of PlayReplay: + let previousOptions = options + try: + window.onFrame = nil + options.replayPath = selected.path + options.recordPath = "" + options.botGroups.setLen(0) + options.playerSlot = 0 + options.serverUrl = "" + options.roomCode = "" + options.specifiedFlags = options.specifiedFlags - + {BotFlag, PlayerFlag, RecordFlag, SeedFlag, ServerFlag, RoomFlag} - + DurationFlags + options.viewMode = 0 + initializeMatch() + runGraphics() + preferences = effectivePreferences( + readLvdPreferences(), inviteServer, previousOptions.serverUrl + ) + replayBrowser.message = "" + finally: + options = previousOptions + clearPlayerCommands() + run = nil + replayBrowser.refreshRequested = true + else: + discard + except CatchableError as problem: + replayBrowser.message = problem.msg + continue if launchLocal: connection.close() connection = nil @@ -766,12 +902,14 @@ proc runFrontend*() = try: config.playerSlot = int32(humanSeat + 1) initializeLocalMatch(config, sources) - runGraphics() + runGraphics(autoSaveReplay = automaticReplaySave()) preferences = effectivePreferences( - readLvdPreferences(), inviteServer, serverAddress + readLvdPreferences(), inviteServer, options.serverUrl ) except CatchableError as problem: error = problem.msg + when not defined(emscripten): + retainUnsavedReplay(problem) page = HomeMenu run = nil window.onFrame = nil diff --git a/games/light_vs_dark/game.nim b/games/light_vs_dark/game.nim index e541d1187..ca0315be2 100644 --- a/games/light_vs_dark/game.nim +++ b/games/light_vs_dark/game.nim @@ -7,7 +7,7 @@ import std/[os, strformat, strutils, times], - polyworld/[cli, controllers, metrics, profiles, rooms, tapes, timings], + polyworld/[cli, controllers, metrics, profiles, tapes, timings], content, maps as mapgen, sim, @@ -65,26 +65,24 @@ when defined(coworld): ) diplomacy.validate() +const SupportedFlags = + when defined(headless): + AllCommonFlags - GraphicalFlags - {NameFlag, ServerFlag, RoomFlag} + else: + AllCommonFlags - {HeadlessTickRateFlag, LlmModeFlag} + var serverAddress* = "ws://127.0.0.1:8090/ws" playerNameOverride*: string proc usage() = ## Prints the command-line and compile-time configuration surface. + echo "Light vs Dark" + echo commonUsageFor(SupportedFlags) echo """ -Light vs Dark, a small real-time strategy match between any number of BASIC overlords. +Bots fill the roster in order around the optional human slot. +The default match lasts 20 minutes and uses seed 2026. - --server URL Multiplayer relay (default ws://127.0.0.1:8090/ws). - --player NAME Set the menu player display name. - --bot PATH[:N] Add N players using one BASIC program (default N=1). - --player Add a human player in slot 1. - --player:N Insert a human in slot N (one-based). - --replay PATH Play a recorded match instead of running bots. - --record PATH Record this match to a replay file. - --seconds N Duration in seconds (default 1200). - --minutes N Duration in minutes (default 20). - --ticks N Duration in ticks (default 28800). - --seed N Map seed (default 2026). --map-layout MODE spoke or random (default spoke). --map-size N Baseline map side for two players (default 90 tiles). --expansions N Nearby expansions per player (default 2). @@ -93,22 +91,15 @@ Light vs Dark, a small real-time strategy match between any number of BASIC over --war-grace-seconds N War warning; alliance withdrawal takes 2N (default 10). --diplomacy-offer-seconds N Peace/alliance offer lifetime (default 60). --view MODE Spectator fog: all or player number (light/dark aliases). - --play=false Start the graphical transport paused. - --speed N Graphical start speed: 1, 2, 4, or 16. - --windowSize WxH Graphical window, such as 800x400. - --vsync:off Unlock the frame rate (default on). - --mute[=true|false] Override saved sound levels for this launch. - --unmute Enable sound for this launch. - --headless-tick-rate N Wall-clock ticks per second, 0 is unlimited. - --llm-mode:async|barrier Wait for all requests between headless ticks. --help Show this message. Compile with -d:headless for a command-line match. Compile with -d:emscripten for the web backend. -Compile with -d:takeScreenshot for a deterministic capture.""" +Screenshots work in ordinary graphical builds.""" -proc parseGameOptions( - settings: var MapSettings, diplomacy: var DiplomacySettings +proc parseGameOptions*( + settings: var MapSettings, diplomacy: var DiplomacySettings, + arguments = commandLineParams() ): GameOptions = ## Reads the command line into a validated match description. result = GameOptions( @@ -117,28 +108,13 @@ proc parseGameOptions( seed: DefaultSeed, speed: 1 ) - let arguments = commandLineParams() var index = 0 while index < arguments.len: - var argument = arguments[index] - if argument == "--player" and index + 1 < arguments.len and - not arguments[index + 1].startsWith("--"): - argument = "--player=" & arguments.argumentValue(index, "--player") - if argument.startsWith("--player=") and - not argument[9 .. ^1].allCharsInSet({'0' .. '9'}): - let name = argument[9 .. ^1].strip() - if name.len > 64 or not name.validName: - fail("--player requires a nonempty name of at most 64 bytes") - playerNameOverride = name - elif result.takeCommonFlag(arguments, index, argument): + let argument = arguments[index] + if result.takeCommonFlag(arguments, index, argument): discard else: case argument - of "--server": - serverAddress = arguments.argumentValue(index, "--server") - if not serverAddress.startsWith("ws://") and - not serverAddress.startsWith("wss://"): - fail("--server requires a ws:// or wss:// URL") of "--war-grace-seconds": diplomacy.warGraceSeconds = parsePositiveInt32( arguments.argumentValue(index, argument), argument @@ -181,9 +157,16 @@ proc parseGameOptions( else: fail("unknown argument: " & argument) inc index + result.rejectUnsupportedFlags(SupportedFlags) + result.resolveGamePaths() let count = result.botGroups.botCount + int(result.playerSlot > 0) - if count > 0 or result.replayPath.len > 0: - result.validateGameOptions(count, "supply at least one --bot or --player") + result.validateGameOptions(count, "supply at least one --bot or --player") + if result.serverUrl.len > 0 or result.roomCode.len > 0: + when defined(headless): + fail("--server and --room require the graphical client") + else: + if count > 0 or result.replayPath.len > 0: + fail("--server and --room use lobby seats; select players and bots in the lobby") if result.replayPath.len == 0 and count > 0: settings.validate(count) diplomacy.validate() @@ -207,6 +190,13 @@ proc initializeOptions*() = options = coworldOptions(0) else: options = parseGameOptions(mapSettings, diplomacySettings) + if options.serverUrl.len > 0: + serverAddress = options.serverUrl + playerNameOverride = options.playerName + if options.verbose: + echo "LvD launch: ", options.botGroups.botCount, " bots, human slot ", + options.playerSlot, ", seed ", options.seed, ", ", + options.maximumTicks, " ticks" optionsInitialized = true proc initializeMatch*() = @@ -350,6 +340,18 @@ proc advanceGame*() = run.sampleMetrics(run.world.over or run.world.tick >= run.maximumTicks) run.metrics.finishTick(run.world.tick) +proc recordingData*(): ReplayData = + ## Captures the full recorded timeline, including ticks after a rewind. + if run == nil or run.recorder == nil or run.replayMode: + raise newException(ReplayError, "There is no live match replay to save.") + if run.world.tick > run.recorder.data.hashes.len: + raise newException(ReplayError, + "The recording is missing the latest simulation tick.") + if run.world.tick == run.recorder.data.hashes.len: + run.sampleMetrics(true) + result = run.recorder.data + result.metrics = run.history.replayMetrics() + proc saveRecording*(path = options.recordPath) = ## Saves every recorded tick, keeping the original match setup. ## Creates the destination directory before writing the tape. @@ -358,10 +360,7 @@ proc saveRecording*(path = options.recordPath) = let directory = path.parentDir if directory.len > 0: createDir(directory) - if run.world.tick == run.recorder.data.hashes.len: - run.sampleMetrics(true) - run.recorder.data.metrics = run.history.replayMetrics() - saveReplay(path, run.recorder.data) + saveReplay(path, recordingData()) proc describeResult*(): string = ## One line naming the outcome and the score behind it. diff --git a/games/light_vs_dark/graphics.nim b/games/light_vs_dark/graphics.nim index 5e430442d..3977c366b 100644 --- a/games/light_vs_dark/graphics.nim +++ b/games/light_vs_dark/graphics.nim @@ -26,9 +26,14 @@ import constructionpresentation, targetfeedback, rendervisibility, harvestpresentation, woodcuttingpresentation, battlesounds +from polyworld/cli import WindowSizeFlag + when defined(takeScreenshot): import std/[os, strutils] +when not defined(emscripten): + import polyworld/replaysaves, replaylibraries + const DefaultCameraDistance = 17.0'f WindowTitle = "Light vs Dark" @@ -57,8 +62,6 @@ type MatchMenuPage = enum HiddenMatchMenu, PauseMenu, MatchSettings GraphicsError = object of CatchableError - CaptureTarget = object - framebuffer, colorTexture, depthBuffer: GLuint SeekCheckpoint = object world: World actionIndex: int @@ -366,7 +369,8 @@ proc initializeGraphics*(visible = true) = builder.write(AtlasPath) (window, sk) = initGameWindow(WindowTitle, AtlasPath, gameWindowSize(options.windowWidth, options.windowHeight), - options.vsync, msaa = msaa4x, visible = visible) + options.vsync, msaa = msaa4x, + visible = visible and not captureActive()) window.onFocusChange = proc() = ## Releases confinement immediately when switching to another app. window.updateCursorConfinement() @@ -374,46 +378,18 @@ proc initializeGraphics*(visible = true) = ## Restores the pointer before closing the game window. releaseCursorConfinement() -proc initCaptureTarget(size: IVec2): CaptureTarget = - ## Allocates color and depth without relying on a visible Cocoa drawable. - glGenFramebuffers(1, result.framebuffer.addr) - glBindFramebuffer(GL_FRAMEBUFFER, result.framebuffer) - glGenTextures(1, result.colorTexture.addr) - glBindTexture(GL_TEXTURE_2D, result.colorTexture) - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8.GLint, size.x, size.y, - 0, GL_RGBA, GL_UNSIGNED_BYTE, nil) - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST.GLint) - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST.GLint) - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, - GL_TEXTURE_2D, result.colorTexture, 0) - glGenRenderbuffers(1, result.depthBuffer.addr) - glBindRenderbuffer(GL_RENDERBUFFER, result.depthBuffer) - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, size.x, size.y) - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, - GL_RENDERBUFFER, result.depthBuffer) - if glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE: - raise newException(GraphicsError, "Unable to allocate screenshot target") - glBindFramebuffer(GL_FRAMEBUFFER, 0) - -proc close(target: var CaptureTarget) = - ## Releases the offscreen target while its OpenGL context is still current. - if target.framebuffer == 0: - return - glBindFramebuffer(GL_FRAMEBUFFER, 0) - glDeleteRenderbuffers(1, target.depthBuffer.addr) - glDeleteTextures(1, target.colorTexture.addr) - glDeleteFramebuffers(1, target.framebuffer.addr) - proc runGraphics*(network: NetworkMatch = nil, connection: Connection = nil, hooks = GraphicsHooks(), - hidden = defined(takeScreenshot)): bool {.discardable.} = + hidden = defined(takeScreenshot), + autoSaveReplay = false): bool {.discardable.} = ## Owns match resources; the application window survives returning to the main menu. - initializeGraphics(visible = not hidden) - var captureTarget: CaptureTarget - if hidden: - captureTarget = initCaptureTarget(window.size) - defer: captureTarget.close() + let + captureHidden = hidden or captureActive() + saveAutomatically = autoSaveReplay and not captureActive() + initializeGraphics(visible = not captureHidden) + var captureTarget: ScreenshotTarget + defer: releaseScreenshotTarget(captureTarget) window.onFrame = nil window.onButtonPress = nil window.onButtonRelease = nil @@ -451,7 +427,20 @@ proc runGraphics*(network: NetworkMatch = nil, matchMenu = HiddenMatchMenu preferences = readLvdPreferences() saveError: string - preferences.applyPreferences(window, configureDisplay = not hidden) + when not defined(emscripten): + var replaySaving: ReplaySaveState + + proc saveToLibrary() = + ## Saves each recorded state once across manual and automatic exports. + replaySaving.requestReplaySave() + let data = recordingData() + discard replaySaving.saveReplaySnapshot(data, + proc(snapshot: ReplayData): string = + ## Writes one validated game snapshot to its replay library. + saveLibraryReplay(snapshot)) + saveError = "" + preferences.applyPreferences(window, configureDisplay = + not captureHidden and WindowSizeFlag notin options.specifiedFlags) window.updateCursorConfinement(preferences.edgeScrolling) let previousBindings = customBindingsEnabled customBindingsEnabled = true @@ -494,6 +483,9 @@ proc runGraphics*(network: NetworkMatch = nil, repeating = network == nil and (run.replayMode or options.playerSlot == 0)) resetMatchState() + if network != nil and (options.pauseOnStart or options.speed != 1): + echo "LvD multiplayer follows the live relay at 1x; --play and --speed " & + "apply to local games and file replays." if network != nil and hooks.reload != nil: raise newException(GraphicsError, "Cannot replace a network match in place") let assetSeed = run.mapSeed @@ -514,7 +506,7 @@ proc runGraphics*(network: NetworkMatch = nil, primaryId = unit.id followSelection = false break - let splash = if hidden: Splash() else: startSplash(sk, window) + let splash = if captureHidden: Splash() else: startSplash(sk, window) profileBlock "terrain": seed = run.mapSeed clearProps() @@ -578,7 +570,7 @@ proc runGraphics*(network: NetworkMatch = nil, pack, woodAxe = axe ) - if not hidden: + if not captureHidden: drawSplash(sk, window, splash.name) let scene = newCharacterScene(window) @@ -1964,7 +1956,7 @@ proc runGraphics*(network: NetworkMatch = nil, observeHumanCommunication(network, packet) feedLvdActions(observeTick = true) emitTickParticles(oldUnitCooldowns, towerTargets) - let audible = not hidden and window.focused and transport.playing and + let audible = not captureHidden and window.focused and transport.playing and transport.speed == 1 and transport.targetTick < 0 and transport.restoreTick < 0 and matchMenu == HiddenMatchMenu for event in battleAudio.observeBattleSounds(run.world, viewMode, @@ -2007,7 +1999,7 @@ proc runGraphics*(network: NetworkMatch = nil, if unit.owner == LightPlayer and unit.state notin {UnitDying, UnitInMine}: selectedIds.add unit.id - var screenshotFrame = 0 + var screenshotFrame = 0 var viewingClock: ViewingClock @@ -2024,7 +2016,7 @@ proc runGraphics*(network: NetworkMatch = nil, let playback = transport resetMatchState() transport.playing = playback.playing - transport.speedIndex = playback.speedIndex + transport.setPlaybackSpeed(playback.speed) transport.repeating = playback.repeating seekCheckpoints.add SeekCheckpoint( world: run.world.clone(), actionIndex: 0, hashCheck: run.hashCheck @@ -2054,18 +2046,19 @@ proc runGraphics*(network: NetworkMatch = nil, hooks.ready(actionCam) lastFrameTime = epochTime() - if not hidden: + if not captureHidden: holdSplash(sk, window, splash) if hooks.ready != nil: hooks.ready(actionCam) window.onFrame = proc() = profileBlock "frame": + discard beginScreenshotFrame(captureTarget, window, captureHidden) updateSounds() window.updateCursorConfinement(preferences.edgeScrolling) if hooks.reload != nil and hooks.reload(): reloadMatch() let dt = frameDelta(lastFrameTime, Step) - let audioActive = not hidden and window.focused and transport.playing and + let audioActive = not captureHidden and window.focused and transport.playing and transport.speed == 1 and transport.targetTick < 0 and transport.restoreTick < 0 and matchMenu == HiddenMatchMenu if audioWasActive and not audioActive and not run.world.over: @@ -2103,7 +2096,7 @@ proc runGraphics*(network: NetworkMatch = nil, network.client.send(RoomMessage(kind: LeaveRoom)) leaveRequested = true transport.playing = not network.finished and network.client.snapshot.phase == rooms.Playing - transport.speedIndex = 0 + transport.setSpeed(0) run.historyPlayback = false networkPresentation.startFrame(dt) try: @@ -2146,6 +2139,15 @@ proc runGraphics*(network: NetworkMatch = nil, if run.recorder != nil: int32(run.recorder.data.hashes.len) else: int32(run.replayPlayer.data.hashes.len) transport.sync(run.world.tick, recordedNow, run.world.over) + when not defined(emscripten): + if not run.replayMode and replaySaving.beginAutomaticReplaySave( + saveAutomatically, + run.world.over or run.world.tick >= run.maximumTicks + ): + try: + saveToLibrary() + except CatchableError as error: + saveError = "Cannot save replay: " & error.msg let active = simulationActive(transport) harvesting.updateHarvest(run.world, dt, viewer = -1, paused = not active) currentSight = run.world.renderVisibilityValues(viewMode, CurrentSightMask) @@ -2340,8 +2342,10 @@ proc runGraphics*(network: NetworkMatch = nil, elif matchMenu == MatchSettings: menuOrigin = sk.beginOverlay(window, vec2(768, 488)) + vec2(24) else: - let panel = sk.beginOverlay(window, vec2(512, 488)) - sk.lobbyPanel(panel, vec2(512, 488)) + let + panelHeight = when defined(emscripten): 488.0'f else: 572.0'f + panel = sk.beginOverlay(window, vec2(512, panelHeight)) + sk.lobbyPanel(panel, vec2(512, panelHeight)) menuOrigin = panel + vec2(24) let beforeHud = transport if matchMenu == HiddenMatchMenu: @@ -2384,10 +2388,12 @@ proc runGraphics*(network: NetworkMatch = nil, if sk.lvdSettingsPanel(window, preferences, "Polyworld LvD", origin): matchMenu = PauseMenu else: - let paused = if network == nil: not transport.playing - else: network.client.snapshot.flag - let activeMatch = network == nil or - network.client.snapshot.phase in {rooms.Playing, Waiting} + let + paused = if network == nil: not transport.playing + else: network.client.snapshot.flag + activeMatch = network == nil or + network.client.snapshot.phase in {rooms.Playing, Waiting} + exitY = when defined(emscripten): 220.0'f else: 276.0'f var controller = network == nil if network != nil: for seat in network.client.snapshot.seats: @@ -2406,12 +2412,16 @@ proc runGraphics*(network: NetworkMatch = nil, match: network.client.match, flag: not paused)) if sk.lobbyButton("Settings", origin + vec2(0, 164), 464): matchMenu = MatchSettings + when not defined(emscripten): + if sk.lobbyButton("Save replay", origin + vec2(0, 220), 464, + enabled = run.recorder != nil and not run.replayMode): + saveToLibrary() if network == nil or network.client.snapshot.phase in {rooms.Ended, Desynced, Lobby}: if sk.lobbyButton(if network == nil: "Return to menu" else: "Return to lobby", - origin + vec2(0, 220), 464): + origin + vec2(0, exitY), 464): leaveMatch = returnToMatchLobby(network) if network != nil and sk.lobbyButton("Quit to main menu", - origin + vec2(0, if activeMatch: 220 else: 276), 464): + origin + vec2(0, if activeMatch: exitY else: exitY + 56), 464): quitToMenu = true if network == nil: leaveMatch = true elif controller and activeMatch: @@ -2421,19 +2431,38 @@ proc runGraphics*(network: NetworkMatch = nil, leaveRequested = true sk.menuLabel(if network == nil: "Use Pause match to stop the game." else: "Unused slots join next match; existing kingdoms can change controllers.", - origin + vec2(0, 332), 464) + origin + vec2(0, exitY + 112), 464) sk.menuLabel("Drag: select group / Shift: add / Ctrl+A: all units", - origin + vec2(0, 368), 464) + origin + vec2(0, exitY + 148), 464) sk.menuLabel("Right drag: formation / A: attack / Shift: queue", - origin + vec2(0, 404), 464) + origin + vec2(0, exitY + 184), 464) except CatchableError as error: saveError = error.msg - if saveError.len > 0: sk.menuLabel(saveError, origin + vec2(0, 340), 464) + when not defined(emscripten): + if matchMenu == PauseMenu: + if saveError.len > 0: + sk.menuLabel(saveError, origin + vec2(0, 500), 464, MenuAccent) + elif replaySaving.savedPath.len > 0: + sk.menuLabel("Replay saved to your library.", + origin + vec2(0, 500), 464, MenuAccent) + elif saveError.len > 0: + sk.menuLabel(saveError, origin + vec2(0, 340), 464) + else: + if saveError.len > 0: + sk.menuLabel(saveError, origin + vec2(0, 340), 464) if matchMenu == HiddenMatchMenu and hooks.overlay != nil: hooks.overlay() sk.endUi() if matchMenu == HiddenMatchMenu: drawStatsOverlay(sk, window, teamColors) + when not defined(emscripten): + if saveAutomatically and matchResultsVisible(): + sk.beginUi(window, window.size) + sk.menuLabel(if saveError.len > 0: saveError + elif replaySaving.savedPath.len > 0: + "Replay saved to your library." else: "", + vec2(24, 24), 1000, MenuAccent) + sk.endUi() # Silky ends rune capture when no editable field was submitted. Restore # chat capture after ALL UI passes, without interfering with Settings. if matchMenu == HiddenMatchMenu: @@ -2442,15 +2471,12 @@ proc runGraphics*(network: NetworkMatch = nil, finishHumanCommunicationFrame() if hooks.frame != nil and hooks.frame(): leaveMatch = true - when defined(takeScreenshot): - captureScreenshot( - window, - screenshotFrame, - 3, - "light_vs_dark.png" - ) + when not defined(emscripten): + if captureFrame(window, screenshotFrame, 3, "light_vs_dark.png"): + window.closeRequested = true + leaveMatch = true profileBlock "present": - window.presentFrame(framePaceHz) + window.presentFrame(if captureActive(): 0 else: framePaceHz) reportDirectorFrame( actionCam, transport, cameraDistance, int32(run.hashCheck.mismatches) ) @@ -2625,7 +2651,20 @@ proc runGraphics*(network: NetworkMatch = nil, window.onButtonRelease = nil shortcutState.resetShortcut() endShortcutEditing() - saveRecording() + var recordingFailure: string + when not defined(emscripten): + var libraryFailure: string + if not run.replayMode: + try: + saveRecording() + except CatchableError as error: + recordingFailure = "Cannot save replay: " & error.msg + when not defined(emscripten): + if replaySaving.shouldSaveReplayOnExit(saveAutomatically): + try: + saveToLibrary() + except CatchableError as error: + libraryFailure = "Cannot save replay: " & error.msg clickMarks.closeClickMarks() attackClickMarks.closeClickMarks() worldShapes.closeShapeRenderer() @@ -2634,4 +2673,12 @@ proc runGraphics*(network: NetworkMatch = nil, particles.closeParticles() harvestBars.closeWorldBarRenderer() finishGameProfile() + when not defined(emscripten): + if libraryFailure.len > 0: + raise newException(ReplaySaveError, libraryFailure) + if recordingFailure.len > 0: + when defined(emscripten): + raise newException(MenusError, recordingFailure) + else: + raise newException(ReplayExportError, recordingFailure) result = quitToMenu diff --git a/games/light_vs_dark/homes.nim b/games/light_vs_dark/homes.nim index 72719a4f4..e14c953bb 100644 --- a/games/light_vs_dark/homes.nim +++ b/games/light_vs_dark/homes.nim @@ -1,15 +1,77 @@ ## Game-specific art and startup routing over the shared main menu. -proc opensMultiplayer*(room: string): bool = - ## A server URL configures a future connection; only invites bypass the main menu. - room.len > 0 +proc opensMultiplayer*(room: string, configuredServer = ""): bool = + ## Explicit server launches and room invites open the multiplayer menu. + room.len > 0 or configuredServer.len > 0 when not defined(headless): - import silky, windy, polyworld/menus, polyworld/homes as sharedHomes, assets + import + chroma, pixie, silky, vmath, windy, + polyworld/[chrome, gameuis, menus, sounds], + polyworld/homes as sharedHomes, assets export sharedHomes - proc drawLvdHome*(sk: Silky, window: Window, focus: var int): HomeAction = - ## Keep the game logo close to the menu without a platform caption. - sharedHomes.drawHome(sk, window, focus, compact = true) + const + HomeSize = vec2(1672, 941) + DesktopLabels = ["Single Player", "Multiplayer", "Replays", "Settings", "Exit"] + DesktopImages = [ + "button-single-player", "button-multiplayer", "button-settings", + "button-settings", "button-exit" + ] + + type LvdHomeAction* = enum + LvdStayHome, LvdPlaySingle, LvdPlayMultiplayer, LvdOpenReplays, + LvdOpenSettings, LvdExitGame + + proc drawLvdHome*(sk: Silky, window: Window, focus: var int): LvdHomeAction = + ## Keeps LvD's compact branding and exposes the replay library on desktop. + when defined(emscripten): + case sharedHomes.drawHome(sk, window, focus, compact = true) + of StayHome: LvdStayHome + of PlaySingle: LvdPlaySingle + of PlayMultiplayer: LvdPlayMultiplayer + of OpenSettings: LvdOpenSettings + of ExitGame: LvdExitGame + else: + sk.uiScale = selectedUiScale(max(0.1'f, min( + window.size.x.float32 / 720, + window.size.y.float32 / HomeSize.y + )), 1080.0'f / HomeSize.y) + sk.beginUi(window, window.size) + sk.mousePos = window.mousePos.vec2 / sk.uiScale + let + view = window.size.vec2 / sk.uiScale + origin = (view - HomeSize) * 0.5'f + sk.drawHomeBackground(window) + sk.drawSprite("home-shade", origin + vec2(386, 95), vec2(900, 850)) + sk.drawSprite("home-logo", origin + vec2(536, 105), vec2(600, 400)) + focus = clamp(focus, 0, DesktopLabels.high) + if window.buttonPressed[KeyUp]: + focus = (focus + DesktopLabels.len - 1) mod DesktopLabels.len + playSound(SelectSound) + if window.buttonPressed[KeyDown] or window.buttonPressed[KeyTab]: + focus = (focus + 1) mod DesktopLabels.len + playSound(SelectSound) + for index, label in DesktopLabels: + let + at = origin + vec2(596, 490 + index.float32 * 80) + size = vec2(480, 70) + panel = GameUiPanel(origin: at, size: size) + hovered = panel.contains(sk.mousePos) + if hovered and window.mouseDelta != ivec2(0): + focus = index + sk.hoverSound(panel) + let + tint = if hovered or focus == index: 255'u8 else: 226'u8 + ink = + if index == 0: rgbx(39, 24, 10, 255) + else: rgbx(255, 242, 213, 255) + sk.drawSprite("home-" & DesktopImages[index], at, size, + rgbx(tint, tint, tint, 255)) + sk.drawLabel(label, at, size, ink, "H1", CenterAlign) + if (hovered and window.buttonReleased[MouseLeft]) or + (focus == index and window.buttonPressed[KeyEnter]): + result = LvdHomeAction(index + 1) + playSound(ClickSound) proc effectivePreferences*(stored: Preferences, queryServer, configuredServer: string): Preferences = @@ -17,9 +79,9 @@ when not defined(headless): result = stored if queryServer.len > 0: result.server = queryServer - elif configuredServer.len > 0 and configuredServer != Preferences().server: - # The backend's default is not an explicit frontend override. + elif configuredServer.len > 0: result.server = configuredServer proc addHomeAssets*(builder: AtlasBuilder) = + ## Packs LvD artwork into the common menu atlas. sharedHomes.addHomeAssets(builder, assets.MenuRoot, assets.MenuImages) diff --git a/games/light_vs_dark/lvd.nim b/games/light_vs_dark/lvd.nim index 3713bdd23..5acf1bb39 100644 --- a/games/light_vs_dark/lvd.nim +++ b/games/light_vs_dark/lvd.nim @@ -15,10 +15,13 @@ when defined(headless): outcome: "winner_" & $run.world.winner )) else: - import windy, polyworld/[menus, pointers, sounds], game, graphics, frontend, + import windy, polyworld/[menus, pointers, sounds, viewers], + game, graphics, frontend, lobbies, assets initializeOptions() - configureSoundLaunch(options.soundMuted, options.soundOverride) + configureCapture(options.capture, "light_vs_dark.png") + configureSoundLaunch(captureActive() or options.soundMuted, + captureActive() or options.soundOverride) try: var preferences = readLvdPreferences() configureSounds( diff --git a/games/light_vs_dark/multiplayer.nim b/games/light_vs_dark/multiplayer.nim index 95e6be765..c99c7f718 100644 --- a/games/light_vs_dark/multiplayer.nim +++ b/games/light_vs_dark/multiplayer.nim @@ -77,13 +77,14 @@ proc encodeChat*(chat: ChatSubmission): string = result.put32(cast[uint32](chat.target)) result.putString(chat.text) -proc decodeChat(bytes: string): ChatSubmission = - var reader = PacketReader(data: bytes) - if reader.get32() != 0: reject("Unknown LvD mailbox payload") - result.player = cast[int32](reader.get32()) +proc readChat(reader: var PacketReader, tick: uint32): ReplayAction = + ## The caller consumed the chat tag while dispatching the packet. + result.kind = ActionChat + result.tick = tick + result.playerId = cast[int32](reader.get32()) result.target = cast[int32](reader.get32()) result.text = reader.getString(MaxChatBytes) - if reader.cursor != bytes.len: reject("Trailing LvD mailbox bytes") + if reader.cursor != reader.data.len: reject("Trailing LvD mailbox bytes") proc newLocalMatch*(config: LvdConfig, sources: openArray[string]): Game = config.validate() @@ -294,18 +295,16 @@ proc applyPacket*(session: NetworkMatch, packet: RoomMessage) = reject("Command refers to an uninitialized LvD player") var reader = PacketReader(data: command.payload) if reader.get32() == 0: - let chat = decodeChat(command.payload) - if chat.player != int32(session.playerForSeat(int(command.seat))) or chat.target < -2 or + let chat = reader.readChat(packet.tick) + if chat.playerId != int32(session.playerForSeat(int(command.seat))) or chat.target < -2 or chat.target == -1 or chat.target >= game.world.players.len: reject("Invalid LvD mailbox sender or target") if chat.text.len > 0: - let action = ReplayAction(kind: ActionChat, tick: packet.tick, - playerId: chat.player, target: chat.target, text: chat.text) try: - action.validateAction(game.recorder.data.header.setup) + chat.validateAction(game.recorder.data.header.setup) except ReplayError as error: reject(error.msg) - actions.add action + actions.add chat inc chatCount continue var action = decodeSubmission(command.payload) diff --git a/games/light_vs_dark/replaylibraries.nim b/games/light_vs_dark/replaylibraries.nim new file mode 100644 index 000000000..3ec17847a --- /dev/null +++ b/games/light_vs_dark/replaylibraries.nim @@ -0,0 +1,46 @@ +import polyworld/replaylibraries as sharedLibraries +import replays + +export sharedLibraries.ReplayEntry + +proc replayTicks(bytes: string): int = + ## Validates this game's complete payload before marking a file playable. + decodeReplay(bytes).hashes.len + +const Library* = ReplayLibrary( + gameFolder: "Light vs Dark", + gamePrefix: "LvD", + format: ReplayLibraryFormat( + game: ReplayGame, + gameVersion: ReplayGameVersion, + tapeVersion: ReplayFormatVersion, + maxBytes: MaxReplayBytes + ), + inspect: replayTicks +) + +proc replayDirectory*(): string = + ## Returns this game's replay folder in the current user's application data. + sharedLibraries.replayDirectory(Library) + +proc ensureReplayDirectory*(directory = replayDirectory()): string = + ## Creates and returns the library directory without relying on the game path. + sharedLibraries.ensureReplayDirectory(Library, directory) + +proc inspectReplay*(path: string): ReplayEntry = + ## Describes a valid, incompatible, or unreadable LvD recording. + sharedLibraries.inspectReplay(Library, path) + +proc listReplays*(directory = replayDirectory()): seq[ReplayEntry] = + ## Lists this game's recordings with newest files first. + sharedLibraries.listReplays(Library, directory) + +proc saveLibraryReplay*( + data: ReplayData, directory = replayDirectory() +): string = + ## Validates and saves the complete match under a unique library filename. + sharedLibraries.saveLibraryReplay(Library, encodeReplay(data), directory) + +proc importReplay*(source: string, directory = replayDirectory()): string = + ## Copies a LvD recording, preserving unsupported versions and the source. + sharedLibraries.importReplay(Library, source, directory) diff --git a/games/light_vs_dark/replaymenus.nim b/games/light_vs_dark/replaymenus.nim new file mode 100644 index 000000000..170add97e --- /dev/null +++ b/games/light_vs_dark/replaymenus.nim @@ -0,0 +1,23 @@ +import + silky, windy, + polyworld/replaymenus as sharedReplayMenus, + content, replaylibraries, replays + +export sharedReplayMenus except drawReplayBrowser + +proc drawReplayBrowser*( + sk: Silky, window: Window, ui: var ReplayBrowserUi, + entries: openArray[ReplayEntry], folder: string, message = "" +): ReplayBrowserResult = + ## Supplies LvD's replay version and clock to the shared desktop browser. + sharedReplayMenus.drawReplayBrowser( + sk, window, ui, entries, folder, ReplayGameVersion, TickRate, message + ) + +proc drawReplayBrowser*( + sk: Silky, window: Window, browser: var ReplayBrowserState +): ReplayBrowserResult = + ## Supplies LvD's replay metadata to the shared library controller. + sharedReplayMenus.drawReplayBrowser( + sk, window, browser, ReplayGameVersion, TickRate + ) diff --git a/games/light_vs_dark/replaysettings.nim b/games/light_vs_dark/replaysettings.nim new file mode 100644 index 000000000..8b29d7164 --- /dev/null +++ b/games/light_vs_dark/replaysettings.nim @@ -0,0 +1,11 @@ +import polyworld/replaysettings as sharedSettings + +export sharedSettings.ReplayPreferences + +proc readReplayPreferences*(): ReplayPreferences = + ## Reads LvD's recording choice from its existing device configuration. + sharedSettings.readReplayPreferences("Polyworld LvD") + +proc saveReplayPreferences*(preferences: ReplayPreferences) = + ## Saves LvD's recording choice separately from shared match settings. + sharedSettings.saveReplayPreferences(preferences, "Polyworld LvD") diff --git a/games/light_vs_dark/tests/test_backend_cli.nim b/games/light_vs_dark/tests/test_backend_cli.nim index b9d55d9f1..8b3c6ce0e 100644 --- a/games/light_vs_dark/tests/test_backend_cli.nim +++ b/games/light_vs_dark/tests/test_backend_cli.nim @@ -1,6 +1,119 @@ -import ../game -initializeOptions() -doAssert run == nil -doAssert serverAddress == "ws://127.0.0.1:8090/ws" -doAssert playerNameOverride == "Alice" +import + std/os, + polyworld/cli, + ../game, ../presets + +proc parsed(arguments: seq[string]): GameOptions = + ## Exercises the game's startup parser without terrain, bots, or a window. + var + settings = MapSettings() + diplomacy = DiplomacySettings() + parseGameOptions(settings, diplomacy, arguments) + +echo "Testing LvD delegates common launch options" +block: + let previousRun = run + for arguments in [ + @["--bots", "players/base.bas:2", "--record", "out/match.replay", + "--seed", "17", "--ticks", "48"], + @["--bots=players/base.bas:2", "--record=out/match.replay", + "--seed=17", "--ticks=48"], + @["--bots:players/base.bas:2", "--record:out/match.replay", + "--seed:17", "--ticks:48"] + ]: + let options = parsed(arguments) + doAssert options.botGroups.botCount == 2 + doAssert options.botGroups[0].path == absolutePath("players/base.bas") + doAssert options.recordPath == absolutePath("out/match.replay") + doAssert options.seed == 17 and options.maximumTicks == 48 + doAssert options.speed == 1 and not options.pauseOnStart + doAssert run == previousRun + +echo "Testing LvD replay paths and menu recording destinations" +block: + let replay = parsed(@["--replay=recordings/a.replay"]) + doAssert replay.replayPath == absolutePath("recordings/a.replay") + let menu = parsed(@["--record:out/menu.replay"]) + doAssert menu.recordPath == absolutePath("out/menu.replay") + doAssert menu.botGroups.len == 0 and menu.playerSlot == 0 + var rejected = false + try: + discard parsed(@["--replay", "a.replay", "--record", "b.replay"]) + except CliError: + rejected = true + doAssert rejected + +when defined(headless): + echo "Testing LvD headless pacing and LLM barriers" + block: + let options = parsed(@["--bot", "players/base.bas:2", + "--headless-tick-rate=12", "--llm-mode:barrier"]) + doAssert options.headlessTickRate == 12 + doAssert options.waitForLlm + let defaults = parsed(@["--headless-tick-rate", "0", "--llm-mode", "async"]) + doAssert defaults.headlessTickRate == 0 + doAssert not defaults.waitForLlm +else: + echo "Testing LvD rejects headless-only options in graphical clients" + block: + for arguments in [ + @["--headless-tick-rate=0"], @["--headless-tick-rate", "12"], + @["--llm-mode:async"], @["--llm-mode", "barrier"] + ]: + var rejected = false + try: + discard parsed(arguments) + except CliError: + rejected = true + doAssert rejected + + echo "Testing LvD retains graphical launch overrides before menu startup" + block: + let options = parsed(@["--record:out/menu.replay", "--play=false", + "--speed:3", "--windowSize=960x640"]) + doAssert options.pauseOnStart and options.speed == 3 + doAssert options.windowWidth == 960 and options.windowHeight == 640 + doAssert WindowSizeFlag in options.specifiedFlags + doAssert options.recordPath == absolutePath("out/menu.replay") + + echo "Testing LvD separates human slots from names" + block: + for arguments in [ + @["--player", "2", "--name", "Alice", "--bot", "players/base.bas"], + @["--player=2", "--name=Alice", "--bot=players/base.bas"], + @["--player:2", "--name:Alice", "--bot:players/base.bas"] + ]: + let options = parsed(arguments) + doAssert options.playerSlot == 2 + doAssert options.playerName == "Alice" + doAssert options.botGroups.botCount == 1 + doAssert parsed(@["--player"]).playerSlot == 1 + var rejected = false + try: + discard parsed(@["--player", "Alice"]) + except CliError: + rejected = true + doAssert rejected + + echo "Testing LvD relay and invitation arguments" + block: + for arguments in [ + @["--server", "ws://127.0.0.1:9911/ws", "--room", "ExactCase"], + @["--server=ws://127.0.0.1:9911/ws", "--room=ExactCase"], + @["--server:ws://127.0.0.1:9911/ws", "--room:ExactCase"] + ]: + let options = parsed(arguments) + doAssert options.serverUrl == "ws://127.0.0.1:9911/ws" + doAssert options.roomCode == "ExactCase" + doAssert options.botGroups.len == 0 and options.playerSlot == 0 + +when defined(headless): + echo "Testing LvD headless launches reject a graphical display name" + var rejected = false + try: + discard parsed(@["--name", "Alice"]) + except CliError: + rejected = true + doAssert rejected + echo "LvD menu CLI options passed" diff --git a/games/light_vs_dark/tests/test_menu_ui.nim b/games/light_vs_dark/tests/test_menu_ui.nim index 1d4d93e02..d5d0b653e 100644 --- a/games/light_vs_dark/tests/test_menu_ui.nim +++ b/games/light_vs_dark/tests/test_menu_ui.nim @@ -24,9 +24,10 @@ suite "LvD roster": check humanAfterRemoval(-1, 0) == -1 suite "LvD menu entry": - test "server overrides do not skip the main menu, room invites do": + test "explicit server launches and room invites open multiplayer": check not opensMultiplayer("") check opensMultiplayer("room-code") + check opensMultiplayer("", "ws://127.0.0.1:9911/ws") when not defined(headless): import polyworld/menus @@ -38,7 +39,8 @@ when not defined(headless): check effectivePreferences(stored, "", configured).server == configured check effectivePreferences(stored, "wss://query.example/ws", configured).server == "wss://query.example/ws" - check effectivePreferences(stored, "", Preferences().server) == stored + check effectivePreferences(stored, "", Preferences().server).server == + Preferences().server check effectivePreferences(stored, "", "") == stored test "server query survives settings and local match preference reloads": diff --git a/games/light_vs_dark/tests/test_recording_library.nim b/games/light_vs_dark/tests/test_recording_library.nim new file mode 100644 index 000000000..6fba4659d --- /dev/null +++ b/games/light_vs_dark/tests/test_recording_library.nim @@ -0,0 +1,118 @@ +import + std/[os, strutils, tempfiles], + polyworld/tapes, + ../[bots, content, controls, game, multiplayer, presets, replaylibraries, + replays, sim] + +proc testRecordingLibrary() = + ## Saves a real match and retains its complete actions and metrics on rewind. + let + directory = createTempDir("lvd-recording-library-", "") + library = directory / "Replays" + previousRun = run + defer: + clearPlayerCommands() + run = previousRun + removeDir(directory) + var config = defaultConfig(2) + config.maxTicks = 60 + config.mapSettings = MapSettings( + layout: RandomLayout, size: 90, expansions: 0 + ) + run = newLocalMatch(config, ["", ""]) + let + live = run + worker = run.world.units[0] + opening = run.world.clone() + doAssert run.sendChat(0, -2, "Opening message") > 0 + queueMove(worker.owner, worker.id, worker.tile.x.int32 + 2, + worker.tile.y.int32) + while run.world.tick < 20: + advanceGame() + let partialPath = directory / "partial.replay" + saveRecording(partialPath) + let partial = loadReplay(partialPath) + doAssert partial.hashes.len == 20 + doAssert partial.metrics.frames[^1].tick == 20 + doAssert partial.actions.len >= 2 + + while run.world.tick < config.maxTicks and not run.world.over: + if run.world.tick == 30: + doAssert run.sendChat(1, -2, "Later message") > 0 + queueCancel(worker.owner, worker.id) + advanceGame() + doAssert run.world.tick == config.maxTicks + let + completed = recordingData() + liveHash = run.stateHash() + path = saveLibraryReplay(completed, library) + loaded = loadReplay(path) + doAssert completed.hashes.len == config.maxTicks + doAssert completed.actions[^1].tick > 20 + doAssert loaded.actions == completed.actions + doAssert loaded.hashes == completed.hashes + doAssert loaded.metrics == completed.metrics + doAssert loaded.metrics.frames[^1].tick == config.maxTicks + let entries = listReplays(library) + doAssert entries.len == 1 + doAssert entries[0].path == path and entries[0].playable + doAssert entries[0].ticks == completed.hashes.len + + let playback = newGame( + live.world.map, config.maxTicks, loaded.header.setup.diplomacySettings + ) + playback.replayMode = true + playback.historyPlayback = true + playback.replayData = loaded + playback.replayPlayer = initReplayPlayer(loaded) + run = playback + for tick in 1 .. loaded.hashes.len: + advanceGame() + doAssert playback.hashCheck.mismatches == 0 + doAssert playback.replayPlayer.finished + doAssert playback.stateHash() == liveHash + var rejected = false + try: + discard recordingData() + except ReplayError: + rejected = true + doAssert rejected, "Watching a replay must not create a new recording." + + run = live + run.world.restore(opening) + run.historyPlayback = true + let rewound = recordingData() + doAssert rewound.hashes == completed.hashes + doAssert rewound.actions == completed.actions + doAssert rewound.metrics == completed.metrics, + "Saving while rewound must keep original late-match telemetry." + let rewoundPath = saveLibraryReplay(rewound, library) + doAssert loadReplay(rewoundPath).hashes == completed.hashes + doAssert listReplays(library).len == 2 + + run.world.tick = config.maxTicks + 1 + rejected = false + try: + discard saveLibraryReplay(recordingData(), library) + except ReplayError as error: + rejected = true + doAssert "missing the latest simulation tick" in error.msg + doAssert rejected + doAssert listReplays(library).len == 2 + run.recorder = nil + rejected = false + try: + discard recordingData() + except ReplayError: + rejected = true + doAssert rejected, "A missing recorder must be reported before saving." + run = nil + rejected = false + try: + discard recordingData() + except ReplayError: + rejected = true + doAssert rejected, "An absent match must be reported before saving." + +testRecordingLibrary() +echo "LvD match recording, library playback, rewind retention, and errors passed." diff --git a/games/light_vs_dark/tests/test_replay_library.nim b/games/light_vs_dark/tests/test_replay_library.nim new file mode 100644 index 000000000..2525e8acb --- /dev/null +++ b/games/light_vs_dark/tests/test_replay_library.nim @@ -0,0 +1,206 @@ +import + std/[os, strutils, tempfiles, times], + polyworld/tapes, + ../content, ../replays, ../replaylibraries + +const RecordedTicks = DecisionTicks * 2 + +proc sampleReplay(): ReplayData = + ## Builds a tiny valid tape with commands and chat without creating a world. + let recorder = initReplayRecorder(Setup( + mapSeed: DefaultSeed, + tickRate: uint16(TickRate), + gridTiles: uint16(DefaultMapSize), + decisionTicks: uint16(DecisionTicks), + maximumTicks: uint32(RecordedTicks), + mapHash: 0x123456789ABCDEF0'u64, + contentHash: contentHash(), + players: @[ + ReplayPlayerSetup(id: 0, startX: 19, startY: 19), + ReplayPlayerSetup( + id: 1, startX: DefaultMapSize - 22, startY: DefaultMapSize - 22 + ) + ] + )) + recorder.recordAction( + uint32(DecisionTicks), LightPlayer, ActionMove, FirstUnitId, 64, 42 + ) + recorder.record ReplayAction( + kind: ActionChat, tick: uint32(DecisionTicks), + playerId: 0, target: -2, text: "Hold the line" + ) + recorder.recordAction( + uint32(RecordedTicks), DarkPlayer, ActionAttack, + FirstUnitId + 5, FirstUnitId + ) + for tick in 1 .. RecordedTicks: + recorder.recordHash(uint64(tick)) + recorder.data + +proc changeVersion(bytes: var string, offset: int, version: uint16) = + ## Rewrites a header field without interpreting an obsolete game payload. + bytes[offset] = char(version and 0xff) + bytes[offset + 1] = char(version shr 8) + +proc rejectsImport(path, directory: string) = + ## Requires malformed imports to leave their source and library unchanged. + let + source = readFile(path) + before = listReplays(directory).len + var rejected = false + try: + discard importReplay(path, directory) + except ReplayError: + rejected = true + doAssert rejected + doAssert readFile(path) == source + doAssert listReplays(directory).len == before + +proc testLibrary() = + ## Exercises saves, old versions, malformed files, and non-destructive imports. + let + root = createTempDir("lvd-replay-library-", "") + library = root / "library with spaces" + data = sampleReplay() + bytes = encodeReplay(data) + payloadOffset = ReplayMagic.len + 6 + ReplayGame.len + defer: + removeDir(root) + + echo "Testing user library locations and empty libraries" + doAssert replayDirectory().isAbsolute() + doAssert replayDirectory().endsWith( + "Polyworld" / "Light vs Dark" / "Replays" + ) + doAssert listReplays(library).len == 0 + doAssert not dirExists(library) + doAssert ensureReplayDirectory(library) == library + + echo "Testing uniquely named atomic replay saves" + let + first = saveLibraryReplay(data, library) + second = saveLibraryReplay(data, library) + doAssert first != second + doAssert first.parentDir == library + doAssert first.splitFile().ext == ".replay" + doAssert readFile(first) == bytes + doAssert readFile(second) == bytes + doAssert loadReplay(first).actions == data.actions + doAssert first.splitFile().name.startsWith("LvD-") + let entry = inspectReplay(first) + doAssert entry.playable + doAssert entry.problem.len == 0 + doAssert entry.ticks == RecordedTicks + doAssert entry.fileVersion == ReplayFileVersion + doAssert entry.gameVersion == ReplayGameVersion + doAssert entry.tapeVersion == ReplayFormatVersion + doAssert entry.size == bytes.len + doAssert entry.path == first + doAssert entry.name == first.splitFile().name + for kind, path in walkDir(library): + doAssert kind == pcFile + doAssert path.endsWith(".replay") + + echo "Testing newest-first ordering and unrelated-file filtering" + setLastModificationTime(first, fromUnix(100)) + setLastModificationTime(second, fromUnix(200)) + writeFile(library / "unfinished.partial", bytes) + writeFile(library / "notes.txt", "not a replay") + createDir(library / "directory.replay") + let ordered = listReplays(library) + doAssert ordered.len == 2 + doAssert ordered[0].path == second + doAssert ordered[1].path == first + + echo "Testing import copies, repeated names, and importing library files" + let source = root / "A match with spaces.REPLAY" + writeFile(source, bytes) + let + imported = importReplay(source, library) + importedAgain = importReplay(source, library) + doAssert imported != importedAgain + doAssert readFile(source) == bytes + doAssert readFile(imported) == bytes + doAssert imported.splitFile().name.startsWith("Imported-A-match-with-spaces-") + let count = listReplays(library).len + doAssert importReplay(imported, library) == imported + doAssert listReplays(library).len == count + + echo "Testing incompatible versions remain visible and import unchanged" + for kind in 0 ..< 4: + var old = bytes + case kind + of 0: + old.changeVersion(ReplayMagic.len + 2, ReplayGameVersion - 1) + old.setLen(payloadOffset) + old.add("old payload whose layout is intentionally unknown") + of 1: + old.changeVersion(ReplayMagic.len, ReplayFileVersion + 1) + old.setLen(payloadOffset) + of 2: + old.changeVersion(payloadOffset, ReplayFormatVersion - 1) + old.setLen(payloadOffset + 4) + else: + old.changeVersion(payloadOffset + 2, ReplayGameVersion + 1) + old.setLen(payloadOffset + 4) + let path = root / ("older-" & $kind & ".replay") + writeFile(path, old) + let + copied = importReplay(path, library) + incompatible = inspectReplay(copied) + doAssert not incompatible.playable + doAssert incompatible.problem.len > 0 + doAssert readFile(copied) == old + doAssert readFile(path) == old + + echo "Testing invalid, truncated, and foreign replays are contained" + for i, bad in [ + "not a replay", + ReplayMagic, + bytes[0 ..< payloadOffset + 4], + encodeReplayFile("gods_of_the_arena", 84, 1'u32) + ]: + let path = root / ("invalid-" & $i & ".replay") + writeFile(path, bad) + let invalid = inspectReplay(path) + doAssert not invalid.playable + doAssert invalid.problem.len > 0 + rejectsImport(path, library) + let broken = library / "broken.replay" + writeFile(broken, "not a replay") + var foundBroken = false + for item in listReplays(library): + if item.path == broken: + foundBroken = true + doAssert not item.playable + doAssert item.problem.len > 0 + doAssert foundBroken + + echo "Testing oversized replays and failed saves" + let oversized = root / "oversized.replay" + block: + let file = open(oversized, fmWrite) + defer: + file.close() + file.setFilePos(MaxReplayBytes) + file.write('x') + doAssert not inspectReplay(oversized).playable + doAssert "64 MiB" in inspectReplay(oversized).problem + var rejected = false + try: + discard importReplay(oversized, library) + except ReplayError: + rejected = true + doAssert rejected + let occupied = root / "occupied" + writeFile(occupied, "keep this file") + rejected = false + try: + discard saveLibraryReplay(data, occupied) + except ReplayError: + rejected = true + doAssert rejected + doAssert readFile(occupied) == "keep this file" + +testLibrary() +echo "LvD replay library checks passed without touching the user library." diff --git a/games/light_vs_dark/tests/test_replay_menu_render.nim b/games/light_vs_dark/tests/test_replay_menu_render.nim new file mode 100644 index 000000000..294a31cbf --- /dev/null +++ b/games/light_vs_dark/tests/test_replay_menu_render.nim @@ -0,0 +1,147 @@ +import + std/[importutils, os, times], + opengl, pixie, silky, vmath, windy/internal, + polyworld/[chrome, lobbies, viewers], + ../[content, homes, replaylibraries, replaymenus, replays] + +privateAccess(Window) + +proc verifyReplayMenu(size: IVec2, screenshot: string, zoom = 0) = + ## Exercises production replay controls with real UI input and rendering. + let + savedMode = uiScaleMode + savedPercent = uiScalePercent + if zoom > 0: + uiScaleMode = CustomUiScale + uiScalePercent = zoom + defer: + uiScaleMode = savedMode + uiScalePercent = savedPercent + let window = newWindow("LvD replay browser test", size, visible = false) + defer: + window.close() + window.makeContextCurrent() + loadExtensions() + let builder = newHudAtlas(4096) + builder.addDefaultFonts() + builder.addLobbyFonts() + builder.addHomeAssets() + let sk = newSilky(window, builder.atlasImage, builder.atlas) + sk.applyThemePatches() + var + browser = ReplayBrowserUi() + entries: seq[ReplayEntry] + framebuffer, texture: GLuint + for index in 0 ..< 12: + entries.add ReplayEntry( + path: "/test/lvd-" & $index & ".replay", + name: "LvD match " & $(index + 1), + modified: fromUnix(1795200000 - int64(index * 3600)), + gameVersion: ReplayGameVersion, + ticks: TickRate * 60 * 12, + playable: true + ) + entries[1].playable = false + entries[1].gameVersion = ReplayGameVersion - 1 + entries[1].problem = "Game version " & $entries[1].gameVersion & + " (requires " & $ReplayGameVersion & ")" + entries[2].playable = false + entries[2].problem = "The replay file is incomplete." + glGenFramebuffers(1, framebuffer.addr) + glGenTextures(1, texture.addr) + glBindTexture(GL_TEXTURE_2D, texture) + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8.GLint, size.x.GLsizei, size.y.GLsizei, + 0, GL_RGBA, GL_UNSIGNED_BYTE, nil) + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer) + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, texture, 0) + doAssert glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE + defer: + glBindFramebuffer(GL_FRAMEBUFFER, 0) + glDeleteTextures(1, texture.addr) + glDeleteFramebuffers(1, framebuffer.addr) + + proc input(point = vec2(-100), pressed = false, released = false, + key = ButtonUnknown) = + ## Updates only the transient events consumed by the real menu widgets. + window.state.perFrame = PerFrame() + window.state.buttonDown = {} + window.state.mousePos = (point * sk.uiScale).ivec2 + window.state.mousePrevPos = window.state.mousePos + if pressed: + window.state.perFrame.buttonPressed.incl MouseLeft + window.state.buttonDown.incl MouseLeft + if released: + window.state.perFrame.buttonReleased.incl MouseLeft + if key != ButtonUnknown: + window.state.perFrame.buttonPressed.incl key + + proc render(point = vec2(-100), pressed = false, released = false, + key = ButtonUnknown): ReplayBrowserResult = + ## Renders the browser without performing its returned filesystem actions. + input(point, pressed, released, key) + result = sk.drawReplayBrowser(window, browser, entries, + "User folder / Polyworld / Light vs Dark / Replays") + sk.endUi() + + proc click(point: Vec2): ReplayBrowserResult = + ## Sends a complete mouse press and release through the renderer. + discard render(point, pressed = true) + render(point, released = true) + + discard render() + let layout = replayBrowserLayout(window.size.vec2 / sk.uiScale) + doAssert layout.back.y + layout.back.h < window.size.y.float32 / sk.uiScale + doAssert layout.folderButton.x + layout.folderButton.w < layout.refresh.x + doAssert layout.panel.y + layout.panel.h < layout.back.y + let watch = layout.rows.xy + vec2(layout.rows.w - 96, 48) + let live = click(watch) + doAssert live.action == PlayReplay and live.path == entries[0].path + doAssert click(watch + vec2(0, ReplayRowHeight)).action == StayReplayBrowser + doAssert click(watch + vec2(0, ReplayRowHeight * 2)).action == StayReplayBrowser + discard render(key = KeyDown) + doAssert browser.selectedPath == entries[0].path + discard render(key = KeyDown) + doAssert browser.selectedPath == entries[3].path + doAssert render(key = KeyEnter).path == entries[3].path + for index in 0 ..< 10: + discard render(key = KeyDown) + doAssert browser.selectedPath == entries[^1].path + doAssert browser.scroll.scrollPos.y > 0 + doAssert render(key = KeyEnter).path == entries[^1].path + doAssert click(layout.importButton.xy + vec2(60, 20)).action == ImportReplayFile + doAssert click(layout.folderButton.xy + vec2(70, 20)).action == OpenReplayFolder + doAssert click(layout.refresh.xy + vec2(70, 20)).action == RefreshReplays + doAssert click(layout.back.xy + vec2(70, 20)).action == BackFromReplays + doAssert render(key = KeyEscape).action == BackFromReplays + browser = ReplayBrowserUi() + discard render() + if screenshot.len > 0: + let image = newImage(size.x, size.y) + glReadPixels(0, 0, size.x.GLsizei, size.y.GLsizei, + GL_RGBA, GL_UNSIGNED_BYTE, image.data[0].addr) + image.flipVertical() + createDir(screenshot.parentDir) + image.writeFile(screenshot) + entries.setLen(0) + browser.selectedPath = "/test/no-longer-present.replay" + doAssert render(key = KeyEnter).action == StayReplayBrowser + doAssert browser.selectedPath.len == 0 + doAssert click(layout.importButton.xy + vec2(60, 20)).action == ImportReplayFile + var focus = 2 + input(key = KeyEnter) + doAssert sk.drawLvdHome(window, focus) == LvdOpenReplays + sk.endUi() + input(key = KeyDown) + doAssert sk.drawLvdHome(window, focus) == LvdStayHome + doAssert focus == 3 + sk.endUi() + input(key = KeyEnter) + doAssert sk.drawLvdHome(window, focus) == LvdOpenSettings + sk.endUi() + +verifyReplayMenu(ivec2(1280, 900), + getEnv("LVD_REPLAY_MENU_SCREENSHOT", "/tmp/lvd-replay-browser.png")) +verifyReplayMenu(ivec2(800, 600), "") +verifyReplayMenu(ivec2(800, 600), "", zoom = 300) +echo "Replay browser mouse, keyboard, disabled versions, and scrolling passed." diff --git a/games/light_vs_dark/tests/test_replay_save_graphics.nim b/games/light_vs_dark/tests/test_replay_save_graphics.nim new file mode 100644 index 000000000..e51f9f254 --- /dev/null +++ b/games/light_vs_dark/tests/test_replay_save_graphics.nim @@ -0,0 +1,141 @@ +import + std/[os, strutils, tempfiles], + windy, + polyworld/[replaysaves, sounds], + ../[game, graphics, presets, replaylibraries, replays, sim] + +proc testReplaySaving() = + ## Exercises automatic recording through the native renderer and cleanup. + const DataVariable = when defined(windows): "APPDATA" else: "XDG_DATA_HOME" + let + directory = createTempDir("lvd-graphics-replays-", "") + hadData = existsEnv(DataVariable) + previousData = getEnv(DataVariable) + previousOptions = options + previousRun = run + doAssert window == nil, "This native graphics test needs its own process." + putEnv(DataVariable, directory) + defer: + if window != nil: + window.close() + window = nil + options = previousOptions + run = previousRun + if hadData: + putEnv(DataVariable, previousData) + else: + delEnv(DataVariable) + removeDir(directory) + let library = replayDirectory() + doAssert library.startsWith(directory) + options.windowWidth = 640 + options.windowHeight = 480 + options.playerSlot = 1 + options.speed = 16 + options.pauseOnStart = false + options.recordPath = "" + options.vsync = false + var config = defaultConfig(2) + config.playerSlot = 1 + config.maxTicks = 6 + config.mapSettings = MapSettings( + layout: RandomLayout, size: 48, expansions: 0, minDistance: 12 + ) + initializeLocalMatch(config, ["", ""]) + var frames = 0 + var completionSaved = false + discard runGraphics(hidden = true, autoSaveReplay = true, + hooks = GraphicsHooks(frame: proc(): bool = + ## Observes a completed file before returning from the match renderer. + inc frames + setSoundMuted(true) + doAssert frames < 300, "The short match did not finish." + if run.world.tick < config.maxTicks: + return false + let entries = listReplays(library) + doAssert entries.len == 1 and entries[0].playable + doAssert loadReplay(entries[0].path).hashes.len == config.maxTicks + completionSaved = true + true + ) + ) + doAssert completionSaved + doAssert listReplays(library).len == 1, + "Exiting a completed match must not save the same snapshot twice." + doAssert window.onFrame == nil and window.onButtonPress == nil + echo "LvD completed replay saves before exit without duplication." + + config.maxTicks = 300 + initializeLocalMatch(config, ["", ""]) + var exitTick = 0 + discard runGraphics(hidden = true, autoSaveReplay = true, + hooks = GraphicsHooks(frame: proc(): bool = + ## Stops a live match before its completion autosave can run. + setSoundMuted(true) + doAssert listReplays(library).len == 1 + exitTick = run.world.tick + true + ) + ) + doAssert exitTick < config.maxTicks + let entries = listReplays(library) + doAssert entries.len == 2 and entries[0].playable + doAssert loadReplay(entries[0].path).hashes.len == exitTick + echo "LvD leaving a partial match saves its available ticks." + + initializeLocalMatch(config, ["", ""]) + discard runGraphics(hidden = true, autoSaveReplay = false, + hooks = GraphicsHooks(frame: proc(): bool = + ## Leaves a match with automatic saving explicitly disabled. + setSoundMuted(true) + true + ) + ) + doAssert listReplays(library).len == 2 + echo "LvD disabled automatic saving leaves the library unchanged." + + let blockedExport = directory / "blocked-export" + writeFile(blockedExport, "Not a directory") + options.recordPath = blockedExport / "requested.replay" + initializeLocalMatch(config, ["", ""]) + var exportRejected = false + try: + discard runGraphics(hidden = true, autoSaveReplay = true, + hooks = GraphicsHooks(frame: proc(): bool = + ## Leaves with an unwritable CLI path and a working replay library. + setSoundMuted(true) + true + ) + ) + except ReplayExportError: + exportRejected = true + doAssert exportRejected + doAssert listReplays(library).len == 3, + "A failed explicit export must not prevent the separate library save." + doAssert window.onFrame == nil and window.onButtonPress == nil + options.recordPath = "" + echo "LvD saves to its library even when a requested CLI export fails." + + let blocked = directory / "blocked" + writeFile(blocked, "Not a directory") + putEnv(DataVariable, blocked) + initializeLocalMatch(config, ["", ""]) + var rejected = false + try: + discard runGraphics(hidden = true, autoSaveReplay = true, + hooks = GraphicsHooks(frame: proc(): bool = + ## Leaves through the same exit path while its destination is blocked. + setSoundMuted(true) + true + ) + ) + except ReplaySaveError as error: + rejected = true + doAssert "Cannot save replay" in error.msg + doAssert rejected + doAssert window.onFrame == nil and window.onButtonPress == nil + discard recordingData() + doAssert listReplays(library).len == 3 + echo "LvD failed saves clean callbacks and preserve the recording for retry." + +testReplaySaving() diff --git a/games/light_vs_dark/tests/tests.nim b/games/light_vs_dark/tests/tests.nim index 964c15968..10463463a 100644 --- a/games/light_vs_dark/tests/tests.nim +++ b/games/light_vs_dark/tests/tests.nim @@ -17,6 +17,8 @@ import test_maps, test_players, test_replays, + test_replay_library, + test_recording_library, test_replay_chat, test_research, test_research_network, @@ -26,6 +28,7 @@ import test_resourcepacks, test_woodcutting_presentation, test_backend_config, + test_backend_cli, test_multiplayer_backend, test_lobby_readiness, test_cosmetic_ready, diff --git a/games/monster/brains.nim b/games/monster/brains.nim index 09ff0a1c0..6581f8eea 100644 --- a/games/monster/brains.nim +++ b/games/monster/brains.nim @@ -825,6 +825,11 @@ proc addEvent*(brain: Brain, text: string) = brain.messages.add Message(role: EventMessage, text: text) brain.saveVisible() +proc disableSaving*(brain: Brain) = + ## Keeps loaded conversation state in memory without writing capture changes. + if brain != nil: + brain.savePath = "" + proc close*(brain: Brain) = ## Saves memories and releases the outstanding inference worker symmetrically. if brain == nil: diff --git a/games/monster/monster.nim b/games/monster/monster.nim index 4a276759c..76f5f9a79 100644 --- a/games/monster/monster.nim +++ b/games/monster/monster.nim @@ -1,12 +1,12 @@ import - std/[os, parseopt, strutils, times], + std/[os, strutils, times], polyworld/cli, - common, maps, sim, brains, conversations + common, maps, sim, brains, conversations, options when not defined(headless): import std/unicode, - opengl, pixie, silky, vmath, windy, + pixie, silky, vmath, windy, polyworld/[assets, rtscameras, viewers], scenes, ui, hudassets, selections, voices, launches @@ -18,90 +18,10 @@ when not defined(headless): CameraDistanceMax = 50'f CameraDistanceDefault = 34'f -type Options = object - seed, width, height, frames: int - offline, noVoice, soundMuted, conversation: bool - saveDir, screenshot, prompt, model, selection: string - -proc options(): Options = - ## Reads a small native launcher interface and explicit capture options. - var customSave = false - result = Options( - seed: 42, width: 1440, height: 900, frames: 3, - model: DefaultMonsterModel, - saveDir: getDataDir() / "polyworld" / "monster" - ) - when defined(takeScreenshot): - result.screenshot = absolutePath( - getEnv("SCREENSHOT_PATH", "output/monster.png") - ) - try: - var arguments: seq[string] - for argument in commandLineParams(): - if result.soundMuted.takeSoundFlag(argument): - result.conversation = not result.soundMuted - else: - arguments.add argument - if arguments.len > 0: - for kind, key, value in getopt(arguments): - case kind - of cmdLongOption, cmdShortOption: - case key - of "seed": - result.seed = parseInt(value) - of "width": - result.width = parseInt(value) - of "height": - result.height = parseInt(value) - of "frames": - result.frames = parseInt(value) - of "save-dir": - result.saveDir = absolutePath(value) - customSave = true - of "screenshot": - result.screenshot = absolutePath(value) - of "select": - result.selection = value - of "prompt": - result.prompt = value - of "model": - result.model = value - of "offline": - result.offline = true - of "no-voice": - result.noVoice = true - of "help", "h": - echo "Monster / Polyworld" - echo "Run from the repository: nim r games/monster/monster.nim" - echo "Options: --model:ID --seed:N --save-dir:PATH --offline" - echo "Modes: Text, or Conversation with an OpenAI key." - echo "Conversation listens continuously and supports interruption." - echo "Audio: --no-voice disables Conversation; --unmute starts it." - echo "Hidden capture: --screenshot:PATH [--prompt:TEXT] [--frames:N]" - echo "Inspect a profile on launch: --select:moss or a person/place ID." - echo "Or compile with -d:takeScreenshot (default: output/monster.png)." - echo "Camera: right-drag to pan, wheel to zoom, F to find Moss." - echo "Click or drag the minimap to look around; click Moss to follow." - echo "Left-click a villager, house, or stash to inspect it." - echo "Conversation: Enter to speak, Escape to release focus." - quit(0) - else: - raise newException(MonsterError, "Unknown option: " & key) - of cmdArgument: - raise newException(MonsterError, "Unexpected argument: " & key) - of cmdEnd: - discard - except ValueError as error: - raise newException(MonsterError, "Invalid Monster option: " & error.msg) - if result.width < 640 or result.height < 480 or result.frames < 1: - raise newException(MonsterError, "Use at least 640x480 and one frame.") - if not customSave: - result.saveDir = result.saveDir / $result.seed - when defined(headless): proc runGame(settings: Options) = ## Exercises a real conversation and its complete physical action plan. - if settings.screenshot.len > 0: + if settings.game.capture.captureRequested(): raise newException(MonsterError, "Use --screenshot or -d:takeScreenshot without -d:headless " & "to capture graphics.") @@ -115,7 +35,7 @@ when defined(headless): ) defer: brain.close() - var world = newWorld(generateMap(settings.seed)) + var world = newWorld(generateMap(settings.game.seed.int)) world.restoreWorld(savePath) let started = epochTime() var @@ -160,31 +80,23 @@ else: builder.addFont(DefaultFontPath, "Small", 12, glyphs) builder.addFont(DefaultFontPath, "WorldName", 32, glyphs) - proc capture(window: Window, path: string) = - ## Saves the rendered game frame in a local PNG for visual inspection. - let screenshot = newImage(window.size.x, window.size.y) - glReadPixels( - 0, 0, window.size.x, window.size.y, GL_RGBA, GL_UNSIGNED_BYTE, - screenshot.data[0].addr - ) - screenshot.flipVertical() - createDir(path.parentDir) - screenshot.writeFile(path) - proc runGame(settings: Options) = ## Runs a responsive camera and chat around the fixed creature simulation. let - capturing = settings.screenshot.len > 0 - savePath = settings.saveDir / "world.json" + capturing = captureActive() + worldPath = settings.saveDir / "world.json" + savePath = if capturing: "" else: worldPath atlasPath = RepositoryRoot / "tmp" / "monster.atlas.png" brain = newBrain( settings.saveDir / "conversation.json", settings.model, - not settings.offline + not settings.offline and (not capturing or settings.prompt.len > 0) ) + if capturing: + brain.disableSaving() defer: brain.close() - var world = newWorld(generateMap(settings.seed)) - world.restoreWorld(savePath) + var world = newWorld(generateMap(settings.game.seed.int)) + world.restoreWorld(worldPath) createDir(atlasPath.parentDir) let builder = newHudAtlas(4096) builder.addFonts() @@ -192,14 +104,18 @@ else: builder.write(atlasPath) let (window, sk) = initGameWindow( "Monster / Polyworld", atlasPath, - ivec2(settings.width.int32, settings.height.int32), - vsync = not capturing, + ivec2(settings.game.windowWidth, settings.game.windowHeight), + vsync = settings.game.vsync, visible = not capturing ) sk.builder = builder defer: - world.saveWorld(savePath) + if not capturing: + world.saveWorld(savePath) window.close() + var captureTarget: ScreenshotTarget + defer: + captureTarget.releaseScreenshotTarget() let scene = newMonsterScene( window, world.map, sk.atlas, sk.atlasTextureId() ) @@ -208,7 +124,8 @@ else: let voice = newMonsterVoice( historyCount = brain.messages.len, enabled = not settings.offline and not settings.noVoice and - not capturing and getEnv("COGAME_LLM").toLowerAscii() != "off" + not settings.game.soundMuted and not capturing and + getEnv("COGAME_LLM").toLowerAscii() != "off" ) defer: voice.close() @@ -219,6 +136,7 @@ else: chat = initChatUi() clock: ViewingClock accumulator = 0'f + paused = settings.game.pauseOnStart cameraDistance = CameraDistanceDefault cameraTarget = rtsFollowFrame( vec3(world.creature.position.x, 0, world.creature.position.y), @@ -246,11 +164,17 @@ else: let dt = if capturing: 1'f / 60 else: min(clock.viewingDelta(window), 0.1'f) - accumulator += dt + if not chat.typing and window.buttonPressed[KeySpace]: + paused = not paused + if not paused: + accumulator += dt * settings.game.speed.float32 while accumulator >= 1'f / TickRate.float32: world.step() accumulator -= 1'f / TickRate.float32 discard world.receive(brain) + if settings.game.verbose: + for text in world.events: + echo text world.outcomes(brain, savePath) voice.observe(brain.messages) voice.submitPending(world, brain) @@ -299,6 +223,7 @@ else: cameraDistance, renderTime) if chat.select(world, picked): following = chat.selection.kind == MossSelection + discard captureTarget.beginScreenshotFrame(window) scene.drawScene( window, world, cameraTarget, cameraDistance, renderTime, chat.selection @@ -334,19 +259,22 @@ else: chat.restoreInput(spoken) voice.observe(brain.messages) voice.poll(window.focused) - if epochTime() - lastSave > 10: + if not capturing and epochTime() - lastSave > 10: world.saveWorld(savePath) lastSave = epochTime() - inc frame - if capturing and frame >= settings.frames and - not brain.pending and not brain.explanationPending and - not world.active and world.actions.len == 0: - window.capture(settings.screenshot) - echo "Saved ", settings.screenshot - break + if capturing: + let ready = settings.prompt.len == 0 or + (not brain.pending and not brain.explanationPending and + not world.active and world.actions.len == 0) + if ready: + if window.captureFrame(frame): + break + else: + inc frame if capturing and epochTime() - started > 120: raise newException(MonsterError, "Timed out waiting for capture.") - window.swapBuffers() + if not capturing: + window.swapBuffers() waitForDisplay() proc main() = @@ -354,19 +282,22 @@ proc main() = try: when not defined(headless): restoreMonsterDirectory() - let settings = options() + let settings = parseOptions() when not defined(headless): + configureCapture(settings.game.capture, "output/monster.png") if not settings.offline and not settings.noVoice and - settings.screenshot.len == 0 and + not settings.game.soundMuted and + not captureActive() and getEnv("COGAME_LLM").toLowerAscii() != "off": if launchMonster(): return setCurrentDir(RepositoryRoot) - createDir(settings.saveDir) + if not settings.game.capture.captureRequested(): + createDir(settings.saveDir) runGame(settings) when not defined(headless): finishMonster() - except MonsterError, IOError: + except MonsterError, ScreenshotError, IOError: stderr.writeLine("Monster: " & getCurrentExceptionMsg()) quit(1) diff --git a/games/monster/notes.md b/games/monster/notes.md index c70a50f50..c03502848 100644 --- a/games/monster/notes.md +++ b/games/monster/notes.md @@ -36,8 +36,9 @@ to reconnect. On macOS, the microphone and speaker share Apple's voice processing audio engine for echo cancellation during simultaneous playback and capture. Other platforms currently use the existing Slappy audio path. -Use `--unmute` to start directly in Conversation, `--mute` for Text, or -`--no-voice` to disable Conversation. `OPENAI_REALTIME_MODEL` and +Use `--conversation` to start directly in Conversation. `--mute` disables +voice audio and `--unmute` enables it without starting the microphone. +`--no-voice` disables Conversation. `OPENAI_REALTIME_MODEL` and `OPENAI_REALTIME_VOICE` override the Voice Lab model and creature voice. Voice uses `OPENAI_API_KEY`, falling back to `MONSTER_KEY_FILE` or `~/secrets/openai.key`, including one retry for @@ -46,6 +47,22 @@ simulation do not open voice connections or microphones. On macOS the normal Nim command launches a local Monster app so its microphone permission belongs to the game. +Monster uses Polyworld's common launch options for `--seed N`, +`--windowSize WIDTHxHEIGHT`, `--vsync BOOL`, `--play BOOL`, `--speed N`, +`--mute`, `--unmute`, `--verbose`, `--screenshot PATH`, and `--frames N`. +Valued arguments accept separate, equals, or colon forms. For example, +`--seed 17`, `--seed=17`, and `--seed:17` have the same meaning. +`--play false` starts the simulation paused; Space pauses or resumes it while +the text editor is unfocused. `--speed` changes the graphical simulation rate +while leaving camera and UI movement unchanged. `--verbose` prints world +events to the terminal. +Headless prompt runs reject graphical transport, window, and capture options. + +The same value forms apply to `--model`, `--prompt`, `--select`, and +`--save-dir`. Relative save directories resolve from the launch directory. +Monster has no BASIC bot roster or action replay system, so it rejects +unsupported match flags such as `--bot`, `--player`, `--record`, and `--replay`. + Try this sequence: 1. `Walk to the village.` @@ -240,12 +257,19 @@ nim r -d:headless games/monster/monster.nim \ Capture the rendered game in a hidden window: ```sh -nim r games/monster/monster.nim --screenshot:output/monster.png +nim r games/monster/monster.nim --screenshot output/monster.png \ + --frames 30 --windowSize 1440x900 ``` -Add `--prompt:'Walk to the village.'` to wait for the model and resulting -actions before capture. `--frames:N` sets the minimum rendered frame count. -Use `--save-dir:build/monster-capture` to keep capture progress separate. +These shared screenshot flags also accept `=` and `:` separators. The default +capture is the thirtieth rendered frame. It runs muted in a hidden window, +creates the output directory, and exits without saving world or conversation +changes. Ordinary captures do not send model requests. + +Add `--prompt:'Walk to the village.'` to request a model instruction and wait +for its resulting actions before capture. In that mode, `--frames N` is the +minimum rendered frame count. `--save-dir:PATH` selects which existing world +and conversation to read; capture still leaves those files unchanged. The shared `nim r -d:takeScreenshot games/monster/monster.nim` option also captures in a hidden window, defaulting to `output/monster.png`. Set diff --git a/games/monster/options.nim b/games/monster/options.nim new file mode 100644 index 000000000..1007d733f --- /dev/null +++ b/games/monster/options.nim @@ -0,0 +1,85 @@ +import + std/os, + polyworld/cli, + common, brains + +type Options* = object + game*: GameOptions + offline*, noVoice*, conversation*: bool + saveDir*, prompt*, model*, selection*: string + +proc help() = + ## Describes supported common settings and Monster's conversation options. + echo "Monster / Polyworld" + echo "Run from the repository: nim r games/monster/monster.nim" + echo "Common: --seed N --windowSize WxH --vsync BOOL" + echo " --play BOOL --speed N --mute --unmute --verbose" + echo "Capture: --screenshot PATH --frames N (default 30)" + echo "Options: --model ID --save-dir PATH --offline --select ID" + echo " --prompt TEXT --conversation --no-voice" + echo "Valued options accept separate, equals, or colon values." + echo "Conversation starts the microphone; --unmute only enables sound." + echo "Capture does not save progress or start voice or inference." + echo "Add --prompt TEXT to wait for an explicit model instruction." + echo "Monster has no BASIC bot roster or action replay playback." + echo "Camera: right-drag to pan, wheel to zoom, F to find Moss." + echo "Space pauses or resumes while the text editor is unfocused." + echo "Click or drag the minimap to look around; click Moss to follow." + echo "Left-click a villager, house, or stash to inspect it." + echo "Conversation: Enter to speak, Escape to release focus." + +proc parseOptions*(parameters = commandLineParams()): Options = + ## Reads common launch arguments and Monster's own conversation settings. + var customSave = false + result = Options( + game: GameOptions(seed: 42, windowWidth: 1440, windowHeight: 900, + speed: 1), + model: DefaultMonsterModel, + saveDir: getDataDir() / "polyworld" / "monster" + ) + try: + var index = 0 + while index < parameters.len: + let + argument = parameters[index] + name = splitFlag(argument).name + if result.game.takeCommonFlag(parameters, index, argument): + discard + else: + case name + of "--save-dir": + result.saveDir = absolutePath( + parameters.flagValue(index, argument) + ) + customSave = true + of "--select": + result.selection = parameters.flagValue(index, argument) + of "--prompt": + result.prompt = parameters.flagValue(index, argument) + of "--model": + result.model = parameters.flagValue(index, argument) + of "--offline", "--no-voice", "--conversation": + if argument != name: + raise newException(MonsterError, name & " does not take a value") + case name + of "--offline": result.offline = true + of "--no-voice": result.noVoice = true + else: result.conversation = true + of "--help", "-h": + help() + quit(0) + of "--width", "--height": + raise newException(MonsterError, "Use --windowSize WIDTHxHEIGHT") + else: + raise newException(MonsterError, "Unknown option: " & argument) + inc index + result.game.rejectUnsupportedFlags({SeedFlag, WindowSizeFlag, VsyncFlag, + PlayFlag, SpeedFlag, SoundFlag, VerboseFlag, ScreenshotFlag, FramesFlag}) + result.game.validateGameOptions(0, "") + except ValueError, ScreenshotError: + raise newException(MonsterError, + "Invalid Monster option: " & getCurrentExceptionMsg()) + if result.game.windowWidth < 640 or result.game.windowHeight < 480: + raise newException(MonsterError, "Use at least a 640x480 window.") + if not customSave: + result.saveDir = result.saveDir / $result.game.seed diff --git a/games/monster/tests/test_capture_options.nim b/games/monster/tests/test_capture_options.nim new file mode 100644 index 000000000..8338bb27f --- /dev/null +++ b/games/monster/tests/test_capture_options.nim @@ -0,0 +1,150 @@ +import + std/[os, strutils, tempfiles], + ../[brains, common, options] + +echo "Monster shares screenshot arguments and rejects invalid captures" +block: + let defaults = parseOptions(@[]) + doAssert defaults.game.capture.path.len == 0 + doAssert defaults.game.capture.frames == 30 + doAssert defaults.game.windowWidth == 1440 + doAssert defaults.game.windowHeight == 900 + doAssert defaults.game.seed == 42 + doAssert defaults.game.speed == 1 and defaults.game.vsync + doAssert not defaults.game.pauseOnStart + doAssert not defaults.conversation + +echo "Monster uses shared values for seed, audio and diagnostic output" +for arguments in [ + @["--seed", "17", "--mute", "--verbose"], + @["--seed=17", "--mute=true", "--verbose=true"], + @["--seed:17", "--mute:true", "--verbose:true"] +]: + let settings = parseOptions(arguments) + doAssert settings.game.seed == 17 + doAssert settings.game.soundMuted and settings.game.soundOverride + doAssert settings.game.verbose + doAssert settings.saveDir.endsWith("17") + +when not defined(headless): + echo "Monster uses shared values for graphical transport and display" + for arguments in [ + @["--play", "false", "--speed", "4", "--vsync", "off"], + @["--play=false", "--speed=4", "--vsync=off"], + @["--play:false", "--speed:4", "--vsync:off"] + ]: + let settings = parseOptions(arguments) + doAssert settings.game.pauseOnStart and settings.game.speed == 4 + doAssert not settings.game.vsync +else: + echo "Headless Monster rejects graphical transport and display options" + for arguments in [ + @["--play", "false"], @["--speed", "4"], @["--vsync", "off"], + @["--windowSize", "800x600"], @["--frames", "7"] + ]: + var rejected = false + try: + discard parseOptions(arguments) + except MonsterError: + rejected = true + doAssert rejected, $arguments + +echo "Monster audio flags do not opt into a microphone conversation" +block: + let unmuted = parseOptions(@["--unmute"]) + doAssert not unmuted.game.soundMuted + doAssert unmuted.game.soundOverride + doAssert not unmuted.conversation + let speaking = parseOptions(@["--conversation", "--unmute"]) + doAssert speaking.conversation and not speaking.game.soundMuted + let muted = parseOptions(@["--unmute", "--mute"]) + doAssert muted.game.soundMuted and not muted.conversation + +echo "Monster-specific values use the same three value forms" +for arguments in [ + @["--model", "example:model", "--prompt", "Wait here.", + "--select", "moss", "--save-dir", "profiles/moss"], + @["--model=example:model", "--prompt=Wait here.", "--select=moss", + "--save-dir=profiles/moss"], + @["--model:example:model", "--prompt:Wait here.", "--select:moss", + "--save-dir:profiles/moss"] +]: + let settings = parseOptions(arguments) + doAssert settings.model == "example:model" + doAssert settings.prompt == "Wait here." and settings.selection == "moss" + doAssert settings.saveDir == absolutePath("profiles/moss") + +echo "Monster rejects unsupported match flags and malformed options" +for arguments in [ + @["--bot", "player.bas"], @["--bots", "player.bas:2"], + @["--player"], @["--name", "Moss"], @["--replay", "input.replay"], + @["--record", "output.replay"], @["--ticks", "20"], + @["--server", "ws://localhost:9911/ws"], @["--room", "ABCD"], + @["--headless-tick-rate", "30"], @["--llm-mode", "barrier"], + @["--width", "800"], @["--height", "600"], + @["--model"], @["--prompt", "--offline"], @["--seed=large"], + @["--play=maybe"], @["--conversation=false"] +]: + var rejected = false + try: + discard parseOptions(arguments) + except MonsterError: + rejected = true + doAssert rejected, $arguments + +when not defined(headless) and not defined(emscripten): + for arguments in [ + @["--screenshot", "shot.png", "--frames", "7", + "--windowSize", "800x600"], + @["--screenshot=shot.png", "--frames=7", "--windowSize=800x600"], + @["--screenshot:shot.png", "--frames:7", "--windowSize:800x600"] + ]: + let capture = parseOptions(arguments) + doAssert capture.game.capture.path == "shot.png" + doAssert capture.game.capture.frames == 7 + doAssert capture.game.windowWidth == 800 + doAssert capture.game.windowHeight == 600 + block: + let prompt = parseOptions(@[ + "--screenshot", "shot.png", "--prompt:Wait here." + ]) + doAssert prompt.prompt == "Wait here." +else: + var rejected = false + try: + discard parseOptions(@["--screenshot", "shot.png"]) + except MonsterError: + rejected = true + doAssert rejected + +for arguments in [ + @["--screenshot"], @["--screenshot="], @["--frames", "0"], + @["--frames", "-1"], @["--frames", "later"], + @["--windowSize", "800"], @["--windowSize", "100x100"] +]: + var rejected = false + try: + discard parseOptions(arguments) + except MonsterError: + rejected = true + doAssert rejected + +echo "Monster capture memory is loaded without overwriting saved history" +block: + let + directory = createTempDir("monster-capture-memory-", "") + path = directory / "conversation.json" + defer: removeDir(directory) + let original = newBrain(path, enabled = false) + original.addEvent("Before capture") + original.close() + let + saved = readFile(path) + captured = newBrain(path, enabled = false) + doAssert captured.messages.len == 1 + captured.disableSaving() + captured.addEvent("Temporary capture event") + captured.close() + doAssert readFile(path) == saved + +echo "Monster capture argument and read-only memory checks passed" diff --git a/games/monster/tests/tests.nim b/games/monster/tests/tests.nim index ae6b8ab61..82d870ac7 100644 --- a/games/monster/tests/tests.nim +++ b/games/monster/tests/tests.nim @@ -1,5 +1,6 @@ import test_sim, test_maps, test_brains, test_conversations, test_resources, test_villages, test_attacks, test_needs, test_selections, test_health, - test_violence_save, test_destruction, test_chores, test_economy + test_violence_save, test_destruction, test_chores, test_economy, + test_capture_options echo "Monster tests passed" diff --git a/src/polyworld/bars.nim b/src/polyworld/bars.nim new file mode 100644 index 000000000..c0e151a23 --- /dev/null +++ b/src/polyworld/bars.nim @@ -0,0 +1,68 @@ +## Pixel-aligned geometry for bars with horizontally uniform texture bodies. + +import + std/math, + vmath + +type + BarRect* = object + position*, size*: Vec2 + BarSlice* = object + bounds*: BarRect + sourcePosition*, sourceSize*: Vec2 + +proc barBounds*(position, size: Vec2, scale: float32): BarRect = + ## Aligns a nonempty bar to framebuffer pixels. + if size.x <= 0 or size.y <= 0: + return + let scale = max(scale, 0.001'f) + result.position = vec2(round(position.x * scale), + round(position.y * scale)) / scale + result.size = vec2(round(size.x * scale), round(size.y * scale)) / scale + +proc barFill*(track: BarRect, ratio, scale: float32): BarRect = + ## Insets a positive fill inside a pixel-aligned track. + if ratio <= 0 or track.size.x <= 0 or track.size.y <= 0: + return + let + scale = max(scale, 0.001'f) + width = round(track.size.x * scale).int + height = round(track.size.y * scale).int + if width <= 0 or height <= 0: + return + let + inset = round(min(3.0'f, track.size.y / 6) * scale).int + insetX = min(inset, (width - 1) div 2) + insetY = min(inset, (height - 1) div 2) + innerWidth = width - insetX * 2 + fillWidth = clamp(round(innerWidth.float32 * ratio).int, 1, innerWidth) + result.position = track.position + vec2(insetX.float32, insetY.float32) / scale + result.size = vec2(fillWidth.float32, (height - insetY * 2).float32) / scale + +proc barSlices*(bounds: BarRect, sourceSize: Vec2, + sourceCap, scale: float32): array[3, BarSlice] = + ## Fits fixed texture caps inside pixel-aligned bounds without overlap. + if bounds.size.x <= 0 or bounds.size.y <= 0 or + sourceSize.x <= 0 or sourceSize.y <= 0: + return + let + scale = max(scale, 0.001'f) + width = round(bounds.size.x * scale).int + cap = clamp(sourceCap, 0.0'f, sourceSize.x / 2) + capPixels = min(width div 2, + round(cap * bounds.size.y / sourceSize.y * scale).int) + capWidth = capPixels.float32 / scale + centerWidth = bounds.size.x - capWidth * 2 + offsets = [0.0'f, capWidth, bounds.size.x - capWidth] + widths = [capWidth, centerWidth, capWidth] + # A single texel column avoids atlas mip bleeding when the body is tiny. + sourceOffsets = [0.0'f, floor(sourceSize.x / 2) + 0.5'f, + sourceSize.x - cap] + sourceWidths = [cap, 0.0'f, cap] + for i in 0 ..< result.len: + result[i] = BarSlice( + bounds: BarRect(position: bounds.position + vec2(offsets[i], 0), + size: vec2(widths[i], bounds.size.y)), + sourcePosition: vec2(sourceOffsets[i], 0), + sourceSize: vec2(sourceWidths[i], sourceSize.y) + ) diff --git a/src/polyworld/chrome.nim b/src/polyworld/chrome.nim index 14883acfd..77c784f0f 100644 --- a/src/polyworld/chrome.nim +++ b/src/polyworld/chrome.nim @@ -3,7 +3,7 @@ import std/[math, strutils, tables, times, unicode], bumpy, chroma, pixie, silky, vmath, windy, - daycycles, gameuis, hovers, inputs, profiles, quadterrain, rtscameras, + bars, daycycles, gameuis, hovers, inputs, profiles, quadterrain, rtscameras, networks, sounds export daycycles @@ -22,7 +22,6 @@ const BarFillName = "barfill.9patch" BarTrackPatch = 7 BarFillPatch = 5 - BarInset = 3.0'f32 KeyPipName = "pip.medium" KeyPipSize = 28.0'f32 KeyPipInset = 2.0'f32 @@ -509,10 +508,24 @@ proc fittedLabel*( return result & "..." result = candidate -proc barPatch(size: Vec2, wanted: int): int = - ## Returns a 9-patch border that still fits inside size. - let cap = min(int(size.x / 2), int(size.y / 2)) - min(wanted, max(cap, 1)) +proc drawBarTexture(sk: Silky, name: string, cap: int, bounds: BarRect, + color: ColorRGBX) = + ## Draws proportional end caps and a horizontally uniform center column. + let + uv = sk.atlas.entries[name] + sourceSize = vec2(uv.width.float32, uv.height.float32) + density = + when compiles(uv.pixelScale): + max(uv.pixelScale, 1) + else: + 1 + sourceCap = (cap * max(sk.sliceScale, 1) * density).float32 + for slice in barSlices(bounds, sourceSize, sourceCap, sk.uiScale): + if slice.bounds.size.x <= 0 or slice.bounds.size.y <= 0: + continue + sk.drawQuad(slice.bounds.position, slice.bounds.size, + vec2(uv.x.float32, uv.y.float32) + slice.sourcePosition, + slice.sourceSize, color) proc drawBar*( sk: Silky, @@ -523,40 +536,26 @@ proc drawBar*( color: ColorRGBX ) = ## Draws one compact resource bar with a clamped fill. + let bounds = barBounds(position, size, sk.uiScale) + if bounds.size.x <= 0 or bounds.size.y <= 0: + return let ratio = if maximum <= 0: 0.0'f32 else: clamp(value / maximum, 0.0'f32, 1.0'f32) if BarTrackName in sk.atlas.entries: - sk.draw9Patch( - BarTrackName, - barPatch(size, BarTrackPatch), - position, - size - ) + sk.drawBarTexture(BarTrackName, BarTrackPatch, bounds, + rgbx(255, 255, 255, 255)) else: - sk.drawRect(position, size, BarBack) + sk.drawRect(bounds.position, bounds.size, BarBack) if ratio <= 0: return - let - inset = min(BarInset, size.y / 6.0'f32) - innerPos = position + vec2(inset) - innerSize = vec2( - max(size.x - inset * 2, 1), - max(size.y - inset * 2, 1) - ) - fillSize = vec2(max(innerSize.x * ratio, 1), innerSize.y) + let fill = barFill(bounds, ratio, sk.uiScale) if BarFillName in sk.atlas.entries: - sk.draw9Patch( - BarFillName, - barPatch(fillSize, BarFillPatch), - innerPos, - fillSize, - color - ) + sk.drawBarTexture(BarFillName, BarFillPatch, fill, color) else: - sk.drawRect(innerPos, fillSize, color) + sk.drawRect(fill.position, fill.size, color) proc drawSprite*( sk: Silky, diff --git a/src/polyworld/cli.nim b/src/polyworld/cli.nim index 9a852424b..5674d2ec7 100644 --- a/src/polyworld/cli.nim +++ b/src/polyworld/cli.nim @@ -1,34 +1,45 @@ -## Shared command-line parsing for Polyworld games. -## -## Every game understands `--bot`, `--player`, `--replay`, `--record`, -## `--seed`, `--play`, `--speed`, `--windowSize`, `--vsync`, `--seconds`, -## `--minutes`, `--ticks`, `--mute`, and `--unmute`. Duration flags all write -## `maximumTicks`; audio uses saved levels unless explicitly overridden. -## Each game runs its own argument loop, farms those flags through -## `takeCommonFlag`, and handles the rest itself. +## Shared launch options for native Polyworld games. +## Games delegate common arguments here and reject unsupported capabilities. import - std/strutils, - configs + std/[os, strutils], + configs, screenshots -export configs +from std/unicode import validateUtf8 + +export configs, screenshots type + CliError* = object of ValueError + + CommonFlag* = enum + BotFlag, PlayerFlag, NameFlag, ReplayFlag, RecordFlag, SeedFlag, + PlayFlag, SpeedFlag, WindowSizeFlag, VsyncFlag, SecondsFlag, + MinutesFlag, TicksFlag, SoundFlag, VerboseFlag, HeadlessTickRateFlag, + LlmModeFlag, ScreenshotFlag, FramesFlag, ServerFlag, RoomFlag + BotGroup* = object path*: string count*: int GameOptions* = object + specifiedFlags*: set[CommonFlag] + capture*: ScreenshotOptions botGroups*: seq[BotGroup] replayPath*: string recordPath*: string + playerName*: string + ## Display name, separate from the controlled player slot. + serverUrl*: string + roomCode*: string seed*: int32 + tickRate*: int32 = SharedTickRate + ## Simulation ticks per second, configured by the game, not the command line. seconds*: int32 ## Duration in seconds, kept in sync with `maximumTicks`. maximumTicks*: int32 - ## Match length in simulation ticks. `--seconds`, `--minutes`, and - ## `--ticks` all write this field. - speed*: int32 + ## Match length in simulation ticks, set by all three duration flags. + speed*: int32 = 1 ## Graphical simulation speed multiplier. verbose*: bool viewMode*: int32 @@ -41,7 +52,6 @@ type windowHeight*: int32 ## Graphical window height. Zero keeps the shared default. vsync*: bool = true - ## Graphical window waits for the display when true. soundMuted*: bool ## Explicit launch mute choice, applied only when soundOverride is set. soundOverride*: bool @@ -53,70 +63,133 @@ type waitForLlm*: bool ## Waits for the whole tick's LLM request batch before advancing. +const + AllCommonFlags* = {low(CommonFlag) .. high(CommonFlag)} + DurationFlags* = {SecondsFlag, MinutesFlag, TicksFlag} + GraphicalFlags* = { + PlayerFlag, NameFlag, PlayFlag, SpeedFlag, WindowSizeFlag, VsyncFlag, + ScreenshotFlag, FramesFlag + } + CommonNames: array[CommonFlag, string] = [ + "--bot", "--player", "--name", "--replay", "--record", "--seed", + "--play", "--speed", "--windowSize", "--vsync", "--seconds", + "--minutes", "--ticks", "--mute", "--verbose", "--headless-tick-rate", + "--llm-mode", "--screenshot", "--frames", "--server", "--room" + ] + CommonHelp: array[CommonFlag, string] = [ + " --bot PATH[:N] Add N bots from a program; repeatable (--bots also works).", + " --player [N] Control slot N, one-based; bare --player selects slot 1.", + " --name TEXT Set the human player's display name.", + " --replay PATH Load a recorded match instead of running bots.", + " --record PATH Save this match's replay to PATH.", + " --seed N Set the signed 32-bit random seed.", + " --play [BOOL] Start playing or paused (default true).", + " --speed N Set the positive integer playback speed (default 1).", + " --windowSize WxH Set the graphical window dimensions.", + " --vsync [BOOL] Wait for the display refresh (default true).", + " --seconds N Limit the match to N simulation seconds.", + " --minutes N Limit the match to N simulation minutes.", + " --ticks N Limit the match to N simulation ticks.", + " --mute [BOOL] Mute launch audio; --unmute restores sound.", + " --verbose [BOOL] Enable verbose output (default false).", + " --headless-tick-rate N Pace headless ticks per second; 0 is unlimited.", + " --llm-mode MODE Use async or barrier LLM requests (default async).", + " --screenshot PATH Save one native screenshot and exit.", + " --frames N Capture the Nth rendered frame (default 30).", + " --server URL Set the multiplayer relay address.", + " --room CODE Select a multiplayer room (--join also works)." + ] + +func commonUsageFor*(supported: set[CommonFlag]): string = + ## Lists the shared syntax for the capabilities implemented by one game. + for flag in CommonFlag: + if flag in supported: + result.add CommonHelp[flag] & "\n" + result.add "Values accept --flag VALUE, --flag=VALUE, or --flag:VALUE.\n" + +const CommonUsage* = commonUsageFor(AllCommonFlags) + proc fail*(message: string) {.noreturn.} = - ## Prints one command-line error and exits. + ## Prints one command-line error and exits at a game launcher boundary. quit(message) +proc cliFail(message: string) {.noreturn.} = + ## Raises one catchable argument error without terminating an embedding process. + raise newException(CliError, message) + +proc splitFlag*(argument: string): tuple[name, value: string, attached: bool] = + ## Splits the first attached-value separator without splitting path contents. + let separator = argument.find({'=', ':'}) + if separator < 0: + return (argument, "", false) + (argument[0 ..< separator], argument[separator + 1 .. ^1], true) + proc argumentValue*( - arguments: seq[string], - index: var int, - name: string + arguments: openArray[string], index: var int, name: string ): string = - ## Consumes and returns the required value after one flag. + ## Consumes a required separate value without consuming another option. + if index + 1 >= arguments.len or arguments[index + 1].startsWith("--") or + arguments[index + 1].len == 0: + cliFail(name & " requires a value") inc index - if index >= arguments.len: - fail(name & " requires a value") arguments[index] +proc flagValue*( + arguments: openArray[string], index: var int, argument: string +): string = + ## Reads a required value in separate, equals, or colon form. + let flag = splitFlag(argument) + if not flag.attached: + return arguments.argumentValue(index, flag.name) + if flag.value.len == 0: + cliFail(flag.name & " requires a value") + flag.value + proc parseInt32*(text, name: string): int32 = ## Parses one signed 32-bit integer flag value. var value: int64 try: value = parseBiggestInt(text) except ValueError: - fail(name & " must be an integer") + cliFail(name & " must be an integer") if value < int32.low or value > int32.high: - fail(name & " must fit int32") + cliFail(name & " must fit int32") int32(value) proc parsePositiveInt32*(text, name: string): int32 = ## Parses one integer flag value that must be greater than zero. result = parseInt32(text, name) if result <= 0: - fail(name & " must be positive") + cliFail(name & " must be positive") proc addBotSpec*(groups: var seq[BotGroup], specification: string) = - ## Parses one bot path with an optional trailing instance count. + ## Parses one program path with an optional positive instance count. if specification.len == 0: - fail("--bot requires a path") + cliFail("--bot requires a path") var path = specification count = 1 - let separator = specification.rfind(':') - if separator >= 0 and separator < specification.high: - let suffix = specification[separator + 1 .. ^1] - var numeric = true - for character in suffix: - if character notin {'0' .. '9'}: - numeric = false - break - if numeric: - path = specification[0 ..< separator] - count = parseInt(suffix) + let + separator = specification.rfind(':') + driveColon = separator == 1 and specification[0] in {'a' .. 'z', 'A' .. 'Z'} + if separator >= 0 and not driveColon: + path = specification[0 ..< separator] + count = parsePositiveInt32( + specification[separator + 1 .. ^1], "--bot count" + ).int if path.len == 0: - fail("--bot requires a path") - if count <= 0: - fail("--bot count must be positive") + cliFail("--bot requires a path") groups.add BotGroup(path: path, count: count) proc botCount*(groups: openArray[BotGroup]): int = - ## Returns the expanded number of configured bot instances. + ## Counts configured instances while rejecting invalid or overflowing totals. for group in groups: + if group.count <= 0 or group.count > int32.high - result: + cliFail("--bot count must total between 1 and " & $int32.high) result += group.count proc botSources*( - groups: openArray[BotGroup], - count: static int + groups: openArray[BotGroup], count: static int ): array[count, string] = ## Loads and expands bot files into one source string per slot. var slot = 0 @@ -124,274 +197,238 @@ proc botSources*( let source = readFile(group.path) for _ in 0 ..< group.count: if slot >= count: - fail("too many bots to expand") + cliFail("too many bots to expand") result[slot] = source inc slot if slot != count: - fail("bot files do not fill every slot") + cliFail("bot files do not fill every slot") proc parseWindowSize*(text, name: string): (int32, int32) = - ## Parses one `WIDTHxHEIGHT` window size, such as `800x400`. + ## Parses one positive `WIDTHxHEIGHT` window size. let separator = text.find({'x', 'X'}) if separator <= 0 or separator >= text.high: - fail(name & " must look like 800x400") + cliFail(name & " must look like 800x400") ( parsePositiveInt32(text[0 ..< separator], name), parsePositiveInt32(text[separator + 1 .. ^1], name) ) -proc ticksFromCount(count, scale: int32, name: string): int32 = - ## Converts a positive count into ticks without overflowing int32. - let ticks = int64(count) * int64(scale) - if ticks > int32.high: - fail(name & " is too large") - int32(ticks) +proc simulationTickRate(options: GameOptions): int32 = + ## Uses the game's configured rate, including zero-initialized nested options. + if options.tickRate < 0: + cliFail("simulation tick rate must be positive") + if options.tickRate == 0: SharedTickRate else: options.tickRate + +proc ticksFromCount(count: int32, scale: int64, name: string): int32 = + ## Converts a positive count into ticks without overflowing the stored range. + if scale <= 0 or count.int64 > int32.high.int64 div scale: + cliFail(name & " is too large") + int32(count.int64 * scale) proc setMaximumTicks*(options: var GameOptions, ticks: int32) = - ## Writes the canonical tick duration and the derived second count. + ## Writes the canonical duration using this game's simulation tick rate. options.maximumTicks = ticks - options.seconds = ticks div SharedTickRate + options.seconds = ticks div options.simulationTickRate() -proc takeDurationFlag( - options: var GameOptions, - arguments: seq[string], - index: var int, - argument: string -): bool = - ## Handles `--seconds`, `--minutes`, and `--ticks`. - var - name = "" - text = "" - if argument.startsWith("--seconds="): - name = "--seconds" - text = argument[10 .. ^1] - elif argument.startsWith("--minutes="): - name = "--minutes" - text = argument[10 .. ^1] - elif argument.startsWith("--ticks="): - name = "--ticks" - text = argument[8 .. ^1] - else: - case argument - of "--seconds", "--minutes", "--ticks": - name = argument - text = arguments.argumentValue(index, argument) - else: - return false - let count = parsePositiveInt32(text, name) - case name - of "--seconds": - options.setMaximumTicks(ticksFromCount(count, SharedTickRate, name)) - of "--minutes": - options.setMaximumTicks( - ticksFromCount(count, 60 * SharedTickRate, name) - ) - of "--ticks": - options.setMaximumTicks(count) - else: - return false - true - -proc takePlayerFlag(options: var GameOptions, argument: string): bool = - ## Handles `--player`, `--player:N`, and `--player=N`. - var text = "" - if argument == "--player": - text = "1" - elif argument.startsWith("--player:"): - text = argument[9 .. ^1] - elif argument.startsWith("--player="): - text = argument[9 .. ^1] - else: - return false - if options.playerSlot != 0: - fail("only one --player allowed") - if text.len == 0: - fail("--player requires a slot") - options.playerSlot = parsePositiveInt32(text, "--player") - true - -proc parsePlayFlag(text: string): bool = - ## Parses `--play` as a boolean. +proc parseBoolean(text, name: string): bool = + ## Parses the same explicit boolean vocabulary for every common switch. case text.strip().toLowerAscii() - of "true", "1", "yes", "on": - result = true - of "false", "0", "no", "off": - result = false - else: - fail("--play must be true or false") + of "true", "1", "yes", "on": true + of "false", "0", "no", "off": false + else: cliFail(name & " must be true or false") -proc parseVsyncFlag(text: string): bool = - ## Parses `--vsync` as on or off. - case text.strip().toLowerAscii() - of "true", "1", "yes", "on": - result = true - of "false", "0", "no", "off": - result = false - else: - fail("--vsync must be on or off") +proc optionalValue( + arguments: openArray[string], index: var int, argument, fallback: string +): string = + ## Reads an optional value while leaving the next option for its own parser. + let flag = splitFlag(argument) + if flag.attached: + return arguments.flagValue(index, argument) + if index + 1 < arguments.len and not arguments[index + 1].startsWith("--"): + return arguments.argumentValue(index, flag.name) + fallback proc takeSoundFlag*(soundMuted: var bool, argument: string): bool = - ## Reads one launch-only mute flag without consuming unrelated arguments. - case argument - of "--mute": - soundMuted = true - of "--unmute": - soundMuted = false - else: - if not argument.startsWith("--mute=") and - not argument.startsWith("--mute:"): - return false - case argument[7 .. ^1].strip().toLowerAscii() - of "true", "1", "yes", "on": - soundMuted = true - of "false", "0", "no", "off": - soundMuted = false - else: - raise newException(ValueError, "--mute must be true or false") + ## Reads a standalone audio flag for callers that do not own an argument loop. + let flag = splitFlag(argument) + if flag.name notin ["--mute", "--unmute"]: + return false + let enabled = + if flag.attached: parseBoolean(flag.value, flag.name) + else: true + soundMuted = if flag.name == "--mute": enabled else: not enabled true proc takeCommonFlag*( - options: var GameOptions, - arguments: seq[string], - index: var int, - argument: string + options: var GameOptions, arguments: openArray[string], + index: var int, argument: string ): bool = - ## Handles one shared flag. Returns false when the game should try it. + ## Handles one common flag and records its capability without consuming unknowns. try: - if options.soundMuted.takeSoundFlag(argument): - options.soundOverride = true - return true - except ValueError as error: - fail(error.msg) - if argument.startsWith("--headless-tick-rate:") or - argument.startsWith("--headless-tick-rate=") or - argument == "--headless-tick-rate": - let text = - if argument == "--headless-tick-rate": - arguments.argumentValue(index, argument) - else: - argument[21 .. ^1] - options.headlessTickRate = parseInt32(text, "--headless-tick-rate") - if options.headlessTickRate < 0 or options.headlessTickRate > 10000: - fail("--headless-tick-rate must be 0 .. 10000") + if options.capture.takeCaptureFlag(arguments, index, argument): + let flag = splitFlag(argument).name + options.specifiedFlags.incl( + if flag == "--frames": FramesFlag else: ScreenshotFlag + ) return true - if argument.startsWith("--llm-mode:") or - argument.startsWith("--llm-mode=") or argument == "--llm-mode": - let text = - if argument == "--llm-mode": - arguments.argumentValue(index, argument) - else: - argument[11 .. ^1] - case text.toLowerAscii() - of "async": options.waitForLlm = false - of "barrier": options.waitForLlm = true - else: fail("--llm-mode must be async or barrier") + if takeWindowSizeFlag( + options.windowWidth, options.windowHeight, arguments, index, argument + ): + options.specifiedFlags.incl WindowSizeFlag return true - if argument.startsWith("--bot:"): - options.botGroups.addBotSpec(argument[6 .. ^1]) - return true - if argument.startsWith("--play="): - options.pauseOnStart = not parsePlayFlag(argument[7 .. ^1]) - return true - if argument.startsWith("--speed="): - options.speed = parsePositiveInt32(argument[8 .. ^1], "--speed") - return true - if argument.startsWith("--windowSize:"): - (options.windowWidth, options.windowHeight) = - parseWindowSize(argument[13 .. ^1], "--windowSize") - return true - if argument.startsWith("--windowSize="): - (options.windowWidth, options.windowHeight) = - parseWindowSize(argument[13 .. ^1], "--windowSize") - return true - if argument.startsWith("--vsync:"): - options.vsync = parseVsyncFlag(argument[8 .. ^1]) - return true - if argument.startsWith("--vsync="): - options.vsync = parseVsyncFlag(argument[8 .. ^1]) - return true - if options.takeDurationFlag(arguments, index, argument): - return true - if options.takePlayerFlag(argument): - return true - case argument + except ScreenshotError as error: + cliFail(error.msg) + let flag = splitFlag(argument) + template value(): string = + ## Reads the current required argument at its original position. + arguments.flagValue(index, argument) + template optional(fallback: string): string = + ## Reads the current optional argument without consuming the next option. + arguments.optionalValue(index, argument, fallback) + case flag.name of "--": - result = true - of "--bot": - options.botGroups.addBotSpec( - arguments.argumentValue(index, "--bot") - ) - result = true + return not flag.attached + of "--bot", "--bots": + options.botGroups.addBotSpec(value()) + options.specifiedFlags.incl BotFlag + of "--player": + if PlayerFlag in options.specifiedFlags: + cliFail("only one --player allowed") + let text = optional("1") + try: + options.playerSlot = parsePositiveInt32(text, "--player") + except CliError: + cliFail("--player requires a positive slot number; " & + "use --name for a display name") + options.specifiedFlags.incl PlayerFlag + of "--name": + let raw = value() + if validateUtf8(raw) >= 0: + cliFail("--name must contain valid UTF-8") + for character in raw: + if character < ' ' or character == '\x7f': + cliFail("--name cannot contain control characters") + let name = raw.strip() + if name.len == 0 or name.len > 64: + cliFail("--name requires a nonempty display name of at most 64 bytes") + options.playerName = name + options.specifiedFlags.incl NameFlag of "--replay": - options.replayPath = arguments.argumentValue(index, "--replay") - result = true + options.replayPath = value() + options.specifiedFlags.incl ReplayFlag of "--record": - options.recordPath = arguments.argumentValue(index, "--record") - result = true + options.recordPath = value() + options.specifiedFlags.incl RecordFlag of "--seed": - options.seed = parseInt32( - arguments.argumentValue(index, "--seed"), - "--seed" - ) - result = true + options.seed = parseInt32(value(), flag.name) + options.specifiedFlags.incl SeedFlag of "--play": - options.pauseOnStart = not parsePlayFlag( - arguments.argumentValue(index, "--play") - ) - result = true + options.pauseOnStart = not parseBoolean(optional("true"), flag.name) + options.specifiedFlags.incl PlayFlag of "--speed": - options.speed = parsePositiveInt32( - arguments.argumentValue(index, "--speed"), - "--speed" - ) - result = true - of "--windowSize": - (options.windowWidth, options.windowHeight) = - parseWindowSize( - arguments.argumentValue(index, "--windowSize"), - "--windowSize" - ) - result = true + options.speed = parsePositiveInt32(value(), flag.name) + options.specifiedFlags.incl SpeedFlag of "--vsync": - options.vsync = parseVsyncFlag( - arguments.argumentValue(index, "--vsync") - ) - result = true + options.vsync = parseBoolean(optional("true"), flag.name) + options.specifiedFlags.incl VsyncFlag + of "--seconds", "--minutes", "--ticks": + let count = parsePositiveInt32(value(), flag.name) + case flag.name + of "--seconds": + options.setMaximumTicks(ticksFromCount( + count, options.simulationTickRate(), flag.name + )) + options.specifiedFlags.incl SecondsFlag + of "--minutes": + options.setMaximumTicks(ticksFromCount( + count, 60'i64 * options.simulationTickRate(), flag.name + )) + options.specifiedFlags.incl MinutesFlag + else: + options.setMaximumTicks(count) + options.specifiedFlags.incl TicksFlag + of "--mute", "--unmute": + let enabled = parseBoolean(optional("true"), flag.name) + options.soundMuted = if flag.name == "--mute": enabled else: not enabled + options.soundOverride = true + options.specifiedFlags.incl SoundFlag + of "--verbose": + options.verbose = parseBoolean(optional("true"), flag.name) + options.specifiedFlags.incl VerboseFlag + of "--headless-tick-rate": + let rate = parseInt32(value(), flag.name) + if rate < 0 or rate > 10000: + cliFail("--headless-tick-rate must be 0 .. 10000") + options.headlessTickRate = rate + options.specifiedFlags.incl HeadlessTickRateFlag + of "--llm-mode": + case value().toLowerAscii() + of "async": options.waitForLlm = false + of "barrier": options.waitForLlm = true + else: cliFail("--llm-mode must be async or barrier") + options.specifiedFlags.incl LlmModeFlag + of "--server": + options.serverUrl = value() + options.specifiedFlags.incl ServerFlag + of "--room", "--join": + options.roomCode = value() + options.specifiedFlags.incl RoomFlag else: - result = false + return false + true + +proc rejectUnsupportedFlags*( + options: GameOptions, supported: set[CommonFlag] +) = + ## Rejects explicit unsupported requests, including false and zero-valued flags. + for flag in options.specifiedFlags - supported: + cliFail(CommonNames[flag] & " is not supported by this game") + +proc resolveGamePaths*(options: var GameOptions) = + ## Resolves launch paths before a game changes its working directory. + if options.replayPath.len > 0: + options.replayPath = absolutePath(options.replayPath) + if options.recordPath.len > 0: + options.recordPath = absolutePath(options.recordPath) + for group in options.botGroups.mitems: + group.path = absolutePath(group.path) + +proc validateHeadlessOptions*(options: GameOptions) = + ## Rejects visual controls in compiled or runtime headless launch modes. + if options.playerSlot != 0: + cliFail("--player requires the graphical client") + for flag in options.specifiedFlags * GraphicalFlags: + cliFail(CommonNames[flag] & " requires the graphical client") proc validateGameOptions*( - options: GameOptions, - liveSlotCount: int, - liveBotMessage: string + options: GameOptions, liveSlotCount = 0, liveBotMessage = "" ) = - ## Checks replay exclusivity and the live-game bot count. + ## Checks replay exclusivity, graphical human control, and the live-game roster. + try: + options.capture.validateCapture() + except ScreenshotError as error: + cliFail(error.msg) when defined(headless): - if options.playerSlot != 0: - fail("--player requires the graphical client") + options.validateHeadlessOptions() + discard options.botGroups.botCount if options.replayPath.len > 0: if options.botGroups.len > 0: - fail("--replay cannot be used with --bot") + cliFail("--replay cannot be used with --bot") if options.playerSlot != 0: - fail("--replay cannot be used with --player") + cliFail("--replay cannot be used with --player") if options.recordPath.len > 0: - fail("--replay cannot be recorded again") + cliFail("--replay cannot be recorded again") + for flag in options.specifiedFlags * (DurationFlags + {SeedFlag}): + cliFail("--replay cannot be used with " & CommonNames[flag]) elif liveSlotCount > 0: if options.playerSlot != 0 and - (options.playerSlot < 1 or - options.playerSlot > liveSlotCount): - fail("--player must be between 1 and " & $liveSlotCount) + (options.playerSlot < 1 or options.playerSlot > liveSlotCount): + cliFail("--player must be between 1 and " & $liveSlotCount) let - needed = - if options.playerSlot != 0: - liveSlotCount - 1 - else: - liveSlotCount + needed = if options.playerSlot != 0: liveSlotCount - 1 else: liveSlotCount count = options.botGroups.botCount if count != needed: if options.playerSlot != 0: - fail( - "live games with --player require " & $needed & - " bots; configured " & $count - ) - fail(liveBotMessage & "; configured " & $count) + cliFail("live games with --player require " & $needed & + " bots; configured " & $count) + cliFail(liveBotMessage & "; configured " & $count) diff --git a/src/polyworld/controllers.nim b/src/polyworld/controllers.nim index ee0971758..7f9a620f5 100644 --- a/src/polyworld/controllers.nim +++ b/src/polyworld/controllers.nim @@ -32,7 +32,7 @@ proc isPlayerIndex*(playerSlot: int32, index: int): bool = playerSlot > 0 and index == playerSlot - 1 proc localGameConfig*(options: GameOptions, slotCount: int): GameConfig = - ## Builds the match config with names derived only from local bot files. + ## Builds the match config with bot filenames and the requested human name. let kinds = controllerKinds(slotCount, options.playerSlot) result = GameConfig( seed: options.seed, @@ -43,6 +43,8 @@ proc localGameConfig*(options: GameOptions, slotCount: int): GameConfig = waitForLlm: options.waitForLlm, players: unnamedPlayers(slotCount) ) + if options.playerSlot > 0 and options.playerName.len > 0: + result.players[options.playerSlot - 1].name = options.playerName var next = 0 for group in options.botGroups: let name = group.path[group.path.rfind({'/', '\\'}) + 1 .. ^1] diff --git a/src/polyworld/distortions.nim b/src/polyworld/distortions.nim new file mode 100644 index 000000000..0dccb5f4c --- /dev/null +++ b/src/polyworld/distortions.nim @@ -0,0 +1,321 @@ +## Screen-space distortion: explosion shockwaves, heat haze and shield bubbles +## that bend what is behind them, like the distortion pass in Recoil (Spring) +## games. +## +## It works on what the window already shows. One blit copies the finished +## scene, multisampled or not, into a texture. Each distortion is then a quad +## facing the camera that re-draws that copy shifted a few pixels: +## +## - `ShockwaveDistortion`: a ring that races from the center to the edge and +## pushes the picture outward as it passes, fading as it grows. +## - `HeatDistortion`: rippling haze that rises and drifts, fading out. +## - `ShieldDistortion`: a bubble that magnifies the middle and bends hard at +## its rim. +## +## Call `drawDistortions` after the world and its particles and before the HUD. +## Quads are depth tested without writing depth, pulled toward the camera by +## their radius, so hills and walls hide distortions behind them. + +import + std/strutils, + opengl, vmath + +type + DistortionKind* = enum + ShockwaveDistortion, HeatDistortion, ShieldDistortion + + Distortion* = object + kind*: DistortionKind + center*: Vec3 ## World position. + radius*: float32 ## World units out to the edge of the effect. + strength*: float32 + ## Peak shift as a share of the effect's radius on screen: 0.05 is gentle. + age*, life*: float32 ## Seconds; the distortion is gone once age reaches life. + seed*: float32 ## Varies heat ripples between sources. + + DistortionRenderer* = object + program, vertexArray, vertexBuffer: GLuint + copyFramebuffer, copyTexture: GLuint + size: IVec2 + ready, unavailable, copyChecked: bool + floats: seq[float32] + viewMatrix, sceneSampler, viewportSize, clock: GLint + + SavedState = object + viewport: array[4, GLint] + depthTest, cullFace, blend: GLboolean + depthMask: GLboolean + blendFuncs: array[4, GLint] + program, vertexArray, activeTexture, texture0: GLint + readFramebuffer, drawFramebuffer, arrayBuffer: GLint + +const + VertexFloats = 9 ## Position 3, corner 2, kind, progress, shift pixels, seed. + + VertexSource = """ +uniform mat4 viewMatrix; +in vec3 position; +in vec2 corner; +in vec4 params; +out vec2 local; +out vec4 shape; +void main() { + local = corner; + shape = params; + gl_Position = viewMatrix * vec4(position, 1.0); +} +""" + + FragmentSource = """ +uniform sampler2D scene; +uniform vec2 viewportSize; +uniform float clock; +in vec2 local; +in vec4 shape; +out vec4 color; +void main() { + float d = length(local); + if (d >= 1.0) discard; + vec2 outward = d > 0.0001 ? local / d : vec2(0.0); + int kind = int(shape.x + 0.5); + float progress = clamp(shape.y, 0.0, 1.0); + float pixels = shape.z; + float seed = shape.w; + vec2 shift = vec2(0.0); + float mask = 0.0; + if (kind == 0) { + // A ring racing outward, pushing the picture away from the center. + float ring = exp(-pow((d - progress) / 0.13, 2.0)); + float fade = 1.0 - progress; + shift = outward * ring * fade; + mask = clamp(ring * fade * 2.0, 0.0, 1.0); + } else if (kind == 1) { + // Rising ripples, strongest in the middle, swelling in then fading out. + float fade = (1.0 - d) * (1.0 - progress) * min(1.0, progress * 6.0); + vec2 p = local * 3.5 + vec2(seed, seed * 1.7); + float rise = clock * 3.0; + shift = vec2(sin(p.y * 4.0 - rise + sin(p.x * 3.1 + seed)), + cos(p.x * 4.7 + rise * 0.8 + p.y * 1.3)) * fade * 0.5; + mask = clamp(fade * 3.0, 0.0, 1.0); + } else { + // A bubble: magnifies its middle and bends hard at its rim. + float rim = pow(d, 8.0); + shift = -outward * (d * (1.0 - d) * 0.6 + rim * 0.8); + mask = 1.0 - smoothstep(0.92, 1.0, d); + } + vec2 uv = gl_FragCoord.xy / viewportSize + shift * pixels / viewportSize; + color = vec4(texture(scene, uv).rgb, mask); +} +""" + +proc shaderHeader(): string = + when defined(emscripten): + "#version 300 es\nprecision highp float;\n" + else: + "#version 410 core\n" + +proc compileStage(kind: GLenum, source: string): GLuint = + result = glCreateShader(kind) + let text = allocCStringArray([shaderHeader() & source]) + defer: deallocCStringArray(text) + glShaderSource(result, 1, text, nil) + glCompileShader(result) + var status: GLint + glGetShaderiv(result, GL_COMPILE_STATUS, status.addr) + if status == 0: + var length: GLint + glGetShaderiv(result, GL_INFO_LOG_LENGTH, length.addr) + var log = newString(max(1, length)) + glGetShaderInfoLog(result, length, nil, log.cstring) + raise newException(ValueError, "Distortion shader failed:\n" & log) + +proc setup(renderer: var DistortionRenderer) = + ## Builds the program and buffers on first use, with a GL context current. + let + vertex = compileStage(GL_VERTEX_SHADER, VertexSource) + fragment = compileStage(GL_FRAGMENT_SHADER, FragmentSource) + renderer.program = glCreateProgram() + glAttachShader(renderer.program, vertex) + glAttachShader(renderer.program, fragment) + glLinkProgram(renderer.program) + glDeleteShader(vertex) + glDeleteShader(fragment) + var linked: GLint + glGetProgramiv(renderer.program, GL_LINK_STATUS, linked.addr) + if linked == 0: + raise newException(ValueError, "Distortion program did not link") + renderer.viewMatrix = glGetUniformLocation(renderer.program, "viewMatrix") + renderer.sceneSampler = glGetUniformLocation(renderer.program, "scene") + renderer.viewportSize = glGetUniformLocation(renderer.program, "viewportSize") + renderer.clock = glGetUniformLocation(renderer.program, "clock") + glGenVertexArrays(1, renderer.vertexArray.addr) + glBindVertexArray(renderer.vertexArray) + glGenBuffers(1, renderer.vertexBuffer.addr) + glBindBuffer(GL_ARRAY_BUFFER, renderer.vertexBuffer) + const stride = (VertexFloats * sizeof(float32)).GLsizei + for (name, count, offset) in [("position", 3, 0), ("corner", 2, 3), ("params", 4, 5)]: + let location = glGetAttribLocation(renderer.program, name.cstring) + if location < 0: continue + glEnableVertexAttribArray(location.GLuint) + glVertexAttribPointer(location.GLuint, count.GLint, cGL_FLOAT, GL_FALSE, stride, + cast[pointer](offset * sizeof(float32))) + glBindVertexArray(0) + glGenFramebuffers(1, renderer.copyFramebuffer.addr) + glGenTextures(1, renderer.copyTexture.addr) + renderer.ready = true + +proc ensureSize(renderer: var DistortionRenderer, size: IVec2) = + ## Matches the scene copy to the window. + if size == renderer.size: return + renderer.size = size + renderer.copyChecked = false + glBindTexture(GL_TEXTURE_2D, renderer.copyTexture) + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8.GLint, size.x, size.y, 0, + GL_RGBA, GL_UNSIGNED_BYTE, nil) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR.GLint) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR.GLint) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE.GLint) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE.GLint) + glBindFramebuffer(GL_FRAMEBUFFER, renderer.copyFramebuffer) + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + renderer.copyTexture, 0) + +proc saveState(): SavedState = + glGetIntegerv(GL_VIEWPORT, result.viewport[0].addr) + result.depthTest = glIsEnabled(GL_DEPTH_TEST) + result.cullFace = glIsEnabled(GL_CULL_FACE) + result.blend = glIsEnabled(GL_BLEND) + glGetBooleanv(GL_DEPTH_WRITEMASK, result.depthMask.addr) + glGetIntegerv(GL_BLEND_SRC_RGB, result.blendFuncs[0].addr) + glGetIntegerv(GL_BLEND_DST_RGB, result.blendFuncs[1].addr) + glGetIntegerv(GL_BLEND_SRC_ALPHA, result.blendFuncs[2].addr) + glGetIntegerv(GL_BLEND_DST_ALPHA, result.blendFuncs[3].addr) + glGetIntegerv(GL_CURRENT_PROGRAM, result.program.addr) + glGetIntegerv(GL_VERTEX_ARRAY_BINDING, result.vertexArray.addr) + glGetIntegerv(GL_ARRAY_BUFFER_BINDING, result.arrayBuffer.addr) + glGetIntegerv(GL_ACTIVE_TEXTURE, result.activeTexture.addr) + glActiveTexture(GL_TEXTURE0) + glGetIntegerv(GL_TEXTURE_BINDING_2D, result.texture0.addr) + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, result.readFramebuffer.addr) + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, result.drawFramebuffer.addr) + +proc setEnabled(capability: GLenum, enabled: GLboolean) = + if enabled: glEnable(capability) else: glDisable(capability) + +proc restore(state: SavedState) = + glViewport(state.viewport[0], state.viewport[1], + state.viewport[2].GLsizei, state.viewport[3].GLsizei) + setEnabled(GL_DEPTH_TEST, state.depthTest) + setEnabled(GL_CULL_FACE, state.cullFace) + setEnabled(GL_BLEND, state.blend) + glDepthMask(state.depthMask) + glBlendFuncSeparate(state.blendFuncs[0].GLenum, state.blendFuncs[1].GLenum, + state.blendFuncs[2].GLenum, state.blendFuncs[3].GLenum) + glUseProgram(state.program.GLuint) + glBindVertexArray(state.vertexArray.GLuint) + glBindBuffer(GL_ARRAY_BUFFER, state.arrayBuffer.GLuint) + glActiveTexture(GL_TEXTURE0) + glBindTexture(GL_TEXTURE_2D, state.texture0.GLuint) + glActiveTexture(state.activeTexture.GLenum) + glBindFramebuffer(GL_READ_FRAMEBUFFER, state.readFramebuffer.GLuint) + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, state.drawFramebuffer.GLuint) + +proc age*(distortions: var seq[Distortion], seconds: float32) = + ## Advances every distortion and drops the finished ones. + var kept = 0 + for item in distortions.mitems: + item.age += seconds + if item.age < item.life: + distortions[kept] = item + inc kept + distortions.setLen(kept) + +proc project(point: Vec3, viewMatrix: Mat4, size: IVec2): Vec2 = + let clip = viewMatrix * vec4(point, 1) + if clip.w <= 0: return vec2(-1e6) + vec2((clip.x / clip.w + 1) * 0.5 * size.x.float32, (clip.y / clip.w + 1) * 0.5 * size.y.float32) + +proc drawDistortions*( + renderer: var DistortionRenderer, + distortions: openArray[Distortion], + viewMatrix: Mat4, + eye, right, up: Vec3, + size: IVec2, + clock: float32, + source: GLuint = 0 +) = + ## Bends what the `source` framebuffer (the window by default) shows under + ## each distortion. `size` is its size in pixels, `right` and `up` the + ## camera's axes, and `clock` seconds for the heat ripples. Leaves GL state + ## as it found it. + if distortions.len == 0 or renderer.unavailable or size.x <= 0 or size.y <= 0: + return + let saved = saveState() + defer: saved.restore() + if not renderer.ready: renderer.setup() + renderer.ensureSize(size) + # Copy the finished scene, resolving multisampling, to sample it shifted. + if not renderer.copyChecked: + while glGetError() != GL_NO_ERROR: discard + glBindFramebuffer(GL_READ_FRAMEBUFFER, source) + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, renderer.copyFramebuffer) + glBlitFramebuffer(0, 0, size.x, size.y, 0, 0, size.x, size.y, + GL_COLOR_BUFFER_BIT, GL_NEAREST.GLenum) + if not renderer.copyChecked: + renderer.copyChecked = true + let error = glGetError() + if error != GL_NO_ERROR: + renderer.unavailable = true + echo "Distortion is off: the window's colors can't be copied (GL error 0x", + toHex(error.int, 4), ")" + return + # One quad per distortion, pulled toward the camera so the ground does not cut it. + renderer.floats.setLen(0) + for item in distortions: + if item.life <= 0 or item.radius <= 0: continue + let + toEye = eye - item.center + lift = if length(toEye) > 1e-6: normalize(toEye) * min(item.radius, length(toEye) * 0.5) else: vec3(0) + center = item.center + lift + onScreen = length(project(item.center + right * item.radius, viewMatrix, size) - + project(item.center, viewMatrix, size)) + pixels = item.strength * onScreen + params = [item.kind.ord.float32, item.age / item.life, pixels, item.seed] + sideways = right * item.radius + upward = up * item.radius + for (u, v) in [(-1'f32, -1'f32), (1'f32, -1'f32), (1'f32, 1'f32), + (-1'f32, -1'f32), (1'f32, 1'f32), (-1'f32, 1'f32)]: + let at = center + sideways * u + upward * v + renderer.floats.add [at.x, at.y, at.z, u, v] + renderer.floats.add params + if renderer.floats.len == 0: return + glBindFramebuffer(GL_FRAMEBUFFER, source) + glViewport(0, 0, size.x, size.y) + glEnable(GL_DEPTH_TEST) + glDepthMask(GL_FALSE) + glDisable(GL_CULL_FACE) + glEnable(GL_BLEND) + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE) + glUseProgram(renderer.program) + var matrix = viewMatrix + glUniformMatrix4fv(renderer.viewMatrix, 1, GL_FALSE, cast[ptr float32](matrix.addr)) + glUniform2f(renderer.viewportSize, size.x.float32, size.y.float32) + glUniform1f(renderer.clock, clock) + glActiveTexture(GL_TEXTURE0) + glBindTexture(GL_TEXTURE_2D, renderer.copyTexture) + glUniform1i(renderer.sceneSampler, 0) + glBindVertexArray(renderer.vertexArray) + glBindBuffer(GL_ARRAY_BUFFER, renderer.vertexBuffer) + glBufferData(GL_ARRAY_BUFFER, renderer.floats.len * sizeof(float32), + renderer.floats[0].addr, GL_STREAM_DRAW) + glDrawArrays(GL_TRIANGLES, 0, GLsizei(renderer.floats.len div VertexFloats)) + +proc close*(renderer: var DistortionRenderer) = + ## Releases the program, buffers and scene copy. + if renderer.ready: + glDeleteProgram(renderer.program) + glDeleteVertexArrays(1, renderer.vertexArray.addr) + glDeleteBuffers(1, renderer.vertexBuffer.addr) + glDeleteFramebuffers(1, renderer.copyFramebuffer.addr) + glDeleteTextures(1, renderer.copyTexture.addr) + renderer = DistortionRenderer() diff --git a/src/polyworld/mailboxes.nim b/src/polyworld/mailboxes.nim index 5cd047719..e26d9aa6c 100644 --- a/src/polyworld/mailboxes.nim +++ b/src/polyworld/mailboxes.nim @@ -9,6 +9,10 @@ type Mailbox* = ref object first*, count*: int lastId*: int32 +proc receivedChatId*(sender, target: int): int32 = + ## For a validated destination, retain the channel or identify the DM sender. + int32(if target < 0: target else: sender) + proc newMailbox*(): Mailbox = ## Reserves one player's bounded inbox before the game starts. result = Mailbox(lastId: NoMailboxId) diff --git a/src/polyworld/player.nim b/src/polyworld/player.nim index eb78ff00c..beceebd86 100644 --- a/src/polyworld/player.nim +++ b/src/polyworld/player.nim @@ -60,10 +60,14 @@ type seekSerial*: int automaticSeek*: bool tickRate: int32 + customSpeed: int32 proc speed*(player: Player): int32 = ## Returns the selected realtime multiplier. - PlayerSpeeds[player.speedIndex] + if player.customSpeed > 0: + player.customSpeed + else: + PlayerSpeeds[player.speedIndex] proc timelineEnd*(player: Player): int32 = ## Returns the right edge of the scrubber. @@ -77,12 +81,20 @@ proc inHistory*(player: Player): bool = (not player.live) or player.tick < player.recordedTicks proc speedIndexOf*(value: int32): int = - ## Maps a requested multiplier onto 1x, 2x, 4x, or 16x. + ## Finds the nearest preset at or below a requested multiplier. result = 0 for i, speed in PlayerSpeeds: if speed <= value: result = i +proc setPlaybackSpeed*(player: var Player, multiplier: int32) = + ## Sets an exact realtime multiplier while retaining the nearest UI preset. + let value = max(multiplier, 1) + player.speedIndex = speedIndexOf(value) + player.customSpeed = + if PlayerSpeeds[player.speedIndex] == value: 0 + else: value + proc initPlayer*( live: bool, durationTicks: int32, @@ -95,7 +107,7 @@ proc initPlayer*( result.durationTicks = max(durationTicks, 0) result.playing = playing result.repeating = repeating - result.speedIndex = speedIndexOf(speed) + result.setPlaybackSpeed(speed) result.restoreTick = -1 result.targetTick = -1 @@ -172,6 +184,7 @@ proc togglePlay*(player: var Player) = proc setSpeed*(player: var Player, index: int) = ## Selects one of the four transport multipliers. player.speedIndex = clamp(index, 0, PlayerSpeeds.high) + player.customSpeed = 0 proc reachedEnd(player: Player): bool = ## Returns whether playback has no further ticks to consume. @@ -195,7 +208,7 @@ proc startFrame*(player: var Player, dt: float32, tickRate: int32) = return player.accumulator = min( player.accumulator + dt * player.speed.float32, - 0.25'f32 + 0.25'f32 * player.speed.float32 ) proc shouldTick*( @@ -224,6 +237,8 @@ proc shouldTick*( return epochTime() - frameStart < CatchUpSeconds if not player.playing: return false + if frameStart > 0 and epochTime() - frameStart >= CatchUpSeconds: + return false let step = 1.0'f32 / max(player.tickRate, 1).float32 if player.accumulator >= step: player.accumulator -= step @@ -385,7 +400,7 @@ proc drawTransport*( elif window.clicked(sk, loopBtn, keyboardAliases): player.repeating = not player.repeating for i, button in speeds: - sk.drawIcon(button, SpeedIcons[i], player.speedIndex == i) + sk.drawIcon(button, SpeedIcons[i], player.speed == PlayerSpeeds[i]) if window.clicked(sk, button, keyboardAliases): player.setSpeed(i) let diff --git a/src/polyworld/policyhosts.nim b/src/polyworld/policyhosts.nim index 23e5f1c56..8798cbecd 100644 --- a/src/polyworld/policyhosts.nim +++ b/src/polyworld/policyhosts.nim @@ -1,5 +1,5 @@ ## Shared policy capabilities; game builders add only their game-specific API. -import bassy, annotations +import bassy, annotations, mailboxes when defined(coworld): import coworld @@ -10,3 +10,11 @@ proc initPolicyHost*(slot = -1): Host = result.addAnnotationFunctions(playerAnnotations(slot)) else: result.addAnnotationFunctions() + +proc pullMailboxString*(runtime: var Runtime, inbox: Mailbox): Value = + ## Copy before popping so a BASIC string limit leaves the message unread. + if inbox.count == 0: + result = runtime.putString("") + else: + result = runtime.putString(inbox.messages[inbox.first]) + discard inbox.pop() diff --git a/src/polyworld/replaylibraries.nim b/src/polyworld/replaylibraries.nim new file mode 100644 index 000000000..81ccd3a4a --- /dev/null +++ b/src/polyworld/replaylibraries.nim @@ -0,0 +1,278 @@ +import + std/[algorithm, os, strutils, tempfiles, times], + tapes + +type + ReplayPayloadHeader* = enum + TapePayloadHeader, OpaquePayloadHeader + ReplayEntry* = object + path*, name*: string + modified*: Time + size*: int64 + gameVersion*, fileVersion*, tapeVersion*: uint16 + playable*: bool + problem*: string + ticks*: int + ReplayLibraryFormat* = object + game*: string + gameVersion*, tapeVersion*: uint16 + maxBytes*: int + payloadHeader*: ReplayPayloadHeader + ReplayInspector* = proc(bytes: string): int + ## Validates a current game payload and returns its recorded tick count. + ReplayLibrary* = object + gameFolder*, gamePrefix*: string + format*: ReplayLibraryFormat + inspect*: ReplayInspector + +proc replayDirectory*(gameFolder: string): string = + ## Keeps each game's recordings in the user's application data directory. + var base = getDataDir() + if base.len == 0 or not base.isAbsolute(): + when defined(windows): + base = getHomeDir() / "AppData" / "Roaming" + elif defined(macosx): + base = getHomeDir() / "Library" / "Application Support" + else: + base = getHomeDir() / ".local" / "share" + base / "Polyworld" / gameFolder / "Replays" + +proc ensureReplayDirectory*(directory: string): string = + ## Creates and returns the library directory without relying on the game path. + if directory.len == 0: + raise newException(ReplayError, "The replay folder is empty.") + try: + createDir(directory) + result = absolutePath(directory) + except IOError, OSError: + raise newException(ReplayError, + "Could not create the replay folder: " & getCurrentExceptionMsg()) + +proc readReplayBytes(path: string, maxBytes: int, headerOnly = false): string = + ## Bounds an imported file before allocating or decoding its contents. + try: + let file = open(path, fmRead) + defer: + file.close() + let size = file.getFileSize() + if size < 0 or size > maxBytes: + raise newException(ReplayError, + "The replay exceeds the " & $(maxBytes div (1024 * 1024)) & + " MiB limit.") + let count = + if headerOnly: + min(size.int, ReplayMagic.len + 10 + MaximumReplayGameBytes) + else: + size.int + result = newString(count) + if result.len > 0 and + file.readBuffer(addr result[0], result.len) != result.len: + raise newException(ReplayError, "The replay file is incomplete.") + if not headerOnly and not file.endOfFile(): + raise newException(ReplayError, "The replay changed while it was read.") + except IOError, OSError: + raise newException(ReplayError, + "Could not read the replay: " & getCurrentExceptionMsg()) + +proc inspectVersions( + bytes: string, format: ReplayLibraryFormat, entry: var ReplayEntry +): bool = + ## Checks versions before attempting the current game's payload decoder. + let header = replayFileHeader(bytes) + entry.fileVersion = header.formatVersion + entry.gameVersion = header.gameVersion + if header.game != format.game: + raise newException(ReplayError, "This replay belongs to another game.") + if header.formatVersion != ReplayFileVersion: + entry.problem = "Replay file version " & $header.formatVersion & + " (requires " & $ReplayFileVersion & ")" + return + if header.gameVersion != format.gameVersion: + entry.problem = "Game version " & $header.gameVersion & + " (requires " & $format.gameVersion & ")" + return + if format.payloadHeader == OpaquePayloadHeader: + return true + let offset = ReplayMagic.len + 6 + header.game.len + if bytes.len < offset + 4: + raise newException(ReplayError, "The replay payload is incomplete.") + entry.tapeVersion = uint16(bytes[offset].ord) or + uint16(bytes[offset + 1].ord shl 8) + if entry.tapeVersion != format.tapeVersion: + entry.problem = "Replay format " & $entry.tapeVersion & + " (requires " & $format.tapeVersion & ")" + return + let gameVersion = uint16(bytes[offset + 2].ord) or + uint16(bytes[offset + 3].ord shl 8) + if gameVersion != format.gameVersion: + entry.problem = "Game version " & $gameVersion & + " (requires " & $format.gameVersion & ")" + return + true + +proc inspectBytes( + bytes: string, format: ReplayLibraryFormat, inspect: ReplayInspector, + entry: var ReplayEntry +) = + ## Decodes only payloads whose outer and inner versions are supported. + if not inspectVersions(bytes, format, entry): + return + entry.ticks = inspect(bytes) + entry.playable = true + +proc inspectReplay*( + path: string, format: ReplayLibraryFormat, inspect: ReplayInspector +): ReplayEntry = + ## Describes one valid, incompatible, or unreadable recording for the browser. + result.path = absolutePath(path) + result.name = path.splitFile().name + try: + result.modified = getLastModificationTime(path) + result.size = getFileSize(path) + if inspectVersions( + readReplayBytes(path, format.maxBytes, headerOnly = true), format, result + ): + inspectBytes(readReplayBytes(path, format.maxBytes), format, inspect, result) + except CatchableError as error: + result.problem = error.msg + except IndexDefect, RangeDefect: + result.problem = "The replay payload is invalid or incomplete." + +proc listReplays*( + directory: string, format: ReplayLibraryFormat, inspect: ReplayInspector +): seq[ReplayEntry] = + ## Lists newest recordings first, retaining disabled entries for old versions. + if not dirExists(directory): + return + try: + for kind, path in walkDir(directory, checkDir = true): + if kind in {pcFile, pcLinkToFile} and + path.splitFile().ext.toLowerAscii() == ".replay": + result.add(inspectReplay(path, format, inspect)) + except OSError as error: + raise newException(ReplayError, + "Could not read the replay folder: " & error.msg) + result.sort(proc(first, second: ReplayEntry): int = + ## Orders ties by their full filename to keep refreshes stable. + result = cmp(second.modified, first.modified) + if result == 0: + result = cmp(first.path, second.path) + ) + +proc filenamePrefix(name: string): string = + ## Retains readable imported names while avoiding platform filename syntax. + for character in name: + if result.len == 60: + break + if character in Letters + Digits + {'-', '_'}: + result.add(character) + elif character == ' ': + result.add('-') + if result.len == 0: + result = "replay" + result = "Imported-" & result & "-" + +proc flushReplay(file: File) = + ## Rejects buffered write failures before publishing a complete recording. + proc fflush(stream: File): cint {.importc, header: "".} + ## Flushes the C stream while retaining its success or failure result. + if fflush(file) != 0: + raise newException(IOError, "Could not finish writing the replay file.") + +proc storeReplayBytes(bytes, directory, prefix: string): string = + ## Publishes a complete file with a unique name, without overwriting replays. + let folder = ensureReplayDirectory(directory) + try: + while true: + let (file, temporary) = createTempFile(prefix, ".partial", folder) + let destination = temporary.changeFileExt(".replay") + var closed = false + try: + if fileExists(destination) or dirExists(destination): + continue + file.write(bytes) + flushReplay(file) + closed = true + file.close() + moveFile(temporary, destination) + return destination + finally: + if not closed: + file.close() + if fileExists(temporary): + removeFile(temporary) + except IOError, OSError: + raise newException(ReplayError, + "Could not save the replay: " & getCurrentExceptionMsg()) + +proc saveLibraryReplay*(bytes, directory, gamePrefix: string): string = + ## Saves game-validated bytes with a time-stamped unique filename. + storeReplayBytes( + bytes, + directory, + gamePrefix & "-" & now().format("yyyy-MM-dd'_'HH-mm-ss") & "-" + ) + +proc importReplay*( + source, directory: string, format: ReplayLibraryFormat, + inspect: ReplayInspector +): string = + ## Copies a game's recording into the library, preserving unsupported versions. + let bytes = readReplayBytes(source, format.maxBytes) + var entry: ReplayEntry + try: + inspectBytes(bytes, format, inspect, entry) + except IndexDefect, RangeDefect: + raise newException(ReplayError, "The replay payload is invalid or incomplete.") + except CatchableError as error: + raise newException(ReplayError, error.msg) + let folder = ensureReplayDirectory(directory) + if source.splitFile().ext.toLowerAscii() == ".replay" and + sameFile(source.absolutePath().parentDir, folder): + return source.absolutePath() + storeReplayBytes(bytes, folder, source.splitFile().name.filenamePrefix()) + +proc replayDirectory*(library: ReplayLibrary): string = + ## Returns this game's stable location in the user's application data. + replayDirectory(library.gameFolder) + +proc libraryDirectory(library: ReplayLibrary, directory: string): string = + ## Resolves an optional override without changing the game's default folder. + if directory.len > 0: + directory + else: + library.replayDirectory() + +proc ensureReplayDirectory*( + library: ReplayLibrary, directory = "" +): string = + ## Creates this game's library or an explicitly supplied test directory. + ensureReplayDirectory(library.libraryDirectory(directory)) + +proc inspectReplay*(library: ReplayLibrary, path: string): ReplayEntry = + ## Checks a recording with the game's supported versions and payload decoder. + inspectReplay(path, library.format, library.inspect) + +proc listReplays*( + library: ReplayLibrary, directory = "" +): seq[ReplayEntry] = + ## Lists this game's recordings using the shared ordering and validation. + listReplays( + library.libraryDirectory(directory), library.format, library.inspect + ) + +proc saveLibraryReplay*( + library: ReplayLibrary, bytes: string, directory = "" +): string = + ## Stores game-validated bytes under the game's unique filename prefix. + saveLibraryReplay( + bytes, library.libraryDirectory(directory), library.gamePrefix + ) + +proc importReplay*( + library: ReplayLibrary, source: string, directory = "" +): string = + ## Imports through the game's decoder while preserving incompatible versions. + importReplay( + source, library.libraryDirectory(directory), library.format, library.inspect + ) diff --git a/src/polyworld/replaymenus.nim b/src/polyworld/replaymenus.nim new file mode 100644 index 000000000..39d6b99b7 --- /dev/null +++ b/src/polyworld/replaymenus.nim @@ -0,0 +1,284 @@ +import + std/[strutils, times], + bumpy, chroma, pixie, silky, vmath, windy, + chrome, homes, lobbies, replaylibraries, sounds, tapes + +const ReplayRowHeight* = 104.0'f + +type + ReplayLengthDisplay* = enum + ReplayDuration, ReplayActionCount + ReplayBrowserAction* = enum + StayReplayBrowser, BackFromReplays, ImportReplayFile, OpenReplayFolder, + RefreshReplays, PlayReplay + ReplayBrowserResult* = object + action*: ReplayBrowserAction + path*: string + ReplayBrowserUi* = object + scroll*: FrameState + selectedPath*: string + ReplayBrowserState* = object + ui*: ReplayBrowserUi + entries*: seq[ReplayEntry] + folder*, message*: string + refreshRequested*: bool + ReplayBrowserStyle* = object + title*: string = "REPLAYS" + titleColor*: ColorRGBX = rgbx(240, 237, 225, 255) + accentColor*: ColorRGBX = LobbyGreen + mutedColor*: ColorRGBX = LobbyMuted + centerTitle*: bool + navigationIcons*: bool = true + background*: proc(sk: Silky, window: Window) + ReplayBrowserLayout* = object + panel*, rows*: Rect + back*, importButton*, folderButton*, refresh*: Rect + +proc initReplayBrowser*( + library: ReplayLibrary, message = "", directory = "" +): ReplayBrowserState = + ## Initializes the desktop library without performing filesystem operations. + result.folder = if directory.len > 0: directory else: library.replayDirectory() + result.message = message + result.refreshRequested = true + +proc refreshReplayBrowser*( + browser: var ReplayBrowserState, library: ReplayLibrary +) = + ## Reloads the current folder after an import, save, or explicit refresh. + browser.refreshRequested = false + browser.folder = library.ensureReplayDirectory(browser.folder) + browser.entries = library.listReplays(browser.folder) + +proc importBrowserReplay*( + browser: var ReplayBrowserState, library: ReplayLibrary, source: string +) = + ## Imports a selected file and focuses it without changing its source. + if source.len == 0: + return + browser.ui.selectedPath = library.importReplay(source, browser.folder) + browser.refreshRequested = true + browser.message = "Replay imported." + +when not defined(emscripten): + proc updateReplayBrowser*( + browser: var ReplayBrowserState, library: ReplayLibrary, + action: ReplayBrowserResult + ): ReplayBrowserResult = + ## Performs desktop file actions after event polling and validates playback. + try: + case action.action + of StayReplayBrowser: + discard + of BackFromReplays: + browser.message = "" + return action + of RefreshReplays: + browser.refreshRequested = true + browser.message = "" + of OpenReplayFolder: + openUrl(library.ensureReplayDirectory(browser.folder)) + of ImportReplayFile: + let source = openFileDialog("Import replay", @[ + FileDialogFilter(name: "Polyworld replay", extensions: "replay") + ], defaultPath = library.ensureReplayDirectory(browser.folder)) + browser.importBrowserReplay(library, source) + of PlayReplay: + let entry = library.inspectReplay(action.path) + if not entry.playable: + raise newException(ReplayError, entry.problem) + result = ReplayBrowserResult(action: PlayReplay, path: entry.path) + if browser.refreshRequested: + browser.refreshReplayBrowser(library) + except CatchableError as error: + browser.message = error.msg + result = ReplayBrowserResult() + +proc replayBrowserLayout*(view: Vec2, folderWidth = 236.0'f): ReplayBrowserLayout = + ## Keeps the list and controls within the current logical desktop viewport. + let + width = min(1240.0'f, max(480.0'f, view.x - 48)) + left = (view.x - width) / 2 + bottom = view.y - 30 + result.panel = rect(left, 132, width, max(260.0'f, bottom - 198)) + result.rows = rect(left + 20, 188, width - 40, result.panel.h - 76) + result.back = rect(left, bottom - 44, 160, 44) + result.importButton = rect(left, 76, 194, 44) + result.refresh = rect(left + width - 154, 76, 154, 44) + result.folderButton = rect(left + 208, 76, + min(max(236.0'f, folderWidth), result.refresh.x - left - 220), 44) + +proc folderButtonLabel*(): string = + ## Names the desktop's file manager without exposing command syntax. + when defined(macosx): "Open in Finder" + elif defined(windows): "Open in File Explorer" + else: "Open replay folder" + +proc drawReplaySaveOption*( + sk: Silky, window: Window, at: Vec2, saveReplay: var bool, + enabled = true, width = 280.0'f +): bool = + ## Draws the common recording preference and reports changes for persistence. + let previous = saveReplay + sk.at = at + if enabled: + checkBox "Save replay", saveReplay + else: + sk.lobbyLabel("Save replay: " & (if saveReplay: "On" else: "Off"), + at, width, tint = LobbyMuted) + previous != saveReplay + +proc drawReplaySaveRetry*(sk: Silky, pending: bool): bool = + ## Keeps the retry action in the same place on each game's desktop menu. + pending and sk.lobbyButton("Retry saving replay", vec2(24, 64), 280) + +proc replayDetails(entry: ReplayEntry, tickRate: int, + lengthDisplay: ReplayLengthDisplay): string = + ## Shows a recording's version and supported time or action-count measure. + result = entry.modified.local.format("yyyy-MM-dd HH:mm") & + " | Game v" & $entry.gameVersion + if entry.playable: + case lengthDisplay + of ReplayDuration: + let seconds = entry.ticks div tickRate + result.add(" | " & $(seconds div 60) & ":" & + align($(seconds mod 60), 2, '0')) + of ReplayActionCount: + result.add(" | " & $entry.ticks & + (if entry.ticks == 1: " action" else: " actions")) + +proc chooseReplay(ui: var ReplayBrowserUi, entries: openArray[ReplayEntry], + direction: int): int = + ## Moves keyboard focus between playable entries only. + var current = if direction > 0: -1 else: entries.len + for index, entry in entries: + if entry.path == ui.selectedPath: + current = index + break + var next = current + direction + while next >= 0 and next < entries.len: + if entries[next].playable: + ui.selectedPath = entries[next].path + return next + next += direction + -1 + +proc drawReplayBrowser*( + sk: Silky, window: Window, ui: var ReplayBrowserUi, + entries: openArray[ReplayEntry], folder: string, + gameVersion: uint16, tickRate: int, message = "", + lengthDisplay = ReplayDuration, style = ReplayBrowserStyle() +): ReplayBrowserResult = + ## Draws the library and returns file actions for the frontend to perform. + doAssert tickRate > 0 + let requestedScale = selectedUiScale(max(0.1'f, min( + window.size.x.float32 / 1080, window.size.y.float32 / 800 + )), 1.35'f) + sk.uiScale = min(requestedScale, max(0.1'f, min( + window.size.x.float32 / 720, window.size.y.float32 / 600 + ))) + sk.beginUi(window, window.size) + sk.textStyle = "LobbyBody" + let + view = window.size.vec2 / sk.uiScale + layout = replayBrowserLayout(view, + sk.getTextSize("LobbyBody", folderButtonLabel()).x + 20) + rowWidth = layout.rows.w - 16 + if style.background != nil: + style.background(sk, window) + else: + sk.drawHomeBackground(window) + sk.drawLabel(style.title, vec2(layout.panel.x, 14), + vec2(layout.panel.w, 56), style.titleColor, "LobbyTitle", + if style.centerTitle: CenterAlign else: LeftAlign) + if sk.lobbyButton("Import replay", layout.importButton.xy, + layout.importButton.w): + result.action = ImportReplayFile + if sk.lobbyButton(folderButtonLabel(), layout.folderButton.xy, + layout.folderButton.w): + result.action = OpenReplayFolder + if sk.lobbyButton("Refresh", layout.refresh.xy, layout.refresh.w, + if style.navigationIcons: "loop" else: ""): + result.action = RefreshReplays + if sk.lobbyButton("Back", layout.back.xy, layout.back.w, + if style.navigationIcons: "arrow_left" else: "") or + window.buttonPressed[KeyEscape]: + result.action = BackFromReplays + sk.lobbyPanel(layout.panel.xy, layout.panel.wh) + sk.lobbyLabel($entries.len & (if entries.len == 1: " replay" else: " replays") & + " | Current game version " & $gameVersion, + layout.panel.xy + vec2(20, 8), layout.panel.w - 40, "LobbyBold") + if ui.scroll == nil: + ui.scroll = FrameState() + var selected = -1 + for index, entry in entries: + if entry.playable and entry.path == ui.selectedPath: + selected = index + break + if selected < 0: + ui.selectedPath = "" + let direction = + if window.buttonPressed[KeyDown]: 1 + elif window.buttonPressed[KeyUp]: -1 + else: 0 + if direction != 0: + let next = ui.chooseReplay(entries, direction) + if next >= 0: + selected = next + let top = next.float32 * ReplayRowHeight + ui.scroll.scrollPos.y = clamp(ui.scroll.scrollPos.y, + top + ReplayRowHeight - layout.rows.h, top) + playSound(SelectSound) + sk.frameScrollbars(window, ui.scroll, layout.rows, + vec2(layout.rows.w, entries.len.float32 * ReplayRowHeight), vec2(1)) + sk.pushClipRect(rect(layout.rows.xy, vec2(rowWidth, layout.rows.h))) + for index, entry in entries: + let + at = layout.rows.xy + + vec2(0, index.float32 * ReplayRowHeight - ui.scroll.scrollPos.y) + size = vec2(rowWidth, ReplayRowHeight - 8) + ink = if entry.playable: sk.theme.defaultTextColor else: style.mutedColor + labelWidth = rowWidth - 180 + if at.y + size.y <= layout.rows.y or at.y >= layout.rows.y + layout.rows.h: + continue + sk.lobbyPanel(at, size, true) + if index == selected: + sk.drawRect(at + vec2(0, 2), vec2(4, size.y - 4), style.accentColor) + if sk.interact(rect(at, vec2(labelWidth + 20, size.y)), + entry.playable) == Released: + ui.selectedPath = entry.path + selected = index + sk.lobbyLabel(sk.fittedLabel(entry.name, labelWidth, "LobbyBold"), + at + vec2(14, 0), labelWidth, "LobbyBold", ink) + sk.lobbyLabel(replayDetails(entry, tickRate, lengthDisplay), + at + vec2(14, 28), labelWidth, tint = style.mutedColor) + let detail = if entry.playable: "Ready to watch" else: entry.problem + sk.lobbyLabel(sk.fittedLabel(detail, labelWidth, "LobbyBody"), + at + vec2(14, 56), labelWidth, + tint = if entry.playable: style.accentColor else: style.mutedColor) + if sk.lobbyButton("Watch", at + vec2(rowWidth - 144, 26), 128, + (if style.navigationIcons: "arrow_right" else: ""), entry.playable): + result = ReplayBrowserResult(action: PlayReplay, path: entry.path) + if entries.len == 0: + sk.lobbyLabel("No saved replays yet.", layout.rows.xy + vec2(20, 38), + rowWidth - 40, "LobbyHeading") + sk.lobbyLabel("Enable Save replay in game setup, or import a replay file.", + layout.rows.xy + vec2(20, 82), rowWidth - 40, tint = style.mutedColor) + sk.popClipRect() + if selected >= 0 and window.buttonPressed[KeyEnter]: + result = ReplayBrowserResult(action: PlayReplay, path: entries[selected].path) + let footer = layout.back.xy + vec2(180, 0) + sk.lobbyLabel(sk.fittedLabel( + if message.len > 0: message else: folder, + layout.panel.w - 180, "LobbyBody" + ), footer, layout.panel.w - 180, + tint = if message.len > 0: sk.theme.defaultTextColor else: style.mutedColor) + +proc drawReplayBrowser*( + sk: Silky, window: Window, browser: var ReplayBrowserState, + gameVersion: uint16, tickRate: int, lengthDisplay = ReplayDuration, + style = ReplayBrowserStyle() +): ReplayBrowserResult = + ## Renders the same controller state for every desktop replay library. + sk.drawReplayBrowser(window, browser.ui, browser.entries, browser.folder, + gameVersion, tickRate, browser.message, lengthDisplay, style) diff --git a/src/polyworld/replaysaves.nim b/src/polyworld/replaysaves.nim new file mode 100644 index 000000000..f40aa719a --- /dev/null +++ b/src/polyworld/replaysaves.nim @@ -0,0 +1,67 @@ +import + std/os, + tapes + +type + ReplaySaveError* = object of ReplayError + ReplayExportError* = object of ReplayError + + ReplaySaveState* = object + savedPath*: string + saveRequested*: bool + automaticAttempted*: bool + savedHashes, savedActions: int = -1 + +proc resetReplaySave*(state: var ReplaySaveState) = + ## Starts a new match without carrying over its predecessor's saved prefix. + state = ReplaySaveState() + +proc requestReplaySave*(state: var ReplaySaveState) = + ## Preserves a save request until its recorded prefix reaches the library. + state.saveRequested = true + +proc beginAutomaticReplaySave*( + state: var ReplaySaveState, enabled, completed: bool +): bool = + ## Allows one automatic completion attempt, leaving retries explicit. + if enabled and completed and not state.automaticAttempted: + state.automaticAttempted = true + result = true + +proc shouldSaveReplayOnExit*( + state: ReplaySaveState, automatic: bool +): bool = + ## Retries an unsuccessful manual save even when automatic saving is off. + automatic or state.saveRequested + +proc shouldRetainReplay*( + automatic: bool, error: ref CatchableError +): bool = + ## Preserves failed saves without duplicating a successful library write. + error of ReplaySaveError or + (automatic and not (error of ReplayExportError)) + +proc saveReplaySnapshot*[T]( + state: var ReplaySaveState, + data: T, + save: proc(data: T): string +): string = + ## Writes an append-only recorded prefix once, recreating a removed file. + state.requestReplaySave() + if state.savedPath.len == 0 or not fileExists(state.savedPath) or + state.savedHashes != data.hashes.len or + state.savedActions != data.actions.len: + let path = save(data) + state.savedPath = path + state.savedHashes = data.hashes.len + state.savedActions = data.actions.len + state.saveRequested = false + state.savedPath + +proc retryReplaySaves*[T]( + pending: var seq[T], save: proc(data: T): string +) = + ## Removes a retained recording only after its library write succeeds. + while pending.len > 0: + discard save(pending[0]) + pending.delete(0) diff --git a/src/polyworld/replaysettings.nim b/src/polyworld/replaysettings.nim new file mode 100644 index 000000000..6e1efb5b4 --- /dev/null +++ b/src/polyworld/replaysettings.nim @@ -0,0 +1,25 @@ +import + jsony, windy, + menus + +type ReplayPreferences* = object + saveReplay*: bool = true + +proc decodeReplayPreferences*(bytes: string): ReplayPreferences = + ## Defaults new installations to recording and rejects malformed settings. + result = ReplayPreferences() + if bytes.len > 0: + try: + result = bytes.fromJson(ReplayPreferences) + except JsonError as error: + raise newException(MenusError, "Cannot read replay settings: " & error.msg) + +proc readReplayPreferences*(appName: string): ReplayPreferences = + ## Loads the device's recording choice independently of shared match rules. + decodeReplayPreferences(getConfig(appName, "replays.json")) + +proc saveReplayPreferences*( + preferences: ReplayPreferences, appName: string +) = + ## Persists the recording choice using the game's existing config namespace. + setConfig(appName, "replays.json", preferences.toJson()) diff --git a/src/polyworld/screenshots.nim b/src/polyworld/screenshots.nim new file mode 100644 index 000000000..caa8c86e1 --- /dev/null +++ b/src/polyworld/screenshots.nim @@ -0,0 +1,154 @@ +## Shared native screenshot options, argument parsing, and capture state. + +import std/[os, strutils] + +const DefaultScreenshotFrames* = 30 + +type + ScreenshotError* = object of CatchableError + ScreenshotOptions* = object + path*: string + frames*: int = DefaultScreenshotFrames + framesSpecified*: bool + +var + captureConfigured = false + captureSettings: ScreenshotOptions + runtimeCapture = false + captureCompleted = false + +proc captureRequested*(options: ScreenshotOptions): bool = + ## Reports whether a launch requests a native screenshot. + options.path.len > 0 or defined(takeScreenshot) + +proc captureValue( + arguments: openArray[string], index: var int, argument, name: string +): string = + ## Reads one separate or attached value without splitting a path's colons. + if argument == name: + if index + 1 >= arguments.len or arguments[index + 1].startsWith("--"): + raise newException(ScreenshotError, name & " requires a value") + inc index + result = arguments[index] + else: + result = argument[name.len + 1 .. ^1] + if result.len == 0: + raise newException(ScreenshotError, name & " requires a value") + +proc positiveCaptureInt(text, name: string): int32 = + ## Parses one positive capture value that fits the common integer range. + var value: int64 + try: + value = parseBiggestInt(text) + except ValueError: + raise newException(ScreenshotError, name & " must be a positive integer") + if value <= 0 or value > int32.high: + raise newException(ScreenshotError, + name & " must be between 1 and " & $int32.high) + value.int32 + +proc matchesCaptureFlag(argument, name: string): bool = + ## Recognizes exactly one common option and its two attached-value forms. + argument == name or argument.startsWith(name & "=") or + argument.startsWith(name & ":") + +proc takeCaptureFlag*( + options: var ScreenshotOptions, arguments: openArray[string], + index: var int, argument: string +): bool = + ## Reads screenshot and frame options without depending on a graphics build. + if argument.matchesCaptureFlag("--screenshot"): + options.path = arguments.captureValue(index, argument, "--screenshot") + if options.frames == 0 and not options.framesSpecified: + options.frames = DefaultScreenshotFrames + return true + if argument.matchesCaptureFlag("--frames"): + options.frames = positiveCaptureInt( + arguments.captureValue(index, argument, "--frames"), "--frames" + ).int + options.framesSpecified = true + return true + +proc takeWindowSizeFlag*( + width, height: var int32, arguments: openArray[string], + index: var int, argument: string +): bool = + ## Parses the common window dimensions in separate, equals, or colon form. + if not argument.matchesCaptureFlag("--windowSize"): + return false + let + value = arguments.captureValue(index, argument, "--windowSize") + separator = value.find({'x', 'X'}) + if separator <= 0 or separator >= value.high: + raise newException(ScreenshotError, "--windowSize must look like 800x600") + let + parsedWidth = positiveCaptureInt(value[0 ..< separator], "--windowSize") + parsedHeight = positiveCaptureInt(value[separator + 1 .. ^1], "--windowSize") + width = parsedWidth + height = parsedHeight + true + +proc validateCapture*( + options: ScreenshotOptions, + graphical = not defined(headless) and not defined(emscripten) +) = + ## Rejects unavailable capture targets and invalid directly constructed options. + if options.frames < 0 or options.frames > int32.high or + (options.frames == 0 and options.framesSpecified): + raise newException(ScreenshotError, "--frames must be a positive int32") + if options.captureRequested() and not graphical: + raise newException(ScreenshotError, + "--screenshot requires a native graphical client") + +proc configureCapture*( + options: ScreenshotOptions, defaultPath = "screenshot.png", + graphical = not defined(headless) and not defined(emscripten) +) = + ## Configures one viewer explicitly, resolving its output before changing cwd. + options.validateCapture(graphical) + var configured = options + if configured.frames == 0: + configured.frames = DefaultScreenshotFrames + if configured.path.len == 0: + when defined(takeScreenshot): + configured.path = getEnv("SCREENSHOT_PATH", defaultPath) + if configured.path.len > 0: + configured.path = absolutePath(configured.path) + captureSettings = configured + runtimeCapture = options.path.len > 0 + captureConfigured = true + captureCompleted = false + +proc captureActive*(): bool = + ## Reports whether the current viewer should render a hidden fixed-step shot. + if captureConfigured: + captureSettings.path.len > 0 + else: + defined(takeScreenshot) + +proc captureWaitFrames*(legacyDefault = DefaultScreenshotFrames): int = + ## Uses the common runtime frame count while retaining developer capture hooks. + if captureConfigured and (runtimeCapture or captureSettings.framesSpecified): + captureSettings.frames + else: + max(1, legacyDefault) + +proc capturePath*(defaultPath = "screenshot.png"): string = + ## Resolves the configured output or an unconfigured developer capture path. + if captureConfigured and captureSettings.path.len > 0: + captureSettings.path + else: + absolutePath(getEnv("SCREENSHOT_PATH", defaultPath)) + +proc captureDue*(frame: int, waitFrames = DefaultScreenshotFrames): bool = + ## Checks a rendered-frame count without advancing simulation or reading pixels. + captureActive() and not captureCompleted and + frame >= captureWaitFrames(waitFrames) + +proc captureFinished*(): bool = + ## Reports a successful capture while allowing the viewer to finish cleanup. + captureCompleted + +proc finishCapture*() = + ## Marks a successful write so extra native frame callbacks cannot overwrite it. + captureCompleted = true diff --git a/src/polyworld/shadows.nim b/src/polyworld/shadows.nim index 3c1ea4c3c..ca6814ba5 100644 --- a/src/polyworld/shadows.nim +++ b/src/polyworld/shadows.nim @@ -379,8 +379,11 @@ proc endSunDepthPass*(windowSize: IVec2) = template sunDepthPasses*(windowSize: IVec2, body: untyped) = ## Draws one map without a cross-fade, otherwise both neighboring maps. ## The injected sunPassIndex is 0 for the first map and 1 for the second. - ## Restores the window target and MSAA setting even if a draw fails. + ## Restores the caller's targets and MSAA setting even if a draw fails. if sunShadowsActive(): + var readFramebuffer, drawFramebuffer: GLint + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, readFramebuffer.addr) + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, drawFramebuffer.addr) when not defined(emscripten): let multisampleEnabled = glIsEnabled(GL_MULTISAMPLE) try: @@ -390,6 +393,8 @@ template sunDepthPasses*(windowSize: IVec2, body: untyped) = body finally: endSunDepthPass(windowSize) + glBindFramebuffer(GL_READ_FRAMEBUFFER, readFramebuffer.GLuint) + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, drawFramebuffer.GLuint) when not defined(emscripten): if multisampleEnabled == GL_TRUE: glEnable(GL_MULTISAMPLE) diff --git a/src/polyworld/stats.nim b/src/polyworld/stats.nim index df3b40f62..017bbdef0 100644 --- a/src/polyworld/stats.nim +++ b/src/polyworld/stats.nim @@ -1,10 +1,7 @@ import - std/algorithm, + std/[algorithm, os], chroma, pixie, silky, vmath, windy, - actioncam, chrome, gameuis, inputs, metrics - -when defined(takeScreenshot): - import std/os + actioncam, chrome, gameuis, inputs, metrics, screenshots const StatsWidth* = 1440.0'f @@ -281,9 +278,8 @@ proc drawStats*(sk: Silky, window: Window, layout: GameUiLayout, state: var StatsState, current: StatsTable, history: MetricHistory, options = StatsOptions()) = ## Draws the overlay after the normal world, HUD, and transport pass. - when defined(takeScreenshot): - if existsEnv("SHOW_STATS"): - state.toggled = true + if captureActive() and existsEnv("SHOW_STATS"): + state.toggled = true let table = state.displayedTable( current, window.buttonPressed[KeySpace] or @@ -468,9 +464,8 @@ proc drawStatsOverlay*(sk: Silky, window: Window, layout: GameUiLayout, state: var StatsState, current: StatsTable, history: MetricHistory, options = StatsOptions()) = ## Draws the readable overlay in its own pass after the ordinary HUD. - when defined(takeScreenshot): - if existsEnv("SHOW_STATS"): - state.toggled = true + if captureActive() and existsEnv("SHOW_STATS"): + state.toggled = true if not state.visible(window.tabHeld): return let diff --git a/src/polyworld/tapes.nim b/src/polyworld/tapes.nim index 750e322bf..e32f0af48 100644 --- a/src/polyworld/tapes.nim +++ b/src/polyworld/tapes.nim @@ -152,10 +152,15 @@ proc saveReplayFile*[T]( data: T, maxBytes = DefaultMaxReplayBytes ) = - ## Writes one game payload with the common Polyworld header. + ## Writes a validated replay, creating its parent directories as needed. if path.len == 0: fail("replay output path is empty") - writeFile(path, encodeReplayFile(game, gameVersion, data, maxBytes)) + let + bytes = encodeReplayFile(game, gameVersion, data, maxBytes) + directory = path.parentDir + if directory.len > 0: + createDir(directory) + writeFile(path, bytes) proc loadReplayFile*[T]( path, diff --git a/src/polyworld/viewers.nim b/src/polyworld/viewers.nim index 2dddca4cd..95d9e9b41 100644 --- a/src/polyworld/viewers.nim +++ b/src/polyworld/viewers.nim @@ -3,7 +3,9 @@ import std/[math, os, strutils, times], chroma, opengl, pixie, silky, vmath, windy, - actioncam, assets, fullscreens, player + actioncam, assets, fullscreens, player, screenshots + +export screenshots when defined(emscripten): {.emit: "#include ".} @@ -79,7 +81,7 @@ proc viewingDelta*(clock: var ViewingClock, window: Window): float32 = result = max(now - clock.last, 0).float32 clock.last = now clock.hidden = hidden - when defined(takeScreenshot): + if captureActive(): result = 1.0'f / 60 proc damping*(rate, dt: float32): float32 = @@ -166,8 +168,8 @@ proc initGameWindow*( let window = newWindow( title, size, - visible = visible and not defined(takeScreenshot), - vsync = vsync, + visible = visible and not captureActive(), + vsync = vsync and not captureActive(), msaa = msaa ) window.prepareDesktopFullscreen() @@ -222,7 +224,7 @@ proc holdSplash*( seconds = SplashSeconds ) = ## Keeps the splash up until the hold time elapses. - when defined(takeScreenshot) or defined(emscripten): + if captureActive() or defined(emscripten): drawSplash(sk, window, splash.name) else: while epochTime() - splash.startedAt < seconds: @@ -239,7 +241,7 @@ proc presentFrame*(window: Window, paceHz = 60) = ## Swaps the back buffer, then waits so presents stay on one cadence. ## ProMotion vsync alone flips between 8.33 ms and 16.67 ms. window.swapBuffers() - if paceHz <= 0: + if paceHz <= 0 or captureActive(): presentDeadline = 0 presentPaceHz = 0 return @@ -265,7 +267,7 @@ proc frameDelta*( let now = epochTime() result = clamp(now - lastFrameTime, 0.0, 0.1).float32 lastFrameTime = now - when defined(takeScreenshot): + if captureActive(): result = captureStep proc simulationActive*(transport: Player): bool = @@ -278,44 +280,118 @@ proc atLiveTickCap*(tick, maximumTicks: int32, live: bool): bool = proc applyScreenshotCamera*(cameraDistance: var float32) = ## Overrides camera distance from CAM_DIST when capturing. - when defined(takeScreenshot): + if captureActive(): if existsEnv("CAM_DIST"): cameraDistance = getEnv("CAM_DIST").parseFloat.float32 + +type ScreenshotTarget* = object + ## Owns a native offscreen color and depth target for hidden capture windows. + framebuffer*, texture*, depth*: GLuint + size*: IVec2 + +proc releaseScreenshotTarget*(target: var ScreenshotTarget) = + ## Releases capture attachments while their owning GL context is current. + if target.depth != 0: + glDeleteRenderbuffers(1, target.depth.addr) + if target.texture != 0: + glDeleteTextures(1, target.texture.addr) + if target.framebuffer != 0: + glDeleteFramebuffers(1, target.framebuffer.addr) + target = ScreenshotTarget() + +proc beginScreenshotFrame*( + target: var ScreenshotTarget, window: Window, enabled = captureActive() +): GLuint = + ## Binds a complete hidden-window target without relying on its drawable. + if not enabled: + return 0 + let size = window.size + if size.x <= 0 or size.y <= 0: + raise newException(ScreenshotError, "Screenshot window has no drawable size") + if target.framebuffer == 0 or target.size != size: + target.releaseScreenshotTarget() + glGenFramebuffers(1, target.framebuffer.addr) + glBindFramebuffer(GL_FRAMEBUFFER, target.framebuffer) + glGenTextures(1, target.texture.addr) + glBindTexture(GL_TEXTURE_2D, target.texture) + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8.GLint, size.x.GLsizei, + size.y.GLsizei, 0, GL_RGBA, GL_UNSIGNED_BYTE, nil) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR.GLint) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR.GLint) + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, target.texture, 0) + glGenRenderbuffers(1, target.depth.addr) + glBindRenderbuffer(GL_RENDERBUFFER, target.depth) + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, + size.x.GLsizei, size.y.GLsizei) + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, + GL_RENDERBUFFER, target.depth) + if glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE: + target.releaseScreenshotTarget() + raise newException(ScreenshotError, + "Unable to allocate screenshot framebuffer") + target.size = size else: - discard cameraDistance + glBindFramebuffer(GL_FRAMEBUFFER, target.framebuffer) + glViewport(0, 0, size.x.GLsizei, size.y.GLsizei) + target.framebuffer + +proc writeScreenshot*(window: Window, path: string) = + ## Writes the current draw target and creates its parent directory if needed. + if path.len == 0: + raise newException(ScreenshotError, "Screenshot output path is empty") + let + size = window.size + image = newImage(size.x, size.y) + directory = path.parentDir + var + previousRead, drawing, readBuffer, packAlignment: GLint + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, previousRead.addr) + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, drawing.addr) + glBindFramebuffer(GL_READ_FRAMEBUFFER, drawing.GLuint) + glGetIntegerv(GL_READ_BUFFER, readBuffer.addr) + glGetIntegerv(GL_PACK_ALIGNMENT, packAlignment.addr) + defer: + glPixelStorei(GL_PACK_ALIGNMENT, packAlignment) + glReadBuffer(readBuffer.GLenum) + glBindFramebuffer(GL_READ_FRAMEBUFFER, previousRead.GLuint) + glReadBuffer(if drawing == 0: GL_BACK else: GL_COLOR_ATTACHMENT0) + glPixelStorei(GL_PACK_ALIGNMENT, 1) + glReadPixels(0, 0, size.x.GLsizei, size.y.GLsizei, + GL_RGBA, GL_UNSIGNED_BYTE, image.data[0].addr) + image.flipVertical() + try: + if directory.len > 0: + createDir(directory) + image.writeFile(path) + except CatchableError as error: + raise newException(ScreenshotError, + "Could not save screenshot: " & error.msg) + +proc captureFrame*( + window: Window, frame: var int, waitFrames = DefaultScreenshotFrames, + defaultPath = "screenshot.png" +): bool = + ## Saves the selected rendered frame and lets the game perform normal cleanup. + if not captureActive(): + return false + if captureFinished(): + return true + inc frame + if not captureDue(frame, waitFrames): + return false + let path = capturePath(defaultPath) + window.writeScreenshot(path) + finishCapture() + echo "Saved screenshot: ", path + true proc captureScreenshot*( - window: Window, - frame: var int, - waitFrames: int, - defaultPath: string + window: Window, frame: var int, waitFrames: int, defaultPath: string ) = - ## Writes one back-buffer capture after waitFrames when capturing. - when defined(takeScreenshot): - inc frame - if frame < waitFrames: - return - let - path = - if existsEnv("SCREENSHOT_PATH"): - getEnv("SCREENSHOT_PATH") - else: - defaultPath - image = newImage(window.size.x, window.size.y) - glReadPixels( - 0, - 0, - window.size.x.GLsizei, - window.size.y.GLsizei, - GL_RGBA, - GL_UNSIGNED_BYTE, - image.data[0].addr - ) - image.flipVertical() - image.writeFile(path) + ## Preserves the standalone developer capture hook that exits after saving. + if captureFrame(window, frame, waitFrames, defaultPath): quit(0) - else: - discard (window, frame, waitFrames, defaultPath) proc reportReplayFrame*(tick, mismatches: int32) = ## Reports browser readiness and divergence after presenting a game frame. diff --git a/src/polyworld/waters.nim b/src/polyworld/waters.nim index d797507c2..5ba45384c 100644 --- a/src/polyworld/waters.nim +++ b/src/polyworld/waters.nim @@ -638,9 +638,14 @@ proc buildShoreFields*() = else: ShoreField() proc captureScene*(size: IVec2) {.measure.} = - ## Copies the window's colour and depth into colorCopy and depthCopy. The depth texture - ## matches the window's 24-bit depth, 8-bit stencil format, which a depth blit requires; - ## a multisampled window is resolved by the blit. + ## Copies the current scene's colour and 24-bit depth into the water textures. + ## Preserves the caller's targets, including an offscreen screenshot buffer. + var readFramebuffer, drawFramebuffer: GLint + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, readFramebuffer.addr) + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, drawFramebuffer.addr) + defer: + glBindFramebuffer(GL_READ_FRAMEBUFFER, readFramebuffer.GLuint) + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, drawFramebuffer.GLuint) if size != sceneCopySize: sceneCopySize = size glBindTexture(GL_TEXTURE_2D, depthCopy) @@ -665,11 +670,10 @@ proc captureScene*(size: IVec2) {.measure.} = depthCopy, 0) if glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE: raise newException(ValueError, "water scene-copy framebuffer is incomplete") - glBindFramebuffer(GL_READ_FRAMEBUFFER, 0) + glBindFramebuffer(GL_READ_FRAMEBUFFER, drawFramebuffer.GLuint) glBindFramebuffer(GL_DRAW_FRAMEBUFFER, sceneCopyFbo) glBlitFramebuffer(0, 0, size.x, size.y, 0, 0, size.x, size.y, GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT, GL_NEAREST.GLenum) - glBindFramebuffer(GL_FRAMEBUFFER, 0) proc reflecting*(params: WaterParams): bool = ## Whether this water shows reflections, so it needs its reflection pass. diff --git a/tests/all.nim b/tests/all.nim index b0c085e36..54f22fe97 100644 --- a/tests/all.nim +++ b/tests/all.nim @@ -11,12 +11,17 @@ import ../games/gods_of_the_arena/tests/test_abilities as TestGotaAbilities import determinism import test_cli, + test_screenshots, ../games/crewrift/tests/test_sim as TestCrewrift, ../games/crewrift/tests/test_bots as TestCrewriftBots, ../games/crewrift/tests/test_skins as TestCrewriftSkins, test_annotations, test_policy_hosts, test_tapes, + test_replaysettings, + test_replaysaves, + test_replaylibraries, + test_replay_browser, test_policy_packages, test_tensors, ../games/gods_of_the_arena/tests/test_tensor_matches as TestTensorMatches, @@ -28,6 +33,8 @@ import ../games/gods_of_the_arena/tests/test_observations as TestGotaObservations, ../games/gods_of_the_arena/tests/test_targets as TestGotaTargets, ../games/gods_of_the_arena/tests/test_replays as TestGotaReplays, + ../games/gods_of_the_arena/tests/test_replay_library as TestGotaReplayLibrary, + ../games/gods_of_the_arena/tests/test_recording_library as TestGotaRecordingLibrary, ../games/gods_of_the_arena/tests/test_attacks as TestGotaAttacks, ../games/gods_of_the_arena/tests/test_decisions as TestGotaDecisions, ../games/gods_of_the_arena/tests/test_events as TestGotaEvents, @@ -65,6 +72,8 @@ import ../games/gods_of_the_arena/tests/test_auto_seats as TestGotaAutoSeats, ../games/gods_of_the_arena/tests/test_match_notice_network as TestGotaLocalNotices, ../games/light_vs_dark/tests/test_live_slots as TestLvdLiveSlots, + ../games/light_vs_dark/tests/test_replay_library as TestLvdReplayLibrary, + ../games/light_vs_dark/tests/test_recording_library as TestLvdRecordingLibrary, ../games/light_vs_dark/tests/test_match_clock as TestLvdLocalNotices, ../games/cac/tests/test_network as TestCacNetwork, ../games/cac/tests/test_network_catchup as TestCacCatchup diff --git a/tests/browser_cac_audio.cjs b/tests/browser_cac_audio.cjs index 074719d32..1aa8fb7ad 100644 --- a/tests/browser_cac_audio.cjs +++ b/tests/browser_cac_audio.cjs @@ -88,7 +88,7 @@ async function nextHumanTurn(page) { await delay(300); } async function startGame(page,mode) { - await page.goto(mode==='duel'?url+'?human=1&players=2&seed=42':url, + await page.goto(mode==='duel'?url+'?player=1&players=2&seed=42':url, {waitUntil:'load',timeout:120000}); await page.waitForFunction(()=>document.querySelector('#loading')?.hidden, null,{timeout:120000}); diff --git a/tests/browser_cac_modal.cjs b/tests/browser_cac_modal.cjs index bbced2ac4..9160c617c 100644 --- a/tests/browser_cac_modal.cjs +++ b/tests/browser_cac_modal.cjs @@ -97,7 +97,7 @@ async function runCase(browser,mode) { page.on('pageerror',error=>result.errors.push(String(error))); page.on('console',message=>{if(message.type()==='error')result.errors.push(message.text());}); try { - await page.goto(mode==='duel'?url+'?human=1&players=2&seed=42':url,{waitUntil:'load',timeout:120000}); + await page.goto(mode==='duel'?url+'?player=1&players=2&seed=42':url,{waitUntil:'load',timeout:120000}); await page.waitForFunction(()=>document.querySelector('#loading')?.hidden,null,{timeout:120000}); if(mode==='ring') await startRing(page,result); else { diff --git a/tests/manual_bars.nim b/tests/manual_bars.nim new file mode 100644 index 000000000..8eb8e75ad --- /dev/null +++ b/tests/manual_bars.nim @@ -0,0 +1,119 @@ +## Captures actual themed bars for local visual inspection, outside CI. +## Run with an optional output directory; each image uses native GL pixels. + +import + std/[os, strformat], + chroma, opengl, silky, vmath, windy, + polyworld/[actioncam, chrome, gameuis, player, viewers] + +const + CanvasSize = vec2(1600, 800) + BarWidth = 164.0'f + ColumnWidth = 190.0'f + Purple = rgbx(151, 82, 199, 255) + Blue = rgbx(96, 132, 190, 255) + Green = rgbx(92, 185, 101, 255) + Captures = [ + (0.5'f, "0.5"), (1.0'f, "1"), (1.25'f, "1.25"), (2.0'f, "2") + ] + Heights = [6.0'f, 12.0'f, 24.0'f] + Colors = [("Replay", Purple), ("Playback", Blue), ("Resource", Green)] + Labels = ["Zero", "0.25 px", "1 px", "2 px", "5 px", "50%", "100%"] + FillPixels = [0.0'f, 0.25'f, 1.0'f, 2.0'f, 5.0'f] + EdgeLabels = ["1 px", "2 px", "3 px", "9 px", "10 px", "11 px", "12 px"] + EdgePixels = [1.0'f, 2.0'f, 3.0'f, 9.0'f, 10.0'f, 11.0'f, 12.0'f] + +proc drawMatrix(sk: Silky, edges: bool) = + ## Draws the production bar primitive using requested physical fill widths. + sk.drawLabel("Actual theme bars", vec2(24, 16), vec2(600, 32), font = "H1") + sk.drawLabel( + "Columns request physical fill pixels; rows use logical bar heights.", + vec2(24, 54), vec2(900, 24) + ) + let labels = if edges: EdgeLabels else: Labels + for column, label in labels: + sk.drawLabel(label, vec2(240 + column.float32 * ColumnWidth, 82), + vec2(BarWidth, 24)) + for colorIndex, (name, color) in Colors: + for heightIndex, height in Heights: + let + row = colorIndex * Heights.len + heightIndex + position = vec2(240, 120 + row.float32 * 42) + inset = min(3.0'f, height / 6) + innerWidth = BarWidth - inset * 2 + sk.drawLabel(name & " h=" & $height.int, + vec2(24, position.y - 8), vec2(200, 28), color) + for column in 0 ..< Labels.len: + let ratio = + if edges: + EdgePixels[column] / sk.uiScale / innerWidth + elif column < FillPixels.len: + FillPixels[column] / sk.uiScale / innerWidth + elif column == 5: + 0.5'f + else: + 1.0'f + sk.drawBar(position + vec2(column.float32 * ColumnWidth, 0), + vec2(BarWidth, height), ratio, 1, color) + +proc drawTransports(sk: Silky, window: Window) = + ## Draws real shared live transports, including the six-pixel purple strip. + var + actionCam = ActionCam() + followSelection = false + transport = initPlayer(live = true, durationTicks = 10000) + transport.sync(3500, 5000, false) + sk.drawLabel("Production live transport / half recorded", vec2(24, 518), + vec2(900, 24)) + transport.drawTransport(sk, window, + GameUiPanel(origin: vec2(16, 550), size: vec2(1568, TransportHeight)), + actionCam, followSelection) + transport.sync(1, 35, false) + sk.drawLabel("Production live transport / tiny recorded fill", vec2(24, 650), + vec2(900, 24)) + transport.drawTransport(sk, window, + GameUiPanel(origin: vec2(16, 682), size: vec2(1568, TransportHeight)), + actionCam, followSelection) + +proc captureBars(directory: string, scale: float32, label: string, + edges: bool) = + ## Renders into the shared hidden target and saves its untouched framebuffer. + let + suffix = if edges: "-edges" else: "" + path = directory / "bars-scale-" & label & suffix & ".png" + size = (CanvasSize * scale).ivec2 + configureCapture(ScreenshotOptions(path: path, frames: 1)) + let window = newWindow("Small bar visual diagnostic", size, + visible = false, vsync = false, msaa = msaaDisabled) + defer: + window.close() + window.makeContextCurrent() + loadExtensions() + let builder = newHudAtlas(2048) + builder.addDefaultFonts() + let sk = newSilky(window, builder.atlasImage, builder.atlas) + sk.applyThemePatches() + sk.uiScale = scale + var + target: ScreenshotTarget + frame: int + defer: + target.releaseScreenshotTarget() + discard target.beginScreenshotFrame(window) + sk.beginUi(window, window.size) + sk.clearScreen(rgbx(20, 23, 30, 255)) + sk.drawMatrix(edges) + sk.drawTransports(window) + sk.endUi() + doAssert glGetError() == GL_NO_ERROR + doAssert window.captureFrame(frame) + echo &"Captured scale {scale}: {window.size.x}x{window.size.y}" + +let outputDirectory = + if paramCount() > 0: + absolutePath(paramStr(1)) + else: + getTempDir() / "polyworld-small-bars" / "current" +for (scale, label) in Captures: + captureBars(outputDirectory, scale, label, false) + captureBars(outputDirectory, scale, label, true) diff --git a/tests/test_bars.nim b/tests/test_bars.nim new file mode 100644 index 000000000..8b359d953 --- /dev/null +++ b/tests/test_bars.nim @@ -0,0 +1,121 @@ +import + std/math, + vmath, + polyworld/bars + +const + Tolerance = 0.0001'f + Scales = [0.25'f, 0.5'f, 1.0'f, 1.25'f, 2.0'f, 4.0'f] + Widths = [0.1'f, 0.4'f, 1.0'f, 2.0'f, 3.0'f, 9.0'f, 10.0'f, + 11.0'f, 12.0'f, 61.3'f, 240.0'f] + Heights = [0.1'f, 0.4'f, 1.0'f, 2.0'f, 3.0'f, 4.0'f, 6.0'f, + 12.0'f, 18.0'f, 23.0'f, 29.0'f] + +proc close(a, b: float32): bool = + ## Compares geometry despite floating-point pixel conversions. + abs(a - b) < Tolerance + +proc aligned(bounds: BarRect, scale: float32): bool = + ## Checks both edges against the framebuffer pixel grid. + for point in [bounds.position, bounds.position + bounds.size]: + let pixel = point * scale + if not close(pixel.x, round(pixel.x)) or + not close(pixel.y, round(pixel.y)): + return false + true + +proc contained(inner, outer: BarRect): bool = + ## Checks that a rectangle stays within the requested bar. + let + innerEnd = inner.position + inner.size + outerEnd = outer.position + outer.size + inner.size.x >= 0 and inner.size.y >= 0 and + inner.position.x >= outer.position.x - Tolerance and + inner.position.y >= outer.position.y - Tolerance and + innerEnd.x <= outerEnd.x + Tolerance and + innerEnd.y <= outerEnd.y + Tolerance + +echo "Testing empty and pixel-aligned bar bounds" +block: + for scale in Scales: + for size in [vec2(0, 6), vec2(6, 0), vec2(-1, 6), vec2(6, -1)]: + doAssert barBounds(vec2(12, 20), size, scale).size == vec2(0) + for width in Widths: + for height in Heights: + let + bounds = barBounds(vec2(-12.3, 20.2), vec2(width, height), scale) + shifted = barBounds(vec2(12.8, 20.7), vec2(width, height), scale) + doAssert aligned(bounds, scale) + doAssert bounds.size == shifted.size + doAssert abs(bounds.size.x - width) <= 0.5'f / scale + Tolerance + doAssert abs(bounds.size.y - height) <= 0.5'f / scale + Tolerance + +echo "Testing tiny fills remain inside their tracks" +block: + for scale in Scales: + for width in Widths: + for height in Heights: + let track = barBounds(vec2(12.2, 20.3), vec2(width, height), scale) + doAssert barFill(track, 0, scale).size == vec2(0) + doAssert barFill(track, -1, scale).size == vec2(0) + var previousWidth = 0.0'f + for ratio in [0.0001'f, 0.01'f, 0.1'f, 0.5'f, 1.0'f, 2.0'f]: + let fill = barFill(track, ratio, scale) + if track.size.x <= 0 or track.size.y <= 0: + doAssert fill.size == vec2(0) + continue + doAssert contained(fill, track) + doAssert aligned(fill, scale) + doAssert fill.size.x * scale >= 1 - Tolerance + doAssert fill.size.y * scale >= 1 - Tolerance + doAssert fill.size.x >= previousWidth + previousWidth = fill.size.x + doAssert barFill(track, 1, scale) == barFill(track, 2, scale) + +echo "Testing textured slices cover bars without overlapping" +block: + for scale in Scales: + for width in Widths: + for height in Heights: + let bounds = barBounds(vec2(12.2, 20.3), vec2(width, height), scale) + for source in [(size: vec2(65, 29), cap: 7.0'f), + (size: vec2(59, 23), cap: 5.0'f)]: + let slices = barSlices(bounds, source.size, source.cap, scale) + if bounds.size.x <= 0 or bounds.size.y <= 0: + for slice in slices: + doAssert slice.bounds.size == vec2(0) + continue + var nextX = bounds.position.x + for slice in slices: + doAssert contained(slice.bounds, bounds) + doAssert aligned(slice.bounds, scale) + doAssert close(slice.bounds.position.x, nextX) + doAssert close(slice.bounds.position.y, bounds.position.y) + doAssert close(slice.bounds.size.y, bounds.size.y) + nextX += slice.bounds.size.x + doAssert close(nextX, bounds.position.x + bounds.size.x) + doAssert slices[0].sourcePosition == vec2(0) + doAssert slices[0].sourceSize == vec2(source.cap, source.size.y) + doAssert slices[2].sourcePosition == + vec2(source.size.x - source.cap, 0) + doAssert slices[2].sourceSize == slices[0].sourceSize + doAssert slices[1].sourceSize == vec2(0, source.size.y) + doAssert close(slices[1].sourcePosition.x, + floor(source.size.x / 2) + 0.5'f) + doAssert slices[1].sourcePosition.y == 0 + +echo "Testing source density preserves destination geometry" +block: + for scale in Scales: + for width in Widths: + let bounds = barBounds(vec2(12, 20), vec2(width, 6), scale) + for cap in [5.0'f, 10.0'f]: + let + ordinary = barSlices(bounds, vec2(59, 23), cap, scale) + dense = barSlices(bounds, vec2(118, 46), cap * 2, scale) + for i in 0 ..< ordinary.len: + doAssert ordinary[i].bounds == dense[i].bounds + if bounds.size.x > 0 and bounds.size.y > 0: + doAssert dense[i].sourceSize == ordinary[i].sourceSize * 2 + +echo "Bar geometry tests passed" diff --git a/tests/test_chats.nim b/tests/test_chats.nim index f95f96ce3..45a084b76 100644 --- a/tests/test_chats.nim +++ b/tests/test_chats.nim @@ -15,9 +15,13 @@ import ../games/light_vs_dark/maps as lvdMaps import ../games/light_vs_dark/sim as lvdSim const Program = """ +publicText$ = pullMailbox$() +publicId = mailboxId() sent = sendChat(mailboxSelf(), "private hello") message$ = pullMailbox$() from = mailboxId() +empty$ = pullMailbox$() +afterEmpty = mailboxId() """ const CtaProgram = """ @@ -80,6 +84,8 @@ proc checkMailboxes[T](game: T) = while inbox.count > 0: discard inbox.pop() for tick in 1 .. 300: + when T isnot ctaSim.Game: + doAssert send(0, -2, "public hello") == game.inboxes.len game.world.tick = int32(tick) when T is ctaSim.Game: for slot in 0'i32 ..< ctaContent.PartySize: @@ -103,6 +109,10 @@ proc checkMailboxes[T](game: T) = "nearby hello" else: doAssert vm.runtime.getGlobal("sent") == 1 + doAssert vm.runtime.getStringGlobal("publicText$") == "public hello" + doAssert vm.runtime.getGlobal("publicId") == -2 + doAssert vm.runtime.getStringGlobal("empty$") == "" + doAssert vm.runtime.getGlobal("afterEmpty") == NoMailboxId doAssert vm.runtime.getGlobal("from") == index doAssert vm.runtime.getString(vm.runtime.getGlobalValue("message$")) == "private hello" diff --git a/tests/test_cli.nim b/tests/test_cli.nim index 727dd6a6f..7b49fa12b 100644 --- a/tests/test_cli.nim +++ b/tests/test_cli.nim @@ -1,5 +1,5 @@ import - std/os, + std/[os, strutils], polyworld/cli proc parseCommon( @@ -85,13 +85,14 @@ block: index = 0 doAssert not options.takeCommonFlag(@["--view"], index, "--view") doAssert not options.takeCommonFlag(@["--help"], index, "--help") - doAssert not options.takeCommonFlag(@["--verbose"], index, "--verbose") + doAssert not options.takeCommonFlag(@["--custom"], index, "--custom") + doAssert index == 0 echo "Testing extra flags in the same loop as shared ones" block: var options = GameOptions(seed: 2026, maximumTicks: 100) - arguments = @["--seed", "9", "--verbose"] + arguments = @["--seed", "9", "--custom-verbose"] index = 0 verbose = false while index < arguments.len: @@ -100,7 +101,7 @@ block: discard else: case argument - of "--verbose": + of "--custom-verbose": verbose = true else: doAssert false, "unexpected argument: " & argument @@ -147,53 +148,74 @@ block: echo "Testing --play=false starts the transport paused" block: - let paused = parseCommon(@["--play=false", "--bot:one.bas"]) - doAssert paused.pauseOnStart - let playing = parseCommon(@["--play=true", "--bot:one.bas"]) - doAssert not playing.pauseOnStart + when not defined(headless): + let paused = parseCommon(@["--play=false", "--bot:one.bas"]) + doAssert paused.pauseOnStart + let playing = parseCommon(@["--play=true", "--bot:one.bas"]) + doAssert not playing.pauseOnStart echo "Testing --speed is a shared flag" block: - let options = parseCommon(@["--speed", "4", "--bot:one.bas"]) - doAssert options.speed == 4 - let compact = parseCommon(@["--speed=16", "--bot:one.bas"]) - doAssert compact.speed == 16 + when not defined(headless): + let options = parseCommon(@["--speed", "4", "--bot:one.bas"]) + doAssert options.speed == 4 + let compact = parseCommon(@["--speed=16", "--bot:one.bas"]) + doAssert compact.speed == 16 echo "Testing --player occupies one slot" block: - let options = parseCommon( - @["--player", "--bot:one.bas:9"], - liveBotCount = 10, - liveBotMessage = "need ten bots" - ) - doAssert options.playerSlot == 1 - doAssert options.botGroups.botCount == 9 + when not defined(headless): + let options = parseCommon( + @["--player", "--bot:one.bas:9"], + liveBotCount = 10, + liveBotMessage = "need ten bots" + ) + doAssert options.playerSlot == 1 + doAssert options.botGroups.botCount == 9 echo "Testing --player:N compact and equals forms" block: - let compact = parseCommon( - @["--player:2", "--bot:one.bas:3"], - liveBotCount = 4, - liveBotMessage = "need four bots" - ) - doAssert compact.playerSlot == 2 - let equals = parseCommon( - @["--player=1", "--bot:one.bas"], - liveBotCount = 2, - liveBotMessage = "need two bots" - ) - doAssert equals.playerSlot == 1 + when not defined(headless): + let compact = parseCommon( + @["--player:2", "--bot:one.bas:3"], + liveBotCount = 4, + liveBotMessage = "need four bots" + ) + doAssert compact.playerSlot == 2 + let equals = parseCommon( + @["--player=1", "--bot:one.bas"], + liveBotCount = 2, + liveBotMessage = "need two bots" + ) + doAssert equals.playerSlot == 1 + +echo "Testing the first explicit player overrides configured defaults" +block: + var + options = GameOptions(playerSlot: 3) + index = 0 + doAssert options.takeCommonFlag(@["--player", "2"], index, "--player") + doAssert options.playerSlot == 2 + doAssert options.specifiedFlags == {PlayerFlag} + index = 0 + var rejected = false + try: + discard options.takeCommonFlag(@["--player=1"], index, "--player=1") + except CliError as error: + rejected = "only one --player" in error.msg + doAssert rejected echo "Testing --vsync is on by default" block: - let options = parseCommon(@["--bot:one.bas"]) - doAssert options.vsync - let off = parseCommon(@["--vsync:off", "--bot:one.bas"]) - doAssert not off.vsync - let on = parseCommon(@["--vsync=on", "--bot:one.bas"]) - doAssert on.vsync - let split = parseCommon(@["--vsync", "off", "--bot:one.bas"]) - doAssert not split.vsync + when not defined(headless): + let options = parseCommon(@["--bot:one.bas"]) + doAssert options.vsync + let off = parseCommon(@["--vsync:off", "--bot:one.bas"]) + doAssert not off.vsync + let on = parseCommon(@["--vsync=on", "--bot:one.bas"]) + doAssert on.vsync + let split = parseCommon(@["--vsync", "off", "--bot:one.bas"]) + doAssert not split.vsync echo "Testing launch audio uses saved settings unless explicitly overridden" block: @@ -227,14 +249,195 @@ block: echo "Testing --windowSize is a shared flag" block: - let options = parseCommon(@["--windowSize:800x400", "--bot:one.bas"]) - doAssert options.windowWidth == 800 - doAssert options.windowHeight == 400 - let split = parseCommon(@["--windowSize", "1024x576", "--bot:one.bas"]) - doAssert split.windowWidth == 1024 - doAssert split.windowHeight == 576 - let equals = parseCommon(@["--windowSize=1280x720", "--bot:one.bas"]) - doAssert equals.windowWidth == 1280 - doAssert equals.windowHeight == 720 + when not defined(headless): + let options = parseCommon(@["--windowSize:800x400", "--bot:one.bas"]) + doAssert options.windowWidth == 800 + doAssert options.windowHeight == 400 + let split = parseCommon(@["--windowSize", "1024x576", "--bot:one.bas"]) + doAssert split.windowWidth == 1024 + doAssert split.windowHeight == 576 + let equals = parseCommon(@["--windowSize=1280x720", "--bot:one.bas"]) + doAssert equals.windowWidth == 1280 + doAssert equals.windowHeight == 720 + +echo "Testing all shared value forms describe identical options" +block: + for (flag, value) in [ + ("--bot", "bots/base.bas:2"), + ("--bots", "C:\\bots\\base.bas:2"), + ("--name", "Ada Lovelace"), + ("--replay", "replays/a match.replay"), + ("--record", "replays/a match.replay"), + ("--seed", "-7"), + ("--play", "false"), + ("--speed", "3"), + ("--windowSize", "1234x768"), + ("--vsync", "off"), + ("--seconds", "2"), + ("--minutes", "2"), + ("--ticks", "2"), + ("--mute", "false"), + ("--unmute", "false"), + ("--verbose", "false"), + ("--headless-tick-rate", "0"), + ("--llm-mode", "barrier"), + ("--frames", "3"), + ("--server", "ws://localhost:9911/ws"), + ("--room", "123456"), + ("--join", "123456") + ]: + when defined(headless): + if flag in ["--name", "--play", "--speed", "--windowSize", "--vsync", "--frames"]: + continue + let separate = parseCommon(@[flag, value]) + for separator in ["=", ":"]: + doAssert separate == parseCommon(@[flag & separator & value]), flag + when not defined(headless): + for (flag, value) in [("--player", "2"), ("--screenshot", "a shot.png")]: + let separate = parseCommon(@[flag, value]) + for separator in ["=", ":"]: + doAssert separate == parseCommon(@[flag & separator & value]), flag + +proc rejects(arguments: seq[string], message: string, + defaults = GameOptions(seed: 2026)) = + ## Checks invalid launch requests without spawning processes or opening games. + var rejected = false + try: + discard parseCommon(arguments, defaults = defaults) + except CliError as error: + rejected = true + doAssert message in error.msg, error.msg + doAssert rejected, "Expected a CLI error for " & $arguments + +echo "Testing missing values do not consume the next option" +block: + for flag in ["--bot", "--bots", "--name", "--replay", "--record", "--seed", + "--speed", "--windowSize", "--seconds", "--minutes", "--ticks", + "--headless-tick-rate", "--llm-mode", "--screenshot", "--frames", + "--server", "--room", "--join"]: + rejects(@[flag], "requires a value") + rejects(@[flag & "="], "requires a value") + rejects(@[flag & ":"], "requires a value") + var + options: GameOptions + index = 0 + try: + discard options.takeCommonFlag(@[flag, "--seed", "7"], index, flag) + doAssert false + except CliError: + doAssert index == 0 + +echo "Testing common boolean defaults and explicit false values" +block: + let defaults = parseCommon(@[]) + doAssert defaults.speed == 1 and defaults.vsync + doAssert not defaults.pauseOnStart and not defaults.verbose + doAssert defaults.specifiedFlags == {} + let bare = parseCommon(@["--mute", "--verbose", "--seed", "9"]) + doAssert bare.soundMuted and bare.verbose and bare.seed == 9 + when not defined(headless): + let visual = parseCommon(@["--play", "--vsync", "--seed", "9"]) + doAssert visual.vsync and not visual.pauseOnStart and visual.seed == 9 + doAssert parseCommon(@["--unmute=false"]).soundMuted + doAssert not parseCommon(@["--verbose", "false"]).verbose + for flag in ["--mute", "--unmute", "--verbose", "--play", "--vsync"]: + rejects(@[flag & "="], "requires a value") + rejects(@[flag & ":maybe"], "true or false") + rejects(@[flag, "maybe"], "true or false") + +echo "Testing invalid player names, slots, numbers, and bot counts" +block: + rejects(@["--name", " "], "nonempty display name") + rejects(@["--name", repeat("n", 65)], "at most 64 bytes") + for name in ["Ada\n", "\tAda", "A\x00da", "Ada\x7f"]: + rejects(@["--name", name], "control characters") + for name in ["\xff", "\xc3", "\xc0\xaf", "A\x80da"]: + rejects(@["--name", name], "valid UTF-8") + when not defined(headless): + doAssert parseCommon(@["--name", "Игрок🌿"]).playerName == "Игрок🌿" + doAssert parseCommon(@["--name", repeat("é", 32)]).playerName == repeat("é", 32) + rejects(@["--name", repeat("é", 33)], "at most 64 bytes") + rejects(@["--player", "Ada"], "use --name") + rejects(@["--player=0"], "positive slot number") + rejects(@["--player", "-1"], "positive slot number") + rejects(@["--player", "--player"], "only one --player") + rejects(@["--seed", "2147483648"], "fit int32") + rejects(@["--seed", "9999999999999999999999999"], "integer") + rejects(@["--speed", "0"], "positive") + rejects(@["--headless-tick-rate", "-1"], "0 .. 10000") + rejects(@["--headless-tick-rate", "10001"], "0 .. 10000") + rejects(@["--llm-mode", "unknown"], "async or barrier") + for count in ["0", "-1", "", "bad", "2147483648", "9999999999999999999"]: + rejects(@["--bot", "bot.bas:" & count], "--bot count") + rejects(@["--bots", ":2"], "requires a path") + rejects(@["--bot", "a.bas:2147483647", "--bot", "b.bas"], "must total") + doAssert parseCommon(@["--bot", "C:2"]).botGroups[0].path == "C:2" + doAssert parseCommon(@["--headless-tick-rate", "10000"]).headlessTickRate == 10000 + when not defined(headless): + doAssert parseCommon(@["--name", " Ada "]).playerName == "Ada" + +echo "Testing replay incompatibilities and build restrictions" +block: + rejects(@["--replay", "a.replay", "--bots", "base.bas"], "cannot be used with --bot") + rejects(@["--replay", "a.replay", "--record", "b.replay"], "cannot be recorded") + for flag in ["--seconds", "--minutes", "--ticks", "--seed"]: + rejects(@["--replay", "a.replay", flag, "1"], "cannot be used with " & flag) + when defined(headless): + rejects(@["--player"], "requires the graphical client") + rejects(@["--screenshot", "a.png"], "requires a native graphical client") + for (flag, value) in [("--name", "Ada"), ("--play", "true"), ("--speed", "1"), + ("--windowSize", "800x600"), ("--vsync", "false"), ("--frames", "1")]: + rejects(@[flag, value], "requires the graphical client") + else: + rejects(@["--replay", "a.replay", "--player"], "cannot be used with --player") + var rejected = false + try: + discard parseCommon(@["--player", "3", "--bot", "base.bas"], 2) + except CliError as error: + rejected = "between 1 and 2" in error.msg + doAssert rejected + +echo "Testing durations use each game's configured simulation rate" +block: + for rate in [2'i32, 24'i32, 32'i32]: + let defaults = GameOptions(tickRate: rate) + doAssert parseCommon(@["--seconds", "3"], defaults = defaults).maximumTicks == 3 * rate + doAssert parseCommon(@["--minutes:2"], defaults = defaults).maximumTicks == 120 * rate + doAssert parseCommon(@["--ticks=96"], defaults = defaults).seconds == 96 div rate + let last = parseCommon(@["--minutes=2", "--ticks", "96"], defaults = defaults) + doAssert last.maximumTicks == 96 and last.seconds == 96 div rate + rejects(@["--minutes", "2147483647"], "too large") + rejects(@["--seconds", "2147483647"], "too large") + let zeroRate = GameOptions(tickRate: 0) + doAssert parseCommon(@["--seconds", "2"], defaults = zeroRate).maximumTicks == 2 * SharedTickRate + +echo "Testing explicit capabilities remain visible even for false and zero" +block: + let options = parseCommon(@["--verbose=false", "--headless-tick-rate=0", "--bots", "base.bas"]) + doAssert options.specifiedFlags == {VerboseFlag, HeadlessTickRateFlag, BotFlag} + options.rejectUnsupportedFlags(AllCommonFlags) + var rejected = false + try: + options.rejectUnsupportedFlags(AllCommonFlags - {VerboseFlag}) + except CliError as error: + rejected = "--verbose is not supported" in error.msg + doAssert rejected + let help = commonUsageFor({BotFlag, RecordFlag}) + doAssert "--bot PATH" in help and "--record PATH" in help + doAssert "--player" notin help and "--server" notin help + doAssert "--play [BOOL]" in CommonUsage + doAssert "--vsync [BOOL]" in CommonUsage + doAssert parseCommon(@["--room", "123"]) == parseCommon(@["--join=123"]) + doAssert parseCommon(@["--bot", "base.bas:2"]) == parseCommon(@["--bots=base.bas:2"]) + +echo "Testing launch paths resolve before changes to the working directory" +block: + var options = parseCommon(@["--bot", "bots/base.bas", "--record", "a match.replay"]) + options.resolveGamePaths() + doAssert options.botGroups[0].path == absolutePath("bots/base.bas") + doAssert options.recordPath == absolutePath("a match.replay") + var replay = parseCommon(@["--replay", "a match.replay"]) + replay.resolveGamePaths() + doAssert replay.replayPath == absolutePath("a match.replay") echo "Cli tests passed" diff --git a/tests/test_controllers.nim b/tests/test_controllers.nim index 2f7f20778..406442358 100644 --- a/tests/test_controllers.nim +++ b/tests/test_controllers.nim @@ -62,11 +62,26 @@ block: PlayerConfig(name: "turtle") ] -echo "Testing local names cannot be supplied through CLI options" +echo "Testing --name only renames the selected human controller" +block: + var + options = GameOptions(playerSlot: 2) + index = 0 + doAssert options.takeCommonFlag(@["--name", "Alice"], index, "--name") + options.botGroups.addBotSpec("bots/dragon.bas:2") + let config = options.localGameConfig(3) + doAssert config.players == @[ + PlayerConfig(name: "dragon"), + PlayerConfig(name: "Alice"), + PlayerConfig(name: "dragon") + ] + doAssert options.playerName == "Alice" + +echo "Testing unsupported naming aliases do not alter bot names" block: static: doAssert not compiles(GameOptions(playerNames: @["Override"])) - for flag in ["--name", "--player-name", "--playerName", "--player-names"]: + for flag in ["--player-name", "--playerName", "--player-names"]: var options: GameOptions index = 0 diff --git a/tests/test_player.nim b/tests/test_player.nim index a515eac51..ff7b72e38 100644 --- a/tests/test_player.nim +++ b/tests/test_player.nim @@ -140,6 +140,39 @@ block: doAssert speedIndexOf(16) == 3 doAssert speedIndexOf(64) == 3 +echo "Testing launch speeds remain exact until a preset is selected" +block: + for value in [3'i32, 8, 64]: + var p = initPlayer(live = true, durationTicks = 100, speed = value) + doAssert p.speed == value + p.setSpeed(2) + doAssert p.speed == 4 + p.setPlaybackSpeed(value) + doAssert p.speed == value + p.setSpeed(0) + doAssert p.speed == 1 + +echo "Testing realtime accumulation scales with the exact speed" +block: + var p = initPlayer(live = true, durationTicks = 1000, speed = 16) + p.startFrame(0.025, 24) + doAssert abs(p.accumulator - 0.4) < 0.00001 + p.setPlaybackSpeed(3) + p.accumulator = 0 + p.startFrame(0.02, 24) + doAssert abs(p.accumulator - 0.06) < 0.00001 + doAssert p.shouldTick(0) + +echo "Testing large realtime speeds still yield to the next frame" +block: + var p = initPlayer(live = true, durationTicks = int32.high, + speed = int32.high) + p.startFrame(0.1, 24) + let remaining = p.accumulator + doAssert not p.shouldTick(epochTime() - 1) + doAssert p.accumulator == remaining + doAssert p.shouldTick(epochTime()) + echo "Testing empty replay playback stays at tick zero" block: var p = initPlayer(live = false, durationTicks = 100) diff --git a/tests/test_replay_browser.nim b/tests/test_replay_browser.nim new file mode 100644 index 000000000..1a7a77426 --- /dev/null +++ b/tests/test_replay_browser.nim @@ -0,0 +1,112 @@ +import + std/[os, strutils, tempfiles], + polyworld/[replaylibraries, replaymenus, tapes] + +type BrowserReplay = object + formatVersion, gameVersion: uint16 + ticks: int + +proc inspectBrowserReplay(bytes: string): int = + ## Decodes a small fixture through the real shared replay container. + decodeReplayFile("browser_test", 7, bytes, BrowserReplay).ticks + +const BrowserLibrary = ReplayLibrary( + gameFolder: "Replay browser test", + gamePrefix: "Test", + format: ReplayLibraryFormat( + game: "browser_test", gameVersion: 7, tapeVersion: 2, + maxBytes: DefaultMaxReplayBytes + ), + inspect: inspectBrowserReplay +) + +proc browserBytes(version = 7'u16): string = + ## Produces current or obsolete fixtures with matching outer and inner versions. + encodeReplayFile("browser_test", version, + BrowserReplay(formatVersion: 2, gameVersion: version, ticks: 42)) + +proc testReplayBrowser() = + ## Exercises shared refresh, import, stale-file validation, and error recovery. + let + root = createTempDir("polyworld-replay-browser-", "") + folder = root / "library with spaces" + source = root / "source.replay" + bytes = browserBytes() + defer: + removeDir(root) + var browser = initReplayBrowser(BrowserLibrary, directory = folder) + doAssert not dirExists(folder) + doAssert browser.refreshRequested + doAssert browser.updateReplayBrowser(BrowserLibrary, + ReplayBrowserResult()).action == StayReplayBrowser + doAssert dirExists(folder) + doAssert not browser.refreshRequested + doAssert browser.entries.len == 0 + + writeFile(source, bytes) + browser.importBrowserReplay(BrowserLibrary, source) + let imported = browser.ui.selectedPath + doAssert imported.parentDir == folder + doAssert readFile(source) == bytes + doAssert browser.refreshRequested + doAssert browser.message == "Replay imported." + discard browser.updateReplayBrowser(BrowserLibrary, ReplayBrowserResult()) + doAssert browser.entries.len == 1 + doAssert browser.entries[0].ticks == 42 + doAssert browser.entries[0].playable + doAssert browser.ui.selectedPath == imported + let chosen = browser.updateReplayBrowser(BrowserLibrary, + ReplayBrowserResult(action: PlayReplay, path: imported)) + doAssert chosen.action == PlayReplay and chosen.path == imported + + browser.importBrowserReplay(BrowserLibrary, "") + doAssert browser.ui.selectedPath == imported + doAssert not browser.refreshRequested + doAssert browser.entries.len == 1 + + writeFile(imported, browserBytes(6)) + doAssert browser.entries[0].playable + doAssert browser.updateReplayBrowser(BrowserLibrary, + ReplayBrowserResult(action: PlayReplay, path: imported) + ).action == StayReplayBrowser + doAssert "Game version 6" in browser.message + discard browser.updateReplayBrowser(BrowserLibrary, + ReplayBrowserResult(action: RefreshReplays)) + doAssert browser.message.len == 0 + doAssert not browser.entries[0].playable + doAssert browser.entries[0].gameVersion == 6 + + let obsolete = root / "obsolete.replay" + writeFile(obsolete, browserBytes(6)) + browser.importBrowserReplay(BrowserLibrary, obsolete) + discard browser.updateReplayBrowser(BrowserLibrary, ReplayBrowserResult()) + doAssert browser.entries.len == 2 + for entry in browser.entries: + doAssert not entry.playable + doAssert readFile(obsolete) == browserBytes(6) + + removeFile(imported) + doAssert browser.updateReplayBrowser(BrowserLibrary, + ReplayBrowserResult(action: PlayReplay, path: imported) + ).action == StayReplayBrowser + doAssert browser.message.len > 0 + doAssert browser.updateReplayBrowser(BrowserLibrary, + ReplayBrowserResult(action: BackFromReplays) + ).action == BackFromReplays + doAssert browser.message.len == 0 + + browser.folder = source / "not a directory" + discard browser.updateReplayBrowser(BrowserLibrary, + ReplayBrowserResult(action: RefreshReplays)) + doAssert browser.message.len > 0 + doAssert not browser.refreshRequested + doAssert browser.entries.len == 2 + doAssert readFile(source) == bytes + browser.folder = folder + discard browser.updateReplayBrowser(BrowserLibrary, + ReplayBrowserResult(action: RefreshReplays)) + doAssert browser.message.len == 0 + doAssert browser.entries.len == 1 + +testReplayBrowser() +echo "Shared replay browser imports, refreshes, and playback validation passed." diff --git a/tests/test_replaylibraries.nim b/tests/test_replaylibraries.nim new file mode 100644 index 000000000..9e73342bd --- /dev/null +++ b/tests/test_replaylibraries.nim @@ -0,0 +1,43 @@ +import + std/[os, strutils, tempfiles], + polyworld/[replaylibraries, tapes] + +proc opaqueTicks(bytes: string): int = + ## Validates a direct game payload without an inner Polyworld tape header. + let data = decodeReplayFile("opaque", 7, bytes, string) + if data != "valid payload": + raise newException(ReplayError, "Invalid opaque replay payload.") + 42 + +proc testReplayPayloadHeaders() = + ## Requires explicit opaque payloads without weakening the default tape checks. + let root = createTempDir("polyworld-payload-headers-", "") + defer: removeDir(root) + var format = ReplayLibraryFormat( + game: "opaque", gameVersion: 7, tapeVersion: 2, + maxBytes: DefaultMaxReplayBytes + ) + let current = root / "current.replay" + writeFile(current, encodeReplayFile("opaque", 7, "valid payload")) + doAssert format.payloadHeader == TapePayloadHeader + let tape = inspectReplay(current, format, opaqueTicks) + doAssert not tape.playable and "Replay format" in tape.problem + format.payloadHeader = OpaquePayloadHeader + let direct = inspectReplay(current, format, opaqueTicks) + doAssert direct.playable and direct.ticks == 42 + doAssert direct.gameVersion == 7 and direct.tapeVersion == 0 + let old = root / "old.replay" + writeFile(old, encodeReplayFile("opaque", 6, "obsolete payload")) + let obsolete = inspectReplay(old, format, opaqueTicks) + doAssert not obsolete.playable and "Game version 6" in obsolete.problem + let invalid = root / "invalid.replay" + writeFile(invalid, encodeReplayFile("opaque", 7, "bad payload")) + let rejected = inspectReplay(invalid, format, opaqueTicks) + doAssert not rejected.playable and "Invalid opaque" in rejected.problem + writeFile(invalid, encodeReplayFile("another", 7, "valid payload")) + doAssert not inspectReplay(invalid, format, opaqueTicks).playable + writeFile(invalid, "POLYWORLDREPLAY") + doAssert not inspectReplay(invalid, format, opaqueTicks).playable + +testReplayPayloadHeaders() +echo "Shared tape and opaque replay payload header checks passed." diff --git a/tests/test_replaysaves.nim b/tests/test_replaysaves.nim new file mode 100644 index 000000000..8438cbaa2 --- /dev/null +++ b/tests/test_replaysaves.nim @@ -0,0 +1,108 @@ +import + std/[os, tempfiles], + polyworld/replaysaves + +type RecordedPrefix = object + hashes, actions: seq[int] + +proc testReplaySaves() = + ## Checks completion, manual retry, deduplication, and removed saved files. + let directory = createTempDir("polyworld-replay-saves-", "") + defer: removeDir(directory) + var + state: ReplaySaveState + writes = 0 + failWrite = false + data = RecordedPrefix(hashes: @[11, 22], actions: @[1]) + + proc save(data: RecordedPrefix): string = + ## Writes a real file while allowing a failed library write to be injected. + if failWrite: + raise newException(IOError, "Replay destination is unavailable.") + inc writes + result = directory / ($writes & ".replay") + writeFile(result, $data) + + doAssert not state.beginAutomaticReplaySave(false, true) + doAssert not state.beginAutomaticReplaySave(true, false) + doAssert not state.shouldSaveReplayOnExit(false) + doAssert state.shouldSaveReplayOnExit(true) + doAssert state.beginAutomaticReplaySave(true, true) + let first = state.saveReplaySnapshot(data, save) + doAssert writes == 1 and fileExists(first) + doAssert not state.saveRequested + doAssert not state.beginAutomaticReplaySave(true, true) + doAssert state.saveReplaySnapshot(data, save) == first + doAssert writes == 1, "Completion and exit must share the same saved prefix." + + data.actions.add(2) + let withChat = state.saveReplaySnapshot(data, save) + doAssert writes == 2 and withChat != first, + "Chat-only additions must make a new snapshot without another game tick." + removeFile(withChat) + let recreated = state.saveReplaySnapshot(data, save) + doAssert writes == 3 and fileExists(recreated), + "A removed replay must be recreated rather than reported as saved." + + data.hashes.add(33) + failWrite = true + var rejected = false + try: + discard state.saveReplaySnapshot(data, save) + except IOError: + rejected = true + doAssert rejected and state.saveRequested + doAssert state.savedPath == recreated + doAssert state.shouldSaveReplayOnExit(false), + "A failed manual save must survive automatic saving being disabled." + failWrite = false + doAssert state.saveReplaySnapshot(data, save) != recreated + doAssert writes == 4 and not state.saveRequested + doAssert not state.shouldSaveReplayOnExit(false) + + state.resetReplaySave() + doAssert state.savedPath.len == 0 and not state.saveRequested + doAssert state.beginAutomaticReplaySave(true, true) + discard state.saveReplaySnapshot(data, save) + doAssert writes == 5, "A new match cannot reuse its predecessor's snapshot." + state.resetReplaySave() + state.requestReplaySave() + doAssert state.shouldSaveReplayOnExit(false), + "A failure while capturing the recording must preserve manual intent." + let + libraryFailure = newException(ReplaySaveError, "Library is full.") + exportFailure = newException(ReplayExportError, "Export path is invalid.") + matchFailure = newException(IOError, "Match was interrupted.") + doAssert shouldRetainReplay(false, libraryFailure), + "The frontend must retain a failed manual save with automatic saving off." + doAssert shouldRetainReplay(true, libraryFailure) + doAssert shouldRetainReplay(true, matchFailure) + doAssert not shouldRetainReplay(false, matchFailure) + doAssert not shouldRetainReplay(true, exportFailure), + "A successful library save must not be queued again after an export fails." + +proc testPendingReplaySaves() = + ## Keeps failed and unattempted recordings after a partial retry succeeds. + var + pending = @[1, 2, 3] + saved: seq[int] + failure = 2 + proc save(data: int): string = + ## Records successful writes and fails at a chosen retained recording. + if data == failure: + raise newException(IOError, "Replay destination is full.") + saved.add(data) + $data + var rejected = false + try: + pending.retryReplaySaves(save) + except IOError: + rejected = true + doAssert rejected and saved == @[1] and pending == @[2, 3] + failure = 0 + pending.retryReplaySaves(save) + doAssert saved == @[1, 2, 3] and pending.len == 0 + +testReplaySaves() +testPendingReplaySaves() +echo "Shared replay save lifecycle tests passed." diff --git a/tests/test_replaysettings.nim b/tests/test_replaysettings.nim new file mode 100644 index 000000000..b250e8189 --- /dev/null +++ b/tests/test_replaysettings.nim @@ -0,0 +1,45 @@ +import + std/[monotimes, os, strutils], + windy, + polyworld/[menus, replaysettings] + +proc testReplayPreferences() = + ## Exercises shared recording preferences without touching any game's config. + let + app = "Polyworld replay preferences test " & $getCurrentProcessId() & + "-" & $getMonoTime().ticks + directory = getConfigHome(app) + otherSettings = """{"name":"Keep me","musicVolume":0}""" + doAssert not dirExists(directory) + defer: + if dirExists(directory): + removeDir(directory) + + echo "Testing replay recording defaults on and missing settings remain absent" + doAssert readReplayPreferences(app).saveReplay + doAssert not dirExists(directory) + doAssert decodeReplayPreferences("").saveReplay + doAssert decodeReplayPreferences("{}").saveReplay + doAssert decodeReplayPreferences("""{"futureSetting":17}""").saveReplay + + echo "Testing replay choices persist separately from other device settings" + setConfig(app, "settings.json", otherSettings) + for enabled in [false, true, false]: + ReplayPreferences(saveReplay: enabled).saveReplayPreferences(app) + doAssert readReplayPreferences(app).saveReplay == enabled + doAssert getConfig(app, "settings.json") == otherSettings + + echo "Testing invalid replay preferences report an error without replacement" + for malformed in ["{", """{"saveReplay":"yes"}"""]: + setConfig(app, "replays.json", malformed) + var rejected = false + try: + discard readReplayPreferences(app) + except MenusError as error: + rejected = error.msg.startsWith("Cannot read replay settings:") + doAssert rejected + doAssert getConfig(app, "replays.json") == malformed + doAssert getConfig(app, "settings.json") == otherSettings + +testReplayPreferences() +echo "Shared replay preference checks passed." diff --git a/tests/test_screenshots.nim b/tests/test_screenshots.nim new file mode 100644 index 000000000..05a991849 --- /dev/null +++ b/tests/test_screenshots.nim @@ -0,0 +1,204 @@ +import + std/os, + polyworld/[cli, screenshots] + +proc parseCapture(arguments: openArray[string]): ScreenshotOptions = + ## Parses capture arguments without requiring a graphical build or window. + var index = 0 + while index < arguments.len: + doAssert result.takeCaptureFlag(arguments, index, arguments[index]) + inc index + +proc rejectCapture(arguments: openArray[string]) = + ## Requires malformed capture arguments to raise the shared boundary error. + var rejected = false + try: + discard parseCapture(arguments) + except ScreenshotError: + rejected = true + doAssert rejected + +proc rejectWindowSize(arguments: openArray[string]) = + ## Requires malformed dimensions to fail before a game creates its window. + var + width, height: int32 + index = 0 + rejected = false + try: + discard takeWindowSizeFlag(width, height, arguments, index, arguments[0]) + except ScreenshotError: + rejected = true + doAssert rejected + +proc testScreenshotFlags() = + ## Checks the common capture contract independently of rendering and files. + echo "Testing shared screenshot defaults and argument spellings" + let defaults = ScreenshotOptions() + doAssert defaults.path.len == 0 + doAssert defaults.frames == 30 + doAssert not defaults.framesSpecified + when not defined(takeScreenshot): + doAssert not defaults.captureRequested() + for arguments in [ + @["--screenshot", "shots/a match.png", "--frames", "7"], + @["--screenshot=shots/a match.png", "--frames=7"], + @["--screenshot:shots/a match.png", "--frames:7"] + ]: + let options = parseCapture(arguments) + doAssert options.path == "shots/a match.png" + doAssert options.frames == 7 and options.framesSpecified + doAssert options.captureRequested() + options.validateCapture(graphical = true) + doAssert parseCapture(@["--screenshot", "one.png"]).frames == 30 + let framesOnly = parseCapture(@["--frames:3"]) + doAssert framesOnly.frames == 3 and framesOnly.path.len == 0 + when not defined(takeScreenshot): + doAssert not framesOnly.captureRequested() + for argument in [ + "--screenshot:C:\\shots\\match.png", "--screenshot=C:\\shots\\match.png" + ]: + doAssert parseCapture(@[argument]).path == "C:\\shots\\match.png" + + echo "Testing missing, invalid, and overflowing capture arguments" + for arguments in [ + @["--screenshot"], @["--screenshot", ""], @["--screenshot="], + @["--screenshot:"], @["--screenshot", "--frames", "2"], + @["--frames"], @["--frames="], @["--frames:0"], + @["--frames=-1"], @["--frames:1.5"], @["--frames=not-a-number"], + @["--frames=2147483648"], @["--frames=999999999999999999999999"] + ]: + rejectCapture(arguments) + var + untouched = ScreenshotOptions(path: "keep.png", frames: 9) + index = 0 + doAssert not untouched.takeCaptureFlag(@["--game-option"], index, + "--game-option") + doAssert index == 0 + doAssert untouched.path == "keep.png" and untouched.frames == 9 + + echo "Testing one shared window-size syntax" + for arguments in [ + @["--windowSize", "1280x720"], @["--windowSize=1280x720"], + @["--windowSize:1280X720"] + ]: + var + width, height: int32 + position = 0 + doAssert takeWindowSizeFlag(width, height, arguments, position, + arguments[0]) + doAssert width == 1280 and height == 720 + doAssert position == arguments.high + for arguments in [ + @["--windowSize"], @["--windowSize="], @["--windowSize:0x720"], + @["--windowSize:1280x0"], @["--windowSize:-1x720"], + @["--windowSize:1280"], @["--windowSize:1280x720x1"], + @["--windowSize:2147483648x720"] + ]: + rejectWindowSize(arguments) + + echo "Testing common game flags share capture parsing" + for arguments in [ + @["--screenshot", "shared.png", "--frames", "12", + "--windowSize", "800x600"], + @["--screenshot=shared.png", "--frames=12", "--windowSize=800x600"], + @["--screenshot:shared.png", "--frames:12", "--windowSize:800x600"] + ]: + var + options = GameOptions() + position = 0 + while position < arguments.len: + doAssert options.takeCommonFlag(arguments, position, arguments[position]) + inc position + doAssert options.capture.path == "shared.png" + doAssert options.capture.frames == 12 + doAssert options.windowWidth == 800 and options.windowHeight == 600 + + echo "Testing nongraphical launches reject screenshot requests" + var rejected = false + try: + ScreenshotOptions(path: "unavailable.png").validateCapture( + graphical = false + ) + except ScreenshotError: + rejected = true + doAssert rejected + when not defined(takeScreenshot): + ScreenshotOptions().validateCapture(graphical = false) + for frames in [0, -1]: + rejected = false + try: + ScreenshotOptions(path: "invalid.png", frames: frames, + framesSpecified: true).validateCapture(graphical = true) + except ScreenshotError: + rejected = true + doAssert rejected + +proc testScreenshotState() = + ## Checks explicit startup state and CLI priority without creating a file. + let + hadPath = existsEnv("SCREENSHOT_PATH") + previousPath = getEnv("SCREENSHOT_PATH") + requested = "shots" / "runtime.png" + putEnv("SCREENSHOT_PATH", "ignored-environment.png") + defer: + if hadPath: + putEnv("SCREENSHOT_PATH", previousPath) + else: + delEnv("SCREENSHOT_PATH") + configureCapture(ScreenshotOptions(), graphical = true) + + echo "Testing capture startup resolves paths and ignores legacy defaults" + var zeroed = default(ScreenshotOptions) + zeroed.path = requested + zeroed.validateCapture(graphical = true) + configureCapture(zeroed, graphical = true) + doAssert captureWaitFrames(2) == 30 + configureCapture(ScreenshotOptions(path: requested), "ignored-default.png", + graphical = true) + doAssert captureActive() + doAssert capturePath("another-default.png") == absolutePath(requested) + doAssert captureWaitFrames(2) == 30 + doAssert not captureDue(0) + doAssert not captureDue(29) + doAssert captureDue(30) and captureDue(31) + configureCapture(parseCapture(@["--frames=4", "--screenshot", requested]), + graphical = true) + doAssert captureWaitFrames(120) == 4 + doAssert not captureDue(3) + doAssert captureDue(4) and captureDue(5) + var rejected = false + try: + configureCapture(ScreenshotOptions(path: "unavailable.png"), + graphical = false) + except ScreenshotError: + rejected = true + doAssert rejected + doAssert capturePath() == absolutePath(requested) + doAssert captureWaitFrames() == 4 + + echo "Testing completed captures cannot become due again" + doAssert not captureFinished() + finishCapture() + doAssert captureFinished() + doAssert not captureDue(4) and not captureDue(300) + configureCapture(parseCapture(@["--frames=4", "--screenshot", requested]), + graphical = true) + doAssert not captureFinished() + doAssert captureDue(4) + + echo "Testing disabled startup clears a prior capture request" + configureCapture(ScreenshotOptions(), graphical = true) + when not defined(takeScreenshot): + doAssert not captureActive() + doAssert not captureDue(300) + else: + doAssert captureActive() + doAssert capturePath() == absolutePath("ignored-environment.png") + doAssert captureWaitFrames(9) == 9 + configureCapture(ScreenshotOptions(frames: 6, framesSpecified: true), + graphical = true) + doAssert captureWaitFrames(9) == 6 + +testScreenshotFlags() +testScreenshotState() +echo "Shared screenshot command-line and startup unit tests passed." diff --git a/tests/test_tapes.nim b/tests/test_tapes.nim index b0ac221b8..e56a15e13 100644 --- a/tests/test_tapes.nim +++ b/tests/test_tapes.nim @@ -1,11 +1,34 @@ import - std/strutils, + std/[os, strutils, tempfiles], polyworld/tapes type TapeAction = object tick*: uint32 kind*: uint8 +echo "Testing replay files create missing output directories" +block: + let + directory = createTempDir("polyworld_tape_", "") + path = directory / "nested" / "match.replay" + defer: removeDir(directory) + saveReplayFile(path, "test", 1, "commands") + doAssert loadReplayFile(path, "test", 1, string) == "commands" + +echo "Testing invalid replay output creates no directories" +block: + let + directory = createTempDir("polyworld_invalid_tape_", "") + parent = directory / "nested" + path = parent / "match.replay" + defer: removeDir(directory) + try: + saveReplayFile(path, "test", 1, "too large", maxBytes = 1) + doAssert false, "Invalid replay data must be rejected" + except ReplayError: + discard + doAssert not dirExists(parent) + echo "Testing action order and exact-tick playback" block: var diff --git a/tests/test_webinputs.js b/tests/test_webinputs.js index 0e7da43cb..9bd90a86c 100644 --- a/tests/test_webinputs.js +++ b/tests/test_webinputs.js @@ -35,11 +35,11 @@ for (const query of ["?mute=1&mute=0", "?mute=false&mute=false", "?mute&mute"]) assert.deepEqual(configure("?replay=query.replay&mute=false"), [ "--replay", "/web/replay.replay", "--unmute" ]); -assert.deepEqual(configure("?mute=0&human=true&players=2", true), [ - "--unmute", "--human", "true", "--players", "2" +assert.deepEqual(configure("?mute=0&player=1&players=2", true), [ + "--player=1", "--unmute", "--players", "2" ]); -assert.deepEqual(configure("?human=true&players=2", true), [ - "--human", "true", "--players", "2" +assert.deepEqual(configure("?player=1&players=2", true), [ + "--player=1", "--players", "2" ]); assert.deepEqual(configure("?bot=../bots/Dragon.bas:3&bot=other/Dragon.bas"), [ diff --git a/tests/tests.nim b/tests/tests.nim index 10a937165..558eb5cff 100644 --- a/tests/tests.nim +++ b/tests/tests.nim @@ -6,6 +6,7 @@ import test_assetpacks, test_actioncam, test_animblend_controls, + test_bars, test_directors, test_bodies, test_body_layers, @@ -13,6 +14,7 @@ import test_characters, test_character_meshes, test_cli, + test_screenshots, ../games/crewrift/tests/test_sim as TestCrewrift, ../games/crewrift/tests/test_bots as TestCrewriftBots, ../games/crewrift/tests/test_skins as TestCrewriftSkins, @@ -105,6 +107,10 @@ import test_rngs, test_rtscameras, test_tapes, + test_replaysettings, + test_replaysaves, + test_replaylibraries, + test_replay_browser, test_terrains, test_terrainmaps, test_aigen_blends, diff --git a/tests/unit_tests.nim b/tests/unit_tests.nim new file mode 100644 index 000000000..dc92a0c46 --- /dev/null +++ b/tests/unit_tests.nim @@ -0,0 +1,35 @@ +{.warning[UnusedImport]: off.} + +import + std/tables, + zippy/ziparchives, + polyworld/policies, + test_bars, test_cli, test_controllers, test_screenshots, test_hashes, + test_rngs, test_mailboxes, + test_tapes, test_replaysaves, test_replaylibraries, + test_rooms, test_roomclients, test_generic_relay, test_cosmetic_ready, + test_room_codes, test_room_resize, test_sparse_rooms, test_opaque_setup, + test_relay_async_hashes, test_relay_readiness, test_start_intent, + test_client_loading_gap + +echo "Testing bounded policy packages without game-specific fixtures" +block: + doAssert loadPolicy("end\n").source == "end\n" + var entries = { + "nested/policy.bas": "end\n", + "weights.bin": "binary\0data" + }.toTable + let policy = loadPolicy(createZipArchive(move(entries))) + doAssert policy.source == "end\n" + doAssert policy.files.len == 1 + doAssert policy.resource("weights.bin") == "binary\0data" + for path in ["", "../escape", "/absolute", "a\\b", "C:relative", + "a/./b", "a//b", "a\0b"]: + var rejected = false + try: + discard resourcePath(path) + except PolicyError: + rejected = true + doAssert rejected + +echo "All Polyworld unit tests passed"