Plan P1 iteration and P3 rendering milestones
Native and manual checks / native (windows-2025) (push) Waiting to run
Native and manual checks / native (ubuntu-24.04) (push) Failing after 32s
Native and manual checks / manual (push) Successful in 27s
Windows editor and software Vulkan / windows-graphics (push) Canceled after 0s

This commit is contained in:
Emil
2026-09-24 01:25:23 +03:00
parent d18c5d77b3
commit bf89ba6f3d
9 changed files with 869 additions and 0 deletions
+17
View File
@@ -0,0 +1,17 @@
# P1 editor visual references
These image prototypes were generated from the recorded native editor screenshot in
`docs/validation/checkpoint5-linux-2026-09-18/editor-blender.png` before changing the
P1 interface. They are visual references for the existing compact dark treatment,
not specifications of behavior, layout measurements, copy, or platform paths.
- `p1-iteration-console-reference.png` explores structured build diagnostics,
source navigation, a cache indicator, and autosave status in the existing editor.
- `p1-project-template-reference.png` explores a compact 2D/3D and C++/Lua project
chooser. Its example Windows path is illustrative; the implementation must use
native paths on Linux and Windows.
Both were created with the built-in image generation tool using the cited screenshot
as the edit reference. The accepted behavior and validation criteria are in the
[P1 design](../superpowers/specs/2026-09-24-p1-iteration-design.md) and
[`PLAN.md`](../../PLAN.md).
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

@@ -0,0 +1,253 @@
# P1 Gameplay Iteration Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Close PLAN P1 with reliable build/schema reuse, useful diagnostics and source navigation, four runnable project starters, safe scene autosave, repeatable iteration evidence, and Linux/Windows Lua validation.
**Architecture:** Keep CMake/Ninja responsible for native dependency analysis and retain immutable last-good build generations. Add a content-checked schema/package cache after native build, normalize diagnostics into the existing job API, run revision-aware autosave in `Session::poll`, and expose all new state through Editor commands shared by GUI and MCP.
**Tech Stack:** C++20, CMake/Ninja, Clang/clang-cl, optional Lua 5.4, SDL3/Vulkan 1.3 for graphical tests, Python 3 for workflow measurements, MkDocs Material.
**Spec:** `docs/superpowers/specs/2026-09-24-p1-iteration-design.md`
## Global Constraints
- Linux and Windows x86-64 desktop 2D/3D are the supported P1 targets; all user-facing Editor copy and Manual pages are English.
- C++ is compiled into the Player; Lua is optional and development reload resets state. No C++ hot reload or dynamic gameplay loading is required.
- MCP addresses Editor authoring/build services, never the live Player world.
- Build and export failures preserve the last successful generation and schema; Debug and Release native trees stay separate.
- CMake/Ninja always run for a requested native build; cache reuse starts only after their success and artifact verification.
- The existing recovery journal protects every authoring transaction; autosave never overwrites a disk conflict or gives an unnamed scene an implicit path.
- The two `docs/design/p1-*-reference.png` images guide visual quality only; `PLAN.md` and the spec define behavior. Paths are cross-platform.
- Keep `BuildService::scaffold(name, dimension)` and `faset_script_open` working for existing callers.
- Before every RED CTest run, register a new named test if needed, reconfigure and rebuild its executable; `ctest --no-tests=error` prevents an empty match from passing.
## Review Focus
- An included project header changes while a build runs: reject the mixed candidate and keep the last-good pointer; Tasks 12 pin this.
- A toolchain executable changes in place while its path remains the same: invalidate the native build tree/package key; Task 1 pins this.
- A valid cached manifest points to a truncated schema or shader: do not return a hit; Task 2 pins this.
- An external editor or another MCP client changes a scene before autosave: never overwrite it or a newer revision; Task 6 pins this.
- A Windows diagnostic contains a drive colon, Unicode directories and a line/column: parse the right location and reject navigation outside `Scripts`; Tasks 34 pin this.
---
### Task 1: Capture complete gameplay inputs and toolchain identity
**Files:** Create `include/faset/editor/build_cache.hpp`, `src/editor/build_cache.cpp`, `tests/build_cache_tests.cpp`; modify `cmake/BuildService.cmake`, `src/editor/build_service.cpp`, `src/editor/session.cpp`.
**Interfaces:** `BuildInputs capture_build_inputs(const BuildConfig&, const scripting::LuaProject&)` records `source_hash` over all regular files under project `Scripts` plus Lua declaration/fingerprint, and separate recipe/toolchain hashes over normalized configure args and executables. `BuildInputs::fingerprint()` combines these fields deterministically. `ensure_native_toolchain_stamp(native_directory, inputs)` forces a fresh native tree if the compiler/CMake/Slang identity changed in place. Extract the common Scripts snapshot so `Session::source_signature()` and `BuildService` use the same content set, while allowing their intended extra fields to differ.
- [ ] **Step 1: Write failing source/identity tests.** In `tests/build_cache_tests.cpp`, construct a temporary project with `Gameplay.cpp`, `Gameplay.hpp` and `Scripts/Extensions/Extra.hpp`; change only the nested header, Lua declaration and then bytes of a fake compiler at the same path. Each change must alter the corresponding fingerprint. A symlink escaping `Scripts` must be rejected. Test the toolchain stamp with a disposable build directory. Register `faset_build_cache_tests` and CTest name `build_cache` in `cmake/BuildService.cmake` before the red run.
```cpp
const auto before = capture_build_inputs(config, lua);
atomic_write(root / "Scripts/Extensions/Extra.hpp", "#define SPEED 2\n");
require(capture_build_inputs(config, lua).fingerprint() != before.fingerprint(),
"Nested gameplay header invalidates the source snapshot");
```
- [ ] **Step 2: Build the red test.** Run `cmake --preset linux-debug`, then `cmake --build --preset linux-debug --target faset_build_cache_tests --parallel 4`. The test target is registered; compilation must fail specifically on the missing `capture_build_inputs` interface, not on an unknown target.
- [ ] **Step 3: Implement the input scanner and toolchain stamp.** Sort project-relative UTF-8 paths, hash file bytes, reject escaping symlinks, include explicit recipe/version values, and hash resolved tool executables. Do not use modification time alone. Compare/persist the stamp before native configure; on a changed stamp clear only the generated native tree for that configuration, never published generations or source files. Replace the narrower two-file post-build race check with the captured complete Scripts snapshot.
```cpp
const auto submitted = capture_build_inputs(config, job.lua);
ensure_native_toolchain_stamp(native_directory, submitted);
// After native build and schema extraction, before publication:
if (capture_build_inputs(config, scripting::loadLuaProject(config.project_root))
.source_hash != submitted.source_hash)
throw std::runtime_error("Gameplay sources changed during the build; build again");
```
- [ ] **Step 4: Rebuild and run focused tests.** Build `faset_build_cache_tests faset_build_schema_tests faset_editor_session_tests`, then run `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^(build_cache|build_schema_publication|editor_session_settings)$'`. All three named tests pass; a changed nested header during the fixture build rejects publication.
- [ ] **Step 5: Commit** `Capture complete gameplay and toolchain build inputs`.
### Task 2: Reuse only verified schema/package generations
**Files:** Modify `include/faset/editor/build_service.hpp`, `src/editor/build_cache.cpp`, `src/editor/build_service.cpp`, `tests/build_cache_tests.cpp`, `tests/build_schema_tests.cpp`, `tests/build_service_tests.cpp`.
**Interfaces:** `build_package_key(inputs, native_directory, configuration)` hashes the post-build Player, SchemaExporter, required SPIR-V/reflection files, runtime libraries and CMake cache. `validate_build_generation(directory, key)` verifies every recorded file hash and validates the schema. Successful `BuildService::build()` returns `schema_cache_hit`, `generation_reused`, `fingerprint`, and phase times without changing existing result paths.
- [ ] **Step 1: Write failing cache and invalidation tests.** The fixture `tests/build_schema_tests.cpp` must count SchemaExporter invocations: two unchanged builds return the same generation and count one export; a changed C++ header, Lua source, configure option, shader bytes or runtime artifact produces a new generation; corrupt or missing cached schema/shader is never a hit. Extend `tests/build_service_tests.cpp` so a failed compile preserves `last_build.json`, and export after changed asset source fails until reimport, then packages the new asset generation despite a gameplay cache hit.
```cpp
const auto first = builds.wait(builds.start_build());
const auto again = builds.wait(builds.start_build());
check(again.result.at("generation") == first.result.at("generation") &&
again.result.at("schema_cache_hit") == true &&
again.result.at("generation_reused") == true,
"Unchanged build reuses a verified generation");
```
- [ ] **Step 2: Run rebuilt red tests.** Build `faset_build_cache_tests faset_build_schema_tests faset_build_service_tests`, then run `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^(build_cache|build_schema_publication|process_and_cook)$'`. At least the newly added cache assertion must fail on missing flags or duplicate schema export; an old binary passing does not count.
- [ ] **Step 3: Implement post-native cache lookup and manifest hashes.** Continue to run configure/build first. Compute the package key, verify the previous generation's manifest/files/schema, then return it without SchemaExporter/copy if valid. Otherwise export schema into staging from the captured Lua snapshot, copy files, write per-file hashes and key, recheck source snapshot, and atomically update `last_build.json`. Never return a damaged generation. Keep the raw job log and phase timing for a hit as well as a miss.
```cpp
if (auto previous = verified_generation(config.cache_root, key))
return result_for(*previous, /*schema_cache_hit=*/true,
/*generation_reused=*/true);
// Only a fully validated staging directory may become last_build.json.
```
- [ ] **Step 4: Rebuild and run focused/integration tests.** Build `faset_build_cache_tests faset_build_schema_tests faset_build_service_tests faset_editor_session_tests`, then run `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^(build_cache|build_schema_publication|process_and_cook|editor_session_settings)$'`. All four pass. Inspect one real no-op build's log: Ninja does no native compile/link; SchemaExporter is absent on the second request. Do not call this a native cache hit unless the log confirms it.
- [ ] **Step 5: Commit** `Reuse verified gameplay schema and build generations`.
### Task 3: Parse structured compiler and Lua diagnostics
**Files:** Create `include/faset/editor/build_diagnostics.hpp`, `src/editor/build_diagnostics.cpp`, `tests/build_diagnostics_tests.cpp`; modify `cmake/BuildService.cmake`, `include/faset/editor/build_service.hpp`, `src/editor/build_service.cpp`.
**Interfaces:** `parse_build_diagnostics(raw_log, phase, project_root)` returns a bounded JSON array of `{severity, phase, message, file?, line?, column?, code?}`. `JobStatus::diagnostics` is serialized by `JobStatus::json()` and returned by `faset_job`; `log` and `error` remain unchanged for old clients.
- [ ] **Step 1: Write failing parser fixtures.** Cover `/project/Scripts/Game.cpp:17:4: error:`, `C:\\Café\\Scripts\\Game.cpp(17,4): error`, `C:\\Café\\Scripts\\Game.cpp:17:4: warning:`, `Scripts/player.lua:6: unexpected symbol`, ANSI escapes, multiline note/caret output, an engine/external path, and a nonzero process with only unparseable text. Assert one-based positive locations and normalized project-relative files only for files under `Scripts`. Register `faset_build_diagnostics_tests` and CTest name `build_diagnostics` in `cmake/BuildService.cmake`.
```cpp
const auto rows = parse_build_diagnostics(
"Scripts/Game.cpp:17:4: error: bad field\n", "compile", project);
require(rows.size() == 1 && rows[0].at("file") == "Scripts/Game.cpp" &&
rows[0].at("line") == 17 && rows[0].at("severity") == "error",
"Clang location is structured");
```
- [ ] **Step 2: Build the red parser test.** Run `cmake --preset linux-debug`, then `cmake --build --preset linux-debug --target faset_build_diagnostics_tests --parallel 4`. Compilation must fail on the missing parser API, not an unknown test target.
- [ ] **Step 3: Implement incremental job collection.** Parse completed log lines as process output arrives, cap row count/message size, strip ANSI, and preserve every raw line in the bounded existing log. Use phase names from `BuildService` checkpoints. On a failed process with no parsed error, add a generic diagnostic with the exit code and `see job log`; never fabricate a navigable file.
```cpp
job.status.diagnostics = parse_build_diagnostics(job.status.log, job.status.stage,
config.project_root);
if (exit_code != 0 && job.status.diagnostics.empty())
job.status.diagnostics.push_back(generic_process_error(exit_code));
```
- [ ] **Step 4: Run parser and real failure tests.** Build `faset_build_diagnostics_tests faset_build_service_tests faset_build_schema_tests`, then run `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^(build_diagnostics|process_and_cook|build_schema_publication)$'`. All three pass; a deliberate `#error` in `Gameplay.cpp` yields both a structured row and the original log, with previous build retained.
- [ ] **Step 5: Commit** `Expose structured gameplay build diagnostics`.
### Task 4: Open project source at a diagnostic location
**Files:** Modify `src/editor/session.cpp`, `src/editor/editor_ui.cpp`, `tests/editor_session_tests.cpp`, `tests/editor_ui_tests.cpp`, `docs/manual/editor/diagnostics.md`.
**Interfaces:** New command `faset_source_open({path, line?, column?, editor?})` validates project code source and opens it with an argv template. Existing `faset_script_open` delegates to the same safe launcher while retaining Lua-only validation. `editor.script_editor` accepts `{file}`, `{line}`, `{column}` and `{project}` tokens. The Console uses Task 3 `diagnostics` and displays cache/timing fields from Task 2.
- [ ] **Step 1: Write failing command/UI tests.** A valid `.cpp` and `.lua` under `Scripts` produce the configured argv with line/column; use a disposable probe executable to record arguments without launching a real editor. A drive/Unicode project path stays one argv element; `../`, symlink escape, directory, `.exe` and nonexistent targets fail with structured `source.*` errors. Clicking a parsed diagnostic issues `faset_source_open` with its location; an external diagnostic has no enabled Open action. Existing `faset_script_open` rejects `.cpp` as before.
```cpp
const auto opened = commands.call("faset_source_open",
{{"path", "Scripts/Gameplay.cpp"}, {"line", 17}, {"column", 4},
{"editor", {path_to_utf8(probe_executable), "{file}:{line}:{column}"}}});
require(opened.at("line") == 17 && opened.at("path") == "Scripts/Gameplay.cpp",
"Project source opens at the diagnostic position");
```
- [ ] **Step 2: Run rebuilt red command/UI tests.** Build `faset_editor_session_tests faset_editor_ui_tests`, then run `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^(editor_session_settings|editor_ui_authoring)$'` with the configured Vulkan ICD. At least the new source-open assertion must fail; a missing GPU or old binary is not the intended red result.
- [ ] **Step 3: Implement the safe source launcher and Console action.** Use `project_path` and extension/regular-file checks, exact argv substitution with no shell, and Zed's verified `path:line:column` default. Keep raw output expandable, show severity/file/line first, and expose a clear editor-launch error without changing build state. Make rows keyboard reachable and update the English diagnostics Manual.
```cpp
commands_.add("faset_source_open", description, source_schema,
[&](const Json& args) { return open_project_source(args, /*lua_only=*/false); });
// UI: call("faset_source_open", {{"path", row.at("file")},
// {"line", row.value("line", 1)}});
```
- [ ] **Step 4: Run focused tests with software Vulkan for UI.** Rebuild `faset_editor_session_tests faset_editor_ui_tests`, then run `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^(editor_session_settings|editor_ui_authoring)$'` on an equipped GPU/software ICD. Both pass; `faset_job` JSON still exposes raw log and normalized rows headlessly.
- [ ] **Step 5: Commit** `Navigate from build diagnostics to project source`.
### Task 5: Four runnable C++/Lua new-project choices
**Files:** Modify `include/faset/editor/build_service.hpp`, `src/editor/build_service.cpp`, `include/faset/editor/project_launcher.hpp`, `src/editor/project_launcher.cpp`, `apps/editor_main.cpp`, `tests/build_service_tests.cpp`, `tests/editor_ui_launcher.cpp`; create `tools/project_templates/lua-main.lua`; update `docs/manual/getting-started/build.md`.
**Interfaces:** New overload `BuildService::scaffold(name, dimension, language)` accepts `cpp|lua` and creates a runnable template; the legacy two-argument call retains its existing C++ scaffold behavior without implicitly creating a scene. `ProjectSelection::language` and `faset_editor --new NAME --dimension 2|3 --language cpp|lua` select the same templates. Explicit template creation adds a minimal `Scenes/main.scene.json`; Lua-only templates receive a declared `Scripts/main.lua` without `Gameplay.cpp/.hpp`.
- [ ] **Step 1: Write failing scaffold/launcher tests.** Create all four explicit combinations under disposable Unicode project paths. Assert dimension/language, scene validity, declared Lua schemas, no C++ stub in Lua projects, ability to `--validate` or launch a built Player, and that existing files are never overwritten. Test legacy `scaffold(name, dimension)` still creates C++ without unexpectedly creating a scene.
```cpp
builds.scaffold("Lua 2D", 2, "lua");
require(fs::exists(root / "Scripts/main.lua") &&
!fs::exists(root / "Scripts/Gameplay.cpp"),
"Lua starter is genuinely Lua-only");
```
- [ ] **Step 2: Run rebuilt red tests.** Build `faset_build_service_tests faset_project_launcher_tests`, then run `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^(process_and_cook|editor_ui_launcher)$'` with the configured Vulkan ICD. Compilation or a new assertion must fail specifically on language selection; old binaries or a missing GPU do not establish red.
- [ ] **Step 3: Add starter files and cross-platform chooser.** Generate the start scene from authoring schema helpers; use source templates for behavior text and LuaLS defaults; reject an existing conflicting destination before writing any starter file. Maintain the dark Editor style, keyboard selection and platform-native path display. The PNG reference guides layout only. Extend CLI help and Manual with exact commands.
```cpp
void BuildService::scaffold(const std::string& name, int dimension,
std::string_view language);
// Existing two-argument overload keeps the legacy scaffold without a scene.
```
- [ ] **Step 4: Run focused and real template builds.** Rebuild `faset_build_service_tests faset_project_launcher_tests faset_player`, then run `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^(process_and_cook|editor_ui_launcher|lua_cli_contracts)$'` with the configured Vulkan ICD. All three pass; build/validate one generated C++ and one generated Lua project for each dimension.
- [ ] **Step 5: Commit** `Offer runnable C++ and Lua project starters`.
### Task 6: Revision-aware autosave controller and MCP status
**Files:** Create `include/faset/editor/autosave.hpp`, `src/editor/autosave.cpp`, `tests/editor_autosave_tests.cpp`; modify `CMakeLists.txt`, `include/faset/authoring/service.hpp`, `src/authoring/service.cpp`, `src/editor/commands.cpp`, `include/faset/editor/session.hpp`, `src/editor/session.cpp`.
**Interfaces:** `AuthoringService::save(document, path={}, expected_revision=std::nullopt)` rejects a stale expected revision. `AutosaveController` takes `SaveFn = std::function<Json(const std::string&, std::uint64_t)>` in its constructor; `observe(documents, now, enabled)` tracks each document's revision/idle deadline and invokes that callback after 2 seconds. `Session::poll()` calls it in both GUI and long-lived MCP modes. Read-only `faset_autosave_status` returns per-document `state`, `revision`, `path`, `error` and enabled flag.
- [ ] **Step 1: Write failing fake-clock and authoring tests.** Coalesce three edits within 2 seconds into one save; unnamed dirty scene stays in recovery; disabling autosave leaves only recovery; an external disk edit fails with `save.disk_conflict`; a newer revision fails with `revision.conflict` then gets a new deadline; a permission/write error remains visible without frame-by-frame retries; Undo after save still restores the prior scene; a Play snapshot captured before autosave remains byte-identical. Register `faset_editor_autosave_tests` and CTest name `editor_autosave` in `CMakeLists.txt`.
```cpp
service.transact(id, revision, rename_ops);
controller.observe(service.documents(), start + 1900ms, true);
require(read_json(scene_path).at("name") == "Before", "Idle timer has not fired");
controller.observe(service.documents(), start + 2100ms, true);
require(read_json(scene_path).at("name") == "After", "Named scene autosaved once");
```
- [ ] **Step 2: Build the red autosave test.** Run `cmake --preset linux-debug`, then `cmake --build --preset linux-debug --target faset_editor_autosave_tests --parallel 4`. Compilation must fail on the missing controller/revision-aware save API, not an unknown target.
- [ ] **Step 3: Implement deterministic scheduling and status.** Use monotonic time injected into the controller, reset deadline only when revision changes, save with expected revision, suppress identical failure repeats until another edit or explicit retry, and never assign a path to an unnamed scene. Keep recovery journaling and disk-hash guard unchanged. Add `expected_revision` as an optional JSON field to `faset_document_save`; preserve existing callers.
```cpp
if (summary.at("dirty") && !summary.at("path").get<std::string>().empty() &&
now >= state.deadline)
authoring.save(id, {}, state.observed_revision);
```
- [ ] **Step 4: Run authoring/session/MCP tests.** Rebuild `faset_authoring_tests faset_editor_autosave_tests faset_editor_session_tests faset_mcp_tests faset_editor`, then run `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^(authoring|editor_autosave|editor_session_settings|editor_mcp|editor_mcp_stdio)$'`. All five pass; a headless MCP session that stays open autosaves a named scene after idle.
- [ ] **Step 5: Commit** `Autosave named scenes with revision and disk conflict safety`.
### Task 7: Autosave settings and visible Editor state
**Files:** Modify `src/editor/session.cpp`, `src/editor/editor_ui.cpp`, `tests/editor_session_tests.cpp`, `tests/editor_ui_project_settings.cpp`, `tests/editor_ui_tests.cpp`, `docs/manual/editor/workspace.md`, `docs/manual/editor/mcp.md`.
**Interfaces:** `project.faset.json` may contain `editor.autosave: bool`, defaulting to `true`; `faset_project_settings_set` updates that property with its existing project revision check, applies it immediately to the current session and preserves `editor.script_editor`. Project settings provide an Autosave toggle. Status bar maps `faset_autosave_status` to Saved, Pending autosave, Saving, Save conflict, Save failed and Save As required. `Session` caches the setting and updates it on the command rather than rereading the project file every polling frame.
- [ ] **Step 1: Write failing settings/UI tests.** Missing setting reads as enabled; toggling off/on survives project reopen and does not change `editor.script_editor`; stale settings revision is rejected; UI shows pending then saved after a deterministic tick, conflict persists with Save As/reload guidance, unnamed dirty scene shows Save As required. Keyboard focus reaches the toggle and conflict action.
```cpp
auto settings = commands.call("faset_project_settings_get", Json::object());
auto changed = commands.call("faset_project_settings_set",
{{"revision", settings.at("revision")},
{"settings", {{"editor", {{"autosave", false}}}}}});
require(changed.at("settings").at("editor").at("autosave") == false,
"Project autosave preference persists");
```
- [ ] **Step 2: Run rebuilt red tests.** Build `faset_editor_session_tests faset_editor_project_settings_ui_tests faset_editor_ui_tests`, then run `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^(editor_session_settings|editor_ui_project_settings|editor_ui_authoring)$'` with the configured Vulkan ICD. At least the new settings/status assertion must fail for the expected behavior.
- [ ] **Step 3: Implement settings validation and UI.** Merge only the `editor.autosave` field into existing `editor` settings; reject non-Boolean values. Poll the read-only status instead of inferring save from dirty flags. Keep the dark compact reference style while making actual status and actions correct; document autosave vs recovery and MCP explicit save.
```cpp
require(changes["editor"]["autosave"].is_boolean(), "project.autosave",
"Autosave must be enabled or disabled");
value["editor"]["autosave"] = changes["editor"]["autosave"];
```
- [ ] **Step 4: Run UI and Manual checks.** Rebuild `faset_editor_session_tests faset_editor_project_settings_ui_tests faset_editor_ui_tests`, then run `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^(editor_session_settings|editor_ui_project_settings|editor_ui_authoring)$'` with the configured Vulkan ICD; all three pass. `python3 -m mkdocs build --strict` from the documentation virtual environment passes. Capture one Editor screenshot to inspect legibility; the image reference is not a pixel-perfect target.
- [ ] **Step 5: Commit** `Show and configure safe Editor autosave`.
### Task 8: Windows and Release Lua execution evidence
**Files:** Create `tools/verify_lua_release_export.py`, `tests/verify_lua_release_export_test.py`; modify `.github/workflows/ci.yml`, `.github/workflows/windows-graphics.yml`; update `docs/validation/lua-module.md` after results exist. `lua_player_reload` is already registered in `cmake/Player.cmake`.
**Interfaces:** The verifier copies `examples/lua` to a disposable Unicode project path, exports a Release Lua-only package with the real Editor, relocates the generation, hides the source project, runs `--validate` and 120 headless rendered frames, and writes a JSON report containing exact revision/build profile/VM presence/source hashes/device/driver/capture hash. It never modifies the checked-in sample.
- [ ] **Step 1: Write failing verifier contract tests.** In `tests/verify_lua_release_export_test.py`, import the verifier's package/report validator and test that it rejects a package containing project `Gameplay.cpp`, a missing declared Lua source, a package that only works with the source project present, or fewer than 120 rendered frames. Its report must distinguish physical GPU and software Vulkan.
```python
assert report["configuration"] == "Release"
assert report["lua_enabled"] is True
assert report["relocated"] is True
assert report["rendered_frames"] == 120
```
- [ ] **Step 2: Run and implement the verifier.** Run `python3 -m unittest discover -s tests -p 'verify_lua_release_export_test.py' -v`; confirm it discovers at least four tests and fails on the absent verifier API. Implement the disposable-project export/relocation/validation/frame runner and report validator in `tools/verify_lua_release_export.py`, then rerun the same test until it passes. Run the verifier on Linux with the real Release Editor and record its exact output. A deliberately incomplete disposable package must still be rejected.
```sh
python3 tools/verify_lua_release_export.py --editor build/linux-release/faset_editor --output .cache/p1-lua-release-check
```
- [ ] **Step 3: Run actual platform jobs.** Linux native CI runs existing Lua CPU tests; Windows native CI runs them without a GPU. Windows graphics CI runs `lua_player_reload` under its pinned SwiftShader ICD and the Release export verifier. Run the same verifier on Linux with a real GPU when available; exact commands and environment go in the report. A failed CI job is not described as covered. Keep `FASET_ENABLE_LUA=OFF` for C++-only projects, preserve Lua source snapshot hashing, and package required notices; any observed integration defect gets a failing regression before its fix.
```sh
ctest --test-dir build/linux-release --no-tests=error --output-on-failure -R '^(lua_contracts|lua_safety_contracts|lua_cli_contracts|lua_player_reload|build_schema_publication)$'
```
- [ ] **Step 4: Store exact evidence and update the Lua record.** Include CI run links, `ctest` totals, report JSON, renderer/driver details and honest unsupported-hardware notes. A functional Windows SwiftShader result is not a physical-Windows-GPU claim.
- [ ] **Step 5: Commit** `Validate Lua gameplay in Windows and Release exports`.
### Task 9: Measure iteration and close P1 documentation
**Files:** Modify `tools/measure_workflows.py`, `docs/manual/editor/export.md`, `docs/manual/editor/profiling.md`, `docs/manual/scripting/lua.md`, `docs/manual/scripting/first-behavior.md`, `docs/ARCHITECTURE.md`, `docs/IMPLEMENTATION.md`, `PLAN.md`; create `tests/measure_workflows_test.py`, `docs/validation/p1-iteration-2026-09-24/README.md` and raw evidence files.
**Interfaces:** Workflow report version 2 retains raw samples with labels and adds median/nearest-rank p95, exact host/toolchain/driver/revision/source-hash metadata, separate cold and warm paths, changed C++ and Lua-to-reload time, Play-to-first-rendered-frame, synthetic Editor input-to-visible-state latency, and a larger generated scene. Timing values are observations, not CI pass/fail thresholds.
- [ ] **Step 1: Write failing report/math tests.** With sample durations `[1, 2, 3, 4, 5]`, median is 3 and nearest-rank p95 is 5; the report rejects an absent revision, mixed Debug/Release samples under one label, missing source hashes, and a sample labeled windowed first frame when the Player profile says `presentation_mode=offscreen`. Fixture generation must be deterministic from a seed.
```python
assert summarize([1, 2, 3, 4, 5]) == {"median": 3, "p95": 5}
assert len(report["samples"]["warm_unchanged_build"]) >= 5
```
- [ ] **Step 2: Run the red Python test.** `python3 -m unittest discover -s tests -p 'measure_workflows_test.py' -v` discovers at least four tests and fails on the missing summary/report behavior before implementation; a zero-test run does not count.
- [ ] **Step 3: Extend the disposable-project workflow and Manual.** Keep raw stdout/stderr and per-run JSON, warm up then repeat each warm/changed case at least five times, record toolchain/GPU/driver and validation/readback settings, and compare reference budgets only for the exact checked-in sample scenes. Measure a 3,000-frame resource-lifecycle run and report explicit memory growth. Document C++/Lua iteration, cache flags, source navigation, templates, autosave/conflict recovery and profile interpretation in English.
```python
def summarize(values):
ordered = sorted(values)
return {"median": statistics.median(ordered),
"p95": ordered[math.ceil(0.95 * len(ordered)) - 1]}
```
- [ ] **Step 4: Run full validation and record dated evidence.** `ctest --preset linux-debug --no-tests=error --output-on-failure`, `ctest --test-dir build/linux-release --no-tests=error --output-on-failure`, available Linux GPU tests, Windows native/SwiftShader CI, `python3 -m mkdocs build --strict` from the documentation virtual environment and the workflow script pass or have exact documented failures. Update `PLAN.md` to P1 complete only after every acceptance-matrix row in the spec has evidence; physical Windows GPU remains marked unverified if unavailable. Run `graphify update .` after code changes where `graphify-out/graph.json` exists, then request independent review and fix load-bearing findings.
- [ ] **Step 5: Commit** `Measure and document P1 gameplay iteration`; publish only after required checks and review are complete.
@@ -0,0 +1,213 @@
# P3 Lighting and Shadows Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Deliver PLAN P3's multi-light shading, four-cascade sun shadows, bounded point/spot shadow atlas, independent shadow-view visibility, explicit budgets and diagnostics, and a measured Forward+ decision.
**Architecture:** An immutable `Snapshot` carries one sun, local lights, and an unjittered camera frustum from scene extraction. Both Direct and P2 GPU graphics paths use the existing material set 0 and shared `fragmentMain`, a new lighting set 1, and, only for P2 GPU vertices, scene set 2. CPU shadow planning produces atomic sun/spot/point views and caster lists; Vulkan renders those views into two bounded D32 atlases before forward shading. Temporal reconstruction has a separate plan.
**Tech Stack:** C++20, Vulkan 1.3 dynamic rendering, Slang/SPIR-V and Faset reflection v1, CMake/Ninja, SDL3, Catch-style existing C++ test executables, Python measurement scripts, MkDocs Material.
**Spec:** `docs/superpowers/specs/2026-09-24-p3-lighting-design.md`
## Global Constraints
- Linux and Windows desktop 3D; exported Player remains independent of Slang, Editor, and MCP.
- Preserve selectable Direct, GPU frustum, and GPU occlusion paths and their equivalent opaque lighting.
- Preserve material descriptor set 0 bindings 03; add lighting set 1; move GPU graphics scene bindings to set 2; leave GPU compute sets unchanged.
- Preserve 96-byte baseline and 112-byte GPU graphics push constants; no optional Vulkan feature may be assumed without a capability check.
- Sun atlas: four 1024² tiles in 2048² D32; local atlas: sixteen 512² tiles in 2048² D32; fallback to half resolution or explicitly unshadowed lighting.
- At most 128 submitted local lights, sixteen local shadow faces, and 4096 caster draws per frame. Overflow is deterministic and visible; a skipped view is entirely unshadowed.
- Shadow caster selection is independent of camera/P2 culling and camera-selected mesh LOD. No incomplete point-light cubemap.
- Sun shadows use unjittered camera data; lighting work must not mutate velocity/TAA history owned by the temporal plan.
- Register each new CTest case before its red run; verify it appears in `ctest --test-dir build/linux-debug -N`, use `--no-tests=error` with exact `-R` names, and treat an absent build target as a failed setup rather than a passing test.
## Review Focus
- A distant, offscreen caster overlapping a visible receiver's sun cascade must still cast a shadow; Task 3's CPU test and Task 4's GPU fixture pin this.
- A point light with fewer than six free atlas tiles must be fully unshadowed, never show partial faces; Task 3's scheduler test and Task 5's image case pin this.
- A view exceeding the caster draw budget must not render only some casters; Task 3's budget test and Task 5's overflow image pin this.
- A material with no local lights, including UI/sprite pixels, must not read an uninitialized storage descriptor or change tint; Tasks 2 and 4 pin this.
- Shader hot reload with a changed light-buffer stride/binding must reject the candidate and retain the displayed frame; Task 2 pins this.
---
## File map and integration order
`include/faset/render/renderer.hpp` owns public light/camera snapshot fields and statistics. New `include/faset/render/lighting.hpp` and `src/render/lighting.cpp` own pure CPU split, shadow-view, tile-allocation, caster-culling, and budget policy, independently testable without Vulkan. `src/player/SceneView.cpp` and `src/authoring/schema.cpp` translate version-1 authoring fields into those typed records. `shaders/baseline.slang`, `shaders/gpu_scene.slang`, `src/render/shader_contract.cpp`, and `src/render/renderer.cpp` own the exact graphics ABI and Vulkan implementation. `src/editor/debug_overlay.cpp`, Player diagnostics, the Manual, and validation studies consume statistics after rendering.
Tasks 13 define the shared interfaces. Integrate Task 2's descriptor ABI before concurrent temporal shader changes; Tasks 45 then implement Vulkan shadow rendering. The temporal plan may proceed independently in its own files, but `renderer.hpp`, `renderer.cpp`, and `baseline.slang` changes must be sequenced or reconciled with a focused Direct/P2/temporal regression pass. Make a checkpoint commit after every green task; do not mark P3 complete until the acceptance record exists.
### Task 1: Authoring schema and typed light extraction
**Files:** Modify `include/faset/render/renderer.hpp`, `src/authoring/schema.cpp`, `src/player/SceneView.cpp`, `tests/authoring_tests.cpp`, `tests/runtime_player_tests.cpp`, and relevant Manual authoring examples.
**Interfaces:** Introduce `SunLight { stable_id, direction, color, intensity, casts_shadow }`, `LocalLight { Kind::Point|Spot, stable_id, position, direction, color, intensity, range, inner_angle, outer_angle, casts_shadow, shadow_priority }`, and `CameraFrustum { view, projection, near_plane, far_plane, perspective }`. Add `std::optional<SunLight> Snapshot::sun`, `std::vector<LocalLight> Snapshot::local_lights`, and `std::optional<CameraFrustum> Snapshot::camera_frustum` after existing aggregate fields; retain `Snapshot::light_direction`. `SceneView::build` fills camera data for 3D scenes and picks the first enabled directional by stable ID.
- [ ] **Step 1: Write failing schema/extraction tests.** Construct a version-1 scene with directional, point, and spot entities in one order and reversed order. Assert all local IDs/properties agree; authored sun color/intensity are preserved; no-light scene retains the default legacy sun; extra directionals emit a diagnostic; invalid `range <= 0`, `inner_angle > outer_angle`, nonfinite color/transform, and unknown kind identify the entity/field. An essential assertion is:
```cpp
auto a = view.build(scene_with_three_lights(), 16.f / 9.f);
auto b = view.build(reordered_scene_with_three_lights(), 16.f / 9.f);
check(a.local_lights.size() == 2 && b.local_lights.size() == 2,
"Point and spot lights survive scene extraction");
check(a.local_lights[0].stable_id == b.local_lights[0].stable_id,
"Light ordering follows stable IDs, not entity array order");
```
- [ ] **Step 2: Run the focused tests red.** Run `cmake --preset linux-debug` and `cmake --build --preset linux-debug --target faset_authoring_tests faset_player_tests --parallel 4`; missing typed fields should fail compilation. If compilation succeeds, `ctest --test-dir build/linux-debug --output-on-failure --no-tests=error -R '^(authoring|player_scene_contracts)$'` must fail on a new behavioral assertion. Record the expected failure rather than assuming the build itself must be red.
- [ ] **Step 3: Add schema defaults and extraction.** Keep builtin version 1; use `fields.value` for additive fields, normalize directions after the world transform, validate finite/color/range/cone values, sort by stable ID, and preserve the legacy fallback. Set `camera_frustum` from the same unjittered view/projection used to form `view_projection`. Update direct C++ API examples to construct one point and one spot light.
```cpp
struct CameraFrustum {
Mat4 view{identity}, projection{identity};
float near_plane{0.1f}, far_plane{1000.f};
bool perspective{true};
};
// Snapshot::light_direction remains available to callers without Snapshot::sun.
```
- [ ] **Step 4: Run focused tests green.** `ctest --test-dir build/linux-debug --output-on-failure -R '^(authoring|player_scene_contracts)$'` passes, including old version-1 scenes and exported-scene decoding.
- [ ] **Step 5: Commit** `Expose authored sun, point, and spot lights in render snapshots`.
### Task 2: Shared lighting shader ABI and unshadowed local PBR
**Files:** Modify `shaders/baseline.slang`, `shaders/gpu_scene.slang`, `src/render/shader_contract.cpp`, `src/render/renderer.cpp`, `include/faset/render/renderer.hpp`, `tests/test_shader_reflection.py`, `tests/render_gpu_shader_contract_tests.cpp`, `tests/render_reload_tests.cpp`, `tests/render_tests.cpp`, `cmake/Renderer.cmake` if a new CPU-only ABI target is useful.
**Interfaces:** Keep set 0 bindings 03 and `Push`/`ScenePush` sizes. Define set 1 bindings 0=`StructuredBuffer<LightingHeader>` (one record), 1=`StructuredBuffer<LocalLightGpu>` (minimum one allocated record even when count zero), 2=`StructuredBuffer<ShadowViewGpu>` (minimum one record), 3=`Texture2D<float>` local atlas. `LightingHeader` is five 16-byte lanes (counts/flags, sun direction+intensity, sun color, camera forward+shadow distance, four split depths); `LocalLightGpu` is five 16-byte lanes (position+range, direction+cosOuter, color+intensity, cone/type/shadow-view indices, reserved); `ShadowViewGpu` is seven 16-byte lanes (matrix, tile scale/offset, guarded clamp, bias/flags). GPU vertex buffers move to set 2 bindings 02. Put host mirrors in `src/render/renderer.cpp` with exact `static_assert` size/offsets and validate Slang element strides in reflection. These 80/80/112-byte records are renderer ABI, not scene-file schema.
- [ ] **Step 1: Write failing ABI and image tests.** Extend the existing registered `render_shader_reflection`, `render_gpu_shader_contract`, `render_shader_reload`, and `render_offscreen` cases; do not rely on an unregistered new test. Assert exact set/binding/type/stride for baseline fragment and GPU vertex entries; corrupt a lighting stride or GPU set number in a copied reflection file and require validation rejection. Render a zero-local-light scene with unchanged sprite/UI tint; place red and blue point lights at different ranges and assert the correct receiver regions brighten without NaNs. Run in Direct and GPU frustum modes.
```python
fragment = json.loads((shader_dir / "fragmentMain.reflection.json").read_text())
gpu_vertex = json.loads((shader_dir / "gpuVertexMain.reflection.json").read_text())
assert next(d for d in fragment["layout"]["descriptors"]
if (d["set"], d["binding"]) == (1, 1))["element_stride"] == 80
assert next(d for d in gpu_vertex["layout"]["descriptors"]
if (d["set"], d["binding"]) == (2, 0))["element_stride"] == 224
```
- [ ] **Step 2: Run focused tests red.** Reconfigure and build the modified test targets, then run `ctest --test-dir build/linux-debug --output-on-failure --no-tests=error -R '^(render_shader_reflection|render_gpu_shader_contract|render_shader_reload|render_offscreen)$'`. The new ABI assertion or the point/spot fixture inside `render_offscreen` must reject missing set 1/2 behavior. Confirm all four expected cases in `ctest --test-dir build/linux-debug -N`.
- [ ] **Step 3: Implement the checked ABI and shading.** Allocate/bind one frame lighting set in Direct and GPU graphics pipelines; update shader contracts and P2 graphics set indices only. Accumulate each direct-light BRDF in linear RGB before tone mapping; keep the zero-normal UI/sprite early return. Use finite-safe inverse-square-like distance attenuation with smooth range cutoff and a smooth spot cone. Keep sun/default image reference close to the old baseline. Reject incompatible runtime shader reload while preserving previous pipelines.
```slang
[[vk::binding(0,1)]] StructuredBuffer<LightingHeader> lightingFrame;
[[vk::binding(1,1)]] StructuredBuffer<LocalLightGpu> localLights;
[[vk::binding(2,1)]] StructuredBuffer<ShadowViewGpu> shadowViews;
[[vk::binding(3,1)]] Texture2D<float> localShadowAtlas;
// GPU scene vertex descriptors change from binding(*,1) to binding(*,2).
```
- [ ] **Step 4: Rebuild shaders and run reflection, reload, offscreen, and Direct/P2 image tests green.** `cmake --build --preset linux-debug --target faset_shaders faset_render_tests faset_render_gpu_shader_contract_tests faset_render_reload_tests --parallel 4`; then the focused `ctest` regex above and `ctest --test-dir build/linux-debug -L p2 --output-on-failure`. Check zero Vulkan validation errors.
- [ ] **Step 5: Commit** `Share typed multi-light shading across Direct and GPU paths`.
### Task 3: Pure CPU shadow planning, caster visibility, and capacity policy
**Files:** Create `include/faset/render/lighting.hpp`, `src/render/lighting.cpp`, `tests/render_lighting_policy_tests.cpp`; modify `cmake/Renderer.cmake` and `src/render/renderer.cpp` only to call the policy after it is tested.
**Interfaces:** `build_shadow_plan(const Snapshot&, std::span<const ShadowCasterBounds>, ShadowBudget) -> ShadowPlan` returns ordered `ShadowView` records (sun cascade 03, spot one, point six), stable tile indices, caster indices, per-view update reason, requested/effective counts, and dropped-reason counters. `ShadowBudget` defaults to four sun views, sixteen local tiles, 4096 caster draws, 128 local lights, and 2048² atlas dimensions. `ShadowCasterBounds` contains source-mesh world AABB and draw index. No Vulkan handle enters this module.
- [ ] **Step 1: Write and register failing policy tests.** Add `faset_render_lighting_policy_tests` and `add_test(NAME render_lighting_policy ...)` in `cmake/Renderer.cmake`. Assert practical split endpoints are increasing and end at `min(far,80)`; translating a camera by less than one cascade texel keeps the snapped projection origin fixed; a caster outside camera view but upstream of a receiver is included; a caster outside the shadow XY footprint is excluded. Fill 15 local tiles, then request one point light and assert no faces are scheduled while the light remains in the submitted lighting list with shadow validity false. Give a shadow view 4097 casters and assert it is skipped whole. Reverse input light order and assert allocations are unchanged.
```cpp
auto plan = build_shadow_plan(snapshot, casters, ShadowBudget{});
require(plan.sun_views.size() == 4, "Explicit camera gets four cascades");
require(plan.local_faces_used <= 16 && plan.caster_draws <= 4096,
"Shadow work stays within the configured budget");
require(plan.dropped_point_faces == 6 || plan.dropped_point_faces == 0,
"Point shadow allocation is all-or-none");
```
- [ ] **Step 2: Run policy test red.** Reconfigure, verify `render_lighting_policy` appears in `ctest --test-dir build/linux-debug -N`, build `faset_render_lighting_policy_tests`, then run `ctest --test-dir build/linux-debug --output-on-failure --no-tests=error -R '^render_lighting_policy$'` if compilation succeeds. Expected failure is the absent `lighting.hpp` interface or the first failing new assertion.
- [ ] **Step 3: Implement the planner.** Use unjittered frustum corners and fixed λ=0.5 splits, enclosing-sphere square extents, two-texel guard, texel-snapped light XY, and conservative caster-derived light Z. Sort by explicit priority, projected influence, and stable ID. Choose entire views under tile/draw limits; never reuse an old tile if its owner/generation changes. Legacy Snapshot without `CameraFrustum` produces one reported sun view. If no atlas profile is usable, return an unshadowed plan with a reason.
```cpp
ShadowPlan build_shadow_plan(const Snapshot& frame,
std::span<const ShadowCasterBounds> casters,
const ShadowBudget& budget);
```
- [ ] **Step 4: Run focused policy and P2 visibility tests green.** `ctest --test-dir build/linux-debug --output-on-failure -R 'render_lighting_policy|visibility_policy|render_gpu_shadow'`. Preserve P2's offscreen caster fixture.
- [ ] **Step 5: Commit** `Plan stable cascades and bounded shadow views independently of camera culling`.
### Task 4: Vulkan sun atlas and cascade sampling
**Files:** Modify `src/render/renderer.cpp`, `shaders/baseline.slang`, `tests/render_tests.cpp`, `tests/render_gpu_acceptance_tests.cpp`; create `tests/render_lighting_gpu_tests.cpp` and register `render_lighting_sun` as `gpu;p3` in `cmake/Renderer.cmake` or a focused `cmake/LightingAcceptance.cmake`.
**Interfaces:** `ShadowPlan::sun_views` supplies four 1024² tile viewports and matrices to one `ShadowAtlases` RenderGraph pass. `LightingHeader` and `ShadowViewGpu` provide split depths, tile transforms, and valid flags to `fragmentMain`; set 0 binding 0 points to the sun atlas. `FrameStats` reports requested/effective cascade count, sun tiles, caster draws, atlas bytes, and aggregated `gpu_sun_shadow_ms`.
- [ ] **Step 1: Write and register failing sun image tests.** Register `render_lighting_sun` with `LABELS "gpu;p3"` in CMake before its red run. Make a receiver cross the first two split distances; require shadow continuity across the blend band. Move the camera by subtexel and whole-texel steps; require stable then updated shadow edges. Move/disable an upstream offscreen caster and require affected receiver pixels to change. Assert four effective cascades for explicit camera and one reported fallback for a legacy low-level Snapshot. Run Direct and GPU frustum; compare the final frames within the existing P2 image tolerance.
```cpp
require(renderer.stats().effective_sun_cascades == 4,
"Explicit 3D camera uses four sun cascades");
std::size_t darker = 0;
for (std::size_t i = 0; i < with_caster.size(); i += 4)
darker += without_caster[i] > with_caster[i] + 12;
require(darker > 20, "Offscreen caster affects a visible cascade receiver");
```
- [ ] **Step 2: Run new GPU test red.** Reconfigure, verify `render_lighting_sun` appears in `ctest --test-dir build/linux-debug -N`, and build its test executable. Run `ctest --test-dir build/linux-debug --output-on-failure --no-tests=error -R '^render_lighting_sun$'`; an old single fixed shadow projection must fail the new count/image assertions. A missing target is setup failure, not green.
- [ ] **Step 3: Render and sample the sun atlas.** Check D32 sampled/depth-attachment format support and image limits; allocate 2048² or 1024² fallback. Transition to depth attachment once, loop tile rendering with per-tile `renderArea`, clear, viewport and scissor, push each matrix, draw only that view's caster list; transition once to depth read-only. Map projected XY into guarded tile UV, clamp every PCF tap, apply slope-aware bias, choose/blend cascades from unjittered depth. When recreating the atlas, rewrite set-0 binding 0 for every live material descriptor before retiring the old image view. Increase the fixed timestamp query capacity before adding pass labels so aggregate timing does not silently disappear.
```cpp
graph.add("ShadowAtlases", {}, {"sun_shadow", "local_shadow"}, [&] {
// For each scheduled view: clear only its renderArea, set tile viewport/scissor,
// push its view_projection, draw exactly plan.caster_indices.
});
```
- [ ] **Step 4: Run sun, existing shadow, reload, P2, and Vulkan validation tests green.** `ctest --test-dir build/linux-debug --output-on-failure -R 'render_lighting_sun|render_offscreen|render_shader_reload|render_gpu_shadow'` and the full `-L p2` suite. Save difference frames before adjusting any threshold.
- [ ] **Step 5: Commit** `Render stable cascaded sun shadows into a bounded atlas`.
### Task 5: Point/spot atlas, face scheduling, and observability
**Files:** Modify `src/render/renderer.cpp`, `shaders/baseline.slang`, `src/editor/debug_overlay.cpp`, Player profile/diagnostics source, `include/faset/render/renderer.hpp`, `tests/render_lighting_gpu_tests.cpp`, `tests/editor_debug_overlay.cpp`, `tests/player_diagnostics_test.py`, and acceptance CMake registration.
**Interfaces:** `ShadowPlan::local_views` supplies one spot or six point faces per assigned light. The shader resolves a point face from the dominant light-to-fragment axis and samples only a valid assigned tile. `FrameStats`/Player/editor expose submitted and omitted local lights, requested and effective faces, tile occupancy, dropped-reason counts, caster draws, atlas bytes, shadow GPU time, and actual lighting path. The common fallback is unshadowed local lighting.
- [ ] **Step 1: Write and register failing image/diagnostic tests.** Register `render_lighting_local` with `LABELS "gpu;p3"`; extend existing Player diagnostics assertions. A spotlight lights inside its outer cone but not outside; a point light lights six cube-face directions and has no seam-caused bright leak at a face boundary. A caster darkens a nearby receiver; disabling its `casts_shadow` restores light. Fill all local tiles and verify the overflow light still contributes unshadowed. Exercise 15 occupied tiles plus one point; assert six faces are dropped and no stale tile is sampled. Verify editor/Player labels use actual effective counts and explicit reasons.
```cpp
require(stats.local_shadow_faces <= 16 && stats.shadow_caster_draws <= 4096,
"Rendered local shadow work obeys both budgets");
require(stats.dropped_shadow_faces == 6,
"Insufficient atlas room disables a whole point shadow");
require(over_capacity_point_pixels[receiver_pixel] > no_point_pixels[receiver_pixel] + 12,
"Unshadowed point light still illuminates its receiver");
```
- [ ] **Step 2: Run the registered GPU and Player cases red.** Reconfigure and verify `render_lighting_local` appears in `ctest --test-dir build/linux-debug -N`; build the test executable and run `ctest --test-dir build/linux-debug --output-on-failure --no-tests=error -R '^(render_lighting_local|player_shutdown_diagnostics)$'`. For the optional overlay, which is absent from the default `linux-debug` preset, configure `cmake -S . -B build/p3-debug-overlay -G Ninja -DFASET_DEBUG_IMGUI=ON -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++`, build `faset_debug_overlay_tests`, verify it appears in that build's `ctest -N`, then run `ctest --test-dir build/p3-debug-overlay --output-on-failure --no-tests=error -R '^editor_debug_overlay$'`. Red must come from the new assertions, not from an absent optional target.
- [ ] **Step 3: Render local faces and sample them.** Allocate/clear local atlas tiles as in Task 4; assign six 90° views atomically for point lights and one cone view for spots. Bind the local atlas at set 1 binding 3. Apply per-tile PCF guard/clamp and correct face projection; skip sampling on `valid=false`. Report fallback when optional sampled D32 or atlas allocation is unavailable. Record conservative redraw reasons rather than claiming cached depth without invalidation proof.
```slang
if (light.shadowFaceCount == 6 && light.shadowValid != 0)
visibility = samplePointAtlas(light, worldPosition, normal);
// An unassigned light always uses visibility = 1, but still illuminates.
```
- [ ] **Step 4: Run local image and diagnostics tests under Khronos validation.** `ctest --test-dir build/linux-debug --output-on-failure --no-tests=error -R '^(render_lighting_local|player_shutdown_diagnostics|render_shader_reload)$'`; `ctest --test-dir build/p3-debug-overlay --output-on-failure --no-tests=error -R '^editor_debug_overlay$'`; then `ctest --test-dir build/linux-debug -L p3 --no-tests=error --output-on-failure`. Run the point-face seam fixture on Linux physical GPU and pinned SwiftShader.
- [ ] **Step 5: Commit** `Add bounded point and spot shadows with explicit fallback diagnostics`.
### Task 6: Release measurement and conditional Forward+
**Files:** Create `examples/renderer/p3_lighting_benchmark.cpp`, `tools/benchmark_p3_lighting.py`, `tests/test_p3_lighting_benchmark.py`, raw CSV under `docs/studies/data/`, and `docs/studies/22-p3-lighting-benchmark-2026-09-24.md`; modify `cmake/Renderer.cmake` and, only if the gate triggers, `shaders/gpu_scene.slang` or a focused new Slang file, `src/render/renderer.cpp`, `src/render/shader_contract.cpp`, `src/editor/build_service.cpp`, shader/package tests, and `tests/render_lighting_gpu_tests.cpp`.
**Interfaces:** Benchmark `--lights 0|4|16|32|64|128 --shadows on|off --visibility direct|gpu-frustum|gpu-occlusion --csv PATH` at 1920×1080, fixed scene/camera, ten warm-up and thirty measured frames, three independent runs. The Python wrapper has `--list-runs` for a fast configuration-contract test and `--sweep` for the full offline measurement; the registered CTest schema smoke invokes one 64×64, one-frame benchmark, not the full sweep. CSV includes commit, device/driver, mode, light count, GPU forward/shadow/total milliseconds, CPU render/readback milliseconds, atlas use, draw counts, validation errors. If the spec threshold triggers, tiled Forward+ uses 16×16 screen tiles with an overflow flag; an overflowing tile evaluates all submitted lights.
- [ ] **Step 1: Write and register benchmark/overflow contract checks.** Register `render_lighting_benchmark_schema` in CMake to run `tests/test_p3_lighting_benchmark.py` against the benchmark executable. Use `--list-runs` to verify the 0/4/16/32/64/128 sweep yields 18 mode×light configurations and 54 independent runs per shadow setting; use one 64×64 frame to verify every CSV row includes the effective lighting path. If tiled mode is needed, write an image case with more than the per-tile index capacity and compare against the full-light reference to ensure no missing illumination.
```cpp
double absolute_error = 0;
std::size_t large_error = 0;
for (std::size_t i = 0; i < tiled_pixels.size(); i += 4)
for (std::size_t channel = 0; channel < 3; ++channel) {
const auto delta = std::abs(int(tiled_pixels[i + channel]) -
int(full_scan_pixels[i + channel]));
absolute_error += delta;
large_error += delta > 16;
}
const double samples = 3.0 * (tiled_pixels.size() / 4);
require(absolute_error / samples <= 2.0 && large_error / samples <= 0.005,
"Forward+ overflow scans all local lights instead of dropping any");
```
- [ ] **Step 2: Run the new checks red.** Reconfigure; verify `render_lighting_benchmark_schema` appears in `ctest --test-dir build/linux-debug -N`; build `faset_p3_lighting_benchmark` and run `ctest --test-dir build/linux-debug --output-on-failure --no-tests=error -R '^render_lighting_benchmark_schema$'`. Expected failure is a missing benchmark interface/output or effective-path CSV column, never an empty CTest selection.
- [ ] **Step 3: Implement and run the fixed-scene benchmark.** Record Linux Release physical GPU and pinned SwiftShader functional runs separately. Do not use whole-render CPU time as a proxy for fragment cost because `Renderer::render` always performs synchronous framebuffer readback.
- [ ] **Step 4: Apply the objective gate.** If at 32, 64, or 128 local lights the median main-raster overhead versus zero lights is at least 1.0 ms or at least 15% of the light-free GPU frame on the Linux reference GPU, implement and verify depth-free 16×16 tiled Forward+ from conservative projected light volumes and record before/after *build + raster* time. If the threshold is not reached, keep the simple path, record the measured reason, and keep the CSV harness. New compute shader entries require exact reflection validation, CMake outputs, Editor build-service copy lists, and exported Player bundle tests.
```text
gate = max_over_32_64_128(Δmain_raster_p50 >= 1.0 ms
OR Δmain_raster_p50 >= 0.15 × gpu_frame_zero_lights_p50)
```
- [ ] **Step 5: Re-run both paths on the same frames.** Compare image output, zero validation errors, and measured GPU construction+raster cost. Keep Direct and P2 modes correct regardless of chosen default. Retain all raw CSV and methodology in the study; never claim universal speedup from one device.
- [ ] **Step 6: Commit** `Measure P3 light scaling and select a verified lighting path`.
### Task 7: End-to-end acceptance, Manual, and public evidence
**Files:** Modify `docs/manual/editor/diagnostics.md`, `docs/manual/editor/profiling.md`, `mkdocs.yml`, `PLAN.md`, `docs/IMPLEMENTATION.md`, `docs/validation/README.md`; create `docs/manual/editor/lighting.md`, `docs/validation/p3-lighting-2026-09-24/README.md`, raw test logs/report files. Update Windows CI files only if the existing GPU-labeled suite does not pick up P3 cases.
**Interfaces:** The Manual explains light kinds/properties, sun shadow distance, atlas face cost and overflow, shadow/camera behavior, editor and MCP authoring examples, and how to read actual diagnostics. The validation dossier names commit, exact Linux/Windows platform and driver, test counts, benchmark raw CSV paths, known limitations, and links to CI. P3 acceptance is an evidence claim, not a checkbox based only on compiling code.
- [ ] **Step 1: Write acceptance cases before the final run.** Use fixed scenes for 0/1/many lights, moving sun/caster, camera pan/cut/resize, a thin receiver at a cascade split, offscreen caster, six point faces, 16-tile and 4096-draw capacity, an unsupported-atlas fallback, Direct/GPU frustum/occlusion equivalence, shader reload, and independent 2D/UI output.
- [ ] **Step 2: Run Linux Debug and Release checks.** `cmake --build --preset linux-debug --parallel 4`; `ctest --preset linux-debug --output-on-failure`; `cmake --build --preset linux-release --parallel 4`; `ctest --test-dir build/linux-release --output-on-failure`. Run pinned Linux SwiftShader `ctest -L p3` and the same cases on a physical Vulkan GPU with validation enabled; record actual skips and layer availability.
- [ ] **Step 3: Run Windows native and software-Vulkan CI.** Verify every `gpu;p3` test executes on pinned SwiftShader, shader reflection/package tests pass, and relocated 2D/3D exported Release Players run at least 120 frames. Publish the exact GitHub Actions run links, test logs, and exported-game report. Do not describe this as physical Windows-GPU validation unless that device was run.
- [ ] **Step 4: Finish the English Manual and evidence.** Link `docs/manual/editor/lighting.md` in `mkdocs.yml`; include authoring JSON/Inspector and script examples, priorities, budgets, actual fallback and default path. Run `python -m mkdocs build --strict`, `git diff --check`, and the updated validation index link check. Update `PLAN.md` only for features whose stated acceptance evidence is present.
- [ ] **Step 5: Review and commit** `Validate and document P3 lighting and shadows`; after independent code review, publish the completed checkpoint to GitHub and Gitea as previously authorized.
@@ -0,0 +1,202 @@
# P3 Temporal Reconstruction Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Deliver selectable 1:1 TAA and, after it passes moving-image acceptance, output-resolution-history temporal upscaling for Direct and P2 visibility paths, with explicit fallback and measurable image quality.
**Architecture:** Keep the existing Off render branch as a reference. Add independent temporal history and per-instance previous transforms; raster the scene to internal color/depth/velocity, resolve against output-resolution history, then composite sharp UI into the existing final color image. HZB and temporal history share no validity flag, while using the same current scene depth and jittered raster projection.
**Tech Stack:** C++20, Vulkan 1.3 dynamic rendering and synchronization2, Slang/SPIR-V, CMake/Ninja, SDL3, headless GPU image tests, Khronos validation, Linux/Windows software-Vulkan CI.
**Spec:** `docs/superpowers/specs/2026-09-24-p3-temporal-design.md`
**Prerequisite checkpoint:** Complete Task 2 of `docs/superpowers/plans/2026-09-24-p3-lighting.md` through the green commit `Share typed multi-light shading across Direct and GPU paths` before the temporal plan changes `renderer.hpp`, `renderer.cpp`, `baseline.slang`, `gpu_scene.slang` or shader-contract validation. Pure temporal policy/test drafting can happen earlier; shared renderer integration cannot. Re-run Direct/P2 lighting reflection, hot-reload and image tests after each temporal shader or pipeline change.
## Global Constraints
- `TemporalMode::Off` and output-resolution `color` remain the defaults and reference output; Direct visibility must work with TAA and Upscale.
- Preserve the lighting graphics ABI: material set 0 bindings 03, frame-lighting set 1, GPU graphics scene set 2 bindings 02, unchanged 96/112-byte graphics push blocks; P2 compute sets remain set 0.
- `Snapshot::view_projection`, projection, `scene_rect`, picking and UI coordinates remain unjittered and in output pixels.
- HZB history and temporal color history have independent validity; GPU occlusion remains correct through temporal mode/scale switches.
- A missing previous transform, anonymous draw, mesh/LOD identity change, camera cut, changed view/projection/scene rectangle, resize or incompatible shader generation cannot reuse stale color history.
- World transparency/sprites retain depth and order, but their composited pixels reject temporal color history; UI is rendered at output resolution after resolve.
- Shadow views and light-space matrices are never jittered or scaled by temporal rendering.
- Player bundles contain complete checked SPIR-V and reflection metadata; no Slang compiler or Editor/MCP service is required at runtime.
- Unsupported temporal capabilities must use Off with an exposed effective mode and reason, never a silent path change.
- Every new pass receives a GPU label and timing; full-frame measurements include the existing synchronous readback cost unless explicitly excluded in a matched experiment.
## Review Focus
- Direct mode while TAA is enabled: a stable opaque instance must gain a valid prior transform on frame two without requiring HZB; Task 1 and Task 4 test this.
- GPU PostRaster after an object emerges from occlusion: its color and velocity must exist before temporal resolve so the same final frame shows it; Tasks 3 and 4 test this.
- Editor scene rectangle and UI: an offset/odd-sized scene viewport may scale internally, but text and buttons must remain pixel-exact in final output; Tasks 3 and 5 test this.
- A translucent object moving across an opaque surface: its pixels must not borrow the underlying opaque motion/history; Tasks 3 and 4 test this.
- Shader reload, format fallback and relocated exports: a partial bundle or unsupported format cannot produce a half-active temporal path; Task 6 tests this.
---
### Task 1: Independent temporal history policy and public mode
**Files:** Create `include/faset/render/temporal.hpp`, `src/render/temporal.cpp`, `tests/render_temporal_policy_tests.cpp`; modify `include/faset/render/renderer.hpp`, `src/render/renderer.cpp`, `cmake/Renderer.cmake`.
**Interfaces:** Add `enum class TemporalMode { Off, TAA, Upscale };`, `RendererConfig::temporal_mode`, `RendererConfig::render_scale`, `Renderer::set_temporal_mode(TemporalMode, float)`, `Renderer::temporal_mode()`, `FrameStats::requested_temporal_mode`, `effective_temporal_mode`, `temporal_history_valid`, `temporal_reset_reason`, and `temporal_internal_width/height`. Define `TemporalResetReason { None, FirstFrame, CameraCut, CameraDiscontinuity, ViewChanged, ViewportChanged, ProjectionChanged, Resize, ModeChanged, ScaleChanged, ShaderReload, Unsupported }` and `TemporalCapabilities { bool compute, formats, extent; }`. A pure `evaluate_temporal_history(previous, current) -> TemporalHistoryDecision` compares `TemporalHistoryKey` values containing view ID, output/internal extent, scene rectangle, unjittered projection, mode, shader generation, camera eye/current VP and explicit cut. `temporal_jitter(frameIndex, viewportWidth, viewportHeight)` returns a deterministic Halton(2,3) clip offset. Add `select_effective_temporal_mode(requested, capabilities)` as a pure policy function. Shared graphics descriptors remain material set 0, lighting set 1, GPU scene set 2; this task does not reallocate those bindings.
- [ ] **Step 1: Write failing policy tests and register their CMake target.** In a Direct visibility configuration, a same-view second frame returns `valid=true` even when HZB is absent. Test first frame, cut, view switch, changed projection, odd scene rectangle, resize, mode/scale change, shader generation, a camera teleport and unsupported format/compute capabilities. Add `faset_render_temporal_policy_tests` / `render_temporal_policy` to `cmake/Renderer.cmake` before the RED build. Example contract:
```cpp
auto decision = evaluate_temporal_history(previous, current);
require(decision.valid && decision.reason == TemporalResetReason::None);
current.camera_cut = true;
require(!evaluate_temporal_history(previous, current).valid);
require(select_effective_temporal_mode(TemporalMode::TAA, {false, true}) == TemporalMode::Off);
```
- [ ] **Step 2: Run the focused target and record the intended missing-interface failure.** Reconfigure with `cmake --preset linux-debug`, then run `cmake --build --preset linux-debug --target faset_render_temporal_policy_tests -j 4`; it must fail compiling the new test against the absent temporal API, not with `unknown target`. After implementation, `ctest --test-dir build/linux-debug --no-tests=error -R '^render_temporal_policy$'` runs its behavioral assertions.
- [ ] **Step 3: Implement the pure policy and attach it to rendered-frame completion.** Keep `scene.hzb_history_valid` and temporal history fields separate; do not call `InstanceTracker::invalidate_view()` merely because P2 occlusion is inactive. Reject invalid scale (`TAA` requires `1`, `Upscale` requires `[0.5, 1)`) with `std::invalid_argument`. Define camera teleport conservatively using eye displacement and an unjittered VP discontinuity, and expose the reason through `FrameStats`.
```cpp
const bool hzb_compatible = evaluate_hzb_history(...);
const auto temporal = evaluate_temporal_history(previous_temporal, current_temporal);
gpu_frame.view.flags[0] = hzb_compatible ? 1u : 0u;
statistics.temporal_history_valid = temporal.valid;
```
- [ ] **Step 4: Run the CPU tests and existing P2 policy tests.** `ctest --test-dir build/linux-debug --output-on-failure -R 'render_temporal_policy|render_visibility_policy|render_gpu_shader_contract'` must pass. Check that the default constructor still selects Off.
- [ ] **Step 5: Commit.** `git add include/faset/render/temporal.hpp src/render/temporal.cpp tests/render_temporal_policy_tests.cpp include/faset/render/renderer.hpp src/render/renderer.cpp cmake/Renderer.cmake && git commit -m "Define independent temporal history and mode policy"`.
### Task 2: Previous transforms and checked motion-vector shaders
**Files:** Modify `src/render/renderer.cpp`, `include/faset/render/visibility.hpp`, `shaders/baseline.slang`, `shaders/gpu_scene.slang`, `cmake/Renderer.cmake`, `src/render/shader_contract.hpp`, `src/render/shader_contract.cpp`, `tests/test_shader_reflection.py`, `tests/render_gpu_shader_contract_tests.cpp`; create `tests/render_temporal_motion_tests.cpp`.
**Interfaces:** Extend the GPU `SceneInstance/InstanceRecord` from 224 to 288 bytes by appending `previousModel` at offset 224; retain slot/generation metadata at offsets 208223. `metadata.x & 1` means prior HZB eligibility; `metadata.x & 2` means prior temporal transform eligibility. A temporal Direct vertex carries `previousClip` and validity alongside existing current clip and material data. Temporal Direct/GPU vertex entries feed one temporal fragment entry that writes scene color and an `R16G16B16A16_SFLOAT` target: `.xy = currentUV - previousUV`, `.z = previous clip depth`, `.w = 1` for valid opaque motion and `0` for reactive/invalid pixels. Add a pure `project_motion(current_clip, previous_clip) -> Vec2` CPU oracle with the same sign/space convention. Preserve the post-lighting baseline Off shader entry points and their layout fingerprints; GPU P2 fingerprints change with the checked record stride. Temporal fragment binds material set 0 and lighting set 1; temporal GPU vertex reads instance/visible-ID/view from set 2. Do not move cull/HZB compute off set 0 or increase 96/112-byte graphics push constants.
- [ ] **Step 1: Write failing shader and motion tests and register their target.** Assert the reflected 288-byte storage stride, current/previous clip varyings, velocity attachment output, lighting set 1/GPU scene set 2, and rejection of a tampered SPIR-V/reflection pair. Add `faset_render_temporal_motion_tests` / `render_temporal_motion` to `cmake/Renderer.cmake`. Test `project_motion` against a known current/prior clip pair and `InstanceTracker` through a two-frame rigid object move; include a replaced mesh and anonymous draw whose motion validity is false. GPU image-level motion tests belong to Task 4 after MRT resources exist.
```cpp
auto previous = tracker.update("cube", mesh, model_a, bounds_a, "main");
tracker.finish_frame();
auto moved = tracker.update("cube", mesh, model_b, bounds_b, "main");
require(moved.previous_valid && moved.previous_model == model_a);
```
- [ ] **Step 2: Observe the expected pre-implementation failure.** Reconfigure, then run `cmake --build --preset linux-debug --target faset_render_temporal_motion_tests -j 4`; the new test fails to compile against missing motion interfaces. Build the changed existing tests with `cmake --build --preset linux-debug --target faset_render_gpu_shader_contract_tests faset_shaders -j 4`, then `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^(render_shader_reflection|render_gpu_shader_contract)$'` must reject the new temporal ABI assertions rather than pass only old cases.
- [ ] **Step 3: Implement both geometry paths and shader contracts.** Retain `InstanceUpdate` in selected Direct draws; compute the previous clip position from its previous model and previous jittered VP. Extend `GpuVertex` only as needed by temporal shader input locations. GPU temporal vertex multiplies `previousViewProjection * previousModel * localVertex`. Current/previous scene clip and validity reach the fragment; encode current-minus-prior local-scene UV, prior clip depth and validity. Make P2 culling read `(metadata.x & 1u) != 0`, not `metadata.x != 0`. Update C++ static assertions and reflection checks together.
```slang
float4 previousClip = mul(view.previousViewProjection,
mul(instance.previousModel, float4(vertex.position, 1)));
bool temporalValid = (instance.metadata.x & 2u) != 0u && previousClip.w > 0;
// Off still uses vertexMain / gpuVertexMain / fragmentMain.
```
- [ ] **Step 4: Run reflection, motion and P2 GPU suites under validation.** `ctest --test-dir build/linux-debug --output-on-failure -R 'render_temporal_motion|render_shader_reflection|render_gpu_shader_contract|render_gpu_visibility'` must pass with zero validation errors. Verify the Off direct/GPU image comparison remains within its established tolerance.
- [ ] **Step 5: Commit.** `git add src/render/renderer.cpp include/faset/render/visibility.hpp shaders/baseline.slang shaders/gpu_scene.slang cmake/Renderer.cmake src/render/shader_contract.hpp src/render/shader_contract.cpp tests/test_shader_reflection.py tests/render_gpu_shader_contract_tests.cpp tests/render_temporal_motion_tests.cpp && git commit -m "Emit checked motion vectors for direct and GPU scenes"`.
### Task 3: Scene targets, post-cull ordering and sharp UI boundary
**Files:** Create `shaders/temporal.slang`, `tests/render_temporal_graph_tests.cpp`; modify `src/render/renderer.cpp`, `src/render/shader_contract.hpp`, `src/render/shader_contract.cpp`, `shaders/baseline.slang`, `shaders/gpu_scene.slang`, `cmake/Renderer.cmake`, `tests/render_tests.cpp`, `tests/render_gpu_acceptance_tests.cpp`.
**Interfaces:** Add temporal-only internal `sceneColor` (`R8G8B8A8_UNORM`, sampled/color attachment), `sceneDepth` (`D32_SFLOAT`, sampled/depth attachment) and `sceneVelocity` (sampled floating-point/color attachment). Keep existing full-resolution `color` for capture and presentation. Temporal opaque pipeline variants use color+velocity MRT; transparent/sprite pixels overwrite velocity validity with invalid/reactive state. Split `draw_sprites_and_ui` so world sprites join the internal scene and UI draws only after resolve. Record names in `FrameStats::graph_passes` for ordering diagnostics. Main and post-raster graphics pipelines bind material set 0 and lighting set 1, plus scene set 2 only for GPU instances; shadow planning remains unjittered. For TAA, internal and output extents are identical; the scaling of Task 5 follows later.
- [ ] **Step 1: Write failing graph/image tests and register their target.** Add `faset_render_temporal_graph_tests` / `render_temporal_graph` to `cmake/Renderer.cmake`. Render an odd, offset Editor `scene_rect`, a textured sprite behind/in front of a mesh, moving translucent geometry and bright UI text/quad. Assert `TemporalResolve` occurs after `PostRasterScene` in GPU occlusion mode, `UI` occurs after resolve, viewport clipping holds, and an unchanged UI pixel matches Off exactly. Check depth and velocity attachment store/load behavior with validation.
```cpp
require(position(pass_names, "PostRasterScene") < position(pass_names, "TemporalResolve"));
require(position(pass_names, "TemporalResolve") < position(pass_names, "TemporalComposite"));
require(position(pass_names, "TemporalComposite") < position(pass_names, "UI"));
require(taa_frame.ui_pixel == off_frame.ui_pixel);
```
- [ ] **Step 2: Run the focused test and confirm the missing scene/UI split.** Reconfigure/build `faset_render_temporal_graph_tests`, then `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^render_temporal_graph$'` must fail at the new pass-order/UI assertion. A compile failure on an absent `FrameStats::graph_passes` field is also a valid RED result; an unregistered test is not.
- [ ] **Step 3: Refactor the render branch without changing Off output.** In the temporal branch, MainRaster clears color/depth/velocity, HZB reads stored scene depth, PostRaster loads all attachments, transparent/sprites retain their scene-depth test and invalidate velocity/reactive pixels, then `TemporalResolve`, `TemporalComposite` and `UI` are separate named passes. First make Resolve a spatial copy into a temporary `resolvedColor` and Composite a fullscreen draw to `color`; Task 4 replaces the spatial result with temporal accumulation. Explicitly transition color/depth/velocity from attachment to sampled layouts before compute, and resolved output to sampled before composite.
```cpp
// Temporal branch only; Off keeps the established ForwardAndUI path.
graph.add("PostRasterScene", {"sceneColor", "sceneDepth", "post_indirect"},
{"sceneColor", "sceneDepth", "sceneVelocity"}, draw_post_scene);
graph.add("TemporalResolve", {"sceneColor", "sceneDepth", "sceneVelocity"},
{"resolvedColor"}, resolve_spatial);
graph.add("TemporalComposite", {"resolvedColor"}, {"color"}, draw_resolved_scene);
graph.add("UI", {"color"}, {"color"}, draw_output_ui);
```
- [ ] **Step 4: Run GPU image/validation and sprite/UI suites.** `ctest --test-dir build/linux-debug --output-on-failure -R 'render_temporal_graph|render_offscreen|render_sprite_alpha|render_gpu_visibility|ui_render'` passes. Compare Off captures before/after this commit to ensure no unrequested shading/UI change.
- [ ] **Step 5: Commit.** `git add src/render/renderer.cpp src/render/shader_contract.hpp src/render/shader_contract.cpp shaders/baseline.slang shaders/gpu_scene.slang shaders/temporal.slang cmake/Renderer.cmake tests/render_tests.cpp tests/render_gpu_acceptance_tests.cpp tests/render_temporal_graph_tests.cpp && git commit -m "Separate temporal scene raster from output UI"`.
### Task 4: Stable 1:1 TAA with disocclusion rejection
**Files:** Create `tests/render_temporal_acceptance_tests.cpp`; modify `shaders/temporal.slang`, `src/render/renderer.cpp`, `cmake/Renderer.cmake`, `src/render/shader_contract.hpp`, `src/render/shader_contract.cpp`, `tests/test_shader_reflection.py`, `tests/render_temporal_graph_tests.cpp`.
**Interfaces:** Allocate two output-resolution `R16G16B16A16_SFLOAT` sampled/storage color histories and two output-resolution `R32_SFLOAT` sampled/storage depth histories. `temporalResolveMain` reads current scene color/depth/velocity and prior history, writes current history. `temporalComposite*` draws the resolved result to the existing RGBA8 final `color`; it does not reapply tone mapping/gamma because scene shading is already display-referred. Add GPU pass time and a history accepted/rejected diagnostic counter that is read only in diagnostic mode.
- [ ] **Step 1: Write failing deterministic frame-sequence tests and register their target.** Add `faset_render_temporal_acceptance_tests` / `render_temporal_acceptance` to `cmake/Renderer.cmake`. On Direct and P2 GPU modes, require first-frame rejection and second-frame acceptance. Test static diagonal/wire variance after 16 jitter phases, slow camera pan, moving rigid cube, opening a door, explicit cut, unmarked teleport, mesh/LOD identity change, and UI opacity. Compare each reveal/cut frame to Off at the same camera; old foreground colors must not trail into exposed background. Record tolerances per fixture in the test, not a universal image-perfect claim.
```cpp
auto cut = render_frame(taa, scene_with_cut);
auto fresh = render_frame(off, scene_without_history);
require(!cut.stats.temporal_history_valid);
require(mean_rgb_error(cut.rgba, fresh.rgba, reveal_roi) <= 8.0);
```
- [ ] **Step 2: Run the acceptance target to see the expected lack of accumulation/rejection.** Reconfigure/build the new target, then `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^render_temporal_acceptance$'` must fail in its new history/variance assertions; a zero-tests pass is not evidence.
- [ ] **Step 3: Implement TAA resolve and real history lifetime.** Use deterministic Halton jitter, local-scene normalized motion and 3×3 nearest-depth velocity dilation. Reject invalid/out-of-bounds motion and sampled prior depth mismatches, clamp previous color to a current 3×3 neighborhood, reduce its bounded weight for high motion/reactive pixels, and use current color on first/rejected pixels. Write current color/depth to the next history only after a successful submitted frame. Grow the 12-query timestamp pool so every graph pass is timed, and expose separate temporal resolve/composite timings.
```slang
float2 previousUV = currentUV - selectedMotion.xy;
bool accept = historyValid && selectedMotion.w > 0 && inBounds(previousUV) &&
depthAgrees(selectedMotion.z, historyDepth.SampleLevel(sampler, previousUV, 0));
float3 resolved = accept ? lerp(current.rgb, clamp(history.rgb, neighborhoodMin,
neighborhoodMax), historyWeight)
: current.rgb;
```
- [ ] **Step 4: Run policy, shader and GPU acceptance under validation.** `ctest --test-dir build/linux-debug --output-on-failure -R 'render_temporal|render_shader_reflection|render_gpu_visibility|render_offscreen'` passes, including Direct/P2. Capture repeatable Off/TAA comparison images and per-pass timing for review; a TAA frame with zero validation errors is not sufficient without the moving-image assertions.
- [ ] **Step 5: Commit.** `git add shaders/temporal.slang tests/render_temporal_acceptance_tests.cpp src/render/renderer.cpp cmake/Renderer.cmake src/render/shader_contract.hpp src/render/shader_contract.cpp tests/test_shader_reflection.py tests/render_temporal_graph_tests.cpp && git commit -m "Resolve scene with depth-rejected temporal AA"`.
### Task 5: Lower-resolution scene and output-resolution history
**Files:** Modify `src/render/renderer.cpp`, `include/faset/render/renderer.hpp`, `include/faset/render/temporal.hpp`, `src/render/temporal.cpp`, `shaders/temporal.slang`, `tests/render_temporal_policy_tests.cpp`, `tests/render_temporal_acceptance_tests.cpp`, `tests/render_gpu_acceptance_tests.cpp`.
**Interfaces:** `Upscale` computes internal width/height by `ceil(outputExtent * renderScale)` with a minimum of one pixel; stores history at output extent. It transforms `scene_rect` into a clipped internal viewport once per frame. P2 HZB, current/post depth and `SceneView` viewport use these internal values. Resolve maps each output-scene pixel to the internal scene signal and handles depth/velocity boundaries before history reuse. Output UI and capture remain full resolution.
- [ ] **Step 1: Write failing scale tests.** Exercise 320×240 at 0.67, 319×241 with an offset scene rectangle at 0.5, resize, 2D sprites, and toggling 1.0 TAA → 0.67 Upscale → Off. Check reported internal extent, exact UI pixels, HZB reset, history reset reason and no stale edge pixels. Compare a static thin-wire and slow-pan sequence to a full-resolution spatial reference; require measured temporal variance to improve over a nearest-neighbor 0.67 spatial baseline, while reporting image error rather than asserting that all scenes improve.
```cpp
require(upscaled.stats.temporal_internal_width == 215);
require(upscaled.stats.temporal_internal_height == 161);
require(upscaled.rgba.size() == 320u * 240u * 4u);
require(upscaled.stats.temporal_reset_reason == TemporalResetReason::ScaleChanged);
```
- [ ] **Step 2: Run the scale test and observe the missing reduced-resolution path.** Rebuild `faset_render_temporal_acceptance_tests` with the new assertions, then `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^render_temporal_acceptance$'` must fail at the internal extent/scale transition assertion.
- [ ] **Step 3: Implement internal target recreation and upscale sampling.** Keep `color`/readback output-sized, resize scene color/depth/velocity and HZB to internal size, scale only scene viewport/scissor, and include internal extent in both history keys. Use output-resolution history and depth-aware current sampling at output pixel centers; keep motion in local-scene normalized coordinates. Recreate descriptors after target changes and invalidate both temporal/HZB histories on scale/resize.
```cpp
const auto internal_w = std::max(1u, static_cast<unsigned>(std::ceil(width * scale)));
const auto internal_h = std::max(1u, static_cast<unsigned>(std::ceil(height * scale)));
// scene_rect is mapped to this extent; UI remains at width x height.
```
- [ ] **Step 4: Run Direct/frustum/occlusion GPU sequences and baseline UI/resize tests.** `ctest --test-dir build/linux-debug --output-on-failure -R 'render_temporal|render_gpu_visibility|render_offscreen|render_sprite_alpha|editor_ui'` passes with zero Vulkan validation errors where the validation layer exists. Inspect side-by-side captures on physical GPU and software Vulkan.
- [ ] **Step 5: Commit.** `git add src/render/renderer.cpp include/faset/render/renderer.hpp include/faset/render/temporal.hpp src/render/temporal.cpp shaders/temporal.slang tests/render_temporal_policy_tests.cpp tests/render_temporal_acceptance_tests.cpp tests/render_gpu_acceptance_tests.cpp && git commit -m "Reconstruct lower-resolution scenes at output resolution"`.
### Task 6: Editor/Player control, shader reload, package and graceful fallback
**Files:** Modify `src/editor/debug_overlay.cpp`, `src/editor/build_service.cpp`, `apps/player_main.cpp`, `src/render/renderer.cpp`, `src/render/shader_contract.cpp`, `cmake/Renderer.cmake`, `tests/render_reload_tests.cpp`, `tests/build_service_tests.cpp`, `tests/player_diagnostics_test.py`, `docs/manual/editor/profiling.md`; add temporal mode usage to the appropriate scripting/manual rendering page.
**Interfaces:** Editor and Player select Off/TAA/Upscale with scale; the Player profile reports requested/effective mode, fallback/reset reason, internal/output extent, jitter, temporal GPU ms and memory. A complete shader bundle includes all temporal entry points and metadata. Reload is transactional: failure preserves the active set and history, success replaces pipelines and resets history. Device feature checks are separate from P2 `scene.available`, then `select_effective_temporal_mode` exposes fallback.
- [ ] **Step 1: Write failing integration tests.** A missing/tampered temporal `.spv` or reflection rejects the bundle and exported game; a failed hot reload leaves previous rendered pixels/actual mode intact; successful reload resets history; a pure unsupported-capability fixture selects Off with a specific reason. A relocated 2D and 3D Player profile contains temporal requested/effective and reset fields. Check Editor control state matches `Renderer::temporal_mode()`.
```cpp
const auto before = renderer.stats().effective_temporal_mode;
require(!renderer.reload_shaders(error) && !error.empty());
renderer.render(scene);
require(renderer.stats().effective_temporal_mode == before);
```
- [ ] **Step 2: Run focused integration tests for the expected package/control failure.** Build `faset_render_reload_tests`, `faset_build_service_tests`, and `faset_player_diagnostics`; then `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R '^(render_shader_reload|process_and_cook|player_shutdown_diagnostics)$'` must execute registered tests and fail in the new temporal assertions. For the optional overlay, configure `cmake -S . -B build/p3-temporal-ui -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DBUILD_TESTING=ON -DFASET_DEBUG_IMGUI=ON`, build `faset_debug_overlay_tests`, and run `ctest --test-dir build/p3-temporal-ui --no-tests=error --output-on-failure -R '^editor_debug_overlay$'`. Record the specific failing assertions; an absent overlay test is not a pass.
- [ ] **Step 3: Implement controls and packaging.** Compile/install temporal shaders in `cmake/Renderer.cmake`; update both explicit shader-copy lists in `src/editor/build_service.cpp`; validate reflection/strides; stage temporal pipelines before replacing live ones. Query sampled/color/storage/filter format support and compute queue support, report Off fallback explicitly, and avoid allocating history on Off. Add concise English Manual examples for mode choice and reading the profile.
```cpp
stats.requested_temporal_mode = config.temporal_mode;
stats.effective_temporal_mode = select_effective_temporal_mode(config.temporal_mode, caps);
stats.temporal_status_reason = stats.effective_temporal_mode == TemporalMode::Off
? missing_capability_name(caps) : std::string{};
```
- [ ] **Step 4: Run focused tests, both sample exports, strict Manual build and native Windows CI.** `ctest --test-dir build/linux-debug --no-tests=error --output-on-failure -R 'render_shader_reload|process_and_cook|player_shutdown_diagnostics|render_temporal'`, `ctest --test-dir build/p3-temporal-ui --no-tests=error --output-on-failure -R '^editor_debug_overlay$'`, and `python -m mkdocs build --strict` pass; relocated exports launch without compiler/source checkout. Record any Windows GPU/validation coverage gap explicitly.
- [ ] **Step 5: Commit.** `git add src/editor/debug_overlay.cpp src/editor/build_service.cpp apps/player_main.cpp src/render/renderer.cpp src/render/shader_contract.cpp cmake/Renderer.cmake tests/render_reload_tests.cpp tests/build_service_tests.cpp tests/player_diagnostics_test.py docs/manual && git commit -m "Expose and package temporal reconstruction"`.
### Task 7: Adversarial quality gate, performance record and P3 integration
**Files:** Add `docs/validation/p3-temporal-2026-09-24/README.md` and image/measurement artifacts; modify `PLAN.md`, `docs/IMPLEMENTATION.md`, `docs/ARCHITECTURE.md`, `docs/manual/editor/profiling.md`, temporal tests as findings require.
**Interfaces:** The evidence dossier binds revision, OS/GPU/driver, exact test commands, mode/scale, output/internal extent, scene sequence, raw image differences, static variance, disocclusion trail length, pass/full-frame time, allocated GPU bytes and feature limits. Lighting/shadow work may use the final `sceneColor/depth/velocity` boundary but does not mark temporal acceptance by itself.
- [ ] **Step 1: Run every adversarial sequence against Off and 1:1 TAA before claiming upscaling readiness.** A newly exposed surface and camera cut must show current color immediately; thin static geometry should have lower temporal variance without unacceptable trail length. Repeat with 0.67 Upscale against 0.67 spatial and 1.0 full-res references on closed/open scenes. Keep the raw captures and metric script with the dossier.
```text
Sequences: wire-static-16, pan-16, moving-cube-16, door-open-4,
cut-2, teleport-2, projection/resize/view-switch, UI+alpha.
Modes: Off, TAA 1.0, Upscale 0.67; visibility: Direct, Frustum, Occlusion.
```
- [ ] **Step 2: Run Debug/Release tests, validation, shader reload, strict docs, software GPU and native CI.** `cmake --build --preset linux-debug --parallel 4`, `ctest --preset linux-debug --output-on-failure`, `cmake --build --preset linux-release --parallel 4`, `ctest --test-dir build/linux-release --output-on-failure`, and strict MkDocs must pass. Run the selected SwiftShader ICD with temporal GPU tests and relocated exports. If a physical Windows GPU is unavailable, say so.
- [ ] **Step 3: Record matched profiling and image metrics.** Use the same scene/camera path and resolution for Off/TAA/Upscale. Report pass GPU ms, full GPU ms, CPU extraction/readback, and live allocation, with raw samples and p50/p95. Report quality metrics on fixed ROIs and representative frames, plus captures for moving thin geometry, disocclusion, UI and transparency; do not turn fixture-specific results into a universal speed/quality claim.
- [ ] **Step 4: Review the final diff independently and close load-bearing findings.** Confirm HZB correctness, history invalidation, shader package/reload atomicity, Direct/P2 equivalence and UI sharpness; run `graphify update .` after final code edits, then update PLAN/Manual/architecture and evidence links to match actual tested scope.
- [ ] **Step 5: Commit and publish only verified work.** `git add PLAN.md docs/IMPLEMENTATION.md docs/ARCHITECTURE.md docs/manual docs/validation/p3-temporal-2026-09-24 tests && git commit -m "Validate P3 temporal reconstruction"`; publish checkpoint and final commits to the authorized remotes once local verification and CI are green.
@@ -0,0 +1,74 @@
# P1 gameplay iteration design
This design closes [PLAN P1](../../../PLAN.md#p1-lua-и-скорость-итераций) for Linux and Windows desktop 2D/3D authoring. It improves the path from changing gameplay or a scene to seeing the result in the Player. C++ remains the compiled gameplay language; Lua remains an optional module with development reload. MCP controls the Editor and authoring/build services, not the live Player world.
The Editor's dark visual treatment should be consistent with [the iteration console reference](../../design/p1-iteration-console-reference.png) and [the new-project reference](../../design/p1-project-template-reference.png). These images are visual references only. The behavior, data contracts, platform paths, accessibility and available actions in this specification and `PLAN.md` are the source of truth. The Windows path shown in the project image is illustrative; the real chooser must use each platform's native paths.
## Existing baseline and scope
The optional Lua VM, LuaLS annotations, component schemas, Inspector fields, atomic development reload and rollback already exist. `BuildService` already serializes GUI/MCP builds, uses incremental CMake/Ninja native trees separated by Debug and Release, publishes immutable successful generations, and preserves the last good generation after failure. The authoring service atomically journals every transaction under `.faset/recovery` and refuses to save over an externally changed scene. A disposable workflow script measures one changed C++ build and first Player frame. These remain the foundation, not new work to replace.
P1 adds verifiable reuse of unchanged schema/build packages, useful compiler diagnostics, convenient new-project choices and code navigation, autosave of named scenes, and repeatable iteration measurements. It also closes the recorded Lua validation gap on Windows and in a graphical Release export. P1 does not add C++ hot reload, dynamic gameplay loading, Lua state preservation across reload, Player-world MCP access, a built-in code editor, or broad performance guarantees. Dynamic gameplay loading is reconsidered only if measured native link time is a material bottleneck.
## User workflows
### C++ edit, build and Play
The developer edits `Scripts/Gameplay.cpp` or a header, presses **Build**, and sees a named job with phase, progress, elapsed time and diagnostics. A compiler error shows severity, a short message, project-relative file and one-based line/column when the tool supplies them. Selecting it opens the source at that location in the configured external editor. Raw compiler output remains available. A failed build leaves the prior Player/schema generation intact and marks Inspector metadata stale. An unchanged second build reports a cache hit and reuses the same validated generation. **Play** still captures the current authoring scene, invokes the build service, then launches an isolated Player; editing after capture does not silently change that snapshot.
### Lua edit and reload
A Lua project declares scripts in `project.faset.json` and can start with no project C++ files. Script edits mark schema metadata stale when declarations change; **Refresh Lua** validates schemas without recompiling unrelated C++ gameplay. The running development Player watches or explicitly reloads scripts; successful reload resets its world/script state, while an invalid edit preserves the old running version. The Editor and MCP surface parseable diagnostics with source locations where available. A packaged Release Player includes only the declared Lua snapshot and needs neither `slangc`, LuaLS nor the Editor.
### New project and source navigation
The new-project chooser offers four clear combinations: C++ 2D, C++ 3D, Lua 2D and Lua 3D. The existing CLI `--new NAME --dimension 2|3` and two-argument `BuildService::scaffold(name, dimension)` retain their C++ scaffold behavior for compatibility. The chooser and an explicit `--language cpp|lua` select a runnable template that adds a minimal start scene and documented starter behavior for the chosen dimension. Template creation never overwrites existing user files and rejects nonempty conflicting destinations. Lua starters include the module declaration and language-server setup without a C++ gameplay stub. The source browser opens C++, headers and Lua under `Scripts`; diagnostic rows open the exact project source line/column when supported by the configured editor.
`faset_source_open` accepts a project-relative path and optional one-based line/column, validates that the target is a regular `.cpp`, `.hpp`, `.h` or `.lua` file beneath `Scripts`, and launches an argv array without a shell. It rejects traversal, symlinks escaping the project, directories and executable files. The existing `faset_script_open` Lua-only command remains a compatibility alias. Editor configuration supports `{file}`, `{line}`, `{column}` and `{project}` tokens. The default Zed invocation uses its `path:line:column` syntax; custom commands can substitute the tokens. Missing editor executables yield a concise actionable error and never make a build fail.
### Autosave
Autosave is enabled by default for named, dirty scene documents while a persistent Editor session is running, including headless MCP sessions. It waits 2 seconds after the last document revision change and saves through `AuthoringService::save`; rapid edits coalesce. A project-level `editor.autosave` Boolean in `project.faset.json` controls it, with a visible toggle in Project settings and a read-only `faset_autosave_status` command. Changing the toggle takes effect immediately in the current session and persists for the next open. `Ctrl+S` and `faset_document_save` remain immediate explicit saves. An unnamed scene is never assigned an implicit path: the UI says **Save As required**, and the existing recovery journal protects its edits.
Autosave carries the document revision it observed into an optional `expected_revision` on the save API. A concurrent edit makes that save fail with `revision.conflict`, after which the newer revision is scheduled normally. Existing `disk_hash` comparison still rejects external modifications; autosave never silently overwrites them. A failed autosave leaves the document dirty and its journal intact, shows a persistent conflict/error with Save As or reload guidance, and does not log the same failure every frame. Another edit or an explicit retry permits a new attempt. Saving creates no Undo operation; Undo/Redo remain valid after autosave. Scene snapshots already captured for Play/export remain immutable. The recovery journal remains active even when autosave is disabled or before its timer expires.
## Build cache and schema correctness
The native build always runs CMake configure and Ninja/selected generator build. Those tools own source/header dependency analysis; a shortcut based only on `Session::source_signature()` is unsafe because that signature covers project `Scripts` but not engine sources, shaders, CMake recipes or toolchain changes. A no-op native build should do no compile or link work, but the UI must not call it a native cache hit merely because the later schema/package stage was reused.
After a successful native build, `BuildService` computes a versioned package key from the selected configuration, normalized build recipe and configure arguments, `CMakeCache.txt` and toolchain identity, complete project `Scripts` content snapshot, Lua declaration/fingerprint, Player and SchemaExporter hashes, all required SPIR-V/reflection hashes, and copied runtime-library hashes. The toolchain identity includes resolved compiler/CMake/Slang executable identity or content hash; changing a toolchain in place must force the native tree to be reconfigured/rebuilt or make the service refuse reuse. Asset source files are not gameplay-build inputs.
If the key matches the last successful immutable build, and every required file passes the stored manifest hash and schema validation, the service returns that generation with explicit `schema_cache_hit=true` and `generation_reused=true`. It skips SchemaExporter and package copying. A missing, malformed or corrupt cached file is never returned as a hit; the service attempts a fresh candidate or fails while retaining the prior pointer. A changed key runs SchemaExporter against the same captured Lua source snapshot, validates the complete schema, stages all files, rechecks the project source snapshot, then atomically publishes the new generation and pointer. Do not publish a mixed snapshot if any `Scripts` source changes during the build. Debug and Release have distinct keys and native trees. Export always revalidates referenced assets and packages their current generations even if gameplay build reuse succeeds; a stale asset must block export until reimport.
`JobStatus` and `faset_job` expose the reused-generation flag, schema hit flag, elapsed phase times and final build fingerprint. Existing `result.directory`, `result.player`, `result.schema` and the last-good pointer remain compatible. Cache results must be understandable in the GUI and MCP without parsing logs.
## Diagnostics and UI behavior
The build service keeps its bounded raw log and adds a structured `diagnostics` array: `{severity, phase, message, file?, line?, column?, code?}`. The parser handles Clang/clang-cl and Lua source-location formats on Linux and Windows, including drive letters and Unicode paths. Project files are normalized to project-relative paths; outside-project diagnostics remain visible as text but cannot be passed to `faset_source_open`. ANSI escape sequences do not contaminate messages. Unrecognized output stays in the raw log; nonzero exit without a parsed error still creates a generic job failure rather than an empty error panel. Multiline notes remain associated with the triggering error where practical.
The Console shows current and recent build jobs, counts by severity, phase, elapsed time, the first actionable error and expandable raw output. Selecting a diagnostic invokes the same `faset_source_open` command available to MCP. Disabled source actions explain why a location cannot be opened. The status bar distinguishes **Saved**, **Pending autosave**, **Saving**, **Save conflict**, **Save failed** and **Save As required**. Controls remain keyboard reachable, compact, high contrast and consistent with the Editor's dark theme. Layout and copy may evolve from the image reference as the actual controls are implemented.
## Measurement and validation
`tools/measure_workflows.py` retains disposable projects and machine-readable raw results. It records cold configure/build, warm unchanged build, changed C++ source/header build, build failure/recovery, Play-to-first-rendered-frame, Lua edit-to-successful-reload, and repeated Editor event-to-visible-state latency. Run at least five repetitions after a stated warm-up for warm/changed cases; retain each sample plus median and nearest-rank p95. Record exact revision and dirty state, OS, CPU, RAM, GPU/driver, compiler, CMake, Slang, build configuration, project/source hashes, scene size and whether validation/readback were enabled. Keep cold-start samples separate from warm samples; label offscreen first frame and windowed first presented frame separately using the Player's existing `startup_ms.main_to_first_frame` and `presentation_mode` profile fields. Include a larger generated scene/content case alongside the checked-in 2D/3D examples. Measurements are observations, not flaky CI timing gates.
For the documented Linux reference host and exact two sample scenes, track the existing budgets: measured frame p95 ≤ 4 ms, GPU and readback p95 ≤ 1 ms each, simulation and snapshot p95 ≤ 0.5 ms each, explicit live Vulkan allocations ≤ 20 MiB, and startup from `main()` ≤ 500 ms. Run a 3,000-frame warm resource-lifecycle sample to check for growth. Report any missed budget honestly and investigate; do not claim the limits for other machines or content. Record a separate available Windows baseline, distinguishing software Vulkan from physical GPU. If physical Windows hardware is unavailable, mark that coverage unverified rather than blocking the functional Windows CI result.
The Lua module must pass Linux and Windows native CPU suites; the watched/explicit reload integration must run under an available Vulkan device on both CI platforms; and a Lua-only Release export must validate and render after relocation with source project paths unavailable. Both Linux and Windows CI report exact test outcomes. Update the English Manual with C++/Lua iteration recipes, template selection, source editor setup, cache indicators, autosave/conflict recovery, and diagnostic navigation. Update `PLAN.md`, `docs/IMPLEMENTATION.md` and a dated validation dossier only after checks and measured evidence exist.
## Acceptance matrix
| Area | Required evidence |
| --- | --- |
| Lua | Existing lifecycle/safety/CLI suites pass on Linux and Windows; watched/explicit reload and relocated Lua-only Release export render on available Vulkan implementations. |
| Cache | Second unchanged build reuses the same verified schema/package generation and does not invoke SchemaExporter; header, Lua, recipe/toolchain, shader or runtime output changes invalidate appropriately; corrupt entries never become hits. |
| Rollback | Failed compile/schema/copy and source-race cases leave the previous successful pointer and Inspector schema available but stale; export still rejects stale assets. |
| Diagnostics | Clang, clang-cl, Lua, Unicode path, drive-letter and unparseable-output fixtures pass; real C++ compile failure produces a navigable diagnostic and raw log. |
| Templates/navigation | All four new-project combinations launch or validate, old CLI/scaffold defaults still work, existing files are not overwritten, source-open rejects traversal and opens project code at the requested position. |
| Autosave | Named scene saves after idle, rapid edits coalesce, unnamed scene remains in recovery, disk/revision conflicts never overwrite, Undo and Play snapshot remain stable; GUI and MCP show status. |
| Iteration | Raw repeated cold/warm/changed/Play/Lua/UI samples and environment metadata are committed; claims are limited to measured scenes/hosts; reference budgets and any misses are shown. |
| Documentation | Strict MkDocs build and compiled tutorial tests pass; Manual, `PLAN.md` and validation dossier describe observed behavior and known coverage gaps. |
## Delivery sequence
Deliver safe cache keys and source snapshots first, then diagnostics/navigation, templates and autosave as independently testable slices. Finish with cross-platform Lua/export validation, repeated measurements, documentation and independent review. Each slice uses a failing contract test before implementation and a focused passing suite before its commit. The final P1 status is only marked complete when the acceptance matrix has linked evidence; unavailable physical Windows GPU or benchmark hardware is recorded as a coverage limit, not silently treated as passed.
@@ -0,0 +1,51 @@
# P3 lighting and shadows design
This design implements the lighting and shadow portion of [PLAN P3](../../../PLAN.md#p3-освещение-тени-и-temporal-reconstruction) for desktop 3D games. Temporal reconstruction has a separate design and implementation plan. The P2 Direct, GPU frustum, and GPU occlusion paths must shade the same scene from the same immutable snapshot. Ordered sprites, editor UI, and 2D presentation remain unlit unless a later 2D-lighting project explicitly changes them.
## Existing behavior and target
`Snapshot` currently carries one `light_direction`; `SceneView::build` overwrites it for each `faset.light`, without using the authored color or intensity. `fragmentMain` evaluates one hard-coded directional BRDF and samples one 1024² D32 shadow map. Its shadow matrix covers a fixed world-origin orthographic box. The shadow pass renders all `cast_shadow` meshes through CPU-transformed geometry even when P2 GPU visibility is selected; it is independent of the camera visibility decision. The compiled `gpuShadowMain` is not used by the current pass. These facts make multiple authored lights, large camera movement, and explicit shadow budgets impossible without changing the scene and shader contracts.
P3 supplies one sun plus point and spot lights, camera-fitted cascaded sun shadows, a bounded local shadow atlas, and independent per-shadow-view caster selection. Authored values reach exported Player games and the editor preview through the existing scene schema. A scene with no light component retains the previous default sun appearance. Lighting is accumulated in linear space before the current tone mapping; the legacy directional factor is preserved for the default so existing unlit UI and basic rendering tests remain meaningful. Artist-facing intensity is unitless in this stage; photometric units and IES profiles are outside P3.
## Scene contract and validation
Keep `faset.light` at builtin schema version 1 and add optional fields with defaults: `kind` (`directional`, `point`, `spot`, default `directional`), `enabled` (true), `color` (white), `intensity` (1, nonnegative), `range` (10, positive, for local lights), `inner_angle` (0.35 radians), `outer_angle` (0.70 radians, strictly below π/2), `casts_shadow` (true), and `shadow_priority` (integer 0). Existing fields and component IDs remain valid. Cross-field validation requires `0 <= inner_angle <= outer_angle`; local range, color channels, intensity, transforms, and cone directions must be finite. Invalid authored values return a diagnostic with entity and field rather than nonfinite GPU data. Missing new fields use the schema defaults.
`Snapshot` retains `light_direction` for existing direct-render clients. Add an optional `SunLight`, a vector of `LocalLight`, and an optional explicit `CameraFrustum` containing unjittered view/projection matrices, near/far distances, and projection kind. `SceneView` populates these from the authoring scene. Each light carries the stable entity/component identity, transformed position or normalized direction, color, intensity, range, cone angles, and shadow options. The first enabled directional light by stable ID is the sun; extra directionals produce a visible diagnostic until a later multi-sun design exists. If there is no authored directional light, the renderer synthesizes the legacy sun from `Snapshot::light_direction`. Local lights are ordered by stable ID to prevent reordering from changing atlas allocation or results. Point attenuation tends smoothly to zero at `range`; a spot multiplies it by a smooth inner-to-outer cone factor. The shader handles zero distance and invalid normals without NaN output.
Explicit camera frustum data is required for four cascades. If a low-level caller supplies only the legacy `view_projection`, the renderer uses one bounded legacy-compatible sun shadow view and reports `effective_sun_cascades = 1`; it never silently claims CSM. 2D sprite-only snapshots do not incur shadow work. The future temporal stage may jitter the main raster projection, but the shadow planner consumes the unjittered `CameraFrustum` exclusively.
## Graphics shader ABI and ownership
Preserve material descriptor **set 0** and its four bindings: sampled sun depth image at binding 0 (formerly the single shadow map), shadow sampler at 1, color image at 2, color sampler at 3. Add frame lighting descriptor **set 1** with a `StructuredBuffer` of a versioned, 16-byte-lane lighting header and local-light records plus one sampled 2D local depth atlas. Both the Direct pipeline and P2 GPU graphics pipeline bind this frame set; their fragment stage remains `fragmentMain` in `shaders/baseline.slang`. Move the P2 GPU vertex scene bindings (instance, visible-ID, view buffers) from set 1 to **set 2** in `shaders/gpu_scene.slang`, the Vulkan graphics layout, and the exact reflection validator. P2 cull and HZB compute bindings stay in their current set 0. Baseline graphics push constants remain 96 bytes and P2 graphics push constants remain 112 bytes, under the Vulkan 1.3 guaranteed 128-byte minimum. The shadow vertex entry can continue to read a per-view matrix through the existing push block, so no new shader entry is required for atlas rasterization.
Host and Slang structs have named offsets, strides, static assertions, and reflection checks. Keep the SPIR-V + normalized Faset reflection package as the runtime boundary; `slangc` remains a build dependency, not a Player dependency. Existing shader-reload behavior must preserve working pipelines when an incompatible or invalid bundle is offered. Update the package validator and export checks whenever an entry or layout changes. Lighting buffers are renderer-owned per frame and never expose Vulkan types to authoring, gameplay, or MCP.
## Sun cascades and atlas
Use four practical-split cascades between the camera near plane and `min(camera far, 80 world units)` with λ = 0.5. Bound each receiver frustum slice by a stable square extent derived from its enclosing sphere in sun-light space; snap the XY projection center to its effective texel grid so small camera movement does not shimmer. The sun atlas is one 2048² D32 image with four 1024² tiles, including a two-texel guard inside each tile. Its C++/shader metadata contains each light VP, split end, atlas scale/offset, effective UV clamp, and bias. Select the cascade by unjittered view depth and blend over the final 5% of a split to avoid a hard line. Three-by-three PCF samples clamp to that tile's guarded interior. Atlas rendering clears each tile independently and samples it only after the whole atlas transitions from depth attachment to depth read-only. The split/fitting, atlas, blend, PCF guard, and depth-bias considerations follow Microsoft's [CSM technical article](https://learn.microsoft.com/en-us/windows/win32/dxtecharts/cascaded-shadow-maps) and [shadow depth-map guidance](https://github.com/MicrosoftDocs/win32/blob/docs/desktop-src/DxTechArts/common-techniques-to-improve-shadow-depth-maps.md); Faset's actual implementation remains Vulkan-native.
The receiver frustum determines a cascade's XY footprint, but casters upstream of the camera slice still matter. Build shadow-view visibility from world-space caster bounds, never the main camera's P2 visible IDs. Extend the light-space depth interval conservatively over all cast-shadow bounds overlapping the cascade's XY footprint, then test candidates against that resulting view. Do not truncate this interval by the main camera far plane. Shadow geometry uses source LOD 0 initially, independent of the main camera's selected mesh LOD; a measured shadow-LOD policy can follow later.
## Local shadows and budgets
The local atlas is a separate 2048² D32 image with sixteen 512² guarded tiles. A spot light uses one perspective shadow view; a point light uses six 90° face views and receives all six tiles or none. A shadow tile stores its owner stable ID/face and generation. Rank candidate shadowed lights by authored `shadow_priority`, then projected influence, then stable ID; keep allocations stable while their owners remain eligible. Lower-priority lights that do not fit still illuminate the scene without shadowing, with an explicit reason/counter. No partial point-light shadow cubemap is allowed.
At most 128 local lights are submitted to the shader per view; select them deterministically by priority/influence if more exist and report the count of omitted lights. At most 16 local shadow faces and 4096 caster draws per frame are scheduled. Shadow views are atomic for draw budgeting: if all casters for a view do not fit, skip that view and treat its contribution as unshadowed. Sun cascades are considered nearest first; local views follow by priority. The policy exposes requested and effective counts. If the nearest cascade itself exceeds the draw budget, it becomes unshadowed rather than emitting an incomplete shadow. No skipped tile is sampled. Atlas allocation is capped at 32 MiB of D32 image payload for both atlases, excluding Vulkan alignment/driver overhead; actual allocation bytes remain visible in `FrameStats`.
Check D32 sampled/depth-attachment support, 2048² image extent, relevant sampled-image/storage-buffer limits, and allocation results before enabling the corresponding shadow feature. If the 2048² profile is unavailable, try a 1024² profile with four 512² sun tiles and sixteen 256² local tiles. If neither profile is available, keep direct lighting and explicitly report shadows unavailable. A failed optional atlas must not silently disable local illumination or crash a scene that previously rendered. Maintain explicit Vulkan transitions and barriers; the current `RenderGraph` validates ordering but does not synthesize barriers. One `ShadowAtlases` graph pass may loop over tile rendering instances because graph pass names must be unique.
Every scheduled view records why it was redrawn (first use, light/camera/caster change, atlas reassignment, or conservative every-frame update), its caster count, tile, and GPU time. Caching is optional in this stage: reporting an every-frame update is preferable to reusing stale depth. If caching is introduced, an uncertain caster revision forces a redraw. Camera cuts, resolution changes, light deletion, and slot reuse invalidate relevant assignments and histories.
## Forward+ measurement gate and diagnostics
Start with a correct bounded loop over local lights in the fragment shader. Benchmark fixed 1080p scenes with 0, 4, 16, 32, 64, and 128 visible local lights in Release, with shadows separately disabled and enabled. Retain raw per-frame CSV, driver/GPU/commit/configuration, warm-up and three repeated runs, median and p95 of main raster, shadow passes, full GPU command span, and capture/readback CPU time. The current full framebuffer readback is synchronous, so its CPU cost is not attributed to light shading. If 32 or more lights add at least 1.0 ms median to main raster or at least 15% of the light-free GPU frame on the Linux reference GPU, add tiled Forward+; otherwise record why the simple path remains default and keep the measurement harness for later hardware. A conservative, depth-free 16×16 screen-tile list built from projected light volumes is sufficient for the first measured optimization; it does not require a depth prepass before the existing forward pass. No light may disappear on list overflow: the fragment path checks an overflow flag and scans the full submitted-light list for that tile. Measure the sum of list construction and raster, not the raster pass alone, before enabling tiled mode by default.
`FrameStats`, Player diagnostics, and the editor debug overlay expose requested/effective sun cascades, visible and omitted local lights, scheduled/dropped shadow faces and reasons, atlas occupancy and allocated bytes, caster draws, shadow GPU time, and the active lighting path. Counters remain diagnostic-only; they do not require GPU readback for scheduling. Shadow atlas thumbnails may be added to developer diagnostics but are not a prerequisite for functional lighting.
## Acceptance and integration boundaries
CPU tests cover schema defaults/invalid fields, stable extraction from reordered entities, shadow-view math, cascade split/texel snap, offscreen casters, deterministic atlas allocation and face/draw capacity, point-light all-or-none behavior, and fallback capability policy. GPU image tests cover point distance, spot cone, color/intensity, sun cascade boundaries, caster movement, camera translation/cut/resize, point seams and atlas tile isolation, overflow as unshadowed light, and Direct vs P2 frustum/occlusion equivalence. Shader reflection, hot reload, exported Player shader contents, and Vulkan validation are exercised on Linux physical GPU and pinned Linux SwiftShader; Windows native build, GPU-labeled CI tests, and relocated exported Player examples run on pinned Windows SwiftShader. A physical Windows GPU is reported only if actually tested. The manual documents light properties, budgets, expected fallbacks, and script/editor examples. Acceptance records commit, hardware/driver, raw benchmark data, tests, known limitations, and links from `PLAN.md` without claiming universal speedups.
Temporal reconstruction owns previous transforms, velocity targets, jitter, history rejection, TAA, and upscaling. Lighting owns only stable unjittered shadow views and direct-light data. The shared files `renderer.hpp`, `renderer.cpp`, and `baseline.slang` need sequenced integration or an agreed ABI commit before concurrent feature work; temporal code must not repurpose the lighting descriptors or shadow camera metadata.
@@ -0,0 +1,59 @@
# P3 temporal reconstruction design
This design implements the temporal half of [PLAN P3](../../../PLAN.md#p3-освещение-тени-и-temporal-reconstruction) for Linux and Windows desktop games. The outcome is a selectable, observable 1:1 TAA path followed by a lower-internal-resolution temporal upscaler. The existing Direct renderer without temporal processing remains the reference and the default. P3 lighting and shadow work has its own design and can change the scene shader's lighting inputs without changing the temporal pass contract.
Temporal renderer and shader integration starts **after** the lighting plan's Task 2 checkpoint commit, `Share typed multi-light shading across Direct and GPU paths`. That commit establishes material descriptor set 0, frame-lighting set 1, and GPU graphics scene set 2; GPU cull/HZB compute descriptors remain in set 0. Temporal graphics variants consume the same material and lighting sets as `fragmentMain`, add prior-transform reads only from the GPU scene set 2, and leave the 96-byte Direct and 112-byte GPU graphics push constants intact. Temporal resolve/composite use their own checked pipeline layouts. The shared reflection and hot-reload validator must accept the combined ABI, not reconstruct the pre-lighting set 1 layout.
## Boundaries and modes
`RendererConfig` selects `TemporalMode::Off`, `TAA`, or `Upscale`; `Upscale` also specifies an internal render scale in `[0.5, 1)`. TAA uses scale `1`. A runtime setter lets Editor and Player select the same modes without changing scene authoring files. Requested and effective modes are recorded separately: unsupported compute/format/extent capabilities produce an explicit `Off` fallback and a readable reason. Invalid scale is rejected as configuration input, rather than silently clamped. An exported Player contains cooked SPIR-V and reflection; Slang is not needed at runtime. Temporal processing is renderer-side and adds no live-game MCP endpoint.
The output extent remains `Renderer::width()/height()`, the swapchain/capture extent and the pixel coordinate system of UI. At scale below one, opaque and world-space raster targets use an internal extent, with integer rounding made deterministic. `Snapshot::scene_rect` remains in output pixels; it is converted once to the internal viewport. Camera aspect and projection remain those of the output scene rectangle. Shadow map dimensions and light-space matrices never depend on render scale. HZB dimensions, viewport metadata, culling projection, and post-cull depth refer to the actual internal scene target.
## Frame data and history ownership
The caller supplies an **unjittered** `Snapshot::view_projection` and `projection`. Picking, gizmos, and authoring coordinates continue using them. The renderer chooses a deterministic Halton(2,3) subpixel offset, applies it only to the scene raster clip transform, and retains both current and previous jittered view-projection matrices. The offset is measured in internal scene pixels and enters clip space as `clip.xy += 2 * jitter / internalViewportSize * clip.w`; the sign is verified by an image/motion test for the Vulkan viewport convention. Culling and HZB projections must match the jittered geometry they test, with conservative edge handling. `Snapshot::camera_cut` is authoritative; a large discontinuity in camera position/orientation also rejects history when a caller fails to mark a teleport.
`InstanceTracker` already records `previous_model`, world bounds, a stable slot/generation, mesh identity and rendered-frame completion. That state becomes available to both Direct and GPU paths. HZB history and temporal color history have **independent** validity decisions; absence of HZB or a Direct visibility mode cannot invalidate an otherwise valid TAA history. Mesh/LOD replacement, reused slot, an anonymous draw, camera cut and changed view make that instance's velocity invalid. GPU `InstanceRecord` gains a previous model matrix while keeping the existing stable slot/generation lanes. The `metadata.x` low bit remains the HZB eligibility bit and a distinct bit marks temporal previous-transform eligibility; culling tests only the HZB bit. Dense candidate indices remain frame-local addresses, not temporal identities.
Temporal color/depth history is renderer-owned and double-buffered at **output resolution**. Each completed render commits one frame. A pending failed render must not promote history. The current active view may reuse history only if the previous frame has the same `view_id`, output/internal extents, scene rectangle, unjittered projection, temporal mode/scale, and compatible shader generation, and is not a cut. Switching among views safely resets history; retaining multiple cached histories is not required. Resize, shader reload, mode or scale change, and camera discontinuity reset it explicitly. The first valid frame uses current color only. The reset reason and whether a previous history was actually used are visible in `FrameStats` and Editor diagnostics.
## Motion and reconstruction signal
Both opaque mesh paths write the same per-pixel motion contract:
- Direct path: the CPU-transformed vertex carries current clip position, prior clip position computed from `InstanceUpdate::previous_model` and prior jittered view-projection, plus a validity flag. The existing Off vertex format/shader remains a compatible path.
- GPU path: the vertex shader reads current/previous model matrices from the instance record and current/previous jittered view-projections from the view record. It emits current and prior clip coordinates plus validity. Both Main and Post raster use this contract.
- The scene fragment writes display-UV motion (`currentUV - previousUV`), expected depth in the previous projection, and validity/reactive state to a sampled floating-point MRT. A missing prior transform, invalid clip `w`, nonfinite projection, or non-opaque/reactive fragment marks motion invalid. UI never contributes motion. UVs are local to the scene rectangle so internal and output extents map consistently.
The scene image remains the current renderer's display-referred LDR shading for this stage. History uses a higher-precision floating-point color image so repeated accumulation does not quantize to 8 bits; the final composite writes the existing `R8G8B8A8_UNORM` output exactly once. There is no exposure adaptation or HDR claim in this temporal implementation. P3 lighting may later move scene shading to linear HDR behind the same `sceneColor/depth/velocity -> resolvedColor` boundary.
The signal checklist is informed by [AMD's FSR 2 integration guide](https://github.com/GPUOpen-Effects/FidelityFX-FSR2/blob/master/README.md#input-resources): it describes current color, depth, motion and reactive data, and explicit reset on camera cuts. Faset implements its own resolver and does not link FSR 2. Faset's **current-minus-previous local UV** motion sign and jitter-inclusive convention are its own contract; an FSR 2 adapter would have to convert to that API's documented motion and jitter conventions. [NVIDIA's Adaptive TAA paper](https://research.nvidia.com/publication/2018-08_adaptive-temporal-antialiasing) identifies blur and ghosting as temporal failure modes, which motivates the moving-image acceptance tests here; its adaptive ray-tracing algorithm is not part of this design.
The 1:1 TAA resolve samples current color/depth/velocity, dilates motion from the nearest depth in a 3×3 neighborhood at silhouettes, and computes `previousUV = currentUV - motion`. It rejects history when view history or fragment motion is invalid, coordinates leave the previous scene rectangle, or previous expected depth disagrees with sampled history depth beyond a depth-aware tolerance. Surviving history color is clipped to a current-color 3×3 neighborhood and blended with a bounded weight reduced by motion and reactive content. A newly exposed background pixel must use current color immediately; it may accumulate normally on following frames. The resolve writes color and depth to the next output-resolution history image. Sky/clear pixels use current color when reliable reprojection is unavailable.
`Upscale` reuses this validated resolve but samples current color/depth/velocity from a lower internal extent. It reconstructs the current signal at output-pixel positions, keeps output-resolution history, and uses the same rejection/dilation and first-frame spatial fallback. Switching render scale resets history. TAA must pass its moving-image tests before upscaling is enabled or described as complete; this path is a small, measured temporal upscaler, not a promise of Unreal TSR quality.
## Render graph and scene/UI split
The temporal path adds internal `sceneColor`, `sceneDepth`, and `sceneVelocity` targets while retaining `color` as the full-resolution final image used by Readback and Presentation. Existing Off rendering and its one-target shader remain available. The temporal graph orders passes as follows:
1. ShadowMap and optional P2 MainCull.
2. Main scene raster clears scene color/depth/velocity and renders opaque meshes. Optional P2 BuildCurrentHZB and PostCull run from this scene depth, then PostRaster loads all three scene attachments and finishes deferred opaque meshes.
3. World transparency and sprites render against the same internal scene depth before resolve. Pixels they blend into color mark their velocity/reactive value invalid, so stale opaque history cannot leak through moving translucent content. They do not acquire synthetic rigid-mesh motion. The existing ordering and depth behavior are retained.
4. TemporalResolve reads the completed scene image/depth/velocity and previous history, writes the next color/depth history. TemporalComposite maps that resolved scene to the full-size `color` target.
5. A separate output-resolution UI pass renders quads, text, gizmo overlays and Editor chrome on `color`, without jitter or TAA. Readback and Presentation then consume `color` as before.
Only the temporal-enabled branch needs new scene targets and a second color attachment in opaque pipelines. A one-target UI pipeline remains valid. `RenderGraph` validates ordering by names; Vulkan layout transitions and compute→sampled/attachment barriers are recorded explicitly. The renderer's single queue, fence-per-frame model makes history lifetime simple but its synchronous capture/readback cost remains part of full-frame timings. The present 12-slot GPU timestamp pool must grow enough to time every new pass instead of silently omitting the end of the graph.
## Shader package, controls and fallback
Temporal vertex/fragment, resolve and composite entry points have validated reflection, SPIR-V hash, descriptor types and record strides. Adding `previousModel` changes the GPU instance stride; the C++ static assertion, Slang record, reflection validator and GPU tests change together. Baseline Off shaders retain their existing entry points and layout fingerprints. Shader reload replaces a **complete** compatible temporal pipeline set atomically or preserves the working set; successful reload invalidates color history. BuildService copies every temporal `.spv` and `.reflection.json` into Linux/Windows exports and validates a relocated Player without Slang installed.
Editor diagnostics expose mode, scale, effective mode/fallback, internal extent, jitter, history accepted/reset reason, reject statistics when requested, GPU temporal pass time and memory. Player profiling records these same fields per frame. GPU readback for per-pixel diagnostics is optional and never required for the normal resolve. If temporal resources cannot be created on a supported Vulkan 1.3 device, the actual mode is `Off`, the frame still renders by the existing path, and the reason is reported. A failed temporal shader reload keeps the prior pipelines and does not corrupt history or change the visible mode.
## Acceptance
Deterministic headless GPU sequences run for Direct, GPU frustum and GPU occlusion where supported. They cover static thin diagonals/wires at subpixel positions, slow camera pan, a moving rigid object, a doorway disocclusion, an explicit camera cut and unmarked teleport, projection/view/scene-rectangle/resize/mode/scale changes, anonymous and mesh-replaced instances, world transparency, sprites and pixel-exact UI. Tests compare current frames to `Off` and a high-resolution spatial reference, with fixed tolerance and documented image metrics rather than requiring bit-identical output across drivers. They assert zero Vulkan validation errors where the layer is present, no reappearance of old color after cut/reveal, correct actual mode and reset reason, and no UI softening. A clean fallback is exercised on a deliberately unsupported capability fixture.
Run CPU policy tests, reflection/package/tamper tests, Linux validation on physical GPU and software Vulkan, Windows software Vulkan CI and native builds, and relocated 2D/3D Player captures. Record the exact revision, driver/GPU, build mode, internal/output resolutions, temporal and full-frame GPU/CPU costs, memory, image differences, and limitations. These results gate any claim that TAA/upscaling improves image quality or frame time in a particular scene.