From a003e58a6a47eb6a6edaa7b4ba54e6611d99560c Mon Sep 17 00:00:00 2001 From: ShinniUwU Date: Wed, 25 Nov 2026 21:48:45 +0100 Subject: [PATCH 1/6] chore: add the systematic-debugging and tdd agent skills --- .claude/skills/systematic-debugging/SKILL.md | 283 ++++++++++++++++++ .../condition-based-waiting.md | 115 +++++++ .../systematic-debugging/defense-in-depth.md | 122 ++++++++ .../systematic-debugging/find-polluter.sh | 72 +++++ .../root-cause-tracing.md | 169 +++++++++++ .claude/skills/tdd/SKILL.md | 38 +++ .claude/skills/tdd/agents/openai.yaml | 3 + .claude/skills/tdd/mocking.md | 59 ++++ .claude/skills/tdd/tests.md | 77 +++++ .gitignore | 3 + skills-lock.json | 28 ++ 11 files changed, 969 insertions(+) create mode 100644 .claude/skills/systematic-debugging/SKILL.md create mode 100644 .claude/skills/systematic-debugging/condition-based-waiting.md create mode 100644 .claude/skills/systematic-debugging/defense-in-depth.md create mode 100644 .claude/skills/systematic-debugging/find-polluter.sh create mode 100644 .claude/skills/systematic-debugging/root-cause-tracing.md create mode 100644 .claude/skills/tdd/SKILL.md create mode 100644 .claude/skills/tdd/agents/openai.yaml create mode 100644 .claude/skills/tdd/mocking.md create mode 100644 .claude/skills/tdd/tests.md create mode 100644 skills-lock.json diff --git a/.claude/skills/systematic-debugging/SKILL.md b/.claude/skills/systematic-debugging/SKILL.md new file mode 100644 index 000000000..62fc752aa --- /dev/null +++ b/.claude/skills/systematic-debugging/SKILL.md @@ -0,0 +1,283 @@ +--- +name: systematic-debugging +description: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes +--- + +# Systematic Debugging + +## Overview + +**Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure. + +**Violating the letter of this process is violating the spirit of debugging.** + +## The Iron Law + +``` +NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST +``` + +If you haven't completed Phase 1, you cannot propose fixes. + +## When to Use + +Use for ANY technical issue: +- Test failures +- Bugs in production +- Unexpected behavior +- Performance problems +- Build failures +- Integration issues + +**Use this ESPECIALLY when:** +- Under time pressure (emergencies make guessing tempting) +- "Just one quick fix" seems obvious +- You've already tried multiple fixes +- Previous fix didn't work +- You don't fully understand the issue + +**Don't skip when:** +- Issue seems simple (simple bugs have root causes too) +- You're in a hurry (rushing guarantees rework) +- Manager wants it fixed NOW (systematic is faster than thrashing) + +## The Four Phases + +You MUST complete each phase before proceeding to the next. + +### Phase 1: Root Cause Investigation + +**BEFORE attempting ANY fix:** + +1. **Read Error Messages Carefully** + - Don't skip past errors or warnings + - They often contain the exact solution + - Read stack traces completely + - Note line numbers, file paths, error codes + +2. **Reproduce Consistently** + - Can you trigger it reliably? + - What are the exact steps? + - Does it happen every time? + - If not reproducible → gather more data, don't guess + +3. **Check Recent Changes** + - What changed that could cause this? + - Git diff, recent commits + - New dependencies, config changes + - Environmental differences + +4. **Gather Evidence in Multi-Component Systems** + + **WHEN system has multiple components (CI → build → signing, API → service → database):** + + **BEFORE proposing fixes, add diagnostic instrumentation:** + ``` + For EACH component boundary: + - Log what data enters component + - Log what data exits component + - Verify environment/config propagation + - Check state at each layer + + Run once to gather evidence showing WHERE it breaks + THEN analyze evidence to identify failing component + THEN investigate that specific component + ``` + + **Example (multi-layer system):** + ```bash + # Layer 1: Workflow + echo "=== Secrets available in workflow: ===" + echo "IDENTITY: $([ -n "${IDENTITY:-}" ] && echo SET || echo UNSET)" + + # Layer 2: Build script + echo "=== Env vars in build script: ===" + printenv IDENTITY >/dev/null 2>&1 && echo "IDENTITY in environment" || echo "IDENTITY not in environment" + + # Layer 3: Signing script + echo "=== Keychain state: ===" + security list-keychains + security find-identity -v + + # Layer 4: Actual signing + codesign --sign "$IDENTITY" --verbose=4 "$APP" + ``` + + **This reveals:** Which layer fails (secrets → workflow ✓, workflow → build ✗) + +5. **Trace Data Flow** + + **WHEN error is deep in call stack:** + + See `root-cause-tracing.md` in this directory for the complete backward tracing technique. + + **Quick version:** + - Where does bad value originate? + - What called this with bad value? + - Keep tracing up until you find the source + - Fix at source, not at symptom + +### Phase 2: Pattern Analysis + +**Find the pattern before fixing:** + +1. **Find Working Examples** + - Locate similar working code in same codebase + - What works that's similar to what's broken? + +2. **Compare Against References** + - If implementing pattern, read reference implementation COMPLETELY + - Don't skim - read every line + - Understand the pattern fully before applying + +3. **Identify Differences** + - What's different between working and broken? + - List every difference, however small + - Don't assume "that can't matter" + +4. **Understand Dependencies** + - What other components does this need? + - What settings, config, environment? + - What assumptions does it make? + +### Phase 3: Hypothesis and Testing + +**Scientific method:** + +1. **Form Single Hypothesis** + - State clearly: "I think X is the root cause because Y" + - Write it down + - Be specific, not vague + +2. **Test Minimally** + - Make the SMALLEST possible change to test hypothesis + - One variable at a time + - Don't fix multiple things at once + +3. **Verify Before Continuing** + - Did it work? Yes → Phase 4 + - Didn't work? Form NEW hypothesis + - DON'T add more fixes on top + +4. **When You Don't Know** + - Say "I don't understand X" + - Don't pretend to know + - Ask for help + - Research more + +### Phase 4: Implementation + +**Fix the root cause, not the symptom:** + +1. **Create Failing Test Case** + - Simplest possible reproduction + - Automated test if possible + - One-off test script if no framework + - MUST have before fixing + - Use the `superpowers:test-driven-development` skill for writing proper failing tests + +2. **Implement Single Fix** + - Address the root cause identified + - ONE change at a time + - No "while I'm here" improvements + - No bundled refactoring + +3. **Verify Fix** + - Test passes now? + - No other tests broken? + - Issue actually resolved? + - Use the `superpowers:verification-before-completion` skill before claiming success + +4. **If Fix Doesn't Work** + - STOP + - Count: How many fixes have you tried? + - If < 3: Return to Phase 1, re-analyze with new information + - **If ≥ 3: STOP and question the architecture (step 5 below)** + - DON'T attempt Fix #4 without architectural discussion + +5. **If 3+ Fixes Failed: Question Architecture** + + **Pattern indicating architectural problem:** + - Each fix reveals new shared state/coupling/problem in different place + - Fixes require "massive refactoring" to implement + - Each fix creates new symptoms elsewhere + + **STOP and question fundamentals:** + - Is this pattern fundamentally sound? + - Are we "sticking with it through sheer inertia"? + - Should we refactor architecture vs. continue fixing symptoms? + + **Discuss with your human partner before attempting more fixes** + + This is NOT a failed hypothesis - this is a wrong architecture. + +## Red Flags - STOP and Follow Process + +If you catch yourself thinking: +- "Quick fix for now, investigate later" +- "Just try changing X and see if it works" +- "Add multiple changes, run tests" +- "Skip the test, I'll manually verify" +- "It's probably X, let me fix that" +- "I don't fully understand but this might work" +- "Pattern says X but I'll adapt it differently" +- "Here are the main problems: [lists fixes without investigation]" +- Proposing solutions before tracing data flow +- **"One more fix attempt" (when already tried 2+)** +- **Each fix reveals new problem in different place** + +**ALL of these mean: STOP. Return to Phase 1.** + +**If 3+ fixes failed:** Question the architecture (see Phase 4.5) + +## your human partner's Signals You're Doing It Wrong + +**Watch for these redirections:** +- "Is that not happening?" - You assumed without verifying +- "Will it show us...?" - You should have added evidence gathering +- "Stop guessing" - You're proposing fixes without understanding +- "Ultra-think this" - Question fundamentals, not just symptoms +- "We're stuck?" (frustrated) - Your approach isn't working + +**When you see these:** STOP. Return to Phase 1. + +## Common Rationalizations + +| Excuse | Reality | +|--------|---------| +| "Issue is simple, don't need process" | Simple issues have root causes too. Process is fast for simple bugs. | +| "Emergency, no time for process" | Systematic debugging is FASTER than guess-and-check thrashing. | +| "Just try this first, then investigate" | First fix sets the pattern. Do it right from the start. | +| "I'll write test after confirming fix works" | Untested fixes don't stick. Test first proves it. | +| "Multiple fixes at once saves time" | Can't isolate what worked. Causes new bugs. | +| "Reference too long, I'll adapt the pattern" | Partial understanding guarantees bugs. Read it completely. | +| "I see the problem, let me fix it" | Seeing symptoms ≠ understanding root cause. | +| "One more fix attempt" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. | + +## Quick Reference + +| Phase | Key Activities | Success Criteria | +|-------|---------------|------------------| +| **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY | +| **2. Pattern** | Find working examples, compare | Identify differences | +| **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis | +| **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass | + +## When Process Reveals "No Root Cause" + +If systematic investigation reveals issue is truly environmental, timing-dependent, or external: + +1. You've completed the process +2. Document what you investigated +3. Implement appropriate handling (retry, timeout, error message) +4. Add monitoring/logging for future investigation + +**But:** 95% of "no root cause" cases are incomplete investigation. + +## Supporting Techniques + +These techniques are part of systematic debugging and available in this directory: + +- **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger +- **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause +- **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling diff --git a/.claude/skills/systematic-debugging/condition-based-waiting.md b/.claude/skills/systematic-debugging/condition-based-waiting.md new file mode 100644 index 000000000..70994f777 --- /dev/null +++ b/.claude/skills/systematic-debugging/condition-based-waiting.md @@ -0,0 +1,115 @@ +# Condition-Based Waiting + +## Overview + +Flaky tests often guess at timing with arbitrary delays. This creates race conditions where tests pass on fast machines but fail under load or in CI. + +**Core principle:** Wait for the actual condition you care about, not a guess about how long it takes. + +## When to Use + +```dot +digraph when_to_use { + "Test uses setTimeout/sleep?" [shape=diamond]; + "Testing timing behavior?" [shape=diamond]; + "Document WHY timeout needed" [shape=box]; + "Use condition-based waiting" [shape=box]; + + "Test uses setTimeout/sleep?" -> "Testing timing behavior?" [label="yes"]; + "Testing timing behavior?" -> "Document WHY timeout needed" [label="yes"]; + "Testing timing behavior?" -> "Use condition-based waiting" [label="no"]; +} +``` + +**Use when:** +- Tests have arbitrary delays (`setTimeout`, `sleep`, `time.sleep()`) +- Tests are flaky (pass sometimes, fail under load) +- Tests timeout when run in parallel +- Waiting for async operations to complete + +**Don't use when:** +- Testing actual timing behavior (debounce, throttle intervals) +- Always document WHY if using arbitrary timeout + +## Core Pattern + +```typescript +// ❌ BEFORE: Guessing at timing +await new Promise(r => setTimeout(r, 50)); +const result = getResult(); +expect(result).toBeDefined(); + +// ✅ AFTER: Waiting for condition +await waitFor(() => getResult() !== undefined); +const result = getResult(); +expect(result).toBeDefined(); +``` + +## Quick Patterns + +| Scenario | Pattern | +|----------|---------| +| Wait for event | `waitFor(() => events.find(e => e.type === 'DONE'))` | +| Wait for state | `waitFor(() => machine.state === 'ready')` | +| Wait for count | `waitFor(() => items.length >= 5)` | +| Wait for file | `waitFor(() => fs.existsSync(path))` | +| Complex condition | `waitFor(() => obj.ready && obj.value > 10)` | + +## Implementation + +Generic polling function: +```typescript +async function waitFor( + condition: () => T | undefined | null | false, + description: string, + timeoutMs = 5000 +): Promise { + const startTime = Date.now(); + + while (true) { + const result = condition(); + if (result) return result; + + if (Date.now() - startTime > timeoutMs) { + throw new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`); + } + + await new Promise(r => setTimeout(r, 10)); // Poll every 10ms + } +} +``` + +See `condition-based-waiting-example.ts` in this directory for complete implementation with domain-specific helpers (`waitForEvent`, `waitForEventCount`, `waitForEventMatch`) from actual debugging session. + +## Common Mistakes + +**❌ Polling too fast:** `setTimeout(check, 1)` - wastes CPU +**✅ Fix:** Poll every 10ms + +**❌ No timeout:** Loop forever if condition never met +**✅ Fix:** Always include timeout with clear error + +**❌ Stale data:** Cache state before loop +**✅ Fix:** Call getter inside loop for fresh data + +## When Arbitrary Timeout IS Correct + +```typescript +// Tool ticks every 100ms - need 2 ticks to verify partial output +await waitForEvent(manager, 'TOOL_STARTED'); // First: wait for condition +await new Promise(r => setTimeout(r, 200)); // Then: wait for timed behavior +// 200ms = 2 ticks at 100ms intervals - documented and justified +``` + +**Requirements:** +1. First wait for triggering condition +2. Based on known timing (not guessing) +3. Comment explaining WHY + +## Real-World Impact + +From debugging session (2025-10-03): +- Fixed 15 flaky tests across 3 files +- Pass rate: 60% → 100% +- Execution time: 40% faster +- No more race conditions diff --git a/.claude/skills/systematic-debugging/defense-in-depth.md b/.claude/skills/systematic-debugging/defense-in-depth.md new file mode 100644 index 000000000..e2483354d --- /dev/null +++ b/.claude/skills/systematic-debugging/defense-in-depth.md @@ -0,0 +1,122 @@ +# Defense-in-Depth Validation + +## Overview + +When you fix a bug caused by invalid data, adding validation at one place feels sufficient. But that single check can be bypassed by different code paths, refactoring, or mocks. + +**Core principle:** Validate at EVERY layer data passes through. Make the bug structurally impossible. + +## Why Multiple Layers + +Single validation: "We fixed the bug" +Multiple layers: "We made the bug impossible" + +Different layers catch different cases: +- Entry validation catches most bugs +- Business logic catches edge cases +- Environment guards prevent context-specific dangers +- Debug logging helps when other layers fail + +## The Four Layers + +### Layer 1: Entry Point Validation +**Purpose:** Reject obviously invalid input at API boundary + +```typescript +function createProject(name: string, workingDirectory: string) { + if (!workingDirectory || workingDirectory.trim() === '') { + throw new Error('workingDirectory cannot be empty'); + } + if (!existsSync(workingDirectory)) { + throw new Error(`workingDirectory does not exist: ${workingDirectory}`); + } + if (!statSync(workingDirectory).isDirectory()) { + throw new Error(`workingDirectory is not a directory: ${workingDirectory}`); + } + // ... proceed +} +``` + +### Layer 2: Business Logic Validation +**Purpose:** Ensure data makes sense for this operation + +```typescript +function initializeWorkspace(projectDir: string, sessionId: string) { + if (!projectDir) { + throw new Error('projectDir required for workspace initialization'); + } + // ... proceed +} +``` + +### Layer 3: Environment Guards +**Purpose:** Prevent dangerous operations in specific contexts + +```typescript +async function gitInit(directory: string) { + // In tests, refuse git init outside temp directories + if (process.env.NODE_ENV === 'test') { + const normalized = normalize(resolve(directory)); + const tmpDir = normalize(resolve(tmpdir())); + + if (!normalized.startsWith(tmpDir)) { + throw new Error( + `Refusing git init outside temp dir during tests: ${directory}` + ); + } + } + // ... proceed +} +``` + +### Layer 4: Debug Instrumentation +**Purpose:** Capture context for forensics + +```typescript +async function gitInit(directory: string) { + const stack = new Error().stack; + logger.debug('About to git init', { + directory, + cwd: process.cwd(), + stack, + }); + // ... proceed +} +``` + +## Applying the Pattern + +When you find a bug: + +1. **Trace the data flow** - Where does bad value originate? Where used? +2. **Map all checkpoints** - List every point data passes through +3. **Add validation at each layer** - Entry, business, environment, debug +4. **Test each layer** - Try to bypass layer 1, verify layer 2 catches it + +## Example from Session + +Bug: Empty `projectDir` caused `git init` in source code + +**Data flow:** +1. Test setup → empty string +2. `Project.create(name, '')` +3. `WorkspaceManager.createWorkspace('')` +4. `git init` runs in `process.cwd()` + +**Four layers added:** +- Layer 1: `Project.create()` validates not empty/exists/writable +- Layer 2: `WorkspaceManager` validates projectDir not empty +- Layer 3: `WorktreeManager` refuses git init outside tmpdir in tests +- Layer 4: Stack trace logging before git init + +**Result:** All 1847 tests passed, bug impossible to reproduce + +## Key Insight + +All four layers were necessary. During testing, each layer caught bugs the others missed: +- Different code paths bypassed entry validation +- Mocks bypassed business logic checks +- Edge cases on different platforms needed environment guards +- Debug logging identified structural misuse + +**Don't stop at one validation point.** Add checks at every layer. diff --git a/.claude/skills/systematic-debugging/find-polluter.sh b/.claude/skills/systematic-debugging/find-polluter.sh new file mode 100644 index 000000000..985f5d08c --- /dev/null +++ b/.claude/skills/systematic-debugging/find-polluter.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# Bisection script to find which test creates unwanted files/state +# Usage: ./find-polluter.sh +# Example: ./find-polluter.sh '.git' 'src/**/*.test.ts' + +set -e + +if [ $# -ne 2 ]; then + echo "Usage: $0 " + echo "Example: $0 '.git' 'src/**/*.test.ts'" + exit 1 +fi + +POLLUTION_CHECK="$1" +TEST_PATTERN="$2" + +echo "🔍 Searching for test that creates: $POLLUTION_CHECK" +echo "Test pattern: $TEST_PATTERN" +echo "" + +# Get list of test files (find . emits ./-prefixed paths, so accept the +# pattern written with or without a leading ./) +TEST_PATTERN="${TEST_PATTERN#./}" +# find -path can't match '**/' against zero directory levels, so a pattern +# like src/**/*.test.ts would skip src/top.test.ts; also try the pattern +# with '**/' collapsed to cover files directly under the base directory. +TEST_FILES=$(find . \( -path "./$TEST_PATTERN" -o -path "./${TEST_PATTERN//\*\*\//}" \) | sort -u) +if [ -z "$TEST_FILES" ]; then + TOTAL=0 +else + TOTAL=$(printf '%s\n' "$TEST_FILES" | wc -l | tr -d ' ') +fi + +echo "Found $TOTAL test files" +echo "" + +COUNT=0 +for TEST_FILE in $TEST_FILES; do + COUNT=$((COUNT + 1)) + + # Skip if pollution already exists + if [ -e "$POLLUTION_CHECK" ]; then + echo "⚠️ Pollution already exists before test $COUNT/$TOTAL" + echo " Skipping: $TEST_FILE" + continue + fi + + echo "[$COUNT/$TOTAL] Testing: $TEST_FILE" + + # Run the test + npm test "$TEST_FILE" > /dev/null 2>&1 || true + + # Check if pollution appeared + if [ -e "$POLLUTION_CHECK" ]; then + echo "" + echo "🎯 FOUND POLLUTER!" + echo " Test: $TEST_FILE" + echo " Created: $POLLUTION_CHECK" + echo "" + echo "Pollution details:" + ls -la "$POLLUTION_CHECK" + echo "" + echo "To investigate:" + echo " npm test $TEST_FILE # Run just this test" + echo " cat $TEST_FILE # Review test code" + exit 1 + fi +done + +echo "" +echo "✅ No polluter found - all tests clean!" +exit 0 diff --git a/.claude/skills/systematic-debugging/root-cause-tracing.md b/.claude/skills/systematic-debugging/root-cause-tracing.md new file mode 100644 index 000000000..0e72e8f95 --- /dev/null +++ b/.claude/skills/systematic-debugging/root-cause-tracing.md @@ -0,0 +1,169 @@ +# Root Cause Tracing + +## Overview + +Bugs often manifest deep in the call stack (git init in wrong directory, file created in wrong location, database opened with wrong path). Your instinct is to fix where the error appears, but that's treating a symptom. + +**Core principle:** Trace backward through the call chain until you find the original trigger, then fix at the source. + +## When to Use + +```dot +digraph when_to_use { + "Bug appears deep in stack?" [shape=diamond]; + "Can trace backwards?" [shape=diamond]; + "Fix at symptom point" [shape=box]; + "Trace to original trigger" [shape=box]; + "BETTER: Also add defense-in-depth" [shape=box]; + + "Bug appears deep in stack?" -> "Can trace backwards?" [label="yes"]; + "Can trace backwards?" -> "Trace to original trigger" [label="yes"]; + "Can trace backwards?" -> "Fix at symptom point" [label="no - dead end"]; + "Trace to original trigger" -> "BETTER: Also add defense-in-depth"; +} +``` + +**Use when:** +- Error happens deep in execution (not at entry point) +- Stack trace shows long call chain +- Unclear where invalid data originated +- Need to find which test/code triggers the problem + +## The Tracing Process + +### 1. Observe the Symptom +``` +Error: git init failed in ~/project/packages/core +``` + +### 2. Find Immediate Cause +**What code directly causes this?** +```typescript +await execFileAsync('git', ['init'], { cwd: projectDir }); +``` + +### 3. Ask: What Called This? +```typescript +WorktreeManager.createSessionWorktree(projectDir, sessionId) + → called by Session.initializeWorkspace() + → called by Session.create() + → called by test at Project.create() +``` + +### 4. Keep Tracing Up +**What value was passed?** +- `projectDir = ''` (empty string!) +- Empty string as `cwd` resolves to `process.cwd()` +- That's the source code directory! + +### 5. Find Original Trigger +**Where did empty string come from?** +```typescript +const context = setupCoreTest(); // Returns { tempDir: '' } +Project.create('name', context.tempDir); // Accessed before beforeEach! +``` + +## Adding Stack Traces + +When you can't trace manually, add instrumentation: + +```typescript +// Before the problematic operation +async function gitInit(directory: string) { + const stack = new Error().stack; + console.error('DEBUG git init:', { + directory, + cwd: process.cwd(), + nodeEnv: process.env.NODE_ENV, + stack, + }); + + await execFileAsync('git', ['init'], { cwd: directory }); +} +``` + +**Critical:** Use `console.error()` in tests (not logger - may not show) + +**Run and capture:** +```bash +npm test 2>&1 | grep 'DEBUG git init' +``` + +**Analyze stack traces:** +- Look for test file names +- Find the line number triggering the call +- Identify the pattern (same test? same parameter?) + +## Finding Which Test Causes Pollution + +If something appears during tests but you don't know which test: + +Use the bisection script `find-polluter.sh` in this directory: + +```bash +bash ./find-polluter.sh '.git' 'src/**/*.test.ts' +``` + +Runs tests one-by-one, stops at first polluter. See script for usage. + +## Real Example: Empty projectDir + +**Symptom:** `.git` created in `packages/core/` (source code) + +**Trace chain:** +1. `git init` runs in `process.cwd()` ← empty cwd parameter +2. WorktreeManager called with empty projectDir +3. Session.create() passed empty string +4. Test accessed `context.tempDir` before beforeEach +5. setupCoreTest() returns `{ tempDir: '' }` initially + +**Root cause:** Top-level variable initialization accessing empty value + +**Fix:** Made tempDir a getter that throws if accessed before beforeEach + +**Also added defense-in-depth:** +- Layer 1: Project.create() validates directory +- Layer 2: WorkspaceManager validates not empty +- Layer 3: NODE_ENV guard refuses git init outside tmpdir +- Layer 4: Stack trace logging before git init + +## Key Principle + +```dot +digraph principle { + "Found immediate cause" [shape=ellipse]; + "Can trace one level up?" [shape=diamond]; + "Trace backwards" [shape=box]; + "Is this the source?" [shape=diamond]; + "Fix at source" [shape=box]; + "Add validation at each layer" [shape=box]; + "Bug impossible" [shape=doublecircle]; + "NEVER fix just the symptom" [shape=octagon, style=filled, fillcolor=red, fontcolor=white]; + + "Found immediate cause" -> "Can trace one level up?"; + "Can trace one level up?" -> "Trace backwards" [label="yes"]; + "Can trace one level up?" -> "NEVER fix just the symptom" [label="no"]; + "Trace backwards" -> "Is this the source?"; + "Is this the source?" -> "Trace backwards" [label="no - keeps going"]; + "Is this the source?" -> "Fix at source" [label="yes"]; + "Fix at source" -> "Add validation at each layer"; + "Add validation at each layer" -> "Bug impossible"; +} +``` + +**NEVER fix just where the error appears.** Trace back to find the original trigger. + +## Stack Trace Tips + +**In tests:** Use `console.error()` not logger - logger may be suppressed +**Before operation:** Log before the dangerous operation, not after it fails +**Include context:** Directory, cwd, environment variables, timestamps +**Capture stack:** `new Error().stack` shows complete call chain + +## Real-World Impact + +From debugging session (2025-10-03): +- Found root cause through 5-level trace +- Fixed at source (getter validation) +- Added 4 layers of defense +- 1847 tests passed, zero pollution diff --git a/.claude/skills/tdd/SKILL.md b/.claude/skills/tdd/SKILL.md new file mode 100644 index 000000000..01eadaa34 --- /dev/null +++ b/.claude/skills/tdd/SKILL.md @@ -0,0 +1,38 @@ +--- +name: tdd +description: Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests. +--- + +# Test-Driven Development + +TDD is the red → green loop. This skill is the reference that makes that loop produce tests worth keeping: what a good test is, where tests go, the anti-patterns, and the rules of the loop. Every section applies on every cycle: consult them before and during the loop, not after. + +When exploring the codebase, read `GLOSSARY.md` (if it exists) so test names and interface vocabulary match the project's domain language, and respect ADRs in the area you're touching. + +## What a good test is + +Tests verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't. A good test reads like a specification: "user can checkout with valid cart" tells you exactly what capability exists, and it survives refactors because it doesn't care about internal structure. + +See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines. + +## Seams: where tests go + +A **seam** is the public boundary you test at: the interface where you observe behavior without reaching inside. Tests live at seams, never against internals. + +**Test only at pre-agreed seams.** Before writing any test, write down the seams under test and confirm them with the user. No test is written at an unconfirmed seam. You can't test everything, so agreeing the seams up front is how testing effort lands on the critical paths and complex logic instead of every edge case. + +Ask: "What's the public interface, and which seams should we test?" Give each proposed seam a one-line note on what it catches and what it misses. + +When the shape of that interface is itself in question (how deep the module is, where the seam belongs, what the interface should expose), call the Skill tool with "codebase-design" for the vocabulary. It is the shared source of the module, interface, depth, seam, adapter, leverage and locality terms, and it is a reference to consult, not a session to run. + +## Anti-patterns + +- **Implementation-coupled**: mocks internal collaborators, tests private methods, or verifies through a side channel (querying the database instead of using the interface). The tell: the test breaks when you refactor but behavior hasn't changed. +- **Tautological**: the assertion recomputes the expected value the way the code does (`expect(add(a, b)).toBe(a + b)`, a snapshot derived by hand the same way, a constant asserted equal to itself), so it passes by construction and can never disagree with the code. Expected values must come from an independent source of truth: a known-good literal, a worked example, the spec. +- **Horizontal slicing**: writing all tests first, then all implementation. Bulk tests verify _imagined_ behavior: you test the _shape_ of things rather than user-facing behavior, the tests go insensitive to real changes, and you commit to test structure before understanding the implementation. Work in **vertical slices** instead: one test → one implementation → repeat, each test a **tracer bullet** that responds to what the last cycle taught you. + +## Rules of the loop + +- **Red before green.** Write the failing test first, then only enough code to pass it. Don't anticipate future tests or add speculative features. +- **One slice at a time.** One seam, one test, one minimal implementation per cycle. +- **Refactoring is not part of the loop.** It belongs to the review stage (see the `code-review` skill), not the red → green implementation cycle. diff --git a/.claude/skills/tdd/agents/openai.yaml b/.claude/skills/tdd/agents/openai.yaml new file mode 100644 index 000000000..651b838a7 --- /dev/null +++ b/.claude/skills/tdd/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "TDD" + short_description: "Test-driven red-green-refactor" diff --git a/.claude/skills/tdd/mocking.md b/.claude/skills/tdd/mocking.md new file mode 100644 index 000000000..71cbfee67 --- /dev/null +++ b/.claude/skills/tdd/mocking.md @@ -0,0 +1,59 @@ +# When to Mock + +Mock at **system boundaries** only: + +- External APIs (payment, email, etc.) +- Databases (sometimes - prefer test DB) +- Time/randomness +- File system (sometimes) + +Don't mock: + +- Your own classes/modules +- Internal collaborators +- Anything you control + +## Designing for Mockability + +At system boundaries, design interfaces that are easy to mock: + +**1. Use dependency injection** + +Pass external dependencies in rather than creating them internally: + +```typescript +// Easy to mock +function processPayment(order, paymentClient) { + return paymentClient.charge(order.total); +} + +// Hard to mock +function processPayment(order) { + const client = new StripeClient(process.env.STRIPE_KEY); + return client.charge(order.total); +} +``` + +**2. Prefer SDK-style interfaces over generic fetchers** + +Create specific functions for each external operation instead of one generic function with conditional logic: + +```typescript +// GOOD: Each function is independently mockable +const api = { + getUser: (id) => fetch(`/users/${id}`), + getOrders: (userId) => fetch(`/users/${userId}/orders`), + createOrder: (data) => fetch('/orders', { method: 'POST', body: data }), +}; + +// BAD: Mocking requires conditional logic inside the mock +const api = { + fetch: (endpoint, options) => fetch(endpoint, options), +}; +``` + +The SDK approach means: +- Each mock returns one specific shape +- No conditional logic in test setup +- Easier to see which endpoints a test exercises +- Type safety per endpoint diff --git a/.claude/skills/tdd/tests.md b/.claude/skills/tdd/tests.md new file mode 100644 index 000000000..7ab86479f --- /dev/null +++ b/.claude/skills/tdd/tests.md @@ -0,0 +1,77 @@ +# Good and Bad Tests + +## Good Tests + +**Integration-style**: Test through real interfaces, not mocks of internal parts. + +```typescript +// GOOD: Tests observable behavior +test("user can checkout with valid cart", async () => { + const cart = createCart(); + cart.add(product); + const result = await checkout(cart, paymentMethod); + expect(result.status).toBe("confirmed"); +}); +``` + +Characteristics: + +- Tests behavior users/callers care about +- Uses public API only +- Survives internal refactors +- Describes WHAT, not HOW +- One logical assertion per test + +## Bad Tests + +**Implementation-detail tests**: Coupled to internal structure. + +```typescript +// BAD: Tests implementation details +test("checkout calls paymentService.process", async () => { + const mockPayment = jest.mock(paymentService); + await checkout(cart, payment); + expect(mockPayment.process).toHaveBeenCalledWith(cart.total); +}); +``` + +Red flags: + +- Mocking internal collaborators +- Testing private methods +- Asserting on call counts/order +- Test breaks when refactoring without behavior change +- Test name describes HOW not WHAT +- Verifying through external means instead of interface + +```typescript +// BAD: Bypasses interface to verify +test("createUser saves to database", async () => { + await createUser({ name: "Alice" }); + const row = await db.query("SELECT * FROM users WHERE name = ?", ["Alice"]); + expect(row).toBeDefined(); +}); + +// GOOD: Verifies through interface +test("createUser makes user retrievable", async () => { + const user = await createUser({ name: "Alice" }); + const retrieved = await getUser(user.id); + expect(retrieved.name).toBe("Alice"); +}); +``` + +**Tautological tests**: Expected value restates the implementation, so the test passes by construction. + +```typescript +// BAD: Expected value is recomputed the way the code computes it +test("calculateTotal sums line items", () => { + const items = [{ price: 10 }, { price: 5 }]; + const expected = items.reduce((sum, i) => sum + i.price, 0); + expect(calculateTotal(items)).toBe(expected); +}); + +// GOOD: Expected value is an independent, known literal +test("calculateTotal sums line items", () => { + expect(calculateTotal([{ price: 10 }, { price: 5 }])).toBe(15); +}); +``` diff --git a/.gitignore b/.gitignore index ba6dd0e69..a5755d01e 100644 --- a/.gitignore +++ b/.gitignore @@ -76,3 +76,6 @@ *.swp Thumbs.db .DS_Store + +# A TypeScript sample shipped with the systematic-debugging skill; .ts is not on the policy allowlist. +/.claude/skills/systematic-debugging/condition-based-waiting-example.ts diff --git a/skills-lock.json b/skills-lock.json new file mode 100644 index 000000000..d1eca2156 --- /dev/null +++ b/skills-lock.json @@ -0,0 +1,28 @@ +{ + "version": 2, + "skills": { + "rust-best-practices": { + "source": "apollographql/skills", + "commit": "9dda1397730370aeb8df4ff8f2015c34c86b5003", + "sourceType": "github", + "skillPath": "skills/rust-best-practices/SKILL.md", + "computedHash": "7e12e68aa50152eb7ba9ea1f88ca5380c846ea0175f8ab6788bb79b7faf12ca0" + }, + "systematic-debugging": { + "source": "obra/superpowers", + "commit": "22f0b463e7a5e579904dd6211a520321035526f7", + "sourceType": "github", + "skillPath": "skills/systematic-debugging/SKILL.md", + "computedHash": "79ff0583175346e39431b0dc713b223edd1bd7a7ea2b6c8b78b2fb9a3fed6782", + "installMode": "copy" + }, + "tdd": { + "source": "mattpocock/skills", + "commit": "6f7f7831a625f040a8e06a0e7954826b87ce775a", + "sourceType": "github", + "skillPath": "skills/engineering/tdd/SKILL.md", + "computedHash": "e3e0f78ff1c2d52ffefa0378baa1e80e129d359288cf9a56f4e59afcd2aac86c", + "installMode": "copy" + } + } +} From 9b5bc431d79c3157145a092246aedf970e1e4121 Mon Sep 17 00:00:00 2001 From: ShinniUwU Date: Wed, 25 Nov 2026 23:05:49 +0100 Subject: [PATCH 2/6] fix: shader warm-up lands in the run cache; run scripts offer a warm-up (P-7) --- TODO.md | 1 - apps/leonida/src/main.rs | 5 +++++ apps/leonida/src/translate.rs | 10 ++++++++- crates/leonida-gpu/src/lib.rs | 10 +++++++++ crates/leonida-hle/src/modules/d3d12x.rs | 12 +++++++++++ measure-gta6.ps1 | 23 ++++++++++++++++++++- run-gta6.ps1 | 26 +++++++++++++++++++++++- 7 files changed, 83 insertions(+), 4 deletions(-) diff --git a/TODO.md b/TODO.md index 0b430fd53..17ad16274 100644 --- a/TODO.md +++ b/TODO.md @@ -38,7 +38,6 @@ The goal: a console-like experience on PC. The game starts straight into play, h | P-4 | While the camera moves, about half the time goes to frames of about 490 ms in which the card is idle for about 330 ms. The title's page-mapping copies (`CopyPageMappingsBatchX` to `xmem::map_alias`) cost 32 ms of every cutscene frame and 246 ms of a streaming frame. | `leonida-hle` | game | | P-5 | The title paces itself with `monitorx` / `mwaitx`, which only AMD processors have: about 280,000 emulated exceptions a second on an Intel processor. Find a cheaper way. | `leonida-loader` | game; an Intel CPU to measure | | P-6 | Translated shaders are too expensive: about 50 ms of a 97 ms frame are the title's own passes as translated. With every pass of the layer's gone, the first rooms would still be near 20 fps. | `leonida-shader` | game, GPU | -| P-7 | The first run stutters while shaders translate and pipelines build. Warm the cache before play (`leonida translate --warm`), with progress shown, so the first session starts smooth. | `apps/leonida`, `run-gta6.ps1` | game | | P-8 | About 24 GB of memory is in use during play. | all | game | | P-9 | A 12 GB card is full from the first world frame (9.2 of a 10.3 GB budget), and thousands of textures are dropped and made again. Levels on demand (`LEONIDA_LEVELS_ON_DEMAND=1`) saved 3.1 GB in one run; test it more and make it the default if it holds. | `leonida-gpu` | game, GPU | diff --git a/apps/leonida/src/main.rs b/apps/leonida/src/main.rs index 6964300f5..f5850cd4b 100644 --- a/apps/leonida/src/main.rs +++ b/apps/leonida/src/main.rs @@ -168,6 +168,11 @@ fn main() -> Result<()> { jobs, warm, } => { + // The warm-up keys its translations on the same host facts a run + // gets from the device; the switches below still override them. + if warm.is_some() && !leonida_hle::modules::d3d12x::probe_translation_host() { + eprintln!("no host D3D12 device: the warm-up's shaders may not match a run's cache"); + } // `LEONIDA_VIEW_LIMIT=`: translate as on a host whose view heap is capped if let Some(n) = std::env::var("LEONIDA_VIEW_LIMIT").ok().and_then(|v| v.parse().ok()) { leonida_shader::emit::set_view_heap_limit(n); diff --git a/apps/leonida/src/translate.rs b/apps/leonida/src/translate.rs index a71772571..6151393d6 100644 --- a/apps/leonida/src/translate.rs +++ b/apps/leonida/src/translate.rs @@ -177,7 +177,9 @@ pub fn warm(paths: Vec, file: &Path, jobs: Option) -> Result<()> let cfg = leonida_core::Config::load()?; leonida_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); let paths = crate::default_paths(paths)?; - let threads = jobs.unwrap_or(4).max(1); + let threads = jobs + .unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get())) + .max(1); let began = std::time::Instant::now(); let done = Mutex::new(HashSet::new()); let counts = [const { AtomicUsize::new(0) }; 5]; @@ -269,6 +271,8 @@ pub fn run( jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get())); let seen = Mutex::new(HashSet::new()); let total = Mutex::new(Tally::default()); + let began = std::time::Instant::now(); + let done = AtomicUsize::new(0); for root in &paths { for entry in walkdir::WalkDir::new(root) .into_iter() @@ -300,6 +304,10 @@ pub fn run( }; while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { translate(job, entry.path(), &seen, &mut t, &mut checks); + let n = done.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_multiple_of(1000) { + println!("translate {n} containers so far, {:.0} s", began.elapsed().as_secs_f64()); + } } lock(&total).merge(t); }); diff --git a/crates/leonida-gpu/src/lib.rs b/crates/leonida-gpu/src/lib.rs index 4ec7d6f64..cf900a534 100644 --- a/crates/leonida-gpu/src/lib.rs +++ b/crates/leonida-gpu/src/lib.rs @@ -76,6 +76,16 @@ mod watch; #[cfg(windows)] pub use host::on_failure; + +/// Makes the host device and hands the translator the facts the shader cache +/// keys on (widest wave, view heap limit), as a run does before its first +/// shader. The offline warm-up calls it so its translations land under the +/// run's key. False: there is no host device. +#[cfg(windows)] +pub fn probe_translation_host() -> bool { + descriptor::host::probe_view_limit(); + host::host().is_some() +} #[cfg(windows)] pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; #[cfg(windows)] diff --git a/crates/leonida-hle/src/modules/d3d12x.rs b/crates/leonida-hle/src/modules/d3d12x.rs index 8034912be..f934cc6c8 100644 --- a/crates/leonida-hle/src/modules/d3d12x.rs +++ b/crates/leonida-hle/src/modules/d3d12x.rs @@ -49,6 +49,18 @@ pub fn warm_shader(container: &[u8]) -> Result { } } +/// See `leonida_gpu::probe_translation_host`. +pub fn probe_translation_host() -> bool { + #[cfg(windows)] + { + leonida_gpu::probe_translation_host() + } + #[cfg(not(windows))] + { + false + } +} + /// Keeps the host's translations of the title's shaders in `dir` (a /// folder of the cache) across runs, and its compiled pipelines beside it /// (`pipelines`). diff --git a/measure-gta6.ps1 b/measure-gta6.ps1 index 866b58cdb..ea8bf2e12 100644 --- a/measure-gta6.ps1 +++ b/measure-gta6.ps1 @@ -7,9 +7,13 @@ # # powershell -ExecutionPolicy Bypass -File .\measure-gta6.ps1 # powershell -ExecutionPolicy Bypass -File .\measure-gta6.ps1 -GameDir 'D:\Games\GTA VI' # this run only +# powershell -ExecutionPolicy Bypass -File .\measure-gta6.ps1 -WarmUp yes # warm up the shader cache without asking param( - [string]$GameDir = '' + [string]$GameDir = '', + # yes: warm up the shader cache before starting, no: skip it, ask: ask (default). + [ValidateSet('ask', 'yes', 'no')] + [string]$WarmUp = 'ask' ) $ErrorActionPreference = 'Stop' @@ -66,6 +70,23 @@ try { $env:LEONIDA_CARD_METER = '1' $env:LEONIDA_CARD_METER_PIPELINES = '1' + # Shaders not in the cache are translated the first time the game uses them, mid-play. + if ($WarmUp -eq 'ask') { + Write-Host '' + Write-Host 'Warm up the shader cache first? It translates every shader before the game starts:' + Write-Host 'about 1 to 2 minutes the first time (and after an update), about 30 s when the cache is full.' + Write-Host 'WARNING: without it, the game translates shaders while you play, so it stutters and runs' + Write-Host 'slower until the cache fills up.' + $answer = Read-Host 'Warm up now? [Y/n]' + $WarmUp = if ($answer.Trim() -match '^(y|yes)?$') { 'yes' } else { 'no' } + } + if ($WarmUp -eq 'yes') { + & $exe translate --warm all + if ($LASTEXITCODE -ne 0) { Write-Warning "the warm-up failed (exit $LASTEXITCODE); starting anyway" } + } else { + Write-Warning 'starting without a warm-up: expect stutter until the shader cache fills up' + } + $logDir = Join-Path $env:LOCALAPPDATA 'leonida\logs' New-Item -ItemType Directory -Force $logDir | Out-Null $log = Join-Path $logDir ("measure-{0:yyyyMMdd-HHmmss}.log" -f (Get-Date)) diff --git a/run-gta6.ps1 b/run-gta6.ps1 index ced6b0789..ab9101f7b 100644 --- a/run-gta6.ps1 +++ b/run-gta6.ps1 @@ -6,11 +6,15 @@ # # powershell -ExecutionPolicy Bypass -File .\run-gta6.ps1 # powershell -ExecutionPolicy Bypass -File .\run-gta6.ps1 -GameDir 'D:\Games\GTA VI' # this run only +# powershell -ExecutionPolicy Bypass -File .\run-gta6.ps1 -WarmUp yes # warm up the shader cache without asking # # To change the remembered folder: target\release\leonida.exe config --game-dir param( - [string]$GameDir = '' + [string]$GameDir = '', + # yes: warm up the shader cache before starting, no: skip it, ask: ask (default). + [ValidateSet('ask', 'yes', 'no')] + [string]$WarmUp = 'ask' ) $ErrorActionPreference = 'Stop' @@ -63,6 +67,26 @@ try { $env:LEONIDA_INDIRECT_GATHER = '1' $env:LEONIDA_CARD_REHASH_RUNS = '1' + # Shaders not in the cache are translated the first time the game uses them, mid-play. + if ($WarmUp -eq 'ask') { + Write-Host '' + Write-Host 'Warm up the shader cache first? It translates every shader before the game starts:' + Write-Host 'about 1 to 2 minutes the first time (and after an update), about 30 s when the cache is full.' + Write-Host 'WARNING: without it, the game translates shaders while you play, so it stutters and runs' + Write-Host 'slower until the cache fills up.' + $answer = Read-Host 'Warm up now? [Y/n]' + $WarmUp = if ($answer.Trim() -match '^(y|yes)?$') { 'yes' } else { 'no' } + } + if ($WarmUp -eq 'yes') { + & $exe translate --warm all + if ($LASTEXITCODE -ne 0) { Write-Warning "the warm-up failed (exit $LASTEXITCODE); starting anyway" } + } else { + Write-Warning 'starting without a warm-up: expect stutter until the shader cache fills up' + } + + # Only warnings and errors in the console; set LEONIDA_LOG=info to see the GPU layer's status lines. + if (-not $env:LEONIDA_LOG) { $env:LEONIDA_LOG = 'warn' } + & $exe run --execute } finally { Pop-Location From 536194777ac6666a7fdff8d898e87d5006fc7e88 Mon Sep 17 00:00:00 2001 From: ShinniUwU Date: Wed, 25 Nov 2026 23:05:50 +0100 Subject: [PATCH 3/6] feat(gpu): water texture read-back and frame shots from victory-fork Cherry-picked from fxceless/victory-fork 895c0b8, 04df435 and 79cfdd9, renamed. --- crates/leonida-gpu/src/capture.rs | 34 +- crates/leonida-gpu/src/draw.rs | 2 + crates/leonida-gpu/src/framelog.rs | 2 +- crates/leonida-gpu/src/host.rs | 309 +++++- crates/leonida-gpu/src/lib.rs | 6 + crates/leonida-gpu/src/pipeline/library.rs | 27 +- crates/leonida-gpu/src/queue.rs | 20 + crates/leonida-gpu/src/renderdoc.rs | 154 +++ crates/leonida-gpu/src/resource.rs | 37 +- crates/leonida-gpu/src/shadow.rs | 171 +++- crates/leonida-gpu/src/shot.rs | 1016 ++++++++++++++++++++ crates/leonida-gpu/src/texback.rs | 274 ++++++ crates/leonida-gpu/src/texture.rs | 47 +- crates/leonida-gpu/src/watch.rs | 1 + crates/leonida-hle/src/modules/dstorage.rs | 155 ++- 15 files changed, 2215 insertions(+), 40 deletions(-) create mode 100644 crates/leonida-gpu/src/renderdoc.rs create mode 100644 crates/leonida-gpu/src/shot.rs create mode 100644 crates/leonida-gpu/src/texback.rs diff --git a/crates/leonida-gpu/src/capture.rs b/crates/leonida-gpu/src/capture.rs index cf5dc2472..03ebed8bc 100644 --- a/crates/leonida-gpu/src/capture.rs +++ b/crates/leonida-gpu/src/capture.rs @@ -58,6 +58,18 @@ pub(crate) fn listed(n: u64) -> bool { /// stays empty. #[cfg(feature = "diagnostics")] pub(crate) fn op(list: usize, what: impl FnOnce() -> String) { + // A frame shot (`crate::shot`) keeps every line of its frame. + if crate::shot::keeping_lines() { + let text = what(); + crate::shot::line(list, &text); + return op_listed(list, move || text); + } + op_listed(list, what); +} + +/// [`op`] for the frames [`listed`] and the lines before the world. +#[cfg(feature = "diagnostics")] +fn op_listed(list: usize, what: impl FnOnce() -> String) { use std::io::Write; let frame = crate::queue::presented() + 1; if !listed(frame) { @@ -212,6 +224,24 @@ fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: } } +/// A PNG of `w` by `h` 8-bit RGB pixels; `raw` is its rows, each after a +/// filter byte 0 (for `crate::shot`, whose pictures have names and sizes +/// of their own). +pub(crate) fn png_rgb(w: u32, h: u32, raw: &[u8]) -> Vec { + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut header = Vec::new(); + header.extend(w.to_be_bytes()); + header.extend(h.to_be_bytes()); + header.extend([8, 2, 0, 0, 0]); // 8-bit RGB + chunk(&mut png, b"IHDR", &header); + let mut compressed = vec![0u8; zlib_rs::compress_bound(raw.len())]; + let (idat, rc) = zlib_rs::compress_slice(&mut compressed, raw, zlib_rs::DeflateConfig::new(3)); + debug_assert_eq!(rc, zlib_rs::ReturnCode::Ok); + chunk(&mut png, b"IDAT", idat); + chunk(&mut png, b"IEND", &[]); + png +} + fn chunk(png: &mut Vec, kind: &[u8; 4], data: &[u8]) { png.extend((data.len() as u32).to_be_bytes()); let start = png.len(); @@ -244,7 +274,7 @@ pub(crate) fn read_back( /// As [`read_back`], of subresource `sub` (the stencil plane of a /// one-level, one-slice depth-stencil texture is subresource 1). -fn read_back_of( +pub(crate) fn read_back_of( device: &ID3D12Device, list: &ID3D12GraphicsCommandList, texture: &ID3D12Resource, @@ -560,7 +590,7 @@ fn small_float(bits: u32, man: u32) -> f32 { /// as channel values scaled so the largest finite one is white (single /// channels: lowest black, highest white, as grey). `None` for formats not /// handled. -fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option> { +pub(crate) fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option> { let mut out = Vec::with_capacity(w * h * 4); let px = |x: usize, y: usize, n: usize| &rows[y * pitch + x * n..][..n]; let u16_at = |b: &[u8], i: usize| u16::from_le_bytes([b[2 * i], b[2 * i + 1]]); diff --git a/crates/leonida-gpu/src/draw.rs b/crates/leonida-gpu/src/draw.rs index e58c977bb..ecc892098 100644 --- a/crates/leonida-gpu/src/draw.rs +++ b/crates/leonida-gpu/src/draw.rs @@ -3538,6 +3538,8 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) { (View::Unordered(resource, _, _), ResourceType::Uav) => { #[cfg(feature = "diagnostics")] crate::capture::note_target(*resource as This); + // Some compute-written textures are also read by the title CPU. + list.texture_written(*resource as This); // Unordered access to a depth texture is its colour twin's. if !list.twin_use(*resource as This, true, true) { crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS); diff --git a/crates/leonida-gpu/src/framelog.rs b/crates/leonida-gpu/src/framelog.rs index 22ccb164c..81c6f04d0 100644 --- a/crates/leonida-gpu/src/framelog.rs +++ b/crates/leonida-gpu/src/framelog.rs @@ -319,7 +319,7 @@ fn page_faults() -> u64 { } /// The PC's free physical memory, in MiB. -fn free_mb() -> u64 { +pub(crate) fn free_mb() -> u64 { use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; // SAFETY: plain data the call fills in. let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; diff --git a/crates/leonida-gpu/src/host.rs b/crates/leonida-gpu/src/host.rs index a328f57fe..38e3cda87 100644 --- a/crates/leonida-gpu/src/host.rs +++ b/crates/leonida-gpu/src/host.rs @@ -36,6 +36,9 @@ pub(crate) fn texture_state(state: u32) -> u32 { /// ring of host descriptors is enough. const RTV_RING: u32 = 1024; +/// Whether the host device has GPU upload heaps (asked when it is made). +static GPU_UPLOAD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + pub(crate) struct Host { pub(crate) device: ID3D12Device, queue: ID3D12CommandQueue, @@ -591,6 +594,10 @@ pub(crate) fn host() -> Option<&'static Host> { fn create() -> windows::core::Result { crate::drvwatch::start(); crate::spread::start(); + // Diagnostics: RenderDoc, if asked for, before any graphics interface + // is made (`LEONIDA_RENDERDOC`). + #[cfg(feature = "diagnostics")] + crate::renderdoc::load(); // SAFETY: plain D3D12 object creation with valid descriptions. unsafe { // The debug layer only in builds with diagnostics. @@ -672,6 +679,20 @@ fn create() -> windows::core::Result { tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes"); leonida_shader::emit::set_host_max_wave(o1.WaveLaneCountMax); } + // Whether the card's own memory can be mapped by the CPU ("GPU + // upload heaps": the card's memory through a resizable BAR). With + // it a host copy the CPU fills and shaders read needs one buffer, + // in the card's memory, and nothing sends it there. + let mut o16 = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default(); + let upload = device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS16, (&raw mut o16).cast(), size_of_val(&o16) as u32) + .is_ok() + && o16.GPUUploadHeapSupported.as_bool(); + GPU_UPLOAD.store(upload, Ordering::Relaxed); + tracing::info!( + supported = upload, + "GPU upload heaps (the card's memory written by the CPU through a resizable BAR; LEONIDA_WINDOW_UPLOAD=1 puts windows outside buffers there)" + ); let messages = debug .then(|| device.cast::().ok()) .flatten(); @@ -861,6 +882,15 @@ pub(crate) struct HostList { /// and at the end, and where they are read back. #[cfg(feature = "diagnostics")] stamps: OnceLock>, + /// While a frame shot records (`crate::shot`): the block of its + /// timestamps the list fills (first place, places used, the shot's + /// number), or zeros. + #[cfg(feature = "diagnostics")] + pub(crate) shot_block: Mutex<(u32, u32, u32)>, + /// The frame of a shot the list was recorded in (the shot's number) and + /// the line its recording began at, or zeros. + #[cfg(feature = "diagnostics")] + pub(crate) shot_mark: Mutex<(u32, u32)>, } /// A list's prelude: an allocator and a closed list. @@ -1940,6 +1970,11 @@ struct Deferred { /// memory they go to, the bytes of a row, the rows, the title's row /// pitch. backs: Vec<(ID3D12Resource, usize, [usize; 3])>, + /// Title textures of the kinds copied back ([`crate::texback`]) that + /// the list's shaders write, copied when the list closes. + back_wanted: Vec, + /// Those copies, whose texels go to title memory once the list has run. + texture_backs: Vec, /// Whether the indirect-work budget is zeroed for this recording (a /// step on the CPU, or in the list for the card's copy). budget_zeroed: bool, @@ -2422,6 +2457,8 @@ struct Sent { number: u64, card: Option, back: Vec, + /// Title-memory ranges written when its shader textures are copied back. + texture_back_ranges: Vec<(usize, usize)>, /// Its bottom-of-pipe writes. writes: Vec<(usize, crate::queue::Written, usize)>, } @@ -2437,6 +2474,7 @@ struct Flight { order: Vec, card: Option, back: Vec, + texture_back_ranges: Vec<(usize, usize)>, } /// One thing in the line of what waits for the card, in order. @@ -2450,8 +2488,8 @@ enum Late { struct Line { line: Vec, - /// The title memory the flights' shaders may write (address, end), in - /// order and joined. + /// The title memory the flights' shaders and texture readbacks may write + /// (address, end), in order and joined. written: Vec<(usize, usize)>, /// Host lists in the flights. lists: usize, @@ -3614,6 +3652,11 @@ pub(crate) fn walls_trace() -> bool { /// without it, so the title read a buffer nobody wrote, as before read-backs /// were made (the exposure metering's two small float targets, every frame). fn read_backs(list: &HostList) { + // Textures shaders wrote that the title reads on the CPU + // ([`crate::texback`]). + for back in &list.deferred().texture_backs { + crate::texback::land(back); + } for (buffer, at, [row, rows, pitch]) in &list.deferred().backs { let mut data = std::ptr::null_mut(); // SAFETY: a read-back buffer of ours, written by the list that has @@ -3852,6 +3895,10 @@ impl Host { notes: Mutex::default(), #[cfg(feature = "diagnostics")] stamps: OnceLock::new(), + #[cfg(feature = "diagnostics")] + shot_block: Mutex::default(), + #[cfg(feature = "diagnostics")] + shot_mark: Mutex::default(), }) } } @@ -4194,6 +4241,8 @@ impl Host { allocator.Reset()?; list.Reset(allocator, None)?; let timed = crate::cardmeter::begin(list, crate::cardmeter::Kind::Sync); + #[cfg(feature = "diagnostics")] + let shot_span = crate::shot::span_begin(list); // Where the next range lies in the landing buffer. let mut at = 0u64; for (shadow, ranges) in &dirty { @@ -4246,6 +4295,8 @@ impl Host { } } crate::cardmeter::end(list, timed); + #[cfg(feature = "diagnostics")] + crate::shot::span_end(list, shot_span, 0, || "SYNC LIST (changed bytes go up to the card's copies and are hashed)".to_string()); list.Close()?; self.queue.ExecuteCommandLists(&[Some(list.cast()?)]); Ok(()) @@ -4312,6 +4363,8 @@ impl Host { allocator.Reset()?; list.Reset(allocator, None)?; let timed = crate::cardmeter::begin(list, crate::cardmeter::Kind::Check); + #[cfg(feature = "diagnostics")] + let shot_span = crate::shot::span_begin(list); // What the submission's shaders wrote, first. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, @@ -4371,6 +4424,8 @@ impl Host { plan.inflight_landed = inflight.landed; } crate::cardmeter::end(list, timed); + #[cfg(feature = "diagnostics")] + crate::shot::span_end(list, shot_span, 0, || "CHECK LIST (the card compares the pieces shaders may have written)".to_string()); list.Close()?; list.cast() })() @@ -4927,6 +4982,7 @@ impl Host { if let Late::Run(flight) = item { *lists += flight.order.len().max(1); ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied())); + ranges.extend(flight.texture_back_ranges.iter().copied()); } } join_ranges(written, ranges); @@ -5126,7 +5182,13 @@ impl Host { let most = { let mut line = line(); let Line { line: items, written, lists: flying, target, .. } = &mut *line; - join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied())); + join_ranges( + written, + sent.back + .iter() + .flat_map(|(_, ranges)| ranges.iter().copied()) + .chain(sent.texture_back_ranges.iter().copied()), + ); *flying += order.len(); *target = *submitted; items.push(Late::Run(Flight { @@ -5136,6 +5198,7 @@ impl Host { order, card: sent.card, back: sent.back, + texture_back_ranges: sent.texture_back_ranges, })); items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); *flying >= late_most() @@ -5170,7 +5233,13 @@ impl Host { { let mut line = line(); let Line { line: items, written, lists: flying, target, .. } = &mut *line; - join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied())); + join_ranges( + written, + sent.back + .iter() + .flat_map(|(_, ranges)| ranges.iter().copied()) + .chain(sent.texture_back_ranges.iter().copied()), + ); *flying += 1; *target = *submitted; items.push(Late::Run(Flight { @@ -5180,6 +5249,7 @@ impl Host { order: Vec::new(), card: sent.card, back: sent.back, + texture_back_ranges: sent.texture_back_ranges, })); items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); } @@ -5491,6 +5561,10 @@ impl Host { fail(format_args!("a submission sent ahead could not be followed by a signal ({e})")); } let back = declared_writes(runs); + let mut texture_back_ranges = Vec::new(); + for list in runs { + texture_back_ranges.extend(list.deferred().texture_backs.iter().map(crate::texback::Back::range)); + } let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); submission_us(0, (prepared - started).saturating_sub(settled).as_micros() as u64); submitting(0, 0); @@ -5500,6 +5574,7 @@ impl Host { number: this_submission, card, back, + texture_back_ranges, writes, }; working(was_working); @@ -5968,6 +6043,7 @@ impl HostList { pub(crate) fn close(&self) { self.twins_to_depth(); + self.textures_back(); let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone(); if let Some((scratch, _)) = scratch { self.indirect_common(&scratch); @@ -5992,6 +6068,8 @@ impl HostList { &self.pipelines.lock().unwrap_or_else(|e| e.into_inner()), ); #[cfg(feature = "diagnostics")] + crate::shot::close(self); + #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); // SAFETY: an open list, our heap and read-back buffer. @@ -6030,6 +6108,11 @@ impl HostList { } #[cfg(feature = "diagnostics")] self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); + #[cfg(feature = "diagnostics")] + { + *self.shot_block.lock().unwrap_or_else(|e| e.into_inner()) = (0, 0, 0); + *self.shot_mark.lock().unwrap_or_else(|e| e.into_inner()) = (0, 0); + } { let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); (scratch.current, scratch.used) = (0, 0); @@ -6050,6 +6133,15 @@ impl HostList { } self.meter .store(crate::cardmeter::begin(&self.list, crate::cardmeter::Kind::Lists).raw(), Ordering::Relaxed); + // A frame shot tells the lists begun inside its frame from the ones + // it found half recorded, and times each from its very start: what + // the card does in a list before the title's first command is the + // list's too. + #[cfg(feature = "diagnostics")] + if crate::shot::keeping_lines() { + crate::shot::stamp(self); + crate::shot::line(std::ptr::from_ref(self) as usize, "LIST BEGINS"); + } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64); } @@ -6066,17 +6158,32 @@ impl HostList { let texture = crate::resource::host_resource(resource)?; let copy = crate::resource::host_copy(resource)?; let wanted = legal_state(texture, wanted); - let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); - match states.entry(std::sync::Arc::as_ptr(©) as usize) { - std::collections::hash_map::Entry::Vacant(v) => { - v.insert((wanted, wanted, copy)); - None - } - std::collections::hash_map::Entry::Occupied(mut o) => { - let before = std::mem::replace(&mut o.get_mut().1, wanted); - (before != wanted).then_some((texture, before)) + // A frame shot names its pictures after the title's textures. + #[cfg(feature = "diagnostics")] + if crate::shot::recording() { + crate::shot::known(std::sync::Arc::as_ptr(©) as usize, resource as usize); + } + let before = { + let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); + match states.entry(std::sync::Arc::as_ptr(©) as usize) { + std::collections::hash_map::Entry::Vacant(v) => { + v.insert((wanted, wanted, copy.clone())); + None + } + std::collections::hash_map::Entry::Occupied(mut o) => Some(std::mem::replace(&mut o.get_mut().1, wanted)), } + }?; + if before == wanted { + return None; } + // A frame shot copies a texture where it leaves a state shaders + // write in, and leaves it in that state: the caller's move is the + // same as in any other frame. + #[cfg(feature = "diagnostics")] + if crate::shot::recording() { + crate::shot::leaves(&self.list, std::ptr::from_ref(self) as usize, Some(self), None, ©, before, wanted); + } + Some((texture, before)) } /// Moves host texture `copy` to `wanted` (a host state) in this list, @@ -6262,6 +6369,34 @@ impl HostList { } } + /// A draw or dispatch being prepared writes title texture `resource` + /// through unordered access: if it is of a kind copied back + /// ([`crate::texback`]), the list copies it when it closes. + pub(crate) fn texture_written(&self, resource: crate::object::This) { + if !crate::texback::wanted(resource) { + return; + } + let mut deferred = self.deferred(); + if !deferred.back_wanted.iter().any(|target| target.owner() == resource as usize) + && let Some(target) = crate::texback::Target::new(resource) + { + deferred.back_wanted.push(target); + } + } + + /// Before the list closes: the textures its shaders wrote that are copied + /// back go into read-back buffers ([`crate::texback::record`]). + fn textures_back(&self) { + const COPY_SOURCE: u32 = 0x800; + let wanted = std::mem::take(&mut self.deferred().back_wanted); + for target in wanted { + self.settle(&target.copy, COPY_SOURCE); + if let Some(back) = crate::texback::record(&self.list, target) { + self.deferred().texture_backs.push(back); + } + } + } + /// The draw or dispatch just prepared is recorded: the twins it writes /// now hold what their depth textures lack. pub(crate) fn twins_written(&self) { @@ -6332,12 +6467,26 @@ impl HostList { } } } + // A frame shot copies the textures that leave a state shaders write + // in between lists, each before the moves below and left in the + // state it was found in. + #[cfg(feature = "diagnostics")] + let shot_begins = crate::shot::of_the_frame(self); + #[cfg(feature = "diagnostics")] + let mut leaving: Vec<(std::sync::Arc, u32, u32)> = Vec::new(); barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| { let real = copy.state.swap(*last, Ordering::Relaxed); let real = copying.get(key).copied().unwrap_or(real); + #[cfg(feature = "diagnostics")] + if shot_begins.is_some() && !copying.contains_key(key) && crate::shot::might_leave(real, *first) { + leaving.push((copy.clone(), real, *first)); + } (real != *first) .then(|| transition(©.texture, host_state(real), host_state(*first))) })); + // (The same order in every frame, whatever order the map gives.) + #[cfg(feature = "diagnostics")] + leaving.sort_by_key(|l| std::sync::Arc::as_ptr(&l.0) as usize); // The records the list's draws read from slots (`crate::indirect::gather`). let gather = self.gather.lock().unwrap_or_else(|e| e.into_inner()); let gathered = gather.sets.iter().any(|s| s.records() > 0); @@ -6356,12 +6505,18 @@ impl HostList { let recorded = unsafe { allocator.Reset().and_then(|()| { list.Reset(allocator, None)?; + #[cfg(feature = "diagnostics")] + let shot_span = if shot_begins.is_some() { crate::shot::span_begin(list) } else { u32::MAX }; if !to_copy.is_empty() { list.ResourceBarrier(&to_copy); } for (depth, twin, colour) in &syncs { record_twin_copy(list, &depth.texture, twin, *colour); } + #[cfg(feature = "diagnostics")] + for (copy, real, first) in &leaving { + crate::shot::leaves(list, std::ptr::from_ref(self) as usize, None, shot_begins, copy, *real, *first); + } if !barriers.is_empty() { list.ResourceBarrier(&barriers); } @@ -6377,6 +6532,16 @@ impl HostList { fail(format_args!("a list's gathered indirect records could not be clamped in its prelude")); } } + #[cfg(feature = "diagnostics")] + crate::shot::span_end(list, shot_span, std::ptr::from_ref(self) as usize, || { + format!( + "PRELUDE of the recording that begins at line {}: {} moves of textures, {} copies between a depth texture and its twin, {} sets of gathered draw records clamped", + shot_begins.unwrap_or(0), + barriers.len() + to_copy.len(), + syncs.len(), + gather.sets.iter().filter(|s| s.records() > 0).count() + ) + }); list.Close() }) }; @@ -6471,6 +6636,8 @@ impl HostList { #[cfg(feature = "diagnostics")] fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) { + // A frame shot times the command: the card's clock before it. + crate::shot::stamp(self); if !dred_on() { crate::capture::op(std::ptr::from_ref(self) as usize, what); return; @@ -6510,7 +6677,8 @@ impl HostList { && deferred.kept.is_empty() && deferred.textures.is_empty() && deferred.writes.is_empty() - && deferred.backs.is_empty()) + && deferred.backs.is_empty() + && deferred.texture_backs.is_empty()) { return false; } @@ -6994,9 +7162,34 @@ impl HostList { /// spread over the threads kept for the snapshots (`crate::shadow::wide`). /// The write-watch journal and the guards are behind their own locks, as /// they are for the title's threads. +/// +/// `LEONIDA_WIDE_REFRESH=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log (run 112 measured the switch worse, +/// copies 52 -> 68 ms, in a build whose copies went through the kernel one +/// by one; they are plain copies with one asking ahead now). fn wide_refresh() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("LEONIDA_WIDE_REFRESH").is_some_and(|v| v == "1")) + /// 0 off, 1 on, 2 in turn. + static MODE: OnceLock = OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("LEONIDA_WIDE_REFRESH").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: OnceLock = OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "a submission's copies are spread over the helper threads from now (LEONIDA_WIDE_REFRESH=alt): {}", + if on { "ON" } else { "off, one after the other as usual" } + ); + } + on + } + } } /// Whether a range of a host copy brought up to date in a submission is @@ -8191,6 +8384,90 @@ impl Host { ); } + /// Whether the device has GPU upload heaps ([`GPU_UPLOAD`]). + pub(crate) fn gpu_upload(&self) -> bool { + GPU_UPLOAD.load(Ordering::Relaxed) + } + + /// A buffer in the card's own memory that the CPU maps and writes (a + /// GPU upload heap; write-combined: reading it back is slow, and + /// nothing of ours does) and shaders read: for host copies the CPU + /// fills and no shader writes. `None` where the device has no such + /// heaps or turns the buffer down (then the caller's usual buffer). + pub(crate) fn gpu_upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + if !self.gpu_upload() { + return None; + } + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_GPU_UPLOAD, + ..Default::default() + }; + // (Unordered access allowed, as the buffers it stands in for: a + // view of that kind over a window must still be makeable.) + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping of a CPU-visible buffer. + let made = unsafe { + self.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + .and_then(|()| { + let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + b.Map(0, None, Some(&mut data)) + }) + }; + match (made, buffer) { + (Ok(()), Some(buffer)) if !data.is_null() => { + // The first one is tried before any is used: title memory + // reaches a host copy by a plain copy and, where a page is + // not there, through the kernel (`read`), and this memory + // is the card's, mapped through the bus. Both ways must + // write it and it must read back the same, or no copy goes + // to such a heap in this run. + static WORKS: OnceLock = OnceLock::new(); + let works = *WORKS.get_or_init(|| { + let n = (size as usize).min(8192); + let pattern: Vec = (0..n).map(|i| (i * 31 + 7) as u8).collect(); + let half = n / 2; + // SAFETY: the buffer's own mapping, `size` bytes of it; a + // source of ours. + let same = unsafe { + std::ptr::copy_nonoverlapping(pattern.as_ptr(), data.cast::(), half); + let by_kernel = read(pattern[half..].as_ptr(), data.cast::().add(half), n - half); + by_kernel && std::slice::from_raw_parts(data.cast::(), n) == pattern.as_slice() + }; + // SAFETY: as above (left as a fresh buffer is: zeroed). + unsafe { std::ptr::write_bytes(data.cast::(), 0, n) }; + if same { + tracing::info!("a buffer in a GPU upload heap takes a plain copy and the kernel's copy and reads back the same: such heaps are used"); + } else { + tracing::warn!("a buffer in a GPU upload heap did not read back what was written into it: such heaps are not used in this run"); + } + same + }); + works.then_some((buffer, data.cast())) + } + (made, _) => { + // Said once: every later one would say the same. + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(size, result = ?made, "a buffer in a GPU upload heap could not be made or mapped: such copies stay in the PC's memory") + }); + None + } + } + } + /// A buffer in system memory that the CPU maps (write-back, so reading /// it is fast too) and shaders read and write: for host copies of title /// memory that shaders write, which upload memory cannot be. Starts in diff --git a/crates/leonida-gpu/src/lib.rs b/crates/leonida-gpu/src/lib.rs index cf900a534..9c60f4bd8 100644 --- a/crates/leonida-gpu/src/lib.rs +++ b/crates/leonida-gpu/src/lib.rs @@ -19,6 +19,10 @@ mod capture; #[cfg(windows)] mod cardmeter; +#[cfg(all(windows, feature = "diagnostics"))] +mod renderdoc; +#[cfg(all(windows, feature = "diagnostics"))] +mod shot; pub mod console; #[cfg(all(windows, feature = "diagnostics"))] mod copystat; @@ -73,6 +77,8 @@ pub mod signature; mod texture; #[cfg(windows)] mod watch; +#[cfg(windows)] +mod texback; #[cfg(windows)] pub use host::on_failure; diff --git a/crates/leonida-gpu/src/pipeline/library.rs b/crates/leonida-gpu/src/pipeline/library.rs index ad7f361fd..3218a0169 100644 --- a/crates/leonida-gpu/src/pipeline/library.rs +++ b/crates/leonida-gpu/src/pipeline/library.rs @@ -429,6 +429,8 @@ fn one_call() -> Option> { } const LIBRARY_FILE: &str = "host-pipelines.bin"; +/// A library the driver refused, kept as it was ([`open`]). +const REJECTED_FILE: &str = "host-pipelines.rejected.bin"; /// A saved library that could not replace [`LIBRARY_FILE`] while this run /// had it mapped (a system that refuses to replace a mapped file): the next /// start renames it over the library first ([`Blob::of`]). @@ -441,6 +443,14 @@ fn library() -> Option<&'static Library> { static LIBRARY: OnceLock> = OnceLock::new(); LIBRARY .get_or_init(|| { + // With RenderDoc loaded the device is RenderDoc's: the card's + // library is not for it, and what it would save is not for + // the card. Neither read nor written in such a run. + #[cfg(feature = "diagnostics")] + if crate::renderdoc::loaded() { + tracing::info!("RenderDoc is loaded: the host pipeline library is neither read nor saved in this run"); + return None; + } let device = crate::host::host()?.device.cast::().ok()?; let blob = DIR.get().map_or(Blob::None, |d| Blob::of(d)); let library = open(&device, blob); @@ -461,6 +471,7 @@ fn open(device: &ID3D12Device1, blob: Blob) -> Option { device.CreatePipelineLibrary::(bytes)?.cast() } }; + let mut rejected = false; if !blob.bytes().is_empty() { match make(blob.bytes()) { Ok(library) => { @@ -479,7 +490,10 @@ fn open(device: &ID3D12Device1, blob: Blob) -> Option { saving: RwLock::new(()), }); } - Err(e) => tracing::info!(error = %e, "host pipeline library rejected; starting an empty one"), + Err(e) => { + rejected = true; + tracing::warn!(error = %e, "host pipeline library rejected; starting an empty one (the rejected file is kept as {REJECTED_FILE})"); + } } } else { tracing::info!("no host pipeline library yet; starting an empty one"); @@ -487,6 +501,17 @@ fn open(device: &ID3D12Device1, blob: Blob) -> Option { // The rejected bytes are let go (a mapped file is unmapped) before the // empty library is made: nothing reads them any more. drop(blob); + // And the file is kept under another name, not written over by this + // run's first save: a refusal may be this device's alone (run 263: + // RenderDoc's device refused the card's library, an empty one was + // saved over 366 MB of built pipelines, and the next run drew black + // until they were built again). + if rejected + && let Some(dir) = DIR.get() + && let Err(e) = std::fs::rename(dir.join(LIBRARY_FILE), dir.join(REJECTED_FILE)) + { + tracing::warn!(error = %e, "the rejected host pipeline library could not be kept under its other name"); + } let library = make(&[]).ok()?; Some(Library { library, diff --git a/crates/leonida-gpu/src/queue.rs b/crates/leonida-gpu/src/queue.rs index 2fedd5348..86411ed00 100644 --- a/crates/leonida-gpu/src/queue.rs +++ b/crates/leonida-gpu/src/queue.rs @@ -263,6 +263,15 @@ fn submit_cut(this: This, lists: &[This]) { } else { 0 }; + // A frame shot learns that its frame's lists are being submitted. + #[cfg(feature = "diagnostics")] + if crate::shot::recording() { + for &l in lists { + if let Some(h) = crate::list::host_list(l) { + crate::shot::submitted(h); + } + } + } #[cfg(feature = "diagnostics")] crate::capture::op(this as usize, || { let named: Vec = lists @@ -344,6 +353,15 @@ fn submit_split(this: This, lists: &[This]) { } else { 0 }; + // A frame shot learns that its frame's lists are being submitted. + #[cfg(feature = "diagnostics")] + if crate::shot::recording() { + for &l in lists { + if let Some(h) = crate::list::host_list(l) { + crate::shot::submitted(h); + } + } + } #[cfg(feature = "diagnostics")] crate::capture::op(this as usize, || { let named: Vec = lists @@ -1365,6 +1383,8 @@ fn present_now(this: This, planes: u32, plane_parameters: *const Plane) -> HRESU #[cfg(all(windows, feature = "diagnostics"))] { crate::capture::frame_drew(frame, crate::draw::drawn()); + crate::renderdoc::frame_drew(frame, crate::draw::drawn()); + crate::shot::present(frame, crate::draw::drawn()); if crate::capture::listed(frame) { crate::capture::dump_targets(frame); } diff --git a/crates/leonida-gpu/src/renderdoc.rs b/crates/leonida-gpu/src/renderdoc.rs new file mode 100644 index 000000000..22ebe4c1a --- /dev/null +++ b/crates/leonida-gpu/src/renderdoc.rs @@ -0,0 +1,154 @@ +//! Diagnostics: one frame of the title captured with RenderDoc. +//! +//! `LEONIDA_RENDERDOC=` loads RenderDoc into +//! this process before the host device is made (its documented +//! in-application use: it hooks the graphics interfaces created after it +//! is loaded). `LEONIDA_RENDERDOC_AT=` (150 by default) then asks it for +//! the frame `n` presents after the first frame of 500 draws or more, and +//! `LEONIDA_RENDERDOC_OUT` names the capture files (by default +//! `leonida_rdc\frame` under the temporary folder). +//! +//! Nothing is loaded unless the variable gives the full path of a file: a +//! bare name is refused, so neither the current folder nor the title's is +//! ever searched for it. + +use std::ffi::c_void; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +/// RenderDoc's in-application interface: a table of function pointers +/// (`RENDERDOC_API_1_1_2` of its `renderdoc_app.h`), by address. +struct Api(usize); + +/// `void SetCaptureFilePathTemplate(const char *)`. +const SET_CAPTURE_FILE_PATH_TEMPLATE: usize = 11; +/// `uint32_t GetNumCaptures(void)`. +const GET_NUM_CAPTURES: usize = 13; +/// `void TriggerCapture(void)`: the next presented frame is captured. +const TRIGGER_CAPTURE: usize = 15; +/// `eRENDERDOC_API_Version_1_1_2`. +const VERSION_1_1_2: i32 = 10102; + +impl Api { + /// The table's entry `index` as a function of type `F`. + /// + /// # Safety + /// `index` is an entry of the 1.1.2 table and `F` its signature. + unsafe fn entry(&self, index: usize) -> F { + let table = self.0 as *const usize; + // SAFETY: by the caller; the table lives as long as the module, + // which is never unloaded. + unsafe { std::mem::transmute_copy::(&*table.add(index)) } + } +} + +static API: OnceLock> = OnceLock::new(); + +/// Whether RenderDoc was loaded into this run ([`load`]): the host device +/// is then RenderDoc's, and what a driver keeps for its own device (the +/// pipeline library's blob) is neither read nor written by this run. +pub(crate) fn loaded() -> bool { + API.get().is_some_and(Option::is_some) +} + +/// Loads RenderDoc when `LEONIDA_RENDERDOC` names its DLL by full path. +/// Called before the host device is made. +pub(crate) fn load() { + API.get_or_init(|| { + let path = std::path::PathBuf::from(std::env::var_os("LEONIDA_RENDERDOC")?); + if !path.is_absolute() || !path.is_file() { + tracing::warn!( + path = %path.display(), + "LEONIDA_RENDERDOC: not the full path of a file; RenderDoc is not loaded" + ); + return None; + } + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::System::LibraryLoader::{ + GetProcAddress, LOAD_WITH_ALTERED_SEARCH_PATH, LoadLibraryExW, + }; + let wide: Vec = path.as_os_str().encode_wide().chain([0]).collect(); + // SAFETY: a NUL-terminated full path, named by the user. + let module = + unsafe { LoadLibraryExW(wide.as_ptr(), std::ptr::null_mut(), LOAD_WITH_ALTERED_SEARCH_PATH) }; + if module.is_null() { + tracing::warn!(path = %path.display(), "LEONIDA_RENDERDOC: the DLL does not load"); + return None; + } + // SAFETY: a loaded module and a NUL-terminated name. + let get = unsafe { GetProcAddress(module, c"RENDERDOC_GetAPI".as_ptr().cast()) }?; + // SAFETY: the export's documented signature, + // `int RENDERDOC_GetAPI(RENDERDOC_Version, void **)`. + let get = unsafe { + std::mem::transmute::< + unsafe extern "system" fn() -> isize, + unsafe extern "C" fn(i32, *mut *mut c_void) -> i32, + >(get) + }; + let mut table: *mut c_void = std::ptr::null_mut(); + // SAFETY: a valid out pointer. + if unsafe { get(VERSION_1_1_2, &mut table) } != 1 || table.is_null() { + tracing::warn!("LEONIDA_RENDERDOC: the DLL does not give its interface 1.1.2"); + return None; + } + let api = Api(table as usize); + let out = std::env::var_os("LEONIDA_RENDERDOC_OUT") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| std::env::temp_dir().join("leonida_rdc").join("frame")); + if let Some(folder) = out.parent() { + let _ = std::fs::create_dir_all(folder); + } + if let Ok(name) = std::ffi::CString::new(out.to_string_lossy().as_bytes()) { + // SAFETY: the entry's signature; a NUL-terminated string it copies. + unsafe { + api.entry::(SET_CAPTURE_FILE_PATH_TEMPLATE)( + name.as_ptr(), + ); + } + } + tracing::info!( + path = %path.display(), + out = %out.display(), + at = at(), + "RenderDoc loaded: it captures one frame of the world" + ); + Some(api) + }); +} + +/// How many presents after the first world frame the capture is asked for. +fn at() -> u64 { + static AT: OnceLock = OnceLock::new(); + *AT.get_or_init(|| { + std::env::var("LEONIDA_RENDERDOC_AT") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(150) + }) +} + +/// At the present of `frame`, with `drawn` draws run on the host so far. +pub(crate) fn frame_drew(frame: u64, drawn: u64) { + let Some(api) = API.get().and_then(|a| a.as_ref()) else { + return; + }; + static LAST: AtomicU64 = AtomicU64::new(0); + static WORLD: AtomicU64 = AtomicU64::new(u64::MAX); + let before = LAST.swap(drawn, Relaxed); + if drawn.saturating_sub(before) >= 500 { + let _ = WORLD.compare_exchange(u64::MAX, frame, Relaxed, Relaxed); + } + let world = WORLD.load(Relaxed); + if world == u64::MAX { + return; + } + if frame == world + at() { + // SAFETY: the entry's signature. + unsafe { api.entry::(TRIGGER_CAPTURE)() }; + tracing::info!(frame, "RenderDoc is asked for the next frame"); + } else if frame == world + at() + 8 { + // SAFETY: the entry's signature. + let captures = unsafe { api.entry:: u32>(GET_NUM_CAPTURES)() }; + tracing::info!(captures, "RenderDoc captures made so far"); + } +} diff --git a/crates/leonida-gpu/src/resource.rs b/crates/leonida-gpu/src/resource.rs index b0e2f01ef..bebace985 100644 --- a/crates/leonida-gpu/src/resource.rs +++ b/crates/leonida-gpu/src/resource.rs @@ -2298,6 +2298,7 @@ fn hand_out_resource( if desc.dimension != BUFFER { let at = std::ptr::from_ref::(&resource) as usize; textures().insert(at); + crate::texback::replaced(resource.data() as usize); if !fills(&desc) { TARGETS_AT .lock() @@ -2322,7 +2323,9 @@ impl Drop for Resource { // Out of the table of textures first: the sweep looks at the ones // in it, under its lock. if self.desc.dimension != BUFFER { - textures().remove(&(std::ptr::from_ref::(self) as usize)); + let address = std::ptr::from_ref::(self) as usize; + crate::texback::released(address); + textures().remove(&address); if !fills(&self.desc) { let mut targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner()); let at = self.data() as u64; @@ -2554,6 +2557,38 @@ pub(crate) fn placed_filler_twins() -> u64 { PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed) } +/// Width, height and format of texture `this` (`None` for a buffer), for +/// `crate::texback`'s kinds. +#[cfg(windows)] +pub(crate) fn texture_kind(this: This) -> Option<(u64, u32, u32)> { + if this.is_null() { + return None; + } + let r = resource(this); + const TEXTURE_2D: u32 = 3; + (r.desc.dimension == TEXTURE_2D && r.desc.sample_count <= 1) + .then_some((r.desc.width, r.desc.height, r.desc.format)) +} + +/// Texture `this`'s console layout (one plane), where it lies in title +/// memory and the bytes that layout takes, for `crate::texback`; `None` for +/// a buffer or a texture with planes. +#[cfg(windows)] +pub(crate) fn title_texture(this: This) -> Option<(leonida_formats::texture::Layout, usize, usize)> { + if this.is_null() { + return None; + } + let r = resource(this); + if r.desc.dimension == BUFFER { + return None; + } + let t = texture_layout(&r.desc)?; + let [plane] = &t.planes[..] else { + return None; + }; + Some((plane.layout.clone(), r.data() as usize, t.size as usize)) +} + /// The bytes of title memory a texture with the resource description /// `desc` (as words) takes where the title placed it; `None` for a buffer /// and for a description without a size. diff --git a/crates/leonida-gpu/src/shadow.rs b/crates/leonida-gpu/src/shadow.rs index d578afac1..05e8ff837 100644 --- a/crates/leonida-gpu/src/shadow.rs +++ b/crates/leonida-gpu/src/shadow.rs @@ -71,6 +71,9 @@ pub(crate) struct Shadow { card: Option, /// A window of title memory outside buffers, not a title buffer's copy. window: bool, + /// A window whose one buffer is in a GPU upload heap ([`window_upload`]): + /// its bytes, counted with the windows on the card. + uploaded: u64, /// With `crate::inplace`: not a copy at all. `buffer` is placed in a /// heap opened on the title memory itself, so shaders read and write /// the title's own bytes and nothing is copied either way. The heap, @@ -329,31 +332,104 @@ fn window_card_most() -> u64 { /// Bytes alive of windows' card sides ([`window_card_most`]). static WINDOW_CARD_BYTES: AtomicU64 = AtomicU64::new(0); +/// Whether windows that go to the card's memory are one buffer in a GPU +/// upload heap, which the CPU fills directly (`LEONIDA_WINDOW_UPLOAD=1`; +/// off by default), where the device has such heaps +/// (`Host::gpu_upload_buffer`). +/// +/// A window on the card ([`window_card_most`]) is two buffers: the CPU's +/// side in the PC's memory, which takes title memory as before, and the +/// card's side, which a list of ours brings up to date before each +/// submission (`Host::card_before`: its copies are part of "our +/// send-and-hash lists", 11 to 14 ms of the card's frame in runs 270 and +/// 271). No shader writes a window (run 91, and every run since: "0.0 MB +/// compared in 0 ranges of windows"), so nothing is ever looked for in one +/// or fetched from one: the CPU's side is only a stop on the way. With +/// the card's memory mapped through a resizable BAR the stop goes: title +/// memory is copied into the card's memory where shaders read it, with no +/// second buffer in the PC's memory and no copy on the card. The same +/// limits hold as for windows on the card (the most asked, the card's +/// room), and a window turned down or not makeable stays in the PC's +/// memory as before. +fn window_upload() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_WINDOW_UPLOAD").is_some_and(|v| v == "1")) +} + +/// A window's buffer in a GPU upload heap and where it is mapped, if +/// [`window_upload`] says so and a window of `size` bytes may go to the +/// card ([`window_card_room`]). +fn window_upload_for(size: u64) -> Option<(ID3D12Resource, *mut u8)> { + if !window_upload() || !host()?.gpu_upload() { + return None; + } + if !window_card_room(size, "in a GPU upload heap:") { + return None; + } + let made = host()?.gpu_upload_buffer(size); + if made.is_none() { + WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); + } + made +} + /// A buffer in the card's memory for a window of `size` bytes, if it is to /// be there ([`window_card_most`]). fn window_card_for(size: u64) -> Option { + if !window_card_room(size, "on the card:") { + return None; + } + let buffer = host()?.uav_buffer(size); + if buffer.is_none() { + WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); + } + buffer +} + +/// Whether a window of `size` bytes may go to the card's memory +/// ([`window_card_most`], the card's room); if so its bytes are counted +/// there from now, and the caller makes the buffer (or takes them off +/// again). `how` is the word for the log. +fn window_card_room(size: u64, how: &str) -> bool { let most = window_card_most(); if most == 0 || !cards() { - return None; + return false; } - let host = host()?; + let Some(host) = host() else { return false }; if !host.card_ready() { - return None; - } + return false; + } + // Windows that went to the card, and those turned down for the card's + // room or for the most asked: said at the first of each and then now + // and again, so a run shows what the switch did. + static COUNTS: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + let say = |which: usize, what: &str| { + let n = COUNTS[which].fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || n.is_multiple_of(64) { + tracing::info!( + "windows outside buffers and the card's memory (LEONIDA_CARD_WINDOWS_MB={}): {what} one of {} KiB; so far {} on the card ({} MB), {} turned down for the card's room, {} for the most asked", + most >> 20, + size >> 10, + COUNTS[0].load(Ordering::Relaxed), + WINDOW_CARD_BYTES.load(Ordering::Relaxed) >> 20, + COUNTS[1].load(Ordering::Relaxed), + COUNTS[2].load(Ordering::Relaxed) + ); + } + }; if let Some([budget, used, ..]) = host.video_memory() && used + size > budget / 10 * 8 { - return None; + say(1, "no room on the card for"); + return false; } if WINDOW_CARD_BYTES.fetch_add(size, Ordering::Relaxed) + size > most { WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); - return None; - } - let buffer = host.uav_buffer(size); - if buffer.is_none() { - WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); + say(2, "the most is reached at"); + return false; } - buffer + say(0, how); + true } /// The copies in the card's memory whose CPU side changed since they were @@ -2001,6 +2077,61 @@ mod merge_tests { assert_eq!(runs, [(0, 1), (3, 1)], "the GPU's bytes only"); } + /// The runs are the ones a walk byte by byte finds, for lengths around + /// the steps of eight and sixty-four the compare takes, and for bytes + /// that differ one here and there, in stretches, and nearly everywhere. + #[test] + fn changed_runs_are_the_ones_a_walk_byte_by_byte_finds() { + let by_bytes = |now: &[u8], was: &[u8]| { + let mut runs: Vec<(usize, usize)> = Vec::new(); + for i in 0..now.len().min(was.len()) { + if now[i] != was[i] { + match runs.last_mut() { + Some(last) if last.0 + last.1 == i => last.1 += 1, + _ => runs.push((i, 1)), + } + } + } + runs + }; + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for case in 0..20_000u32 { + let n = match case % 4 { + 0 => (next() % 20) as usize, + 1 => 56 + (next() % 20) as usize, + 2 => 120 + (next() % 20) as usize, + _ => (next() % 700) as usize, + }; + let was: Vec = (0..n).map(|_| next() as u8).collect(); + let mut now = was.clone(); + // One byte in `rarity` differs; some cases also get a stretch + // that differs throughout, and some differ nearly everywhere. + let rarity = [1, 2, 3, 9, 40, 300][(next() % 6) as usize]; + for b in now.iter_mut() { + if next() % rarity == 0 { + *b ^= 1 + (next() % 255) as u8; + } + } + if n > 0 && next() % 3 == 0 { + let from = (next() as usize) % n; + let to = (from + (next() % 90) as usize).min(n); + for b in &mut now[from..to] { + *b = !*b; + } + } + // (A byte may also keep a zero difference inside a stretch.) + assert_eq!(changed_runs(&now, &was), by_bytes(&now, &was), "case {case}, {n} bytes"); + } + // Slices of unlike lengths: the shorter one's bytes. + assert_eq!(changed_runs(&[1, 2, 3, 4, 5, 6, 7, 8, 9], &[1, 2, 0]), vec![(2, 1)]); + } + /// The runs hold exactly the bytes that differ: putting them into the /// old bytes gives the new ones, and no run holds an equal byte. #[test] @@ -2045,6 +2176,9 @@ impl Drop for Shadow { KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed); } let window = self.window; + if self.uploaded != 0 { + WINDOW_CARD_BYTES.fetch_sub(self.uploaded, Ordering::Relaxed); + } if let Some(card) = &mut self.card { if window { WINDOW_CARD_BYTES.fetch_sub(card.size, Ordering::Relaxed); @@ -2413,6 +2547,7 @@ impl Shadow { }, card: None, window: false, + uploaded: 0, place: None, } } @@ -3933,6 +4068,20 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option` switches it on. A shot is taken of the frame +//! after a present at which +//! * the file `take` is found in that folder (it is removed; the script +//! `shot.ps1` makes it), or +//! * the frame is one of `LEONIDA_SHOT_AT` (comma-separated, counted from +//! the first frame of 500 draws or more, as `LEONIDA_RENDERDOC_AT`). +//! +//! Of that frame the shot keeps, in `\shot-`: +//! * `events.txt`: every draw, dispatch, copy, submission and drop in the +//! order recorded, with the list it was recorded into, the thread, and +//! the place of its timestamp (the lines of `capture::op`: shaders, +//! targets, states, what is read); +//! * `stamps.txt`: the card's clock before each of those commands, so the +//! time to the next one in the same list is that command's; +//! * `snap-*.png`: what a texture held where it left a state shaders +//! write in (render target, depth write, unordered access): the picture +//! a pass left. The title gives its textures' states in a form without +//! states (enhanced barriers), so the layer moves every texture itself, +//! and that is where the copies are made: inside a list +//! (`HostList::transition`) and between lists, in the list that runs +//! before each one (`HostList::prelude`). `snaps.txt` lists them; +//! * `info.txt`, and `done` when everything is written. +//! +//! **Pictures come in parts.** With the title running the PC has one to +//! four gigabytes free (run 269: 3.6 GB in the opening cutscene, 0.9 GB in +//! the first room), and a frame's targets are more than that. A place +//! where a picture can be taken is named by its texture and how many +//! times the texture left a written state before in the frame: the same +//! name in every frame that is built the same way. The shot's own frame +//! takes as many as fit in half of the memory that is free above 0.7 GB +//! (`LEONIDA_SHOT_MB` at most, 1024 unless said); when they are written and +//! their buffers gone, a later frame takes the ones still missing, and so +//! on until none is, or a frame gets none. The lines and times are all of +//! the first frame, and are taken even when there is no room for any +//! picture; a picture says which frame it is of. +//! +//! The pictures are read two seconds and eight frames after their frame +//! (every list of it has long run) and written by a thread of their own on +//! the slow cores. Multisampled textures and volumes are not copied; of an +//! array the first six slices' first level; a texture at most eight times +//! a frame; at most `LEONIDA_SHOT_MAX` (12) shots a run. + +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering::Relaxed}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +const IDLE: u8 = 0; +const RECORDING: u8 = 1; +const PENDING: u8 = 2; +const SAVING: u8 = 3; +static PHASE: AtomicU8 = AtomicU8::new(IDLE); +/// Whether the frame being recorded keeps its lines and times (a shot's +/// first frame; the later ones only take pictures). +static LINES: AtomicBool = AtomicBool::new(false); + +/// Which frame of which shot is being taken (1, 2, ...): what a list holds +/// for a shot belongs to one. +static SHOT_ID: AtomicU32 = AtomicU32::new(0); + +/// Timestamps of a shot, and how many a list takes at a time. +const SLOTS: u32 = 131_072; +const BLOCK: u32 = 128; +/// The next free timestamp of the shot being taken. +static NEXT: AtomicU32 = AtomicU32::new(0); + +/// Lines a shot holds at most. +const MAX_EVENTS: usize = 400_000; +/// Copies of one texture in a frame. +const REPEATS: u32 = 8; +/// Frames a shot takes its pictures in, at most. +const MAX_PARTS: u32 = 48; +/// When this many lists recorded for a shot's frame have been submitted, +/// the frame is the title's to finish: lists begun from then on are the +/// next frame's (the title records it while the layer still runs this +/// one: run 269's first shot held frame 0x781 and, behind its submissions, +/// all of 0x782), and the present that follows ends the shot's frame. A +/// present before that is of a frame recorded before the shot began, and +/// the shot goes on through it, three presents at most. +const FRAME_LISTS: u32 = 20; +/// Lists of the frame being recorded that the title has submitted. +static SUBMITTED: AtomicU32 = AtomicU32::new(0); + +/// Whether the title has begun to submit the frame being recorded. +fn closing() -> bool { + SUBMITTED.load(Relaxed) >= FRAME_LISTS +} + +/// The title submits `list`, while a shot records. +pub(crate) fn submitted(list: &crate::host::HostList) { + let mark = *list.shot_mark.lock().unwrap_or_else(|e| e.into_inner()); + if mark.0 != 0 && mark.0 == SHOT_ID.load(Relaxed) { + SUBMITTED.fetch_add(1, Relaxed); + } +} +/// Memory left alone (MB), and the least a frame's pictures need. +const RESERVE_MB: u64 = 700; +const LEAST_MB: u64 = 48; +/// The host state copies are read in. +const COPY_SOURCE: u32 = 0x800; + +/// The folder shots go to, if the tool is on. +fn folder() -> Option<&'static PathBuf> { + static FOLDER: OnceLock> = OnceLock::new(); + FOLDER + .get_or_init(|| { + let folder = PathBuf::from(std::env::var_os("LEONIDA_SHOT")?); + if !folder.is_absolute() { + tracing::warn!(folder = %folder.display(), "LEONIDA_SHOT is not a full path: no frame shots"); + return None; + } + if let Err(e) = std::fs::create_dir_all(&folder) { + tracing::warn!(error = %e, folder = %folder.display(), "the folder for frame shots could not be made: none are taken"); + return None; + } + tracing::info!( + folder = %folder.display(), + at = ?at(), + "frame shots are on (LEONIDA_SHOT): one is taken when the file `take` appears in the folder, and at the frames of LEONIDA_SHOT_AT" + ); + Some(folder) + }) + .as_ref() +} + +fn number(name: &str, default: u64) -> u64 { + std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default) +} + +/// `LEONIDA_SHOT_AT`: frames counted from the first one of 500 draws. +fn at() -> &'static [u64] { + static AT: OnceLock> = OnceLock::new(); + AT.get_or_init(|| { + std::env::var("LEONIDA_SHOT_AT").unwrap_or_default().split(',').filter_map(|f| f.trim().parse().ok()).collect() + }) +} + +/// The read-back memory (MB) a frame of a shot may take now. +fn room_mb() -> u64 { + (crate::framelog::free_mb().saturating_sub(RESERVE_MB) / 2).min(number("LEONIDA_SHOT_MB", 1024)) +} + +/// A line of the shot. +struct Event { + list: usize, + thread: u32, + /// The place of the timestamp recorded before the command, or none. + stamp: u32, + text: String, +} + +/// A picture of the shot, still in its read-back buffer. +struct Snap { + /// How many times its texture left a written state before in the + /// frame. + occurrence: u32, + name: String, + buffer: ID3D12Resource, + footprint: D3D12_SUBRESOURCE_FOOTPRINT, + bytes: u64, + /// The title's texture (or, unknown, the host copy), its own size and + /// format, the slice copied, and the states it left and went to. + texture: usize, + width: u64, + height: u32, + format: i32, + slice: u32, + before: u32, + after: u32, +} + +/// What a shot carries from one of its frames to the next. +#[derive(Clone, Default)] +struct Carry { + /// The shot's first frame (its folder's name) and why it was taken. + first: u64, + why: String, + /// Frames taken so far; pictures saved and failed in them. + parts: u32, + saved: u32, + failed: u32, + /// The places done: host copy, occurrence, slice. + done: std::collections::HashSet<(usize, u32, u32)>, + /// Of the first frame: lines, draws and dispatches, presents, places. + lines: usize, + work: u32, + presents: u32, + places: u32, + not_taken: u32, + read_back_mb: u64, +} + +struct Shot { + id: u32, + /// The frame this part is of. + frame: u64, + carry: Carry, + presents: u32, + /// Draws and dispatches among its lines. + work: u32, + events: Vec, + snaps: Vec, + /// Read-back bytes so far, and the most allowed. + bytes: u64, + budget: u64, + /// Places met so far in this frame; how many are left for a later + /// frame; the ones never taken (repeats, too large). + places: u32, + later: u32, + not_taken: u32, + /// Times a texture (host copy) left a written state so far. + per_texture: std::collections::HashMap, + /// The title's texture by host copy. + titles: std::collections::HashMap, + /// The ranges of timestamps lists resolved: first place and count. + resolved: Vec<(u32, u32)>, + /// When recording ended, and the frame's number. + stopped: Option<(std::time::Instant, u64)>, +} + +// SAFETY: host objects (free-threaded), handed from the recording threads +// to the one that writes the shot out, behind a lock. +unsafe impl Send for Shot {} + +static SHOT: Mutex> = Mutex::new(None); +/// A shot between two of its frames. +static WAITING: Mutex> = Mutex::new(None); + +/// The timestamps' heap and where they are read back. +struct Clock { + heap: ID3D12QueryHeap, + back: ID3D12Resource, + /// The read-back buffer's bytes, mapped for good. + mapped: usize, + frequency: u64, +} + +// SAFETY: host objects (free-threaded) and a mapping that is only read. +unsafe impl Send for Clock {} +// SAFETY: as above. +unsafe impl Sync for Clock {} + +static CLOCK: OnceLock> = OnceLock::new(); + +fn make_clock() -> Option { + if std::env::var_os("LEONIDA_SHOT_TIMES").is_some_and(|v| v == "0") { + return None; + } + let host = crate::host::host()?; + let device = host.device(); + let mut heap: Option = None; + let mut back: Option = None; + let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: u64::from(SLOTS) * 8, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + // SAFETY: plain object creation; the buffer is mapped once and stays so + // (the card meter's heap and buffer, made the same way). + unsafe { + device + .CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: SLOTS, NodeMask: 0 }, &mut heap) + .ok()?; + device + .CreateCommittedResource(&readback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut back) + .ok()?; + let (heap, back) = (heap?, back?); + let mut mapped = std::ptr::null_mut(); + back.Map(0, None, Some(&mut mapped)).ok()?; + let frequency = host.timestamp_frequency(); + if mapped.is_null() || frequency == 0 { + return None; + } + Some(Clock { heap, back, mapped: mapped as usize, frequency }) + } +} + +/// Whether a frame is being recorded for a shot. One load: asked at every +/// state change of a texture in every diagnostics run. +pub(crate) fn recording() -> bool { + PHASE.load(Relaxed) == RECORDING +} + +/// Whether the frame being recorded keeps its lines ([`line`]). Asked at +/// every noted command of every diagnostics run. +pub(crate) fn keeping_lines() -> bool { + recording() && LINES.load(Relaxed) +} + +thread_local! { + /// The timestamp [`stamp`] recorded for the line this thread is about + /// to give to [`line`]. + static STAMP: std::cell::Cell = const { std::cell::Cell::new(u32::MAX) }; + /// The line this thread is about to give to [`line`] is of a list of + /// the next frame ([`stamp`]): not kept. + static NEXT_FRAME: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// A fresh block of timestamps, if any are left. +fn take_block() -> Option { + let base = NEXT.fetch_add(BLOCK, Relaxed); + (base <= SLOTS - BLOCK).then_some(base) +} + +/// Resolves `count` timestamps from `base` in `list` and notes the range. +fn resolve(list: &ID3D12GraphicsCommandList, clock: &Clock, id: u32, base: u32, count: u32) { + // SAFETY: an open list, our heap and our read-back buffer; the places + // are the block's own, and each was ended in this list before. + unsafe { list.ResolveQueryData(&clock.heap, D3D12_QUERY_TYPE_TIMESTAMP, base, count, &clock.back, u64::from(base) * 8) }; + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(s) = shot.as_mut().filter(|s| s.id == id) { + s.resolved.push((base, count)); + } +} + +/// Before a command of the title is recorded into `list`, while a shot +/// records: the list is marked as one of the shot's frame, and in a frame +/// that keeps its lines the card's clock goes into the list here, for the +/// line that follows ([`line`]). +pub(crate) fn stamp(list: &crate::host::HostList) { + if !recording() { + return; + } + let id = SHOT_ID.load(Relaxed); + { + let mut mark = list.shot_mark.lock().unwrap_or_else(|e| e.into_inner()); + if mark.0 != id { + // A list begun after the frame's lists were submitted is the + // next frame's. + if closing() { + NEXT_FRAME.set(true); + return; + } + let lines = SHOT.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map_or(0, |s| s.events.len()); + *mark = (id, lines as u32); + } + } + if !LINES.load(Relaxed) { + return; + } + let Some(Some(clock)) = CLOCK.get() else { + return; + }; + let mut block = list.shot_block.lock().unwrap_or_else(|e| e.into_inner()); + let (base, used, of) = *block; + let end = |slot: u32| { + // SAFETY: an open list and a place of our heap. + unsafe { list.list.EndQuery(&clock.heap, D3D12_QUERY_TYPE_TIMESTAMP, slot) }; + }; + let slot = if used == 0 || of != id { + let Some(base) = take_block() else { return }; + *block = (base, 1, id); + base + } else if used == BLOCK - 1 { + // The block's last place ends it; the command opens the next. + end(base + used); + resolve(&list.list, clock, id, base, BLOCK); + let Some(next) = take_block() else { + *block = (0, 0, 0); + return; + }; + *block = (next, 1, id); + next + } else { + *block = (base, used + 1, id); + base + used + }; + end(slot); + STAMP.set(slot); +} + +/// `list` is about to be closed: the block of timestamps it holds is ended +/// and resolved. +pub(crate) fn close(list: &crate::host::HostList) { + let mut block = list.shot_block.lock().unwrap_or_else(|e| e.into_inner()); + let (base, used, of) = std::mem::take(&mut *block); + if used == 0 || of != SHOT_ID.load(Relaxed) { + return; + } + let Some(Some(clock)) = CLOCK.get() else { + return; + }; + // SAFETY: an open list and a place of our heap (a block always keeps + // its last place for this). + unsafe { list.list.EndQuery(&clock.heap, D3D12_QUERY_TYPE_TIMESTAMP, base + used) }; + resolve(&list.list, clock, of, base, used + 1); +} + +/// A list of the layer's own (the one that runs before a title list, the +/// one that sends changed bytes to the card and hashes them, the one that +/// compares) begins in `cmd`, while a shot's first frame records: the +/// card's clock, for [`span_end`]. The title's commands are a part of the +/// card's frame; these are the rest of it. +pub(crate) fn span_begin(cmd: &ID3D12GraphicsCommandList) -> u32 { + if !keeping_lines() { + return u32::MAX; + } + let Some(Some(clock)) = CLOCK.get() else { + return u32::MAX; + }; + let slot = NEXT.fetch_add(2, Relaxed); + if slot > SLOTS - 2 { + return u32::MAX; + } + // SAFETY: an open list and a place of our heap. + unsafe { cmd.EndQuery(&clock.heap, D3D12_QUERY_TYPE_TIMESTAMP, slot) }; + slot +} + +/// The list [`span_begin`] timed ends here; `what` is its line, for the +/// title list `list` or none. +pub(crate) fn span_end(cmd: &ID3D12GraphicsCommandList, slot: u32, list: usize, what: impl FnOnce() -> String) { + if slot == u32::MAX { + return; + } + let Some(Some(clock)) = CLOCK.get() else { + return; + }; + // SAFETY: an open list, our heap and read-back buffer, the two places + // `span_begin` took. + unsafe { + cmd.EndQuery(&clock.heap, D3D12_QUERY_TYPE_TIMESTAMP, slot + 1); + cmd.ResolveQueryData(&clock.heap, D3D12_QUERY_TYPE_TIMESTAMP, slot, 2, &clock.back, u64::from(slot) * 8); + } + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + let Some(s) = shot.as_mut() else { return }; + if s.carry.parts != 0 || s.events.len() >= MAX_EVENTS { + return; + } + s.resolved.push((slot, 2)); + // SAFETY: a plain query. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + s.events.push(Event { list, thread, stamp: slot, text: what() }); +} + +/// A line of `capture::op`, while a shot's first frame records. +pub(crate) fn line(list: usize, text: &str) { + let stamp = STAMP.replace(u32::MAX); + if NEXT_FRAME.replace(false) { + return; + } + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + let Some(s) = shot.as_mut() else { return }; + if s.stopped.is_some() || s.carry.parts != 0 || s.events.len() >= MAX_EVENTS { + return; + } + if ["draw ", "indexed ", "mesh ", "indirect ", "dispatch "].iter().any(|k| text.starts_with(k)) { + s.work += 1; + } + // SAFETY: a plain query. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + s.events.push(Event { list, thread, stamp, text: text.to_owned() }); +} + +/// Whether pictures of host format `format` can be shown +/// (`capture::to_rgba`'s formats, by the texture's own format). +fn shows(format: i32) -> bool { + matches!(format, 1..=2 | 9..=16 | 19..=65 | 87..=93) +} + +/// `list` says which title texture a host copy is of, while a shot +/// records (pictures are named after the title's texture, as the lines +/// name targets). +pub(crate) fn known(copy: usize, title: usize) { + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(s) = shot.as_mut() { + s.titles.insert(copy, title); + } +} + +/// Whether `list` was recorded in the frame of the shot being taken, and +/// if so the line its recording began at: for the list that runs before it +/// at submission ([`leaves`] there), which may be made after the frame's +/// present. +pub(crate) fn of_the_frame(list: &crate::host::HostList) -> Option { + if !matches!(PHASE.load(Relaxed), RECORDING | PENDING) { + return None; + } + let mark = *list.shot_mark.lock().unwrap_or_else(|e| e.into_inner()); + (mark.0 != 0 && mark.0 == SHOT_ID.load(Relaxed)).then_some(mark.1) +} + +/// Whether a move from host state `before` to `after` takes a texture out +/// of a state shaders write in (render target, unordered access, depth +/// write): a place for a picture. +pub(crate) fn might_leave(before: u32, after: u32) -> bool { + const WRITES: u32 = 0x4 | 0x8 | 0x10; + before & WRITES != 0 && before != after && before != COPY_SOURCE +} + +/// Host texture `copy` is about to be moved from state `before` to `after` +/// by commands recorded into `cmd`: either the title's list `recording` +/// itself, or (`begins`: the line that list's recording began at) the list +/// that runs before it at submission. If the texture leaves a state +/// shaders write in, this is a place for a picture: where one is taken, +/// the texture is moved to the copy-source state, copied, and moved back +/// to `before` here, so the caller's own move is recorded as in any +/// other frame (a caller may read "no change of state" as "not used +/// since": the alias copies of `crate::texture` do). +pub(crate) fn leaves( + cmd: &ID3D12GraphicsCommandList, + list: usize, + recording: Option<&crate::host::HostList>, + begins: Option, + copy: &std::sync::Arc, + before: u32, + after: u32, +) { + if !might_leave(before, after) { + return; + } + let texture = ©.texture; + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + if d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || d.SampleDesc.Count > 1 || !shows(d.Format.0) { + return; + } + let Some(host) = crate::host::host() else { return }; + let key = std::sync::Arc::as_ptr(copy) as usize; + let slices = if d.DepthOrArraySize <= 6 { u32::from(d.DepthOrArraySize) } else { 1 }; + // In the title's own list the copy gets a timestamp of its own, so + // its time is not the command's before it. (A list of the next frame + // has no places.) + if let Some(recording) = recording { + stamp(recording); + if NEXT_FRAME.replace(false) { + return; + } + } + let stamp = STAMP.replace(u32::MAX); + // SAFETY: a plain query. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + // Which place this is: the texture's n-th in the frame. + let (occurrence, title) = { + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + let Some(s) = shot.as_mut() else { return }; + let met = s.per_texture.entry(key).or_default(); + *met += 1; + (*met - 1, s.titles.get(&key).copied().unwrap_or(key)) + }; + let most = number("LEONIDA_SHOT_MB", 1024) << 20; + let mut moved = false; + for slice in 0..slices { + let sub = slice * u32::from(d.MipLevels); + let mut total = 0u64; + // SAFETY: a live device; outputs for one subresource. + unsafe { host.device().GetCopyableFootprints(&d, sub, 1, 0, None, None, None, Some(&mut total)) }; + // Whether the place's picture is taken in this frame; the line of + // a frame that keeps lines says which. + { + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + let Some(s) = shot.as_mut() else { break }; + let first = s.carry.parts == 0; + if first { + s.places += 1; + } + let what = format!( + "texture {title:#x} n {occurrence} slice {slice} {}x{} f{} leaves state {before:#x} for {after:#x}{}", + d.Width, + d.Height, + d.Format.0, + begins.map_or(String::new(), |b| format!(" at the start of the recording that begins at line {b}")) + ); + let say = |s: &mut Shot, word: &str, why: &str| { + if first && s.events.len() < MAX_EVENTS { + s.events.push(Event { list, thread, stamp: if slice == 0 { stamp } else { u32::MAX }, text: format!("{word} {what}{why}") }); + } + }; + // The same in every frame: a texture's ninth place on, and a + // picture larger than a frame may ever take. + if occurrence >= REPEATS { + if first { + s.not_taken += 1; + } + say(s, "SNAP-NOT", " (the texture's ninth place or later)"); + continue; + } + if total == 0 || total > most { + if first { + s.not_taken += 1; + } + say(s, "SNAP-NOT", " (too large)"); + continue; + } + if s.carry.done.contains(&(key, occurrence, slice)) { + // Taken by an earlier frame of the shot. + continue; + } + if s.bytes + total > s.budget { + s.later += 1; + say(s, "SNAP-LATER", ""); + continue; + } + s.bytes += total; + s.carry.done.insert((key, occurrence, slice)); + say(s, "SNAP", ""); + } + if !moved { + // SAFETY: an open list and a live texture in state `before`. + unsafe { + cmd.ResourceBarrier(&[crate::host::transition( + texture, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATES(COPY_SOURCE as i32), + )]); + } + moved = true; + } + let Some((buffer, footprint)) = crate::capture::read_back_of(host.device(), cmd, texture, sub) else { + continue; + }; + let name = format!("snap-{title:x}-n{occurrence}-s{slice}-{}x{}-f{}", d.Width, d.Height, d.Format.0); + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + let Some(s) = shot.as_mut() else { break }; + s.snaps.push(Snap { + occurrence, + name, + buffer, + footprint: footprint.Footprint, + bytes: total, + texture: title, + width: d.Width, + height: d.Height, + format: d.Format.0, + slice, + before, + after, + }); + } + if moved { + // SAFETY: an open list and a live texture in the copy-source state. + unsafe { + cmd.ResourceBarrier(&[crate::host::transition( + texture, + D3D12_RESOURCE_STATES(COPY_SOURCE as i32), + D3D12_RESOURCE_STATES(before as i32), + )]); + } + } +} + +/// The first frame of 500 draws or more, for `LEONIDA_SHOT_AT`. +static WORLD: AtomicU64 = AtomicU64::new(u64::MAX); + +/// Why a shot is taken of the frame after `frame`, if one is. +fn trigger(folder: &std::path::Path, frame: u64) -> Option { + let world = WORLD.load(Relaxed); + if world != u64::MAX && at().contains(&(frame + 1 - world)) { + return Some(format!("frame {} after the first one of 500 draws (LEONIDA_SHOT_AT)", frame + 1 - world)); + } + // The file is looked for at every fourth present. + if frame.is_multiple_of(4) { + let take = folder.join("take"); + if take.exists() { + // A file that cannot be removed would ask again at once. + return match std::fs::remove_file(&take) { + Ok(()) => Some("asked for (the file `take`)".to_string()), + Err(e) => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(error = %e, "the file `take` could not be removed: no frame shot for it")); + None + } + }; + } + } + None +} + +/// At the present of `frame`, on the thread that presents; `drawn` is the +/// number of draws run on the host so far. +pub(crate) fn present(frame: u64, drawn: u64) { + let Some(folder) = folder() else { return }; + static LAST: AtomicU64 = AtomicU64::new(0); + if drawn.saturating_sub(LAST.swap(drawn, Relaxed)) >= 500 { + let _ = WORLD.compare_exchange(u64::MAX, frame, Relaxed, Relaxed); + } + match PHASE.load(Relaxed) { + IDLE => { + let waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some(carry) = waiting { + // The next frame of a shot: one built like its first (the + // title's frames come in pairs: an even number of frames on). + if (frame + 1 - carry.first).is_multiple_of(2) { + *WAITING.lock().unwrap_or_else(|e| e.into_inner()) = None; + arm(frame + 1, carry, folder); + } + } else if let Some(why) = trigger(folder, frame) { + static TAKEN: AtomicU32 = AtomicU32::new(0); + let most = number("LEONIDA_SHOT_MAX", 12); + if u64::from(TAKEN.fetch_add(1, Relaxed)) >= most { + tracing::warn!(most, "frame shot not taken: the run has its most already (LEONIDA_SHOT_MAX)"); + } else { + arm(frame + 1, Carry { first: frame + 1, why, ..Default::default() }, folder); + } + } + } + RECORDING => { + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + let Some(s) = shot.as_mut() else { + PHASE.store(IDLE, Relaxed); + return; + }; + s.presents += 1; + // The frame's own present is the one after its lists were + // submitted. + let goes_on = !closing() && s.presents < 3; + if s.carry.parts == 0 { + let text = format!( + "PRESENT frame {frame}: {} draws and dispatches recorded since the shot began{}", + s.work, + if goes_on { "; the shot goes on through the next frame" } else { "" } + ); + s.events.push(Event { list: 0, thread: 0, stamp: u32::MAX, text }); + } + if !goes_on { + s.stopped = Some((std::time::Instant::now(), frame)); + PHASE.store(PENDING, Relaxed); + tracing::info!( + frame, + part = s.carry.parts, + lines = s.events.len(), + places = s.places, + pictures = s.snaps.len(), + for_later = s.later, + read_back_mb = s.bytes >> 20, + "frame shot: a frame is recorded; its pictures are read in two seconds" + ); + } + } + PENDING => { + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + let ready = shot + .as_ref() + .and_then(|s| s.stopped) + .is_some_and(|(when, of)| when.elapsed() >= std::time::Duration::from_secs(2) && frame >= of + 8); + if ready && let Some(s) = shot.take() { + PHASE.store(SAVING, Relaxed); + let to = folder.join(format!("shot-{}", s.carry.first)); + let spawned = std::thread::Builder::new().name("leonida-shot".into()).spawn(move || { + crate::framelog::keep_on_slow_cores("frame shot"); + let next = save(s, &to); + *WAITING.lock().unwrap_or_else(|e| e.into_inner()) = next; + PHASE.store(IDLE, Relaxed); + }); + if let Err(e) = spawned { + tracing::warn!(error = %e, "frame shot: no thread to write it out; dropped"); + PHASE.store(IDLE, Relaxed); + } + } + } + _ => {} + } +} + +/// Starts a frame of a shot: frame `frame`, the shot's first or (`carry` +/// says) a later one. +fn arm(frame: u64, carry: Carry, folder: &std::path::Path) { + let mut room = room_mb(); + if room < LEAST_MB { + if carry.parts != 0 { + tracing::warn!( + free_mb = crate::framelog::free_mb(), + part = carry.parts, + "frame shot ends here: too little memory free for more of its pictures" + ); + finish(&carry, &folder.join(format!("shot-{}", carry.first)), "ended early: too little memory free for more pictures", 0); + return; + } + // The lines and times need none of it. + room = 0; + } + let lines = carry.parts == 0; + let clock = lines && CLOCK.get_or_init(make_clock).is_some(); + NEXT.store(0, Relaxed); + SUBMITTED.store(0, Relaxed); + let id = SHOT_ID.fetch_add(1, Relaxed) + 1; + tracing::info!( + frame, + part = carry.parts, + pictures_so_far = carry.done.len(), + why = carry.why, + room_mb = room, + free_mb = crate::framelog::free_mb(), + timestamps = clock, + "frame shot: recording the next frame" + ); + *SHOT.lock().unwrap_or_else(|e| e.into_inner()) = Some(Shot { + id, + frame, + carry, + presents: 0, + work: 0, + events: Vec::with_capacity(if lines { 32768 } else { 0 }), + snaps: Vec::new(), + bytes: 0, + budget: room << 20, + places: 0, + later: 0, + not_taken: 0, + per_texture: Default::default(), + titles: Default::default(), + resolved: Vec::new(), + stopped: None, + }); + LINES.store(lines, Relaxed); + PHASE.store(RECORDING, Relaxed); +} + +/// Writes one frame of a shot out and lets its buffers go. What the shot +/// carries on, if pictures are left for a later frame. +fn save(shot: Shot, to: &std::path::Path) -> Option { + use std::fmt::Write; + use std::io::Write as _; + let started = std::time::Instant::now(); + if let Err(e) = std::fs::create_dir_all(to) { + tracing::warn!(error = %e, folder = %to.display(), "frame shot not saved: no folder"); + return None; + } + let mut carry = shot.carry.clone(); + let part = carry.parts; + if part == 0 { + // Lines: place, list, thread, timestamp's place (-1: none), text. + let mut events = String::with_capacity(shot.events.iter().map(|e| e.text.len() + 40).sum()); + for (seq, e) in shot.events.iter().enumerate() { + let stamp = if e.stamp == u32::MAX { -1 } else { i64::from(e.stamp) }; + let _ = writeln!(events, "{seq}\t{:#x}\t{}\t{stamp}\t{}", e.list, e.thread, e.text.replace(['\n', '\r', '\t'], " ")); + } + if let Err(e) = std::fs::write(to.join("events.txt"), events) { + tracing::warn!(error = %e, folder = %to.display(), "frame shot: its lines could not be written"); + } + // Timestamps: the places lists resolved, as the card wrote them. + let mut stamps = String::new(); + if let Some(Some(clock)) = CLOCK.get() { + let _ = writeln!(stamps, "frequency\t{}", clock.frequency); + for &(base, count) in &shot.resolved { + for slot in base..(base + count).min(SLOTS) { + // SAFETY: a place inside the mapped read-back buffer, + // which the card wrote long ago (or never: then what + // it held). + let ticks = unsafe { std::ptr::read_volatile((clock.mapped as *const u64).add(slot as usize)) }; + let _ = writeln!(stamps, "{slot}\t{ticks}"); + } + } + } + let _ = std::fs::write(to.join("stamps.txt"), stamps); + let _ = std::fs::write( + to.join("snaps.txt"), + "texture\tn\tslice\tfile\tpart\tframe\twidth\theight\tformat\tbefore\tafter\tnot_black_percent\tmean_rgb\n", + ); + carry.lines = shot.events.len(); + carry.work = shot.work; + carry.presents = shot.presents; + carry.places = shot.places; + carry.not_taken = shot.not_taken; + } + // Pictures. + let full = std::env::var_os("LEONIDA_SHOT_FULL").is_some_and(|v| v == "1"); + let mut list = String::new(); + let (mut saved, mut failed) = (0u32, 0u32); + for snap in shot.snaps { + let f = snap.footprint; + let mut data = std::ptr::null_mut(); + // SAFETY: the copy finished long ago; the mapping spans the bytes + // the footprint was sized for. + let rgba = unsafe { + if snap.buffer.Map(0, None, Some(&mut data)).is_err() || data.is_null() { + None + } else { + let rows = std::slice::from_raw_parts(data.cast::(), snap.bytes as usize); + let rgba = crate::capture::to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, f.RowPitch as usize, rows); + snap.buffer.Unmap(0, None); + rgba + } + }; + let Some(rgba) = rgba else { + failed += 1; + continue; + }; + // Every `step`th pixel each way: 1280 across at most, unless asked. + let step = if full { 1 } else { (f.Width.max(f.Height) as usize).div_ceil(1280).max(1) }; + let (w, h) = ((f.Width as usize).div_ceil(step), (f.Height as usize).div_ceil(step)); + let mut raw = Vec::with_capacity((w * 3 + 1) * h); + let (mut lit, mut sum) = (0u64, [0u64; 3]); + for y in 0..h { + raw.push(0); + for x in 0..w { + let p = &rgba[((y * step) * f.Width as usize + x * step) * 4..][..3]; + raw.extend_from_slice(p); + lit += u64::from(p.iter().any(|&c| c > 8)); + for (s, &c) in sum.iter_mut().zip(p) { + *s += u64::from(c); + } + } + } + let n = (w * h).max(1) as u64; + match std::fs::write(to.join(format!("{}.png", snap.name)), crate::capture::png_rgb(w as u32, h as u32, &raw)) { + Ok(()) => saved += 1, + Err(_) => { + failed += 1; + continue; + } + } + let _ = writeln!( + list, + "{:#x}\t{}\t{}\t{}.png\t{part}\t{}\t{}\t{}\t{}\t{:#x}\t{:#x}\t{:.1}\t{},{},{}", + snap.texture, + snap.occurrence, + snap.slice, + snap.name, + shot.frame, + snap.width, + snap.height, + snap.format, + snap.before, + snap.after, + lit as f64 * 100.0 / n as f64, + sum[0] / n, + sum[1] / n, + sum[2] / n + ); + } + if let Ok(mut file) = std::fs::OpenOptions::new().append(true).create(true).open(to.join("snaps.txt")) { + let _ = file.write_all(list.as_bytes()); + } + carry.parts += 1; + carry.saved += saved; + carry.failed += failed; + carry.read_back_mb += shot.bytes >> 20; + tracing::info!( + folder = %to.display(), + part, + frame = shot.frame, + pictures = saved, + failed, + for_later = shot.later, + seconds = started.elapsed().as_secs_f64(), + "frame shot: a frame's part is saved" + ); + // More pictures in a later frame, while frames still get some. + if shot.later == 0 { + finish(&carry, to, "complete", 0); + None + } else if (saved == 0 && part != 0) || carry.parts >= MAX_PARTS { + finish(&carry, to, "ended early: a frame got no further picture", shot.later); + None + } else { + Some(carry) + } +} + +/// A shot's last files: `info.txt` and `done`. +fn finish(carry: &Carry, to: &std::path::Path, how: &str, missing: u32) { + let info = format!( + "frame\t{}\nwhy\t{}\nended\t{how}\npresents\t{}\ndraws_and_dispatches\t{}\nlines\t{}\nplaces_for_pictures\t{}\nplaces_never_taken\t{}\n\ + frames_taken_in\t{}\npictures_saved\t{}\npictures_failed\t{}\npictures_missing\t{missing}\nread_back_mb\t{}\n", + carry.first, + carry.why, + carry.presents, + carry.work, + carry.lines, + carry.places, + carry.not_taken, + carry.parts, + carry.saved, + carry.failed, + carry.read_back_mb + ); + let _ = std::fs::write(to.join("info.txt"), info); + let _ = std::fs::write(to.join("done"), ""); + tracing::info!( + folder = %to.display(), + how, + frames = carry.parts, + lines = carry.lines, + places = carry.places, + pictures = carry.saved, + failed = carry.failed, + missing, + "frame shot saved" + ); +} + +#[cfg(test)] +mod tests { + #[test] + fn the_formats_shown_are_the_ones_the_pictures_decode() { + // Every format `shows` names decodes, and one it does not name + // does not (a block-compressed one: never a target). + for format in (1..=2).chain(9..=16).chain(19..=65).chain(87..=93) { + assert!(super::shows(format)); + let pixel = [0u8; 16]; + assert!(crate::capture::to_rgba(format as u32, 1, 1, 16, &pixel).is_some(), "format {format}"); + } + assert!(!super::shows(71)); + assert!(crate::capture::to_rgba(71, 1, 1, 16, &[0u8; 16]).is_none()); + } +} diff --git a/crates/leonida-gpu/src/texback.rs b/crates/leonida-gpu/src/texback.rs new file mode 100644 index 000000000..7582793c6 --- /dev/null +++ b/crates/leonida-gpu/src/texback.rs @@ -0,0 +1,274 @@ +//! Textures shaders write that the title's own code then reads on the CPU. +//! On the console the CPU and the GPU share memory, so what a compute pass +//! stores into a texture is in title memory for the CPU to read. Here it stays +//! in the texture's host copy. The title's ocean is one: its wave passes write +//! a 256x256 height map (R32_FLOAT) and a displacement map (R32G32_FLOAT), and +//! its CPU code samples both, which is what boats float on; it read memory +//! nothing had written (run rw1, `LEONIDA_READ_WATCH=1`: about 30 places in +//! the title read those two kinds), and boats sank. +//! +//! For textures of the kinds in `LEONIDA_TEXTURE_BACK` (comma-separated +//! `xf`; `1` for the four water formats found by +//! the upstream trace), a list in which shaders write one copies it +//! into a read-back buffer of ours when it closes, and once the list has run +//! the texels are tiled into the texture's title memory in the console's +//! layout, as the console's GPU would have left them. +//! +//! shortcut: by kind, not by texture: textures of those kinds the title never +//! reads are copied back too (about a megabyte per such list). The copy shows +//! what the list's last write left; a title read in between sees the frame +//! before, as it would before the console's GPU has run. + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, Weak}; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::object::This; + +/// The kinds copied back: (width, height, format). +fn kinds() -> &'static [(u64, u32, u32)] { + static KINDS: OnceLock> = OnceLock::new(); + KINDS.get_or_init(|| { + const DEFAULT: &str = "256x256f41,256x256f16,64x64f16,128x128f36"; + let list = match std::env::var("LEONIDA_TEXTURE_BACK").as_deref() { + Ok("1") => DEFAULT.to_owned(), + Ok(spec) => spec.to_owned(), + Err(_) => String::new(), + }; + let kinds: Vec<(u64, u32, u32)> = list + .split(',') + .filter_map(|k| { + let (size, format) = k.trim().split_once('f')?; + let (w, h) = size.split_once('x')?; + Some((w.parse().ok()?, h.parse().ok()?, format.parse().ok()?)) + }) + .collect(); + if !kinds.is_empty() { + tracing::info!(?kinds, "textures of these kinds that shaders write are copied back into title memory (LEONIDA_TEXTURE_BACK)"); + } + kinds + }) +} + +/// Whether title texture `resource` is of a kind copied back. +pub(crate) fn wanted(resource: This) -> bool { + let kinds = kinds(); + !kinds.is_empty() + && crate::resource::texture_kind(resource).is_some_and(|k| kinds.contains(&k)) +} + +/// An outstanding write to a specific allocation. Mapping and resource +/// changes invalidate only the writes that could touch the replaced memory. +struct Ticket { + owner: usize, + at: usize, + end: usize, + valid: AtomicBool, +} + +static TICKETS: Mutex>> = Mutex::new(Vec::new()); +static TRACKING: AtomicBool = AtomicBool::new(false); + +fn track(owner: usize, at: usize, end: usize) -> Arc { + let ticket = Arc::new(Ticket { owner, at, end, valid: AtomicBool::new(true) }); + let mut tickets = TICKETS.lock().unwrap_or_else(|e| e.into_inner()); + tickets.retain(|weak| weak.strong_count() != 0); + tickets.push(Arc::downgrade(&ticket)); + TRACKING.store(true, Ordering::Relaxed); + ticket +} + +fn invalidate(matches: impl Fn(&Ticket) -> bool) { + if !TRACKING.load(Ordering::Relaxed) { + return; + } + TICKETS.lock().unwrap_or_else(|e| e.into_inner()).retain(|weak| { + let Some(ticket) = weak.upgrade() else { return false }; + if matches(&ticket) { + ticket.valid.store(false, Ordering::Release); + } + true + }); +} + +pub(crate) fn released(owner: usize) { + invalidate(|ticket| ticket.owner == owner); +} + +pub(crate) fn replaced(at: usize) { + invalidate(|ticket| ticket.at == at); +} + +pub(crate) fn remapped(at: usize, len: usize) { + let end = at.saturating_add(len); + invalidate(|ticket| at < ticket.end && ticket.at < end); +} + +pub(crate) struct Target { + pub(crate) copy: Arc, + layout: leonida_formats::texture::Layout, + ticket: Arc, +} + +impl Target { + pub(crate) fn new(resource: This) -> Option { + // Keep the host copy independently of the title's resource lifetime. + let copy = crate::resource::host_copy(resource)?; + let _mapping = crate::watch::title_memory_reading(); + let (layout, at, size) = crate::resource::title_texture(resource)?; + let end = at.checked_add(size).filter(|&end| at != 0 && end > at)?; + let ticket = track(resource as usize, at, end); + Some(Self { copy, layout, ticket }) + } + + pub(crate) fn owner(&self) -> usize { self.ticket.owner } +} + +/// The readback resources and the allocation the pixels belong to. +pub(crate) struct Back { + buffer: ID3D12Resource, + footprints: Vec, + rows: Vec, + mips: u32, + layout: leonida_formats::texture::Layout, + ticket: Arc, +} + +impl Back { + pub(crate) fn range(&self) -> (usize, usize) { + (self.ticket.at, self.ticket.end) + } +} + +/// Records a host copy from a texture already in COPY_SOURCE. +pub(crate) fn record(list: &ID3D12GraphicsCommandList, target: Target) -> Option { + if !target.ticket.valid.load(Ordering::Acquire) { + return None; + } + let host = crate::host::host()?; + let texture = &target.copy.texture; + // SAFETY: a live texture kept through the command list's state tracking. + let desc = unsafe { texture.GetDesc() }; + let mips = u32::from(desc.MipLevels.max(1)); + let subresources = mips * u32::from(desc.DepthOrArraySize.max(1)); + let n = subresources as usize; + let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n]; + let mut rows = vec![0u32; n]; + let mut total = 0u64; + // SAFETY: out arrays of `n` entries. + unsafe { + host.device.GetCopyableFootprints( + &desc, + 0, + subresources, + 0, + Some(footprints.as_mut_ptr()), + Some(rows.as_mut_ptr()), + None, + Some(&mut total), + ) + }; + // The last footprint's advertised extent can omit row-end padding. + // The tiler reads a pitched slice, so the mapped buffer must include it. + for (footprint, &rows) in footprints.iter().zip(&rows) { + let format = footprint.Footprint; + let pitched = u64::from(format.RowPitch) + .checked_mul(u64::from(rows))? + .checked_mul(u64::from(format.Depth))?; + total = total.max(footprint.Offset.checked_add(pitched)?); + } + let buffer = host.read_back_buffer(total)?; + for (i, footprint) in footprints.iter().enumerate() { + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(&buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *footprint }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: i as u32 }, + }; + // SAFETY: an open list; the texture is in the copy-source state. + unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + Some(Back { buffer, footprints, rows, mips, layout: target.layout, ticket: target.ticket }) +} + +/// Once the list has run, tile its texels back into the same title allocation. +pub(crate) fn land(back: &Back) { + static COPIED: AtomicU64 = AtomicU64::new(0); + static STALE: AtomicU64 = AtomicU64::new(0); + let _mapping = crate::watch::title_memory_reading(); + let _ticket_guard = TICKETS.lock().unwrap_or_else(|e| e.into_inner()); + if !back.ticket.valid.load(Ordering::Acquire) { + let skipped = STALE.fetch_add(1, Ordering::Relaxed) + 1; + if skipped.is_power_of_two() { + tracing::info!(skipped, "skipping texture readbacks whose title allocation changed"); + } + return; + } + let (at, end) = back.range(); + let size = end - at; + let mut tiled = vec![0u8; size]; + // Keep title bytes the subresources do not cover. + if !crate::host::read_into(at as *const u8, &mut tiled) { + return; + } + let mut data = std::ptr::null_mut(); + // SAFETY: our read-back buffer, written by the list that has run. + unsafe { + if back.buffer.Map(0, None, Some(&mut data)).is_err() || data.is_null() { + return; + } + } + for (i, (footprint, &rows)) in back.footprints.iter().zip(&back.rows).enumerate() { + let (mip, slice) = (i as u32 % back.mips, i as u32 / back.mips); + let f = footprint.Footprint; + let pitch = f.RowPitch as usize; + let len = pitch * rows as usize * f.Depth as usize; + // SAFETY: the subresource's part of the mapped buffer. + let linear = unsafe { std::slice::from_raw_parts(data.cast::().add(footprint.Offset as usize), len) }; + if let Err(e) = back.layout.tile(&mut tiled, mip, slice, linear, pitch, pitch * rows as usize) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(?e, mip, slice, "a texture copied back could not be tiled")); + // SAFETY: mapped above. + unsafe { back.buffer.Unmap(0, None) }; + return; + } + } + // SAFETY: mapped above. + unsafe { back.buffer.Unmap(0, None) }; + crate::host::copy_mapped(at as *mut u8, tiled.as_ptr(), size, true); + let copied = COPIED.fetch_add(1, Ordering::Relaxed) + 1; + if copied == 1 || copied.is_multiple_of(128) { + tracing::info!(copied, bytes = size, "texture readback landed"); + } +} + + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_readbacks_for_changed_allocations_are_invalidated() { + let first = track(91, 0x1000, 0x2000); + let next = track(92, 0x2000, 0x3000); + let far = track(93, 0x4000, 0x5000); + + remapped(0x0f00, 0x200); + assert!(!first.valid.load(Ordering::Acquire)); + assert!(next.valid.load(Ordering::Acquire)); + replaced(0x2000); + assert!(!next.valid.load(Ordering::Acquire)); + assert!(far.valid.load(Ordering::Acquire)); + + released(93); + assert!(!far.valid.load(Ordering::Acquire)); + assert!(track(94, 0x2000, 0x3000).valid.load(Ordering::Acquire)); + } +} diff --git a/crates/leonida-gpu/src/texture.rs b/crates/leonida-gpu/src/texture.rs index 2aca7afe6..51d364d78 100644 --- a/crates/leonida-gpu/src/texture.rs +++ b/crates/leonida-gpu/src/texture.rs @@ -102,10 +102,16 @@ pub(crate) static SPARE_STATS: [std::sync::atomic::AtomicU64; 2] = [const { std: /// dip. Buffers of up to 8 MiB are now kept by size and used again, /// zeroed as a new one is (levels not there yet must read as zeros). /// `LEONIDA_STAGING_POOL=0`: made and freed each time, as before. +/// `LEONIDA_STAGING_POOL=alt`: twenty seconds with the pool, twenty +/// without, in turn, each change said in the log: a buffer made without +/// is freed as before, and the spare ones wait for the next turn. +/// `LEONIDA_STAGING_POOL_MB`: the most kept spare (256 unless said). fn staging_buffer(host: &crate::host::Host, total: u64) -> Option<(ID3D12Resource, *mut u8, u64)> { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); let size = total.max(64 << 10).next_power_of_two(); - if size > SPARE_MOST.1 || !*ON.get_or_init(|| std::env::var_os("LEONIDA_STAGING_POOL").is_none_or(|v| v != "0")) { + if size > SPARE_MOST.1 || !staging_pool() { + // (Counted as made: the frame log's "staging N made" is then the + // buffers of a run without the pool too.) + SPARE_STATS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); return host.upload_buffer(total).map(|(buffer, data)| (buffer, data, 0)); } let spare = { @@ -127,6 +133,41 @@ fn staging_buffer(host: &crate::host::Host, total: u64) -> Option<(ID3D12Resourc host.upload_buffer(size).map(|(buffer, data)| (buffer, data, size)) } +/// Whether staging buffers are taken from and returned to the spare ones +/// now (`LEONIDA_STAGING_POOL`). +fn staging_pool() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("LEONIDA_STAGING_POOL").as_deref() { + Ok("0") => 0, + Ok("alt") => 2, + _ => 1, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "texture staging buffers are taken from the spare ones from now (LEONIDA_STAGING_POOL=alt): {}", + if on { "ON" } else { "off, made and freed each time" } + ); + } + on + } + } +} + +/// The most bytes of staging buffers kept spare (`LEONIDA_STAGING_POOL_MB`). +fn spare_most() -> u64 { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("LEONIDA_STAGING_POOL_MB").ok().and_then(|v| v.trim().parse::().ok()).map_or(SPARE_MOST.0, |mb| mb << 20) + }) +} + /// What a texture's staging buffer holds: the hash of the memory detiled /// (memory not watched), or the write-watch asking it was detiled after. #[derive(Default)] @@ -465,7 +506,7 @@ impl Drop for Staging { // reset, after their submission has run): its buffer is spare. if self.pooled != 0 { let mut all = SPARE.lock().unwrap_or_else(|e| e.into_inner()); - if all.1 + self.pooled <= SPARE_MOST.0 { + if all.1 + self.pooled <= spare_most() { all.1 += self.pooled; all.0.entry(self.pooled).or_default().push(Spare(self.buffer.clone(), self.data as usize)); } diff --git a/crates/leonida-gpu/src/watch.rs b/crates/leonida-gpu/src/watch.rs index 4746e833e..79c449597 100644 --- a/crates/leonida-gpu/src/watch.rs +++ b/crates/leonida-gpu/src/watch.rs @@ -1109,6 +1109,7 @@ pub fn title_memory_reading_now() -> Option { /// shows is new and read-write, so it is no longer guarded (nor known /// unmapped). pub fn title_memory_remapped(at: usize, len: usize) { + crate::texback::remapped(at, len); // A placed texture there arrives, goes or changes with no descriptor // written. crate::descriptor::host::remapped(at, len); diff --git a/crates/leonida-hle/src/modules/dstorage.rs b/crates/leonida-hle/src/modules/dstorage.rs index aaf25d8b4..2f6ab4f0a 100644 --- a/crates/leonida-hle/src/modules/dstorage.rs +++ b/crates/leonida-hle/src/modules/dstorage.rs @@ -368,6 +368,9 @@ struct Lane { clock: u64, /// Enqueued, not yet submitted. unsubmitted: Vec, + /// Left out when the queue submitted itself, until the title's Submit: + /// reads into physical pages and the status entries behind them. + held: Vec, /// Submitted, by sequence number: reads not started, status entries /// not written, reads running, and failures not yet reported. reads: VecDeque<(u64, Request)>, @@ -606,8 +609,20 @@ impl Lanes { } } - /// Moves a queue's enqueued commands to the workers. + /// Moves a queue's enqueued commands to the workers (the title's + /// Submit). fn submit(&mut self, id: u64) { + self.submit_as(id, true); + } + + /// As [`Lanes::submit`]; `explicit` false when a half-full queue submits + /// itself, which leaves reads into physical pages for the title's + /// Submit: their page lists point into the title's page table, which + /// The title fills for the batch in its own submit path, right + /// before Submit (`sub_1400e88f0`), so until then they name no page or a + /// page that now holds something else. A status entry behind a held + /// read waits with it. + fn submit_as(&mut self, id: u64, explicit: bool) { let Some(class) = self.lanes.get(&id).map(|l| l.class) else { return; }; @@ -626,7 +641,18 @@ impl Lanes { if lane.reads.is_empty() { lane.clock = lane.clock.max(self.lane_now[class]); } - for command in std::mem::take(&mut lane.unsubmitted) { + let mut commands = if explicit { std::mem::take(&mut lane.held) } else { Vec::new() }; + commands.append(&mut lane.unsubmitted); + for command in commands { + let hold = !explicit + && match &command { + Command::Read(r) => r.options & PAGE_DESTINATION != 0, + Command::Status(_) => !lane.held.is_empty(), + }; + if hold { + lane.held.push(command); + continue; + } let seq = self.next_seq; self.next_seq += 1; match command { @@ -645,6 +671,7 @@ impl Lane { capacity: usize::from(capacity), clock: 0, unsubmitted: Vec::new(), + held: Vec::new(), reads: VecDeque::new(), statuses: VecDeque::new(), running: BTreeSet::new(), @@ -655,7 +682,11 @@ impl Lane { /// Requests and status entries held, submitted or not. fn entries(&self) -> usize { - self.unsubmitted.len() + self.reads.len() + self.statuses.len() + self.running.len() + self.unsubmitted.len() + + self.held.len() + + self.reads.len() + + self.statuses.len() + + self.running.len() } /// Writes the status entries whose earlier reads have all finished. @@ -703,6 +734,7 @@ fn close_lane(id: u64) { }; lane.closed = true; lane.unsubmitted.clear(); + lane.held.clear(); lane.reads.clear(); lane.statuses.clear(); // releases their arrays while lanes.lanes.get(&id).is_some_and(|l| !l.running.is_empty()) { @@ -814,6 +846,16 @@ fn queue(this: QueueRef, command: Command) { if lane.entries() + 1 < lane.capacity.max(2) { break; } + // Full with reads held for a Submit the title cannot make while it + // waits here: they go now, page lists as they are. + if !lane.held.is_empty() { + static WARNED: AtomicBool = AtomicBool::new(false); + if !WARNED.swap(true, Ordering::Relaxed) { + tracing::warn!("dstorage: a full queue's reads into physical pages start before the title's Submit"); + } + lanes.submit(id); + scheduler.work.notify_all(); + } lanes = scheduler .finished .wait(lanes) @@ -824,8 +866,19 @@ fn queue(this: QueueRef, command: Command) { }; lane.unsubmitted.push(command); if lane.unsubmitted.len() >= (lane.capacity / 2).max(1) { - lanes.submit(id); + let capacity = lane.capacity; + lanes.submit_as(id, false); scheduler.work.notify_all(); + let held = lanes.lanes.get(&id).map_or(0, |l| l.held.len()); + let n = AUTO_SUBMITS.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + tracing::info!( + n, + capacity, + held, + "dstorage: a queue half full submitted itself; reads into physical pages wait for the title's Submit" + ); + } } } @@ -836,7 +889,7 @@ extern "system" fn submit(this: QueueRef) { return; }; let mut lanes = scheduler.lock(); - let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len()); + let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len() + l.held.len()); tracing::debug!(commands = pending, "dstorage: submit"); lanes.submit(id); scheduler.work.notify_all(); @@ -1167,6 +1220,9 @@ fn into_destination( } } +/// Queues that submitted themselves, half full (diagnostics). +static AUTO_SUBMITS: AtomicU32 = AtomicU32::new(0); + /// Slots by the 2020 order, which the argument shapes at /// the title's call sites match (0x18, 0x20, 0x30 and 0x40 are called). static QUEUE_VTABLE: Methods<12> = Methods([ @@ -1679,6 +1735,95 @@ mod tests { let seen = unsafe { std::slice::from_raw_parts(mapped.cast::().add(PAGE - 40), 100) }; assert_eq!(seen, plain); } + #[test] + fn a_queue_that_submits_itself_holds_reads_into_pages() { + let mut l = lanes(STAGING); + l.lanes.insert(0, Lane::new(0, 64)); + let array = status_array(1).cast::>(); + read(&mut l, 0, PAGE_DESTINATION, 16); + read(&mut l, 0, 0, 16); + add_ref_instance(array); + l.lanes.get_mut(&0).unwrap().unsubmitted.push(Command::Status(Status { array, index: 0 })); + l.submit_as(0, false); + // Only the plain read starts; the status waits behind the held one. + let plain = l.start().unwrap(); + assert_eq!(plain.request.options, 0); + assert!(l.start().is_none()); + l.finish(&plain, Ok(())); + assert_eq!(l.lanes[&0].held.len(), 2); + l.submit(0); + let paged = l.start().unwrap(); + assert_eq!(paged.request.options, PAGE_DESTINATION); + assert!(l.lanes[&0].held.is_empty()); + assert!(!l.lanes[&0].statuses.is_empty()); + l.finish(&paged, Ok(())); + assert!(l.lanes[&0].statuses.is_empty()); + } + + #[test] + fn a_page_list_the_title_changes_before_its_submit() { + use crate::modules::xmem; + let (mut given, mut pages) = (2usize, [0usize; 2]); + assert_eq!( + xmem::XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()), + 1 + ); + let mapped = xmem::XMemVirtualAlloc( + std::ptr::null_mut(), + 2 * PAGE, + 0x2000 | 0x2040_0000, // reserve, 64 KiB pages + 0, + 0x04, + ); + assert!(!mapped.is_null()); + assert_eq!(xmem::XMemMapPhysicalPages(mapped, 2, pages.as_ptr()), mapped); + // The title's page table: still the page's previous owner when the + // request is enqueued, the right page by its Submit. + let mut list = [pages[0]]; + let plain = pattern(4096); + let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT = + call(factory(), 0x50); + let desc = QueueDesc { + source_type: 0, + capacity: 4, + priority: 1, + name: c"pages".as_ptr(), + unknown: 1, + }; + let mut queue = std::ptr::null_mut(); + assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK); + let array = status_array(1); + let r = request( + PAGE_DESTINATION | MEMORY_SOURCE, + list.as_mut_ptr().cast(), + plain.len(), + plain.as_ptr().cast(), + 0, + plain.len(), + ); + enqueue(queue, &r); + let mut out = [0u8; 16]; + enqueue(queue, &request(MEMORY_SOURCE, out.as_mut_ptr().cast(), 16, plain.as_ptr().cast(), 0, 16)); + // Half of four: the queue submitted itself. Time for a read started + // then to land in the old page. + std::thread::sleep(std::time::Duration::from_millis(50)); + // SAFETY: the list outlives the request, which reads it when it runs. + unsafe { std::ptr::write_volatile(list.as_mut_ptr(), pages[1]) }; + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, plain[..16]); + // SAFETY: both pages are mapped read-write. + let (first, second) = unsafe { + ( + std::slice::from_raw_parts(mapped.cast::(), plain.len()), + std::slice::from_raw_parts(mapped.cast::().add(PAGE), plain.len()), + ) + }; + assert_eq!(second, plain); + assert!(first.iter().all(|&b| b == 0), "the old page was written"); + } + #[test] fn zlib_into_pages_in_place_and_across_allocations() { use crate::modules::xmem; From f631ee016c2a2e3907794d99cbec4f971c522fc4 Mon Sep 17 00:00:00 2001 From: ShinniUwU Date: Wed, 25 Nov 2026 23:05:50 +0100 Subject: [PATCH 4/6] fix: README run script path; rename script skips CLAUDE.md and TODO.md --- README.md | 2 +- scripts/rename-from-upstream.ps1 | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 26e625971..81f37c56d 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ settings. off by default). It asks for the game folder too, and whether to remember it: ```powershell -powershell -ExecutionPolicy Bypass -File . un-gta6.ps1 +powershell -ExecutionPolicy Bypass -File .\run-gta6.ps1 ``` `measure-gta6.ps1` does the same with the diagnostics build, the frame log and the card meter on, and saves diff --git a/scripts/rename-from-upstream.ps1 b/scripts/rename-from-upstream.ps1 index f29063578..05cfd6603 100644 --- a/scripts/rename-from-upstream.ps1 +++ b/scripts/rename-from-upstream.ps1 @@ -33,6 +33,9 @@ $protectAll = @( ) $protectReadme = @('VIctory(?![A-Za-z])') +# This fork's own files, which name upstream on purpose. +$keepAsIs = @('CLAUDE.md', 'TODO.md') + function Convert-Name([string]$text, [string[]]$protect) { $saved = New-Object System.Collections.Generic.List[string] foreach ($p in $protect) { @@ -57,6 +60,7 @@ foreach ($rel in $tracked + $Also) { $path = Join-Path $Root $rel if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { continue } if ((Resolve-Path -LiteralPath $path).Path -eq $self) { continue } + if ($keepAsIs -contains $rel) { continue } $bytes = [System.IO.File]::ReadAllBytes($path) if ([Array]::IndexOf($bytes, [byte]0) -ge 0) { continue } try { $text = $strict.GetString($bytes) } catch { Write-Host "not UTF-8, left alone: $rel"; continue } From 5147a1504acf86ff46b9e7d653c9957bd6595976 Mon Sep 17 00:00:00 2001 From: ShinniUwU Date: Wed, 25 Nov 2026 23:19:25 +0100 Subject: [PATCH 5/6] fix(gpu): LEONIDA_SKIP_PIPELINES works in every build and keeps the pipeline from the driver --- crates/leonida-gpu/src/pipeline.rs | 30 ++++++++++++++++--------- crates/leonida-gpu/src/pipeline/make.rs | 9 ++++++-- 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/crates/leonida-gpu/src/pipeline.rs b/crates/leonida-gpu/src/pipeline.rs index 6096f0a4e..8f495bf41 100644 --- a/crates/leonida-gpu/src/pipeline.rs +++ b/crates/leonida-gpu/src/pipeline.rs @@ -493,7 +493,7 @@ pub(crate) fn making() -> u64 { static DROPS: Mutex>> = Mutex::new(None); /// Shader hashes as printed in the pipeline diagnostics. -#[cfg(all(windows, feature = "diagnostics"))] +#[cfg(windows)] fn parse_skip_hashes(value: &str) -> Vec { value .split(',') @@ -513,19 +513,27 @@ fn parse_skip_hashes(value: &str) -> Vec { .collect() } +/// Whether `hash` is in `LEONIDA_SKIP_PIPELINES` (every build): pipelines +/// with such a shader are never handed to the host driver, and their draws +/// and dispatches are dropped. For a shader whose pipeline crashes a +/// driver's compiler (an RX 9070 in `amdxc64.dll` on `0a12de46c4d5db08`). +#[cfg(windows)] +pub(crate) fn skip_listed(hash: &str) -> bool { + static HASHES: OnceLock> = OnceLock::new(); + HASHES + .get_or_init(|| { + let value = std::env::var("LEONIDA_SKIP_PIPELINES").unwrap_or_default(); + parse_skip_hashes(&value) + }) + .iter() + .any(|h| h == hash) +} + #[cfg(all(windows, feature = "diagnostics"))] fn skipped_shader(p: &Pipeline) -> Option<&str> { - static HASHES: OnceLock> = OnceLock::new(); - let hashes = HASHES.get_or_init(|| { - let value = std::env::var("LEONIDA_SKIP_PIPELINES").unwrap_or_default(); - parse_skip_hashes(&value) - }); - if hashes.is_empty() { - return None; - } p.shaders .iter() - .find(|shader| hashes.contains(&shader.hash)) + .find(|shader| skip_listed(&shader.hash)) .map(|shader| shader.hash.as_str()) } @@ -819,7 +827,7 @@ pub fn save_pipeline_cache() { #[cfg(test)] mod tests { - #[cfg(all(windows, feature = "diagnostics"))] + #[cfg(windows)] #[test] fn skip_hashes_accepts_full_hashes_only() { assert!(super::parse_skip_hashes(" , ").is_empty()); diff --git a/crates/leonida-gpu/src/pipeline/make.rs b/crates/leonida-gpu/src/pipeline/make.rs index ad5b9ef51..059eb2920 100644 --- a/crates/leonida-gpu/src/pipeline/make.rs +++ b/crates/leonida-gpu/src/pipeline/make.rs @@ -60,8 +60,13 @@ impl Pending { } fn make(&self) { - self.made - .get_or_init(|| HostPipeline::new(&self.shaders, self.graphics.as_deref())); + self.made.get_or_init(|| { + if let Some(s) = self.shaders.iter().find(|s| super::skip_listed(&s.hash)) { + tracing::warn!(hash = %s.hash, "host pipeline not made: its shader is in LEONIDA_SKIP_PIPELINES"); + return None; + } + HostPipeline::new(&self.shaders, self.graphics.as_deref()) + }); let (lock, done) = &DONE; let _held = lock.lock().unwrap_or_else(|e| e.into_inner()); done.notify_all(); From 2f977c56e577deef364563557e93e48fe88d9e0a Mon Sep 17 00:00:00 2001 From: ShinniUwU Date: Wed, 25 Nov 2026 23:19:25 +0100 Subject: [PATCH 6/6] feat: shot-run.ps1 takes frame shots unattended --- README.md | 6 +++++ shot-run.ps1 | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 shot-run.ps1 diff --git a/README.md b/README.md index 81f37c56d..bf1428b80 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,12 @@ powershell -ExecutionPolicy Bypass -File .\run-gta6.ps1 `measure-gta6.ps1` does the same with the diagnostics build, the frame log and the card meter on, and saves everything the game prints to `%LOCALAPPDATA%\leonida\logs`. +`shot-run.ps1` runs the game unattended and takes frame shots (`-ShotAt`, with `-Keys` to get through the menus) into +`%LOCALAPPDATA%\leonida\shots`. Shots come from your game: keep them on your PC. + +If the GPU driver crashes while building one shader's pipeline, `LEONIDA_SKIP_PIPELINES=<16-digit shader hash>` keeps +that pipeline from ever reaching the driver (its draws are dropped). + Saves, settings and `crashes.log` are kept in `%LOCALAPPDATA%\leonida\data`, derived data in `%LOCALAPPDATA%\leonida\cache`. diff --git a/shot-run.ps1 b/shot-run.ps1 new file mode 100644 index 000000000..471c861ec --- /dev/null +++ b/shot-run.ps1 @@ -0,0 +1,64 @@ +# Runs the game unattended and takes frame shots (LEONIDA_SHOT) at fixed frames, then closes it. +# Uses the diagnostics build, like measure-gta6.ps1. Shots go under %LOCALAPPDATA%\leonida\shots: +# per shot, the frame's commands (events.txt), the card's clock (stamps.txt) and the picture each +# pass left (snap-*.png). They come from your game: keep them on your PC, never post them. +# +# powershell -ExecutionPolicy Bypass -File .\shot-run.ps1 -Keys '30:Enter,35:Enter' -ShotAt '300,600' +# +# -Keys LEONIDA_KEYS: :,... pressed after start, to get from the menus into play +# -ShotAt frames to shoot, counted from the first frame of 500 draws or more (the world) +# -Seconds the most the run may take before the game is closed + +param( + [string]$Keys = '', + [string]$ShotAt = '300,600', + [int]$Seconds = 600, + [string]$ShotDir = (Join-Path $env:LOCALAPPDATA 'leonida\shots') +) + +$ErrorActionPreference = 'Stop' + +Push-Location $PSScriptRoot +try { + cargo build --profile diag -p leonida --features diagnostics + if ($LASTEXITCODE -ne 0) { throw "cargo build failed (exit $LASTEXITCODE); is leonida.exe still running?" } + $exe = Join-Path $PSScriptRoot 'target\diag\leonida.exe' + + $line = & $exe config | Where-Object { $_ -match '^game_dir\s*:' } | Select-Object -First 1 + if ($line -notmatch '^game_dir\s*:\s*(.+?)\s*$' -or $Matches[1] -match '\(not set\)|\(does not exist\)') { + throw 'no game folder saved: run run-gta6.ps1 once and let it remember the folder' + } + + $run = Join-Path $ShotDir (Get-Date -Format 'yyyyMMdd-HHmmss') + New-Item -ItemType Directory -Force $run | Out-Null + $wanted = @($ShotAt -split ',' | Where-Object { $_.Trim() -ne '' }).Count + + $env:LEONIDA_SHOT = $run + $env:LEONIDA_SHOT_AT = $ShotAt + if ($Keys -ne '') { $env:LEONIDA_KEYS = $Keys } + $env:LEONIDA_LOG = 'warn' + $env:LEONIDA_ASYNC_SUBMIT = '1' + $env:LEONIDA_QUEUE2 = '1' + $env:LEONIDA_INDIRECT_WINDOW = '1' + $env:LEONIDA_COPY_PLAIN = '1' + $env:LEONIDA_JOIN_PARTS = '1' + $env:LEONIDA_BACK_OWN_VIEW = '1' + $env:LEONIDA_INDIRECT_GATHER = '1' + $env:LEONIDA_CARD_REHASH_RUNS = '1' + + Write-Host "shots go to $run; the game is closed after $Seconds s or when $wanted shot(s) are written" + $log = Join-Path $run 'run.log' + $game = Start-Process -FilePath $exe -ArgumentList 'run', '--execute' -PassThru -NoNewWindow ` + -RedirectStandardError $log -RedirectStandardOutput (Join-Path $run 'stdout.log') + $began = Get-Date + while (-not $game.HasExited -and ((Get-Date) - $began).TotalSeconds -lt $Seconds) { + $done = @(Get-ChildItem -Path $run -Recurse -Filter 'done' -ErrorAction SilentlyContinue).Count + if ($done -ge $wanted) { break } + Start-Sleep -Seconds 5 + } + if (-not $game.HasExited) { Stop-Process -Id $game.Id -Force } + $done = @(Get-ChildItem -Path $run -Recurse -Filter 'done' -ErrorAction SilentlyContinue).Count + Write-Host "$done of $wanted shot(s) written to $run" +} finally { + Pop-Location +}