diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 721840cd4..77506770b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -231,20 +231,16 @@ jobs: shell: powershell run: choco install ccache --yes --no-progress - # The pinned TypeScript, and it is not optional here even though the build - # treats it as optional. + # The pinned TypeScript compiler stages Studio's authored panels during + # the build. The Studio target treats it as optional and reports when + # panels are skipped, so install it here to keep release artifacts whole. + # `just typecheck` also uses this compiler for the panels and generated + # engine declarations. `node_modules/` is gitignored, so every fresh + # runner needs this install or its cache. # - # `Mirrors-1-world.ts` and `Mirrors-4-worlds.ts` are transpiled to - # JavaScript during the build and staged as example scenes. A missing - # `node_modules/.bin/tsc` is not fatal - mono.engine/examples/CMakeLists.txt - # prints one STATUS line and skips them - so a runner without this step - # produces a green build and a release quietly short two scenes, which is - # the failure nobody notices. `node_modules/` is gitignored, so without an - # install step that is every run. - # - # `install` rather than `ci`: package.json pins typescript to an exact - # version and there is no package-lock.json to honour. The repository's - # bun.lock is for `bun`, and npm is what every runner image already has. + # `install` uses package.json's exact TypeScript version. There is no npm + # lockfile to honour; bun.lock is for Bun, and npm is available on every + # runner image. - name: Restore the TypeScript transpiler id: typescript-cache uses: actions/cache/restore@v4 diff --git a/.github/workflows/version-impact.yml b/.github/workflows/version-impact.yml new file mode 100644 index 000000000..e4403f006 --- /dev/null +++ b/.github/workflows/version-impact.yml @@ -0,0 +1,101 @@ +name: demo performance impact + +on: + workflow_dispatch: + inputs: + baseline: + description: Baseline branch or commit carrying the benchmark recorder + default: origin/v0.24.1 + required: true + pull_request: + paths: + - 'CMakeLists.txt' + - 'CMakePresets.json' + - 'Justfile' + - 'mono.build/**' + - 'mono.vendor/**' + - 'mono.engine/**' + - 'mono.client/**' + - 'mono.server/**' + - 'mono.tools/benchrunner/**' + - 'scripts/demos/version-impact*' + - 'scripts/demos/compare-version-impact.sh' + - '.github/workflows/version-impact.yml' + +permissions: + contents: read + +concurrency: + group: demo-impact-${{ github.ref }} + cancel-in-progress: true + +jobs: + compare: + runs-on: ubuntu-24.04 + timeout-minutes: 180 + env: + # Both revisions use the same software Vulkan device. These measurements + # form their own baseline and are not compared to desktop GPU timings. + BUILD_JOBS: 4 + SDL_VIDEO_DRIVER: offscreen + SDL_AUDIO_DRIVER: dummy + SDL_GPU_DRIVER: vulkan + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + submodules: recursive + - name: Install build and software Vulkan dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + ninja-build ccache time mesa-vulkan-drivers libvulkan1 \ + libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev \ + libxfixes-dev libxss-dev libxkbcommon-dev libxtst-dev \ + libwayland-dev wayland-protocols libdecor-0-dev \ + libasound2-dev libpulse-dev libudev-dev libdbus-1-dev libibus-1.0-dev + for icd in /usr/share/vulkan/icd.d/lvp_icd*.json; do + if test -f "$icd"; then + echo "VK_DRIVER_FILES=$icd" >> "$GITHUB_ENV" + break + fi + done + - name: Restore compiler cache + id: ccache-restore + uses: actions/cache/restore@v4 + with: + path: ~/.cache/ccache + key: demo-impact-${{ runner.os }}-${{ github.sha }} + restore-keys: demo-impact-${{ runner.os }}- + - name: Fetch shader compiler dependencies + run: python3 mono.vendor/shaderc/utils/git-sync-deps + - name: Build, collect and compare three fifteen-second runs + env: + BASELINE_REF: ${{ inputs.baseline || 'origin/v0.24.1' }} + run: | + rm -f docs/VERSION_IMPACT.md + bash scripts/demos/compare-version-impact.sh "$BASELINE_REF" docs/VERSION_IMPACT.md + - name: Save compiler cache + if: ${{ !cancelled() && steps.ccache-restore.outcome == 'success' && steps.ccache-restore.outputs.cache-hit != 'true' }} + uses: actions/cache/save@v4 + with: + path: ~/.cache/ccache + key: ${{ steps.ccache-restore.outputs.cache-primary-key }} + - name: Publish comparison table in the job summary + if: always() + run: | + if test -s docs/VERSION_IMPACT.md; then + cat docs/VERSION_IMPACT.md >> "$GITHUB_STEP_SUMMARY" + else + echo 'Demo measurement did not complete. Inspect the failed step and retained evidence.' >> "$GITHUB_STEP_SUMMARY" + fi + - name: Retain measurement evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: version-impact + path: | + docs/VERSION_IMPACT.md + .cache/build/profile/version-impact/ + .cache/build/version-impact-reference/.cache/build/profile/version-impact/ + include-hidden-files: true diff --git a/.gitmodules b/.gitmodules index bd09a65bc..3f0e7cfa6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,27 +4,8 @@ ; shallow = true keeps `just setup` to a single commit per vendor. The exact ; commit is still pinned by the superproject, so a clone is reproducible. -; The window, the input and the GPU abstraction. Pinned to the `release-3.4.14` -; tag rather than to the head of its branch, because the version is a number -; documents quote and a branch head is not one. -; -; **Moved 3.2.31 to 3.4.14 at v0.15, and nothing in this repository changed with -; it.** All 219 SDL symbols the engine names still exist - checked against the -; 3.4 headers rather than by building and hoping - so the bump is additive. What -; it buys is `SDL_GetGPUDeviceProperties` (device and driver name, version and -; info, for a probe that currently has none) and the GPU device-creation feature -; toggles that let a device be made on hardware missing clip distance, depth -; clamping or anisotropy. -; -; **It does not buy a GPU timestamp query, and that was checked rather than -; hoped for**: 3.4.14's `SDL_gpu.h` still has no timestamp, no query pool and no -; `SDL_GPUQuery`. `docs/DEFERRED.md` D00046 is blocked on exactly that and is -; unmoved by this. -; -; One new configure warning comes with it and it is honest: 3.4 warns when -; `libdecor-0` is absent, which 3.2 checked for silently. Wayland window -; decorations on GNOME and Weston want it; an X11 session does not care. Install -; `libdecor-0-dev` to silence it rather than turning the feature off. +; The window, input and GPU abstraction. Pinned to the `release-3.4.16` tag so +; references use a stable version while the superproject records its exact SHA. [submodule "mono.vendor/sdl"] path = mono.vendor/sdl url = https://github.com/libsdl-org/SDL.git @@ -136,33 +117,8 @@ url = https://github.com/facebook/zstd.git branch = release shallow = true -; Luau is vendored ahead of its consumer. Nothing links it until v0.6 runs a -; script; MonoVendor.cmake adds it EXCLUDE_FROM_ALL so it costs a clone and no -; build time until then. `v05.md` open question 3 is what this answers, and it -; is answered early because the bindings manifest generates Luau type -; declarations and those are written against a value model rather than in the -; abstract. -; -; master, because Luau tags releases rather than publishing a release branch - -; the same situation as glm and the cryptopp pair above, and the superproject -; pins the SHA regardless. -; -; **Held at luau-lsp's revision deliberately, and this is the one submodule that -; is not simply "as new as possible".** It is pinned to the same commit as -; `mono.vendor/luau-lsp/luau`, so the language server in an editor and -; `mono.tools/scriptcheck` in `just typecheck` type-check against one Luau and -; cannot disagree about the language. -; -; **What sets the number is luau-lsp, not us.** It is `fd83819b`, one commit -; before the 0.734 tag, which is what luau-lsp `d5df9af` - "Sync to upstream Luau -; 0.733" - pins. `just luau-lsp` asserts the two match rather than trusting this -; comment, and `docs/DEFERRED.md` D00019 carries the reopen trigger: bump both -; the day luau-lsp syncs again. -; -; It was 0.731 from v0.7 to v0.15, held there because 0.732 removed the -; `ConstraintSolver::reportError` overloads luau-lsp called in -; `src/platform/roblox/RobloxLuauExt.cpp`. Upstream did that work, so the ceiling -; that argument describes is gone rather than raised. +; Luau is pinned to the commit nested by luau-lsp 1.70.0, currently 0.739. +; `just luau-lsp` checks that the editor and `just typecheck` use this same VM. [submodule "mono.vendor/luau"] path = mono.vendor/luau url = https://github.com/luau-lang/luau.git @@ -185,45 +141,11 @@ url = https://github.com/quickjs-ng/quickjs.git branch = master shallow = true -; luau-lsp is the editor's language server, and it is the one vendor this build -; never compiles. `update = none` is why `just setup` walks past it: setup's -; contract is what a fresh clone needs *before it can configure*, and nothing -; here needs a language server to configure. `just luau-lsp` clones and builds -; it on demand, for whoever wants completion in an editor. -; -; **It brings its own Luau, and that is the reason it is built in a tree of its -; own rather than added to ours.** Its CMakeLists does `add_subdirectory(luau)` -; against a submodule pinned to its own commit, which declares `Luau.Ast`, -; `Luau.Analysis` and `Luau.VM` - the same target names `mono.vendor/luau` -; already gives us. Adding it to this build fails at configure time with "another -; target with the same name already exists", and there is no flag that makes it -; consume an existing Luau. -; -; **The two Luaus are pinned to the same commit**, so the editor and -; `just typecheck` type-check against one language rather than two. That is a -; constraint on `mono.vendor/luau` as much as on this one - see its entry - and -; `just luau-lsp` asserts it instead of trusting either comment. -; -; The revision is luau-lsp's: whatever its nested `luau` pins is what both trees -; build against, because it is the tree that cannot follow upstream freely. That -; was 0.731 for eight versions - 0.732 removed the -; `ConstraintSolver::reportError` overloads it calls in -; `src/platform/roblox/RobloxLuauExt.cpp` - and `d5df9af` is upstream doing that -; work. `docs/DEFERRED.md` D00019 holds the reopen trigger. -; -; Pinned to a commit on `main` rather than to the 1.69.0 tag, because that tag -; carries an older Luau still: matching the engine matters more here than -; matching a release number. -; -; **It is also the one vendor that is patched, and the patch never touches this -; working tree.** `scripts/vendor-tree.sh` archives the commit pinned here into -; `.cache/vendor/luau-lsp` and applies `mono.vendor/patches/luau-lsp/*.patch` -; there; the submodule stays exactly as cloned, so a superproject `git status` is -; clean and a `git submodule update` has nothing to revert. It was applied here -; once, and a permanently modified submodule in every status - one `git commit -; -a` away from a pointer nobody meant to move - is why it is not any more. -; `mono.vendor/AGENTS.md` argues the shape and says why it does not generalise -; to a vendor the engine links. +; luau-lsp is built on demand because it is an editor tool. It embeds Luau, whose +; target names conflict with the engine's copy, so it builds in its own tree. +; `update = none` keeps `just setup` from cloning it. `just luau-lsp` clones it, +; verifies the nested Luau SHA, then builds a patched archive without modifying +; this submodule. [submodule "mono.vendor/luau-lsp"] path = mono.vendor/luau-lsp url = https://github.com/JohnnyMorganz/luau-lsp.git @@ -319,9 +241,9 @@ ; hardest to reproduce, and `just determinism` and `just replay-check` both ; depend on it not doing that. ; -; Pinned at the `v1.25.0` tag rather than at the head of `main`, for the reason -; SDL is pinned at a release: the version is a number documents quote. Upstream -; cuts no release branch, so `main` is what the tag sits on. +; Pinned to the upstream `main` snapshot `48228939787d4b5bea94c7795b8c7fe0781d918e` +; from 2026-10-11. The stable `v1.25.0` tag is older; pinning the exact commit +; keeps the moving branch reproducible. ; ; Only `lib/` is built - `MonoVendor.cmake` configures with `ENABLE_LIB_ONLY`, ; so the `crypto/` helpers for OpenSSL, GnuTLS, wolfSSL and picotls are never @@ -331,6 +253,7 @@ url = https://github.com/ngtcp2/ngtcp2.git branch = main shallow = true +; MoltenVK is pinned to the latest stable v1.4.2 release tag, not moving main head. [submodule "mono.vendor/moltenvk"] path = mono.vendor/moltenvk url = https://github.com/KhronosGroup/MoltenVK.git @@ -352,3 +275,28 @@ path = mono.vendor/sqlitecpp url = https://github.com/SRombauts/SQLiteCpp.git branch = sqlitecpp-3.x +[submodule "mono.vendor/harfbuzz"] + path = mono.vendor/harfbuzz + url = https://github.com/harfbuzz/harfbuzz.git + shallow = true +[submodule "mono.vendor/freetype"] + path = mono.vendor/freetype + url = https://github.com/freetype/freetype.git + shallow = true +[submodule "mono.vendor/utf8proc"] + path = mono.vendor/utf8proc + url = https://github.com/JuliaStrings/utf8proc.git + shallow = true +[submodule "mono.vendor/sheenbidi"] + path = mono.vendor/sheenbidi + url = https://github.com/Tehreer/SheenBidi.git + branch = master + shallow = true +[submodule "mono.vendor/libunibreak"] + path = mono.vendor/libunibreak + url = https://github.com/adah1972/libunibreak.git + branch = master + shallow = true +[submodule "mono.vendor/accesskit-c"] + path = mono.vendor/accesskit-c + url = https://github.com/AccessKit/accesskit-c diff --git a/CMakeLists.txt b/CMakeLists.txt index 5ac7c9f2d..f78903119 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,6 +35,20 @@ project(atomic set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/VERSION") +# One compiler for every Linux build: GCC. Generated output depends on it +# (`ecs::HasPadding` needs `__builtin_clear_padding`, which clang lacks, so +# docs/ECS_COMPONENTS.md reads differently under clang), and `just check` +# compares builds against files the GCC `ci` preset wrote. The libFuzzer builds +# are the exception, since libFuzzer is clang-only; they arrive with a +# MONO_FUZZ_* option set on the command line. +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND + NOT (MONO_FUZZ_GUI OR MONO_FUZZ_BAKE OR MONO_FUZZ_SHADER OR MONO_FUZZ_PRESENTATION OR + MONO_FUZZ_PORTAL_EXCHANGE)) + message(FATAL_ERROR + "Linux builds use GCC; this configure picked ${CMAKE_CXX_COMPILER_ID} (${CMAKE_CXX_COMPILER}).\n" + " Reconfigure without a compiler override: `cmake --preset --fresh`.") +endif() + set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) @@ -392,6 +406,12 @@ endif() # nondeterministic bytes into every `.gch`, so precompiled-header users never # share across presets whatever is set here. # +# `CCACHE_DEPEND=true` keeps a cache miss out of the preprocessor. Without it, +# ccache runs `cc1plus -E -fpch-preprocess` on a PCH-backed source. One physics +# object grew that process past 66 GiB RSS before it was stopped. Ninja already +# requests dependency files with `-MD`, which is what depend mode hashes. +# Direct hits still work; a miss compiles once instead of expanding the PCH. +# # Two calls per build still report as errors, and they are the two PCH # *generation* steps - ccache cannot parse a header as a source, so it passes # them to the compiler untouched. Correct, and 0.11% of the build. @@ -440,6 +460,7 @@ if(MONO_CCACHE) "CCACHE_SLOPPINESS=pch_defines,time_macros" "CCACHE_BASEDIR=${CMAKE_SOURCE_DIR}" "CCACHE_NOHASHDIR=true" + "CCACHE_DEPEND=true" "${MONO_COMPILER_CACHE}") else() set(MONO_CACHE_LAUNCHER "${MONO_COMPILER_CACHE}") diff --git a/CMakePresets.json b/CMakePresets.json index cf65067d8..24a6ead29 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -47,6 +47,14 @@ "MONO_UNITY_BUILD": "ON" } }, + { + "name": "release-tests", + "inherits": "release", + "displayName": "release tests with release optimisation", + "cacheVariables": { + "MONO_BUILD_TESTS": "ON" + } + }, { "name": "profile", "inherits": "release", @@ -163,6 +171,10 @@ "name": "release", "configurePreset": "release" }, + { + "name": "release-tests", + "configurePreset": "release-tests" + }, { "name": "profile", "configurePreset": "profile" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 801672a07..e3c68e281 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,51 +1,23 @@ # Contributing -Thanks for looking. This engine is being built mostly by and for people coming -from the Roblox community, and the assumption throughout is that you know games -better than you know C++ build systems. +This guide covers the local prerequisites, contribution expectations, review gate, and responsible disclosure path for this repository. ---- +## Get started -## Get it building - -You need: - -| Tool | Version | Why | -|---|---|---| -| CMake | 3.24+ | the build | -| Ninja | any recent | the generator every preset uses | -| A C++20 compiler | GCC 13+, Clang 16+, MSVC 19.3+ | | -| `clang-format` | 18+ | `just format`; optional, but a pull request without it says so | -| `just` | optional | the entry point; raw CMake works too | -| Python 3 | 3.8+ | **`just setup` only** - see below | - -Nothing in the build or the test suite needs a scripting runtime: the test -runner is C++ and the architecture check is a CMake script. - -`just setup` is the exception, and only for shaderc. It pins glslang, -SPIRV-Tools and SPIRV-Headers in its own `DEPS` file rather than as submodules, -so `git submodule update --recursive` clones shaderc and leaves `third_party/` -empty. `utils/git-sync-deps` fills it, and that script is Python. You need it -once, on a fresh clone. - -You do **not** need `glslc` installed. It is built from `mono.vendor/shaderc`, -which is what makes the SPIR-V reproducible between machines. Configure with -`-DMONO_VENDORED_GLSLC=OFF` to use one from your PATH instead and skip building -glslang - faster first build, at the cost of whatever version you happen to -have. - -On Linux you will also want the usual X11/Wayland development packages - SDL -picks its backends at configure time and tells you what it found. +Install a recent CMake, Ninja, C++20 compiler, Python 3, and `just`. +`clang-format` is also required for the formatting check. On Linux, install the +SDL development packages required by the window system you use. ```sh git clone --recurse-submodules cd atomic-game-engine - -just setup # or: git submodule update --init --recursive --depth 1 +just setup just build just run --stats ``` +`just setup` initializes the pinned vendor dependencies and installs the +repository hook. All build output is disposable and lives under `.cache/`. Without `just`: ```sh @@ -54,151 +26,42 @@ cmake --build .cache/build/dev ./.cache/build/dev/client/client --stats ``` -Everything derived lands in `.cache/`. Deleting it costs you a rebuild and -nothing else. - ---- - -## Run the tests - -```sh -just test # only what your change could have affected -just test-all # everything -``` - -The first one is not a guess. Each suite's signature is a hash of its source, -every header that source includes, and the signatures of the suites it declares -a dependency on - so changing a header at the bottom of the stack re-runs -everything above it and nothing else. It prints what it skipped. - -`ctest` from a build directory also works and always runs everything. +[RUNNING.md](RUNNING.md) is the complete command index, including product, +test, benchmark, documentation, and integration commands. -Tests live with the thing they test - `mono.engine//tests/`, -`mono.client/tests/`, `mono.server/tests/`, `mono.tools/tests/`. There is no -central test directory. +## Make a change ---- +Read the root `AGENTS.md`, then every module `AGENTS.md` for folders you touch. +Keep the change focused, add or update the tests that prove its behavior, and +remove code that the change replaces. Public APIs need documentation in their +headers. -## Try it +Before opening a pull request, follow +[the code-quality checklist](docs/CODE_QUALITY.md). At minimum, run the checks +that cover the change and report any relevant check you could not run. A strict +local gate is: ```sh -just run --stats --graph +just preset=ci check ``` -- **F3** - frame rate, and the shape of the last twenty seconds. The minimum - is the interesting number. -- **F5** - the frame graph. **F6**/**F7** move between views: the flamegraph, - time by category, per-system cost, and the metrics counters. -- **Esc** - quit. - -`--uncapped` unpins the frame from your display, which is the only way the -numbers mean anything. `client --help` lists the rest. - -The server is headless and has no window at all: - -```sh -just host --ticks 300 --entities 20000 -``` - -`just check-server-is-headless` configures with no client, and fails if the -staged `server/` directory has grown a `shaders/` folder. That is the tier -split proved rather than asserted. - -[RUNNING.md](RUNNING.md) has the rest: every flag on every program, how to run -one suite directly, how to attach Tracy, and why `--uncapped` is not optional -when you care about the numbers. - ---- - -## Before you open a pull request - -**Work through [`docs/CODE_QUALITY.md`](docs/CODE_QUALITY.md) and [`docs/CODE_BAD_PRACTICES.md`](docs/CODE_BAD_PRACTICES.md).** That is the -completion checklist - the mechanical gate first, then the review questions, -then what the pull request itself has to say. - -It lives there rather than here on purpose. A checklist copied into two files -is two checklists, and within a few months nobody knows which one is current. - -Working with Claude Code, `/run-checklist` walks the whole thing and reports -what it could not verify rather than skipping it quietly. `/new-module` walks -through adding an engine module without missing one of the six things that have -to line up. Both live in [`.claude/`](.claude/README.md) and are checked in. - -Two things the checklist cannot check for you: - -**Keep it small.** A change a reviewer can hold in their head gets reviewed -properly; one that cannot gets approved instead. Several small pull requests -beat one large one, even when the large one is better work. - -**Say what you did not do.** A pull request that names its own gaps is easier -to trust than one that does not mention any. - ---- - -## On AI - -This project uses AI models heavily and says so on the front page. That is a -deliberate choice about pace, and it comes with one condition, which is not -negotiable: - -> **You are responsible for every line you submit.** You must be able to -> explain it, defend it in review, and maintain it. "The model wrote it" is not -> an answer to a review comment. - -Practically, that means: read what it produced before you send it. If you do -not understand a section, either understand it or take it out. A change nobody -can explain is a change nobody can fix, and this is a codebase intended to last. - -Use AI freely for the parts where it is genuinely good - boilerplate, -mechanical refactors, working out an unfamiliar API, writing the test you know -you should write. Be much more careful with it on architecture, on anything -touching the untrusted parsing boundaries, and on anything where "looks right" -and "is right" are hard to tell apart. - -Always test your code, always benchmark and profile your code, always check if you need to rename variables and always check if you need to split code from one file to multiple. - ---- - -## Reporting a bug - -Say what you did, what happened, and what you expected. A frame from `--stats` -or `--graph` is worth several paragraphs. Include your GPU backend - the F3 -panel prints it. - -For anything touching the sandbox, the game file reader or the network path, -see `SECURITY.md` before opening a public issue. - ---- - -## Completion Checklist - -**It lives in [`docs/CODE_QUALITY.md`](docs/CODE_QUALITY.md).** A checklist -copied into two files is two checklists, and within a few months nobody knows -which one is current - so this section is a pointer, not a copy. - -The short version, and where each part is answered in full: +Use concise pull-request descriptions: what changed, why, how it was verified, +and what remains unverified. Keep performance claims tied to the preset, +scenario, and measurement that produced them. -| Ask yourself | Section | -|---|---| -| Have you profiled the code? | [5 · Performance](docs/CODE_QUALITY.md#5--performance) | -| Have you tested the code? | [6 · Tests](docs/CODE_QUALITY.md#6--tests) | -| Are all code paths covered in tests? | [6 · Tests](docs/CODE_QUALITY.md#6--tests) | -| Can you improve the code further? | [8 · Craft](docs/CODE_QUALITY.md#8--craft) | -| Are variables and fields not named generic things? | [8 · Craft](docs/CODE_QUALITY.md#8--craft) | -| Are there dead code paths you must remove? | [8 · Craft](docs/CODE_QUALITY.md#8--craft) | -| Have you formatted your code correctly? | [1 · The mechanical gate](docs/CODE_QUALITY.md#1--the-mechanical-gate) | -| Any 'negative' C++ practices? | [8 · Craft](docs/CODE_QUALITY.md#8--craft) - named, one by one | -| Any 'negative' general practices? | [8 · Craft](docs/CODE_QUALITY.md#8--craft) - likewise | -| Avoid bad code practices | [`docs/CODE_BAD_PRACTICES.md`](docs/CODE_BAD_PRACTICES.md) +## AI-assisted changes -The full checklist also covers the layer stack, the untrusted parsing -boundaries, thread affinity, and what the pull request itself has to say. Those -are the ones a reviewer cannot check for you afterwards. +AI assistance is welcome. The contributor submitting a change remains +responsible for understanding, testing, explaining, and maintaining every line +in it. Treat architecture, untrusted input, and concurrency as review-heavy +areas, not generated boilerplate. -Working with Claude Code, `/run-checklist` walks all of it. +## Bugs and security ---- +For a normal bug, include the command or scene, the expected and actual result, +and relevant logs or captures. For vulnerabilities or hostile-input failures, +follow [SECURITY.md](SECURITY.md) and do not open a public issue. ## Licence -MPL-2.0. By contributing you agree your contribution is licensed under it. +Contributions are licensed under MPL-2.0. diff --git a/HANDOFF.md b/HANDOFF.md new file mode 100644 index 000000000..f650d14bd --- /dev/null +++ b/HANDOFF.md @@ -0,0 +1,219 @@ +# Work handoff + +Updated 2026-09-24. This records the unfinished work in the main `v0.25` +checkout and the linked worktrees. It is a working note, not a completion claim. + +## Current direction + +- Finish the smaller worktrees first, one at a time. Keep Pixel Composer moving + where it has an independent path. Handle larger remaining items afterward. +- Merge a completed branch into `v0.25` when safe, as the user requested. + Patch equivalent branches need no merge. The main checkout has extensive + uncommitted changes, so inspect overlap before any merge. +- Preserve every dirty worktree until its changes are understood. Do not use + `git worktree remove --force`, `git clean`, or `git reset --hard` to make a + worktree look finished. +- The main checkout contains concurrent uncommitted work from several tasks. + Review ownership before editing shared files or committing. In particular, + do not commit changes made by another agent or the user. +- Follow the repository `AGENTS.md` and each touched module's `AGENTS.md`. + Use CodeGraph first when `.codegraph/` exists. Read `RUNNING.md` before + choosing commands. Never edit the protected instruction documents. + +## Main checkout + +Path: `/home/declan/Documents/GitHub/atomic-game-engine`, branch `v0.25`, +The priority phase benchmark was integrated as `5e30f523`. This handoff and +the portal test fixture fix were committed afterward. The active goal is the +six items in `/home/declan/.codex/attachments/ccb8ba64-ca25-4eaf-a502-18231242fbeb/pasted-text-1.txt`: +virtual camera lock, v0.25 render cleanup, v0.25 MCP cleanup, engine stress +and optimization audit, seamless portals, and Pixel Composer. All remain open. + +### Verified work and next steps + +1. **Virtual camera lock.** A free inspection viewport uses the live camera; + culling, LOD, lighting, particles, and portal demand use the frozen behavior + position with live orientation. This matches the user's choice. Focused + checks passed earlier. Inspect any other camera behavior covered by the + original broad claim, then run the relevant combined gate. +2. **Render pipeline cleanup.** Real GPU render gate previously passed + 1,678,712 assertions in 150 cases. Later history, scope, deferred host, + supersession, and cancellation gates passed. Two real host fixtures for an + incompatible binding and viewport removal passed after correcting fixture + premises. The attempted staged layer import refusal fixture failed its + pending upload premise because an invalid layer is rejected before upload. + It now checks that preflight refusal and last image retention; the focused + Vulkan case passed 20 assertions. An actual failure after staging is still + untested. Review remaining gates in + `docs/v025-RENDER-PIPELINE-CLEANUP.md` before closing this item. +3. **MCP cleanup.** Stages 0 through 5 and the M6 PNG bundle tool are present. + Focused Runner, CLI, architecture, listener, bridge, and 128 cycle soak + checks passed. Quiet paired HEAD/current release timing and broad CI are + still open. The HEAD comparison archive is + `/tmp/atomic-mcp-quiet-3c4i6u88`; current bench binaries need building. + See `docs/v025-MCP-CLEANUP.md` and `docs/v025-MCP-PERF-EVIDENCE.md`. +4. **Stress work.** `docs/ENGINE_STRESS_AUDIT_2026-09-22.md` lists at least five + optimization candidates per engine module. Exact parity checks passed for + replication fixed width deferral, physics solver topology comparison + removal, and MSL reserve adjustment. A matched 200 client Authority + `RecoverRows` rerun is still needed after quiet profiling. The prior + baseline had 200 Playing clients and 194,936 inputs, but its profiler + dropped 73,246 scopes, so its sampled 41.06% share is partial evidence. +5. **Seamless portals.** Scene pose invalidation and local rig demand fixes + passed focused tests. Strict product captures at 30 and 60 Hz still fail. + The 60 Hz resident slot request is received and the first crossing commits + at frame 75, then frame 77 lacks the predicted destination root for one + frame. A red `Replicated` adoption test was linked; implementation was + being compiled when agent capacity ended. Check `mono.client/src/Replicated.cpp` + and `mono.client/tests/Replicated.cpp`, run the focused prediction adoption + gate, then rerun the strict 30/60/144/240 matrix, network, resolution, + profiling, and GPU gates. The 60 Hz trace is under + `.cache/portal-profile/remote/runs/20260924-resident-slot1-60`. +6. **Pixel Composer.** The inventory in `docs/v026-pixel-composer.md` has 990 + documented node rows. Five PXC projects and reference GIFs are at + `/home/declan/Documents/GitHub/atomic-game-engine-hidden-docs/files/pixel-composer-com`. + There is no licensed Pixel Composer 1.21.10 beta executable; the user chose + GIF and documented behavior as references and requested all features. + Native graph, Studio, PXC interchange, selected 2D nodes, Transform Image + 3D, GIF timing, audio capture, and sequence bake work is partial. Do not + claim full product parity. + +### Pixel Composer details that need ownership + +- Five spatial warp nodes passed `test_imagegraph '[imagegraph]'`: 1,966 + assertions in 221 cases. Mirror, Barrel Distort, and Chromatic Aberration + supplied PXC records still need guarded authored control import projection. +- Bounded audio capture parser passed 56 assertions in 6 cases, including + aggregate sample cap refusal before allocation. Audio Window, WAV import, + live device input, audio keyframes, and feedback history remain open. +- `.aseq` 257 to 4096 frame bake and exact variable GIF delays passed asset, + bake, and assetc suites. The scene/client/private playback adapter was + staged and syntax checked. The linked `test_scene`, `test_render`, and + `test_client` build passed; focused sequence checks passed 51, 34, and 11 + assertions respectively. Renderer texture publication remains open. Per + particle age playback needs separate GPU paging. +- Native Transform Image 3D records a bounded pass into the existing batch + command. The focused Vulkan recorder case passed 19 assertions. The + recorder preserves resources until the submit fence, including a failed + render pass after copy commands. A later uncommitted edit now makes + `PollSceneFrames` call `TextureTable::ReplaceAdopt` for successful completed + generations, while older, cancelled, and failed slots are released. The + focused GPU test now checks exact owner/name publication, replacement by a + newer generation, and cancellation retaining the previous output. That test + initially exposed reversed `Succeeded` assignments in the untracked live + recorder; the assignments were corrected and the Vulkan case passed 35 + assertions. Add failed pass, owner retirement, and GPU accounting checks + before calling the edit complete. `QueueTransformImage3D` still has no product + caller outside tests; `client/ImageGraphRuntime.cpp` uses the synchronous + `ExecuteTransformImage3D` adapter. Wire the resident path into graph output + publication before claiming native graph playback. These renderer source and test files remain + untracked alongside the previous agent's implementation, so they were not + included in the handoff commit. +- Source ownership from the prior parallel work is no longer active because + those agents hit a usage limit. Before resuming, inspect the live worktree + and build processes rather than assuming a gate completed. + +## Linked worktrees + +The last audit found 27 linked worktrees, all dirty. All 27 have since +been closed, leaving only the main checkout. `git worktree prune --dry-run --verbose` found no stale +records. Twenty four clean idle `/tmp` worktrees had already been safely +removed. The table gives tracked and +untracked status counts, not an assessment of the changes. Start with the +smallest effective diffs and classify build or submodule pointer noise before +changing source. + +An initial classification found 21 worktrees with no top level source changes, +only `mono.vendor/*` status. Several vendor checkouts contain staged deletions +of their own tracked files, while others only point at a different submodule +commit. Do not assume these are clean from the top level diff count. `git +cherry v0.25 HEAD` showed the authored transmission branch's five commits +were patch equivalent to the main branch. Its sole top level difference was +a clean `ngtcp2` checkout at a different commit. Its worktree was removed; +the `feature/authored-transmission` branch remains. `studio-qa`, `tornado-world`, +`material-capture`, and `lighting-effects` were also removed after confirming +no top level source changes, clean nested vendor repositories, and no commits +unique by patch to `v0.25`. Ten further vendor-only worktrees were removed +after confirming their nested status contained only staged deletions of +missing vendor files, and their commits were patch equivalent to `v0.25`. +Their branch refs remain. The other branches need individual review before +removal or integration. + +The scoring worktree's unique priority phase benchmark commit was integrated +into `v0.25` as `5e30f523`. `bench_replication` built and its priority +refinement suite ran once, printing per-phase samples and a benchmark row. +Its remaining commits were patch equivalent, so its worktree was removed. +The CDN grouper optimization's source and test were byte identical to `v0.25` +and its focused suite passed 56 assertions in 14 cases. Its attempted matched +baseline build failed at CMake regeneration because that worktree's SDL vendor +checkout was missing. Its source was restored afterward. Both CDN worktrees +were removed after confirming the optimized one contained only duplicate +source and vendor symlinks, and the baseline one contained only vendor file +deletions. A matched timing comparison remains unavailable. + +The tornado GPU particle authoring and storm structure damage branches were +reviewed against the current implementation, which contains their behavior +and tests. The rebuilt scene registration suite passed 319 assertions in 13 +cases; the rebuilt physics storm suite passed 30 assertions in 7 cases. The +tornado visual parity branch's 16 volume cap and layered stack test are also +in `v0.25`. Its older example camera and panel values were superseded by a +newer TornadoSim scene; current volume and example tests passed 33 and 143 +assertions. These three worktrees were removed, with branch refs kept. +Debug panel close controls and click routing are in `v0.25`; its panel suite +passed 122 assertions in 43 cases. The detached debug worktree was removed, +and `codex/archived-debug-panel` now preserves its unique commit. +The lighting capability branch's selection logic, shader cap, release stress +target, and tests are present in `v0.25`; its worktree was removed with the +branch ref kept. The remote local play worktree contained only formatting +changes beyond its patch equivalent commit, so it was also removed with the +branch ref kept. + +The local light branch's per-light response planes, control bridge, and tests +are present in `v0.25`, which also has shadow visibility capture. The focused +render data capture suite passed 134,223 assertions in 45 cases. Its 295 MB +untracked vendor backup was moved to `/tmp/atomic-local-light-vendor-backup`, +then the worktree was removed with its branch ref kept. The tornado cap worktree contains an +older all-parcel shader experiment, while `v0.25` now uses bounded depth-sliced +condensation. Preserve its capture script and shader diff until the current +visual parity result is assessed. The portal worktree's host-only Ready fence +change weakens the replica check and was not merged. The main checkout has a +newer source/destination fence condition and a destination prediction seed; +the focused portal adoption test passed 12 assertions in one case. +The detached portal worktree's source diff was saved at +`/tmp/atomic-head-portal-source.patch`, its base commit is preserved by +`codex/archived-head-portal`, and its worktree was removed. The older harness +may still offer useful real transfer coverage, but needs porting to the +current test and cannot justify the host-only fence change. +The tornado cap worktree's source and binary world diff is saved at +`/tmp/atomic-tornado-isolated-cap-fix.patch`, and its capture script is at +`/tmp/atomic-capture-tornado-isolated.sh`. Its branch ref remains. The current +TornadoSim example and GPU particle tests passed 143 and 126 assertions. The +worktree's all-parcel shader and 2.1 million triangle capture threshold do not +fit the newer bounded depth-sliced path, so its uncommitted experiment was not +merged. Visual parity remains open. +The broader `test_client '[client][portal]'` selector initially exited 42: +six cases passed and two GPU cases failed during client initialization because +`PortalLighting.cpp` left a process wide assets override set to +`.cache/build/dev/assets`, where shaders are not staged. The fixture now +restores its prior assets path. After rebuilding, the same selector passed +422,745 assertions in eight cases. The strict 30/60/144/240 product matrix +remains open. + +The primary checkout's unfinished product work continues below. Archived +patches are reference material, not accepted code. + +## Last verification and environment + +- `git diff --check` in the main checkout and `git diff --cached --check` for + the handoff and portal fixture fix passed at 09:23 UTC. The staged priority + benchmark passed `git diff --cached --check` before integration. +- At 09:14 UTC, the filesystem had about 114 GiB free. Avoid duplicating full + build trees without checking space first. +- Commits in this handoff session include `5e30f523`, which preserved the + original benchmark commit's author and message and contains only + `mono.engine/replication/benchmarks/PriorityRefinement.cpp`; `0598d7ce`, + which contains this handoff and the portal lighting test fixture cleanup; + and `4d2d8175`, which updates the handoff after worktree cleanup and GPU + validation. Later handoff edits may be uncommitted. +- Web reference for worktree removal semantics: + . diff --git a/Justfile b/Justfile index 44928435c..249bb5b3e 100644 --- a/Justfile +++ b/Justfile @@ -163,6 +163,26 @@ render-check filter="[render][gpu]" backend="vulkan": (build "test_render") export MONO_RENDER_REVISION="$(git describe --always --dirty)" ./{{build}}/tests/test_render "{{filter}}" +# Loads the authored high-count point, spot, fog and environment course, then +# proves its sixteen-volume GPU budget. The light collector's receiver-aware +# sixteen-light cap is exercised by the world-view release test. Each measured +# submission waits for the GPU; no benchmark artifact is written outside build. +volume-light-stress frames="120": + #!/usr/bin/env bash + set -euo pipefail + cmake --preset release-tests > /dev/null + cmake --build --preset release-tests --target test_examples test_scene test_render + ./.cache/build/release-tests/tests/test_examples "[examples][lighting-stress]" + ./.cache/build/release-tests/tests/test_scene "[scene][volume]" + ./.cache/build/release-tests/tests/test_render "[render][lighting-stress]" + MONO_LIGHT_SELECTION_STRESS_FRAMES={{frames}} ./.cache/build/release-tests/tests/test_render "[render][world-view]" + MONO_VOLUME_STRESS_FRAMES={{frames}} ./.cache/build/release-tests/tests/test_render "[render][gpu][volume-stress]" + +# Runs the authored 256-point, 256-spot and 256-volume course through the +# release renderer. The end-of-run statistics print to the terminal. +lighting-stress-scene frames="720": (build "client") + ./{{build}}/client/client --headless --script mono.engine/examples/assets/scripts/LightingStress.luau --frames {{frames}} --stats --graph --uncapped + # Whole camera-batch signature costs, with unchanged rows and one-row edits. render-preparation-bench samples="5": cmake --preset bench > /dev/null @@ -175,6 +195,40 @@ data-capture-hook-bench samples="5": cmake --build --preset bench --target benchrunner bench_render ./.cache/build/bench/tools/benchrunner --build .cache/build/bench --filter engine.render.bench.data-capture-hooks --all --samples {{samples}} +# Repeat a fixed headless Vulkan data-capture workload in the release-optimised preset. +data-capture-gpu-profile captures="30": + #!/usr/bin/env bash + set -euo pipefail + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_render + if ! MONO_DATA_CAPTURE_PROFILE=1 MONO_DATA_CAPTURE_PROFILE_CAPTURES={{captures}} timeout --foreground --kill-after=10s 180s ./.cache/build/bench/bench/bench_render --suite engine.render.bench.data-capture-gpu-profile --samples 1; then + echo "data-capture-gpu-profile failed or exceeded its 180s device deadline" >&2 + exit 1 + fi + +# Release-optimised MCP discovery, capture dispatch, and provider lifecycle cost. +mcp-control-profile: + #!/usr/bin/env bash + set -euo pipefail + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_control + if ! timeout --foreground --kill-after=10s 180s ./.cache/build/bench/bench/bench_control --suite engine.control.bench.mcp-control --samples 1; then + echo "mcp-control-profile failed or exceeded its 180s deadline" >&2 + exit 1 + fi + +# Repeatedly activate and remove the real capture tool provider around a +# synthetic 64 KiB pending ticket, then report live-byte slope and ownership. +mcp-capture-hook-soak cycles="128": + #!/usr/bin/env bash + set -euo pipefail + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_control + if ! MONO_MCP_CAPTURE_SOAK=1 MONO_MCP_CAPTURE_SOAK_CYCLES={{cycles}} timeout --foreground --kill-after=10s 180s ./.cache/build/bench/bench/bench_control --suite engine.control.bench.mcp-control --samples 1; then + echo "mcp-capture-hook-soak failed or exceeded its 180s device deadline" >&2 + exit 1 + fi + # The normal benchmark runner reports only wall time. This GPU suite also emits # CPU recording, Vulkan timestamp, residency, allocation, cache and transfer # counters, so invoke its selected suite directly in the optimized preset. @@ -191,6 +245,19 @@ gpu-texture-atlas-bench samples="1": exit 1 fi +# Release-optimised compute, draw, timestamp and logical-memory measurement +# for every supported analytical storm field preset. Allocation refusal remains +# a reported result so modest GPUs still document their supported ceiling. +gpu-particle-field-bench samples="1": + #!/usr/bin/env bash + set -euo pipefail + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_render + if ! MONO_GPU_PARTICLE_FIELD_REPORT=1 timeout --foreground --kill-after=10s 900s ./.cache/build/bench/bench/bench_render --suite engine.render.bench.gpu-particle-field --samples {{samples}}; then + echo "gpu-particle-field-bench failed or exceeded its 900s device deadline" >&2 + exit 1 + fi + # Builds the device-owning benchmark without running it, then proves every # compiled resource shader was staged beside that benchmark. check-bench-render-shaders: @@ -294,6 +361,23 @@ presentation-fuzz runs="10000" compiler="clang++-21": "$fuzz_build/fuzz/fuzz_presentation" --write-seeds "$fuzz_build/fuzz/presentation-corpus" "$fuzz_build/fuzz/fuzz_presentation" "$fuzz_build/fuzz/presentation-corpus" -runs={{runs}} -max_len=65536 -timeout=10 -rss_limit_mb=1024 -artifact_prefix="$fuzz_build/fuzz/presentation-artifacts/" +# Coverage-guided hostile GUI parsing under AddressSanitizer and UBSan. The +# targets generate deterministic canonical documents, markup, a font package, +# binding paths, and a bounded SVG before their bounded smoke run. +fuzz-ui runs="1000" compiler="clang++-21": + #!/usr/bin/env bash + set -euo pipefail + fuzz_build=".cache/build/gui-fuzz" + cmake --preset server -B "$fuzz_build" -DCMAKE_CXX_COMPILER="{{compiler}}" -DCMAKE_C_COMPILER="${CC:-clang-21}" -DMONO_BUILD_TESTS=OFF -DMONO_TRACY=OFF -DMONO_HEAP_PROFILE=OFF -DMONO_FUZZ_GUI=ON -DMONO_FUZZ_BAKE=ON + cmake --build "$fuzz_build" --target fuzz_gui_document fuzz_gui_text fuzz_gui_binding fuzz_bake_svg -j 4 + for target in fuzz_gui_document fuzz_gui_text fuzz_gui_binding fuzz_bake_svg; do + corpus="$fuzz_build/fuzz/$target-corpus" + artifacts="$fuzz_build/fuzz/$target-artifacts" + mkdir -p "$corpus" "$artifacts" + "$fuzz_build/fuzz/$target" --write-seeds "$corpus" + "$fuzz_build/fuzz/$target" "$corpus" -runs={{runs}} -max_len=65536 -timeout=10 -rss_limit_mb=1024 -artifact_prefix="$artifacts/" + done + # Measure the benchmark suites a change could have affected. # # **The same selection as `just test`, over `bench/` instead of `tests/`.** A @@ -318,6 +402,72 @@ bench *args: # Every benchmark, whatever changed. bench-all *args: (bench "--all" args) +# just engine-stress-bench # 5 samples, CPU suites +# just engine-stress-bench 11 1 # 11 samples, GPU suites too +# +# One table: module, stress target, row, min, spread, and the 2026-09-22 audit +# figure where one exists. Device suites run only with gpu=1. +# Run every engine and CDN benchmark suite into docs/ENGINE_STRESS_TEST.md. +engine-stress-bench samples="5" gpu="0": + cmake --preset bench > /dev/null + cmake --build --preset bench + python3 scripts/engine-stress-report.py --build .cache/build/bench --samples {{samples}} {{ if gpu == "1" { "--gpu" } else { "" } }} + +# Lookup across a large, text-sorted bake-pipeline set. Output stays on the +# terminal so a busy machine cannot turn one measurement into a stored claim. +bakegraph-pipeline-set-bench samples="5": + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_bakegraph + ./.cache/build/bench/bench/bench_bakegraph --suite engine.bakegraph.bench.pipeline-set --samples {{samples}} + +# Durable datastore cost for a complete snapshot, using a disposable SQLite file under the bench build. +datastore-sqlite-bench samples="5": + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_datastore + ./.cache/build/bench/bench/bench_datastore --suite engine.datastore.bench.sqlite-snapshot --samples {{samples}} + +# Each scheduler fixture gets a fresh heap-profile tree. Keep raw timings on stdout. +scheduler-timing-bench samples="5": + #!/usr/bin/env bash + set -euo pipefail + case "{{samples}}" in [1-5]) ;; *) echo "samples must be 1 through 5" >&2; exit 2 ;; esac + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_ecs + for scheduler_case in $(seq 0 79); do + ATOMIC_SCHEDULER_TIMING_PROFILE=1 ATOMIC_SCHEDULER_TIMING_CASE="$scheduler_case" \ + ./.cache/build/bench/bench/bench_ecs --suite engine.ecs.bench.scheduler --samples {{samples}} + done + +# Example orbit and spin systems over deterministic ECS fixtures. +examples-motion-bench samples="5": + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_examples + ./.cache/build/bench/bench/bench_examples --suite engine.examples.bench.motion --samples {{samples}} + +# Runtime SPIR-V to MSL translation through the same fixture used by the unit suite. +msl-translation-bench samples="5": + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_msl + ./.cache/build/bench/bench/bench_msl --suite engine.msl.bench.translate --samples {{samples}} + +# Steady-state script source mirroring for cached LocalScripts. +script-source-mirror-bench samples="5": + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_script + ./.cache/build/bench/bench/bench_script --suite engine.script.bench.source-mirror --samples {{samples}} + +# QuickJS property reads and writes through the engine's ECS bindings. +scriptjs-property-access-bench samples="5": + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_scriptjs + ./.cache/build/bench/bench/bench_scriptjs --suite engine.scriptjs.bench.property-access --samples {{samples}} + +# Headless ImGui layout and geometry hashing; this does not open a GPU device. +ui-headless-bench samples="5": + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_ui + ./.cache/build/bench/bench/bench_ui --suite engine.ui.bench.headless-interface --samples {{samples}} + # Portal reply encoding and decoding, per complete batch. No GPU or process transport. # Run the binary directly so measurements stay on the terminal. portal-exchange-bench samples="5": @@ -345,6 +495,17 @@ portal-ambient-profile samples="5": cmake --build --preset bench --target bench_render MONO_PORTAL_CODEC_PROFILE=1 ./.cache/build/bench/bench/bench_render --suite engine.render.bench.portal-ambient --samples {{samples}} +# Runs the portal product acceptance matrix and writes one reviewable report +# under the release-tests build: product walks at every rate, the stall schedule, +# the 24-cell impairment grid, matched seam captures and uncaptured timing. It +# exits nonzero unless every row passed. +portal-product-acceptance: + #!/usr/bin/env bash + set -euo pipefail + cmake --preset release-tests > /dev/null + cmake --build --preset release-tests --target client server test_client test_script + python3 scripts/demos/portal-product-acceptance.py --build .cache/build/release-tests + # The Luau boundary rows, including the complete async compute lifecycle. Keep # this explicit because a binding benchmark is useful while working on the VM # without running every benchmark in the repository. @@ -353,6 +514,12 @@ script-binding-bench samples="5": cmake --build --preset bench --target benchrunner bench_scriptluau ./.cache/build/bench/tools/benchrunner --build .cache/build/bench --filter engine.scriptluau.bench.bindings --all --samples {{samples}} +# Active input dispatch through both VMs, with unchanged and sparse key words. +script-input-dispatch-bench samples="5": + cmake --preset bench > /dev/null + cmake --build --preset bench --target benchrunner bench_scripthost + ./.cache/build/bench/tools/benchrunner --build .cache/build/bench --filter engine.scripthost.bench.input-dispatch --all --samples {{samples}} + # Repeated public ParticleEmitter:Emit calls plus one enabled-emitter tick. This # is the Luau boundary row for the ECS burst queue, measured in the bench preset. particle-emit-bench samples="5": @@ -397,6 +564,12 @@ persistent-manifold-bench samples="5": cmake --build --preset bench --target benchrunner bench_physics ./.cache/build/bench/tools/benchrunner --build .cache/build/bench --filter engine.physics.bench.narrowphase --all --samples {{samples}} +# Compare candidate counts and stage costs for the deterministic 4,000-body pile. +physics-pile-cell-bench samples="1": + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_physics + ./.cache/build/bench/bench/bench_physics --suite engine.physics.bench.pile-cells --samples {{samples}} + # Separated closing pairs through speculative generation, with and without the # broad-phase sync and query. Output remains on the terminal. speculative-contact-bench samples="5": @@ -483,6 +656,46 @@ simulation-publish-sweep samples="3": --samples "{{samples}}" done +# The scored and refined multi-row publish path. The priority hook locates one +# Bearing slot per entity and refinement must reuse it across component rows. +priority-refinement-bench samples="5": + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_replication + ./.cache/build/bench/bench/bench_replication --suite engine.replication.bench.priority-refinement --samples {{samples}} + +# Compare grid cells on the dense pile and stacked/scattered controls. Exact +# contacts and body-state parity is required before the profiled benchmark runs. +physics-cell-size-sweep samples="5": + test "{{samples}}" -ge 1 -a "{{samples}}" -le 5 + cmake --preset release-tests > /dev/null + cmake --build --preset release-tests --target test_physics + ./.cache/build/release-tests/tests/test_physics '[physics][cell-sizes]' + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_physics + ./.cache/build/bench/bench/bench_physics --suite engine.physics.bench.cell-sizes --samples {{samples}} + +# Repeat pile, stack, scattered and mixed-scale cell orders in fresh processes. +# Owner frames exclude occupancy diagnostics and exact comparisons in each BENCH call. +physics-cell-size-counterbalance samples="5": + test "{{samples}}" -ge 1 -a "{{samples}}" -le 5 + cmake --preset release-tests > /dev/null + cmake --build --preset release-tests --target test_physics test_spatial + ./.cache/build/release-tests/tests/test_spatial '[hashgrid]' + ./.cache/build/release-tests/tests/test_physics '[physics][cell-sizes]' + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_physics + sha256sum ./.cache/build/bench/bench/bench_physics + printf '# cell-run repeat=1 preset=bench compute=serial background=unattributed\n' + ./.cache/build/bench/bench/bench_physics --suite engine.physics.bench.cell-size-counterbalance --samples {{samples}} + printf '# cell-run repeat=2 preset=bench compute=serial background=unattributed\n' + ./.cache/build/bench/bench/bench_physics --suite engine.physics.bench.cell-size-counterbalance --samples {{samples}} + +# Recovery-row re-offer work with acknowledgements withheld after the initial join. +recovery-rows-bench samples="5": + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_replication + ./.cache/build/bench/bench/bench_replication --suite engine.replication.bench.recovery-rows --samples {{samples}} + # How much of the repository is code, comment and blank, as markdown. # # `just linecount` walks everything except mono.vendor and the dot-directories; @@ -835,18 +1048,17 @@ bindings: (build "bindings") bindings-check: (build "bindings") ./{{build}}/tools/bindings --check -# Every authored script against the declarations, in both languages. +# Luau examples and Studio's TypeScript panels against the engine declarations. # # **The other half of `bindings-check`.** That one asks whether the declarations -# still match the class table; this asks whether the scripts still match the -# declarations. A property removed from the class table regenerates cleanly and -# leaves every script that named it broken, with nothing reporting it until the -# scene fails to build. +# still match the class table; this checks the Luau examples and Studio panels +# against those declarations. A property removed from the class table regenerates +# cleanly and leaves a caller broken, with nothing reporting it until runtime. # -# The Luau half is `mono.tools/scriptcheck`, which exists because upstream's -# `luau-analyze` has no way to load a definition file - see MonoVendor.cmake. -# The TypeScript half is `tsc` against the checked-in `tsconfig.json`, which -# already lists the generated `.d.ts` as its type root. +# Luau examples go through `mono.tools/scriptcheck`, which exists because +# upstream's `luau-analyze` has no way to load a definition file - see +# MonoVendor.cmake. Studio panels go through `tsc` and the checked-in +# `tsconfig.json`, which lists the generated `.d.ts` as its type root. # # **The compiler is the pinned one, not whatever `bunx tsc` resolves to.** # `package.json` names an exact version and this runs `node_modules/.bin/tsc`, @@ -855,8 +1067,8 @@ bindings-check: (build "bindings") # # **`tsc` is skipped rather than fatal when no runner is installed.** It is the # one check here that needs something outside the C++ toolchain, and a -# prerequisite list that grows a Node runtime for two example files is a worse -# trade than a check that says out loud when it did not run. +# prerequisite list that grows a Node runtime is a worse trade than a check that +# says out loud when it did not run. typecheck: (build "scriptcheck") #!/usr/bin/env bash set -euo pipefail @@ -872,7 +1084,7 @@ typecheck: (build "scriptcheck") fi ./node_modules/.bin/tsc --noEmit - echo "typecheck ok - luau and typescript $(./node_modules/.bin/tsc --version | cut -d' ' -f2)" + echo "typecheck ok - luau and studio typescript $(./node_modules/.bin/tsc --version | cut -d' ' -f2)" # The same scripts again, through the language server an editor actually runs. # @@ -1140,11 +1352,32 @@ client-smoke: (build "client") || { echo "FAIL: the button was pressed and its Activated never reached the script"; tail -20 "$log"; exit 1; } echo "client ok - pressed a button with no display and the script heard it" +# Runs the packaged TornadoSim world without publishing or serving content. The +# check proves its sound rows resolve from the files staged beside the client. +packaged-tornado-audio: (build "client") + PRESET={{preset}} ./scripts/packaged-tornado-audio-test.sh "./{{build}}/client/client" + # Capture the shipped GUI compositor at two sizes and compare click-driven # status changes. The report keeps the BMPs beside the build for human review. ui-check: (build "client") PRESET={{preset}} ./scripts/demos/ui-visual-check.sh +# Open the UI lab in the client. Extra arguments are passed to the client. +ui-lab *args: (build "client") + ./{{build}}/client/client --script '{{build}}/assets/examples/scripts/UiLab.luau' {{args}} + +# Rerun the UI lab contract suite, including after script-only edits. +ui-test: (build "test_examples") + ./{{build}}/tests/test_examples '[ui-lab]' + +# Capture every shipped Luau demo and authored world through the headless client. +demo-check frames="120": client + python3 scripts/demos/check-demos.py --build {{build}} --frames {{frames}} + +# Exercise the UI lab through the native desktop input path. +ui-live-check *args: (build "client") + python3 scripts/demos/ui-live-check.py --preset '{{preset}}' {{args}} + # Run the client to a frame budget and check the process actually ends. # # **A hang is the one failure a `TEST_CASE` cannot report**, which is why this @@ -1276,6 +1509,14 @@ studio-resize: (build "studio") studio-viewport-isolation: (build "studio") ./scripts/studio-viewport-isolation-test.sh ./{{build}}/studio/studio +# Captures the View-menu virtual-camera position lock, a translation-only free +# inspection view, a recapture and an unlock. The script retains scene BMPs, +# menu XWDs and read-only renderer diagnostics for each phase. +# +# It is not part of `just check`: it requires X11, a Vulkan device and xdotool. +studio-virtual-camera-capture: (build "studio") + ./scripts/studio-virtual-camera-capture-test.sh ./{{build}}/studio/studio + # Run the headless server. `just host --ticks 100` passes flags through. host *args: (build "server") ./{{build}}/server/server {{args}} @@ -1445,6 +1686,17 @@ stress label="baseline" clients="200" seconds="45" port="45100": (build "server" stress-motion label="motion-baseline" clients="1" seconds="20" port="45200" window="30": (build "server") (build "loadtest") ./scripts/stress-test.sh {{build}} {{label}} {{clients}} {{seconds}} {{port}} ReplicationStress.luau {{window}} +# Two hundred moving clients with a fixed seed, ready to compare across server +# changes. The script records both random-heading arguments beside the capture. +stress-random-motion label="random-motion" clients="200" seconds="45" port="45300" window="30" seed="1" every="30": (build "server") (build "loadtest") + ./scripts/stress-test.sh {{build}} {{label}} {{clients}} {{seconds}} {{port}} Stress.luau {{window}} {{seed}} {{every}} + +# One driver, eight hosted remote worlds, 200 moving clients and a signed CDN +# fetch cohort. Run with `just preset=release integrated-stress`; output stays +# under the selected build directory's integrated-stress/ folder. +integrated-stress seconds="45" port="45100": (build "server") (build "cdn") (build "loadtest") + ./scripts/integrated-stress-test.sh ./{{build}} {{seconds}} {{port}} + # Configure and build with no client at all, which is how the tier split is # proved rather than asserted: the staged server/ gets no shaders/ directory. check-server-is-headless: @@ -1483,19 +1735,15 @@ check-cdn-is-bare: # wrong, in the half nobody tests: the cycle guard, or the hash. # # A third would arrive as a file rather than as a decision. The render pipeline -# editor and `Engine::bakegraph`'s pipeline documents are both still to be -# written, and either could start its own registry and its own canvas without -# anybody noticing until the first divergence - which is exactly what AGENTS.md -# rule 6 says to make the build check rather than leave in somebody's memory. +# editor uses this library; future graph editors must do the +# same so their cycle guards and canvases do not diverge. AGENTS.md rule 6 says +# to make that a build check rather than leave it in somebody's memory. # # Extend the library where it lives. `mono.studio/nodegraph` is ours: it was a # vendored submodule against a separate repository until v0.18.0, an engine # module until v0.19, and a library of the editor's since - so extending it is # an edit here rather than a pull request against somewhere else. # -# The studio's Demo Nodes set is not a second implementation. It registers types -# through that module's public `NodeTypes::Register` and implements none of the -# model, which is the seam this rule is protecting rather than one it forbids. check-one-node-graph: #!/usr/bin/env bash set -euo pipefail @@ -1764,6 +2012,40 @@ em-dash-check: fi echo "em-dash-check ok - no U+2014 in ${#files[@]} first-party file(s)" +# Shows which complete preset trees can be reclaimed without touching sources, +# downloads, the test signature cache or the shared compiler cache. `yes` is +# required to delete. dev and release are kept for the normal edit/ship loop; +# ci and the other checks can be rebuilt from their presets when needed. +build-prune apply="no": + #!/usr/bin/env bash + set -euo pipefail + case "{{apply}}" in + no|yes) ;; + *) echo "Use 'just build-prune' to preview or 'just build-prune yes' to delete." >&2; exit 2 ;; + esac + root=$PWD + total=0 + for dir in .cache/build/*/; do + [ -d "$dir" ] && [ ! -L "$dir" ] || continue + name=${dir%/} + name=${name##*/} + case "$name" in dev|release) continue ;; esac + cache="$dir/CMakeCache.txt" + [ -f "$cache" ] || continue + # A build directory copied from another checkout does not belong to us. + if ! grep -qxF "CMAKE_HOME_DIRECTORY:INTERNAL=$root" "$cache"; then + echo "skipping $dir: CMake source is not this checkout" + continue + fi + bytes=$(du -sx --block-size=1 "$dir" | cut -f1) + total=$((total + bytes)) + printf '%-28s %8d MiB\n' "$dir" "$((bytes / 1048576))" + if [ "{{apply}}" = yes ]; then + rm -rf -- "$dir" + fi + done + printf '%s: %d MiB %s\n' build-prune "$((total / 1048576))" "$(if [ "{{apply}}" = yes ]; then echo reclaimed; else echo reclaimable; fi)" + clean: rm -rf .cache/build @@ -1774,3 +2056,36 @@ clean-all: bench-mesh-lod samples="5": cmake --build --preset bench --target bench_assets ./.cache/build/bench/bench/bench_assets --suite engine.assets.bench.mesh-decimate --samples {{samples}} + +# Headless whole-rig pose resolution. Profile/canonical diagnostics remain stdout. +scene-skinning-bench samples="5": + @test {{samples}} -ge 1 && test {{samples}} -le 5 || { echo "samples must be 1..5" >&2; exit 2; } + cmake --preset bench > /dev/null + cmake --build --preset bench --target benchrunner bench_scene + ./.cache/build/bench/tools/benchrunner --build .cache/build/bench --filter engine.scene.bench.skinning --all --samples {{samples}} + +# Direct headless convex-hull build phases and returned payload residency. +convex-hull-bench samples="5": + @test {{samples}} -ge 1 && test {{samples}} -le 5 || { echo "samples must be 1..5" >&2; exit 2; } + cmake --preset bench > /dev/null + cmake --build --preset bench --target benchrunner bench_collision + ./.cache/build/bench/tools/benchrunner --build .cache/build/bench --filter engine.collision.bench.convexhull --all --samples {{samples}} + +# Actual Audio Window observer/cache paths. Optional in-memory stdout capture by root driver. +audio-window-panel-bench samples="5": + test "{{samples}}" -ge 1 -a "{{samples}}" -le 5 + cmake --preset release-tests > /dev/null + cmake --build --preset release-tests --target test_studio + ./.cache/build/release-tests/tests/test_studio '[studio][audio_window_presentation]' + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_studio + ./.cache/build/bench/bench/bench_studio --suite studio.bench.audio-window --samples {{samples}} + +# Tagged Metrics lookup diagnostic. Numeric capture uses the isolated driver; stdout stays in RAM. +metrics-lookup-bench: + # Eight warm and exactly five measured phases are required by the diagnostic gate. + cmake --preset bench > /dev/null + cmake --build --preset bench --target bench_core + ATOMIC_METRICS_LOOKUP_PROFILE=1 timeout --foreground --kill-after=10s 180s ./.cache/build/bench/bench/bench_core --suite engine.core.bench.instrumentation --samples 5 + +import 'scripts/demos/version-impact.just' diff --git a/ROADMAP.md b/ROADMAP.md index 241ad9d44..d7573b225 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -39,61 +39,24 @@ The milestone headings below are development labels. Not in line with project ve ### v0.25 -- [_] review over v0.24 and consolidate, improve, tweak, etc. -- [_] improve atomic-game-engine build file usage sizes. Takes over 120GB right now, needs to be reduced. Reduce hash for each mono repository to a reasonable size for each, cleanup old files, etc. -- [_] simplify down RUNNING.md, should be minimal, shows each available `just` job, how to build each, etc. Should not contain lots of descriptive information about how those systems work, just short descriptions and what they are aimed at to do. -- [_] USER WORK: cleanup documents in `docs/`, maybe a `docs/systems` folder would be more suited for things like `RENDER-HOOKS.md`, `DEMOS.md`, `ECS_COMPONENTS.md`, `schema.toml` and `schema-data.toml`. -- [_] Prune `PLAN-procedural-planets.md`, `PORTAL-HANDOFF.md`, `RENDER-POST-HOOK-REFACTOR.md`, `RENDER-REFACTOR-TASKS.md`, `RENDER-REFACTOR.md` and `TORNADOSIM.md`. -- [_] Prune old files in `docs/future-work/` as well. e.g. merge `FUTURE_COMPONENTS.md` components into relevent document files in `docs/future-work/`, then leave the remaining orphaned ones in `FUTURE_COMPONENTS.md`. -- [_] improve `schema.toml` and `schema-data.toml` so its better laid out (schema is the general layout, schema-data is the actual useful information that we would grep and search specific classes, components and functions in). Like Roblox Studio Class API Reference. -- [_] consolidate/improve `CONTRIBUTING.md`, `SECURITY.md`, `docs/THIRD_PARTY_NOTICES.md`, `CODE_ARCH.md`, `CODE_DOCUMENTING.md`, `CODE_FORMAT.md` and `CODE_QUALITY.md`, with small sentences at the start of the file describing what they contain in succinct detail. -- [_] cleanup documentation and layout -- [_] review and cleanup render pipeline (plan first) -- [_] plan a consolidation for the MCP-ADDITIONS.md systems. Super big, needs to ensure its properly implemented and looks good. Maybe even isolating code to a separate folder and then using hooks to ingest (and make those hooks hot loadable and unloadable so we can disable when we don't need to use them). -- [_] update and prune old content in documentation. check each statement, update, remove or replace. -- [_] create a "sky grid" of floating terrain balls with each one having one of 8 custom made shaders, then have the camera fly forward between the seams. this is a benchmark called BenchmarkSkyGrid.luau built-in demo example. We'll also use this as a performance profiler for editablemesh + terrain + etc. -- [_] add gpu resource constraining (freezes all other applications right now) -- [_] check LOD is cleaned up when the mesh changes / is deleted / LOD properties are changed so they release and are recomputed -- [_] stress test all underlying engine systems (input, cdn, assets, parallel world, physics, hundreds of players + characters all moving around randomly, etc). for each, find at least 5 optimisations. -- [_] create two stress test demos: 100 unique 4k textures on material spheres with PBR (like the PBR demo), and 1 unique 4k texture on material spheres with PBR. tests instancing (for 1 duplicate item) and mem/compute usage for the uniques. -- [_] add a "light path visualiser" that shows a visualisation of the spatial casting of light emitters so i can see what path they take, what they hit, etc. basically blue for empty space it travels, red for end of light, orange for pass-through or reflections. -- [_] fix multi-select multi-property editing (when i select multiple objects, it should check all objects for the same component and value im editing and match them). - -- [_] add typed, read-only physics observation hooks at declared fixed-tick boundaries. Use stable string discovery names, typed immutable per-hook contexts and bounded non-blocking records. Define whether each record observes pre-solve, completed-solver or post-integration state; retain exact tick, world, units and availability; and expose completed records to data-factory MCP without allowing a hook to mutate physics state. -- [_] add typed, read-only replication observation hooks at declared exchange boundaries. Use stable string discovery names, typed immutable per-hook contexts and bounded non-blocking records. Preserve world, authority, client, baseline, tick and exchange-round identity; expose applied, rejected, repaired and dropped work without crossing a world boundary by pointer; and keep private payloads behind the existing permission boundary. -- [_] optimise server startup time -- [_] optimise and improve tests (particularly server and physics, can we add deterministic hooks so we can immediately wait for an update for a change instead of guessing with timestamps? test.solver, test.replication, etc) - -- [_] add extensive (freecam) camera tests (like flying through portals) -- [_] add extensive client character tests -- [_] add extensive client character CAMERA tests (zooming out and projecting camera through portal) -- [_] fix lights passing through portals not working -- [_] fix portals so they are seamless. really plan out how to make them seamless and how to handle "standing in the middle" so objects are visually there on both sides of the portal with no seam especially during movement (and how to make replication seamless too) - -- [_] more lighting capabilities; god rays, blue, depth of field, fog fields (not global fog, more like "fog across area of ground") -- [_] create a weather system demo using all the lighting capabilities (clouds, atmosphere, rain particles, etc). -- [_] remake the tornado simulation demo using the C++ repository as a base. Check the existing documentation, add missing engine features that we need (ask user questions about it first, you'll need to swap into plan mode), then implement once you get the OK. -- [_] pack multi-channel supporting render data in other channels, depth = r channel - ambient occulusion = g - anti-alias = b, for example. -- [_] add a way to "virtually lock" the camera position, with a adornment visual, such that all camera behavior acts as if its from that location, this way i can test if culling works and other behaviors. - -- [_] test studio and fix found bugs +- [x] Add typed physics, replication and portal observations with optional trace IDs, bounded per-world records and server JSONL export (physics and replication: `1dd7743d`). +- [x] Finish the measured engine stress pass and matched 200-client `RecoverRows` profiling. Retain the 4 m physics grid default; cell-size results vary by scene. The recovery candidate was rejected without a demonstrated gain. See the [stress audit](docs/ENGINE_STRESS_AUDIT_2026-09-22.md). +- [x] Validate the same-world follow-camera repair and extended tunnel walk with native presentation and render tests (`04315bcd`). Passed native dev/Vulkan validation on 2026-10-04: 32 presentation cases, the 64-frame tunnel sweep and 5 portal GPU cases. +- [x] Fix Studio widgets that start unsnapped from their viewport slots. +- [x] Allow Studio UI elements to move from the Studio screen to other screens. +- [x] Carry forward completed portal traversal and camera fixes. +- [x] Carry forward scheduler timing and Metrics fixes, plus physics, world, GUI and script fixes. +- [x] Carry forward Studio dock and window fixes. +- [x] Carry forward audio decode and mixer fixes. +- [x] Carry forward texture format, material shader and sequence fixes. +- [x] Bound PNG inflation before excess output allocation; preserve accepted output on malformed streams. +- [x] Carry forward benchmark reports and jobs. ### v0.26 -- [_] go through engine and consolidate and cleanup dead code branches. remove backport compatibilities with previous engine versions and ground this as the version. -- [_] go over render system and consolidate/improve hooks, nodes, graph system and visualiser of graph system - -- [_] do heavy memory, cpu and gpu benchmarking and profiling and see if we can squash data into multi-channel representations, improve computations and memory usage, trade lower precision for tiny visual changes, etc. - -- [_] add typed render hooks at proven boundaries. `DataFactoryHookBind` registers and discovers twelve stable read-only data-capture hooks and the synchronous `view.camera` mutation hook. Data capture remains pinned to exact pipeline, revision, view, snapshot and node identity and returns bounded asynchronous readbacks. `view.camera` accepts owned one-shot camera-frame, camera, and projection patches only for an exact installed pipeline revision, world, snapshot, and view slot; conflicts, stale revisions, malformed values, cancellation, and generation reuse are explicit. The renderer copies only the matching view before capture preparation and never calls external code or exposes a mutable view. The release CPU lifecycle benchmark fell from 41.62 to 20.48 microseconds per 64 lifecycles after dispatch stopped copying the full graph snapshot; validated capture planes now take ownership of readback vectors instead of copying them. GPU and readback release profiling plus a second real consumer remain open. A hook is an observer node, declared node output, or this bounded typed pre-view patch, not a second callback graph beside it. - 1. Inventory the current node output, resource lifetime, GPU submission and asynchronous readback boundaries, then choose one stable post-pass observation point. - 2. Give each internal hook an enum value and a stable string name for discovery, manifests and MCP. Never serialize the enum number. - 3. Give each hook its own typed immutable context. Do not use a generic `any` bag or an inheritance tree. A context states its valid lifetime, thread, resource access and unavailable fields. - 4. Keep observation non-blocking and read-only. GPU hooks append bounded records or schedule bounded asynchronous readback; the client polls completed records later. They never wait for the CPU or call arbitrary external code from the render thread. - 5. Apply render changes through CPU-owned scene or graph state before submission, then upload the normal delta. The bounded `view.camera` patch is the named exception: it is a synchronously consumed value record, not an observation callback. - 6. Make the existing data-capture resource observation the first consumer. Expose supported hook names and limits through capability discovery, then verify snapshot, camera, frame, crop and resource identity remain aligned. - 7. Profile record bytes, allocations, readback latency, dropped records and GPU work in a release capture before adding another hook point. - 8. Design separate typed observation hooks for physics and replication only after the render hook has two real consumers. Reuse the naming, bounded queue and polling rules, while keeping each subsystem's own tick, thread and lifetime contract. +- [_] Create owned 2D images usable by `ParticleEmitter`, `ImageLabel` and existing image consumers, with basic 2D transform and composition nodes. +- [_] Review the preserved full work on the `v0.26.5-imagegraph-full` branch before integration. +- [_] Exclude 3D, audio and broad simulation features from the first integration. ### v0.27 @@ -118,7 +81,6 @@ When you create a new world/scene, it auto appends the scripts in. - [_] expose automation tools (AutomationService) like mouse clicks and keyboard inputs to luau scripts (so we can create ai that plays for you) - [_] /docs/future-work/physics-expansion.md -- [_] /docs/future-work/ui-system.md - [_] /docs/future-work/world-streaming.md ### FUTURE diff --git a/RUNNING.md b/RUNNING.md index e3d80e945..965267cce 100644 --- a/RUNNING.md +++ b/RUNNING.md @@ -1,4054 +1,211 @@ -# Running +# Build and run -Every way to build and run something in this repository, and what each one is -for. +This is the command index for this checkout: use `just` from the repository root, and use each program's `--help` for its runtime options. -For getting a first build working on a fresh machine, see -[CONTRIBUTING.md](CONTRIBUTING.md). This file assumes the clone configures. +`just` defaults to `preset=dev`. Override it before the recipe, for example +`just preset=release build` or `just preset=server test`. Build products live in +`.cache/build//`. Build and test outputs live under `.cache/`; +documentation generators can update checked-in reference files. ---- +Every Linux preset builds with GCC, and configure refuses any other compiler. +Only the fuzz recipes use `clang++-21`, because libFuzzer needs it. If a build +directory picked up another compiler, run `cmake --preset --fresh`. -## The short version +## Start here ```sh -git clone --recurse-submodules -cd atomic-game-engine - -just setup # submodules, and shaderc's own DEPS -just build # everything, dev preset -just run --stats --graph # the client, both debug panels open -just edit # the editor, on a new game -just test # only the suites your change could have affected +just setup +just build +just run --stats ``` -Needs CMake 3.24+, Ninja and a C++20 compiler - nothing else. `glslc` is built -from the vendored shaderc, so it is not a prerequisite. Everything derived lands -in `.cache/`. - -A compiler cache is optional and strongly worth having: the build uses ccache -or sccache when one is on PATH, across every preset out of one shared cache. -The ccache default cap is 5 GB, which this tree outgrows - a full cache -silently evicts and the hit rate falls over. On a machine with room, raise it -once with `just ccache 20G` and check the reported lines to confirm the -pressure is gone (`Cleanups` stops climbing). - -On Windows the compiler has to be in the shell's environment rather than merely -installed on the machine, which is a requirement no other platform has and no -error message names. [On Windows](#on-windows) is what it looks like when it is -missing, and `scripts\build-windows.bat` is the build that arranges it itself. - ---- +For a specific product, use `just client`, `just server`, `just cdn`, +`just studio`, or `just launcher`. The executables are staged at: -# Building +| Program | Path | +|---|---| +| Client | `.cache/build//client/client` | +| Server | `.cache/build//server/server` | +| CDN | `.cache/build//cdn/cdn` | +| Studio | `.cache/build//studio/studio` | +| Launcher | `.cache/build//launcher/launcher` | ## Presets -```sh -cmake --preset dev # everything, tests, Tracy, unoptimised first-party code -cmake --preset release # optimised - the only preset that turns -O0 off -cmake --preset server # no client at all, and therefore no graphics stack -cmake --preset cdn # the content origin alone, on a machine with nothing installed -cmake --preset ci # dev, with warnings fatal -cmake --preset bench # release, plus the benchmark binaries -``` - -| Preset | Client | Server | CDN | Tests | First-party `-O` | -|---|---|---|---|---|---| -| `dev` | yes | yes | yes | yes | `-O0` | -| `release` | yes | yes | yes | no | optimised | -| `server` | **no** | yes | no | yes | `-O0` | -| `cdn` | **no** | **no** | yes | yes | `-O0` | -| `ci` | yes | yes | yes | yes | `-O0`, warnings fatal | - -`server` and `cdn` are the two presets that prove something rather than build -something. `server` proves the client tier is absent; `cdn` proves the content -origin needs no graphics stack at all - it configures where there is no Vulkan -SDK, no SDL and no shader compiler. - -## The `ci` preset, and the hook that runs it - -`ci` is `dev` with `MONO_WERROR=ON`, which makes every warning fatal. Nothing on -GitHub runs it and nothing on GitHub is going to - that is a decision, and -`docs/retired/DEFERRED.md` D00005 carries it. What runs it is your own push: - -```sh -just install-hooks # once per clone; `just setup` already does it -``` - -which points `core.hooksPath` at the checked-in `.githooks/`, and -`.githooks/pre-push` runs `just preset=ci check` before a push leaves the -machine. No branch push starts anything on GitHub - the one workflow there -builds release artefacts from tags - so the push is the last moment anything -verifies the tree, and the hook verifies all of it rather than only the -compile. - -**It exists because this preset went uncompilable three times while being -described as the standard.** At v0.4 - a `-Wmissing-field-initializers` in -`core::Arguments` and a `-Wdangling-reference` across `world`'s suites. Twice -more inside v0.15, the second a `-Wdangling-reference` in `cdn::OriginFromFlags` -iterating a `std::span` straight off a temporary `Flag`, live while a roadmap -line written hours earlier said the preset exited 0. Each was there for as long -as it took somebody to think of typing `preset=ci`. A check nobody runs stops -being read and then stops being true, which is the same thing this repository -already learnt from `just docs-check` at v0.2. - -**The hook runs the whole chain, not just the build.** It used to build and not -test, on the argument that the suites were `just check`'s job and a gate that -failed for somebody else's half-finished module would get skipped every time. -That argument assumed a remote build was still coming; with branch pushes -building nothing anywhere, a tree that compiles but fails its suites would -otherwise be caught by nobody. So the hook holds a push to the same -`just preset=ci check` a person runs by hand - format, build, tests, -architecture, source rules, shaders, bindings, typecheck, determinism, replay, -client smoke, orphans - and the escape for a shared tree with live warnings in -it is `git push --no-verify`, said out loud. - -| What | Cost, measured on this machine | +| Preset | Use | |---|---| -| `just preset=ci build`, nothing changed | ~1 s | -| `just preset=ci build`, a day of another preset's drift | ~1 min | -| `just preset=ci build`, from an empty `.cache/build/ci/` | ~3 min, once - 1,998 targets, vendors included | -| `just preset=ci check`, warm | ~3 min, and `test-all` is most of it - plus determinism, replay and client smoke | - -`ci` builds into `.cache/build/ci/`, a tree of its own, so the first push after -working in `dev` recompiles what changed since the last push rather than -nothing. That is part of the cost; the rest is the chain actually running. -Warm, the hook costs minutes, and it is expensive exactly when a lot has -changed, which is exactly when it should run. - -Skip one deliberately with `git push --no-verify`. There is no way to skip one -accidentally, and that asymmetry is the point. - -It compiles the working tree rather than the commits being pushed, so in a tree -several people or agents are editing at once, somebody else's live warning -refuses your push. That is the tree you are publishing, so it is the right -answer - but it is worth knowing before it happens. - -**Third-party code is optimised in every preset, and only first-party code is -not.** `AGENTS.md`'s argument for `-O0` - a profile should measure what this -engine does rather than what the optimiser rescued - is about this engine, and -SDL is not it. Measured on the editor: `SDL_SubmitGPUCommandBuffer` is where the -Vulkan backend turns a recorded command buffer into queue submissions, and the -`submit` span read **17 ms in a `dev` build against a p50 of 0.2 ms in -`release`** on one scene and one machine. That is not the renderer being slow; -it is somebody else's library at `-O0`, and it made every `dev` profile point at -the wrong thing. - -So `MONO_OPTIMISE_VENDOR` is on by default and `mono.vendor` builds at `-O2` -with its debug information kept. First-party targets append their own `-O0` -after it and the later flag wins, so `dev` still measures unoptimised engine -code. Pass `-DMONO_OPTIMISE_VENDOR=OFF` when the thing being debugged *is* a -vendored library. - -The first configure of a client preset builds glslang, SPIRV-Tools and shaderc, -so that the `glslc` compiling the engine's shaders is pinned rather than -whatever is on your PATH. It is the slowest part of a fresh build and it happens -once. `-DMONO_VENDORED_GLSLC=OFF` skips it and uses a system `glslc`. +| `dev` | Default development build. | +| `release` | Optimized shipping-cost build. | +| `profile` | Instrumented profiling build. | +| `server` | Headless server-only build. | +| `cdn` | Content-origin build. | +| `ci` | Strict CI build. | +| `bench` | Optimized benchmark build. | +| `bench-o0`, `bench-o1`, `bench-o2`, `bench-o3` | Benchmark compiler-optimization comparisons. | +| `dist-dev` | Development distribution build. | +| `windows-cross` | Windows cross-build. | -`just` works against `dev` unless told otherwise. **One override, written before -the recipe name, and it applies to every recipe:** +Configure or build a preset directly: ```sh +just preset=release configure just preset=release build -just preset=release run --stats --uncapped just preset=server test ``` -It is not a recipe argument. `build` is derived from `preset` when the Justfile -is read, and an argument cannot reach a derived variable - which is what made -the older `just test server` configure one preset and then run another's -binaries. The override is applied before anything is derived, so the configure, -the build and the directory the binary is run from cannot disagree. - -## Building all the monos - -```sh -just build # every target the preset configures -just preset=release build # the same, optimised -cmake --build --preset dev # without just -``` - -## On Windows - -```bat -scripts\build-windows.bat :: everything, dev preset -scripts\build-windows.bat client :: one target and its deps -scripts\build-windows.bat engine_ecs engine_world :: several -set PRESET=release (then run it) :: any other preset -``` - -The same configure and build as everywhere else, with the compiler environment -put in front of them. That is the whole of what the script adds, and it is not -optional: the presets generate Ninja, and Ninja has no per-command environment - -`build.ninja` is a flat list of literal command lines, so CMake cannot record -the toolchain's include and library paths in it. MSVC reads those from `INCLUDE` -and `LIB` in the environment instead, and a plain `cmd` or PowerShell window has -neither. - -Configuring still succeeds without them, so the first sign of it is every source -file in the repository failing at its first `#include` of anything at all: - -``` -fatal error C1083: Cannot open include file: 'cstddef': No such file or directory -``` - -which reads like the standard library is missing and is really the shell being -wrong. `vcvars64.bat` is what sets those variables, and a Developer Command -Prompt is nothing more than a `cmd` window that has already run it - so this -script runs it too, inside its own `setlocal`, and nothing it sets outlives the -build. Started from a Developer Command Prompt it finds the environment already -there and leaves it alone. - -`just build` has the same requirement, because the environment belongs to the -shell rather than to the tool driving CMake. The Visual Studio generator is the -one thing that does not, since MSBuild rebuilds the environment from the -`.vcxproj` - but it is not the generator the presets pin, and it is not the one -the build times here assume. - -Build once with this and the demo and studio scripts work from an ordinary -window too: they call CMake before running, and a build with nothing to do never -reaches the compiler. - -## Building one mono - -Every module is one CMake target, so building one is `just build `. -Its dependencies come with it; nothing above it does. - -```sh -just build engine_ecs # mono.engine/ecs and what it needs -just build client_lib # mono.client's library, not the program -just build test_render # one test binary -just preset=release build engine_ecs # any of the above, other preset -``` - -| Folder | Library target | Alias | Test binary | Tier | -|---|---|---|---|---| -| `mono.engine/core` | `engine_core` | `Engine::core` | `test_core` | shared | -| `mono.engine/parallel` | `engine_parallel` | `Engine::parallel` | `test_parallel` | shared | -| `mono.engine/ecs` | `engine_ecs` | `Engine::ecs` | `test_ecs` | shared | -| `mono.engine/world` | `engine_world` | `Engine::world` | `test_world` | shared | -| `mono.engine/spatial` | `engine_spatial` | `Engine::spatial` | `test_spatial` | shared | -| `mono.engine/scene` | `engine_scene` | `Engine::scene` | `test_scene` | shared | -| `mono.engine/gui` | `engine_gui` | `Engine::gui` | `test_gui` | shared | -| `mono.engine/assets` | `engine_assets` | `Engine::assets` | `test_assets` | shared | -| `mono.engine/physics` | `engine_physics` | `Engine::physics` | `test_physics` | shared | -| `mono.engine/effects` | `engine_effects` | `Engine::effects` | `test_effects` | shared | -| `mono.engine/script` | `engine_script` | `Engine::script` | `test_script` | shared | -| `mono.engine/bake` | `engine_bake` | `Engine::bake` | `test_bake` | shared | -| `mono.engine/graph` | `engine_graph` | `Engine::graph` | `test_graph` | shared | -| `mono.engine/game` | `engine_game` | `Engine::game` | `test_game` | shared | -| `mono.engine/examples` | `engine_examples` | `Engine::examples` | `test_examples` | shared | -| `mono.engine/net` | `engine_net` | `Engine::net` | `test_net` | shared | -| `mono.engine/delivery` | `engine_delivery` | `Engine::delivery` | `test_delivery` | shared | -| `mono.engine/replication` | `engine_replication` | `Engine::replication` | `test_replication` | shared | -| `mono.engine/control` | `engine_control` | `Engine::control` | - | shared | -| `mono.engine/audio` | `engine_audio` | `Engine::audio` | `test_audio` | client | -| `mono.engine/input` | `engine_input` | `Engine::input` | `test_input` | client | -| `mono.engine/render` | `engine_render` | `Engine::render` | `test_render` | client | -| `mono.engine/ui` | `engine_ui` | `Engine::ui` | `test_ui` | client | -| `mono.client` | `client_lib` | `Mono::client` | `test_client` | client | -| `mono.server` | `server_lib` | `Mono::server` | `test_server` | server | -| `mono.unified_tests` | `unified_tests_lib` | `Mono::unified_tests` | `test_unified_tests` | client | -| `mono.studio` | `studio_lib` | `Mono::studio` | `test_studio` | client | -| `mono.cdn` | `cdn_lib` | `Mono::cdn` | `test_cdn` | shared | -| `mono.tools/testrunner` | `testrunner_lib` | `Tool::testrunner` | `test_testrunner` | shared | -| `mono.tools/linecount` | `linecount_lib` | `Tool::linecount` | `test_linecount` | shared | -| `mono.tools/sourcecheck` | `sourcecheck_lib` | `Tool::sourcecheck` | `test_sourcecheck` | shared | - -The names are derived, not chosen per module: `mono_add_library` makes -`engine_` for an `Engine::` module and `_lib` for a product's own -library, and `mono_add_tests` makes `test_`. See -`mono.build/MonoLibrary.cmake`. - -The remaining tools are also built from `mono.tools/`: `bindings`, `docgen`, -`scriptcheck`, `mcpbridge`, `contentimport` and `assetc`. They are command-line -tools rather than engine modules; `testrunner`, `benchrunner` and `linecount` -are the other tool entry points. - -**`engine_input` and `engine_render` do not exist under the `server` preset.** -`mono.engine/CMakeLists.txt` only adds them when `MONO_BUILD_CLIENT` is on, so a -server configure never compiles SDL and never needs a shader compiler. That is -what makes "the server contains no graphics stack" a property of the build -rather than a claim about a link line - and it is why -`just preset=server build engine_render` fails with `unknown target` rather than -quietly building it. - -## Building one program - -```sh -just client # the client program and only its dependencies -just server # the server program and only its dependencies -just cdn # the content origin and only its dependencies -just build testrunner # the test runner -just preset=release client # optimised -``` - -`mono.engine` is libraries and never a product, so there is no target that -"builds the engine" on its own. Building a program builds the subset of modules -it links. - -## Where things land - -Each preset writes to `.cache/build//`: - -``` -.cache/build/dev/ -├─ client/ the client - binary, SDL3, shaders/resources/ -├─ server/ the server - no shaders, no SDL -├─ cdn/ the content origin - no shaders, no SDL -├─ tools/ testrunner -├─ tests/ every test binary -├─ lib/ static libraries, intermediate and never shipped -└─ shaderstage/ compiled SPIR-V, staged into each program that links it -``` - -A program's directory is runnable as it stands - see -[Running from somewhere else](#running-from-somewhere-else). Libraries are -intermediate and ship nowhere. - -## Cleaning - -```sh -just clean # .cache/build - every preset's build tree -just clean-all # .cache - including the smart-test cache -``` - -## Formatting - -```sh -just format # clang-format -i over every first-party .cpp and .hpp -just format-check # fails if anything is misformatted, changes nothing -``` - -Both skip `mono.vendor/` by construction: the directory list is explicit rather -than `find .`, because reformatting a submodule turns every future update into a -conflict. - -**`mono.studio/` is not in that list, and it should be.** It is a first-party -member that has never been swept, so its files are formatted by whoever last -edited them. Adding it is a one-line change and a fifty-eight file diff, which -is why it has not been folded into a feature commit - do it on its own. - ---- - -# What there is to run - -`mono.engine/` is libraries. No `main.cpp` lives under it and nothing ships from -it alone, so there is no single binary that "runs the engine" - there are thin -mains over the parts of it they need. - -| You want to | Run | Adds, over the engine | -|---|---|---| -| Pick one of the below without remembering its flags | `launcher` *(v0.18)* | a window, and nothing else | -| Run a script with nothing else in the way | `atomic` *(v0.6)* | nothing | -| Build a game | `studio` *(v0.7)* | the editor: explorer, properties, script editor, run and play | -| See something on screen | `client` | window, input, renderer, and the client half of networking | -| Host a simulation with no window | `server` | the tick loop, and the hosting half of networking | -| Serve a game's content | `cdn` | a content store, published and signed, served over HTTP | -| Exercise one module | its test binary | Catch2 | -| Re-run only what your change affected | `testrunner` | - | -| Check the architecture held | a CMake script | - | -| Put a server under two hundred real clients | `loadtest` *(v0.16)* | many genuine sessions in one process, and a flamegraph of the server | - -**The client and the server are shims, not the engine.** What they add is the -part that has to exist between two machines - name resolution, peer-to-peer, -hosting, the session - plus, on the client, presentation. A script that needs -none of that does not need either program, which is what the standalone runtime -is for. - -`client --help`, `server --help` and `studio --help` print their own options, -generated from the option declarations, so they cannot drift from what the -program accepts. - -**`--describe` prints the same table as JSON** *(v0.18)*, and every program in -the tree answers it because `core::Arguments` declares the flag itself. It -carries both settings surfaces - the options, and `core::Flags`' declared table - -and it is what the launcher builds its screens out of. - -```sh -./client --describe | jq '.options[] | select(.takesValue) | .name' -``` - ---- - -## The launcher *(v0.18)* - -```sh -just launch # the front screen -just launch --mode cdn # straight onto one mode -``` - -A window with one button per mode - Play, Join, Host, Studio, Serve content - -and, behind each, a form holding **every option and every setting that program -declared**. Nothing is filtered out; it is split across three tabs: - -| Tab | What is on it | -|---|---| -| Common | The four to seven options that decide what the run *is*, filled in | -| All options | Every option the program declared, grouped by name prefix | -| Engine settings | `core::Flags`' table, written as `--flag NAME=VALUE` | - -Both option tabs edit the same rows, so a value typed on one is the value on the -other. The search box above the tabs filters all three at once, and each group -header carries its hit count so a collapsed group still says how much is inside. - -An option whose value is a `PATH` or a `DIR` gets a browse button - a page for a -file, a folder for a folder, and the folder one picks **several at a time**: tick -three and confirm, and the option gets three rows. The ticks survive walking into -another parent, so the folders do not have to be siblings. `+` gives an option -another value by hand and `-` takes a row away. - -Ctrl+Enter launches, Escape goes back. - -It shows the command line it will run, in full, above the Launch button, with a -Copy next to it. That line is the same list it hands the child, so pasting it -into a terminal reproduces the run exactly. - -**It links none of the programs it starts.** It finds them staged beside it - -`/client/client` and so on - asks each one `--describe`, and spawns the -one you picked. So it needs them built: - -```sh -just build # everything, then every mode is available -just build cdn && just launch --mode cdn # or one program and its mode -``` - -A mode whose program is not staged is greyed out with the reason on the row, -which is the ordinary state under the `server` and `cdn` presets. Each row also -shows its program's version - two different versions in one tree means a -half-rebuilt tree, and that is worth seeing before the run rather than after. - -Host and Serve content keep the launcher up: it reports whether the child is -running, how long for, and how it ended, and offers Stop, Kill and Restart. Play, -Join and Studio hand the display over and the launcher minimises until the child -exits. - -The launcher has its own few options: - -```sh -./launcher --mode host --width 1400 --height 900 --scale 1.25 -./launcher --headless --frames 5 # for a smoke test; needs a frame budget -``` - -Forms live as long as the window. There are no saved profiles - `--config PATH` -is on every mode's form like any other option, and a settings file is the thing -that already does that job. - ---- - -# Settings *(v0.15)* - -Every program takes the same three, on top of its own options: - -```sh -./client --config atomic.cfg # a settings file -./client --flag client.width=1600 # one setting, above everything else -./client --flags # print every setting and where it came from, then exit - -ATOMIC_CONFIG=atomic.cfg ./server # the file, from the environment -ATOMIC_CLIENT_WIDTH=1600 ./client # one setting, from the environment -``` - -**What wins is decided by where a value came from, not by what ran first:** - - built-in default < config file < environment < command line - -so a config file cannot overwrite what somebody typed, whichever order the -program happens to read them in. `--flags` prints the source beside each value, -which is the answer to "why is this not what I set". - -## The file - -Sectioned `key = value`, where the section is the setting's prefix. `#` and `;` -start a comment, and a double quote keeps a value that contains one. - -```ini -# atomic.cfg -[engine] -log-level = trace -jobs.workers = 8 - -[server] -tick-rate = 30 -listen = true -listen-port = 9099 -idle-sleep = never - -[client] -# A setting that is genuinely several repeats its key, and order is kept. -content-sources = dir:/srv/atomic/processed -content-sources = 10.0.0.4:9080 - -[content] -gif = false # this process will not decode a GIF -svg = false # nor rasterise an SVG - -[cdn.publish] -mp4 = false # and an origin will not publish one -``` - -**A key naming no setting this program has is an error**, not a shrug - the same -position `--help` takes for an unknown option, and for the same reason: a typo -that is silently ignored fails at the behaviour rather than at the file. Run -`--flags` to see what a program actually has. - -**A file named with `--config` and missing is an error too**, where no file at -all is ordinary. A program launched with `--config prod.cfg` that silently ran -on defaults is the deployment failure this whole layer exists to prevent. - -**A repeated key appends and a source that outranks it replaces.** Three origins -in a file are three lines and all three are meant; one `--flag` on the command -line replaces all three, rather than being appended to a list the person running -it cannot see. A `--flag client.content-sources=` with nothing after it is how a -command line says "none". Nothing is split on a separator, so a path may contain -anything. - -## Where a client's content comes from *(v0.16)* - -A server gives its clients content one of two ways, and **which one is a field -rather than a shape**: `server.content-mode`, `relay` or `redirect`. There is no -second server program, no second settings type and no rebuild between them, for -the reason `cdn`'s three deployments are flag combinations rather than three -classes - moving between them has to stay a deployment decision. - -| Mode | What crosses | The client talks to a CDN | -|---|---|---| -| `relay` | content, over the game link the client already has | **no** | -| `redirect` | a list of origins, a grant and the publisher key | yes, to what it was told about | - -**`relay` is the default**, because it asks least of a player's network: one -port, already reached, already admitted. - -### The settings - -| Setting | Means | -|---|---| -| `server.content-mode` | `relay` or `redirect`. Anything else warns and uses `relay` | -| `server.content-sources` | An origin, as `dir:PATH` or `HOST:PORT`, optionally `NAME=` in front. **Repeatable, and the order is the priority** | -| `server.content-publisher-key` | 64 hex characters - the publisher whose signature content must carry | -| `server.content-store` | Unchanged. Also the fallback for `content-sources` when that names nothing | -| `server.content-grant-key` | Unchanged. What a `redirect` grant is signed with, and what the origin checks | -| `client.content-allowed-hosts` | A host a **server-named** origin may live on. Repeatable; empty allows any | - -`server.content-sources` is spelled exactly as `client.content-sources` is, -because it means the same thing. A server with a `content-store` and no -`content-sources` fetches from its own store, so the self-hosted case is one -flag rather than two saying the same thing. - -### Relay, in full - -```ini -# atomic.cfg - a server that holds the only origin connection -[server] -listen = true -listen-port = 9000 -content-mode = relay -content-store = /srv/atomic/processed -content-grant-key = 7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a -content-publisher-key = ba42458e83ba... -``` - -```sh -just host --config atomic.cfg -just run --connect 127.0.0.1:9000 --publisher-key ba42458e83ba... -``` - -The client asks the server for `/manifest`, `/dictionary` and `/bundle/` -over the game link and **verifies every byte against the publisher's signature** -exactly as it would off a socket - relaying moves the transport and not the trust -boundary. The server tells it the publisher key at admission, so a client that -was given none still has a root of trust. - -**The client has no authority in it, and the limits are the server's.** It may -ask and it may ask again; how often is `server::ContentRelay`'s to decide. A -client over its allowance has the request **dropped** and counted, and one that -keeps at it is flagged and refused outright for a cooldown - refused rather than -disconnected, so a client on a bad script stays distinguishable from one on a bad -network and can recover. `ContentRelayStatistics` counts asking-too-fast, -nothing-to-serve and the-link-was-full apart, because those are three incidents -with three different fixes. - -**Content never outranks the simulation.** A relayed piece is offered *after* the -world has been published, out of whatever is left of that tick's link budget, and -a piece the link would not take is offered again on the next tick from exactly -where it stopped. - -### Redirect, in full - -```ini -# atomic.cfg - a server that names the origins instead -[server] -listen = true -listen-port = 9000 -content-mode = redirect -content-sources = near=10.0.0.4:9080 -content-sources = far=203.0.113.9:9080 -content-store = /srv/atomic/processed -content-grant-key = 7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a -content-publisher-key = ba42458e83ba... - -[client] -# What this machine will let a server point it at. Empty allows any. -content-allowed-hosts = 10.0.0.4 -content-allowed-hosts = 203.0.113.9 -``` - -At admission the server sends the list, **a grant issued for that session**, and -the publisher key. The grant is what lets `cdn::Gate` admit the client's requests -without the origin knowing anything about sessions or players - so the origins -need the same `--grant-key` and nothing else about the game. - -**What the client does with the list is decided by where each value came from**, -which is this file's precedence rule applied one layer along: - -- **A source this client was configured with wins and is tried first.** The - server's list is *appended*, never substituted - the order of the list is the - policy, so "mine first, then whatever the host knows about" needs no flag. -- **The link itself goes last**, when there is one. It is the source that always - exists, so it is the one that answers when nothing before it did. -- **A publisher key pinned with `--publisher-key` is kept.** A server's is - adopted only when none was pinned, because a pinned client refuses rather than - downgrades. -- **A server-named origin is untrusted.** It passes `client.content-allowed-hosts` - before it is fetched from, and one naming a host *name* rather than an address - is skipped with **one** warning - `net::Endpoint::Parse` refuses a name on - purpose, because resolving one blocks and nothing on the fetch path may block. - -A server that names a hostile origin still cannot hand a client content that -verifies: the manifest's signature is checked against the publisher key, then a -group's length against that manifest, then every asset against its root. - -## Turning content formats off - -Two settings per format, and they are two because they are different verbs: - -| Setting | Means | -|---|---| -| `content.
` | this process will not decode, route or hand it over | -| `cdn.publish.` | this form does not enter a publication | - -`` is the extension - `gif`, `svg`, `mp4`, `png`, `glb`, `spv` - plus -`unknown`, which is every extension this build has no row for. Turning -`content.unknown` off closes the list to what the engine understands. - -```sh -./cdn --publish art/ --store cdn/ --signing-key HEX --flag cdn.publish.svg=false -./client --flag content.mp4=false -``` - -An origin refuses at **publish** time and nowhere else, and that is a fact about -an origin rather than an omission: after a publish there are only hashes, and a -hash cannot be walked back to a name. A refused file is never chunked, never -stored and never in the manifest - `cdn` says how many it refused, and `assetc` -keeps a row per source saying which form it was. - ---- - -# The editor *(v0.7)* - -```sh -just edit # a new game, one world, a baseplate -just edit --game My.agame # open one -``` - -The one program where `RunService:IsStudio()` is true. It writes a `.agame`, -which is the file the other two programs read: - -```sh -just host --game My.agame # a dedicated server hosting every world in it -just run --game My.agame # single-player, both roles in one process -``` - -### Editing a universe and a world - -Click a row in the Explorer and the Properties panel describes it. There are -three kinds of row and all three answer: - -- **the universe row** at the top: name, execution mode, maximum catch-up ticks, - bus budget per tick, channel queue limit and channels per world, with the - federated flag, world counts, fault counts, tick cost and bus traffic - read-only; -- **a world row**: `TickRate`, `IdleTickRate`, `PhysicsTickRate`, - `ReplicationTickRate`, the simulated network latency and the fault limit, with - the world's state, isolation, rendering profile and per-world statistics - read-only. A world's *name* is changed with Rename Scene in the row's own - context menu, because the universe's registry is keyed on it; -- **an instance row**: its class's properties, as before. - -**`PhysicsTickRate` is the one to reach for on a world that cannot keep up.** -Zero follows the tick rate; anything lower runs the solver every few ticks while -scripts, signals and rendering keep the tick rate. A climbing `Dropped Ticks` in -the same panel is what says a world needs it. - -### Options - -| Option | Default | What it does | -|---|---|---| -| `--verbose` | off | log at trace level | -| `--force-serial-compute` | off | run parallel dispatches on one thread | -| `--game PATH` | - | open a game file at startup | -| `--rojo PATH` | `$ATOMIC_ROJO_PROJECT` | sync a Rojo project or universe once the scene exists | -| `--config-root DIR` | user config folder | keep this run's preferences, keybinds and layout in `DIR` | -| `--width`, `--height` | 1600×900 | window size | -| `--scale FACTOR` | 1.0 | multiplies every font and padding | -| `--tick-rate HZ` | 60 | simulation rate while running | -| `--frames N` | - | exit after N frames, for a script or a screenshot | -| `--capture PATH` | - | write the viewport's world to a BMP and carry on | -| `--headless` | off | run with no window at all; needs `--frames` | -| `--run MODE` | `edit` | start in `edit`, `server` or `play` | -| `--uncapped` | off | draw with no frame rate ceiling | -| `--frames-in-flight N` | 2 | frames the CPU may queue ahead of the GPU, 1 to 3 | -| `--stats`, `--graph` | off | open the statistics or frame-graph panel | -| `--assets` | off | open the assets manager | -| `--viewports N` | 1 | open N viewport panels; `--viewport2` is the old spelling of `--viewports 2` | -| `--profile-snapshot PATH` | - | write a frame-graph snapshot on exit | -| `--idle-close SECONDS` | 300 | close an empty world after this long | -| `--mcp-port PORT` | off | open the loopback control surface | -| `--override-assets-directory DIR` | - | read staged data from here | - -**`--rojo` is how an external project is checked without driving the menu.** -Syncing is otherwise a file prompt and two clicks, which makes "does this -repository still sync" something nobody verifies. With no flag the editor reads -`ATOMIC_ROJO_PROJECT`, so a shell that works on one game can carry it - the flag -is for one run and the variable is for a day, and nothing writes the variable -back. A path ending `.universe.json` syncs every world it names; anything else -is read as one project into the scene that is open. - -```sh -ATOMIC_ROJO_PROJECT=~/Documents/GitHub/raceapet/default.project.json \ - ./.cache/build/dev/studio/studio --headless --frames 3 -# synced 1356 instances, 1082 scripts from RaceAPet -``` - -The count is the check. It should equal the number of `.luau`, `.lua` and -`.json` files the project's `$path`s actually reach - a package whose -`default.project.json` maps `lib` contributes `lib`, and nothing else it was -published with. - -**`submit` is where the GPU is paid for.** The passes above it only *record* -commands; `SDL_SubmitGPUCommandBuffer` is where the driver gets the work. Studio -defaults to two frames in flight so the CPU can record the next frame while the -GPU finishes the previous one. Setting `--frames-in-flight 1` makes submit block -for the previous frame and removes the extra frame of input latency. Measured on -the four-world demo: p99 6.9 ms at one, 6.1 ms at two, and the same 0.21 ms -median either way. - -**The editor is not paced by the display.** It starts with vertical sync off and -a 120 fps ceiling, because sync puts a whole refresh - 16.7 ms on a 60 Hz panel, -before the compositor takes its turn - between the mouse and the viewport, and -that delay is what dragging something feels like. The ceiling is what stops the -other extreme: a still scene redrawn nine hundred times a second is a laptop -with its fans up for one picture. - -Both are on the Preferences page under **Frames**, live, so a viewport that tears -is one click from paced and the ceiling is a slider. `--uncapped` removes the -ceiling for a run, which is what to pass when the number being read is the -frame's own cost - otherwise the sleep padding each frame out to 8.3 ms is -measured as that cost. On a device with no immediate present mode the editor says -so and stays paced by the display. - -### The Demo tab *(v0.14)* - -The ribbon's last tab, and its one entry is **Demo Nodes** - a typed node graph -with live evaluation. It changes nothing in the scene; it is there to be looked -at, and to be the place the two node systems `ROADMAP.md` wants get designed -against rather than invented twice. - -``` -drag port → port connect. Types must match, or it says why it refused -drag a wired input picks the link up and moves it -drag port → empty a palette of what would fit there -right click the palette anywhere -middle or alt-drag pan · wheel zooms to the cursor -Del · F delete the selection · fit -``` - -What it computes is terrain. **Noise, Ridged, Domain Warp, Terrace, Slope, -Threshold and Combine** are the sync half - they run inside the frame, so a -slider drag re-runs the chain between frames. **Colourise** turns a height field -into an actual picture, which is what the thumbnails on the nodes are drawing. - -**Erode** and **Staged Task** are the async half. Erosion is genuinely slow at -256², so it runs on a worker and the node grows a progress bar and the stage it -is on; the frame keeps drawing. Two staged tasks in two branches run at once -because the evaluator starts every node whose inputs are ready - there is no -scheduler deciding it, readiness *is* the schedule. - -Three properties worth knowing while using it: - -- **A result is cached against a hash** of the node's parameters and its inputs' - hashes, so one slider recomputes exactly the sub-tree below it. Dragging a - node recomputes nothing: position is not in the hash. -- **A node whose input is still being computed waits** rather than running with - the unconnected fallback, which would cache a picture of nothing under a hash - that claims otherwise. -- **Live** follows every edit; turn it off and drive it with **Build** when the - graph has a six-second task in it. - -The inspector down the right-hand side shows the selected node's picture large - -the same texture the node draws, so it costs one conversion - with its stages and -whatever number it produced. - -### Driving it with no display - -```sh -just studio-smoke # loads, plays, renders, writes a capture -just edit --headless --frames 12 --run play --capture shot.bmp -``` - -For window, swapchain, docking and mouse tests without touching the live -desktop or Studio configuration, run the whole editor on a private X display: - -```sh -scripts/run-studio-virtual.sh --frames 120 --run play -``` - -**`--headless` is a renderer with no window rather than a hidden one.** There is -no swapchain, nothing is presented, and the overlay and editor chrome do not -draw - but the game loads, the panels lay themselves out, `--run play` starts the -scripts, the worlds tick and the world is drawn into an offscreen target that -`--capture` writes out. A hidden window would still own a swapchain, and whether -one can be acquired for a window nobody can see is a per-platform answer nobody -should have to know. - -That is what makes the editor checkable by a build server, by a golden-image -comparison, or by something driving it that is not a person - none of which -should depend on a display being free. - -`--capture` works with a window too, and captures the world rather than the -whole editor: the chrome is drawn onto the swapchain, and SDL does not promise -that is readable. What it answers is "did the scene render", which is the -question a renderer is asked. - -### The file it writes - -A `.agame` is one XML document holding the universe, every world, every -instance and every script's text. It is meant to be read: - -```xml - - - - - - - - 128, 1, 128 - - - -``` - -Only properties that differ from their class default are written, which is what -keeps a scene of a thousand parts a file you can read a diff of. A single world -exports on its own as a `.aworld` - File ▸ Export Active World - and imports -back into any universe. - -**It is not a snapshot and does not replace one.** `--record` still writes the -binary format, which carries a *running* universe including tick counters and -bus state and is same-build only. A game file is content: it survives an engine -version, and that is what it is for. - ---- - -# Running a script file *(v0.6)* - -The client and server can load a scene script, and the unified harness can load -one for its authority. A game is a script, not a compiled artefact; the studio -opens an authored game file: - -```sh -just run --script .cache/build/dev/assets/examples/scripts/Rings.luau -server --game My.agame --tick-rate 60 -``` - -The client and server use explicit options because neither program treats a -bare positional path as a script: - -```sh -just run --script path/to/game.luau -server --game path/to/game.agame -``` - -`.ts` is TypeScript/JavaScript and `.luau` is Luau; which one a file is comes -from its extension, and a game may mix them. TypeScript is transpiled to staged -JavaScript during the build when the pinned compiler is available, with a -`.js.map` beside each one - **so a script that throws names the line in the -`.ts` you wrote** rather than a line in the generated file. Stripping types -shifts everything below a multi-line annotation upward, so the two rarely agree. -`mono.engine/examples/assets/scripts/` holds the script demos, each written twice - once in each -language, doing the same thing - so that the binding surface is exercised from -both. - -### Opening an example in the studio - -Every staged `.luau` scene is offered by the studio in three places, all of which -already offer New World: - -- the **World** menu, as `New Scene from Example`; -- the universe's right-click menu at the top of the **Explorer**; -- the **Example...** button in the **Worlds** panel, beside New and Import. - -Picking one adds a world named after the file and puts the scene in it as a -`Script` in `ServerScriptService`, so nothing is built until Play runs it and -Stop takes it away again. The list walks the staged directory rather than a -hand-kept table, so a scene added to `mono.engine/examples/assets/scripts/` is there after a -build. - -It is refused while anything is running, for the reason New World is: the -snapshot Stop restores was taken before the run began, so a world added during -Play would vanish on Stop. - -### The stress scenes *(v0.17)* - -Three scenes exist to be measured rather than looked at. All three name their -knobs at the top of the file and say what each one costs. - -| scene | what it loads | run it with | -| --- | --- | --- | -| `StressParticles.luau` | fourteen bays covering every authored `ParticleEmitter` property, then 1,024 parts carrying five emitters each - 512,000 particles | `just run --script .../StressParticles.luau --stats` | -| `StressPhysics.luau` | 100,000 unanchored blocks in a tray that tilts, so nothing ever settles | `server --game .../StressPhysics.luau --physics-tick-rate 20` | -| `StressMirrors.luau` | an ico-sphere mirror ball - 80 facets, 16 of them mirrors | `just run --script .../StressMirrors.luau` | - -Two things are worth knowing before running them rather than afterwards. - -**A client does not simulate `StressPhysics.luau`.** A client installs the -character systems and not the physics pipeline, so a scripted client world -integrates nothing: the blocks hang in the air. The studio's Play and -`server --game` are the two hosts that install it, and -`--physics-tick-rate` - or the world's `PhysicsTickRate` in the studio - is what -makes a hundred thousand bodies affordable, by solving slower than the world -ticks. Measured on `release`, 24 threads, headless at 30 Hz over 600 ticks: the -tick rate costs a 361 ms mean tick, and `--physics-tick-rate 10` costs 125 ms. -The scene's own header carries the percentiles, and the short version is that a -hundred thousand contacting bodies is past interactive either way. - -**`StressMirrors.luau` states its own bounce depth**, and the line is a guard -rather than a preference: a ball is the worst shape the automatic depth rule has, -because every pane can see most of the others and it therefore asks for one level -deeper every frame. The passes go as `panes x (panes - 1) ^ (levels - 1)`, so -sixteen panes cost 16 at one level and 3,600 at three. Compare depths with -`--surface-bounces N`, which overrides the scene. - -`dev` is `-O0` and no frame-rate number from it means anything. Build `release` -before quoting one. - -### Shared Luau libraries - -`mono.engine/examples/assets/scripts/libraries/` holds Luau *libraries* rather than scenes. Every -directory under it is staged with its structure intact and mirrored into -`ReplicatedStorage` as a tree of `ModuleScript` instances before any scene runs, -so a script finds `ReplicatedStorage.MagicCore` the way it would in a Rojo place. -`script::MountModuleTree` does the mirroring and follows Rojo's rule that -`init.luau` collapses into its own directory. - -| library | what it is | -| --- | --- | -| `MagicCore` | pure-data spells: config, compile, projectile, effect, status, presets | -| `MagicRuntime` | the part of a compiled spell this engine can draw | -| `TerrainCore` | pure-data voxel terrain: noise, height field, edits, meshing | -| `TerrainRuntime` | terrain boxes as Parts | -| `MagicTests` | `MagicCore` and `TerrainCore`'s own 183-test suite | - -`MagicCore` and `TerrainCore` came from an external Rojo project and are byte -identical to it, which is the point: they are checked by running that project's -own tests here. `MagicRuntime` and `TerrainRuntime` are this engine's, because -that is the only layer that names an instance. - -```sh -just run --script .cache/build/dev/assets/examples/scripts/Magic.luau # spells cratering terrain -just run --script .cache/build/dev/assets/examples/scripts/Libraries.luau # libraries, loaded and exercised -just run --script .cache/build/dev/assets/examples/scripts/MagicTests.luau # their tests, in this VM -``` - -**`MagicRuntime` draws everything the Roblox original draws.** A -`ParticleEmitter` per authored emitter - 42 across the five demo lanes, which -`Magic.luau` prints at startup - plus a `Trail` behind each projectile, a muzzle -`Beam` and a `PointLight`. - -It drew only a body until v0.18. The module was written when this engine had -`Part` and none of the rest, said so at the top of itself, and went on saying it -after `mono.engine/effects` landed - so the spells solved correctly, cratered -the terrain, and looked like coloured cubes. Two things had to change: the -module, and `examples::LoadScene`, which registered the 3D and 2D class trees -and not the effects one. See `lib/MagicRuntime/init.luau` for how a -`Timeline.EmitParticles` burst is spelled without a `ParticleEmitter:Emit`. - -### Autocomplete while you write one - -Both languages are typed against files generated from the class table, so an -editor knows what a script may name without anything being restated by hand: - -| file | what it is | checked in | -| --- | --- | --- | -| `mono.engine/script/bindings/engine.d.luau` | the Luau definitions | yes, generated | -| `mono.engine/script/bindings/engine.d.ts` | the TypeScript type root | yes, generated | -| `.luaurc` | strict by default, and the lints | yes | -| `luau-lsp.json` | points the language server at the definitions | yes | -| `tsconfig.json` | lists the type root; `types: []`, no DOM | yes | -| `package.json` | pins the exact `tsc` the check runs | yes | -| `.vscode/settings.json` | the same luau-lsp keys, for VS Code | **no** - `.vscode/` is gitignored | - -**Nothing needs installing.** The language server is vendored at -`mono.vendor/luau-lsp` and built on demand: - -```sh -just luau-lsp # clones the submodule if needed, prints the binary's path -``` - -That recipe also applies `mono.vendor/patches/luau-lsp/*.patch`, and **stops -rather than building without one**. The patch lands on a copy of the submodule -under `.cache/vendor/luau-lsp`, never on `mono.vendor/luau-lsp` itself - which is -why building a language server does not leave a modified submodule in every -`git status` afterwards. There is one today: it -registers the `Enum` prefix so `local face: Enum.NormalId` resolves the way it -already does in `just typecheck`, and the file's own preamble says why it is a -patch here rather than a fork. If it ever fails to apply, upstream moved the code -it edits - the message names the file to read. - -Point your editor at that binary and at `luau-lsp.json`. `.vscode/` is -gitignored - editor configuration is personal here - so `luau-lsp.json` is the -copy that survives a fresh clone, and a VS Code `settings.json` should mirror it -rather than diverge from it. - -**One of its settings is load-bearing rather than a preference.** -`luau-lsp.fflags.enableNewSolver` must be on: the declarations use the `keyof` -and `index` type functions, which exist only in Luau's new solver, and without -it the definitions file fails to load *entirely* - every global reads as -unknown, which looks like the file is missing rather than misconfigured. - -TypeScript needs no separate setup: `tsconfig.json` lists the type root and -`package.json` pins the compiler, which `just typecheck` installs on first run. - -Both languages are checked together by `just typecheck`, which `just check` -runs - see [The script type check](#the-script-type-check) for what it catches -that `just bindings-check` does not. The declarations themselves are regenerated -by `just bindings`. **A change to either is a change to what every script can -name**, so the diff is the review. - -They do not describe the same surface everywhere, and that is deliberate: the -two VMs differ. `game:GetService("Workspace")` and `RunService:IsServer()` are -Luau's, and each file says what its own VM installs rather than what the other -one has. - -### Autocomplete in the studio's own editor - -The above is for the editor you already use. The Script Editor in the studio has -its own, and it needs no language server and no configuration: - -| key | what it does | -| --- | --- | -| `Ctrl+Space` | offer a list, whatever is under the caret | -| `.` or `:`, or two characters | offer one automatically | -| `Up` / `Down` | move through it | -| `Enter`, `Tab`, or a click | accept | -| `Escape` | dismiss | -| `Tab` with the list closed | indents, as always | - -It offers classes inside an `Instance.new` call, properties after a dot, methods -and signals after a colon, enum sets and their members, the globals of whichever -language the script's `CodeSourceContainerSelector` selected, that language's -keywords, the identifiers already in the file, and **the names of the instances -beside the script in the tree** - which is the one thing luau-lsp cannot know, -because it reads files and not a world. - -**None of that list is written down anywhere.** Classes, properties and enums -come from `ecs::Classes` and `ecs::EnumTable`; the globals and instance methods -come from `script::Runtime::Surface`, which walks the global table of a VM built -for the purpose. A global added anywhere in `mono.engine/script` is offered with -nothing else changing, and one removed stops being offered in the same commit. -The reason it is built that way rather than from a list is in -`script/Vocabulary.hpp`, and it is two bugs this engine has already shipped. - -It does **not** infer types. A local from `Instance.new("Part")` resolves, -because the class is written on the line; one from `FindFirstChild` gets the -union of every scriptable property instead - a longer list, never a wrong one. -`D00114` carries what narrowing it would take and why the obvious answer only -helps one of the two languages. - -The list shows the typed prefix highlighted in each row and, under it, what -kind of thing the chosen row is - for a keyword, its one-line doc. - -**Resting the mouse on a word** shows the same information as a tooltip: a -keyword's doc line, what a global is, an enum set, a class and its parent, a -sibling instance, a narrowed local's class, or a property's type and declaring -class. It stays quiet over strings, comments, numbers, empty space and -anything the editor does not know, and it never appears while the completion -list is up. - -**The minimap** on the code field's right is a shrunken impression of the -whole file - bright stripes for identifiers, dim for punctuation, since the -field itself does no syntax tinting - with the visible region marked. Click or -drag it to scroll. - -### What happens today - -The Luau runtime, QuickJS runtime, bindings and game-file reader are active. -`--script` loads a scene script, and `--game` loads an authored `.agame` file. -The file extension selects Luau or JavaScript for script files; TypeScript -sources are transpiled to staged `.js` files when the pinned TypeScript compiler -is available. `atomic` is still not a target or a recipe. - -The example sources are real scenes, not placeholders. The default client scene -is `Rings.luau`; staged script demos live under -`.cache/build//assets/examples/scripts/` and authored worlds under -`.cache/build//assets/examples/worlds/` after a build. A missing TypeScript -compiler skips JavaScript twins and leaves Luau scenes available. - ---- - -# The client - -```sh -just run # dev preset, no panels -just run --stats --graph # both debug panels open -just demo # the same, spelled shorter -scripts/demos/run-demo.sh # the same again, without just -./.cache/build/dev/client/client # directly, no just and no build -``` - -`just run` passes everything after it straight through, and builds the client -first. - -### One script per scene - -`scripts/demos/` holds a `run-.sh` and a `run-.bat` for every -example, so seeing one is a command rather than a path to look up: - -| Script | Scene | -|---|---| -| `run-demo` | the default scripted scene - `examples/scripts/Rings.luau` | -| `run-rings` | orbiting, spinning parts - the loading path | -| `run-skygrid` | a lattice of blocks in empty sky | -| `run-terrain` | 16384² voxel terrain, streamed around a camera | -| `run-magic` | spells fired at terrain they dig holes in | -| `run-magic-tests` | the ported libraries' 183 tests, run here | -| `run-libraries` | `MagicCore` and `TerrainCore`, loaded and exercised | -| `run-interface` | a `ScreenGui` built entirely from a script | -| `run-mirrors` | one room of mirrors, each with a different effect - the rendering path | -| `run-mirrors-4-worlds` | four worlds composited into one frame | -| `run-portals` | a square building with three rooms in it, and a lap that closes early | -| `run-non-euclidean` | six exhibits, each a room that lies about its own size | -| `run-meshes` | imported meshes and textures. Wants `--cdn` | -| `run-mesh-grid` | bakes and publishes art, then draws it | -| `run-local-server` | one server and several clients, all on this machine | -| `run-local-server` + `SCENE=PlayerList.luau` | the same, with a live player list in every client | - -### Somebody to be *(v0.14)* - -```sh -scripts/demos/run-local-server.sh # a server and two clients -scripts/demos/run-local-server.sh 4 # four clients instead -PORT=9100 scripts/demos/run-local-server.sh # a different port -SCENE=Slide.luau scripts/demos/run-local-server.sh -``` - -**A server hosting `Playground.luau`, and a client window per player.** Each one -is admitted, given a blocky character on the spawn pad and told which player it -is; WASD walks it, Space jumps, the right mouse button turns the camera. Every -client sees every other character move, because the movement happens once - on -the server - and what crosses is the intent going up and the transform coming -down. - -**This is not `mono.unified_tests`, and the difference is the reason to -run it.** That harness cuts `net` out of the middle to prove the -serialise/deserialise seam; this puts the socket, the handshake, the cipher and -the bandwidth budget back, and adds the thing neither of them had - more than -one player. `--net` is on by default in the script because the F4 panel is where -this demo is read from: two characters that do not move have three explanations, -and the panel separates them. - -### Who is in the game *(v0.15)* - -```sh -SCENE=PlayerList.luau scripts/demos/run-local-server.sh 4 -``` - -**The same four clients, and a panel in each naming all four.** A name appears -when a client starts and vanishes when one is closed, and each client's own row -is tinted - with everybody called `Player1` through `Player4` there is otherwise -nothing on screen saying which of them you are. - -**The rows are written into each player's own `PlayerGui` and not into -`StarterGui`.** A `StarterGui` is a template that is cloned when a character -spawns, so a row added after somebody joined never reaches the copy they are -looking at; a `PlayerGui` is live *and* private on the wire, and it is the only -place both are true. Watching one client's panel while another closes is the -demonstration. - -**TAB holds the panel open where there is a keyboard, and there is not one on a -dedicated server** - so in this arrangement the panels stay shown. Press Play in -the studio, or run `./client --script PlayerList.luau`, to see the toggle -itself. Holding a key is a fact about a *viewer* and closing that gap needs a -script running in the replica, which `docs/DEFERRED.md` `D00122` carries. - -**The same arrangement without a second program is the studio.** Press Play and -the editor hosts both halves in its own viewports: a server view and a client -view, with a character in the client one. `Spawn Player` and `Remove Player` on -the ribbon act on the viewport you are in, so a Run becomes a Play one client at -a time, and two clients is what turns "the replica disagrees with the server" -into "these two clients disagree". A new game opens with a **Playground** and an -**Arena**, and a pad in each that teleports you to the other. - -**Live Instances** is where those two halves are listed, and it opens itself when -a run starts. A row per server and a row per client, each with the counts that -say whether a client is keeping up, and a `View` on each that is the way back to -that instance's viewport - closing a view no longer loses it. `Stop` on a client -row removes that client, which is also what the ribbon's Stop does while you are -looking at one, and `+ Player` on a server row admits another. A client view is -listed here rather than among the scenes in the Worlds panel: it exists only -between Play and Stop and there is nothing about it to author. - -### Things fall *(v0.13)* - -A new game gained a fourth world at v0.13, and it is **Slide** - a curved -ramp with blocks that spawn at the top, slide down, launch off the lip and are -destroyed ten seconds later. It is the first world this engine ever simulated. - -**The physics module was complete and connected to nothing.** Integrate, broad -phase, narrow phase and solver had suites, benchmarks and no consumer: -`RegisterPhysicsSystems` was called from `physics/tests/` and nowhere else. Every -world that shipped was anchored throughout, which is why nobody noticed - an -anchored part carries no rigid body at all, so a scene of anchored geometry -integrates nothing and solves nothing. - -Two things were missing, and they are separate features: - -| | | -|---|---| -| the pipeline | `PreparePhysicsWorld` and `RegisterPhysicsSystems`, per world | -| the weight | `scene::PrepareGravity` and `RegisterGravitySystem` | - -**`Engine::physics` deliberately has no gravity and should not gain one.** A -top-down game should not have to switch one off, so `RigidBody` carries no -gravity scale and the pipeline has no gravity step - weight is a rule the world -holds. `scene::Gravity` is that rule: a resource, so a world under water or on -the moon authors a different vector, defaulting to 9.81 m/s² down. Earth's, in -metres, because this engine measures parts in metres - Roblox's 196.2 is the same -acceleration in studs and copying it here would make everything fall twenty times -too fast. - -The editor installs both on every world it makes. **It costs an anchored world -nothing**, which is why it can be on everywhere rather than behind a switch -nobody would find. - -For a script the whole of it is one line: - -```lua -part.Anchored = false -- and it has a rigid body, and it falls -``` - -### Swapping a mesh's texture *(v0.13)* - -A `MeshPart` names two things and they are independent: - -```lua -part.MeshId = "characters/hero.amesh" -part.TextureID = "skins/hero-winter.atex" -``` - -**Setting only `MeshId` still works** - the part wears whatever each of its -submeshes recorded at bake time, which is how a character with six sheets loads -without a script knowing any of them. What it does not give you is a handle: the -sheet names live *inside* the mesh file, so there is nothing to read and nothing -to put back. - -`ContentService:GetMeshTextures(mesh)` is that handle: - -```lua -local worn = ContentService:GetMeshTextures("characters/hero.amesh") -part.TextureID = worn[1] -- the same picture, said out loud -part.TextureID = "skins/summer.atex" -- a different outfit -``` - -It answers in **submesh order, unsorted, duplicates kept** - unlike every other -list that service hands out. Which run wears which is a fact, and a character -with twenty submeshes sharing four sheets is four names repeated. An untextured -run is an empty string in its own slot rather than a hole, so the index keeps -meaning "submesh number". A built-in wears nothing and answers an empty table, -as does a mesh this world has not been told about. - -**`TextureID` overrides every run at once** - Roblox's rule and this one's - so a -twenty-submesh character given one sheet wears that sheet all over. That is the -thing to know before reaching for it on an imported model. - -`run-mesh-grid` shows both halves: each cell names its own sheet explicitly when -it has exactly one, and a row of identical cubes below wears the characters' -sheets, so the only difference between them is a string. - -### What a mirror can show *(v0.13)* - -A `SurfaceCamera` has an `Effect`, and `run-mirrors` gives each of its four walls -a different one: - -| `Enum.SurfaceEffect` | What it looks like | -|---|---| -| `None` | the reflection as rendered | -| `NightVision` | an image intensifier - everything to green, lifted, grained, vignetted | -| `Thermal` | a heat map, black through blue, magenta, red and yellow to white | -| `Cctv` | grey, scanlined, with a bright band rolling down it | -| `Swirl` | the image twisted about its own centre, turning slowly | - -```lua -local reflection = Instance.new("SurfaceCamera") -reflection.Face = Enum.NormalId.Back -reflection.Effect = Enum.SurfaceEffect.Thermal -reflection.Parent = pane -``` - -**A grade on the way out, not a second render.** The surface pass draws the world -exactly as it would have whatever the effect says; the effect is applied in -`opaque.frag` where the pane samples the texture. So a graded wall costs the same -as an ungraded one - no extra target, no extra pipeline, no extra bind - and -switching one at runtime redraws nothing. - -That is also why a reflection of a reflection is graded once. The texture holds -an ungraded picture and only the pane showing it grades, so standing between the -thermal wall and the swirl gives you a corridor carrying both, each applied by -the wall it belongs to rather than compounding down the recursion. - -**Thermal reads luminance as temperature**, which is a lie an engine with no -thermal model cannot avoid. It looks right because bright things in a lit scene -usually are the hot ones, and `scene::SurfaceEffect` says so rather than implying -otherwise. - -**A closed list rather than a shader name**, and that is a deliberate limit. This -pipeline has one fragment program for opaque geometry; a mirror naming an -arbitrary program would need a pipeline per program, a compilation path, and an -answer for what happens when the file is missing on somebody else's machine - -which is the render graph `ROADMAP.md` puts behind a prototype project, not a -field. Every effect here is a handful of instructions on the fragment that -samples an image somebody already rendered. - -### Holes that lead somewhere else *(v0.14)* - -A `Portal` is a `SurfaceCamera` with one more property on it, and that property -is the whole feature: - -```lua -local hole = Instance.new("Portal") -hole.Face = Enum.NormalId.Back -hole.Destination = someOtherWall -- and the wall is now a hole -hole.Parent = pane -``` - -A mirror puts its camera where the eye would be reflected through the pane's own -plane. A portal puts it through `destination · half-turn · source⁻¹` instead. -Everything after that is the mirror's path unchanged - the same surface pass, the -same projected sampling in `opaque.frag`, the same per-surface `TagFilter`, the -same one-frame-old texture - so a hole costs a mirror and nothing else. - -**Nothing constrains the two panes to describe one space**, and that is the -non-Euclidean part. A destination turned, moved, or placed three hundred units -away is still a legal pair, so a room can be bigger on the inside and a corridor -can turn through more than four right angles. `run-portals` is a square building -with four quarters and three rooms in it: hall, library and garden clockwise -round the middle, and one pair of holes joining the garden's west wall to the -hall's south wall, where the fourth room would have been. The two panes are -perpendicular, so the pair carries a quarter turn - walk the loop and you make -three right turns and arrive where you started, facing the way you set off. The -middle of that building is a cone point with ninety degrees missing. -`NON-EUCLIDEAN.md` is the investigation behind it. - -**`Face` is resolved on the destination too, and it is the one rule to know.** -The far frame is built by applying the *portal's own* `Face` to the destination's -transform, so the destination must be a part whose matching face points at the -space the hole should show. Aim it at a wall whose matching face points the other -way and nothing complains - the pane renders, and it shows the empty space behind -that wall. For unrotated rooms that means the wall on the same side of the far -room; rotating the destination is the general answer. - -**A destination that is missing, cleared or deleted falls back to a mirror** -rather than to a blank pane. A surface that stopped reflecting reads as something -to fix; a pane that vanished reads as a broken renderer. - -**You can walk through these.** `scene::CrossPortals` maps a body - and both -halves of its `Motion`, and the camera's yaw when the body is the one the camera -follows - through the same product the picture goes through, and `scene::OpenPortals` -takes the pane's collider out of the solver's way so a walker reaches it at all. -Press Play in the studio on `Portals-1-world.luau`, or host it with -`scripts/demos/run-local-server.sh`; the standalone client has no character and -walks the lap on rails instead. What is left of `docs/retired/DEFERRED.md` D00112 is the -seam on the frame you cross, which needs the portal chain rendered inside the -frame, deepest first. - -**`Bidirectional` off makes it a one-way door.** By default a mouth may be -entered from either side and the pair's map is its own inverse - walk through -and walk back and you are where you started. Turn it off and only a body that -enters *in front* crosses, where in front is the side the face's normal points -at: the side the pane shows its image on. That is an entrance you cannot walk -back out of, or an exit you cannot be pulled back into. Nothing else changes - -the pane still draws from both sides, still cuts a body standing in it and still -lights the room behind it, because a mouth that vanished when you walked round -it would read as a rendering fault rather than as a rule. - -**A pane must be one part and it should be white.** One part because the -rectangle a surface camera is fitted to and the rectangle `CrossPortals` tests -against is that part's face - a hole built out of several is several holes -against a budget of sixteen. White because `opaque.frag` tints the projected -image by the pane's own colour, so a grey pane shows the far room dimmed, which -reads as a lighting bug in a room that is lit correctly. - -**`NonEuclidean.luau` is the catalogue rather than the mechanism.** Six exhibits -in a row, twelve holes, and the camera sweeps past them: a tunnel shorter inside -than out and one longer inside than out, a house with four doors onto three -rooms, a pillar with a different room behind each side, a hill whose bottom -opens onto its own top, and a cell that holds four times the volume it occupies. -Every one of them is the same pair of panes with the destination moved - no new -engine code, which is the point. The one shape it *cannot* express is the tunnel -that changes your scale, because the map through a portal is rigid; that is -filed with D00112 as well. - -```sh -scripts/demos/run-demo.sh Terrain --stats # uncapped, held at 165 fps -scripts/demos/run-demo.sh Terrain --stats --graph # extra flags reach the client -MAX_FPS=60 scripts/demos/run-demo.sh Terrain --stats # hold a different rate -MAX_FPS=0 scripts/demos/run-demo.sh Terrain --stats # no limit at all -PRESET=release scripts/demos/run-demo.sh Terrain --stats # any preset but `server` -scripts\demos\run-demo.bat Terrain --stats # Windows, same everything -``` - -**`--uncapped --max-fps 165` is one decision rather than two**, and every script -here makes it. `--uncapped` alone turns off the vblank wait and lets the loop -run as fast as the GPU allows - several hundred frames a second of heat for a -display that shows a fraction of them. The vblank wait alone paces to whatever -the display reports, which is not comparable between two machines and is not -what a variable-refresh monitor does. So: do not wait for the display, and do -not run away from it either. - -The pair is what `--max-fps` is for, and it does nothing without `--uncapped` - -with the wait on, the display is already the limiter and a second one fighting -it produces judder rather than a lower number. - -**Running a demo without them is what a bottleneck looks like when there is -none.** Bare, `EditableMesh.luau` reports a mean frame of 7.8 ms with a 34 ms -tail and reads as choking; with the pair it is 1.3 ms, and uncapped with no -ceiling at all it is 0.26 ms - a quarter of a millisecond of actual work behind -eight of waiting. The whole difference is the `submit` span, which is the CPU -sitting on the vblank, and it is worst on a scene that is *not* busy: with only -one frame in flight there is nothing queued to cover a missed interval, so -missing by a hair costs a whole one. - -`--frames-in-flight` is the other end of that and is **not** the cure - measured -on this machine the tail grew with the queue rather than shrank, 35 ms at one, -52 at two, 69 at three, because a deeper queue means a longer stall when a -present is late. It is here for parity with the studio, which has had it since -v0.14, and because it is the first knob anybody reaches for. Reach for -`--uncapped` instead. - -Everything shared lives in `_common.sh` and `_common.bat`; a scene script is a -header, a filename and its own flags. They call CMake rather than `just`, so the -two halves cannot drift apart, and they resolve the repository from their own -path - run them from anywhere. The `.bat` wants a Developer Command Prompt, -because it builds before it runs and a plain `cmd` window has no compiler in it; -`scripts\build-windows.bat` first leaves nothing for it to compile, and -[On Windows](#on-windows) is the reason either is necessary. - -### Options - -``` ---stats Open the F3 statistics panel at startup ---net Open the F4 network panel (needs --connect) ---graph Open the F5 frame graph at startup ---uncapped Present without waiting for vblank ---max-fps N Hold this frame rate; needs --uncapped ---frames-in-flight N Frames the CPU may queue ahead of the GPU, 1 to 3 ---verbose Log at trace level ---force-serial-compute Run parallel dispatches on one thread ---worlds N Worlds to simulate and composite (default 1) ---view-spacing UNITS World units between composited views (default 40) ---entities N Cubes in the demo scene, per world (default 2048) ---tick-rate HZ Simulation ticks per second (default 60) ---frames N Exit after N presented frames ---width PX Window width (default 1280) ---height PX Window height (default 720) ---profiler-tab NAME frame, categories, systems, counters or heap ---script PATH Luau or JavaScript scene to run at startup ---game PATH Game file to play single-player (.agame) ---connect HOST:PORT Replicate a world from this server ---server-key HEX Pin the server identity ---cdn SOURCE Content source; repeatable, `dir:PATH` allowed ---content-cache DIR Keep verified content between runs ---publisher-key HEX Pin the content publisher ---sound PATH Loop a .wav or .mp3 ---capture PATH Write a BMP near the end; needs --frames ---capture-sequence DIR Write each frame as BMP + camera JSON; needs --frames ---enable-profiler SECONDS Wait for a Tracy profiler before starting ---profile-seconds SECONDS Run for this long, then exit ---profile-snapshot PATH Write a frame-graph snapshot when the run ends ---heap-report PATH Write a heap profile when the run ends ---heap-growth-limit BYTES_PER_S Exit 3 if a tag's live bytes climb faster than this ---heap-warmup SECONDS Leave this much of the start out of the growth fit ---override-assets-directory DIR Read shaders and data from here ---help Show this text -``` - -Naming a `--profiler-tab` opens the graph, and `--profile-seconds` turns -collection on - asking to see something is not a separate flag from showing it. -`--profile-snapshot` does the same and then writes the window out, which is how -a profile gets read rather than looked at: the overlay is a picture and the -snapshot is a table with a mean, a median and a worst reading per span. - -**Pair it with `--force-serial-compute` or the interesting spans are missing.** -A world ticks on a pinned worker and a span opened off the frame's owning -thread is refused, so `worlds (pinned workers)` arrives as one bar with the -whole tick inside it and nothing underneath. Serial makes the frame slower on -purpose and complete. - -**And read the table as per occurrence, not per frame.** A run that is dropping -ticks runs several of them per frame, and each one opens its own `ecs.systems`; -the column is the worst *single* reading, so the parent can be several times -the child without a millisecond being unaccounted for. - -`--game` plays a `.agame` written by the editor: every world in it is -simulated, its scripts run with both roles true, and there is no socket and no -server library involved - single-player is the format and a VM, not a server -hosted in this process. Given both `--game` and `--script`, the game file wins -and the client says so rather than choosing quietly. - -For a supervised portal image producer, the driver launches `client` with -`--game PATH --headless --frames N --presentation-world NAME ---presentation-session SESSION` and an inherited `ProcessChannel`. -The session must be positive and fresh for each host lifetime. The selected -world must exist in the game. Only that world runs locally; the other world -names remain remote routes. -For a live producer, replace `--game PATH` with -`--connect HOST:PORT --server-key PUBLIC_KEY`. This renders an authenticated -replica under `--presentation-world NAME`, without a local demo, fresh player, -movement messages or audio device. It advertises only after the snapshot joins, -and withdraws the endpoint if the source session ends. Game-file and live-source -arguments are mutually exclusive. Trusted driver directories supply remote world -names that were not part of the replica. -It advertises its image endpoint, accepts trusted driver route updates and -serves HDR requests between ticks. Stop or channel disconnect ends the loop. -These flags require a supervising process, so a standalone shell invocation -without the inherited channel fails startup. -Supervised producers may use `--frames -1`: their driver link and replication -source bound their lifetime. Ordinary headless clients still need a frame budget. - -A listening Server can own this launch with `--presentation-program PATH`, where -PATH is the staged Client executable. The option also passes to remote world -hosts. Each listening host launches one live producer, pins its server identity, -grants its temporary client identity through restricted admission, and advertises -the delegated image/topology endpoints through its own presentation directory. -The producer consumes one replication connection slot. Shutdown or producer -failure withdraws its endpoints; there is no automatic producer restart yet. -Omitting the option keeps the Server deployment independent of a graphics stack. -Supervised hosts load saved projects by their granted world names; ungranted -worlds stay remote and run no local scripts. - -Ordinary connected Clients discover image/topology routes through their existing -authenticated play connection. Server grants private return channels per player -and withdraws them on disconnect. Control/session endpoints stay out of the player -presentation directory. No additional Client flag is needed. Presentation streams -are bounded to 64 frames and 32 MiB per direction, with at most 16 player streams -per Server. A successor connection replaces the old Client route directory. -An exited or disconnected image producer is reaped and restarted with a fresh -identity and session. Its old endpoints are withdrawn before retrying. Repeated -failures back off from one second to 30 seconds; 30 seconds connected resets that -delay. Server shutdown cancels pending retries. -Once joined, Client displays the replica's own camera and unshifted draw rows; -`--view-spacing` remains for composing local worlds before a play connection joins. -Portal surfaces, lighting and image requests follow the joined world through -successor adoption. The `[portal-successor]` process test checks discovery and a -decoded seam-image request alongside the six session handoff outcomes. It does -not compare the pixels of a complete physical crossing. - -Build `client` and `test_client`, then run -`.cache/build/dev/tests/test_client '[presentation-host]'` for the actual -process-channel GPU check. It covers saved and live worlds, changed lighting -pixels, source-session loss and driver shutdown. It uses an isolated configuration -and game under the build's tests directory. -Build `server` too and run `test_client '[server-presentation-host]'` for the -Server-owned launch and relay check. It covers restricted admission, seam and eye -images, a saved project with an ungranted world, Stop and driver disconnect. -The player-connection cases discover routes, receive topology and a fragmented -128 KiB image over authenticated UDP, and recover after a missing-endpoint request. -The consumer in this fixture is a CPU Connector; it does not verify a complete -standalone Client walk through the portal. -On POSIX, the player/seam case also expires its first producer, observes endpoint -withdrawal and receives another image from its replacement over the same player -connection. A retired-receipt request must not close that connection. The Windows -case does not inject this producer lifetime limit. - -Run `test_client '[portal-product-walk]'` for the combined physical round trip. -It uses the real Client, a listening Server, its supervised destination and both -image producers. SDL keyboard events drive entry and return; the test requires -both Client session adoptions. Its saved game runs both worlds at 30 Hz and then -60 Hz against the listening driver's 30 Hz cadence, with both trailing and -scroll-selected first-person cameras. Replicated LocalScripts sample the local -character's Humanoid camera subject on Heartbeat before entry, after adoption -and after return. Each stage checks zoom while stationary before resuming movement; -a moving predicted camera and the delayed authoritative body are different samples. -Missing services and retired characters are outside this sample window. -When trace logging is compiled in, the fixture checks actual move submissions -for increasing ticks in each connection, including updates between presentations. -Right-button mouse motion must also change the observed camera direction during -both legs. Mouse events follow captured frames, including the missing-rig gap; -the accumulated control yaw must not reset at adoption. Each camera/rate case -runs with automatic follow and with a LocalScript explicitly assigning the -Humanoid to `CameraSubject`. Each combination runs both a stop-at-adoption case -and a case holding its movement key for 12 destination submissions, for 16 -scenarios total. Held-key captures add `-held` before `-frames` and require moving -native prediction on both legs. Capture metadata includes `subject_automatic` so -the explicit case cannot silently exercise automatic follow instead. Only this -property opts into runtime writes on a live predicted camera; authority-owned -cameras and ordinary replica properties remain protected. Each case records 600 -frames at a 60 Hz presentation limit, checking -every BMP and its matching camera metadata. Every frame after the initial -Humanoid binding must contain visible scene pixels. The fixture's default camera -far plane must survive binding and both handoffs. -Every foreign-eye frame must have an image, and every ready whole-eye image must -show the fixture's floor pixel, catching missing replies and images bound to a -different world or draw slot. The final eye -must return to `server.world`. Source-world portal-surface continuity remains a -separate check. -The 128 x 128 sequences are at -`tests/portal-client-walk-{30,60}-{first,third}-frames/` under the build directory. -Explicit-subject sequences add `-explicit` before `-frames`. -Capture metadata records `submitted_move_tick`, `replication_applied_tick` and -`unconfirmed_inputs`. `predicted_root` remains the immediately reconciled replay -baseline; `presented_predicted_root` is the shared fractional body/camera pose. -Small positional corrections blend out over 100 ms of presentation time. -Larger ones use at most half walking speed and settle within one second; -corrections beyond that bound snap to authority. Remaining offset/time are -recorded separately. The held movement gate measures -the displayed pose. Authority, replay coverage and input acknowledgements are -never delayed by this presentation correction. Its vector maps through the -portal on adoption; stopped movement still settles, and unchanged authority -poses do not restart the correction timer. Input submissions must keep advancing through Proceed and -source retirement; the client's input clock is separate from the server's world -clock. Protocol 12 carries explicit consumed-input acknowledgements, so Client -and Server must be rebuilt together. -The product Client keeps submitted input ticks monotonic across adoption. -`input_local_epoch` and `input_sequence_epoch` show how the current replica's -clock maps onto that timeline; the replica's own `tick` is unchanged. The walk -checks increasing submissions across connections as well as within each one. -Portal host movement uses the PPT5 bus envelope and carries the originating -client input stamp through control assignment and acknowledgement. All portal -hosts must use the same build. `AcknowledgedInputTick` in a transfer receipt -confirms destination control assignment; the separate optional `Motion` sample -contains a completed destination tick, input stamp, root pose and prediction -movement state. The sample is captured after physics and animation and is decoded -atomically. Motion samples also carry `SimulationSeconds`, the completed -world clock copied with the pose, independently of the acknowledged input stamp. -The shared motion codec has grown by eight bytes; rebuild all Clients and -Servers together. Held and native replay use this clock to keep acknowledged input duration -separate from integrated world time. The mapping survives adoption. When authority advances beyond all recorded input time, reconciliation accepts -its completed pose and rebases the uncovered interval onto that pose. It does -not wait indefinitely for a slow client clock. Unacknowledged control and jump -edges remain active even when their integration interval is already covered. -The authenticated source session forwards newer completed samples -under the accepted transfer claim. `portal_handoff.completed_motion` records -those accepted by the client, and the product walk requires them in both -directions. Pending handoffs replay retained submitted moves against these -samples using each move's recorded prediction duration. `portal_input_history` -reports retained count, coverage, last submission, applied sample ticks and -discarded inputs. `prediction_authority_world` identifies the destination when -its sample supplies the held prediction baseline. Run -`test_client '[portal-product-camera-clear]'` for four offscreen round trips -with a LocalScript clearing CameraSubject during source retirement, then an R -key restoring Humanoid follow after adoption. It checks the cleared pose across -the switch and completes the return. -Run `test_client '[portal-product-image-handoff]'` for the 30/60 Hz third-person -fixed-eye adoption checks. A blue destination floor distinguishes the far side -from the orange source floor; the check requires blue pixels to survive the -local-to-remote image switch. Keep representative before/after captures when -inspecting a failure, and remove redundant image conversions after review. This -check does not prove character appearance parity or absence of black frames -while the eye itself crosses the portal. -Run `test_client '[portal-input-history]'` for scaled-seam replay, history coverage -and snapshot lifetime checks. Client adoption carries the mapped presentation -onto the accepted destination rig and ignores older authority updates. The walk -requires prediction on each adoption frame. Body and Humanoid-follow camera use -a shared fractional prediction pose; adoption carries its phase between local -clocks without changing replay coverage. `test_client '[prediction]'` covers -fractional body/camera movement, replay duration and scaled-seam phase continuity. Native destination correction can -still jump later; these gates do not establish seamless movement. -For control timing, run the walk with -`ATOMIC_ENGINE_LOG_LEVEL='info,portal-input=trace'`. The opt-in `portal-input` -category logs forwarded and native assignments with destination incarnation, -player, input tick, world tick, step duration, direction and root position. -In the product Server, forwarded assignment runs before that world tick's -physics, while native assignment runs after physics and first affects the next -tick. Keep the final assignment for each physics tick when comparing held -controls; several received inputs may overwrite one another before a step. -These traces do not measure release cost or prove visual continuity. -`MoveInput::StepSeconds` carries seconds per client input tick separately from -host physics duration. Product Client fills it from its simulation clock; zero -means unavailable timing for callers with no such clock. Negative and nonfinite -values are rejected. The move payload is now 22 bytes, and forwarded PPT5 moves -preserve duration through retries and same-build snapshots. Rebuild Client and -Server together. Timed native portal controls now use a 64-entry queue on the authority Player. -Its clock is anchored to the last forwarded physics assignment. Controls for the -same physics tick coalesce while preserving jump edges. Pending input can lead -by at most one second or one physics step, whichever is longer. Untimed local -control cancels the queue; invalid or changed clock rates are refused. The -completed pose reports physics-applied input while this queue is active. -`test_game '[portal-input-schedule]'` checks timing, acknowledgement, capacity, -snapshot restore, rig replacement and return transfer. The `route=scheduled` -trace is pre-physics, like forwarded assignment. Adoption now carries the receipt-validated source history into the new -connector's bounded prediction buffer, mapping movement into destination space. -The connector resends this history before newer input and retains its unsent -suffix through local budget refusal. A matching applied pose can retire inputs -already handled by the source. Run `test_replication '[input-continuation]'` for -both wire modes with tight budgets and early applied-pose retirement. Actual -network loss/reordering and reconnect stress still need broader coverage; -held-movement camera cadence and the first destination-pose correction remain -open. -Server also sends `PlayMessage::PlayerMotion`, pairing a completed own-player -pose with that connection's input frontier, using physics-applied input for the native portal queue. This uses the same bounded -motion codec but a distinct message from the old source portal receipt. Client -prediction after adoption now uses these atomic samples, retaining unconfirmed -inputs until a matching pose is applied. `native_prediction` reports received -and applied pose/input ticks; `prediction_covered_through` exposes retained-input -coverage. Samples wait for the matching root component, and cannot acknowledge -an uncovered input prefix or replace prediction with a nonfinite replay result. -`test_game '[player-motion]'` checks the -codec; `test_server 'a client is told which player*'` checks real owning-client -delivery and a native input stamp distinct from the world tick. Build target -`server` explicitly before running process tests; rebuilding `test_server` -alone does not relink the program they launch. -Shots carry their rendered authoritative fractional tick separately from the -input sequence. The 36-byte shot payload requires matching rebuilt Client and -Server binaries. Run `test_examples '[shooting]'` for the codec and -`test_server "a client's click is a shot*"` for current and historical target -views with an independent input sequence. Zero or out-of-history view time uses -present state; this check does not verify shots across a pending portal handoff. -While a handoff is pending, `portal_handoff` records Proceed, Crossed, Resume, -Ready and Commit alongside destination character count and accepted-rig presence. -An unassigned destination character is only an availability diagnostic; it is -not evidence that this player's transfer receipt has been accepted. -`retained_character` identifies the local four-instance camera hold. Its stored -pose is `retained_root`, never `authoritative_root`; `predicted_root` records the -advancing presentation pose. `prediction_authority_tick` and `predicted_velocity` -identify that prediction's baseline and current motion. During a handoff, -`destination_applied_tick` identifies the successor replica's completed update; -`through`, `through_origin` and `through_scale` map source poses into destination -coordinates for comparison with `accepted_root`. These are distinct clocks and -poses, not proof that forwarded input has advanced destination physics. -The walk requires moving retained prediction to advance when input advances. -This is a GPU check and does not yet compare every displayed camera or pixel -across the seam. -Run `test_server '[portal-product-walk]'` for the CPU saved-game round trip at -both world rates over QUIC and datagram. It requires the transferred character -rig before Commit on entry and return, with its Humanoid health preserved. -Run `test_replication '[applied-order]'` for deterministic reordered structure, -multipart acknowledgement and bounded recovery checks. `[replica-clock]` verifies -that joins and resnapshots preserve local simulation and presentation time. - -### The heap *(v0.18)* - -The `heap` view is the one tab that is not about the last frame, and that is why -it is arranged the other way up: a plot of live bytes over minutes first, then -the tag tree under it. A frame that is fast and forty megabytes heavier than the -one before it reads as healthy on every other view here. - -Tags come from the `ENGINE_PROFILE` scopes the flamegraph is already made of, so -a row on one has a row on the other. `LIVE` is a tag and everything under it; -`SELF` is that tag alone; `GROWTH` is a least-squares slope over the readings, -sampled once a second. A dash means the tag is not moving. - -**A slope alone is not a leak, which is what the `--heap-growth-limit` check is -careful about.** A world loading its content is a step, and a step has a large -slope; a leak is a line. The check requires both a rate and a *fit* - see -`HeapProfile::RUNAWAY_FIT` - and `--heap-warmup` keeps the load out of the -window altogether. - -```sh -./client --headless --frames 1000000 --profile-seconds 120 \ - --script Rings.luau --heap-report heap.txt -``` - -writes the totals, the forty heaviest tags and the growth of each. Adding -`--heap-growth-limit 8192` makes the run exit 3 and name every tag over it, -which is what `just heap-soak` is built on. - -The hooks are compiled in by `MONO_HEAP_PROFILE`, which is on in every preset -but `release` - a shipped build does not pay a 24-byte header on every -allocation. A `release` client says so rather than showing an empty tree. - -### Soaking for leaks *(v0.18)* - -```sh -just heap-soak # five scenes, a minute each -just heap-soak 300 # five minutes each, so twenty-five -just heap-soak 60 8192 15 "Stress" # one scene, everything spelled out -``` - -Arguments are positional. A minute of wall clock is about a quarter of a million -headless frames and a real 60 Hz of ticks, so both axes a leak can live on are -exercised; the reports are left in `.cache/heap-.txt` whether the run -passes or fails, because a green soak is the baseline the next one is read -against. - -Not part of `just check`: it needs a GPU, for `just client-smoke`'s reason. - -### Benchmarks - -```sh -just bench # only what a change could have affected -just bench-all # every suite -just bench-accept # make what was measured the new baseline -just bench --filter ecs # one area -``` - -The same selection as `just test`, over `bench/` instead of `tests/`: a -benchmark declares `TEST_SUITE_ID` and gets the same cascading signature, so a -change at the bottom of the stack re-measures everything above it and nothing -else. That matters more here than for tests - a test suite costs milliseconds -and a benchmark suite costs seconds by design. - -Always against the `bench` preset, which optimises. A debug build measures the -debug build, and the danger is not that it is slower: it is that the *ratios* -between two implementations invert. - -``` -engine.ecs.bench.iteration - Each · 500k entities 198.84 us -1.8% - EachParallel · 500k entities 90.46 us +33.6% slower -``` - -**A number is reported, never enforced.** `just bench` does not fail on a slow -figure and it should not: a laptop on battery, a CI runner with a noisy -neighbour and a desktop with a compile going all swing further than most real -regressions - the `+33.6%` above is one of those, not a change to the code. Read -the number, then decide. `docs/CODE_QUALITY.md`'s rule about attaching a -measurement to an algorithm change is what this exists to serve. - -Take a baseline on a quiet machine, and say so in the commit. One taken while -something else was compiling makes every later run look like an improvement. - -### Compositing several worlds - -```sh -just run --worlds 3 --entities 512 -``` - -Three whole worlds, each with its own clock, its own store and its own view -channel, drawn into one frame side by side. They are *placed* rather than -overlaid because two worlds' coordinates do not mean the same thing - nothing -says they should, and drawing two scenes inside each other and calling it one is -the mistake `--view-spacing` exists to avoid. - -The renderer draws what the compositor took off the channels rather than -reaching into a store. Between a world at its tick rate and a frame at the -display's sit three slots and an atomic index, so a slow frame **drops rather -than throttles a simulation** - and a producer that stalls keeps its last frame -instead of vanishing for one. - -`--name=value` works everywhere `--name value` does. Everything after a bare -`--` is a path, including something that looks like an option. - -### While it is running - -| Key | Does | -|---|---| -| **F3** | frame counter - FPS now, and min/avg/max over the last twenty seconds | -| **F5** | frame graph - last frame's scope tree, and the heap | -| **F6** / **F7** | next / previous frame-graph view | -| **PgUp** / **PgDn** | scroll a graph taller than the panel | -| **-** / **=** | shallower / deeper flamegraph | -| **F8** | write `frame-graph-snapshot.txt` beside the binary | -| **Esc** | quit | - -The five frame-graph views are the flamegraph, time by category, per-system cost -from the scheduler, whatever was written to the metrics sink, and the heap. - -#### Reading the flamegraph - -One row per span, indented by nesting, with a colour chip for its category and a -timeline strip on the right showing *when* in the frame it ran - which the -numbers cannot say, because two systems costing 2 ms each read identically -whether they ran back to back or with the GPU wait between them. - -| Column | Is | -|---|---| -| `MS` | this frame | -| `RMAX` | the worst single reading in the last 300 frames | -| `SHARE` | of the frame | - -**`RMAX` is the column to read first.** A span costing 0.2 ms now and 14 ms -every fortieth frame shows 0.2 in `MS` on a panel repainted at any rate a person -can watch, and the fortieth frame is the one worth knowing about. The header -says how much history that maximum is over, because a worst case over a fifth of -a second and one over five seconds are different claims. - -Rows deeper than the depth limit are hidden and their nearest visible ancestor -is marked `+`, so a collapsed subtree never looks like a leaf. - -#### F8, for what the panel cannot show - -The panel shows one frame. `F8` writes the retained window - five seconds or -20,000 frames, whichever comes first - to `frame-graph-snapshot.txt`: mean, p50, -p99 and max per span, then the forty worst frames and the biggest spans in each. -That last section is what separates "this span spikes" from "the whole frame -went with it". - -Collection only runs while the panel is open, so `F8` with `F5` closed has -nothing to write and says so rather than leaving a zero-byte file. - -#### Stopping the graph on the bad frame - -In the studio's frame-graph panel, **Event scheduler** arms rules that pause the -graph on the frame that meets one. The reported case is a pump that lags now and -then: - -| Field | Set to | -|---|---| -| subject | `span` | -| name | `pump events` | -| test | `over` | -| threshold | `2` | - -The next frame whose `pump events` spans total more than 2 ms freezes the panel -with *that* frame on it, and the pause label says what fired and what it read. -**Resume** disarms the latch, so the next bad frame stops it again. - -A rule is evaluated where the frame is collected, not where it is drawn. That is -the whole reason the feature exists: the panel samples four times a second at its -shortest interval, and the frame you are hunting is one frame long. Subjects are -a span's inclusive or self time, a category's self time, the whole frame, the -unmarked remainder, or the dropped-span count. Rules are saved with the rest of -your preferences and armed at start-up, whether or not the panel is open. - -An `under` rule waits for its span rather than firing on a frame that never ran -it: "`pump events` under 1 ms" is a question about a frame that pumped events. - -### Measuring rather than watching - -```sh -just run --stats --graph --uncapped -``` - -**Always pass `--uncapped` when you care about the numbers.** Without it the -frame is paced by your display, every frame reads as 16.7 ms, and the flamegraph -is dominated by the swapchain wait. With it you see what the frame actually -costs. - -Remember that `dev` builds first-party code at `-O0` on purpose - a profile -there measures what the engine does rather than what the optimiser rescued. Use -the `release` preset when you want the shipped number instead: - -```sh -just preset=release run --stats --graph --uncapped -``` - -### Repeatable runs - -```sh -just run --frames 600 --entities 4000 --uncapped -``` - -`--frames` makes the client usable from a script or a CI job. The demo scene is -a function of elapsed time and is deterministic, so two runs with the same -arguments simulate the same thing - which is what makes comparing them mean -anything. - -**`--entities` is also the view channel's ceiling**, which is worth knowing -before it bites: it sizes the buffer a world publishes its draw list through, so -a scripted scene with more parts than that number publishes nothing at all and -the window is empty. The log says so - *"N instances is past this channel's -maximum"* - and the fix is to raise `--entities`, not to shrink the scene. - -### Seeing a frame - `--capture` - -```sh -just run --frames 60 --capture shot.bmp -``` - -Writes a BMP of the scene near the end of the run and carries on. **A diagnostic -rather than a feature, and it changes how the frame is rendered**: a capture -needs an offscreen target, so asking for one puts the scene into a texture and -presents the window from that. A game pays nothing for it because the flag is -off. - -Needs `--frames`, because the capture is requested one frame before the last so -that it is written by the next and the run still ends when it was told to. - -Use `--capture-sequence DIR --frames N` to record every rendered frame as -`0.bmp` / `0.json` through `N-1.bmp` / `N-1.json`. The JSON records the actual -submitted camera, controller angles/basis, input and eye worlds, portal mapping, Humanoid subject and -authoritative/predicted character roots when available. Portal entries record -the sampled image handle, authored key and aperture geometry. World names may be local -replica aliases; the eye history records its authored world name. -The frame budget must be positive, and `--capture` cannot be combined with this -flag. Each capture waits for GPU readback and writes files, so use this for -visual diagnosis, not performance measurements. - -```sh -just run --frames 60 --entities 2048 \ - --script .cache/build/dev/assets/examples/scripts/Meshes.luau \ - --cdn dir:store --publisher-key PUBLIC --capture meshes.bmp -``` - -The closing log line is the other half of the same question: *"88302 triangle(s) -in 136 draw call(s) at the busiest frame"*. A world of cubes is twelve triangles -an instance and a world of imported meshes is tens of thousands, so a run whose -triangle count did not move is one where every `MeshId` resolved to the fallback -cube - which is the deliberate degraded state and looks like a scene of boxes. - ---- - -# The server - -Headless. No window, and no renderer in the binary at all. - -```sh -just host # 30 Hz until you stop it -just host --ticks 300 --entities 20000 -./.cache/build/dev/server/server --help -``` - -### Options - -``` ---unpaced Tick back to back instead of pacing to the tick rate ---graph Collect the frame graph (for a Tracy capture) ---verbose Log at trace level ---force-serial-compute Run parallel dispatches on one thread ---mcp-port PORT Open the loopback control surface (default 8734) ---tick-rate HZ Ticks per second (default 30) ---physics-tick-rate HZ Physics steps per second (default: the tick rate) ---replication-tick-rate HZ Snapshots per second (default: every tick) ---entities N Entities in the placeholder world (default 4096) ---ticks N Exit after N ticks ---seconds N Exit after N seconds ---game PATH Scene script, or a .agame universe to host (v0.7) ---record PATH Write a recording of this run ---replay PATH Replay a recording instead of simulating ---override-assets-directory DIR Read staged data from here ---chatter Make every world publish on a shared topic ---host NAME Run as a supervised host under a driver ---world NAME A world this host was granted (repeatable) ---remote-world NAME Place this world in a host process (repeatable) ---worlds-per-host N Shared worlds per host process (default 8) ---host-program PATH The program a host runs (default: this one) ---processes N How many processes share this machine ---listen PORT Serve a world to clients over UDP ---transport MODE quic (default), datagram, or both ---identity-key HEX Ed25519 seed for the server identity ---content-store DIR Serve a local content store ---content-port PORT Port for the attached content origin ---content-grant-key HEX Secret used for content grants ---help Show this text -``` - -### Three rates, not one - -A world ticks, steps its physics, and publishes snapshots. Those are three -different costs and they get three different numbers: - -```sh -./server --game My.agame --tick-rate 60 --physics-tick-rate 30 --replication-tick-rate 20 -``` - -- `--tick-rate` is what scripts, signals and character input run at. -- `--physics-tick-rate` is what the solver runs at. Lower it when a world is - spending its tick in physics and the scripts still need the full rate; raise - it for a world of fast, precise bodies. Zero follows the tick rate. -- `--replication-tick-rate` is how often a snapshot goes on the wire. Zero - publishes every tick. Lowering it does not lose state: the world holds its - change bits across the ticks it does not publish, so a property written on - any of them still reaches the client on the next one that does. - -Both are measured in *simulated* seconds, so a suspended world owes nothing for -the time it was asked to and an idle world at 2 Hz cannot publish twenty times a -second however loudly it was asked to. - -The three flags apply to the worlds this program creates itself. A `.agame` -carries `physicsTickRate` and `replicationTickRate` per world under -``, and those win - a scene authored to solve at 30 solves at -30 whoever hosts it. - -### Recording and replaying - -A recording is one snapshot plus every bus envelope applied since, which is -complete because a world is deterministic given its state and its inbox. - -```sh -./server --entities 512 --ticks 200 --unpaced --record run.rec -./server --replay run.rec # the same run, again -./server --replay run.rec --record again.rec # and record what it replayed -``` - -The third form is what `just replay-check` runs: `again.rec` has to come back -byte-identical to `run.rec`, which says the snapshot, the frame times and every -envelope all reproduced - not merely that the replay survived. -`just determinism` makes the weaker but broader claim, that two live runs of one scene -produce identical files. Both are same-binary, same-machine; cross-machine -agreement is deliberately not promised, because floating point differs between -compilers and chips. - -### Host mode - -A host is not a different program. It is this one, holding some of a universe's -worlds in its own address space so that a hard fault in one of them takes that -process rather than the server - which is what makes the grouping a deployment -decision instead of an engine one. - -You do not run the host side by hand. You run the *driver* side, and it spawns -what it needs: - -```sh -./server --seconds 10 --chatter --remote-world lobby --remote-world arena -``` - -That starts one host holding both worlds, links it, and routes every bus -operation through the driver's own MessagingService, MemoryStore and DataStore - -there is one router, so a world behaves the same wherever it is held. `--chatter` -exists because there is no game file yet and therefore no traffic: it makes every -world publish its name and tick on a shared topic, which is the only thing that -crosses a link until v0.5 gives worlds something real to say. - -Running the host side directly is refused: - -```sh -./server --host host.one --world lobby --world arena # refuses: no driver -``` - -Deliberately. A host with no driver would tick worlds nobody asked for and answer -to nobody, and accepting it would make `--host` look like a way to run the server -under a nicer name. - -`--processes` is the worker budget. Every process calling for one worker per core -is the bug it prevents: a driver and seven hosts on a twenty-four core machine -would run a hundred and ninety threads over twenty-four cores. The driver works -it out from the hosts it is about to spawn and passes the answer down, so you -should not normally set it. - -### Stopping it - -Ctrl-C, or `SIGTERM`. The handler sets one flag that the loop reads between -ticks, so the current tick finishes and the run summary still prints: - -``` -30 tick(s) over 0.97s · mean 0.336 ms · slowest 0.540 ms · 0 overrun(s) -``` - -**`overruns` is the number worth reading.** It counts ticks that took longer -than their budget. Zero means the tick rate was actually held; anything else -means the server is behind, and `slowest` tells you by how much. - -### Measuring a tick - -```sh -just host --unpaced --ticks 1000 --entities 50000 -``` - -`--unpaced` removes the sleep between ticks, so `mean` measures the simulation -rather than the pacing. Use it for any comparison; leave it off to check that a -given entity count actually holds a given tick rate. - ---- - -## Every arrangement of the halves *(v0.18)* - -```sh -just unified # the bisection, one screen of it -just unified --all # all twelve, one line each -just unified --arrangement lossy+relayed # content over a link that loses -``` - -`unified_tests` holds a server and a client in **one process** and lets you -choose what goes between them. It answers two questions that a pair of real -programs cannot. - -**Which stage lost the world.** `--arrangement direct` hands the authority's -byte vectors straight to the replica: no socket, no framing, no cipher, no -acknowledgement window, no MTU. The table it prints is a column per stage - -produced, sent, applied, drawn - so the first column that stops making sense is -the answer. A blank scene here is above `net`; a blank scene against a real -server and a full one here is below it. - -**Whether the modules agree with each other.** Underneath the table it prints -every module's own report - `replication`'s authority and replica, `net`'s -sessions and links, `cdn`'s publication, `server`'s relay, `client`'s content -link, `network`'s beacon and directory, and `core`'s heap - and then the claims -that span two of them. Those are the ones no module's own suite can make, -because the tier system stops each module linking the other end of its seams: - -``` -contradictions - client/server the relay answered 12 route(s) in full and the client reassembled 11 -``` - -### The three axes - -| axis | values | what it adds | -|---|---|---| -| transport | `direct`, `loopback`, `lossy` | nothing, a real `net` link, a link that drops datagrams | -| content | `relayed` | a `cdn` publication, a `server` relay, a `client` link | -| discovery | `advertised` | a `network` beacon announcing and a directory collecting | - -Names join with `+` in any order, and `--all` runs the whole cross product - -twelve of them. `--list-arrangements` prints the names, which is how -`just unified-soak` stays in step with the axes rather than holding a copy. - -### Options - -| option | what it does | -|---|---| -| `--arrangement NAME` | one arrangement; `direct` unless given | -| `--all` | every arrangement in turn, one summary line each | -| `--list-arrangements` | print the names and exit | -| `--entities N` | rows in the placeholder world (64) | -| `--scene PATH` | author the server's world from a scene script instead | -| `--ticks N` | ticks after the join (120) | -| `--seconds N` | run on wall clock instead, for the heap axis | -| `--tick-rate HZ` | the authority's rate (30) | -| `--frames-per-tick N` | frames drawn per tick (4) | -| `--delay-ticks N` | the snapshot buffer's delay (2) | -| `--drop N,N,...` | ordinals to lose silently | -| `--quiet` | the reports only, no line per tick | -| `--heap-report PATH` | write the heap profile when the run ends | -| `--heap-growth-limit BYTES` | exit 3 when a tag climbs faster than this | -| `--heap-warmup SECONDS` | readings to leave out of the growth fit (10) | - -`--drop` numbers different things per transport, because a transport can only -lose what it carries: outgoing **messages** under `direct`, datagram **arrival -numbers** under `lossy`. `loopback` drops nothing - it exists to add framing and -nothing else. A `lossy` run with no `--drop` uses a built-in set that lands -inside the join, so the reliable channel's retransmission is exercised rather -than merely available. - -The exit code is `0` when every arrangement joined and no module contradicted -another, `1` when one did, and `3` when a heap tag ran away. - -### Soaking the seams *(v0.18)* - -```sh -just unified-soak # twelve arrangements, 25s each -just unified-soak 60 # twelve minutes -just unified-soak 30 4096 10 # tighter limit, longer warm-up -``` - -`just heap-soak` asks whether drawing a world leaks. This asks whether -*crossing* one does, which is a different question with different answers: a -leak in a session's retransmission buffer or in the relay's reassembly is -invisible to a client that is not connected to anything. - -One process per arrangement, deliberately - a single process running all twelve -in turn has one heap history with twelve workloads in it, and a slope fitted -across that is fitted across the changeovers. Reports land in -`.cache/heap-unified-.txt` whether the run passes or fails. - -Not part of `just check`: at the default it is five minutes, and a check -somebody skips is a check that is not run. - ---- - -## Which transport a session runs on - -**QUIC is the default and the server decides. The client has no flag.** - -```sh -server --listen 9000 # quic, which is the default -server --listen 9000 --transport datagram # the stack this engine had before v0.19 -server --listen 9000 --transport both # whichever a client opens with -``` - -A client always opens with QUIC. A server that does not serve it answers with a -refusal rather than with silence, and the client retries over the datagram -stack immediately - one round trip, not a timeout. A server that serves only -QUIC refuses a datagram hello the same way. Either way the log line says which -transport the connection landed on and why: - -``` -replication: quic did not connect (the server does not serve this transport) - retrying over the datagram wire. -replication: connected over datagram on attempt 2 of 2 -``` - -**Both modes share one UDP port.** There is no second socket and no second -accept loop: the first packet from an unknown peer is a QUIC Initial or a -`net::Packet`, and one bit of its first byte says which. `mono.engine/net/ -include/engine/net/Wire.hpp` carries the bit positions. - -A server that is announcing itself puts its mode in the advert, so a client that -found it in a browser opens on the right stack and pays no refusal at all. A -typed-in address has no advert, so that client pays one round trip when the -server is on the old stack. - -Both transports use `--identity-key` when supplied. Otherwise the server draws -an ephemeral signing identity for the run and logs its public key. A client must -pin that public key through trusted discovery or configuration to identify the -server. Portal lease routes carry the destination's public key for this purpose. - ---- - -## Proving which server a client reached - -```sh -server --listen 9000 --identity-key $SEED # 64 hex characters, an Ed25519 seed -client --connect HOST:9000 --server-key $PUB # the public half the server logs -``` - -**Without a trusted server-key pin the exchange identifies nobody.** It is encrypted, so a -listener on the path learns nothing; but whoever *carries* the two key-exchange -messages can substitute their own key, hold one session with each side and read -everything. `net/Handshake.hpp` has said so since v0.3. - -With them, every `Welcome` carries an Ed25519 signature over the transcript, and -a relay cannot produce one - it would have to make the server sign a transcript -naming the relay's own ephemeral key. A client whose pin does not match refuses -outright rather than connecting anyway: - -``` -replication: this is not the server that was pinned - refusing to connect. -``` - -The server prints the public half on start-up, which is what to give a client: - -``` -replication identity f78b1da9b3dfb3fa3a3e54c43e79389d2f04d6bccb62984f28bd6f91798a750d -``` - -**It is the same key a publisher signs content with** - `cdn --signing-key` and -`client --publisher-key`. A server and the content it serves are one identity as -far as a player is concerned, and two keys would be two things to distribute and -two chances to pin the wrong one. - -**Both ends default to the weaker mode and both say so**, because refusing to -run without a key would refuse every deployment in this engine today, and -refusing quietly would be worse than either. - ---- - -## Finding a server without being told an address - -Everything below is off by default. A recipe that does not ask for it opens no -extra socket and broadcasts nothing. - -### On the same switch - -```sh -server --listen 0 --advertise --session-name "User's game" -client --browse -``` - -The server announces itself once a second to `255.255.255.255:47600` and the -client listens there. `--listen 0` binds an ephemeral port and the announcement -carries **the port that was bound**, so nothing has to be agreed in advance. - -The address a client dials is the address the announcement *arrived from*, with -the advertised port. A host binds `0.0.0.0` and cannot know which of its -addresses a given client can route to; the one a datagram already crossed needs -no guess. - -| Flag | On | What it does | -|---|---|---| -| `--advertise` | server, cdn | announce on the subnet | -| `--session-name NAME` | server | what a browser shows | -| `--browse` | client | look instead of being told | -| `--browse-seconds N` | client | how long to look (default 3) | -| `--session-name NAME` | client | join that one rather than the first | - -**The search is the one blocking wait in the client**, and it happens before the -loop starts, in the same place as binding a socket. A beacon announces once a -second, so anything under two seconds is a coin flip. - -### Invited only - -```sh -server --listen 0 --advertise --session-key "a sentence we agreed on" -client --browse --session-key "a sentence we agreed on" -``` - -A private session's announcement carries a MAC under the key, so a client -holding it can tell the session it was invited to from somebody else's wearing -the same name. A key is 64 hex characters or a passphrase, and the same words -derive the same key on both machines. - -**Private authenticates; it does not hide.** A private session on a subnet is -visible to everybody on that subnet and joinable by nobody without the key. A -browser shows it as locked, which is deliberate - the person about to be given -the key has to be able to see it exists. - -### Across the internet - -```sh -cdn --store DIR --rendezvous-listen 47601 # somewhere already reachable -server --listen 0 --rendezvous ORIGIN:47601 --session-name "mine" -client --rendezvous ORIGIN:47601 --session-id 036e0c6d109c14220d0d7d2bdae7239a -``` - -The point introduces two peers and carries none of their traffic. Both sides -then poke each other directly until one gets through; the address that results -is on **the same socket the session uses**, because a router's NAT mapping -belongs to a port. - -The rendezvous point runs inside the content origin rather than as a fifth -program: it holds an id, an address and a timestamp, and it needs to be -somewhere an operator has already put on an address. - -**A private session is not listed at the point and cannot be.** The point holds -no key and must not - that would make every operator of one a holder of every -private session's secret. So reaching a private session needs its id, which the -host hands over along with the key. `server --advertise` prints both: - -``` -announcing session 036e0c6d109c14220d0d7d2bdae7239a (private) on the local subnet -``` - -**There is no relay.** When both routers refuse, the attempt fails and says so: - -``` -could not reach session 036e... through ORIGIN:47601 -``` - -That is an honest answer. A hidden fallback would make "peer-to-peer" mean two -different things depending on the day, and a relay is bandwidth somebody pays -for. - -### Distribution streams - -The same three reaches, offered by a content origin instead of a game server: - -```sh -cdn --store DIR --advertise # LAN -cdn --store DIR --advertise --stream-key SECRET # private, key required -cdn --store DIR --rendezvous POINT:47601 # listed for anyone off-subnet -cdn --store DIR --rendezvous-listen 47601 # be the meeting place -``` - -A stream is not a second kind of origin - the same six routes are served to -everybody. What a stream decides is how a client *finds* it and whether it was -invited, and `--stream-key` gates discovery rather than delivery: a grant is -still what admits a fetch. - -### What a part collides as - -A part is drawn at its `Size` and collides at its `CollisionShape`, and nothing -keeps those the same. **View → Collider Outlines** draws what the solver -actually has: a colour per face, so a hull reads as an object rather than as a -tangle of lines. - -**View → Collider Shape** picks which of the three a part has: - -| Mode | Draws | -|---|---| -| As chosen | What `CollisionShape` selects - what actually collides | -| Precise | The baked triangle soup, for anything that has one | -| Hull | The baked convex hull, for anything that has one | -| Bounds | The part's own box - what a shape falls back to when its name does not resolve | - -The two that are *not* selected are usually what answers "why does this collide -like that": a rock whose hull swallows the gap it should have, a chunk whose -bound is a box the size of the whole tile. A mode with nothing baked to show -falls back to drawing what the collider actually is, because the absence is the -answer for a part somebody expected a hull on. - -**Fill faces** fills them as well as outlining them - filled is how a shape reads -as a solid, outlined is how two overlapping ones stay separable. **Hide -textures** draws the world flat while the view is open, because a wireframe over -a textured scene is a wireframe over a photograph. - -### Geometry a script builds, and standing on it - -An `EditableMesh` is drawn *and* collides. `MeshPart.MeshId` names it for the -renderer and `CollisionGeometry` names it for the solver: - -```lua -local mesh = Instance.new("EditableMesh") --- ... AddVertex / AddTriangle ... - -local part = Instance.new("MeshPart") -part.MeshId = mesh.ContentId -part.Parent = workspace -part.CollisionShape = Enum.ShapeKind.Mesh -- or Hull -part.CollisionGeometry = mesh.ContentId -``` - -**Build the vertices around the mesh's own origin.** A baked shape is used in -the part's object space and is not scaled to it, so a mesh written in world -coordinates draws correctly - `ToGpu` fits it to the part - and puts its -collider wherever the part is not. - -**The shape arrives on the next tick.** `physics::RegisterPhysicsSystems` bakes -it in `PreSimulation` for every host that solves, and a collider naming a shape -that has not resolved yet collides as the part's own bound. For a terrain chunk -that bound is a solid box the height of the whole tile, so a streamer should -leave a new chunk `CanCollide = false` for one frame - `Terrain.luau` does, and -says why where it does it. - -**The soup is baked always and the hull only when a collider asks for one.** -Measured on a 4,225-point chunk the soup costs 1.3 ms and quickhull costs 7.3, -and a heightfield's hull is a dome over its summit. Switching a part to `Hull` -later still gets one, on the next tick. - -Shapes are forgotten when their mesh is destroyed, so a world that streams a -mesh per chunk does not accumulate one per chunk ever built. - -### In the editor - -**View → Team Create.** The editor announces itself at the same layer, sees the -other editors on the subnet or through a point, and hands over a session id and -a key to invite somebody with. - -**Edits replicate.** Host a session, and every editor that joins sees what you -do - a create, a delete, a reparent, a property write. A recording crosses as -one message, so "set these forty parts to neon" arrives whole or not at all. - -The panel lists the editors it can see; **Join** connects to one, and the row -underneath reports what has crossed. - -**Undo does not replicate, and that is deliberate.** Ctrl+Z reverses what *you* -did, never what somebody else did. An editor that undid a colleague's change -because you pressed it once too often would be an editor nobody could work in. - -**Two editors on one model take turns, and neither loses their work.** Before a -waypoint goes out, its author asks the host for the subtree it touches. If -nobody has it, the host hands it over and the edit goes; if somebody does, the -request waits in line. When the person in front is done the next one goes, and -their change lands *on top of* the first. - -**Nobody is ever refused for being second.** That is the whole reason there is -a queue rather than a rejection: somebody asking for a model in use is not -doing anything wrong, they are second, and second still gets a turn. - -**The person does not wait.** Their edit is applied at their own machine the -moment they make it; what waits for the turn is the *message*. A queued editor -carries on working and their waypoints go out in the order they made them. - -If somebody else's edit is ordered ahead of one you are still waiting to send, -your machine re-applies yours on top when theirs arrives - so every editor ends -on the same answer, and it is the host's order that decides which. - -A turn covers a subtree, not one instance: a turn over a model that let -somebody else edit its parts would order nothing, because moving a model moves -its children. Two editors in different corners never wait for each other. - -**A grant has a short guard**, so an editor that is handed a subtree and then -dies costs the next person a pause rather than the session. It is a bound on -one protocol step, not a lease on editing. - -**The ordering is at the host**, which is already the thing that decides order. -The panel shows whose turn it is and how many edits are waiting; a guest running -a modified build cannot jump the queue. - -**Everybody has to have the project open already.** A join carries edits, not -the document - a scene the peer does not have is an edit that is dropped and -counted. Open the same `.agame` on both machines first. - -### ChangeHistoryService - -A plugin tells the editor what one undo should reverse, exactly as it does in -Roblox: - -```lua -local ChangeHistoryService = game:GetService("ChangeHistoryService") - -local recording = ChangeHistoryService:TryBeginRecording("Set selection to neon") -if not recording then - return -- a recording was already in progress -end - -for _, part in Selection:Get() do - part.Material = "Neon" -end - -ChangeHistoryService:FinishRecording(recording, Enum.FinishRecordingOperation.Commit) -``` - -Forty property writes, one press of Ctrl+Z. That grouping is the reason the -service exists and is also the unit a shared document will travel in - a peer -that applied half of a group would show a state the author never saw. - -`Commit` keeps the recording as its own step, `Cancel` reverts it and puts -nothing on the redo stack, and `Append` folds it into the step before. - -| Method | | -|---|---| -| `TryBeginRecording(name, displayName?)` | the identifier, or nil when one is already open | -| `FinishRecording(id, operation, finalOptions?)` | `Commit`, `Cancel` or `Append` | -| `IsRecordingInProgress(id?)` | | -| `GetCanUndo()` / `GetCanRedo()` | | -| `Undo()` / `Redo()` | raises when there is nothing | -| `SetWaypoint(name)` | merges everything since the last cut | -| `ResetWaypoints()` / `SetEnabled(state)` | | -| `OnUndo(f)` · `OnRedo(f)` · `OnRecordingStarted(f)` · `OnRecordingFinished(f)` | | - -**Two differences from Roblox, and both are the seam rather than a choice.** - -`GetCanUndo` and `GetCanRedo` return a table, because a host call answers one -value - `local can, name = table.unpack(ChangeHistoryService:GetCanUndo())`. - -The events are calls that take a handler rather than signals with `:Connect`, -because the host seam has no `RBXScriptSignal` type and inventing one for four -events would be a second way to hear about something. - -**One recording at a time for the editor, not per plugin.** This service is the -editor's single history; two plugins recording into one undo stack would produce -a step neither of them described. - -**`SetWaypoint` merges and the editor never calls it.** Roblox's rule is that the -changes between two waypoints are one undo; this log's default is one edit per -step, so a cut merges everything since the previous one. A plugin that writes -forty properties and then calls it gets one step. The editor's own edits are -unaffected, which is the point rather than an oversight. - ---- - -# The content origin - -Serves a game's content out of a directory. Two deployments, one program: beside -the game for single-player, LAN and split-screen, or on its own for a large -content collection. Nothing inside the program tells them apart - the difference -is which directory it mounts and who can reach it. - -Publishing and serving are **two invocations, and the split is deliberate**: the -signing key belongs to whoever publishes the game and the origin holds none, -which is what makes it safe to deploy on hardware nobody here owns. - -## Quick CDN setup - -Build with `just cdn`. Put baked assets in `content/`, choose different -64-character hex signing and grant secrets, then publish: - -```sh -SIGNING_KEY=YOUR_64_HEX_SIGNING_SECRET -./.cache/build/dev/cdn/cdn \ - --publish ./content --store ./store --signing-key "$SIGNING_KEY" -``` - -Save the `publisher key` printed by the command. To use the folder directly: - -```sh -PUBLISHER_KEY=THE_KEY_PRINTED_BY_PUBLISH -just run --cdn dir:./store --publisher-key "$PUBLISHER_KEY" -``` - -To serve the same store over HTTP: - -```sh -GRANT_KEY=YOUR_DIFFERENT_64_HEX_GRANT_SECRET -./.cache/build/dev/cdn/cdn \ - --store ./store --grant-key "$GRANT_KEY" --port 9080 -``` - -`curl http://127.0.0.1:9080/health` should answer `ok`. - -### Use a custom CDN from a game server - -In another terminal, point the game server at an IP address its clients can -reach: - -```sh -GRANT_KEY=THE_SAME_64_HEX_GRANT_SECRET -PUBLISHER_KEY=THE_KEY_PRINTED_BY_PUBLISH -CDN_HOST=192.168.1.20 -just host --game My.agame --listen 9000 \ - --content-grant-key "$GRANT_KEY" \ - --flag server.content-mode=redirect \ - --flag server.content-sources="$CDN_HOST:9080" \ - --flag server.content-publisher-key="$PUBLISHER_KEY" -``` - -The CDN and game server must use the same grant key. - -### Add the store to Studio - -Open **Edit > Preferences > Content**: - -1. Choose **Add local store**. -2. Set **Use** to `read` and **Location** to the published `store/` directory. -3. Paste the publisher key under **Trust**. - -Changes save immediately. For a remote origin, choose **Add origin** and enter -its `HOST:PORT`. Protected remote downloads still need a grant from a game -server, so use the local store in Studio for direct authoring and preview. - -### Connect a client - -Normally the server supplies the CDN address, session grant and publisher key: - -```sh -just run --connect GAME_SERVER:9000 -``` - -To pin your own CDN and key, pass them explicitly. The client tries this source -before any source announced by the server and refuses a different publisher: - -```sh -PUBLISHER_KEY=THE_KEY_PRINTED_BY_PUBLISH -CDN_HOST=192.168.1.20 -just run --connect GAME_SERVER:9000 \ - --cdn "$CDN_HOST:9080" --publisher-key "$PUBLISHER_KEY" -``` - -That HTTP CDN must accept the grant issued by the game server. A `dir:` source -needs no grant. - -The detailed publishing, serving and troubleshooting reference follows. - -### Publish a directory of files - -```sh -./.cache/build/dev/cdn/cdn \ - --publish ./content \ - --store ./store \ - --signing-key $(printf '7a%.0s' {1..32}) -``` - -It walks the directory, cuts every file into content-defined chunks, writes them -into the store, classifies each asset from its extension, groups them, trains a -compression dictionary if there is enough content to learn from, and signs the -manifest root. It prints the root and **the publisher key**, which is what a -client has to be told: - -``` -[info] cdn: published 5 assets in 1 bundles - 717432 bytes of content in 717432 bytes of chunks -[info] cdn: manifest root 8a1c34d1d3f8... -[info] cdn: publisher key ba42458e83ba... -``` - -Republishing is cheap: unchanged content is already in the store and every write -of it is a no-op. - -### Serve one - -```sh -just serve --store ./store # serve a prepared content store -./.cache/build/dev/cdn/cdn --store ./store --grant-key HEX --port 9080 -``` - -```sh -curl http://127.0.0.1:9080/health # ok 5 assets 1 bundles -curl -o manifest.acm http://127.0.0.1:9080/manifest -curl -o group.zst -H "x-atomic-grant: HEX" http://127.0.0.1:9080/bundle/ -``` - -### Options - -``` ---store DIR The content store to serve or publish into ---publish DIR Publish this directory of files into the store, then exit ---signing-key HEX 64 hex characters - the Ed25519 seed to sign a publish with ---grant-key HEX 64 hex characters - the secret shared with the server ---port N Port to listen on (default 9080; 0 binds an ephemeral one) ---ingest-key SECRET Accept uploads at /ingest from whoever sends this ---inbox DIR Where uploads land (default: the raw/ beside a processed store) ---upstream NAME=HOST:PORT An origin to forward a miss to. Repeatable ---allow-upstream Forward a miss. Off unless asked for ---no-local-first Always ask an upstream - a pure proxy ---no-cache-upstream Do not keep what an upstream returned ---compression-level N Zstd level groups are prepared at (default 9) ---cache-bytes N What the prepared-group cache may hold ---frames N Serve this many pumps and exit. For a smoke test ---gui Watch it serve in the terminal ---verbose Log at trace level -``` - -### Watching it serve - -```sh -./.cache/build/dev/cdn/cdn --store ./store --grant-key HEX --port 9080 --gui -``` - -A scrolling terminal view of the origin, on the alternate screen, redrawn four -times a second: - -``` -atomic - content origin · 0.0.0.0:9080 - -NETWORK - now out 31.8 KB/s in 4.9 KB/s - last hour out 42.5 KB in 6.6 KB (60 minutes, the newest partial) - since start out 42.5 KB in 6.6 KB - out ···························································█ peak 42.5 KB/min - in ···························································█ peak 6.6 KB/min - -REQUESTS - bundles 0 · manifests 40 · dictionaries 0 · health 40 - refused 0 · missing 0 · rejected 0 - group payload served 0 B - prepared cache 0 groups · 0 B of 256.0 MB - -CONTENT - 4 assets in 1 bundles - 752.0 KB of content, uncompressed - 752.0 KB on disk in 12 chunks - -BY KIND … LARGEST 5 … ASSETS (4, largest first) … -``` - -| Key | Does | -|---|---| -| `↑` `↓` or `k` `j` | one line | -| `PgUp` `PgDn`, or `b` and space | one screen | -| `g` `G` | top, bottom | -| `q` or Ctrl-C | leave, restoring the terminal | - -**Out and in are measured at the socket**, so they count headers, health checks -and a request that never finished arriving - which is what an operator watching -bandwidth wants. `group payload served` is the other question, what delivery -actually cost, and one number could not answer both. - -**The log level is raised to errors while it is up**, because the log and the -dashboard share a screen and the log would win a line at a time. It goes back on -the way out, and the summary still prints. - -`--gui` on something that is not a terminal - a pipe, a log file, a service -manager - warns and serves without it. Escape sequences written into a log file -are a log nobody can read. - -`--grant-key` is **required to serve**, and it is not a convenience to remove. -An origin that admitted everyone would be deciding who may have what, which is -the server's job. - -The three deployments are flag combinations rather than three programs: - -| Deployment | Flags | -|---|---| -| Local store - serve your own disk | the default | -| Cache server - local first, forward a miss, keep it | `--allow-upstream --upstream a=host:port` | -| Pure proxy - always ask, keep nothing | `--allow-upstream --no-local-first --no-cache-upstream` | - -### Attached to a server instead - -A server can run one in-process, which is the self-hosted case: - -```sh -just host --content-store ./store --content-grant-key HEX --content-port 9080 -``` - -That store is also what a `relay` server relays out of and what a `redirect` -server names, unless `server.content-sources` says otherwise - see -[Where a client's content comes from](#where-a-clients-content-comes-from-v016). - -The grant is then issued and verified across a function call, and **both halves -are real** - the MAC is computed and checked. A path skipped in the -configuration people develop against is a path that breaks the first time -somebody ships the other one. - -### Fetching it - -```sh -just run --cdn 127.0.0.1:9080 --publisher-key HEX --content-cache ./cache -just run --cdn dir:./store --publisher-key HEX # a local store, no wire -``` - -`--cdn` is repeatable and **the order is the priority**: the first source that -answers wins, and one that fails is passed over. That is how "local cache first, -otherwise ask the origin" is expressed - there is no policy flag, because the -order of the list *is* the policy. The studio edits the same list under -Preferences → Content. - -Without `--publisher-key` nothing is fetched, and that is deliberate: a client -that accepted an unsigned manifest would have no trust boundary at all. - ---- - -# Audio - -```sh -just run --sound ./assets/tone.wav # plays it on a loop -just run --sound ./assets/track.mp3 # the same, and the decoder is picked - # from the bytes rather than the name -``` - -**Two formats, and the second arrived with a licence rather than with a change -of mind.** RIFF/WAV - 8, 16 and 24-bit integer PCM and 32-bit float - and MPEG -Layer I, II and III, behind minimp3, which is CC0. `.ogg` and `.flac` are still -classified by the content manifest and **not decoded**: each is a vendored codec -and a licence decision, and listing an extension without a decoder behind it -would be worse than the honest gap. - -### A sound in a world - -`Instance.new("Sound")` is a class like any other, and **its parent decides how -it is heard**: - -| Parented to | Heard | -|---|---| -| `workspace`, or any service | everywhere, at one level - music | -| a part, or anything with a place in the world | from that part, falling off between `RollOffMinDistance` and `RollOffMaxDistance` | - -```lua -local music = Instance.new("Sound") -music.SoundId = "audio/lilium-lainu.mp3" -- the manifest's name, extension included -music.Looped = true -music.Volume = 0.6 -music.Parent = workspace -music.Playing = true -``` - -`SoundId` names a **published asset**, exactly as `MeshId` names a mesh - so the -client plays it when it is pointed at a store that has it and is silent when it -is not. Setting `Playing` before the content has streamed is fine: the row keeps -asking and it starts on the frame the asset lands. - -**`Playing` is a property rather than a `Play()` method**, and that is a fact -about the script binding rather than about audio. Methods live on one metatable -shared by every instance, so a `Play` there would be a method on every `Part` in -the world. Roblox has this property too and `sound.Playing = true` is what it -means. - -There is a working one in `mono.engine/examples/assets/scripts/Terrain.luau`: - -```sh -cdn --publish ./content --store ./store --signing-key HEX # content/audio/*.mp3 -just run --script .cache/build/dev/assets/examples/scripts/Terrain.luau \ - --cdn dir:./store --publisher-key PUBLIC -``` - -``` -[info] content: audio/lilium-lainu.mp3 decoded (342.3s, 48000 Hz, 2 channel(s)) -[info] content: 0 mesh(es), 0 texture(s) and 1 sound(s) registered -``` - -Decoding and resampling happen **once, at load**, never on the device thread - -which is why the line above reports the device's rate rather than the file's. - -**A machine with no audio output is not an error.** The client says so and runs -quietly: - -``` -[info] audio: no output available (No available audio device) - running silently -[warning] audio: 'tone.wav' decoded (1.00s) but there is no output on this machine -``` - -A file that cannot be read, or is not audio this engine decodes, **is** an error -and stops start-up - and it is reported whether or not there is a device, so a -typo'd path is visible on a headless box too. - -### What it is doing underneath - -The pipeline is a node graph: `Player` inputs, `Fader`, `Emitter` and `Bus` -processors, one `Output`. A tick never touches it - it posts a command carrying -a **sample deadline**, and the mixer splits its block at every deadline inside -it. That is the one thing here that is a requirement rather than a refinement: a -game ticks at frame rate and audio runs at sample rate, so a sound applied at -the top of whichever block comes next is audibly early or late. - -`mono.engine/audio/AGENTS.md` carries the rest. - -A store that is missing, or that holds no manifest, is refused at start-up with -exit code 1, rather than being accepted and failing one request at a time. - -What exists is `cdn::ContentRoot` - the boundary between a content name and the -filesystem. It refuses traversal by default, and both of its checks are -load-bearing: components are checked before the disk is touched, which catches -`..` and absolute names but cannot see a symlink, and the resolved path is then -checked for containment, which catches the symlink. A symlink that stays inside -the root is served, because an atomically swapped `current` is the deployment -pattern this is for. - -Content addressing, the hierarchical hash, grants, and streaming groups so a -game builds progressively are built. What is still open at v0.9 is `control/` -(the upload API and dashboard, in -TypeScript), invalidation, and chunk-level verification of what an upstream -returned - today that is a length check against the signed manifest, which is -real and is not the whole of one. - -### Proving it needs no graphics stack - -```sh -just check-cdn-is-bare -``` - -Configures with no client and no server, builds, and fails if the staged `cdn/` -directory has grown a `shaders/` folder or if another program was built into a -cdn-only preset. The tier rule is what actually enforces this - `mono.cdn` is -`shared` tier, and a `shared` target may link only `shared` - so a presentation -module reaching this link line fails the configure with the edge named. The -recipe is the version of that anybody can see without a graph query. - ---- - -# The tools - -## The test runner - -```sh -just test # only what your change affected -just test-all # everything -just test --gpu-tests # everything, including headless GPU cases -just test-list # what it would run, and why -./.cache/build/dev/tools/testrunner --help -``` - -GPU cases carry the `[gpu]` tag and are excluded from ordinary test runs. Pass -`--gpu-tests` when a Vulkan device is available. This forces every suite to run, -including the GPU cases, with `Renderer::Initialise(nullptr)`: a real device, -shader compiler, pipelines, compute queues, offscreen targets, captures and -readbacks, but no window or swapchain. A missing or broken device fails the run -instead of silently skipping coverage. - -For the render module alone, `just render-check` builds and runs the existing -Catch suite's GPU cases. `just render-check '[fixture]'` selects the analytic -projection/depth fixtures; other Catch filters work in the same argument. -The optional second argument is the backend, currently `vulkan`. Requesting an -unimplemented backend fails explicitly. A missing device fails the tests. - -Fixtures compare named graph images against independent CPU pinhole rays, with -odd/non-square targets, padded transfer rows, depth overlap, clipping, edits and -camera motion. Failure bundles go beside the test binary under -`render-failures///`: inputs and graph, device/driver, shader -hashes, exact expected/actual bytes, preview images and a mismatch mask. Float -depth previews share the reference depth scale; raw files preserve precision. -The recipe records the source revision, including a dirty marker. - -`just render-preparation-bench 5` measures whole camera batches signing unchanged -world rows and one-row edits in the optimized `bench` preset. It is a CPU -preparation baseline, not GPU or full-frame timing. Cache/baseline paths stay -under `.cache/build/bench`; results print to the terminal. - -`just shader-fuzz 10000` builds the real cooked shader parser with Clang -libFuzzer, AddressSanitizer and UndefinedBehaviorSanitizer, then runs a bounded -mutation campaign from three generated transport seeds. It checks transactional -refusal and canonical round trips. A seed is transport-valid metadata and does -not certify an executable shader. This headless target creates no device. -Pass a different Clang C++ executable as the second argument if needed, with -`CC` naming its matching C compiler. The dedicated build, corpus and crash -artifacts stay under `.cache/build/shader-fuzz/`. `-max_len=65536` bounds this -routine campaign; the asset suite separately checks the 64 MiB container cap. - -`just presentation-fuzz 10000` instruments the actual cross-world presentation -message parser with the same sanitizers. It checks canonical message round trips -and transactional refusal of malformed envelopes. It shares the Clang build -tree above, with separate `presentation-corpus` and `presentation-artifacts` -directories under `fuzz/`. Run the two fuzz recipes sequentially because both -configure that build tree. This campaign uses the same 64 KiB mutation bound; -the world suite separately checks maximum payload sizes and queue pressure. - -``` ---build DIR A configured build directory ---cache PATH Cache file (default .cache/smart-tests.txt) ---report DIR Where test-output.md/.html go (default .cache) ---no-report Write no documents ---all Run every suite, cache or not ---gpu-tests Run every suite, including headless GPU cases ---list List suites and signatures, run nothing ---verbose Name every skipped suite ---jobs N Suites to run at once (default 2; 1 is one after another) -``` - -**Suites run beside each other, and the default is two.** The slowest suites are -the ones that wait: `server.replication` is 35 seconds of a 168-second run and -`server.hostmode` another 12, and nearly all of both is a client ticking in real -time while a spawned server process gets somewhere. That wait cannot be -shortened without breaking what it waits for, and a sleeping suite does not need -a core - so the saving is running them alongside each other. - -Measured on this machine, 24 threads: - -| `--jobs` | Wall clock | Stability | -|---|---|---| -| 1 | 2 min 54 s | the old behaviour | -| 2 | 1 min 36 s | three clean runs | -| 4 | 1 min 11 s | `server.replication` red once in three | - -Two is the default because it is the fastest setting that was not observed to -flake: loading the machine loads the server the tests are waiting for, and a -runner that goes red under its own concurrency is worse than a slow one. Results -are printed in list order rather than completion order, so a run can still be -diffed against another. - -It prints what it skipped, and warns when it had to narrow - no header closure -for a suite, an unknown `TEST_DEPENDS`, a dependency cycle. Those warnings mean -the cascade is covering less than it claims to, so do not ignore them. - -To force a full re-run, either pass `--all` or delete `.cache/smart-tests.txt`. -That file is text: one tab-separated line per suite, so you can also delete a -single line to re-run one thing. - -`just preset=server test` runs the server preset's suites with the server -preset's runner - the preset override reaches `--build` too, so the binaries and -the build directory cannot come from different presets. - -## The report - -Every run writes `.cache/test-output.md` and `.cache/test-output.html`, and -prints both paths. `--list` writes nothing, because it ran nothing. - -Sections are the suite identifiers themselves: `engine.core.arguments` sits -under `engine`, then under `engine.core`, and is a row of its own. There is no -second taxonomy to keep in step with the first. - -Both documents cover **every** suite, not only the ones this invocation ran. A -suite the cascade skipped shows its last known numbers and says `pass (cached)` -in its result column - a green row you cannot tell from a row nothing -re-checked is a green row that lies by omission. The counts and durations behind -those rows live in `smart-tests.txt`, which is why it is at `v2`; a `v1` cache is -discarded on sight rather than reported as a tree of suites holding no tests and -costing no time. - -The numbers come from the test binaries. `mono.build/testmain` registers a -Catch2 reporter named `mono` that writes one tab-separated line per test case, -and the runner asks for it alongside the console reporter - so the output you -read when something goes red is unchanged, and the report is a record of the run -rather than a parse of its console text. You can ask a binary for it directly: - -```sh -./.cache/build/dev/tests/test_core --reporter "mono::out=-" -``` - -Neither document carries a timestamp. Two runs that learned the same thing -produce the same bytes, so a diff shows what moved rather than that it was -written again. - -`ctest` writes no report. It never consults the cache either - see below. - -### Timings - -The runner prints what each suite cost as it goes, and both documents carry the -same numbers - `Time` and `Slowest case` columns in the Markdown tables, and a -flamegraph in the HTML. - -**Two clocks, measuring two different things.** A suite is timed by the runner, -from the outside, so its number includes starting the process and running its -static initialisers. A case is timed by the reporter, from the inside. A suite -is therefore always wider than its cases add up to, and that gap is real: it is -the fixed price of a suite existing, paid once per suite per run. - -That gap is the first thing the report is good for. If `engine.core.arguments` -costs 300 ms and its slowest case costs 29 µs, none of that 300 ms is a test. - -`Time` beside `Slowest case` is the other diagnosis. A slow suite whose slowest -case is most of it is one pathological test; a slow suite whose slowest case is a -fraction of it is a lot of ordinary ones. Those want different fixes. - -### The flamegraph - -`test-output.html` opens with one. Width is wall-clock, depth is the identifier -one component at a time - everything, then `engine`, then `engine.core`, then the -suite, then its cases. Hover a box for its name and what it cost. Widest first, -so what is worth looking at is where you are already looking. - -It is nested `div`s with percentage widths and no script, so it stays -proportional when you resize the window and renders on a machine with no network. - -A suite the cascade skipped is a **leaf** - washed out, with no cases under it. -`smart-tests.txt` is one line per suite, so it keeps a suite's total and not its -breakdown; one line per *case* would be a different file with a different -contract. Run `just test-all` for a graph that goes all the way down. - -## Everything, always - -```sh -cd .cache/build/dev && ctest --output-on-failure -ctest -N # list without running -ctest -R ecs # only suites matching a pattern -``` - -`ctest` never consults the cache. Use it before a pull request - there is no CI -to use it in, and [the `ci` preset](#the-ci-preset-and-the-hook-that-runs-it) -says why; use `just test` in the inner loop. - -## One suite, directly - -Test binaries are ordinary Catch2 executables: - -```sh -./.cache/build/dev/tests/test_ecs # all of it -./.cache/build/dev/tests/test_ecs "a component round-trips" -./.cache/build/dev/tests/test_ecs "[scheduler]" # by tag -./.cache/build/dev/tests/test_ecs -# "[#Store]" # by source file -./.cache/build/dev/tests/test_ecs --help # Catch2's own options -``` - -`-# "[#File]"` is how the runner re-runs exactly one suite, since a suite is one -file. - -They also answer one option Catch2 does not know about: - -```sh -./.cache/build/dev/tests/test_ecs --mono-suites -``` - -which prints `id source dependencies` for each suite it contains. -That listing is how the runner discovers what exists, rather than scanning -sources and hoping a regex holds. - -## The architecture check - -```sh -just test-architecture -``` - -It needs a *configure*, not a build - its input is the `target-graph.json` that -CMake emits. Directly: - -```sh -cmake -DGRAPH=.cache/build/dev/target-graph.json \ - -DEXPECTED=mono.tools/architecture/expected_graph.json \ - -P mono.tools/architecture/CheckTargetGraph.cmake -``` - -This is not what enforces the tier rule - `mono_check_all_tiers` does that at -configure time and fails the build with the offending edge named. This checks -the graph against the checked-in expectation, so that an architectural change -shows up as a diff somebody reviews. - -## The source-text architecture rules - -```sh -just source-check -``` - -The other half of `test-architecture`. That one reads CMake's output, so it can -see the module set, the tiers, the link sets and the layer heights; it cannot -see a member's type, a header's includers, or an argument reaching a writer. -This reads first-party C++ as text and checks the four rules -`docs/CODE_ARCH.md` §11 listed as convention until v0.19: a private copy of data -the ECS owns, a pointer inside a type marked as crossing a world boundary, a -`core::Name` serialized as its `Id()`, and a header under `include/` that -nothing outside its module includes. - -It needs a *build* of one target and nothing else - the tool reads sources, not -objects. Directly, and with `--rule` for one rule at a time: - -```sh -./.cache/build/dev/tools/sourcecheck . # every rule -./.cache/build/dev/tools/sourcecheck . --rule name-id # one of them -./.cache/build/dev/tools/sourcecheck . --verbose # waived findings too -``` - -Three of the four gate. `public-header` reports and never fails: an unwired -subsystem is not dead code, and it currently names 87 of 393 public headers, -twenty-five of them `mono.studio`'s. - -A rule is switched off at one declaration with a comment above it, reason -included - a waiver with nothing after the colon is reported rather than -honoured: - -```cpp -// arch-waiver ecs-copy: composed from N views for one frame out. No world -// holds this camera, because it is not any world's camera. -engine::scene::Camera ComposedCamera; -``` - -`just source-check` runs the fixture trees under -`mono.tools/sourcecheck/tests/fixtures/` before it runs the repository, because -a scanner that read nothing would report success over both. - -## The shader check - -```sh -just shader-check -``` - -Every `.spv` the build produced, against the resource contract -`SDL_CreateGPUShader` documents: one entry point named what the renderer asks -for, at the stage the filename claims; every resource carrying an explicit -`layout(set = ..., binding = ...)`; every resource in the descriptor set SDL -names for its stage; bindings contiguous within a set; and no SPIR-V capability -outside an allowlist of what MSL can express. - -It also reads the translation back. The build writes an `.msl` beside every -`.spv` - `mono.tools/shadercross` runs `Engine::msl` over each one - and this -holds each translation to the module it came from: one entry point, named -`main0` because MSL reserves `main`, qualified for the right stage; the file -structurally well-formed; and every `[[texture]]`, `[[buffer]]` and -`[[sampler]]` index the one SDL's documented order derives. A `.spv` with no -`.msl` beside it is a failure rather than a skip. - -Directly, and without `--quiet`, for the per-shader table - including the -`[[texture(n)]]` or `[[buffer(n)]]` each resource lands on: - -```sh -./.cache/build/dev/tools/shadercheck .cache/build/dev/shaderstage -``` - -One shader by hand, if you want to read what a translation looks like: - -```sh -./.cache/build/dev/tools/shadercross \ - .cache/build/dev/shaderstage/resources/opaque.frag.spv -o /tmp/opaque.frag.msl -``` - -**It says nothing about a Metal device.** There is no Metal compiler here, so -"the MSL is valid" means balanced, prefaced and bound where SDL will look - a -type error inside a function body passes. What it is for is the half of -`docs/DEFERRED.md` D00001 that a machine with no Mac can answer, and that half -is now larger than it was: MSL, DXIL and DXBC all derive their bindings from -those descriptor sets, and the MSL derived from them is on disk to be read. A -`server` or `cdn` preset compiles no shader and the recipe says it skipped -rather than passing quietly. - -## The stress test *(v0.16)* - -Two hundred real clients against one server, and a flamegraph of what the server -spent the tick on. - -```sh -just preset=release stress # 200 clients, 45 seconds -just preset=release stress iter1 200 45 # the next capture, under another name -just preset=release stress quick 50 20 45200 # fewer clients, a different port -``` - -**Run it on `release` or `bench`.** First-party code is `-O0` under every other -preset, so a tick cost measured there is a number about the compiler. The recipe -does not force the preset, for the reason none of them do: the override goes -before the recipe name and applies to everything derived from it. - -It is deliberately not part of `just check`. It takes a minute, its numbers -depend on what else the machine is doing, and a gate that fails because somebody -started a build is a gate people learn to ignore. - -### What it runs - -`mono.tools/loadtest` opens N genuine sessions in **one process** - a UDP socket -each, a real X25519 handshake, a real cookie challenge, a real admission, a -sealed stream and an `ecs::Store` replica the snapshot and every delta are -applied into. It sends a move input every tick once the server has given that -client a character. - -One process rather than N, because `client --headless` still builds a GPU device -and two hundred of those measure the driver rather than the server. The harness -links no `render`, `input`, `audio`, `ui` or `client` - see -`mono.tools/loadtest/CMakeLists.txt`. - -```sh -./.cache/build/release/tools/loadtest --help -./.cache/build/release/tools/loadtest --port 45100 --clients 200 --seconds 45 -``` - -The server it points at is an ordinary `server` with three flags that exist for -this: - -```sh -server --game .cache/build/release/assets/examples/scripts/Stress.luau \ - --listen 45100 --max-clients 216 --profile-out run.folded -``` - -- `--max-clients N` raises `replication::ListenerSettings::MaximumClients`, which - is 64 by default. -- `--profile-out PATH` folds the whole run's frame graph into a `.folded` file. - It turns frame collection on with it, so it is a measurement rather than - something to leave on in a deployment. -- `Stress.luau` is a floor, one spawn and `Players.MaxPlayers = 512` - bare on - purpose, so what is measured is replication rather than scenery. - -### Reading the graphs - -Artefacts land in `.cache/stress/`: - -| File | What it is | -|---|---| -| `