Skip to content

"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/

Python

feat: add RenderDoc CLI harness for GPU frame capture analysis

Levi17e9aae519d8
diff --git a/.gitignore b/.gitignore
index 8afe11ee9..fa0f7a3d1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -56,6 +56,7 @@
!/musescore/
!/krita/
!/iterm2/
+!/renderdoc/
# Step 5: Inside each software dir, ignore everything (including dotfiles)
/gimp/*
@@ -100,6 +101,8 @@
/krita/.*
/iterm2/*
/iterm2/.*
+/renderdoc/*
+/renderdoc/.*
# Step 6: ...except agent-harness/
!/gimp/agent-harness/
@@ -124,6 +127,7 @@
!/musescore/agent-harness/
!/krita/agent-harness/
!/iterm2/agent-harness/
+!/renderdoc/agent-harness/
# Step 7: Ignore build artifacts within allowed dirs
**/__pycache__/
diff --git a/README.md b/README.md
index a32dc5396..7302b2bd9 100644
--- a/README.md
+++ b/README.md
@@ -456,6 +456,7 @@ The catalog auto-updates whenever `registry.json` changes โ€” new community CLIs
| **๐Ÿ“ž Communication & Collaboration** | Automate meeting scheduling, participant management, recording retrieval, and reporting through structured CLI | Zoom, Jitsi Meet, BigBlueButton, Mattermost |
| **๐Ÿ“ Diagramming & Visualization** | Create and manipulate diagrams, flowcharts, architecture diagrams, and visual documentation programmatically | Draw.io (diagrams.net), Mermaid, PlantUML, Excalidraw, yEd |
| **๐ŸŒ Network & Infrastructure** | Manage network services, DNS, ad-blocking, and infrastructure through structured CLI commands | AdGuardHome |
+| **๐Ÿ”ฌ Graphics & GPU Debugging** | Analyze GPU frame captures, inspect pipeline state, export shaders, and diff rendering state | RenderDoc |
| **โœจ AI Content Generation** | Generate professional deliverables (slides, docs, diagrams, websites, research reports) through AI-powered cloud APIs | [AnyGen](https://www.anygen.io), Gamma, Beautiful.ai, Tome |
---
@@ -771,8 +772,9 @@ comfyui 70 passed โœ… (60 unit + 10 e2e)
adguardhome 36 passed โœ… (24 unit + 12 e2e)
ollama 98 passed โœ… (87 unit + 11 e2e)
sketch 19 passed โœ… (19 jest, Node.js)
+renderdoc 59 passed โœ… (45 unit + 14 e2e)
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
-TOTAL 1,858 passed โœ… 100% pass rate
+TOTAL 1,917 passed โœ… 100% pass rate
```
---
@@ -840,7 +842,8 @@ cli-anything/
โ”œโ”€โ”€ ๐Ÿง  notebooklm/agent-harness/ # NotebookLM CLI (experimental, 21 tests)
โ”œโ”€โ”€ ๐Ÿ›ก๏ธ adguardhome/agent-harness/ # AdGuard Home CLI (36 tests)
โ”œโ”€โ”€ ๐Ÿฆ™ ollama/agent-harness/ # Ollama CLI (98 tests)
-โ””โ”€โ”€ ๐ŸŽจ sketch/agent-harness/ # Sketch CLI (19 tests, Node.js)
+โ”œโ”€โ”€ ๐ŸŽจ sketch/agent-harness/ # Sketch CLI (19 tests, Node.js)
+โ””โ”€โ”€ ๐Ÿ”ฌ renderdoc/agent-harness/ # RenderDoc CLI (59 tests)
```
Each `agent-harness/` contains an installable Python package under `cli_anything.<software>/` with Click CLI, core modules, utils (including `repl_skin.py` and backend wrapper), and comprehensive tests.
diff --git a/registry.json b/registry.json
index 8b49c4008..00aa78292 100644
--- a/registry.json
+++ b/registry.json
@@ -326,6 +326,20 @@
"category": "devops",
"contributor": "voidfreud",
"contributor_url": "https://github.com/voidfreud"
+ },
+ {
+ "name": "renderdoc",
+ "display_name": "RenderDoc",
+ "version": "0.1.0",
+ "description": "GPU frame capture analysis: pipeline state, shader export, texture inspection, draw call browsing",
+ "requires": "renderdoc (Python bindings from RenderDoc installation)",
+ "homepage": "https://renderdoc.org",
+ "install_cmd": "pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=renderdoc/agent-harness",
+ "entry_point": "cli-anything-renderdoc",
+ "skill_md": "renderdoc/agent-harness/cli_anything/renderdoc/skills/SKILL.md",
+ "category": "graphics",
+ "contributor": "levishilf",
+ "contributor_url": "https://github.com/levishilf"
}
]
}
diff --git a/renderdoc/agent-harness/.gitignore b/renderdoc/agent-harness/.gitignore
new file mode 100644
index 000000000..3eaa0d1e0
--- /dev/null
+++ b/renderdoc/agent-harness/.gitignore
@@ -0,0 +1,5 @@
+# Python
+__pycache__/
+*.pyc
+*.egg-info/
+.pytest_cache/
diff --git a/renderdoc/agent-harness/HARNESS.md b/renderdoc/agent-harness/HARNESS.md
new file mode 100644
index 000000000..b2ebe5fa8
--- /dev/null
+++ b/renderdoc/agent-harness/HARNESS.md
@@ -0,0 +1,82 @@
+# HARNESS.md โ€“ RenderDoc CLI Harness Specification
+
+## Overview
+
+This harness wraps the **RenderDoc** graphics debugger Python API into a Click-based
+CLI tool called `cli-anything-renderdoc`. It enables headless, scriptable analysis
+of GPU frame captures (`.rdc` files) without requiring the RenderDoc GUI.
+
+## Architecture
+
+```
+agent-harness/
+โ”œโ”€โ”€ HARNESS.md # This file
+โ”œโ”€โ”€ RENDERDOC.md # Software-specific SOP
+โ”œโ”€โ”€ setup.py # PEP 420 namespace package
+โ””โ”€โ”€ cli_anything/ # NO __init__.py (namespace package)
+ โ””โ”€โ”€ renderdoc/ # HAS __init__.py
+ โ”œโ”€โ”€ renderdoc_cli.py # Main CLI entry point (Click)
+ โ”œโ”€โ”€ core/
+ โ”‚ โ”œโ”€โ”€ capture.py # Capture file open/close/metadata/convert
+ โ”‚ โ”œโ”€โ”€ actions.py # Draw call / action tree navigation
+ โ”‚ โ”œโ”€โ”€ textures.py # Texture listing, pixel picking, export
+ โ”‚ โ”œโ”€โ”€ pipeline.py # Pipeline state, shader disassembly, cbuffers
+ โ”‚ โ”œโ”€โ”€ resources.py # Buffer/resource enumeration and reading
+ โ”‚ โ”œโ”€โ”€ mesh.py # Vertex input/output decoding
+ โ”‚ โ””โ”€โ”€ counters.py # GPU performance counters
+ โ”œโ”€โ”€ utils/
+ โ”‚ โ”œโ”€โ”€ output.py # JSON/table output formatting
+ โ”‚ โ””โ”€โ”€ errors.py # Error handling
+ โ”œโ”€โ”€ skills/
+ โ”‚ โ””โ”€โ”€ SKILL.md # AI-discoverable skill definition
+ โ””โ”€โ”€ tests/
+ โ”œโ”€โ”€ TEST.md # Test plan and results
+ โ”œโ”€โ”€ test_core.py # Unit tests (mock-based, no renderdoc dep)
+ โ””โ”€โ”€ test_full_e2e.py # E2E tests (requires renderdoc + .rdc files)
+```
+
+## Command Groups
+
+| Group | Commands |
+|-------------|--------------------------------------------------|
+| `capture` | `info`, `thumb`, `convert` |
+| `actions` | `list`, `summary`, `find`, `get` |
+| `textures` | `list`, `get`, `save`, `save-outputs`, `pick` |
+| `pipeline` | `state`, `disasm`, `cbuffer` |
+| `resources` | `list`, `buffers`, `read-buffer` |
+| `mesh` | `inputs`, `outputs` |
+| `counters` | `list`, `fetch` |
+
+## Global Options
+
+- `--capture / -c <path>`: Path to the `.rdc` capture file (or `$RENDERDOC_CAPTURE`)
+- `--json`: Output in JSON format (machine-readable)
+- `--debug`: Show tracebacks on errors
+- `--version`: Show version
+
+## Patterns
+
+1. **Lazy loading**: `renderdoc` module is only imported when a command runs, not at
+ CLI parse time. This allows `--help` to work without renderdoc installed.
+2. **CaptureHandle**: Single context manager that owns the CaptureFile and
+ ReplayController lifecycle.
+3. **Dict-based returns**: Every core function returns plain `dict`/`list` for
+ direct JSON serialisation.
+4. **Dual output**: `_output()` helper picks JSON or human-readable based on `--json`.
+5. **Error dicts**: Errors returned as `{"error": "message"}` rather than exceptions
+ at the boundary layer.
+
+## Testing Strategy
+
+- **Unit tests** (`test_core.py`): Test all core module functions using mocks.
+ No dependency on `renderdoc` module. Uses synthetic data.
+- **E2E tests** (`test_full_e2e.py`): Require a real RenderDoc installation and
+ at least one `.rdc` capture file. Test full CLI invocation via subprocess.
+- **Subprocess tests**: Use `_resolve_cli("cli-anything-renderdoc")` to find the
+ installed CLI binary.
+
+## Dependencies
+
+- **Required**: `click>=8.0`, `python>=3.8`
+- **Optional** (runtime): `renderdoc` Python module (from RenderDoc installation)
+- **Test**: `pytest>=7.0`
diff --git a/renderdoc/agent-harness/RENDERDOC.md b/renderdoc/agent-harness/RENDERDOC.md
new file mode 100644
index 000000000..89f854f03
--- /dev/null
+++ b/renderdoc/agent-harness/RENDERDOC.md
@@ -0,0 +1,81 @@
+# RENDERDOC.md โ€“ Software-Specific SOP
+
+## About RenderDoc
+
+RenderDoc is a free, open-source GPU frame capture and analysis tool for
+Vulkan, D3D11, D3D12, OpenGL, and OpenGL ES. It captures a single frame
+of GPU commands and allows detailed inspection of every draw call, resource,
+shader, and pipeline state.
+
+## Key Concepts
+
+### Capture File (.rdc)
+A binary file containing all GPU state and commands for a single frame.
+Contains embedded sections (textures, shaders, structured data, thumbnails).
+
+### Actions
+GPU operations recorded in the capture. Hierarchical tree structure:
+- **PushMarker / PopMarker**: Debug groups (like `RenderPass: ForwardOpaque`)
+- **Drawcall**: Actual draw calls with triangle/vertex counts
+- **Clear**: Clear render target/depth
+- **Dispatch**: Compute shader dispatch
+- **Copy/Resolve**: Resource copy operations
+- **Present**: Frame present
+
+### Resources
+GPU resources tracked by unique `ResourceId`:
+- **Textures**: 2D, 3D, cube, array textures with mips
+- **Buffers**: Vertex, index, constant, structured buffers
+- **Shaders**: Compiled shader programs
+
+### Pipeline State
+At any event, the complete GPU pipeline is inspectable:
+- Bound shaders (VS, HS, DS, GS, PS, CS)
+- Vertex inputs (attribute layout)
+- Render targets and depth target
+- Viewports and scissors
+- Blend, depth/stencil, rasterizer state
+- Shader resources (textures, buffers, samplers)
+- Constant buffer contents
+
+### Replay
+Captures can be replayed on the local GPU. The ReplayController allows:
+- Setting the current event (seeking to any draw call)
+- Reading back textures, buffers, mesh data
+- Picking pixels
+- Fetching GPU counters
+- Disassembling shaders
+
+## CLI Coverage Map
+
+| RenderDoc Feature | CLI Command | Status |
+|-----------------------------|---------------------------|-----------|
+| Open/close capture | `capture info` | โœ… Done |
+| Capture metadata | `capture info` | โœ… Done |
+| List sections | `capture info` | โœ… Done |
+| Extract thumbnail | `capture thumb` | โœ… Done |
+| Convert capture | `capture convert` | โœ… Done |
+| List all actions | `actions list` | โœ… Done |
+| Action summary | `actions summary` | โœ… Done |
+| Find actions by name | `actions find` | โœ… Done |
+| Get single action | `actions get` | โœ… Done |
+| Filter draw calls only | `actions list --draws-only` | โœ… Done |
+| List textures | `textures list` | โœ… Done |
+| Get texture details | `textures get` | โœ… Done |
+| Save texture to file | `textures save` | โœ… Done |
+| Save render target outputs | `textures save-outputs` | โœ… Done |
+| Pick pixel value | `textures pick` | โœ… Done |
+| Pipeline state | `pipeline state` | โœ… Done |
+| Shader disassembly | `pipeline shader-export` | โœ… Done |
+| Constant buffer contents | `pipeline cbuffer` | โœ… Done |
+| Pipeline diff | `pipeline diff` | โœ… Done |
+| List resources | `resources list` | โœ… Done |
+| List buffers | `resources buffers` | โœ… Done |
+| Read buffer data | `resources read-buffer` | โœ… Done |
+| Vertex inputs | `mesh inputs` | โœ… Done |
+| Post-VS outputs | `mesh outputs` | โœ… Done |
+| GPU counters list | `counters list` | โœ… Done |
+| Fetch counter results | `counters fetch` | โœ… Done |
+| Remote capture | โ€” | โŒ Future |
+| Shader debugging | โ€” | โŒ Future |
+| Resource diff | โ€” | โŒ Future |
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/README.md b/renderdoc/agent-harness/cli_anything/renderdoc/README.md
new file mode 100644
index 000000000..890f3c438
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/README.md
@@ -0,0 +1,103 @@
+# cli-anything-renderdoc
+
+Command-line interface for [RenderDoc](https://renderdoc.org/) graphics debugger.
+
+Provides headless, scriptable analysis of GPU frame captures (`.rdc` files)
+without requiring the RenderDoc GUI.
+
+## Installation
+
+```bash
+cd renderdoc/agent-harness
+pip install -e .
+```
+
+**Prerequisites**: RenderDoc must be installed and its Python module must be
+importable. Add the RenderDoc Python directory to `PYTHONPATH`:
+
+```bash
+# Windows (typical)
+set PYTHONPATH=C:\Program Files\RenderDoc
+# Linux (typical)
+export PYTHONPATH=/opt/renderdoc/lib
+```
+
+## Quick Start
+
+```bash
+# Show capture info
+cli-anything-renderdoc --capture frame.rdc capture info
+
+# List all draw calls
+cli-anything-renderdoc -c frame.rdc actions list --draws-only
+
+# Get action summary
+cli-anything-renderdoc -c frame.rdc actions summary
+
+# Save a texture as PNG
+cli-anything-renderdoc -c frame.rdc textures save <resourceId> -o output.png
+
+# Pick a pixel
+cli-anything-renderdoc -c frame.rdc textures pick <resourceId> 100 200
+
+# Get pipeline state at a draw call
+cli-anything-renderdoc -c frame.rdc pipeline state 42
+
+# Get shader disassembly
+cli-anything-renderdoc -c frame.rdc pipeline shader-export 42 --stage Fragment
+
+# List GPU counters
+cli-anything-renderdoc -c frame.rdc counters list
+
+# Read buffer data
+cli-anything-renderdoc -c frame.rdc resources read-buffer <resourceId> --format float32
+
+# JSON output for all commands
+cli-anything-renderdoc -c frame.rdc --json actions list
+```
+
+## Command Reference
+
+### Global Options
+
+| Option | Description |
+|-------------|--------------------------------------|
+| `--capture` | Path to `.rdc` capture file |
+| `--json` | JSON output mode |
+| `--debug` | Show error tracebacks |
+| `--version` | Show version |
+
+### Commands
+
+| Group | Command | Description |
+|-------------|----------------|--------------------------------------------|
+| `capture` | `info` | Show metadata and sections |
+| `capture` | `thumb` | Extract thumbnail image |
+| `capture` | `convert` | Convert capture format |
+| `actions` | `list` | List all actions / draw calls |
+| `actions` | `summary` | Count actions by type |
+| `actions` | `find` | Search actions by name |
+| `actions` | `get` | Get single action details |
+| `textures` | `list` | List all textures |
+| `textures` | `get` | Get texture details |
+| `textures` | `save` | Export texture to image file |
+| `textures` | `save-outputs` | Save all render targets at an event |
+| `textures` | `pick` | Read pixel value |
+| `pipeline` | `state` | Full pipeline state at event |
+| `pipeline` | `shader-export` | Export shader source / disassembly |
+| `pipeline` | `cbuffer` | Constant buffer contents |
+| `pipeline` | `diff` | Compare pipeline state between events |
+| `resources` | `list` | List all resources |
+| `resources` | `buffers` | List buffer resources |
+| `resources` | `read-buffer` | Read raw buffer data |
+| `mesh` | `inputs` | Vertex shader input data |
+| `mesh` | `outputs` | Post-VS output data |
+| `counters` | `list` | Available GPU counters |
+| `counters` | `fetch` | Fetch counter results |
+
+## Environment Variables
+
+| Variable | Description |
+|-------------------|--------------------------------|
+| `RENDERDOC_CAPTURE` | Default capture file path |
+| `PYTHONPATH` | Must include RenderDoc Python |
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/__init__.py b/renderdoc/agent-harness/cli_anything/renderdoc/__init__.py
new file mode 100644
index 000000000..5fc9c1aed
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/__init__.py
@@ -0,0 +1,13 @@
+"""RenderDoc CLI harness - command-line interface for RenderDoc graphics debugger."""
+
+__version__ = "0.1.0"
+
+# Ensure the native renderdoc.pyd / renderdoc.dll are importable.
+# Try the system-installed renderdoc first; fall back to the bundled native/ copy.
+try:
+ import renderdoc as _rd_probe # noqa: F401
+ del _rd_probe
+except ImportError:
+ from cli_anything.renderdoc._bootstrap import ensure_native_on_path as _ensure
+ _ensure()
+ del _ensure
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/__main__.py b/renderdoc/agent-harness/cli_anything/renderdoc/__main__.py
new file mode 100644
index 000000000..0b9f4d070
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/__main__.py
@@ -0,0 +1,3 @@
+"""Allow running as python -m cli_anything.renderdoc"""
+from cli_anything.renderdoc.renderdoc_cli import main
+main()
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/_bootstrap.py b/renderdoc/agent-harness/cli_anything/renderdoc/_bootstrap.py
new file mode 100644
index 000000000..af00031ea
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/_bootstrap.py
@@ -0,0 +1,20 @@
+"""
+Bootstrap renderdoc native module import.
+
+This module ensures the native renderdoc.pyd (and its dependency renderdoc.dll)
+can be found by Python. It adds the ``native/`` directory to sys.path so that
+``import renderdoc`` resolves to the compiled SWIG bindings built for
+Python 3.10.
+"""
+
+import os
+import sys
+
+_HERE = os.path.dirname(os.path.abspath(__file__))
+_NATIVE_DIR = os.path.join(_HERE, "native")
+
+
+def ensure_native_on_path():
+ """Add the native/ directory to sys.path (idempotent)."""
+ if _NATIVE_DIR not in sys.path:
+ sys.path.insert(0, _NATIVE_DIR)
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/core/__init__.py b/renderdoc/agent-harness/cli_anything/renderdoc/core/__init__.py
new file mode 100644
index 000000000..df75d68a9
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/core/__init__.py
@@ -0,0 +1 @@
+"""Core modules for RenderDoc CLI harness."""
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/core/actions.py b/renderdoc/agent-harness/cli_anything/renderdoc/core/actions.py
new file mode 100644
index 000000000..ab0c9c77b
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/core/actions.py
@@ -0,0 +1,168 @@
+"""
+Action (draw call) inspection: list, search, navigate the action tree.
+
+Works with a CaptureHandle's ReplayController to enumerate draw calls,
+clears, dispatches, and other GPU actions recorded in a frame capture.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List, Optional
+
+try:
+ import renderdoc as rd
+
+ HAS_RD = True
+except ImportError:
+ rd = None # type: ignore[assignment]
+ HAS_RD = False
+
+
+# ---------------------------------------------------------------------------
+# Action helpers
+# ---------------------------------------------------------------------------
+
+def _action_to_dict(action, structured_file=None) -> Dict[str, Any]:
+ """Serialise one ActionDescription to a plain dict."""
+ name = action.customName
+ if not name and structured_file is not None:
+ name = action.GetName(structured_file)
+ flags_list = _decode_flags(action.flags)
+ return {
+ "eventId": action.eventId,
+ "actionId": action.actionId,
+ "name": name or "",
+ "flags": flags_list,
+ "numIndices": action.numIndices,
+ "numInstances": action.numInstances,
+ "indexOffset": action.indexOffset,
+ "baseVertex": action.baseVertex,
+ "vertexOffset": action.vertexOffset,
+ "instanceOffset": action.instanceOffset,
+ "outputs": [str(o) for o in action.outputs],
+ "depthOut": str(action.depthOut),
+ "children_count": len(action.children),
+ }
+
+
+def _decode_flags(flags) -> List[str]:
+ """Decode ActionFlags bitmask into list of human-readable names."""
+ if rd is None:
+ return []
+ names = []
+ flag_map = {
+ rd.ActionFlags.Clear: "Clear",
+ rd.ActionFlags.Drawcall: "Drawcall",
+ rd.ActionFlags.Dispatch: "Dispatch",
+ rd.ActionFlags.CmdList: "CmdList",
+ rd.ActionFlags.SetMarker: "SetMarker",
+ rd.ActionFlags.PushMarker: "PushMarker",
+ rd.ActionFlags.PopMarker: "PopMarker",
+ rd.ActionFlags.Present: "Present",
+ rd.ActionFlags.MultiAction: "MultiAction",
+ rd.ActionFlags.Copy: "Copy",
+ rd.ActionFlags.Resolve: "Resolve",
+ rd.ActionFlags.GenMips: "GenMips",
+ rd.ActionFlags.PassBoundary: "PassBoundary",
+ rd.ActionFlags.Indexed: "Indexed",
+ rd.ActionFlags.Instanced: "Instanced",
+ rd.ActionFlags.Auto: "Auto",
+ rd.ActionFlags.Indirect: "Indirect",
+ rd.ActionFlags.ClearColor: "ClearColor",
+ rd.ActionFlags.ClearDepthStencil: "ClearDepthStencil",
+ rd.ActionFlags.BeginPass: "BeginPass",
+ rd.ActionFlags.EndPass: "EndPass",
+ }
+ for flag_val, flag_name in flag_map.items():
+ if flags & flag_val:
+ names.append(flag_name)
+ return names
+
+
+# ---------------------------------------------------------------------------
+# Flat enumeration
+# ---------------------------------------------------------------------------
+
+def _flatten_actions(actions, out: list, structured_file=None, depth: int = 0):
+ """Recursively flatten action tree."""
+ for a in actions:
+ d = _action_to_dict(a, structured_file)
+ d["depth"] = depth
+ out.append(d)
+ if len(a.children) > 0:
+ _flatten_actions(a.children, out, structured_file, depth + 1)
+
+
+def list_actions(controller, flat: bool = True) -> List[Dict[str, Any]]:
+ """Return all actions in the capture.
+
+ Parameters
+ ----------
+ controller : rd.ReplayController
+ flat : bool
+ If True (default), return a flat list with a ``depth`` key.
+ If False, return only root-level actions.
+ """
+ sf = controller.GetStructuredFile()
+ root_actions = controller.GetRootActions()
+ if flat:
+ result: List[Dict[str, Any]] = []
+ _flatten_actions(root_actions, result, sf)
+ return result
+ return [_action_to_dict(a, sf) for a in root_actions]
+
+
+def find_action_by_event(controller, event_id: int) -> Optional[Dict[str, Any]]:
+ """Find a single action by its eventId."""
+ sf = controller.GetStructuredFile()
+ # Use the flat list and filter
+ all_actions: List[Dict[str, Any]] = []
+ _flatten_actions(controller.GetRootActions(), all_actions, sf)
+ for a in all_actions:
+ if a["eventId"] == event_id:
+ return a
+ return None
+
+
+def find_actions_by_name(controller, pattern: str) -> List[Dict[str, Any]]:
+ """Find actions whose name contains *pattern* (case-insensitive)."""
+ sf = controller.GetStructuredFile()
+ all_actions: List[Dict[str, Any]] = []
+ _flatten_actions(controller.GetRootActions(), all_actions, sf)
+ pat = pattern.lower()
+ return [a for a in all_actions if pat in a["name"].lower()]
+
+
+def get_drawcalls_only(controller) -> List[Dict[str, Any]]:
+ """Return only actual draw calls (not markers, clears, etc.)."""
+ all_actions = list_actions(controller, flat=True)
+ return [a for a in all_actions if "Drawcall" in a["flags"]]
+
+
+def action_summary(controller) -> Dict[str, Any]:
+ """High-level summary: counts of different action types."""
+ all_actions = list_actions(controller, flat=True)
+ summary = {
+ "total_actions": len(all_actions),
+ "drawcalls": 0,
+ "clears": 0,
+ "dispatches": 0,
+ "copies": 0,
+ "markers": 0,
+ "presents": 0,
+ }
+ for a in all_actions:
+ flags = a["flags"]
+ if "Drawcall" in flags:
+ summary["drawcalls"] += 1
+ if "Clear" in flags:
+ summary["clears"] += 1
+ if "Dispatch" in flags:
+ summary["dispatches"] += 1
+ if "Copy" in flags:
+ summary["copies"] += 1
+ if "PushMarker" in flags or "SetMarker" in flags:
+ summary["markers"] += 1
+ if "Present" in flags:
+ summary["presents"] += 1
+ return summary
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/core/capture.py b/renderdoc/agent-harness/cli_anything/renderdoc/core/capture.py
new file mode 100644
index 000000000..b87ac70ac
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/core/capture.py
@@ -0,0 +1,163 @@
+"""
+Capture management: open, inspect metadata, list sections, convert captures.
+
+This module wraps the renderdoc Python API for capture file operations.
+It works in two modes:
+ 1. LIVE mode: when `renderdoc` is importable (RenderDoc installed)
+ 2. MOCK mode: when `renderdoc` is NOT importable (unit-test / offline)
+
+Every public function returns plain Python dicts/lists for JSON serialisation.
+"""
+
+from __future__ import annotations
+
+import os
+import struct
+import json
+from typing import Any, Dict, List, Optional, Tuple
+
+# ---------------------------------------------------------------------------
+# Import renderdoc โ€“ gracefully degrade if unavailable
+# ---------------------------------------------------------------------------
+try:
+ import renderdoc as rd
+
+ HAS_RD = True
+except ImportError:
+ rd = None # type: ignore[assignment]
+ HAS_RD = False
+
+
+def _require_rd():
+ if not HAS_RD:
+ raise RuntimeError(
+ "renderdoc Python module not available. "
+ "Ensure RenderDoc is installed and its Python bindings are on PYTHONPATH."
+ )
+
+
+# ---------------------------------------------------------------------------
+# Capture file handle wrapper
+# ---------------------------------------------------------------------------
+class CaptureHandle:
+ """Wraps an open renderdoc CaptureFile + optional ReplayController."""
+
+ def __init__(self, path: str):
+ _require_rd()
+ self.path = os.path.abspath(path)
+ if not os.path.isfile(self.path):
+ raise FileNotFoundError(f"Capture file not found: {self.path}")
+
+ rd.InitialiseReplay(rd.GlobalEnvironment(), [])
+ self._cap = rd.OpenCaptureFile()
+ result = self._cap.OpenFile(self.path, "", None)
+ if result != rd.ResultCode.Succeeded:
+ raise RuntimeError(f"Failed to open capture: {result}")
+
+ self._controller: Any = None
+
+ # -- lazy replay init ---------------------------------------------------
+ def _ensure_replay(self):
+ if self._controller is not None:
+ return
+ if not self._cap.LocalReplaySupport():
+ raise RuntimeError("Capture cannot be replayed locally")
+ result, ctrl = self._cap.OpenCapture(rd.ReplayOptions(), None)
+ if result != rd.ResultCode.Succeeded:
+ raise RuntimeError(f"Failed to initialise replay: {result}")
+ self._controller = ctrl
+
+ @property
+ def controller(self):
+ self._ensure_replay()
+ return self._controller
+
+ # -- metadata -----------------------------------------------------------
+ def metadata(self) -> Dict[str, Any]:
+ """Return capture-level metadata."""
+ result: Dict[str, Any] = {"path": self.path}
+ try:
+ props = self._cap.APIProperties()
+ result["api"] = str(props.pipelineType)
+ result["driver"] = str(getattr(props, "degraded", props.pipelineType))
+ except AttributeError:
+ # Fallback: get API info from replay controller
+ self._ensure_replay()
+ api_props = self._controller.GetAPIProperties()
+ result["api"] = str(api_props.pipelineType)
+ result["driver"] = str(api_props.pipelineType)
+ try:
+ result["replay_supported"] = self._cap.LocalReplaySupport()
+ except AttributeError:
+ result["replay_supported"] = self._controller is not None
+ return result
+
+ # -- embedded sections --------------------------------------------------
+ def list_sections(self) -> List[Dict[str, Any]]:
+ """List embedded sections in the capture."""
+ count = self._cap.GetSectionCount()
+ sections = []
+ for i in range(count):
+ props = self._cap.GetSectionProperties(i)
+ sections.append({
+ "index": i,
+ "name": props.name,
+ "type": str(props.type),
+ "flags": int(props.flags),
+ "uncompressed_size": props.uncompressedSize,
+ "compressed_size": props.compressedSize,
+ })
+ return sections
+
+ # -- thumbnail ----------------------------------------------------------
+ def thumbnail(self, output_path: str, max_dim: int = 0) -> Dict[str, Any]:
+ """Extract thumbnail from capture to output_path (PNG)."""
+ thumb = self._cap.GetThumbnail(rd.FileType.PNG, max_dim)
+ if thumb.type == rd.FileType.PNG and len(thumb.data) > 0:
+ with open(output_path, "wb") as f:
+ f.write(bytes(thumb.data))
+ return {"path": output_path, "size": len(thumb.data), "format": "PNG"}
+ return {"error": "No thumbnail available"}
+
+ # -- convert capture format ---------------------------------------------
+ def convert(self, output_path: str, export_format: str = "") -> Dict[str, Any]:
+ """Convert / re-save the capture."""
+ result = self._cap.Convert(
+ output_path, export_format, None, None
+ )
+ if result != rd.ResultCode.Succeeded:
+ return {"error": f"Conversion failed: {result}"}
+ return {"path": output_path, "format": export_format or "rdc"}
+
+ # -- cleanup ------------------------------------------------------------
+ def close(self):
+ if self._controller is not None:
+ self._controller.Shutdown()
+ self._controller = None
+ if self._cap is not None:
+ self._cap.Shutdown()
+ self._cap = None
+ rd.ShutdownReplay()
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ self.close()
+
+
+# ---------------------------------------------------------------------------
+# High-level convenience functions (stateless)
+# ---------------------------------------------------------------------------
+
+def open_capture(path: str) -> CaptureHandle:
+ """Open a capture file and return a CaptureHandle."""
+ return CaptureHandle(path)
+
+
+def capture_info(path: str) -> Dict[str, Any]:
+ """Return metadata dict for a capture without starting replay."""
+ with CaptureHandle(path) as cap:
+ meta = cap.metadata()
+ meta["sections"] = cap.list_sections()
+ return meta
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/core/counters.py b/renderdoc/agent-harness/cli_anything/renderdoc/core/counters.py
new file mode 100644
index 000000000..f9c1991c3
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/core/counters.py
@@ -0,0 +1,79 @@
+"""
+GPU performance counters: enumerate, fetch, and describe counters.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List, Optional
+
+try:
+ import renderdoc as rd
+
+ HAS_RD = True
+except ImportError:
+ rd = None # type: ignore[assignment]
+ HAS_RD = False
+
+
+def list_counters(controller) -> List[Dict[str, Any]]:
+ """Enumerate all available GPU counters and their descriptions."""
+ counters = controller.EnumerateCounters()
+ result = []
+ for c in counters:
+ desc = controller.DescribeCounter(c)
+ result.append({
+ "counter": int(c),
+ "name": str(desc.name),
+ "description": str(desc.description),
+ "resultByteWidth": desc.resultByteWidth,
+ "resultType": str(desc.resultType),
+ "unit": str(desc.unit),
+ })
+ return result
+
+
+def fetch_counters(
+ controller,
+ counter_ids: Optional[List[int]] = None,
+) -> Dict[str, Any]:
+ """Fetch counter results for specified counters (or SamplesPassed by default).
+
+ Returns per-event counter values.
+ """
+ available = controller.EnumerateCounters()
+
+ if counter_ids is None:
+ # Default to SamplesPassed if available
+ if rd.GPUCounter.SamplesPassed in available:
+ counter_ids = [int(rd.GPUCounter.SamplesPassed)]
+ else:
+ # Use first available counter
+ if available:
+ counter_ids = [int(available[0])]
+ else:
+ return {"error": "No counters available"}
+
+ # Convert int IDs to rd.GPUCounter
+ rd_counters = [rd.GPUCounter(c) for c in counter_ids]
+
+ results = controller.FetchCounters(rd_counters)
+
+ # Group by counter
+ output: Dict[str, List[Dict[str, Any]]] = {}
+ for r in results:
+ counter_name = str(rd.GPUCounter(r.counter))
+ if counter_name not in output:
+ output[counter_name] = []
+
+ desc = controller.DescribeCounter(r.counter)
+ if desc.resultByteWidth == 4:
+ val = r.value.u32
+ else:
+ val = r.value.u64
+
+ output[counter_name].append({
+ "eventId": r.eventId,
+ "value": val,
+ })
+
+ return {"counters": output, "total_results": len(results)}
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/core/diff.py b/renderdoc/agent-harness/cli_anything/renderdoc/core/diff.py
new file mode 100644
index 000000000..a8af7610e
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/core/diff.py
@@ -0,0 +1,459 @@
+"""
+Pipeline diff -- compare two pipeline snapshots and output only differences.
+
+Usage:
+ from core.diff import diff_pipeline
+ result = diff_pipeline(controller_a, event_a, controller_b, event_b)
+
+The result dict only contains sections that have at least one difference.
+Sections that are completely identical are either omitted or marked "SAME".
+
+The snapshot format matches the output of ``dump_pipeline_for_diff``:
+
+ {
+ "eventId": ...,
+ "PipelineState": {
+ "pipelineType": ...,
+ "vertexInputs": [...],
+ "outputTargets": [...],
+ "depthTarget": {...},
+ "viewport": {...},
+ "rasterizer": {...},
+ "blend": {...},
+ "depthStencil": {...},
+ "stages": {
+ "Vertex": {
+ "shader": "ResourceId::...",
+ "entryPoint": "...",
+ "ShaderReflection": { ... },
+ "bindings": {
+ "constantBlocks": [ { ..., "variables": [...] } ],
+ "readOnlyResources": [...],
+ "readWriteResources": [...],
+ "samplers": [...]
+ }
+ },
+ ...
+ }
+ }
+ }
+"""
+
+from __future__ import annotations
+
+import math
+from typing import Any, Dict, List, Optional
+
+from cli_anything.renderdoc.core.pipeline import dump_pipeline_for_diff
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+_FLOAT_TOL = 1e-6
+
+
+def _floats_equal(a, b) -> bool:
+ """Compare two floats with tolerance; handle NaN/Inf."""
+ if isinstance(a, float) and isinstance(b, float):
+ if math.isnan(a) and math.isnan(b):
+ return True
+ if math.isinf(a) and math.isinf(b):
+ return a == b
+ return abs(a - b) <= _FLOAT_TOL
+ return a == b
+
+
+def _values_equal(a, b) -> bool:
+ """Deep equality check for plain JSON-like values."""
+ if type(a) != type(b):
+ return False
+ if isinstance(a, dict):
+ if set(a.keys()) != set(b.keys()):
+ return False
+ return all(_values_equal(a[k], b[k]) for k in a)
+ if isinstance(a, list):
+ if len(a) != len(b):
+ return False
+ return all(_values_equal(x, y) for x, y in zip(a, b))
+ if isinstance(a, float):
+ return _floats_equal(a, b)
+ return a == b
+
+
+def _diff_dicts(
+ a: Optional[Dict], b: Optional[Dict], label: str = "",
+) -> Optional[Dict[str, Any]]:
+ """Compare two flat/nested dicts, return only differing keys.
+
+ Returns None if both are equal (or both None).
+ """
+ if a is None and b is None:
+ return None
+ if a is None or b is None:
+ return {"A": a, "B": b}
+
+ diffs: Dict[str, Any] = {}
+ all_keys = sorted(set(list(a.keys()) + list(b.keys())))
+ for k in all_keys:
+ va = a.get(k)
+ vb = b.get(k)
+ if not _values_equal(va, vb):
+ diffs[k] = {"A": va, "B": vb}
+
+ return diffs if diffs else None
+
+
+def _diff_lists(
+ a: Optional[List], b: Optional[List], key_field: str = "name",
+) -> Optional[List[Dict[str, Any]]]:
+ """Compare two lists of dicts by a key field, return only diffs.
+
+ Items present in A but not B get status "only_in_A", vice versa.
+ Items present in both get per-field diff.
+ Returns None if identical.
+ """
+ if a is None and b is None:
+ return None
+ a = a or []
+ b = b or []
+
+ a_map = {str(item.get(key_field, i)): item for i, item in enumerate(a)}
+ b_map = {str(item.get(key_field, i)): item for i, item in enumerate(b)}
+ all_keys = sorted(set(list(a_map.keys()) + list(b_map.keys())))
+
+ diffs = []
+ for k in all_keys:
+ va = a_map.get(k)
+ vb = b_map.get(k)
+ if va is None:
+ diffs.append({"key": k, "status": "only_in_B", "B": vb})
+ elif vb is None:
+ diffs.append({"key": k, "status": "only_in_A", "A": va})
+ else:
+ d = _diff_dicts(va, vb)
+ if d:
+ diffs.append({"key": k, "status": "changed", "fields": d})
+
+ return diffs if diffs else None
+
+
+# ---------------------------------------------------------------------------
+# CBuffer variable diff (recursive, handles struct members)
+# ---------------------------------------------------------------------------
+
+def _diff_cbuffer_vars(
+ vars_a: List[Dict], vars_b: List[Dict],
+) -> Optional[List[Dict]]:
+ """Compare two lists of cbuffer variables; return only diffs."""
+ a_map = {v["name"]: v for v in vars_a}
+ b_map = {v["name"]: v for v in vars_b}
+ all_names = sorted(set(list(a_map.keys()) + list(b_map.keys())))
+
+ diffs = []
+ for name in all_names:
+ va = a_map.get(name)
+ vb = b_map.get(name)
+ if va is None:
+ diffs.append({"name": name, "status": "only_in_B", "B": vb})
+ elif vb is None:
+ diffs.append({"name": name, "status": "only_in_A", "A": va})
+ else:
+ if "members" in va or "members" in vb:
+ sub = _diff_cbuffer_vars(
+ va.get("members", []),
+ vb.get("members", []),
+ )
+ if sub:
+ diffs.append({"name": name, "status": "changed", "members": sub})
+ else:
+ vals_a = va.get("values", [])
+ vals_b = vb.get("values", [])
+ if not _values_equal(vals_a, vals_b):
+ diffs.append({
+ "name": name,
+ "status": "changed",
+ "A": vals_a,
+ "B": vals_b,
+ })
+
+ return diffs if diffs else None
+
+
+# ---------------------------------------------------------------------------
+# Stage-level diff (new structure)
+# ---------------------------------------------------------------------------
+
+def _diff_bindings(bindings_a: Dict, bindings_b: Dict) -> Optional[Dict[str, Any]]:
+ """Diff the bindings sub-dict of a stage.
+
+ Handles: constantBlocks (with nested variable values),
+ readOnlyResources, readWriteResources, samplers.
+ """
+ result: Dict[str, Any] = {}
+ has_diff = False
+
+ # --- constantBlocks ---
+ cbs_a = bindings_a.get("constantBlocks", [])
+ cbs_b = bindings_b.get("constantBlocks", [])
+
+ # Build maps keyed by index
+ a_map = {cb.get("index", i): cb for i, cb in enumerate(cbs_a)}
+ b_map = {cb.get("index", i): cb for i, cb in enumerate(cbs_b)}
+ all_indices = sorted(set(list(a_map.keys()) + list(b_map.keys())))
+
+ cb_diffs = []
+ var_diffs_all = []
+ for idx in all_indices:
+ ca = a_map.get(idx)
+ cb_ = b_map.get(idx)
+ if ca is None:
+ cb_diffs.append({"index": idx, "status": "only_in_B", "B": cb_})
+ elif cb_ is None:
+ cb_diffs.append({"index": idx, "status": "only_in_A", "A": ca})
+ else:
+ # Compare binding metadata (resource, byteOffset, byteSize)
+ ca_meta = {k: v for k, v in ca.items() if k not in ("variables",)}
+ cb_meta = {k: v for k, v in cb_.items() if k not in ("variables",)}
+ meta_diff = _diff_dicts(ca_meta, cb_meta)
+ if meta_diff:
+ cb_diffs.append({"index": idx, "status": "changed", "fields": meta_diff})
+
+ # Compare runtime variable values
+ va_vars = ca.get("variables", [])
+ vb_vars = cb_.get("variables", [])
+ vdiff = _diff_cbuffer_vars(va_vars, vb_vars)
+ if vdiff:
+ var_diffs_all.append({"index": idx, "variables": vdiff})
+
+ cb_result: Dict[str, Any] = {}
+ if cb_diffs:
+ cb_result["metadata"] = cb_diffs
+ if var_diffs_all:
+ cb_result["variables"] = var_diffs_all
+
+ if cb_result:
+ result["constantBlocks"] = cb_result
+ has_diff = True
+ else:
+ result["constantBlocks"] = "SAME"
+
+ # --- readOnlyResources, readWriteResources, samplers ---
+ for section in ("readOnlyResources", "readWriteResources", "samplers"):
+ d = _diff_lists(
+ bindings_a.get(section, []),
+ bindings_b.get(section, []),
+ key_field="index",
+ )
+ if d:
+ result[section] = d
+ has_diff = True
+ else:
+ result[section] = "SAME"
+
+ return result if has_diff else None
+
+
+def _diff_stages(stages_a: Dict, stages_b: Dict) -> Optional[Dict[str, Any]]:
+ """Diff the stages sub-dict of PipelineState.
+
+ For each stage present in either snapshot, compare:
+ - shader / entryPoint (as a dict)
+ - ShaderReflection (deep dict diff)
+ - bindings (structured diff with variable values)
+ """
+ all_names = sorted(set(list(stages_a.keys()) + list(stages_b.keys())))
+ result: Dict[str, Any] = {}
+ has_diff = False
+
+ for name in all_names:
+ sa = stages_a.get(name)
+ sb = stages_b.get(name)
+
+ if sa is None:
+ result[name] = {"status": "only_in_B", "B": sb}
+ has_diff = True
+ continue
+ if sb is None:
+ result[name] = {"status": "only_in_A", "A": sa}
+ has_diff = True
+ continue
+
+ stage_result: Dict[str, Any] = {}
+ stage_has_diff = False
+
+ # shader + entryPoint
+ shader_dict_a = {"shader": sa.get("shader"), "entryPoint": sa.get("entryPoint")}
+ shader_dict_b = {"shader": sb.get("shader"), "entryPoint": sb.get("entryPoint")}
+ shader_diff = _diff_dicts(shader_dict_a, shader_dict_b)
+ if shader_diff:
+ stage_result["shader"] = shader_diff
+ stage_has_diff = True
+ else:
+ stage_result["shader"] = "SAME"
+
+ # ShaderReflection
+ refl_diff = _diff_dicts(
+ sa.get("ShaderReflection"),
+ sb.get("ShaderReflection"),
+ )
+ if refl_diff:
+ stage_result["ShaderReflection"] = refl_diff
+ stage_has_diff = True
+ else:
+ stage_result["ShaderReflection"] = "SAME"
+
+ # bindings
+ bindings_diff = _diff_bindings(
+ sa.get("bindings", {}),
+ sb.get("bindings", {}),
+ )
+ if bindings_diff:
+ stage_result["bindings"] = bindings_diff
+ stage_has_diff = True
+ else:
+ stage_result["bindings"] = "SAME"
+
+ if stage_has_diff:
+ result[name] = stage_result
+ has_diff = True
+ else:
+ result[name] = "SAME"
+
+ return result if has_diff else None
+
+
+# ---------------------------------------------------------------------------
+# Core diff from two snapshot dicts
+# ---------------------------------------------------------------------------
+
+def _diff_from_snapshots(snap_a: Dict[str, Any], snap_b: Dict[str, Any]) -> Dict[str, Any]:
+ """Shared implementation: diff two dump_pipeline_for_diff snapshots."""
+ ps_a = snap_a.get("PipelineState", {})
+ ps_b = snap_b.get("PipelineState", {})
+
+ result: Dict[str, Any] = {
+ "eventA": snap_a.get("eventId"),
+ "eventB": snap_b.get("eventId"),
+ }
+
+ has_diff = False
+
+ # pipelineType
+ pt_a = ps_a.get("pipelineType")
+ pt_b = ps_b.get("pipelineType")
+ if pt_a != pt_b:
+ result["pipelineType"] = {"A": pt_a, "B": pt_b}
+ has_diff = True
+ else:
+ result["pipelineType"] = pt_a
+
+ # Simple sections: vertexInputs, outputTargets, depthTarget, viewport,
+ # rasterizer, depthStencil
+ for section, key_field in [
+ ("vertexInputs", "name"),
+ ("outputTargets", "index"),
+ ]:
+ d = _diff_lists(
+ ps_a.get(section, []),
+ ps_b.get(section, []),
+ key_field=key_field,
+ )
+ if d:
+ result[section] = d
+ has_diff = True
+ else:
+ result[section] = "SAME"
+
+ for section in ("depthTarget", "viewport", "rasterizer", "depthStencil"):
+ d = _diff_dicts(ps_a.get(section), ps_b.get(section))
+ if d:
+ result[section] = d
+ has_diff = True
+ else:
+ result[section] = "SAME"
+
+ # blend โ€” nested: top-level dict keys + blends list
+ blend_a = ps_a.get("blend")
+ blend_b = ps_b.get("blend")
+ if blend_a is None and blend_b is None:
+ result["blend"] = "SAME"
+ elif blend_a is None or blend_b is None:
+ result["blend"] = {"A": blend_a, "B": blend_b}
+ has_diff = True
+ else:
+ blend_diff: Dict[str, Any] = {}
+ blend_has_diff = False
+ # Top-level scalar keys
+ for k in sorted(set(list(blend_a.keys()) + list(blend_b.keys()))):
+ if k == "blends":
+ continue
+ va = blend_a.get(k)
+ vb = blend_b.get(k)
+ if not _values_equal(va, vb):
+ blend_diff[k] = {"A": va, "B": vb}
+ blend_has_diff = True
+ # blends list
+ blends_diff = _diff_lists(
+ blend_a.get("blends", []),
+ blend_b.get("blends", []),
+ key_field="index",
+ )
+ if blends_diff:
+ blend_diff["blends"] = blends_diff
+ blend_has_diff = True
+ if blend_has_diff:
+ result["blend"] = blend_diff
+ has_diff = True
+ else:
+ result["blend"] = "SAME"
+
+ # stages
+ stages_diff = _diff_stages(
+ ps_a.get("stages", {}),
+ ps_b.get("stages", {}),
+ )
+ if stages_diff:
+ result["stages"] = stages_diff
+ has_diff = True
+ else:
+ result["stages"] = "SAME"
+
+ result["identical"] = not has_diff
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+def diff_pipeline(
+ controller_a,
+ event_a: int,
+ controller_b,
+ event_b: int,
+) -> Dict[str, Any]:
+ """Compare full pipeline state at two events (possibly from different captures).
+
+ Returns a dict containing only the dimensions that differ.
+ Each section is either omitted (identical) or marked "SAME".
+ """
+ snap_a = dump_pipeline_for_diff(controller_a, event_a)
+ snap_b = dump_pipeline_for_diff(controller_b, event_b)
+ return _diff_from_snapshots(snap_a, snap_b)
+
+
+def diff_pipeline_from_snapshots(
+ snap_a: Dict[str, Any],
+ snap_b: Dict[str, Any],
+) -> Dict[str, Any]:
+ """Compare two pre-built pipeline snapshots (for testing or offline use).
+
+ Expects snapshots in the ``dump_pipeline_for_diff`` format::
+
+ {"eventId": ..., "PipelineState": { ... }}
+
+ Same logic as diff_pipeline but without needing live controllers.
+ """
+ return _diff_from_snapshots(snap_a, snap_b)
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/core/mesh.py b/renderdoc/agent-harness/cli_anything/renderdoc/core/mesh.py
new file mode 100644
index 000000000..7e80c4e5f
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/core/mesh.py
@@ -0,0 +1,172 @@
+"""
+Mesh data decoding: vertex inputs, post-VS outputs, index buffers.
+"""
+
+from __future__ import annotations
+
+import struct as _struct
+from typing import Any, Dict, List, Optional
+
+import click
+
+try:
+ import renderdoc as rd
+
+ HAS_RD = True
+except ImportError:
+ rd = None # type: ignore[assignment]
+ HAS_RD = False
+
+
+def _unpack_data(fmt, data):
+ """Unpack vertex data according to resource format."""
+ if fmt.Special():
+ return None # packed formats not supported
+
+ format_chars = {}
+ format_chars[rd.CompType.UInt] = "xBHxIxxxL"
+ format_chars[rd.CompType.SInt] = "xbhxixxxl"
+ format_chars[rd.CompType.Float] = "xxexfxxxd"
+ format_chars[rd.CompType.UNorm] = format_chars[rd.CompType.UInt]
+ format_chars[rd.CompType.UScaled] = format_chars[rd.CompType.UInt]
+ format_chars[rd.CompType.SNorm] = format_chars[rd.CompType.SInt]
+ format_chars[rd.CompType.SScaled] = format_chars[rd.CompType.SInt]
+
+ vertex_format = str(fmt.compCount) + format_chars[fmt.compType][fmt.compByteWidth]
+ value = _struct.unpack_from(vertex_format, data, 0)
+
+ if fmt.compType == rd.CompType.UNorm:
+ divisor = float((2 ** (fmt.compByteWidth * 8)) - 1)
+ value = tuple(float(i) / divisor for i in value)
+ elif fmt.compType == rd.CompType.SNorm:
+ max_neg = -float(2 ** (fmt.compByteWidth * 8)) / 2
+ divisor = float(-(max_neg - 1))
+ value = tuple(
+ (float(i) if (i == max_neg) else (float(i) / divisor)) for i in value
+ )
+
+ if fmt.BGRAOrder():
+ value = tuple(value[i] for i in [2, 1, 0, 3])
+
+ return value
+
+
+def get_mesh_inputs(controller, event_id: int, max_vertices: int = 100) -> Dict[str, Any]:
+ """Get vertex shader input data at a draw call.
+
+ Returns decoded vertex data for up to *max_vertices* vertices.
+ """
+ controller.SetFrameEvent(event_id, True)
+ state = controller.GetPipelineState()
+
+ ib = state.GetIBuffer()
+ vbs = state.GetVBuffers()
+ attrs = state.GetVertexInputs()
+
+ # get draw info
+ action = None
+ for a in _flatten(controller.GetRootActions()):
+ if a.eventId == event_id:
+ action = a
+ break
+ if action is None:
+ return {"error": f"No action at event {event_id}"}
+
+ # Decode indices
+ indices = _get_indices(controller, ib, action)
+ num = min(len(indices), max_vertices)
+
+ attributes = []
+ for attr in attrs:
+ attr_data = {
+ "name": str(attr.name),
+ "format": str(attr.format),
+ "vertices": [],
+ }
+ if attr.perInstance:
+ attr_data["perInstance"] = True
+ attributes.append(attr_data)
+ continue
+
+ vb = vbs[attr.vertexBuffer]
+ for i in range(num):
+ idx = indices[i]
+ offset = (
+ attr.byteOffset
+ + vb.byteOffset
+ + (idx + action.vertexOffset) * vb.byteStride
+ )
+ data = controller.GetBufferData(vb.resourceId, offset, 64)
+ try:
+ val = _unpack_data(attr.format, bytes(data))
+ attr_data["vertices"].append({"index": idx, "value": list(val) if val else None})
+ except Exception as e:
+ attr_data["vertices"].append({"index": idx, "error": str(e)})
+
+ attributes.append(attr_data)
+
+ return {
+ "eventId": event_id,
+ "numIndices": action.numIndices,
+ "decoded_count": num,
+ "attributes": attributes,
+ }
+
+
+def get_mesh_outputs(controller, event_id: int, max_vertices: int = 100) -> Dict[str, Any]:
+ """Get post-vertex-shader output data at a draw call."""
+ controller.SetFrameEvent(event_id, True)
+
+ postvs = controller.GetPostVSData(0, 0, rd.MeshDataStage.VSOut)
+ if postvs.vertexResourceId == rd.ResourceId.Null():
+ return {"eventId": event_id, "error": "No post-VS data available"}
+
+ vs = controller.GetPipelineState().GetShaderReflection(rd.ShaderStage.Vertex)
+ if vs is None:
+ return {"eventId": event_id, "error": "No vertex shader bound"}
+
+ outputs = []
+ for attr in vs.outputSignature:
+ outputs.append({
+ "name": attr.semanticIdxName if attr.varName == "" else str(attr.varName),
+ "compCount": attr.compCount,
+ "systemValue": str(attr.systemValue),
+ })
+
+ return {
+ "eventId": event_id,
+ "numIndices": postvs.numIndices,
+ "outputs": outputs,
+ }
+
+
+def _flatten(actions, out=None):
+ if out is None:
+ out = []
+ for a in actions:
+ out.append(a)
+ if len(a.children) > 0:
+ _flatten(a.children, out)
+ return out
+
+
+def _get_indices(controller, ib, action):
+ """Decode index buffer."""
+ if action.flags & rd.ActionFlags.Indexed and ib.resourceId != rd.ResourceId.Null():
+ idx_fmt = "B"
+ if ib.byteStride == 2:
+ idx_fmt = "H"
+ elif ib.byteStride == 4:
+ idx_fmt = "I"
+
+ ibdata = controller.GetBufferData(ib.resourceId, ib.byteOffset, 0)
+ offset = action.indexOffset * ib.byteStride
+ fmt_str = str(action.numIndices) + idx_fmt
+ try:
+ indices = _struct.unpack_from(fmt_str, bytes(ibdata), offset)
+ return [i + action.baseVertex for i in indices]
+ except Exception as e:
+ click.echo(f"Warning: failed to unpack indices: {e}", err=True)
+ return list(range(action.numIndices))
+ else:
+ return list(range(action.numIndices))
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/core/pipeline.py b/renderdoc/agent-harness/cli_anything/renderdoc/core/pipeline.py
new file mode 100644
index 000000000..3aecebb2c
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/core/pipeline.py
@@ -0,0 +1,1421 @@
+"""
+Pipeline state inspection.
+
+Inspect the full graphics/compute pipeline state at any event:
+shader stages, bound resources, viewports, blend state, depth/stencil, etc.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from typing import Any, Dict, List, Optional
+
+import click
+
+try:
+ import renderdoc as rd
+
+ HAS_RD = hasattr(rd, "ShaderStage")
+except ImportError:
+ rd = None # type: ignore[assignment]
+ HAS_RD = False
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _write_json(path: str, data: Any) -> None:
+ """Write data as pretty-printed JSON."""
+ with open(path, "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False, default=str)
+
+
+# ---------------------------------------------------------------------------
+# Pipeline state at a given event
+# ---------------------------------------------------------------------------
+
+def get_pipeline_state(controller, event_id: int) -> Dict[str, Any]:
+ """Return a comprehensive pipeline state dict at the given event."""
+ controller.SetFrameEvent(event_id, True)
+ pipe = controller.GetPipelineState()
+
+ result: Dict[str, Any] = {
+ "eventId": event_id,
+ "pipeline_type": str(controller.GetAPIProperties().pipelineType),
+ }
+
+ # Shader stages
+ stages = [
+ ("Vertex", rd.ShaderStage.Vertex),
+ ("TessControl", rd.ShaderStage.Tess_Control),
+ ("TessEval", rd.ShaderStage.Tess_Eval),
+ ("Geometry", rd.ShaderStage.Geometry),
+ ("Fragment", rd.ShaderStage.Fragment),
+ ("Compute", rd.ShaderStage.Compute),
+ ]
+ shaders = {}
+ for name, stage in stages:
+ refl = pipe.GetShaderReflection(stage)
+ if refl is not None:
+ shaders[name] = {
+ "bound": True,
+ "resourceId": str(refl.resourceId),
+ "entryPoint": str(refl.entryPoint),
+ "debugInfo": str(refl.debugInfo.debuggable) if refl.debugInfo else "N/A",
+ "numInputs": len(refl.inputSignature),
+ "numOutputs": len(refl.outputSignature),
+ "numCBuffers": len(refl.constantBlocks),
+ "numReadOnly": len(refl.readOnlyResources),
+ "numReadWrite": len(refl.readWriteResources),
+ }
+ else:
+ shaders[name] = {"bound": False}
+ result["shaders"] = shaders
+
+ # Vertex inputs
+ try:
+ vinputs = pipe.GetVertexInputs()
+ result["vertexInputs"] = [
+ {
+ "name": str(v.name),
+ "vertexBuffer": v.vertexBuffer,
+ "byteOffset": v.byteOffset,
+ "perInstance": v.perInstance,
+ "instanceRate": v.instanceRate,
+ "format": str(v.format),
+ }
+ for v in vinputs
+ ]
+ except Exception as e:
+ click.echo(f"Warning: failed to get vertexInputs: {e}", err=True)
+ result["vertexInputs"] = []
+
+ # Render targets
+ try:
+ targets = pipe.GetOutputTargets()
+ result["renderTargets"] = [
+ {"resourceId": str(t.resourceId), "index": i}
+ for i, t in enumerate(targets)
+ if t.resourceId != rd.ResourceId.Null()
+ ]
+ except Exception as e:
+ click.echo(f"Warning: failed to get renderTargets: {e}", err=True)
+ result["renderTargets"] = []
+
+ # Depth target
+ try:
+ depth = pipe.GetDepthTarget()
+ if depth.resourceId != rd.ResourceId.Null():
+ result["depthTarget"] = {"resourceId": str(depth.resourceId)}
+ else:
+ result["depthTarget"] = None
+ except Exception as e:
+ click.echo(f"Warning: failed to get depthTarget: {e}", err=True)
+ result["depthTarget"] = None
+
+ # Viewports
+ try:
+ vp = pipe.GetViewport(0)
+ result["viewport"] = {
+ "x": vp.x,
+ "y": vp.y,
+ "width": vp.width,
+ "height": vp.height,
+ "minDepth": vp.minDepth,
+ "maxDepth": vp.maxDepth,
+ }
+ except Exception as e:
+ click.echo(f"Warning: failed to get viewport: {e}", err=True)
+ result["viewport"] = None
+
+ # Rasterizer state
+ result["rasterizer"] = get_rasterizer_state(pipe)
+
+ # Blend state
+ result["blend"] = get_blend_state(pipe)
+
+ # Depth-stencil state
+ result["depthStencil"] = get_depth_stencil_state(pipe)
+
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Stage map helper (shared)
+# ---------------------------------------------------------------------------
+
+STAGE_MAP = {
+ "vertex": rd.ShaderStage.Vertex if HAS_RD else None,
+ "tesscontrol": rd.ShaderStage.Tess_Control if HAS_RD else None,
+ "tesseval": rd.ShaderStage.Tess_Eval if HAS_RD else None,
+ "geometry": rd.ShaderStage.Geometry if HAS_RD else None,
+ "fragment": rd.ShaderStage.Fragment if HAS_RD else None,
+ "pixel": rd.ShaderStage.Fragment if HAS_RD else None,
+ "compute": rd.ShaderStage.Compute if HAS_RD else None,
+}
+
+STAGE_PAIRS = [
+ ("Vertex", "vertex"),
+ ("TessControl", "tesscontrol"),
+ ("TessEval", "tesseval"),
+ ("Geometry", "geometry"),
+ ("Fragment", "fragment"),
+ ("Compute", "compute"),
+]
+
+
+def _resolve_stage(stage_name: str):
+ """Resolve a stage name string to rd.ShaderStage enum, or None."""
+ return STAGE_MAP.get(stage_name.lower())
+
+
+# ---------------------------------------------------------------------------
+# Rasterizer / Blend / Depth-Stencil state extraction
+# ---------------------------------------------------------------------------
+
+def get_rasterizer_state(pipe) -> Optional[Dict[str, Any]]:
+ """Extract rasterizer state from a PipeState object."""
+ try:
+ d3d11 = getattr(pipe, "GetD3D11PipelineState", None)
+ d3d12 = getattr(pipe, "GetD3D12PipelineState", None)
+ gl = getattr(pipe, "GetGLPipelineState", None)
+ vk = getattr(pipe, "GetVulkanPipelineState", None)
+
+ if d3d11:
+ ps = d3d11()
+ rs = ps.rasterizer.state
+ return {
+ "fillMode": str(rs.fillMode),
+ "cullMode": str(rs.cullMode),
+ "frontCCW": rs.frontCCW,
+ "depthBias": rs.depthBias,
+ "depthBiasClamp": rs.depthBiasClamp,
+ "slopeScaledDepthBias": rs.slopeScaledDepthBias,
+ "depthClip": rs.depthClip,
+ "scissorEnable": rs.scissorEnable,
+ "multisampleEnable": rs.multisampleEnable,
+ "antialiasedLines": rs.antialiasedLines,
+ }
+ if d3d12:
+ ps = d3d12()
+ rs = ps.rasterizer.state
+ return {
+ "fillMode": str(rs.fillMode),
+ "cullMode": str(rs.cullMode),
+ "frontCCW": rs.frontCCW,
+ "depthBias": rs.depthBias,
+ "depthBiasClamp": rs.depthBiasClamp,
+ "slopeScaledDepthBias": rs.slopeScaledDepthBias,
+ "depthClip": rs.depthClip,
+ "conservativeRasterization": str(rs.conservativeRasterization),
+ }
+ if gl:
+ ps = gl()
+ rs = ps.rasterizer.state
+ return {
+ "fillMode": str(rs.fillMode),
+ "cullMode": str(rs.cullMode),
+ "frontCCW": rs.frontCCW,
+ "depthBias": rs.depthBias,
+ "slopeScaledDepthBias": rs.slopeScaledDepthBias,
+ "offsetClamp": rs.offsetClamp,
+ "depthClamp": rs.depthClamp,
+ }
+ if vk:
+ ps = vk()
+ rs = ps.rasterizer
+ return {
+ "fillMode": str(rs.fillMode),
+ "cullMode": str(rs.cullMode),
+ "frontCCW": rs.frontCCW,
+ "depthBiasEnable": rs.depthBiasEnable,
+ "depthBias": rs.depthBias,
+ "depthBiasClamp": rs.depthBiasClamp,
+ "slopeScaledDepthBias": rs.slopeScaledDepthBias,
+ "depthClampEnable": rs.depthClampEnable,
+ "lineWidth": rs.lineWidth,
+ }
+ except Exception as e:
+ click.echo(f"Warning: {e}", err=True)
+ return None
+
+
+def get_blend_state(pipe) -> Optional[Dict[str, Any]]:
+ """Extract blend state from a PipeState object."""
+ try:
+ d3d11 = getattr(pipe, "GetD3D11PipelineState", None)
+ d3d12 = getattr(pipe, "GetD3D12PipelineState", None)
+ gl = getattr(pipe, "GetGLPipelineState", None)
+ vk = getattr(pipe, "GetVulkanPipelineState", None)
+
+ def _blend_eq(b):
+ return {
+ "enabled": b.enabled,
+ "colorBlendSrc": str(b.colorBlend.source),
+ "colorBlendDst": str(b.colorBlend.destination),
+ "colorBlendOp": str(b.colorBlend.operation),
+ "alphaBlendSrc": str(b.alphaBlend.source),
+ "alphaBlendDst": str(b.alphaBlend.destination),
+ "alphaBlendOp": str(b.alphaBlend.operation),
+ "writeMask": int(b.writeMask),
+ }
+
+ if d3d11:
+ ps = d3d11()
+ om = ps.outputMerger
+ return {
+ "alphaToCoverage": om.blendState.alphaToCoverage,
+ "independentBlend": om.blendState.independentBlend,
+ "blends": [dict(_blend_eq(b), index=i) for i, b in enumerate(om.blendState.blends)],
+ }
+ if d3d12:
+ ps = d3d12()
+ om = ps.outputMerger
+ return {
+ "alphaToCoverage": om.blendState.alphaToCoverage,
+ "independentBlend": om.blendState.independentBlend,
+ "blends": [dict(_blend_eq(b), index=i) for i, b in enumerate(om.blendState.blends)],
+ }
+ if gl:
+ ps = gl()
+ fb = ps.framebuffer
+ return {
+ "blends": [dict(_blend_eq(b), index=i) for i, b in enumerate(fb.blendState.blends)],
+ }
+ if vk:
+ ps = vk()
+ cb = ps.colorBlend
+ return {
+ "alphaToCoverage": cb.alphaToCoverageEnable,
+ "blends": [dict(_blend_eq(b), index=i) for i, b in enumerate(cb.blends)],
+ }
+ except Exception as e:
+ click.echo(f"Warning: {e}", err=True)
+ return None
+
+
+def get_depth_stencil_state(pipe) -> Optional[Dict[str, Any]]:
+ """Extract depth-stencil state from a PipeState object."""
+ try:
+ d3d11 = getattr(pipe, "GetD3D11PipelineState", None)
+ d3d12 = getattr(pipe, "GetD3D12PipelineState", None)
+ gl = getattr(pipe, "GetGLPipelineState", None)
+ vk = getattr(pipe, "GetVulkanPipelineState", None)
+
+ def _stencil_face(s):
+ return {
+ "failOp": str(s.failOperation),
+ "depthFailOp": str(s.depthFailOperation),
+ "passOp": str(s.passOperation),
+ "function": str(s.function),
+ }
+
+ if d3d11:
+ ps = d3d11()
+ ds = ps.outputMerger.depthStencilState
+ return {
+ "depthEnable": ds.depthEnable,
+ "depthFunction": str(ds.depthFunction),
+ "depthWrites": ds.depthWrites,
+ "stencilEnable": ds.stencilEnable,
+ "frontFace": _stencil_face(ds.frontFace),
+ "backFace": _stencil_face(ds.backFace),
+ }
+ if d3d12:
+ ps = d3d12()
+ ds = ps.outputMerger.depthStencilState
+ return {
+ "depthEnable": ds.depthEnable,
+ "depthFunction": str(ds.depthFunction),
+ "depthWrites": ds.depthWrites,
+ "stencilEnable": ds.stencilEnable,
+ "frontFace": _stencil_face(ds.frontFace),
+ "backFace": _stencil_face(ds.backFace),
+ }
+ if gl:
+ ps = gl()
+ ds = ps.depthState
+ st = ps.stencilState
+ return {
+ "depthEnable": ds.depthEnable,
+ "depthFunction": str(ds.depthFunction),
+ "depthWrites": ds.depthWrites,
+ "stencilEnable": st.stencilEnable,
+ "frontFace": _stencil_face(st.frontFace),
+ "backFace": _stencil_face(st.backFace),
+ }
+ if vk:
+ ps = vk()
+ ds = ps.depthStencil
+ return {
+ "depthTestEnable": ds.depthTestEnable,
+ "depthWriteEnable": ds.depthWriteEnable,
+ "depthFunction": str(ds.depthFunction),
+ "depthBoundsEnable": ds.depthBoundsEnable,
+ "stencilTestEnable": ds.stencilTestEnable,
+ "frontFace": _stencil_face(ds.frontFace),
+ "backFace": _stencil_face(ds.backFace),
+ }
+ except Exception as e:
+ click.echo(f"Warning: {e}", err=True)
+ return None
+
+
+def get_shader_disasm(
+ controller,
+ event_id: int,
+ stage_name: str = "Fragment",
+ disasm_target_index: int = 0,
+) -> Dict[str, Any]:
+ """Get only the disassembly text from RenderDoc.
+
+ Returns a lightweight dict with encoding info and the disassembly string,
+ without gathering signatures, cbuffer values, or debug source files.
+ """
+ stage = _resolve_stage(stage_name)
+ if stage is None:
+ return {"error": "Unknown stage: %s" % stage_name}
+
+ controller.SetFrameEvent(event_id, True)
+ pipe = controller.GetPipelineState()
+ refl = pipe.GetShaderReflection(stage)
+ if refl is None:
+ return {"error": "No shader bound at stage %s for event %d" % (stage_name, event_id)}
+
+ pso = pipe.GetGraphicsPipelineObject()
+ enc_str = _get_encoding_str(refl)
+ enc_info = _get_encoding_info(enc_str)
+ raw = bytes(refl.rawBytes) if refl.rawBytes else b""
+
+ result = {
+ "eventId": event_id,
+ "stage": stage_name,
+ "resourceId": str(refl.resourceId),
+ "entryPoint": str(refl.entryPoint),
+ "encoding": enc_info["format"],
+ "encoding_description": enc_info["description"],
+ "is_text": enc_info["is_text"],
+ "disasm_ext": enc_info["disasm_ext"],
+ "rawBytes_size": len(raw),
+ }
+
+ # Disassembly
+ targets = controller.GetDisassemblyTargets(True)
+ result["disasmTargets"] = [str(t) for t in targets]
+ if targets:
+ tidx = min(disasm_target_index, len(targets) - 1)
+ disasm = controller.DisassembleShader(pso, refl, targets[tidx])
+ result["disasmTarget"] = str(targets[tidx])
+ result["disassembly"] = disasm
+ else:
+ result["disassembly"] = None
+
+ # Fallback: for text encodings, if disasm failed use raw source
+ disasm = result.get("disassembly", "")
+ if disasm and ("failed" in disasm.lower()[:100] or "error" in disasm.lower()[:200]):
+ if enc_info["is_text"] and raw:
+ result["disassembly"] = raw.decode("utf-8", errors="replace")
+ result["disasmTarget"] = enc_info["format"] + " (raw source fallback)"
+
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Shader export (human-readable)
+# ---------------------------------------------------------------------------
+
+def export_shader(
+ controller,
+ event_id: int,
+ stage_name: str = "Fragment",
+ output_dir: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Export a shader in human-readable form, plus the raw binary.
+
+ Saves two files into *output_dir*:
+
+ 1. **Raw shader** โ€” the original bytes (e.g. ``.dxbc``, ``.glsl``)
+ 2. **Readable shader** (only if raw is binary) โ€” tried in order:
+ a. Embedded debug source (HLSL/GLSL compiled with ``/Zi``)
+ b. RenderDoc disassembly (bytecode asm)
+
+ For text encodings (GLSL, HLSL, Slang) the raw file *is* the readable
+ file, so only one file is produced.
+
+ Returns a summary dict with ``saved_files``, ``readable_path``,
+ ``readable_kind`` (``"source"`` | ``"disasm"`` | ``None``).
+ """
+ stage = _resolve_stage(stage_name)
+ if stage is None:
+ return {"error": "Unknown stage: %s" % stage_name}
+
+ controller.SetFrameEvent(event_id, True)
+ pipe = controller.GetPipelineState()
+ refl = pipe.GetShaderReflection(stage)
+ if refl is None:
+ return {"error": "No shader bound at stage %s for event %d" % (stage_name, event_id)}
+
+ enc_str = _get_encoding_str(refl)
+ enc_info = _get_encoding_info(enc_str)
+ raw = bytes(refl.rawBytes) if refl.rawBytes else b""
+ if not raw:
+ return {"error": "Shader has no rawBytes data"}
+
+ rid_str = str(refl.resourceId).replace("::", "_")
+ if output_dir is None:
+ output_dir = os.getcwd()
+ os.makedirs(output_dir, exist_ok=True)
+
+ # --- Save raw ---
+ raw_ext = enc_info.get("file_ext", ".bin")
+ raw_name = "shader_%s_%s_eid%d%s" % (rid_str, stage_name, event_id, raw_ext)
+ raw_path = os.path.join(output_dir, raw_name)
+ mode = "w" if enc_info["is_text"] else "wb"
+ with open(raw_path, mode,
+ encoding="utf-8" if enc_info["is_text"] else None) as f:
+ if enc_info["is_text"]:
+ f.write(raw.decode("utf-8", errors="replace"))
+ else:
+ f.write(raw)
+ raw_path = os.path.abspath(raw_path)
+
+ saved_files = [raw_path]
+ readable_path = None
+ readable_kind = None
+
+ if enc_info["is_text"]:
+ # Raw is already human-readable
+ readable_path = raw_path
+ readable_kind = "source"
+ else:
+ # Binary โ€” try embedded debug source first
+ source_text, source_ext = _extract_debug_source(refl, enc_str)
+
+ if source_text:
+ src_name = "shader_%s_%s_eid%d%s" % (
+ rid_str, stage_name, event_id, source_ext)
+ readable_path = os.path.abspath(os.path.join(output_dir, src_name))
+ with open(readable_path, "w", encoding="utf-8") as f:
+ f.write(source_text)
+ readable_kind = "source"
+ saved_files.append(readable_path)
+ else:
+ # Fallback: disassembly
+ disasm_data = get_shader_disasm(controller, event_id, stage_name, 0)
+ disasm_text = disasm_data.get("disassembly") or ""
+ if disasm_text:
+ disasm_ext = enc_info.get("disasm_ext", ".asm")
+ asm_name = "shader_%s_%s_eid%d%s" % (
+ rid_str, stage_name, event_id, disasm_ext)
+ readable_path = os.path.abspath(os.path.join(output_dir, asm_name))
+ with open(readable_path, "w", encoding="utf-8") as f:
+ f.write(disasm_text)
+ readable_kind = "disasm"
+ saved_files.append(readable_path)
+
+ return {
+ "eventId": event_id,
+ "stage": stage_name,
+ "resourceId": str(refl.resourceId),
+ "entryPoint": str(refl.entryPoint),
+ "encoding": enc_info["format"],
+ "encoding_description": enc_info["description"],
+ "is_text": enc_info["is_text"],
+ "size_bytes": len(raw),
+ "raw_path": raw_path,
+ "saved_files": saved_files,
+ "readable_path": readable_path,
+ "readable_kind": readable_kind,
+ }
+
+
+def _extract_debug_source(refl, enc_str: str):
+ """Try to extract embedded debug source from ShaderReflection.
+
+ Returns ``(source_text, extension)`` or ``(None, None)``.
+ """
+ if not refl.debugInfo or not refl.debugInfo.files:
+ return None, None
+
+ for f in refl.debugInfo.files:
+ contents = str(f.contents)
+ if not contents:
+ continue
+
+ # Determine file extension from debug encoding
+ ext = None
+ if hasattr(refl.debugInfo, "encoding"):
+ dbg_enc = str(refl.debugInfo.encoding)
+ if "HLSL" in dbg_enc:
+ ext = ".hlsl"
+ elif "GLSL" in dbg_enc:
+ ext = ".glsl"
+
+ if ext is None:
+ # Guess from filename
+ fname = str(f.filename)
+ if fname.endswith(".hlsl"):
+ ext = ".hlsl"
+ elif fname.endswith(".glsl"):
+ ext = ".glsl"
+
+ if ext is None:
+ # Guess from shader encoding: SPIR-V โ†’ GLSL, DXBC/DXIL โ†’ HLSL
+ if enc_str in ("SPIRV", "OpenGLSPIRV"):
+ ext = ".glsl"
+ else:
+ ext = ".hlsl"
+
+ return contents, ext
+
+ return None, None
+
+
+# ---------------------------------------------------------------------------
+# Constant buffer contents
+# ---------------------------------------------------------------------------
+
+def get_cbuffer_contents(
+ controller,
+ event_id: int,
+ stage_name: str = "Fragment",
+ cbuffer_index: int = 0,
+) -> Dict[str, Any]:
+ """Get constant buffer variable contents at a specific event."""
+ stage = _resolve_stage(stage_name)
+ if stage is None:
+ return {"error": f"Unknown stage: {stage_name}"}
+
+ controller.SetFrameEvent(event_id, True)
+ pipe = controller.GetPipelineState()
+ refl = pipe.GetShaderReflection(stage)
+ if refl is None:
+ return {"error": f"No shader bound at stage {stage_name}"}
+
+ if cbuffer_index >= len(refl.constantBlocks):
+ return {"error": f"CBuffer index {cbuffer_index} out of range (max {len(refl.constantBlocks) - 1})"}
+
+ pso = pipe.GetGraphicsPipelineObject()
+ entry = pipe.GetShaderEntryPoint(stage)
+ cb = pipe.GetConstantBlock(stage, cbuffer_index, 0)
+
+ variables = controller.GetCBufferVariableContents(
+ pso, refl.resourceId, stage, entry,
+ cbuffer_index, cb.descriptor.resource, 0, 0
+ )
+
+ return {
+ "eventId": event_id,
+ "stage": stage_name,
+ "cbuffer_index": cbuffer_index,
+ "variables": [_runtime_var_to_dict(v) for v in variables],
+ }
+
+
+# ---------------------------------------------------------------------------
+# Shader encoding info map
+# ---------------------------------------------------------------------------
+
+_ENCODING_INFO = {
+ "DXBC": {
+ "format": "DXBC",
+ "description": "Direct3D 11 bytecode container (binary)",
+ "is_text": False,
+ "file_ext": ".dxbc",
+ "disasm_ext": ".dxbc.asm",
+ },
+ "DXIL": {
+ "format": "DXIL",
+ "description": "Direct3D 12 DXIL bytecode (binary)",
+ "is_text": False,
+ "file_ext": ".dxil",
+ "disasm_ext": ".dxil.asm",
+ },
+ "GLSL": {
+ "format": "GLSL",
+ "description": "OpenGL/ES GLSL source code (text, already human-readable)",
+ "is_text": True,
+ "file_ext": ".glsl",
+ "disasm_ext": ".glsl",
+ },
+ "SPIRV": {
+ "format": "SPIR-V",
+ "description": "Vulkan SPIR-V binary module (binary)",
+ "is_text": False,
+ "file_ext": ".spv",
+ "disasm_ext": ".spv.asm",
+ },
+ "OpenGLSPIRV": {
+ "format": "OpenGL SPIR-V",
+ "description": "OpenGL variant of SPIR-V binary (binary)",
+ "is_text": False,
+ "file_ext": ".spv",
+ "disasm_ext": ".spv.asm",
+ },
+ "HLSL": {
+ "format": "HLSL",
+ "description": "High Level Shading Language source (text, already human-readable)",
+ "is_text": True,
+ "file_ext": ".hlsl",
+ "disasm_ext": ".hlsl",
+ },
+ "Slang": {
+ "format": "Slang",
+ "description": "Slang shader source (text, already human-readable)",
+ "is_text": True,
+ "file_ext": ".slang",
+ "disasm_ext": ".slang",
+ },
+}
+
+
+def _get_encoding_str(refl) -> str:
+ """Extract encoding name string from ShaderReflection."""
+ enc = str(refl.encoding)
+ if "." in enc:
+ enc = enc.split(".")[-1]
+ return enc
+
+
+def _get_encoding_info(enc_str: str) -> Dict[str, Any]:
+ return _ENCODING_INFO.get(enc_str, {
+ "format": enc_str,
+ "description": "Unknown shader encoding",
+ "is_text": False,
+ "file_ext": ".bin",
+ "disasm_ext": ".asm",
+ })
+
+
+# ---------------------------------------------------------------------------
+# Internal: get raw shader info (used by disasm fallback)
+# ---------------------------------------------------------------------------
+
+# ---------------------------------------------------------------------------
+# Pipeline dump (full PipelineState + ShaderReflection export)
+# ---------------------------------------------------------------------------
+
+def _serialize_sig(sig) -> Dict[str, Any]:
+ """Serialize a SigParameter to dict."""
+ return {
+ "varName": str(sig.varName),
+ "semanticName": str(sig.semanticName),
+ "semanticIndex": sig.semanticIndex,
+ "regIndex": sig.regIndex,
+ "systemValue": str(sig.systemValue),
+ "varType": str(sig.varType),
+ "compCount": sig.compCount,
+ }
+
+
+def _serialize_shader_type(t) -> Dict[str, Any]:
+ """Serialize a ShaderVariableType to dict."""
+ result = {}
+ for attr in ("name", "rows", "columns", "elements", "arrayByteStride",
+ "matrixByteStride", "pointerTypeID", "baseType"):
+ if hasattr(t, attr):
+ val = getattr(t, attr)
+ result[attr] = str(val) if not isinstance(val, (int, float, bool)) else val
+ if hasattr(t, "members") and t.members:
+ result["members"] = [_serialize_cbuffer_var(m) for m in t.members]
+ return result
+
+
+def _serialize_cbuffer_var(v) -> Dict[str, Any]:
+ """Serialize a ShaderConstant (cbuffer variable) to dict."""
+ d = {
+ "name": str(v.name),
+ "byteOffset": v.byteOffset,
+ }
+ if hasattr(v, "type"):
+ d["type"] = _serialize_shader_type(v.type)
+ if hasattr(v, "defaultValue"):
+ d["defaultValue"] = v.defaultValue
+ return d
+
+
+def dump_shader_reflection(refl, include_file_contents: bool = False) -> Dict[str, Any]:
+ """Serialize a ShaderReflection object to a JSON-friendly dict.
+
+ Maps all fields from the RenderDoc Python API ShaderReflection class.
+
+ Parameters
+ ----------
+ include_file_contents : bool
+ If False (default), debugInfo.files[].contents is replaced with
+ ``contents_length`` to avoid multi-MB JSON blobs.
+ If True, the full source text is included (for disk export).
+ """
+ if refl is None:
+ return None
+
+ enc_str = _get_encoding_str(refl)
+ raw = bytes(refl.rawBytes) if refl.rawBytes else b""
+
+ result = {
+ "resourceId": str(refl.resourceId),
+ "entryPoint": str(refl.entryPoint),
+ "encoding": enc_str,
+ "stage": str(refl.stage) if hasattr(refl, "stage") else None,
+ "rawBytes_size": len(raw),
+ }
+
+ # outputTopology / dispatchThreadsDimension
+ if hasattr(refl, "outputTopology"):
+ result["outputTopology"] = str(refl.outputTopology)
+ if hasattr(refl, "dispatchThreadsDimension"):
+ dim = refl.dispatchThreadsDimension
+ result["dispatchThreadsDimension"] = [dim[0], dim[1], dim[2]]
+
+ # constantBlocks
+ cblocks = []
+ for cb in refl.constantBlocks:
+ entry = {
+ "name": str(cb.name),
+ "byteSize": cb.byteSize,
+ }
+ if hasattr(cb, "bindPoint"):
+ entry["bindPoint"] = cb.bindPoint
+ if hasattr(cb, "fixedBindNumber"):
+ entry["fixedBindNumber"] = cb.fixedBindNumber
+ entry["fixedBindSetOrSpace"] = cb.fixedBindSetOrSpace
+ if cb.variables:
+ entry["variables"] = [_serialize_cbuffer_var(v) for v in cb.variables]
+ cblocks.append(entry)
+ result["constantBlocks"] = cblocks
+
+ # readOnlyResources
+ def _serialize_resource(r):
+ d = {"name": str(r.name)}
+ if hasattr(r, "resType"):
+ d["resType"] = str(r.resType)
+ if hasattr(r, "textureType"):
+ d["textureType"] = str(r.textureType)
+ if hasattr(r, "fixedBindSetOrSpace"):
+ d["fixedBindSetOrSpace"] = r.fixedBindSetOrSpace
+ d["fixedBindNumber"] = r.fixedBindNumber
+ if hasattr(r, "isTexture"):
+ d["isTexture"] = r.isTexture
+ if hasattr(r, "isReadOnly"):
+ d["isReadOnly"] = r.isReadOnly
+ return d
+
+ result["readOnlyResources"] = [_serialize_resource(r) for r in refl.readOnlyResources]
+ result["readWriteResources"] = [_serialize_resource(r) for r in refl.readWriteResources]
+
+ # samplers
+ samps = []
+ for s in refl.samplers:
+ d = {"name": str(s.name)}
+ if hasattr(s, "fixedBindSetOrSpace"):
+ d["fixedBindSetOrSpace"] = s.fixedBindSetOrSpace
+ d["fixedBindNumber"] = s.fixedBindNumber
+ samps.append(d)
+ result["samplers"] = samps
+
+ # signatures
+ result["inputSignature"] = [_serialize_sig(s) for s in refl.inputSignature]
+ result["outputSignature"] = [_serialize_sig(s) for s in refl.outputSignature]
+
+ # interfaces
+ if hasattr(refl, "interfaces"):
+ result["interfaces"] = [str(i) for i in refl.interfaces]
+
+ # debugInfo
+ if refl.debugInfo:
+ dbg = refl.debugInfo
+ debug = {
+ "debuggable": dbg.debuggable,
+ }
+ if hasattr(dbg, "compiler"):
+ debug["compiler"] = str(dbg.compiler)
+ if hasattr(dbg, "encoding"):
+ debug["encoding"] = str(dbg.encoding)
+ if hasattr(dbg, "debugStatus"):
+ debug["debugStatus"] = str(dbg.debugStatus)
+ if hasattr(dbg, "entrySourceName"):
+ debug["entrySourceName"] = str(dbg.entrySourceName)
+ try:
+ flags = dbg.compileFlags
+ if flags and hasattr(flags, "flags"):
+ debug["compileFlags"] = [
+ {"name": str(f.name), "value": str(f.value)}
+ for f in flags.flags
+ ]
+ except Exception as e:
+ click.echo(f"Warning: failed to get compileFlags: {e}", err=True)
+ debug["compileFlags"] = None
+ try:
+ if dbg.files:
+ if include_file_contents:
+ debug["files"] = [
+ {
+ "filename": str(f.filename),
+ "contents": str(f.contents),
+ }
+ for f in dbg.files
+ ]
+ else:
+ debug["files"] = [
+ {
+ "filename": str(f.filename),
+ "contents_length": len(str(f.contents)),
+ }
+ for f in dbg.files
+ ]
+ except Exception as e:
+ click.echo(f"Warning: failed to get files: {e}", err=True)
+ debug["files"] = []
+ result["debugInfo"] = debug
+ else:
+ result["debugInfo"] = None
+
+ return result
+
+
+def export_shader_reflection(
+ controller,
+ event_id: int,
+ stage_name: str = "Fragment",
+ output_dir: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Export complete ShaderReflection for a shader stage to a folder.
+
+ Creates:
+ <output_dir>/
+ reflection.json โ€” full ShaderReflection (with debugInfo file contents)
+ bindings.json โ€” runtime GPU bindings (bound resources, cbuffers, samplers)
+ cbuffer_values.json โ€” runtime constant buffer variable values
+ sources/ โ€” individual debug source files (if available)
+ <filename>
+
+ Returns a summary dict with paths and metadata.
+ """
+ stage = _resolve_stage(stage_name)
+ if stage is None:
+ return {"error": "Unknown stage: %s" % stage_name}
+
+ controller.SetFrameEvent(event_id, True)
+ pipe = controller.GetPipelineState()
+ refl = pipe.GetShaderReflection(stage)
+ if refl is None:
+ return {"error": "No shader bound at stage %s for event %d" % (stage_name, event_id)}
+
+ pso = pipe.GetGraphicsPipelineObject()
+ entry = pipe.GetShaderEntryPoint(stage)
+
+ # Build output directory
+ if output_dir is None:
+ rid_str = str(refl.resourceId).replace("::", "_")
+ output_dir = "shader_%s_%s_eid%d_reflection" % (rid_str, stage_name, event_id)
+ os.makedirs(output_dir, exist_ok=True)
+
+ files_written = []
+
+ # 1. reflection.json โ€” full ShaderReflection including source contents
+ refl_data = dump_shader_reflection(refl, include_file_contents=True)
+ refl_path = os.path.join(output_dir, "reflection.json")
+ _write_json(refl_path, refl_data)
+ files_written.append("reflection.json")
+
+ # 2. bindings.json โ€” runtime GPU bindings
+ bindings_data = dump_stage_bindings(controller, pipe, pso, stage, refl)
+ bindings_path = os.path.join(output_dir, "bindings.json")
+ _write_json(bindings_path, bindings_data)
+ files_written.append("bindings.json")
+
+ # 3. cbuffer_values.json โ€” runtime constant buffer variable values
+ cbuffer_values = []
+ for idx in range(len(refl.constantBlocks)):
+ cb_block = refl.constantBlocks[idx]
+ entry_dict: Dict[str, Any] = {
+ "index": idx,
+ "name": str(cb_block.name),
+ }
+ try:
+ cb = pipe.GetConstantBlock(stage, idx, 0)
+ variables = controller.GetCBufferVariableContents(
+ pso, refl.resourceId, stage, entry,
+ idx, cb.descriptor.resource, 0, 0,
+ )
+ entry_dict["variables"] = [_runtime_var_to_dict(v) for v in variables]
+ except Exception as e:
+ entry_dict["variables"] = []
+ entry_dict["error"] = str(e)
+ cbuffer_values.append(entry_dict)
+ cbuf_path = os.path.join(output_dir, "cbuffer_values.json")
+ _write_json(cbuf_path, cbuffer_values)
+ files_written.append("cbuffer_values.json")
+
+ # 4. sources/ โ€” individual debug source files
+ source_files = []
+ if refl.debugInfo and refl.debugInfo.files:
+ sources_dir = os.path.join(output_dir, "sources")
+ os.makedirs(sources_dir, exist_ok=True)
+ for f in refl.debugInfo.files:
+ fname = str(f.filename)
+ contents = str(f.contents)
+ if not contents:
+ continue
+ safe_name = fname.replace("\\", "/").replace("/", "_").replace(":", "_")
+ if not safe_name:
+ safe_name = "unnamed_source"
+ src_path = os.path.join(sources_dir, safe_name)
+ with open(src_path, "w", encoding="utf-8") as fh:
+ fh.write(contents)
+ source_files.append({
+ "original_path": fname,
+ "saved_as": safe_name,
+ "size": len(contents),
+ })
+ files_written.append("sources/%s" % safe_name)
+
+ # 5. raw shader bytes
+ raw = bytes(refl.rawBytes) if refl.rawBytes else b""
+ if raw:
+ enc_str = _get_encoding_str(refl)
+ enc_info = _get_encoding_info(enc_str)
+ raw_ext = enc_info.get("file_ext", ".bin")
+ raw_name = "shader_raw%s" % raw_ext
+ raw_path = os.path.join(output_dir, raw_name)
+ mode = "w" if enc_info["is_text"] else "wb"
+ with open(raw_path, mode,
+ encoding="utf-8" if enc_info["is_text"] else None) as fh:
+ if enc_info["is_text"]:
+ fh.write(raw.decode("utf-8", errors="replace"))
+ else:
+ fh.write(raw)
+ files_written.append(raw_name)
+
+ return {
+ "eventId": event_id,
+ "stage": stage_name,
+ "resourceId": str(refl.resourceId),
+ "entryPoint": str(refl.entryPoint),
+ "encoding": _get_encoding_str(refl),
+ "output_dir": os.path.abspath(output_dir),
+ "files": files_written,
+ "source_files": source_files,
+ "constantBlocks_count": len(refl.constantBlocks),
+ "readOnlyResources_count": len(refl.readOnlyResources),
+ "readWriteResources_count": len(refl.readWriteResources),
+ "samplers_count": len(refl.samplers),
+ }
+
+
+def _serialize_used_descriptor(idx, used) -> Dict[str, Any]:
+ """Serialize a UsedDescriptor to dict."""
+ desc = used.descriptor
+ entry_d = {"index": idx, "resource": str(desc.resource)}
+ if hasattr(desc, "type"):
+ entry_d["type"] = str(desc.type)
+ if hasattr(desc, "textureType"):
+ entry_d["textureType"] = str(desc.textureType)
+ if hasattr(desc, "byteOffset"):
+ entry_d["byteOffset"] = desc.byteOffset
+ if hasattr(desc, "byteSize") and desc.byteSize:
+ entry_d["byteSize"] = desc.byteSize
+ return entry_d
+
+
+def dump_stage_bindings(controller, pipe, pso, stage, refl) -> Dict[str, Any]:
+ """Serialize GPU runtime bindings for a shader stage.
+
+ Returns the actual resources bound at capture time:
+ constant buffers, textures, UAVs, samplers.
+
+ Note: GetConstantBlock(stage, idx, 0) is per-index.
+ GetReadOnlyResources(stage), GetReadWriteResources(stage),
+ GetSamplers(stage) return full lists.
+ """
+ bindings = {}
+
+ # Constant block bindings (per-index API)
+ cb_bindings = []
+ for idx in range(len(refl.constantBlocks)):
+ try:
+ cb = pipe.GetConstantBlock(stage, idx, 0)
+ desc = cb.descriptor
+ cb_bindings.append({
+ "index": idx,
+ "resource": str(desc.resource),
+ "byteOffset": desc.byteOffset,
+ "byteSize": desc.byteSize,
+ })
+ except Exception as e:
+ click.echo(f"Warning: failed to read constant block {idx}: {e}", err=True)
+ cb_bindings.append({
+ "index": idx,
+ "error": "failed to read",
+ })
+ bindings["constantBlocks"] = cb_bindings
+
+ # Read-only resource bindings (list API)
+ try:
+ ro_list = pipe.GetReadOnlyResources(stage)
+ bindings["readOnlyResources"] = [
+ _serialize_used_descriptor(i, used) for i, used in enumerate(ro_list)
+ ]
+ except Exception as e:
+ click.echo(f"Warning: failed to get readOnlyResources: {e}", err=True)
+ bindings["readOnlyResources"] = []
+
+ # Read-write resource bindings (list API)
+ try:
+ rw_list = pipe.GetReadWriteResources(stage)
+ bindings["readWriteResources"] = [
+ _serialize_used_descriptor(i, used) for i, used in enumerate(rw_list)
+ ]
+ except Exception as e:
+ click.echo(f"Warning: failed to get readWriteResources: {e}", err=True)
+ bindings["readWriteResources"] = []
+
+ # Sampler bindings (list API)
+ try:
+ sam_list = pipe.GetSamplers(stage)
+ bindings["samplers"] = [
+ _serialize_used_descriptor(i, used) for i, used in enumerate(sam_list)
+ ]
+ except Exception as e:
+ click.echo(f"Warning: failed to get samplers: {e}", err=True)
+ bindings["samplers"] = []
+
+ return bindings
+
+
+def _runtime_var_to_dict(v) -> Dict[str, Any]:
+ """Serialize a runtime CBuffer variable (ShaderVariable) to dict.
+
+ This is the module-level equivalent of the nested ``_var_to_dict``
+ formerly duplicated as nested ``_var_to_dict`` in several functions.
+ """
+ d: Dict[str, Any] = {"name": v.name, "rows": v.rows, "columns": v.columns}
+ if len(v.members) == 0:
+ vals = []
+ for r in range(v.rows):
+ for c in range(v.columns):
+ vals.append(v.value.f32v[r * v.columns + c])
+ d["values"] = vals
+ else:
+ d["members"] = [_runtime_var_to_dict(m) for m in v.members]
+ return d
+
+
+def dump_pipeline_for_diff(controller, event_id: int) -> Dict[str, Any]:
+ """Build a complete pipeline snapshot suitable for ``diff_pipeline``.
+
+ Calls :func:`dump_pipeline` for the base structure, then enriches every
+ bound stage's ``bindings.constantBlocks[i]`` with a ``variables`` list
+ containing runtime CBuffer values (via ``GetCBufferVariableContents``).
+ """
+ data = dump_pipeline(controller, event_id)
+ ps = data.get("PipelineState", {})
+
+ controller.SetFrameEvent(event_id, True)
+ pipe = controller.GetPipelineState()
+ pso = pipe.GetGraphicsPipelineObject()
+
+ stage_defs = [
+ ("Vertex", rd.ShaderStage.Vertex),
+ ("TessControl", rd.ShaderStage.Tess_Control),
+ ("TessEval", rd.ShaderStage.Tess_Eval),
+ ("Geometry", rd.ShaderStage.Geometry),
+ ("Fragment", rd.ShaderStage.Fragment),
+ ("Compute", rd.ShaderStage.Compute),
+ ]
+
+ for name, stage_enum in stage_defs:
+ stage_data = ps.get("stages", {}).get(name)
+ if stage_data is None:
+ continue
+ refl = pipe.GetShaderReflection(stage_enum)
+ if refl is None:
+ continue
+ entry = pipe.GetShaderEntryPoint(stage_enum)
+ cb_bindings = stage_data.get("bindings", {}).get("constantBlocks", [])
+ for cb_entry in cb_bindings:
+ idx = cb_entry.get("index")
+ if idx is None or "error" in cb_entry:
+ continue
+ try:
+ cb = pipe.GetConstantBlock(stage_enum, idx, 0)
+ variables = controller.GetCBufferVariableContents(
+ pso, refl.resourceId, stage_enum, entry,
+ idx, cb.descriptor.resource, 0, 0,
+ )
+ cb_entry["variables"] = [_runtime_var_to_dict(v) for v in variables]
+ except Exception as e:
+ click.echo(f"Warning: failed to get variables: {e}", err=True)
+ cb_entry["variables"] = []
+
+ return data
+
+
+def dump_pipeline(controller, event_id: int) -> Dict[str, Any]:
+ """Dump the complete pipeline state and shader reflections at an event.
+
+ Produces a JSON-serializable dict with:
+ - PipelineState: vertex inputs, render targets, viewport, rasterizer,
+ blend, depth/stencil
+ - For each bound shader stage: ShaderReflection + runtime bindings
+
+ This is intended for human debugging, not for AI consumption.
+ """
+ controller.SetFrameEvent(event_id, True)
+ pipe = controller.GetPipelineState()
+ pso = pipe.GetGraphicsPipelineObject()
+
+ pipeline_type = str(controller.GetAPIProperties().pipelineType)
+
+ ps = {
+ "pipelineType": pipeline_type,
+ }
+
+ # Vertex inputs
+ try:
+ vinputs = pipe.GetVertexInputs()
+ ps["vertexInputs"] = [
+ {
+ "name": str(v.name),
+ "vertexBuffer": v.vertexBuffer,
+ "byteOffset": v.byteOffset,
+ "perInstance": v.perInstance,
+ "instanceRate": v.instanceRate,
+ "format": v.format.Name() if hasattr(v.format, "Name") else str(v.format),
+ }
+ for v in vinputs
+ ]
+ except Exception as e:
+ click.echo(f"Warning: failed to get vertexInputs: {e}", err=True)
+ ps["vertexInputs"] = []
+
+ # Output targets
+ try:
+ targets = pipe.GetOutputTargets()
+ ps["outputTargets"] = [
+ {"resourceId": str(t.resourceId), "index": i}
+ for i, t in enumerate(targets)
+ if t.resourceId != rd.ResourceId.Null()
+ ]
+ except Exception as e:
+ click.echo(f"Warning: failed to get outputTargets: {e}", err=True)
+ ps["outputTargets"] = []
+
+ # Depth target
+ try:
+ depth = pipe.GetDepthTarget()
+ if depth.resourceId != rd.ResourceId.Null():
+ ps["depthTarget"] = {"resourceId": str(depth.resourceId)}
+ else:
+ ps["depthTarget"] = None
+ except Exception as e:
+ click.echo(f"Warning: failed to get depthTarget: {e}", err=True)
+ ps["depthTarget"] = None
+
+ # Viewport
+ try:
+ vp = pipe.GetViewport(0)
+ ps["viewport"] = {
+ "x": vp.x, "y": vp.y,
+ "width": vp.width, "height": vp.height,
+ "minDepth": vp.minDepth, "maxDepth": vp.maxDepth,
+ }
+ except Exception as e:
+ click.echo(f"Warning: failed to get viewport: {e}", err=True)
+ ps["viewport"] = None
+
+ # State blocks โ€” use new unified PipeState API
+ # Blend state
+ try:
+ color_blends = pipe.GetColorBlends()
+ def _blend_eq(b):
+ return {
+ "enabled": b.enabled,
+ "colorBlendSrc": str(b.colorBlend.source),
+ "colorBlendDst": str(b.colorBlend.destination),
+ "colorBlendOp": str(b.colorBlend.operation),
+ "alphaBlendSrc": str(b.alphaBlend.source),
+ "alphaBlendDst": str(b.alphaBlend.destination),
+ "alphaBlendOp": str(b.alphaBlend.operation),
+ "writeMask": int(b.writeMask),
+ "logicOperationEnabled": b.logicOperationEnabled,
+ "logicOperation": str(b.logicOperation),
+ }
+ ps["blend"] = {
+ "independentBlend": pipe.IsIndependentBlendingEnabled(),
+ "blends": [dict(_blend_eq(b), index=i) for i, b in enumerate(color_blends)],
+ }
+ except Exception as e:
+ click.echo(f"Warning: failed to get blend: {e}", err=True)
+ ps["blend"] = get_blend_state(pipe)
+
+ # Depth-stencil state
+ try:
+ stencil_faces = pipe.GetStencilFaces()
+ def _stencil_face(s):
+ return {
+ "failOp": str(s.failOperation),
+ "depthFailOp": str(s.depthFailOperation),
+ "passOp": str(s.passOperation),
+ "function": str(s.function),
+ "reference": s.reference,
+ "compareMask": s.compareMask,
+ "writeMask": s.writeMask,
+ }
+ ps["depthStencil"] = {
+ "frontFace": _stencil_face(stencil_faces[0]),
+ "backFace": _stencil_face(stencil_faces[1]),
+ }
+ except Exception as e:
+ click.echo(f"Warning: failed to get depthStencil: {e}", err=True)
+ ps["depthStencil"] = get_depth_stencil_state(pipe)
+
+ # Rasterizer state
+ try:
+ ps["rasterizer"] = {
+ "topology": str(pipe.GetPrimitiveTopology()),
+ }
+ sc = pipe.GetScissor(0)
+ ps["rasterizer"]["scissor"] = {
+ "enabled": sc.enabled,
+ "x": sc.x, "y": sc.y,
+ "width": sc.width, "height": sc.height,
+ }
+ except Exception as e:
+ click.echo(f"Warning: failed to get rasterizer: {e}", err=True)
+ ps["rasterizer"] = get_rasterizer_state(pipe)
+
+ # Shader stages
+ stages_dict = {}
+ stage_defs = [
+ ("Vertex", rd.ShaderStage.Vertex),
+ ("TessControl", rd.ShaderStage.Tess_Control),
+ ("TessEval", rd.ShaderStage.Tess_Eval),
+ ("Geometry", rd.ShaderStage.Geometry),
+ ("Fragment", rd.ShaderStage.Fragment),
+ ("Compute", rd.ShaderStage.Compute),
+ ]
+ for name, stage_enum in stage_defs:
+ refl = pipe.GetShaderReflection(stage_enum)
+ if refl is None:
+ continue
+ stage_data = {
+ "shader": str(refl.resourceId),
+ "entryPoint": str(refl.entryPoint),
+ "ShaderReflection": dump_shader_reflection(refl),
+ "bindings": dump_stage_bindings(controller, pipe, pso, stage_enum, refl),
+ }
+ stages_dict[name] = stage_data
+ ps["stages"] = stages_dict
+
+ return {
+ "eventId": event_id,
+ "PipelineState": ps,
+ }
+
+
+def get_shader_raw(
+ controller,
+ event_id: int,
+ stage_name: str = "Fragment",
+) -> Dict[str, Any]:
+ """Get raw shader encoding info. For text shaders includes source."""
+ stage = _resolve_stage(stage_name)
+ if stage is None:
+ return {"error": "Unknown stage: %s" % stage_name}
+
+ controller.SetFrameEvent(event_id, True)
+ pipe = controller.GetPipelineState()
+ refl = pipe.GetShaderReflection(stage)
+ if refl is None:
+ return {"error": "No shader bound at stage %s for event %d" % (stage_name, event_id)}
+
+ enc_str = _get_encoding_str(refl)
+ enc_info = _get_encoding_info(enc_str)
+ raw = bytes(refl.rawBytes) if refl.rawBytes else b""
+
+ result = {
+ "encoding": enc_info["format"],
+ "is_text": enc_info["is_text"],
+ "size_bytes": len(raw),
+ }
+ if enc_info["is_text"] and raw:
+ result["source"] = raw.decode("utf-8", errors="replace")
+
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Save raw shader to file (equivalent to RenderDoc UI "Save" button)
+# ---------------------------------------------------------------------------
+
+def save_shader_raw(
+ controller,
+ event_id: int,
+ stage_name: str = "Fragment",
+ output_path: Optional[str] = None,
+ default_dir: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Save raw shader bytes to file, identical to RenderDoc UI Save.
+
+ Parameters
+ ----------
+ default_dir : str or None
+ Directory for auto-generated filename when output_path is None.
+ If None, uses current working directory.
+ """
+ stage = _resolve_stage(stage_name)
+ if stage is None:
+ return {"error": "Unknown stage: %s" % stage_name}
+
+ controller.SetFrameEvent(event_id, True)
+ pipe = controller.GetPipelineState()
+ refl = pipe.GetShaderReflection(stage)
+ if refl is None:
+ return {"error": "No shader bound at stage %s for event %d" % (stage_name, event_id)}
+
+ enc_str = _get_encoding_str(refl)
+ enc_info = _get_encoding_info(enc_str)
+
+ raw = bytes(refl.rawBytes) if refl.rawBytes else b""
+ if not raw:
+ return {"error": "Shader has no rawBytes data"}
+
+ if output_path is None:
+ rid_str = str(refl.resourceId).replace("::", "_")
+ fname = "shader_%s_%s_eid%d%s" % (
+ rid_str, stage_name, event_id, enc_info["file_ext"])
+ if default_dir:
+ output_path = os.path.join(default_dir, fname)
+ else:
+ output_path = fname
+
+ mode = "w" if enc_info["is_text"] else "wb"
+ with open(output_path, mode,
+ encoding="utf-8" if enc_info["is_text"] else None) as f:
+ if enc_info["is_text"]:
+ f.write(raw.decode("utf-8", errors="replace"))
+ else:
+ f.write(raw)
+
+ # Query available disassembly targets from RenderDoc runtime
+ disasm_targets = []
+ try:
+ targets = controller.GetDisassemblyTargets(True)
+ disasm_targets = [str(t) for t in targets]
+ except Exception as e:
+ click.echo(f"Warning: {e}", err=True)
+
+ return {
+ "eventId": event_id,
+ "stage": stage_name,
+ "resourceId": str(refl.resourceId),
+ "encoding": enc_info["format"],
+ "encoding_description": enc_info["description"],
+ "is_text": enc_info["is_text"],
+ "size_bytes": len(raw),
+ "output_path": os.path.abspath(output_path),
+ "disasm_targets": disasm_targets,
+ }
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/core/resources.py b/renderdoc/agent-harness/cli_anything/renderdoc/core/resources.py
new file mode 100644
index 000000000..b09005768
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/core/resources.py
@@ -0,0 +1,90 @@
+"""
+Resource inspection: list buffers, get buffer data, enumerate all resources.
+"""
+
+from __future__ import annotations
+
+import struct as _struct
+from typing import Any, Dict, List, Optional
+
+try:
+ import renderdoc as rd
+
+ HAS_RD = True
+except ImportError:
+ rd = None # type: ignore[assignment]
+ HAS_RD = False
+
+
+def list_resources(controller) -> List[Dict[str, Any]]:
+ """List all resources in the capture."""
+ resources = controller.GetResources()
+ return [
+ {
+ "resourceId": str(r.resourceId),
+ "name": str(r.name),
+ "type": str(r.type),
+ }
+ for r in resources
+ ]
+
+
+def list_buffers(controller) -> List[Dict[str, Any]]:
+ """List all buffer resources."""
+ buffers = controller.GetBuffers()
+ return [
+ {
+ "resourceId": str(b.resourceId),
+ "length": b.length,
+ "creationFlags": int(b.creationFlags),
+ }
+ for b in buffers
+ ]
+
+
+def get_buffer_data(
+ controller,
+ resource_id_str: str,
+ offset: int = 0,
+ length: int = 0,
+ fmt: str = "hex",
+) -> Dict[str, Any]:
+ """Read raw buffer data.
+
+ Parameters
+ ----------
+ fmt : str
+ 'hex' returns hex string, 'float32' unpacks as floats,
+ 'uint32' unpacks as unsigned ints, 'raw' returns byte list.
+ """
+ buf_id = None
+ for b in controller.GetBuffers():
+ if str(b.resourceId) == resource_id_str:
+ buf_id = b.resourceId
+ break
+ if buf_id is None:
+ return {"error": f"Buffer {resource_id_str} not found"}
+
+ data = controller.GetBufferData(buf_id, offset, length)
+ raw_bytes = bytes(data)
+
+ result: Dict[str, Any] = {
+ "resourceId": resource_id_str,
+ "offset": offset,
+ "length": len(raw_bytes),
+ }
+
+ if fmt == "hex":
+ result["data"] = raw_bytes.hex()
+ elif fmt == "float32":
+ count = len(raw_bytes) // 4
+ result["data"] = list(_struct.unpack(f"<{count}f", raw_bytes[: count * 4]))
+ elif fmt == "uint32":
+ count = len(raw_bytes) // 4
+ result["data"] = list(_struct.unpack(f"<{count}I", raw_bytes[: count * 4]))
+ elif fmt == "raw":
+ result["data"] = list(raw_bytes)
+ else:
+ result["data"] = raw_bytes.hex()
+
+ return result
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/core/textures.py b/renderdoc/agent-harness/cli_anything/renderdoc/core/textures.py
new file mode 100644
index 000000000..923ca9d34
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/core/textures.py
@@ -0,0 +1,222 @@
+"""
+Texture inspection and export.
+
+List all textures in a capture, inspect individual texture metadata,
+pick pixel values, and save textures to disk in various formats.
+"""
+
+from __future__ import annotations
+
+import os
+from typing import Any, Dict, List, Optional
+
+try:
+ import renderdoc as rd
+
+ HAS_RD = True
+except ImportError:
+ rd = None # type: ignore[assignment]
+ HAS_RD = False
+
+
+# ---------------------------------------------------------------------------
+# Texture enumeration
+# ---------------------------------------------------------------------------
+
+def _tex_to_dict(tex) -> Dict[str, Any]:
+ """Serialise TextureDescription to a plain dict."""
+ return {
+ "resourceId": str(tex.resourceId),
+ "name": str(getattr(tex, "name", "")),
+ "width": tex.width,
+ "height": tex.height,
+ "depth": tex.depth,
+ "mips": tex.mips,
+ "arraysize": tex.arraysize,
+ "msQual": tex.msQual,
+ "msSamp": tex.msSamp,
+ "format": str(tex.format),
+ "dimension": tex.dimension,
+ "type": str(tex.type) if hasattr(tex, "type") else str(tex.dimension),
+ "cubemap": getattr(tex, "cubemap", False),
+ "byteSize": getattr(tex, "byteSize", 0),
+ "creationFlags": int(getattr(tex, "creationFlags", 0)),
+ }
+
+
+def list_textures(controller) -> List[Dict[str, Any]]:
+ """Return all textures in the capture."""
+ textures = controller.GetTextures()
+ return [_tex_to_dict(t) for t in textures]
+
+
+def get_texture(controller, resource_id_str: str) -> Optional[Dict[str, Any]]:
+ """Get a single texture by resource ID string."""
+ for tex in controller.GetTextures():
+ if str(tex.resourceId) == resource_id_str:
+ return _tex_to_dict(tex)
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Pixel picking
+# ---------------------------------------------------------------------------
+
+def pick_pixel(
+ controller,
+ resource_id_str: str,
+ x: int,
+ y: int,
+ mip: int = 0,
+ slice_idx: int = 0,
+ sample: int = 0,
+) -> Dict[str, Any]:
+ """Pick a pixel value from a texture.
+
+ Returns dict with float, uint, and int value representations.
+ """
+ # Find the resource ID
+ tex_id = None
+ for tex in controller.GetTextures():
+ if str(tex.resourceId) == resource_id_str:
+ tex_id = tex.resourceId
+ break
+ if tex_id is None:
+ return {"error": f"Texture {resource_id_str} not found"}
+
+ sub = rd.Subresource(mip, slice_idx, sample)
+ pix = controller.PickPixel(tex_id, x, y, sub, rd.CompType.Typeless)
+
+ return {
+ "x": x,
+ "y": y,
+ "resourceId": resource_id_str,
+ "float": list(pix.floatValue),
+ "uint": list(pix.uintValue),
+ "int": list(pix.intValue),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Texture export
+# ---------------------------------------------------------------------------
+
+_FORMAT_MAP = {}
+if HAS_RD and hasattr(rd, "FileType"):
+ _FORMAT_MAP = {
+ "png": rd.FileType.PNG,
+ "jpg": rd.FileType.JPG,
+ "jpeg": rd.FileType.JPG,
+ "bmp": rd.FileType.BMP,
+ "tga": rd.FileType.TGA,
+ "hdr": rd.FileType.HDR,
+ "exr": rd.FileType.EXR,
+ "dds": rd.FileType.DDS,
+ }
+
+
+def save_texture(
+ controller,
+ resource_id_str: str,
+ output_path: str,
+ file_format: str = "png",
+ mip: int = 0,
+ slice_idx: int = 0,
+ alpha: str = "preserve",
+) -> Dict[str, Any]:
+ """Save a texture to disk.
+
+ Parameters
+ ----------
+ controller : ReplayController
+ resource_id_str : str
+ The resource ID as a string.
+ output_path : str
+ Destination file path.
+ file_format : str
+ One of: png, jpg, bmp, tga, hdr, exr, dds
+ mip : int
+ Mip level to save (-1 for all, DDS only).
+ slice_idx : int
+ Array slice to save (-1 for all, DDS only).
+ alpha : str
+ Alpha handling: 'preserve', 'discard', 'blend_checkerboard'
+ """
+ fmt_lower = file_format.lower()
+ if fmt_lower not in _FORMAT_MAP:
+ return {"error": f"Unsupported format: {file_format}. Use: {list(_FORMAT_MAP.keys())}"}
+
+ tex_id = None
+ for tex in controller.GetTextures():
+ if str(tex.resourceId) == resource_id_str:
+ tex_id = tex.resourceId
+ break
+ if tex_id is None:
+ return {"error": f"Texture {resource_id_str} not found"}
+
+ save = rd.TextureSave()
+ save.resourceId = tex_id
+ save.destType = _FORMAT_MAP[fmt_lower]
+ save.mip = mip
+ save.slice.sliceIndex = slice_idx
+
+ alpha_lower = alpha.lower()
+ if alpha_lower == "preserve":
+ save.alpha = rd.AlphaMapping.Preserve
+ elif alpha_lower == "discard":
+ save.alpha = rd.AlphaMapping.Discard
+ elif alpha_lower in ("blend", "blend_checkerboard", "checkerboard"):
+ save.alpha = rd.AlphaMapping.BlendToCheckerboard
+ else:
+ save.alpha = rd.AlphaMapping.Preserve
+
+ output_path = os.path.abspath(output_path)
+ controller.SaveTexture(save, output_path)
+
+ if os.path.isfile(output_path):
+ return {
+ "path": output_path,
+ "format": fmt_lower,
+ "size": os.path.getsize(output_path),
+ }
+ return {"error": "Failed to save texture (file not created)"}
+
+
+def save_action_outputs(
+ controller,
+ event_id: int,
+ output_dir: str,
+ file_format: str = "png",
+) -> List[Dict[str, Any]]:
+ """Save all render target outputs at a specific event.
+
+ Moves the replay to *event_id*, then saves each colour output and
+ the depth output (if any) to *output_dir*.
+ """
+ controller.SetFrameEvent(event_id, True)
+ state = controller.GetPipelineState()
+ targets = state.GetOutputTargets()
+ depth = state.GetDepthTarget()
+
+ results = []
+ os.makedirs(output_dir, exist_ok=True)
+
+ for i, t in enumerate(targets):
+ if t.resourceId == rd.ResourceId.Null():
+ continue
+ rid = str(t.resourceId)
+ fname = f"event{event_id}_rt{i}.{file_format}"
+ path = os.path.join(output_dir, fname)
+ r = save_texture(controller, rid, path, file_format)
+ r["label"] = f"RT{i}"
+ results.append(r)
+
+ if depth.resourceId != rd.ResourceId.Null():
+ rid = str(depth.resourceId)
+ fname = f"event{event_id}_depth.{file_format}"
+ path = os.path.join(output_dir, fname)
+ r = save_texture(controller, rid, path, file_format)
+ r["label"] = "Depth"
+ results.append(r)
+
+ return results
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/native/renderdoc.dll b/renderdoc/agent-harness/cli_anything/renderdoc/native/renderdoc.dll
new file mode 100644
index 000000000..7e6959fed
Binary files /dev/null and b/renderdoc/agent-harness/cli_anything/renderdoc/native/renderdoc.dll differ
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/native/renderdoc.pyd b/renderdoc/agent-harness/cli_anything/renderdoc/native/renderdoc.pyd
new file mode 100644
index 000000000..f461195a2
Binary files /dev/null and b/renderdoc/agent-harness/cli_anything/renderdoc/native/renderdoc.pyd differ
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/renderdoc_cli.py b/renderdoc/agent-harness/cli_anything/renderdoc/renderdoc_cli.py
new file mode 100644
index 000000000..d67af3456
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/renderdoc_cli.py
@@ -0,0 +1,894 @@
+#!/usr/bin/env python3
+"""
+RenderDoc CLI - Command-line interface for RenderDoc graphics debugger.
+
+Provides headless access to RenderDoc capture analysis:
+ - Inspect capture metadata and sections
+ - List and search draw calls / actions
+ - Inspect pipeline state at any event
+ - List, inspect, and export textures
+ - Read buffer and mesh data
+ - Query GPU performance counters
+ - Pick pixel values
+
+Usage:
+ renderdoc-cli [OPTIONS] COMMAND [ARGS]...
+
+All commands support --json for machine-readable output.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import Optional
+
+import click
+
+# ---------------------------------------------------------------------------
+# Lazy import helpers โ€“ we don't want to import renderdoc at CLI parse time
+# ---------------------------------------------------------------------------
+
+_capture_handle = None # type: ignore
+_repl_mode = False
+
+
+def _get_export_dir(ctx: click.Context, subfolder: str = "") -> str:
+ """Return the default export directory for the current capture.
+
+ Layout: <capture_dir>/<stem>_exported/<subfolder>/
+ e.g. tests/pc_exported/shaders/
+ """
+ capture_path = ctx.obj.get("capture_path", "capture")
+ capture_dir = os.path.dirname(os.path.abspath(capture_path))
+ stem = os.path.splitext(os.path.basename(capture_path))[0]
+ export_dir = os.path.join(capture_dir, "%s_exported" % stem)
+ if subfolder:
+ export_dir = os.path.join(export_dir, subfolder)
+ os.makedirs(export_dir, exist_ok=True)
+ return export_dir
+
+
+def _get_handle(ctx: click.Context):
+ """Return the active CaptureHandle, opening it if needed."""
+ global _capture_handle
+ if _capture_handle is not None:
+ return _capture_handle
+ path = ctx.obj.get("capture_path")
+ if not path:
+ click.echo("Error: No capture file specified. Use --capture <path>", err=True)
+ ctx.exit(1)
+ from cli_anything.renderdoc.core.capture import CaptureHandle
+ from cli_anything.renderdoc.utils.errors import handle_error
+
+ try:
+ _capture_handle = CaptureHandle(path)
+ except Exception as e:
+ debug = ctx.obj.get("debug", False)
+ err = handle_error(e, debug=debug)
+ if ctx.obj.get("json_mode"):
+ from cli_anything.renderdoc.utils.output import output_json
+ output_json(err)
+ ctx.exit(1)
+ else:
+ msg = "Failed to open capture: %s" % err["error"]
+ if debug and "traceback" in err:
+ msg += "\n" + err["traceback"]
+ raise click.ClickException(msg)
+ return _capture_handle
+
+
+def _output(ctx: click.Context, data, human_fn=None):
+ """Output data as JSON or human-readable."""
+ if ctx.obj.get("json_mode"):
+ from cli_anything.renderdoc.utils.output import output_json
+
+ output_json(data)
+ elif human_fn:
+ human_fn(data)
+ else:
+ from cli_anything.renderdoc.utils.output import output_json
+
+ output_json(data)
+
+
+# ===========================================================================
+# Root group
+# ===========================================================================
+
+
[email protected](invoke_without_command=True)
+ "--capture", "-c",
+ type=click.Path(exists=False),
+ envvar="RENDERDOC_CAPTURE",
+ help="Path to .rdc capture file.",
+)
[email protected]("--json", "json_mode", is_flag=True, help="Output in JSON format.")
[email protected]("--debug", is_flag=True, help="Show debug tracebacks on errors.")
[email protected]_option(package_name="cli-anything-renderdoc")
+def cli(ctx, capture, json_mode, debug):
+ """RenderDoc CLI โ€“ headless capture analysis tool.
+
+ Run without a subcommand to enter interactive REPL mode.
+ """
+ ctx.ensure_object(dict)
+ ctx.obj["capture_path"] = capture
+ ctx.obj["json_mode"] = json_mode
+ ctx.obj["debug"] = debug
+
+ if ctx.invoked_subcommand is None:
+ ctx.invoke(repl)
+
+
+# ===========================================================================
+# capture commands
+# ===========================================================================
+
+
+def capture_group():
+ """Capture file operations."""
+ pass
+
+
+@capture_group.command("info")
+def capture_info(ctx):
+ """Show capture file metadata and sections."""
+ handle = _get_handle(ctx)
+ meta = handle.metadata()
+ meta["sections"] = handle.list_sections()
+
+ def _human(data):
+ click.echo(f"Capture: {data['path']}")
+ click.echo(f"API: {data['api']}")
+ click.echo(f"Replay: {'yes' if data['replay_supported'] else 'no'}")
+ click.echo(f"\nSections ({len(data['sections'])}):")
+ for s in data["sections"]:
+ click.echo(f" [{s['index']}] {s['name']} ({s['type']}) - {s['uncompressed_size']} bytes")
+
+ _output(ctx, meta, _human)
+
+
+@capture_group.command("thumb")
[email protected]("--output", "-o", required=True, type=click.Path(), help="Output image path.")
[email protected]("--max-dim", default=0, type=int, help="Max thumbnail dimension (0 = original).")
+def capture_thumb(ctx, output, max_dim):
+ """Extract capture thumbnail to an image file."""
+ handle = _get_handle(ctx)
+ result = handle.thumbnail(output, max_dim)
+ _output(ctx, result)
+
+
+@capture_group.command("convert")
[email protected]("--output", "-o", required=True, type=click.Path(), help="Output file path.")
[email protected]("--format", "fmt", default="", help="Target format (default: rdc).")
+def capture_convert(ctx, output, fmt):
+ """Convert capture to a different format."""
+ handle = _get_handle(ctx)
+ result = handle.convert(output, fmt)
+ _output(ctx, result)
+
+
+# ===========================================================================
+# action commands
+# ===========================================================================
+
+
+def actions_group():
+ """Draw call / action inspection."""
+ pass
+
+
+@actions_group.command("list")
[email protected]("--flat/--no-flat", default=True, help="Flat list vs root-only.")
[email protected]("--draws-only", is_flag=True, help="Only show actual draw calls.")
+def actions_list(ctx, flat, draws_only):
+ """List all actions (draw calls, clears, etc.) in the capture."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.actions import list_actions, get_drawcalls_only
+
+ if draws_only:
+ data = get_drawcalls_only(handle.controller)
+ else:
+ data = list_actions(handle.controller, flat=flat)
+
+ def _human(actions):
+ click.echo(f"Total actions: {len(actions)}")
+ for a in actions:
+ indent = " " * a.get("depth", 0)
+ flags = ",".join(a["flags"]) if a["flags"] else ""
+ click.echo(f"{indent}[{a['eventId']:>5}] {a['name']:<50} {flags}")
+
+ _output(ctx, data, _human)
+
+
+@actions_group.command("summary")
+def actions_summary(ctx):
+ """Show action count summary by type."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.actions import action_summary
+
+ data = action_summary(handle.controller)
+
+ def _human(d):
+ click.echo("Action Summary:")
+ for k, v in d.items():
+ click.echo(f" {k}: {v}")
+
+ _output(ctx, data, _human)
+
+
+@actions_group.command("find")
+def actions_find(ctx, pattern):
+ """Find actions by name pattern (case-insensitive)."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.actions import find_actions_by_name
+
+ data = find_actions_by_name(handle.controller, pattern)
+ _output(ctx, data)
+
+
+@actions_group.command("get")
[email protected]("event_id", type=int)
+def actions_get(ctx, event_id):
+ """Get details of a single action by eventId."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.actions import find_action_by_event
+
+ data = find_action_by_event(handle.controller, event_id)
+ if data is None:
+ data = {"error": f"No action found with eventId={event_id}"}
+ _output(ctx, data)
+
+
+# ===========================================================================
+# texture commands
+# ===========================================================================
+
+
[email protected]("textures")
+def textures_group():
+ """Texture inspection and export."""
+ pass
+
+
+@textures_group.command("list")
+def textures_list(ctx):
+ """List all textures in the capture."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.textures import list_textures
+
+ data = list_textures(handle.controller)
+
+ def _human(textures):
+ click.echo(f"Total textures: {len(textures)}")
+ for t in textures:
+ click.echo(
+ f" [{t['resourceId']}] {t['width']}x{t['height']} "
+ f"mips={t['mips']} fmt={t['format']}"
+ )
+
+ _output(ctx, data, _human)
+
+
+@textures_group.command("get")
[email protected]("resource_id")
+def textures_get(ctx, resource_id):
+ """Get details of a single texture by resource ID."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.textures import get_texture
+
+ data = get_texture(handle.controller, resource_id)
+ if data is None:
+ data = {"error": f"Texture {resource_id} not found"}
+ _output(ctx, data)
+
+
+@textures_group.command("save")
[email protected]("resource_id")
[email protected]("--output", "-o", required=True, type=click.Path(), help="Output file path.")
[email protected]("--format", "fmt", default="png", help="Image format: png, jpg, bmp, tga, hdr, exr, dds.")
[email protected]("--mip", default=0, type=int, help="Mip level (-1 for all, DDS only).")
[email protected]("--slice", "slice_idx", default=0, type=int, help="Array slice (-1 for all, DDS only).")
[email protected]("--alpha", default="preserve", help="Alpha: preserve, discard, blend_checkerboard.")
+def textures_save(ctx, resource_id, output, fmt, mip, slice_idx, alpha):
+ """Save a texture to an image file."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.textures import save_texture
+
+ data = save_texture(handle.controller, resource_id, output, fmt, mip, slice_idx, alpha)
+ _output(ctx, data)
+
+
+@textures_group.command("save-outputs")
[email protected]("event_id", type=int)
[email protected]("--output-dir", "-o", required=True, type=click.Path(), help="Output directory.")
[email protected]("--format", "fmt", default="png", help="Image format.")
+def textures_save_outputs(ctx, event_id, output_dir, fmt):
+ """Save all render target outputs at a specific event."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.textures import save_action_outputs
+
+ data = save_action_outputs(handle.controller, event_id, output_dir, fmt)
+ _output(ctx, data)
+
+
+@textures_group.command("pick")
[email protected]("resource_id")
[email protected]("x", type=int)
[email protected]("y", type=int)
[email protected]("--mip", default=0, type=int)
[email protected]("--slice", "slice_idx", default=0, type=int)
+def textures_pick(ctx, resource_id, x, y, mip, slice_idx):
+ """Pick a pixel value from a texture."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.textures import pick_pixel
+
+ data = pick_pixel(handle.controller, resource_id, x, y, mip, slice_idx)
+ _output(ctx, data)
+
+
+# ===========================================================================
+# pipeline commands
+# ===========================================================================
+
+
[email protected]("pipeline")
+def pipeline_group():
+ """Pipeline state inspection."""
+ pass
+
+
+@pipeline_group.command("state")
[email protected]("event_id", type=int)
+def pipeline_state(ctx, event_id):
+ """Show full pipeline state at a specific event."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.pipeline import get_pipeline_state
+
+ data = get_pipeline_state(handle.controller, event_id)
+ _output(ctx, data)
+
+
+@pipeline_group.command("shader-export")
[email protected]("event_id", type=int)
[email protected]("--stage", default="Fragment", help="Shader stage: Vertex, Fragment, Compute, etc.")
[email protected]("-o", "--output", "output_dir", default=None,
+ help="Output directory. Default: <capture>_exported/shaders/")
+def pipeline_shader_export(ctx, event_id, stage, output_dir):
+ """Export shader source in human-readable form.
+
+ For text shaders (GLSL, HLSL, Slang) the raw bytes are already
+ readable โ€” they are saved directly.
+
+ For binary shaders (DXBC, SPIR-V, DXIL) the tool tries, in order:
+
+ \b
+ 1. Embedded debug source (HLSL/GLSL compiled with /Zi)
+ 2. RenderDoc disassembly (bytecode asm)
+
+ The raw binary is always saved alongside for completeness.
+
+ \b
+ Default output: <capture>_exported/shaders/
+ """
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.pipeline import export_shader
+
+ if output_dir is None:
+ output_dir = _get_export_dir(ctx, "shaders")
+
+ data = export_shader(handle.controller, event_id, stage, output_dir=output_dir)
+
+ def _human(d):
+ if "error" in d:
+ click.echo("Error: %s" % d["error"])
+ return
+ click.echo(" Encoding: %s" % d["encoding"])
+ click.echo(" Raw: %s" % d["raw_path"])
+ rp = d.get("readable_path")
+ if rp and rp != d["raw_path"]:
+ label = "Source" if d.get("readable_kind") == "source" else "Disassembly"
+ click.echo(" %s: %s" % (label.ljust(12), rp))
+
+ _output(ctx, data, _human)
+
+
+@pipeline_group.command("dump-shader-reflection", hidden=True)
[email protected]("event_id", type=int)
[email protected]("--stage", default="Fragment", help="Shader stage: Vertex, Fragment, Compute, etc.")
[email protected]("-o", "--output", "output_dir", default=None, help="Output directory path.")
+def pipeline_dump_shader_reflection(ctx, event_id, stage, output_dir):
+ """Export complete ShaderReflection for a shader stage to a folder.
+
+ Creates a directory containing:
+
+ \b
+ reflection.json Full ShaderReflection (signatures, cbuffer layouts,
+ resource declarations, debug info with source)
+ bindings.json Runtime GPU bindings (bound resource IDs, offsets)
+ cbuffer_values.json Runtime constant buffer variable values
+ shader_raw.* Raw shader bytes (e.g. .dxbc, .glsl)
+ sources/ Debug source files (if compiled with debug info)
+
+ \b
+ Default output: <capture>_exported/shaders/<shader>_reflection/
+ """
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.pipeline import export_shader_reflection
+
+ if output_dir is None:
+ # Build default output_dir under the capture's export directory.
+ # We need the resourceId to name the folder, so do a quick probe first.
+ import renderdoc as rd
+ from cli_anything.renderdoc.core.pipeline import STAGE_MAP
+ stage_enum = STAGE_MAP.get(stage.lower())
+ if stage_enum is None:
+ _output(ctx, {"error": "Unknown stage: %s" % stage})
+ return
+ handle.controller.SetFrameEvent(event_id, True)
+ pipe = handle.controller.GetPipelineState()
+ refl = pipe.GetShaderReflection(stage_enum)
+ if refl is None:
+ _output(ctx, {"error": "No shader bound at stage %s for event %d" % (stage, event_id)})
+ return
+ rid_str = str(refl.resourceId).replace("::", "_")
+ shader_dir = _get_export_dir(ctx, "shaders")
+ output_dir = os.path.join(
+ shader_dir,
+ "shader_%s_%s_eid%d_reflection" % (rid_str, stage, event_id),
+ )
+
+ data = export_shader_reflection(
+ handle.controller, event_id, stage,
+ output_dir=output_dir,
+ )
+
+ def _human(d):
+ if "error" in d:
+ click.echo("Error: %s" % d["error"])
+ return
+ click.echo("Exported: %s" % d["output_dir"])
+ click.echo(" Stage: %s" % d["stage"])
+ click.echo(" ResourceId: %s" % d["resourceId"])
+ click.echo(" EntryPoint: %s" % d["entryPoint"])
+ click.echo(" Encoding: %s" % d["encoding"])
+ click.echo("")
+ click.echo(" Files:")
+ for f in d.get("files", []):
+ click.echo(" %s" % f)
+ src_files = d.get("source_files", [])
+ if src_files:
+ click.echo("")
+ click.echo(" Debug sources: %d files" % len(src_files))
+ for sf in src_files:
+ click.echo(" %s (%d bytes)" % (sf["original_path"], sf["size"]))
+ click.echo("")
+ click.echo(" CBuffers: %d, ReadOnly: %d, ReadWrite: %d, Samplers: %d" % (
+ d["constantBlocks_count"],
+ d["readOnlyResources_count"],
+ d["readWriteResources_count"],
+ d["samplers_count"],
+ ))
+
+ _output(ctx, data, _human)
+
+
+@pipeline_group.command("dump", hidden=True)
[email protected]("event_id", type=int)
[email protected]("-o", "--output", "output_path", default=None, help="Output JSON file path.")
+def pipeline_dump(ctx, event_id, output_path):
+ """Dump full PipelineState + ShaderReflection at EVENT_ID to JSON.
+
+ Exports the complete pipeline state, shader reflection metadata for all
+ bound stages, and GPU runtime bindings. Intended for human debugging.
+
+ \b
+ Default output: <capture>_exported/pipeline_eid<EID>_dump.json
+ """
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.pipeline import dump_pipeline
+
+ data = dump_pipeline(handle.controller, event_id)
+
+ if output_path is None:
+ export_dir = _get_export_dir(ctx)
+ output_path = os.path.join(export_dir, "pipeline_eid%d_dump.json" % event_id)
+
+ output_path = os.path.abspath(output_path)
+ with open(output_path, "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False, default=str)
+
+ if ctx.obj.get("json_mode"):
+ _output(ctx, {"path": output_path})
+ else:
+ click.echo(output_path)
+
+
+@pipeline_group.command("cbuffer")
[email protected]("event_id", type=int)
[email protected]("--stage", default="Fragment", help="Shader stage.")
[email protected]("--index", "cbuffer_index", default=0, type=int, help="CBuffer index.")
+def pipeline_cbuffer(ctx, event_id, stage, cbuffer_index):
+ """Get constant buffer contents at a specific event."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.pipeline import get_cbuffer_contents
+
+ data = get_cbuffer_contents(handle.controller, event_id, stage, cbuffer_index)
+ _output(ctx, data)
+
+
+# ===========================================================================
+# resource commands
+# ===========================================================================
+
+
[email protected]("resources")
+def resources_group():
+ """Resource (buffer/texture) listing and data reading."""
+ pass
+
+
+@resources_group.command("list")
+def resources_list(ctx):
+ """List all resources in the capture."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.resources import list_resources
+
+ data = list_resources(handle.controller)
+
+ def _human(resources):
+ click.echo(f"Total resources: {len(resources)}")
+ for r in resources:
+ click.echo(f" [{r['resourceId']}] {r['type']}: {r['name']}")
+
+ _output(ctx, data, _human)
+
+
+@resources_group.command("buffers")
+def resources_buffers(ctx):
+ """List all buffer resources."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.resources import list_buffers
+
+ data = list_buffers(handle.controller)
+ _output(ctx, data)
+
+
+@resources_group.command("read-buffer")
[email protected]("resource_id")
[email protected]("--offset", default=0, type=int, help="Byte offset.")
[email protected]("--length", default=256, type=int, help="Number of bytes to read.")
[email protected]("--format", "fmt", default="hex", help="Output format: hex, float32, uint32, raw.")
+def resources_read_buffer(ctx, resource_id, offset, length, fmt):
+ """Read raw buffer data."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.resources import get_buffer_data
+
+ data = get_buffer_data(handle.controller, resource_id, offset, length, fmt)
+ _output(ctx, data)
+
+
+# ===========================================================================
+# mesh commands
+# ===========================================================================
+
+
+def mesh_group():
+ """Mesh data (vertex inputs/outputs) inspection."""
+ pass
+
+
+@mesh_group.command("inputs")
[email protected]("event_id", type=int)
[email protected]("--max-vertices", default=100, type=int, help="Max vertices to decode.")
+def mesh_inputs(ctx, event_id, max_vertices):
+ """Get vertex shader inputs at a draw call."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.mesh import get_mesh_inputs
+
+ data = get_mesh_inputs(handle.controller, event_id, max_vertices)
+ _output(ctx, data)
+
+
+@mesh_group.command("outputs")
[email protected]("event_id", type=int)
[email protected]("--max-vertices", default=100, type=int, help="Max vertices to decode.")
+def mesh_outputs(ctx, event_id, max_vertices):
+ """Get post-vertex-shader outputs at a draw call."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.mesh import get_mesh_outputs
+
+ data = get_mesh_outputs(handle.controller, event_id, max_vertices)
+ _output(ctx, data)
+
+
+# ===========================================================================
+# counter commands
+# ===========================================================================
+
+
[email protected]("counters")
+def counters_group():
+ """GPU performance counters."""
+ pass
+
+
+@counters_group.command("list")
+def counters_list(ctx):
+ """List all available GPU counters."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.counters import list_counters
+
+ data = list_counters(handle.controller)
+
+ def _human(counters):
+ click.echo(f"Available GPU counters: {len(counters)}")
+ for c in counters:
+ click.echo(f" [{c['counter']}] {c['name']}: {c['description']}")
+
+ _output(ctx, data, _human)
+
+
+@counters_group.command("fetch")
[email protected]("--ids", default=None, help="Comma-separated counter IDs (default: SamplesPassed).")
+def counters_fetch(ctx, ids):
+ """Fetch GPU counter results."""
+ handle = _get_handle(ctx)
+ from cli_anything.renderdoc.core.counters import fetch_counters
+
+ counter_ids = None
+ if ids:
+ counter_ids = [int(i.strip()) for i in ids.split(",")]
+
+ data = fetch_counters(handle.controller, counter_ids)
+ _output(ctx, data)
+
+
+# ===========================================================================
+# pipeline diff (compare two events)
+# ===========================================================================
+
+# Secondary capture handle for diff B-side
+_capture_handle_b = None # type: ignore
+
+
+def _get_handle_b(ctx: click.Context, path: str):
+ """Open a second capture file for the B-side of a diff."""
+ global _capture_handle_b
+ if _capture_handle_b is not None:
+ return _capture_handle_b
+ from cli_anything.renderdoc.core.capture import CaptureHandle
+ from cli_anything.renderdoc.utils.errors import handle_error
+
+ try:
+ _capture_handle_b = CaptureHandle(path)
+ except Exception as e:
+ debug = ctx.obj.get("debug", False)
+ err = handle_error(e, debug=debug)
+ if ctx.obj.get("json_mode"):
+ from cli_anything.renderdoc.utils.output import output_json
+ output_json(err)
+ ctx.exit(1)
+ else:
+ msg = "Failed to open capture-b: %s" % err["error"]
+ if debug and "traceback" in err:
+ msg += "\n" + err["traceback"]
+ raise click.ClickException(msg)
+ return _capture_handle_b
+
+
+@pipeline_group.command("diff")
[email protected]("event_a", type=int)
[email protected]("event_b", type=int)
+ "--capture-b", "-b",
+ type=click.Path(exists=False),
+ default=None,
+ help="Path to second .rdc capture (default: same as --capture).",
+)
+ "--compact/--no-compact",
+ default=True,
+ help="Omit identical sections (default: compact).",
+)
+ "--output", "-o",
+ type=click.Path(),
+ default=None,
+ help="Output JSON path. Default: auto-generated next to capture.",
+)
+def pipeline_diff_cmd(ctx, event_a, event_b, capture_b, compact, output):
+ """Compare pipeline state at EVENT_A vs EVENT_B.
+
+ By default both events come from the same capture (--capture).
+ Use --capture-b / -b to specify a second capture file.
+
+ Results are written to a JSON file; only the path is printed to stdout.
+
+ \b
+ Examples:
+ # Two events in different captures
+ cli-anything-renderdoc -c a.rdc pipeline diff 100 200 -b b.rdc
+ # Two events in the same capture
+ cli-anything-renderdoc -c frame.rdc pipeline diff 100 200
+ # Custom output path
+ cli-anything-renderdoc -c a.rdc pipeline diff 100 200 -b b.rdc -o result.json
+ """
+ handle_a = _get_handle(ctx)
+ if capture_b:
+ handle_b = _get_handle_b(ctx, capture_b)
+ else:
+ handle_b = handle_a
+
+ from cli_anything.renderdoc.core.diff import diff_pipeline
+
+ data = diff_pipeline(
+ handle_a.controller, event_a,
+ handle_b.controller, event_b,
+ )
+
+ if compact:
+ def _prune_same(obj):
+ """Recursively remove 'SAME' markers and empty containers."""
+ if isinstance(obj, dict):
+ pruned = {}
+ for k, v in obj.items():
+ if v == "SAME":
+ continue
+ cleaned = _prune_same(v)
+ if cleaned is not None:
+ pruned[k] = cleaned
+ return pruned if pruned else None
+ if isinstance(obj, list):
+ pruned = [_prune_same(item) for item in obj if item != "SAME"]
+ pruned = [item for item in pruned if item is not None]
+ return pruned if pruned else None
+ return obj
+
+ data = _prune_same(data) or {}
+
+ # Determine output file path
+ if output is None:
+ capture_a_path = ctx.obj.get("capture_path", "capture")
+ base_dir = os.path.dirname(os.path.abspath(capture_a_path))
+ stem_a = os.path.splitext(os.path.basename(capture_a_path))[0]
+ if capture_b:
+ stem_b = os.path.splitext(os.path.basename(capture_b))[0]
+ output = os.path.join(
+ base_dir,
+ "diff_%s_eid%d_vs_%s_eid%d.json" % (stem_a, event_a, stem_b, event_b),
+ )
+ else:
+ output = os.path.join(
+ base_dir,
+ "diff_%s_eid%d_vs_eid%d.json" % (stem_a, event_a, event_b),
+ )
+
+ output = os.path.abspath(output)
+ with open(output, "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False, default=str)
+
+ if ctx.obj.get("json_mode"):
+ _output(ctx, {"path": output})
+ else:
+ click.echo(output)
+# Cleanup hook
+# ===========================================================================
+
+def cleanup(ctx, *args, **kwargs):
+ global _capture_handle, _capture_handle_b
+ if _capture_handle is not None:
+ _capture_handle.close()
+ _capture_handle = None
+ if _capture_handle_b is not None:
+ _capture_handle_b.close()
+ _capture_handle_b = None
+
+
+# ===========================================================================
+# REPL
+# ===========================================================================
+
+
+def repl(ctx):
+ """Start interactive REPL session."""
+ from cli_anything.renderdoc.utils.repl_skin import ReplSkin
+
+ global _repl_mode
+ _repl_mode = True
+
+ skin = ReplSkin("renderdoc", version="0.1.0")
+ skin.print_banner()
+
+ pt_session = skin.create_prompt_session()
+
+ _repl_commands = {
+ "capture": "info|thumb|convert",
+ "actions": "list|summary|find|get",
+ "textures": "list|get|save|save-outputs|pick",
+ "pipeline": "state|shader-export|cbuffer|diff",
+ "resources": "list|buffers|read-buffer",
+ "mesh": "inputs|outputs",
+ "counters": "list|fetch",
+ "help": "Show this help",
+ "quit": "Exit REPL",
+ }
+
+ capture_path = ctx.obj.get("capture_path", "")
+ context = os.path.basename(capture_path) if capture_path else ""
+
+ while True:
+ try:
+ line = skin.get_input(pt_session, project_name=context, modified=False)
+ if not line:
+ continue
+ if line.lower() in ("quit", "exit", "q"):
+ skin.print_goodbye()
+ break
+ if line.lower() == "help":
+ skin.help(_repl_commands)
+ continue
+
+ args = line.split()
+ try:
+ cli.main(args, standalone_mode=False)
+ except SystemExit:
+ pass
+ except click.exceptions.UsageError as e:
+ skin.warning("Usage error: %s" % e)
+ except Exception as e:
+ skin.error("%s" % e)
+
+ except (EOFError, KeyboardInterrupt):
+ skin.print_goodbye()
+ break
+
+ _repl_mode = False
+
+
+# ===========================================================================
+# Entry point
+# ===========================================================================
+
+def main():
+ cli(obj={})
+
+
+if __name__ == "__main__":
+ main()
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/skills/SKILL.md b/renderdoc/agent-harness/cli_anything/renderdoc/skills/SKILL.md
new file mode 100644
index 000000000..8daae5250
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/skills/SKILL.md
@@ -0,0 +1,125 @@
+---
+name: cli-anything-renderdoc
+description: CLI harness for RenderDoc graphics debugger capture analysis
+version: 0.1.0
+command: cli-anything-renderdoc
+install: pip install cli-anything-renderdoc
+requires:
+ - renderdoc (Python bindings from RenderDoc installation)
+ - click>=8.0
+categories:
+ - graphics
+ - debugging
+ - gpu
+ - rendering
+---
+
+# RenderDoc CLI Skill
+
+Headless command-line analysis of RenderDoc GPU frame captures (`.rdc` files).
+
+## Capabilities
+
+- **Capture inspection**: metadata, sections, thumbnails, format conversion
+- **Action tree**: list/search/filter draw calls, clears, dispatches, markers
+- **Texture operations**: list, inspect, export (PNG/JPG/DDS/HDR/EXR), pixel picking
+- **Pipeline state**: full shader/RT/viewport state at any event
+- **Shader analysis**: export shader in human-readable form (HLSL/GLSL/disasm), constant buffer readback
+- **Resource inspection**: buffer/texture enumeration, raw data reading
+- **Mesh data**: vertex shader input/output decoding
+- **GPU counters**: enumerate and fetch hardware performance counters
+
+## Command Groups
+
+### capture
+```bash
+cli-anything-renderdoc -c frame.rdc capture info # Metadata + sections
+cli-anything-renderdoc -c frame.rdc capture thumb -o t.png # Extract thumbnail
+cli-anything-renderdoc -c frame.rdc capture convert -o out.rdc --format rdc
+```
+
+### actions
+```bash
+cli-anything-renderdoc -c frame.rdc actions list # All actions
+cli-anything-renderdoc -c frame.rdc actions list --draws-only # Draw calls only
+cli-anything-renderdoc -c frame.rdc actions summary # Counts by type
+cli-anything-renderdoc -c frame.rdc actions find "Shadow" # Search by name
+cli-anything-renderdoc -c frame.rdc actions get 42 # Single action
+```
+
+### textures
+```bash
+cli-anything-renderdoc -c frame.rdc textures list
+cli-anything-renderdoc -c frame.rdc textures get <id>
+cli-anything-renderdoc -c frame.rdc textures save <id> -o out.png --format png
+cli-anything-renderdoc -c frame.rdc textures save-outputs 42 -o ./renders/
+cli-anything-renderdoc -c frame.rdc textures pick <id> 100 200
+```
+
+### pipeline
+```bash
+cli-anything-renderdoc -c frame.rdc pipeline state 42
+
+# Export shader in human-readable form
+# Text shaders (GLSL/HLSL) โ†’ saved directly
+# Binary shaders (DXBC/SPIR-V) โ†’ embedded source (HLSL/GLSL) or disassembly
+cli-anything-renderdoc -c frame.rdc pipeline shader-export 42 --stage Fragment
+cli-anything-renderdoc -c frame.rdc pipeline shader-export 42 --stage Vertex -o ./shaders/
+
+cli-anything-renderdoc -c frame.rdc pipeline cbuffer 42 --stage Vertex --index 0
+
+# Compare pipeline state between two events
+# Default output: same directory as the capture file ; use -o to override
+cli-anything-renderdoc -c a.rdc pipeline diff 100 200 -b b.rdc
+cli-anything-renderdoc -c frame.rdc pipeline diff 100 200 # same capture
+cli-anything-renderdoc -c a.rdc pipeline diff 100 200 -b b.rdc -o result.json
+cli-anything-renderdoc -c a.rdc pipeline diff 100 200 -b b.rdc --no-compact
+```
+
+### resources
+```bash
+cli-anything-renderdoc -c frame.rdc resources list
+cli-anything-renderdoc -c frame.rdc resources buffers
+cli-anything-renderdoc -c frame.rdc resources read-buffer <id> --format float32
+```
+
+### mesh
+```bash
+cli-anything-renderdoc -c frame.rdc mesh inputs 42 --max-vertices 10
+cli-anything-renderdoc -c frame.rdc mesh outputs 42
+```
+
+### counters
+```bash
+cli-anything-renderdoc -c frame.rdc counters list
+cli-anything-renderdoc -c frame.rdc counters fetch --ids 1,2,3
+```
+
+## JSON Mode
+
+All commands support `--json` for machine-readable output:
+```bash
+cli-anything-renderdoc -c frame.rdc --json actions summary
+```
+
+## Environment Variables
+
+| Variable | Description |
+|----------------------|------------------------------|
+| `RENDERDOC_CAPTURE` | Default capture file path |
+| `PYTHONPATH` | Must include RenderDoc path |
+
+## Agent Usage Notes
+
+- **Use `pipeline shader-export` to extract shaders** โ€” for binary shaders (DXBC/SPIR-V) it auto-exports embedded HLSL/GLSL source or falls back to disassembly; for text shaders (GLSL/HLSL) it saves the raw source directly
+- **Shader formats by capture API**:
+ - D3D11 โ†’ DXBC binary, exported as embedded HLSL source (`.hlsl`) or bytecode asm (`.dxbc.asm`)
+ - OpenGL/GLES โ†’ GLSL source text (`.glsl`), already human-readable
+ - Vulkan โ†’ SPIR-V binary, exported as embedded GLSL source (`.glsl`) or SPIR-V asm (`.spv.asm`)
+- **Use `pipeline diff` to compare two events** โ€” it writes a JSON file and prints only the path; use `-b` for a second capture
+- Always specify `--json` for programmatic consumption
+- Use `actions summary` first to understand capture complexity
+- Use `actions list --draws-only` to focus on actual rendering
+- Pipeline state requires an event ID from the action list
+- Texture save supports: png, jpg, bmp, tga, hdr, exr, dds
+- Buffer data can be decoded as hex, float32, uint32, or raw bytes
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/tests/TEST.md b/renderdoc/agent-harness/cli_anything/renderdoc/tests/TEST.md
new file mode 100644
index 000000000..6e31a5fed
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/tests/TEST.md
@@ -0,0 +1,96 @@
+# TEST.md โ€“ RenderDoc CLI Test Plan & Results
+
+## Test Strategy
+
+### Unit Tests (`test_core.py`)
+Mock-based tests for all core modules. No dependency on the `renderdoc` Python
+module or actual `.rdc` capture files. Tests synthetic data paths.
+
+### E2E Tests (`test_full_e2e.py`)
+Full integration tests requiring:
+1. RenderDoc installed with Python bindings accessible
+2. A `.rdc` capture file (set via `RENDERDOC_TEST_CAPTURE` env var)
+
+Skips gracefully if either prerequisite is missing.
+
+## Running Tests
+
+```bash
+# Unit tests (always runnable)
+cd renderdoc/agent-harness
+pytest cli_anything/renderdoc/tests/test_core.py -v
+
+# E2E tests (requires RenderDoc + capture file)
+RENDERDOC_TEST_CAPTURE=/path/to/capture.rdc pytest cli_anything/renderdoc/tests/test_full_e2e.py -v
+
+# All tests
+pytest cli_anything/renderdoc/tests/ -v
+```
+
+## Test Coverage
+
+| Module | Tests | Status |
+|------------------------|-------|--------|
+| utils/output.py | 4 | โœ… Pass |
+| utils/errors.py | 2 | โœ… Pass |
+| core/actions.py | 9 | โœ… Pass |
+| core/textures.py | 4 | โœ… Pass |
+| core/resources.py | 5 | โœ… Pass |
+| CLI help (all groups) | 8 | โœ… Pass |
+| CLI subprocess | 1 | โœ… Pass |
+| **Total Unit** | **33**| **โœ… All Pass** |
+| E2E (capture info) | 2 | โญ๏ธ Skip (no RD) |
+| E2E (actions) | 4 | โญ๏ธ Skip (no RD) |
+| E2E (textures) | 2 | โญ๏ธ Skip (no RD) |
+| E2E (resources) | 2 | โญ๏ธ Skip (no RD) |
+| E2E (pipeline) | 2 | โญ๏ธ Skip (no RD) |
+| E2E (counters) | 1 | โญ๏ธ Skip (no RD) |
+| E2E (workflow) | 1 | โญ๏ธ Skip (no RD) |
+| **Total E2E** | **14**| **โญ๏ธ All Skip** |
+
+## Test Results
+
+```
+============================= test session starts =============================
+platform win32 -- Python 3.10.2, pytest-9.0.2
+
+cli_anything/renderdoc/tests/test_core.py::TestOutputUtils::test_output_json PASSED
+cli_anything/renderdoc/tests/test_core.py::TestOutputUtils::test_output_table PASSED
+cli_anything/renderdoc/tests/test_core.py::TestOutputUtils::test_output_table_empty PASSED
+cli_anything/renderdoc/tests/test_core.py::TestOutputUtils::test_format_size PASSED
+cli_anything/renderdoc/tests/test_core.py::TestErrorUtils::test_handle_error PASSED
+cli_anything/renderdoc/tests/test_core.py::TestErrorUtils::test_handle_error_debug PASSED
+cli_anything/renderdoc/tests/test_core.py::TestActionsModule::test_decode_flags PASSED
+cli_anything/renderdoc/tests/test_core.py::TestActionsModule::test_decode_flags_multiple PASSED
+cli_anything/renderdoc/tests/test_core.py::TestActionsModule::test_action_to_dict PASSED
+cli_anything/renderdoc/tests/test_core.py::TestActionsModule::test_list_actions_flat PASSED
+cli_anything/renderdoc/tests/test_core.py::TestActionsModule::test_list_actions_root_only PASSED
+cli_anything/renderdoc/tests/test_core.py::TestActionsModule::test_find_actions_by_name PASSED
+cli_anything/renderdoc/tests/test_core.py::TestActionsModule::test_find_action_by_event PASSED
+cli_anything/renderdoc/tests/test_core.py::TestActionsModule::test_get_drawcalls_only PASSED
+cli_anything/renderdoc/tests/test_core.py::TestActionsModule::test_action_summary PASSED
+cli_anything/renderdoc/tests/test_core.py::TestTexturesModule::test_tex_to_dict PASSED
+cli_anything/renderdoc/tests/test_core.py::TestTexturesModule::test_list_textures PASSED
+cli_anything/renderdoc/tests/test_core.py::TestTexturesModule::test_get_texture_found PASSED
+cli_anything/renderdoc/tests/test_core.py::TestTexturesModule::test_get_texture_not_found PASSED
+cli_anything/renderdoc/tests/test_core.py::TestResourcesModule::test_list_resources PASSED
+cli_anything/renderdoc/tests/test_core.py::TestResourcesModule::test_list_buffers PASSED
+cli_anything/renderdoc/tests/test_core.py::TestResourcesModule::test_get_buffer_data_hex PASSED
+cli_anything/renderdoc/tests/test_core.py::TestResourcesModule::test_get_buffer_data_float32 PASSED
+cli_anything/renderdoc/tests/test_core.py::TestResourcesModule::test_get_buffer_data_not_found PASSED
+cli_anything/renderdoc/tests/test_core.py::TestCLIHelp::test_main_help PASSED
+cli_anything/renderdoc/tests/test_core.py::TestCLIHelp::test_capture_help PASSED
+cli_anything/renderdoc/tests/test_core.py::TestCLIHelp::test_actions_help PASSED
+cli_anything/renderdoc/tests/test_core.py::TestCLIHelp::test_textures_help PASSED
+cli_anything/renderdoc/tests/test_core.py::TestCLIHelp::test_pipeline_help PASSED
+cli_anything/renderdoc/tests/test_core.py::TestCLIHelp::test_resources_help PASSED
+cli_anything/renderdoc/tests/test_core.py::TestCLIHelp::test_mesh_help PASSED
+cli_anything/renderdoc/tests/test_core.py::TestCLIHelp::test_counters_help PASSED
+cli_anything/renderdoc/tests/test_core.py::TestCLISubprocess::test_cli_help_subprocess PASSED
+
+============================= 33 passed in 0.15s ==============================
+
+cli_anything/renderdoc/tests/test_full_e2e.py - 14 skipped (no RenderDoc)
+
+============================= 47 total, 33 passed, 14 skipped ================
+```
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/tests/__init__.py b/renderdoc/agent-harness/cli_anything/renderdoc/tests/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_core.py b/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_core.py
new file mode 100644
index 000000000..cb3b4eaec
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_core.py
@@ -0,0 +1,691 @@
+"""
+Unit tests for RenderDoc CLI core modules.
+
+These tests use mocks and synthetic data โ€” no renderdoc dependency needed.
+Run with: pytest test_core.py -v
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import struct
+from unittest.mock import MagicMock, patch, PropertyMock
+
+import pytest
+
+# ---------------------------------------------------------------------------
+# Ensure the package is importable
+# ---------------------------------------------------------------------------
+HARNESS_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
+if HARNESS_ROOT not in sys.path:
+ sys.path.insert(0, HARNESS_ROOT)
+
+
+# ===========================================================================
+# Test utils/output.py
+# ===========================================================================
+
+class TestOutputUtils:
+ def test_output_json(self):
+ from cli_anything.renderdoc.utils.output import output_json
+ import io
+ buf = io.StringIO()
+ output_json({"key": "value", "num": 42}, file=buf)
+ result = json.loads(buf.getvalue())
+ assert result["key"] == "value"
+ assert result["num"] == 42
+
+ def test_output_table(self):
+ from cli_anything.renderdoc.utils.output import output_table
+ import io
+ buf = io.StringIO()
+ output_table(
+ [["Alice", 30], ["Bob", 25]],
+ ["Name", "Age"],
+ file=buf,
+ )
+ text = buf.getvalue()
+ assert "Alice" in text
+ assert "Bob" in text
+ assert "Name" in text
+
+ def test_output_table_empty(self):
+ from cli_anything.renderdoc.utils.output import output_table
+ import io
+ buf = io.StringIO()
+ output_table([], ["Name"], file=buf)
+ assert "(no data)" in buf.getvalue()
+
+ def test_format_size(self):
+ from cli_anything.renderdoc.utils.output import format_size
+ assert format_size(512) == "512 B"
+ assert "KB" in format_size(2048)
+ assert "MB" in format_size(2 * 1024 * 1024)
+ assert "GB" in format_size(3 * 1024 * 1024 * 1024)
+
+
+# ===========================================================================
+# Test utils/errors.py
+# ===========================================================================
+
+class TestErrorUtils:
+ def test_handle_error(self):
+ from cli_anything.renderdoc.utils.errors import handle_error
+ result = handle_error(ValueError("test error"))
+ assert result["error"] == "test error"
+ assert result["type"] == "ValueError"
+ assert "traceback" not in result
+
+ def test_handle_error_debug(self):
+ from cli_anything.renderdoc.utils.errors import handle_error
+ try:
+ raise RuntimeError("boom")
+ except RuntimeError as e:
+ result = handle_error(e, debug=True)
+ assert "traceback" in result
+ assert "boom" in result["traceback"]
+
+
+# ===========================================================================
+# Test core/actions.py (with mock rd)
+# ===========================================================================
+
+class MockActionFlags:
+ Clear = 0x0001
+ Drawcall = 0x0002
+ Dispatch = 0x0004
+ CmdList = 0x0008
+ SetMarker = 0x0010
+ PushMarker = 0x0020
+ PopMarker = 0x0040
+ Present = 0x0080
+ MultiAction = 0x0100
+ Copy = 0x0200
+ Resolve = 0x0400
+ GenMips = 0x0800
+ PassBoundary = 0x1000
+ Indexed = 0x2000
+ Instanced = 0x4000
+ Auto = 0x8000
+ Indirect = 0x10000
+ ClearColor = 0x20000
+ ClearDepthStencil = 0x40000
+ BeginPass = 0x80000
+ EndPass = 0x100000
+
+
+def _make_mock_action(event_id, name, flags=0x0002, num_indices=100, children=None):
+ action = MagicMock()
+ action.eventId = event_id
+ action.actionId = event_id
+ action.customName = name
+ action.GetName = MagicMock(return_value=name)
+ action.flags = flags
+ action.numIndices = num_indices
+ action.numInstances = 1
+ action.indexOffset = 0
+ action.baseVertex = 0
+ action.vertexOffset = 0
+ action.instanceOffset = 0
+ action.outputs = []
+ action.depthOut = MagicMock()
+ action.depthOut.__str__ = lambda s: "0"
+ action.children = children or []
+ action.next = None
+ return action
+
+
+class TestActionsModule:
+ @patch("cli_anything.renderdoc.core.actions.rd")
+ def test_decode_flags(self, mock_rd):
+ # Patch the flag values
+ mock_rd.ActionFlags = MockActionFlags
+ from cli_anything.renderdoc.core.actions import _decode_flags
+ result = _decode_flags(0x0002) # Drawcall
+ assert "Drawcall" in result
+
+ @patch("cli_anything.renderdoc.core.actions.rd")
+ def test_decode_flags_multiple(self, mock_rd):
+ mock_rd.ActionFlags = MockActionFlags
+ from cli_anything.renderdoc.core.actions import _decode_flags
+ result = _decode_flags(0x0002 | 0x2000) # Drawcall + Indexed
+ assert "Drawcall" in result
+ assert "Indexed" in result
+
+ @patch("cli_anything.renderdoc.core.actions.rd")
+ def test_action_to_dict(self, mock_rd):
+ mock_rd.ActionFlags = MockActionFlags
+ from cli_anything.renderdoc.core.actions import _action_to_dict
+ action = _make_mock_action(1, "Draw Triangle", 0x0002)
+ d = _action_to_dict(action, None)
+ assert d["eventId"] == 1
+ assert d["name"] == "Draw Triangle"
+ assert "Drawcall" in d["flags"]
+
+ @patch("cli_anything.renderdoc.core.actions.rd")
+ def test_list_actions_flat(self, mock_rd):
+ mock_rd.ActionFlags = MockActionFlags
+ from cli_anything.renderdoc.core.actions import list_actions
+
+ child = _make_mock_action(2, "DrawIndexed", 0x0002)
+ root = _make_mock_action(1, "RenderPass", 0x0020, children=[child])
+
+ controller = MagicMock()
+ controller.GetRootActions.return_value = [root]
+ controller.GetStructuredFile.return_value = MagicMock()
+
+ result = list_actions(controller, flat=True)
+ assert len(result) == 2
+ assert result[0]["eventId"] == 1
+ assert result[1]["eventId"] == 2
+ assert result[1]["depth"] == 1
+
+ @patch("cli_anything.renderdoc.core.actions.rd")
+ def test_list_actions_root_only(self, mock_rd):
+ mock_rd.ActionFlags = MockActionFlags
+ from cli_anything.renderdoc.core.actions import list_actions
+
+ child = _make_mock_action(2, "DrawIndexed")
+ root = _make_mock_action(1, "RenderPass", 0x0020, children=[child])
+
+ controller = MagicMock()
+ controller.GetRootActions.return_value = [root]
+ controller.GetStructuredFile.return_value = MagicMock()
+
+ result = list_actions(controller, flat=False)
+ assert len(result) == 1
+
+ @patch("cli_anything.renderdoc.core.actions.rd")
+ def test_find_actions_by_name(self, mock_rd):
+ mock_rd.ActionFlags = MockActionFlags
+ from cli_anything.renderdoc.core.actions import find_actions_by_name
+
+ a1 = _make_mock_action(1, "Clear RenderTarget", 0x0001)
+ a2 = _make_mock_action(2, "DrawIndexed(100)", 0x0002)
+ a3 = _make_mock_action(3, "DrawIndexed(200)", 0x0002)
+
+ controller = MagicMock()
+ controller.GetRootActions.return_value = [a1, a2, a3]
+ controller.GetStructuredFile.return_value = MagicMock()
+
+ result = find_actions_by_name(controller, "drawindex")
+ assert len(result) == 2
+
+ @patch("cli_anything.renderdoc.core.actions.rd")
+ def test_find_action_by_event(self, mock_rd):
+ mock_rd.ActionFlags = MockActionFlags
+ from cli_anything.renderdoc.core.actions import find_action_by_event
+
+ a1 = _make_mock_action(10, "Draw", 0x0002)
+ controller = MagicMock()
+ controller.GetRootActions.return_value = [a1]
+ controller.GetStructuredFile.return_value = MagicMock()
+
+ result = find_action_by_event(controller, 10)
+ assert result is not None
+ assert result["eventId"] == 10
+
+ result = find_action_by_event(controller, 999)
+ assert result is None
+
+ @patch("cli_anything.renderdoc.core.actions.rd")
+ def test_get_drawcalls_only(self, mock_rd):
+ mock_rd.ActionFlags = MockActionFlags
+ from cli_anything.renderdoc.core.actions import get_drawcalls_only
+
+ a1 = _make_mock_action(1, "Clear", 0x0001) # Clear
+ a2 = _make_mock_action(2, "Draw", 0x0002) # Drawcall
+ a3 = _make_mock_action(3, "Marker", 0x0020) # PushMarker
+
+ controller = MagicMock()
+ controller.GetRootActions.return_value = [a1, a2, a3]
+ controller.GetStructuredFile.return_value = MagicMock()
+
+ result = get_drawcalls_only(controller)
+ assert len(result) == 1
+ assert result[0]["name"] == "Draw"
+
+ @patch("cli_anything.renderdoc.core.actions.rd")
+ def test_action_summary(self, mock_rd):
+ mock_rd.ActionFlags = MockActionFlags
+ from cli_anything.renderdoc.core.actions import action_summary
+
+ actions = [
+ _make_mock_action(1, "Clear", 0x0001),
+ _make_mock_action(2, "Draw1", 0x0002),
+ _make_mock_action(3, "Draw2", 0x0002),
+ _make_mock_action(4, "Dispatch", 0x0004),
+ _make_mock_action(5, "Copy", 0x0200),
+ _make_mock_action(6, "Marker", 0x0020),
+ _make_mock_action(7, "Present", 0x0080),
+ ]
+ controller = MagicMock()
+ controller.GetRootActions.return_value = actions
+ controller.GetStructuredFile.return_value = MagicMock()
+
+ result = action_summary(controller)
+ assert result["total_actions"] == 7
+ assert result["drawcalls"] == 2
+ assert result["clears"] == 1
+ assert result["dispatches"] == 1
+ assert result["copies"] == 1
+ assert result["markers"] == 1
+ assert result["presents"] == 1
+
+
+# ===========================================================================
+# Test core/textures.py (mock-based)
+# ===========================================================================
+
+class TestTexturesModule:
+ def _make_mock_tex(self, rid="123", w=512, h=512, mips=1, fmt="R8G8B8A8_UNORM"):
+ tex = MagicMock()
+ tex.resourceId = MagicMock()
+ tex.resourceId.__str__ = lambda s: rid
+ tex.name = f"Texture_{rid}"
+ tex.width = w
+ tex.height = h
+ tex.depth = 1
+ tex.mips = mips
+ tex.arraysize = 1
+ tex.msQual = 0
+ tex.msSamp = 1
+ tex.format = MagicMock()
+ tex.format.__str__ = lambda s: fmt
+ tex.dimension = 2
+ tex.type = MagicMock()
+ tex.type.__str__ = lambda s: "Texture2D"
+ tex.cubemap = False
+ tex.byteSize = w * h * 4
+ tex.creationFlags = 0
+ return tex
+
+ def test_tex_to_dict(self):
+ from cli_anything.renderdoc.core.textures import _tex_to_dict
+ tex = self._make_mock_tex()
+ d = _tex_to_dict(tex)
+ assert d["resourceId"] == "123"
+ assert d["width"] == 512
+ assert d["height"] == 512
+ assert d["mips"] == 1
+
+ def test_list_textures(self):
+ from cli_anything.renderdoc.core.textures import list_textures
+ controller = MagicMock()
+ controller.GetTextures.return_value = [
+ self._make_mock_tex("1", 256, 256),
+ self._make_mock_tex("2", 1024, 1024),
+ ]
+ result = list_textures(controller)
+ assert len(result) == 2
+ assert result[0]["width"] == 256
+ assert result[1]["width"] == 1024
+
+ def test_get_texture_found(self):
+ from cli_anything.renderdoc.core.textures import get_texture
+ controller = MagicMock()
+ controller.GetTextures.return_value = [
+ self._make_mock_tex("42", 800, 600),
+ ]
+ result = get_texture(controller, "42")
+ assert result is not None
+ assert result["width"] == 800
+
+ def test_get_texture_not_found(self):
+ from cli_anything.renderdoc.core.textures import get_texture
+ controller = MagicMock()
+ controller.GetTextures.return_value = []
+ result = get_texture(controller, "999")
+ assert result is None
+
+
+# ===========================================================================
+# Test core/resources.py (mock-based)
+# ===========================================================================
+
+class TestResourcesModule:
+ def test_list_resources(self):
+ from cli_anything.renderdoc.core.resources import list_resources
+
+ r1 = MagicMock()
+ r1.resourceId = MagicMock()
+ r1.resourceId.__str__ = lambda s: "1"
+ r1.name = "Backbuffer"
+ r1.type = MagicMock()
+ r1.type.__str__ = lambda s: "Texture"
+
+ controller = MagicMock()
+ controller.GetResources.return_value = [r1]
+
+ result = list_resources(controller)
+ assert len(result) == 1
+ assert result[0]["name"] == "Backbuffer"
+
+ def test_list_buffers(self):
+ from cli_anything.renderdoc.core.resources import list_buffers
+
+ b1 = MagicMock()
+ b1.resourceId = MagicMock()
+ b1.resourceId.__str__ = lambda s: "5"
+ b1.length = 4096
+ b1.creationFlags = 0
+
+ controller = MagicMock()
+ controller.GetBuffers.return_value = [b1]
+
+ result = list_buffers(controller)
+ assert len(result) == 1
+ assert result[0]["length"] == 4096
+
+ def test_get_buffer_data_hex(self):
+ from cli_anything.renderdoc.core.resources import get_buffer_data
+
+ b1 = MagicMock()
+ b1.resourceId = MagicMock()
+ b1.resourceId.__str__ = lambda s: "5"
+
+ controller = MagicMock()
+ controller.GetBuffers.return_value = [b1]
+ controller.GetBufferData.return_value = b"\x01\x02\x03\x04"
+
+ result = get_buffer_data(controller, "5", 0, 4, "hex")
+ assert result["data"] == "01020304"
+ assert result["length"] == 4
+
+ def test_get_buffer_data_float32(self):
+ from cli_anything.renderdoc.core.resources import get_buffer_data
+
+ b1 = MagicMock()
+ b1.resourceId = MagicMock()
+ b1.resourceId.__str__ = lambda s: "5"
+
+ controller = MagicMock()
+ controller.GetBuffers.return_value = [b1]
+ test_data = struct.pack("<2f", 1.0, 2.5)
+ controller.GetBufferData.return_value = test_data
+
+ result = get_buffer_data(controller, "5", 0, 8, "float32")
+ assert len(result["data"]) == 2
+ assert abs(result["data"][0] - 1.0) < 0.001
+ assert abs(result["data"][1] - 2.5) < 0.001
+
+ def test_get_buffer_data_not_found(self):
+ from cli_anything.renderdoc.core.resources import get_buffer_data
+
+ controller = MagicMock()
+ controller.GetBuffers.return_value = []
+
+ result = get_buffer_data(controller, "999", 0, 4, "hex")
+ assert "error" in result
+
+
+# ===========================================================================
+# Test CLI entry point (Click testing)
+# ===========================================================================
+
+class TestCLIHelp:
+ """Test that CLI help works without renderdoc installed."""
+
+ def test_main_help(self):
+ from click.testing import CliRunner
+ from cli_anything.renderdoc.renderdoc_cli import cli
+ runner = CliRunner()
+ result = runner.invoke(cli, ["--help"])
+ assert result.exit_code == 0
+ assert "RenderDoc CLI" in result.output
+
+ def test_capture_help(self):
+ from click.testing import CliRunner
+ from cli_anything.renderdoc.renderdoc_cli import cli
+ runner = CliRunner()
+ result = runner.invoke(cli, ["capture", "--help"])
+ assert result.exit_code == 0
+ assert "info" in result.output
+
+ def test_actions_help(self):
+ from click.testing import CliRunner
+ from cli_anything.renderdoc.renderdoc_cli import cli
+ runner = CliRunner()
+ result = runner.invoke(cli, ["actions", "--help"])
+ assert result.exit_code == 0
+ assert "list" in result.output
+
+ def test_textures_help(self):
+ from click.testing import CliRunner
+ from cli_anything.renderdoc.renderdoc_cli import cli
+ runner = CliRunner()
+ result = runner.invoke(cli, ["textures", "--help"])
+ assert result.exit_code == 0
+ assert "save" in result.output
+
+ def test_pipeline_help(self):
+ from click.testing import CliRunner
+ from cli_anything.renderdoc.renderdoc_cli import cli
+ runner = CliRunner()
+ result = runner.invoke(cli, ["pipeline", "--help"])
+ assert result.exit_code == 0
+ assert "state" in result.output
+
+ def test_resources_help(self):
+ from click.testing import CliRunner
+ from cli_anything.renderdoc.renderdoc_cli import cli
+ runner = CliRunner()
+ result = runner.invoke(cli, ["resources", "--help"])
+ assert result.exit_code == 0
+ assert "buffers" in result.output
+
+ def test_mesh_help(self):
+ from click.testing import CliRunner
+ from cli_anything.renderdoc.renderdoc_cli import cli
+ runner = CliRunner()
+ result = runner.invoke(cli, ["mesh", "--help"])
+ assert result.exit_code == 0
+ assert "inputs" in result.output
+
+ def test_counters_help(self):
+ from click.testing import CliRunner
+ from cli_anything.renderdoc.renderdoc_cli import cli
+ runner = CliRunner()
+ result = runner.invoke(cli, ["counters", "--help"])
+ assert result.exit_code == 0
+ assert "fetch" in result.output
+
+
+# ===========================================================================
+# Test subprocess invocation pattern
+# ===========================================================================
+
+class TestCLISubprocess:
+ """Test CLI via subprocess (requires pip install -e .)"""
+
+ def test_cli_help_subprocess(self):
+ import subprocess
+ try:
+ result = subprocess.run(
+ [sys.executable, "-m", "cli_anything.renderdoc.renderdoc_cli", "--help"],
+ capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "RenderDoc CLI" in result.stdout
+ except FileNotFoundError:
+ pytest.skip("CLI not installed")
+
+
+# ===========================================================================
+# Test core/diff.py (snapshot-based, no renderdoc needed)
+# ===========================================================================
+
+class TestDiffModule:
+ """Unit tests for diff_pipeline_from_snapshots and helpers."""
+
+ @staticmethod
+ def _make_snapshot(event_id, pipeline_state=None):
+ """Build a minimal snapshot dict."""
+ return {
+ "eventId": event_id,
+ "PipelineState": pipeline_state or {},
+ }
+
+ def test_identical_snapshots(self):
+ from cli_anything.renderdoc.core.diff import diff_pipeline_from_snapshots
+
+ ps = {
+ "pipelineType": "Graphics",
+ "viewport": {"x": 0, "y": 0, "width": 1920, "height": 1080},
+ "rasterizer": {"fillMode": "Solid"},
+ "depthStencil": {"depthEnable": True},
+ "stages": {},
+ }
+ snap = self._make_snapshot(100, ps)
+ result = diff_pipeline_from_snapshots(snap, snap)
+ assert result["identical"] is True
+
+ def test_different_viewport(self):
+ from cli_anything.renderdoc.core.diff import diff_pipeline_from_snapshots
+
+ ps_a = {"viewport": {"x": 0, "y": 0, "width": 1920, "height": 1080}}
+ ps_b = {"viewport": {"x": 0, "y": 0, "width": 1280, "height": 720}}
+ result = diff_pipeline_from_snapshots(
+ self._make_snapshot(1, ps_a),
+ self._make_snapshot(2, ps_b),
+ )
+ assert result["identical"] is False
+ assert "viewport" in result
+ assert result["viewport"]["width"]["A"] == 1920
+ assert result["viewport"]["width"]["B"] == 1280
+
+ def test_float_tolerance(self):
+ from cli_anything.renderdoc.core.diff import _values_equal
+
+ assert _values_equal(1.0, 1.0 + 1e-9) is True
+ assert _values_equal(1.0, 1.1) is False
+
+ def test_float_nan_equal(self):
+ import math
+ from cli_anything.renderdoc.core.diff import _values_equal
+
+ assert _values_equal(float("nan"), float("nan")) is True
+ assert _values_equal(float("inf"), float("inf")) is True
+ assert _values_equal(float("inf"), float("-inf")) is False
+
+ def test_diff_lists_only_in_one_side(self):
+ from cli_anything.renderdoc.core.diff import diff_pipeline_from_snapshots
+
+ ps_a = {
+ "vertexInputs": [
+ {"name": "POSITION", "format": "R32G32B32_FLOAT"},
+ ],
+ }
+ ps_b = {
+ "vertexInputs": [
+ {"name": "POSITION", "format": "R32G32B32_FLOAT"},
+ {"name": "TEXCOORD", "format": "R32G32_FLOAT"},
+ ],
+ }
+ result = diff_pipeline_from_snapshots(
+ self._make_snapshot(1, ps_a),
+ self._make_snapshot(2, ps_b),
+ )
+ assert result["identical"] is False
+ assert isinstance(result["vertexInputs"], list)
+ statuses = [d["status"] for d in result["vertexInputs"]]
+ assert "only_in_B" in statuses
+
+ def test_diff_dicts_missing_key(self):
+ from cli_anything.renderdoc.core.diff import _diff_dicts
+
+ a = {"x": 1, "y": 2}
+ b = {"x": 1, "z": 3}
+ result = _diff_dicts(a, b)
+ assert result is not None
+ assert "y" in result
+ assert "z" in result
+
+ def test_diff_dicts_identical(self):
+ from cli_anything.renderdoc.core.diff import _diff_dicts
+
+ a = {"x": 1, "y": 2}
+ result = _diff_dicts(a, a)
+ assert result is None
+
+ def test_diff_dicts_none_inputs(self):
+ from cli_anything.renderdoc.core.diff import _diff_dicts
+
+ assert _diff_dicts(None, None) is None
+ result = _diff_dicts(None, {"x": 1})
+ assert result is not None
+ assert result["A"] is None
+
+ def test_stage_diff_shader_changed(self):
+ from cli_anything.renderdoc.core.diff import diff_pipeline_from_snapshots
+
+ ps_a = {
+ "stages": {
+ "Vertex": {
+ "shader": "ResourceId::100",
+ "entryPoint": "main",
+ "ShaderReflection": {},
+ "bindings": {"constantBlocks": [], "readOnlyResources": [],
+ "readWriteResources": [], "samplers": []},
+ },
+ },
+ }
+ ps_b = {
+ "stages": {
+ "Vertex": {
+ "shader": "ResourceId::200",
+ "entryPoint": "main",
+ "ShaderReflection": {},
+ "bindings": {"constantBlocks": [], "readOnlyResources": [],
+ "readWriteResources": [], "samplers": []},
+ },
+ },
+ }
+ result = diff_pipeline_from_snapshots(
+ self._make_snapshot(1, ps_a),
+ self._make_snapshot(2, ps_b),
+ )
+ assert result["identical"] is False
+ assert result["stages"]["Vertex"]["shader"]["shader"]["A"] == "ResourceId::100"
+ assert result["stages"]["Vertex"]["shader"]["shader"]["B"] == "ResourceId::200"
+
+ def test_cbuffer_variable_diff(self):
+ from cli_anything.renderdoc.core.diff import _diff_cbuffer_vars
+
+ vars_a = [
+ {"name": "color", "values": [1.0, 0.0, 0.0, 1.0]},
+ {"name": "intensity", "values": [0.5]},
+ ]
+ vars_b = [
+ {"name": "color", "values": [0.0, 1.0, 0.0, 1.0]},
+ {"name": "intensity", "values": [0.5]},
+ ]
+ result = _diff_cbuffer_vars(vars_a, vars_b)
+ assert result is not None
+ assert len(result) == 1
+ assert result[0]["name"] == "color"
+ assert result[0]["status"] == "changed"
+
+ def test_cbuffer_variable_identical(self):
+ from cli_anything.renderdoc.core.diff import _diff_cbuffer_vars
+
+ vars_a = [{"name": "x", "values": [1.0]}]
+ result = _diff_cbuffer_vars(vars_a, vars_a)
+ assert result is None
+
+ def test_output_table_extra_columns(self):
+ """Verify output_table truncates rows longer than headers."""
+ from cli_anything.renderdoc.utils.output import output_table
+ import io
+
+ buf = io.StringIO()
+ output_table(
+ [["Alice", 30, "extra_col"]],
+ ["Name", "Age"],
+ file=buf,
+ )
+ text = buf.getvalue()
+ assert "Alice" in text
+ assert "extra_col" not in text
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_full_e2e.py b/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_full_e2e.py
new file mode 100644
index 000000000..8589a5546
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_full_e2e.py
@@ -0,0 +1,228 @@
+"""
+End-to-end tests for RenderDoc CLI.
+
+These tests require:
+ 1. RenderDoc installed with Python bindings accessible
+ 2. A .rdc capture file (set via RENDERDOC_TEST_CAPTURE env var)
+
+Skip gracefully if either is unavailable.
+
+Run with: pytest test_full_e2e.py -v
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import tempfile
+
+import pytest
+
+# ---------------------------------------------------------------------------
+# Configuration
+# ---------------------------------------------------------------------------
+
+HARNESS_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
+if HARNESS_ROOT not in sys.path:
+ sys.path.insert(0, HARNESS_ROOT)
+
+TEST_CAPTURE = os.environ.get("RENDERDOC_TEST_CAPTURE", "")
+HAS_CAPTURE = os.path.isfile(TEST_CAPTURE) if TEST_CAPTURE else False
+
+try:
+ import renderdoc as rd
+ HAS_RD = True
+except ImportError:
+ HAS_RD = False
+
+skip_no_rd = pytest.mark.skipif(not HAS_RD, reason="renderdoc module not available")
+skip_no_cap = pytest.mark.skipif(not HAS_CAPTURE, reason="RENDERDOC_TEST_CAPTURE not set or file missing")
+
+
+def _run_cli(*args, json_mode=True) -> dict | list | str:
+ """Run CLI via module invocation and parse output."""
+ cmd = [sys.executable, "-m", "cli_anything.renderdoc.renderdoc_cli"]
+ if TEST_CAPTURE:
+ cmd.extend(["--capture", TEST_CAPTURE])
+ if json_mode:
+ cmd.append("--json")
+ cmd.extend(args)
+
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=60, cwd=HARNESS_ROOT)
+ if result.returncode != 0:
+ raise RuntimeError(f"CLI failed: {result.stderr}\n{result.stdout}")
+
+ if json_mode:
+ return json.loads(result.stdout)
+ return result.stdout
+
+
+# ===========================================================================
+# E2E: Capture info
+# ===========================================================================
+
+@skip_no_rd
+@skip_no_cap
+class TestCaptureE2E:
+ def test_capture_info(self):
+ data = _run_cli("capture", "info")
+ assert "path" in data
+ assert "api" in data
+ assert "sections" in data
+ assert isinstance(data["sections"], list)
+
+ def test_capture_thumb(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ output = os.path.join(tmpdir, "thumb.png")
+ data = _run_cli("capture", "thumb", "--output", output)
+ # May fail if no thumbnail - that's ok
+ if "error" not in data:
+ assert os.path.isfile(output)
+
+
+# ===========================================================================
+# E2E: Actions
+# ===========================================================================
+
+@skip_no_rd
+@skip_no_cap
+class TestActionsE2E:
+ def test_actions_list(self):
+ data = _run_cli("actions", "list")
+ assert isinstance(data, list)
+ assert len(data) > 0
+ assert "eventId" in data[0]
+
+ def test_actions_summary(self):
+ data = _run_cli("actions", "summary")
+ assert "total_actions" in data
+ assert data["total_actions"] > 0
+
+ def test_actions_draws_only(self):
+ data = _run_cli("actions", "list", "--draws-only")
+ assert isinstance(data, list)
+ for a in data:
+ assert "Drawcall" in a["flags"]
+
+ def test_actions_get(self):
+ # First get list to find a valid eventId
+ actions = _run_cli("actions", "list")
+ if actions:
+ eid = actions[0]["eventId"]
+ data = _run_cli("actions", "get", str(eid))
+ assert data["eventId"] == eid
+
+
+# ===========================================================================
+# E2E: Textures
+# ===========================================================================
+
+@skip_no_rd
+@skip_no_cap
+class TestTexturesE2E:
+ def test_textures_list(self):
+ data = _run_cli("textures", "list")
+ assert isinstance(data, list)
+ if len(data) > 0:
+ assert "resourceId" in data[0]
+ assert "width" in data[0]
+
+ def test_textures_save(self):
+ textures = _run_cli("textures", "list")
+ if not textures:
+ pytest.skip("No textures in capture")
+ rid = textures[0]["resourceId"]
+ with tempfile.TemporaryDirectory() as tmpdir:
+ output = os.path.join(tmpdir, "tex.png")
+ data = _run_cli("textures", "save", rid, "--output", output)
+ if "error" not in data:
+ assert os.path.isfile(output)
+
+
+# ===========================================================================
+# E2E: Resources
+# ===========================================================================
+
+@skip_no_rd
+@skip_no_cap
+class TestResourcesE2E:
+ def test_resources_list(self):
+ data = _run_cli("resources", "list")
+ assert isinstance(data, list)
+
+ def test_resources_buffers(self):
+ data = _run_cli("resources", "buffers")
+ assert isinstance(data, list)
+
+
+# ===========================================================================
+# E2E: Pipeline
+# ===========================================================================
+
+@skip_no_rd
+@skip_no_cap
+class TestPipelineE2E:
+ def test_pipeline_state(self):
+ # Get first draw call
+ draws = _run_cli("actions", "list", "--draws-only")
+ if not draws:
+ pytest.skip("No draw calls in capture")
+ eid = draws[0]["eventId"]
+ data = _run_cli("pipeline", "state", str(eid))
+ assert "shaders" in data
+ assert "eventId" in data
+
+ def test_pipeline_shader_export(self):
+ draws = _run_cli("actions", "list", "--draws-only")
+ if not draws:
+ pytest.skip("No draw calls")
+ eid = draws[0]["eventId"]
+ data = _run_cli("pipeline", "shader-export", str(eid), "--stage", "Fragment")
+ # May have error if no pixel shader - acceptable
+ assert "eventId" in data or "error" in data
+
+
+# ===========================================================================
+# E2E: Counters
+# ===========================================================================
+
+@skip_no_rd
+@skip_no_cap
+class TestCountersE2E:
+ def test_counters_list(self):
+ data = _run_cli("counters", "list")
+ assert isinstance(data, list)
+
+
+# ===========================================================================
+# Workflow: Full analysis pipeline
+# ===========================================================================
+
+@skip_no_rd
+@skip_no_cap
+class TestWorkflowE2E:
+ def test_full_analysis_workflow(self):
+ """Simulate a typical analysis: info โ†’ list draws โ†’ inspect โ†’ export."""
+ # Step 1: Capture info
+ info = _run_cli("capture", "info")
+ assert "api" in info
+
+ # Step 2: Action summary
+ summary = _run_cli("actions", "summary")
+ assert summary["total_actions"] > 0
+
+ # Step 3: Find draw calls
+ draws = _run_cli("actions", "list", "--draws-only")
+ if not draws:
+ return # No draws to inspect
+
+ # Step 4: Inspect pipeline at first draw
+ eid = draws[0]["eventId"]
+ pipeline = _run_cli("pipeline", "state", str(eid))
+ assert "shaders" in pipeline
+
+ # Step 5: List textures
+ textures = _run_cli("textures", "list")
+ assert isinstance(textures, list)
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/utils/__init__.py b/renderdoc/agent-harness/cli_anything/renderdoc/utils/__init__.py
new file mode 100644
index 000000000..6e192bbe8
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/utils/__init__.py
@@ -0,0 +1 @@
+"""Utility modules for RenderDoc CLI harness."""
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/utils/errors.py b/renderdoc/agent-harness/cli_anything/renderdoc/utils/errors.py
new file mode 100644
index 000000000..a182fa8bc
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/utils/errors.py
@@ -0,0 +1,29 @@
+"""
+Error handling utilities.
+"""
+
+from __future__ import annotations
+
+import sys
+import traceback
+from typing import Any, Dict
+
+
+def handle_error(e: Exception, debug: bool = False) -> Dict[str, Any]:
+ """Convert an exception into an error dict.
+
+ If *debug* is True, includes the full traceback.
+ """
+ result = {
+ "error": str(e),
+ "type": type(e).__name__,
+ }
+ if debug:
+ result["traceback"] = traceback.format_exc()
+ return result
+
+
+def die(message: str, code: int = 1):
+ """Print error message and exit."""
+ sys.stderr.write(f"Error: {message}\n")
+ sys.exit(code)
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/utils/output.py b/renderdoc/agent-harness/cli_anything/renderdoc/utils/output.py
new file mode 100644
index 000000000..91d03e7ae
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/utils/output.py
@@ -0,0 +1,56 @@
+"""
+Output formatting: JSON and human-readable output helpers.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from typing import Any
+
+
+def output_json(data: Any, indent: int = 2, file=None):
+ """Write data as JSON to stdout or a file."""
+ if file is None:
+ file = sys.stdout
+ json.dump(data, file, indent=indent, default=str)
+ file.write("\n")
+
+
+def output_table(rows: list, headers: list, file=None):
+ """Print a simple ASCII table."""
+ if file is None:
+ file = sys.stdout
+
+ if not rows:
+ file.write("(no data)\n")
+ return
+
+ # Calculate column widths
+ col_widths = [len(h) for h in headers]
+ for row in rows:
+ for i, val in enumerate(row):
+ if i < len(col_widths):
+ col_widths[i] = max(col_widths[i], len(str(val)))
+
+ # Header
+ header_line = " ".join(str(h).ljust(col_widths[i]) for i, h in enumerate(headers))
+ file.write(header_line + "\n")
+ file.write(" ".join("-" * w for w in col_widths) + "\n")
+
+ # Rows
+ for row in rows:
+ truncated = row[:len(headers)]
+ line = " ".join(str(v).ljust(col_widths[i]) for i, v in enumerate(truncated))
+ file.write(line + "\n")
+
+
+def format_size(size_bytes: int) -> str:
+ """Format byte count as human-readable string."""
+ if size_bytes < 1024:
+ return f"{size_bytes} B"
+ elif size_bytes < 1024 * 1024:
+ return f"{size_bytes / 1024:.1f} KB"
+ elif size_bytes < 1024 * 1024 * 1024:
+ return f"{size_bytes / (1024 * 1024):.1f} MB"
+ return f"{size_bytes / (1024 * 1024 * 1024):.1f} GB"
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/utils/repl_skin.py b/renderdoc/agent-harness/cli_anything/renderdoc/utils/repl_skin.py
new file mode 100644
index 000000000..c7312348a
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/utils/repl_skin.py
@@ -0,0 +1,521 @@
+"""cli-anything REPL Skin โ€” Unified terminal interface for all CLI harnesses.
+
+Copy this file into your CLI package at:
+ cli_anything/<software>/utils/repl_skin.py
+
+Usage:
+ from cli_anything.<software>.utils.repl_skin import ReplSkin
+
+ skin = ReplSkin("shotcut", version="1.0.0")
+ skin.print_banner() # auto-detects skills/SKILL.md inside the package
+ prompt_text = skin.prompt(project_name="my_video.mlt", modified=True)
+ skin.success("Project saved")
+ skin.error("File not found")
+ skin.warning("Unsaved changes")
+ skin.info("Processing 24 clips...")
+ skin.status("Track 1", "3 clips, 00:02:30")
+ skin.table(headers, rows)
+ skin.print_goodbye()
+"""
+
+import os
+import sys
+
+# โ”€โ”€ ANSI color codes (no external deps for core styling) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+_RESET = "\033[0m"
+_BOLD = "\033[1m"
+_DIM = "\033[2m"
+_ITALIC = "\033[3m"
+_UNDERLINE = "\033[4m"
+
+# Brand colors
+_CYAN = "\033[38;5;80m" # cli-anything brand cyan
+_CYAN_BG = "\033[48;5;80m"
+_WHITE = "\033[97m"
+_GRAY = "\033[38;5;245m"
+_DARK_GRAY = "\033[38;5;240m"
+_LIGHT_GRAY = "\033[38;5;250m"
+
+# Software accent colors โ€” each software gets a unique accent
+_ACCENT_COLORS = {
+ "gimp": "\033[38;5;214m", # warm orange
+ "blender": "\033[38;5;208m", # deep orange
+ "inkscape": "\033[38;5;39m", # bright blue
+ "audacity": "\033[38;5;33m", # navy blue
+ "libreoffice": "\033[38;5;40m", # green
+ "obs_studio": "\033[38;5;55m", # purple
+ "kdenlive": "\033[38;5;69m", # slate blue
+ "shotcut": "\033[38;5;35m", # teal green
+}
+_DEFAULT_ACCENT = "\033[38;5;75m" # default sky blue
+
+# Status colors
+_GREEN = "\033[38;5;78m"
+_YELLOW = "\033[38;5;220m"
+_RED = "\033[38;5;196m"
+_BLUE = "\033[38;5;75m"
+_MAGENTA = "\033[38;5;176m"
+
+# โ”€โ”€ Brand icon โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+# The cli-anything icon: a small colored diamond/chevron mark
+_ICON = f"{_CYAN}{_BOLD}โ—†{_RESET}"
+_ICON_SMALL = f"{_CYAN}โ–ธ{_RESET}"
+
+# โ”€โ”€ Box drawing characters โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+_H_LINE = "โ”€"
+_V_LINE = "โ”‚"
+_TL = "โ•ญ"
+_TR = "โ•ฎ"
+_BL = "โ•ฐ"
+_BR = "โ•ฏ"
+_T_DOWN = "โ”ฌ"
+_T_UP = "โ”ด"
+_T_RIGHT = "โ”œ"
+_T_LEFT = "โ”ค"
+_CROSS = "โ”ผ"
+
+
+def _strip_ansi(text: str) -> str:
+ """Remove ANSI escape codes for length calculation."""
+ import re
+ return re.sub(r"\033\[[^m]*m", "", text)
+
+
+def _visible_len(text: str) -> int:
+ """Get visible length of text (excluding ANSI codes)."""
+ return len(_strip_ansi(text))
+
+
+class ReplSkin:
+ """Unified REPL skin for cli-anything CLIs.
+
+ Provides consistent branding, prompts, and message formatting
+ across all CLI harnesses built with the cli-anything methodology.
+ """
+
+ def __init__(self, software: str, version: str = "1.0.0",
+ history_file: str | None = None, skill_path: str | None = None):
+ """Initialize the REPL skin.
+
+ Args:
+ software: Software name (e.g., "gimp", "shotcut", "blender").
+ version: CLI version string.
+ history_file: Path for persistent command history.
+ Defaults to ~/.cli-anything-<software>/history
+ skill_path: Path to the SKILL.md file for agent discovery.
+ Auto-detected from the package's skills/ directory if not provided.
+ Displayed in banner for AI agents to know where to read skill info.
+ """
+ self.software = software.lower().replace("-", "_")
+ self.display_name = software.replace("_", " ").title()
+ self.version = version
+
+ # Auto-detect skill path from package layout:
+ # cli_anything/<software>/utils/repl_skin.py (this file)
+ # cli_anything/<software>/skills/SKILL.md (target)
+ if skill_path is None:
+ from pathlib import Path
+ _auto = Path(__file__).resolve().parent.parent / "skills" / "SKILL.md"
+ if _auto.is_file():
+ skill_path = str(_auto)
+ self.skill_path = skill_path
+ self.accent = _ACCENT_COLORS.get(self.software, _DEFAULT_ACCENT)
+
+ # History file
+ if history_file is None:
+ from pathlib import Path
+ hist_dir = Path.home() / f".cli-anything-{self.software}"
+ hist_dir.mkdir(parents=True, exist_ok=True)
+ self.history_file = str(hist_dir / "history")
+ else:
+ self.history_file = history_file
+
+ # Detect terminal capabilities
+ self._color = self._detect_color_support()
+
+ def _detect_color_support(self) -> bool:
+ """Check if terminal supports color."""
+ if os.environ.get("NO_COLOR"):
+ return False
+ if os.environ.get("CLI_ANYTHING_NO_COLOR"):
+ return False
+ if not hasattr(sys.stdout, "isatty"):
+ return False
+ return sys.stdout.isatty()
+
+ def _c(self, code: str, text: str) -> str:
+ """Apply color code if colors are supported."""
+ if not self._color:
+ return text
+ return f"{code}{text}{_RESET}"
+
+ # โ”€โ”€ Banner โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def print_banner(self):
+ """Print the startup banner with branding."""
+ inner = 54
+
+ def _box_line(content: str) -> str:
+ """Wrap content in box drawing, padding to inner width."""
+ pad = inner - _visible_len(content)
+ vl = self._c(_DARK_GRAY, _V_LINE)
+ return f"{vl}{content}{' ' * max(0, pad)}{vl}"
+
+ top = self._c(_DARK_GRAY, f"{_TL}{_H_LINE * inner}{_TR}")
+ bot = self._c(_DARK_GRAY, f"{_BL}{_H_LINE * inner}{_BR}")
+
+ # Title: โ—† cli-anything ยท Shotcut
+ icon = self._c(_CYAN + _BOLD, "โ—†")
+ brand = self._c(_CYAN + _BOLD, "cli-anything")
+ dot = self._c(_DARK_GRAY, "ยท")
+ name = self._c(self.accent + _BOLD, self.display_name)
+ title = f" {icon} {brand} {dot} {name}"
+
+ ver = f" {self._c(_DARK_GRAY, f' v{self.version}')}"
+ tip = f" {self._c(_DARK_GRAY, ' Type help for commands, quit to exit')}"
+ empty = ""
+
+ # Skill path for agent discovery
+ skill_line = None
+ if self.skill_path:
+ skill_icon = self._c(_MAGENTA, "โ—‡")
+ skill_label = self._c(_DARK_GRAY, " Skill:")
+ skill_path_display = self._c(_LIGHT_GRAY, self.skill_path)
+ skill_line = f" {skill_icon} {skill_label} {skill_path_display}"
+
+ print(top)
+ print(_box_line(title))
+ print(_box_line(ver))
+ if skill_line:
+ print(_box_line(skill_line))
+ print(_box_line(empty))
+ print(_box_line(tip))
+ print(bot)
+ print()
+
+ # โ”€โ”€ Prompt โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def prompt(self, project_name: str = "", modified: bool = False,
+ context: str = "") -> str:
+ """Build a styled prompt string for prompt_toolkit or input().
+
+ Args:
+ project_name: Current project name (empty if none open).
+ modified: Whether the project has unsaved changes.
+ context: Optional extra context to show in prompt.
+
+ Returns:
+ Formatted prompt string.
+ """
+ parts = []
+
+ # Icon
+ if self._color:
+ parts.append(f"{_CYAN}โ—†{_RESET} ")
+ else:
+ parts.append("> ")
+
+ # Software name
+ parts.append(self._c(self.accent + _BOLD, self.software))
+
+ # Project context
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ parts.append(f" {self._c(_DARK_GRAY, '[')}")
+ parts.append(self._c(_LIGHT_GRAY, f"{ctx}{mod}"))
+ parts.append(self._c(_DARK_GRAY, ']'))
+
+ parts.append(self._c(_GRAY, " โฏ "))
+
+ return "".join(parts)
+
+ def prompt_tokens(self, project_name: str = "", modified: bool = False,
+ context: str = ""):
+ """Build prompt_toolkit formatted text tokens for the prompt.
+
+ Use with prompt_toolkit's FormattedText for proper ANSI handling.
+
+ Returns:
+ list of (style, text) tuples for prompt_toolkit.
+ """
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+ tokens = []
+
+ tokens.append(("class:icon", "โ—† "))
+ tokens.append(("class:software", self.software))
+
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ tokens.append(("class:bracket", " ["))
+ tokens.append(("class:context", f"{ctx}{mod}"))
+ tokens.append(("class:bracket", "]"))
+
+ tokens.append(("class:arrow", " โฏ "))
+
+ return tokens
+
+ def get_prompt_style(self):
+ """Get a prompt_toolkit Style object matching the skin.
+
+ Returns:
+ prompt_toolkit.styles.Style
+ """
+ try:
+ from prompt_toolkit.styles import Style
+ except ImportError:
+ return None
+
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+
+ return Style.from_dict({
+ "icon": "#5fdfdf bold", # cyan brand color
+ "software": f"{accent_hex} bold",
+ "bracket": "#585858",
+ "context": "#bcbcbc",
+ "arrow": "#808080",
+ # Completion menu
+ "completion-menu.completion": "bg:#303030 #bcbcbc",
+ "completion-menu.completion.current": f"bg:{accent_hex} #000000",
+ "completion-menu.meta.completion": "bg:#303030 #808080",
+ "completion-menu.meta.completion.current": f"bg:{accent_hex} #000000",
+ # Auto-suggest
+ "auto-suggest": "#585858",
+ # Bottom toolbar
+ "bottom-toolbar": "bg:#1c1c1c #808080",
+ "bottom-toolbar.text": "#808080",
+ })
+
+ # โ”€โ”€ Messages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def success(self, message: str):
+ """Print a success message with green checkmark."""
+ icon = self._c(_GREEN + _BOLD, "โœ“")
+ print(f" {icon} {self._c(_GREEN, message)}")
+
+ def error(self, message: str):
+ """Print an error message with red cross."""
+ icon = self._c(_RED + _BOLD, "โœ—")
+ print(f" {icon} {self._c(_RED, message)}", file=sys.stderr)
+
+ def warning(self, message: str):
+ """Print a warning message with yellow triangle."""
+ icon = self._c(_YELLOW + _BOLD, "โš ")
+ print(f" {icon} {self._c(_YELLOW, message)}")
+
+ def info(self, message: str):
+ """Print an info message with blue dot."""
+ icon = self._c(_BLUE, "โ—")
+ print(f" {icon} {self._c(_LIGHT_GRAY, message)}")
+
+ def hint(self, message: str):
+ """Print a subtle hint message."""
+ print(f" {self._c(_DARK_GRAY, message)}")
+
+ def section(self, title: str):
+ """Print a section header."""
+ print()
+ print(f" {self._c(self.accent + _BOLD, title)}")
+ print(f" {self._c(_DARK_GRAY, _H_LINE * len(title))}")
+
+ # โ”€โ”€ Status display โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def status(self, label: str, value: str):
+ """Print a key-value status line."""
+ lbl = self._c(_GRAY, f" {label}:")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def status_block(self, items: dict[str, str], title: str = ""):
+ """Print a block of status key-value pairs.
+
+ Args:
+ items: Dict of label -> value pairs.
+ title: Optional title for the block.
+ """
+ if title:
+ self.section(title)
+
+ max_key = max(len(k) for k in items) if items else 0
+ for label, value in items.items():
+ lbl = self._c(_GRAY, f" {label:<{max_key}}")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def progress(self, current: int, total: int, label: str = ""):
+ """Print a simple progress indicator.
+
+ Args:
+ current: Current step number.
+ total: Total number of steps.
+ label: Optional label for the progress.
+ """
+ pct = int(current / total * 100) if total > 0 else 0
+ bar_width = 20
+ filled = int(bar_width * current / total) if total > 0 else 0
+ bar = "โ–ˆ" * filled + "โ–‘" * (bar_width - filled)
+ text = f" {self._c(_CYAN, bar)} {self._c(_GRAY, f'{pct:3d}%')}"
+ if label:
+ text += f" {self._c(_LIGHT_GRAY, label)}"
+ print(text)
+
+ # โ”€โ”€ Table display โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def table(self, headers: list[str], rows: list[list[str]],
+ max_col_width: int = 40):
+ """Print a formatted table with box-drawing characters.
+
+ Args:
+ headers: Column header strings.
+ rows: List of rows, each a list of cell strings.
+ max_col_width: Maximum column width before truncation.
+ """
+ if not headers:
+ return
+
+ # Calculate column widths
+ col_widths = [min(len(h), max_col_width) for h in headers]
+ for row in rows:
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ col_widths[i] = min(
+ max(col_widths[i], len(str(cell))), max_col_width
+ )
+
+ def pad(text: str, width: int) -> str:
+ t = str(text)[:width]
+ return t + " " * (width - len(t))
+
+ # Header
+ header_cells = [
+ self._c(_CYAN + _BOLD, pad(h, col_widths[i]))
+ for i, h in enumerate(headers)
+ ]
+ sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ header_line = f" {sep.join(header_cells)}"
+ print(header_line)
+
+ # Separator
+ sep_parts = [self._c(_DARK_GRAY, _H_LINE * w) for w in col_widths]
+ sep_line = self._c(_DARK_GRAY, f" {'โ”€โ”€โ”€'.join([_H_LINE * w for w in col_widths])}")
+ print(sep_line)
+
+ # Rows
+ for row in rows:
+ cells = []
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ cells.append(self._c(_LIGHT_GRAY, pad(str(cell), col_widths[i])))
+ row_sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ print(f" {row_sep.join(cells)}")
+
+ # โ”€โ”€ Help display โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def help(self, commands: dict[str, str]):
+ """Print a formatted help listing.
+
+ Args:
+ commands: Dict of command -> description pairs.
+ """
+ self.section("Commands")
+ max_cmd = max(len(c) for c in commands) if commands else 0
+ for cmd, desc in commands.items():
+ cmd_styled = self._c(self.accent, f" {cmd:<{max_cmd}}")
+ desc_styled = self._c(_GRAY, f" {desc}")
+ print(f"{cmd_styled}{desc_styled}")
+ print()
+
+ # โ”€โ”€ Goodbye โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def print_goodbye(self):
+ """Print a styled goodbye message."""
+ print(f"\n {_ICON_SMALL} {self._c(_GRAY, 'Goodbye!')}\n")
+
+ # โ”€โ”€ Prompt toolkit session factory โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def create_prompt_session(self):
+ """Create a prompt_toolkit PromptSession with skin styling.
+
+ Returns:
+ A configured PromptSession, or None if prompt_toolkit unavailable.
+ """
+ try:
+ from prompt_toolkit import PromptSession
+ from prompt_toolkit.history import FileHistory
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
+ from prompt_toolkit.formatted_text import FormattedText
+
+ style = self.get_prompt_style()
+
+ session = PromptSession(
+ history=FileHistory(self.history_file),
+ auto_suggest=AutoSuggestFromHistory(),
+ style=style,
+ enable_history_search=True,
+ )
+ return session
+ except ImportError:
+ return None
+
+ def get_input(self, pt_session, project_name: str = "",
+ modified: bool = False, context: str = "") -> str:
+ """Get input from user using prompt_toolkit or fallback.
+
+ Args:
+ pt_session: A prompt_toolkit PromptSession (or None).
+ project_name: Current project name.
+ modified: Whether project has unsaved changes.
+ context: Optional context string.
+
+ Returns:
+ User input string (stripped).
+ """
+ if pt_session is not None:
+ from prompt_toolkit.formatted_text import FormattedText
+ tokens = self.prompt_tokens(project_name, modified, context)
+ return pt_session.prompt(FormattedText(tokens)).strip()
+ else:
+ raw_prompt = self.prompt(project_name, modified, context)
+ return input(raw_prompt).strip()
+
+ # โ”€โ”€ Toolbar builder โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def bottom_toolbar(self, items: dict[str, str]):
+ """Create a bottom toolbar callback for prompt_toolkit.
+
+ Args:
+ items: Dict of label -> value pairs to show in toolbar.
+
+ Returns:
+ A callable that returns FormattedText for the toolbar.
+ """
+ def toolbar():
+ from prompt_toolkit.formatted_text import FormattedText
+ parts = []
+ for i, (k, v) in enumerate(items.items()):
+ if i > 0:
+ parts.append(("class:bottom-toolbar.text", " โ”‚ "))
+ parts.append(("class:bottom-toolbar.text", f" {k}: "))
+ parts.append(("class:bottom-toolbar", v))
+ return FormattedText(parts)
+ return toolbar
+
+
+# โ”€โ”€ ANSI 256-color to hex mapping (for prompt_toolkit styles) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+_ANSI_256_TO_HEX = {
+ "\033[38;5;33m": "#0087ff", # audacity navy blue
+ "\033[38;5;35m": "#00af5f", # shotcut teal
+ "\033[38;5;39m": "#00afff", # inkscape bright blue
+ "\033[38;5;40m": "#00d700", # libreoffice green
+ "\033[38;5;55m": "#5f00af", # obs purple
+ "\033[38;5;69m": "#5f87ff", # kdenlive slate blue
+ "\033[38;5;75m": "#5fafff", # default sky blue
+ "\033[38;5;80m": "#5fd7d7", # brand cyan
+ "\033[38;5;208m": "#ff8700", # blender deep orange
+ "\033[38;5;214m": "#ffaf00", # gimp warm orange
+}
diff --git a/renderdoc/agent-harness/setup.py b/renderdoc/agent-harness/setup.py
new file mode 100644
index 000000000..bc095a54a
--- /dev/null
+++ b/renderdoc/agent-harness/setup.py
@@ -0,0 +1,33 @@
+"""Setup for cli-anything-renderdoc package."""
+
+from setuptools import setup, find_namespace_packages
+
+setup(
+ name="cli-anything-renderdoc",
+ version="0.1.0",
+ description="CLI harness for RenderDoc graphics debugger",
+ long_description=open("cli_anything/renderdoc/README.md").read(),
+ long_description_content_type="text/markdown",
+ author="cli-anything",
+ packages=find_namespace_packages(include=["cli_anything.*"]),
+ python_requires=">=3.10",
+ install_requires=[
+ "click>=8.0",
+ ],
+ extras_require={
+ "test": ["pytest>=7.0"],
+ },
+ entry_points={
+ "console_scripts": [
+ "cli-anything-renderdoc=cli_anything.renderdoc.renderdoc_cli:main",
+ ],
+ },
+ package_data={
+ "cli_anything.renderdoc": ["skills/*.md", "README.md", "native/*.pyd", "native/*.dll"],
+ },
+ classifiers=[
+ "Programming Language :: Python :: 3",
+ "License :: OSI Approved :: MIT License",
+ "Topic :: Software Development :: Debuggers",
+ ],
+)