diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1d87ab1b..fcb24530 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -147,6 +147,8 @@ jobs: - name: Browser gameplay working-directory: tools/web_tests timeout-minutes: 30 + env: + WEB_GRAPHICS_PROFILE: low run: npm test - name: Every mission in browser @@ -155,6 +157,7 @@ jobs: timeout-minutes: 30 env: WEB_BROAD: '1' + WEB_GRAPHICS_PROFILE: low run: npm test - name: Full browser audio qualification @@ -163,6 +166,7 @@ jobs: timeout-minutes: 15 env: WEB_AUDIO_QA: '1' + WEB_GRAPHICS_PROFILE: low run: npm test -- --grep real-mixer - name: Upload browser evidence and export logs @@ -244,6 +248,7 @@ jobs: WEB_DEPLOYMENT_URL: ${{ steps.deployment.outputs.url }} WEB_DEPLOYMENT_COMMIT: ${{ github.sha }} WEB_DEPLOYMENT_BYPASS_SECRET: ${{ secrets.VERCEL_AUTOMATION_BYPASS_SECRET }} + WEB_GRAPHICS_PROFILE: low run: npx playwright test --config playwright.deployment.config.cjs - name: Promote production diff --git a/README.md b/README.md index 29478a64..827b82f2 100644 --- a/README.md +++ b/README.md @@ -1,211 +1,92 @@ # Farlanding -A single-player 3D real-time strategy game about a survey expedition following -a trail of beacons across unknown planets. Built with Godot 4.7 and Blender. +Build a foothold on an unfamiliar world. Follow what it leaves behind. -![A Lander, a new Reactor, two Fabricators and a Hauler on Kessel Reach](docs/media/phase2-base.png) +Farlanding is a single-player 3D real-time strategy game about a survey expedition +beyond familiar space. Build bases, command a growing force, and uncover a trail +of discoveries that changes what your expedition can do. Made with Godot and Blender. -## Run it +**[Play in your browser](https://farlanding.vercel.app)** · +[Player guide](docs/PLAYER_GUIDE.md) · [Development plan](docs/PLAN.md) -Open `game/` in Godot 4.7.2 and press Play, or: +![The Meridian in orbit above the expedition's first world](docs/media/browser-orbit.png) -``` -godot --path game -``` +## An expedition, one landing at a time -## Play - -**New campaign** puts you aboard the *Meridian*, the expedition carrier. The star map -shows the route of landings: hover one for its orbital scan (planet, rule, mission -type, unresolved `?` signals), click an open one and press LAUNCH. A won landing banks -the Intel you still hold when it ends (a lost one banks nothing, but its finds stay in -the codex) and opens the landings it leads to; the route branches, and taking one side -closes the other. On the Meridian (MERIDIAN on the star map) spend banked Intel on the -tech web: clear the Survey Lab, Lancer, Sentry and Arc, upgrade Haulers, scanners and -optics; some techs need an Antecedent find from an earlier landing. Pick a loadout -(escort squad, a pre-charged ship ability, cargo). Every later landing starts with -all of it, and the briefing lists what it brings. The campaign autosaves after every -landing and purchase; **Continue** picks it up. **Single missions** plays any landing -on its own. - -Landings are on Kessel Reach (Conquest, Survey or Infiltration), Thalassa Low -(Tidewater Landing, a Conquest, and Low-Water Recovery) and Emberfall (Caldera -Conquest and Caldera Holdout). Dust storms sweep Kessel's -basin every few minutes: everyone sees half as far, ground units slow down and long -guns lose reach (the gauge under the top-right buttons counts the next one down). On -Thalassa the tide rises and falls on the same gauge: high water closes the fords and -floods the tidal pans (ground units caught in them wade slowly and take damage, -haulers stop mining there, nothing can be built on ground that floods); the causeway -always stays dry and hover units cross flooded shallows. In a Recovery, command a unit -onto the Antecedent artefact to pick it up and bring it back to the Lander; its -carrier is slow and cannot fight, and drops it if killed. On Emberfall the rich Flux -vents fill with pressure while a Flux Tap draws on them and erupt when full (a ring on -the ground counts down; buildings near it are hit hard, units less, the Tap is knocked -out for a while); select the Tap and press **VENT** to release the pressure early at a -small cost, then wait out its cooldown. The gauge shows the vent closest to bursting. -Lava is never crossable: use the bridges and the caldera's ramps. In a Holdout, keep -the Lander standing until the extraction ship lands while growing waves come for it. -Field notes explain each new thing the first time you meet it. - -| Input | Does | -|---|---| -| Left click (classic scheme) | select, and command by context: move, attack, harvest, scan, build, carry, rally | -| Right click (classic scheme) | deselect, cancel placement or aiming | -| Shift | add to selection, queue orders | -| Ctrl+1–9 / 1–9 | store / recall a control group | -| WASD, arrows, screen edge, middle drag | pan · wheel: zoom · Q/E: turn | -| C | codex · F1: all controls · F3: debug overlay | -| F5 / F9 (native), K / L (Web) | quicksave / quickload | -| Esc or P | pause menu: resume, save, load, settings, how to play, restart, quit | - -These are the default keys: every one can be rebound per mouse scheme under -Settings > KEYS (a key already in use is named, and pressing it again swaps the two). -Hints and the F1 panel always name the keys as bound. - -**Difficulty** (Easy, Normal, Hard) is chosen when starting a new campaign or on the -mission list, and can be changed aboard the Meridian between landings. It changes how -fast the Combine decides, when it attacks and how often it slips, never its income. -Normal plays each landing as designed; Easy and Hard shift it one step. - -Settings (from the title, the mission list or the pause menu): GENERAL (volumes for -master, music, effects, ambience, voice and interface; mouse scheme, classic or -modern: left selects, right commands; edge-pan, pan speed, fullscreen, quality, -resolution scale, "Reset hints"), ACCESSIBILITY (team colour palettes for red-green -and blue-yellow colour blindness, subtitles for the Advisor and their size, interface -size 100/115/130%, fewer flashes, sticky Shift, game speed of single missions) and -KEYS. **How to play** and **Credits** are on the title screen. - -## Building a release - -Install the Godot **4.7.2.stable** export templates (Editor > Manage Export -Templates), then from the repository root: +Travel aboard the *Meridian* and choose where to land next. On the surface, +establish a base, gather resources, produce units, and respond to an enemy with +its own foothold. Each mission adds a different reason to explore. -``` -tools/export.sh # macOS, Windows and Linux -tools/export.sh Linux # or just some -``` +- **Build and command.** Grow from a small landing crew into a working base and an army. +- **Look beyond the battle.** Scan unusual signals and gather intel to unlock new options. +- **Adapt to the planet.** Weather, terrain and local conditions change how you move and fight. +- **Bring discoveries home.** Invest in your expedition between missions and shape your next landing. -The builds land in `build/` (git-ignored): `build/macos/Farlanding.zip` (ad-hoc -signed, not notarised), `build/windows/Farlanding.exe` and -`build/linux/Farlanding.x86_64`, each with its `.pck`. The presets are in -`game/export_presets.cfg`; they leave out the tests, GUT and the showcase scenes and -hold no signing identities. Set `GODOT=/path/to/godot` to use another binary of the -same version; the script stops with a message if the version or the templates are -missing. +Some missions reward a strong assault. Others call for a quiet approach or a +careful search. The screenshots show the first world; the rest is yours to discover. -## Work on it +![The first landing on Kessel Reach, rendered in the browser at High quality](docs/media/browser-kessel.png) -| Read | For | -|---|---| -| `docs/PLAN.md` | Game design, architecture and the phased build plan | -| `docs/CONVENTIONS.md` | Code conventions | -| `docs/ART_STYLE.md` | Visual style and the scripted Blender pipeline | -| `docs/AUDIO_STYLE.md` | Sound identity and the synthesis pipeline | -| `docs/adr/` | Decisions that would be expensive to reverse | +## Start playing -Before pushing, run `tools/check.sh` (format, lint, import, script check, -tests, boot test, mission smoke test). CI runs the same script. Performance numbers -and how to measure them: `docs/PERFORMANCE.md`. +The browser build needs a desktop browser with WebGL2, a keyboard and a mouse. +Click **Play Farlanding**, then choose **New campaign** or **Single missions**. +Press **F1** for controls or **Esc** for the pause menu. -Rebuild generated assets: +High graphics uses full 3D resolution, shadows, glow and 2× antialiasing. Choose +**Balanced** or **Performance** in the launcher if your GPU needs a lighter preset. +Saved graphics choices are remembered. [Graphics details and measurements](docs/WEB_GRAPHICS.md). -``` -blender -b -P art/pipeline/build_all.py -uv run --python 3.12 --with numpy==2.5.4 --with scipy==1.18.1 audio_src/build.py -``` +Browser saves stay at the same origin in the same browser. Wait for the saved +confirmation before closing or reloading; clearing site data removes those saves. +Use the stable play link above to keep the same origin between updates. -## Play in a desktop browser +## Run locally -Use Godot **4.7.2.stable**, Python **3.11+**, WebAssembly and WebGL2. Install the -matching templates in the editor, or install just the verified Web templates: +Open `game/` in **Godot 4.7.2** and press Play, or run: + +```sh +godot --path game +``` + +To build and serve the browser version, install the matching export templates, +then run: ```sh tools/install_godot_templates.sh tools/export.sh Web -python3 tools/web_manifest.py build/web --verify python3 tools/serve_web.py build/web ``` -Open **http://127.0.0.1:8060** and click **Play Farlanding**. Keep the terminal -running; Ctrl-C stops the server. Opening `index.html` as a local file will not work. -The server binds only to this computer and supplies the headers needed by threads. +Open **http://127.0.0.1:8060**. Keep the server running; opening `index.html` +as a local file will not work. [Browser build and deployment guide](docs/WEB_DEVELOPMENT.md). -Web uses threaded Stream audio to preserve mixer effects. The local server supplies -the isolation headers that this requires. +## Development -Fresh Web profiles start at low graphics quality and 50% 3D render scale to keep -modest GPUs and software WebGL responsive. Menus render at full resolution. Adjust -both in Settings; saved choices override these defaults. Native defaults stay high. +Game code lives in `game/`, the scripted Blender pipeline in `art/`, and sound +sources in `audio_src/`. Definitions are resources; gameplay runs on simulation +ticks, with presentation and audio responding to events. -Web uses **K/L** for quicksave/quickload. Settings and landings stay in this browser -at this origin. Wait for the saved confirmation before reloading. Denied storage -or failed persistence produces a warning. Clearing site data or changing the port -or origin can make existing progress unavailable. Fullscreen requires a user -click. Leaving the tab pauses the mission; resume explicitly when returning. -Keyboard and mouse are required. Mobile controls remain outside this milestone. +Run `tools/check.sh` before pushing. CI checks native behavior and browser gameplay. +Successful pushes to `main` deploy the tested browser artifact to Vercel after +staged checks pass. -Every successful CI `web` job publishes `farlanding-web-` in the run's -Artifacts section. Download and extract it, then run the same manifest verification -and serving commands from the extracted root. The artifact includes `build/web/` -and the two Python tools. `manifest.json` identifies the commit, engine, headers, -and every bundle file's hash. It describes required HTTP headers; a ZIP has none. - -### Browser checks +| Read | For | +| --- | --- | +| [Plan](docs/PLAN.md) | Game design, architecture and phased development | +| [Conventions](docs/CONVENTIONS.md) | Code structure and contribution checks | +| [Art style](docs/ART_STYLE.md) | Visual identity and Blender asset generation | +| [Audio style](docs/AUDIO_STYLE.md) | Sound identity and the synthesis pipeline | +| [Browser development](docs/WEB_DEVELOPMENT.md) | Exports, Playwright checks and Vercel CI | +| [Graphics qualification](docs/WEB_GRAPHICS.md) | Profiles, visual references and GPU measurements | +| [Performance](docs/PERFORMANCE.md) | Simulation and rendering benchmarks | +| [Architecture decisions](docs/adr/) | Decisions and their tradeoffs | -Node **26.x** is needed only for testing and deployment. Export diagnostics separately: +Rebuild generated assets: ```sh -tools/export.sh Web WebDiagnostics -cd tools/web_tests -npm ci -npx playwright install chromium -npm test -WEB_BROAD=1 npm test -WEB_AUDIO_QA=1 npm test -- --grep real-mixer -WEB_PERFORMANCE=1 npm test -- --grep 233-unit -WEB_BROWSER=firefox npm test +blender -b -P art/pipeline/build_all.py +uv run --python 3.12 --with numpy==2.5.4 --with scipy==1.18.1 audio_src/build.py ``` -Install Firefox or WebKit with `npx playwright install firefox webkit` before using -those browser names. The suite starts loopback servers on 8070/8071, uses fresh -profiles, and has no automatic retries. It retains console/network logs, state, -screenshots and traces on failures; `WEB_RECORD=1` enables video capture. Video is -opt-in to avoid competing with software WebGL on CI runners. The broad mission -matrix also runs from CI's manual **Run workflow** action. `WebDiagnostics` is for -testing only; play the release under `build/web`. Browser versions and acceptance -evidence are tracked in [the Web results](docs/WEB_CI_RESULTS.md). - -### Production deployment - -Successful pushes to `main` deploy to [Farlanding](https://farlanding.vercel.app) -after native checks and browser gameplay pass. Pull requests and manual test runs -do not deploy. Both the CI Node steps and the Vercel project use Node 26.x. - -The Vercel Hobby project uses the same team and CI-controlled deployment policy as -Space Explorer. Its Git auto-deploys are disabled. Because the exported game exceeds -Hobby's 100 MB CLI source-upload limit, CI uploads a small build script referring -to that run's tested GitHub artifact by ID and digest. Vercel resolves a fresh -download URL when its build starts, using that CI job's short-lived GitHub token -as a build-only secret with repository contents/Actions read permissions. It is -never stored in source files or public assets and is not forwarded to artifact -storage. The build verifies GitHub's archive digest and the release's complete -file inventory and commit. Godot is not rebuilt on Vercel. - -CI first creates an unaliased production deployment and runs real browser input -against it, including the isolation headers and WebAssembly MIME type. Only a -passing staged game is promoted. CI then checks the public production domain -without authentication. Use that stable domain for play so browser saves stay at -the same origin across deployments. - -Repository secrets: `VERCEL_TOKEN`, `VERCEL_ORG_ID`, `VERCEL_PROJECT_ID`, and -`VERCEL_AUTOMATION_BYPASS_SECRET`. The last one lets the staged browser check pass -Vercel's preview protection; traces are disabled when it is used so request -credentials are not recorded. `VERCEL_PRODUCTION_URL` is a repository variable. -The deployment uses the GitHub `production` environment and Vercel CLI 65.16.0. - -Deploy through CI rather than rebuilding an old deployment in the Vercel dashboard: -the job's GitHub token expires when that job finishes. Rerun the deployment job in -a push-to-`main` workflow while its tested artifact is retained, or rerun that entire push workflow -to create a fresh artifact. Manual **Run workflow** runs remain test-only. -Existing ready deployments can still be promoted or rolled back without -downloading the source artifact again. +Released under the [MIT license](LICENSE). diff --git a/docs/PLAYER_GUIDE.md b/docs/PLAYER_GUIDE.md new file mode 100644 index 00000000..fe0b0610 --- /dev/null +++ b/docs/PLAYER_GUIDE.md @@ -0,0 +1,64 @@ +# Player guide + +Detailed controls and mission rules follow, including planet-specific mechanics. + + +**New campaign** puts you aboard the *Meridian*, the expedition carrier. The star map +shows the route of landings: hover one for its orbital scan (planet, rule, mission +type, unresolved `?` signals), click an open one and press LAUNCH. A won landing banks +the Intel you still hold when it ends (a lost one banks nothing, but its finds stay in +the codex) and opens the landings it leads to; the route branches, and taking one side +closes the other. On the Meridian (MERIDIAN on the star map) spend banked Intel on the +tech web: clear the Survey Lab, Lancer, Sentry and Arc, upgrade Haulers, scanners and +optics; some techs need an Antecedent find from an earlier landing. Pick a loadout +(escort squad, a pre-charged ship ability, cargo). Every later landing starts with +all of it, and the briefing lists what it brings. The campaign autosaves after every +landing and purchase; **Continue** picks it up. **Single missions** plays any landing +on its own. + +Landings are on Kessel Reach (Conquest, Survey or Infiltration), Thalassa Low +(Tidewater Landing, a Conquest, and Low-Water Recovery) and Emberfall (Caldera +Conquest and Caldera Holdout). Dust storms sweep Kessel's +basin every few minutes: everyone sees half as far, ground units slow down and long +guns lose reach (the gauge under the top-right buttons counts the next one down). On +Thalassa the tide rises and falls on the same gauge: high water closes the fords and +floods the tidal pans (ground units caught in them wade slowly and take damage, +haulers stop mining there, nothing can be built on ground that floods); the causeway +always stays dry and hover units cross flooded shallows. In a Recovery, command a unit +onto the Antecedent artefact to pick it up and bring it back to the Lander; its +carrier is slow and cannot fight, and drops it if killed. On Emberfall the rich Flux +vents fill with pressure while a Flux Tap draws on them and erupt when full (a ring on +the ground counts down; buildings near it are hit hard, units less, the Tap is knocked +out for a while); select the Tap and press **VENT** to release the pressure early at a +small cost, then wait out its cooldown. The gauge shows the vent closest to bursting. +Lava is never crossable: use the bridges and the caldera's ramps. In a Holdout, keep +the Lander standing until the extraction ship lands while growing waves come for it. +Field notes explain each new thing the first time you meet it. + +| Input | Does | +|---|---| +| Left click (classic scheme) | select, and command by context: move, attack, harvest, scan, build, carry, rally | +| Right click (classic scheme) | deselect, cancel placement or aiming | +| Shift | add to selection, queue orders | +| Ctrl+1–9 / 1–9 | store / recall a control group | +| WASD, arrows, screen edge, middle drag | pan · wheel: zoom · Q/E: turn | +| C | codex · F1: all controls · F3: debug overlay | +| F5 / F9 (native), K / L (Web) | quicksave / quickload | +| Esc or P | pause menu: resume, save, load, settings, how to play, restart, quit | + +These are the default keys: every one can be rebound per mouse scheme under +Settings > KEYS (a key already in use is named, and pressing it again swaps the two). +Hints and the F1 panel always name the keys as bound. + +**Difficulty** (Easy, Normal, Hard) is chosen when starting a new campaign or on the +mission list, and can be changed aboard the Meridian between landings. It changes how +fast the Combine decides, when it attacks and how often it slips, never its income. +Normal plays each landing as designed; Easy and Hard shift it one step. + +Settings (from the title, the mission list or the pause menu): GENERAL (volumes for +master, music, effects, ambience, voice and interface; mouse scheme, classic or +modern: left selects, right commands; edge-pan, pan speed, fullscreen, quality, +resolution scale, "Reset hints"), ACCESSIBILITY (team colour palettes for red-green +and blue-yellow colour blindness, subtitles for the Advisor and their size, interface +size 100/115/130%, fewer flashes, sticky Shift, game speed of single missions) and +KEYS. **How to play** and **Credits** are on the title screen. diff --git a/docs/WEB_DEVELOPMENT.md b/docs/WEB_DEVELOPMENT.md new file mode 100644 index 00000000..23eb8186 --- /dev/null +++ b/docs/WEB_DEVELOPMENT.md @@ -0,0 +1,100 @@ +# Browser builds, testing and deployment + +Use Godot **4.7.2.stable**, Python **3.11+**, WebAssembly and WebGL2. Install the +matching templates in the editor, or install just the verified Web templates: + +```sh +tools/install_godot_templates.sh +tools/export.sh Web +python3 tools/web_manifest.py build/web --verify +python3 tools/serve_web.py build/web +``` + +Open **http://127.0.0.1:8060** and click **Play Farlanding**. Keep the terminal +running; Ctrl-C stops the server. Opening `index.html` as a local file will not work. +The server binds only to this computer and supplies the headers needed by threads. + +Web uses threaded Stream audio to preserve mixer effects. The local server supplies +the isolation headers that this requires. + +Fresh profiles start at **High**, 100% 3D resolution and 2× MSAA. The launcher +offers High, Balanced and Performance before loading the game; Saved keeps your +preferences. Performance uses 50% 3D resolution with shadows, SSAO and glow off; +the UI stays at full resolution. Existing Web players with the old Low/50% +settings get a one-time choice to keep them or use High. Audio, controls and +progress are retained. Settings also lets you customize resolution and MSAA. +See [graphics qualification](WEB_GRAPHICS.md) for renderer differences, +hardware measurements and reproducible comparisons. + +Web uses **K/L** for quicksave/quickload. Settings and landings stay in this browser +at this origin. Wait for the saved confirmation before reloading. Denied storage +or failed persistence produces a warning. Clearing site data or changing the port +or origin can make existing progress unavailable. Fullscreen requires a user +click. Leaving the tab pauses the mission; resume explicitly when returning. +Keyboard and mouse are required. Mobile controls remain outside this milestone. + +Every successful CI `web` job publishes `farlanding-web-` in the run's +Artifacts section. Download and extract it, then run the same manifest verification +and serving commands from the extracted root. The artifact includes `build/web/` +and the two Python tools. `manifest.json` identifies the commit, engine, headers, +and every bundle file's hash. It describes required HTTP headers; a ZIP has none. + +### Browser checks + +Node **26.x** is needed only for testing and deployment. Export diagnostics separately: + +```sh +tools/export.sh Web WebDiagnostics +cd tools/web_tests +npm ci +npx playwright install chromium +npm test +WEB_BROAD=1 npm test +WEB_AUDIO_QA=1 npm test -- --grep real-mixer +WEB_PERFORMANCE=1 npm test -- --grep 233-unit +WEB_BROWSER=firefox npm test +``` + +Install Firefox or WebKit with `npx playwright install firefox webkit` before using +those browser names. The suite starts loopback servers on 8070/8071, uses fresh +profiles, and has no automatic retries. It retains console/network logs, state, +screenshots and traces on failures; `WEB_RECORD=1` enables video capture. Video is +opt-in to avoid competing with software WebGL on CI runners. The broad mission +matrix also runs from CI's manual **Run workflow** action. `WebDiagnostics` is for +testing only; play the release under `build/web`. Browser versions and acceptance +evidence are tracked in [the Web results](WEB_CI_RESULTS.md). + +### Production deployment + +Successful pushes to `main` deploy to [Farlanding](https://farlanding.vercel.app) +after native checks and browser gameplay pass. Pull requests and manual test runs +do not deploy. Both the CI Node steps and the Vercel project use Node 26.x. + +The Vercel Hobby project uses the same team and CI-controlled deployment policy as +Space Explorer. Its Git auto-deploys are disabled. Because the exported game exceeds +Hobby's 100 MB CLI source-upload limit, CI uploads a small build script referring +to that run's tested GitHub artifact by ID and digest. Vercel resolves a fresh +download URL when its build starts, using that CI job's short-lived GitHub token +as a build-only secret with repository contents/Actions read permissions. It is +never stored in source files or public assets and is not forwarded to artifact +storage. The build verifies GitHub's archive digest and the release's complete +file inventory and commit. Godot is not rebuilt on Vercel. + +CI first creates an unaliased production deployment and runs real browser input +against it, including the isolation headers and WebAssembly MIME type. Only a +passing staged game is promoted. CI then checks the public production domain +without authentication. Use that stable domain for play so browser saves stay at +the same origin across deployments. + +Repository secrets: `VERCEL_TOKEN`, `VERCEL_ORG_ID`, `VERCEL_PROJECT_ID`, and +`VERCEL_AUTOMATION_BYPASS_SECRET`. The last one lets the staged browser check pass +Vercel's preview protection; traces are disabled when it is used so request +credentials are not recorded. `VERCEL_PRODUCTION_URL` is a repository variable. +The deployment uses the GitHub `production` environment and Vercel CLI 65.16.0. + +Deploy through CI rather than rebuilding an old deployment in the Vercel dashboard: +the job's GitHub token expires when that job finishes. Rerun the deployment job in +a push-to-`main` workflow while its tested artifact is retained, or rerun that entire push workflow +to create a fresh artifact. Manual **Run workflow** runs remain test-only. +Existing ready deployments can still be promoted or rolled back without +downloading the source artifact again. diff --git a/docs/WEB_GRAPHICS.md b/docs/WEB_GRAPHICS.md new file mode 100644 index 00000000..e1fc76b5 --- /dev/null +++ b/docs/WEB_GRAPHICS.md @@ -0,0 +1,124 @@ +# Browser graphics qualification + +The browser uses Godot 4.7.2 Compatibility/WebGL2, while the desktop editor uses +Forward+. The goal is a sharp picture with the same planet palette, readable +silhouettes and atmospheric effects. It is not pixel-identical HDR rendering. + +## Profiles and persistence + +| Profile | 3D resolution | MSAA | Shadow atlas | SSAO / glow | +| --- | --- | --- | --- | --- | +| High (fresh default) | 100% | 2× | 4096, soft | Authored | +| Balanced | 100% | Off | 2048 | Authored | +| Performance | 50% | Off | Off | Off | + +The launcher can override saved graphics explicitly. Saved uses existing +preferences. Resolution and antialiasing are independently adjustable +in Settings; the preset selector reports Custom when they differ. The old Web +Low/50% default gets a one-time upgrade choice. Neither choice changes controls, +audio, accessibility, tutorial history or campaign progress. + +Environments are local to scene instances, so visiting a Low menu cannot turn +off an environment's authored glow for a later High scene. Renderer preparation +happens before weather initialization, preserving storm interpolation baselines. +The browser keeps a full physical-pixel canvas while sizing the HUD in CSS pixels: +UI scale multiplies display pixel density, so Retina sharpness does not shrink +menus or controls. The saved UI preference remains 100/115/130%. + +## Reproduce the evidence + +Build release and diagnostic exports with `tools/export.sh Web WebDiagnostics`. +From `tools/web_tests`, use these commands on an otherwise idle hardware GPU: + +```sh +WEB_VISUALS=1 npm test -- visual.spec.cjs +WEB_GRAPHICS_QUALIFY=1 npm test -- graphics.spec.cjs +WEB_PERFORMANCE=1 WEB_BENCH_QUALITY=high WEB_BENCH_MSAA=2 npm test -- performance.spec.cjs +WEB_PERFORMANCE=1 WEB_BENCH_QUALITY=high WEB_BENCH_MSAA=2 WEB_BENCH_NORMAL=1 npm test -- performance.spec.cjs +``` + +The battle is the seeded 233-unit encounter, with five seconds of warm-up and +120 seconds measured. The normal lane keeps the starting mission and camera, +without adding armies. `WEB_BENCH_SECONDS=30` is a short diagnostic, not a +replacement for the full measurement. `WEB_WIDTH`, `WEB_HEIGHT`, and `WEB_DPR` +control the browser viewport; attached reports record actual canvas/CSS sizes. +`WEB_SOFTWARE=1 WEB_GRAPHICS_PROFILE=low npm test` reproduces CI's correctness +profile. Performance tests record evidence rather than turning software GPU +timing into a hardware release gate. + +For a native reference, launch the diagnostic scene directly, e.g.: + +```sh +godot --path game --rendering-method forward_plus --resolution 1280x720 \ + res://tests/web/visual_compare.tscn -- --visual=conquest --visual-output=/tmp/native-conquest +``` + +Repeat with `gl_compatibility` and with `thalassa_recovery`, `emberfall_conquest`, +`verdance_conquest`, `hollow_power`. The comparison uses seed 1729, the authored +landing camera and starting crew, a paused simulation and fixed quality/scale. +Animated shaders and visual/audio effects remain real, so this is a visual +reference, not a byte-identical image test. Native output includes a PNG and +metadata; Web attaches PNGs and renderer/profile/viewport metadata. An additional +`orbit` reference uses the real Meridian backdrop with a fixed clean camera +composition, without campaign UI or route spoilers; this is the README ship image. + +## Evidence and remaining limits + +Before changing production defaults, five Forward+ and five native Compatibility +references plus ten browser Low/High references were captured. The old High/100% +AA-off 233-unit hardware baseline on Apple M4 / Chromium 159 / ANGLE Metal at +1280×720, DPR 1 produced frame p95 values of 34.06, 33.91 and 34.53 ms across +three 120-second runs. This already missed the strict 33.3 ms large-battle target. +Do not describe mean frame time as a p95 pass. + +The first new High/100%/2× MSAA 120-second battle run measured mean 17.34 ms, +p95 26.00 ms and max 46.90 ms, with render-submit p95 8.65 ms and draw-call p95 +2786. This is one observed device result, not a causal performance claim from the +lighting calibration or a guarantee for other hardware. + +Three subsequent 120-second High runs on the same idle M4 / ANGLE Metal device +measured frame p95 values of **25.42, 26.11 and 27.04 ms**, all within the +33.3 ms large-battle budget. Means were 17.38–17.46 ms; maxima 55.48–77.80 ms. +The live starting-mission lane (no added armies, peak 26 units) measured mean +16.67 ms, p95 18.49 ms, max 45.13 ms and render-submit p95 2.55 ms over 120 +seconds. The strict 16.7 ms p95 normal-play target is therefore still unmet; +the approximately 60 FPS mean is not a p95 pass. Neither lane certifies 1080p +or Retina performance; those sizes have visual/input checks only. + +Qualification on the same M4 machine: + +| Check | Observed result | +| --- | --- | +| Native gameplay / real-time mixer | 713 + 416 tests passed; all 11 mission smoke tests passed | +| Graphics UI regression | 13 tests, 68 assertions passed | +| Chromium hardware functional suite | 23 cases passed, including Retina menu input, legacy Keep / High and save recovery | +| Chromium software correctness profile | Performance gameplay and persistence checks passed; CI also covers Retina menu input | +| High visual references | Six each passed in Chromium 159, Firefox and Playwright WebKit | +| 1920×1080, DPR 1 | Actual 1920×1080 canvas, High / scale 1 / 2× MSAA | +| 1280×720, DPR 2 | Actual 2560×1440 canvas, High / scale 1 / 2× MSAA | +| Retina input qualification | Six menu layouts, movement, build/gather/produce/save and graphics migration passed at DPR 2 | +| Python build/deployment tooling | 13 tests passed | + +The references include all five planets and the clean orbital composition. They +were inspected for sharp edges, palette, terrain readability, shadows, glow and +missing geometry. WebKit visual smoke is not a full Safari gameplay or hardware +performance certification. Native lighting remains authored Forward+; browser +LDR glow and tone response are deliberately calibrated approximations. + +The palette atlas intentionally uses nearest filtering: faces sample swatch +centers. Increasing filtering or texture size cannot add authored surface detail. +The model inventory already has one static body plus named animated parts per +unit; blindly joining those parts breaks legs, wheels, turrets and fans. No +unmeasured batching or asset rewrite is included solely to lower draw calls. + +Local evidence lives under the ignored `build/evidence/graphics/` directory. +CI attaches its export logs and browser evidence to the workflow run. Hardware +results are device-specific; they do not certify every integrated GPU or Safari. + +## Primary references + +- [Godot 4.7 renderer features](https://docs.godotengine.org/en/4.7/tutorials/rendering/renderers.html) +- [Environment and post-processing](https://docs.godotengine.org/en/4.7/tutorials/3d/environment_and_post_processing.html) +- [Environment properties and Compatibility glow limitations](https://docs.godotengine.org/en/4.7/classes/class_environment.html) +- [Window content scaling](https://docs.godotengine.org/en/4.7/classes/class_window.html) +- [Web export limitations](https://docs.godotengine.org/en/4.7/tutorials/export/exporting_for_web.html) diff --git a/docs/adr/0021-browser-graphics-profiles.md b/docs/adr/0021-browser-graphics-profiles.md new file mode 100644 index 00000000..5760a1bf --- /dev/null +++ b/docs/adr/0021-browser-graphics-profiles.md @@ -0,0 +1,44 @@ +# 0021 — Browser graphics profiles and renderer calibration + +Status: accepted + +## Context + +Fresh Web profiles previously selected Low and 50% 3D resolution to accommodate +software-rendered CI. This removed shadows/glow and rendered only a quarter of +the pixels. The resulting picture did not represent the game's authored look. +WebGL2 Compatibility also shades differently from desktop Forward+. + +## Decision + +Use authored `GraphicsProfile` resources for High (100%, 2× MSAA, 4096 shadows, +SSAO/glow), Balanced (100%, no MSAA, 2048 shadows, SSAO/glow), and Performance +(50%, no MSAA/shadows/SSAO/glow). High is the fresh-profile default. Resolution +and MSAA can be customized independently. Simulation and audio are unaffected. + +On Web, multiply the saved UI scale by display pixel density so HUD dimensions +follow CSS pixels while the 3D canvas retains its physical resolution. Reconcile +this runtime scale when the window size changes, without writing preferences. + +CI selects Performance through the same launcher as a player. It proves +correctness on software WebGL2, not hardware performance or High visual quality. +Hardware qualification records physical canvas size, DPR, browser and renderer. + +Preserve existing preferences. Old Web Low/50% files cannot reliably distinguish +an automatic downgrade from an intentional choice, so offer Keep Current or Use +High once. A version stamp records the decision without resetting progress, +controls, audio or accessibility settings. Existing files without MSAA retain Off. + +Prepare scene-local environments before weather caches their baselines. On +Compatibility, calibrate direct/ambient lighting against fixed-camera Forward+ +references, lower the glow threshold for LDR highlights, preserve overbright +emission hues, and mix fog-of-war colors in linear space. Forward+ retains its +authored lighting and emission. Visibility still comes from the same vision map. + +## Consequences + +High costs more GPU time and is not a universal frame-rate guarantee. Players +can select Performance before launch. Web still uses Compatibility/WebGL2; +Forward+ HDR, volumetrics and temporal AA cannot be promised in the browser. +Diagnostic reference scenes and benchmarks stay excluded from release exports. +Measurements and limitations are recorded in [WEB_GRAPHICS.md](../WEB_GRAPHICS.md). diff --git a/docs/media/browser-kessel.png b/docs/media/browser-kessel.png new file mode 100644 index 00000000..d3bc0855 Binary files /dev/null and b/docs/media/browser-kessel.png differ diff --git a/docs/media/browser-orbit.png b/docs/media/browser-orbit.png new file mode 100644 index 00000000..125cf931 Binary files /dev/null and b/docs/media/browser-orbit.png differ diff --git a/game/assets/environments/emberfall_env.tres b/game/assets/environments/emberfall_env.tres index 8ef3db22..4d2abf26 100644 --- a/game/assets/environments/emberfall_env.tres +++ b/game/assets/environments/emberfall_env.tres @@ -12,6 +12,7 @@ sun_angle_max = 12.0 sky_material = SubResource("sky_mat") [resource] +resource_local_to_scene = true background_mode = 2 sky = SubResource("sky") ambient_light_source = 3 diff --git a/game/assets/environments/hollow_env.tres b/game/assets/environments/hollow_env.tres index 75d193e7..2d5a0108 100644 --- a/game/assets/environments/hollow_env.tres +++ b/game/assets/environments/hollow_env.tres @@ -12,6 +12,7 @@ sun_angle_max = 12.0 sky_material = SubResource("sky_mat") [resource] +resource_local_to_scene = true background_mode = 2 sky = SubResource("sky") ambient_light_source = 3 diff --git a/game/assets/environments/kessel_env.tres b/game/assets/environments/kessel_env.tres index 75e5f608..e389e89a 100644 --- a/game/assets/environments/kessel_env.tres +++ b/game/assets/environments/kessel_env.tres @@ -12,6 +12,7 @@ sun_angle_max = 12.0 sky_material = SubResource("sky_mat") [resource] +resource_local_to_scene = true background_mode = 2 sky = SubResource("sky") ambient_light_source = 3 diff --git a/game/assets/environments/thalassa_env.tres b/game/assets/environments/thalassa_env.tres index bc409151..d907e0d6 100644 --- a/game/assets/environments/thalassa_env.tres +++ b/game/assets/environments/thalassa_env.tres @@ -12,6 +12,7 @@ sun_angle_max = 12.0 sky_material = SubResource("sky_mat") [resource] +resource_local_to_scene = true background_mode = 2 sky = SubResource("sky") ambient_light_source = 3 diff --git a/game/assets/environments/verdance_env.tres b/game/assets/environments/verdance_env.tres index 2efe77e1..768122b4 100644 --- a/game/assets/environments/verdance_env.tres +++ b/game/assets/environments/verdance_env.tres @@ -12,6 +12,7 @@ sun_angle_max = 12.0 sky_material = SubResource("sky_mat") [resource] +resource_local_to_scene = true background_mode = 2 sky = SubResource("sky") ambient_light_source = 3 diff --git a/game/core/graphics_profile.gd b/game/core/graphics_profile.gd new file mode 100644 index 00000000..89656f36 --- /dev/null +++ b/game/core/graphics_profile.gd @@ -0,0 +1,21 @@ +class_name GraphicsProfile +extends Resource +## Authored graphics budgets. Profiles never change simulation or audio settings. + +const PATHS: Dictionary[StringName, String] = { + &"low": "res://data/graphics/performance.tres", + &"medium": "res://data/graphics/balanced.tres", + &"high": "res://data/graphics/high.tres", +} + +@export var render_scale: float = 1.0 +@export var msaa_3d: Viewport.MSAA = Viewport.MSAA_DISABLED +@export var shadow_size: int = 4096 +@export var soft_shadows: bool = true +@export var ssao_enabled: bool = true +@export var glow_enabled: bool = true + + +static func for_quality(quality: StringName) -> GraphicsProfile: + var path: String = PATHS.get(quality, PATHS[&"high"]) + return load(path) as GraphicsProfile diff --git a/game/core/graphics_profile.gd.uid b/game/core/graphics_profile.gd.uid new file mode 100644 index 00000000..d918a0d0 --- /dev/null +++ b/game/core/graphics_profile.gd.uid @@ -0,0 +1 @@ +uid://b6kpakl4pwt5w diff --git a/game/core/settings.gd b/game/core/settings.gd index 9d0d1829..eeac574c 100644 --- a/game/core/settings.gd +++ b/game/core/settings.gd @@ -61,10 +61,13 @@ const OPTIONS: Dictionary[StringName, String] = { &"sticky_shift": SECTION_ACCESS, &"game_speed": SECTION_GAME, &"difficulty": SECTION_GAME, + &"msaa_3d": SECTION_DISPLAY, } const MIN_PAN_SPEED: float = 0.5 const MAX_PAN_SPEED: float = 2.0 const MIN_RENDER_SCALE: float = 0.5 +const GRAPHICS_DEFAULTS_VERSION: int = 2 +const MSAA_MODES: Array[int] = [Viewport.MSAA_DISABLED, Viewport.MSAA_2X, Viewport.MSAA_4X] ## Linear volumes in [0, 1]. var master_volume: float = 1.0 @@ -85,6 +88,10 @@ var fullscreen: bool = false var quality: StringName = QUALITY_HIGH ## 3D resolution scale, MIN_RENDER_SCALE..1. var render_scale: float = 1.0 +var msaa_3d: Viewport.MSAA = Viewport.MSAA_2X +var graphics_defaults_version: int = GRAPHICS_DEFAULTS_VERSION +var graphics_upgrade_available: bool = false +var launch_graphics_changed: bool = false ## One of PALETTES. var colour_palette: StringName = PALETTE_DEFAULT ## The Advisor's lines are written on screen. @@ -117,18 +124,22 @@ var _web_fullscreen_pending: bool = false func _ready() -> void: KeyBindings.install() - # Conservative Web defaults keep software WebGL and modest GPUs responsive. - # Load afterwards so the player's saved graphics choices take precedence. - if OS.has_feature("web"): - quality = QUALITY_LOW - render_scale = MIN_RENDER_SCALE load_from(path) if OS.has_feature("web"): fullscreen = false + get_tree().root.size_changed.connect(_apply_ui_scale) _web_fullscreen_callback = JavaScriptBridge.create_callback(_on_web_fullscreen_changed) var browser: JavaScriptObject = JavaScriptBridge.get_interface("window") browser.set("farlandingFullscreenChanged", _web_fullscreen_callback) + # An explicit launcher choice wins over saved preferences; Saved keeps them. + for arg: String in OS.get_cmdline_user_args(): + if arg.begins_with("--graphics-profile="): + launch_graphics_changed = _use_graphics_profile( + StringName(arg.get_slice("=", 1)), false + ) apply_display() + if launch_graphics_changed: + save_to() func save_to(target: String = "") -> Error: @@ -145,6 +156,7 @@ func save_to(target: String = "") -> Error: config.set_value(SECTION_DISPLAY, "fullscreen", fullscreen) config.set_value(SECTION_DISPLAY, "quality", String(quality)) config.set_value(SECTION_DISPLAY, "render_scale", render_scale) + config.set_value(SECTION_DISPLAY, "graphics_defaults_version", graphics_defaults_version) config.set_value(SECTION_HINTS, "seen", hints_seen) config.set_value(SECTION_GAME, "missions_won", missions_won) for key: StringName in OPTIONS: @@ -181,6 +193,18 @@ func load_from(source: String = "") -> void: quality = StringName(preset) if QUALITIES.has(StringName(preset)) else QUALITY_HIGH var scale: float = config.get_value(SECTION_DISPLAY, "render_scale", render_scale) render_scale = clampf(scale, MIN_RENDER_SCALE, 1.0) + # Existing files without AA preserve their previous (disabled) antialiasing. + var aa: Variant = config.get_value(SECTION_DISPLAY, "msaa_3d", Viewport.MSAA_DISABLED) + var aa_code: int = aa if aa is int else Viewport.MSAA_DISABLED + msaa_3d = aa_code as Viewport.MSAA if MSAA_MODES.has(aa_code) else Viewport.MSAA_DISABLED + var version: Variant = config.get_value(SECTION_DISPLAY, "graphics_defaults_version", 0) + graphics_defaults_version = version if version is int else 0 + graphics_upgrade_available = ( + OS.has_feature("web") + and graphics_defaults_version < GRAPHICS_DEFAULTS_VERSION + and quality == QUALITY_LOW + and is_equal_approx(render_scale, MIN_RENDER_SCALE) + ) var seen: PackedStringArray = config.get_value(SECTION_HINTS, "seen", PackedStringArray()) hints_seen = seen # Older files have no list: nothing won yet. @@ -250,6 +274,7 @@ func set_quality(preset: StringName) -> void: if not QUALITIES.has(preset) or preset == quality: return quality = preset + _acknowledge_graphics() _changed() @@ -258,13 +283,40 @@ func set_render_scale(value: float) -> void: if is_equal_approx(clamped, render_scale): return render_scale = clamped + _acknowledge_graphics() apply_display() _changed() +## Applies only graphics; audio, controls, accessibility and progress are retained. +func _use_graphics_profile(preset: StringName, persist: bool = true) -> bool: + if not QUALITIES.has(preset) and preset != &"saved": + return false + if preset != &"saved": + var profile: GraphicsProfile = GraphicsProfile.for_quality(preset) + quality = preset + render_scale = profile.render_scale + msaa_3d = profile.msaa_3d + _acknowledge_graphics() + apply_display() + if persist: + _changed() + return true + + +func _acknowledge_graphics() -> void: + graphics_defaults_version = GRAPHICS_DEFAULTS_VERSION + graphics_upgrade_available = false + + ## Sets one of OPTIONS (`key`) to `value`; a value it cannot take is refused. ## Returns true when the option changed. func set_option(key: StringName, value: Variant) -> bool: + if key == &"graphics_profile": + if not (value is String or value is StringName): + return false + var preset: StringName = value + return _use_graphics_profile(preset) if not OPTIONS.has(key): return false var current: Variant = get(key) @@ -272,7 +324,9 @@ func set_option(key: StringName, value: Variant) -> bool: if next == null or next == current: return false set(key, next) - if key == &"ui_scale": + if key == &"msaa_3d": + _acknowledge_graphics() + if key in [&"ui_scale", &"msaa_3d"]: apply_display() _changed() return true @@ -338,7 +392,7 @@ func reset_hints() -> void: func apply_display() -> void: if not is_inside_tree(): return - get_tree().root.content_scale_factor = ui_scale + _apply_ui_scale() if DisplayServer.get_name() == "headless": return var mode: DisplayServer.WindowMode = ( @@ -347,6 +401,16 @@ func apply_display() -> void: if DisplayServer.window_get_mode() != mode: DisplayServer.window_set_mode(mode) get_tree().root.scaling_3d_scale = render_scale + get_tree().root.msaa_3d = msaa_3d + + +func _apply_ui_scale() -> void: + var scale: float = ui_scale + if OS.has_feature("web"): + # Web canvas sizes are physical pixels; UI preferences are CSS-sized. + scale *= DisplayServer.screen_get_scale() + if not is_equal_approx(get_tree().root.content_scale_factor, scale): + get_tree().root.content_scale_factor = scale ## The InputMap follows the bindings of the current scheme (the autoload only: a @@ -369,6 +433,8 @@ static func _volume(config: ConfigFile, key: String, fallback: float) -> float: ## `value` as option `key` takes it, or `fallback` when it cannot. static func _sanitized(key: StringName, value: Variant, fallback: Variant) -> Variant: match key: + &"msaa_3d": + return value if value is int and MSAA_MODES.has(value) else fallback &"colour_palette": var palette: StringName = StringName(str(value)) return palette if PALETTES.has(palette) else fallback diff --git a/game/data/graphics/balanced.tres b/game/data/graphics/balanced.tres new file mode 100644 index 00000000..fd4b6254 --- /dev/null +++ b/game/data/graphics/balanced.tres @@ -0,0 +1,12 @@ +[gd_resource type="Resource" script_class="GraphicsProfile" load_steps=2 format=3] + +[ext_resource type="Script" path="res://core/graphics_profile.gd" id="1"] + +[resource] +script = ExtResource("1") +render_scale = 1.0 +msaa_3d = 0 +shadow_size = 2048 +soft_shadows = false +ssao_enabled = true +glow_enabled = true diff --git a/game/data/graphics/high.tres b/game/data/graphics/high.tres new file mode 100644 index 00000000..96402ba5 --- /dev/null +++ b/game/data/graphics/high.tres @@ -0,0 +1,12 @@ +[gd_resource type="Resource" script_class="GraphicsProfile" load_steps=2 format=3] + +[ext_resource type="Script" path="res://core/graphics_profile.gd" id="1"] + +[resource] +script = ExtResource("1") +render_scale = 1.0 +msaa_3d = 1 +shadow_size = 4096 +soft_shadows = true +ssao_enabled = true +glow_enabled = true diff --git a/game/data/graphics/performance.tres b/game/data/graphics/performance.tres new file mode 100644 index 00000000..416c676b --- /dev/null +++ b/game/data/graphics/performance.tres @@ -0,0 +1,12 @@ +[gd_resource type="Resource" script_class="GraphicsProfile" load_steps=2 format=3] + +[ext_resource type="Script" path="res://core/graphics_profile.gd" id="1"] + +[resource] +script = ExtResource("1") +render_scale = 0.5 +msaa_3d = 0 +shadow_size = 0 +soft_shadows = false +ssao_enabled = false +glow_enabled = false diff --git a/game/main.gd b/game/main.gd index 45195cf7..efa50c91 100644 --- a/game/main.gd +++ b/game/main.gd @@ -95,7 +95,7 @@ var _web_focus_callback: JavaScriptObject func _ready() -> void: - if OS.has_feature("web_diagnostics"): + if OS.has_feature("web_diagnostics") and get_parent() == get_tree().root: var args: PackedStringArray = OS.get_cmdline_user_args() if args.has("--web-bench"): get_tree().change_scene_to_file.call_deferred("res://tests/bench/bench_battle.tscn") @@ -103,6 +103,9 @@ func _ready() -> void: if args.has("--web-audio"): get_tree().change_scene_to_file.call_deferred("res://tests/web/audio_qa.tscn") return + if args.has("--web-visual"): + get_tree().change_scene_to_file.call_deferred("res://tests/web/visual_compare.tscn") + return Events.campaign_save_failed.connect(_on_campaign_save_failed) if campaign_def == null and ResourceLoader.exists(CAMPAIGN): campaign_def = load(CAMPAIGN) as CampaignDef @@ -199,12 +202,31 @@ func _ready() -> void: _web_storage.confirmed.connect(_on_storage_confirmed) Events.campaign_saved.connect(_confirm_storage) Settings.changed.connect(_confirm_settings.call_deferred) + if Settings.launch_graphics_changed: + _confirm_settings.call_deferred() JavaScriptBridge.eval("window.farlanding.ready = true") if not OS.is_userfs_persistent(): JavaScriptBridge.eval("storageFailed()") if OS.has_feature("web_diagnostics"): var probe: Node = (load("res://tests/web/web_probe.gd") as GDScript).new() add_child(probe) + if Settings.graphics_upgrade_available: + _offer_graphics_upgrade.call_deferred() + + +func _offer_graphics_upgrade() -> void: + var prompt: GraphicsUpgradePrompt = GraphicsUpgradePrompt.new() + _layer.add_child(prompt) + prompt.use_high_pressed.connect( + func() -> void: + Settings.set_option(&"graphics_profile", Settings.QUALITY_HIGH) + prompt.queue_free() + ) + prompt.keep_current_pressed.connect( + func() -> void: + Settings.set_option(&"graphics_profile", &"saved") + prompt.queue_free() + ) func _notification(what: int) -> void: @@ -377,6 +399,7 @@ func start_mission( return Events.ui_feedback.emit(&"menu_close") map = mission.map_scene.instantiate() + GraphicsSettings.prepare(map) map.set(&"mission", mission) if modifiers != null: map.set(&"modifiers", modifiers) @@ -716,6 +739,7 @@ func _show_backdrop(path: String) -> void: var scene: PackedScene = load(path) as PackedScene if scene != null: backdrop = scene.instantiate() + GraphicsSettings.prepare(backdrop) backdrop.name = &"Backdrop" add_child(backdrop) move_child(backdrop, 0) diff --git a/game/platform/web_shell.html b/game/platform/web_shell.html index c5ffff52..dad0a826 100644 --- a/game/platform/web_shell.html +++ b/game/platform/web_shell.html @@ -9,6 +9,7 @@ #canvas { display:block; width:100%; height:100%; outline:none; } #launch { position:fixed; inset:0; display:grid; place-content:center; text-align:center; background:#131b20; z-index:2; } button { padding:16px 32px; background:#df813a; color:#10171c; border:0; border-radius:4px; font:inherit; cursor:pointer; } +select { margin:8px 0 16px; padding:10px; background:#202c34; color:#e5edf0; border:1px solid #536572; border-radius:4px; font:inherit; } #message { max-width:34em; white-space:pre-wrap; } #storage-warning { position:fixed; bottom:8px; left:8px; max-width:36em; padding:10px; background:#7b311f; z-index:3; } @@ -16,7 +17,7 @@ -

Farlanding

A Concord Survey expedition

Keyboard and mouse required. Saves stay in this browser.

+

Farlanding

A Concord Survey expedition

Keyboard and mouse required. Saves stay in this browser.

@@ -29,7 +30,16 @@ if (query.has('encounter')) config.args.push('--', '--web-encounter'); if (query.has('latency')) config.args.push('--', '--web-audio', '--web-latency'); if (query.has('audio')) config.args.push('--', '--web-audio'); - if (query.has('bench')) config.args.push('--', '--web-bench', '--seconds=' + (query.get('seconds') === '30' ? '30' : '120')); + if (query.has('visual')) { + const visual = query.get('visual'); + if (/^[a-z_]+$/.test(visual)) config.args.push('--', '--web-visual', '--visual=' + visual, + '--visual-quality=' + (query.get('quality') === 'low' ? 'low' : 'high'), + '--visual-scale=' + (query.get('scale') === '0.5' ? '0.5' : '1')); + } + if (query.has('bench')) { + config.args.push('--', '--web-bench', '--seconds=' + (query.get('seconds') === '30' ? '30' : '120'), '--bench-quality=' + (query.get('quality') === 'high' ? 'high' : 'medium'), '--bench-msaa=' + (query.get('msaa') === '2' ? '2' : '0')); + if (query.has('normal')) config.args.push('--normal-mission'); + } } const engine = new Engine(config); const canvas = document.getElementById('canvas'); @@ -115,6 +125,8 @@ canvas.addEventListener('contextmenu', event => event.preventDefault()); canvas.addEventListener('wheel', event => event.preventDefault(), {passive:false}); document.getElementById('start').addEventListener('click', async event => { + const profile = document.getElementById('graphics').value; + if (['high','medium','low'].includes(profile)) config.args.push('--', '--graphics-profile=' + profile); event.target.disabled = true; const missing = Engine.getMissingFeatures({ threads:$GODOT_THREADS_ENABLED }); if (missing.length) { diff --git a/game/presentation/campaign/star_backdrop.tscn b/game/presentation/campaign/star_backdrop.tscn index c0bd323e..2bb05639 100644 --- a/game/presentation/campaign/star_backdrop.tscn +++ b/game/presentation/campaign/star_backdrop.tscn @@ -13,6 +13,7 @@ sky_material = SubResource("sky_material") radiance_size = 1 [sub_resource type="Environment" id="env"] +resource_local_to_scene = true background_mode = 2 sky = SubResource("sky") ambient_light_source = 2 diff --git a/game/presentation/shaders/compatibility_color.gdshaderinc b/game/presentation/shaders/compatibility_color.gdshaderinc new file mode 100644 index 00000000..30e710d4 --- /dev/null +++ b/game/presentation/shaders/compatibility_color.gdshaderinc @@ -0,0 +1,9 @@ +// Compatibility has an LDR target. Preserve the hue of overbright highlights +// instead of letting each channel clip independently to white or yellow. +vec3 display_emission(vec3 color) { +#if CURRENT_RENDERER == RENDERER_COMPATIBILITY + return color / max(1.0, max(color.r, max(color.g, color.b))); +#else + return color; +#endif +} diff --git a/game/presentation/shaders/compatibility_color.gdshaderinc.uid b/game/presentation/shaders/compatibility_color.gdshaderinc.uid new file mode 100644 index 00000000..900a093d --- /dev/null +++ b/game/presentation/shaders/compatibility_color.gdshaderinc.uid @@ -0,0 +1 @@ +uid://cha6muow85qb5 diff --git a/game/presentation/shaders/fog.gdshaderinc b/game/presentation/shaders/fog.gdshaderinc index 363e2e38..9d16f706 100644 --- a/game/presentation/shaders/fog.gdshaderinc +++ b/game/presentation/shaders/fog.gdshaderinc @@ -20,9 +20,18 @@ vec2 fog_at(vec3 world) { // Three looks: never seen = the orbital chart (dark, cold, colourless); // seen before = a dimmed memory; visible = untouched. vec3 fog_color(vec3 color, vec2 fog) { +#if CURRENT_RENDERER == RENDERER_COMPATIBILITY + // Forward+ mixes in linear space; Compatibility shades in sRGB. Match the + // chart/memory contrast without changing the vision texture or visibility. + color = pow(max(color, vec3(0.0)), vec3(2.2)); +#endif float grey = dot(color, vec3(0.299, 0.587, 0.114)); // Values are low because they are still lit by the sun afterwards. vec3 charted = vec3(grey) * vec3(0.045, 0.062, 0.090); vec3 remembered = mix(vec3(grey), color, 0.5) * 0.30; - return mix(mix(charted, remembered, fog.g), color, fog.r); + vec3 result = mix(mix(charted, remembered, fog.g), color, fog.r); +#if CURRENT_RENDERER == RENDERER_COMPATIBILITY + result = pow(max(result, vec3(0.0)), vec3(1.0 / 2.2)); +#endif + return result; } diff --git a/game/presentation/shaders/lava.gdshader b/game/presentation/shaders/lava.gdshader index 937127cf..10fead6f 100644 --- a/game/presentation/shaders/lava.gdshader +++ b/game/presentation/shaders/lava.gdshader @@ -5,6 +5,7 @@ render_mode unshaded, cull_back; // slide past each other. #include "fog.gdshaderinc" +#include "compatibility_color.gdshaderinc" uniform vec3 hot_color : source_color = vec3(1.0, 0.62, 0.12); uniform vec3 flow_color : source_color = vec3(0.95, 0.22, 0.03); @@ -31,4 +32,5 @@ void fragment() { vec2 fog = fog_at(world_pos); // Unexplored lava is charted dark like everything else; remembered lava dims. ALBEDO = fog_color(color, fog) * mix(3.0, 1.0, fog.r); + ALBEDO = display_emission(ALBEDO); } diff --git a/game/presentation/shaders/terrain.gdshader b/game/presentation/shaders/terrain.gdshader index 2d0697bd..f0e3fd34 100644 --- a/game/presentation/shaders/terrain.gdshader +++ b/game/presentation/shaders/terrain.gdshader @@ -27,6 +27,7 @@ uniform float panel_size = 0.0; uniform vec3 panel_glow : source_color = vec3(0.75, 0.9, 1.0); #include "fog.gdshaderinc" +#include "compatibility_color.gdshaderinc" varying vec3 world_pos; varying vec3 world_normal; @@ -84,4 +85,5 @@ void fragment() { } NORMAL_MAP = texture(detail_normal, world_pos.xz / 7.0).rgb; NORMAL_MAP_DEPTH = mix(0.55, 0.15, cliff); + EMISSION = display_emission(EMISSION); } diff --git a/game/presentation/shaders/unit.gdshader b/game/presentation/shaders/unit.gdshader index 6e874bc0..8b848128 100644 --- a/game/presentation/shaders/unit.gdshader +++ b/game/presentation/shaders/unit.gdshader @@ -48,6 +48,7 @@ uniform vec3 cloak_color : source_color = vec3(0.2, 0.85, 1.0); const int BAYER[16] = int[16](0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5); #include "fog.gdshaderinc" +#include "compatibility_color.gdshaderinc" varying vec3 world_pos; @@ -99,4 +100,5 @@ void fragment() { if (build_progress < 1.0) { EMISSION += build_glow * (1.0 - smoothstep(0.0, 0.35, build_front - height)) * 3.0; } + EMISSION = display_emission(EMISSION); } diff --git a/game/tests/bench/bench_battle.gd b/game/tests/bench/bench_battle.gd index 5e43e2b7..789f355c 100644 --- a/game/tests/bench/bench_battle.gd +++ b/game/tests/bench/bench_battle.gd @@ -42,6 +42,9 @@ var _frame_ms: Array[float] = [] var _last_frame_usec: int = 0 var _peak_units: int = 0 var _finished: bool = false +var _quality: StringName = Settings.QUALITY_MEDIUM +var _normal_mission: bool = false +var _msaa: Viewport.MSAA = Viewport.MSAA_DISABLED var _logic_start: int = 0 var _render_start: int = 0 var _physics_start: int = 0 @@ -59,10 +62,18 @@ func _ready() -> void: RenderingServer.frame_post_draw.connect(_on_post_draw) var args: PackedStringArray = OS.get_cmdline_user_args() _storm = args.has("--storm") + _normal_mission = args.has("--normal-mission") + if args.has("--bench-msaa=2"): + _msaa = Viewport.MSAA_2X for arg: String in args: if arg.begins_with("--seconds="): _seconds = float(arg.get_slice("=", 1)) + elif arg.begins_with("--bench-quality="): + var requested: StringName = StringName(arg.get_slice("=", 1)) + if Settings.QUALITIES.has(requested): + _quality = requested _map = (load("res://maps/kessel_proving/kessel_proving.tscn") as PackedScene).instantiate() + GraphicsSettings.prepare(_map) _map.mission = load(MISSION) as MissionDef if args.has("--no-props"): _map.with_props = false @@ -71,8 +82,29 @@ func _ready() -> void: if OS.has_feature("web"): # Keep the reference benchmark comparable when fresh-profile defaults change. get_viewport().scaling_3d_scale = 1.0 - GraphicsSettings.apply(_map, Settings.QUALITY_MEDIUM) - _map.camera.center_on(Vector3.ZERO) + get_viewport().msaa_3d = _msaa + GraphicsSettings.apply(_map, _quality) + ( + JavaScriptBridge + . eval( + ( + "window.farlanding.benchmarkProfile = " + + ( + JSON + . stringify( + { + "quality": _quality, + "render_scale": 1.0, + "msaa": get_viewport().msaa_3d, + "normal_mission": _normal_mission, + } + ) + ) + ) + ) + ) + if not _normal_mission: + _map.camera.center_on(Vector3.ZERO) JavaScriptBridge.eval("window.farlanding.ready = true") @@ -93,8 +125,9 @@ func _process(_delta: float) -> void: func _drop_armies() -> void: var world: SimWorld = _map.world - _spawn(world, PLAYER_ROSTER, 0, PLAYER_CENTRE, ENEMY_CENTRE) - _spawn(world, ENEMY_ROSTER, 1, ENEMY_CENTRE, PLAYER_CENTRE) + if not _normal_mission: + _spawn(world, PLAYER_ROSTER, 0, PLAYER_CENTRE, ENEMY_CENTRE) + _spawn(world, ENEMY_ROSTER, 1, ENEMY_CENTRE, PLAYER_CENTRE) _peak_units = world.units.size() world.profiling = OS.get_cmdline_user_args().has("--sections") world.profiling_units = world.profiling diff --git a/game/tests/test_settings_menu.gd b/game/tests/test_settings_menu.gd index 74086f96..6a7a4436 100644 --- a/game/tests/test_settings_menu.gd +++ b/game/tests/test_settings_menu.gd @@ -20,6 +20,9 @@ func before_each() -> void: "fullscreen", "quality", "render_scale", + "msaa_3d", + "graphics_defaults_version", + "graphics_upgrade_available", "hints_seen", "path", ]: @@ -119,6 +122,14 @@ func test_the_settings_panel_writes_through() -> void: assert_eq(Settings.edge_pan, edge) panel._on_quality_selected(0) assert_eq(Settings.quality, Settings.QUALITY_LOW) + assert_eq(Settings.render_scale, 0.5) + assert_eq(Settings.msaa_3d, Viewport.MSAA_DISABLED) + panel._on_quality_selected(2) + assert_eq(Settings.render_scale, 1.0) + assert_eq(Settings.msaa_3d, Viewport.MSAA_2X) + panel._on_antialiasing_selected(2) + assert_eq(Settings.msaa_3d, Viewport.MSAA_4X) + assert_eq(panel._quality.selected, 3, "independent AA changes report a custom preset") Settings.mark_hint_seen(&"storm") panel._on_reset_hints() assert_false(Settings.has_seen_hint(&"storm")) diff --git a/game/tests/ui/settings_guard.gd b/game/tests/ui/settings_guard.gd index 05373227..6400e779 100644 --- a/game/tests/ui/settings_guard.gd +++ b/game/tests/ui/settings_guard.gd @@ -18,6 +18,10 @@ const KEYS: Array[String] = [ "fullscreen", "quality", "render_scale", + "msaa_3d", + "graphics_defaults_version", + "graphics_upgrade_available", + "launch_graphics_changed", "colour_palette", "subtitles", "subtitle_size", diff --git a/game/tests/ui/test_graphics_profiles.gd b/game/tests/ui/test_graphics_profiles.gd new file mode 100644 index 00000000..31a3b260 --- /dev/null +++ b/game/tests/ui/test_graphics_profiles.gd @@ -0,0 +1,107 @@ +extends GutTest + +const SETTINGS_SCRIPT = preload("res://core/settings.gd") +const PATH: String = "user://test_graphics_profiles.cfg" + + +func after_each() -> void: + DirAccess.remove_absolute(ProjectSettings.globalize_path(PATH)) + + +func test_fresh_profiles_start_high_at_full_resolution_with_msaa() -> void: + var prefs := SETTINGS_SCRIPT.new() + autofree(prefs) + assert_eq(prefs.quality, Settings.QUALITY_HIGH) + assert_eq(prefs.render_scale, 1.0) + assert_eq(prefs.msaa_3d, Viewport.MSAA_2X) + + +func test_switching_profiles_preserves_non_graphics_preferences() -> void: + var prefs := SETTINGS_SCRIPT.new() + autofree(prefs) + prefs.path = PATH + prefs.music_volume = 0.27 + prefs.control_scheme = Settings.SCHEME_MODERN + prefs.hints_seen = PackedStringArray(["select_move"]) + prefs.missions_won = PackedStringArray(["conquest"]) + assert_true(prefs.set_option(&"graphics_profile", &"low")) + assert_eq(prefs.render_scale, 0.5) + assert_eq(prefs.msaa_3d, Viewport.MSAA_DISABLED) + assert_true(prefs.set_option(&"graphics_profile", &"high")) + assert_eq(prefs.render_scale, 1.0) + assert_eq(prefs.msaa_3d, Viewport.MSAA_2X) + assert_eq(prefs.music_volume, 0.27) + assert_eq(prefs.control_scheme, Settings.SCHEME_MODERN) + assert_eq(prefs.hints_seen, PackedStringArray(["select_move"])) + assert_eq(prefs.missions_won, PackedStringArray(["conquest"])) + + +func test_custom_resolution_and_antialiasing_survive_reload() -> void: + var prefs := SETTINGS_SCRIPT.new() + autofree(prefs) + prefs.path = PATH + prefs.render_scale = 0.85 + assert_true(prefs.set_option(&"msaa_3d", Viewport.MSAA_4X)) + var loaded := SETTINGS_SCRIPT.new() + autofree(loaded) + loaded.load_from(PATH) + assert_eq(loaded.render_scale, 0.85) + assert_eq(loaded.msaa_3d, Viewport.MSAA_4X) + assert_eq(loaded.graphics_defaults_version, Settings.GRAPHICS_DEFAULTS_VERSION) + + +func test_keeping_legacy_graphics_acknowledges_without_overwriting_them() -> void: + var config: ConfigFile = ConfigFile.new() + config.set_value("display", "quality", "low") + config.set_value("display", "render_scale", 0.5) + config.set_value("audio", "music_volume", 0.42) + config.save(PATH) + var prefs := SETTINGS_SCRIPT.new() + autofree(prefs) + prefs.path = PATH + prefs.load_from(PATH) + assert_eq(prefs.msaa_3d, Viewport.MSAA_DISABLED, "old files keep their prior AA") + assert_eq(prefs.graphics_defaults_version, 0) + assert_true(prefs.set_option(&"graphics_profile", &"saved")) + assert_eq(prefs.quality, Settings.QUALITY_LOW) + assert_eq(prefs.render_scale, 0.5) + assert_eq(prefs.music_volume, 0.42) + assert_eq(prefs.graphics_defaults_version, Settings.GRAPHICS_DEFAULTS_VERSION) + + +func test_invalid_graphics_options_are_refused() -> void: + var prefs := SETTINGS_SCRIPT.new() + autofree(prefs) + prefs.path = PATH + assert_false(prefs.set_option(&"msaa_3d", -1)) + assert_false(prefs.set_option(&"msaa_3d", 3)) + assert_false(prefs.set_option(&"graphics_profile", &"ultra")) + assert_false(prefs.set_option(&"graphics_profile", 123)) + assert_eq(prefs.msaa_3d, Viewport.MSAA_2X) + + +func test_quality_restores_authored_ambient_occlusion() -> void: + var root: Node3D = Node3D.new() + autofree(root) + var world: WorldEnvironment = WorldEnvironment.new() + world.environment = Environment.new() + world.environment.ssao_enabled = true + root.add_child(world) + GraphicsSettings.apply(root, Settings.QUALITY_LOW) + assert_false(world.environment.ssao_enabled) + GraphicsSettings.apply(root, Settings.QUALITY_HIGH) + assert_true(world.environment.ssao_enabled) + + +func test_low_quality_does_not_change_a_new_scene_authored_environment() -> void: + var scene: PackedScene = load("res://presentation/campaign/star_backdrop.tscn") as PackedScene + var first: Node3D = scene.instantiate() as Node3D + autofree(first) + GraphicsSettings.apply(first, Settings.QUALITY_LOW) + var second: Node3D = scene.instantiate() as Node3D + autofree(second) + GraphicsSettings.apply(second, Settings.QUALITY_HIGH) + var environment: Environment = ( + (second.get_node(^"WorldEnvironment") as WorldEnvironment).environment + ) + assert_true(environment.glow_enabled, "High restores the authored glow in a fresh scene") diff --git a/game/tests/ui/test_graphics_profiles.gd.uid b/game/tests/ui/test_graphics_profiles.gd.uid new file mode 100644 index 00000000..b2e76ff3 --- /dev/null +++ b/game/tests/ui/test_graphics_profiles.gd.uid @@ -0,0 +1 @@ +uid://c4tkj8rno778x diff --git a/game/tests/web/visual_compare.gd b/game/tests/web/visual_compare.gd new file mode 100644 index 00000000..5aff89a3 --- /dev/null +++ b/game/tests/web/visual_compare.gd @@ -0,0 +1,90 @@ +extends Node +## Diagnostic-only, fixed-camera visual reference. Never included in release exports. + +var _main: Main + + +func _ready() -> void: + var mission_id: String = "conquest" + var quality: StringName = Settings.QUALITY_HIGH + var scale: float = 1.0 + var output: String = "" + for arg: String in OS.get_cmdline_user_args(): + if arg.begins_with("--visual="): + mission_id = arg.get_slice("=", 1) + elif arg.begins_with("--visual-quality="): + quality = StringName(arg.get_slice("=", 1)) + elif arg.begins_with("--visual-scale="): + scale = float(arg.get_slice("=", 1)) + elif arg.begins_with("--visual-output="): + output = arg.get_slice("=", 1) + Settings.path = "user://visual_comparison_settings.cfg" + Settings.launch_graphics_changed = false + Settings.graphics_upgrade_available = false + SaveSlots.default_dir = "user://visual_comparison_saves/" + Settings.quality = quality + Settings.render_scale = scale + Settings.msaa_3d = GraphicsProfile.for_quality(quality).msaa_3d + Settings.ui_scale = 1.0 + Settings.edge_pan = false + Settings.fullscreen = false + Settings.apply_display() + seed(1729) + var subject: Node3D + if mission_id == "orbit": + subject = (load(Main.STAR_BACKDROP_SCENE) as PackedScene).instantiate() as Node3D + GraphicsSettings.prepare(subject) + add_child(subject) + GraphicsSettings.apply(subject, quality) + subject.set_process(false) + # A clean reference composition, without the campaign's UI framing. + var orbit_camera: Camera3D = subject.get_node(^"Camera3D") as Camera3D + orbit_camera.position.y = 80.0 + orbit_camera.fov = 30.0 + else: + _main = (load("res://main.tscn") as PackedScene).instantiate() as Main + add_child(_main) + var mission: MissionDef = load("res://data/missions/%s.tres" % mission_id) as MissionDef + _main.start_mission(mission, _main.single_modifiers(Difficulty.NORMAL)) + await get_tree().process_frame + _main.runner.context.sim_clock.paused = true + _main._hints.end_mission() + var camera: RtsCamera = _main.map.get(&"camera") + camera.set_process(false) + subject = _main.map as Node3D + var environment: WorldEnvironment = ( + subject.find_child("WorldEnvironment", true, false) as WorldEnvironment + ) + # Capture the authored landing camera identically, with the full starting crew. + for frame: int in 12: + await get_tree().process_frame + var lights: Array[Node] = subject.find_children("*", "DirectionalLight3D", true, false) + var report: Dictionary = { + "ambient_energy": environment.environment.ambient_light_energy, + "exposure": environment.environment.tonemap_exposure, + "sun_energy": + (lights[0] as DirectionalLight3D).light_energy if not lights.is_empty() else 0.0, + "physical_lights": + ProjectSettings.get_setting("rendering/lights_and_shadows/use_physical_light_units", false), + "mission": mission_id, + "renderer": RenderingServer.get_current_rendering_method(), + "quality": quality, + "render_scale": scale, + "viewport": + [get_viewport().get_visible_rect().size.x, get_viewport().get_visible_rect().size.y], + "msaa": get_viewport().msaa_3d, + "display_scale": get_tree().root.content_scale_factor, + "draw_calls": + RenderingServer.get_rendering_info( + RenderingServer.RENDERING_INFO_TOTAL_DRAW_CALLS_IN_FRAME + ), + } + if OS.has_feature("web"): + JavaScriptBridge.eval("window.farlanding.visual = " + JSON.stringify(report)) + JavaScriptBridge.eval("window.farlanding.ready = true") + elif output != "": + await RenderingServer.frame_post_draw + get_viewport().get_texture().get_image().save_png(output + ".png") + var file: FileAccess = FileAccess.open(output + ".json", FileAccess.WRITE) + file.store_string(JSON.stringify(report, "\t")) + get_tree().quit() diff --git a/game/tests/web/visual_compare.gd.uid b/game/tests/web/visual_compare.gd.uid new file mode 100644 index 00000000..062deb7a --- /dev/null +++ b/game/tests/web/visual_compare.gd.uid @@ -0,0 +1 @@ +uid://b0sayjivo4l8 diff --git a/game/tests/web/visual_compare.tscn b/game/tests/web/visual_compare.tscn new file mode 100644 index 00000000..3bd15763 --- /dev/null +++ b/game/tests/web/visual_compare.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://tests/web/visual_compare.gd" id="1"] + +[node name="VisualComparison" type="Node"] +script = ExtResource("1") diff --git a/game/tests/web/web_probe.gd b/game/tests/web/web_probe.gd index c7fb6551..7f596180 100644 --- a/game/tests/web/web_probe.gd +++ b/game/tests/web/web_probe.gd @@ -39,8 +39,15 @@ func _process(delta: float) -> void: var data: Dictionary = { "quality": Settings.quality, "render_scale": Settings.render_scale, + "msaa": Settings.msaa_3d, + "graphics_upgrade_available": Settings.graphics_upgrade_available, + "graphics_defaults_version": Settings.graphics_defaults_version, + "viewport_size": + [get_viewport().get_visible_rect().size.x, get_viewport().get_visible_rect().size.y], "scheme": Settings.control_scheme, + "music_volume": Settings.music_volume, "ui_scale": Settings.ui_scale, + "display_scale": get_tree().root.content_scale_factor, "fullscreen": Settings.fullscreen, "audio_playback": "stream" if playback_type == 0 else "sample", "music_source_layers": _score.clips[0].layers.size(), @@ -102,14 +109,14 @@ func _process(delta: float) -> void: for offset: Vector3 in [Vector3(12, 0, 0), Vector3(0, 0, -12), Vector3(15, 0, -15)]: var point: Vector3 = map.camera.get_focus() + offset point.y = map.heights.sample(point.x, point.z) - var pixel: Vector2 = camera.unproject_position(point) + var pixel: Vector2 = camera.unproject_position(point) * _css_scale() ground.append([pixel.x, pixel.y]) JavaScriptBridge.eval("window.farlanding.diagnostics = " + JSON.stringify(data)) func _entity(entity: Node3D, camera: Camera3D) -> Dictionary: var point: Vector3 = entity.global_position - var pixel: Vector2 = camera.unproject_position(point + Vector3.UP) + var pixel: Vector2 = camera.unproject_position(point + Vector3.UP) * _css_scale() return { "id": entity.get("entity_id"), "position": [point.x, point.y, point.z], @@ -122,7 +129,7 @@ func _buttons(node: Node, result: Array, popups: Array) -> void: var button: Button = node as Button if button.is_visible_in_tree() and not button.disabled: var rect: Rect2 = button.get_global_rect() - var point: Vector2 = rect.get_center() * get_tree().root.content_scale_factor + var point: Vector2 = rect.get_center() * _css_scale() result.append({"name": button.name, "text": button.text, "pixel": [point.x, point.y]}) if node is PopupMenu: var popup: PopupMenu = node as PopupMenu @@ -136,15 +143,8 @@ func _buttons(node: Node, result: Array, popups: Array) -> void: { "items": items, "position": - [ - popup.position.x * get_tree().root.content_scale_factor, - popup.position.y * get_tree().root.content_scale_factor - ], - "size": - [ - popup.size.x * get_tree().root.content_scale_factor, - popup.size.y * get_tree().root.content_scale_factor - ], + [popup.position.x * _css_scale(), popup.position.y * _css_scale()], + "size": [popup.size.x * _css_scale(), popup.size.y * _css_scale()], } ) ) @@ -152,6 +152,10 @@ func _buttons(node: Node, result: Array, popups: Array) -> void: _buttons(child, result, popups) +func _css_scale() -> float: + return get_tree().root.content_scale_factor / DisplayServer.screen_get_scale() + + func _p95() -> float: var sorted: Array[float] = _frames.duplicate() sorted.sort() diff --git a/game/ui/graphics_settings.gd b/game/ui/graphics_settings.gd index f32189e2..9294a52a 100644 --- a/game/ui/graphics_settings.gd +++ b/game/ui/graphics_settings.gd @@ -7,21 +7,43 @@ extends RefCounted const SHADOW_META: StringName = &"fl_shadow_enabled" const GLOW_META: StringName = &"fl_glow_enabled" -## Directional shadow atlas size per preset (0 = shadows off). -const SHADOW_SIZE: Dictionary[StringName, int] = {&"low": 0, &"medium": 2048, &"high": 4096} +const SSAO_META: StringName = &"fl_ssao_enabled" +const LIGHTING_META: StringName = &"fl_compatibility_lighting" +## Matched against the fixed-camera Forward+ references, not a quality reduction. +const COMPATIBILITY_LIGHT_ENERGY: float = 0.35 +const COMPATIBILITY_AMBIENT_ENERGY: float = 0.55 + + +## Call before adding the map to the tree: weather caches these authored baselines. +static func prepare(root: Node) -> void: + if RenderingServer.get_current_rendering_method() != "gl_compatibility": + return + if root.has_meta(LIGHTING_META): + return + root.set_meta(LIGHTING_META, true) + for node: Node in root.find_children("*", "DirectionalLight3D", true, false): + (node as DirectionalLight3D).light_energy *= COMPATIBILITY_LIGHT_ENERGY + for node: Node in root.find_children("*", "WorldEnvironment", true, false): + var environment: Environment = (node as WorldEnvironment).environment + if environment != null: + environment.ambient_light_energy *= COMPATIBILITY_AMBIENT_ENERGY + # LDR highlights cannot cross the native HDR threshold (> 1). + environment.glow_hdr_threshold = minf(environment.glow_hdr_threshold, 0.9) + environment.glow_hdr_scale = 0.2 ## Applies `preset` to every light and environment under `root`. static func apply(root: Node, preset: StringName) -> void: if root == null: return - var size: int = SHADOW_SIZE.get(preset, 4096) + var profile: GraphicsProfile = GraphicsProfile.for_quality(preset) + var size: int = profile.shadow_size if size > 0: RenderingServer.directional_shadow_atlas_set_size(size, true) RenderingServer.directional_soft_shadow_filter_set_quality( ( RenderingServer.SHADOW_QUALITY_SOFT_HIGH - if preset == Settings.QUALITY_HIGH + if profile.soft_shadows else RenderingServer.SHADOW_QUALITY_SOFT_LOW ) ) @@ -39,4 +61,8 @@ static func apply(root: Node, preset: StringName) -> void: if not world_environment.has_meta(GLOW_META): world_environment.set_meta(GLOW_META, environment.glow_enabled) var glow: bool = world_environment.get_meta(GLOW_META) - environment.glow_enabled = glow and preset != Settings.QUALITY_LOW + if not world_environment.has_meta(SSAO_META): + world_environment.set_meta(SSAO_META, environment.ssao_enabled) + var ssao: bool = world_environment.get_meta(SSAO_META) + environment.glow_enabled = glow and profile.glow_enabled + environment.ssao_enabled = ssao and profile.ssao_enabled diff --git a/game/ui/graphics_upgrade_prompt.gd b/game/ui/graphics_upgrade_prompt.gd new file mode 100644 index 00000000..266b245f --- /dev/null +++ b/game/ui/graphics_upgrade_prompt.gd @@ -0,0 +1,46 @@ +class_name GraphicsUpgradePrompt +extends Control +## A one-time choice for profiles that may have inherited the old Web downgrade. + +signal use_high_pressed +signal keep_current_pressed + + +func _ready() -> void: + set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + mouse_filter = Control.MOUSE_FILTER_STOP + var dim: ColorRect = ColorRect.new() + dim.color = Color(0.02, 0.03, 0.04, 0.88) + add_child(dim) + dim.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + var centre: CenterContainer = CenterContainer.new() + add_child(centre) + centre.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + var panel: PanelContainer = HudStyle.make_panel() + centre.add_child(panel) + var column: VBoxContainer = VBoxContainer.new() + column.custom_minimum_size.x = 430 + column.add_theme_constant_override(&"separation", 14) + panel.add_child(column) + column.add_child(HudStyle.make_label(24, HudStyle.TEXT_COLOR, "Sharper graphics are available")) + var text: Label = HudStyle.make_label( + 14, + HudStyle.MUTED_COLOR, + ( + "Try full-resolution rendering, clearer edges, shadows and glow.\n" + + "Your controls, audio and progress stay as they are." + ) + ) + text.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + text.custom_minimum_size.x = 430 + column.add_child(text) + var buttons: HBoxContainer = HBoxContainer.new() + buttons.add_theme_constant_override(&"separation", 12) + column.add_child(buttons) + var keep: Button = HudStyle.make_small_button("KEEP CURRENT") + keep.pressed.connect(func() -> void: keep_current_pressed.emit()) + buttons.add_child(keep) + var high: Button = HudStyle.make_small_button("USE HIGH GRAPHICS") + high.pressed.connect(func() -> void: use_high_pressed.emit()) + buttons.add_child(high) + high.grab_focus() diff --git a/game/ui/graphics_upgrade_prompt.gd.uid b/game/ui/graphics_upgrade_prompt.gd.uid new file mode 100644 index 00000000..4fdde1c8 --- /dev/null +++ b/game/ui/graphics_upgrade_prompt.gd.uid @@ -0,0 +1 @@ +uid://cnq8t07orwjwp diff --git a/game/ui/settings_panel.gd b/game/ui/settings_panel.gd index 58b90795..4b247238 100644 --- a/game/ui/settings_panel.gd +++ b/game/ui/settings_panel.gd @@ -38,8 +38,8 @@ const VOLUME_LABELS: Dictionary[StringName, String] = { &"ui_volume": "Interface", } const QUALITY_LABELS: Dictionary[StringName, String] = { - &"low": "Low (no shadows or glow)", - &"medium": "Medium", + &"low": "Performance", + &"medium": "Balanced", &"high": "High", } @@ -53,6 +53,7 @@ var _pan_speed: HSlider var _fullscreen: CheckButton var _quality: OptionButton var _render_scale: HSlider +var _antialiasing: OptionButton var _reset_hints: Button var _hint_note: Label var _palette: OptionButton @@ -144,12 +145,17 @@ func _build_general(column: VBoxContainer) -> void: var names: Array[String] = [] for preset: StringName in Settings.QUALITIES: names.append(QUALITY_LABELS[preset]) + names.append("Custom") _quality = _options(names) + _quality.set_item_disabled(3, true) _quality.item_selected.connect(_on_quality_selected) - _row(column, "Quality", _quality) + _row(column, "Graphics preset", _quality) _render_scale = _slider(Settings.MIN_RENDER_SCALE, 1.0, 0.05) _render_scale.value_changed.connect(_on_render_scale_changed) _row(column, "Resolution", _render_scale) + _antialiasing = _options(["Off", "2× MSAA", "4× MSAA"]) + _antialiasing.item_selected.connect(_on_antialiasing_selected) + _row(column, "Antialiasing", _antialiasing) _section(column, "TUTORIAL") _reset_hints = HudStyle.make_small_button("RESET HINTS") _reset_hints.pressed.connect(_on_reset_hints) @@ -273,7 +279,15 @@ func sync_from_settings() -> void: _pan_speed.value = Settings.pan_speed _fullscreen.button_pressed = Settings.fullscreen _quality.selected = Settings.QUALITIES.find(Settings.quality) + var profile: GraphicsProfile = GraphicsProfile.for_quality(Settings.quality) + if ( + not is_equal_approx(Settings.render_scale, profile.render_scale) + or Settings.msaa_3d != profile.msaa_3d + ): + _quality.selected = 3 _render_scale.value = Settings.render_scale + _render_scale.tooltip_text = "3D resolution: %d%%" % roundi(Settings.render_scale * 100) + _antialiasing.selected = Settings.MSAA_MODES.find(Settings.msaa_3d) var seen: int = Settings.hints_seen.size() _hint_note.text = "%d seen" % seen if seen > 0 else "all hints will show" _reset_hints.disabled = seen == 0 @@ -322,11 +336,17 @@ func _on_fullscreen_toggled(on: bool) -> void: func _on_quality_selected(index: int) -> void: - if not _syncing: - Settings.set_quality(Settings.QUALITIES[index]) + if not _syncing and index < Settings.QUALITIES.size(): + Settings.set_option(&"graphics_profile", Settings.QUALITIES[index]) Events.ui_feedback.emit(&"toggle") +func _on_antialiasing_selected(index: int) -> void: + if not _syncing: + Settings.set_option(&"msaa_3d", Settings.MSAA_MODES[index]) + _tick() + + func _on_render_scale_changed(value: float) -> void: if not _syncing: Settings.set_render_scale(value) diff --git a/tools/web_tests/audio.spec.cjs b/tools/web_tests/audio.spec.cjs index 2245705f..989bb35b 100644 --- a/tools/web_tests/audio.spec.cjs +++ b/tools/web_tests/audio.spec.cjs @@ -1,9 +1,10 @@ +const { play } = require('./launch.cjs'); const { test, expect } = require('@playwright/test'); const { captureAudio } = require('./audio-capture.cjs'); test('browser emits and records actual streamed audio after a gesture', async ({ page }, info) => { await page.addInitScript(captureAudio); await page.goto('http://127.0.0.1:8070'); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect.poll(() => page.evaluate(() => window.farlanding?.ready), { timeout: 90000 }).toBe(true); await page.mouse.click(630, 396, { delay: 80 }); await expect.poll(() => page.evaluate(() => window.audioCapture.rms)).toBeGreaterThan(0.0001); @@ -24,7 +25,7 @@ if (process.env.WEB_AUDIO_QA) { page.on('console', entry => logs.push({ type: entry.type(), text: entry.text() })); await page.addInitScript(captureAudio); await page.goto('http://127.0.0.1:8071/?audio'); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect.poll(() => page.evaluate(() => window.farlanding?.ready), { timeout: 90000 }).toBe(true); await page.mouse.click(600, 360, { delay: 80 }); await expect.poll(() => page.evaluate(() => window.farlanding.audioQa), { timeout: 540000 }).toBeTruthy(); diff --git a/tools/web_tests/campaign.spec.cjs b/tools/web_tests/campaign.spec.cjs index 4f94dc5d..e77424a7 100644 --- a/tools/web_tests/campaign.spec.cjs +++ b/tools/web_tests/campaign.spec.cjs @@ -1,3 +1,4 @@ +const { play } = require('./launch.cjs'); const { test, expect } = require('@playwright/test'); async function state(page) { return page.evaluate(() => window.farlanding?.diagnostics); } async function button(page, text) { @@ -9,7 +10,7 @@ async function button(page, text) { if (process.env.WEB_CAMPAIGN || process.env.WEB_BROAD) { test('campaign launch and Continue preserve the landing across reload', async ({ page }) => { await page.goto('http://127.0.0.1:8071'); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect.poll(async () => (await state(page))?.screen, { timeout: 90000 }).toBe('title'); await button(page, 'NEW CAMPAIGN'); await button(page, 'START'); @@ -26,7 +27,7 @@ test('campaign launch and Continue preserve the landing across reload', async ({ await expect.poll(async () => (await state(page)).quicksave).not.toBe(''); const saved = (await state(page)).quicksave; await page.reload(); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect.poll(async () => (await state(page))?.quicksave, { timeout: 90000 }).toBe(saved); await button(page, 'CONTINUE'); await expect.poll(async () => (await state(page)).tick).toBeGreaterThan(0); diff --git a/tools/web_tests/controls.spec.cjs b/tools/web_tests/controls.spec.cjs index f3072e6f..2db5e564 100644 --- a/tools/web_tests/controls.spec.cjs +++ b/tools/web_tests/controls.spec.cjs @@ -1,8 +1,9 @@ +const { play } = require('./launch.cjs'); const { test, expect } = require('@playwright/test'); async function state(page) { return page.evaluate(() => window.farlanding?.diagnostics); } async function boot(page, query = '') { await page.goto('http://127.0.0.1:8071/' + query); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect.poll(() => page.evaluate(() => window.farlanding?.ready), { timeout: 90000 }).toBe(true); await expect.poll(async () => !!(await state(page))).toBe(true); } @@ -34,6 +35,7 @@ for (const viewport of [{ width: 1280, height: 720 }, { width: 1920, height: 108 await button(page, `${Math.round((await state(page)).ui_scale * 100)}%`); await option(page, `${Math.round(scale * 100)}%`); await expect.poll(async () => (await state(page)).ui_scale).toBe(scale); + expect((await state(page)).display_scale).toBeCloseTo(scale * await page.evaluate(() => devicePixelRatio)); const back = (await state(page)).buttons.find(item => item.text.startsWith('BACK')); expect(back.pixel[0]).toBeGreaterThan(0); expect(back.pixel[0]).toBeLessThan(viewport.width); @@ -67,7 +69,7 @@ test('modern mouse scheme accepts movement and persists across reload', async ({ }).toBeGreaterThan(1); await expect.poll(() => page.evaluate(() => window.farlanding.saves.settings?.status)).toBe('saved'); await page.reload(); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect.poll(async () => (await state(page))?.scheme, { timeout: 90000 }).toBe('modern'); expect(await page.evaluate(() => window.farlanding.errors)).toEqual([]); }); diff --git a/tools/web_tests/deployment.spec.cjs b/tools/web_tests/deployment.spec.cjs index 56c1887d..2f843463 100644 --- a/tools/web_tests/deployment.spec.cjs +++ b/tools/web_tests/deployment.spec.cjs @@ -1,3 +1,4 @@ +const { play } = require('./launch.cjs'); const { test, expect } = require('@playwright/test'); if (process.env.WEB_DEPLOYMENT_URL && !process.env.WEB_DEPLOYMENT_PUBLIC_ONLY) { @@ -21,7 +22,7 @@ if (process.env.WEB_DEPLOYMENT_URL && !process.env.WEB_DEPLOYMENT_PUBLIC_ONLY) { expect(manifest.dirty).toBe(false); expect(manifest.preset).toBe('Web'); await page.goto(url); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect.poll(() => page.evaluate(() => window.farlanding?.ready), { timeout: 90000 }).toBe(true); expect(await page.evaluate(() => crossOriginIsolated)).toBe(true); expect(await page.evaluate(() => window.farlanding.diagnostics)).toBeUndefined(); diff --git a/tools/web_tests/failures.spec.cjs b/tools/web_tests/failures.spec.cjs index eb9101bf..ea31438d 100644 --- a/tools/web_tests/failures.spec.cjs +++ b/tools/web_tests/failures.spec.cjs @@ -1,9 +1,10 @@ +const { play } = require('./launch.cjs'); const { test, expect } = require('@playwright/test'); test('missing assets produce an actionable launch failure', async ({ page }) => { await page.route('**/index.pck', route => route.abort('failed')); await page.goto('http://127.0.0.1:8070'); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect.poll(() => page.evaluate(() => window.farlanding.errors.length), { timeout: 90000 }).toBeGreaterThan(0); await expect(page.locator('#message')).not.toHaveText('Loading expedition…'); expect(await page.evaluate(() => window.farlanding.ready)).toBe(false); @@ -21,7 +22,7 @@ test('a missing ready signal cannot pass the runtime gate', async ({ page }) => }); }); await page.goto('http://127.0.0.1:8070'); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect(page.locator('#launch')).toHaveCount(0, { timeout: 90000 }); await expect(page.waitForFunction(() => window.farlanding.ready, null, { timeout: 500 })).rejects.toThrow(); }); diff --git a/tools/web_tests/game.spec.cjs b/tools/web_tests/game.spec.cjs index 1a5126f9..df733800 100644 --- a/tools/web_tests/game.spec.cjs +++ b/tools/web_tests/game.spec.cjs @@ -1,3 +1,4 @@ +const { play } = require('./launch.cjs'); const { test, expect } = require('@playwright/test'); const fs = require('node:fs/promises'); const { captureAudio } = require('./audio-capture.cjs'); @@ -5,7 +6,7 @@ const { captureAudio } = require('./audio-capture.cjs'); async function state(page) { return page.evaluate(() => window.farlanding?.diagnostics); } async function boot(page, url) { await page.goto(url); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect.poll(() => page.evaluate(() => window.farlanding?.ready), { timeout: 90000 }).toBe(true); } async function button(page, label) { @@ -80,8 +81,9 @@ test('worker orders construction production and saves survive reload', async ({ expect((await state(page)).music_layers).toBe((await state(page)).music_source_layers); expect((await state(page)).music_volumes).toBe((await state(page)).music_source_layers); expect((await state(page)).audio_playback).toBe('stream'); - expect((await state(page)).quality).toBe('low'); - expect((await state(page)).render_scale).toBe(0.5); + const softwareProfile = process.env.WEB_GRAPHICS_PROFILE === 'low' || process.env.WEB_SOFTWARE || process.env.CI; + expect((await state(page)).quality).toBe(softwareProfile ? 'low' : 'high'); + expect((await state(page)).render_scale).toBe(softwareProfile ? 0.5 : 1); await page.evaluate(() => { const original = confirmFile; window.saveChecks = []; @@ -130,7 +132,7 @@ test('worker orders construction production and saves survive reload', async ({ const saved = (await state(page)).quicksave; await page.screenshot({ path: info.outputPath('saved-landing.png') }); await page.reload(); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect.poll(async () => (await state(page))?.quicksave, { timeout: 90000 }).toBe(saved); await page.keyboard.press('l'); await expect.poll(async () => (await state(page)).notice).toContain('Loaded Quicksave'); @@ -146,7 +148,7 @@ test('worker orders construction production and saves survive reload', async ({ test('denied storage shows an honest warning', async ({ page }) => { await page.addInitScript(() => Object.defineProperty(window, 'indexedDB', { get() { throw new DOMException('Denied', 'SecurityError'); } })); await page.goto('http://127.0.0.1:8070'); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect(page.getByRole('alert')).toContainText('storage is unavailable'); await expect.poll(() => page.evaluate(() => window.farlanding.ready), { timeout: 90000 }).toBe(true); }); diff --git a/tools/web_tests/graphics.spec.cjs b/tools/web_tests/graphics.spec.cjs new file mode 100644 index 00000000..818add91 --- /dev/null +++ b/tools/web_tests/graphics.spec.cjs @@ -0,0 +1,119 @@ +const { test, expect } = require('@playwright/test'); +const { play } = require('./launch.cjs'); + +const state = page => page.evaluate(() => window.farlanding?.diagnostics); + +test.describe('Retina layout', () => { + test.use({ deviceScaleFactor: 2 }); + test('Retina keeps readable menus and real CSS-coordinate input', async ({ page }, info) => { + await boot(page, 'low'); + expect((await state(page)).display_scale).toBe(2); + await button(page, 'SETTINGS'); + await expect.poll(async () => (await state(page)).buttons.some(item => item.text === 'ACCESSIBILITY')).toBe(true); + await page.screenshot({ path: info.outputPath('retina-settings.png') }); + await button(page, 'BACK'); + await expect.poll(async () => (await state(page)).screen).toBe('title'); + expect(await page.evaluate(() => window.farlanding.errors)).toEqual([]); + }); +}); + +async function boot(page, choice = 'saved') { + await page.goto('http://127.0.0.1:8071/'); + await play(page, choice); + await expect.poll(async () => (await state(page))?.quality, { timeout: 90000 }).toBeTruthy(); +} +async function button(page, text) { + await expect.poll(async () => (await state(page)).buttons.some(b => b.text.startsWith(text))).toBe(true); + const target = (await state(page)).buttons.find(b => b.text.startsWith(text)); + await page.mouse.click(...target.pixel, { delay: 80 }); +} +async function legacyProfile(page) { + await boot(page, 'low'); + await expect.poll(() => page.evaluate(() => window.farlanding.saves.settings?.status)).toBe('saved'); + await page.evaluate(async () => { + const db = await new Promise((resolve, reject) => { + const request = indexedDB.open('/userfs'); + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + await new Promise((resolve, reject) => { + const tx = db.transaction('FILE_DATA', 'readwrite'); + const store = tx.objectStore('FILE_DATA'); + const cursor = store.openCursor(); + cursor.onsuccess = () => { + const item = cursor.result; + if (!item) return; + if (String(item.key).endsWith('/settings.cfg')) { + const record = item.value; + let text = new TextDecoder().decode(record.contents); + text = text.replace(/^graphics_defaults_version=.*\n/gm, '').replace(/^msaa_3d=.*\n/gm, ''); + text = text.replace(/^music_volume=.*$/m, 'music_volume=0.42'); + text = text.replace(/^control_scheme=.*$/m, 'control_scheme="modern"'); + record.contents = new TextEncoder().encode(text); + record.timestamp = new Date(Date.now() + 1000); + item.update(record); + } + item.continue(); + }; + tx.oncomplete = resolve; + tx.onerror = () => reject(tx.error); + }); + db.close(); + }); + await page.reload(); + await play(page, 'saved'); + await expect.poll(async () => (await state(page))?.graphics_upgrade_available, { timeout: 90000 }).toBe(true); +} + +test('a fresh browser starts at High, full resolution and 2x MSAA', async ({ page }, info) => { + await boot(page); + expect((await state(page)).quality).toBe('high'); + expect((await state(page)).render_scale).toBe(1); + expect((await state(page)).msaa).toBe(1); + expect((await state(page)).display_scale).toBe(await page.evaluate(() => devicePixelRatio)); + expect((await state(page)).graphics_upgrade_available).toBe(false); + await info.attach('fresh-graphics', { body: JSON.stringify(await state(page)), contentType: 'application/json' }); +}); + +test('the launcher Performance choice persists when Saved is used on reload', async ({ page }) => { + await boot(page, 'low'); + await expect.poll(() => page.evaluate(() => window.farlanding.saves.settings?.status)).toBe('saved'); + await page.reload(); + await play(page, 'saved'); + await expect.poll(async () => (await state(page))?.quality, { timeout: 90000 }).toBe('low'); + expect((await state(page)).render_scale).toBe(0.5); + expect((await state(page)).msaa).toBe(0); + expect((await state(page)).graphics_upgrade_available).toBe(false); +}); + +test('legacy players can keep their graphics without a repeated upgrade prompt', async ({ page }) => { + await legacyProfile(page); + await button(page, 'KEEP CURRENT'); + await expect.poll(async () => (await state(page)).graphics_upgrade_available).toBe(false); + await expect.poll(() => page.evaluate(() => window.farlanding.saves.settings?.status)).toBe('saved'); + await page.reload(); + await play(page, 'saved'); + await expect.poll(async () => (await state(page))?.graphics_defaults_version, { timeout: 90000 }).toBe(2); + expect((await state(page)).quality).toBe('low'); + expect((await state(page)).scheme).toBe('modern'); + expect((await state(page)).music_volume).toBe(0.42); + expect((await state(page)).graphics_upgrade_available).toBe(false); +}); + +if (process.env.WEB_GRAPHICS_QUALIFY) { + test('legacy players can upgrade to High while retaining unrelated preferences', async ({ page }, info) => { + await legacyProfile(page); + await button(page, 'USE HIGH GRAPHICS'); + await expect.poll(async () => (await state(page)).quality).toBe('high'); + expect((await state(page)).render_scale).toBe(1); + expect((await state(page)).msaa).toBe(1); + expect((await state(page)).scheme).toBe('modern'); + expect((await state(page)).music_volume).toBe(0.42); + await expect.poll(() => page.evaluate(() => window.farlanding.saves.settings?.status)).toBe('saved'); + await page.reload(); + await play(page, 'saved'); + await expect.poll(async () => (await state(page))?.quality, { timeout: 90000 }).toBe('high'); + expect((await state(page)).graphics_upgrade_available).toBe(false); + await page.screenshot({ path: info.outputPath('high-title.png') }); + }); +} diff --git a/tools/web_tests/latency.spec.cjs b/tools/web_tests/latency.spec.cjs index f2da057a..5a9a7f08 100644 --- a/tools/web_tests/latency.spec.cjs +++ b/tools/web_tests/latency.spec.cjs @@ -1,3 +1,4 @@ +const { play } = require('./launch.cjs'); const { test, expect } = require('@playwright/test'); const { captureAudio } = require('./audio-capture.cjs'); test.use({ video: 'off', trace: 'off' }); @@ -5,7 +6,7 @@ if (process.env.WEB_LATENCY) { test('measures keydown to captured UI cue', async ({ page }, info) => { await page.addInitScript(captureAudio); await page.goto('http://127.0.0.1:8071/?latency'); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect.poll(() => page.evaluate(() => window.farlanding?.ready), { timeout: 90000 }).toBe(true); await page.locator('#canvas').click(); await page.evaluate(() => { diff --git a/tools/web_tests/launch.cjs b/tools/web_tests/launch.cjs new file mode 100644 index 00000000..9033821e --- /dev/null +++ b/tools/web_tests/launch.cjs @@ -0,0 +1,8 @@ +// Select a normal player-facing profile. CI's software renderer is not a player default. +async function play(page, choice) { + const profile = choice ?? process.env.WEB_GRAPHICS_PROFILE ?? + (process.env.WEB_SOFTWARE || process.env.CI ? 'low' : 'saved'); + await page.getByLabel('Graphics', { exact: true }).selectOption(profile); + await page.getByRole('button', { name: 'Play Farlanding' }).click(); +} +module.exports = { play }; diff --git a/tools/web_tests/performance.spec.cjs b/tools/web_tests/performance.spec.cjs index 03139183..d4c783b7 100644 --- a/tools/web_tests/performance.spec.cjs +++ b/tools/web_tests/performance.spec.cjs @@ -1,13 +1,14 @@ +const { play } = require('./launch.cjs'); const { test, expect } = require('@playwright/test'); test.use({ video: 'off', trace: 'off' }); if (process.env.WEB_PERFORMANCE) { - test('233-unit Web battle reports measured frame and simulation costs', async ({ page }, info) => { + test(process.env.WEB_BENCH_NORMAL ? 'normal Web landing reports measured frame and simulation costs' : '233-unit Web battle reports measured frame and simulation costs', async ({ page }, info) => { test.setTimeout(180000); const errors = []; page.on('pageerror', error => errors.push(String(error))); const start = Date.now(); - await page.goto('http://127.0.0.1:8071/?bench' + (process.env.WEB_BENCH_SECONDS === '30' ? '&seconds=30' : '')); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await page.goto('http://127.0.0.1:8071/?bench' + (process.env.WEB_BENCH_SECONDS === '30' ? '&seconds=30' : '') + (process.env.WEB_BENCH_QUALITY === 'high' ? '&quality=high' : '') + (process.env.WEB_BENCH_MSAA === '2' ? '&msaa=2' : '') + (process.env.WEB_BENCH_NORMAL ? '&normal' : '')); + await play(page); await expect.poll(() => page.evaluate(() => window.farlanding?.ready), { timeout: 90000 }).toBe(true); const startupMs = Date.now() - start; const device = await page.evaluate(() => { @@ -19,9 +20,10 @@ if (process.env.WEB_PERFORMANCE) { const report = await page.evaluate(() => window.farlanding); expect(report.errors).toEqual([]); expect(errors).toEqual([]); - expect(report.benchmark[0]).toContain('peak 233 units'); + if (!process.env.WEB_BENCH_NORMAL) expect(report.benchmark[0]).toContain('peak 233 units'); + const dimensions = await page.evaluate(() => ({ canvas: [document.querySelector('canvas').width, document.querySelector('canvas').height], css: [innerWidth, innerHeight], dpr: devicePixelRatio })); await info.attach('benchmark', { body: JSON.stringify({ startupMs, device, report }, null, 2), contentType: 'application/json' }); - console.log(JSON.stringify({ startupMs, device, benchmark: report.benchmark })); + console.log(JSON.stringify({ startupMs, device, dimensions, profile: report.benchmarkProfile, benchmark: report.benchmark })); await page.screenshot({ path: info.outputPath('battle.png') }); }); } diff --git a/tools/web_tests/persistence.spec.cjs b/tools/web_tests/persistence.spec.cjs index b8f9882c..a2eca16c 100644 --- a/tools/web_tests/persistence.spec.cjs +++ b/tools/web_tests/persistence.spec.cjs @@ -1,20 +1,21 @@ +const { play } = require('./launch.cjs'); const { test, expect } = require('@playwright/test'); test('quicksave reaches IndexedDB and survives immediate reload', async ({ page }) => { await page.goto('http://127.0.0.1:8071/?mission=conquest'); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect.poll(() => page.evaluate(() => window.farlanding?.diagnostics?.tick), { timeout: 90000 }).toBeGreaterThan(0); await page.keyboard.press('k'); await expect.poll(() => page.evaluate(() => window.farlanding.diagnostics.quicksave)).not.toBe(''); await expect.poll(() => page.evaluate(() => window.farlanding.diagnostics.notice)).toBe('Saved to Quicksave.'); const saved = await page.evaluate(() => window.farlanding.diagnostics.quicksave); await page.reload(); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect.poll(() => page.evaluate(() => window.farlanding?.diagnostics?.quicksave), { timeout: 90000 }).toBe(saved); }); test('a corrupt persisted landing is refused after reload', async ({ page }) => { await page.goto('http://127.0.0.1:8071/?mission=conquest'); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect.poll(() => page.evaluate(() => window.farlanding?.diagnostics?.tick), { timeout: 90000 }).toBeGreaterThan(0); await page.keyboard.press('k'); await expect.poll(() => page.evaluate(() => window.farlanding.saves.quicksave?.status)).toBe('saved'); @@ -39,7 +40,7 @@ test('a corrupt persisted landing is refused after reload', async ({ page }) => }); }); await page.reload(); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); await expect.poll(() => page.evaluate(() => window.farlanding?.diagnostics?.tick), { timeout: 90000 }).toBeGreaterThan(0); await page.keyboard.press('l'); await expect.poll(() => page.evaluate(() => window.farlanding.diagnostics.notice)).toBe('This is not a Farlanding save.'); diff --git a/tools/web_tests/playwright.config.cjs b/tools/web_tests/playwright.config.cjs index 67de3e6a..54bb91cc 100644 --- a/tools/web_tests/playwright.config.cjs +++ b/tools/web_tests/playwright.config.cjs @@ -4,7 +4,8 @@ module.exports = defineConfig({ retries: 0, timeout: 180000, expect: { timeout: 30000 }, reporter: [['list'], ['html', { open: 'never' }]], use: { - viewport: { width: 1280, height: 720 }, + viewport: { width: Number(process.env.WEB_WIDTH || 1280), height: Number(process.env.WEB_HEIGHT || 720) }, + deviceScaleFactor: Number(process.env.WEB_DPR || 1), screenshot: 'only-on-failure', trace: 'retain-on-failure', video: process.env.WEB_RECORD ? 'on' : 'off', launchOptions: { args: process.platform === 'darwin' && !process.env.WEB_SOFTWARE ? ['--use-angle=metal'] : ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] }, }, diff --git a/tools/web_tests/soak.spec.cjs b/tools/web_tests/soak.spec.cjs index 7121c434..df0b9df8 100644 --- a/tools/web_tests/soak.spec.cjs +++ b/tools/web_tests/soak.spec.cjs @@ -1,3 +1,4 @@ +const { play } = require('./launch.cjs'); const { test, expect } = require('@playwright/test'); test.use({ video: 'off', trace: 'off' }); if (process.env.WEB_SOAK) { @@ -12,7 +13,7 @@ if (process.env.WEB_SOAK) { const started = Date.now(); const cycles = []; await page.goto('http://127.0.0.1:8071/?mission=conquest'); - await page.getByRole('button', { name: 'Play Farlanding' }).click(); + await play(page); while (Date.now() - started < 1800000) { await expect.poll(async () => (await state())?.tick, { timeout: 90000 }).toBeGreaterThan(0); const worker = (await state()).units.find(unit => unit.kind === 'concord_fabricator'); diff --git a/tools/web_tests/visual.spec.cjs b/tools/web_tests/visual.spec.cjs new file mode 100644 index 00000000..fd771470 --- /dev/null +++ b/tools/web_tests/visual.spec.cjs @@ -0,0 +1,25 @@ +const { play } = require('./launch.cjs'); +const { test, expect } = require('@playwright/test'); + +if (process.env.WEB_VISUALS) { + test.use({ video: 'off', trace: 'off' }); + for (const mission of ['orbit', 'conquest', 'thalassa_recovery', 'emberfall_conquest', 'verdance_conquest', 'hollow_power']) { + for (const profile of (process.env.WEB_VISUAL_BASELINE ? ['low', 'high'] : ['high'])) { + test(`visual reference ${mission} ${profile}`, async ({ page }, info) => { + await page.goto(`http://127.0.0.1:8071/?visual=${mission}&quality=${profile}&scale=${profile === 'low' ? '0.5' : '1'}`); + await play(page); + await expect.poll(() => page.evaluate(() => window.farlanding?.visual), { timeout: 90000 }).toBeTruthy(); + const report = await page.evaluate(() => ({ ...window.farlanding.visual, + canvas: [document.querySelector('canvas').width, document.querySelector('canvas').height], + css: [innerWidth, innerHeight], dpr: devicePixelRatio, + })); + expect(report.quality).toBe(profile); + expect(report.canvas).toEqual(report.css.map(size => size * report.dpr)); + expect(await page.evaluate(() => window.farlanding.errors)).toEqual([]); + await page.screenshot({ path: info.outputPath(`${mission}-${profile}.png`) }); + await info.attach('visual-profile', { body: JSON.stringify(report), contentType: 'application/json' }); + console.log(JSON.stringify(report)); + }); + } + } +}