mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-30 02:21:12 +00:00
Compare commits
156
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6e0b882691 | ||
|
|
6c52bfb030 | ||
|
|
6059d701e2 | ||
|
|
d0a1c21a4e | ||
|
|
4fde342db1 | ||
|
|
a17edafe3b | ||
|
|
3cd97c3cc0 | ||
|
|
c504eb8fc8 | ||
|
|
0f9a6e1e11 | ||
|
|
e24fa6d42f | ||
|
|
c46611ff9d | ||
|
|
29a5cd70c0 | ||
|
|
15b11b4be8 | ||
|
|
690c756037 | ||
|
|
5c1efdb517 | ||
|
|
413c46545d | ||
|
|
0565e0ac37 | ||
|
|
a74ad2da44 | ||
|
|
fc358d0525 | ||
|
|
e502559470 | ||
|
|
06cd29a9a4 | ||
|
|
b49b0d9696 | ||
|
|
5a53fe1fd5 | ||
|
|
0c8a583378 | ||
|
|
6fbe856b4e | ||
|
|
084714739f | ||
|
|
23f73ee906 | ||
|
|
33a3ec2329 | ||
|
|
84dd9e2df5 | ||
|
|
2dc58a3b25 | ||
|
|
8d7c3bf66c | ||
|
|
394525b8d0 | ||
|
|
5acabd2f6e | ||
|
|
6957389fef | ||
|
|
147888c125 | ||
|
|
d649610b7b | ||
|
|
7f241ad170 | ||
|
|
97947085bf | ||
|
|
f5aed211b5 | ||
|
|
49e98cd684 | ||
|
|
df7a83c734 | ||
|
|
710103c70a | ||
|
|
bddd6f0030 | ||
|
|
daca10b4fb | ||
|
|
441fec14c8 | ||
|
|
9dd8f4f916 | ||
|
|
c9388313e4 | ||
|
|
073aa40a97 | ||
|
|
142fec28a2 | ||
|
|
a1fcd96836 | ||
|
|
26003c37e2 | ||
|
|
05b27f886f | ||
|
|
86ebd5c12c | ||
|
|
73cee37ee3 | ||
|
|
10238c33b4 | ||
|
|
5a8aa63835 | ||
|
|
c0698e9fd4 | ||
|
|
75f2ed8c3c | ||
|
|
9f6fef064c | ||
|
|
94a22926d2 | ||
|
|
f6bec97548 | ||
|
|
638673a173 | ||
|
|
1e0ffb642c | ||
|
|
b88fb86dbc | ||
|
|
7feebe38f6 | ||
|
|
b8d709fed0 | ||
|
|
f3eadff31c | ||
|
|
c4ceadc39e | ||
|
|
00c270062b | ||
|
|
00782e62e9 | ||
|
|
961cf7e26c | ||
|
|
4389f74b2b | ||
|
|
0ab348cb5d | ||
|
|
46e7135f6c | ||
|
|
784e1ea439 | ||
|
|
bff53517be | ||
|
|
6898077c20 | ||
|
|
49585b92b0 | ||
|
|
c2f5652694 | ||
|
|
41b755014a | ||
|
|
9d5ecf39e4 | ||
|
|
d910e43df3 | ||
|
|
c0aaaa005b | ||
|
|
69242d1215 | ||
|
|
808c5d17c5 | ||
|
|
23d631e3c7 | ||
|
|
64f9b1dcb5 | ||
|
|
740df46b10 | ||
|
|
a648cdecc7 | ||
|
|
911c27f62b | ||
|
|
9b9c3c63ee | ||
|
|
b16bdc1d4a | ||
|
|
340cd1deec | ||
|
|
ab7863142e | ||
|
|
21700c2869 | ||
|
|
a4026459d9 | ||
|
|
80fb4cc1f6 | ||
|
|
77af218878 | ||
|
|
da82407073 | ||
|
|
2e55cf2259 | ||
|
|
4cb858e6f5 | ||
|
|
b36e397681 | ||
|
|
5bc4ff5cf4 | ||
|
|
5e204bd883 | ||
|
|
620019564b | ||
|
|
36a0f3f6c5 | ||
|
|
29c8a29051 | ||
|
|
6db66dc4a4 | ||
|
|
5c2e2c9b63 | ||
|
|
77dd9ffef3 | ||
|
|
abecde1c39 | ||
|
|
e532fc56ba | ||
|
|
9239ba6551 | ||
|
|
ef58b18147 | ||
|
|
2deada1f9d | ||
|
|
65eef5b08e | ||
|
|
4c5cd55884 | ||
|
|
ec3dea9942 | ||
|
|
1fed04a80c | ||
|
|
a9efeffc6f | ||
|
|
365b411fed | ||
|
|
1b4b1bf7d7 | ||
|
|
aeac1892c1 | ||
|
|
a9674bf9c7 | ||
|
|
eee9a4fcdc | ||
|
|
fe28c5c2af | ||
|
|
e21f41ae24 | ||
|
|
04148f77f8 | ||
|
|
5a6e786850 | ||
|
|
34f744aa5d | ||
|
|
afc093ee54 | ||
|
|
224586917f | ||
|
|
2af3e7d10a | ||
|
|
17e2e2a835 | ||
|
|
3ec40ba7fb | ||
|
|
b3aad0d948 | ||
|
|
277edd592a | ||
|
|
d4996ba9fd | ||
|
|
ca2b48ef83 | ||
|
|
dc41f00cb3 | ||
|
|
1b04d6e237 | ||
|
|
9116c0a39e | ||
|
|
b96a9b5978 | ||
|
|
27bfa17cb1 | ||
|
|
261d71d8d1 | ||
|
|
f7748387da | ||
|
|
28a9c868e6 | ||
|
|
6cfade83fe | ||
|
|
84f4370227 | ||
|
|
e57046a17d | ||
|
|
79e1906c27 | ||
|
|
d65c12f6a9 | ||
|
|
3f2f2732ed | ||
|
|
7c807d8b3a | ||
|
|
ca2ad143f9 | ||
|
|
0b474941f0 |
No files matched your search
@@ -4,46 +4,103 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
|
||||
|
||||
---
|
||||
|
||||
## 0. Contributor & Agent Task Dispatch (Onboarding & Priority Order)
|
||||
## 0. What to Do When Told "Work"
|
||||
|
||||
Whenever a user points their agent at BetterXen to contribute, get started, or pick work (even with a short prompt like *"help me contribute"* or *"what should we work on?"*), walk through preflight and then select work in the **strict 3-tier priority order** below:
|
||||
Collaborators point their agent at this repository and say "work" (or "contribute", "continue", "what next?"). That is a complete instruction. Do not ask what to work on: follow this section. The method behind it is in [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md).
|
||||
|
||||
1. **Preflight host & tools:**
|
||||
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
|
||||
- If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
|
||||
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`).
|
||||
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor` to report Apple Silicon, Rosetta 2, CrossOver, and toolchain readiness.
|
||||
- Verify whether the user has push access or needs a fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
|
||||
2. **Select work in strict priority order:**
|
||||
- **Priority 1 (Highest) — Handle your own claimed PRs with requested changes or review feedback:**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,reviews,statusCheckRollup,mergeStateStatus
|
||||
```
|
||||
Inspect comments and reviews (`gh pr view <pr> --repo MacosPorters/betterxen --comments` and `gh api repos/MacosPorters/betterxen/pulls/<pr>/comments`). If any of the user's open/claimed PRs has `CHANGES_REQUESTED`, unresolved reviewer feedback, failing CI, or merge conflicts, **address that PR first before starting new work**: check out the PR branch, resolve every review item, re-run Section 8 checks, push the DCO-signed update (with the user's authorization, per Section 7), and summarize how each comment was addressed.
|
||||
- **Priority 2 — Pick an unclaimed open issue:**
|
||||
If Priority 1 is clear, query open issues (preferring `status: ready` in the active milestone, then other actionable open issues):
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --json number,title,labels,assignees
|
||||
gh issue list --repo MacosPorters/betterxen --state open --json number,title,labels,assignees
|
||||
```
|
||||
Inspect comments and open PRs on candidate issues to filter out any issue with an active claim (< 7 days old) or open PR. Present the unclaimed options in plain English (recommending 1–2 good matches) and confirm with the user before coding.
|
||||
- **Priority 3 — Review & independently verify open PRs needing review:**
|
||||
When Priority 1 is clear and no unclaimed open issues remain (or the user asks to help unblock the queue), query open non-draft PRs by other contributors that still need review/verification:
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,headRefName,reviewDecision,isDraft
|
||||
```
|
||||
Fetch a candidate PR (`reviewDecision` empty or `REVIEW_REQUIRED`) into an isolated worktree, independently verify its contract and implementation per Section 5, run the Section 8 checks locally (including live CrossOver / D3DMetal runs where available), and draft an honest evidence-backed review for user approval before posting.
|
||||
3. **Claim & isolate (for Priority 2 issue work):**
|
||||
- Post `Claiming — branch: track-<a..f>/<issue>-<slug>` on the chosen issue and create that branch (or `git worktree`) off `origin/main`.
|
||||
4. **Implement strictly in scope:**
|
||||
- Read the full issue body (`gh issue view <issue> --repo MacosPorters/betterxen`) and the relevant contracts in `abi/defs/` and `abi/include/`.
|
||||
- Edit **only** files inside the issue's **Exclusive file scope** (plus `CHANGELOG.md`). Add new synthetic C++ conformance tests under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake).
|
||||
5. **Verify locally (including hosts without CrossOver):**
|
||||
- Run every command in Section 8 and fix all warnings/failures before stopping.
|
||||
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (cross-compiling the 16 mingw-w64 C++ shim DLLs, building the Rust `bx_shader_bridge.dll` with `cargo`, and verifying the exact exports of all 17 PE32+ DLLs), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
|
||||
6. **Review & submit PR:**
|
||||
- Present a concise summary of changes and exact verification outputs, and ask explicit user permission before running `git commit -s` (DCO sign-off, zero AI trailers), pushing, and opening a PR (`Closes #<issue>`).
|
||||
- After opening the PR, watch CI (`gh pr checks --watch`) until both `Hybrid build and shim checks` and `Repository hygiene` pass.
|
||||
**"Work" authorizes, for the one item you pick:** opening a draft pull request, posting a review, committing with DCO sign-off, and pushing a branch. It does not authorize merging your own person's pull request, changing rules, or anything marked `needs-human`. A more specific instruction from your person always wins.
|
||||
|
||||
### Step 1 — Preflight: make the machine ready yourself
|
||||
|
||||
```sh
|
||||
cargo build --locked -p bx-cli && target/debug/bx-cli preflight
|
||||
```
|
||||
|
||||
`bx-cli preflight` must print `Ready to work.` It requires **all** of:
|
||||
|
||||
| Required | How it is found |
|
||||
| --- | --- |
|
||||
| An Apple Silicon Mac with CrossOver 26.3+, D3DMetal and `mingw-w64` | Checked on the host |
|
||||
| **The project-authorized target build** | Found and saved by `bx-cli setup --find` |
|
||||
| **The GDK** (headers and compilers, under the project's authorization) | Found and saved by `bx-cli setup --find` |
|
||||
| **The Ghidra results of the target build** (the static-analysis run: `RUN_REPORT.md`, `exports/`, `decompiled/`) covering its executable | Found and saved by `bx-cli setup --find` |
|
||||
| At least 10 GiB of free disk space | Measured |
|
||||
|
||||
**The target build, the GDK and the Ghidra results are a hard requirement.** An agent that lacks even one of them does not work on this repository at all: no code, tests, reviews, merges, issues or documentation.
|
||||
|
||||
**If preflight fails, fix it yourself and run it again.** Your person said "work"; do not hand the setup back to them.
|
||||
|
||||
| `MISSING` line | What you do |
|
||||
| --- | --- |
|
||||
| Target build, GDK, Ghidra results | `target/debug/bx-cli setup --find`. It searches the home folder, recognises the GDK by its header, the build by its structure (never by name) and the Ghidra results by their layout and the program they cover, and saves all three. |
|
||||
| `mingw-w64 g++` (also `cmake`, `gh`) | `brew install mingw-w64 cmake gh`. Being told to "work" authorizes installing these three. |
|
||||
| Free disk space | Remove your own scratch: build folders and scratch bottles of worktrees you created. Never another session's files. |
|
||||
|
||||
**Stop only for what an agent cannot supply**, and say exactly which:
|
||||
|
||||
- the host is not an Apple Silicon Mac;
|
||||
- CrossOver is not installed (it is licensed software; do not install it);
|
||||
- `setup --find` reports that the target build, the GDK or the Ghidra results covering the build are not on this machine, or found more than one distinct build (which build to use is your person's choice: they run `bx-cli setup --target-exe <path>` once).
|
||||
|
||||
In those cases stop and do not work around it: no fixes, tests, reviews, merges or documentation "for someone else to verify". Work here is found by running the target build, located in the Ghidra results and checked against the GDK; an agent without all three is guessing.
|
||||
|
||||
Also check `git`, `gh` (`gh auth status`; if not logged in, ask the user to run `gh auth login`), `cargo`, `cmake` and `python3`; verify push access or fork (`gh repo fork MacosPorters/betterxen --remote`); sync with `origin/main`. Work in your own worktree and your own bottle; never use a bottle another session is using.
|
||||
|
||||
`bx-cli setup` remembers the three locations in `~/.config/betterxen/local.conf`, outside every checkout, so it happens once per machine and works in every worktree, shell and agent session. (`BX_TARGET_EXE`, `BX_GDK_ROOT` and `BX_GHIDRA_RESULTS` override it for one command.) Never commit those paths, and never put a path, file name, hash or byte from the target build, the GDK or the Ghidra results into a commit, issue or pull request (Section 6).
|
||||
|
||||
### Step 2 — Pick exactly one thing, in this order
|
||||
|
||||
Take the first that applies.
|
||||
|
||||
1. **Your person's pull requests that need attention.**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,isDraft,reviewDecision,statusCheckRollup,mergeStateStatus
|
||||
```
|
||||
Requested changes, unresolved review comments, failing checks, conflicts, or a draft you opened and have not finished: do that. Resolve every review point, re-run Section 8, push, and reply to each point.
|
||||
|
||||
2. **Review someone else's pull request.**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,reviewDecision,isDraft,createdAt
|
||||
```
|
||||
Take the oldest open, non-draft pull request that your person did not open and that has no current review. Check out its branch, run Section 8 and its new test **twice in a row**, confirm the test fails without the fix, and post an approval or a change request with what you ran. If it is approved, green and not your person's, merge it (Section 7).
|
||||
|
||||
3. **A handoff issue of the current stage.**
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label handoff --label "stage: <current>" --json number,title,labels
|
||||
```
|
||||
A handoff is something a collaborator found and could not finish. The current stage is named on the pinned issue labelled `ladder`. Take the lowest-numbered one that no open pull request mentions, and follow Step 3.
|
||||
|
||||
4. **Run the target build and fix the first thing it stops on.** Run it under the [run protocol](docs/process/working-method.md#run-protocol) and read `bx-cli report`. Take the first signature in the report that no open pull request is titled with or mentions, and follow Step 3. A blocker you can see and fix needs **no issue**: the pull request is the record.
|
||||
|
||||
5. **The run stops on nothing.** Make the stage's gate check (ten runs). If it passes, post the result on the ladder issue and label it `needs-human`; a person confirms the stage change. Then stop.
|
||||
|
||||
**Stop and label `needs-human`** whenever the next step is a decision that is not yours: a decision gate, a licence or provenance question, sources of truth that disagree, or a rule change.
|
||||
|
||||
### Step 3 — Work one blocker
|
||||
|
||||
**Before touching any problem the game shows you, find out whether someone already has it.** This applies every time: to the blocker you picked, and to every further problem you meet along the way (a failed load, a refused request, an assert, a crash). Search by the log event, stub symbol, error code and the files you would change:
|
||||
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --state open --search "<event, symbol or file>" --json number,title,headRefName
|
||||
gh pr list --repo MacosPorters/betterxen --state merged --search "<event, symbol or file>" --limit 10 --json number,title,mergedAt
|
||||
gh issue list --repo MacosPorters/betterxen --state open --search "<event, symbol or file>" --json number,title,labels
|
||||
```
|
||||
|
||||
- **An open pull request covers it:** check out that branch (`gh pr checkout <n>`), run the build with it, and work there: report what you saw on the pull request, and push a fix to its branch or request changes. Do not write a second fix.
|
||||
- **A merged pull request covers it:** sync with `origin/main` and run again before investigating.
|
||||
- **An issue covers it:** take it up from the issue's notes, and link it from your pull request.
|
||||
- **Nothing covers it:** carry on with step 1 below.
|
||||
|
||||
1. **Claim with a draft pull request, before writing the fix.** Branch `track-<a..f>/<slug>` from `origin/main`, push it with an empty commit or the first small change, and open a **draft** pull request titled `[<Stage>] <signature>`. Before opening it, list open pull requests once more; if one now covers the signature, take the next signature instead. A draft with no push for 3 days may be taken over; say so on it.
|
||||
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. Check the contract against the GDK where the GDK covers it.
|
||||
3. **Smallest fix:** only what removes this blocker. Stay inside the track directories it needs (Section 2); a new cross-DLL export goes through an `[ABI]` pull request first.
|
||||
4. **Test:** every contract the fix introduces gets a synthetic conformance test under `tests/conformance/test_<name>/` that fails without the fix and passes twice in a row. The test is what holds on every machine; your run is only why you looked.
|
||||
5. **Verify:** every command in Section 8.
|
||||
6. **Proof:** runs before and after on your machine, every run reported, with the machine and the `main` commit. Another collaborator's machine may never take the path yours took; say which path your runs took.
|
||||
7. **Finish:** fill in the five-part description (Blocker, Contract with its source rank, Fix, Test, Proof), sign off, no AI trailers, mark the pull request ready. Do not wait for CI before moving on.
|
||||
8. **Stop.** The next "work" starts again at Step 2.
|
||||
|
||||
**If you cannot fix what you found** (too large, out of session, or it needs a decision): close your draft, file one **handoff issue** labelled `handoff` and `stage: <name>`, titled `[handoff] <signature>`, with what you saw, what you tried and what is still unknown. That is the only time a blocker gets an issue.
|
||||
|
||||
---
|
||||
|
||||
@@ -58,6 +115,7 @@ Whenever a user points their agent at BetterXen to contribute, get started, or p
|
||||
- `tests/conformance/` — Clean-room synthetic x86-64 PE32+ test binaries (auto-discovered via `test_*/CMakeLists.txt`).
|
||||
- **Retired native-first code:** The earlier native-first workspace was retired from `main` per ADR 0006 and remains preserved permanently at Git tag `native-first-final`. Do not open native-only issues; if hybrid work requires an independent component (such as RDNA 2 decoding), file a focused track issue.
|
||||
- **No unverified compatibility assumptions:** This is an active engineering foundation, not a verified Xbox game compatibility stack. Do not assume CrossOver, Rosetta 2, or D3DMetal provide Xbox runtime behavior without measurement.
|
||||
- **GDK texture libraries (ADR 0010):** Console texture layouts (tiling) and BCPack decompression come from the GDK's own PC libraries, `xg_xs.dll` and `BCPack.dll`, which `bx-cli run` stages for the target build from the configured GDK. Do not reimplement them, and never commit or ship them.
|
||||
|
||||
---
|
||||
|
||||
@@ -115,13 +173,13 @@ _Reserved — policy migration in progress._
|
||||
|
||||
## 7. Claiming, Git Safety & Changelog
|
||||
|
||||
1. **Check before coding (open backlog issues):** When picking an unclaimed backlog issue, read every comment and check open PRs so you never claim over an active claim; reply `Claiming — branch: track-<a..f>/<issue>-<slug>` (stale after 7 days without commits/PR). Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
|
||||
1. **Check before coding (claims):** A blocker is claimed by an open draft pull request titled with its signature (Section 0, Step 3); check open pull requests before opening yours. Every problem met while running the game, not only the one picked, is searched for in open and merged pull requests and open issues before it is investigated; when a pull request covers it, check that branch out and work there (Section 0, Step 3). A draft with no push for 3 days may be taken over. Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
|
||||
2. **Isolate with branches or worktrees:**
|
||||
```sh
|
||||
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
|
||||
git worktree add ../wt-<slug> -b track-<a..f>/<slug> origin/main
|
||||
```
|
||||
3. **Link & sign off:** Reference any related issue (`Closes #<issue>` when applicable) in the PR description and sign off every commit (`git commit -s`, DCO).
|
||||
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user; never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user (being told to "work" authorizes them for the one item picked, Section 0); never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
5. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
|
||||
|
||||
### Merge eligibility
|
||||
|
||||
@@ -10,10 +10,53 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- **Check for existing work before investigating any problem the game shows** (AGENTS.md Section 0 Step 3 and Section 7, `docs/process/working-method.md`). Every problem met while running the game, not only the picked blocker, is searched for in open and merged pull requests and open issues by its log event, stub symbol, error code and files. An open pull request that covers it is checked out and worked on, never duplicated. Prompted by a duplicate fix for physical-page DirectStorage requests made alongside #707.
|
||||
- **The Ghidra results of the target build are required to work on the repository**, like the target build and the GDK (AGENTS.md Section 0, `docs/process/working-method.md`). An agent that lacks any of the three does not work on the repository. `bx-cli preflight` adds a `Ghidra results` row: present, and covering the configured target build's executable. `bx-cli setup --ghidra-results <dir>` saves them, and `setup --find` finds them by layout (`RUN_REPORT.md`, `decompiled/`, `exports/*/manifest.json` naming the program, `functions.csv`). `BX_GHIDRA_RESULTS` overrides the setting for one command. Unit tests cover an unset setting, a folder that isn't a results folder, results for another program, and results covering the target.
|
||||
- **Roadmap, Picture stage: BetterXen writes its own shader translator** (repository owner's decision, 2026-11-29). The step that said to vendor the upstream GFX10-to-DXIL translator now describes a translator of our own in `shader-transpiler/`: one rule per instruction, control flow as numbered blocks, each rule checked against the console compiler.
|
||||
- **A collaborator only has to say "work"** (AGENTS.md §0, step 1). When `bx-cli preflight` fails, the agent makes the machine ready itself: the new `bx-cli setup --find` searches the home folder, recognises the GDK by its header and the target build by its structure (a large PE32+ file that imports `d3d12_xs.dll`; never by name), ignores the GDK's own tools, treats byte-identical copies as one build and keeps the copy with its imported DLLs beside it, and saves both settings. The agent may install `mingw-w64`, `cmake` and `gh` with Homebrew and free disk space by removing its own scratch. It stops only for what it cannot supply: no Apple Silicon Mac, no CrossOver, the build or the GDK not on the machine, or more than one distinct build.
|
||||
- **Working rules: the pull request is the unit of work, and the target build and the GDK are required** (AGENTS.md §0, [working method](docs/process/working-method.md)). An agent told to "work" first runs the new `bx-cli preflight`, which fails unless the host is an Apple Silicon Mac with CrossOver, D3DMetal and `mingw-w64`, the target build's executable and the GDK folder are known, and 10 GiB of disk is free. A collaborator records the two locations once with the new `bx-cli setup --target-exe <path> --gdk-root <folder>`, which checks them and keeps them in `~/.config/betterxen/local.conf`, outside the repository (`BX_TARGET_EXE` and `BX_GDK_ROOT` override it). If preflight fails the agent stops and does no work. A blocker the agent can fix no longer gets an issue: it is claimed by a draft pull request titled with its run-report signature. Issues are kept for handoffs (label `handoff`), decisions for a person, and the ladder status. Claims by comment and the 7-day stale window are gone; an idle draft may be taken over after 3 days.
|
||||
- **BetterXen is no longer a clean-room project** (repository owner's decision, #650). `CONTRIBUTING.md` now says that material the project is authorized to use, such as the GDK and its compilers, may be used and that facts derived from it may be committed, while the material and its outputs are never committed. Leaked or unauthorized material remains forbidden.
|
||||
- **Roadmap and working method (proposed).** `docs/roadmap.md` replaces the subsystem milestones M3–M6 with stages the project-authorized target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), each judged on ten recorded runs on a 16 GB Mac, with decision gates for the D3DMetal back end, reference images, memory and frame rate. [docs/process/working-method.md](docs/process/working-method.md) describes the blocker queue for a team that works by telling coding agents to "work": where state lives, the order of work (own pull requests, review, one blocker, discover), the run protocol, source ranks and pull-request shape. AGENTS.md §0 is rewritten to match.
|
||||
- `xg_xs.dll` follows the documented XG contract titles call: `XG_RESOURCE_DESC` and the 14-method `XGTextureAddressComputer`, from the authorized GDK documentation. Behaviour:
|
||||
- **Linear layouts:** every texture is laid out linearly with BetterXen's documented alignment.
|
||||
- **`SW_64KB_S` addressing** for a texture that fits one 64 KiB tile.
|
||||
- **Other requested swizzle modes** are laid out linearly and reported as `LINEAR`, logged once per mode. Refusing them crashed a title that does not check the result.
|
||||
- **`GetResourceTiling`** reports the D3D12 standard 64 KB tile shapes and a packed mip tail. 3D resources get the 3D tile shapes with depth tiles; 1D textures and buffers get 64 KiB tiles.
|
||||
- **Limits:** descriptions past the public D3D12 limits (16384 for 1D/2D, 2048 for 3D and array sizes) are refused rather than truncated, and so is a 3D subresource past the mip count.
|
||||
|
||||
The earlier clean-room interface is removed: `xg_xs.cpp`, `xg_texture.h` and `test_xg_xs`. `test_xg_xbox` (42 checks) replaces it, and stage 13 of `test_integration_boot` uses the documented contract.
|
||||
- `BXVM` configuration writes the output `cpu_pointer` before changing shared configuration or releasing a cached backing heap. If that write fails after the accessibility check, the call returns `E_INVALIDARG` without applying the configuration.
|
||||
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
|
||||
|
||||
### Added
|
||||
- **Unattended runs get past input screens and continuable asserts** (`docs/testing/target-build-review.md`, Diagnostics).
|
||||
- **`GameInput.dll`:** `BX_INPUT_SCRIPT=A@40,DOWN@50.5,...` presses gamepad buttons at given seconds after the first reading, each for 300 ms, without window focus. Each press, and each entry it cannot read, is logged (`input_script`).
|
||||
- **`bx_runtime_veh.dll`:** `BX_CONTINUE_ASSERTS=1` steps over an `int3` in the title's own executable instead of letting it reach the crash reporter, and logs each address once (`assert_continued`). An `int3` anywhere else is left alone.
|
||||
- **Tests:** `test_gameinput_script` (readings at fixed times carry exactly the scripted buttons, and unreadable entries are skipped) and `test_veh_continue_asserts` (the executable's `int3` is stepped over twice; one outside any module is not). Both fail on `main`'s shims and pass twice with these.
|
||||
- **The GDK's texture libraries at run time (ADR 0010).** Console texture layouts and BCPack come from the GDK's own PC libraries instead of being reimplemented.
|
||||
- **`bx-cli run`** stages the configured GDK's `xg_xs.dll` (in place of the `xg_xs` shim) and `BCPack.dll` (named to `XCRDAPI.dll` through `BX_BCPACK_DLL`) when the executable is the configured target build, or with `--gdk-libraries`; `--no-gdk-libraries` turns it off. The libraries are recognised by their exports (`gdk_libs.rs`), copied into a temporary shim folder for the run, and never committed. Conformance tests keep BetterXen's own shims.
|
||||
- **`d3d12_xs.dll`** answers `GetResourceAllocationInfo`, `GetResourceAllocationInfo1` and `GetResourceAllocationInfo2` for console texture layouts (`Layout >= 0x100`) with the GDK's XG size and base alignment (`gdk_xg.cpp`), other descriptions with the host's answer, laid out in order at their alignments. It enables XG's exclusive locking at device creation, since the title and the shim both create XG texture computers. Without the GDK's XG, sizes stay as before and the run log says so (`gdk_xg`).
|
||||
- **Tests:** `test_d3d12_gdk_xg_sizes` loads a stand-in XG library with answers the test computes (not Microsoft's code) and checks the sizes, alignments, the two-description layout and the locking. On the previous `d3d12_xs.dll` 6 checks fail; with this change it passes twice. `bx-cli` unit tests cover recognising the libraries by their exports and merging them beside the shims.
|
||||
- **Measured** on the target build (Apple Silicon, CrossOver 26.3, offline, scripted input): the launcher staged both libraries; XG answered 48 console-layout size queries; with #709, 0 page-destination errors, 0 zlib failures and 0 refused BCPack requests. 14 partial reads of compressed blocks remain, so the allocation size is not the only place the title gets a short size (#708 stays open).
|
||||
- `GameInput.dll` exposes one keyboard-backed gamepad through v0 blocking enumeration and current readings. Enter or Space maps to A, Escape or Backspace to B, arrow keys to the D-pad, WASD and IJKL to the two sticks, Q/E to shoulders, Z/C to triggers, F/H to stick clicks, X/Y to the matching face buttons, and P/Tab to Menu/View. Input returns to neutral when another application owns the foreground.
|
||||
- **D3DMetal capability checks for translated console shaders** (#671). `test_d3dmetal_translator_caps` measures, against the host D3D12 runtime, the features a translator of console code needs: SM 6.6 descriptors fetched by index (UAV, raw and typed SRVs, texture and sampler) run correctly; a 64-lane wave emulated over a 64-thread group gives the 64-lane answers through groupshared memory and through merged 32-lane host waves; amplification and mesh shaders draw correctly. With the 64-bit atomic results of `test_d3dmetal_gpu_limits` (native 64-bit atomics are not run even though D3DMetal reports support; the lock emulation with a 1024 cap is exact), no need is blocked. Results are in [D3DMetal GPU limits](docs/research/d3dmetal-gpu-limits.md#capability-checks-for-translated-console-shaders-671).
|
||||
- `xgameruntime.dll` serves `XGameSaveGetContainerInfo` (slot 13) and `XGameSaveEnumerateContainerInfoByName` (slot 15) on `IXGameSaveImpl` (#667). `XGameSaveGetContainerInfo` reads container metadata without loading blob payloads and, when the named container does not exist, succeeds without invoking the callback (source rank 3 inference). `XGameSaveEnumerateContainerInfoByName` filters containers by name prefix (treating `nullptr` or empty prefix as all containers), sorts by name, and stops early when the callback returns `false`. `test_xgameruntime_saves` checks both slots through `QueryApiImpl`.
|
||||
- `xgameruntime.dll` serves `XAsyncRun`, `XTaskQueueCreateComposite`, `XTaskQueueGetPort` and `XTaskQueueDuplicateHandle` through `IXGameRuntimeCore` slots 6, 13, 14 and 15 (#666). `XAsyncRun` runs the title's work callback on the block's work port and completes the block with its result. A duplicated queue handle shares the queue, and only the last close shuts its lanes down. A composite queue forwards each port to the port it was made from, and an async block's completion returns through the queue the block named. A project-authorized target build uses these for its save-game work and exited when `XAsyncRun` was unimplemented. `test_xgameruntime` checks all four through `QueryApiImpl`.
|
||||
- `bx-cli report <log.jsonl>...` (#664, part 1): a run report per log (one log is one run) and a summary across runs. Per run: how it ended, the frames presented (a lower bound), every unimplemented call with its count, faults whose innermost frame is in a BetterXen module, and pipelines by kind. The summary counts clean runs and lists each blocker signature with the number of runs that hit it; blocker issues are titled with those signatures. `bx-cli run` now appends a `run_end` record to its log (exited with a status, timeout, signal or launch failure), which the report reads. A log without it has an unknown outcome and is never counted as clean.
|
||||
- `xgameruntime.dll` serves `XUserDuplicateHandle` through `IXUser` slot 3 (#680). A duplicate is a new handle to the one offline user; each handle is closed on its own, and `XUserCompare` returns 0 for any two valid handles of that user. A project-authorized target build duplicates its user handle after sign-in and waited when the slot was unimplemented. `test_xgameruntime` checks the slot through `QueryApiImpl`.
|
||||
- Shader corpus, Phase 0 of the console shader translator (#649). `shader-transpiler/corpus/hlsl/` holds eight BetterXen-authored compute kernels covering integer and float ALU, divergent branches, loops, groupshared memory, wave operations, atomics and system values. `scripts/shader-corpus/build.sh` compiles each one locally with the console `xdxc` (a title-style container: `DXIL` plus `ACCC`/`FSPX`), the console PIX compiler (Microsoft's ISA listing) and the public PC DXC (DXIL for a D3DMetal reference run). `extract_code.py` then takes the code from the `FSPX` kind-6 section, skips the leading `v_nop_xbox_data` words and disassembles it with LLVM's public `gfx1030` decoder. All eight kernels build and decode cleanly. The extractor has nine unit tests on synthetic containers that need no GDK. Compiler outputs stay in the git-ignored `target/shader-corpus/`. One open question is recorded: a `v_cmp_class_f16` in the `wave` kernel's ballot sequence.
|
||||
- `docs/research/console-shader-abi.md` and `CLAIM-XBOX-CS-ENTRY-ABI` (class U, not yet independently reproduced): the compute shader entry ABI observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler, used under Microsoft's authorization, on eleven project-authored probes. Compute code is wave64. Root data starts at `s4` in root-parameter order: one SGPR per constant, two per root descriptor address, one per 32-bit table pointer. The thread-group IDs follow the root data, and `s0:s1` holds the root-data address when it overflows. Root buffer descriptors are built inline with no effective bounds check, table buffer descriptors are 32 bytes apart (samplers 16), and the compiler reports the HLSL binding of each descriptor load. No compiler output, binary or documentation text is in the repository. Register roles are inferences, and the ACCC container layout remains unknown.
|
||||
- Opt-in diagnostics in `bx_runtime_veh.dll`, all off by default:
|
||||
- an access-violation context with the memory type and the faulting thread's stack (`BX_VEH_AV_CONTEXT`, `BX_VEH_AV_ALL`);
|
||||
- software write watches over one address, a range or a pointer chain (`BX_VEH_WATCH`, `BX_VEH_WATCH_RANGE`);
|
||||
- software code breakpoints that log string arguments (`BX_VEH_HIT`, `BX_VEH_HIT_ALL`);
|
||||
- an all-threads sampling profiler (`BX_VEH_SAMPLE`).
|
||||
|
||||
Records are bounded, JSON-escaped and UTF-8. A protection change that fails disarms the diagnostic, which is logged, and the guest gets its exception. Detach disarms everything. With the switches unset, nothing runs. `bx-cli run` lets these named switches through its isolated guest environment. `test_veh_diagnostics` covers every mode.
|
||||
- `bx_runtime_veh.dll` records breakpoints (`0x80000003`) and assertion failures (`0xC0000420`) from its vectored handler as `breakpoint_exception` JSONL records with the exception code, module name, module base and RVA. A guest with its own crash reporter replaces the top-level filter installed at attach, so its assertions never reached `unhandled_exception`; the vectored handler runs before the guest's top-level filter and any vectored handler the guest registers last (one it registers first can resume the exception before BetterXen sees it). Module names are written as UTF-8, and `bx-cli trace` notes when the record cap was reached. The records are first-chance (the guest may still handle the exception), handling is unchanged, and at most 16 are written per process. `bx-telemetry` parses them and `bx-cli trace` lists them under "Breakpoint/assert exceptions, first chance".
|
||||
- **Test:** `tests/conformance/test_veh_breakpoint/` replaces the top-level filter and resumes from its own vectored handler, as such a guest does. It raises 21 int3 breakpoints at a labelled site and one `STATUS_ASSERTION_FAILURE`, and requires exactly 16 records, the int3 records at the RVA it computes from the label and its own module base, and no `unhandled_exception`. It fails against the previous `bx_runtime_veh.dll`.
|
||||
- [Target-build bring-up: development cycle and review](docs/testing/target-build-review.md): how contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently.
|
||||
- `xgameruntime.dll` serves the XPackage installation monitor offline: the running package is reported fully installed, launchable and complete. Monitor handles share the mount handles' table, generation and lock: stale handles are rejected, closing twice is harmless, and uninitialize releases them. Progress registrations are accepted, logged and never fired. `XPackageEnumeratePackages` reports this game for `XPackageKind::Game` and no content packages. Both replace stubs that a project-authorized target build calls at startup. The save-container mount path ends with the drive-root separator, and `test_xgameruntime_saves` expects it.
|
||||
- `AcpHal.dll`:
|
||||
- **Shape contexts:** `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` allocate from the APU heap. The layout is the documented `SHAPE_CONTEXTS` (96 bytes; CPU pointers at 24, APU addresses at 72). A second allocation returns `ACP_E_ALREADY_ALLOCATED`.
|
||||
- **`IAcpHal`** has the documented non-COM slot order: `Connect`, `Disconnect`, `SubmitCommand`, `PopMessage`, `GetNumMessages`, `Release`.
|
||||
@@ -61,6 +104,38 @@ remains unsupported.
|
||||
- `d3d12_xs.dll!D3D12ConfigureVirtualMemoryX` now decodes the Xbox virtual-memory configuration (`D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION`) alongside the existing `BXVM` contract. Layout and behaviour follow the authorized GDK documentation of the function and structure: no flags, a GPU page-table size in 4 MB units clamped to 33, a frame-buffer preserve size (0, -1 for the legacy size, or bytes clamped to 64 MiB), and two output addresses, the minimum always 2 GiB and the maximum 159.375 GiB at the default 5 pages. The call fails with `E_FAIL` once a D3D12 device exists. Call-site observation of a project-authorized target build agrees with the documented layout. Inferred, and marked as such: the maximum for other page-table sizes scales linearly (`max_estimated=1` in the log), and a page-table size of 0, an unreadable configuration or unwritable outputs fail with `E_INVALIDARG`. The host sizes no GPU page tables and keeps no cross-process frame buffer, so the path records both (`vmem_config_recorded`, `applied=0 recorded_only=1`), leaves the `BXVM` record and cached backing heap untouched, and still emits `BX_STUB_LOG`. `tests/conformance/test_d3d12_vmem_xbox/` checks the documented outputs, clamps and post-device `E_FAIL`, the refused cases, and that a cached `BXVM` backing heap survives.
|
||||
|
||||
### Fixed
|
||||
- **`XCRDAPI.dll`: physical-page destinations are mapped when the request runs, partial reads of compressed blocks are delivered, and BCPack requests can be decoded.**
|
||||
- **Page array timing:** a title can fill the `DestinationPageArray` of a `DestinationIsPhysicalPages` request after `EnqueueRequest` returns. #707 read the array at enqueue, so such requests failed (in the target build, about 290 per run named page 0). The array is now read, and its pages mapped, when the request runs; they are unmapped once it is fulfilled.
|
||||
- **Partial compressed reads:** a title may ask for only the first `DestinationSize` bytes of a zlib block (in the target build, 8 to 128 KiB blocks read 4 to 16 KiB at a time; 16 failures per run). The whole stream is decoded, its Adler-32 checked, and its first `DestinationSize` bytes delivered; a stream shorter than the destination is still an error. Logged as `dstorage_zlib_partial`.
|
||||
- **BCPack:** a request with `BcpackMode` 1 to 7 is decoded with `BCPackDecompress` from the GDK's own `BCPack.dll` when `BX_BCPACK_DLL` names it (the collaborator's GDK; nothing from the GDK is shipped). Without it, or combined with zlib, BCPack stays refused with `E_NOTIMPL`. Logged as `bcpack_codec` and `dstorage_bcpack_failed`.
|
||||
- **Tests:** `test_xcrdapi_page_destination` (24 checks) adds a page array filled after `EnqueueRequest` and a 4096-byte zlib destination from a 136000-byte stream (exact first part, nothing written past it). Both fail on the previous shim (4 checks) and pass twice with this one. BCPack needs the GDK's decoder, so it is not covered by a conformance test.
|
||||
- **`GetFrameStatisticsX` is implemented** (#701). Slot 81 of the Xbox device table returned `E_NOTIMPL`, which the documented method never returns. It now answers as the authorized GDK documentation describes: frame-event (ORIGIN: wait call, signal and wait return) and present (PresentX call and return) statistics per frame pipeline token for the last 17 frames, in QueryPerformanceCounter ticks; `S_FALSE` when none of the requested types is available; `E_INVALIDARG` for unknown tokens, invalid type sets and invalid list arrangements. Interval, power-scaling, render, display and input statistics have no host source and are never reported; `GPUProcessTime` is 0 (not measured). Test: `test_d3d12_frame_statistics_x`.
|
||||
- **`CreateCommittedResourceX` is implemented** (#696). Slot 76 of the Xbox device table takes a `D3D12XBOX_RESOURCE_DESC`, which is the PC resource description followed by `DccOptions` (authorized GDK header). It now creates the resource from the PC part through the same path as `CreateCommittedResource` (console format translation, the `XMemAlloc` request a title's hook sees); `DccOptions` (a struct of `CompressionLevel` and `ColorTransform`), console colour compression, has no host counterpart; both fields are logged for the first 8 calls and ignored. Until now the slot returned `E_NOTIMPL`, and the target build exited with status 99 about a second after it was refused. `tools/gen_xbox_tables.py` routes the slot to the new entry point; the regenerated table differs only there. Test: `test_d3d12_committed_resource_x`.
|
||||
- `xmem.dll!XMemGetWorkingSetStatistics` takes the documented `(WorkingSetFlags, Statistics)` and fills the documented 120-byte `XMEM_WORKING_SET_STATISTICS` (source: the authorized GDK header). Before, it took `(out_stats, stats_size)` and wrote BetterXen's own 32-byte `bx_xmem_stats_t`. A title calling it as documented had its flags read as the output address and its structure pointer as the size, and the shim zeroed memory at the flags value. A project-authorized target build calls it on a tools-memory path with the tools and kernel-pool flags and treats `FALSE` as fatal; runs have not reached that path yet.
|
||||
- **Values:** the whole structure is written, whatever the flags. `GameLimit` is the title cap, `GameUsed` everything the cap counts (XMem heap, virtual commits, physical pages and external charges), `GameUsedPeak` its highest value and `GameAllocatedPhysicalPageCount` the 64 KiB physical pages. The tools fields are 0, since `XMemIsToolsMemAvailable` is `FALSE`. The counters the host does not have or xmem does not count are 0 (stack, GPU-optimal bandwidth, kernel pool, DirectStorage, frame-preserve buffer, page tables), and so are the reserved words. These values are BetterXen's inference.
|
||||
- **Refusals:** a NULL structure, or flags outside the five `XMEM_WORKING_SET_*` values, fails with `ERROR_INVALID_PARAMETER` and logs `working_set_statistics`. `bx_xmem_get_internal_stats` is unchanged for internal callers.
|
||||
- **Tests:** new `test_xmem_working_set` reads the structure between guard bands at offsets written out from the header, with the tools and kernel-pool flags, `XMEM_WORKING_SET_TITLE` and `XMEM_WORKING_SET_ALL`. Against the previous `xmem.dll` it fails with an access violation inside the call. `test_xmem`, `test_xmem_physical`, `test_xmem_external_charge` and `test_d3d12_placed` use the documented form. `test_xmem_physical` now reads its two aliased page views through `volatile`: the compiler cannot see that they share a page, and after this change it scheduled the read before the write.
|
||||
- **Not covered:** `XMemVirtualQuery` and `XMemTransferMemory` still differ from their documented signatures (#642).
|
||||
- **`XCRDAPI.dll`: DirectStorage requests can write into physical pages** (#705). With `DestinationIsPhysicalPages` (bit 21 of `DSTORAGE_REQUEST_OPTIONS`), the destination of an Xbox request is an array of 64 KB page numbers from `XMemAllocatePhysicalPages` and a 16-bit offset into the first page, at +0x08 and +0x10 (authorized GDK header). `IDStorageQueueX::EnqueueRequest` refused such requests with `E_NOTIMPL`, and the target build stopped at a breakpoint about two milliseconds later (exit status 3). The request now maps its pages through `xmem.dll`'s `XMemMapPhysicalPages` with a NULL address (the existing BetterXen extension) into a span of its own, writes the destination there, file or memory source, plain or zlib, and unmaps the span once it is fulfilled; the pages are sections, so the title's views see the bytes. A physical-page source (`SourceIsPhysicalPages`) is still refused and logged as `EnqueueRequest_physical_page_source`. Test: `test_xcrdapi_page_destination` (19 checks: a zlib file request across three pages given out of order from an offset, an uncompressed memory request across a page boundary, an unallocated page number, the refused source form).
|
||||
- **`d3d12_xs.dll`: index and vertex data bound from plain title memory are drawn.** A title keeps such data in its own memory with no Direct3D resource, and may write it after recording the draw. A bound range now gets a CPU-writable host buffer (once; later ranges inside it reuse it) and every range bound on a list is copied from the title memory when the list is submitted (`bx_xbox_bind_title_memory`, `placed_x.cpp`). This replaces leaving such bindings empty; only memory that is not readable is still left empty and logged as unimplemented. Tests: `test_d3d12_title_memory_geometry` (26 checks, pixel readback, data written after recording and changed between submissions); `test_d3d12_unbacked_buffers` now covers the unreadable case.
|
||||
- **`d3d12_xs.dll`: console rectangle lists are drawn.** `D3D_PRIMITIVE_TOPOLOGY_RECTLIST` (17) and the pipeline topology type `D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT` (19) are Xbox extensions (GDK `d3d12_xs.h`): three vertices per rectangle, the fourth corner `v0 + v2 - v1`. The host knew neither value, so a title's full-screen passes drew half a rectangle or nothing. A rectangle list is now drawn as triangle strips (`rect_list.cpp`): the pipeline is created with the triangle type, and a non-indexed draw builds four vertices per rectangle from the title's vertex data and the pipeline's input layout. Indexed rectangle lists and quad lists are not emulated and are logged as unimplemented. Test: `test_d3d12_rect_list` (25 checks, pixel readback).
|
||||
- **`bx_runtime_veh.dll`: a CLWB range loop completes in one exception.** A title flushes an address range with `clwb [reg]; add reg, 0x40; cmp reg, <reg64>; jbe|jb`; each CLWB trapped under Rosetta, about 94,000 exception round trips per 6 MiB buffer. CLWB changes no register, flag or memory, so the handler now advances the pointer register to the last value the loop would have used and the title's own add/cmp/jcc leaves the loop. Other forms keep the per-instruction path. Test: `test_veh_clwb_loop` (15 checks; without the fix the four loop cases take one exception per line).
|
||||
- **Committed render targets request the console's size from XMemAlloc** (#695). The console lays out a 2D render-target or unordered-access texture with one mip and one sample in 64 KB tiles (64KB_R_X for every size: 128x128 elements at 4 bytes, 128x64 at 8, 64x64 at 16, 256x128 at 2, 256x256 at 1; authorized GDK XG library), and a title that hooks XMemAlloc sizes its pool for those requests and asserts that less than 2 MB is left over. `d3d12_xs.dll` requested the host's size instead, 1920x1080 RGBA8 as 128 pages where the console takes 135, and on the Series S path the target build stopped on that assertion. The XMemAlloc request for those textures is now the tile size, computed from the title's format; every other resource keeps the host's size, and XG's render-target compression metadata after the tiles (8 KB to 96 KB in the cases measured) is not modelled. `GetResourceAllocationInfo` still answers with the host's size. Test: `test_d3d12_committed_tile_size`.
|
||||
- **The console type is published where a title reads it** (#692). A title can read the REG_DWORD `ConsoleMode` under `HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM` instead of calling `XSystemGetDeviceType`: 0x60 is Series S, 0x64 Series X and 0x68 the Scarlett devkit, and without the value the title takes itself for a PC and sizes its memory for Series X. Wine has no such value, so under the Lockhart profile the target build asked for its Series X memory set and stopped on the 8 GiB budget. `bx-cli run` writes the value in the selected Wine environment before launching the guest, using the same profile as `XSystemGetDeviceType` (0x60 for Lockhart, 0x64 for Anaconda). `--profile` is matched without regard to case, as the shims match `BX_PROFILE`, and a value other than `lockhart` or `anaconda` is refused, so the two cannot name different consoles. The test `test_console_mode` reads it the way the title does and checks it against the profile and `XSystemGetDeviceType`.
|
||||
- **XCRDAPI holds an xmem guard while accessing title memory** (#668). Replacing a mapped view on Windows or Wine can temporarily make pages in that view inaccessible. DirectStorage reads and writes that can touch title memory now hold the shared guard while xmem mapping and freeing operations hold it exclusively. A loaded xmem DLL without both guard exports produces a warning. The guard covers DirectStorage accesses through BetterXen. `test_xcrdapi_remap_guard` exercises memory-to-memory stores into a window, zlib streams inflated into it and memory requests reading out of it while it is remapped; accesses by the title's own threads are not covered.
|
||||
- **`d3d12_xs.dll`: an index or vertex binding at a title address without a host buffer no longer crashes the process.** A title binds index and vertex data by address in plain title memory, with no Direct3D resource behind it. The address reached D3DMetal unchanged and it read through a null buffer (`IASetIndexBuffer`). Such a binding is now left empty and logged as unimplemented (`IASetIndexBuffer(title memory without a host buffer)`, likewise `IASetVertexBuffers`); bindings inside resources BetterXen created are translated as before. Supplying the data is separate work. Test: `test_d3d12_unbacked_buffers` (13 checks; without the fix it dies with the same null read).
|
||||
- **`d3d12_xs.dll`: console-only DXGI formats and depth-stencil unordered-access views no longer end the process.** The Xbox Series `DXGI_FORMAT` enumeration has values the PC one lacks (116-120, 189, 190; GDK `d3d12_xs.h`). D3DMetal turns one into an invalid Metal pixel format and Metal aborts, which a target build's crash reporter then turned into either "exit status 5" or a stall with every thread stopped.
|
||||
- **Formats:** `console_formats.h` maps each to the nearest host format (a depth texture is created typeless, each view names the concrete format). The three `GetResourceAllocationInfo` forms, `CreatePlacedResource`, `CreateReservedResource`, the four view-creation methods, the committed-resource forms and the placed (X) resource and view forms translate before the host call.
|
||||
- **Depth-stencil unordered-access views** (allowed on the console, forbidden on PC): the descriptor gets a null view and the call is logged as unimplemented (`CreateUnorderedAccessView(depth-stencil resource)`).
|
||||
- **Limits:** sizes reported for a translated format are the host format's, `GetDesc` reports the host format, and pipeline-state formats are not translated yet.
|
||||
- **Test:** `test_d3d12_console_formats` (21 checks; without the fix the process dies at the first console-only format).
|
||||
- `bx_runtime_veh.dll` completes a `CLZERO` loop in one exception (#665). A title that zeroes memory with `clzero; add rax,0x40; cmp rax,<reg64>; jb` raised one illegal-instruction exception per 64 bytes under Rosetta 2, which stalled a project-authorized target build's frame loop for tens of seconds. When the trapped `CLZERO` is followed by exactly that form, the handler zeroes every remaining line below the limit and leaves `RAX` at the last one, so the title's own `add`/`cmp`/`jb` leaves the loop. The range is zeroed region by region and stops at memory that is not committed and writable, where the next `CLZERO` traps and faults as before. Other loop forms keep the per-instruction path. `test_veh_clzero_loop` checks the memory result and counts the exceptions; it fails on the old handler.
|
||||
- `d3d12_xs.dll` no longer turns `DeserializeGraphicsPipelineStateX`, `DeserializeComputePipelineStateX`, `CreateDerivedGraphicsPipelineStateX` or `CreateDerivedComputePipelineStateX` into null pipelines in null-render mode (`BX_NULL_RENDER=1`) (#669). All four calls now always return `E_NOTIMPL`, clear `*ppv` and log `pipeline_refused` without `; null pipeline returned`, so a title falls back to creating pipelines from shader containers instead of silently receiving null pipelines. `test_d3d12_serialized_pipelines` checks all four slots and their refusal log lines with `BX_NULL_RENDER=1` active alongside a control shader-container null pipeline.
|
||||
- `XCRDAPI.dll` Xbox DirectStorage fixes:
|
||||
- **Zlib requests read the file.** The file handle was not set for them, so every compressed file request failed. The request options are now decoded, and zlib streams are inflated in-tree.
|
||||
- **`AutoSubmitDisabled` is honoured.** Xbox `CreateQueueX` respects `DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled`: a queue with the flag runs nothing before `Submit`, and when it is full the enqueuer waits until `Submit` is called on another thread. A queue without the flag submits by itself once half full.
|
||||
- **Request trace:** `BX_DSTORAGE_TRACE=1`.
|
||||
- **Tests:** `test_xcrdapi_xbox` covers a file-source zlib request and both queue behaviours. Each check fails with its fix reverted.
|
||||
- `xmem.dll` physical page numbers count 4 KiB frames. A 64 KiB page's number is a multiple of 16, and each allocation's numbers start at a multiple of 0x1000 frames. With consecutive numbers, callers that keep `number >> 4` collapsed 16 pages into one, and memory written through one page appeared in others. Physical pages are mapped as runs: one view per run of consecutive pages instead of one per page. On a project-authorized target build, startup went from 36 s to 6 s, under the title's 30-second watchdog. Allocation goes through the title's registered allocation hooks, with one section per physical-page call. A GPU-only reservation with large pages (no CPU access, a `PAGE_GRAPHICS_*` bit set) becomes a mappable placeholder region, so console page-mapping calls can fill it. `BX_XMEM_TRACE=1` logs allocations, frees and maps. `test_xmem_physical` checks the page-number units, and `test_xmem_hooks` checks the hooks.
|
||||
- `d3d12_xs.dll` refuses an Xbox-layout object the host cannot back. If the host object lacked the interface an Xbox table forwards to (on vkd3d, `ID3D12Device10`), `bx_xbox_wrap` returned the PC object, and `D3D12XboxCreateDevice` reported an Xbox-layout device. A title calling Xbox slot numbers would then have reached PC methods. The device and every wrapped family now fail with `E_NOINTERFACE`, logged as `xbox_wrap_refused`. `test_d3d12_xbox_layout` verifies the refusal on such a host and skips (exit 77); it passes on D3DMetal.
|
||||
- `d3d12_xs` validates placement on **every heap and every placement entry point** (#554, #572). `CreatePlacedResource` (slot 29) checked alignment, extent, buffer clear value and the UPLOAD/READBACK initial state only on the backing heap, and `CreatePlacedResource1` (`ID3D12Device8` slot 70) and `CreatePlacedResource2` (`ID3D12Device10` slot 77) were generated pass-throughs with no check and no `kPlacedResourceHeap` retention, so the shim heap wrapper and its xmem charge could be released while a resource placed through them was still alive. All three now share `create_placed_common` in `vmem.cpp`: a null heap or desc, a misaligned offset or a resource past the heap end returns `E_INVALIDARG` with `*out` null and a `placed_resource` log line naming the method, and a shim heap is retained by the resource on all three. `CreatePlacedResource2` takes a barrier layout, so the resource-state rule is not applied to it, and its allocation info comes from `GetResourceAllocationInfo2` without the castable-format list. `tools/gen_proxy.py` gains a `HANDOFF` table that keeps the generated trace and null-host stub and passes the host interface and unmodified arguments to a function declared from the header signature; `proxy_generated.{h,cpp}` are regenerated, and no new vtable slot is patched. `test_d3d12_placed` adds misaligned, aligned-overhang, valid-offset and UPLOAD-state cases on an ordinary heap for each entry point, and runs the heap-charge retention check through all three. Run live under CrossOver 26.3 in a D3DMetal bottle: passes (173 checks, 1 skipped — the 512 MiB pairing check; at `BX_MEM_LIMIT_MB=512`, 189 checks, 0 skipped), including every `CreatePlacedResource2` case. Against the previous shim the new cases fail ten checks there: D3DMetal returned `S_OK` for a misaligned offset, an aligned overhang and an UPLOAD heap in `COPY_DEST` on all three entry points it was asked about, and the slot 70/77 resources dropped the heap charge. Under `bx-cli run` (vkd3d) the fixture also passes (163 checks, 3 skipped); that host does not expose `ID3D12Device10`.
|
||||
|
||||
+2
-2
@@ -31,10 +31,10 @@ python3 scripts/audit/docs_hygiene.py
|
||||
|
||||
Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/skip counts. Never report a skipped test or unavailable tool as a pass.
|
||||
|
||||
## Clean-Room, Licensing & Provenance Policy
|
||||
## Licensing & Provenance Policy
|
||||
|
||||
- Use publicly accessible specifications, publicly licensed software, independently authored synthetic workloads, and project-authorized target builds only under every condition in [AGENTS.md](AGENTS.md) §6 (maintainer approval alone is not enough). Never obtain or use leaked or unauthorized material, and never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
|
||||
- Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
|
||||
- BetterXen is **not** a clean-room project (repository owner's decision, 2026-11-29, #650). Material the project is authorized to use, such as the Microsoft GDK and its compilers under the project's authorization, may be used by contributors, and facts derived from it (layouts, slot orders, flag values, binary conventions) may be committed. The material itself, and its outputs, are never committed. **Leaked or unauthorized material is still forbidden:** anyone who has used it for this work must not contribute what they learned from it. Do not post details of restricted material in issues or PRs.
|
||||
- Before incorporating third-party code, verify **per-file** license compatibility with `GPL-3.0-or-later`, record provenance in [docs/research/upstream-registry.md](docs/research/upstream-registry.md) and [docs/research/component-reuse-matrix.md](docs/research/component-reuse-matrix.md), preserve copyright notices, and update [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). Public visibility or a GPL license does not clear code derived from leaked material.
|
||||
- Never bundle or redistribute proprietary components (CrossOver, D3DMetal, Rosetta 2).
|
||||
- Never claim Xbox hardware verification (BetterXen has no Xbox hardware access) or independent certification of your own work; classify evidence per [docs/claims.toml](docs/claims.toml).
|
||||
|
||||
@@ -23,7 +23,7 @@ BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Ro
|
||||
- **Shader pipeline** (`shader-transpiler/`, Rust) for classifying `DXBC` containers (`DXIL` vs. `ACCC`/`FSPX` RDNA 2 machine code) and handling console shader translation where required.
|
||||
|
||||
> [!CAUTION]
|
||||
> **Clean-room and anti-piracy policy.** BetterXen strictly opposes piracy and does not distribute copyrighted game files, firmware, decryption keys, or DRM circumvention tooling. Zero proprietary binaries, assets, or leaked materials are permitted in this repository or its Git history. All in-repo tests use independently authored synthetic PE32+ workloads.
|
||||
> **Provenance and anti-piracy policy.** BetterXen strictly opposes piracy and does not distribute copyrighted game files, firmware, decryption keys, or DRM circumvention tooling. Zero proprietary binaries, assets, or leaked materials are permitted in this repository or its Git history. All in-repo tests use independently authored synthetic PE32+ workloads.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -17,3 +17,5 @@ EXPORTS
|
||||
bx_xmem_get_internal_stats
|
||||
bx_xmem_try_charge_external
|
||||
bx_xmem_release_charge_external
|
||||
bx_xmem_remap_guard_enter @18
|
||||
bx_xmem_remap_guard_leave @19
|
||||
@@ -51,6 +51,18 @@ int bx_xmem_try_charge_external(uint64_t bytes);
|
||||
* unchanged and an external_charge error is logged. */
|
||||
void bx_xmem_release_charge_external(uint64_t bytes);
|
||||
|
||||
/* The remap guard protects BetterXen reads and writes to title memory while
|
||||
* XMemMapPhysicalPages, XMemMapPhysicalPagesScatter or XMemFreePhysicalPages
|
||||
* replaces mapped views. Those operations wait for active guards and block
|
||||
* new guards until the remap completes.
|
||||
*
|
||||
* Pair each enter with one leave on the same thread. Keep the guard short,
|
||||
* avoid nesting it, and release it before calling an XMem function.
|
||||
* Consumers that resolve the helpers dynamically must resolve both or
|
||||
* call neither. */
|
||||
void bx_xmem_remap_guard_enter(void);
|
||||
void bx_xmem_remap_guard_leave(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
+7
-2
@@ -3,7 +3,8 @@
|
||||
## Getting Started & Architecture
|
||||
|
||||
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
|
||||
- [Roadmap](roadmap.md) — Single authoritative plan (Milestones M0–M6) and completion gates.
|
||||
- [Roadmap](roadmap.md) — Single authoritative plan: the foundation milestones (M0–M2) and the stages the target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), with exit gates and decision gates.
|
||||
- [Working Method](process/working-method.md) — What an agent does when told "work" — the blocker queue, run protocol, source ranks, pull-request shape and the starting queue.
|
||||
- [Parallel Track Architecture](architecture/parallel-tracks.md) — 6-track directory ownership, ABI freeze rule, and multi-agent Git workflow.
|
||||
- [Wave 1 Parallel Backlog](issues/wave-1-backlog.md) — Non-overlapping starter issues across Tracks A–F.
|
||||
- [Frozen ABI Contracts](../abi/README.md) — Cross-DLL C headers (`abi/include/`) and canonical `.def` export tables (`abi/defs/`).
|
||||
@@ -16,22 +17,26 @@
|
||||
- [ADR 0006: Retire in-tree native-first workspace](adr/0006-retire-in-tree-native-workspace.md) — Retirement of paused native code/scripts/docs from `main` (preserved at Git tag `native-first-final`).
|
||||
- [ADR 0007: API-set win32_bridge shims under CrossOver](adr/0007-api-set-shims-under-crossover.md) — Accepted: CrossOver answers the six API-set import names itself, so the shims are not loaded for static imports.
|
||||
- [ADR 0008: M2 Shader Format Gate](adr/0008-m2-shader-format-gate.md) — Proposed: Branch D1 (DXIL through D3DMetal, with the measured wave64 and 64-bit-atomic gaps as M3 work); ACCC-only containers refused with `E_NOTIMPL` until a lawful format source exists.
|
||||
- [ADR 0010: The GDK's texture libraries at run time](adr/0010-gdk-texture-libraries.md) — Accepted: console texture layouts and BCPack come from the GDK's own PC libraries (`xg_xs.dll`, `BCPack.dll`), staged by `bx-cli run` for the target build from each machine's GDK; never reimplemented, committed or shipped.
|
||||
- [ADR 0009: Xbox-layout D3D12 objects](adr/0009-xbox-layout-d3d12-objects.md) — Proposed: `d3d12_xs` gives titles objects with the Xbox object layout and function-table order (generated from the Xbox header), hosting the PC proxies; Phase 1 covers the device chain and the objects it creates.
|
||||
|
||||
## Research, Testing & Licensing
|
||||
|
||||
- [Target-Build Bring-Up: Development Cycle and Review](testing/target-build-review.md) — How contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently without proprietary details.
|
||||
- [Hybrid Workloads & Measurement Protocol](testing/hybrid-workloads.md) — Original Windows workloads, receipt fields, timing conventions, and negative controls.
|
||||
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
|
||||
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
|
||||
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
|
||||
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
|
||||
- [Shader Corpus](../shader-transpiler/corpus/README.md) — Phase 0 of the console shader translator: BetterXen-authored kernels built locally into console containers, Microsoft ISA listings and PC DXIL, with the derived `FSPX` code-section layout (#649).
|
||||
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
|
||||
- [Console Compute Shader Entry ABI](research/console-shader-abi.md) — Wave size, root-argument registers, descriptor forms and binding metadata observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler on project-authored probes (class U: an authorized, not yet independently reproduced observation; inferred register roles).
|
||||
- [Public Technical References](research/sources.md), [Xbox GDK Notes](research/xbox-gdk.md), [RDNA 2 Notes](research/rdna2.md), and [Shader Containers](research/shader-containers.md) — Public specification references for shim and shader work.
|
||||
|
||||
## Governance, Security & Legal
|
||||
|
||||
- [Engineering & Agent Rules](../AGENTS.md) (`CLAUDE.md` symlink) — Mandatory rules for human contributors and coding agents.
|
||||
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, clean-room policy, and DCO sign-off.
|
||||
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, provenance policy, and DCO sign-off.
|
||||
- [Claims & Evidence Classes](claims.toml) — Scoped claims with an evidence-class legend (A, B, D, E, U); classes describe evidence type, not Xbox hardware verification.
|
||||
- [Legal Scope](legal.md), [Dependency Licensing](licenses.md), and [Third-Party Notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution boundaries.
|
||||
- [Threat Model](threat-model.md) & [Security Policy](../SECURITY.md) — Isolation boundaries and vulnerability reporting.
|
||||
@@ -0,0 +1,29 @@
|
||||
# ADR 0010: The GDK's texture libraries at run time
|
||||
|
||||
Status: **Accepted** (2026-11-30, by the repository owner). The evidence is from local Apple Silicon runs by the implementer.
|
||||
|
||||
## Context
|
||||
|
||||
Console textures differ from PC textures in two ways that BetterXen had no answer for:
|
||||
|
||||
- **Tiled layouts.** A console texture carries a swizzle layout (`D3D12XBOX_TEXTURE_LAYOUT`, `0x100 | XG_SWIZZLE_MODE`; most of the target build's textures use the 4 KB "S" mode). A title sizes its placements and loads from the layout, and the bytes arrive tiled. BetterXen's `xg_xs` shim answers every layout as linear, so sizes were too small (#708) and textures could not be uploaded.
|
||||
- **BCPack.** Texture data in the target build's archives is BCPack-compressed (`DSTORAGE_BCPACK_MODE` 1 to 7). There is no public specification of the format. `XCRDAPI.dll` refused those requests (34 per run).
|
||||
|
||||
The GDK the project is authorized to use contains Microsoft's **PC builds** of both: the XG library (`xg_xs.dll`, which computes layouts and copies between tiled and linear data) and the BCPack decoder (`BCPack.dll`). Both are pure computation, with only standard Windows imports, and load under CrossOver. Measured on the target build with them in place: the GDK's XG answers the device's console-layout size queries, detiling through it produced the first real image of the title's menu artwork, and BCPack requests decode.
|
||||
|
||||
Reimplementing either would mean deriving the console's tiling rules and the BCPack format from observation, with the result only ever approximating Microsoft's.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Use Microsoft's libraries at run time; do not reimplement them.** `bx-cli run` stages the GDK's `xg_xs.dll` in place of BetterXen's shim and `BCPack.dll` beside it, and names the decoder to `XCRDAPI.dll` through `BX_BCPACK_DLL` (`launcher/crates/bx-cli/src/gdk_libs.rs`). `d3d12_xs` uses the XG library when it is the loaded `xg_xs.dll` (`shims/d3d12_xs/gdk_xg.cpp`).
|
||||
2. **From each machine's own GDK.** The libraries come from the GDK configured by `bx-cli setup`, which preflight already requires. They are found by their exports, not their place in the GDK.
|
||||
3. **Never committed or shipped**, unless the project records an authorization that covers redistributing them. Commits name only the documented interfaces (`XGCreateTextureComputer`, `BCPackDecompress`, ...), as with every other GDK contract.
|
||||
4. **Only for the target build.** Conformance tests check BetterXen's own shims, so the GDK's libraries are staged only when the executable is the configured target build, or with `--gdk-libraries`. `--no-gdk-libraries` turns them off.
|
||||
5. **BetterXen's `xg_xs` shim stays** as the fallback (and for CI, which has no GDK). Without the GDK's XG, console textures are sized linearly, and the run log says so (`gdk_xg`).
|
||||
|
||||
## Consequences
|
||||
|
||||
- Correct console layouts and BCPack decoding now, without a reverse-engineering effort for either.
|
||||
- Running the title needs the GDK on the machine. Preflight already requires it.
|
||||
- Conformance tests cannot call Microsoft's libraries in CI. Tests cover BetterXen's side of the contract with stand-ins whose answers the test computes (`test_d3d12_gdk_xg_sizes`). Microsoft's results are exercised on machines with the GDK.
|
||||
- Agents need no special knowledge: the target build's run protocol stages the libraries automatically, and `CLAUDE.md` Section 1 says not to reimplement them.
|
||||
@@ -268,3 +268,13 @@ retrieved = "2026-11-22"
|
||||
architecture = "Xbox Series X, Hot Chips 32 architectural presentation"
|
||||
test = "Read slides 12 and 13. No console execution."
|
||||
uncertainty = "The slides do not specify opcode semantics, an ABI or a command packet layout."
|
||||
|
||||
[[claim]]
|
||||
id = "CLAIM-XBOX-CS-ENTRY-ABI"
|
||||
class = "U"
|
||||
claim = "For project-authored compute shaders with explicit root signatures, the NewBE backend of Microsoft's Series X|S PIX shader compiler generated wave64 code that receives root data from s4 in root-parameter order (one SGPR per constant, two per root descriptor address, one per 32-bit table pointer), thread-group IDs after the root data, the root-data address in s0:s1 when the data overflows, and root buffer descriptors built inline with a record count of -1."
|
||||
sources = ["docs/research/console-shader-abi.md"]
|
||||
retrieved = "2026-11-28"
|
||||
architecture = "Xbox Series X|S compute shaders, as compiled by the GDK 2026.10 (10.0.26100.9661) Scarlett PIX shader compiler (NewBE) under CrossOver 26.3 (26.3.0.39832) on Apple M5, macOS 27.2.1"
|
||||
test = "Compiled eleven project-authored cs_6_5/cs_6_6 probes and read the compiler's assembly listings; the compiler and its outputs are used under Microsoft's authorization and are not in the repository."
|
||||
uncertainty = "Class U: no public source establishes this; it rests on an authorized reading of a non-public compiler's listings, which only a contributor with the same authorization can reproduce, and which has not been independently reproduced. Register roles are inferred from the generated code and the reported COMPUTE_PGM_RSRC2 fields. NewBE only: the ACO backend (xdxc), which produces ACCC code, generates different code and agrees so far only on the root UAV address in s[4:5]. One compiler build, compute only, no console execution, and the ACCC container layout is not covered."
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# Clean-room scope
|
||||
# Legal scope
|
||||
|
||||
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation, its own synthetic workloads and, under the conditions in [AGENTS.md](../AGENTS.md) §6, local observation of lawfully obtained target builds.
|
||||
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation, vendor documentation and tools the project is authorized to use (never committed; see [CONTRIBUTING](../CONTRIBUTING.md)), its own synthetic workloads and, under the conditions in [AGENTS.md](../AGENTS.md) §6, local observation of lawfully obtained target builds.
|
||||
|
||||
## User-provided game files
|
||||
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
# Working Method: Run, Fix, Pull Request
|
||||
|
||||
**Status: in effect since 2026-11-29** (#662), together with [AGENTS.md §0](../../AGENTS.md). The pinned ladder issue is #663.
|
||||
|
||||
BetterXen is built by collaborators who each have the project-authorized target build, the GDK and the target build's Ghidra results, and who work by pointing a coding agent at this repository and saying **"work"**. This document answers one question for an agent that has just been told to work: *what is the single most useful thing to do now, and how do I do it without colliding with the other agents?*
|
||||
|
||||
The short answer: run the build, fix the first thing it stops on, and open a pull request. The pull request is the unit of work. There are no meetings, no rotating roles and no backlog to interpret.
|
||||
|
||||
## What you must have
|
||||
|
||||
No agent works without all of these. `bx-cli preflight` checks them and fails if one is missing:
|
||||
|
||||
- an Apple Silicon Mac with CrossOver, D3DMetal and `mingw-w64`;
|
||||
- **the project-authorized target build**;
|
||||
- **the GDK**, headers and compilers, under the project's authorization;
|
||||
- **the Ghidra results of the target build**: the static-analysis run (`RUN_REPORT.md`, `exports/`, `decompiled/`) covering its executable;
|
||||
- at least 10 GiB of free disk space.
|
||||
|
||||
The target build, the GDK and the Ghidra results are a hard requirement: an agent that lacks even one of them does not work on the repository at all.
|
||||
|
||||
A collaborator only says "work". When preflight fails, the agent makes the machine ready itself: `bx-cli setup --find` searches the home folder, recognises the GDK by its header, the target build by its structure (never by name) and the Ghidra results by their layout and the program they cover, and saves all three in `~/.config/betterxen/local.conf`, outside the repository, where every worktree and agent session on that machine finds them. It installs missing build tools with Homebrew and frees disk space by removing its own scratch.
|
||||
|
||||
Work here is found by running the build, located in the Ghidra results and checked against the GDK. Without all three an agent can only guess, and a guess that looks like a fix costs a reviewer more than it saves. An agent stops only for what it cannot supply: the host is not an Apple Silicon Mac, CrossOver is not installed, the build, the GDK or the Ghidra results are not on the machine, or more than one distinct build is (the choice is the collaborator's). Then it says exactly which, and does not write fixes, tests or reviews "for someone else to verify".
|
||||
|
||||
## Why this shape
|
||||
|
||||
What the first target-build runs taught us:
|
||||
|
||||
- **The build finds what tests cannot.** With the start-up milestone verified complete, the build still stopped on a missing handle-duplication call, an instruction loop that trapped two million times and a page-remapping race. Nobody would have written an issue for any of them in advance.
|
||||
- **Guessing is expensive.** A stall was blamed on network polling for a day; a thread sample found the real cause in minutes.
|
||||
- **A helpful workaround can hide the real path.** Answering every pipeline call with success kept the frame loop alive and hid the build's fallback to shader containers.
|
||||
- **One run proves little.** The build takes different start-up paths from run to run. Two blockers looked like one "intermittent stop" until runs were counted.
|
||||
- **Agents left alone drift.** They wrote long documents, opened large stacked pull requests that nobody reviewed, investigated the same symptom twice, shared one game bottle and filled a disk.
|
||||
|
||||
So: the build decides what is next, the queue makes it unambiguous, and reviewing comes before new work.
|
||||
|
||||
## The stages
|
||||
|
||||
The [roadmap](../roadmap.md) is a ladder of stages the target build reaches: **Boot → Picture → Menus → World → Fidelity → Playable**. Exactly one stage is current. Its exit gate is a ten-run check anyone can repeat.
|
||||
|
||||
## Where the state lives
|
||||
|
||||
| What | Where |
|
||||
| --- | --- |
|
||||
| A blocker someone is fixing | An open pull request titled with its signature (a draft while in progress) |
|
||||
| A blocker someone found and could not finish | A **handoff issue** (label `handoff`, plus `stage: <name>`) |
|
||||
| The current stage and its latest gate result | The pinned **ladder issue** (label `ladder`) |
|
||||
| What needs a person | Label `needs-human` |
|
||||
| Rules | AGENTS.md and this document, changed by pull request |
|
||||
|
||||
Nothing about status is kept in files in the repository: agents editing one status file would conflict all day.
|
||||
|
||||
### Why a blocker gets a pull request and not an issue
|
||||
|
||||
An agent that runs the build and sees what it stops on usually knows the fix a few minutes later. Writing an issue, claiming it and then opening a pull request that closes it is three steps where one does the job. And an issue of the form "the build stops at X" is a fact about one run on one machine: the build takes different start-up paths from run to run, so another collaborator may never see it.
|
||||
|
||||
What holds on every machine is the **test**: "the console does X for this call, and this test fails without the fix". The run is why you looked; the test is the proof.
|
||||
|
||||
So:
|
||||
|
||||
- **You can fix it:** open a draft pull request titled with the signature, before writing the fix. The draft is the claim.
|
||||
- **You cannot fix it** (too large, out of session, needs a decision): file one handoff issue with what you saw, what you tried and what is unknown.
|
||||
|
||||
### Signatures
|
||||
|
||||
A signature is the fixed string `bx-cli report` prints for something a run stopped on: `unimplemented IXUser slot 3`, `fault in XCRDAPI.dll`, `exit status 5`. Pull requests and handoff issues are titled with it (`[Boot] unimplemented IXUser slot 3`), so searching open pull requests for a signature tells you whether someone is already on it.
|
||||
|
||||
## What an agent does when told "work"
|
||||
|
||||
AGENTS.md §0 has the binding version. In short, in strict order:
|
||||
|
||||
1. **Preflight.** `bx-cli preflight` must pass. If it does not, stop.
|
||||
2. **Your own pull requests first.** Requested changes, failing checks, conflicts, or a draft you have not finished.
|
||||
3. **Then review.** The oldest open, non-draft pull request from *another* person that has no current review. Merge it if it is approved, green and not your person's. Review comes before new work because unreviewed work is worth nothing to the next run.
|
||||
4. **Then a handoff issue** of the current stage that no pull request covers.
|
||||
5. **Then run the build** and fix the first thing it stops on that no open pull request covers.
|
||||
6. **If the run stops on nothing,** make the stage's ten-run gate check and post it on the ladder issue with `needs-human`.
|
||||
|
||||
An agent stops and labels `needs-human` whenever it meets a decision that is not its to make: a decision gate, a licence or provenance question, a rule change, or two sources of truth that disagree.
|
||||
|
||||
## Working one blocker
|
||||
|
||||
```text
|
||||
run → signature → draft pull request (the claim) → evidence → smallest fix + test → runs before and after → ready → someone else reviews and merges
|
||||
```
|
||||
|
||||
1. **Claim with a draft pull request.** Check open pull requests for the signature. If nobody has it, branch from `origin/main`, push, and open a draft titled `[<Stage>] <signature>`. A draft with no push for 3 days may be taken over.
|
||||
2. **Is it already someone's?** Before investigating any problem the game shows (the picked blocker or one met along the way), search open and merged pull requests and open issues for its log event, stub symbol, error code and the files a fix would touch. If an open pull request covers it, check that branch out, run with it and work there. If a merged one does, sync and run again. On 2026-11-30 a session fixed physical-page DirectStorage requests in parallel with an open pull request for the same problem (#707), and found the overlap only afterwards.
|
||||
3. **Evidence before code.** Find what the build asked for and what it got: the run report, then the diagnostics (thread sampler, fault context, call trace). Check the contract against the GDK where the GDK covers it. Do not guess a fix.
|
||||
4. **Smallest fix.** Only what removes this blocker. A new cross-DLL export still goes through an `[ABI]` pull request first.
|
||||
5. **A test for the contract.** It fails without the fix and passes twice in a row in the same bottle.
|
||||
6. **Proof.** Runs before and after on your machine, every run reported. Say which start-up path your runs took: another machine may take a different one.
|
||||
7. **Mark it ready** with the five-part description. Then stop: the next "work" starts from the top of the list.
|
||||
|
||||
If the blocker turns out to be more than you can finish, close the draft and file a handoff issue.
|
||||
|
||||
### Pull-request description
|
||||
|
||||
Five parts and nothing else:
|
||||
|
||||
1. **Blocker:** `Closes #<issue>` and one sentence on what the build did.
|
||||
2. **Contract:** what the console does, and which source says so (ranks below).
|
||||
3. **Fix:** what changed.
|
||||
4. **Test:** the conformance test, and that it fails without the fix.
|
||||
5. **Proof:** before and after over ten runs (for example "status-5 exits: 4/10 → 0/10"), with the machine and the `main` commit.
|
||||
|
||||
### Review
|
||||
|
||||
The reviewing agent checks out the branch, runs the Section 8 commands and the new test, confirms the test fails without the fix, and reads the proof. It does not repeat the ten runs unless the proof looks wrong.
|
||||
|
||||
**Deep review** — re-deriving the contract from its source, by an agent working for a different person than the author — is required only for:
|
||||
|
||||
- a change under `abi/`;
|
||||
- a new or changed translator instruction class;
|
||||
- a contract from source rank 4 or 5;
|
||||
- anything touching the sandbox, security or licensing.
|
||||
|
||||
**Merging.** The author's agent never merges its own person's pull request. Any other collaborator's agent merges once the pull request is approved and green. A pull request that is green and unreviewed after one working day gets the label `needs-human`.
|
||||
|
||||
**Stacks.** A pull request is based on `main`. One level of stacking is allowed when a fix truly needs an unmerged one; deeper stacks are not.
|
||||
|
||||
## Run protocol
|
||||
|
||||
A run counts only if it is made this way. The launcher does it; agents do not hand-roll it.
|
||||
|
||||
Until the launcher does, the offline-run procedure and the diagnostic switches are in [Target-Build Bring-Up: Development Cycle and Review](../testing/target-build-review.md). Where that document and this one differ on roles, the order of work or review, this one replaces it once accepted.
|
||||
|
||||
- **Build:** current `main`, or `main` plus exactly the one branch under test.
|
||||
- **Sandbox:** the offline runner, which refuses to start unless a probe confirms outbound network is blocked.
|
||||
- **Bottle:** one per agent session, created by the launcher and named for the session. Never a shared one.
|
||||
- **One game at a time per machine.** The launcher takes a machine-wide lock; a second run waits.
|
||||
- **Disk:** at least 10 GB free, checked before the run; the session's scratch bottle and build directory are removed afterwards.
|
||||
- **Count and length:** ten runs, each as long as the stage needs (five minutes for Boot).
|
||||
- **Machine:** the report states chip and memory. Gates are judged on 16 GB machines.
|
||||
|
||||
**The run report** is generated, not written. Per run:
|
||||
|
||||
- outcome: frames presented, clean timeout, early exit with its status, or hang;
|
||||
- the start-up path taken;
|
||||
- every unimplemented call reached, counted;
|
||||
- every fault inside a BetterXen module;
|
||||
- pipelines drawn with: translated, passed through, skipped;
|
||||
- on a stall: every thread's stack.
|
||||
|
||||
It ends with a ten-run summary and a list of **signatures**, the strings pull requests and handoff issues are titled with.
|
||||
|
||||
**What exists today** (#664): `bx-cli report <log.jsonl>...` produces the per-run report and the summary with signatures from run logs, and `bx-cli run` records how each run ended. Not yet in the launcher: the offline runner, per-session bottles, the machine-wide lock, thread stacks on a stall, and stall detection itself (frames are logged at powers of two, so a log cannot yet tell a stall from slow presentation).
|
||||
|
||||
## Sources of truth
|
||||
|
||||
When a fix needs to know what the console does, use the strongest source available and name its rank in the pull request.
|
||||
|
||||
| Rank | Source | Notes |
|
||||
| --- | --- | --- |
|
||||
| 1 | Authorized GDK documentation and headers | Derived facts may be committed. The files never are. |
|
||||
| 2 | Our own compiler output for our own source | Built with the console compiler from the GDK. |
|
||||
| 3 | Run-time observation of the target build | What it calls, with what, and what it does with the answer. |
|
||||
| 4 | Call-site analysis of the target build (a disassembler such as Ghidra) | When observation cannot explain a wait or a branch. Local only. |
|
||||
| 5 | The authorized upstream emulator's source | A hint about what the build needs, not a reference for correctness. Confirm with ranks 1–4 or with runs. |
|
||||
|
||||
Collaborators may install the GDK and a disassembler for this. AGENTS.md §6 is unchanged: nothing from the build enters git, issues or pull requests — no bytes, file names, hashes, addresses or decompiled code.
|
||||
|
||||
## Evidence and references
|
||||
|
||||
- **Private evidence store.** Run logs, dumps, disassembly and captures go in a folder outside the repository on the collaborator's machine. Issues and pull requests carry counts, sizes, call shapes and the contract learned.
|
||||
- **Reference images** (needed from the Picture stage on): a collaborator's own capture from a real console running the same content, or published footage. They live in the private store; a pull request says "matches reference screen 3".
|
||||
|
||||
## Finding blockers once the game runs
|
||||
|
||||
From the Menus stage on, the build no longer stops by itself at the next missing piece: someone has to take it somewhere. Agents are poor players, so the method does not depend on an agent holding a controller. BetterXen owns both ends of the build's contact with the machine — input (`GameInput`) and graphics (`d3d12_xs`) — and records and replays both.
|
||||
|
||||
**1. People play; the launcher records.** A play session with recording on saves the input stream with timestamps and the save files it started from. A hotkey marks a moment ("texture wrong here", "audio cut out"). A crash or hang needs no mark: the run report has it.
|
||||
|
||||
**2. Agents replay routes.** A route is a starting save plus a short recorded input stream (about two minutes: load, walk somewhere, enter a vehicle). An agent replays it through the input shim and compares the run with the last good one. Replays drift, because the build is not deterministic, so routes stay short and start from a save. Each route is a regression test, run ten times like any gate.
|
||||
|
||||
**3. Frame capture and offline replay.** The graphics layer records every call the build makes for one frame, with the data it referenced. The frame is then redrawn without the build running, in seconds and identically every time. An agent fixing a picture bug replays that frame after each change instead of booting and travelling to the spot again.
|
||||
|
||||
**How a problem is recognised,** from most to least reliable without a person:
|
||||
|
||||
| Signal | Catches | Needs a person |
|
||||
| --- | --- | --- |
|
||||
| Crash, hang, early exit | Stability | No |
|
||||
| Run-report counters: skipped draws, stubbed shader instructions, unimplemented calls, failed storage requests | Missing pieces, even when the picture looks plausible | No |
|
||||
| Frame compared with the last good capture of the same route | Regressions | No |
|
||||
| Frame compared with a console reference image | Wrong rendering | To supply the reference |
|
||||
| An agent looking at a capture | Obvious breakage: black screen, missing geometry, garbage textures | No; subtle errors are missed |
|
||||
| A person's mark during play | Feel, audio sync, input lag, anything that "looks off" | Yes |
|
||||
|
||||
Findings become pull requests (or handoff issues, when they cannot be fixed at once) with signatures of the same kind: `route 7: crash at 1:40 (3/10)`, `capture 12: 340 draws skipped`, `capture 12: differs from reference in the sky`. The order of work does not change.
|
||||
|
||||
Whether the game is good to play is a question only people answer. Their time goes into playing and marking, never into reproducing or bisecting.
|
||||
|
||||
## What people do
|
||||
|
||||
People are needed for exactly four things, each marked `needs-human`:
|
||||
|
||||
1. confirming a stage change after a gate passes;
|
||||
2. deciding a decision gate (for example the graphics back end);
|
||||
3. licence, provenance and legal questions;
|
||||
4. changing these rules.
|
||||
|
||||
Everything else is the queue.
|
||||
|
||||
## The first handoffs
|
||||
|
||||
When this method started, the first target-build runs had already found more than could be fixed at once. Those were filed as issues #664–#680. The ones that were only "a blocker with a fix on the way" close as their pull requests merge; the ones that remain open as handoffs are the larger pieces: the run tooling, the D3DMetal capability checks, the translator, the reference images and the record-and-replay tools.
|
||||
@@ -0,0 +1,75 @@
|
||||
# Console compute shader entry ABI (probe results)
|
||||
|
||||
Recorded 2026-11-28 (CLAIM-XBOX-CS-ENTRY-ABI). This page lists facts derived from the assembly listing of Microsoft's Series X|S PIX shader compiler (its NewBE code generator), used under an authorization Microsoft gave the project for its GDK material (see "Provenance"). The compiler, its output and the GDK files are not in this repository. No listing, binary or documentation text is reproduced. Only the observations below are. It complements [RDNA 2 notes](rdna2.md), which cover AMD's public ISA, and [Shader containers](shader-containers.md).
|
||||
|
||||
What this is:
|
||||
- **Measured:** what the compiler emitted for eleven compute shaders the project wrote (p00–p10 below), compiled on one host: Apple M5, macOS 27.2.1, CrossOver 26.3 (26.3.0.39832), GDK 2026.10 (10.0.26100.9661).
|
||||
- **Inferred:** what each register holds. The interpretations below are read from the generated code. They agree with the user-SGPR, thread-group-ID and thread-ID fields of AMD's publicly documented `COMPUTE_PGM_RSRC2` register, which the compiler reports for each shader.
|
||||
|
||||
What this is not: a console run, a description of the ACCC/FSPX container, a description of the ACO backend that produces the code in ACCC containers (see "Root buffer access"), or anything about graphics stages. The compiler used here writes plain DXIL objects. The console code appears only in its assembly listing, so how that code is stored in an ACCC container is still unknown (CLAIM-XBOX-ISA-ABI).
|
||||
|
||||
## Method
|
||||
|
||||
Each probe is a `cs_6_5` compute shader (`cs_6_6` for the 64-bit atomic) with an explicit `[RootSignature]`. The compiler needs a root signature to generate console code. It reported "GFX10" for the target. The probes change one thing at a time:
|
||||
|
||||
| Probe | Root signature | Shader |
|
||||
| --- | --- | --- |
|
||||
| p00 | `SRV(t0), SRV(t1), UAV(u0)` | `o[i] = a[i] + b[i]`, 64 threads |
|
||||
| p01 | `RootConstants(num32BitConstants=4, b0), UAV(u0)` | uses all four constants |
|
||||
| p02 | `CBV(b0), UAV(u0)` | reads two constants |
|
||||
| p03 | `DescriptorTable(SRV(t0, numDescriptors=2)), DescriptorTable(UAV(u0))` | p00 through tables |
|
||||
| p04 | `DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), UAV(u0)` | `Texture2D.SampleLevel` |
|
||||
| p05 | `UAV(u0), SRV(t0), SRV(t1)` | p00 with the parameters reordered |
|
||||
| p06 | `UAV(u0)` | `[numthreads(8,8,1)]`, writes group and thread IDs |
|
||||
| p07 | `SRV(t0), UAV(u0)` | `WaveActiveSum` |
|
||||
| p08 | `SRV(t0), UAV(u0)` | 256 bytes of `groupshared` and a barrier |
|
||||
| p09 | `UAV(u0)` | 64-bit `InterlockedAdd` |
|
||||
| p10 | `RootConstants(num32BitConstants=20, b0), UAV(u0)` | sums all 20 constants |
|
||||
|
||||
## Observations
|
||||
|
||||
**Wave size.** Every probe was compiled for 64-lane waves: the compiler reported wave32 as disabled. In p07 `WaveActiveSum` became a full 64-lane reduction that combines the two 32-lane halves and uses a 64-bit execution mask. D3DMetal 4.0b3, the version measured in [D3DMetal GPU limits](d3dmetal-gpu-limits.md), runs 32-lane waves only; D3DMetal 3.0 was not measured. None of the probes declares a wave size, so wave64 is what this compiler generates by default, and console-compiled compute code has to be treated as wave64 unless it declares otherwise, not only when a shader declares `WaveSize(64)`.
|
||||
|
||||
**Root arguments in registers.** Root-signature data starts at `s4`, in root-parameter order. p05 moves the registers with the parameters.
|
||||
- A root constant takes one SGPR (p01: `s4`–`s7`).
|
||||
- A root CBV, SRV or UAV takes two SGPRs, a 64-bit GPU address (p00: `s4:s5`, `s6:s7`, `s8:s9`).
|
||||
- A descriptor table takes one SGPR, a 32-bit pointer. The shader clears the upper half itself (p03, p04).
|
||||
- The thread-group IDs follow the root data, x before y (p00: `s10`; p06: `s6`, `s7`). Thread IDs arrive in `v0` (x) and `v1` (y), as the reported thread-ID count indicates.
|
||||
|
||||
**Overflow.** `s0`–`s3` come before the root data. When the root data does not fit in user SGPRs (p10: 20 constants and a UAV), only those four are passed, and `s0:s1` holds the address of the root data in memory. The shader loads the constants from offset 0 and the UAV address from offset `0x50`, which is root dword 20. Whether `s0:s1` points at the same data when the arguments also fit in registers was not tested.
|
||||
|
||||
**Root buffer access.** For a root SRV, UAV or CBV, the shader builds the buffer descriptor itself from the root address:
|
||||
- **Stride:** in word 1, the `STRIDE` field (bits 29:16 in the public GFX10 layout), taken from the element type: 4 bytes for `uint`, 8 for `uint64_t`, 16 for the root CBV.
|
||||
- **Record count:** `-1` (`NUM_RECORDS` = 0xFFFFFFFF). With the `OOB_SELECT` below, the only bounds check compares the index against `NUM_RECORDS`, so it never fires: accesses through root descriptors are effectively not bounds-checked.
|
||||
- **Word 3:** the constant `0x11014fac` in every probe. Decoded with the public GFX10 buffer-descriptor layout (Mesa `src/amd/common/ac_descriptors.c` / `gfx10-rsrc.json`, LLVM `SIDefines.h`): destination swizzle X, Y, Z, W; `FORMAT` 20 (`32_UINT`); `RESOURCE_LEVEL` 1; `OOB_SELECT` 1 (the index is checked against `NUM_RECORDS`); `TYPE` 0 (buffer). These observations describe the NewBE path only. The ACO path (`xdxc`), which produces the code in the ACCC containers titles ship, generates different code for the same HLSL: its word 3 is `0x31016fac`, which decodes the same way except `FORMAT` 22 (`32_FLOAT`) and `OOB_SELECT` 3 (raw), two bits apart (`0x20002000`). Of these probes' facts, only the root UAV address in `s[4:5]` has been checked to agree on ACO. That comparison is recorded in the shader corpus PR [#650](https://github.com/MacosPorters/betterxen/pull/650) (open); until it lands, treat ACO agreement beyond that as unverified.
|
||||
|
||||
**Descriptor tables.** Descriptors are loaded from the table address:
|
||||
- buffer descriptors 32 bytes apart (p03 loads at offsets `0` and `0x20`);
|
||||
- a texture descriptor of 32 bytes and a sampler descriptor of 16 bytes (p04).
|
||||
|
||||
For each such load, the compiler also reported the instruction offset and the HLSL binding it came from: class, register, space and resource kind.
|
||||
|
||||
**Other.** p08 uses LDS (`ds_write_b32`, `ds_read_b32`), and its size shows in the reported LDS allocation. p09 is a native `buffer_atomic_add_x2`. The shader hash from the container's `HASH` part is embedded at the start of the generated code.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Branch D2** ([ADR 0008](../adr/0008-m2-shader-format-gate.md)) gains a candidate compute entry ABI: where root constants, root descriptors, table pointers and IDs are, and how buffer descriptors are formed, as the NewBE path generates them. It is not accepted for D2 until it is reproduced independently, and checked against the ACO code that ACCC containers carry.
|
||||
- **Binding recovery** may not need data-flow analysis if ACCC containers carry the same per-load binding table. That depends on the container format, which is still unknown.
|
||||
- **Wave64** is the default. The D1 path also needs to know whether a title's DXIL assumes 64 lanes.
|
||||
- **Bounds:** out-of-range accesses through root descriptors are not discarded on the console the way bounds-checked descriptors would discard them.
|
||||
|
||||
## Open
|
||||
|
||||
- **Graphics stages** (vertex and pixel inputs, exports) were not probed.
|
||||
- **ACCC-only output:** `xdxc` emits containers that keep DXIL and add ACCC. Which compiler or option emits ACCC-only (DXIL-stripped) containers, like those in the target workload's upscaler component (see the [roadmap](../roadmap.md) scan entry), is open.
|
||||
- **ACO agreement:** which of these NewBE facts hold for the ACO code (see "Root buffer access").
|
||||
- **SGPR alignment:** every probe placed its 64-bit root addresses after an even number of SGPRs. Whether an odd count of one-SGPR parameters before a root descriptor inserts a padding SGPR is untested.
|
||||
- **Overflow threshold:** the probes jump from 6 root dwords to 22. The exact cutoff, and whether overflow is always all-or-nothing, are unmeasured.
|
||||
- **`s0`–`s3`:** what they hold when root data fits in registers.
|
||||
- **One compiler build, one host:** a different GDK version may differ.
|
||||
|
||||
## Provenance
|
||||
|
||||
- **Source:** facts were read from listings that Microsoft's licensed Series X|S shader compiler produced for shaders the project wrote. That compiler is not public, so none of this can be checked against a public source, except the descriptor decode above.
|
||||
- **Authorization:** the maintainer (@atesahmet0) has stated that Microsoft's authorization for the project's use of its GDK material covers publishing derived observations like these in this repository. The material itself (the compiler, its listings and binaries, and the GDK documentation) is never committed. The authorization record is held privately (the process is proposed in [#661](https://github.com/MacosPorters/betterxen/pull/661)).
|
||||
- **Reproduction:** only a contributor with the same authorization can reproduce these observations. That reproduction has not happened yet, so the claim is recorded as class U: unestablished by public sources, with an authorized observation behind it.
|
||||
@@ -127,6 +127,26 @@ for a recording recipe. Through `bx-cli run` the guest status is returned unchan
|
||||
Still to do for the issue's validation requirement: an independent run on CrossOver 26.3
|
||||
(D3DMetal 3.0) by another contributor.
|
||||
|
||||
## Capability checks for translated console shaders (#671)
|
||||
|
||||
A translator of console code needs four things from D3DMetal. Each has a synthetic check with
|
||||
one of three results: *runs correctly*, *workaround* (the translator can get the console's
|
||||
answer another way) or *blocked*. The checks talk to the host `d3d12.dll` directly, so they
|
||||
measure D3DMetal, not BetterXen. Expected values are computed on the CPU.
|
||||
|
||||
Machine: Apple M5 (32 GB), macOS 27.2.1, CrossOver 26.3, D3DMetal; each check run twice in a
|
||||
row with the same result.
|
||||
|
||||
| Need | Check | Result | What was measured |
|
||||
| --- | --- | --- | --- |
|
||||
| Descriptors fetched by index (SM 6.6 dynamic resources) | `test_d3dmetal_translator_caps` `heap_index` | **runs correctly** | Resource binding tier 3. A UAV, a raw SRV, a typed SRV, a texture and a sampler, all taken from the descriptor heaps by index (`ResourceDescriptorHeap`, `SamplerDescriptorHeap`, root signature flags `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and `SAMPLER_HEAP_DIRECTLY_INDEXED`): all 65 values correct. |
|
||||
| 64-lane waves | `test_d3dmetal_translator_caps` `wave64`, with `test_d3dmetal_gpu_limits` `wave` | **workaround** | The host runs 32-lane waves (`WaveLaneCountMin = Max = 32`), and a `[WaveSize(64)]` kernel is created but not run (above). A 64-thread group standing for one 64-lane wave gives the 64-lane ballot, exclusive prefix sum, read-lane and sum on all 64 lanes, both through groupshared memory and through the host's own wave operations merged across its two waves. |
|
||||
| 64-bit atomics on typed resources | `test_d3dmetal_gpu_limits` `atomic64`, `lock64` | **workaround** | D3DMetal reports `AtomicInt64OnTypedResourceSupported = 1` and `AtomicInt64OnDescriptorHeapResourceSupported = 1`, but kernels using 64-bit atomics, on typed and on raw resources, are created and not run: even their plain stores are missing. The per-texel lock over 32-bit words with a retry cap of 1024 is exact (0 of 512 updates dropped); with a cap of 64 it drops updates. A translator must not trust the reported support. |
|
||||
| Amplification and mesh shaders | `test_d3dmetal_translator_caps` `mesh` | **runs correctly** | `D3D12_MESH_SHADER_TIER_1` (enum value 10). An amplification shader passes a payload to two mesh groups through `DispatchMesh`; each draws half of a 4x4 target with a pixel shader: all 16 pixels correct. |
|
||||
|
||||
No need is *blocked*, so no ADR is required by #671. The shaders are regenerated with
|
||||
`tests/conformance/test_d3dmetal_translator_caps/shaders/compile.sh` (same DXC release as below).
|
||||
|
||||
## Unverified reports (not evidence)
|
||||
|
||||
Reported on #453 from local VIctory-macOS-based builds running a commercial title on one
|
||||
|
||||
+15
-9
@@ -137,8 +137,10 @@ not define the patterns.
|
||||
|
||||
`scarlett-tex-layouts` returns HTTP 200 with only the membership gate; all
|
||||
`/windows/win32/api/xg/*` paths 404. The numeric `XG_SWIZZLE_MODE` values are
|
||||
not public, so BetterXen's `BX_XG_LAYOUT_*` values 1/2/3 are **local** constants,
|
||||
not the console's.
|
||||
not public. BetterXen's earlier local `BX_XG_LAYOUT_*` constants and clean-room XG
|
||||
interface have been retired: `xg_xs.dll` now follows the documented XG contract
|
||||
titles call, with values from the authorized GDK documentation recorded as derived
|
||||
facts in `shims/xg_xs/xg_xbox.cpp`.
|
||||
|
||||
### Element sizes and the derived masks
|
||||
|
||||
@@ -164,11 +166,15 @@ distinct offsets, each block-aligned and inside the tile).
|
||||
### Verification
|
||||
|
||||
The three masks above were expanded and their bijectivity checked against an
|
||||
independently written `pdep` reference, outside the shim. `test_xg_xs.exe`
|
||||
re-derives its expected offsets from those masks (and, at 32 bpp, from the
|
||||
D3D12 page) rather than reading them back from the shim: one test per block
|
||||
size, covering intra-block offsets (the 16 texels of a BC block share one byte
|
||||
offset), independently derived absolute offsets, and an offset -> texel -> offset
|
||||
round trip. It keeps asserting `E_NOTIMPL` for `SW_64KB_D`, `SW_64KB_R`, 1D/3D,
|
||||
MSAA, and every multi-mip or multi-slice case. Synthetic evidence only; no
|
||||
independently written `pdep` reference, outside the shim. `test_xg_xbox.exe`
|
||||
(which replaced the retired `test_xg_xs.exe`) does not read its expected values
|
||||
back from the shim:
|
||||
- at 32 bpp it compares every offset of a one-tile texture with the public D3D12
|
||||
standard swizzle, and checks the offset -> texel inverse and a copy round trip;
|
||||
- at 8 and 16 bytes per element (the 8-byte case as BC1 blocks) it checks that
|
||||
the offsets are a bijection of aligned slots inside the 64 KiB tile;
|
||||
- it checks that the 16 texels of a BC block share one byte offset.
|
||||
|
||||
Requested modes the shim does not implement (`SW_64KB_D`, multi-tile, multi-mip)
|
||||
are laid out linearly and reported as `LINEAR`. Synthetic evidence only; no
|
||||
Xbox-hardware claim.
|
||||
+81
-20
@@ -1,6 +1,6 @@
|
||||
# BetterXen Roadmap
|
||||
|
||||
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). Track ownership and parallel workflow rules live in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); Wave 1 contributor issues live in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
|
||||
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). How the team and its agents work is in [docs/process/working-method.md](process/working-method.md). Track (directory) ownership is in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); the completed Wave 1 issues are in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
|
||||
|
||||
## Direction
|
||||
|
||||
@@ -19,7 +19,7 @@ External Foundation (user-installed, never bundled):
|
||||
Apple Silicon: ARM64, Metal, unified memory
|
||||
```
|
||||
|
||||
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. Progress is measured strictly by reproducible synthetic conformance tests and recorded verification evidence — never by commit counts or unverified compatibility claims.
|
||||
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. The product goal is one project-authorized target build, fully playable on Apple Silicon Macs with 16 GB of memory. From the Boot stage on, progress is measured by how far that build gets in repeated, recorded runs ([working method](process/working-method.md)); every contract a fix introduces is also pinned by a synthetic conformance test. Progress is never measured by commit counts or unverified compatibility claims.
|
||||
|
||||
Priorities, in order: practical compatibility, correctness, stability, observability, Apple Silicon performance, and long-term maintainability.
|
||||
|
||||
@@ -35,34 +35,95 @@ Priorities, in order: practical compatibility, correctness, stability, observabi
|
||||
|
||||
---
|
||||
|
||||
## Milestones (M0 → M6)
|
||||
## Foundation and stages
|
||||
|
||||
| Milestone | Objective | Exit Gate | Status |
|
||||
The first three milestones (M0 to M2) were defined by subsystems and synthetic tests. They built the foundation, and they also showed the limit of that approach: with M1 verified complete, the target build still stopped at more than a dozen missing or wrong contracts that no synthetic test had asked for. From here on, the roadmap is a ladder of **stages the target build reaches**, observed in runs every collaborator can repeat. Synthetic conformance tests stay mandatory for every contract a fix introduces; they no longer define progress.
|
||||
|
||||
### Foundation (history)
|
||||
|
||||
| Milestone | What it established | Status |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Repo, ABI & cross-build** | Track layout, frozen `.def`/header contracts, env-isolated `bx-cli`, export verifier, live smoke tests | **Verified complete (#406)** |
|
||||
| **M1 — Startup shims to `D3D12XboxCreateDevice`** | Wave 1 shims across Tracks A–F and the combined synthetic boot fixture | **Verified complete (Milestone #17)** |
|
||||
| **M2 — Synthetic first frame & shader format gate** | `PresentX` through D3DMetal with pixel readback; Xbox-layout D3D12 objects (ADR 0009); the shader format question | **Closing.** Remaining: amend ADR 0008 to select Branch D2. The target build supplies console-compiled code only: shader containers whose `DXIL` part carries no bitcode, and serialized pipelines. |
|
||||
|
||||
### The stages
|
||||
|
||||
Every gate below is measured the same way ([working method](process/working-method.md#run-protocol)): the current `main`, the offline sandbox, a contributor's own bottle, **ten runs**, on a 16 GB Apple Silicon Mac. A gate that says "10/10" means ten of ten. Stages have names, not numbers: exactly one is current, and blocker issues carry its label (`stage: boot`, `stage: picture`, …).
|
||||
|
||||
| Stage | The target build… | Exit gate | Status |
|
||||
| --- | --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; all 17 PE32+ DLLs (16 mingw-w64 C++ shims + the Rust `bx_shader_bridge.dll`) pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **Verified complete (`#406`)** |
|
||||
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime` + dynamic loader exports, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, supervised `bx-cli run`, ADR 0007, and combined synthetic integration boot fixture | All Wave 1 conformance binaries pass under CrossOver 26.3 + Rosetta 2; combined `test_integration_boot.exe` passes (19 pass, 2 ADR-0007 pending, 0 fail) | **Verified complete (Milestone #17, 16/16)** |
|
||||
| **M2 — First Rendered Frame & Shader Format Gate** | Clear dynamic GDK startup (`system32` staging + public GDK COM `QueryApiImpl` dispatch), implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), integrate the shipped xmem-configured D3D12 placed heap (#464) into the first-frame fixture (#469), bridge `dxbc-accc` into Windows guests (`#445`), measure D3DMetal GPU limits (`#453`), and establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)**. Measured translator constraints: [D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | **In development (Milestone #18)** |
|
||||
| **M3 — Full Shaders, Streaming & Texture Correctness** | DirectStorage decompression, accurate RDNA 2 (`gfx1030`) `xg_xs` tile-addressing & deswizzling, full `d3d12_xs` command-list/barrier/GPUVA fidelity, and Branch D1 DXIL normalization or Branch D2 `ACCC`/`FSPX` → DXIL/MSL transpiler, within the [measured D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) (`WaveSize(64)` and SM 6.6 64-bit atomics not run; bounded lock emulation) | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
|
||||
| **M4 — 3D Rendering, DXR/BVH4 & Upscaling** | Bridge `XboxBvhBuilder` / `ID3D12StateObject` ray tracing to D3DMetal 3.0 DXR (intercepting incompatible AMD BVH4 rehydration → live rebuild), provide PC FidelityFX / MetalFX upscaling shim, and wire full `GameInput` controller/KB/M input | Synthetic DXR + upscaled 3D scene and scripted `GameInput` conformance tests pass | Planned |
|
||||
| **M5 — Software Audio/DSP, Saves & Stability** | Replace `AcpHal`/`xapu`/`chad` stubs with software audio/DSP decoding + XAudio2_9/CoreAudio output, wire `PersistentLocalStorage`, and resolve concurrency/memory/GPU hang bugs under soak testing | Synthetic audio playback, save round-trip, and multi-hour soak benchmarks pass with bounded memory | Planned |
|
||||
| **M6 — Shader Cache, 16 GB Optimization & Polish** | Persistent disk PSO + translated-shader cache, Lockhart 16 GB unified memory pressure tuning, Metal System Trace optimization, and optional Swift launcher UI | Reproducible frame-pacing and memory-pressure receipts under [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) | Planned |
|
||||
| **Boot** | starts, reaches its frame loop and stays there | 10/10 runs present frames for 5 minutes; the run report lists no unimplemented call on the path taken, no fault in a BetterXen module, and no early exit | **In development** |
|
||||
| **Picture** | shows its first non-black screen, correctly | In 10/10 runs the first reference screen matches the reference image within the agreed tolerance; every pipeline drawn with is a translated pipeline, none is skipped | Planned |
|
||||
| **Menus** | plays its opening sequence and menus with sound and input | A scripted input sequence goes from launch to the last menu before gameplay in 10/10 runs; audio is audible and in sync by the checklist; a save written in one run is read in the next | Planned |
|
||||
| **World** | loads into gameplay and keeps running | 10/10 runs enter gameplay and run 10 minutes with no crash, hang or early exit; streaming requests complete without error; memory stays inside the 16 GB profile | Planned |
|
||||
| **Fidelity** | draws its 3D scenes as the console does | The scene checklist (geometry, textures, lighting, effects, HUD) passes against the reference set at the fixed capture points; no draw or dispatch is skipped or stubbed | Planned |
|
||||
| **Playable** | is playable start to finish on every supported Mac | 30 fps or better at the tier's resolution for each chip tier; a 2-hour session with bounded memory and no hang; warm start uses the shader cache; controller and keyboard/mouse complete | Planned |
|
||||
|
||||
### Startup diagnosis
|
||||
"Reference image" and "reference set" are captures of the same content from a real console or from published footage, kept in the private evidence store, never in the repository ([working method](process/working-method.md#evidence-and-references)).
|
||||
|
||||
The product goal is to reach a frame presented by the target software. Under the current [contribution rules](../CONTRIBUTING.md), project runs use original synthetic workloads. Start with `test_integration_boot.exe` for startup and `test_veh_unhandled.exe` as a crash-logging control. Use a focused synthetic reproducer once a failing contract is identified.
|
||||
### Boot
|
||||
|
||||
Before treating either startup warning as causal, add diagnostics that record the requested DirectStorage factory IID and returned HRESULT (#483) and distinguish null, unrecognized and supported BetterXen virtual-memory configurations (#464 follow-up). On a pinned launcher, shim set and backend, repeat the synthetic case before and after a fix. Record normal exit, crash or timeout, the last completed checkpoint, and the exception thread and module offset when available. Progress means reaching the next named checkpoint in the same reproducer. Startup diagnosis and the budget fix proceed alongside the M2 exit gates.
|
||||
**Known work, all found by running the target build:**
|
||||
|
||||
### M2 first-frame acceptance and parallel memory work
|
||||
| Blocker | Effect | State |
|
||||
| --- | --- | --- |
|
||||
| `CLZERO` trapped once per 64 bytes | The frame loop stalls for tens of seconds while the build zeroes memory | Fix exists locally (the loop completes in one trap); needs a PR and a conformance test |
|
||||
| A storage worker writes into a page xmem is remapping | The build's own fault handler exits (status 5) | Bounded retry exists locally. The real fix is an atomic remap in `xmem` |
|
||||
| Missing runtime calls: `XUserDuplicateHandle`, `XAsyncRun`, `XTaskQueue` duplicate/port/composite, `XGameSaveGetContainerInfo` and its by-name variant | The build waits forever or exits (status 1) | Implemented locally; need PRs and tests |
|
||||
| Serialized-pipeline calls answered with success in null-render mode | The build never falls back to its shader containers | Decide and document: these calls fail (logged) until they are implemented |
|
||||
| One early exit (status 1) with nothing logged | 1 run in 5 | Open: needs the run report's exit capture |
|
||||
| Run tooling lives outside the repository | Nobody else can repeat a run or read its result the same way | Move the offline runner, the run report and the sampler into `launcher/` and `scripts/` |
|
||||
|
||||
- **First frame (#465, #469).** The synthetic placement criterion uses BetterXen's `BXVM` block to configure the separate D3D12-owned WRITE_BACK heap shipped in #486. On the recorded overlay, #494 copied the backbuffer before the flip, counted one host `Present`, then compared 256 RGBA8 pixels through the D3D12 mapping after waiting. The xmem sentinel shows that the original page remained separate. Visibility through the original xmem address remains an open compatibility question for M3, informed by #473. Displayed-image verification is outside this fixture's measurements. Record a single `main` commit containing the integrated presentation and fixture changes, confirm that the fixture executable built, and have someone who authored neither the fixture nor the presentation bridge verify the D3DMetal run and pixel-mismatch control. The shader gate still requires a recorded D1/D2 selection. [Fixture and receipts](https://github.com/MacosPorters/betterxen/pull/494) · [ADR 0008](adr/0008-m2-shader-format-gate.md)
|
||||
- **Shader format gate (#466, ADR 0008).** D1 remains the only branch with end-to-end execution evidence, and the static scan gives it measured inputs in the target workload: 52 DXIL SM 6.5 compute containers with LLVM bitcode. The same scan makes D2 a concrete compatibility candidate rather than a hypothesis: the workload's FidelityFX upscaler component embeds 29 ACCC-only containers. Select D2 work only when a required pipeline-creation path refuses an ACCC-only container at runtime — if that refusal precedes the first presented frame, treat it as a first-frame blocker; if it appears only with upscaling enabled, track it under M4 upscaling. Two Track D parser prerequisites precede any D2 trial: extend the clean-room `FSPX` section-table layout to accept the observed tables (a maintainer provenance decision, since no public format description exists), and stop the classifier from treating a `NOBC` header-only program as executable DXIL. The first `shader_gate` record the target workload writes names the shader path its first pipeline creation actually submits. [ADR 0008](adr/0008-m2-shader-format-gate.md)
|
||||
- **Title budget (#550, #552).** Keep current allocation ownership and give xmem atomic admission authority through an ABI-first contract. The initial scope combines xmem usage with the existing charged `CreateHeap` path. Under a 512 MiB cap, an xmem allocation of 256 MiB followed by a 384 MiB heap was refused, while the reverse admitted 640 MiB. Test both orders, concurrent admission and rollback. Charge a backing allocation once across aliases. Accounting for `CreateHeap1`, committed and reserved resources, and internal buffers such as XCRDAPI staging remains an open scope decision. Placement and wrapper lifetime have separate checks (#554, #572). [Merged-base reproduction](https://github.com/MacosPorters/betterxen/pull/486#issuecomment-7209751182)
|
||||
- **M3 resource handling.** Keep explicit paths for fixed addresses, existing contents, pre-device allocations, sections/scatter and opaque textures. The draft eligibility analysis found no reliable end-to-end classifier. Resolve the `XMemVirtualAlloc` argument-count question (#518) before using graphics flags as evidence. A mapped-buffer trial is optional and opt-in, with the existing path as fallback. Require a known consumer before returning a pointer, verify its alignment and lifetime, and confirm completion on every participating queue before reusing memory for work BetterXen submits. #483 retains its DirectStorage interface scope. [Draft eligibility analysis](https://github.com/MacosPorters/betterxen/blob/7e0b515131150fec6b5117c9498b6c0faf0ca382/docs/architecture/proposals/001-unified-memory/appendix/eligibility.md)
|
||||
- **M6 optimization.** Compare the existing path with a candidate allocator or bounded pool on the same 16 GB host and backend. Check correct output for both paths across repeated matched workloads. Include cold setup, transfers, fragmentation, pending retirements, post-release footprint and whole-frame time. Require a repeatable workload benefit before choosing a default.
|
||||
**Not needed for the gate:** audio output, correct pictures, performance.
|
||||
|
||||
### Picture
|
||||
|
||||
This is where the shader translator becomes the critical path, and where the D3DMetal route is tested for real. The risk checks come **first**, before feature work depends on them.
|
||||
|
||||
1. **Capability checks on D3DMetal (first).** Synthetic tests, one each, for what translated shaders need: direct descriptor-heap indexing (SM 6.6), 64-lane compute behaviour through the translator's emulation, 64-bit atomics on typed resources, mesh and amplification shaders. Each ends in *runs correctly*, *can be worked around in the translator*, or *blocked*. A *blocked* result opens an ADR on the back end, marked `needs-human`, before anything else in this stage continues.
|
||||
2. **The translator.** BetterXen writes its own GFX10-to-DXIL translator in `shader-transpiler/` and exposes it through `bx_shader_bridge.dll`; the upstream emulator's translator is not used (repository owner's decision, 2026-11-29). The design is mechanical: one rule per instruction, registers as variables, and control flow as numbered blocks in a dispatch loop, so no structure has to be reconstructed. Each rule is checked against the console compiler's output for a shader of our own (source rank 2). A prototype on branch `experiment/visible-frame` translates the four pipelines of the build's first screen and is the reference for that screen.
|
||||
3. **Translator verification.** Extend the known-source corpus (#650) so every instruction class the first screens use is checked against a reference result. A translator bug is found with a ten-line shader, not in a broken frame.
|
||||
4. **The first pipelines.** The clear pipeline, the display-mapping compute shader, and whatever the first reference screen draws with, created on the host on first use.
|
||||
5. **Descriptors and memory the shaders read.** The descriptor model the translated shaders expect; contents of textures placed in title memory (today a logged stub); title-written constant and vertex data reaching the GPU.
|
||||
|
||||
### Menus to Playable — known work and unknowns
|
||||
|
||||
Listed so lanes can prepare, not as a commitment to order. Each item is confirmed by a run before work starts on it.
|
||||
|
||||
| Stage | Known work | Main unknown |
|
||||
| --- | --- | --- |
|
||||
| **Menus** | XMA decoding and audio output through the audio coprocessor contract; `GameInput` devices; speech/accessibility provider; saves round trip | What the build waits for between sign-in and its first screen |
|
||||
| **World** | DirectStorage page destinations, BCPack and swizzle options; XG tiling modes beyond linear; atomic page remapping; the Series S memory profile as the 16 GB default | Streaming behaviour under memory pressure |
|
||||
| **Fidelity** | Mesh/amplification pipelines; indirect draws with console argument types; rectangle lists; the unimplemented command-list state calls; upscaler substitute (FSR 3.1 or plain scaling in place of the console's FSR 4); ray tracing: bridge it, or run the profile that does not use it | How much of the frame depends on the console's ray-tracing path |
|
||||
| **Playable** | Translated-shader and pipeline cache; memory copies removed where the host allows; frame pacing against the display; chip-tier matrix | Whether the base 16 GB tier reaches 30 fps, and at what resolution |
|
||||
|
||||
### Decision gates
|
||||
|
||||
A gate is a question answered by a measurement, with the options written down before the measurement is taken.
|
||||
|
||||
| Gate | When | Question | If the answer is no |
|
||||
| --- | --- | --- | --- |
|
||||
| **Back end** | Start of Picture | Does D3DMetal run what translated console shaders need? | ADR: translator-side lowering, another host back end, or a narrower shader profile |
|
||||
| **Reference** | Start of Picture | Do we have reference images for the first screens? | The Picture gate falls back to a written checklist per screen, agreed by two collaborators |
|
||||
| **Memory** | Start of World | Does the build load into gameplay inside the 16 GB profile? | Series S profile only; reduce copies before any other World work |
|
||||
| **Frame rate** | Start of Playable | Is the base tier within 2x of 30 fps? | Publish tiers honestly; lower the base tier's resolution before promising it |
|
||||
|
||||
### What counts as progress
|
||||
|
||||
A change belongs on `main` only if it passes the **step-forward test**. It must do one of these, and say which:
|
||||
|
||||
1. remove a blocker of the current stage (shown by the run report before and after);
|
||||
2. remove a blocker already confirmed for a later stage, when every blocker of the current stage is claimed;
|
||||
3. make a blocker faster to find (run tooling, diagnostics, a corpus test);
|
||||
4. retire a risk at a decision gate.
|
||||
|
||||
Work that does none of these waits: subsystems nobody has seen the build need, documentation about work not yet done, and optimisation before the Playable stage.
|
||||
|
||||
---
|
||||
|
||||
## How Progress Is Reported
|
||||
|
||||
Milestone status is one of: `Planned`, `In development`, `In validation`, `Verified complete`, or `Blocked`. A milestone reaches `Verified complete` only after independent verification of its exit gate per [AGENTS.md](../AGENTS.md).
|
||||
|
||||
For the stages, the pinned ladder issue carries the live status: the current stage, the latest ten-run result for its gate, and the open blocker issues with their claims. A gate result is reported with every run counted, the machine it ran on, and the `main` commit.
|
||||
@@ -0,0 +1,139 @@
|
||||
# Target-Build Bring-Up: Development Cycle and Review
|
||||
|
||||
This is how any number of contributors run a project-authorized target build on BetterXen, turn what they find into pull requests, and review each other's work. It applies [AGENTS.md](../../AGENTS.md) Sections 5–7, the clean-room and provenance rules in [CONTRIBUTING.md](../../CONTRIBUTING.md), and [docs/legal.md](../legal.md). It adds no new permissions.
|
||||
|
||||
## Authorization is recorded, not assumed
|
||||
|
||||
AGENTS.md §6 allows evidence from *project-authorized* target builds, but it does not define who authorizes a build or how. Until a governance change defines that, this procedure requires a **recorded authorization**:
|
||||
|
||||
- **Before any target-build work,** a contributor writes an authorization note in the team's private evidence store (see "Evidence"). The note covers:
|
||||
- the build;
|
||||
- the evidence class: target-build observation, or authorized SDK documentation;
|
||||
- the maintainer who approved it;
|
||||
- how the contributor obtained the build or documentation lawfully, under terms that permit the inspection;
|
||||
- the confirmation that the work needs no decryption or circumvention of security, DRM, licensing or activation controls.
|
||||
- **Maintainer approval alone is not enough** (CONTRIBUTING.md). If any of these points is unknown, the build is not used.
|
||||
- **The note's ID goes into every PR and every review** that relies on that evidence.
|
||||
|
||||
## Roles
|
||||
|
||||
- **Bring-up keeper.** One person keeps a running branch (for example `bringup/<topic>`). It merges the open fix branches, so the title can be run end to end. This branch is never proposed for `main`. The role can rotate.
|
||||
- **Author.** Turns one finding into one single-track PR.
|
||||
- **Reviewer.** Anyone other than the author whose own recorded authorization covers the same evidence class. The reviewer re-derives the contract from their own authorized source, never from the author's copies, notes or binaries. Someone who has accessed leaked or confidential material does not review (CONTRIBUTING.md).
|
||||
- **Merger.** A maintainer other than the original author (AGENTS.md §7).
|
||||
|
||||
Work is organised by **area**, not by person. Areas follow the tracks in [parallel-tracks.md](../architecture/parallel-tracks.md): memory and storage, D3D12, XG, runtime and audio, shaders, tests and tooling. Each contributor claims an issue in an area. As more people join, an area takes more claims, but its file scope stays the same.
|
||||
|
||||
## Cycle
|
||||
|
||||
1. **Measure on the bring-up branch.** Run the title only through the offline-run procedure below. Find the first blocker with BetterXen's own diagnostics.
|
||||
2. **Record the evidence privately,** under an evidence note ID.
|
||||
3. **Open an issue** for the blocker. Name the API or contract. Do not name the title.
|
||||
4. **Fix it on a track branch off `main`.** Stay within the issue's file scope. Add or update a synthetic conformance test for every contract the fix relies on.
|
||||
5. **Open a PR** using the template below. The bring-up keeper merges the branch into the bring-up branch so that later blockers can be found.
|
||||
6. **Review independently** (see "What a reviewer does").
|
||||
7. **Merge and re-sync.** After a merge, the bring-up keeper rebases the bring-up branch on `main`.
|
||||
|
||||
### Bring-up checkpoints
|
||||
|
||||
These checkpoints describe how far a target build gets. They are **not** milestone status: milestones, their exit gates and the status vocabulary are defined only in [docs/roadmap.md](../roadmap.md) (M0–M6). A checkpoint can serve as evidence for a roadmap exit gate only where that gate says so.
|
||||
|
||||
1. **Starts:** reaches its first graphics device.
|
||||
2. **Presents:** presents its first frame, whatever it contains.
|
||||
3. **Frame loop:** keeps presenting for a recorded duration.
|
||||
4. **Rendered content:** presents pixels produced by its own shaders (needs the M2/M3 shader work).
|
||||
5. **Interactive:** reaches a menu that accepts input.
|
||||
|
||||
Each PR states which checkpoint it affects, and the measured result before and after.
|
||||
|
||||
## PR description template
|
||||
|
||||
```text
|
||||
Contract: the derived facts (sizes, offsets, slot orders, flags, units, return values)
|
||||
Source: "authorized SDK documentation" and/or "target-build observation";
|
||||
never quote header or documentation text, never name the title or build
|
||||
Authorization: authorization note ID
|
||||
Evidence: evidence note ID(s)
|
||||
Reproduce: the BetterXen commit, bx-cli options, BX_* switches and log events a reviewer checks
|
||||
Test: the conformance test that asserts the contract, and how its expected
|
||||
values were derived independently of the implementation
|
||||
Checkpoint: the checkpoint this affects, with the measured result before and after
|
||||
```
|
||||
|
||||
## What a reviewer does
|
||||
|
||||
The reviewer re-derives the contract and does not rely on the PR's conclusions (AGENTS.md §5).
|
||||
|
||||
1. **Documentation facts.** Compile a local probe against their own authorized headers and print the sizes, offsets and constants. Probes and their output stay outside this repository.
|
||||
2. **Title behaviour.** If the fix depends on how the title uses an API (for example, units it stores or flags it passes), check this in their own analysis, under their own authorization.
|
||||
3. **Title run.** Run the PR branch merged into the bring-up branch, using the offline-run procedure, and confirm the stated before-and-after result.
|
||||
4. **Checks.** Run the AGENTS.md §8 checks. Confirm that the conformance test's expected values do not come from the code under test.
|
||||
5. **Post the review.** Say what was re-derived and what was run, without proprietary details, and cite the note IDs.
|
||||
|
||||
## Offline-run procedure
|
||||
|
||||
Every title run must be unable to reach the network, because some titles upload crash dumps. The run is wrapped in a macOS sandbox profile that denies outbound IP traffic. Apple marks `sandbox-exec` as deprecated, but it still enforces profiles on current macOS; if it stops working, do not run the title until a replacement is documented here.
|
||||
|
||||
Copy these commands, filling in the bracketed values. Record the BetterXen commit (`git rev-parse HEAD`) and these exact commands in the evidence note.
|
||||
|
||||
```sh
|
||||
CX=/Applications/CrossOver.app/Contents/SharedSupport/CrossOver
|
||||
BOTTLE=<bottle name>
|
||||
PREFIX="$HOME/Library/Application Support/CrossOver/Bottles/$BOTTLE"
|
||||
PROFILE='(version 1)(allow default)(deny network-outbound (remote ip))'
|
||||
|
||||
# 1. Stop the bottle's wineserver. A wineserver started outside the sandbox would
|
||||
# serve the title outside it.
|
||||
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -k
|
||||
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -w
|
||||
|
||||
# 2. Confirm the profile blocks outbound traffic. This must print BLOCKED; otherwise stop.
|
||||
sandbox-exec -p "$PROFILE" /usr/bin/curl -sS -m 5 https://example.com >/dev/null 2>&1 \
|
||||
&& echo REACHABLE || echo BLOCKED
|
||||
|
||||
# 3. Run the title inside the same profile. Every process it starts, including the new
|
||||
# wineserver, inherits the sandbox.
|
||||
env -i HOME="$HOME" USER="$USER" TMPDIR="$TMPDIR" PATH=/usr/bin:/bin:/usr/sbin:/sbin \
|
||||
BX_TRACE_D3D=0 BX_NULL_RENDER=1 BX_PRESENT_DUMP='Z:\<frames folder>' BX_INPUT_SCRIPT=A@40,A@50 \
|
||||
sandbox-exec -p "$PROFILE" target/debug/bx-cli run --inherit-env \
|
||||
--bottle "$BOTTLE" --backend d3dmetal --profile <profile> \
|
||||
--log <run>.jsonl --shims build-shims/bin --exe <path to the title executable>
|
||||
```
|
||||
|
||||
**Why `env -i` with `--inherit-env`:** `bx-cli run` normally clears the guest environment to a fixed allowlist (AGENTS.md §3), and that allowlist has no `BX_*` diagnostic switches. Here `env -i` builds an environment that contains only the listed variables, and `--inherit-env` passes exactly that to the guest. Host credentials and other variables still never reach it.
|
||||
|
||||
**Confirming that the title stayed offline.** Run a guest-side probe that tries an outbound connection the same way. It must fail inside the sandbox and succeed outside it. The probe and its output belong in the evidence note.
|
||||
|
||||
Everyone uses the same pinned environment: the BetterXen commit, the CrossOver version, the macOS version and the `bx-cli` profile. A result is reported together with that environment.
|
||||
|
||||
## Diagnostics
|
||||
|
||||
All switches are off unless set, and none changes behaviour beyond what its row says. Only switches that exist on `main` are listed. Switches from open PRs are added here when those PRs merge.
|
||||
|
||||
| Switch | Where | Effect |
|
||||
| --- | --- | --- |
|
||||
| `BX_TRACE_D3D=1` | `d3d12_xs` | Logs every D3D12 call |
|
||||
| `BX_NULL_RENDER=1` | `d3d12_xs` | Pipelines that cannot be built become null pipelines; their draws and dispatches are skipped and logged |
|
||||
| `BX_PRESENT_DUMP=<folder>` | `d3d12_xs` | Writes presented frames as BMP files, every Nth present (`BX_PRESENT_DUMP_EVERY`, default 64) |
|
||||
| `BX_XMEM_TRACE=1` | `xmem` | Logs physical page allocations, frees and mappings |
|
||||
| `BX_INPUT_SCRIPT=<presses>` | `GameInput` | Scripted gamepad presses for unattended runs, without window focus: comma-separated `BUTTON@SECONDS` (`A@40,DOWN@50.5,A@52`), each held 300 ms, timed from the first gamepad reading. Buttons `MENU VIEW A B X Y UP DOWN LEFT RIGHT`. Each press is logged (`input_script`), and so is each entry that cannot be read |
|
||||
| `BX_CONTINUE_ASSERTS=1` | `bx_runtime_veh` | Steps over an `int3` in the title's own executable (a continuable assert) instead of letting it reach the title's crash reporter. Each address is logged once (`assert_continued`), so the report still lists every assert. Use it to get past a known assert to the next blocker, and say so in the evidence |
|
||||
|
||||
Their output can contain title addresses and file names, so it goes only into the private evidence store.
|
||||
|
||||
## Evidence
|
||||
|
||||
Logs, addresses, decompiled output, screenshots and authorization notes live in the team's private evidence store, outside this repository. PRs and reviews refer to them by note ID only.
|
||||
|
||||
## What never enters the repository
|
||||
|
||||
CONTRIBUTING.md (clean-room and provenance) and docs/legal.md set the rules. For target-build work in particular, never commit or post:
|
||||
|
||||
- SDK header or documentation text;
|
||||
- the title's name or file names;
|
||||
- identifiers derived from the title or build: its hashes, addresses or raw logs;
|
||||
- decompiled code or disassembly;
|
||||
- screenshots of the title;
|
||||
- personal paths.
|
||||
|
||||
Hashes that record the provenance of third-party code (`THIRD_PARTY_NOTICES.md`, `docs/research/upstream-registry.md`) are not affected. Contracts are recorded as derived facts only.
|
||||
@@ -0,0 +1,184 @@
|
||||
//! The GDK's own texture libraries, staged for runs of the target build (ADR 0010).
|
||||
//!
|
||||
//! Console textures use tiled layouts and BCPack compression. BetterXen does not reimplement
|
||||
//! either: a run of the target build loads Microsoft's PC builds of the GDK's XG library
|
||||
//! (`xg_xs.dll`, in place of BetterXen's `xg_xs` shim) and BCPack decoder (`BCPack.dll`, named to
|
||||
//! `XCRDAPI.dll` through `BX_BCPACK_DLL`) from the GDK configured on this machine. Nothing from
|
||||
//! the GDK is committed or shipped.
|
||||
//!
|
||||
//! The libraries are recognised by what they export, never by their place in the GDK: an
|
||||
//! x86-64 PE32+ file named `xg_xs.dll` that exports `XGComputeTexture2DLayout` and does not
|
||||
//! import `xmem.dll` (the console build does), and one named `BCPack.dll` that exports
|
||||
//! `BCPackDecompress`. Conformance tests keep BetterXen's own shim: the GDK's are staged only
|
||||
//! for the configured target build, or with `--gdk-libraries`.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use bx_probe::probe_pe32_plus;
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct GdkLibraries {
|
||||
pub xg: Option<PathBuf>,
|
||||
pub bcpack: Option<PathBuf>,
|
||||
}
|
||||
|
||||
fn contains(bytes: &[u8], needle: &[u8]) -> bool {
|
||||
bytes.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
|
||||
/// Whether `bytes` are the PC build of the GDK's XG library.
|
||||
pub fn is_pc_xg(bytes: &[u8]) -> bool {
|
||||
let Ok(summary) = probe_pe32_plus(bytes) else {
|
||||
return false;
|
||||
};
|
||||
contains(bytes, b"XGComputeTexture2DLayout\0")
|
||||
&& contains(bytes, b"XGCreateTextureComputer\0")
|
||||
&& !summary
|
||||
.imports
|
||||
.keys()
|
||||
.any(|dll| dll.eq_ignore_ascii_case("xmem.dll"))
|
||||
}
|
||||
|
||||
/// Whether `bytes` are the GDK's BCPack decoder.
|
||||
pub fn is_bcpack(bytes: &[u8]) -> bool {
|
||||
probe_pe32_plus(bytes).is_ok() && contains(bytes, b"BCPackDecompress\0")
|
||||
}
|
||||
|
||||
/// Finds the two libraries under `root` (bounded depth). When the GDK holds several builds,
|
||||
/// the first by path order is used, so the choice is the same on every run.
|
||||
pub fn find(root: &Path) -> GdkLibraries {
|
||||
let mut xg = Vec::new();
|
||||
let mut bcpack = Vec::new();
|
||||
let mut stack = vec![(root.to_path_buf(), 0usize)];
|
||||
while let Some((dir, depth)) = stack.pop() {
|
||||
let Ok(entries) = fs::read_dir(&dir) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let Ok(kind) = entry.file_type() else {
|
||||
continue;
|
||||
};
|
||||
if kind.is_dir() {
|
||||
if depth < 14 {
|
||||
stack.push((path, depth + 1));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
|
||||
if name != "xg_xs.dll" && name != "bcpack.dll" {
|
||||
continue;
|
||||
}
|
||||
let Ok(bytes) = fs::read(&path) else {
|
||||
continue;
|
||||
};
|
||||
if name == "xg_xs.dll" && is_pc_xg(&bytes) {
|
||||
xg.push(path);
|
||||
} else if name == "bcpack.dll" && is_bcpack(&bytes) {
|
||||
bcpack.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
xg.sort();
|
||||
bcpack.sort();
|
||||
GdkLibraries {
|
||||
xg: xg.into_iter().next(),
|
||||
bcpack: bcpack.into_iter().next(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds `out` as a copy of the shim folder's files with the GDK's libraries added: its
|
||||
/// `xg_xs.dll` replaces BetterXen's shim, and `BCPack.dll` sits beside it. Returns the path of
|
||||
/// the staged `BCPack.dll`, when there is one.
|
||||
pub fn merge_shims(shims: &Path, libs: &GdkLibraries, out: &Path) -> io::Result<Option<PathBuf>> {
|
||||
fs::create_dir_all(out)?;
|
||||
for entry in fs::read_dir(shims)? {
|
||||
let entry = entry?;
|
||||
if entry.file_type()?.is_file() {
|
||||
fs::copy(entry.path(), out.join(entry.file_name()))?;
|
||||
}
|
||||
}
|
||||
if let Some(xg) = &libs.xg {
|
||||
fs::copy(xg, out.join("xg_xs.dll"))?;
|
||||
}
|
||||
match &libs.bcpack {
|
||||
Some(bcpack) => {
|
||||
let staged = out.join("BCPack.dll");
|
||||
fs::copy(bcpack, &staged)?;
|
||||
Ok(Some(staged))
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A minimal x86-64 PE32+ image with no sections, followed by `tail`. Import tables are
|
||||
/// not modelled, so "imports xmem.dll" is covered by `is_pc_xg` on a real probe only.
|
||||
fn pe(tail: &[u8]) -> Vec<u8> {
|
||||
let mut b = vec![0u8; 0x200];
|
||||
b[0..2].copy_from_slice(b"MZ");
|
||||
b[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
b[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
b[0x44..0x46].copy_from_slice(&0x8664u16.to_le_bytes()); // machine
|
||||
b[0x54..0x56].copy_from_slice(&240u16.to_le_bytes()); // SizeOfOptionalHeader
|
||||
b[0x58..0x5A].copy_from_slice(&0x020Bu16.to_le_bytes()); // PE32+
|
||||
b[0x58 + 108..0x58 + 112].copy_from_slice(&16u32.to_le_bytes()); // NumberOfRvaAndSizes
|
||||
b.extend_from_slice(tail);
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recognises_the_libraries_by_their_exports() {
|
||||
assert!(is_pc_xg(&pe(
|
||||
b"XGCreateTextureComputer\0XGComputeTexture2DLayout\0"
|
||||
)));
|
||||
// BetterXen's own shim exports only what titles import.
|
||||
assert!(!is_pc_xg(&pe(
|
||||
b"XGCreateTextureComputer\0XGSuggestSwizzleMode\0"
|
||||
)));
|
||||
assert!(!is_pc_xg(
|
||||
b"XGCreateTextureComputer\0XGComputeTexture2DLayout\0"
|
||||
));
|
||||
assert!(is_bcpack(&pe(b"BCPackCompress\0BCPackDecompress\0")));
|
||||
assert!(!is_bcpack(&pe(b"BCPackCompress\0")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_by_content_and_merges_beside_the_shims() {
|
||||
let root = std::env::temp_dir().join(format!("bx-gdk-libs-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
let gdk = root.join("gdk");
|
||||
fs::create_dir_all(gdk.join("a/b")).unwrap();
|
||||
fs::create_dir_all(gdk.join("c")).unwrap();
|
||||
fs::write(
|
||||
gdk.join("a/b/xg_xs.dll"),
|
||||
pe(b"XGCreateTextureComputer\0XGComputeTexture2DLayout\0"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(gdk.join("c/xg_xs.dll"), pe(b"XGCreateTextureComputer\0")).unwrap(); // not the PC library
|
||||
fs::write(gdk.join("c/BCPack.dll"), pe(b"BCPackDecompress\0")).unwrap();
|
||||
let libs = find(&gdk);
|
||||
assert_eq!(libs.xg, Some(gdk.join("a/b/xg_xs.dll")));
|
||||
assert_eq!(libs.bcpack, Some(gdk.join("c/BCPack.dll")));
|
||||
|
||||
let shims = root.join("shims");
|
||||
fs::create_dir_all(&shims).unwrap();
|
||||
fs::write(shims.join("xg_xs.dll"), b"shim").unwrap();
|
||||
fs::write(shims.join("d3d12_xs.dll"), b"d3d12").unwrap();
|
||||
let out = root.join("out");
|
||||
let staged = merge_shims(&shims, &libs, &out).unwrap();
|
||||
assert_eq!(staged, Some(out.join("BCPack.dll")));
|
||||
assert_eq!(fs::read(out.join("d3d12_xs.dll")).unwrap(), b"d3d12");
|
||||
assert_eq!(
|
||||
fs::read(out.join("xg_xs.dll")).unwrap(),
|
||||
fs::read(gdk.join("a/b/xg_xs.dll")).unwrap()
|
||||
);
|
||||
assert_eq!(fs::read(shims.join("xg_xs.dll")).unwrap(), b"shim");
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
+1249
-26
File diff suppressed because it is too large.
Load diff
@@ -6,6 +6,8 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub mod report;
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct TraceSummary {
|
||||
pub total_lines: usize,
|
||||
@@ -18,6 +20,9 @@ pub struct TraceSummary {
|
||||
pub amd_traps: BTreeMap<String, TrapCount>,
|
||||
pub adx_errors: usize,
|
||||
pub unhandled_exceptions: Vec<UnhandledException>,
|
||||
/// First-chance `breakpoint_exception` records (int3 and assertion failures), which a
|
||||
/// guest's own crash reporter would otherwise hide from `unhandled_exception`.
|
||||
pub breakpoint_exceptions: Vec<BreakpointException>,
|
||||
pub unimpl_apis: BTreeMap<String, usize>,
|
||||
pub unimpl_vtables: BTreeMap<String, usize>,
|
||||
/// Aggregated `shader_gate` records from `d3d12_xs.dll` (#496).
|
||||
@@ -182,6 +187,30 @@ pub struct UnhandledException {
|
||||
pub rip: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct BreakpointException {
|
||||
pub exception_code: Option<String>,
|
||||
pub module: Option<String>,
|
||||
pub module_base: Option<String>,
|
||||
pub rva: Option<String>,
|
||||
/// The faulting address, which locates a breakpoint outside any image (module `?`).
|
||||
pub address: Option<String>,
|
||||
/// 1-based index of this record and the per-process cap, so a reader can tell a run
|
||||
/// that hit the cap (later breakpoints not recorded) from one that stopped short of it.
|
||||
pub record: Option<u32>,
|
||||
pub limit: Option<u32>,
|
||||
}
|
||||
|
||||
fn extract_json_u32(line: &str, key: &str) -> Option<u32> {
|
||||
let needle = format!("\"{key}\":");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
let digits: &str = &line[start..];
|
||||
let end = digits
|
||||
.find(|c: char| !c.is_ascii_digit())
|
||||
.unwrap_or(digits.len());
|
||||
digits[..end].parse().ok()
|
||||
}
|
||||
|
||||
fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
|
||||
let needle = format!("\"{key}\":\"");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
@@ -344,6 +373,17 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
rip: extract_json_str(trimmed, "rip").map(str::to_owned),
|
||||
});
|
||||
}
|
||||
"breakpoint_exception" => {
|
||||
summary.breakpoint_exceptions.push(BreakpointException {
|
||||
exception_code: extract_json_str(trimmed, "exception_code").map(str::to_owned),
|
||||
module: extract_json_str(trimmed, "module").map(str::to_owned),
|
||||
module_base: extract_json_str(trimmed, "module_base").map(str::to_owned),
|
||||
rva: extract_json_str(trimmed, "rva").map(str::to_owned),
|
||||
address: extract_json_str(trimmed, "address").map(str::to_owned),
|
||||
record: extract_json_u32(trimmed, "record"),
|
||||
limit: extract_json_u32(trimmed, "limit"),
|
||||
});
|
||||
}
|
||||
"unimpl_api" => *summary.unimpl_apis.entry(detail.to_string()).or_insert(0) += 1,
|
||||
"unimpl_vtable" => {
|
||||
*summary
|
||||
@@ -420,6 +460,39 @@ mod tests {
|
||||
assert_eq!(summary.clwb_trap_lower_bound, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_breakpoint_exceptions_in_log_order() {
|
||||
let log = r#"
|
||||
{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x0000000002236178","address":"0x0000000142236178","record":1,"limit":16}
|
||||
{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0xc0000420","module":"?","module_base":"0x0000000000000000","rva":"0x0000000000000000","address":"0x0000000000410000","record":2,"limit":16}
|
||||
"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert!(summary.unhandled_exceptions.is_empty());
|
||||
assert_eq!(
|
||||
summary.breakpoint_exceptions,
|
||||
[
|
||||
BreakpointException {
|
||||
exception_code: Some("0x80000003".into()),
|
||||
module: Some("title.exe".into()),
|
||||
module_base: Some("0x0000000140000000".into()),
|
||||
rva: Some("0x0000000002236178".into()),
|
||||
address: Some("0x0000000142236178".into()),
|
||||
record: Some(1),
|
||||
limit: Some(16),
|
||||
},
|
||||
BreakpointException {
|
||||
exception_code: Some("0xc0000420".into()),
|
||||
module: Some("?".into()),
|
||||
module_base: Some("0x0000000000000000".into()),
|
||||
rva: Some("0x0000000000000000".into()),
|
||||
address: Some("0x0000000000410000".into()),
|
||||
record: Some(2),
|
||||
limit: Some(16),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_unhandled_exceptions_in_log_order() {
|
||||
let log = r#"
|
||||
|
||||
@@ -0,0 +1,582 @@
|
||||
//! Run reports for the blocker queue (docs/process/working-method.md, "Run protocol").
|
||||
//!
|
||||
//! One JSONL log is one run. [`report_run`] reduces it to what decides the next task: how the
|
||||
//! run ended, how far it got, and everything it stopped on. [`RunReport::signatures`] turns
|
||||
//! those into the fixed strings blocker issues are titled with, so two people who hit the
|
||||
//! same thing file the same issue. [`render_summary`] puts several runs side by side.
|
||||
//!
|
||||
//! What a log cannot show is said, not guessed: a run with no `run_end` record has an unknown
|
||||
//! outcome, and a stall cannot be told from slow presentation because frames are logged at
|
||||
//! powers of two.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
/// BetterXen's own guest modules. A fault whose innermost frame is in one of them is ours.
|
||||
const BETTERXEN_MODULES: &[&str] = &[
|
||||
"d3d12_xs.dll",
|
||||
"xmem.dll",
|
||||
"xcrdapi.dll",
|
||||
"xgameruntime.dll",
|
||||
"xg_xs.dll",
|
||||
"acphal.dll",
|
||||
"xapu.dll",
|
||||
"chad.dll",
|
||||
"gameinput.dll",
|
||||
"bx_runtime_veh.dll",
|
||||
"bx_shader_bridge.dll",
|
||||
"ffx_bvh_hooks.dll",
|
||||
];
|
||||
|
||||
/// How a run ended, from the launcher's `run_end` record.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub enum RunEnd {
|
||||
/// No `run_end` record: the launcher was killed, or the log predates the record.
|
||||
#[default]
|
||||
Unknown,
|
||||
/// The guest exited by itself with this status.
|
||||
Exited(i32),
|
||||
/// The launcher's `--timeout` stopped it: the run lasted as long as it was allowed to.
|
||||
TimedOut,
|
||||
/// A signal stopped the launcher.
|
||||
Signalled(i32),
|
||||
/// CrossOver could not be started.
|
||||
LaunchFailed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct RunReport {
|
||||
pub events: u64,
|
||||
/// Guest clock span of the log, in milliseconds.
|
||||
pub span_ms: u64,
|
||||
pub end: RunEnd,
|
||||
/// The last power-of-two frame count logged: at least this many frames were presented.
|
||||
pub frames_at_least: Option<u64>,
|
||||
/// Unimplemented calls reached, by signature, with how often.
|
||||
pub unimplemented: BTreeMap<String, u64>,
|
||||
/// Faults whose innermost frame is in a BetterXen module, by module.
|
||||
pub faults: BTreeMap<String, u64>,
|
||||
/// Exceptions nothing handled.
|
||||
pub unhandled_exceptions: u64,
|
||||
/// Pipeline stages that reached the shader gate, by "kind decision" (for example
|
||||
/// "stream reject_unclassified_dxil").
|
||||
pub shader_gate: BTreeMap<String, u64>,
|
||||
/// Refused pipeline creations by kind.
|
||||
pub pipelines_refused: BTreeMap<String, u64>,
|
||||
/// Draws and dispatches skipped with a null pipeline bound (a lower bound).
|
||||
pub skipped_work_at_least: Option<u64>,
|
||||
}
|
||||
|
||||
fn json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
|
||||
let needle = format!("\"{key}\":\"");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
let rest = &line[start..];
|
||||
// Details do not contain escaped quotes in practice; stop at the first unescaped one.
|
||||
let mut end = 0;
|
||||
let bytes = rest.as_bytes();
|
||||
while end < bytes.len() {
|
||||
if bytes[end] == b'"' && (end == 0 || bytes[end - 1] != b'\\') {
|
||||
return Some(&rest[..end]);
|
||||
}
|
||||
end += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn json_u64(line: &str, key: &str) -> Option<u64> {
|
||||
let needle = format!("\"{key}\":");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
let digits = &line[start..];
|
||||
let end = digits
|
||||
.find(|c: char| !c.is_ascii_digit())
|
||||
.unwrap_or(digits.len());
|
||||
digits[..end].parse().ok()
|
||||
}
|
||||
|
||||
fn number_after(detail: &str, key: &str) -> Option<u64> {
|
||||
let start = detail.find(key)? + key.len();
|
||||
let digits = &detail[start..];
|
||||
let end = digits
|
||||
.find(|c: char| !c.is_ascii_digit())
|
||||
.unwrap_or(digits.len());
|
||||
digits[..end].parse().ok()
|
||||
}
|
||||
|
||||
/// `IXUser[3]::slot_3` -> `unimplemented IXUser slot 3`;
|
||||
/// `XboxDevice[81]::GetFrameStatisticsX` -> `unimplemented XboxDevice slot 81 (GetFrameStatisticsX)`.
|
||||
fn vtable_signature(detail: &str) -> String {
|
||||
let parsed = (|| {
|
||||
let open = detail.find('[')?;
|
||||
let close = detail[open..].find(']')? + open;
|
||||
let slot: u32 = detail[open + 1..close].parse().ok()?;
|
||||
let method = detail[close + 1..].strip_prefix("::")?;
|
||||
Some((&detail[..open], slot, method))
|
||||
})();
|
||||
match parsed {
|
||||
Some((interface, slot, method)) if method.starts_with("slot_") || method.is_empty() => {
|
||||
format!("unimplemented {interface} slot {slot}")
|
||||
}
|
||||
Some((interface, slot, method)) => {
|
||||
format!("unimplemented {interface} slot {slot} ({method})")
|
||||
}
|
||||
None => format!("unimplemented {detail}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The module of the innermost stack frame in an `av_context` detail (`... | stack: A.dll+12 B.dll+34`).
|
||||
fn fault_module(detail: &str) -> Option<&str> {
|
||||
let stack = detail.split("stack: ").nth(1)?;
|
||||
let frame = stack.split_whitespace().next()?;
|
||||
Some(frame.split('+').next().unwrap_or(frame))
|
||||
}
|
||||
|
||||
fn is_betterxen_module(module: &str) -> bool {
|
||||
BETTERXEN_MODULES
|
||||
.iter()
|
||||
.any(|m| m.eq_ignore_ascii_case(module))
|
||||
}
|
||||
|
||||
/// Reduces one run's JSONL log to its report.
|
||||
pub fn report_run(input: &str) -> RunReport {
|
||||
let mut report = RunReport::default();
|
||||
let mut first_ts = None;
|
||||
let mut last_ts = 0;
|
||||
for line in input.lines() {
|
||||
let line = line.trim();
|
||||
if !line.starts_with('{') {
|
||||
continue;
|
||||
}
|
||||
report.events += 1;
|
||||
let event = json_str(line, "event").unwrap_or("");
|
||||
let detail = json_str(line, "detail").unwrap_or("");
|
||||
if event == "run_end" {
|
||||
report.end = match detail {
|
||||
d if d.starts_with("outcome=exited") => {
|
||||
let status = d
|
||||
.split("status=")
|
||||
.nth(1)
|
||||
.and_then(|s| s.trim().parse().ok());
|
||||
status.map_or(RunEnd::Unknown, RunEnd::Exited)
|
||||
}
|
||||
"outcome=timeout" => RunEnd::TimedOut,
|
||||
d if d.starts_with("outcome=signal") => {
|
||||
RunEnd::Signalled(number_after(d, "signal=").unwrap_or(0) as i32)
|
||||
}
|
||||
"outcome=launch_failed" => RunEnd::LaunchFailed,
|
||||
_ => RunEnd::Unknown,
|
||||
};
|
||||
continue; // the launcher's record carries no guest timestamp
|
||||
}
|
||||
if let Some(ts) = json_u64(line, "ts_ms") {
|
||||
first_ts.get_or_insert(ts);
|
||||
last_ts = last_ts.max(ts);
|
||||
}
|
||||
match event {
|
||||
"presentx_frames" => {
|
||||
if let Some(n) = number_after(detail, "presented=") {
|
||||
report.frames_at_least = Some(report.frames_at_least.unwrap_or(0).max(n));
|
||||
}
|
||||
}
|
||||
"unimpl_vtable" => {
|
||||
*report
|
||||
.unimplemented
|
||||
.entry(vtable_signature(detail))
|
||||
.or_default() += 1
|
||||
}
|
||||
"unimpl_api" => {
|
||||
*report
|
||||
.unimplemented
|
||||
.entry(format!("unimplemented {detail}"))
|
||||
.or_default() += 1
|
||||
}
|
||||
"av_context" => {
|
||||
if let Some(module) = fault_module(detail).filter(|m| is_betterxen_module(m)) {
|
||||
*report.faults.entry(module.to_owned()).or_default() += 1;
|
||||
}
|
||||
}
|
||||
"unhandled_exception" => report.unhandled_exceptions += 1,
|
||||
"shader_gate" => {
|
||||
let kind = detail
|
||||
.split("pso=")
|
||||
.nth(1)
|
||||
.and_then(|s| s.split_whitespace().next());
|
||||
let decision = detail
|
||||
.split("decision=")
|
||||
.nth(1)
|
||||
.and_then(|s| s.split_whitespace().next());
|
||||
if let (Some(kind), Some(decision)) = (kind, decision) {
|
||||
*report
|
||||
.shader_gate
|
||||
.entry(format!("{kind} {decision}"))
|
||||
.or_default() += 1;
|
||||
}
|
||||
}
|
||||
"pipeline_refused" => {
|
||||
let kind = detail.split(" pipeline refused").next().unwrap_or(detail);
|
||||
*report.pipelines_refused.entry(kind.to_owned()).or_default() += 1;
|
||||
}
|
||||
"null_render_skip" => {
|
||||
if let Some(n) = number_after(detail, "total skipped=") {
|
||||
report.skipped_work_at_least =
|
||||
Some(report.skipped_work_at_least.unwrap_or(0).max(n));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
report.span_ms = first_ts.map_or(0, |first| last_ts.saturating_sub(first));
|
||||
report
|
||||
}
|
||||
|
||||
impl RunReport {
|
||||
/// The strings blocker issues are titled with (`[blocker] <signature>`), most severe first.
|
||||
pub fn signatures(&self) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
match self.end {
|
||||
RunEnd::Exited(status) if status != 0 => out.push(format!("exit status {status}")),
|
||||
RunEnd::LaunchFailed => out.push("launch failed".to_owned()),
|
||||
_ => {}
|
||||
}
|
||||
if self.unhandled_exceptions > 0 {
|
||||
out.push("unhandled exception".to_owned());
|
||||
}
|
||||
out.extend(
|
||||
self.faults
|
||||
.keys()
|
||||
.map(|module| format!("fault in {module}")),
|
||||
);
|
||||
out.extend(self.unimplemented.keys().cloned());
|
||||
if self.skipped_work_at_least.is_some() {
|
||||
out.push("draws or dispatches skipped with a null pipeline".to_owned());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// True when the run reached the frame loop and stopped on nothing: the Boot gate's
|
||||
/// per-run condition, except for its length, which the caller sets with `--timeout`.
|
||||
pub fn clean_boot(&self) -> bool {
|
||||
self.end == RunEnd::TimedOut
|
||||
&& self.frames_at_least.is_some()
|
||||
&& self.unimplemented.is_empty()
|
||||
&& self.faults.is_empty()
|
||||
&& self.unhandled_exceptions == 0
|
||||
}
|
||||
}
|
||||
|
||||
fn end_text(end: &RunEnd) -> String {
|
||||
match end {
|
||||
RunEnd::Unknown => "unknown (no run_end record)".to_owned(),
|
||||
RunEnd::Exited(status) => format!("exited by itself, status {status}"),
|
||||
RunEnd::TimedOut => "ran until the timeout".to_owned(),
|
||||
RunEnd::Signalled(signal) => format!("stopped by signal {signal}"),
|
||||
RunEnd::LaunchFailed => "launch failed".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The report of one run, as text.
|
||||
pub fn render_run(name: &str, report: &RunReport) -> String {
|
||||
let mut out = String::new();
|
||||
let _ = writeln!(out, "Run {name}");
|
||||
let _ = writeln!(out, " outcome : {}", end_text(&report.end));
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" frames presented : {}",
|
||||
report
|
||||
.frames_at_least
|
||||
.map_or("none".to_owned(), |n| format!("at least {n}"))
|
||||
);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" log span : {:.1} s, {} events",
|
||||
report.span_ms as f64 / 1000.0,
|
||||
report.events
|
||||
);
|
||||
if !report.unimplemented.is_empty() {
|
||||
let _ = writeln!(out, " unimplemented calls:");
|
||||
for (signature, count) in &report.unimplemented {
|
||||
let _ = writeln!(out, " {count:>7}x {signature}");
|
||||
}
|
||||
}
|
||||
if !report.faults.is_empty() || report.unhandled_exceptions > 0 {
|
||||
let _ = writeln!(out, " faults:");
|
||||
for (module, count) in &report.faults {
|
||||
let _ = writeln!(out, " {count:>7}x fault in {module}");
|
||||
}
|
||||
if report.unhandled_exceptions > 0 {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {:>7}x unhandled exception",
|
||||
report.unhandled_exceptions
|
||||
);
|
||||
}
|
||||
}
|
||||
if !report.shader_gate.is_empty() || !report.pipelines_refused.is_empty() {
|
||||
let _ = writeln!(out, " pipelines:");
|
||||
for (kind, count) in &report.shader_gate {
|
||||
let _ = writeln!(out, " {count:>7}x shader stage: {kind}");
|
||||
}
|
||||
for (kind, count) in &report.pipelines_refused {
|
||||
let _ = writeln!(out, " {count:>7}x refused: {kind}");
|
||||
}
|
||||
if let Some(skipped) = report.skipped_work_at_least {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" at least {skipped} draws or dispatches skipped (null pipeline)"
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Several runs side by side, then every signature with the number of runs that hit it.
|
||||
pub fn render_summary(runs: &[(String, RunReport)]) -> String {
|
||||
let mut out = String::new();
|
||||
let total = runs.len();
|
||||
let _ = writeln!(out, "Summary of {total} run(s)");
|
||||
for (name, report) in runs {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {name}: {}; frames {}; {}",
|
||||
end_text(&report.end),
|
||||
report
|
||||
.frames_at_least
|
||||
.map_or("none".to_owned(), |n| format!(">= {n}")),
|
||||
if report.clean_boot() {
|
||||
"clean"
|
||||
} else {
|
||||
"not clean"
|
||||
}
|
||||
);
|
||||
}
|
||||
let clean = runs.iter().filter(|(_, r)| r.clean_boot()).count();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"Clean runs (frame loop reached, nothing stopped on, ran to the timeout): {clean} of {total}"
|
||||
);
|
||||
let mut hits: BTreeMap<String, usize> = BTreeMap::new();
|
||||
for (_, report) in runs {
|
||||
for signature in report.signatures() {
|
||||
*hits.entry(signature).or_default() += 1;
|
||||
}
|
||||
}
|
||||
if hits.is_empty() {
|
||||
let _ = writeln!(out, "Signatures: none");
|
||||
} else {
|
||||
let _ = writeln!(out, "Signatures (runs that hit each):");
|
||||
let mut ordered: Vec<_> = hits.into_iter().collect();
|
||||
ordered.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||
for (signature, count) in ordered {
|
||||
let _ = writeln!(out, " {count} of {total} {signature}");
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn line(ts: u64, sub: &str, event: &str, detail: &str) -> String {
|
||||
format!(
|
||||
"{{\"ts_ms\":{ts},\"tid\":1,\"level\":\"INFO\",\"sub\":\"{sub}\",\"event\":\"{event}\",\"detail\":\"{detail}\"}}\n"
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clean_run_reports_frames_span_and_no_signatures() {
|
||||
let log = line(
|
||||
1000,
|
||||
"d3d12_xs",
|
||||
"presentx_frames",
|
||||
"frames presented=1 last hr=0x00000000",
|
||||
) + &line(
|
||||
4000,
|
||||
"d3d12_xs",
|
||||
"presentx_frames",
|
||||
"frames presented=64 last hr=0x00000000",
|
||||
) + &line(0, "bx_cli", "run_end", "outcome=timeout");
|
||||
let report = report_run(&log);
|
||||
assert_eq!(report.frames_at_least, Some(64));
|
||||
assert_eq!(
|
||||
report.span_ms, 3000,
|
||||
"the launcher's record must not stretch the guest span"
|
||||
);
|
||||
assert_eq!(report.end, RunEnd::TimedOut);
|
||||
assert!(report.clean_boot());
|
||||
assert!(report.signatures().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unimplemented_calls_become_stable_signatures() {
|
||||
let log = line(1, "com_vtable", "unimpl_vtable", "IXUser[3]::slot_3")
|
||||
+ &line(
|
||||
2,
|
||||
"com_vtable",
|
||||
"unimpl_vtable",
|
||||
"XboxDevice[81]::GetFrameStatisticsX",
|
||||
)
|
||||
+ &line(
|
||||
3,
|
||||
"com_vtable",
|
||||
"unimpl_vtable",
|
||||
"XboxDevice[81]::GetFrameStatisticsX",
|
||||
)
|
||||
+ &line(
|
||||
4,
|
||||
"stub",
|
||||
"unimpl_api",
|
||||
"d3d12_xs.dll!CreatePlacedResourceX(texture contents)",
|
||||
);
|
||||
let report = report_run(&log);
|
||||
assert_eq!(
|
||||
report.unimplemented.get("unimplemented IXUser slot 3"),
|
||||
Some(&1)
|
||||
);
|
||||
assert_eq!(
|
||||
report
|
||||
.unimplemented
|
||||
.get("unimplemented XboxDevice slot 81 (GetFrameStatisticsX)"),
|
||||
Some(&2)
|
||||
);
|
||||
assert!(report.signatures().contains(
|
||||
&"unimplemented d3d12_xs.dll!CreatePlacedResourceX(texture contents)".to_owned()
|
||||
));
|
||||
assert!(
|
||||
!report.clean_boot(),
|
||||
"an unimplemented call is not a clean run"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fault_counts_only_when_its_innermost_frame_is_a_betterxen_module() {
|
||||
let ours = line(
|
||||
1,
|
||||
"runtime_veh",
|
||||
"av_context",
|
||||
"rip=1 fault=2 | stack: XCRDAPI.dll+9a51 ntdll.dll+10",
|
||||
);
|
||||
let theirs = line(
|
||||
2,
|
||||
"runtime_veh",
|
||||
"av_context",
|
||||
"rip=1 fault=2 | stack: title.exe+10 XCRDAPI.dll+9a51",
|
||||
);
|
||||
let report = report_run(&(ours + &theirs));
|
||||
assert_eq!(report.faults.get("XCRDAPI.dll"), Some(&1));
|
||||
assert_eq!(report.faults.len(), 1);
|
||||
assert_eq!(report.signatures(), vec!["fault in XCRDAPI.dll".to_owned()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_of_a_run_is_read_from_the_launcher_record() {
|
||||
let exited = report_run(&line(0, "bx_cli", "run_end", "outcome=exited status=5"));
|
||||
assert_eq!(exited.end, RunEnd::Exited(5));
|
||||
assert_eq!(exited.signatures(), vec!["exit status 5".to_owned()]);
|
||||
assert_eq!(
|
||||
report_run(&line(0, "bx_cli", "run_end", "outcome=exited status=0")).signatures(),
|
||||
Vec::<String>::new()
|
||||
);
|
||||
assert_eq!(
|
||||
report_run(&line(0, "bx_cli", "run_end", "outcome=signal signal=15")).end,
|
||||
RunEnd::Signalled(15)
|
||||
);
|
||||
assert_eq!(
|
||||
report_run(&line(0, "bx_cli", "run_end", "outcome=launch_failed")).end,
|
||||
RunEnd::LaunchFailed
|
||||
);
|
||||
// No record: unknown, and never "clean".
|
||||
let unknown = report_run(&line(
|
||||
1,
|
||||
"d3d12_xs",
|
||||
"presentx_frames",
|
||||
"frames presented=8 last hr=0x0",
|
||||
));
|
||||
assert_eq!(unknown.end, RunEnd::Unknown);
|
||||
assert!(!unknown.clean_boot());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipelines_are_counted_by_kind() {
|
||||
let log = line(
|
||||
1,
|
||||
"d3d12_xs",
|
||||
"shader_gate",
|
||||
"pso=stream stage=VS decision=reject_unclassified_dxil hr=0x80004001",
|
||||
) + &line(
|
||||
2,
|
||||
"d3d12_xs",
|
||||
"shader_gate",
|
||||
"pso=compute stage=CS decision=pass_dxil hr=0x00000000",
|
||||
) + &line(
|
||||
3,
|
||||
"d3d12_xs",
|
||||
"pipeline_refused",
|
||||
"deserialized graphics (console code) pipeline refused hr=0x80004001",
|
||||
) + &line(
|
||||
4,
|
||||
"d3d12_xs",
|
||||
"null_render_skip",
|
||||
"DrawInstanced with a null pipeline bound; total skipped=4",
|
||||
) + &line(
|
||||
5,
|
||||
"d3d12_xs",
|
||||
"null_render_skip",
|
||||
"DrawInstanced with a null pipeline bound; total skipped=8",
|
||||
);
|
||||
let report = report_run(&log);
|
||||
assert_eq!(
|
||||
report.shader_gate.get("stream reject_unclassified_dxil"),
|
||||
Some(&1)
|
||||
);
|
||||
assert_eq!(report.shader_gate.get("compute pass_dxil"), Some(&1));
|
||||
assert_eq!(
|
||||
report
|
||||
.pipelines_refused
|
||||
.get("deserialized graphics (console code)"),
|
||||
Some(&1)
|
||||
);
|
||||
assert_eq!(report.skipped_work_at_least, Some(8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_summary_counts_runs_per_signature_and_clean_runs() {
|
||||
let clean = report_run(
|
||||
&(line(
|
||||
1,
|
||||
"d3d12_xs",
|
||||
"presentx_frames",
|
||||
"frames presented=16 last hr=0x0",
|
||||
) + &line(0, "bx_cli", "run_end", "outcome=timeout")),
|
||||
);
|
||||
let stopped = report_run(
|
||||
&(line(1, "com_vtable", "unimpl_vtable", "IXUser[3]::slot_3")
|
||||
+ &line(0, "bx_cli", "run_end", "outcome=exited status=1")),
|
||||
);
|
||||
let text = render_summary(&[
|
||||
("a".to_owned(), clean),
|
||||
("b".to_owned(), stopped.clone()),
|
||||
("c".to_owned(), stopped),
|
||||
]);
|
||||
assert!(
|
||||
text.contains(
|
||||
"Clean runs (frame loop reached, nothing stopped on, ran to the timeout): 1 of 3"
|
||||
),
|
||||
"{text}"
|
||||
);
|
||||
assert!(text.contains(" 2 of 3 exit status 1\n"), "{text}");
|
||||
assert!(
|
||||
text.contains(" 2 of 3 unimplemented IXUser slot 3\n"),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_that_are_not_json_records_are_ignored() {
|
||||
let report = report_run("warning: not a record\n\n{\"broken\n");
|
||||
assert_eq!(
|
||||
report.events, 1,
|
||||
"a line starting with a brace is counted even when malformed"
|
||||
);
|
||||
assert!(report.signatures().is_empty());
|
||||
}
|
||||
}
|
||||
Executable
+66
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env bash
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# Build the shader corpus (#649) locally. For every kernel in shader-transpiler/corpus/hlsl:
|
||||
# <name>.xs.cso / .xs.lst console container (DXIL + ACCC/FSPX) and listing, from xdxc
|
||||
# <name>.pix.lst console ISA listing with encodings, from the PIX compiler
|
||||
# <name>.pc.cso DXIL from the public PC DXC, for a D3DMetal reference run
|
||||
# <name>.code.bin / .aco.s console machine code extracted from the ACCC chunk, and its
|
||||
# llvm-mc gfx1030 disassembly
|
||||
# Outputs go to $OUT (default target/shader-corpus, which git ignores) and must not be
|
||||
# committed: they are compiler outputs from authorized GDK tools (see the corpus README).
|
||||
#
|
||||
# Required environment:
|
||||
# WINE a CrossOver/Wine loader that accepts --bottle (CrossOver's bin/wine)
|
||||
# BOTTLE a scratch bottle for the compilers (never a title's bottle)
|
||||
# XDXC the console xdxc.exe (GDK, xbox/bin/gen9)
|
||||
# PIX_DXC the console PIX dxc.exe (GDK, bin/Scarlett/pixsc)
|
||||
# DXC the PC dxc.exe from DXC release v1.9.2609
|
||||
# LLVM_MC llvm-mc built with the AMDGPU target
|
||||
set -euo pipefail
|
||||
|
||||
for var in WINE BOTTLE XDXC PIX_DXC DXC LLVM_MC; do
|
||||
if [ -z "${!var:-}" ]; then
|
||||
echo "error: set $var (see the header of $0)" >&2
|
||||
exit 2
|
||||
fi
|
||||
done
|
||||
|
||||
root=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
src="$root/shader-transpiler/corpus/hlsl"
|
||||
out=${OUT:-$root/target/shader-corpus}
|
||||
mkdir -p "$out"
|
||||
|
||||
# Wine takes Windows paths; Z: maps the host root.
|
||||
win() { printf 'Z:%s' "$1"; }
|
||||
compile() { WINEDEBUG=-all "$WINE" --bottle "$BOTTLE" "$@"; }
|
||||
|
||||
failures=0
|
||||
for hlsl in "$src"/*.hlsl; do
|
||||
name=$(basename "$hlsl" .hlsl)
|
||||
log="$out/$name.log"
|
||||
: > "$log"
|
||||
if ! compile "$XDXC" -T cs_6_6 -E main -Fo "$(win "$out/$name.xs.cso")" -Fc "$(win "$out/$name.xs.lst")" \
|
||||
"$(win "$hlsl")" >>"$log" 2>&1; then
|
||||
echo "FAIL $name: xdxc (see $log)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
if ! compile "$PIX_DXC" -T cs_6_6 -E main -Fc "$(win "$out/$name.pix.lst")" "$(win "$hlsl")" >>"$log" 2>&1; then
|
||||
echo "FAIL $name: PIX dxc (see $log)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
if ! compile "$DXC" -nologo -T cs_6_6 -E main -Fo "$(win "$out/$name.pc.cso")" "$(win "$hlsl")" >>"$log" 2>&1; then
|
||||
echo "FAIL $name: PC dxc (see $log)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
if ! python3 "$root/scripts/shader-corpus/extract_code.py" "$out/$name.xs.cso" \
|
||||
--bin "$out/$name.code.bin" --asm "$out/$name.aco.s" --llvm-mc "$LLVM_MC"; then
|
||||
echo "FAIL $name: code extraction or decode (see $out/$name.aco.s)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$failures" -ne 0 ]; then
|
||||
echo "FAIL: shader corpus ($failures kernel(s) failed)"
|
||||
exit 1
|
||||
fi
|
||||
# Sums of the compiled inputs, so two people with the compilers can confirm they hold the same
|
||||
# corpus (README, "Reproducibility"). Local only, like every other output.
|
||||
(cd "$out" && shasum -a 256 ./*.xs.cso ./*.pc.cso > SHA256SUMS)
|
||||
echo "PASS: shader corpus built in $out"
|
||||
@@ -0,0 +1,158 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Extract the RDNA 2 code from a console-compiled DXBC container (#649).
|
||||
|
||||
The layout below was derived from containers the console compiler produced for BetterXen's own
|
||||
corpus kernels (shader-transpiler/corpus/README.md). Every assumption is checked; anything that
|
||||
does not match raises instead of guessing.
|
||||
|
||||
- DXBC: chunk count at byte 28, chunk offsets from byte 32; each chunk is a FourCC, a u32 size
|
||||
and the payload. The console code is in the `ACCC` chunk.
|
||||
- FSPX (the ACCC payload): a 16-byte header (magic `FSPX`, version, section count, total size),
|
||||
then one 16-byte entry per section: kind, offset, size, reserved (0). Offsets are relative to
|
||||
the start of the payload.
|
||||
- Section kind 6 holds the code. It starts with `v_nop_xbox_data` instructions that carry the
|
||||
shader hash, followed by gfx1030 machine code ending in `s_endpgm`. A `v_nop_xbox_data` is the
|
||||
public VOP3 `v_nop` opcode (top 16 bits of the first word 0xD580) whose third source operand is
|
||||
a 32-bit literal (operand value 255), which makes it 12 bytes; the public decoder rejects that
|
||||
form. A plain `v_nop` (8 bytes, no literal) is ordinary code and is not skipped.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
FSPX_MAGIC = b"FSPX"
|
||||
CODE_SECTION_KIND = 6
|
||||
XBOX_DATA_NOP_HIGH = 0xD580 # VOP3 v_nop, top 16 bits of the first word
|
||||
XBOX_DATA_NOP_BYTES = 12 # two VOP3 words and one 32-bit literal
|
||||
VOP3_SRC2_SHIFT = 18 # second word: src0 [8:0], src1 [17:9], src2 [26:18]
|
||||
VOP3_OPERAND_MASK = 0x1FF
|
||||
OPERAND_LITERAL = 255 # public gfx10 operand value for "a 32-bit literal follows"
|
||||
S_ENDPGM = 0xBF810000
|
||||
|
||||
|
||||
class LayoutError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def chunk(container, fourcc):
|
||||
if container[:4] != b"DXBC" or len(container) < 32:
|
||||
raise LayoutError("not a DXBC container")
|
||||
count = struct.unpack_from("<I", container, 28)[0]
|
||||
if 32 + 4 * count > len(container):
|
||||
raise LayoutError("chunk table overruns the container")
|
||||
for i in range(count):
|
||||
offset = struct.unpack_from("<I", container, 32 + 4 * i)[0]
|
||||
if offset + 8 > len(container):
|
||||
raise LayoutError(f"chunk {i} header overruns the container")
|
||||
size = struct.unpack_from("<I", container, offset + 4)[0]
|
||||
if container[offset:offset + 4] == fourcc:
|
||||
if offset + 8 + size > len(container):
|
||||
raise LayoutError(f"{fourcc.decode()} chunk overruns the container")
|
||||
return container[offset + 8:offset + 8 + size]
|
||||
raise LayoutError(f"no {fourcc.decode()} chunk")
|
||||
|
||||
|
||||
def sections(payload):
|
||||
if payload[:4] != FSPX_MAGIC or len(payload) < 16:
|
||||
raise LayoutError("ACCC payload does not start with FSPX")
|
||||
_version, count, total = struct.unpack_from("<III", payload, 4)
|
||||
if total != len(payload):
|
||||
raise LayoutError(f"FSPX total size {total} != payload size {len(payload)}")
|
||||
table_end = 16 + 16 * count
|
||||
if table_end > len(payload):
|
||||
raise LayoutError("FSPX section table overruns the payload")
|
||||
result = []
|
||||
for i in range(count):
|
||||
kind, offset, size, reserved = struct.unpack_from("<IIII", payload, 16 + 16 * i)
|
||||
if reserved != 0:
|
||||
raise LayoutError(f"FSPX section {i} reserved word is {reserved:#x}, not 0")
|
||||
if offset < table_end or offset + size > len(payload):
|
||||
raise LayoutError(f"FSPX section {i} [{offset}, {offset + size}) is out of bounds")
|
||||
result.append((kind, offset, size))
|
||||
return result
|
||||
|
||||
|
||||
def code_section(payload):
|
||||
matches = [(o, s) for k, o, s in sections(payload) if k == CODE_SECTION_KIND]
|
||||
if len(matches) != 1:
|
||||
raise LayoutError(f"expected one kind-{CODE_SECTION_KIND} section, found {len(matches)}")
|
||||
offset, size = matches[0]
|
||||
return payload[offset:offset + size]
|
||||
|
||||
|
||||
def is_xbox_data_nop(code):
|
||||
"""True when `code` starts with a v_nop whose third source operand is a literal."""
|
||||
if len(code) < XBOX_DATA_NOP_BYTES:
|
||||
return False
|
||||
first, second = struct.unpack_from("<II", code, 0)
|
||||
return (first >> 16 == XBOX_DATA_NOP_HIGH
|
||||
and (second >> VOP3_SRC2_SHIFT) & VOP3_OPERAND_MASK == OPERAND_LITERAL)
|
||||
|
||||
|
||||
def strip_xbox_data(code):
|
||||
"""Return (machine code, number of v_nop_xbox_data skipped)."""
|
||||
skipped = 0
|
||||
while is_xbox_data_nop(code):
|
||||
code = code[XBOX_DATA_NOP_BYTES:]
|
||||
skipped += 1
|
||||
return code, skipped
|
||||
|
||||
|
||||
def until_endpgm(code):
|
||||
"""Cut after the first dword-aligned s_endpgm. A literal that happens to equal it is not
|
||||
excluded here; the disassembler run is the authority on instruction boundaries."""
|
||||
for i in range(0, len(code) - 3, 4):
|
||||
if struct.unpack_from("<I", code, i)[0] == S_ENDPGM:
|
||||
return code[:i + 4]
|
||||
raise LayoutError("no s_endpgm in the code section")
|
||||
|
||||
|
||||
def extract(container):
|
||||
code, skipped = strip_xbox_data(code_section(chunk(container, b"ACCC")))
|
||||
return until_endpgm(code), skipped
|
||||
|
||||
|
||||
def disassemble(code, llvm_mc):
|
||||
text = " ".join(f"0x{b:02x}" for b in code)
|
||||
run = subprocess.run(
|
||||
[llvm_mc, "-arch=amdgcn", "-mcpu=gfx1030", "--disassemble", "-show-encoding"],
|
||||
input=text, capture_output=True, text=True, check=False,
|
||||
)
|
||||
lines = [ln.strip() for ln in run.stdout.splitlines() if ln.strip() and not ln.strip().startswith(".")]
|
||||
problems = [ln for ln in run.stderr.splitlines() if "invalid" in ln.lower() or "warning" in ln.lower()]
|
||||
return lines, problems
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("container", help="console-compiled .cso (DXBC with an ACCC chunk)")
|
||||
parser.add_argument("--bin", help="write the extracted machine code here")
|
||||
parser.add_argument("--asm", help="write the llvm-mc disassembly here (needs --llvm-mc)")
|
||||
parser.add_argument("--llvm-mc", help="path to llvm-mc with the AMDGPU target")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
code, skipped = extract(open(args.container, "rb").read())
|
||||
except LayoutError as error:
|
||||
print(f"error: {args.container}: {error}", file=sys.stderr)
|
||||
return 2
|
||||
if args.bin:
|
||||
open(args.bin, "wb").write(code)
|
||||
status = 0
|
||||
summary = f"{len(code)} code bytes, {skipped} v_nop_xbox_data skipped"
|
||||
if args.llvm_mc:
|
||||
lines, problems = disassemble(code, args.llvm_mc)
|
||||
summary += f", {len(lines)} instructions"
|
||||
if problems or not lines or "s_endpgm" not in lines[-1]:
|
||||
summary += ", DECODE PROBLEMS"
|
||||
status = 1
|
||||
if args.asm:
|
||||
open(args.asm, "w").write("\n".join(lines + problems) + "\n")
|
||||
print(f"{args.container}: {summary}")
|
||||
return status
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,106 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Unit tests for extract_code.py on synthetic containers (no GDK or compiler needed)."""
|
||||
|
||||
import importlib.util
|
||||
import struct
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
spec = importlib.util.spec_from_file_location("extract_code", Path(__file__).with_name("extract_code.py"))
|
||||
ec = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(ec)
|
||||
|
||||
S_NOP = struct.pack("<I", 0xBF800000) # public gfx10 encoding of s_nop 0
|
||||
S_ENDPGM = struct.pack("<I", 0xBF810000)
|
||||
# Synthetic, not compiler output: the v_nop opcode with made-up low bits, a second word whose
|
||||
# third source operand is 255 (literal) with made-up low bits, and a made-up literal.
|
||||
XBOX_DATA = struct.pack("<III", 0xD5801111, 0x03FC2222, 0x33333333)
|
||||
# The public VOP3 encoding of a plain `v_nop` (llvm-mc -mcpu=gfx1030): 8 bytes, no literal.
|
||||
V_NOP_E64 = struct.pack("<II", 0xD5800000, 0x02010080)
|
||||
|
||||
|
||||
def fspx(sections, total=None):
|
||||
"""sections: list of (kind, bytes). Builds an FSPX payload with the parsed layout."""
|
||||
count = len(sections)
|
||||
offset = 16 + 16 * count
|
||||
table, body = b"", b""
|
||||
for kind, data in sections:
|
||||
table += struct.pack("<IIII", kind, offset + len(body), len(data), 0)
|
||||
body += data
|
||||
size = 16 + len(table) + len(body)
|
||||
return b"FSPX" + struct.pack("<III", 1, count, size if total is None else total) + table + body
|
||||
|
||||
|
||||
def dxbc(chunks):
|
||||
"""chunks: list of (fourcc, bytes)."""
|
||||
header = 32 + 4 * len(chunks)
|
||||
offsets, body = [], b""
|
||||
for fourcc, data in chunks:
|
||||
offsets.append(header + len(body))
|
||||
body += fourcc + struct.pack("<I", len(data)) + data
|
||||
total = header + len(body)
|
||||
head = b"DXBC" + b"\0" * 16 + struct.pack("<III", 1, total, len(chunks))
|
||||
return head + b"".join(struct.pack("<I", o) for o in offsets) + body
|
||||
|
||||
|
||||
class ExtractTests(unittest.TestCase):
|
||||
def test_extracts_code_after_xbox_data_nops(self):
|
||||
code = XBOX_DATA * 3 + S_NOP + S_ENDPGM + b"\0" * 8
|
||||
container = dxbc([(b"DXIL", b"x" * 12), (b"ACCC", fspx([(0, b"a" * 28), (6, code), (7, b"b" * 8)]))])
|
||||
extracted, skipped = ec.extract(container)
|
||||
self.assertEqual(skipped, 3)
|
||||
self.assertEqual(extracted, S_NOP + S_ENDPGM)
|
||||
|
||||
def test_plain_v_nop_is_code_not_xbox_data(self):
|
||||
# A plain v_nop at the start of the code must not be skipped as 12 bytes, which would
|
||||
# misalign everything after it.
|
||||
code = V_NOP_E64 + S_NOP + S_ENDPGM
|
||||
container = dxbc([(b"ACCC", fspx([(6, code)]))])
|
||||
self.assertEqual(ec.extract(container), (code, 0))
|
||||
|
||||
def test_plain_v_nop_after_xbox_data_is_kept(self):
|
||||
code = XBOX_DATA * 2 + V_NOP_E64 + S_ENDPGM
|
||||
container = dxbc([(b"ACCC", fspx([(6, code)]))])
|
||||
self.assertEqual(ec.extract(container), (V_NOP_E64 + S_ENDPGM, 2))
|
||||
|
||||
def test_no_xbox_data_nops(self):
|
||||
container = dxbc([(b"ACCC", fspx([(6, S_NOP + S_ENDPGM)]))])
|
||||
self.assertEqual(ec.extract(container), (S_NOP + S_ENDPGM, 0))
|
||||
|
||||
def test_missing_accc(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "no ACCC chunk"):
|
||||
ec.extract(dxbc([(b"DXIL", b"x" * 4)]))
|
||||
|
||||
def test_not_fspx(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "does not start with FSPX"):
|
||||
ec.extract(dxbc([(b"ACCC", b"ABCD" + b"\0" * 12)]))
|
||||
|
||||
def test_total_size_mismatch(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "total size"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(6, S_ENDPGM)], total=999))]))
|
||||
|
||||
def test_section_inside_table_is_rejected(self):
|
||||
payload = bytearray(fspx([(6, S_ENDPGM)]))
|
||||
struct.pack_into("<I", payload, 16 + 4, 4) # section offset points into the header
|
||||
with self.assertRaisesRegex(ec.LayoutError, "out of bounds"):
|
||||
ec.extract(dxbc([(b"ACCC", bytes(payload))]))
|
||||
|
||||
def test_nonzero_reserved_word_is_rejected(self):
|
||||
payload = bytearray(fspx([(6, S_ENDPGM)]))
|
||||
struct.pack_into("<I", payload, 16 + 12, 1)
|
||||
with self.assertRaisesRegex(ec.LayoutError, "reserved word"):
|
||||
ec.extract(dxbc([(b"ACCC", bytes(payload))]))
|
||||
|
||||
def test_needs_exactly_one_code_section(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "found 0"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(0, S_ENDPGM)]))]))
|
||||
with self.assertRaisesRegex(ec.LayoutError, "found 2"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(6, S_ENDPGM), (6, S_ENDPGM)]))]))
|
||||
|
||||
def test_code_without_endpgm(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "no s_endpgm"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(6, S_NOP * 4)]))]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,110 @@
|
||||
# Shader corpus (Phase 0, #649)
|
||||
|
||||
A corpus of BetterXen-authored compute kernels compiled for the console, so the RDNA 2 shader
|
||||
translator ([ADR 0008](../../docs/adr/0008-m2-shader-format-gate.md), Branch D2) can be tested
|
||||
against inputs whose correct behaviour is known independently of the translator
|
||||
([AGENTS.md](../../AGENTS.md) §5).
|
||||
|
||||
For each kernel in [`hlsl/`](hlsl), three compilers produce:
|
||||
|
||||
- the **console container** a title would ship: DXBC with `DXIL` **and** an `ACCC` chunk whose
|
||||
payload is an `FSPX` package holding the RDNA 2 code;
|
||||
- **the console compiler's listing** of the RDNA 2 code for the same source, with encodings (compiler output, not
|
||||
Microsoft documentation);
|
||||
- **PC DXIL** from the public DXC, which runs on D3DMetal today and gives the reference result.
|
||||
|
||||
## What is committed and what is not
|
||||
|
||||
| Committed | Not committed |
|
||||
|---|---|
|
||||
| The HLSL kernels in `hlsl/` (original BetterXen code, GPL-3.0-or-later) | Every compiler output: containers, listings, extracted code and disassembly |
|
||||
| [`scripts/shader-corpus/build.sh`](../../scripts/shader-corpus/build.sh) and [`extract_code.py`](../../scripts/shader-corpus/extract_code.py) with its unit tests | The GDK, its compilers, and any file from it |
|
||||
| Layout facts derived from our own outputs (below) | |
|
||||
|
||||
The console compilers come from authorized GDK material and run on BetterXen's own HLSL only.
|
||||
Their outputs stay in `target/shader-corpus/` (git-ignored) and are never committed. Run the
|
||||
compilers in a scratch bottle, never in a title's bottle.
|
||||
|
||||
The layout facts below are derived from those outputs and **are** published in this file. On
|
||||
2026-11-29 the repository owner reported that the team had approved publishing them, and decided
|
||||
that BetterXen is no longer a clean-room project ([CONTRIBUTING](../../CONTRIBUTING.md), #650):
|
||||
contributors may use the GDK compilers and read this file. The compilers, their outputs and the
|
||||
GDK itself are still never committed.
|
||||
|
||||
## Reproducibility
|
||||
|
||||
The corpus can only be rebuilt by someone who has the GDK compilers. CI cannot rebuild it, and a
|
||||
contributor without the GDK cannot reproduce its inputs. That limits what the corpus proves: it
|
||||
checks a translator against shaders with known source, on the word of whoever built it.
|
||||
|
||||
To let two people with access confirm they hold the same inputs, `build.sh` writes
|
||||
`target/shader-corpus/SHA256SUMS` with the SHA-256 of every `.xs.cso` and `.pc.cso`. The sums are
|
||||
not listed here yet: they are worth committing only once two independent builds agree, which
|
||||
also shows whether the compilers' output is deterministic.
|
||||
|
||||
## Building
|
||||
|
||||
```sh
|
||||
WINE=/Applications/CrossOver.app/Contents/SharedSupport/CrossOver/bin/wine \
|
||||
BOTTLE=<scratch bottle> \
|
||||
XDXC=<GDK>/…/xbox/bin/gen9/xdxc.exe \
|
||||
PIX_DXC=<GDK>/…/bin/Scarlett/pixsc/dxc.exe \
|
||||
DXC=<DXC v1.9.2609>/bin/x64/dxc.exe \
|
||||
LLVM_MC=$(brew --prefix llvm)/bin/llvm-mc \
|
||||
scripts/shader-corpus/build.sh
|
||||
```
|
||||
|
||||
All eight kernels currently build, and every kernel's console code extracts and decodes with
|
||||
LLVM's public `gfx1030` disassembler (2026-11-28, Apple Silicon, CrossOver 26.3):
|
||||
|
||||
| Kernel | What it exercises | Console instructions |
|
||||
|---|---|---|
|
||||
| `fill` | integer ALU | 11 |
|
||||
| `branch` | divergent if/else | 17 |
|
||||
| `loop` | per-lane trip count, early exit | 60 |
|
||||
| `lds` | groupshared memory, barriers, tree reduction | 58 |
|
||||
| `wave` | `WaveActiveSum`, `WavePrefixSum`, `WaveReadLaneFirst`, `WaveActiveBallot` | 47 |
|
||||
| `atomic` | global `InterlockedAdd` / `InterlockedMax` with returned values | 57 |
|
||||
| `floatmath` | `mad`, `sqrt`, `rcp`, float/uint conversion | 22 |
|
||||
| `groupid` | 2D groups, `SV_GroupID`, `SV_GroupThreadID`, `SV_GroupIndex` | 17 |
|
||||
|
||||
`extract_code.py`'s unit tests use synthetic containers and need no GDK:
|
||||
`python3 -m unittest scripts/shader-corpus/test_extract_code.py`.
|
||||
|
||||
## Layout facts (derived from our own outputs)
|
||||
|
||||
- **Container:** `xdxc` keeps the `DXIL` chunk and adds `ACCC`. Title containers can be `ACCC`-only;
|
||||
the `ACCC` format is the same. `bx-cli shader` rejects these containers with the same `FSPX`
|
||||
error as a title's console-only shaders, so the corpus is a faithful stand-in for that format.
|
||||
- **`FSPX`:** a 16-byte header (magic `FSPX`, version `1`, section count, total size equal to the
|
||||
payload size), then one 16-byte entry per section: kind, offset from the start of the payload,
|
||||
size, and a reserved `0`. The corpus containers have four sections, of kinds 0, 1, 6 and 7.
|
||||
- **Code:** section kind 6. It starts with `v_nop_xbox_data` instructions that carry the shader
|
||||
hash: the public VOP3 `v_nop` opcode (top 16 bits `0xD580`) with a literal as its third source
|
||||
operand, 12 bytes each, a form the public decoder rejects. A plain `v_nop` (8 bytes) is ordinary
|
||||
code. Every corpus kernel has three `v_nop_xbox_data`. They are followed by `gfx1030` machine code ending in `s_endpgm`, then
|
||||
padding.
|
||||
- **Two console backends.** `xdxc`'s `ACCC` code comes from its ACO step; the PIX compiler's
|
||||
listing comes from its NewBE step. They generate different code for the same source (for example,
|
||||
the inline buffer descriptor's word 3 is `0x31016fac` from ACO and `0x11014fac` from NewBE). The
|
||||
NewBE listing documents the console ABI (#638); the ACO code is what `ACCC` containers carry.
|
||||
Both use the root UAV address in `s[4:5]` here.
|
||||
|
||||
## Observations so far
|
||||
|
||||
- `wave` compiles to the cross-lane instructions that matter for running 64-wide waves on 32-wide
|
||||
Apple GPUs: DPP `row_shr` and `quad_perm`, `v_permlanex16`, `v_readlane` and `v_readfirstlane`.
|
||||
- **Open question:** in `wave`, LLVM decodes one instruction in the ballot sequence as
|
||||
`v_cmp_class_f16` with literal `0x7c01`, although the kernel has no half-precision code. Either
|
||||
ACO genuinely emits it there, or the console gives that opcode a meaning the public `gfx1030`
|
||||
decoder does not know. The reference runs below should tell.
|
||||
|
||||
## Next steps
|
||||
|
||||
1. A reference runner: dispatch each kernel's PC DXIL on D3DMetal with fixed inputs and record
|
||||
the output buffers as expected results, plus CPU-computed expectations where the result is a
|
||||
pure function of the inputs.
|
||||
2. The decoder (Phase 1), checked instruction by instruction against LLVM's disassembly and the
|
||||
NewBE listings.
|
||||
3. More kernels as the decoder grows: textures and samplers, structured control flow with nested
|
||||
loops, 64-bit atomics, and wave32 versus wave64 variants.
|
||||
@@ -0,0 +1,17 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Global atomics: add and max into shared counters, with returned old values.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint x = input[tid.x];
|
||||
uint before;
|
||||
InterlockedAdd(output[0], x, before);
|
||||
InterlockedMax(output[1], x);
|
||||
output[2u + tid.x] = before;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Divergent control flow: lanes take different sides of an if/else.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint x = input[tid.x];
|
||||
uint r;
|
||||
if ((x & 1u) != 0u) { r = x * 3u + 1u; } else { r = x >> 1; }
|
||||
output[tid.x] = r;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Integer ALU: multiply, shift, xor-add (no memory reads).
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint v = tid.x * 0x9e3779b1u;
|
||||
output[tid.x] = (v ^ (v >> 15)) + 0x01234567u;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Float ALU and conversions: fma, sqrt, rcp, float<->uint.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
float f = (float)input[tid.x] * asfloat(c0);
|
||||
float g = mad(f, 0.5f, 1.0f);
|
||||
float h = sqrt(abs(g)) + rcp(g + 2.0f);
|
||||
output[tid.x] = asuint(h) ^ (uint)floor(h * 256.0f);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// System values: group id, group thread id and flattened indices with a 2D group.
|
||||
[RootSignature(BX_RS)] [numthreads(8, 8, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID, uint3 gtid : SV_GroupThreadID, uint3 gid : SV_GroupID, uint gi : SV_GroupIndex) {
|
||||
uint idx = (gid.y * c0 + gid.x) * 64u + gi;
|
||||
output[idx] = (gtid.x << 24) | (gtid.y << 16) | (tid.x << 8) | tid.y;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Groupshared memory and barriers: a per-group tree reduction.
|
||||
groupshared uint scratch[64];
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID, uint3 gtid : SV_GroupThreadID, uint3 gid : SV_GroupID) {
|
||||
scratch[gtid.x] = input[tid.x];
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
for (uint s = 32u; s > 0u; s >>= 1) {
|
||||
if (gtid.x < s) { scratch[gtid.x] += scratch[gtid.x + s]; }
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
if (gtid.x == 0u) { output[gid.x] = scratch[0]; }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Loop with a per-lane, data-dependent trip count and an early exit.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint n = input[tid.x] % (c0 + 1u);
|
||||
uint acc = 0u;
|
||||
for (uint i = 0u; i < n; ++i) {
|
||||
acc += i * c1;
|
||||
if (acc > c2) { break; }
|
||||
}
|
||||
output[tid.x] = acc;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Cross-lane wave operations: the costly case when a 64-wide wave runs as two 32-wide halves.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint x = input[tid.x];
|
||||
uint sum = WaveActiveSum(x);
|
||||
uint prefix = WavePrefixSum(x);
|
||||
uint first = WaveReadLaneFirst(x);
|
||||
uint4 ballot = WaveActiveBallot((x & 1u) != 0u);
|
||||
output[tid.x * 4u + 0u] = sum;
|
||||
output[tid.x * 4u + 1u] = prefix;
|
||||
output[tid.x * 4u + 2u] = first;
|
||||
output[tid.x * 4u + 3u] = countbits(ballot.x) + countbits(ballot.y);
|
||||
}
|
||||
@@ -8,9 +8,12 @@ bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
|
||||
xbox_facade.cpp
|
||||
frame_pacing.cpp
|
||||
placed_x.cpp
|
||||
gdk_xg.cpp
|
||||
descriptor_heaps.cpp
|
||||
committed.cpp
|
||||
console_formats.cpp
|
||||
pipelines.cpp
|
||||
rect_list.cpp
|
||||
gpu_writes.cpp
|
||||
fences.cpp
|
||||
presentx_xbox.cpp
|
||||
|
||||
@@ -11,10 +11,21 @@
|
||||
* hooks and title address checks see what they would see on the console. The page size the
|
||||
* console runtime requests is not documented: this layer asks for 2 MB pages for allocations of
|
||||
* at least 2 MB and 64 KB pages otherwise (measured against one title; logged per resource).
|
||||
*
|
||||
* The size of that request is the console's, not the host's, where the console layout is known:
|
||||
* a 2D render-target or unordered-access texture with one mip and one sample is laid out by the
|
||||
* console in 64 KB tiles (swizzle mode 64KB_R_X for every size; authorized GDK XG library). A
|
||||
* title that sizes its pool for those requests and checks what is left over sees the amount it
|
||||
* expects. The compression metadata XG adds after the tiles of a render target (8 KB to 96 KB in
|
||||
* the cases measured) is not included; every other resource keeps the host's size.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include "console_formats.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
extern "C" __declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, ULONGLONG attributes);
|
||||
|
||||
@@ -26,18 +37,67 @@ constexpr ULONGLONG kPageSize64K = 1ull << 14; // XALLOC_ATTRIBUTES.PageS
|
||||
constexpr ULONGLONG kPageSize2M = 2ull << 14;
|
||||
constexpr UINT64 k2M = 2ull << 20;
|
||||
|
||||
HRESULT finish(ID3D12Device* device, HRESULT hr, REFIID riid, void** ppv, const char* method) {
|
||||
constexpr UINT64 k64K = 64ull << 10;
|
||||
|
||||
// Bytes per element of an uncompressed colour format, 0 for anything else (depth, block
|
||||
// compressed, video, 96-bit). Formats 116, 117, 189 and 190 are console-only (GDK DXGI_FORMAT).
|
||||
UINT colour_element_bytes(DXGI_FORMAT f) {
|
||||
const UINT v = static_cast<UINT>(f);
|
||||
if (v >= DXGI_FORMAT_R32G32B32A32_TYPELESS && v <= DXGI_FORMAT_R32G32B32A32_SINT) return 16;
|
||||
if (v >= DXGI_FORMAT_R16G16B16A16_TYPELESS && v <= DXGI_FORMAT_R32G32_SINT) return 8;
|
||||
if (v >= DXGI_FORMAT_R10G10B10A2_TYPELESS && v <= DXGI_FORMAT_R32_SINT) return v == DXGI_FORMAT_D32_FLOAT ? 0 : 4;
|
||||
if (v >= DXGI_FORMAT_R8G8_TYPELESS && v <= DXGI_FORMAT_R16_SINT) return v == DXGI_FORMAT_D16_UNORM ? 0 : 2;
|
||||
if (v >= DXGI_FORMAT_R8_TYPELESS && v <= DXGI_FORMAT_A8_UNORM) return 1;
|
||||
if (v >= DXGI_FORMAT_B8G8R8A8_UNORM && v <= DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) return 4;
|
||||
if (v == DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM || v == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) return 4;
|
||||
if (v >= DXGI_FORMAT_B5G6R5_UNORM && v <= DXGI_FORMAT_B5G5R5A1_UNORM) return 2;
|
||||
if (v == DXGI_FORMAT_B4G4R4A4_UNORM) return 2;
|
||||
if (v == 116 || v == 117 || v == 189) return 4; // R10G10B10_7E3_A2_FLOAT, _6E4_A2_FLOAT, _SNORM_A2_UNORM
|
||||
if (v == 190) return 1; // R4G4_UNORM
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The console's size for `desc` (the host's geometry, the title's format) where its layout is
|
||||
// known, else 0. The tile of a 64 KB swizzle holds 64 KB of elements: 256x256 at 1 byte,
|
||||
// 256x128 at 2, 128x128 at 4, 128x64 at 8 and 64x64 at 16 (authorized GDK XG library: these
|
||||
// tile counts match its sizes exactly, before the metadata of a render target).
|
||||
UINT64 console_tiled_size(const D3D12_RESOURCE_DESC& desc, DXGI_FORMAT title_format) {
|
||||
constexpr UINT kTargets = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN ||
|
||||
desc.MipLevels != 1 || desc.SampleDesc.Count != 1 || !(desc.Flags & kTargets) ||
|
||||
(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
|
||||
return 0;
|
||||
}
|
||||
UINT tile_w = 0, tile_h = 0;
|
||||
switch (colour_element_bytes(title_format)) {
|
||||
case 1: tile_w = 256; tile_h = 256; break;
|
||||
case 2: tile_w = 256; tile_h = 128; break;
|
||||
case 4: tile_w = 128; tile_h = 128; break;
|
||||
case 8: tile_w = 128; tile_h = 64; break;
|
||||
case 16: tile_w = 64; tile_h = 64; break;
|
||||
default: return 0;
|
||||
}
|
||||
const UINT64 across = (desc.Width + tile_w - 1) / tile_w;
|
||||
const UINT64 down = (static_cast<UINT64>(desc.Height) + tile_h - 1) / tile_h;
|
||||
return across * down * desc.DepthOrArraySize * k64K;
|
||||
}
|
||||
|
||||
HRESULT finish(ID3D12Device* device, HRESULT hr, REFIID riid, void** ppv, const char* method,
|
||||
DXGI_FORMAT title_format) {
|
||||
if (FAILED(hr) || !ppv || !*ppv) return hr;
|
||||
// *ppv is the host resource as `riid`; every ID3D12Resource* interface pointer is the object.
|
||||
auto* resource = static_cast<ID3D12Resource*>(*ppv);
|
||||
const D3D12_RESOURCE_DESC desc = resource->GetDesc();
|
||||
const D3D12_RESOURCE_ALLOCATION_INFO info = device->GetResourceAllocationInfo(0, 1, &desc);
|
||||
const UINT64 size = info.SizeInBytes ? info.SizeInBytes : desc.Width;
|
||||
const UINT64 host_size = info.SizeInBytes ? info.SizeInBytes : desc.Width;
|
||||
const UINT64 console_size = console_tiled_size(desc, title_format);
|
||||
const UINT64 size = console_size ? console_size : host_size;
|
||||
const ULONGLONG attributes = kObjectTypeResource | kAllocatorIdD3D | (size >= k2M ? kPageSize2M : kPageSize64K);
|
||||
void* title = XMemAlloc(static_cast<SIZE_T>(size), attributes);
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "%s dim=%d size=%llu page=%s title_va=%p", method,
|
||||
char detail[240];
|
||||
std::snprintf(detail, sizeof(detail), "%s dim=%d size=%llu (%s, host %llu) page=%s title_va=%p", method,
|
||||
static_cast<int>(desc.Dimension), static_cast<unsigned long long>(size),
|
||||
console_size ? "console 64 KB tiles" : "host", static_cast<unsigned long long>(host_size),
|
||||
size >= k2M ? "2MB" : "64KB", title);
|
||||
bx_log_emit(title ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "committed_title_memory", detail);
|
||||
if (!title || !bx_xbox_title_memory_attach(resource, reinterpret_cast<uint64_t>(title), size, attributes)) {
|
||||
@@ -57,9 +117,14 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource(void* self, c
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource");
|
||||
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
|
||||
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
|
||||
const DXGI_FORMAT title_format = desc ? desc->Format : DXGI_FORMAT_UNKNOWN;
|
||||
desc = host_desc.of_resource(desc, "CreateCommittedResource");
|
||||
clear = host_clear.of(clear, "CreateCommittedResource");
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
return finish(device, device->CreateCommittedResource(heap, flags, desc, state, clear, riid, ppv), riid, ppv,
|
||||
"CreateCommittedResource");
|
||||
"CreateCommittedResource", title_format);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource1(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
@@ -68,9 +133,14 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource1(void* self,
|
||||
ID3D12ProtectedResourceSession* session, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource1");
|
||||
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
|
||||
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
|
||||
const DXGI_FORMAT title_format = desc ? desc->Format : DXGI_FORMAT_UNKNOWN;
|
||||
desc = host_desc.of_resource(desc, "CreateCommittedResource1");
|
||||
clear = host_clear.of(clear, "CreateCommittedResource1");
|
||||
auto* device = bx_xbox_host<ID3D12Device4>(self);
|
||||
return finish(device, device->CreateCommittedResource1(heap, flags, desc, state, clear, bx_xbox_unwrap_as(session), riid, ppv),
|
||||
riid, ppv, "CreateCommittedResource1");
|
||||
riid, ppv, "CreateCommittedResource1", title_format);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource2(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
@@ -79,9 +149,14 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource2(void* self,
|
||||
ID3D12ProtectedResourceSession* session, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource2");
|
||||
BxHostFormat<D3D12_RESOURCE_DESC1> host_desc;
|
||||
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
|
||||
const DXGI_FORMAT title_format = desc ? desc->Format : DXGI_FORMAT_UNKNOWN;
|
||||
desc = host_desc.of_resource(desc, "CreateCommittedResource2");
|
||||
clear = host_clear.of(clear, "CreateCommittedResource2");
|
||||
auto* device = bx_xbox_host<ID3D12Device8>(self);
|
||||
return finish(device, device->CreateCommittedResource2(heap, flags, desc, state, clear, bx_xbox_unwrap_as(session), riid, ppv),
|
||||
riid, ppv, "CreateCommittedResource2");
|
||||
riid, ppv, "CreateCommittedResource2", title_format);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
@@ -90,11 +165,41 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self,
|
||||
ID3D12ProtectedResourceSession* session, UINT32 formats,
|
||||
DXGI_FORMAT* castable, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource3");
|
||||
BxHostFormat<D3D12_RESOURCE_DESC1> host_desc;
|
||||
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
|
||||
const DXGI_FORMAT title_format = desc ? desc->Format : DXGI_FORMAT_UNKNOWN;
|
||||
desc = host_desc.of_resource(desc, "CreateCommittedResource3");
|
||||
clear = host_clear.of(clear, "CreateCommittedResource3");
|
||||
auto* device = bx_xbox_host<ID3D12Device10>(self);
|
||||
return finish(device,
|
||||
device->CreateCommittedResource3(heap, flags, desc, layout, clear, bx_xbox_unwrap_as(session), formats,
|
||||
castable, riid, ppv),
|
||||
riid, ppv, "CreateCommittedResource3");
|
||||
riid, ppv, "CreateCommittedResource3", title_format);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource_x(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const void* xbox_desc,
|
||||
D3D12_RESOURCE_STATES state,
|
||||
const D3D12_CLEAR_VALUE* clear, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResourceX");
|
||||
if (!xbox_desc) return E_INVALIDARG;
|
||||
// D3D12XBOX_RESOURCE_DESC begins with the PC description; DccOptions follows it. DccOptions is
|
||||
// a struct of two 32-bit enums, CompressionLevel and ColorTransform; every value of either
|
||||
// selects some form of colour compression (CompressionLevel 0 is 64B, not "none").
|
||||
D3D12_RESOURCE_DESC desc{};
|
||||
std::memcpy(&desc, xbox_desc, sizeof(desc));
|
||||
UINT32 dcc[2] = {};
|
||||
std::memcpy(dcc, static_cast<const char*>(xbox_desc) + sizeof(desc), sizeof(dcc));
|
||||
static std::atomic<UINT> logged{0};
|
||||
if (logged.fetch_add(1) < 8) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"DccOptions CompressionLevel=%u ColorTransform=%u ignored (no colour compression on the host)",
|
||||
dcc[0], dcc[1]);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "CreateCommittedResourceX", detail);
|
||||
}
|
||||
return bx_xbox_device_create_committed_resource(self, heap, flags, &desc, state, clear, riid, ppv);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,244 @@
|
||||
/*
|
||||
* Console-only DXGI formats and console-only view combinations: the Xbox-layout device entry
|
||||
* points that carry a format to the host and are otherwise plain forwarders. See
|
||||
* console_formats.h for the formats and the reason.
|
||||
*
|
||||
* Covered here: the three GetResourceAllocationInfo forms, CreatePlacedResource,
|
||||
* CreateReservedResource and the four view-creation methods. Committed resources and the placed
|
||||
* (X) resources and views translate in committed.cpp and placed_x.cpp. Pipeline-state formats are
|
||||
* not translated yet: no console pipeline is created on the host so far.
|
||||
*/
|
||||
#include "console_formats.h"
|
||||
|
||||
#include "xbox_facade.h"
|
||||
#include "gdk_xg.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
void bx_note_console_format(DXGI_FORMAT format, const char* where) {
|
||||
static std::atomic<uint32_t> noted{0}; // one bit per console-only format
|
||||
const int f = static_cast<int>(format);
|
||||
const uint32_t bit = 1u << (f >= 189 ? f - 189 + 8 : f - 116);
|
||||
if (noted.fetch_or(bit) & bit) return;
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"console-only format %d is translated for the host (view and clear format %d, resource format %d; first seen in %s)",
|
||||
f, static_cast<int>(bx_host_format(format)), static_cast<int>(bx_host_resource_format(format)), where);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_format", detail);
|
||||
}
|
||||
|
||||
/* The console allows D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL together with ALLOW_UNORDERED_ACCESS,
|
||||
* and a title writes the depth plane from a compute shader through an R32_FLOAT unordered-access
|
||||
* view. PC Direct3D 12 forbids the combination. D3DMetal accepts the resource, answers the view
|
||||
* with a Metal texture view that Metal refuses ("texture view pixelFormat
|
||||
* (MTLPixelFormatDepth32Float) not castable"), and Metal aborts the process.
|
||||
*
|
||||
* Until that write path is emulated, such a descriptor gets a null view of the same description
|
||||
* (Direct3D 12 defines it: reads return zero, writes are discarded) and the call is logged as
|
||||
* unimplemented, so the gap is visible in every run report instead of ending the process. */
|
||||
void bx_xbox_create_host_uav(ID3D12Device* device, ID3D12Resource* host, ID3D12Resource* counter,
|
||||
const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE host_dest,
|
||||
const char* method) {
|
||||
BxHostFormat<D3D12_UNORDERED_ACCESS_VIEW_DESC> translated;
|
||||
desc = translated.of(desc, method);
|
||||
if (host && (host->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
|
||||
BX_STUB_LOG("d3d12_xs.dll", "CreateUnorderedAccessView(depth-stencil resource)");
|
||||
// A null view needs a description; without one the descriptor is left as it was.
|
||||
if (desc) device->CreateUnorderedAccessView(nullptr, nullptr, desc, host_dest);
|
||||
return;
|
||||
}
|
||||
device->CreateUnorderedAccessView(host, counter, desc, host_dest);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* An array of resource descriptions as the host must see it. */
|
||||
template <typename Desc>
|
||||
class HostDescs {
|
||||
public:
|
||||
HostDescs(const Desc* in, UINT count, const char* where) : descs_(in) {
|
||||
if (!in) return;
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
if (!bx_is_console_only_format(in[i].Format)) continue;
|
||||
if (copy_.empty()) copy_.assign(in, in + count);
|
||||
bx_note_console_format(in[i].Format, where);
|
||||
copy_[i].Format = bx_host_resource_format(in[i].Format);
|
||||
}
|
||||
if (!copy_.empty()) descs_ = copy_.data();
|
||||
}
|
||||
const Desc* get() const { return descs_; }
|
||||
|
||||
private:
|
||||
const Desc* descs_;
|
||||
std::vector<Desc> copy_;
|
||||
};
|
||||
|
||||
D3D12_RESOURCE_DESC as_desc(const D3D12_RESOURCE_DESC& d) { return d; }
|
||||
D3D12_RESOURCE_DESC as_desc(const D3D12_RESOURCE_DESC1& d) {
|
||||
D3D12_RESOURCE_DESC out{};
|
||||
out.Dimension = d.Dimension;
|
||||
out.Alignment = d.Alignment;
|
||||
out.Width = d.Width;
|
||||
out.Height = d.Height;
|
||||
out.DepthOrArraySize = d.DepthOrArraySize;
|
||||
out.MipLevels = d.MipLevels;
|
||||
out.Format = d.Format;
|
||||
out.SampleDesc = d.SampleDesc;
|
||||
out.Layout = d.Layout;
|
||||
out.Flags = d.Flags;
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Allocation info for descriptions that include a console texture layout. The console sizes come
|
||||
from the GDK's XG (gdk_xg.h); other descriptions keep the host's answer, one at a time. The
|
||||
total follows Direct3D 12: each resource at its alignment, in order; the total alignment is the
|
||||
largest. Returns false (the host answers everything) when no description has a console layout
|
||||
or XG is not loaded. */
|
||||
template <typename Desc>
|
||||
bool console_allocation(ID3D12Device* device, UINT mask, UINT count, const Desc* descs, D3D12_RESOURCE_ALLOCATION_INFO* total,
|
||||
D3D12_RESOURCE_ALLOCATION_INFO1* each, const char* method) {
|
||||
if (!descs || !count || !bx_gdk_xg_available()) return false;
|
||||
bool any = false;
|
||||
for (UINT i = 0; i < count && !any; ++i) any = bx_is_console_texture_layout(as_desc(descs[i]));
|
||||
if (!any) return false;
|
||||
uint64_t offset = 0, max_alignment = 0;
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
const D3D12_RESOURCE_DESC desc = as_desc(descs[i]);
|
||||
uint64_t size = 0, alignment = 0;
|
||||
if (!bx_is_console_texture_layout(desc) || !bx_gdk_xg_layout_size(desc, &size, &alignment)) {
|
||||
D3D12_RESOURCE_DESC host = desc;
|
||||
if (bx_is_console_only_format(host.Format)) host.Format = bx_host_resource_format(host.Format);
|
||||
if (bx_is_console_texture_layout(host)) host.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
|
||||
D3D12_RESOURCE_ALLOCATION_INFO one{};
|
||||
device->GetResourceAllocationInfo(&one, mask, 1, &host);
|
||||
size = one.SizeInBytes;
|
||||
alignment = one.Alignment;
|
||||
} else {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) < 24) {
|
||||
char detail[192];
|
||||
std::snprintf(detail, sizeof(detail), "%s %llux%ux%u mips=%u format=%d layout=0x%x: console size %llu, alignment %llu",
|
||||
method, static_cast<unsigned long long>(desc.Width), desc.Height, desc.DepthOrArraySize, desc.MipLevels,
|
||||
static_cast<int>(desc.Format), static_cast<UINT>(desc.Layout), static_cast<unsigned long long>(size),
|
||||
static_cast<unsigned long long>(alignment));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_allocation", detail);
|
||||
}
|
||||
}
|
||||
if (size == UINT64_MAX || !alignment) return false;
|
||||
offset = (offset + alignment - 1) / alignment * alignment;
|
||||
if (each) each[i] = D3D12_RESOURCE_ALLOCATION_INFO1{offset, alignment, size};
|
||||
offset += size;
|
||||
if (alignment > max_alignment) max_alignment = alignment;
|
||||
}
|
||||
total->SizeInBytes = offset;
|
||||
total->Alignment = max_alignment;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info(void* self, UINT mask, UINT count,
|
||||
const D3D12_RESOURCE_DESC* descs) {
|
||||
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo");
|
||||
D3D12_RESOURCE_ALLOCATION_INFO result{};
|
||||
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, nullptr, "GetResourceAllocationInfo")) {
|
||||
return result;
|
||||
}
|
||||
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo");
|
||||
bx_xbox_host<ID3D12Device>(self)->GetResourceAllocationInfo(&result, mask, count, host.get());
|
||||
return result;
|
||||
}
|
||||
|
||||
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info1(
|
||||
void* self, UINT mask, UINT count, const D3D12_RESOURCE_DESC* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) {
|
||||
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo1");
|
||||
D3D12_RESOURCE_ALLOCATION_INFO result{};
|
||||
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, each, "GetResourceAllocationInfo1")) {
|
||||
return result;
|
||||
}
|
||||
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo1");
|
||||
bx_xbox_host<ID3D12Device4>(self)->GetResourceAllocationInfo1(&result, mask, count, host.get(), each);
|
||||
return result;
|
||||
}
|
||||
|
||||
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info2(
|
||||
void* self, UINT mask, UINT count, const D3D12_RESOURCE_DESC1* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) {
|
||||
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo2");
|
||||
D3D12_RESOURCE_ALLOCATION_INFO result{};
|
||||
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, each, "GetResourceAllocationInfo2")) {
|
||||
return result;
|
||||
}
|
||||
const HostDescs<D3D12_RESOURCE_DESC1> host(descs, count, "GetResourceAllocationInfo2");
|
||||
bx_xbox_host<ID3D12Device8>(self)->GetResourceAllocationInfo2(&result, mask, count, host.get(), each);
|
||||
return result;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource(void* self, ID3D12Heap* heap, UINT64 offset,
|
||||
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
|
||||
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedResource");
|
||||
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
|
||||
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
|
||||
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreatePlacedResource(
|
||||
bx_xbox_unwrap_as<ID3D12Heap>(heap), offset, host_desc.of_resource(desc, "CreatePlacedResource"), state,
|
||||
host_clear.of(clear, "CreatePlacedResource"), riid, ppv);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreatePlacedResource", hr);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_reserved_resource(void* self, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateReservedResource");
|
||||
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
|
||||
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
|
||||
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateReservedResource(
|
||||
host_desc.of_resource(desc, "CreateReservedResource"), state, host_clear.of(clear, "CreateReservedResource"), riid, ppv);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateReservedResource", hr);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_shader_resource_view(void* self, ID3D12Resource* resource,
|
||||
const D3D12_SHADER_RESOURCE_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateShaderResourceView");
|
||||
BxHostFormat<D3D12_SHADER_RESOURCE_VIEW_DESC> host;
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(bx_xbox_unwrap_as<ID3D12Resource>(resource),
|
||||
host.of(desc, "CreateShaderResourceView"),
|
||||
bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_unordered_access_view(void* self, ID3D12Resource* resource, ID3D12Resource* counter,
|
||||
const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateUnorderedAccessView");
|
||||
bx_xbox_create_host_uav(bx_xbox_host<ID3D12Device>(self), bx_xbox_unwrap_as<ID3D12Resource>(resource),
|
||||
bx_xbox_unwrap_as<ID3D12Resource>(counter), desc, bx_xbox_host_cpu_handle(dest),
|
||||
"CreateUnorderedAccessView");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_render_target_view(void* self, ID3D12Resource* resource,
|
||||
const D3D12_RENDER_TARGET_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateRenderTargetView");
|
||||
BxHostFormat<D3D12_RENDER_TARGET_VIEW_DESC> host;
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateRenderTargetView(bx_xbox_unwrap_as<ID3D12Resource>(resource),
|
||||
host.of(desc, "CreateRenderTargetView"),
|
||||
bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_depth_stencil_view(void* self, ID3D12Resource* resource,
|
||||
const D3D12_DEPTH_STENCIL_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDepthStencilView");
|
||||
BxHostFormat<D3D12_DEPTH_STENCIL_VIEW_DESC> host;
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateDepthStencilView(bx_xbox_unwrap_as<ID3D12Resource>(resource),
|
||||
host.of(desc, "CreateDepthStencilView"),
|
||||
bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,91 @@
|
||||
/* Console-only DXGI formats.
|
||||
*
|
||||
* The Xbox Series DXGI_FORMAT enumeration (GDK d3d12_xs.h) has values the PC enumeration does
|
||||
* not have: 116-120, 189 and 190. A PC Direct3D 12 implementation does not know them. D3DMetal
|
||||
* turns one into an invalid Metal pixel format, and Metal then aborts the process ("Texture
|
||||
* Descriptor Validation: MTLTextureDescriptor has invalid pixelFormat"), so no error code ever
|
||||
* comes back. Every format that reaches the host therefore goes through bx_host_format first.
|
||||
*
|
||||
* The host format is the nearest one the host can create that holds at least the same precision:
|
||||
*
|
||||
* 116 R10G10B10_7E3_A2_FLOAT -> R16G16B16A16_FLOAT
|
||||
* 117 R10G10B10_6E4_A2_FLOAT -> R16G16B16A16_FLOAT
|
||||
* 118 D16_UNORM_S8_UINT -> D32_FLOAT_S8X24_UINT (depth + stencil; views, clear values)
|
||||
* -> R32G8X24_TYPELESS (the texture itself, see below)
|
||||
* 119 R16_UNORM_X8_TYPELESS -> R32_FLOAT_X8X24_TYPELESS (its depth plane, read)
|
||||
* 120 X16_TYPELESS_G8_UINT -> X32_TYPELESS_G8X24_UINT (its stencil plane, read)
|
||||
* 189 R10G10B10_SNORM_A2_UNORM -> R16G16B16A16_SNORM
|
||||
* 190 R4G4_UNORM -> R8G8_UNORM
|
||||
*
|
||||
* A depth texture that is also read is created typeless on the host, with the concrete format
|
||||
* named by each view: D3DMetal creates a fully typed depth-stencil texture without the ability
|
||||
* to be viewed in another format, and Metal aborts on the depth-plane view. The title's own
|
||||
* D32 buffers already follow that pattern (R32G8X24_TYPELESS texture, D32_FLOAT_S8X24_UINT view).
|
||||
* bx_host_resource_format is therefore used for resource descriptions and bx_host_format for
|
||||
* everything else.
|
||||
*
|
||||
* Known limits. The texel size differs, so a host resource of a substituted format cannot take
|
||||
* the title's raw texel bytes (part of uploading placed texture contents, which is separate
|
||||
* work), the sizes GetResourceAllocationInfo and GetCopyableFootprints report are the host
|
||||
* format's, and GetDesc on such a resource reports the host format.
|
||||
*/
|
||||
#ifndef BX_D3D12_XS_CONSOLE_FORMATS_H
|
||||
#define BX_D3D12_XS_CONSOLE_FORMATS_H
|
||||
|
||||
#include <dxgiformat.h>
|
||||
|
||||
constexpr int kBxFormatR10G10B10_7E3_A2_FLOAT = 116;
|
||||
constexpr int kBxFormatR10G10B10_6E4_A2_FLOAT = 117;
|
||||
constexpr int kBxFormatD16_UNORM_S8_UINT = 118;
|
||||
constexpr int kBxFormatR16_UNORM_X8_TYPELESS = 119;
|
||||
constexpr int kBxFormatX16_TYPELESS_G8_UINT = 120;
|
||||
constexpr int kBxFormatR10G10B10_SNORM_A2_UNORM = 189;
|
||||
constexpr int kBxFormatR4G4_UNORM = 190;
|
||||
|
||||
constexpr bool bx_is_console_only_format(DXGI_FORMAT format) {
|
||||
const int f = static_cast<int>(format);
|
||||
return (f >= 116 && f <= 120) || f == 189 || f == 190;
|
||||
}
|
||||
|
||||
constexpr DXGI_FORMAT bx_host_format(DXGI_FORMAT format) {
|
||||
switch (static_cast<int>(format)) {
|
||||
case kBxFormatR10G10B10_7E3_A2_FLOAT:
|
||||
case kBxFormatR10G10B10_6E4_A2_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT;
|
||||
case kBxFormatD16_UNORM_S8_UINT: return DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
|
||||
case kBxFormatR16_UNORM_X8_TYPELESS: return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
|
||||
case kBxFormatX16_TYPELESS_G8_UINT: return DXGI_FORMAT_X32_TYPELESS_G8X24_UINT;
|
||||
case kBxFormatR10G10B10_SNORM_A2_UNORM: return DXGI_FORMAT_R16G16B16A16_SNORM;
|
||||
case kBxFormatR4G4_UNORM: return DXGI_FORMAT_R8G8_UNORM;
|
||||
default: return format;
|
||||
}
|
||||
}
|
||||
|
||||
constexpr DXGI_FORMAT bx_host_resource_format(DXGI_FORMAT format) {
|
||||
return static_cast<int>(format) == kBxFormatD16_UNORM_S8_UINT ? DXGI_FORMAT_R32G8X24_TYPELESS : bx_host_format(format);
|
||||
}
|
||||
|
||||
/* Logs the first translation of each console-only format (console_formats.cpp). */
|
||||
void bx_note_console_format(DXGI_FORMAT format, const char* where);
|
||||
|
||||
/* A structure with a `Format` member (resource description, clear value, view description) as
|
||||
* the host must see it. of() returns the caller's pointer unchanged when nothing needs
|
||||
* translating, so the common case costs one comparison and no copy. */
|
||||
template <typename T>
|
||||
class BxHostFormat {
|
||||
public:
|
||||
const T* of(const T* in, const char* where) { return translate(in, where, false); }
|
||||
/* For D3D12_RESOURCE_DESC and D3D12_RESOURCE_DESC1. */
|
||||
const T* of_resource(const T* in, const char* where) { return translate(in, where, true); }
|
||||
|
||||
private:
|
||||
const T* translate(const T* in, const char* where, bool resource) {
|
||||
if (!in || !bx_is_console_only_format(in->Format)) return in;
|
||||
bx_note_console_format(in->Format, where);
|
||||
value_ = *in;
|
||||
value_.Format = resource ? bx_host_resource_format(in->Format) : bx_host_format(in->Format);
|
||||
return &value_;
|
||||
}
|
||||
T value_;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -79,7 +79,12 @@ extern "C" {
|
||||
* models (or one the host device answers); anything else fails with E_NOINTERFACE and a logged
|
||||
* IID.
|
||||
*/
|
||||
extern "C" void bx_gdk_xg_enable_locking();
|
||||
|
||||
HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv) {
|
||||
// The title creates XG texture computers on its own threads; the shim does too (gdk_xg.h).
|
||||
static const bool xg_locking = (bx_gdk_xg_enable_locking(), true);
|
||||
(void)xg_locking;
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
|
||||
@@ -214,6 +214,29 @@ void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count
|
||||
dsv ? &host_dsv : nullptr);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* On the console a GPU virtual address is the title's own address, so a title can bind index and
|
||||
* vertex data that lives in plain title memory, with no Direct3D resource created for it.
|
||||
* bx_xbox_bind_title_memory (placed_x.cpp) gives such a range a host buffer and has it refreshed
|
||||
* when the list is submitted. When that is not possible (the memory is not readable, or no
|
||||
* buffer could be made) the address must still not reach the host: it is not a host address,
|
||||
* and D3DMetal dereferences the buffer it fails to find (a null read under IASetIndexBuffer).
|
||||
* The binding is then left empty and logged as unimplemented; the first few are logged with
|
||||
* their details. */
|
||||
void note_unbacked(const char* what, D3D12_GPU_VIRTUAL_ADDRESS address, UINT size, const char* stub) {
|
||||
static std::atomic<uint32_t> noted{0};
|
||||
if (noted.fetch_add(1) < 8) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "%s at 0x%llx (%u bytes) cannot get a host buffer; the binding is left empty", what,
|
||||
static_cast<unsigned long long>(address), size);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "unbacked_buffer", detail);
|
||||
}
|
||||
BX_STUB_LOG("d3d12_xs.dll", stub);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start, UINT count,
|
||||
const D3D12_VERTEX_BUFFER_VIEW* views) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetVertexBuffers");
|
||||
@@ -221,9 +244,16 @@ void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start
|
||||
const UINT n = count > 32 ? 32 : count;
|
||||
for (UINT i = 0; views && i < n; ++i) {
|
||||
host[i] = views[i];
|
||||
host[i].BufferLocation = bx_xbox_host_gpu_va(views[i].BufferLocation);
|
||||
if (views[i].BufferLocation &&
|
||||
!bx_xbox_bind_title_memory(bx_xbox_host<ID3D12GraphicsCommandList>(self), views[i].BufferLocation, views[i].SizeInBytes,
|
||||
&host[i].BufferLocation)) {
|
||||
note_unbacked("vertex buffer", views[i].BufferLocation, views[i].SizeInBytes,
|
||||
"IASetVertexBuffers(title memory without a host buffer)");
|
||||
host[i] = D3D12_VERTEX_BUFFER_VIEW{};
|
||||
}
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetVertexBuffers(start, n, views ? host : nullptr);
|
||||
bx_xbox_rect_note_vertex_buffers(bx_xbox_host<ID3D12GraphicsCommandList>(self), start, n, views);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_ia_set_index_buffer(void* self, const D3D12_INDEX_BUFFER_VIEW* view) {
|
||||
@@ -231,7 +261,13 @@ void STDMETHODCALLTYPE bx_xbox_list_ia_set_index_buffer(void* self, const D3D12_
|
||||
D3D12_INDEX_BUFFER_VIEW host{};
|
||||
if (view) {
|
||||
host = *view;
|
||||
host.BufferLocation = bx_xbox_host_gpu_va(view->BufferLocation);
|
||||
if (view->BufferLocation &&
|
||||
!bx_xbox_bind_title_memory(bx_xbox_host<ID3D12GraphicsCommandList>(self), view->BufferLocation, view->SizeInBytes,
|
||||
&host.BufferLocation)) {
|
||||
note_unbacked("index buffer", view->BufferLocation, view->SizeInBytes,
|
||||
"IASetIndexBuffer(title memory without a host buffer)");
|
||||
view = nullptr;
|
||||
}
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetIndexBuffer(view ? &host : nullptr);
|
||||
}
|
||||
|
||||
@@ -7,10 +7,17 @@
|
||||
* FLIP events, and IntervalOffsetInMicroseconds later the ORIGIN event, which also produces a
|
||||
* new frame pipeline token. Each signal also sets the ancillary events given to
|
||||
* ScheduleFrameEventX. Timing follows the host's Sleep granularity; no display is involved.
|
||||
*
|
||||
* GetFrameStatisticsX (authorized GDK documentation) answers from a history of the last 17
|
||||
* frames, kept per pipeline token: the ORIGIN event (wait call, signal and wait return times)
|
||||
* and PresentX (call and return times), in QueryPerformanceCounter ticks as documented. The
|
||||
* other statistics types (interval, power scaling, render, display, input) have no host source
|
||||
* and are never reported; a query for only those answers S_FALSE, "not available yet".
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
@@ -43,6 +50,35 @@ UINT64 g_next_token = 1;
|
||||
UINT64 g_last_origin_token = 0;
|
||||
bool g_thread_started = false;
|
||||
|
||||
// Frame statistics history (GetFrameStatisticsX): the runtime keeps the last 17 frames.
|
||||
constexpr UINT kHistory = 17;
|
||||
struct FrameRecord {
|
||||
UINT64 token = 0;
|
||||
UINT64 wait_call = 0, signal = 0, wait_return = 0;
|
||||
UINT offset_us = 0;
|
||||
bool signaled = false;
|
||||
bool waited = false;
|
||||
bool presented = false;
|
||||
UINT64 present_call = 0, present_return = 0;
|
||||
};
|
||||
FrameRecord g_history[kHistory];
|
||||
|
||||
UINT64 qpc_now() {
|
||||
LARGE_INTEGER t;
|
||||
QueryPerformanceCounter(&t);
|
||||
return static_cast<UINT64>(t.QuadPart);
|
||||
}
|
||||
|
||||
// The record for `token`, created when `create` (replacing the one 17 frames older); else null.
|
||||
FrameRecord* record_for(UINT64 token, bool create) {
|
||||
FrameRecord& r = g_history[token % kHistory];
|
||||
if (r.token == token) return &r;
|
||||
if (!create) return nullptr;
|
||||
r = FrameRecord{};
|
||||
r.token = token;
|
||||
return &r;
|
||||
}
|
||||
|
||||
void close_ancillary(Scheduled& e) {
|
||||
for (UINT i = 0; i < e.ancillary_count; ++i) CloseHandle(e.ancillary[i]);
|
||||
e.ancillary_count = 0;
|
||||
@@ -52,7 +88,13 @@ void signal(UINT type) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
const Scheduled& e = g_events[type];
|
||||
if (!e.active) return;
|
||||
if (type == kOrigin) g_last_origin_token = g_next_token++;
|
||||
if (type == kOrigin) {
|
||||
g_last_origin_token = g_next_token++;
|
||||
FrameRecord* r = record_for(g_last_origin_token, true);
|
||||
r->signal = qpc_now();
|
||||
r->offset_us = e.offset_us;
|
||||
r->signaled = true;
|
||||
}
|
||||
SetEvent(g_signal[type]);
|
||||
for (UINT i = 0; i < e.ancillary_count; ++i) SetEvent(e.ancillary[i]);
|
||||
}
|
||||
@@ -156,6 +198,7 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void*, UINT type, UI
|
||||
}
|
||||
const UINT ancillary = waits ? waits->Count : 0;
|
||||
for (UINT i = 0; i < ancillary; ++i) handles[1 + i] = waits->pObjects[i];
|
||||
const UINT64 wait_call = qpc_now();
|
||||
const DWORD result = WaitForMultipleObjects(1 + ancillary, handles, (flags & kWaitAll) != 0,
|
||||
timeout_ms == kInfinite ? INFINITE : timeout_ms);
|
||||
const bool satisfied = result < WAIT_OBJECT_0 + 1 + ancillary;
|
||||
@@ -166,8 +209,68 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void*, UINT type, UI
|
||||
if (type == kOrigin && token && (satisfied || (flags & kWaitProcessTokenOnTimeout))) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
*token = satisfied ? g_last_origin_token : g_next_token++;
|
||||
if (FrameRecord* r = record_for(*token, true)) {
|
||||
r->wait_call = wait_call;
|
||||
r->wait_return = qpc_now();
|
||||
r->waited = true;
|
||||
}
|
||||
}
|
||||
return satisfied ? S_OK : S_FALSE;
|
||||
}
|
||||
|
||||
void bx_xbox_frame_stats_present(UINT64 token, UINT64 call_time, UINT64 return_time) {
|
||||
if (!token) return;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (FrameRecord* r = record_for(token, false)) {
|
||||
r->presented = true;
|
||||
r->present_call = call_time;
|
||||
r->present_return = return_time;
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_get_frame_statistics_x(void*, UINT64 token, UINT type_set, UINT* count,
|
||||
void* statistics) {
|
||||
BX_D3D_TRACE("XboxDevice", "GetFrameStatisticsX");
|
||||
if (!count || type_set == 0 || (type_set & ~kStatsKnownTypes) != 0 || (*count && !statistics)) return E_INVALIDARG;
|
||||
BxXboxFrameStatistics found[2];
|
||||
UINT n = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (token == 0 || token >= g_next_token) return E_INVALIDARG; // documented: unknown pipeline token
|
||||
if (const FrameRecord* r = record_for(token, false)) {
|
||||
if ((type_set & kStatsFrameEvent) && (r->signaled || r->waited)) {
|
||||
BxXboxFrameStatistics& out = found[n++];
|
||||
std::memset(&out, 0, sizeof(out));
|
||||
out.Type = kStatsFrameEvent;
|
||||
out.Event.EventType = kOrigin;
|
||||
out.Event.WaitCallTime = r->wait_call;
|
||||
out.Event.SignalTime = r->signal;
|
||||
out.Event.WaitReturnTime = r->wait_return;
|
||||
out.Event.IntervalOffsetInMicroseconds = r->offset_us;
|
||||
out.Event.StatisticsFlags = r->signaled ? 0 : kEventSignalPending;
|
||||
}
|
||||
if ((type_set & kStatsPresent) && r->presented) {
|
||||
BxXboxFrameStatistics& out = found[n++];
|
||||
std::memset(&out, 0, sizeof(out));
|
||||
out.Type = kStatsPresent;
|
||||
out.Present.PlaneIndex = 0;
|
||||
out.Present.PlaneCount = 1;
|
||||
out.Present.ViewCount = 1;
|
||||
out.Present.PresentCallTime = r->present_call;
|
||||
out.Present.PresentQueueTime = r->present_call; // queued in the call itself
|
||||
out.Present.PresentReturnTime = r->present_return;
|
||||
out.Present.PlaneSwapMask = 1; // GPUProcessTime: not measured, 0
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!statistics) { // a size query
|
||||
*count = n;
|
||||
return n ? S_OK : S_FALSE;
|
||||
}
|
||||
const UINT written = n < *count ? n : *count;
|
||||
std::memcpy(statistics, found, written * sizeof(BxXboxFrameStatistics));
|
||||
*count = written;
|
||||
return n ? S_OK : S_FALSE;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,94 @@
|
||||
/* Console texture layouts through the GDK's own XG library (see gdk_xg.h).
|
||||
*
|
||||
* The documented interface (GDK xg_xs.h):
|
||||
* HRESULT XGCreateTextureComputer(const XG_RESOURCE_DESC*, XGTextureAddressComputer**);
|
||||
* XG_RESOURCE_DESC has the field order and sizes of D3D12_RESOURCE_DESC, with
|
||||
* XG12_RESOURCE_MISC_FLAG in place of D3D12_RESOURCE_FLAGS; the title's console flags
|
||||
* (render target, depth, UAV, deny-compression) are those values.
|
||||
* XGTextureAddressComputer vtable: 0 AddRef, 1 Release, 2 GetResourceLayout,
|
||||
* 3 GetResourceSizeBytes, 4 GetResourceBaseAlignmentBytes, ...
|
||||
* void XGEnableExclusiveLocking(BOOL), to be called before any computer is created.
|
||||
*/
|
||||
#include "gdk_xg.h"
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
|
||||
namespace {
|
||||
|
||||
struct XgComputer;
|
||||
struct XgComputerVtbl {
|
||||
ULONG(__cdecl* AddRef)(XgComputer*);
|
||||
ULONG(__cdecl* Release)(XgComputer*);
|
||||
void* GetResourceLayout;
|
||||
UINT64 (*GetResourceSizeBytes)(XgComputer*);
|
||||
UINT64 (*GetResourceBaseAlignmentBytes)(XgComputer*);
|
||||
};
|
||||
struct XgComputer {
|
||||
const XgComputerVtbl* vtbl;
|
||||
};
|
||||
using CreateTextureComputerFn = HRESULT(__cdecl*)(const D3D12_RESOURCE_DESC*, XgComputer**);
|
||||
using EnableLockingFn = void(__cdecl*)(BOOL);
|
||||
|
||||
HMODULE microsoft_xg() {
|
||||
static const HMODULE module = [] {
|
||||
HMODULE xg = GetModuleHandleW(L"xg_xs.dll");
|
||||
if (!xg) xg = LoadLibraryW(L"xg_xs.dll");
|
||||
const bool microsoft = xg && GetProcAddress(xg, "XGComputeTexture2DLayout");
|
||||
bx_log_emit(microsoft ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "gdk_xg",
|
||||
microsoft ? "GDK XG library loaded: console texture layouts are computed by it"
|
||||
: "GDK XG library not loaded: console textures are sized linearly (bx-cli run stages it "
|
||||
"from the configured GDK)");
|
||||
return microsoft ? xg : static_cast<HMODULE>(nullptr);
|
||||
}();
|
||||
return module;
|
||||
}
|
||||
|
||||
CreateTextureComputerFn create_computer() {
|
||||
static const CreateTextureComputerFn fn = [] {
|
||||
HMODULE xg = microsoft_xg();
|
||||
return xg ? reinterpret_cast<CreateTextureComputerFn>(reinterpret_cast<void*>(GetProcAddress(xg, "XGCreateTextureComputer")))
|
||||
: nullptr;
|
||||
}();
|
||||
return fn;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool bx_gdk_xg_available() { return create_computer() != nullptr; }
|
||||
|
||||
bool bx_is_console_texture_layout(const D3D12_RESOURCE_DESC& desc) {
|
||||
return desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && desc.Dimension != D3D12_RESOURCE_DIMENSION_UNKNOWN &&
|
||||
static_cast<UINT>(desc.Layout) >= 0x100;
|
||||
}
|
||||
|
||||
bool bx_gdk_xg_layout_size(const D3D12_RESOURCE_DESC& desc, uint64_t* size, uint64_t* alignment) {
|
||||
const CreateTextureComputerFn create = create_computer();
|
||||
if (!create || !bx_is_console_texture_layout(desc)) return false;
|
||||
XgComputer* computer = nullptr;
|
||||
const HRESULT hr = create(&desc, &computer);
|
||||
if (FAILED(hr) || !computer) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) < 8) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "XGCreateTextureComputer refused %llux%u layout=0x%x format=%d: hr=0x%08lx",
|
||||
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<UINT>(desc.Layout),
|
||||
static_cast<int>(desc.Format), static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gdk_xg", detail);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
*size = computer->vtbl->GetResourceSizeBytes(computer);
|
||||
*alignment = computer->vtbl->GetResourceBaseAlignmentBytes(computer);
|
||||
computer->vtbl->Release(computer);
|
||||
return true;
|
||||
}
|
||||
|
||||
extern "C" void bx_gdk_xg_enable_locking() {
|
||||
HMODULE xg = microsoft_xg();
|
||||
if (!xg) return;
|
||||
auto enable = reinterpret_cast<EnableLockingFn>(reinterpret_cast<void*>(GetProcAddress(xg, "XGEnableExclusiveLocking")));
|
||||
if (enable) enable(TRUE);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
/* Console texture layouts through the GDK's own XG library.
|
||||
*
|
||||
* Console textures are laid out in tiled swizzle modes (D3D12XBOX_TEXTURE_LAYOUT / XG_TEXTURE_LAYOUT,
|
||||
* 0x100 | XG_SWIZZLE_MODE). A title sizes its loads and placements from those layouts, so a
|
||||
* linear answer makes it read less than the tiled data it stored. The layouts are computed by
|
||||
* Microsoft's xg_xs.dll from the collaborator's own GDK, staged by `bx-cli run` in place of
|
||||
* BetterXen's xg_xs shim (which exports only the two functions titles import). Nothing from the
|
||||
* GDK is shipped. Without it these helpers report that no console layout is available.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
#include <cstdint>
|
||||
|
||||
/* True when Microsoft's XG library is the loaded xg_xs.dll (it exports XGComputeTexture2DLayout). */
|
||||
bool bx_gdk_xg_available();
|
||||
|
||||
/* A console texture layout (Layout >= 0x100) that the GDK's XG can describe. */
|
||||
bool bx_is_console_texture_layout(const D3D12_RESOURCE_DESC& desc);
|
||||
|
||||
/* Size and base alignment of `desc` in the console layout. False when XG is not available or
|
||||
refuses the description; `size` and `alignment` are then untouched. */
|
||||
bool bx_gdk_xg_layout_size(const D3D12_RESOURCE_DESC& desc, uint64_t* size, uint64_t* alignment);
|
||||
|
||||
/* Enables XG's internal lock (XGEnableExclusiveLocking) before any texture computer is created,
|
||||
so the title's threads and the shim can both create computers. Called at device creation. */
|
||||
extern "C" void bx_gdk_xg_enable_locking();
|
||||
@@ -155,6 +155,7 @@ void execute(void* self, UINT count, ID3D12CommandList* const* lists) {
|
||||
}
|
||||
}
|
||||
bx_xbox_sync_mapped_buffers();
|
||||
bx_xbox_refresh_bound_memory(host.data(), count);
|
||||
for (const Write& w : pending) {
|
||||
if (w.wait) apply_wait(queue, w);
|
||||
}
|
||||
|
||||
@@ -173,6 +173,13 @@ HRESULT refused(ID3D12Device* device, HRESULT hr, const char* kind, REFIID riid,
|
||||
return bx_xbox_wrap_result(S_OK, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT refused_always_fail(HRESULT hr, const char* kind) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "%s pipeline refused hr=0x%08lx", kind, static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_refused", detail);
|
||||
return hr;
|
||||
}
|
||||
|
||||
void log_extended(const char* kind, UINT count) {
|
||||
if (!count) return;
|
||||
char detail[96];
|
||||
@@ -193,6 +200,12 @@ HRESULT create_compute(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
/* The console's pipeline topology types for rectangle and quad lists
|
||||
(D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT = 19, _QUAD = 32) are drawn with triangles on the host. */
|
||||
D3D12_PRIMITIVE_TOPOLOGY_TYPE host_topology_type(D3D12_PRIMITIVE_TOPOLOGY_TYPE type) {
|
||||
return type > D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : type;
|
||||
}
|
||||
|
||||
HRESULT create_graphics(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, REFIID riid, void** ppv) {
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
@@ -205,8 +218,11 @@ HRESULT create_graphics(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* de
|
||||
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "DS", desc->DS, admitted.DS);
|
||||
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "HS", desc->HS, admitted.HS);
|
||||
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "GS", desc->GS, admitted.GS);
|
||||
admitted.PrimitiveTopologyType = host_topology_type(desc->PrimitiveTopologyType);
|
||||
if (SUCCEEDED(hr)) hr = device->CreateGraphicsPipelineState(&admitted, riid, ppv);
|
||||
if (FAILED(hr)) return refused(device, hr, "graphics", riid, ppv);
|
||||
bx_xbox_rect_pipeline_created(static_cast<ID3D12PipelineState*>(*ppv), desc->InputLayout.pInputElementDescs,
|
||||
desc->InputLayout.NumElements);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
@@ -240,10 +256,23 @@ HRESULT create_stream(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
|
||||
hr = gate.admit("stream", names[i], in, out);
|
||||
if (SUCCEEDED(hr)) std::memcpy(&stream[offsets[i]], &out, sizeof(out));
|
||||
}
|
||||
const size_t topology_at = bx_stream_payload(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY);
|
||||
if (topology_at != SIZE_MAX) {
|
||||
D3D12_PRIMITIVE_TOPOLOGY_TYPE type{};
|
||||
std::memcpy(&type, &stream[topology_at], sizeof(type));
|
||||
type = host_topology_type(type);
|
||||
std::memcpy(&stream[topology_at], &type, sizeof(type));
|
||||
}
|
||||
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
|
||||
admitted.pPipelineStateSubobjectStream = stream.data();
|
||||
if (SUCCEEDED(hr)) hr = device->CreatePipelineState(&admitted, riid, ppv);
|
||||
if (FAILED(hr)) return refused(device, hr, "stream", riid, ppv);
|
||||
{
|
||||
D3D12_INPUT_LAYOUT_DESC layout{};
|
||||
const size_t layout_at = bx_stream_payload(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT);
|
||||
if (layout_at != SIZE_MAX) std::memcpy(&layout, &stream[layout_at], sizeof(layout));
|
||||
bx_xbox_rect_pipeline_created(static_cast<ID3D12PipelineState*>(*ppv), layout.pInputElementDescs, layout.NumElements);
|
||||
}
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
@@ -267,12 +296,19 @@ void bx_xbox_pipeline_forget(IUnknown* host) {
|
||||
}
|
||||
|
||||
void bx_xbox_list_forget(IUnknown* host) {
|
||||
bx_xbox_rect_list_forget(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
erase(g_lists, g_list_count, static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_ia_set_primitive_topology(void* self, D3D12_PRIMITIVE_TOPOLOGY topology) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetPrimitiveTopology");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
list->IASetPrimitiveTopology(bx_xbox_rect_note_topology(list, topology));
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateComputePipelineState");
|
||||
@@ -307,6 +343,7 @@ void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12Pipelin
|
||||
bool is_null = false;
|
||||
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
|
||||
set_list_null(list, is_null);
|
||||
bx_xbox_rect_note_pipeline(list, host);
|
||||
if (!is_null) list->SetPipelineState(host);
|
||||
}
|
||||
|
||||
@@ -317,6 +354,8 @@ HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator*
|
||||
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
|
||||
set_list_null(list, is_null);
|
||||
bx_xbox_gpu_writes_reset(list);
|
||||
bx_xbox_bound_memory_reset(list);
|
||||
bx_xbox_rect_list_reset(list, host);
|
||||
return list->Reset(bx_xbox_unwrap_as(allocator), host);
|
||||
}
|
||||
|
||||
@@ -324,16 +363,22 @@ void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UI
|
||||
UINT first_instance) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawInstanced");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (!list_skips(list, "DrawInstanced")) list->DrawInstanced(vertices, instances, first_vertex, first_instance);
|
||||
if (list_skips(list, "DrawInstanced")) return;
|
||||
if (!bx_xbox_draw_rect_list(list, vertices, instances, first_vertex, first_instance)) {
|
||||
list->DrawInstanced(vertices, instances, first_vertex, first_instance);
|
||||
}
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_draw_indexed_instanced(void* self, UINT indices, UINT instances, UINT first_index,
|
||||
INT base_vertex, UINT first_instance) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawIndexedInstanced");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (!list_skips(list, "DrawIndexedInstanced")) {
|
||||
list->DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance);
|
||||
if (list_skips(list, "DrawIndexedInstanced")) return;
|
||||
if (bx_xbox_rect_list_bound(list)) {
|
||||
BX_STUB_LOG("d3d12_xs.dll", "DrawIndexedInstanced(rectangle list)");
|
||||
return;
|
||||
}
|
||||
list->DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_dispatch(void* self, UINT x, UINT y, UINT z) {
|
||||
@@ -433,33 +478,35 @@ void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void*, void* callback, U
|
||||
|
||||
/*
|
||||
* DeserializeGraphics/ComputePipelineStateX create a pipeline from a serialized console pipeline
|
||||
* (console shader code), which has no host form. They fail with E_NOTIMPL (logged as a refused
|
||||
* pipeline); in null-render mode they return a null pipeline like any other refused pipeline.
|
||||
* (console shader code), which has no host form. They always fail with E_NOTIMPL and log
|
||||
* `pipeline_refused` — even in null-render mode — so a title falls back to creating its pipelines
|
||||
* from shader containers instead of receiving a null pipeline (#669).
|
||||
*/
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void*, REFIID riid,
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void*, const void*, REFIID,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "DeserializeGraphicsPipelineStateX");
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized graphics (console code)", riid, ppv);
|
||||
return refused_always_fail(E_NOTIMPL, "deserialized graphics (console code)");
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void*, REFIID riid,
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void*, const void*, REFIID,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "DeserializeComputePipelineStateX");
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized compute (console code)", riid, ppv);
|
||||
return refused_always_fail(E_NOTIMPL, "deserialized compute (console code)");
|
||||
}
|
||||
|
||||
/*
|
||||
* CreateDerived{Graphics,Compute}PipelineStateX: a pipeline equal to `source` with some state
|
||||
* groups replaced. Derived from a null pipeline, the result is a null pipeline too. Deriving
|
||||
* from a host pipeline needs its creation description, which this layer does not keep yet: that
|
||||
* case is refused (logged) and, in null-render mode, is a null pipeline as well.
|
||||
* groups replaced. Deriving from a host pipeline needs its creation description, which this layer
|
||||
* does not keep yet. Both calls always fail with E_NOTIMPL and log `pipeline_refused` — even in
|
||||
* null-render mode — so a title falls back to creating its pipelines from shader containers
|
||||
* instead of silently receiving null pipelines (#669).
|
||||
*/
|
||||
namespace {
|
||||
HRESULT derived(void* self, ID3D12PipelineState* source, REFIID riid, void** ppv, const char* kind) {
|
||||
HRESULT derived(ID3D12PipelineState* source, void** ppv, const char* kind) {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
const bool from_null = bx_xbox_pipeline_is_null(source);
|
||||
@@ -470,18 +517,18 @@ HRESULT derived(void* self, ID3D12PipelineState* source, REFIID riid, void** ppv
|
||||
"deriving from a host pipeline is not implemented (its creation description is not kept)");
|
||||
}
|
||||
}
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, kind, riid, ppv);
|
||||
return refused_always_fail(E_NOTIMPL, kind);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void* self, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID riid, void** ppv) {
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void*, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDerivedGraphicsPipelineStateX");
|
||||
return derived(self, source, riid, ppv, "derived graphics");
|
||||
return derived(source, ppv, "derived graphics");
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void* self, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID riid, void** ppv) {
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void*, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDerivedComputePipelineStateX");
|
||||
return derived(self, source, riid, ppv, "derived compute");
|
||||
return derived(source, ppv, "derived compute");
|
||||
}
|
||||
+128
-6
@@ -15,12 +15,15 @@
|
||||
* from GetGPUVirtualAddress. Keeping the shadow in step with later CPU writes, and translating
|
||||
* title addresses in GPU calls, are not done yet; both are logged when reached.
|
||||
*/
|
||||
#include "console_formats.h"
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
|
||||
extern "C" __declspec(dllimport) VOID WINAPI XMemFree(PVOID address, ULONGLONG attributes);
|
||||
|
||||
@@ -102,6 +105,10 @@ HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURC
|
||||
constexpr UINT kPcResourceFlags = 0x1FF;
|
||||
host_desc.Layout = buffer ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR : D3D12_TEXTURE_LAYOUT_UNKNOWN;
|
||||
host_desc.Flags = static_cast<D3D12_RESOURCE_FLAGS>(desc.Flags & kPcResourceFlags);
|
||||
if (bx_is_console_only_format(desc.Format)) {
|
||||
bx_note_console_format(desc.Format, "CreatePlacedResourceX");
|
||||
host_desc.Format = bx_host_resource_format(desc.Format);
|
||||
}
|
||||
ID3D12Resource* resource = nullptr;
|
||||
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &host_desc, D3D12_RESOURCE_STATE_COMMON,
|
||||
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
|
||||
@@ -207,7 +214,8 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const
|
||||
if (!resource) return;
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
|
||||
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
device->CreateShaderResourceView(resource, &pc, bx_xbox_host_cpu_handle(dest));
|
||||
BxHostFormat<D3D12_SHADER_RESOURCE_VIEW_DESC> host;
|
||||
device->CreateShaderResourceView(resource, host.of(&pc, "CreatePlacedRawShaderResourceViewX"), bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
|
||||
@@ -219,7 +227,7 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const
|
||||
if (!resource) return;
|
||||
D3D12_UNORDERED_ACCESS_VIEW_DESC pc{};
|
||||
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
device->CreateUnorderedAccessView(resource, nullptr, &pc, bx_xbox_host_cpu_handle(dest));
|
||||
bx_xbox_create_host_uav(device, resource, nullptr, &pc, bx_xbox_host_cpu_handle(dest), "CreatePlacedRawUnorderedAccessViewX");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
|
||||
@@ -227,8 +235,10 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Reso
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedShaderResourceViewX");
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
|
||||
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(bx_xbox_unwrap_as(resource), xbox_desc ? &pc : nullptr,
|
||||
bx_xbox_host_cpu_handle(dest));
|
||||
BxHostFormat<D3D12_SHADER_RESOURCE_VIEW_DESC> host;
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(
|
||||
bx_xbox_unwrap_as(resource), xbox_desc ? host.of(&pc, "CreatePlacedShaderResourceViewX") : nullptr,
|
||||
bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
|
||||
@@ -236,8 +246,120 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Reso
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedUnorderedAccessViewX");
|
||||
D3D12_UNORDERED_ACCESS_VIEW_DESC pc{};
|
||||
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateUnorderedAccessView(bx_xbox_unwrap_as(resource), nullptr,
|
||||
xbox_desc ? &pc : nullptr, bx_xbox_host_cpu_handle(dest));
|
||||
bx_xbox_create_host_uav(bx_xbox_host<ID3D12Device>(self), bx_xbox_unwrap_as(resource), nullptr, xbox_desc ? &pc : nullptr,
|
||||
bx_xbox_host_cpu_handle(dest), "CreatePlacedUnorderedAccessViewX");
|
||||
}
|
||||
|
||||
bool bx_xbox_try_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title, D3D12_GPU_VIRTUAL_ADDRESS* host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
const Shadow& s = g_shadows[i];
|
||||
if (title >= s.title_va && title < s.title_va + s.size) {
|
||||
*host = s.host->GetGPUVirtualAddress() + (title - s.title_va);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* Title memory bound as index or vertex data.
|
||||
*
|
||||
* On the console a GPU virtual address is the title's own address and the GPU reads the memory
|
||||
* when the commands execute. A title therefore binds index and vertex data that it keeps in
|
||||
* plain memory, with no Direct3D resource, and may still be writing it after it has recorded the
|
||||
* draw. Here such a range gets a CPU-writable host buffer of its own (once: later ranges inside
|
||||
* it reuse it; like the other implicit shadows it lives for the rest of the process), and every
|
||||
* range bound on a list is copied from the title memory to its host buffer when that list is
|
||||
* submitted. A range inside a buffer this layer already has is refreshed the same way.
|
||||
*/
|
||||
namespace {
|
||||
|
||||
constexpr UINT64 kMaxBoundBytes = 256ull << 20; // refuse absurd sizes instead of allocating them
|
||||
|
||||
struct BoundRange {
|
||||
uint64_t va, size;
|
||||
};
|
||||
std::mutex g_bound_lock;
|
||||
std::unordered_map<const void*, std::vector<BoundRange>> g_bound; // host list -> ranges bound since its reset
|
||||
|
||||
// The index of a buffer shadow that holds the whole range, or SIZE_MAX. g_lock must be held.
|
||||
size_t buffer_holding_locked(uint64_t va, uint64_t size) {
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
const Shadow& s = g_shadows[i];
|
||||
if (s.buffer && va >= s.title_va && va + size <= s.title_va + s.size) return i;
|
||||
}
|
||||
return SIZE_MAX;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool bx_xbox_bind_title_memory(ID3D12GraphicsCommandList* list, D3D12_GPU_VIRTUAL_ADDRESS title, UINT64 size,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS* host) {
|
||||
if (!list || !title || !size || size > kMaxBoundBytes) return false;
|
||||
bool found = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
const size_t i = buffer_holding_locked(title, size);
|
||||
if (i != SIZE_MAX) {
|
||||
*host = g_shadows[i].host->GetGPUVirtualAddress() + (title - g_shadows[i].title_va);
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
if (!readable(reinterpret_cast<const void*>(title), size)) return false;
|
||||
ID3D12Device* device = nullptr;
|
||||
if (FAILED(list->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) || !device) return false;
|
||||
D3D12_RESOURCE_DESC desc{};
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
desc.Width = size;
|
||||
desc.Height = 1;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
ID3D12Resource* resource = nullptr;
|
||||
const HRESULT hr = make_shadow(device, title, desc, "host buffer for bound title memory", &resource);
|
||||
device->Release();
|
||||
if (FAILED(hr) || !resource) return false;
|
||||
*host = resource->GetGPUVirtualAddress();
|
||||
}
|
||||
std::lock_guard<std::mutex> guard(g_bound_lock);
|
||||
std::vector<BoundRange>& ranges = g_bound[list];
|
||||
for (const BoundRange& r : ranges) {
|
||||
if (title >= r.va && title + size <= r.va + r.size) return true; // already recorded
|
||||
}
|
||||
ranges.push_back({title, size});
|
||||
return true;
|
||||
}
|
||||
|
||||
void bx_xbox_bound_memory_reset(IUnknown* host_list) {
|
||||
std::lock_guard<std::mutex> guard(g_bound_lock);
|
||||
g_bound.erase(host_list);
|
||||
}
|
||||
|
||||
void bx_xbox_refresh_bound_memory(ID3D12CommandList* const* host_lists, UINT count) {
|
||||
std::vector<BoundRange> ranges;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_bound_lock);
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
auto it = g_bound.find(host_lists[i]);
|
||||
if (it == g_bound.end()) continue;
|
||||
for (const BoundRange& r : it->second) {
|
||||
bool covered = false;
|
||||
for (const BoundRange& have : ranges) covered = covered || (r.va >= have.va && r.va + r.size <= have.va + have.size);
|
||||
if (!covered) ranges.push_back(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const BoundRange& r : ranges) {
|
||||
if (!readable(reinterpret_cast<const void*>(r.va), r.size)) continue; // freed since it was bound
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
const size_t i = buffer_holding_locked(r.va, r.size);
|
||||
if (i == SIZE_MAX) continue;
|
||||
const uint64_t begin = r.va - g_shadows[i].title_va;
|
||||
copy_buffer(g_shadows[i], true, begin, begin + r.size);
|
||||
}
|
||||
}
|
||||
|
||||
D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title) {
|
||||
|
||||
@@ -281,6 +281,21 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT pl
|
||||
const void* parameters) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "PresentX");
|
||||
(void)parameters;
|
||||
// Call and return times for GetFrameStatisticsX, kept for the first plane's pipeline token.
|
||||
struct PresentTimes {
|
||||
UINT64 token;
|
||||
UINT64 call;
|
||||
~PresentTimes() {
|
||||
LARGE_INTEGER now;
|
||||
QueryPerformanceCounter(&now);
|
||||
bx_xbox_frame_stats_present(token, call, static_cast<UINT64>(now.QuadPart));
|
||||
}
|
||||
} times{plane_count && planes_raw ? static_cast<const PlaneParameters*>(planes_raw)[0].Token : 0, 0};
|
||||
{
|
||||
LARGE_INTEGER now;
|
||||
QueryPerformanceCounter(&now);
|
||||
times.call = static_cast<UINT64>(now.QuadPart);
|
||||
}
|
||||
const auto* planes = static_cast<const PlaneParameters*>(planes_raw);
|
||||
if (plane_count == 0 || !planes || planes[0].ResourceCount == 0 || !planes[0].ppResources) return S_OK;
|
||||
ID3D12Resource* source = bx_xbox_unwrap_as(planes[0].ppResources[0]);
|
||||
|
||||
@@ -559,6 +559,19 @@ HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<ui
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
size_t bx_stream_payload(const std::vector<uint8_t>& stream, uint32_t type) {
|
||||
size_t offset = 0;
|
||||
while (offset + sizeof(SIZE_T) <= stream.size()) {
|
||||
uint32_t raw = 0;
|
||||
std::memcpy(&raw, &stream[offset], sizeof(raw));
|
||||
const StreamSubobject* entry = find_subobject(raw);
|
||||
if (!entry) return SIZE_MAX;
|
||||
if (raw == type) return offset + entry->payload_offset;
|
||||
offset += entry->record_size;
|
||||
}
|
||||
return SIZE_MAX;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("ID3D12Device2", "CreatePipelineState");
|
||||
if (!h_ID3D12Device2) {
|
||||
|
||||
@@ -124,3 +124,5 @@ using BxCommandListProxy = BxChildProxy<BxCommandListProxyGen>;
|
||||
HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<uint8_t>& copy,
|
||||
std::vector<size_t>& stage_offsets, std::vector<const char*>& stage_names,
|
||||
size_t* root_offset);
|
||||
/* The payload offset of the subobject of `type` in a stream copy_stream accepted, or SIZE_MAX. */
|
||||
size_t bx_stream_payload(const std::vector<uint8_t>& stream, uint32_t type);
|
||||
@@ -0,0 +1,261 @@
|
||||
/*
|
||||
* Console rectangle lists.
|
||||
*
|
||||
* The Xbox Series headers add primitive topologies PC Direct3D 12 does not have. A title draws
|
||||
* its full-screen passes with D3D_PRIMITIVE_TOPOLOGY_RECTLIST (17): three vertices per rectangle,
|
||||
* the fourth corner being v0 + v2 - v1, in pipelines whose topology type is
|
||||
* D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT (19). The host knows neither value. Passed through, the
|
||||
* pipeline is created anyway and the three vertices are drawn as one triangle: half of every
|
||||
* rectangle is missing and no error is reported.
|
||||
*
|
||||
* Here a rectangle list is drawn as triangle strips:
|
||||
* - the pipeline's topology type becomes TRIANGLE when it is created (pipelines.cpp);
|
||||
* - IASetPrimitiveTopology(RECTLIST) sets TRIANGLESTRIP on the host and is remembered;
|
||||
* - a non-indexed draw builds four vertices per rectangle, in the order v1, v2, v0, v3 (which
|
||||
* keeps the winding of v0, v1, v2), in a host upload buffer and draws them. The vertices are
|
||||
* read from the title's memory behind vertex-buffer slot 0, and v3 is computed element by
|
||||
* element from the pipeline's input layout.
|
||||
*
|
||||
* Limits, each logged as unimplemented when reached: indexed rectangle lists; layouts with
|
||||
* per-vertex elements outside slot 0; element formats other than 32-bit float and 8-bit
|
||||
* normalised (those elements take the third vertex's value). Quad lists, quad strips and line
|
||||
* loops are not emulated.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kRectList = 17; // D3D_PRIMITIVE_TOPOLOGY_RECTLIST (Xbox extension)
|
||||
|
||||
struct Element {
|
||||
DXGI_FORMAT format;
|
||||
UINT slot;
|
||||
UINT offset;
|
||||
bool per_vertex;
|
||||
};
|
||||
|
||||
struct ListState {
|
||||
int topology = 0; // the title's last IASetPrimitiveTopology value
|
||||
D3D12_VERTEX_BUFFER_VIEW vb0{}; // the title's view of slot 0 (title address)
|
||||
ID3D12PipelineState* pipeline = nullptr; // host pipeline bound, or nullptr
|
||||
};
|
||||
|
||||
std::mutex g_lock;
|
||||
std::unordered_map<const void*, ListState> g_lists;
|
||||
std::unordered_map<const void*, std::vector<Element>> g_layouts; // host pipeline -> input elements
|
||||
|
||||
bool readable(uint64_t address, uint64_t size) {
|
||||
uint64_t cursor = address;
|
||||
const uint64_t end = address + size;
|
||||
while (cursor < end) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(cursor), ®ion, sizeof(region)) || region.State != MEM_COMMIT ||
|
||||
(region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
|
||||
return false;
|
||||
}
|
||||
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Space for generated vertices: one upload buffer used as a ring. A position is reused after the
|
||||
ring wraps, which is 4 MiB of generated rectangles later; frames use a few hundred bytes. */
|
||||
bool ring_place(ID3D12Device* device, const uint8_t* data, size_t size, D3D12_GPU_VIRTUAL_ADDRESS* address) {
|
||||
constexpr uint64_t kRing = 4ull << 20;
|
||||
static std::mutex lock;
|
||||
static ID3D12Resource* ring = nullptr;
|
||||
static uint8_t* mapped = nullptr;
|
||||
static uint64_t cursor = 0;
|
||||
if (size == 0 || size > kRing) return false;
|
||||
std::lock_guard<std::mutex> guard(lock);
|
||||
if (!ring) {
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
heap.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
D3D12_RESOURCE_DESC desc{};
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
desc.Width = kRing;
|
||||
desc.Height = 1;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
ID3D12Resource* created = nullptr;
|
||||
void* base = nullptr;
|
||||
if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&created))) ||
|
||||
!created) {
|
||||
return false;
|
||||
}
|
||||
if (FAILED(created->Map(0, nullptr, &base)) || !base) {
|
||||
created->Release();
|
||||
return false;
|
||||
}
|
||||
ring = created;
|
||||
mapped = static_cast<uint8_t*>(base);
|
||||
}
|
||||
const uint64_t aligned = (size + 15) & ~15ull;
|
||||
if (cursor + aligned > kRing) cursor = 0;
|
||||
std::memcpy(mapped + cursor, data, size);
|
||||
*address = ring->GetGPUVirtualAddress() + cursor;
|
||||
cursor += aligned;
|
||||
return true;
|
||||
}
|
||||
|
||||
void unimplemented(const char* what) { BX_STUB_LOG("d3d12_xs.dll", what); }
|
||||
|
||||
} // namespace
|
||||
|
||||
void bx_xbox_rect_pipeline_created(ID3D12PipelineState* host, const D3D12_INPUT_ELEMENT_DESC* elements, UINT count) {
|
||||
if (!host) return;
|
||||
std::vector<Element> layout;
|
||||
for (UINT i = 0; elements && i < count; ++i) {
|
||||
layout.push_back({elements[i].Format, elements[i].InputSlot, elements[i].AlignedByteOffset,
|
||||
elements[i].InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA});
|
||||
}
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
g_layouts[host] = std::move(layout); // also replaces a released pipeline's entry at a reused address
|
||||
}
|
||||
|
||||
D3D12_PRIMITIVE_TOPOLOGY bx_xbox_rect_note_topology(ID3D12GraphicsCommandList* list, D3D12_PRIMITIVE_TOPOLOGY topology) {
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
g_lists[list].topology = static_cast<int>(topology);
|
||||
}
|
||||
return static_cast<int>(topology) == kRectList ? D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP : topology;
|
||||
}
|
||||
|
||||
void bx_xbox_rect_note_vertex_buffers(ID3D12GraphicsCommandList* list, UINT start, UINT count,
|
||||
const D3D12_VERTEX_BUFFER_VIEW* views) {
|
||||
if (start != 0 || count == 0) return;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
g_lists[list].vb0 = views ? views[0] : D3D12_VERTEX_BUFFER_VIEW{};
|
||||
}
|
||||
|
||||
void bx_xbox_rect_note_pipeline(ID3D12GraphicsCommandList* list, ID3D12PipelineState* host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
g_lists[list].pipeline = host;
|
||||
}
|
||||
|
||||
void bx_xbox_rect_list_reset(ID3D12GraphicsCommandList* list, ID3D12PipelineState* host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
g_lists[list] = ListState{};
|
||||
g_lists[list].pipeline = host;
|
||||
}
|
||||
|
||||
void bx_xbox_rect_list_forget(ID3D12GraphicsCommandList* list) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
g_lists.erase(list);
|
||||
}
|
||||
|
||||
bool bx_xbox_rect_list_bound(ID3D12GraphicsCommandList* list) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
auto it = g_lists.find(list);
|
||||
return it != g_lists.end() && it->second.topology == kRectList;
|
||||
}
|
||||
|
||||
/* True when the list's topology is the rectangle list: the draw was done here, or could not be
|
||||
and was logged as unimplemented. Either way the caller must not issue its own draw. */
|
||||
bool bx_xbox_draw_rect_list(ID3D12GraphicsCommandList* list, UINT vertices, UINT instances, UINT first_vertex,
|
||||
UINT first_instance) {
|
||||
ListState state;
|
||||
std::vector<Element> layout;
|
||||
bool have_layout = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
auto it = g_lists.find(list);
|
||||
if (it == g_lists.end() || it->second.topology != kRectList) return false;
|
||||
state = it->second;
|
||||
auto found = g_layouts.find(state.pipeline);
|
||||
if (found != g_layouts.end()) {
|
||||
layout = found->second;
|
||||
have_layout = true;
|
||||
}
|
||||
}
|
||||
const UINT stride = state.vb0.StrideInBytes;
|
||||
const UINT rects = vertices / 3;
|
||||
if (rects == 0) return true;
|
||||
if (!have_layout || !state.vb0.BufferLocation || stride == 0 || stride > 1024) {
|
||||
unimplemented("DrawInstanced(rectangle list without a known input layout or slot-0 vertex buffer)");
|
||||
return true;
|
||||
}
|
||||
for (const Element& e : layout) {
|
||||
if (e.per_vertex && e.slot != 0) {
|
||||
unimplemented("DrawInstanced(rectangle list with per-vertex elements outside slot 0)");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
const uint64_t source = state.vb0.BufferLocation + static_cast<uint64_t>(first_vertex) * stride;
|
||||
if (!readable(source, static_cast<uint64_t>(rects) * 3 * stride)) {
|
||||
unimplemented("DrawInstanced(rectangle list whose vertices are not readable title memory)");
|
||||
return true;
|
||||
}
|
||||
std::vector<uint8_t> out(static_cast<size_t>(rects) * 4 * stride);
|
||||
for (UINT r = 0; r < rects; ++r) {
|
||||
const auto* v0 = reinterpret_cast<const uint8_t*>(source + static_cast<uint64_t>(3 * r) * stride);
|
||||
const uint8_t* v1 = v0 + stride;
|
||||
const uint8_t* v2 = v1 + stride;
|
||||
uint8_t* dst = &out[static_cast<size_t>(r) * 4 * stride];
|
||||
std::memcpy(dst, v1, stride);
|
||||
std::memcpy(dst + stride, v2, stride);
|
||||
std::memcpy(dst + 2 * stride, v0, stride);
|
||||
uint8_t* v3 = dst + 3 * stride;
|
||||
std::memcpy(v3, v2, stride);
|
||||
for (const Element& e : layout) {
|
||||
if (!e.per_vertex || e.offset >= stride) continue;
|
||||
unsigned floats = 0, bytes = 0;
|
||||
switch (e.format) {
|
||||
case DXGI_FORMAT_R32G32B32A32_FLOAT: floats = 4; break;
|
||||
case DXGI_FORMAT_R32G32B32_FLOAT: floats = 3; break;
|
||||
case DXGI_FORMAT_R32G32_FLOAT: floats = 2; break;
|
||||
case DXGI_FORMAT_R32_FLOAT: floats = 1; break;
|
||||
case DXGI_FORMAT_R8G8B8A8_UNORM:
|
||||
case DXGI_FORMAT_B8G8R8A8_UNORM: bytes = 4; break;
|
||||
default: unimplemented("DrawInstanced(rectangle list element format; third vertex's value used)"); break;
|
||||
}
|
||||
for (unsigned i = 0; i < floats && e.offset + 4 * (i + 1) <= stride; ++i) {
|
||||
float a, b, c;
|
||||
std::memcpy(&a, v0 + e.offset + 4 * i, 4);
|
||||
std::memcpy(&b, v1 + e.offset + 4 * i, 4);
|
||||
std::memcpy(&c, v2 + e.offset + 4 * i, 4);
|
||||
const float d = a + c - b;
|
||||
std::memcpy(v3 + e.offset + 4 * i, &d, 4);
|
||||
}
|
||||
for (unsigned i = 0; i < bytes && e.offset + i < stride; ++i) {
|
||||
const int d = static_cast<int>(v0[e.offset + i]) + v2[e.offset + i] - v1[e.offset + i];
|
||||
v3[e.offset + i] = static_cast<uint8_t>(d < 0 ? 0 : d > 255 ? 255 : d);
|
||||
}
|
||||
}
|
||||
}
|
||||
ID3D12Device* device = nullptr;
|
||||
D3D12_GPU_VIRTUAL_ADDRESS placed = 0;
|
||||
const bool ok = SUCCEEDED(list->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) && device &&
|
||||
ring_place(device, out.data(), out.size(), &placed);
|
||||
if (device) device->Release();
|
||||
if (!ok) {
|
||||
unimplemented("DrawInstanced(rectangle list: no host buffer for the generated vertices)");
|
||||
return true;
|
||||
}
|
||||
const D3D12_VERTEX_BUFFER_VIEW generated{placed, static_cast<UINT>(out.size()), stride};
|
||||
list->IASetVertexBuffers(0, 1, &generated);
|
||||
for (UINT r = 0; r < rects; ++r) list->DrawInstanced(4, instances, 4 * r, first_instance);
|
||||
// Put the title's own slot-0 binding back.
|
||||
D3D12_VERTEX_BUFFER_VIEW title = state.vb0;
|
||||
if (bx_xbox_try_host_gpu_va(state.vb0.BufferLocation, &title.BufferLocation)) {
|
||||
list->IASetVertexBuffers(0, 1, &title);
|
||||
} else {
|
||||
list->IASetVertexBuffers(0, 1, nullptr);
|
||||
}
|
||||
static std::atomic<bool> logged{false};
|
||||
if (!logged.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "rect_list",
|
||||
"console rectangle lists are drawn as triangle strips (fourth corner v0 + v2 - v1); later draws are not logged");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -54,6 +54,8 @@ CUSTOM = {
|
||||
"WaitFrameEventX": "bx_xbox_device_wait_frame_event_x",
|
||||
"CreatePlacedResourceX": "bx_xbox_device_create_placed_resource_x",
|
||||
"CreatePlacedResourceX1": "bx_xbox_device_create_placed_resource_x1",
|
||||
"GetFrameStatisticsX": "bx_xbox_device_get_frame_statistics_x",
|
||||
"CreateCommittedResourceX": "bx_xbox_device_create_committed_resource_x",
|
||||
"CreateDescriptorHeap": "bx_xbox_device_create_descriptor_heap",
|
||||
"GetDescriptorHandleIncrementSize": "bx_xbox_device_get_descriptor_handle_increment_size",
|
||||
"CreateConstantBufferView": "bx_xbox_device_create_constant_buffer_view",
|
||||
@@ -71,6 +73,15 @@ CUSTOM = {
|
||||
"CreateGraphicsPipelineState": "bx_xbox_device_create_graphics_pipeline_state",
|
||||
"CreateComputePipelineStateX": "bx_xbox_device_create_compute_pipeline_state_x",
|
||||
"CreateGraphicsPipelineStateX": "bx_xbox_device_create_graphics_pipeline_state_x",
|
||||
"GetResourceAllocationInfo": "bx_xbox_device_get_resource_allocation_info",
|
||||
"GetResourceAllocationInfo1": "bx_xbox_device_get_resource_allocation_info1",
|
||||
"GetResourceAllocationInfo2": "bx_xbox_device_get_resource_allocation_info2",
|
||||
"CreatePlacedResource": "bx_xbox_device_create_placed_resource",
|
||||
"CreateReservedResource": "bx_xbox_device_create_reserved_resource",
|
||||
"CreateShaderResourceView": "bx_xbox_device_create_shader_resource_view",
|
||||
"CreateUnorderedAccessView": "bx_xbox_device_create_unordered_access_view",
|
||||
"CreateRenderTargetView": "bx_xbox_device_create_render_target_view",
|
||||
"CreateDepthStencilView": "bx_xbox_device_create_depth_stencil_view",
|
||||
"CreateCommittedResource": "bx_xbox_device_create_committed_resource",
|
||||
"CreateCommittedResource1": "bx_xbox_device_create_committed_resource1",
|
||||
"CreateCommittedResource2": "bx_xbox_device_create_committed_resource2",
|
||||
@@ -96,6 +107,7 @@ CUSTOM = {
|
||||
"CopyTextureRegion": "bx_xbox_list_copy_texture_region",
|
||||
"OMSetRenderTargets": "bx_xbox_list_om_set_render_targets",
|
||||
"IASetVertexBuffers": "bx_xbox_list_ia_set_vertex_buffers",
|
||||
"IASetPrimitiveTopology": "bx_xbox_list_ia_set_primitive_topology",
|
||||
"IASetIndexBuffer": "bx_xbox_list_ia_set_index_buffer",
|
||||
"SetPipelineState": "bx_xbox_list_set_pipeline_state",
|
||||
"Reset": "bx_xbox_list_reset",
|
||||
|
||||
@@ -218,6 +218,7 @@ ULONG STDMETHODCALLTYPE bx_xbox_release(void* self) {
|
||||
if (object->iface == &bx_xbox_GraphicsCommandList) {
|
||||
bx_xbox_list_forget(object->host);
|
||||
bx_xbox_gpu_writes_reset(object->host);
|
||||
bx_xbox_bound_memory_reset(object->host);
|
||||
}
|
||||
object->host->Release();
|
||||
delete object;
|
||||
|
||||
@@ -154,6 +154,48 @@ struct BxXboxFrameObjectList {
|
||||
UINT Count;
|
||||
HANDLE* pObjects;
|
||||
};
|
||||
// GetFrameStatisticsX (authorized GDK header): D3D12XBOX_FRAME_STATISTICS is a 32-bit Type and,
|
||||
// 8 bytes in, a union of the per-type structures; the two this layer fills are mirrored here.
|
||||
constexpr UINT kStatsFrameEvent = 0x2, kStatsPresent = 0x1000;
|
||||
constexpr UINT kStatsKnownTypes = 0x1 | 0x2 | 0x4 | 0x100 | 0x1000 | 0x10000 | 0x100000;
|
||||
constexpr UINT kEventSignalPending = 0x1; // D3D12XBOX_FRAME_EVENT_STATISTICS_FLAG_SIGNAL_PENDING
|
||||
struct BxXboxFrameEventStatistics { // D3D12XBOX_FRAME_EVENT_STATISTICS
|
||||
UINT32 EventType;
|
||||
UINT64 WaitCallTime;
|
||||
UINT64 SignalTime;
|
||||
UINT64 WaitReturnTime;
|
||||
UINT32 IntervalOffsetInMicroseconds;
|
||||
UINT32 SignalFlags;
|
||||
UINT32 StatisticsFlags;
|
||||
};
|
||||
struct BxXboxPresentStatistics { // D3D12XBOX_PRESENT_STATISTICS
|
||||
UINT8 PlaneIndex;
|
||||
UINT8 PlaneCount;
|
||||
UINT8 ViewCount;
|
||||
UINT64 PresentCallTime;
|
||||
UINT64 PresentQueueTime;
|
||||
UINT64 PresentReturnTime;
|
||||
UINT64 GPUProcessTime;
|
||||
UINT8 QueuedFrameCount;
|
||||
UINT16 PlaneSwapMask;
|
||||
UINT32 Flags;
|
||||
};
|
||||
struct BxXboxFrameStatistics { // D3D12XBOX_FRAME_STATISTICS
|
||||
UINT32 Type;
|
||||
union {
|
||||
BxXboxFrameEventStatistics Event;
|
||||
BxXboxPresentStatistics Present;
|
||||
UINT8 Bytes[48]; // the union's size: its largest members are 48 bytes
|
||||
};
|
||||
};
|
||||
static_assert(sizeof(BxXboxFrameEventStatistics) == 48 && sizeof(BxXboxPresentStatistics) == 48, "statistics layout");
|
||||
static_assert(sizeof(BxXboxFrameStatistics) == 56 && offsetof(BxXboxFrameStatistics, Event) == 8, "frame statistics layout");
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_get_frame_statistics_x(void* self, UINT64 token, UINT type_set, UINT* count,
|
||||
void* statistics);
|
||||
// Records PresentX for its frame pipeline token (frame_pacing.cpp keeps the history).
|
||||
void bx_xbox_frame_stats_present(UINT64 token, UINT64 call_time, UINT64 return_time);
|
||||
|
||||
struct BxXboxFrameWaitList {
|
||||
UINT Count;
|
||||
HANDLE* pObjects;
|
||||
@@ -176,6 +218,17 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void* self, UINT typ
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE bx_xbox_host_cpu_handle(D3D12_CPU_DESCRIPTOR_HANDLE title);
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE bx_xbox_host_gpu_handle(D3D12_GPU_DESCRIPTOR_HANDLE title);
|
||||
D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title);
|
||||
/* True, with the host address in *host, when `title` lies in memory this layer has a host buffer
|
||||
* for; false (and *host untouched) otherwise. */
|
||||
bool bx_xbox_try_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title, D3D12_GPU_VIRTUAL_ADDRESS* host);
|
||||
/* Title memory bound as index or vertex data (placed_x.cpp). Finds the host buffer that holds
|
||||
* [title, title + size), creating one for plain title memory that has none, gives its address
|
||||
* in *host and records the range on `list` so that it is copied from the title memory when the
|
||||
* list is submitted. False when the memory is not readable or no buffer could be made. */
|
||||
bool bx_xbox_bind_title_memory(ID3D12GraphicsCommandList* list, D3D12_GPU_VIRTUAL_ADDRESS title, UINT64 size,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS* host);
|
||||
void bx_xbox_bound_memory_reset(IUnknown* host_list);
|
||||
void bx_xbox_refresh_bound_memory(ID3D12CommandList* const* host_lists, UINT count);
|
||||
UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type);
|
||||
void bx_xbox_descriptor_heap_forget(IUnknown* host);
|
||||
/* Records title-visible memory (from XMemAlloc) for a host resource; freed when it is released. */
|
||||
@@ -270,6 +323,14 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_register_page_pool_x(void* self, D3D12_
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_unregister_page_pool_x(void* self, HANDLE handle);
|
||||
|
||||
/* Committed resources with title-visible memory (committed.cpp). */
|
||||
// CreateCommittedResourceX takes D3D12XBOX_RESOURCE_DESC: the PC D3D12_RESOURCE_DESC followed by
|
||||
// DccOptions, a struct of CompressionLevel and ColorTransform (authorized GDK header). DccOptions
|
||||
// selects console colour compression, which the host does not have; it is logged and otherwise ignored.
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource_x(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const void* xbox_desc,
|
||||
D3D12_RESOURCE_STATES state,
|
||||
const D3D12_CLEAR_VALUE* clear, REFIID riid,
|
||||
void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
@@ -290,6 +351,51 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self,
|
||||
ID3D12ProtectedResourceSession* session, UINT32 formats,
|
||||
DXGI_FORMAT* castable, REFIID riid, void** ppv);
|
||||
|
||||
/* Creates an unordered-access view on the host, or a null view (logged as unimplemented) when the
|
||||
* resource is a depth-stencil texture, which the host cannot give one (console_formats.cpp). */
|
||||
void bx_xbox_create_host_uav(ID3D12Device* device, ID3D12Resource* host, ID3D12Resource* counter,
|
||||
const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE host_dest,
|
||||
const char* method);
|
||||
|
||||
/* Entry points that only translate console-only formats before the host call (console_formats.cpp). */
|
||||
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info(void* self, UINT mask, UINT count,
|
||||
const D3D12_RESOURCE_DESC* descs);
|
||||
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info1(
|
||||
void* self, UINT mask, UINT count, const D3D12_RESOURCE_DESC* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each);
|
||||
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info2(
|
||||
void* self, UINT mask, UINT count, const D3D12_RESOURCE_DESC1* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource(void* self, ID3D12Heap* heap, UINT64 offset,
|
||||
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
|
||||
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_reserved_resource(void* self, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
REFIID riid, void** ppv);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_shader_resource_view(void* self, ID3D12Resource* resource,
|
||||
const D3D12_SHADER_RESOURCE_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_unordered_access_view(void* self, ID3D12Resource* resource, ID3D12Resource* counter,
|
||||
const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_render_target_view(void* self, ID3D12Resource* resource,
|
||||
const D3D12_RENDER_TARGET_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_depth_stencil_view(void* self, ID3D12Resource* resource,
|
||||
const D3D12_DEPTH_STENCIL_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
|
||||
/* Console rectangle lists (rect_list.cpp). */
|
||||
void bx_xbox_rect_pipeline_created(ID3D12PipelineState* host, const D3D12_INPUT_ELEMENT_DESC* elements, UINT count);
|
||||
D3D12_PRIMITIVE_TOPOLOGY bx_xbox_rect_note_topology(ID3D12GraphicsCommandList* list, D3D12_PRIMITIVE_TOPOLOGY topology);
|
||||
void bx_xbox_rect_note_vertex_buffers(ID3D12GraphicsCommandList* list, UINT start, UINT count,
|
||||
const D3D12_VERTEX_BUFFER_VIEW* views);
|
||||
void bx_xbox_rect_note_pipeline(ID3D12GraphicsCommandList* list, ID3D12PipelineState* host);
|
||||
void bx_xbox_rect_list_reset(ID3D12GraphicsCommandList* list, ID3D12PipelineState* host);
|
||||
void bx_xbox_rect_list_forget(ID3D12GraphicsCommandList* list);
|
||||
bool bx_xbox_rect_list_bound(ID3D12GraphicsCommandList* list);
|
||||
bool bx_xbox_draw_rect_list(ID3D12GraphicsCommandList* list, UINT vertices, UINT instances, UINT first_vertex,
|
||||
UINT first_instance);
|
||||
extern "C" void STDMETHODCALLTYPE bx_xbox_list_ia_set_primitive_topology(void* self, D3D12_PRIMITIVE_TOPOLOGY topology);
|
||||
|
||||
/* Descriptor heaps with title-visible storage (descriptor_heaps.cpp). */
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_descriptor_heap(void* self, const D3D12_DESCRIPTOR_HEAP_DESC* desc,
|
||||
REFIID riid, void** ppv);
|
||||
|
||||
@@ -62,22 +62,6 @@ static HRESULT STDMETHODCALLTYPE x_Device_16(void* self, UINT a0, const void * a
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateRootSignature", hr);
|
||||
return bx_xbox_wrap_result(hr, a3, a4);
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_Device_18(void* self, ID3D12Resource * a0, const D3D12_SHADER_RESOURCE_VIEW_DESC * a1, D3D12_CPU_DESCRIPTOR_HANDLE a2) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateShaderResourceView");
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(bx_xbox_unwrap_as<ID3D12Resource>(a0), a1, bx_xbox_host_cpu_handle(a2));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_Device_19(void* self, ID3D12Resource * a0, ID3D12Resource * a1, const D3D12_UNORDERED_ACCESS_VIEW_DESC * a2, D3D12_CPU_DESCRIPTOR_HANDLE a3) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateUnorderedAccessView");
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateUnorderedAccessView(bx_xbox_unwrap_as<ID3D12Resource>(a0), bx_xbox_unwrap_as<ID3D12Resource>(a1), a2, bx_xbox_host_cpu_handle(a3));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_Device_20(void* self, ID3D12Resource * a0, const D3D12_RENDER_TARGET_VIEW_DESC * a1, D3D12_CPU_DESCRIPTOR_HANDLE a2) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateRenderTargetView");
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateRenderTargetView(bx_xbox_unwrap_as<ID3D12Resource>(a0), a1, bx_xbox_host_cpu_handle(a2));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_Device_21(void* self, ID3D12Resource * a0, const D3D12_DEPTH_STENCIL_VIEW_DESC * a1, D3D12_CPU_DESCRIPTOR_HANDLE a2) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDepthStencilView");
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateDepthStencilView(bx_xbox_unwrap_as<ID3D12Resource>(a0), a1, bx_xbox_host_cpu_handle(a2));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_Device_22(void* self, const D3D12_SAMPLER_DESC * a0, D3D12_CPU_DESCRIPTOR_HANDLE a1) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateSampler");
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateSampler(a0, bx_xbox_host_cpu_handle(a1));
|
||||
@@ -86,12 +70,6 @@ static void STDMETHODCALLTYPE x_Device_24(void* self, UINT a0, const D3D12_CPU_D
|
||||
BX_D3D_TRACE("XboxDevice", "CopyDescriptorsSimple");
|
||||
bx_xbox_host<ID3D12Device>(self)->CopyDescriptorsSimple(a0, bx_xbox_host_cpu_handle(a1), bx_xbox_host_cpu_handle(a2), a3);
|
||||
}
|
||||
static D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE x_Device_25(void* self, UINT a0, UINT a1, const D3D12_RESOURCE_DESC * a2) {
|
||||
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo");
|
||||
D3D12_RESOURCE_ALLOCATION_INFO result{};
|
||||
bx_xbox_host<ID3D12Device>(self)->GetResourceAllocationInfo(&result, a0, a1, a2);
|
||||
return result;
|
||||
}
|
||||
static D3D12_HEAP_PROPERTIES STDMETHODCALLTYPE x_Device_26(void* self, UINT a0, D3D12_HEAP_TYPE a1) {
|
||||
BX_D3D_TRACE("XboxDevice", "GetCustomHeapProperties");
|
||||
D3D12_HEAP_PROPERTIES result{};
|
||||
@@ -104,18 +82,6 @@ static HRESULT STDMETHODCALLTYPE x_Device_28(void* self, const D3D12_HEAP_DESC *
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateHeap", hr);
|
||||
return bx_xbox_wrap_result(hr, a1, a2);
|
||||
}
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_29(void* self, ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC * a2, D3D12_RESOURCE_STATES a3, const D3D12_CLEAR_VALUE * a4, REFIID a5, void ** a6) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedResource");
|
||||
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreatePlacedResource(bx_xbox_unwrap_as<ID3D12Heap>(a0), a1, a2, a3, a4, a5, a6);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreatePlacedResource", hr);
|
||||
return bx_xbox_wrap_result(hr, a5, a6);
|
||||
}
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_30(void* self, const D3D12_RESOURCE_DESC * a0, D3D12_RESOURCE_STATES a1, const D3D12_CLEAR_VALUE * a2, REFIID a3, void ** a4) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateReservedResource");
|
||||
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateReservedResource(a0, a1, a2, a3, a4);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateReservedResource", hr);
|
||||
return bx_xbox_wrap_result(hr, a3, a4);
|
||||
}
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_31(void* self, ID3D12DeviceChild * a0, const SECURITY_ATTRIBUTES * a1, DWORD a2, const WCHAR * a3, HANDLE * a4) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateSharedHandle");
|
||||
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateSharedHandle(bx_xbox_unwrap_as<ID3D12DeviceChild>(a0), a1, a2, a3, a4);
|
||||
@@ -221,12 +187,8 @@ static HRESULT STDMETHODCALLTYPE x_Device_69(void*) { BX_VTABLE_STUB_LOG("XboxDe
|
||||
/* Xbox-only method */
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_72(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 72u, "SetGpuMemoryPriorityX"); return E_NOTIMPL; }
|
||||
/* Xbox-only method */
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_76(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 76u, "CreateCommittedResourceX"); return E_NOTIMPL; }
|
||||
/* Xbox-only method */
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_77(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 77u, "CreateComponentPlacedResourceX1"); return E_NOTIMPL; }
|
||||
/* Xbox-only method */
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_81(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 81u, "GetFrameStatisticsX"); return E_NOTIMPL; }
|
||||
/* Xbox-only method */
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_82(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 82u, "CreateCounterSetX"); return E_NOTIMPL; }
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_83(void* self, const void * a0, SIZE_T a1, REFIID a2, void ** a3) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePipelineLibrary");
|
||||
@@ -294,12 +256,6 @@ static HRESULT STDMETHODCALLTYPE x_Device_94(void* self, const D3D12_RESOURCE_DE
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateReservedResource1", hr);
|
||||
return bx_xbox_wrap_result(hr, a4, a5);
|
||||
}
|
||||
static D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE x_Device_95(void* self, UINT a0, UINT a1, const D3D12_RESOURCE_DESC * a2, D3D12_RESOURCE_ALLOCATION_INFO1 * a3) {
|
||||
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo1");
|
||||
D3D12_RESOURCE_ALLOCATION_INFO result{};
|
||||
bx_xbox_host<ID3D12Device4>(self)->GetResourceAllocationInfo1(&result, a0, a1, a2, a3);
|
||||
return result;
|
||||
}
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_96(void* self, ID3D12LifetimeOwner * a0, REFIID a1, void ** a2) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateLifetimeTracker");
|
||||
HRESULT hr = bx_xbox_host<ID3D12Device5>(self)->CreateLifetimeTracker(bx_xbox_unwrap_as<ID3D12LifetimeOwner>(a0), a1, a2);
|
||||
@@ -362,12 +318,6 @@ static HRESULT STDMETHODCALLTYPE x_Device_107(void* self, const D3D12_PROTECTED_
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateProtectedResourceSession1", hr);
|
||||
return bx_xbox_wrap_result(hr, a1, a2);
|
||||
}
|
||||
static D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE x_Device_108(void* self, UINT a0, UINT a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_RESOURCE_ALLOCATION_INFO1 * a3) {
|
||||
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo2");
|
||||
D3D12_RESOURCE_ALLOCATION_INFO result{};
|
||||
bx_xbox_host<ID3D12Device8>(self)->GetResourceAllocationInfo2(&result, a0, a1, a2, a3);
|
||||
return result;
|
||||
}
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_110(void* self, ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_RESOURCE_STATES a3, const D3D12_CLEAR_VALUE * a4, REFIID a5, void ** a6) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedResource1");
|
||||
HRESULT hr = bx_xbox_host<ID3D12Device8>(self)->CreatePlacedResource1(bx_xbox_unwrap_as<ID3D12Heap>(a0), a1, a2, a3, a4, a5, a6);
|
||||
@@ -468,19 +418,19 @@ const void* const kDeviceTable[] = {
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_get_descriptor_handle_increment_size),
|
||||
reinterpret_cast<const void*>(&x_Device_16),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_constant_buffer_view),
|
||||
reinterpret_cast<const void*>(&x_Device_18),
|
||||
reinterpret_cast<const void*>(&x_Device_19),
|
||||
reinterpret_cast<const void*>(&x_Device_20),
|
||||
reinterpret_cast<const void*>(&x_Device_21),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_shader_resource_view),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_unordered_access_view),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_render_target_view),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_depth_stencil_view),
|
||||
reinterpret_cast<const void*>(&x_Device_22),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_copy_descriptors),
|
||||
reinterpret_cast<const void*>(&x_Device_24),
|
||||
reinterpret_cast<const void*>(&x_Device_25),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_get_resource_allocation_info),
|
||||
reinterpret_cast<const void*>(&x_Device_26),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_committed_resource),
|
||||
reinterpret_cast<const void*>(&x_Device_28),
|
||||
reinterpret_cast<const void*>(&x_Device_29),
|
||||
reinterpret_cast<const void*>(&x_Device_30),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_placed_resource),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_reserved_resource),
|
||||
reinterpret_cast<const void*>(&x_Device_31),
|
||||
reinterpret_cast<const void*>(&x_Device_32),
|
||||
reinterpret_cast<const void*>(&x_Device_33),
|
||||
@@ -526,12 +476,12 @@ const void* const kDeviceTable[] = {
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_command_list_x),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_register_page_pool_x),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_unregister_page_pool_x),
|
||||
reinterpret_cast<const void*>(&x_Device_76),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_committed_resource_x),
|
||||
reinterpret_cast<const void*>(&x_Device_77),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_set_frame_interval_x),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_schedule_frame_event_x),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_wait_frame_event_x),
|
||||
reinterpret_cast<const void*>(&x_Device_81),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_get_frame_statistics_x),
|
||||
reinterpret_cast<const void*>(&x_Device_82),
|
||||
reinterpret_cast<const void*>(&x_Device_83),
|
||||
reinterpret_cast<const void*>(&x_Device_84),
|
||||
@@ -545,7 +495,7 @@ const void* const kDeviceTable[] = {
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_committed_resource1),
|
||||
reinterpret_cast<const void*>(&x_Device_93),
|
||||
reinterpret_cast<const void*>(&x_Device_94),
|
||||
reinterpret_cast<const void*>(&x_Device_95),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_get_resource_allocation_info1),
|
||||
reinterpret_cast<const void*>(&x_Device_96),
|
||||
reinterpret_cast<const void*>(&x_Device_97),
|
||||
reinterpret_cast<const void*>(&x_Device_98),
|
||||
@@ -558,7 +508,7 @@ const void* const kDeviceTable[] = {
|
||||
reinterpret_cast<const void*>(&x_Device_105),
|
||||
reinterpret_cast<const void*>(&x_Device_106),
|
||||
reinterpret_cast<const void*>(&x_Device_107),
|
||||
reinterpret_cast<const void*>(&x_Device_108),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_get_resource_allocation_info2),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_committed_resource2),
|
||||
reinterpret_cast<const void*>(&x_Device_110),
|
||||
reinterpret_cast<const void*>(&x_Device_111),
|
||||
@@ -607,7 +557,7 @@ const IID kDeviceIids[] = {
|
||||
{0xc4fec28f, 0x7966, 0x4e95, {0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8}}, /* ID3D12Object */
|
||||
};
|
||||
|
||||
/* ID3D12Device11: 139 slots (63 forwarded, 35 shared, 41 stubs); hosted on ID3D12Device10. */
|
||||
/* ID3D12Device11: 139 slots (54 forwarded, 46 shared, 39 stubs); hosted on ID3D12Device10. */
|
||||
const IID kHostDevice = __uuidof(ID3D12Device10);
|
||||
|
||||
static HRESULT STDMETHODCALLTYPE x_Resource_3(void* self, REFGUID a0, UINT * a1, void * a2) {
|
||||
@@ -1348,10 +1298,6 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_19(void* self, ID3D12Resourc
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "ResolveSubresource");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResolveSubresource(bx_xbox_unwrap_as<ID3D12Resource>(a0), a1, bx_xbox_unwrap_as<ID3D12Resource>(a2), a3, a4);
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_20(void* self, D3D12_PRIMITIVE_TOPOLOGY a0) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetPrimitiveTopology");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetPrimitiveTopology(a0);
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_21(void* self, UINT a0, const D3D12_VIEWPORT * a1) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "RSSetViewports");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->RSSetViewports(a0, a1);
|
||||
@@ -1716,7 +1662,7 @@ const void* const kGraphicsCommandListTable[] = {
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_17),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_18),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_19),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_20),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_ia_set_primitive_topology),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_21),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_22),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_23),
|
||||
@@ -1863,7 +1809,7 @@ const IID kGraphicsCommandListIids[] = {
|
||||
{0xc4fec28f, 0x7966, 0x4e95, {0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8}}, /* ID3D12Object */
|
||||
};
|
||||
|
||||
/* ID3D12GraphicsCommandList8: 150 slots (66 forwarded, 24 shared, 60 stubs); hosted on ID3D12GraphicsCommandList7. */
|
||||
/* ID3D12GraphicsCommandList8: 150 slots (65 forwarded, 25 shared, 60 stubs); hosted on ID3D12GraphicsCommandList7. */
|
||||
const IID kHostGraphicsCommandList = __uuidof(ID3D12GraphicsCommandList7);
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
bx_add_shim_dll(gameinput GameInput GameInput.def
|
||||
gameinput.cpp
|
||||
keyboard_gamepad.cpp
|
||||
)
|
||||
target_link_libraries(gameinput PRIVATE bx_runtime_veh kernel32)
|
||||
target_link_libraries(gameinput PRIVATE bx_runtime_veh kernel32 user32)
|
||||
@@ -7,16 +7,19 @@
|
||||
#include <unordered_map>
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "keyboard_gamepad.h"
|
||||
|
||||
namespace {
|
||||
// GameInputCreate @1 exposes the legacy v0 COM layout.
|
||||
constexpr GUID game_input_v0 = {0x11be2a7e, 0x4254, 0x445a,
|
||||
{0x9c, 0x09, 0xff, 0xc4, 0x0f, 0x00, 0x69, 0x18}};
|
||||
using Callback = void (WINAPI*)();
|
||||
using DeviceCallback = void (WINAPI*)(uint64_t, void*, IUnknown*, uint64_t, uint32_t, uint32_t);
|
||||
|
||||
// GameInputEnumerationKind values from Microsoft's public GDK GameInput (v0) reference:
|
||||
// 0 = GameInputNoEnumeration, 1 = GameInputAsyncEnumeration, 2 = GameInputBlockingEnumeration.
|
||||
constexpr uint32_t kMaxEnumerationKind = 2;
|
||||
constexpr uint32_t kAsyncEnumeration = 1;
|
||||
constexpr uint32_t kBlockingEnumeration = 2;
|
||||
|
||||
struct SrwExclusiveLock {
|
||||
explicit SrwExclusiveLock(SRWLOCK& lock) : lock_(lock) { AcquireSRWLockExclusive(&lock_); }
|
||||
@@ -34,7 +37,7 @@ struct RegisteredDeviceCallback {
|
||||
uint32_t status_filter = 0;
|
||||
uint32_t enumeration_kind = 0;
|
||||
void* context = nullptr;
|
||||
Callback callback = nullptr;
|
||||
DeviceCallback callback = nullptr;
|
||||
bool stopped = false;
|
||||
};
|
||||
|
||||
@@ -91,9 +94,15 @@ public:
|
||||
virtual uint64_t WINAPI GetCurrentTimestamp() {
|
||||
return GetTickCount64() * 1000;
|
||||
}
|
||||
virtual HRESULT WINAPI GetCurrentReading(uint32_t, void*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 4, "GetCurrentReading");
|
||||
return unavailable(out);
|
||||
virtual HRESULT WINAPI GetCurrentReading(uint32_t kind, void* device, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!(kind & keyboard_gamepad::input_kind)) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 4, "GetCurrentReading(non-gamepad)");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
if (device && device != keyboard_gamepad::device()) return keyboard_gamepad::device_not_found;
|
||||
return keyboard_gamepad::read(out);
|
||||
}
|
||||
virtual HRESULT WINAPI GetNextReading(void*, uint32_t, void*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 5, "GetNextReading");
|
||||
@@ -117,25 +126,45 @@ public:
|
||||
uint32_t status_filter,
|
||||
uint32_t enumeration_kind,
|
||||
void* context,
|
||||
Callback callback,
|
||||
DeviceCallback callback,
|
||||
uint64_t* out_token
|
||||
) {
|
||||
if (out_token) *out_token = 0;
|
||||
if (!callback || input_kind == 0 || status_filter == 0 || enumeration_kind > kMaxEnumerationKind) {
|
||||
if (!callback || input_kind == 0 || status_filter == 0 || enumeration_kind > kBlockingEnumeration) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
SrwExclusiveLock guard(callback_lock_);
|
||||
const uint64_t token = next_token_++;
|
||||
callbacks_.emplace(token, RegisteredDeviceCallback{
|
||||
device,
|
||||
input_kind,
|
||||
status_filter,
|
||||
enumeration_kind,
|
||||
context,
|
||||
callback,
|
||||
false,
|
||||
});
|
||||
uint64_t token;
|
||||
{
|
||||
SrwExclusiveLock guard(callback_lock_);
|
||||
token = next_token_++;
|
||||
callbacks_.emplace(token, RegisteredDeviceCallback{
|
||||
device,
|
||||
input_kind,
|
||||
status_filter,
|
||||
enumeration_kind,
|
||||
context,
|
||||
callback,
|
||||
false,
|
||||
});
|
||||
}
|
||||
if (out_token) *out_token = token;
|
||||
|
||||
auto* pad = keyboard_gamepad::device();
|
||||
const bool matches = (!device || device == pad) &&
|
||||
(input_kind & keyboard_gamepad::input_kind) &&
|
||||
(status_filter & keyboard_gamepad::device_status);
|
||||
if (matches && enumeration_kind == kBlockingEnumeration) {
|
||||
// The title requests blocking enumeration. The callback may reenter
|
||||
// GameInput, so never call it under the registration lock.
|
||||
static std::atomic_flag reported;
|
||||
if (!reported.test_and_set(std::memory_order_relaxed)) {
|
||||
bx_log_emit(BX_LOG_INFO, "gameinput", "keyboard_gamepad_connected",
|
||||
"keyboard gamepad announced through v0 device enumeration");
|
||||
}
|
||||
callback(token, context, pad, GetCurrentTimestamp(), keyboard_gamepad::device_status, 0);
|
||||
} else if (matches && enumeration_kind == kAsyncEnumeration) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 9, "RegisterDeviceCallback(async gamepad enumeration)");
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
virtual HRESULT WINAPI RegisterSystemButtonCallback(void*, uint32_t, void*, Callback, uint64_t* out) {
|
||||
@@ -166,9 +195,15 @@ public:
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 15, "CreateAggregateDevice");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI FindDeviceFromId(const void*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 16, "FindDeviceFromId");
|
||||
return unavailable(out);
|
||||
virtual HRESULT WINAPI FindDeviceFromId(const void* id, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!id) return E_INVALIDARG;
|
||||
if (!keyboard_gamepad::has_id(id)) return keyboard_gamepad::device_not_found;
|
||||
auto* pad = keyboard_gamepad::device();
|
||||
pad->AddRef();
|
||||
*out = pad;
|
||||
return S_OK;
|
||||
}
|
||||
virtual HRESULT WINAPI FindDeviceFromObject(IUnknown*, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 17, "FindDeviceFromObject");
|
||||
|
||||
@@ -0,0 +1,393 @@
|
||||
#include "keyboard_gamepad.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
namespace keyboard_gamepad {
|
||||
namespace {
|
||||
|
||||
// Legacy GameInput v0 interface identities and Win64 data layouts.
|
||||
constexpr GUID device_iid = {0x31dd86fb, 0x4c1b, 0x408a, {0x86, 0x8f, 0x43, 0x9b, 0x3c, 0xd4, 0x71, 0x25}};
|
||||
constexpr GUID reading_iid = {0x2156947a, 0xe1fa, 0x4de0, {0xa3, 0x0b, 0xd8, 0x12, 0x93, 0x1d, 0xbd, 0x8d}};
|
||||
|
||||
struct GamepadState {
|
||||
uint32_t buttons;
|
||||
float left_trigger;
|
||||
float right_trigger;
|
||||
float left_x;
|
||||
float left_y;
|
||||
float right_x;
|
||||
float right_y;
|
||||
};
|
||||
static_assert(sizeof(GamepadState) == 28);
|
||||
|
||||
struct BatteryState {
|
||||
float rate, max_rate, remaining, capacity;
|
||||
uint32_t status;
|
||||
};
|
||||
static_assert(sizeof(BatteryState) == 20);
|
||||
|
||||
struct DeviceString {
|
||||
uint32_t bytes;
|
||||
uint32_t code_points;
|
||||
const char* text;
|
||||
};
|
||||
|
||||
using DeviceId = std::array<uint8_t, 32>;
|
||||
constexpr DeviceId device_id{{'B', 'e', 't', 't', 'e', 'r', 'X', 'e', 'n', '-', 'K', 'e', 'y', 'b', 'o', 'a', 'r', 'd'}};
|
||||
constexpr char device_name[] = "BetterXen Keyboard Gamepad";
|
||||
constexpr DeviceString display_name{
|
||||
sizeof(device_name) - 1, sizeof(device_name) - 1, device_name,
|
||||
};
|
||||
// Menu, View, A/B/X/Y, D-pad, shoulders, and stick clicks, in v0 label order.
|
||||
constexpr std::array<uint32_t, 14> gamepad_labels{{4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 17, 20}};
|
||||
|
||||
// The virtual device supplies only fixed-format gamepad data. The arrays group
|
||||
// the zero-valued v0 metadata for raw reports, other input kinds, and motors.
|
||||
struct DeviceInfo {
|
||||
uint32_t size;
|
||||
uint16_t vendor_id, product_id, revision;
|
||||
uint8_t interface_number, collection_number;
|
||||
uint16_t usage_page, usage;
|
||||
uint16_t hardware_version[4], firmware_version[4];
|
||||
DeviceId id, root_id;
|
||||
int32_t family;
|
||||
uint32_t capabilities, supported_input, supported_rumble;
|
||||
uint32_t counts[12];
|
||||
const void* other_input_info[12];
|
||||
const uint32_t* gamepad_info;
|
||||
const void* wheel_navigation_motor_info[4];
|
||||
const DeviceString* display_name;
|
||||
const void* device_strings;
|
||||
const void* descriptor;
|
||||
};
|
||||
static_assert(sizeof(DeviceInfo) == 320);
|
||||
static_assert(offsetof(DeviceInfo, id) == 32);
|
||||
static_assert(offsetof(DeviceInfo, supported_input) == 104);
|
||||
static_assert(offsetof(DeviceInfo, gamepad_info) == 256);
|
||||
static_assert(offsetof(DeviceInfo, display_name) == 296);
|
||||
|
||||
constexpr DeviceInfo device_info{
|
||||
.size = sizeof(DeviceInfo),
|
||||
.vendor_id = 0,
|
||||
.product_id = 0,
|
||||
.revision = 0,
|
||||
.interface_number = 0,
|
||||
.collection_number = 0,
|
||||
.usage_page = 1,
|
||||
.usage = 5,
|
||||
.hardware_version = {},
|
||||
.firmware_version = {},
|
||||
.id = device_id,
|
||||
.root_id = device_id,
|
||||
.family = -1, // GameInputFamilyVirtual
|
||||
.capabilities = 0,
|
||||
.supported_input = input_kind,
|
||||
.supported_rumble = 0,
|
||||
.counts = {},
|
||||
.other_input_info = {},
|
||||
.gamepad_info = gamepad_labels.data(),
|
||||
.wheel_navigation_motor_info = {},
|
||||
.display_name = &display_name,
|
||||
.device_strings = nullptr,
|
||||
.descriptor = nullptr,
|
||||
};
|
||||
|
||||
#define DEVICE_STUB(slot, method) BX_VTABLE_STUB_LOG("IGameInputDevice", slot, method)
|
||||
#define READING_STUB(slot, method) BX_VTABLE_STUB_LOG("IGameInputReading", slot, method)
|
||||
|
||||
class Device final : public IUnknown {
|
||||
LONG refs_ = 1; // The shim owns one reference for the lifetime of the device.
|
||||
|
||||
public:
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (iid != IID_IUnknown && iid != device_iid) return E_NOINTERFACE;
|
||||
AddRef();
|
||||
*out = this;
|
||||
return S_OK;
|
||||
}
|
||||
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs_); }
|
||||
ULONG WINAPI Release() override { return InterlockedDecrement(&refs_); }
|
||||
|
||||
virtual const DeviceInfo* WINAPI GetDeviceInfo() { return &device_info; }
|
||||
virtual uint32_t WINAPI GetDeviceStatus() { return device_status; }
|
||||
virtual void WINAPI GetBatteryState(BatteryState* out) { if (out) *out = {}; }
|
||||
virtual HRESULT WINAPI CreateForceFeedbackEffect(uint32_t, const void*, void** out) {
|
||||
DEVICE_STUB(6, "CreateForceFeedbackEffect");
|
||||
if (out) *out = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual bool WINAPI IsForceFeedbackMotorPoweredOn(uint32_t) { return false; }
|
||||
virtual void WINAPI SetForceFeedbackMotorGain(uint32_t, float) { DEVICE_STUB(8, "SetForceFeedbackMotorGain"); }
|
||||
virtual HRESULT WINAPI SetHapticMotorState(uint32_t, const void*) {
|
||||
DEVICE_STUB(9, "SetHapticMotorState");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual void WINAPI SetRumbleState(const void*) { DEVICE_STUB(10, "SetRumbleState"); }
|
||||
virtual void WINAPI SetInputSynchronizationState(bool) { DEVICE_STUB(11, "SetInputSynchronizationState"); }
|
||||
virtual void WINAPI SendInputSynchronizationHint() { DEVICE_STUB(12, "SendInputSynchronizationHint"); }
|
||||
virtual void WINAPI PowerOff() { DEVICE_STUB(13, "PowerOff"); }
|
||||
virtual HRESULT WINAPI CreateRawDeviceReport(uint32_t, uint32_t, void** out) {
|
||||
DEVICE_STUB(14, "CreateRawDeviceReport");
|
||||
if (out) *out = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual HRESULT WINAPI GetRawDeviceFeature(uint32_t, void** out) {
|
||||
DEVICE_STUB(15, "GetRawDeviceFeature");
|
||||
if (out) *out = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual HRESULT WINAPI SetRawDeviceFeature(void*) {
|
||||
DEVICE_STUB(16, "SetRawDeviceFeature");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual HRESULT WINAPI SendRawDeviceOutput(void*) {
|
||||
DEVICE_STUB(17, "SendRawDeviceOutput");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual HRESULT WINAPI SendRawDeviceOutputWithResponse(void*, void** out) {
|
||||
DEVICE_STUB(18, "SendRawDeviceOutputWithResponse");
|
||||
if (out) *out = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual HRESULT WINAPI ExecuteRawDeviceIoControl(uint32_t, size_t, const void*, size_t, void*, size_t* out) {
|
||||
DEVICE_STUB(19, "ExecuteRawDeviceIoControl");
|
||||
if (out) *out = 0;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual bool WINAPI AcquireExclusiveRawDeviceAccess(uint64_t) {
|
||||
DEVICE_STUB(20, "AcquireExclusiveRawDeviceAccess");
|
||||
return false;
|
||||
}
|
||||
virtual void WINAPI ReleaseExclusiveRawDeviceAccess() { DEVICE_STUB(21, "ReleaseExclusiveRawDeviceAccess"); }
|
||||
};
|
||||
Device virtual_device;
|
||||
|
||||
bool pressed(int key) { return (GetAsyncKeyState(key) & 0x8000) != 0; }
|
||||
|
||||
bool owns_foreground() {
|
||||
const HWND foreground = GetForegroundWindow();
|
||||
DWORD pid = 0;
|
||||
return foreground && GetWindowThreadProcessId(foreground, &pid) && pid == GetCurrentProcessId();
|
||||
}
|
||||
|
||||
void sample_stick(int left, int right, int down, int up, float& x, float& y) {
|
||||
x = static_cast<float>(pressed(right) - pressed(left));
|
||||
y = static_cast<float>(pressed(up) - pressed(down));
|
||||
if (x != 0 && y != 0) {
|
||||
constexpr float diagonal = 0.70710678f;
|
||||
x *= diagonal;
|
||||
y *= diagonal;
|
||||
}
|
||||
}
|
||||
|
||||
/* Diagnostic (off unless BX_INPUT_SCRIPT is set): scripted gamepad presses, so an unattended run
|
||||
can get past screens that wait for input without window focus. The script is a comma-separated
|
||||
list of BUTTON@SECONDS, for example "A@40,DOWN@50.5,A@52"; each press holds the button for
|
||||
300 ms, timed from the first reading of the keyboard gamepad. Buttons: MENU VIEW A B X Y UP DOWN
|
||||
LEFT RIGHT. Each press is logged once (input_script); an entry it cannot read is logged and
|
||||
skipped. */
|
||||
struct ScriptedPress {
|
||||
uint32_t button;
|
||||
uint64_t at_ms;
|
||||
};
|
||||
constexpr size_t kMaxScriptedPresses = 128;
|
||||
constexpr uint64_t kScriptedHoldMs = 300;
|
||||
|
||||
struct InputScript {
|
||||
ScriptedPress presses[kMaxScriptedPresses];
|
||||
std::atomic<bool> logged[kMaxScriptedPresses];
|
||||
size_t count = 0;
|
||||
uint64_t start_ms = 0;
|
||||
};
|
||||
|
||||
uint32_t script_button(const char* name, size_t length) {
|
||||
constexpr struct { const char* name; uint32_t bit; } names[] = {
|
||||
{"MENU", 0x1}, {"VIEW", 0x2}, {"A", 0x4}, {"B", 0x8}, {"X", 0x10},
|
||||
{"Y", 0x20}, {"UP", 0x40}, {"DOWN", 0x80}, {"LEFT", 0x100}, {"RIGHT", 0x200},
|
||||
};
|
||||
for (const auto& n : names) {
|
||||
if (std::strlen(n.name) == length && std::strncmp(n.name, name, length) == 0) return n.bit;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
InputScript* load_script() {
|
||||
char spec[2048] = {};
|
||||
const DWORD n = GetEnvironmentVariableA("BX_INPUT_SCRIPT", spec, sizeof(spec));
|
||||
if (n == 0 || n >= sizeof(spec)) return nullptr;
|
||||
auto* script = new (std::nothrow) InputScript();
|
||||
if (!script) return nullptr;
|
||||
for (const char* item = spec; *item && script->count < kMaxScriptedPresses;) {
|
||||
const char* end = std::strchr(item, ',');
|
||||
const size_t length = end ? static_cast<size_t>(end - item) : std::strlen(item);
|
||||
const char* at = static_cast<const char*>(std::memchr(item, '@', length));
|
||||
char seconds[32] = {};
|
||||
uint32_t button = 0;
|
||||
if (at && static_cast<size_t>(item + length - at - 1) < sizeof(seconds)) {
|
||||
std::memcpy(seconds, at + 1, static_cast<size_t>(item + length - at - 1));
|
||||
button = script_button(item, static_cast<size_t>(at - item));
|
||||
}
|
||||
char* parsed_end = nullptr;
|
||||
const double when = std::strtod(seconds, &parsed_end);
|
||||
if (button && parsed_end != seconds && *parsed_end == 0 && when >= 0) {
|
||||
script->presses[script->count++] = {button, static_cast<uint64_t>(when * 1000.0)};
|
||||
} else {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "unreadable entry '%.*s' skipped", static_cast<int>(length < 40 ? length : 40), item);
|
||||
bx_log_emit(BX_LOG_WARN, "gameinput", "input_script", detail);
|
||||
}
|
||||
item = end ? end + 1 : item + length;
|
||||
}
|
||||
script->start_ms = GetTickCount64();
|
||||
return script;
|
||||
}
|
||||
|
||||
uint32_t scripted_buttons() {
|
||||
static InputScript* const script = load_script();
|
||||
if (!script) return 0;
|
||||
const uint64_t now = GetTickCount64() - script->start_ms;
|
||||
uint32_t buttons = 0;
|
||||
for (size_t i = 0; i < script->count; ++i) {
|
||||
const ScriptedPress& press = script->presses[i];
|
||||
if (now < press.at_ms || now >= press.at_ms + kScriptedHoldMs) continue;
|
||||
buttons |= press.button;
|
||||
if (!script->logged[i].exchange(true)) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "scripted press 0x%x at %.1f s", press.button, now / 1000.0);
|
||||
bx_log_emit(BX_LOG_INFO, "gameinput", "input_script", detail);
|
||||
}
|
||||
}
|
||||
return buttons;
|
||||
}
|
||||
|
||||
GamepadState sample_keyboard() {
|
||||
GamepadState state{};
|
||||
const uint32_t scripted = scripted_buttons();
|
||||
if (!owns_foreground()) {
|
||||
state.buttons = scripted;
|
||||
return state;
|
||||
}
|
||||
|
||||
constexpr struct KeyBinding { int key; uint32_t button; } buttons[] = {
|
||||
{'P', 0x1}, {VK_TAB, 0x2}, {VK_RETURN, 0x4}, {VK_SPACE, 0x4},
|
||||
{VK_ESCAPE, 0x8}, {VK_BACK, 0x8}, {'X', 0x10}, {'Y', 0x20},
|
||||
{VK_UP, 0x40}, {VK_DOWN, 0x80}, {VK_LEFT, 0x100}, {VK_RIGHT, 0x200},
|
||||
{'Q', 0x400}, {'E', 0x800}, {'F', 0x1000}, {'H', 0x2000},
|
||||
};
|
||||
for (const auto& binding : buttons) {
|
||||
if (pressed(binding.key)) state.buttons |= binding.button;
|
||||
}
|
||||
state.left_trigger = pressed('Z') ? 1.0f : 0.0f;
|
||||
state.right_trigger = pressed('C') ? 1.0f : 0.0f;
|
||||
sample_stick('A', 'D', 'S', 'W', state.left_x, state.left_y);
|
||||
sample_stick('J', 'L', 'K', 'I', state.right_x, state.right_y);
|
||||
if (!owns_foreground()) state = GamepadState{};
|
||||
state.buttons |= scripted;
|
||||
return state;
|
||||
}
|
||||
|
||||
struct Sample {
|
||||
GamepadState state{};
|
||||
uint64_t sequence = 0;
|
||||
uint64_t timestamp = 0;
|
||||
};
|
||||
|
||||
SRWLOCK sample_lock = SRWLOCK_INIT;
|
||||
Sample latest;
|
||||
|
||||
Sample sample() {
|
||||
AcquireSRWLockExclusive(&sample_lock);
|
||||
const GamepadState state = sample_keyboard();
|
||||
if (!latest.sequence || std::memcmp(&state, &latest.state, sizeof(state)) != 0) {
|
||||
latest = {state, latest.sequence + 1, GetTickCount64() * 1000};
|
||||
}
|
||||
const Sample snapshot = latest;
|
||||
ReleaseSRWLockExclusive(&sample_lock);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
class Reading final : public IUnknown {
|
||||
LONG refs_ = 1;
|
||||
const Sample sample_;
|
||||
|
||||
public:
|
||||
explicit Reading(const Sample& value) : sample_(value) {}
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (iid != IID_IUnknown && iid != reading_iid) return E_NOINTERFACE;
|
||||
AddRef();
|
||||
*out = this;
|
||||
return S_OK;
|
||||
}
|
||||
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs_); }
|
||||
ULONG WINAPI Release() override {
|
||||
const auto left = InterlockedDecrement(&refs_);
|
||||
if (!left) delete this;
|
||||
return left;
|
||||
}
|
||||
|
||||
virtual uint32_t WINAPI GetInputKind() { return input_kind; }
|
||||
virtual uint64_t WINAPI GetSequenceNumber(uint32_t kind) { return kind & input_kind ? sample_.sequence : 0; }
|
||||
virtual uint64_t WINAPI GetTimestamp() { return sample_.timestamp; }
|
||||
virtual void WINAPI GetDevice(void** out) {
|
||||
if (!out) return;
|
||||
virtual_device.AddRef();
|
||||
*out = &virtual_device;
|
||||
}
|
||||
virtual bool WINAPI GetRawReport(void** out) {
|
||||
if (out) *out = nullptr;
|
||||
return false;
|
||||
}
|
||||
virtual uint32_t WINAPI GetControllerAxisCount() { return 0; }
|
||||
virtual uint32_t WINAPI GetControllerAxisState(uint32_t, float*) { return 0; }
|
||||
virtual uint32_t WINAPI GetControllerButtonCount() { return 0; }
|
||||
virtual uint32_t WINAPI GetControllerButtonState(uint32_t, bool*) { return 0; }
|
||||
virtual uint32_t WINAPI GetControllerSwitchCount() { return 0; }
|
||||
virtual uint32_t WINAPI GetControllerSwitchState(uint32_t, uint32_t*) { return 0; }
|
||||
virtual uint32_t WINAPI GetKeyCount() { return 0; }
|
||||
virtual uint32_t WINAPI GetKeyState(uint32_t, void*) { return 0; }
|
||||
virtual bool WINAPI GetMouseState(void*) { READING_STUB(16, "GetMouseState"); return false; }
|
||||
virtual uint32_t WINAPI GetTouchCount() { return 0; }
|
||||
virtual uint32_t WINAPI GetTouchState(uint32_t, void*) { return 0; }
|
||||
virtual bool WINAPI GetMotionState(void*) { READING_STUB(19, "GetMotionState"); return false; }
|
||||
virtual bool WINAPI GetArcadeStickState(void*) { READING_STUB(20, "GetArcadeStickState"); return false; }
|
||||
virtual bool WINAPI GetFlightStickState(void*) { READING_STUB(21, "GetFlightStickState"); return false; }
|
||||
virtual bool WINAPI GetGamepadState(GamepadState* out) {
|
||||
if (!out) return false;
|
||||
*out = sample_.state;
|
||||
static std::atomic_flag reported;
|
||||
if ((out->buttons || out->left_trigger || out->right_trigger || out->left_x || out->left_y ||
|
||||
out->right_x || out->right_y) && !reported.test_and_set(std::memory_order_relaxed)) {
|
||||
bx_log_emit(BX_LOG_INFO, "gameinput", "keyboard_gamepad_input",
|
||||
"guest read a non-neutral keyboard gamepad state");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
virtual bool WINAPI GetRacingWheelState(void*) { READING_STUB(23, "GetRacingWheelState"); return false; }
|
||||
virtual bool WINAPI GetUiNavigationState(void*) { READING_STUB(24, "GetUiNavigationState"); return false; }
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
IUnknown* device() { return &virtual_device; }
|
||||
|
||||
bool has_id(const void* id) {
|
||||
return id && std::memcmp(id, device_id.data(), device_id.size()) == 0;
|
||||
}
|
||||
|
||||
HRESULT read(void** out) {
|
||||
*out = new (std::nothrow) Reading(sample());
|
||||
return *out ? S_OK : E_OUTOFMEMORY;
|
||||
}
|
||||
|
||||
} // namespace keyboard_gamepad
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <cstdint>
|
||||
|
||||
namespace keyboard_gamepad {
|
||||
|
||||
constexpr uint32_t input_kind = 0x00040000;
|
||||
constexpr uint32_t device_status = 0x3; // connected and input enabled
|
||||
constexpr HRESULT device_not_found = static_cast<HRESULT>(0x838a0002u);
|
||||
|
||||
IUnknown* device();
|
||||
bool has_id(const void* id);
|
||||
HRESULT read(void** out);
|
||||
|
||||
} // namespace keyboard_gamepad
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,6 @@
|
||||
bx_add_shim_dll(xcrdapi XCRDAPI XCRDAPI.def
|
||||
xcrdapi.cpp
|
||||
zlib_inflate.cpp
|
||||
)
|
||||
target_include_directories(xcrdapi PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/dstorage")
|
||||
target_link_libraries(xcrdapi PRIVATE bx_runtime_veh kernel32 uuid)
|
||||
|
||||
@@ -55,12 +55,23 @@ struct Request {
|
||||
UINT compression;
|
||||
ID3D12Resource* resource = nullptr;
|
||||
UINT64 resource_offset = 0;
|
||||
DWORD output_size = 0; // compression_zlib/bcpack: bytes the stream decodes to at `destination`
|
||||
UINT bcpack_mode = 0; // compression_bcpack: DSTORAGE_BCPACK_MODE (BCn format 1-7)
|
||||
// Xbox physical-page destination: the title's array of 64 KB page numbers and the offset into
|
||||
// the first page. The title may fill the array after it enqueues the request, so the pages are
|
||||
// mapped into `page_span` only when the request runs, and unmapped once it has been fulfilled.
|
||||
const ULONG_PTR* page_array = nullptr;
|
||||
UINT32 page_offset = 0;
|
||||
void* page_span = nullptr;
|
||||
ULONG_PTR page_span_count = 0;
|
||||
};
|
||||
|
||||
inline constexpr UINT compression_none = 0;
|
||||
inline constexpr UINT compression_lz = 1;
|
||||
inline constexpr UINT compression_bcpack = 2;
|
||||
inline constexpr UINT compression_gdeflate = 3;
|
||||
// RFC 1950 zlib streams (Xbox DSTORAGE_REQUEST_OPTIONS.ZlibDecompress); decoded by zlib_inflate.cpp.
|
||||
inline constexpr UINT compression_zlib = 4;
|
||||
|
||||
struct ErrorRecord {
|
||||
HRESULT first_error;
|
||||
|
||||
+341
-17
@@ -1,4 +1,5 @@
|
||||
#include "synthetic_storage.h"
|
||||
#include "zlib_inflate.h"
|
||||
|
||||
// Public PC DirectStorage contract: Microsoft.Direct3D.DirectStorage 1.4.0,
|
||||
// MIT per file, vendored unmodified under dstorage/ (see dstorage/README.md).
|
||||
@@ -8,6 +9,8 @@
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <mutex>
|
||||
#include <atomic>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
@@ -209,11 +212,48 @@ void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* resource,
|
||||
list->ResourceBarrier(1, &barrier);
|
||||
}
|
||||
|
||||
HRESULT read_bytes(HANDLE file, UINT64 offset, void* destination, const void* source, DWORD size) {
|
||||
// Title memory can be temporarily inaccessible while xmem replaces a mapped view. Keep reads
|
||||
// and writes out of that window. Never nest guards or hold one across an XMem call.
|
||||
class RemapGuard {
|
||||
public:
|
||||
explicit RemapGuard(bool needed = true) {
|
||||
if (!needed) return;
|
||||
const HMODULE xmem = GetModuleHandleW(L"xmem.dll");
|
||||
if (!xmem) return;
|
||||
const auto enter = resolve(xmem, "bx_xmem_remap_guard_enter");
|
||||
leave_ = resolve(xmem, "bx_xmem_remap_guard_leave");
|
||||
if (enter && leave_) {
|
||||
enter();
|
||||
} else {
|
||||
leave_ = nullptr;
|
||||
static std::atomic<bool> warned{false};
|
||||
if (!warned.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_remap_guard",
|
||||
"loaded xmem.dll does not provide both remap guard exports");
|
||||
}
|
||||
}
|
||||
}
|
||||
~RemapGuard() {
|
||||
if (leave_) leave_();
|
||||
}
|
||||
RemapGuard(const RemapGuard&) = delete;
|
||||
RemapGuard& operator=(const RemapGuard&) = delete;
|
||||
|
||||
private:
|
||||
using Fn = void (*)();
|
||||
static Fn resolve(HMODULE module, const char* name) {
|
||||
return reinterpret_cast<Fn>(reinterpret_cast<void*>(GetProcAddress(module, name)));
|
||||
}
|
||||
Fn leave_ = nullptr;
|
||||
};
|
||||
|
||||
HRESULT read_bytes(HANDLE file, UINT64 offset, void* destination, const void* source, DWORD size,
|
||||
bool title_destination = false) {
|
||||
if (!size) return S_OK;
|
||||
if (!destination) return E_INVALIDARG;
|
||||
if (!file) {
|
||||
if (!source) return E_INVALIDARG;
|
||||
RemapGuard remap_guard;
|
||||
std::memmove(destination, source, size);
|
||||
return S_OK;
|
||||
}
|
||||
@@ -226,6 +266,7 @@ HRESULT read_bytes(HANDLE file, UINT64 offset, void* destination, const void* so
|
||||
|
||||
DWORD bytes = 0;
|
||||
HRESULT result = S_OK;
|
||||
RemapGuard remap_guard(title_destination);
|
||||
if (!ReadFile(file, destination, size, &bytes, &operation)) {
|
||||
const DWORD error = GetLastError();
|
||||
if (error != ERROR_IO_PENDING) {
|
||||
@@ -249,7 +290,7 @@ HRESULT write_mapped(HANDLE file, const Request& request) {
|
||||
return E_FAIL;
|
||||
}
|
||||
auto* destination = static_cast<unsigned char*>(mapped) + static_cast<SIZE_T>(request.resource_offset);
|
||||
const HRESULT read_hr = read_bytes(file, request.file_offset, destination, request.source, request.size);
|
||||
const HRESULT read_hr = read_bytes(file, request.file_offset, destination, request.source, request.size, true);
|
||||
D3D12_RANGE written{
|
||||
static_cast<SIZE_T>(request.resource_offset),
|
||||
static_cast<SIZE_T>(request.resource_offset + request.size)};
|
||||
@@ -415,14 +456,155 @@ CopyResult copy_staged(HANDLE file, const Request& request) {
|
||||
return staged.finish(win32_error());
|
||||
}
|
||||
|
||||
/* A title may read only the first part of a compressed block: the stream then holds more than
|
||||
DestinationSize bytes. The whole stream is decoded and checked (Adler-32), and its first
|
||||
`output_size` bytes are delivered. A stream shorter than the destination stays an error. */
|
||||
BxInflateResult inflate_first_part(const uint8_t* compressed, const Request& request) {
|
||||
const size_t capacity = static_cast<size_t>(request.output_size) * 64 + 0x40000;
|
||||
auto* whole = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, capacity));
|
||||
if (!whole) return BxInflateResult::output_mismatch;
|
||||
size_t produced = 0;
|
||||
BxInflateResult r = bx_zlib_inflate_any(compressed, request.size, whole, capacity, &produced);
|
||||
if (r == BxInflateResult::ok && produced > request.output_size) {
|
||||
std::memcpy(request.destination, whole, request.output_size);
|
||||
} else if (r == BxInflateResult::ok) {
|
||||
r = BxInflateResult::output_mismatch;
|
||||
}
|
||||
static std::atomic<UINT> logged{0};
|
||||
if (logged.fetch_add(1) < 16) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "zlib stream of %lu bytes holds %llu bytes, destination %lu: %s", request.size,
|
||||
static_cast<unsigned long long>(produced), request.output_size,
|
||||
r == BxInflateResult::ok ? "first part delivered" : bx_inflate_result_name(r));
|
||||
bx_log_emit(r == BxInflateResult::ok ? BX_LOG_INFO : BX_LOG_WARN, "xcrdapi", "dstorage_zlib_partial", detail);
|
||||
}
|
||||
HeapFree(GetProcessHeap(), 0, whole);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* BCPack (Xbox texture block compression, DSTORAGE_BCPACK_MODE). The codec is Microsoft's
|
||||
BCPack.dll from the GDK's PC tools, loaded from BX_BCPACK_DLL when set (each collaborator's own
|
||||
GDK; never shipped). Its documented entry point (GDK BCPack.h): BCPackDecompress(bcIndex,
|
||||
output, outputSize, packed, packedSize). Without it, BCPack requests stay refused (E_NOTIMPL). */
|
||||
using BcpackDecompressFn = HRESULT(__cdecl*)(size_t, void*, size_t, const void*, size_t);
|
||||
BcpackDecompressFn bcpack_decompress() {
|
||||
static const BcpackDecompressFn fn = [] {
|
||||
wchar_t path[MAX_PATH];
|
||||
const DWORD n = GetEnvironmentVariableW(L"BX_BCPACK_DLL", path, MAX_PATH);
|
||||
if (n == 0 || n >= MAX_PATH) return static_cast<BcpackDecompressFn>(nullptr);
|
||||
HMODULE dll = LoadLibraryW(path);
|
||||
auto found = dll ? reinterpret_cast<BcpackDecompressFn>(reinterpret_cast<void*>(GetProcAddress(dll, "BCPackDecompress")))
|
||||
: nullptr;
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "BX_BCPACK_DLL %s (error %lu)", found ? "loaded" : "not usable",
|
||||
found ? 0ul : GetLastError());
|
||||
bx_log_emit(found ? BX_LOG_INFO : BX_LOG_WARN, "xcrdapi", "bcpack_codec", detail);
|
||||
return found;
|
||||
}();
|
||||
return fn;
|
||||
}
|
||||
|
||||
HRESULT bcpack_request(HANDLE file, const Request& request) {
|
||||
const BcpackDecompressFn decompress = bcpack_decompress();
|
||||
if (!decompress) return E_NOTIMPL;
|
||||
if (!request.destination || !request.output_size || !request.size) return E_INVALIDARG;
|
||||
auto* packed = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, request.size));
|
||||
if (!packed) return E_OUTOFMEMORY;
|
||||
HRESULT hr = read_bytes(file, request.file_offset, packed, request.source, request.size);
|
||||
if (SUCCEEDED(hr)) {
|
||||
RemapGuard remap_guard;
|
||||
hr = decompress(request.bcpack_mode, request.destination, request.output_size, packed, request.size);
|
||||
if (FAILED(hr)) {
|
||||
static std::atomic<UINT> logged{0};
|
||||
if (logged.fetch_add(1) < 16) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "BCPack BC%u stream of %lu bytes to %lu bytes: hr=0x%08lx", request.bcpack_mode,
|
||||
request.size, request.output_size, static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_bcpack_failed", detail);
|
||||
}
|
||||
hr = E_DSTORAGE_DECOMPRESSION_ERROR;
|
||||
}
|
||||
}
|
||||
HeapFree(GetProcessHeap(), 0, packed);
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT inflate_request(HANDLE file, const Request& request) {
|
||||
if (!request.destination || !request.output_size || request.size >= request.output_size) return E_INVALIDARG;
|
||||
auto* compressed = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, request.size));
|
||||
if (!compressed) return E_OUTOFMEMORY;
|
||||
HRESULT hr = read_bytes(file, request.file_offset, compressed, request.source, request.size);
|
||||
if (SUCCEEDED(hr)) {
|
||||
RemapGuard remap_guard;
|
||||
BxInflateResult r = bx_zlib_inflate(compressed, request.size, static_cast<uint8_t*>(request.destination),
|
||||
request.output_size);
|
||||
if (r == BxInflateResult::output_mismatch) r = inflate_first_part(compressed, request);
|
||||
if (r != BxInflateResult::ok) {
|
||||
static std::atomic<UINT> logged{0};
|
||||
if (logged.fetch_add(1) < 16) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "zlib stream of %lu bytes to %lu bytes: %s", request.size,
|
||||
request.output_size, bx_inflate_result_name(r));
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_zlib_failed", detail);
|
||||
}
|
||||
hr = E_DSTORAGE_DECOMPRESSION_ERROR;
|
||||
}
|
||||
}
|
||||
HeapFree(GetProcessHeap(), 0, compressed);
|
||||
return hr;
|
||||
}
|
||||
|
||||
CopyResult fulfill_request(HANDLE file, const Request& request);
|
||||
|
||||
// Diagnostics (off unless BX_DSTORAGE_TRACE=1): one line per memory-destination request with its
|
||||
// destination range, sizes, file offset, result and the first 16 bytes written, up to 20000.
|
||||
bool dstorage_trace_enabled() {
|
||||
static const bool on = [] {
|
||||
char value[8];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_DSTORAGE_TRACE", value, sizeof(value));
|
||||
return n > 0 && n < sizeof(value) && value[0] == '1';
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
|
||||
CopyResult fulfill(HANDLE file, const Request& request) {
|
||||
const CopyResult result = fulfill_request(file, request);
|
||||
if (!dstorage_trace_enabled() || request.resource) return result;
|
||||
static std::atomic<UINT> traced{0};
|
||||
if (traced.fetch_add(1) >= 20000) return result;
|
||||
const DWORD out = (request.compression == compression_zlib || request.compression == compression_bcpack) ? request.output_size
|
||||
: request.size;
|
||||
uint64_t head[2] = {0, 0};
|
||||
if (SUCCEEDED(result.hr) && request.destination && out >= 16) {
|
||||
RemapGuard remap_guard;
|
||||
std::memcpy(head, request.destination, 16);
|
||||
}
|
||||
char detail[220];
|
||||
std::snprintf(detail, sizeof(detail), "dst=%p..%p out=%lu src=%lu offset=0x%llx compression=%u hr=0x%08lx head=%016llx %016llx",
|
||||
request.destination, static_cast<const uint8_t*>(request.destination) + out, out, request.size,
|
||||
static_cast<unsigned long long>(request.file_offset), request.compression,
|
||||
static_cast<unsigned long>(result.hr), static_cast<unsigned long long>(head[0]),
|
||||
static_cast<unsigned long long>(head[1]));
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_request", detail);
|
||||
return result;
|
||||
}
|
||||
|
||||
CopyResult fulfill_request(HANDLE file, const Request& request) {
|
||||
if (request.compression == compression_bcpack && request.bcpack_mode) {
|
||||
if (request.resource) return {E_NOTIMPL, false};
|
||||
return {bcpack_request(file, request), false};
|
||||
}
|
||||
if (request.compression == compression_zlib) {
|
||||
if (request.resource) return {E_NOTIMPL, false};
|
||||
return {inflate_request(file, request), false};
|
||||
}
|
||||
if (request.compression) {
|
||||
log_compression(request.compression);
|
||||
return {E_NOTIMPL, false};
|
||||
}
|
||||
if (!request.size) return {};
|
||||
if (!request.resource) {
|
||||
return {read_bytes(file, request.file_offset, request.destination, request.source, request.size), false};
|
||||
return {read_bytes(file, request.file_offset, request.destination, request.source, request.size, true), false};
|
||||
}
|
||||
|
||||
const D3D12_RESOURCE_DESC desc = request.resource->GetDesc();
|
||||
@@ -443,10 +625,63 @@ CopyResult fulfill(HANDLE file, const Request& request) {
|
||||
}
|
||||
|
||||
// Each queue is drained serially, in FIFO order, by a single threadpool work item.
|
||||
// A `blocking` queue makes a full enqueue wait for a free slot (submitting what is
|
||||
// pending first) instead of failing with ERROR_BUSY. A non-zero `auto_submit`
|
||||
// submits once that many entries are waiting. The public DirectStorage queues use
|
||||
// A `blocking` queue makes a full enqueue wait for a free slot instead of failing
|
||||
// with ERROR_BUSY. A non-zero `auto_submit` submits once that many entries are
|
||||
// waiting, and a full queue submits what is pending before it waits. With
|
||||
// `auto_submit` 0 (Xbox DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled) nothing runs
|
||||
// before Submit: a full queue stalls the enqueuer until Submit is called on
|
||||
// another thread and the drain frees a slot. The public DirectStorage queues use
|
||||
// both; the BetterXen synthetic queues use neither.
|
||||
// Xbox physical-page destinations (DSTORAGE_REQUEST.DestinationPageArray, authorized GDK header):
|
||||
// 64 KB page numbers from XMemAllocatePhysicalPages. The request writes through a span of its own:
|
||||
// xmem.dll's XMemMapPhysicalPages with a NULL address (a BetterXen extension, see
|
||||
// shims/xmem/physical_pages.cpp) maps the pages contiguously, and the same call with a NULL page
|
||||
// array unmaps the span. The pages are sections, so the title's own views see the bytes.
|
||||
using MapPhysicalPagesFn = PVOID(WINAPI*)(PVOID, ULONG_PTR, PULONG_PTR);
|
||||
|
||||
MapPhysicalPagesFn map_physical_pages() {
|
||||
static const MapPhysicalPagesFn fn = [] {
|
||||
HMODULE xmem = GetModuleHandleW(L"xmem.dll");
|
||||
if (!xmem) xmem = LoadLibraryW(L"xmem.dll");
|
||||
return xmem ? reinterpret_cast<MapPhysicalPagesFn>(
|
||||
reinterpret_cast<void*>(GetProcAddress(xmem, "XMemMapPhysicalPages")))
|
||||
: nullptr;
|
||||
}();
|
||||
return fn;
|
||||
}
|
||||
|
||||
/* Maps a physical-page destination's pages when the request runs. The title can fill its page
|
||||
array after EnqueueRequest returns, so the array is read here, not at enqueue. */
|
||||
HRESULT map_page_destination(Request& request) {
|
||||
if (!request.page_array) return S_OK;
|
||||
const MapPhysicalPagesFn map = map_physical_pages();
|
||||
void* span = map ? map(nullptr, request.page_span_count, const_cast<PULONG_PTR>(request.page_array)) : nullptr;
|
||||
if (!span) {
|
||||
const DWORD error = map ? GetLastError() : ERROR_PROC_NOT_FOUND;
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "mapping %llu destination pages failed error=%lu",
|
||||
static_cast<unsigned long long>(request.page_span_count), error);
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_page_destination", detail);
|
||||
return HRESULT_FROM_WIN32(error);
|
||||
}
|
||||
request.page_span = span;
|
||||
request.destination = static_cast<BYTE*>(span) + request.page_offset;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
void unmap_page_span(Request& request) {
|
||||
if (!request.page_span) return;
|
||||
const MapPhysicalPagesFn map = map_physical_pages();
|
||||
if (!map || !map(request.page_span, request.page_span_count, nullptr)) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "unmapping %llu destination pages failed error=%lu",
|
||||
static_cast<unsigned long long>(request.page_span_count), GetLastError());
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_page_destination", detail);
|
||||
}
|
||||
request.page_span = nullptr;
|
||||
request.page_span_count = 0;
|
||||
}
|
||||
|
||||
class WorkQueue final : public Object<Queue, queue_iid> {
|
||||
public:
|
||||
WorkQueue(Entry* entries, UINT capacity, bool blocking = false, UINT auto_submit = 0)
|
||||
@@ -471,7 +706,9 @@ public:
|
||||
}
|
||||
Entry entry{Kind::request, *request};
|
||||
if (request->resource) request->resource->AddRef();
|
||||
if (request->file && !request->compression) {
|
||||
// Uncompressed and zlib requests read the file; other compressions are refused when fulfilled.
|
||||
if (request->file && (request->compression == compression_none || request->compression == compression_zlib ||
|
||||
request->compression == compression_bcpack)) {
|
||||
const HRESULT result = request->file->GetHandle(&entry.handle);
|
||||
if (FAILED(result)) {
|
||||
if (request->resource) request->resource->Release();
|
||||
@@ -613,7 +850,7 @@ private:
|
||||
if (closed_) return HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE);
|
||||
if (size_ < capacity_) return S_OK;
|
||||
if (!blocking_) return HRESULT_FROM_WIN32(ERROR_BUSY);
|
||||
if (submitted_ < size_) submit();
|
||||
if (auto_submit_ && submitted_ < size_) submit();
|
||||
SleepConditionVariableSRW(&space_, &mutex_, INFINITE, 0);
|
||||
}
|
||||
}
|
||||
@@ -662,8 +899,10 @@ private:
|
||||
HRESULT result = S_OK;
|
||||
switch (entry.kind) {
|
||||
case Kind::request: {
|
||||
const CopyResult outcome = fulfill(entry.handle, entry.request);
|
||||
const HRESULT mapped = map_page_destination(entry.request);
|
||||
const CopyResult outcome = SUCCEEDED(mapped) ? fulfill(entry.handle, entry.request) : CopyResult{mapped, false};
|
||||
result = outcome.hr;
|
||||
unmap_page_span(entry.request);
|
||||
if (entry.handle) CloseHandle(entry.handle);
|
||||
// keep_destination holds the AddRef taken at enqueue. Releasing
|
||||
// it while the staged copy is still on the GPU frees the dest.
|
||||
@@ -1297,8 +1536,10 @@ static_assert(offsetof(XboxQueueDesc, flags) == 0x18, "flags offset");
|
||||
|
||||
struct XboxRequest {
|
||||
UINT64 options; // +0x00: bit 22 (0x400000) = memory source, bit 0 = compressed
|
||||
void* destination; // +0x08
|
||||
UINT64 destination_pad; // +0x10
|
||||
void* destination; // +0x08: buffer, or the 64 KB page-number array (DestinationIsPhysicalPages)
|
||||
UINT16 destination_page_offset; // +0x10: offset into the first page (DestinationIsPhysicalPages)
|
||||
UINT16 reserved12;
|
||||
UINT32 reserved14;
|
||||
UINT32 destination_size; // +0x18
|
||||
UINT32 reserved1c; // +0x1c
|
||||
void* source_ptr; // +0x20: IXboxDStorageFile* (file) or const void* (memory)
|
||||
@@ -1309,13 +1550,45 @@ struct XboxRequest {
|
||||
static_assert(sizeof(XboxRequest) == 56, "XboxRequest must be 56 bytes");
|
||||
static_assert(offsetof(XboxRequest, options) == 0x00, "options offset");
|
||||
static_assert(offsetof(XboxRequest, destination) == 0x08, "destination offset");
|
||||
static_assert(offsetof(XboxRequest, destination_page_offset) == 0x10, "destination_page_offset offset");
|
||||
static_assert(offsetof(XboxRequest, destination_size) == 0x18, "destination_size offset");
|
||||
static_assert(offsetof(XboxRequest, source_ptr) == 0x20, "source_ptr offset");
|
||||
static_assert(offsetof(XboxRequest, file_offset) == 0x28, "file_offset offset");
|
||||
static_assert(offsetof(XboxRequest, source_size) == 0x30, "source_size offset");
|
||||
|
||||
constexpr UINT64 kXboxRequestSourceMemoryBit = 0x400000ull;
|
||||
constexpr UINT64 kXboxRequestCompressedBit = 0x1ull;
|
||||
// DSTORAGE_REQUEST_OPTIONS (authorized GDK documentation): ZlibDecompress:1, BcpackMode:4,
|
||||
// SwizzleMode:16, DestinationIsPhysicalPages:1, SourceType:1, SourceIsPhysicalPages:1.
|
||||
constexpr UINT64 kXboxRequestSourceMemoryBit = 0x400000ull; // SourceType, bit 22
|
||||
constexpr UINT64 kXboxRequestCompressedBit = 0x1ull; // ZlibDecompress, bit 0
|
||||
constexpr UINT64 kXboxRequestBcpackMask = 0xFull << 1;
|
||||
constexpr UINT64 kXboxRequestSwizzleMask = 0xFFFFull << 5;
|
||||
constexpr UINT64 kXboxRequestDestinationPagesBit = 1ull << 21;
|
||||
constexpr UINT64 kXboxRequestSourcePagesBit = 1ull << 23;
|
||||
|
||||
// Logs each distinct option combination once, so a run shows which MDU stages a title uses.
|
||||
void log_request_options(UINT64 options, UINT32 source_size, UINT32 destination_size, UINT32 intermediate_size) {
|
||||
static std::mutex lock;
|
||||
static UINT64 seen[64];
|
||||
static size_t count = 0;
|
||||
const UINT64 key = options & ~kXboxRequestSourceMemoryBit;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(lock);
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
if (seen[i] == key) return;
|
||||
}
|
||||
if (count < 64) seen[count++] = key;
|
||||
}
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"options=0x%llx zlib=%d bcpack_mode=%llu swizzle_mode=%llu dest_pages=%d source_memory=%d source_pages=%d "
|
||||
"first sizes: source=%u destination=%u intermediate=%u",
|
||||
static_cast<unsigned long long>(options), static_cast<int>(options & 1),
|
||||
static_cast<unsigned long long>((options & kXboxRequestBcpackMask) >> 1),
|
||||
static_cast<unsigned long long>((options & kXboxRequestSwizzleMask) >> 5),
|
||||
(options & kXboxRequestDestinationPagesBit) ? 1 : 0, (options & kXboxRequestSourceMemoryBit) ? 1 : 0,
|
||||
(options & kXboxRequestSourcePagesBit) ? 1 : 0, source_size, destination_size, intermediate_size);
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_request_options", detail);
|
||||
}
|
||||
|
||||
struct IXboxDStorageFile : IUnknown {
|
||||
virtual void STDMETHODCALLTYPE Close() = 0;
|
||||
@@ -1424,12 +1697,29 @@ public:
|
||||
reject(E_DSTORAGE_INVALID_SOURCE_TYPE, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
if ((request->options & kXboxRequestCompressedBit) != 0) {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_compressed");
|
||||
log_request_options(request->options, request->source_size, request->destination_size, request->reserved34);
|
||||
// BCPack (BcpackMode, DSTORAGE_BCPACK_MODE 1-7) is decoded by the GDK's BCPack.dll when
|
||||
// BX_BCPACK_DLL names it; combined with zlib, or without the codec, it stays refused.
|
||||
const UINT bcpack_mode = static_cast<UINT>((request->options & kXboxRequestBcpackMask) >> 1);
|
||||
if (bcpack_mode && ((request->options & kXboxRequestCompressedBit) || bcpack_mode > 7 || !bcpack_decompress())) {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_bcpack");
|
||||
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
if (!request->destination || request->source_size != request->destination_size) {
|
||||
if (request->options & kXboxRequestSwizzleMask) {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_swizzle");
|
||||
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
if (request->options & kXboxRequestSourcePagesBit) {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_physical_page_source");
|
||||
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
const bool to_pages = (request->options & kXboxRequestDestinationPagesBit) != 0;
|
||||
const bool zlib = (request->options & kXboxRequestCompressedBit) != 0;
|
||||
if (!request->destination || (zlib ? request->source_size >= request->destination_size
|
||||
: (!bcpack_mode && request->source_size != request->destination_size))) {
|
||||
reject(E_DSTORAGE_INVALID_DESTINATION_SIZE, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
@@ -1437,6 +1727,14 @@ public:
|
||||
Request translated{};
|
||||
translated.destination = request->destination;
|
||||
translated.size = request->source_size;
|
||||
if (zlib) {
|
||||
translated.compression = compression_zlib;
|
||||
translated.output_size = request->destination_size;
|
||||
} else if (bcpack_mode) {
|
||||
translated.compression = compression_bcpack;
|
||||
translated.bcpack_mode = bcpack_mode;
|
||||
translated.output_size = request->destination_size;
|
||||
}
|
||||
if (is_memory) {
|
||||
if (!request->source_ptr) {
|
||||
reject(E_INVALIDARG, Kind::request, "EnqueueRequest");
|
||||
@@ -1452,6 +1750,21 @@ public:
|
||||
translated.file = file->inner();
|
||||
translated.file_offset = request->file_offset;
|
||||
}
|
||||
if (to_pages) {
|
||||
// DestinationSize bytes from DestinationPageOffset in the first page, across as many
|
||||
// 64 KB pages of the array as that covers.
|
||||
constexpr UINT64 page = 64 * 1024;
|
||||
const UINT64 end = static_cast<UINT64>(request->destination_page_offset) + request->destination_size;
|
||||
const ULONG_PTR count = static_cast<ULONG_PTR>((end + page - 1) / page);
|
||||
if (!map_physical_pages()) {
|
||||
reject(HRESULT_FROM_WIN32(ERROR_PROC_NOT_FOUND), Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
// The array stays the title's: it is read when the request runs (map_page_destination).
|
||||
translated.page_array = static_cast<const ULONG_PTR*>(request->destination);
|
||||
translated.page_offset = request->destination_page_offset;
|
||||
translated.page_span_count = count;
|
||||
}
|
||||
accept(queue_->EnqueueRequest(&translated), Kind::request, "EnqueueRequest");
|
||||
}
|
||||
|
||||
@@ -1623,11 +1936,22 @@ public:
|
||||
const UINT slots = desc->capacity - 1u;
|
||||
auto* entries = new (std::nothrow) Entry[slots];
|
||||
if (!entries) return E_OUTOFMEMORY;
|
||||
auto* queue = new (std::nothrow) WorkQueue(entries, slots, true, desc->capacity / 2u);
|
||||
// desc->flags is DSTORAGE_QUEUE_OPTIONS (authorized GDK documentation): bit 0,
|
||||
// AutoSubmitDisabled, makes the queue wait for Submit. A title maps a request's
|
||||
// destination pages after enqueueing it and before submitting, so starting work at half
|
||||
// capacity wrote into pages that were not mapped yet.
|
||||
constexpr UINT64 kAutoSubmitDisabled = 1;
|
||||
const UINT auto_submit = (desc->flags & kAutoSubmitDisabled) ? 0u : desc->capacity / 2u;
|
||||
auto* queue = new (std::nothrow) WorkQueue(entries, slots, true, auto_submit);
|
||||
if (!queue) {
|
||||
delete[] entries;
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "xbox queue '%s' capacity=%u source=%llu auto_submit=%s",
|
||||
desc->name ? desc->name : "", static_cast<unsigned>(desc->capacity),
|
||||
static_cast<unsigned long long>(desc->source_type), auto_submit ? "half capacity" : "disabled");
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_queue", detail);
|
||||
if (!queue->create_work()) {
|
||||
const HRESULT error = win32_error();
|
||||
queue->Release();
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
/* zlib (RFC 1950) / deflate (RFC 1951) decoder; see zlib_inflate.h. */
|
||||
#include "zlib_inflate.h"
|
||||
|
||||
namespace {
|
||||
|
||||
struct Bits {
|
||||
const uint8_t* data;
|
||||
size_t size;
|
||||
size_t pos = 0; // next byte
|
||||
uint32_t buffer = 0;
|
||||
int count = 0; // valid bits in buffer
|
||||
bool overrun = false;
|
||||
|
||||
// RFC 1951 3.1.1: data elements are packed starting with the least significant bit.
|
||||
uint32_t get(int n) {
|
||||
while (count < n) {
|
||||
if (pos >= size) {
|
||||
overrun = true;
|
||||
return 0;
|
||||
}
|
||||
buffer |= static_cast<uint32_t>(data[pos++]) << count;
|
||||
count += 8;
|
||||
}
|
||||
const uint32_t value = buffer & ((n == 32) ? 0xFFFFFFFFu : ((1u << n) - 1u));
|
||||
buffer >>= n;
|
||||
count -= n;
|
||||
return value;
|
||||
}
|
||||
void align_to_byte() {
|
||||
buffer >>= (count & 7);
|
||||
count -= (count & 7);
|
||||
}
|
||||
};
|
||||
|
||||
constexpr int kMaxBits = 15;
|
||||
|
||||
// Canonical Huffman decoding (RFC 1951 3.2.2): counts per code length and symbols sorted by code.
|
||||
struct Huffman {
|
||||
uint16_t counts[kMaxBits + 1] = {};
|
||||
uint16_t symbols[320] = {};
|
||||
|
||||
// Returns false for an over-subscribed set of lengths. An incomplete set is allowed (a
|
||||
// single distance code is legal), and decoding an unassigned code then fails.
|
||||
bool build(const uint8_t* lengths, int n) {
|
||||
for (int i = 0; i <= kMaxBits; ++i) counts[i] = 0;
|
||||
for (int i = 0; i < n; ++i) ++counts[lengths[i]];
|
||||
counts[0] = 0;
|
||||
int left = 1;
|
||||
for (int len = 1; len <= kMaxBits; ++len) {
|
||||
left <<= 1;
|
||||
left -= counts[len];
|
||||
if (left < 0) return false;
|
||||
}
|
||||
uint16_t offsets[kMaxBits + 2] = {};
|
||||
for (int len = 1; len <= kMaxBits; ++len) offsets[len + 1] = offsets[len] + counts[len];
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (lengths[i]) symbols[offsets[lengths[i]]++] = static_cast<uint16_t>(i);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Huffman codes are packed most significant bit first, one bit at a time.
|
||||
int decode(Bits& in) const {
|
||||
int code = 0, first = 0, index = 0;
|
||||
for (int len = 1; len <= kMaxBits; ++len) {
|
||||
code |= static_cast<int>(in.get(1));
|
||||
if (in.overrun) return -1;
|
||||
const int count = counts[len];
|
||||
if (code - first < count) return symbols[index + (code - first)];
|
||||
index += count;
|
||||
first += count;
|
||||
first <<= 1;
|
||||
code <<= 1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
};
|
||||
|
||||
// RFC 1951 3.2.5 length and distance tables.
|
||||
constexpr uint16_t kLengthBase[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
|
||||
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
|
||||
constexpr uint8_t kLengthExtra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
|
||||
constexpr uint16_t kDistBase[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
|
||||
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
|
||||
constexpr uint8_t kDistExtra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
|
||||
|
||||
struct Output {
|
||||
uint8_t* data;
|
||||
size_t size;
|
||||
size_t pos = 0;
|
||||
};
|
||||
|
||||
BxInflateResult codes(Bits& in, Output& out, const Huffman& lit, const Huffman& dist) {
|
||||
for (;;) {
|
||||
const int symbol = lit.decode(in);
|
||||
if (symbol < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
|
||||
if (symbol < 256) {
|
||||
if (out.pos >= out.size) return BxInflateResult::output_mismatch;
|
||||
out.data[out.pos++] = static_cast<uint8_t>(symbol);
|
||||
continue;
|
||||
}
|
||||
if (symbol == 256) return BxInflateResult::ok;
|
||||
const int li = symbol - 257;
|
||||
if (li >= 29) return BxInflateResult::bad_data;
|
||||
const size_t length = kLengthBase[li] + in.get(kLengthExtra[li]);
|
||||
const int ds = dist.decode(in);
|
||||
if (ds < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
|
||||
if (ds >= 30) return BxInflateResult::bad_data;
|
||||
const size_t distance = kDistBase[ds] + in.get(kDistExtra[ds]);
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
if (distance > out.pos) return BxInflateResult::bad_data;
|
||||
if (length > out.size - out.pos) return BxInflateResult::output_mismatch;
|
||||
for (size_t i = 0; i < length; ++i, ++out.pos) out.data[out.pos] = out.data[out.pos - distance];
|
||||
}
|
||||
}
|
||||
|
||||
BxInflateResult fixed_block(Bits& in, Output& out) {
|
||||
static Huffman lit, dist;
|
||||
static bool built = [] {
|
||||
uint8_t lengths[288];
|
||||
int i = 0;
|
||||
for (; i < 144; ++i) lengths[i] = 8;
|
||||
for (; i < 256; ++i) lengths[i] = 9;
|
||||
for (; i < 280; ++i) lengths[i] = 7;
|
||||
for (; i < 288; ++i) lengths[i] = 8;
|
||||
lit.build(lengths, 288);
|
||||
uint8_t dl[30];
|
||||
for (int d = 0; d < 30; ++d) dl[d] = 5;
|
||||
dist.build(dl, 30);
|
||||
return true;
|
||||
}();
|
||||
(void)built;
|
||||
return codes(in, out, lit, dist);
|
||||
}
|
||||
|
||||
BxInflateResult dynamic_block(Bits& in, Output& out) {
|
||||
const int hlit = static_cast<int>(in.get(5)) + 257;
|
||||
const int hdist = static_cast<int>(in.get(5)) + 1;
|
||||
const int hclen = static_cast<int>(in.get(4)) + 4;
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
if (hlit > 286 || hdist > 30) return BxInflateResult::bad_data;
|
||||
static constexpr uint8_t kOrder[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
|
||||
uint8_t lengths[320] = {};
|
||||
for (int i = 0; i < hclen; ++i) lengths[kOrder[i]] = static_cast<uint8_t>(in.get(3));
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
Huffman code_lengths;
|
||||
if (!code_lengths.build(lengths, 19)) return BxInflateResult::bad_data;
|
||||
int index = 0;
|
||||
while (index < hlit + hdist) {
|
||||
int symbol = code_lengths.decode(in);
|
||||
if (symbol < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
|
||||
if (symbol < 16) {
|
||||
lengths[index++] = static_cast<uint8_t>(symbol);
|
||||
continue;
|
||||
}
|
||||
uint8_t value = 0;
|
||||
int repeat;
|
||||
if (symbol == 16) {
|
||||
if (index == 0) return BxInflateResult::bad_data;
|
||||
value = lengths[index - 1];
|
||||
repeat = 3 + static_cast<int>(in.get(2));
|
||||
} else if (symbol == 17) {
|
||||
repeat = 3 + static_cast<int>(in.get(3));
|
||||
} else {
|
||||
repeat = 11 + static_cast<int>(in.get(7));
|
||||
}
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
if (index + repeat > hlit + hdist) return BxInflateResult::bad_data;
|
||||
while (repeat--) lengths[index++] = value;
|
||||
}
|
||||
if (lengths[256] == 0) return BxInflateResult::bad_data; // no end-of-block code
|
||||
Huffman lit, dist;
|
||||
if (!lit.build(lengths, hlit) || !dist.build(lengths + hlit, hdist)) return BxInflateResult::bad_data;
|
||||
return codes(in, out, lit, dist);
|
||||
}
|
||||
|
||||
uint32_t adler32(const uint8_t* data, size_t size) {
|
||||
uint32_t a = 1, b = 0;
|
||||
while (size) {
|
||||
size_t chunk = size < 5552 ? size : 5552; // largest n with no 32-bit overflow before the modulo
|
||||
size -= chunk;
|
||||
while (chunk--) {
|
||||
a += *data++;
|
||||
b += a;
|
||||
}
|
||||
a %= 65521u;
|
||||
b %= 65521u;
|
||||
}
|
||||
return (b << 16) | a;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
BxInflateResult inflate_impl(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size, size_t* produced) {
|
||||
// RFC 1950 2.2: CMF (method 8 = deflate, window <= 32 KiB), FLG (check bits, no FDICT).
|
||||
if (!input || input_size < 6 || (!output && output_size)) return BxInflateResult::bad_header;
|
||||
const uint8_t cmf = input[0], flg = input[1];
|
||||
if ((cmf & 0x0F) != 8 || (cmf >> 4) > 7 || ((cmf << 8) | flg) % 31 != 0 || (flg & 0x20)) {
|
||||
return BxInflateResult::bad_header;
|
||||
}
|
||||
Bits in{input + 2, input_size - 2};
|
||||
Output out{output, output_size};
|
||||
for (;;) {
|
||||
const uint32_t final_block = in.get(1);
|
||||
const uint32_t type = in.get(2);
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
BxInflateResult r;
|
||||
if (type == 0) {
|
||||
in.align_to_byte();
|
||||
const uint32_t len = in.get(16), nlen = in.get(16);
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
if ((len ^ 0xFFFFu) != nlen) return BxInflateResult::bad_data;
|
||||
// After aligning, the bit buffer is empty: copy straight from the byte stream.
|
||||
if (len > in.size - in.pos) return BxInflateResult::truncated;
|
||||
if (len > out.size - out.pos) return BxInflateResult::output_mismatch;
|
||||
for (uint32_t i = 0; i < len; ++i) out.data[out.pos++] = in.data[in.pos++];
|
||||
r = BxInflateResult::ok;
|
||||
} else if (type == 1) {
|
||||
r = fixed_block(in, out);
|
||||
} else if (type == 2) {
|
||||
r = dynamic_block(in, out);
|
||||
} else {
|
||||
return BxInflateResult::bad_data;
|
||||
}
|
||||
if (r != BxInflateResult::ok) return r;
|
||||
if (final_block) break;
|
||||
}
|
||||
if (produced) *produced = out.pos;
|
||||
else if (out.pos != out.size) return BxInflateResult::output_mismatch;
|
||||
// RFC 1950: the Adler-32 trailer follows the deflate data, byte-aligned, most significant first.
|
||||
in.align_to_byte();
|
||||
const size_t trailer = in.pos - static_cast<size_t>(in.count / 8);
|
||||
if (input_size - 2 - trailer < 4) return BxInflateResult::truncated;
|
||||
const uint8_t* t = in.data + trailer;
|
||||
const uint32_t expected = (static_cast<uint32_t>(t[0]) << 24) | (static_cast<uint32_t>(t[1]) << 16) |
|
||||
(static_cast<uint32_t>(t[2]) << 8) | t[3];
|
||||
return adler32(output, out.pos) == expected ? BxInflateResult::ok : BxInflateResult::bad_checksum;
|
||||
}
|
||||
|
||||
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size) {
|
||||
return inflate_impl(input, input_size, output, output_size, nullptr);
|
||||
}
|
||||
|
||||
BxInflateResult bx_zlib_inflate_any(const uint8_t* input, size_t input_size, uint8_t* output, size_t capacity, size_t* produced) {
|
||||
*produced = 0;
|
||||
return inflate_impl(input, input_size, output, capacity, produced);
|
||||
}
|
||||
|
||||
const char* bx_inflate_result_name(BxInflateResult result) {
|
||||
switch (result) {
|
||||
case BxInflateResult::ok: return "ok";
|
||||
case BxInflateResult::bad_header: return "bad_header";
|
||||
case BxInflateResult::bad_data: return "bad_data";
|
||||
case BxInflateResult::truncated: return "truncated";
|
||||
case BxInflateResult::output_mismatch: return "output_mismatch";
|
||||
case BxInflateResult::bad_checksum: return "bad_checksum";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
* A zlib stream decoder written from the public specifications: IETF RFC 1950 (the zlib
|
||||
* wrapper and its Adler-32 check) and RFC 1951 (deflate: stored, fixed-Huffman and
|
||||
* dynamic-Huffman blocks, 32 KiB window). No third-party code.
|
||||
*
|
||||
* Used for DirectStorage requests whose DSTORAGE_REQUEST_OPTIONS.ZlibDecompress bit is set
|
||||
* (authorized GDK documentation: RFC 1950 streams, full 32 KiB window, compressed size smaller
|
||||
* than the decompressed size).
|
||||
*/
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
enum class BxInflateResult {
|
||||
ok,
|
||||
bad_header, // not an RFC 1950 header, or a preset dictionary is required
|
||||
bad_data, // malformed deflate data
|
||||
truncated, // the input ended before the final block
|
||||
output_mismatch, // the stream does not produce exactly `output_size` bytes
|
||||
bad_checksum, // Adler-32 of the output does not match the stream trailer
|
||||
};
|
||||
|
||||
/* Decodes `input` into exactly `output_size` bytes at `output`. */
|
||||
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size);
|
||||
|
||||
/* Decodes `input` into at most `capacity` bytes and reports how many the stream produced
|
||||
(checksum verified over those bytes). */
|
||||
BxInflateResult bx_zlib_inflate_any(const uint8_t* input, size_t input_size, uint8_t* output, size_t capacity, size_t* produced);
|
||||
|
||||
const char* bx_inflate_result_name(BxInflateResult result);
|
||||
@@ -1,4 +1,4 @@
|
||||
bx_add_shim_dll(xg_xs xg_xs xg_xs.def
|
||||
xg_xs.cpp
|
||||
xg_xbox.cpp
|
||||
)
|
||||
target_link_libraries(xg_xs PRIVATE bx_runtime_veh kernel32)
|
||||
@@ -1,195 +0,0 @@
|
||||
#ifndef BETTERXEN_XG_TEXTURE_H
|
||||
#define BETTERXEN_XG_TEXTURE_H
|
||||
|
||||
/*
|
||||
* BetterXen M1 linear texture-address contract for xg_xs.dll.
|
||||
*
|
||||
* Field meanings follow the public D3D12 resource and footprint documents
|
||||
* (D3D12_RESOURCE_DIMENSION, D3D12_SUBRESOURCE_FOOTPRINT, and
|
||||
* D3D12_TEXTURE_DATA_PITCH_ALIGNMENT / D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT).
|
||||
* Block-compressed footprint width and height are texels rounded up to the
|
||||
* 4x4 block, the same rounding D3D12 uses for a copyable footprint.
|
||||
* Format numbers are the public DXGI_FORMAT values. This is not the Xbox
|
||||
* GDK XG interface and it is not an Xbox hardware result.
|
||||
*/
|
||||
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
|
||||
#include <windows.h>
|
||||
#include <stdint.h>
|
||||
#include <dxgiformat.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Public D3D12_RESOURCE_DIMENSION values used by this shim. */
|
||||
#define BX_XG_DIMENSION_BUFFER 1u
|
||||
#define BX_XG_DIMENSION_TEXTURE1D 2u
|
||||
#define BX_XG_DIMENSION_TEXTURE2D 3u
|
||||
#define BX_XG_DIMENSION_TEXTURE3D 4u
|
||||
|
||||
/* Public D3D12 texture copy alignments, in bytes. */
|
||||
#define BX_XG_LINEAR_PITCH_ALIGNMENT 256u
|
||||
#define BX_XG_LINEAR_PLACEMENT_ALIGNMENT 512u
|
||||
|
||||
/* Public D3D12 texture size limits used as the acceptance cap. */
|
||||
#define BX_XG_MAX_TEXTURE_EDGE 16384u
|
||||
#define BX_XG_MAX_ARRAY_SLICES 2048u
|
||||
|
||||
/*
|
||||
* Layout selectors for this shim. LINEAR is computed exactly.
|
||||
* SW_64KB_S / D / R are named RDNA 2 tile modes reserved for M3. They are
|
||||
* accepted by XGCreateTextureComputer and every layout or copy call on them
|
||||
* returns E_NOTIMPL without writing an address.
|
||||
* XGSuggestSwizzleMode never returns a tile mode. It returns LINEAR or NONE.
|
||||
*/
|
||||
typedef enum bx_xg_layout_mode {
|
||||
BX_XG_LAYOUT_LINEAR = 0,
|
||||
BX_XG_LAYOUT_SW_64KB_S = 1,
|
||||
BX_XG_LAYOUT_SW_64KB_D = 2,
|
||||
BX_XG_LAYOUT_SW_64KB_R = 3,
|
||||
BX_XG_LAYOUT_NONE = 0xFFFFFFFFu
|
||||
} bx_xg_layout_mode;
|
||||
|
||||
typedef struct bx_xg_sample_desc {
|
||||
uint32_t count;
|
||||
uint32_t quality;
|
||||
} bx_xg_sample_desc;
|
||||
|
||||
typedef struct bx_xg_resource_desc {
|
||||
uint32_t dimension;
|
||||
uint32_t alignment; /* 0 or BX_XG_LINEAR_PLACEMENT_ALIGNMENT */
|
||||
uint64_t width; /* texels */
|
||||
uint32_t height; /* texels */
|
||||
uint16_t depth_or_array_size;
|
||||
uint16_t mip_levels; /* 0 selects the full chain, down to 1x1 */
|
||||
uint32_t format; /* DXGI_FORMAT */
|
||||
bx_xg_sample_desc sample_desc;
|
||||
uint32_t layout; /* bx_xg_layout_mode */
|
||||
uint32_t flags; /* must be 0 */
|
||||
} bx_xg_resource_desc;
|
||||
|
||||
typedef struct bx_xg_subresource_footprint {
|
||||
uint32_t format;
|
||||
uint32_t width; /* texels, rounded up to the format block width */
|
||||
uint32_t height; /* texels, rounded up to the format block height */
|
||||
uint32_t depth;
|
||||
uint32_t row_pitch; /* bytes, multiple of BX_XG_LINEAR_PITCH_ALIGNMENT */
|
||||
} bx_xg_subresource_footprint;
|
||||
|
||||
typedef struct bx_xg_placed_footprint {
|
||||
uint64_t offset;
|
||||
bx_xg_subresource_footprint footprint;
|
||||
/*
|
||||
* Absolute byte just past this subresource's last payload byte:
|
||||
* offset + (row_count - 1) * row_pitch + row_bytes.
|
||||
* That is the D3D12 GetCopyableFootprints end. It does not include the
|
||||
* last row's pitch padding or the 512-byte tail. The copy span of a
|
||||
* GetResourceLayout call is layouts[last].copy_end - base_offset.
|
||||
*/
|
||||
uint64_t copy_end;
|
||||
} bx_xg_placed_footprint;
|
||||
|
||||
/* {B7E4C8A1-6F2D-4C55-8A19-3D0E5F7B91C4} BetterXen IXGTextureAddressComputer */
|
||||
static const GUID BX_IID_IXGTextureAddressComputer = {
|
||||
0xB7E4C8A1u, 0x6F2Du, 0x4C55u, {0x8Au, 0x19u, 0x3Du, 0x0Eu, 0x5Fu, 0x7Bu, 0x91u, 0xC4u}};
|
||||
|
||||
/* Public COM IUnknown IID. */
|
||||
static const GUID BX_IID_IUnknown = {
|
||||
0x00000000u, 0x0000u, 0x0000u, {0xC0u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x46u}};
|
||||
|
||||
/*
|
||||
* GetResourceLayout places every subresource at its absolute offset from
|
||||
* base_offset, including subresources before first_subresource. total_bytes
|
||||
* is the BetterXen allocation span: the 512-aligned end of the last requested
|
||||
* subresource, measured from base_offset, so a partial range still covers the
|
||||
* earlier subresources and a 1x1 RGBA8 texture reports 512. copy_end on each
|
||||
* footprint is the separate D3D12-style copy span end described above.
|
||||
*/
|
||||
typedef struct bx_xg_texture_computer bx_xg_texture_computer;
|
||||
|
||||
typedef struct bx_xg_texture_computer_vtbl {
|
||||
HRESULT(WINAPI* QueryInterface)(bx_xg_texture_computer* self, const GUID* riid, void** object);
|
||||
ULONG(WINAPI* AddRef)(bx_xg_texture_computer* self);
|
||||
ULONG(WINAPI* Release)(bx_xg_texture_computer* self);
|
||||
HRESULT(WINAPI* GetResourceLayout)(
|
||||
bx_xg_texture_computer* self,
|
||||
uint32_t first_subresource,
|
||||
uint32_t subresource_count,
|
||||
uint64_t base_offset,
|
||||
bx_xg_placed_footprint* layouts,
|
||||
uint32_t* row_counts,
|
||||
uint64_t* row_sizes_in_bytes,
|
||||
uint64_t* total_bytes);
|
||||
HRESULT(WINAPI* GetResourceSizeBytes)(bx_xg_texture_computer* self, uint64_t* size_bytes);
|
||||
HRESULT(WINAPI* GetResourceBaseAlignmentBytes)(bx_xg_texture_computer* self, uint64_t* alignment_bytes);
|
||||
HRESULT(WINAPI* GetMipLevelOffsetBytes)(
|
||||
bx_xg_texture_computer* self,
|
||||
uint32_t array_slice,
|
||||
uint32_t mip_level,
|
||||
uint64_t* offset_bytes);
|
||||
HRESULT(WINAPI* GetTexelElementOffsetBytes)(
|
||||
bx_xg_texture_computer* self,
|
||||
uint32_t array_slice,
|
||||
uint32_t mip_level,
|
||||
uint32_t x,
|
||||
uint32_t y,
|
||||
uint32_t z,
|
||||
uint64_t* offset_bytes);
|
||||
HRESULT(WINAPI* CopyIntoSubresource)(
|
||||
bx_xg_texture_computer* self,
|
||||
void* destination,
|
||||
uint64_t destination_size,
|
||||
uint32_t subresource,
|
||||
const void* source,
|
||||
uint64_t source_size,
|
||||
uint32_t source_row_pitch,
|
||||
uint32_t source_depth_pitch);
|
||||
HRESULT(WINAPI* CopyFromSubresource)(
|
||||
bx_xg_texture_computer* self,
|
||||
void* destination,
|
||||
uint64_t destination_size,
|
||||
uint32_t destination_row_pitch,
|
||||
uint32_t destination_depth_pitch,
|
||||
const void* source,
|
||||
uint64_t source_size,
|
||||
uint32_t subresource);
|
||||
} bx_xg_texture_computer_vtbl;
|
||||
|
||||
struct bx_xg_texture_computer {
|
||||
const bx_xg_texture_computer_vtbl* lpVtbl;
|
||||
};
|
||||
|
||||
/*
|
||||
* On success, *computer is an IXGTextureAddressComputer with a reference
|
||||
* count of 1. On failure, *computer is NULL when computer itself is non-NULL.
|
||||
* Subresource index is mip_level + array_slice * mip_levels.
|
||||
* A row pitch of 0 on a copy selects the tight logical row size.
|
||||
*/
|
||||
HRESULT WINAPI XGCreateTextureComputer(const bx_xg_resource_desc* desc, void** computer);
|
||||
|
||||
/*
|
||||
* Returns BX_XG_LAYOUT_LINEAR when this shim can lay the texture out, and
|
||||
* BX_XG_LAYOUT_NONE otherwise. The same arguments always return the same mode.
|
||||
*/
|
||||
uint32_t WINAPI XGSuggestSwizzleMode(
|
||||
uint32_t resource_type,
|
||||
uint32_t format,
|
||||
uint32_t width,
|
||||
uint32_t height,
|
||||
uint32_t depth,
|
||||
uint32_t mip_levels,
|
||||
uint32_t sample_count,
|
||||
uint32_t flags);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* BETTERXEN_XG_TEXTURE_H */
|
||||
@@ -0,0 +1,683 @@
|
||||
/*
|
||||
* The XG texture-address contract as titles call it (authorized GDK documentation, xg_xs.h):
|
||||
* XGCreateTextureComputer(const XG_RESOURCE_DESC*, XGTextureAddressComputer**) and
|
||||
* XGSuggestSwizzleMode(const XG_RESOURCE_DESC*, flags, XG_TEXTURE_LAYOUT*). Only the structure
|
||||
* layouts, enum values and the method order are taken from there; no header text is reproduced.
|
||||
*
|
||||
* The layout this computer reports is BetterXen's, not the console's: every texture is laid out
|
||||
* linearly (swizzle mode LINEAR), mip-major (each mip holds all of its array or depth slices),
|
||||
* rows aligned to 256 bytes, mips to 512 bytes, the resource to 64 KB. Depth-stencil formats
|
||||
* get a separate depth plane and stencil plane. Every method uses the same layout, so sizes,
|
||||
* offsets, texel addresses and copies agree with each other. Data a title stores pre-tiled for
|
||||
* the console's swizzle modes is not detiled by this layer.
|
||||
*
|
||||
* The one exception is an explicit request for XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_S on a 2D
|
||||
* texture that fits in one 64 KiB tile (one mip, one slice, 4-, 8- or 16-byte elements): that
|
||||
* gets the RDNA 2 SW_64KB_S addresses (see Sw64kbS). Any other explicit swizzle mode, and
|
||||
* SW_64KB_S on a texture larger than one tile, is laid out linearly, reported as LINEAR
|
||||
* (SwizzleMode 0) and logged once per mode: titles do not check XGCreateTextureComputer for a
|
||||
* mode they request, so refusing it crashed one.
|
||||
*/
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <dxgiformat.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
namespace {
|
||||
|
||||
// --- XG types (layouts from xg_xs.h) -------------------------------------------------------
|
||||
enum : uint32_t {
|
||||
kDimBuffer = 1,
|
||||
kDimTexture1D = 2,
|
||||
kDimTexture2D = 3,
|
||||
kDimTexture3D = 4,
|
||||
};
|
||||
// XG_TEXTURE_LAYOUT: 0 default (XG chooses), 1 row major, 2 64 KB with an undefined swizzle, or
|
||||
// 0x100 | XG_SWIZZLE_MODE to request one swizzle mode.
|
||||
constexpr uint32_t kLayoutSwizzleFlag = 0x100;
|
||||
constexpr uint32_t kLayoutSwizzleLinear = 0x100; // XG_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR
|
||||
constexpr uint32_t kSwizzleModeLinear = 0;
|
||||
constexpr uint32_t kSwizzleMode64KbS = 9; // XG_SWIZZLE_MODE_64KB_S
|
||||
enum : uint32_t { kPlaneUnused = 0, kPlaneDefault = 1, kPlaneDepth = 7, kPlaneStencil = 8 };
|
||||
|
||||
// --- RDNA 2 SW_64KB_S (clean-room, ported from the earlier xg_xs.cpp) ---------------------
|
||||
// Within one 64 KiB tile, the byte offset of element (x, y) is pdep(x, x_mask) | pdep(y, y_mask),
|
||||
// x and y in elements (texels, or 4x4 blocks for BC). The masks come from the public AddrLib RB+
|
||||
// pattern tables (GFX10_SW_64K_S_RBPLUS_PATINFO, MIT); at 4 bytes per element the x mask equals
|
||||
// the public D3D12 standard-swizzle xBytesMask 0xAA8F without its two intra-texel bits, and the y
|
||||
// mask equals D3D12's 0x5570. Each row is a bijection over its tile. How tiles are ordered across a
|
||||
// larger surface is not established from public sources, so only surfaces that fit in one tile
|
||||
// are addressed; larger ones fall back to the logged linear layout.
|
||||
struct Sw64kbS {
|
||||
uint32_t bytes;
|
||||
uint32_t x_mask;
|
||||
uint32_t y_mask;
|
||||
uint32_t tile_x; // elements per tile row
|
||||
uint32_t tile_y; // element rows per tile
|
||||
};
|
||||
bool sw64kb_s_params(uint32_t bytes, Sw64kbS* out) {
|
||||
switch (bytes) {
|
||||
case 4: *out = {4, 0xAA8Cu, 0x5570u, 128, 128}; return true;
|
||||
case 8: *out = {8, 0xAAC8u, 0x5530u, 128, 64}; return true;
|
||||
case 16: *out = {16, 0xAAC0u, 0x5530u, 64, 64}; return true;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
uint32_t pdep(uint32_t value, uint32_t mask) {
|
||||
uint32_t out = 0;
|
||||
for (uint32_t bit = 1; mask; bit <<= 1) {
|
||||
const uint32_t lowest = mask & (0u - mask);
|
||||
if (value & bit) out |= lowest;
|
||||
mask ^= lowest;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
uint32_t pext(uint32_t value, uint32_t mask) {
|
||||
uint32_t out = 0;
|
||||
for (uint32_t bit = 1; mask; bit <<= 1) {
|
||||
const uint32_t lowest = mask & (0u - mask);
|
||||
if (value & lowest) out |= bit;
|
||||
mask ^= lowest;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
constexpr uint64_t kTileBytes = 64 * 1024;
|
||||
|
||||
struct XgSampleDesc {
|
||||
UINT Count;
|
||||
UINT Quality;
|
||||
};
|
||||
|
||||
struct XgResourceDesc {
|
||||
uint32_t Dimension;
|
||||
UINT64 Alignment;
|
||||
UINT64 Width;
|
||||
UINT Height;
|
||||
UINT16 DepthOrArraySize;
|
||||
UINT16 MipLevels;
|
||||
uint32_t Format;
|
||||
XgSampleDesc SampleDesc;
|
||||
uint32_t Layout;
|
||||
uint32_t MiscFlags;
|
||||
};
|
||||
|
||||
struct XgMipLevelLayout {
|
||||
UINT64 SizeBytes;
|
||||
UINT64 OffsetBytes;
|
||||
UINT64 Slice2DSizeBytes;
|
||||
UINT32 PitchPixels;
|
||||
UINT32 PitchBytes;
|
||||
UINT32 AlignmentBytes;
|
||||
UINT32 PaddedWidthElements;
|
||||
UINT32 PaddedHeightElements;
|
||||
UINT32 PaddedDepthOrArraySize;
|
||||
UINT32 WidthElements;
|
||||
UINT32 HeightElements;
|
||||
UINT32 WidthPixels;
|
||||
UINT32 HeightPixels;
|
||||
UINT32 DepthOrArraySize;
|
||||
UINT32 SampleCount;
|
||||
uint32_t SwizzleMode;
|
||||
UINT64 BankRotationAddressBitMask;
|
||||
UINT64 BankRotationBytesPerSlice;
|
||||
UINT32 SliceDepthElements;
|
||||
UINT32 IsMipTail;
|
||||
UINT32 MipTailOffsetElementsX : 11;
|
||||
UINT32 MipTailOffsetElementsY : 11;
|
||||
UINT32 MipTailOffsetElementsZ : 10;
|
||||
};
|
||||
|
||||
constexpr int kMaxMips = 15;
|
||||
constexpr int kMaxPlanes = 4;
|
||||
|
||||
struct XgPlaneLayout {
|
||||
uint32_t Usage;
|
||||
UINT64 SizeBytes;
|
||||
UINT64 SliceSizeBytes;
|
||||
UINT64 BaseOffsetBytes;
|
||||
UINT64 BaseAlignmentBytes;
|
||||
UINT32 BytesPerElement;
|
||||
UINT32 StandardMipCount;
|
||||
UINT32 MipTailMipCount;
|
||||
XgMipLevelLayout MipLayout[kMaxMips];
|
||||
};
|
||||
|
||||
struct XgResourceLayout {
|
||||
UINT64 SizeBytes;
|
||||
UINT64 BaseAlignmentBytes;
|
||||
UINT32 MipLevels;
|
||||
UINT32 Planes;
|
||||
XgPlaneLayout Plane[kMaxPlanes];
|
||||
uint32_t Dimension;
|
||||
};
|
||||
|
||||
// Pinned against the layouts derived from the GDK header (natural x64 alignment).
|
||||
static_assert(sizeof(XgResourceDesc) == 56, "XG_RESOURCE_DESC size");
|
||||
static_assert(offsetof(XgResourceDesc, Alignment) == 8 && offsetof(XgResourceDesc, Width) == 16, "XG_RESOURCE_DESC");
|
||||
static_assert(sizeof(XgMipLevelLayout) == 112, "XG_MIPLEVEL_LAYOUT size");
|
||||
static_assert(offsetof(XgPlaneLayout, MipLayout) == 56 && sizeof(XgPlaneLayout) == 1736, "XG_PLANE_LAYOUT size");
|
||||
static_assert(offsetof(XgResourceLayout, Plane) == 24 && sizeof(XgResourceLayout) == 6976, "XG_RESOURCE_LAYOUT size");
|
||||
|
||||
struct XgPackedMipDesc {
|
||||
UINT8 NumStandardMips;
|
||||
UINT8 NumPackedMips;
|
||||
UINT32 NumTilesForPackedMips;
|
||||
UINT32 StartTileIndexInOverallResource;
|
||||
};
|
||||
struct XgTileShape {
|
||||
UINT32 WidthInTexels;
|
||||
UINT32 HeightInTexels;
|
||||
UINT32 DepthInTexels;
|
||||
};
|
||||
struct XgSubresourceTiling {
|
||||
UINT32 WidthInTiles;
|
||||
UINT16 HeightInTiles;
|
||||
UINT16 DepthInTiles;
|
||||
UINT32 StartTileIndexInOverallResource;
|
||||
};
|
||||
|
||||
// --- Formats -------------------------------------------------------------------------------
|
||||
struct FormatInfo {
|
||||
uint32_t block; // texels per element edge: 1, or 4 for block compression
|
||||
uint32_t bytes; // bytes per element
|
||||
uint32_t stencil; // 1 when the format carries a stencil plane
|
||||
};
|
||||
|
||||
bool format_info(uint32_t f, FormatInfo* out) {
|
||||
auto set = [&](uint32_t block, uint32_t bytes, uint32_t stencil = 0) {
|
||||
*out = {block, bytes, stencil};
|
||||
return true;
|
||||
};
|
||||
if (f >= DXGI_FORMAT_R32G32B32A32_TYPELESS && f <= DXGI_FORMAT_R32G32B32A32_SINT) return set(1, 16);
|
||||
if (f >= DXGI_FORMAT_R32G32B32_TYPELESS && f <= DXGI_FORMAT_R32G32B32_SINT) return set(1, 12);
|
||||
if (f >= DXGI_FORMAT_R16G16B16A16_TYPELESS && f <= DXGI_FORMAT_R32G32_SINT) return set(1, 8);
|
||||
if (f >= DXGI_FORMAT_R32G8X24_TYPELESS && f <= DXGI_FORMAT_X32_TYPELESS_G8X24_UINT) return set(1, 4, 1);
|
||||
if (f >= DXGI_FORMAT_R10G10B10A2_TYPELESS && f <= DXGI_FORMAT_R32_SINT) return set(1, 4);
|
||||
if (f >= DXGI_FORMAT_R24G8_TYPELESS && f <= DXGI_FORMAT_X24_TYPELESS_G8_UINT) return set(1, 4, 1);
|
||||
if (f >= DXGI_FORMAT_R8G8_TYPELESS && f <= DXGI_FORMAT_R16_SINT) return set(1, 2);
|
||||
if (f >= DXGI_FORMAT_R8_TYPELESS && f <= DXGI_FORMAT_A8_UNORM) return set(1, 1);
|
||||
if (f == DXGI_FORMAT_R9G9B9E5_SHAREDEXP || f == DXGI_FORMAT_R8G8_B8G8_UNORM || f == DXGI_FORMAT_G8R8_G8B8_UNORM) return set(1, 4);
|
||||
if ((f >= DXGI_FORMAT_BC1_TYPELESS && f <= DXGI_FORMAT_BC1_UNORM_SRGB) ||
|
||||
(f >= DXGI_FORMAT_BC4_TYPELESS && f <= DXGI_FORMAT_BC4_SNORM)) {
|
||||
return set(4, 8);
|
||||
}
|
||||
if ((f >= DXGI_FORMAT_BC2_TYPELESS && f <= DXGI_FORMAT_BC3_UNORM_SRGB) ||
|
||||
(f >= DXGI_FORMAT_BC5_TYPELESS && f <= DXGI_FORMAT_BC5_SNORM) ||
|
||||
(f >= DXGI_FORMAT_BC6H_TYPELESS && f <= DXGI_FORMAT_BC7_UNORM_SRGB)) {
|
||||
return set(4, 16);
|
||||
}
|
||||
if (f >= DXGI_FORMAT_B5G6R5_UNORM && f <= DXGI_FORMAT_B5G5R5A1_UNORM) return set(1, 2);
|
||||
if (f >= DXGI_FORMAT_B8G8R8A8_UNORM && f <= DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) return set(1, 4);
|
||||
if (f == DXGI_FORMAT_B4G4R4A4_UNORM) return set(1, 2);
|
||||
return false;
|
||||
}
|
||||
|
||||
uint64_t align_up(uint64_t v, uint64_t a) { return (v + a - 1) / a * a; }
|
||||
uint32_t mip_extent(uint64_t base, uint32_t mip) {
|
||||
const uint64_t v = base >> mip;
|
||||
return v ? static_cast<uint32_t>(v) : 1u;
|
||||
}
|
||||
|
||||
constexpr uint64_t kRowAlign = 256;
|
||||
constexpr uint64_t kMipAlign = 512;
|
||||
constexpr uint64_t kResourceAlign = 64 * 1024;
|
||||
|
||||
void log_rejected(const XgResourceDesc* d, const char* why) {
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "%s: dim=%u width=%llu height=%u depth_or_array=%u mips=%u format=%u samples=%u layout=0x%x",
|
||||
why, d->Dimension, static_cast<unsigned long long>(d->Width), d->Height, d->DepthOrArraySize,
|
||||
d->MipLevels, d->Format, d->SampleDesc.Count, d->Layout);
|
||||
bx_log_emit(BX_LOG_WARN, "xg_xs", "texture_computer_rejected", detail);
|
||||
}
|
||||
|
||||
// A requested swizzle mode this layer does not implement: laid out (and reported) linearly; the
|
||||
// first request for each mode is logged, with the description.
|
||||
void log_linear_instead(const XgResourceDesc* d) {
|
||||
static std::atomic<uint32_t> seen[32];
|
||||
const uint32_t mode = d->Layout & 0x1F;
|
||||
if (seen[mode].exchange(1)) return;
|
||||
log_rejected(d, "requested swizzle mode is not implemented; laid out and reported as LINEAR");
|
||||
}
|
||||
|
||||
// --- The computer ---------------------------------------------------------------------------
|
||||
class XGTextureAddressComputer {
|
||||
public:
|
||||
virtual ULONG AddRef() = 0;
|
||||
virtual ULONG Release() = 0;
|
||||
virtual HRESULT GetResourceLayout(XgResourceLayout* layout) = 0;
|
||||
virtual UINT64 GetResourceSizeBytes() = 0;
|
||||
virtual UINT64 GetResourceBaseAlignmentBytes() = 0;
|
||||
virtual UINT64 GetMipLevelOffsetBytes(UINT32 plane, UINT32 mip) = 0;
|
||||
virtual UINT64 GetTexelElementOffsetBytes(UINT32 plane, UINT32 mip, UINT64 x, UINT32 y, UINT32 z_or_slice,
|
||||
UINT32 sample, UINT32* bit_position) = 0;
|
||||
virtual HRESULT GetTexelCoordinate(UINT64 offset, UINT32* plane, UINT32* mip, UINT64* x, UINT32* y,
|
||||
UINT32* z_or_slice, UINT32* sample) = 0;
|
||||
virtual HRESULT CopyIntoSubresource(void* base, UINT32 plane, UINT32 subresource, const void* linear,
|
||||
UINT32 row_pitch, UINT32 slice_pitch) = 0;
|
||||
virtual HRESULT CopyFromSubresource(void* linear, UINT32 plane, UINT32 subresource, UINT32 sample,
|
||||
const void* base, UINT32 row_pitch, UINT32 slice_pitch) = 0;
|
||||
virtual HRESULT GetResourceTiling(UINT32* total_tiles, XgPackedMipDesc* packed, XgTileShape* shape,
|
||||
UINT32* subresource_count, UINT32 first_subresource,
|
||||
XgSubresourceTiling* tilings) = 0;
|
||||
virtual HRESULT GetTextureViewDescriptor(UINT32 plane, void* descriptor) = 0;
|
||||
virtual bool IsTiledResource() = 0;
|
||||
virtual HRESULT GetSwizzlePatternInfo(UINT32 plane, void* info) = 0;
|
||||
};
|
||||
|
||||
class LayoutComputer final : public XGTextureAddressComputer {
|
||||
public:
|
||||
static HRESULT create(const XgResourceDesc& desc, XGTextureAddressComputer** out);
|
||||
|
||||
ULONG AddRef() override { return ++refs_; }
|
||||
ULONG Release() override {
|
||||
const ULONG left = --refs_;
|
||||
if (!left) delete this;
|
||||
return left;
|
||||
}
|
||||
HRESULT GetResourceLayout(XgResourceLayout* layout) override {
|
||||
if (!layout) return E_POINTER;
|
||||
*layout = layout_;
|
||||
return S_OK;
|
||||
}
|
||||
UINT64 GetResourceSizeBytes() override { return layout_.SizeBytes; }
|
||||
UINT64 GetResourceBaseAlignmentBytes() override { return layout_.BaseAlignmentBytes; }
|
||||
UINT64 GetMipLevelOffsetBytes(UINT32 plane, UINT32 mip) override {
|
||||
if (plane >= layout_.Planes || mip >= layout_.MipLevels) return 0;
|
||||
return layout_.Plane[plane].MipLayout[mip].OffsetBytes;
|
||||
}
|
||||
UINT64 GetTexelElementOffsetBytes(UINT32 plane, UINT32 mip, UINT64 x, UINT32 y, UINT32 z, UINT32 sample,
|
||||
UINT32* bit_position) override {
|
||||
if (bit_position) *bit_position = 0;
|
||||
if (plane >= layout_.Planes || mip >= layout_.MipLevels) return 0;
|
||||
const XgPlaneLayout& p = layout_.Plane[plane];
|
||||
const XgMipLevelLayout& m = p.MipLayout[mip];
|
||||
const uint64_t ex = x / block_, ey = y / block_;
|
||||
if (swizzled_) {
|
||||
if (ex >= sw_.tile_x || ey >= sw_.tile_y) return 0;
|
||||
return m.OffsetBytes + element_offset(static_cast<uint32_t>(ex), static_cast<uint32_t>(ey));
|
||||
}
|
||||
return m.OffsetBytes + z * m.Slice2DSizeBytes + ey * m.PitchBytes +
|
||||
(ex * m.SampleCount + sample) * p.BytesPerElement;
|
||||
}
|
||||
HRESULT GetTexelCoordinate(UINT64 offset, UINT32* plane, UINT32* mip, UINT64* x, UINT32* y, UINT32* z,
|
||||
UINT32* sample) override {
|
||||
for (UINT32 pi = 0; pi < layout_.Planes; ++pi) {
|
||||
const XgPlaneLayout& p = layout_.Plane[pi];
|
||||
for (UINT32 mi = 0; mi < layout_.MipLevels; ++mi) {
|
||||
const XgMipLevelLayout& m = p.MipLayout[mi];
|
||||
if (offset < m.OffsetBytes || offset >= m.OffsetBytes + m.SizeBytes) continue;
|
||||
const uint64_t rel = offset - m.OffsetBytes;
|
||||
if (swizzled_) {
|
||||
const uint32_t in_tile = static_cast<uint32_t>(rel);
|
||||
if (plane) *plane = pi;
|
||||
if (mip) *mip = mi;
|
||||
if (z) *z = 0;
|
||||
if (y) *y = pext(in_tile, sw_.y_mask) * block_;
|
||||
if (x) *x = static_cast<UINT64>(pext(in_tile, sw_.x_mask)) * block_;
|
||||
if (sample) *sample = 0;
|
||||
return S_OK;
|
||||
}
|
||||
const uint64_t in_slice = rel % m.Slice2DSizeBytes;
|
||||
const uint64_t element = (in_slice % m.PitchBytes) / p.BytesPerElement;
|
||||
if (plane) *plane = pi;
|
||||
if (mip) *mip = mi;
|
||||
if (z) *z = static_cast<UINT32>(rel / m.Slice2DSizeBytes);
|
||||
if (y) *y = static_cast<UINT32>(in_slice / m.PitchBytes * block_);
|
||||
if (x) *x = element / m.SampleCount * block_;
|
||||
if (sample) *sample = static_cast<UINT32>(element % m.SampleCount);
|
||||
return S_OK;
|
||||
}
|
||||
}
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
HRESULT CopyIntoSubresource(void* base, UINT32 plane, UINT32 subresource, const void* linear, UINT32 row_pitch,
|
||||
UINT32 slice_pitch) override {
|
||||
return copy(static_cast<uint8_t*>(base), plane, subresource, static_cast<const uint8_t*>(linear), row_pitch,
|
||||
slice_pitch, true);
|
||||
}
|
||||
HRESULT CopyFromSubresource(void* linear, UINT32 plane, UINT32 subresource, UINT32, const void* base,
|
||||
UINT32 row_pitch, UINT32 slice_pitch) override {
|
||||
return copy(static_cast<uint8_t*>(const_cast<void*>(base)), plane, subresource, static_cast<uint8_t*>(linear),
|
||||
row_pitch, slice_pitch, false);
|
||||
}
|
||||
HRESULT GetResourceTiling(UINT32* total_tiles, XgPackedMipDesc* packed, XgTileShape* shape, UINT32* count,
|
||||
UINT32 first, XgSubresourceTiling* tilings) override {
|
||||
// D3D12 standard 64 KB tiles (the public D3D12 tiled-resource rules): the tile shape follows
|
||||
// the element size (256x256 one-byte elements down to 64x64 sixteen-byte ones, in blocks for
|
||||
// block-compressed formats). Leading mips at least one tile wide and high are standard; the
|
||||
// smaller rest are packed into a mip tail per array slice, as on the console, whose titles
|
||||
// expect few standard mips. Tiles are numbered over the subresources in order (mip-major
|
||||
// within a slice), each slice's packed tail after its standard mips.
|
||||
// 3D resources use the D3D12 standard 3D tile shapes (64x32x32 one-byte elements down to
|
||||
// 16x16x16 sixteen-byte ones), 1D textures a 64 KiB row of elements, buffers 64 KiB.
|
||||
const uint32_t bpe = layout_.Plane[0].BytesPerElement;
|
||||
const bool volume = layout_.Dimension == kDimTexture3D;
|
||||
uint32_t tile_w = 128, tile_h = 128, tile_d = 1;
|
||||
if (layout_.Dimension == kDimBuffer) {
|
||||
tile_w = 65536;
|
||||
tile_h = 1;
|
||||
} else if (layout_.Dimension == kDimTexture1D) {
|
||||
tile_w = 65536 / (bpe ? bpe : 1) * block_;
|
||||
tile_h = 1;
|
||||
} else if (volume) {
|
||||
switch (bpe) {
|
||||
case 1: tile_w = 64; tile_h = 32; tile_d = 32; break;
|
||||
case 2: tile_w = 32; tile_h = 32; tile_d = 32; break;
|
||||
case 4: tile_w = 32; tile_h = 32; tile_d = 16; break;
|
||||
case 8: tile_w = 32; tile_h = 16; tile_d = 16; break;
|
||||
case 16: tile_w = 16; tile_h = 16; tile_d = 16; break;
|
||||
default: tile_w = 32; tile_h = 32; tile_d = 16; break;
|
||||
}
|
||||
tile_w *= block_;
|
||||
tile_h *= block_;
|
||||
} else {
|
||||
switch (bpe) {
|
||||
case 1: tile_w = 256; tile_h = 256; break;
|
||||
case 2: tile_w = 256; tile_h = 128; break;
|
||||
case 4: tile_w = 128; tile_h = 128; break;
|
||||
case 8: tile_w = 128; tile_h = 64; break;
|
||||
case 16: tile_w = 64; tile_h = 64; break;
|
||||
default: break;
|
||||
}
|
||||
tile_w *= block_;
|
||||
tile_h *= block_;
|
||||
}
|
||||
auto depth_of = [&](UINT32 m) { return volume ? layout_.Plane[0].MipLayout[m].DepthOrArraySize : 1u; };
|
||||
const UINT32 mips = layout_.MipLevels;
|
||||
UINT32 standard = 0;
|
||||
while (standard < mips && layout_.Plane[0].MipLayout[standard].WidthPixels >= tile_w &&
|
||||
layout_.Plane[0].MipLayout[standard].HeightPixels >= tile_h && depth_of(standard) >= tile_d) {
|
||||
++standard;
|
||||
}
|
||||
uint64_t tail_bytes = 0;
|
||||
for (UINT32 m = standard; m < mips; ++m) {
|
||||
tail_bytes += volume ? layout_.Plane[0].MipLayout[m].SizeBytes : layout_.Plane[0].MipLayout[m].Slice2DSizeBytes;
|
||||
}
|
||||
const UINT32 tail_tiles = standard < mips ? static_cast<UINT32>((tail_bytes + kResourceAlign - 1) / kResourceAlign) : 0;
|
||||
auto tiles_of = [&](UINT32 m) {
|
||||
const XgMipLevelLayout& l = layout_.Plane[0].MipLayout[m];
|
||||
return ((l.WidthPixels + tile_w - 1) / tile_w) * ((l.HeightPixels + tile_h - 1) / tile_h) *
|
||||
((depth_of(m) + tile_d - 1) / tile_d);
|
||||
};
|
||||
UINT32 per_slice = tail_tiles;
|
||||
for (UINT32 m = 0; m < standard; ++m) per_slice += tiles_of(m);
|
||||
if (total_tiles) *total_tiles = per_slice * slices_;
|
||||
UINT32 standard_tiles = 0;
|
||||
for (UINT32 m = 0; m < standard; ++m) standard_tiles += tiles_of(m);
|
||||
if (packed) {
|
||||
*packed = {static_cast<UINT8>(standard), static_cast<UINT8>(mips - standard), tail_tiles,
|
||||
standard < mips ? standard_tiles : 0};
|
||||
}
|
||||
if (shape) *shape = {tile_w, tile_h, tile_d};
|
||||
if (count) {
|
||||
const UINT32 total = mips * slices_;
|
||||
UINT32 written = 0;
|
||||
for (UINT32 i = first; i < total && written < *count && tilings; ++i, ++written) {
|
||||
const UINT32 m = i % mips, slice = i / mips;
|
||||
if (m >= standard) {
|
||||
tilings[written] = {0, 0, 0, 0xFFFFFFFFu}; // packed: no tiling of its own
|
||||
continue;
|
||||
}
|
||||
UINT32 start = slice * per_slice;
|
||||
for (UINT32 k = 0; k < m; ++k) start += tiles_of(k);
|
||||
const XgMipLevelLayout& l = layout_.Plane[0].MipLayout[m];
|
||||
tilings[written] = {(l.WidthPixels + tile_w - 1) / tile_w,
|
||||
static_cast<UINT16>((l.HeightPixels + tile_h - 1) / tile_h),
|
||||
static_cast<UINT16>((depth_of(m) + tile_d - 1) / tile_d), start};
|
||||
}
|
||||
*count = written;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT GetTextureViewDescriptor(UINT32, void*) override {
|
||||
BX_STUB_LOG("xg_xs.dll", "XGTextureAddressComputer::GetTextureViewDescriptor");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
bool IsTiledResource() override { return false; }
|
||||
HRESULT GetSwizzlePatternInfo(UINT32, void*) override {
|
||||
BX_STUB_LOG("xg_xs.dll", "XGTextureAddressComputer::GetSwizzlePatternInfo");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
private:
|
||||
HRESULT copy(uint8_t* tiled, UINT32 plane, UINT32 subresource, uint8_t* linear_rw, UINT32 row_pitch,
|
||||
UINT32 slice_pitch, bool into) {
|
||||
return copy(tiled, plane, subresource, static_cast<const uint8_t*>(linear_rw), row_pitch, slice_pitch, into,
|
||||
linear_rw);
|
||||
}
|
||||
HRESULT copy(uint8_t* tiled, UINT32 plane, UINT32 subresource, const uint8_t* linear, UINT32 row_pitch,
|
||||
UINT32 slice_pitch, bool into, uint8_t* linear_out = nullptr) {
|
||||
if (!tiled || !linear || plane >= layout_.Planes) return E_INVALIDARG;
|
||||
const UINT32 mip = subresource % layout_.MipLevels;
|
||||
const UINT32 slice = subresource / layout_.MipLevels;
|
||||
const XgPlaneLayout& p = layout_.Plane[plane];
|
||||
const XgMipLevelLayout& m = p.MipLayout[mip];
|
||||
const bool volume = layout_.Dimension == kDimTexture3D;
|
||||
if (slice >= slices_) return E_INVALIDARG; // slices_ is 1 for a volume: its subresources are its mips
|
||||
const UINT32 depth = volume ? m.DepthOrArraySize : 1;
|
||||
if (swizzled_) { // one 2D tile, one mip, one slice: element by element
|
||||
if (subresource != 0) return E_INVALIDARG;
|
||||
for (UINT32 row = 0; row < m.HeightElements; ++row) {
|
||||
for (UINT32 col = 0; col < m.WidthElements; ++col) {
|
||||
uint8_t* t = tiled + m.OffsetBytes + element_offset(col, row);
|
||||
const uint64_t lin = static_cast<uint64_t>(row) * row_pitch + static_cast<uint64_t>(col) * sw_.bytes;
|
||||
if (into) std::memcpy(t, linear + lin, sw_.bytes);
|
||||
else std::memcpy(linear_out + lin, t, sw_.bytes);
|
||||
}
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
const uint64_t row_bytes = static_cast<uint64_t>(m.WidthElements) * m.SampleCount * p.BytesPerElement;
|
||||
for (UINT32 z = 0; z < depth; ++z) {
|
||||
uint8_t* dst_slice = tiled + m.OffsetBytes + (volume ? z : slice) * m.Slice2DSizeBytes;
|
||||
for (UINT32 row = 0; row < m.HeightElements; ++row) {
|
||||
uint8_t* t = dst_slice + static_cast<uint64_t>(row) * m.PitchBytes;
|
||||
const uint64_t lin = static_cast<uint64_t>(z) * slice_pitch + static_cast<uint64_t>(row) * row_pitch;
|
||||
if (into) std::memcpy(t, linear + lin, row_bytes);
|
||||
else std::memcpy(linear_out + lin, t, row_bytes);
|
||||
}
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
uint32_t element_offset(uint32_t ex, uint32_t ey) const { return pdep(ex, sw_.x_mask) | pdep(ey, sw_.y_mask); }
|
||||
|
||||
XgResourceLayout layout_{};
|
||||
uint32_t block_ = 1;
|
||||
uint32_t slices_ = 1;
|
||||
bool swizzled_ = false; // SW_64KB_S, one tile (see Sw64kbS)
|
||||
Sw64kbS sw_{};
|
||||
std::atomic<ULONG> refs_{1};
|
||||
};
|
||||
|
||||
HRESULT LayoutComputer::create(const XgResourceDesc& d, XGTextureAddressComputer** out) {
|
||||
FormatInfo fi{1, 1, 0};
|
||||
const bool buffer = d.Dimension == kDimBuffer;
|
||||
if (!buffer && !format_info(d.Format, &fi)) {
|
||||
log_rejected(&d, "format not in the BetterXen XG table");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (d.Dimension < kDimBuffer || d.Dimension > kDimTexture3D || d.Width == 0) {
|
||||
log_rejected(&d, "invalid description");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// The public D3D12 resource limits (D3D12_REQ_TEXTURE1D/2D_U_DIMENSION 16384,
|
||||
// D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION 2048, D3D12_REQ_TEXTURE1D/2D_ARRAY_AXIS_DIMENSION
|
||||
// 2048). Within them every pitch fits 32 bits and no size computation overflows. A buffer
|
||||
// only needs its 64 KiB-aligned size to fit 64 bits.
|
||||
{
|
||||
const bool volume = d.Dimension == kDimTexture3D;
|
||||
const uint64_t max_xy = volume ? 2048 : 16384;
|
||||
const uint32_t height = d.Dimension == kDimTexture1D ? 1 : d.Height;
|
||||
const bool too_big = buffer ? d.Width > UINT64_MAX - kResourceAlign
|
||||
: d.Width > max_xy || height > max_xy || d.DepthOrArraySize > 2048;
|
||||
if (too_big) {
|
||||
log_rejected(&d, "dimension past the D3D12 resource limits");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
}
|
||||
auto* c = new (std::nothrow) LayoutComputer();
|
||||
if (!c) return E_OUTOFMEMORY;
|
||||
XgResourceLayout& L = c->layout_;
|
||||
L.Dimension = d.Dimension;
|
||||
L.BaseAlignmentBytes = d.Alignment > kResourceAlign ? d.Alignment : kResourceAlign;
|
||||
if (buffer) {
|
||||
L.MipLevels = 1;
|
||||
L.Planes = 1;
|
||||
XgPlaneLayout& p = L.Plane[0];
|
||||
p.Usage = kPlaneDefault;
|
||||
p.BytesPerElement = 1;
|
||||
p.StandardMipCount = 1;
|
||||
p.SizeBytes = p.SliceSizeBytes = d.Width;
|
||||
p.BaseAlignmentBytes = L.BaseAlignmentBytes;
|
||||
XgMipLevelLayout& m = p.MipLayout[0];
|
||||
m.SizeBytes = m.Slice2DSizeBytes = d.Width;
|
||||
m.PitchBytes = static_cast<UINT32>(d.Width > UINT32_MAX ? UINT32_MAX : d.Width);
|
||||
m.WidthElements = m.WidthPixels = m.PitchPixels = m.PaddedWidthElements = m.PitchBytes;
|
||||
m.HeightElements = m.HeightPixels = m.PaddedHeightElements = 1;
|
||||
m.DepthOrArraySize = m.PaddedDepthOrArraySize = m.SampleCount = m.SliceDepthElements = 1;
|
||||
m.AlignmentBytes = static_cast<UINT32>(kRowAlign);
|
||||
L.SizeBytes = align_up(d.Width, kResourceAlign);
|
||||
*out = c;
|
||||
return S_OK;
|
||||
}
|
||||
const uint32_t height = d.Dimension == kDimTexture1D ? 1 : (d.Height ? d.Height : 1);
|
||||
const uint32_t depth_or_array = d.DepthOrArraySize ? d.DepthOrArraySize : 1;
|
||||
uint32_t full = 1;
|
||||
for (uint64_t w = d.Width, h = height, z = d.Dimension == kDimTexture3D ? depth_or_array : 1; w > 1 || h > 1 || z > 1;
|
||||
w >>= 1, h >>= 1, z >>= 1) {
|
||||
++full;
|
||||
}
|
||||
uint32_t mips = d.MipLevels ? d.MipLevels : full;
|
||||
if (mips > full) mips = full;
|
||||
if (mips > kMaxMips) {
|
||||
log_rejected(&d, "more than 15 mip levels");
|
||||
delete c;
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
const uint32_t samples = d.SampleDesc.Count ? d.SampleDesc.Count : 1;
|
||||
c->block_ = fi.block;
|
||||
c->slices_ = d.Dimension == kDimTexture3D ? 1 : depth_or_array;
|
||||
// Default, row-major and undefined-swizzle requests leave the choice to XG: BetterXen picks
|
||||
// linear and reports it. A request for SW_64KB_S on one 2D tile gets that layout. Any other
|
||||
// requested swizzle mode is laid out linearly and reported as LINEAR (titles do not expect
|
||||
// XGCreateTextureComputer to fail for a mode they ask for); each such mode is logged once.
|
||||
const uint32_t width_el = static_cast<uint32_t>((d.Width + fi.block - 1) / fi.block);
|
||||
const uint32_t height_el = (height + fi.block - 1) / fi.block;
|
||||
Sw64kbS sw{};
|
||||
const bool requested = (d.Layout & kLayoutSwizzleFlag) && d.Layout != kLayoutSwizzleLinear;
|
||||
const bool single_tile_s = d.Layout == (kLayoutSwizzleFlag | kSwizzleMode64KbS) && d.Dimension == kDimTexture2D &&
|
||||
mips == 1 && depth_or_array == 1 && samples == 1 && !fi.stencil &&
|
||||
sw64kb_s_params(fi.bytes, &sw) && width_el <= sw.tile_x && height_el <= sw.tile_y;
|
||||
if (requested && !single_tile_s) log_linear_instead(&d);
|
||||
if (single_tile_s) {
|
||||
c->swizzled_ = true;
|
||||
c->sw_ = sw;
|
||||
L.MipLevels = 1;
|
||||
L.Planes = 1;
|
||||
L.BaseAlignmentBytes = d.Alignment > kTileBytes ? d.Alignment : kTileBytes;
|
||||
XgPlaneLayout& p = L.Plane[0];
|
||||
p.Usage = kPlaneDefault;
|
||||
p.BytesPerElement = fi.bytes;
|
||||
p.StandardMipCount = 1;
|
||||
p.BaseAlignmentBytes = L.BaseAlignmentBytes;
|
||||
p.SizeBytes = p.SliceSizeBytes = kTileBytes;
|
||||
XgMipLevelLayout& m = p.MipLayout[0];
|
||||
m.WidthPixels = static_cast<UINT32>(d.Width);
|
||||
m.HeightPixels = height;
|
||||
m.WidthElements = width_el;
|
||||
m.HeightElements = height_el;
|
||||
m.DepthOrArraySize = m.PaddedDepthOrArraySize = m.SampleCount = m.SliceDepthElements = 1;
|
||||
m.PitchBytes = sw.tile_x * sw.bytes;
|
||||
m.PitchPixels = sw.tile_x * fi.block;
|
||||
m.PaddedWidthElements = sw.tile_x;
|
||||
m.PaddedHeightElements = sw.tile_y;
|
||||
m.AlignmentBytes = static_cast<UINT32>(kTileBytes);
|
||||
m.SwizzleMode = kSwizzleMode64KbS;
|
||||
m.SizeBytes = m.Slice2DSizeBytes = kTileBytes;
|
||||
L.SizeBytes = kTileBytes;
|
||||
*out = c;
|
||||
return S_OK;
|
||||
}
|
||||
L.MipLevels = mips;
|
||||
L.Planes = fi.stencil ? 2 : 1;
|
||||
uint64_t cursor = 0;
|
||||
for (uint32_t pi = 0; pi < L.Planes; ++pi) {
|
||||
XgPlaneLayout& p = L.Plane[pi];
|
||||
p.Usage = fi.stencil ? (pi == 0 ? kPlaneDepth : kPlaneStencil) : kPlaneDefault;
|
||||
p.BytesPerElement = fi.stencil && pi == 1 ? 1 : fi.bytes;
|
||||
p.StandardMipCount = mips;
|
||||
p.MipTailMipCount = 0;
|
||||
p.BaseAlignmentBytes = L.BaseAlignmentBytes;
|
||||
cursor = align_up(cursor, kResourceAlign);
|
||||
p.BaseOffsetBytes = cursor;
|
||||
for (uint32_t mi = 0; mi < mips; ++mi) {
|
||||
XgMipLevelLayout& m = p.MipLayout[mi];
|
||||
m.WidthPixels = mip_extent(d.Width, mi);
|
||||
m.HeightPixels = mip_extent(height, mi);
|
||||
m.DepthOrArraySize = d.Dimension == kDimTexture3D ? mip_extent(depth_or_array, mi) : depth_or_array;
|
||||
m.WidthElements = (m.WidthPixels + fi.block - 1) / fi.block;
|
||||
m.HeightElements = (m.HeightPixels + fi.block - 1) / fi.block;
|
||||
m.SampleCount = samples;
|
||||
m.PitchBytes = static_cast<UINT32>(align_up(static_cast<uint64_t>(m.WidthElements) * samples * p.BytesPerElement, kRowAlign));
|
||||
m.PitchPixels = m.PitchBytes / (p.BytesPerElement * samples) * fi.block;
|
||||
m.PaddedWidthElements = m.PitchBytes / (p.BytesPerElement * samples);
|
||||
m.PaddedHeightElements = m.HeightElements;
|
||||
m.PaddedDepthOrArraySize = m.DepthOrArraySize;
|
||||
m.SliceDepthElements = 1;
|
||||
m.AlignmentBytes = static_cast<UINT32>(kMipAlign);
|
||||
m.SwizzleMode = kSwizzleModeLinear;
|
||||
m.Slice2DSizeBytes = static_cast<uint64_t>(m.PitchBytes) * m.HeightElements;
|
||||
m.SizeBytes = m.Slice2DSizeBytes * m.DepthOrArraySize;
|
||||
cursor = align_up(cursor, kMipAlign);
|
||||
m.OffsetBytes = cursor;
|
||||
cursor += m.SizeBytes;
|
||||
}
|
||||
p.SizeBytes = cursor - p.BaseOffsetBytes;
|
||||
p.SliceSizeBytes = p.MipLayout[0].Slice2DSizeBytes;
|
||||
}
|
||||
L.SizeBytes = align_up(cursor, kResourceAlign);
|
||||
*out = c;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
__declspec(dllexport) HRESULT WINAPI XGCreateTextureComputer(const XgResourceDesc* desc, XGTextureAddressComputer** out) {
|
||||
if (!desc || !out) return E_INVALIDARG;
|
||||
*out = nullptr;
|
||||
const HRESULT hr = LayoutComputer::create(*desc, out);
|
||||
if (SUCCEEDED(hr)) {
|
||||
static std::atomic<uint64_t> created{0};
|
||||
const uint64_t n = ++created;
|
||||
if ((n & (n - 1)) == 0) {
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"BetterXen linear layout (not console tiling): dim=%u %llux%u x%u mips=%u format=%u layout=0x%x size=%llu; total created=%llu",
|
||||
desc->Dimension, static_cast<unsigned long long>(desc->Width), desc->Height,
|
||||
desc->DepthOrArraySize, desc->MipLevels, desc->Format, desc->Layout,
|
||||
static_cast<unsigned long long>((*out)->GetResourceSizeBytes()), static_cast<unsigned long long>(n));
|
||||
bx_log_emit(BX_LOG_INFO, "xg_xs", "texture_computer", detail);
|
||||
}
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
__declspec(dllexport) HRESULT WINAPI XGSuggestSwizzleMode(const XgResourceDesc* desc, uint32_t, uint32_t* layout) {
|
||||
if (!desc || !layout) return E_INVALIDARG;
|
||||
*layout = kLayoutSwizzleLinear; // this layer lays every texture out linearly
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
File diff suppressed because it is too large.
Load diff
@@ -37,6 +37,9 @@ HRESULT WINAPI XTaskQueueSubmitCallback(void*, bx::gdk::Port, void*, void (CALLB
|
||||
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void*, bx::gdk::Port, uint32_t, void*,
|
||||
void (CALLBACK*)(void*, bool));
|
||||
bool WINAPI XTaskQueueGetCurrentProcessTaskQueue(void**);
|
||||
HRESULT WINAPI bx_xtq_duplicate_handle(void*, void**);
|
||||
HRESULT WINAPI bx_xtq_get_port(void*, bx::gdk::Port, void**);
|
||||
HRESULT WINAPI bx_xtq_create_composite(void*, void*, void**);
|
||||
|
||||
HRESULT WINAPI XAsyncGetStatus(void*, bool);
|
||||
HRESULT WINAPI XAsyncGetResultSize(void*, size_t*);
|
||||
@@ -45,6 +48,8 @@ void WINAPI XAsyncCancel(void*);
|
||||
HRESULT WINAPI XUserAddAsync(uint32_t, void*);
|
||||
HRESULT WINAPI XUserAddResult(void*, void**);
|
||||
void WINAPI XUserCloseHandle(void*);
|
||||
HRESULT WINAPI bx_xuser_duplicate_handle(void*, void**);
|
||||
bool WINAPI bx_xuser_is_handle(void*);
|
||||
HRESULT WINAPI XUserGetId(void*, uint64_t*);
|
||||
HRESULT WINAPI XUserGetGamertag(void*, uint32_t, size_t, char*, size_t*);
|
||||
HRESULT WINAPI XUserGetTokenAndSignatureAsync(void*, uint32_t, const char*, const char*, size_t, const void*, size_t,
|
||||
@@ -176,6 +181,32 @@ HRESULT WINAPI core_async_get_result_size(void*, void* async, size_t* size) {
|
||||
void WINAPI core_async_cancel(void*, void* async) {
|
||||
XAsyncCancel(async);
|
||||
}
|
||||
// XAsyncRun: the title's work callback runs on the block's work port and its return value
|
||||
// completes the block (no result payload).
|
||||
struct AsyncRunOp final : bx::gdk::AsyncOp {
|
||||
using Work = HRESULT (CALLBACK*)(void*);
|
||||
Work work;
|
||||
void* block;
|
||||
AsyncRunOp(Work work, void* block) : work(work), block(block) {}
|
||||
uint32_t kind() const override { return 0x4E5552u; } // "RUN"
|
||||
HRESULT execute() override { return work(block); }
|
||||
size_t result_size() const override { return 0; }
|
||||
};
|
||||
HRESULT WINAPI core_async_run(void*, void* async, AsyncRunOp::Work work) {
|
||||
if (!async || !work) return E_INVALIDARG;
|
||||
auto op = std::unique_ptr<bx::gdk::AsyncOp>(new (std::nothrow) AsyncRunOp(work, async));
|
||||
if (!op) return E_OUTOFMEMORY;
|
||||
return bx::gdk::begin_async_op(async, std::move(op));
|
||||
}
|
||||
HRESULT WINAPI core_tq_create_composite(void*, void* work_port, void* completion_port, void** out) {
|
||||
return bx_xtq_create_composite(work_port, completion_port, out);
|
||||
}
|
||||
HRESULT WINAPI core_tq_get_port(void*, void* queue, Port port, void** out) {
|
||||
return bx_xtq_get_port(queue, port, out);
|
||||
}
|
||||
HRESULT WINAPI core_tq_duplicate(void*, void* queue, void** out) {
|
||||
return bx_xtq_duplicate_handle(queue, out);
|
||||
}
|
||||
HRESULT WINAPI core_tq_create(void*, DispatchMode work, DispatchMode comp, void** out) {
|
||||
return XTaskQueueCreate(work, comp, out);
|
||||
}
|
||||
@@ -220,7 +251,11 @@ const std::array<const void*, 36> kCoreVtbl = [] {
|
||||
v[3] = reinterpret_cast<const void*>(&core_async_get_status);
|
||||
v[4] = reinterpret_cast<const void*>(&core_async_get_result_size);
|
||||
v[5] = reinterpret_cast<const void*>(&core_async_cancel);
|
||||
v[6] = reinterpret_cast<const void*>(&core_async_run);
|
||||
v[12] = reinterpret_cast<const void*>(&core_tq_create);
|
||||
v[13] = reinterpret_cast<const void*>(&core_tq_create_composite);
|
||||
v[14] = reinterpret_cast<const void*>(&core_tq_get_port);
|
||||
v[15] = reinterpret_cast<const void*>(&core_tq_duplicate);
|
||||
v[16] = reinterpret_cast<const void*>(&core_tq_dispatch);
|
||||
v[17] = reinterpret_cast<const void*>(&core_tq_close);
|
||||
v[18] = reinterpret_cast<const void*>(&core_tq_submit);
|
||||
@@ -433,8 +468,16 @@ std::unordered_set<uint64_t> user_event_tokens;
|
||||
void WINAPI user_close_handle(void*, void* h) {
|
||||
XUserCloseHandle(h);
|
||||
}
|
||||
HRESULT WINAPI user_duplicate_handle(void*, void* user, void** out) {
|
||||
const HRESULT hr = bx_xuser_duplicate_handle(user, out);
|
||||
bx_log_emit(SUCCEEDED(hr) ? BX_LOG_INFO : BX_LOG_WARN, "xgameruntime", "XUserDuplicateHandle",
|
||||
SUCCEEDED(hr) ? "duplicate handle for the offline user" : "invalid user handle");
|
||||
return hr;
|
||||
}
|
||||
int32_t WINAPI user_compare(void*, void* u1, void* u2) {
|
||||
if (u1 == u2) return 0;
|
||||
// One offline user: every valid handle (duplicates included) names the same user.
|
||||
if (bx_xuser_is_handle(u1) && bx_xuser_is_handle(u2)) return 0;
|
||||
return reinterpret_cast<uintptr_t>(u1) < reinterpret_cast<uintptr_t>(u2) ? -1 : 1;
|
||||
}
|
||||
HRESULT WINAPI user_get_max_users(void*, uint32_t* max_users) {
|
||||
@@ -517,6 +560,7 @@ HRESULT WINAPI user_get_gamertag(void*, void* user, uint32_t comp, size_t sz, ch
|
||||
|
||||
const std::array<const void*, 64> kUserVtbl = [] {
|
||||
auto v = make_default_vtbl<64>();
|
||||
v[3] = reinterpret_cast<const void*>(&user_duplicate_handle);
|
||||
v[4] = reinterpret_cast<const void*>(&user_close_handle);
|
||||
v[5] = reinterpret_cast<const void*>(&user_compare);
|
||||
v[6] = reinterpret_cast<const void*>(&user_get_max_users);
|
||||
@@ -742,8 +786,6 @@ BX_HR(gs_quota_result, "IXGameSaveImpl", 9, "XGameSaveGetRemainingQuotaResult")
|
||||
BX_HR(gs_delete, "IXGameSaveImpl", 10, "XGameSaveDeleteContainer")
|
||||
BX_HR(gs_delete_async, "IXGameSaveImpl", 11, "XGameSaveDeleteContainerAsync")
|
||||
BX_HR(gs_delete_result, "IXGameSaveImpl", 12, "XGameSaveDeleteContainerResult")
|
||||
BX_HR(gs_container_info, "IXGameSaveImpl", 13, "XGameSaveGetContainerInfo")
|
||||
BX_HR(gs_enum_by_name, "IXGameSaveImpl", 15, "XGameSaveEnumerateContainerInfoByName")
|
||||
BX_HR(gs_enum_blobs, "IXGameSaveImpl", 18, "XGameSaveEnumerateBlobInfo")
|
||||
BX_HR(gs_enum_blobs_by_name, "IXGameSaveImpl", 19, "XGameSaveEnumerateBlobInfoByName")
|
||||
BX_HR(gs_blob_delete, "IXGameSaveImpl", 26, "XGameSaveSubmitBlobDelete")
|
||||
@@ -751,12 +793,6 @@ BX_HR(gs_files_folder_async, "IXGameSaveImpl2", 30, "XGameSaveFilesGetFolderWith
|
||||
BX_HR(gs_files_folder_result, "IXGameSaveImpl2", 31, "XGameSaveFilesGetFolderWithUiResult")
|
||||
BX_HR(gs_files_quota, "IXGameSaveImpl2", 32, "XGameSaveFilesGetRemainingQuota")
|
||||
|
||||
BX_HR(pk_create_monitor, "IXPackageImpl", 5, "XPackageCreateInstallationMonitor")
|
||||
BX_VOID(pk_close_monitor, "IXPackageImpl", 6, "XPackageCloseInstallationMonitorHandle")
|
||||
BX_VOID(pk_get_progress, "IXPackageImpl", 7, "XPackageGetInstallationProgress")
|
||||
BX_BOOL(pk_update_monitor, "IXPackageImpl", 8, "XPackageUpdateInstallationMonitor")
|
||||
BX_HR(pk_reg_progress, "IXPackageImpl", 9, "XPackageRegisterInstallationProgressChanged")
|
||||
BX_BOOL(pk_unreg_progress, "IXPackageImpl", 10, "XPackageUnregisterInstallationProgressChanged")
|
||||
BX_HR(pk_locale, "IXPackageImpl", 11, "XPackageGetUserLocale")
|
||||
BX_HR(pk_find_chunk, "IXPackageImpl", 12, "XPackageFindChunkAvailability")
|
||||
BX_HR(pk_enum_chunk, "IXPackageImpl", 13, "XPackageEnumerateChunkAvailability")
|
||||
@@ -770,16 +806,13 @@ BX_HR(pk_unknown_20, "IXPackageImpl", 20, "unknown")
|
||||
BX_HR(pk_unknown_21, "IXPackageImpl", 21, "unknown")
|
||||
BX_BOOL(pk_unreg_installed, "IXPackageImpl", 22, "XPackageUnregisterPackageInstalled")
|
||||
BX_HR(pk_unknown_27, "IXPackageImpl", 27, "unknown")
|
||||
BX_HR(pk_enum_packages, "IXPackageImpl", 28, "XPackageEnumeratePackages")
|
||||
BX_HR(pk_reg_installed, "IXPackageImpl", 29, "XPackageRegisterPackageInstalled")
|
||||
BX_HR(pk_write_stats, "IXPackageImpl", 30, "XPackageGetWriteStats")
|
||||
BX_HR(pk_unknown_31, "IXPackageImpl", 31, "unknown")
|
||||
BX_HR(pk_uninstall_uwp, "IXPackageImpl", 32, "XPackageUninstallUWPInstance")
|
||||
BX_HR(pk_enum_features, "IXPackageImpl", 33, "XPackageEnumerateFeatures")
|
||||
BX_HR(pk_uninstall, "IXPackageImpl", 34, "XPackageUninstallPackage")
|
||||
BX_HR(pk_enum_packages_2, "IXPackageImpl2", 35, "XPackageEnumeratePackages")
|
||||
BX_HR(pk_reg_installed_2, "IXPackageImpl2", 36, "XPackageRegisterPackageInstalled")
|
||||
BX_HR(pk_enum_packages_3, "IXPackageImpl3", 39, "XPackageEnumeratePackages")
|
||||
BX_HR(pk_reg_installed_3, "IXPackageImpl3", 40, "XPackageRegisterPackageInstalled")
|
||||
#undef BX_HR
|
||||
#undef BX_VOID
|
||||
@@ -798,9 +831,9 @@ const std::array<const void*, 33> kGameSaveVtbl = [] {
|
||||
v[10] = reinterpret_cast<const void*>(&gs_delete);
|
||||
v[11] = reinterpret_cast<const void*>(&gs_delete_async);
|
||||
v[12] = reinterpret_cast<const void*>(&gs_delete_result);
|
||||
v[13] = reinterpret_cast<const void*>(&gs_container_info);
|
||||
v[13] = reinterpret_cast<const void*>(&get_container_info);
|
||||
v[14] = reinterpret_cast<const void*>(&enumerate_container_info);
|
||||
v[15] = reinterpret_cast<const void*>(&gs_enum_by_name);
|
||||
v[15] = reinterpret_cast<const void*>(&enumerate_container_info_by_name);
|
||||
v[16] = reinterpret_cast<const void*>(&create_container);
|
||||
v[17] = reinterpret_cast<const void*>(&close_container);
|
||||
v[18] = reinterpret_cast<const void*>(&gs_enum_blobs);
|
||||
@@ -827,12 +860,12 @@ const std::array<const void*, 42> kPackageVtbl = [] {
|
||||
v[0] = reinterpret_cast<const void*>(&package_query_interface);
|
||||
v[3] = reinterpret_cast<const void*>(&get_current_process_package_identifier);
|
||||
v[4] = reinterpret_cast<const void*>(&is_packaged_process);
|
||||
v[5] = reinterpret_cast<const void*>(&pk_create_monitor);
|
||||
v[6] = reinterpret_cast<const void*>(&pk_close_monitor);
|
||||
v[7] = reinterpret_cast<const void*>(&pk_get_progress);
|
||||
v[8] = reinterpret_cast<const void*>(&pk_update_monitor);
|
||||
v[9] = reinterpret_cast<const void*>(&pk_reg_progress);
|
||||
v[10] = reinterpret_cast<const void*>(&pk_unreg_progress);
|
||||
v[5] = reinterpret_cast<const void*>(&create_installation_monitor);
|
||||
v[6] = reinterpret_cast<const void*>(&close_installation_monitor);
|
||||
v[7] = reinterpret_cast<const void*>(&get_installation_progress);
|
||||
v[8] = reinterpret_cast<const void*>(&update_installation_monitor);
|
||||
v[9] = reinterpret_cast<const void*>(®ister_installation_progress);
|
||||
v[10] = reinterpret_cast<const void*>(&unregister_installation_progress);
|
||||
v[11] = reinterpret_cast<const void*>(&pk_locale);
|
||||
v[12] = reinterpret_cast<const void*>(&pk_find_chunk);
|
||||
v[13] = reinterpret_cast<const void*>(&pk_enum_chunk);
|
||||
@@ -850,18 +883,18 @@ const std::array<const void*, 42> kPackageVtbl = [] {
|
||||
v[25] = reinterpret_cast<const void*>(&get_mount_path);
|
||||
v[26] = reinterpret_cast<const void*>(&close_mount_handle);
|
||||
v[27] = reinterpret_cast<const void*>(&pk_unknown_27);
|
||||
v[28] = reinterpret_cast<const void*>(&pk_enum_packages);
|
||||
v[28] = reinterpret_cast<const void*>(&enumerate_packages);
|
||||
v[29] = reinterpret_cast<const void*>(&pk_reg_installed);
|
||||
v[30] = reinterpret_cast<const void*>(&pk_write_stats);
|
||||
v[31] = reinterpret_cast<const void*>(&pk_unknown_31);
|
||||
v[32] = reinterpret_cast<const void*>(&pk_uninstall_uwp);
|
||||
v[33] = reinterpret_cast<const void*>(&pk_enum_features);
|
||||
v[34] = reinterpret_cast<const void*>(&pk_uninstall);
|
||||
v[35] = reinterpret_cast<const void*>(&pk_enum_packages_2);
|
||||
v[35] = reinterpret_cast<const void*>(&enumerate_packages);
|
||||
v[36] = reinterpret_cast<const void*>(&pk_reg_installed_2);
|
||||
v[37] = reinterpret_cast<const void*>(&mount_with_ui_async);
|
||||
v[38] = reinterpret_cast<const void*>(&mount_with_ui_result);
|
||||
v[39] = reinterpret_cast<const void*>(&pk_enum_packages_3);
|
||||
v[39] = reinterpret_cast<const void*>(&enumerate_packages);
|
||||
v[40] = reinterpret_cast<const void*>(&pk_reg_installed_3);
|
||||
v[41] = reinterpret_cast<const void*>(&get_package_kind);
|
||||
return v;
|
||||
|
||||
@@ -841,7 +841,55 @@ HRESULT WINAPI read_blob_data_result(void*, void* async, size_t size, void* blob
|
||||
});
|
||||
}
|
||||
|
||||
HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, GameSaveContainerInfoCallback callback) {
|
||||
HRESULT WINAPI get_container_info(void*, void* provider, const char* container_name, void* context,
|
||||
GameSaveContainerInfoCallback callback) {
|
||||
if (!callback) return E_INVALIDARG;
|
||||
const auto typed = reinterpret_cast<ContainerInfoCallback>(callback);
|
||||
const auto generation = active_runtime_generation();
|
||||
ContainerData data;
|
||||
bool exists = false;
|
||||
try {
|
||||
std::wstring dir;
|
||||
{
|
||||
std::lock_guard lock(handle_mutex);
|
||||
const auto* open = find_provider(provider, generation);
|
||||
if (!open) return stale_handle_error(generation);
|
||||
if (!valid_container_name(container_name)) return kInvalidContainerName;
|
||||
dir = open->dir;
|
||||
}
|
||||
const std::string name(container_name);
|
||||
DirectoryLock lock(dir);
|
||||
if (FAILED(lock.status())) return lock.status();
|
||||
const auto path = container_file(dir, name);
|
||||
std::vector<uint8_t> bytes;
|
||||
const auto hr = read_file(path, bytes, exists);
|
||||
if (FAILED(hr)) return hr;
|
||||
if (exists) {
|
||||
if (!parse(bytes, data, false)) {
|
||||
log_bad_file("corrupt_container", path);
|
||||
return kFileCorrupt;
|
||||
}
|
||||
if (data.name != name) {
|
||||
log_bad_file("container_id_collision", path);
|
||||
return HRESULT_FROM_WIN32(ERROR_FILE_EXISTS);
|
||||
}
|
||||
}
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
// Inference (source rank 3, #667): when the named container does not exist, succeed without
|
||||
// invoking the callback.
|
||||
if (!exists) return S_OK;
|
||||
// No lock is held here, so the callback may call back into XGameSave.
|
||||
const ContainerInfo info{data.name.c_str(), data.display_name.c_str(),
|
||||
static_cast<uint32_t>(data.blobs.size()), data.total_size,
|
||||
static_cast<time_t>(data.last_modified), false};
|
||||
(void)typed(&info, context);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI enumerate_container_info_by_name(void*, void* provider, const char* prefix, void* context,
|
||||
GameSaveContainerInfoCallback callback) {
|
||||
if (!callback) return E_INVALIDARG;
|
||||
const auto typed = reinterpret_cast<ContainerInfoCallback>(callback);
|
||||
const auto generation = active_runtime_generation();
|
||||
@@ -854,10 +902,14 @@ HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, Ga
|
||||
if (!open) return stale_handle_error(generation);
|
||||
dir = open->dir;
|
||||
}
|
||||
const std::string filter = prefix ? std::string(prefix) : std::string();
|
||||
DirectoryLock lock(dir);
|
||||
if (FAILED(lock.status())) return lock.status();
|
||||
const auto hr = list_containers(dir, list);
|
||||
if (FAILED(hr)) return hr;
|
||||
if (!filter.empty()) {
|
||||
std::erase_if(list, [&](const ContainerData& item) { return !item.name.starts_with(filter); });
|
||||
}
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
@@ -872,6 +924,10 @@ HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, Ga
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, GameSaveContainerInfoCallback callback) {
|
||||
return enumerate_container_info_by_name(nullptr, provider, nullptr, context, callback);
|
||||
}
|
||||
|
||||
// Synchronous public slots. Each one runs the async operation above on the process task
|
||||
// queue (a null XAsyncBlock queue) and waits. syncOnDemand is passed through and has no
|
||||
// effect, the same as InitializeProviderAsync. Signatures follow the public Microsoft Learn
|
||||
|
||||
@@ -22,9 +22,18 @@
|
||||
* mounted; BetterXen allows the game's own package so titles can locate their files. Offline
|
||||
* there is no license or parental-consent prompt, so the asynchronous form shows no UI; an
|
||||
* identifier mismatch is reported as the operation's status (ERROR_NOT_FOUND).
|
||||
* - The last XGameRuntimeUninitialize closes every mount handle.
|
||||
* - The last XGameRuntimeUninitialize closes every mount handle and installation monitor.
|
||||
* - Installation monitors (XPackageCreateInstallationMonitor and the functions taking its
|
||||
* handle) accept only that identifier. The package is fully on local storage, so progress is
|
||||
* {1, 1, 1, launchable, completed} and never changes: a registered progress callback is
|
||||
* accepted, logged and never called. Handles share the mount table's lock and generation, so
|
||||
* a closed or stale handle is rejected and closing twice is harmless.
|
||||
* - XPackageEnumeratePackages reports this game for XPackageKind::Game in every scope (the
|
||||
* documented ThisOnly output is the calling game; offline there are no related or publisher
|
||||
* games), and no packages for Content or PublisherContent: none are installed offline.
|
||||
* - An executable path of MAX_PATH or more fails with ERROR_FILENAME_EXCED_RANGE.
|
||||
*/
|
||||
#include "bx_log.h"
|
||||
#include "runtime_internal.h"
|
||||
#include "synthetic_keys.h"
|
||||
|
||||
@@ -37,6 +46,7 @@
|
||||
#include <new>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace bx::gdk {
|
||||
namespace {
|
||||
@@ -250,6 +260,148 @@ void WINAPI close_mount_handle(void*, void* handle) {
|
||||
|
||||
namespace {
|
||||
|
||||
struct Monitor {
|
||||
uint32_t generation;
|
||||
std::vector<uint64_t> tokens;
|
||||
};
|
||||
// Guarded by mount_mutex, like the mount handles. Tag 5 in bits 40-43 keeps these handles apart
|
||||
// from mount handles (tag 4) and XGameSave handles.
|
||||
std::unordered_map<void*, Monitor> monitors;
|
||||
constexpr uintptr_t kMonitorTag = 5;
|
||||
uint64_t token_counter = 0;
|
||||
|
||||
// Caller holds mount_mutex.
|
||||
Monitor* find_monitor(void* handle, uint32_t generation) {
|
||||
const auto found = monitors.find(handle);
|
||||
if (found == monitors.end() || generation == 0 || found->second.generation != generation) return nullptr;
|
||||
return &found->second;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
HRESULT WINAPI create_installation_monitor(void*, const char* identifier, uint32_t, const void*, uint32_t, void*,
|
||||
void** monitor) {
|
||||
if (!monitor) return E_POINTER;
|
||||
*monitor = nullptr;
|
||||
if (!identifier) return E_INVALIDARG;
|
||||
const auto generation = active_runtime_generation();
|
||||
if (!generation) return kRuntimeNotInitialized;
|
||||
bool match = false;
|
||||
const auto hr = is_current_package(identifier, match);
|
||||
if (FAILED(hr)) return hr;
|
||||
if (!match) return kNotFound;
|
||||
try {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
++handle_counter;
|
||||
void* handle = reinterpret_cast<void*>(kMonitorTag << 40 | (handle_counter & 0xFFFFFFFFFu) << 4);
|
||||
monitors.emplace(handle, Monitor{generation, {}});
|
||||
*monitor = handle;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageCreateInstallationMonitor",
|
||||
"monitor for the running package: fully installed, progress never changes (offline)");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
void WINAPI close_installation_monitor(void*, void* monitor) {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
monitors.erase(monitor); // an unknown or already closed handle is ignored
|
||||
}
|
||||
|
||||
void WINAPI get_installation_progress(void*, void* monitor, XPackageInstallationProgress* progress) {
|
||||
if (!progress) return;
|
||||
const auto generation = active_runtime_generation();
|
||||
std::lock_guard lock(mount_mutex);
|
||||
*progress = find_monitor(monitor, generation) ? XPackageInstallationProgress{1, 1, 1, true, true}
|
||||
: XPackageInstallationProgress{};
|
||||
}
|
||||
|
||||
bool WINAPI update_installation_monitor(void*, void*) {
|
||||
return false; // progress never changes offline
|
||||
}
|
||||
|
||||
HRESULT WINAPI register_installation_progress(void*, void* monitor, void*, void* callback, uint64_t* token) {
|
||||
if (!token) return E_POINTER;
|
||||
*token = 0;
|
||||
if (!callback) return E_INVALIDARG;
|
||||
const auto generation = active_runtime_generation();
|
||||
try {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
Monitor* open = find_monitor(monitor, generation);
|
||||
if (!open) return stale_handle_error(generation);
|
||||
*token = ++token_counter;
|
||||
open->tokens.push_back(*token);
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "token=%llu accepted; offline progress never changes, so the callback is never called",
|
||||
static_cast<unsigned long long>(*token));
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageRegisterInstallationProgressChanged", detail);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
bool WINAPI unregister_installation_progress(void*, void* monitor, uint64_t token, bool) {
|
||||
const auto generation = active_runtime_generation();
|
||||
std::lock_guard lock(mount_mutex);
|
||||
Monitor* open = find_monitor(monitor, generation);
|
||||
if (!open) return false;
|
||||
for (auto it = open->tokens.begin(); it != open->tokens.end(); ++it) {
|
||||
if (*it == token) {
|
||||
open->tokens.erase(it);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
struct XVersionValue {
|
||||
uint16_t major, minor, build, revision;
|
||||
};
|
||||
struct XPackageDetails {
|
||||
const char* packageIdentifier;
|
||||
XVersionValue version;
|
||||
uint32_t kind;
|
||||
const char* displayName;
|
||||
const char* description;
|
||||
const char* publisher;
|
||||
const char* storeId;
|
||||
bool installing;
|
||||
uint32_t index;
|
||||
uint32_t count;
|
||||
bool ageRestricted;
|
||||
const char* titleId;
|
||||
};
|
||||
using EnumerationCallback = bool(CALLBACK*)(void* context, const XPackageDetails* details);
|
||||
constexpr uint32_t kKindGame = 0, kScopeThisPublisher = 2;
|
||||
|
||||
} // namespace
|
||||
|
||||
HRESULT WINAPI enumerate_packages(void*, uint32_t kind, uint32_t scope, void* context, void* callback) {
|
||||
if (!callback) return E_INVALIDARG;
|
||||
if (!active_runtime_generation()) return kRuntimeNotInitialized;
|
||||
if (kind > 2 || scope > kScopeThisPublisher) return E_INVALIDARG;
|
||||
char detail[128];
|
||||
if (kind != kKindGame) {
|
||||
std::snprintf(detail, sizeof(detail), "kind=%u scope=%u: no content packages installed (offline)", kind, scope);
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageEnumeratePackages", detail);
|
||||
return S_OK;
|
||||
}
|
||||
char id[kIdBytes];
|
||||
const auto hr = current_identifier(id);
|
||||
if (FAILED(hr)) return hr;
|
||||
const XPackageDetails details{id, {}, kKindGame, "", "", "", "", false, 0, 1, false, ""};
|
||||
std::snprintf(detail, sizeof(detail), "kind=%u scope=%u: reported the running game only (offline)", kind, scope);
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageEnumeratePackages", detail);
|
||||
reinterpret_cast<EnumerationCallback>(callback)(context, &details);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// --- COM object ---
|
||||
|
||||
HRESULT WINAPI query_interface(void* self, const GUID* iid, void** out) {
|
||||
@@ -301,6 +453,7 @@ const void* const package_object = &kObject;
|
||||
void release_package_state() {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
mounts.clear();
|
||||
monitors.clear();
|
||||
}
|
||||
|
||||
} // namespace bx::gdk
|
||||
@@ -83,8 +83,12 @@ HRESULT WINAPI initialize_provider_result(void* self, void* async, void** provid
|
||||
void WINAPI close_provider(void* self, void* provider);
|
||||
HRESULT WINAPI create_container(void* self, void* provider, const char* name, void** out);
|
||||
void WINAPI close_container(void* self, void* container);
|
||||
HRESULT WINAPI get_container_info(void* self, void* provider, const char* container_name, void* context,
|
||||
GameSaveContainerInfoCallback callback);
|
||||
HRESULT WINAPI enumerate_container_info(void* self, void* provider, void* context,
|
||||
GameSaveContainerInfoCallback callback);
|
||||
HRESULT WINAPI enumerate_container_info_by_name(void* self, void* provider, const char* prefix, void* context,
|
||||
GameSaveContainerInfoCallback callback);
|
||||
HRESULT WINAPI read_blob_data(void* self, void* container, const char** names, uint32_t* count, size_t size,
|
||||
void* blobs);
|
||||
HRESULT WINAPI read_blob_data_async(void* self, void* container, const char** names, uint32_t count, void* async);
|
||||
@@ -106,4 +110,23 @@ HRESULT WINAPI get_mount_path_size(void* self, void* handle, size_t* size);
|
||||
HRESULT WINAPI get_mount_path(void* self, void* handle, size_t size, char* path);
|
||||
void WINAPI close_mount_handle(void* self, void* handle);
|
||||
|
||||
// Installation monitors and enumeration (package.cpp), served on IXPackageImpl slots 5-10 and
|
||||
// the XPackageEnumeratePackages slots. Layouts follow the documented XPackage structures.
|
||||
struct XPackageInstallationProgress {
|
||||
uint64_t totalBytes;
|
||||
uint64_t installedBytes;
|
||||
uint64_t launchBytes;
|
||||
bool launchable;
|
||||
bool completed;
|
||||
};
|
||||
HRESULT WINAPI create_installation_monitor(void* self, const char* identifier, uint32_t selector_count,
|
||||
const void* selectors, uint32_t interval_ms, void* queue, void** monitor);
|
||||
void WINAPI close_installation_monitor(void* self, void* monitor);
|
||||
void WINAPI get_installation_progress(void* self, void* monitor, XPackageInstallationProgress* progress);
|
||||
bool WINAPI update_installation_monitor(void* self, void* monitor);
|
||||
HRESULT WINAPI register_installation_progress(void* self, void* monitor, void* context, void* callback,
|
||||
uint64_t* token);
|
||||
bool WINAPI unregister_installation_progress(void* self, void* monitor, uint64_t token, bool wait);
|
||||
HRESULT WINAPI enumerate_packages(void* self, uint32_t kind, uint32_t scope, void* context, void* callback);
|
||||
|
||||
} // namespace bx::gdk
|
||||
@@ -185,13 +185,31 @@ public:
|
||||
Queue(DispatchMode work, DispatchMode completion) : lanes{{this, work}, {this, completion}} {}
|
||||
|
||||
Lane lanes[2];
|
||||
// A composite queue (XTaskQueueCreateComposite) has no lanes of its own in use: each port
|
||||
// forwards to a port of another queue.
|
||||
QueueRef forward[2];
|
||||
Port forward_port[2] = {Port::work, Port::completion};
|
||||
};
|
||||
|
||||
// Follows composite forwarding to the queue and port that hold the lane.
|
||||
static void resolve_lane(QueueRef& queue, Port& port) {
|
||||
for (int depth = 0; depth < 8 && queue; ++depth) {
|
||||
const auto index = static_cast<uint32_t>(port);
|
||||
if (!queue->forward[index]) return;
|
||||
const Port next_port = queue->forward_port[index];
|
||||
queue = queue->forward[index];
|
||||
port = next_port;
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
std::mutex queues_mutex;
|
||||
std::unordered_map<uintptr_t, QueueRef> handles;
|
||||
uintptr_t next_handle = 1;
|
||||
// XTaskQueuePortHandle values (even numbers, so they never collide with queue handles).
|
||||
std::unordered_map<uintptr_t, std::pair<QueueRef, Port>> port_handles;
|
||||
uintptr_t next_port_handle = 2;
|
||||
QueueRef process_queue;
|
||||
|
||||
HRESULT make_queue(DispatchMode work, DispatchMode completion, QueueRef& queue) {
|
||||
@@ -238,7 +256,9 @@ QueueRef acquire_queue(void* handle) {
|
||||
}
|
||||
|
||||
bool submit(const QueueRef& queue, Port port, std::unique_ptr<Task> task, bool is_completion) {
|
||||
return queue->lanes[static_cast<uint32_t>(port)].push(std::move(task), is_completion);
|
||||
QueueRef target = queue;
|
||||
resolve_lane(target, port);
|
||||
return target->lanes[static_cast<uint32_t>(port)].push(std::move(task), is_completion);
|
||||
}
|
||||
|
||||
|
||||
@@ -275,6 +295,10 @@ void WINAPI XTaskQueueCloseHandle(void* handle) {
|
||||
queue = std::move(it->second);
|
||||
close_queue = queue != process_queue;
|
||||
handles.erase(it);
|
||||
// Duplicated handles share the queue: only the last close shuts its lanes down.
|
||||
for (const auto& other : handles) {
|
||||
if (other.second == queue) close_queue = false;
|
||||
}
|
||||
}
|
||||
// The frozen ABI exposes no termination or duplicate-handle API. Drain manual
|
||||
// completion callbacks on close and let accepted pool work finish normally.
|
||||
@@ -285,8 +309,64 @@ void WINAPI XTaskQueueCloseHandle(void* handle) {
|
||||
|
||||
bool WINAPI XTaskQueueDispatch(void* handle, Port port, uint32_t timeout) {
|
||||
if (!handle || port > Port::completion) return false;
|
||||
auto queue = acquire_queue(handle);
|
||||
if (!queue) return false;
|
||||
resolve_lane(queue, port);
|
||||
return queue->lanes[static_cast<uint32_t>(port)].dispatch(timeout);
|
||||
}
|
||||
|
||||
// Not exported: reached through IXGameRuntimeCore (com_dispatch.cpp).
|
||||
HRESULT WINAPI bx_xtq_duplicate_handle(void* handle, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
const auto queue = acquire_queue(handle);
|
||||
return queue && queue->lanes[static_cast<uint32_t>(port)].dispatch(timeout);
|
||||
if (!queue) return E_HANDLE;
|
||||
try {
|
||||
std::lock_guard lock(queues_mutex);
|
||||
*out = add_handle(queue);
|
||||
return S_OK;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT WINAPI bx_xtq_get_port(void* handle, Port port, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (port > Port::completion) return E_INVALIDARG;
|
||||
const auto queue = acquire_queue(handle);
|
||||
if (!queue) return E_HANDLE;
|
||||
try {
|
||||
std::lock_guard lock(queues_mutex);
|
||||
const auto id = next_port_handle;
|
||||
next_port_handle += 2;
|
||||
port_handles.emplace(id, std::make_pair(queue, port));
|
||||
*out = reinterpret_cast<void*>(id);
|
||||
return S_OK;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT WINAPI bx_xtq_create_composite(void* work_port, void* completion_port, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
try {
|
||||
std::lock_guard lock(queues_mutex);
|
||||
const auto work = port_handles.find(reinterpret_cast<uintptr_t>(work_port));
|
||||
const auto completion = port_handles.find(reinterpret_cast<uintptr_t>(completion_port));
|
||||
if (work == port_handles.end() || completion == port_handles.end()) return E_HANDLE;
|
||||
// Immediate lanes: never used, every submit and dispatch is forwarded.
|
||||
auto queue = std::make_shared<Queue>(DispatchMode::immediate, DispatchMode::immediate);
|
||||
queue->forward[0] = work->second.first;
|
||||
queue->forward_port[0] = work->second.second;
|
||||
queue->forward[1] = completion->second.first;
|
||||
queue->forward_port[1] = completion->second.second;
|
||||
*out = add_handle(queue);
|
||||
return S_OK;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void* handle, Port port, uint32_t delay_ms, void* context,
|
||||
|
||||
@@ -167,6 +167,10 @@ public:
|
||||
Operation operation;
|
||||
std::unique_ptr<AsyncOp> op;
|
||||
std::unique_ptr<CompletionTask> completion;
|
||||
// The queue the block named. A composite queue forwards its ports to other queues, and a
|
||||
// task runs with the queue that owns the lane, so the completion must go back through
|
||||
// this one to reach the composite's completion port.
|
||||
QueueRef origin;
|
||||
bool queued = false;
|
||||
|
||||
AsyncTask(AsyncBlock* block, Operation operation, std::unique_ptr<AsyncOp> op)
|
||||
@@ -225,7 +229,7 @@ private:
|
||||
queued = false;
|
||||
write_state(block, state);
|
||||
}
|
||||
if (completion) submit(queue, Port::completion, std::move(completion), true);
|
||||
if (completion) submit(origin ? origin : queue, Port::completion, std::move(completion), true);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -236,6 +240,7 @@ HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr, std
|
||||
|
||||
auto work = std::unique_ptr<AsyncTask>(new (std::nothrow) AsyncTask(block, operation, std::move(op)));
|
||||
if (!work) return E_OUTOFMEMORY;
|
||||
work->origin = queue;
|
||||
if (block->callback) {
|
||||
work->completion.reset(new (std::nothrow) CompletionTask(block));
|
||||
if (!work->completion) return E_OUTOFMEMORY;
|
||||
@@ -643,6 +648,21 @@ HRESULT WINAPI XUserAddResult(AsyncBlock* block, void** out) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Not exported: XUserDuplicateHandle is reached through IXUser (com_dispatch.cpp). A duplicate is
|
||||
// a new handle to the same (single, offline) user; each handle is closed separately.
|
||||
HRESULT WINAPI bx_xuser_duplicate_handle(void* user, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
std::lock_guard lock(state_mutex);
|
||||
if (!users.contains(user)) return runtime_invalid_handle;
|
||||
return create_handle(users, out);
|
||||
}
|
||||
|
||||
bool WINAPI bx_xuser_is_handle(void* user) {
|
||||
std::lock_guard lock(state_mutex);
|
||||
return users.contains(user);
|
||||
}
|
||||
|
||||
void WINAPI XUserCloseHandle(void* user) {
|
||||
std::lock_guard lock(state_mutex);
|
||||
users.erase(user);
|
||||
|
||||
@@ -97,6 +97,17 @@ struct Lock {
|
||||
~Lock() { ReleaseSRWLockExclusive(&memory_lock); }
|
||||
};
|
||||
|
||||
// Replacing part of a mapped view can leave a temporary gap across that view
|
||||
// while its remaining runs are restored. DirectStorage holds remap_lock shared
|
||||
// while accessing title memory. Mapping and freeing take it exclusively during
|
||||
// replacement. Acquire it before memory_lock to keep the lock order consistent.
|
||||
SRWLOCK remap_lock = SRWLOCK_INIT;
|
||||
|
||||
struct RemapExclusive {
|
||||
RemapExclusive() { AcquireSRWLockExclusive(&remap_lock); }
|
||||
~RemapExclusive() { ReleaseSRWLockExclusive(&remap_lock); }
|
||||
};
|
||||
|
||||
using ReservePlaceholder = PVOID (WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG,
|
||||
MEM_EXTENDED_PARAMETER*, ULONG);
|
||||
using ReplacePlaceholder = PVOID (WINAPI*)(HANDLE, HANDLE, PVOID, ULONG64, SIZE_T, ULONG,
|
||||
@@ -690,6 +701,7 @@ extern "C" BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR page_ar
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
RemapExclusive remap;
|
||||
Lock lock;
|
||||
SIZE_T validated = 0;
|
||||
for (; validated < count; ++validated) {
|
||||
@@ -741,6 +753,7 @@ extern "C" PVOID WINAPI XMemMapPhysicalPages(PVOID address, ULONG_PTR count, PUL
|
||||
return nullptr;
|
||||
}
|
||||
if (!have_placeholder_api()) return nullptr;
|
||||
RemapExclusive remap;
|
||||
Lock lock;
|
||||
auto* base = static_cast<BYTE*>(address);
|
||||
const auto begin = reinterpret_cast<uintptr_t>(address);
|
||||
@@ -799,6 +812,7 @@ static BOOL scatter_impl(PVOID* addresses, ULONG_PTR count, PULONG_PTR page_arra
|
||||
return FALSE;
|
||||
}
|
||||
if (!have_placeholder_api()) return FALSE;
|
||||
RemapExclusive remap;
|
||||
Lock lock;
|
||||
for (ULONG_PTR i = 0; i < count; ++i) {
|
||||
const auto slot = reinterpret_cast<uintptr_t>(addresses[i]);
|
||||
@@ -838,6 +852,14 @@ static BOOL scatter_impl(PVOID* addresses, ULONG_PTR count, PULONG_PTR page_arra
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
extern "C" void bx_xmem_remap_guard_enter(void) {
|
||||
AcquireSRWLockShared(&remap_lock);
|
||||
}
|
||||
|
||||
extern "C" void bx_xmem_remap_guard_leave(void) {
|
||||
ReleaseSRWLockShared(&remap_lock);
|
||||
}
|
||||
|
||||
extern "C" int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info) {
|
||||
if (!out_info) return 0;
|
||||
|
||||
|
||||
+89
-15
@@ -85,6 +85,53 @@ void update_peak() {
|
||||
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes + physical_bytes + external_bytes);
|
||||
}
|
||||
|
||||
// The accounting as the internal ABI reports it. The caller holds usage_lock.
|
||||
bx_xmem_stats_t stats_locked() {
|
||||
return {title_limit(), heap_bytes + virtual_bytes + external_bytes, physical_bytes, peak_bytes};
|
||||
}
|
||||
|
||||
// XMEM_WORKING_SET_STATISTICS as the authorized GDK header lays it out for x64: SIZE_T fields
|
||||
// are 8 bytes and UINT32 fields 4, in declaration order with natural alignment.
|
||||
struct WorkingSetStatistics {
|
||||
uint64_t game_limit;
|
||||
uint64_t game_used;
|
||||
uint64_t tools_limit;
|
||||
uint64_t tools_used;
|
||||
uint32_t stack_used;
|
||||
uint32_t game_allocated_physical_page_count;
|
||||
uint64_t gpu_optimal_bandwidth_limit;
|
||||
uint64_t gpu_optimal_bandwidth_used;
|
||||
uint64_t tools_gpu_optimal_bandwidth_limit;
|
||||
uint64_t tools_gpu_optimal_bandwidth_used;
|
||||
uint32_t kernel_pool_used;
|
||||
uint32_t kernel_pool_limit;
|
||||
uint32_t direct_storage_used;
|
||||
uint32_t frame_preserve_buffer_size;
|
||||
uint64_t game_used_peak;
|
||||
uint32_t gpu_page_table_size;
|
||||
uint32_t cpu_page_table_size;
|
||||
uint64_t reserved[2];
|
||||
};
|
||||
static_assert(offsetof(WorkingSetStatistics, stack_used) == 0x20);
|
||||
static_assert(offsetof(WorkingSetStatistics, gpu_optimal_bandwidth_limit) == 0x28);
|
||||
static_assert(offsetof(WorkingSetStatistics, kernel_pool_used) == 0x48);
|
||||
static_assert(offsetof(WorkingSetStatistics, game_used_peak) == 0x58);
|
||||
static_assert(offsetof(WorkingSetStatistics, reserved) == 0x68);
|
||||
static_assert(sizeof(WorkingSetStatistics) == 0x78);
|
||||
|
||||
// XMEM_WORKING_SET_TITLE, _TOOLS, _STACK, _KERNEL_POOL and _CPU_PTE are 0x20000001, 0x20000002,
|
||||
// 0x20000004, 0x20000008 and 0x20000010: a shared 0x20000000 bit and one bit per category.
|
||||
constexpr DWORD working_set_marker = 0x20000000;
|
||||
constexpr DWORD working_set_categories = 0x1F;
|
||||
|
||||
bool valid_working_set_flags(DWORD flags) {
|
||||
return (flags & working_set_marker) && (flags & working_set_categories)
|
||||
&& !(flags & ~(working_set_marker | working_set_categories));
|
||||
}
|
||||
|
||||
// Physical pages are always 64 KiB (physical_pages.cpp).
|
||||
constexpr uint64_t physical_page_bytes = 64 * 1024;
|
||||
|
||||
uintptr_t region_end(const MEMORY_BASIC_INFORMATION& region) {
|
||||
return reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
@@ -365,19 +412,47 @@ BOOL WINAPI XMemTransferMemory(PVOID dst, LPCVOID src, SIZE_T bytes, uint64_t /*
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size) {
|
||||
if (!out_stats || stats_size < sizeof(bx_xmem_stats_t)) {
|
||||
/*
|
||||
* XMemGetWorkingSetStatistics(WorkingSetFlags, Statistics), as the authorized GDK header declares
|
||||
* it. The whole structure is written, whichever categories the flags select, from xmem's own
|
||||
* accounting:
|
||||
* - GameLimit: the title memory cap.
|
||||
* - GameUsed: everything the cap counts (XMem heap, virtual commits, physical pages and
|
||||
* external charges); GameUsedPeak is its highest value so far.
|
||||
* - GameAllocatedPhysicalPageCount: the 64 KiB physical pages allocated.
|
||||
* - Tools fields: 0, since tools memory is unavailable (XMemIsToolsMemAvailable).
|
||||
* - Every other field: 0. The host has no console kernel pool, GPU or CPU page tables,
|
||||
* frame-preserve buffer or separate GPU-optimal memory, and xmem does not count thread
|
||||
* stacks or DirectStorage buffers.
|
||||
* A NULL Statistics, or flags outside the five XMEM_WORKING_SET_* values, is refused.
|
||||
*/
|
||||
BOOL WINAPI XMemGetWorkingSetStatistics(DWORD flags, PVOID statistics) {
|
||||
if (!statistics || !valid_working_set_flags(flags)) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "refused flags=0x%lx statistics=%p",
|
||||
static_cast<unsigned long>(flags), statistics);
|
||||
bx_log_emit(BX_LOG_WARN, "xmem", "working_set_statistics", detail);
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
std::lock_guard guard(usage_lock);
|
||||
if (!refresh_virtual_commits()) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
bx_xmem_stats_t stats;
|
||||
{
|
||||
std::lock_guard guard(usage_lock);
|
||||
if (!refresh_virtual_commits()) {
|
||||
bx_log_emit(BX_LOG_ERROR, "xmem", "working_set_statistics",
|
||||
"refresh_virtual_commits failed; statistics not reported");
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
stats = stats_locked();
|
||||
}
|
||||
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes + external_bytes, physical_bytes, peak_bytes};
|
||||
std::memset(out_stats, 0, stats_size);
|
||||
std::memcpy(out_stats, &stats, sizeof(stats));
|
||||
WorkingSetStatistics out{};
|
||||
out.game_limit = stats.title_limit_bytes;
|
||||
out.game_used = stats.committed_virtual_bytes + stats.allocated_physical_bytes;
|
||||
out.game_used_peak = stats.peak_committed_bytes;
|
||||
out.game_allocated_physical_page_count = static_cast<uint32_t>(std::min<uint64_t>(
|
||||
stats.allocated_physical_bytes / physical_page_bytes, std::numeric_limits<uint32_t>::max()));
|
||||
std::memcpy(statistics, &out, sizeof(out));
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
@@ -387,12 +462,11 @@ BOOL WINAPI XMemIsToolsMemAvailable(void) {
|
||||
|
||||
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats) {
|
||||
if (!out_stats) return;
|
||||
if (!XMemGetWorkingSetStatistics(out_stats, sizeof(*out_stats))) {
|
||||
// The internal ABI has no error return. Preserve the most recent
|
||||
// accounting snapshot if refreshing it runs out of bookkeeping memory.
|
||||
std::lock_guard guard(usage_lock);
|
||||
*out_stats = {title_limit(), heap_bytes + virtual_bytes + external_bytes, physical_bytes, peak_bytes};
|
||||
}
|
||||
std::lock_guard guard(usage_lock);
|
||||
// The internal ABI has no error return. If refreshing runs out of bookkeeping memory, the
|
||||
// tracked commits are left as they were and the most recent snapshot is reported.
|
||||
(void)refresh_virtual_commits();
|
||||
*out_stats = stats_locked();
|
||||
}
|
||||
|
||||
int bx_xmem_try_charge_external(uint64_t bytes) {
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
add_executable(test_console_mode main.cpp)
|
||||
target_link_libraries(test_console_mode PRIVATE xgameruntime advapi32 kernel32)
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* The console type in the registry. A title can read the REG_DWORD ConsoleMode under
|
||||
* HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM instead of calling XSystemGetDeviceType
|
||||
* (target-build observation): it opens the key with RegOpenKeyW, reads the value with
|
||||
* RegQueryValueExW and maps 0x60 to Series S, 0x64 to Series X and 0x68 to the Scarlett devkit;
|
||||
* with no key it takes itself for a PC and sizes its memory for Series X. The XSystemDeviceType
|
||||
* numbers below are those of the authorized GDK (XboxScarlettLockhart 6, XboxScarlettAnaconda 7,
|
||||
* XboxScarlettDevkit 8, Pc 1). This test reads the value the same way and checks it against the
|
||||
* BetterXen profile (BX_PROFILE, as bx-cli run sets it) and against XSystemGetDeviceType.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
extern "C" uint32_t WINAPI XSystemGetDeviceType();
|
||||
|
||||
namespace {
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
std::fprintf(stderr, "console mode:%d: %s\n", __LINE__, #condition); \
|
||||
return 1; \
|
||||
} \
|
||||
} while (false)
|
||||
|
||||
// The title's mapping of ConsoleMode to XSystemDeviceType, written out from the observation.
|
||||
uint32_t device_type_for(DWORD mode) {
|
||||
switch (mode) {
|
||||
case 0x10: case 0x20: case 0x21: case 0x30: case 0x31: return 2; // XboxOne
|
||||
case 0x40: return 3; // XboxOneS
|
||||
case 0x50: return 4; // XboxOneX
|
||||
case 0x58: return 5; // XboxOneXDevkit
|
||||
case 0x60: return 6; // XboxScarlettLockhart
|
||||
case 0x64: return 7; // XboxScarlettAnaconda
|
||||
case 0x68: return 8; // XboxScarlettDevkit
|
||||
default: return 0; // Unknown
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
char profile[32] = {};
|
||||
GetEnvironmentVariableA("BX_PROFILE", profile, sizeof(profile));
|
||||
const bool anaconda = _stricmp(profile, "anaconda") == 0;
|
||||
const DWORD expected_mode = anaconda ? 0x64 : 0x60;
|
||||
|
||||
HKEY key = nullptr;
|
||||
CHECK(RegOpenKeyW(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM", &key) ==
|
||||
ERROR_SUCCESS); // without it the title takes itself for a PC
|
||||
DWORD mode = 0;
|
||||
DWORD type = 0;
|
||||
DWORD size = sizeof(mode);
|
||||
const LSTATUS status = RegQueryValueExW(key, L"ConsoleMode", nullptr, &type, reinterpret_cast<BYTE*>(&mode), &size);
|
||||
RegCloseKey(key);
|
||||
CHECK(status == ERROR_SUCCESS);
|
||||
CHECK(type == REG_DWORD && size == sizeof(DWORD));
|
||||
std::printf("ConsoleMode=0x%lx profile=%s XSystemGetDeviceType=%u\n", static_cast<unsigned long>(mode),
|
||||
anaconda ? "anaconda" : "lockhart", XSystemGetDeviceType());
|
||||
CHECK(mode == expected_mode);
|
||||
CHECK(device_type_for(mode) == (anaconda ? 7u : 6u));
|
||||
CHECK(device_type_for(mode) == XSystemGetDeviceType()); // both ways of asking agree
|
||||
|
||||
std::puts("PASS: test_console_mode");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_d3d12_committed_resource_x main.cpp)
|
||||
target_compile_definitions(test_d3d12_committed_resource_x PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_committed_resource_x PRIVATE d3d12_xs xmem kernel32 uuid)
|
||||
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
* CreateCommittedResourceX (Xbox device table slot 76): CreateCommittedResource with a
|
||||
* D3D12XBOX_RESOURCE_DESC, which is the PC D3D12_RESOURCE_DESC followed by DccOptions, a struct of
|
||||
* two 32-bit enums, CompressionLevel and ColorTransform (authorized GDK header). The resource must be created with the PC part of the description,
|
||||
* whatever DccOptions says, and its memory requested through XMemAlloc like any committed
|
||||
* resource (AllocatorId D3D 128, ObjectType Resource 4), so a title hooking XMemAlloc sees it.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
|
||||
void** ppv);
|
||||
extern "C" __declspec(dllimport) PVOID WINAPI XMemAllocDefault(SIZE_T, ULONGLONG);
|
||||
extern "C" __declspec(dllimport) VOID WINAPI XMemFreeDefault(PVOID, ULONGLONG);
|
||||
|
||||
namespace {
|
||||
|
||||
// D3D12XBOX_RESOURCE_DESC, written out from the GDK header's field list.
|
||||
struct DccOptions {
|
||||
UINT32 CompressionLevel; // D3D12XBOX_DCC_COMPRESSION_LEVEL: 64B 0, 128B 1, 256B 2, DEFAULT 3
|
||||
UINT32 ColorTransform; // D3D12XBOX_DCC_COLOR_TRANSFORM: 0..3
|
||||
};
|
||||
struct XboxResourceDesc {
|
||||
D3D12_RESOURCE_DESC pc;
|
||||
DccOptions Dcc;
|
||||
};
|
||||
static_assert(offsetof(XboxResourceDesc, Dcc) == 56, "DccOptions follows the 56-byte PC description");
|
||||
static_assert(sizeof(XboxResourceDesc) == 64, "DccOptions is two 32-bit enums");
|
||||
|
||||
constexpr ULONGLONG kD3DResource = (128ull << 16) | 4;
|
||||
int g_d3d_requests = 0;
|
||||
PVOID WINAPI alloc_hook(SIZE_T size, ULONGLONG attributes) {
|
||||
if ((attributes & ((0xFFull << 16) | 0x1F)) == kD3DResource) ++g_d3d_requests;
|
||||
return XMemAllocDefault(size, attributes);
|
||||
}
|
||||
VOID WINAPI free_hook(PVOID address, ULONGLONG attributes) { XMemFreeDefault(address, attributes); }
|
||||
|
||||
constexpr int kRelease = 2, kResGetDesc = 10, kDevCreateCommittedResourceX = 76;
|
||||
template <typename Fn>
|
||||
Fn slot(void* object, int index) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
|
||||
}
|
||||
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
using GetDescFn = void(STDMETHODCALLTYPE*)(void*, D3D12_RESOURCE_DESC*);
|
||||
using CreateCommittedXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
|
||||
const XboxResourceDesc*, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, REFIID, void**);
|
||||
int g_failed = 0;
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
if (!(cond)) { \
|
||||
++g_failed; \
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_committed_resource_x:%d: ", __LINE__); \
|
||||
std::fprintf(stderr, __VA_ARGS__); \
|
||||
std::fprintf(stderr, "\n"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
void create_and_check(void* dev, const XboxResourceDesc& x, const char* what) {
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
const int before = g_d3d_requests;
|
||||
void* resource = nullptr;
|
||||
const HRESULT hr = slot<CreateCommittedXFn>(dev, kDevCreateCommittedResourceX)(
|
||||
dev, &heap, D3D12_HEAP_FLAG_NONE, &x, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), &resource);
|
||||
CHECK(hr == S_OK && resource, "%s: hr=0x%08lx", what, static_cast<unsigned long>(hr));
|
||||
if (!resource) return;
|
||||
D3D12_RESOURCE_DESC got{};
|
||||
slot<GetDescFn>(resource, kResGetDesc)(resource, &got);
|
||||
CHECK(got.Dimension == x.pc.Dimension && got.Width == x.pc.Width && got.Height == x.pc.Height &&
|
||||
got.MipLevels == x.pc.MipLevels && got.Format == x.pc.Format,
|
||||
"%s: created with dim=%d %llux%u mips=%u format=%d", what, static_cast<int>(got.Dimension),
|
||||
static_cast<unsigned long long>(got.Width), got.Height, got.MipLevels, static_cast<int>(got.Format));
|
||||
CHECK(g_d3d_requests == before + 1, "%s: %d XMemAlloc requests for its memory", what, g_d3d_requests - before);
|
||||
std::printf("%s: hr=0x%08lx %llux%u format=%d, XMemAlloc requests=%d\n", what, static_cast<unsigned long>(hr),
|
||||
static_cast<unsigned long long>(got.Width), got.Height, static_cast<int>(got.Format),
|
||||
g_d3d_requests - before);
|
||||
slot<ReleaseFn>(resource, kRelease)(resource);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
struct AllocationHooks {
|
||||
PVOID(WINAPI* alloc)(SIZE_T, ULONGLONG);
|
||||
VOID(WINAPI* free)(PVOID, ULONGLONG);
|
||||
};
|
||||
extern "C" __declspec(dllexport) AllocationHooks __XMemAllocationHooks__ = {alloc_hook, free_hook};
|
||||
|
||||
int main() {
|
||||
alignas(8) unsigned char title_params[80] = {};
|
||||
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
|
||||
std::memcpy(title_params, &version, sizeof(version));
|
||||
void* dev = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
|
||||
if (hr == E_NOINTERFACE) {
|
||||
std::printf("SKIP: test_d3d12_committed_resource_x: host lacks the Xbox-layout device interface\n");
|
||||
return 77;
|
||||
}
|
||||
if (FAILED(hr) || !dev) {
|
||||
std::fprintf(stderr, "FAIL: device creation hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
|
||||
XboxResourceDesc target{};
|
||||
target.pc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
target.pc.Width = 1920;
|
||||
target.pc.Height = 1080;
|
||||
target.pc.DepthOrArraySize = 1;
|
||||
target.pc.MipLevels = 1;
|
||||
target.pc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
target.pc.SampleDesc.Count = 1;
|
||||
target.pc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
|
||||
target.Dcc = {2, 3}; // 256B with a correlated colour transform: the host has no compression
|
||||
create_and_check(dev, target, "render target with DccOptions");
|
||||
|
||||
XboxResourceDesc buffer{};
|
||||
buffer.pc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
buffer.pc.Width = 256 * 1024;
|
||||
buffer.pc.Height = 1;
|
||||
buffer.pc.DepthOrArraySize = 1;
|
||||
buffer.pc.MipLevels = 1;
|
||||
buffer.pc.SampleDesc.Count = 1;
|
||||
buffer.pc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
create_and_check(dev, buffer, "buffer");
|
||||
|
||||
void* none = reinterpret_cast<void*>(1);
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
hr = slot<CreateCommittedXFn>(dev, kDevCreateCommittedResourceX)(dev, &heap, D3D12_HEAP_FLAG_NONE, nullptr,
|
||||
D3D12_RESOURCE_STATE_COMMON, nullptr,
|
||||
__uuidof(ID3D12Resource), &none);
|
||||
CHECK(hr == E_INVALIDARG, "null description: hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
slot<ReleaseFn>(dev, kRelease)(dev);
|
||||
if (g_failed) return 1;
|
||||
std::puts("PASS: test_d3d12_committed_resource_x");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_d3d12_committed_tile_size main.cpp)
|
||||
target_compile_definitions(test_d3d12_committed_tile_size PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_committed_tile_size PRIVATE d3d12_xs xmem kernel32 uuid)
|
||||
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* The XMemAlloc request a committed render-target or unordered-access texture makes. On the
|
||||
* console the D3D12 runtime asks XMemAlloc (AllocatorId D3D 128, ObjectType Resource 4) for the
|
||||
* resource's memory, and a title hooking XMemAlloc can size its pool for those requests and check
|
||||
* what is left. A 2D render-target or UAV texture with one mip and one sample is laid out in 64 KB
|
||||
* tiles (64KB_R_X): 128x128 elements at 4 bytes, 128x64 at 8, per slice. The expected sizes below
|
||||
* are the tile part of the sizes the authorized GDK XG library reports for these descriptions,
|
||||
* written out here; XG's render-target compression metadata after the tiles is not modelled.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
|
||||
void** ppv);
|
||||
extern "C" __declspec(dllimport) PVOID WINAPI XMemAllocDefault(SIZE_T, ULONGLONG);
|
||||
extern "C" __declspec(dllimport) VOID WINAPI XMemFreeDefault(PVOID, ULONGLONG);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr ULONGLONG kD3DResource = (128ull << 16) | 4; // AllocatorId bits 16-23, ObjectType bits 0-4
|
||||
SIZE_T g_last_request = 0;
|
||||
|
||||
PVOID WINAPI alloc_hook(SIZE_T size, ULONGLONG attributes) {
|
||||
if ((attributes & ((0xFFull << 16) | 0x1F)) == kD3DResource) g_last_request = size;
|
||||
return XMemAllocDefault(size, attributes);
|
||||
}
|
||||
VOID WINAPI free_hook(PVOID address, ULONGLONG attributes) { XMemFreeDefault(address, attributes); }
|
||||
|
||||
constexpr int kRelease = 2, kDevGetResourceAllocationInfo = 25, kDevCreateCommittedResource = 27;
|
||||
int g_failed = 0;
|
||||
|
||||
template <typename Fn>
|
||||
Fn slot(void* object, int index) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
|
||||
}
|
||||
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
using AllocationInfoFn = D3D12_RESOURCE_ALLOCATION_INFO(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_RESOURCE_DESC*);
|
||||
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
|
||||
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, REFIID, void**);
|
||||
|
||||
D3D12_RESOURCE_DESC texture(UINT64 w, UINT h, UINT16 slices, DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags) {
|
||||
D3D12_RESOURCE_DESC d{};
|
||||
d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
d.Width = w;
|
||||
d.Height = h;
|
||||
d.DepthOrArraySize = slices;
|
||||
d.MipLevels = 1;
|
||||
d.Format = format;
|
||||
d.SampleDesc.Count = 1;
|
||||
d.Flags = flags;
|
||||
return d;
|
||||
}
|
||||
|
||||
// Creates the resource and returns the size of the XMemAlloc request it made (0 on failure).
|
||||
SIZE_T request_for(void* dev, const D3D12_RESOURCE_DESC& desc) {
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
g_last_request = 0;
|
||||
void* resource = nullptr;
|
||||
const HRESULT hr = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(
|
||||
dev, &heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), &resource);
|
||||
if (FAILED(hr) || !resource) return 0;
|
||||
slot<ReleaseFn>(resource, kRelease)(resource);
|
||||
return g_last_request;
|
||||
}
|
||||
|
||||
void expect(const char* what, SIZE_T got, SIZE_T want) {
|
||||
std::printf("%-44s request=0x%llx expected=0x%llx\n", what, static_cast<unsigned long long>(got),
|
||||
static_cast<unsigned long long>(want));
|
||||
if (got != want) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_committed_tile_size: %s\n", what);
|
||||
++g_failed;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
struct AllocationHooks {
|
||||
PVOID(WINAPI* alloc)(SIZE_T, ULONGLONG);
|
||||
VOID(WINAPI* free)(PVOID, ULONGLONG);
|
||||
};
|
||||
extern "C" __declspec(dllexport) AllocationHooks __XMemAllocationHooks__ = {alloc_hook, free_hook};
|
||||
|
||||
int main() {
|
||||
alignas(8) unsigned char title_params[80] = {};
|
||||
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
|
||||
std::memcpy(title_params, &version, sizeof(version));
|
||||
void* dev = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
|
||||
if (hr == E_NOINTERFACE) {
|
||||
std::printf("SKIP: test_d3d12_committed_tile_size: host lacks the Xbox-layout device interface\n");
|
||||
return 77;
|
||||
}
|
||||
if (FAILED(hr) || !dev) {
|
||||
std::fprintf(stderr, "FAIL: device creation hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
constexpr auto RT = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
|
||||
constexpr auto UAV = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
constexpr SIZE_T k64K = 64 * 1024;
|
||||
|
||||
expect("1920x1080 RGBA8 RT+UAV: 15x9 tiles",
|
||||
request_for(dev, texture(1920, 1080, 1, DXGI_FORMAT_R8G8B8A8_UNORM, RT | UAV)), 135 * k64K);
|
||||
expect("3840x2160 RGBA8 RT: 30x17 tiles",
|
||||
request_for(dev, texture(3840, 2160, 1, DXGI_FORMAT_R8G8B8A8_UNORM, RT)), 510 * k64K);
|
||||
expect("1920x1080 RGBA16F UAV: 15x17 tiles",
|
||||
request_for(dev, texture(1920, 1080, 1, DXGI_FORMAT_R16G16B16A16_FLOAT, UAV)), 255 * k64K);
|
||||
expect("1920x1080 RGBA8 RT+UAV x4 slices",
|
||||
request_for(dev, texture(1920, 1080, 4, DXGI_FORMAT_R8G8B8A8_UNORM, RT | UAV)), 4 * 135 * k64K);
|
||||
expect("64x64 RGBA8 RT: one tile",
|
||||
request_for(dev, texture(64, 64, 1, DXGI_FORMAT_R8G8B8A8_UNORM, RT)), k64K);
|
||||
|
||||
// Outside that scope (no render-target or UAV flag) the request stays the host's size.
|
||||
const D3D12_RESOURCE_DESC sampled = texture(1920, 1080, 1, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE);
|
||||
const D3D12_RESOURCE_ALLOCATION_INFO host =
|
||||
slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 1, &sampled);
|
||||
expect("1920x1080 RGBA8 sampled only: host size", request_for(dev, sampled), static_cast<SIZE_T>(host.SizeInBytes));
|
||||
|
||||
slot<ReleaseFn>(dev, kRelease)(dev);
|
||||
if (g_failed) return 1;
|
||||
std::puts("PASS: test_d3d12_committed_tile_size");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_d3d12_console_formats main.cpp)
|
||||
target_compile_definitions(test_d3d12_console_formats PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_console_formats PRIVATE d3d12_xs kernel32 uuid)
|
||||
@@ -0,0 +1,300 @@
|
||||
/*
|
||||
* Conformance test: console-only DXGI formats and console-only view combinations must not reach
|
||||
* the host Direct3D 12 implementation.
|
||||
*
|
||||
* Contract (Xbox Series GDK d3d12_xs.h): DXGI_FORMAT has values the PC enumeration lacks:
|
||||
* 116 R10G10B10_7E3_A2_FLOAT, 117 R10G10B10_6E4_A2_FLOAT, 118 D16_UNORM_S8_UINT,
|
||||
* 119 R16_UNORM_X8_TYPELESS, 120 X16_TYPELESS_G8_UINT, 189 R10G10B10_SNORM_A2_UNORM,
|
||||
* 190 R4G4_UNORM.
|
||||
* A title built for the console passes them to resource, allocation-info and view calls, and
|
||||
* creates unordered-access views on depth-stencil textures (the console allows
|
||||
* ALLOW_DEPTH_STENCIL together with ALLOW_UNORDERED_ACCESS; PC Direct3D 12 does not).
|
||||
*
|
||||
* On a host that does not know them (D3DMetal), either makes Metal abort the process, so the
|
||||
* failure mode of this test without the fix is that the process dies at the first such call and
|
||||
* the runner sees a non-zero exit with no PASS line.
|
||||
*
|
||||
* Every call goes through the Xbox-layout function table of an Xbox-layout device (ADR 0009).
|
||||
* Slots: 2 Release; device 14 CreateDescriptorHeap, 18 CreateShaderResourceView,
|
||||
* 19 CreateUnorderedAccessView, 21 CreateDepthStencilView, 25 GetResourceAllocationInfo,
|
||||
* 27 CreateCommittedResource, 95 GetResourceAllocationInfo1, 108 GetResourceAllocationInfo2;
|
||||
* resource 10 GetDesc; descriptor heap 9 GetCPUDescriptorHandleForHeapStart.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
|
||||
void** ppv);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kRelease = 2;
|
||||
constexpr int kDevCreateDescriptorHeap = 14, kDevCreateShaderResourceView = 18, kDevCreateUnorderedAccessView = 19;
|
||||
constexpr int kDevCreateDepthStencilView = 21, kDevGetResourceAllocationInfo = 25, kDevCreateCommittedResource = 27;
|
||||
constexpr int kDevGetResourceAllocationInfo1 = 95, kDevGetResourceAllocationInfo2 = 108;
|
||||
constexpr int kResGetDesc = 10, kHeapGetCpuStart = 9;
|
||||
|
||||
// Console-only formats, by number: the PC <dxgiformat.h> has no names for them.
|
||||
constexpr DXGI_FORMAT kD16_UNORM_S8_UINT = static_cast<DXGI_FORMAT>(118);
|
||||
constexpr DXGI_FORMAT kR16_UNORM_X8_TYPELESS = static_cast<DXGI_FORMAT>(119);
|
||||
constexpr DXGI_FORMAT kX16_TYPELESS_G8_UINT = static_cast<DXGI_FORMAT>(120);
|
||||
|
||||
int g_checks = 0;
|
||||
int g_failed = 0;
|
||||
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
++g_checks; \
|
||||
if (!(cond)) { \
|
||||
++g_failed; \
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_console_formats:%d: ", __LINE__); \
|
||||
std::fprintf(stderr, __VA_ARGS__); \
|
||||
std::fprintf(stderr, "\n"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
template <typename Fn>
|
||||
Fn slot(void* object, int index) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
|
||||
}
|
||||
|
||||
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
using AllocationInfoFn = D3D12_RESOURCE_ALLOCATION_INFO(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_RESOURCE_DESC*);
|
||||
using AllocationInfo1Fn = D3D12_RESOURCE_ALLOCATION_INFO(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_RESOURCE_DESC*,
|
||||
D3D12_RESOURCE_ALLOCATION_INFO1*);
|
||||
using AllocationInfo2Fn = D3D12_RESOURCE_ALLOCATION_INFO(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_RESOURCE_DESC1*,
|
||||
D3D12_RESOURCE_ALLOCATION_INFO1*);
|
||||
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
|
||||
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, REFIID, void**);
|
||||
using CreateHeapFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_DESCRIPTOR_HEAP_DESC*, REFIID, void**);
|
||||
using HeapStartFn = D3D12_CPU_DESCRIPTOR_HANDLE(STDMETHODCALLTYPE*)(void*);
|
||||
using GetDescFn = void(STDMETHODCALLTYPE*)(void*, D3D12_RESOURCE_DESC*);
|
||||
using CreateSrvFn = void(STDMETHODCALLTYPE*)(void*, void*, const D3D12_SHADER_RESOURCE_VIEW_DESC*, D3D12_CPU_DESCRIPTOR_HANDLE);
|
||||
using CreateUavFn = void(STDMETHODCALLTYPE*)(void*, void*, void*, const D3D12_UNORDERED_ACCESS_VIEW_DESC*,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE);
|
||||
using CreateDsvFn = void(STDMETHODCALLTYPE*)(void*, void*, const D3D12_DEPTH_STENCIL_VIEW_DESC*, D3D12_CPU_DESCRIPTOR_HANDLE);
|
||||
|
||||
D3D12_RESOURCE_DESC texture(DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags) {
|
||||
D3D12_RESOURCE_DESC desc{};
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
desc.Width = 256;
|
||||
desc.Height = 256;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.Format = format;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Flags = flags;
|
||||
return desc;
|
||||
}
|
||||
|
||||
std::string read_log() {
|
||||
char path[MAX_PATH];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (n == 0 || n >= sizeof(path)) return {};
|
||||
std::string text;
|
||||
if (FILE* f = std::fopen(path, "rb")) {
|
||||
char buffer[4096];
|
||||
size_t got;
|
||||
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
|
||||
std::fclose(f);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
size_t count_of(const std::string& text, const char* needle) {
|
||||
size_t n = 0;
|
||||
for (size_t pos = text.find(needle); pos != std::string::npos; pos = text.find(needle, pos + 1)) ++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
alignas(8) unsigned char title_params[80] = {};
|
||||
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
|
||||
std::memcpy(title_params, &version, sizeof(version));
|
||||
void* dev = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
|
||||
if (hr == E_NOINTERFACE) {
|
||||
std::printf("SKIP: test_d3d12_console_formats: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
|
||||
return 77;
|
||||
}
|
||||
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!dev) return 1;
|
||||
const size_t stubs_before = count_of(read_log(), "CreateUnorderedAccessView(depth-stencil resource)");
|
||||
|
||||
// 1. Allocation info for a console-only format. The host's answer for the PC format the shim
|
||||
// documents as its substitute (R32G8X24_TYPELESS for a D16_UNORM_S8_UINT texture) is the
|
||||
// expected value, asked for directly so the expectation does not pass through the
|
||||
// translation under test.
|
||||
const D3D12_RESOURCE_FLAGS depth = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
|
||||
const D3D12_RESOURCE_DESC console_depth = texture(kD16_UNORM_S8_UINT, depth);
|
||||
const D3D12_RESOURCE_DESC pc_depth = texture(DXGI_FORMAT_R32G8X24_TYPELESS, depth);
|
||||
const D3D12_RESOURCE_ALLOCATION_INFO want = slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 1, &pc_depth);
|
||||
CHECK(want.SizeInBytes != 0 && want.SizeInBytes != UINT64_MAX, "control: host sizes a PC depth texture (size=%llu)",
|
||||
static_cast<unsigned long long>(want.SizeInBytes));
|
||||
D3D12_RESOURCE_ALLOCATION_INFO got = slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 1, &console_depth);
|
||||
CHECK(got.SizeInBytes == want.SizeInBytes && got.Alignment == want.Alignment,
|
||||
"GetResourceAllocationInfo(format 118): size=%llu alignment=%llu, want %llu/%llu",
|
||||
static_cast<unsigned long long>(got.SizeInBytes), static_cast<unsigned long long>(got.Alignment),
|
||||
static_cast<unsigned long long>(want.SizeInBytes), static_cast<unsigned long long>(want.Alignment));
|
||||
|
||||
D3D12_RESOURCE_ALLOCATION_INFO1 each{};
|
||||
got = slot<AllocationInfo1Fn>(dev, kDevGetResourceAllocationInfo1)(dev, 0, 1, &console_depth, &each);
|
||||
CHECK(got.SizeInBytes == want.SizeInBytes, "GetResourceAllocationInfo1(format 118): size=%llu, want %llu",
|
||||
static_cast<unsigned long long>(got.SizeInBytes), static_cast<unsigned long long>(want.SizeInBytes));
|
||||
|
||||
D3D12_RESOURCE_DESC1 console_depth1{};
|
||||
std::memcpy(&console_depth1, &console_depth, sizeof(console_depth)); // DESC1 is DESC plus a trailing region
|
||||
got = slot<AllocationInfo2Fn>(dev, kDevGetResourceAllocationInfo2)(dev, 0, 1, &console_depth1, &each);
|
||||
CHECK(got.SizeInBytes == want.SizeInBytes, "GetResourceAllocationInfo2(format 118): size=%llu, want %llu",
|
||||
static_cast<unsigned long long>(got.SizeInBytes), static_cast<unsigned long long>(want.SizeInBytes));
|
||||
|
||||
// An array with a console-only format in the second place only: every entry is translated,
|
||||
// not just the first.
|
||||
const D3D12_RESOURCE_DESC pair[2] = {texture(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE), console_depth};
|
||||
const D3D12_RESOURCE_DESC pc_pair[2] = {pair[0], pc_depth};
|
||||
const D3D12_RESOURCE_ALLOCATION_INFO want_pair = slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 2, pc_pair);
|
||||
got = slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 2, pair);
|
||||
CHECK(got.SizeInBytes == want_pair.SizeInBytes && got.SizeInBytes != 0,
|
||||
"GetResourceAllocationInfo(two descriptions, the second console-only): size=%llu, want %llu",
|
||||
static_cast<unsigned long long>(got.SizeInBytes), static_cast<unsigned long long>(want_pair.SizeInBytes));
|
||||
|
||||
// The colour formats: each is sized as the documented substitute.
|
||||
const struct {
|
||||
int console;
|
||||
DXGI_FORMAT substitute;
|
||||
} colour[] = {{116, DXGI_FORMAT_R16G16B16A16_FLOAT},
|
||||
{117, DXGI_FORMAT_R16G16B16A16_FLOAT},
|
||||
{189, DXGI_FORMAT_R16G16B16A16_SNORM},
|
||||
{190, DXGI_FORMAT_R8G8_UNORM}};
|
||||
for (const auto& c : colour) {
|
||||
const D3D12_RESOURCE_DESC a = texture(static_cast<DXGI_FORMAT>(c.console), D3D12_RESOURCE_FLAG_NONE);
|
||||
const D3D12_RESOURCE_DESC b = texture(c.substitute, D3D12_RESOURCE_FLAG_NONE);
|
||||
const D3D12_RESOURCE_ALLOCATION_INFO expected = slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 1, &b);
|
||||
got = slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 1, &a);
|
||||
CHECK(got.SizeInBytes == expected.SizeInBytes && got.SizeInBytes != 0, "GetResourceAllocationInfo(format %d): size=%llu, want %llu",
|
||||
c.console, static_cast<unsigned long long>(got.SizeInBytes), static_cast<unsigned long long>(expected.SizeInBytes));
|
||||
}
|
||||
|
||||
// 2. A committed depth texture of the console format, with a clear value of the console format.
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
D3D12_CLEAR_VALUE clear{};
|
||||
clear.Format = kD16_UNORM_S8_UINT;
|
||||
clear.DepthStencil.Depth = 1.0f;
|
||||
void* depth_texture = nullptr;
|
||||
hr = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &heap, D3D12_HEAP_FLAG_NONE, &console_depth,
|
||||
D3D12_RESOURCE_STATE_DEPTH_WRITE, &clear,
|
||||
__uuidof(ID3D12Resource), &depth_texture);
|
||||
CHECK(hr == S_OK && depth_texture, "CreateCommittedResource(format 118) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
// Views on it: depth-stencil in the console format, and its two planes read through the
|
||||
// console's plane formats.
|
||||
D3D12_DESCRIPTOR_HEAP_DESC dsv_heap_desc{};
|
||||
dsv_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
|
||||
dsv_heap_desc.NumDescriptors = 2;
|
||||
void* dsv_heap = nullptr;
|
||||
hr = slot<CreateHeapFn>(dev, kDevCreateDescriptorHeap)(dev, &dsv_heap_desc, __uuidof(ID3D12DescriptorHeap), &dsv_heap);
|
||||
CHECK(hr == S_OK && dsv_heap, "CreateDescriptorHeap(DSV) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
D3D12_DESCRIPTOR_HEAP_DESC view_heap_desc{};
|
||||
view_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
|
||||
view_heap_desc.NumDescriptors = 8;
|
||||
void* view_heap = nullptr;
|
||||
hr = slot<CreateHeapFn>(dev, kDevCreateDescriptorHeap)(dev, &view_heap_desc, __uuidof(ID3D12DescriptorHeap), &view_heap);
|
||||
CHECK(hr == S_OK && view_heap, "CreateDescriptorHeap(CBV_SRV_UAV) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!depth_texture || !dsv_heap || !view_heap) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_console_formats: setup\n");
|
||||
return 1;
|
||||
}
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE dsv = slot<HeapStartFn>(dsv_heap, kHeapGetCpuStart)(dsv_heap);
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE views = slot<HeapStartFn>(view_heap, kHeapGetCpuStart)(view_heap);
|
||||
constexpr SIZE_T kXboxViewSize = 32; // console CBV/SRV/UAV descriptor size (ADR 0009)
|
||||
|
||||
D3D12_DEPTH_STENCIL_VIEW_DESC dsv_desc{};
|
||||
dsv_desc.Format = kD16_UNORM_S8_UINT;
|
||||
dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
|
||||
slot<CreateDsvFn>(dev, kDevCreateDepthStencilView)(dev, depth_texture, &dsv_desc, dsv);
|
||||
CHECK(true, "CreateDepthStencilView(format 118) returned");
|
||||
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc{};
|
||||
srv_desc.Format = kR16_UNORM_X8_TYPELESS;
|
||||
srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
|
||||
srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
|
||||
srv_desc.Texture2D.MipLevels = 1;
|
||||
slot<CreateSrvFn>(dev, kDevCreateShaderResourceView)(dev, depth_texture, &srv_desc, views);
|
||||
CHECK(true, "CreateShaderResourceView(format 119, depth plane) returned");
|
||||
srv_desc.Format = kX16_TYPELESS_G8_UINT;
|
||||
srv_desc.Texture2D.PlaneSlice = 1;
|
||||
slot<CreateSrvFn>(dev, kDevCreateShaderResourceView)(dev, depth_texture, &srv_desc, {views.ptr + kXboxViewSize});
|
||||
CHECK(true, "CreateShaderResourceView(format 120, stencil plane) returned");
|
||||
|
||||
// The documented limit: GetDesc reports the host format of the texture.
|
||||
D3D12_RESOURCE_DESC reported{};
|
||||
slot<GetDescFn>(depth_texture, kResGetDesc)(depth_texture, &reported);
|
||||
CHECK(reported.Format == DXGI_FORMAT_R32G8X24_TYPELESS && reported.Width == 256,
|
||||
"GetDesc of the format-118 texture reports host format %d (want %d)", static_cast<int>(reported.Format),
|
||||
static_cast<int>(DXGI_FORMAT_R32G8X24_TYPELESS));
|
||||
|
||||
// 3. An unordered-access view on a depth-stencil texture: the descriptor gets a null view and
|
||||
// the call is logged as unimplemented. A view on an ordinary texture is not affected.
|
||||
void* depth_uav_texture = nullptr;
|
||||
const D3D12_RESOURCE_DESC depth_uav =
|
||||
texture(DXGI_FORMAT_R32G8X24_TYPELESS, depth | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
|
||||
hr = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &heap, D3D12_HEAP_FLAG_NONE, &depth_uav,
|
||||
D3D12_RESOURCE_STATE_DEPTH_WRITE, nullptr,
|
||||
__uuidof(ID3D12Resource), &depth_uav_texture);
|
||||
D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc{};
|
||||
uav_desc.Format = DXGI_FORMAT_R32_FLOAT;
|
||||
uav_desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
|
||||
bool depth_uav_exercised = false;
|
||||
if (hr == S_OK && depth_uav_texture) {
|
||||
slot<CreateUavFn>(dev, kDevCreateUnorderedAccessView)(dev, depth_uav_texture, nullptr, &uav_desc,
|
||||
{views.ptr + 2 * kXboxViewSize});
|
||||
CHECK(true, "CreateUnorderedAccessView(R32_FLOAT on a depth-stencil texture) returned");
|
||||
depth_uav_exercised = true;
|
||||
} else {
|
||||
// A host that refuses the resource itself cannot reach the view; say so instead of passing silently.
|
||||
std::printf("note: host refused a depth-stencil texture with unordered access (hr=0x%08lx); the view check did not run\n",
|
||||
static_cast<unsigned long>(hr));
|
||||
}
|
||||
|
||||
void* colour_texture = nullptr;
|
||||
const D3D12_RESOURCE_DESC colour_uav = texture(DXGI_FORMAT_R32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
|
||||
hr = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &heap, D3D12_HEAP_FLAG_NONE, &colour_uav,
|
||||
D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr,
|
||||
__uuidof(ID3D12Resource), &colour_texture);
|
||||
CHECK(hr == S_OK && colour_texture, "CreateCommittedResource(R32_FLOAT, unordered access) hr=0x%08lx",
|
||||
static_cast<unsigned long>(hr));
|
||||
if (colour_texture) {
|
||||
slot<CreateUavFn>(dev, kDevCreateUnorderedAccessView)(dev, colour_texture, nullptr, &uav_desc,
|
||||
{views.ptr + 3 * kXboxViewSize});
|
||||
}
|
||||
|
||||
const std::string log = read_log();
|
||||
if (!log.empty()) {
|
||||
const size_t stubs = count_of(log, "CreateUnorderedAccessView(depth-stencil resource)") - stubs_before;
|
||||
CHECK(stubs == (depth_uav_exercised ? 1u : 0u),
|
||||
"the depth-stencil view is logged as unimplemented once and the ordinary view is not (logged %zu time(s))", stubs);
|
||||
CHECK(log.find("console-only format 118") != std::string::npos, "the first translation of format 118 is logged");
|
||||
} else {
|
||||
std::printf("note: no BX_LOG_FILE; the log checks did not run\n");
|
||||
}
|
||||
|
||||
if (colour_texture) slot<ReleaseFn>(colour_texture, kRelease)(colour_texture);
|
||||
if (depth_uav_texture) slot<ReleaseFn>(depth_uav_texture, kRelease)(depth_uav_texture);
|
||||
slot<ReleaseFn>(view_heap, kRelease)(view_heap);
|
||||
slot<ReleaseFn>(dsv_heap, kRelease)(dsv_heap);
|
||||
slot<ReleaseFn>(depth_texture, kRelease)(depth_texture);
|
||||
slot<ReleaseFn>(dev, kRelease)(dev);
|
||||
|
||||
std::printf("%s: test_d3d12_console_formats (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS", g_checks - g_failed,
|
||||
g_checks);
|
||||
return g_failed ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_d3d12_frame_statistics_x main.cpp)
|
||||
target_compile_definitions(test_d3d12_frame_statistics_x PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_frame_statistics_x PRIVATE d3d12_xs kernel32 uuid)
|
||||
@@ -0,0 +1,228 @@
|
||||
/*
|
||||
* GetFrameStatisticsX (Xbox device table slot 81), against the authorized GDK documentation:
|
||||
* GetFrameStatisticsX(Token, TypeSet, pCount, pStatistics) returns S_OK when one or more sets of
|
||||
* the requested types are available (written subject to list space, *pCount updated to the
|
||||
* number written), S_FALSE when none is available yet, and E_INVALIDARG for unknown frame
|
||||
* pipeline tokens, invalid type sets and invalid list arrangements. The runtime keeps the last
|
||||
* 17 frames. Times are QueryPerformanceCounter values.
|
||||
* D3D12XBOX_FRAME_STATISTICS is written out below from the header's field list: a 32-bit Type,
|
||||
* then (8 bytes in) a union whose largest members are 48 bytes. Tokens come from WaitFrameEventX
|
||||
* on the ORIGIN event; PresentX gets the token through its plane parameters.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
|
||||
void** ppv);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr UINT kTypeFrameEvent = 0x2, kTypeRender = 0x100, kTypePresent = 0x1000;
|
||||
constexpr UINT kOrigin = 0;
|
||||
|
||||
struct FrameEventStatistics {
|
||||
UINT32 EventType;
|
||||
UINT64 WaitCallTime;
|
||||
UINT64 SignalTime;
|
||||
UINT64 WaitReturnTime;
|
||||
UINT32 IntervalOffsetInMicroseconds;
|
||||
UINT32 SignalFlags;
|
||||
UINT32 StatisticsFlags;
|
||||
};
|
||||
struct PresentStatistics {
|
||||
UINT8 PlaneIndex;
|
||||
UINT8 PlaneCount;
|
||||
UINT8 ViewCount;
|
||||
UINT64 PresentCallTime;
|
||||
UINT64 PresentQueueTime;
|
||||
UINT64 PresentReturnTime;
|
||||
UINT64 GPUProcessTime;
|
||||
UINT8 QueuedFrameCount;
|
||||
UINT16 PlaneSwapMask;
|
||||
UINT32 Flags;
|
||||
};
|
||||
struct FrameStatistics {
|
||||
UINT32 Type;
|
||||
union {
|
||||
FrameEventStatistics Event;
|
||||
PresentStatistics Present;
|
||||
UINT8 Bytes[48];
|
||||
};
|
||||
};
|
||||
static_assert(sizeof(FrameStatistics) == 56 && offsetof(FrameStatistics, Event) == 8, "D3D12XBOX_FRAME_STATISTICS");
|
||||
|
||||
struct PlaneParameters { // D3D12XBOX_PRESENT_PLANE_PARAMETERS
|
||||
UINT64 Token;
|
||||
UINT ResourceCount;
|
||||
void** ppResources;
|
||||
D3D12_RECT* pSrcViewRects;
|
||||
void* pDestPlacementBase;
|
||||
UINT ColorSpace;
|
||||
UINT ScaleFilter;
|
||||
UINT ExtendedDescCount;
|
||||
void* pExtendedDescs;
|
||||
UINT Flags;
|
||||
};
|
||||
|
||||
constexpr int kRelease = 2, kDevCreateCommandQueue = 8, kDevCreateCommittedResource = 27;
|
||||
constexpr int kDevSetFrameIntervalX = 78, kDevScheduleFrameEventX = 79, kDevWaitFrameEventX = 80;
|
||||
constexpr int kDevGetFrameStatisticsX = 81, kQueuePresentX = 32;
|
||||
|
||||
template <typename Fn>
|
||||
Fn slot(void* object, int index) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
|
||||
}
|
||||
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateQueueFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_COMMAND_QUEUE_DESC*, REFIID, void**);
|
||||
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
|
||||
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, REFIID, void**);
|
||||
using SetIntervalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT, UINT, UINT);
|
||||
using ScheduleFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, UINT, const void*, UINT);
|
||||
using WaitFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, UINT, const void*, UINT, UINT64*);
|
||||
using StatsFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, UINT, UINT*, FrameStatistics*);
|
||||
using PresentFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const PlaneParameters*, const void*);
|
||||
|
||||
int g_failed = 0, g_checks = 0;
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
++g_checks; \
|
||||
if (!(cond)) { \
|
||||
++g_failed; \
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_frame_statistics_x:%d: ", __LINE__); \
|
||||
std::fprintf(stderr, __VA_ARGS__); \
|
||||
std::fprintf(stderr, "\n"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
alignas(8) unsigned char title_params[80] = {};
|
||||
const UINT version = 0x20004;
|
||||
std::memcpy(title_params, &version, sizeof(version));
|
||||
void* dev = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
|
||||
if (hr == E_NOINTERFACE) {
|
||||
std::printf("SKIP: test_d3d12_frame_statistics_x: host lacks the Xbox-layout device interface\n");
|
||||
return 77;
|
||||
}
|
||||
if (FAILED(hr) || !dev) {
|
||||
std::fprintf(stderr, "FAIL: device creation hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
auto stats = slot<StatsFn>(dev, kDevGetFrameStatisticsX);
|
||||
FrameStatistics out[4]{};
|
||||
UINT count = 4;
|
||||
|
||||
// Invalid arrangements, type sets and tokens.
|
||||
CHECK(stats(dev, 1, kTypeFrameEvent, nullptr, out) == E_INVALIDARG, "null pCount");
|
||||
CHECK(stats(dev, 1, 0, &count, out) == E_INVALIDARG, "empty type set");
|
||||
count = 4;
|
||||
CHECK(stats(dev, 1, 0x8, &count, out) == E_INVALIDARG, "unknown type bit");
|
||||
count = 4;
|
||||
CHECK(stats(dev, 1, kTypeFrameEvent, &count, nullptr) == E_INVALIDARG, "entries but no list");
|
||||
count = 4;
|
||||
CHECK(stats(dev, 0, kTypeFrameEvent, &count, out) == E_INVALIDARG, "token 0");
|
||||
count = 4;
|
||||
CHECK(stats(dev, 1ull << 40, kTypeFrameEvent, &count, out) == E_INVALIDARG, "token never issued");
|
||||
|
||||
// One frame: the ORIGIN event gives a token.
|
||||
CHECK(slot<SetIntervalFn>(dev, kDevSetFrameIntervalX)(dev, nullptr, 16667, 1, 0) == S_OK, "SetFrameIntervalX");
|
||||
CHECK(slot<ScheduleFn>(dev, kDevScheduleFrameEventX)(dev, kOrigin, 0, nullptr, 0) == S_OK, "ScheduleFrameEventX");
|
||||
auto wait = slot<WaitFn>(dev, kDevWaitFrameEventX);
|
||||
UINT64 token = 0;
|
||||
hr = wait(dev, kOrigin, 2000, nullptr, 0, &token);
|
||||
CHECK(hr == S_OK && token != 0, "WaitFrameEventX(ORIGIN) hr=0x%08lx token=%llu", static_cast<unsigned long>(hr),
|
||||
static_cast<unsigned long long>(token));
|
||||
|
||||
count = 4;
|
||||
hr = stats(dev, token, kTypeFrameEvent, &count, out);
|
||||
CHECK(hr == S_OK && count == 1, "FRAME_EVENT: hr=0x%08lx count=%u", static_cast<unsigned long>(hr), count);
|
||||
if (hr == S_OK && count == 1) {
|
||||
const FrameEventStatistics& e = out[0].Event;
|
||||
CHECK(out[0].Type == kTypeFrameEvent && e.EventType == kOrigin, "FRAME_EVENT type %u event %u", out[0].Type,
|
||||
e.EventType);
|
||||
CHECK(e.SignalTime && e.WaitCallTime && e.WaitReturnTime >= e.SignalTime && e.WaitReturnTime >= e.WaitCallTime,
|
||||
"FRAME_EVENT times wait=%llu signal=%llu return=%llu", static_cast<unsigned long long>(e.WaitCallTime),
|
||||
static_cast<unsigned long long>(e.SignalTime), static_cast<unsigned long long>(e.WaitReturnTime));
|
||||
LARGE_INTEGER now;
|
||||
QueryPerformanceCounter(&now);
|
||||
CHECK(e.WaitReturnTime <= static_cast<UINT64>(now.QuadPart), "times are QueryPerformanceCounter values");
|
||||
}
|
||||
count = 4;
|
||||
CHECK(stats(dev, token, kTypePresent, &count, out) == S_FALSE && count == 0, "PRESENT before PresentX: S_FALSE");
|
||||
count = 4;
|
||||
CHECK(stats(dev, token, kTypeRender, &count, out) == S_FALSE && count == 0, "RENDER (no host source): S_FALSE");
|
||||
|
||||
// PresentX with that token records the present.
|
||||
D3D12_COMMAND_QUEUE_DESC queue_desc{};
|
||||
queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
|
||||
void* queue = nullptr;
|
||||
hr = slot<CreateQueueFn>(dev, kDevCreateCommandQueue)(dev, &queue_desc, __uuidof(ID3D12CommandQueue), &queue);
|
||||
CHECK(hr == S_OK && queue, "CreateCommandQueue hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
D3D12_RESOURCE_DESC rt{};
|
||||
rt.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
rt.Width = 64;
|
||||
rt.Height = 64;
|
||||
rt.DepthOrArraySize = 1;
|
||||
rt.MipLevels = 1;
|
||||
rt.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
rt.SampleDesc.Count = 1;
|
||||
rt.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
|
||||
void* target = nullptr;
|
||||
hr = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &heap, D3D12_HEAP_FLAG_NONE, &rt,
|
||||
D3D12_RESOURCE_STATE_COMMON, nullptr,
|
||||
__uuidof(ID3D12Resource), &target);
|
||||
CHECK(hr == S_OK && target, "render target hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (queue && target) {
|
||||
PlaneParameters plane{};
|
||||
plane.Token = token;
|
||||
plane.ResourceCount = 1;
|
||||
plane.ppResources = ⌖
|
||||
slot<PresentFn>(queue, kQueuePresentX)(queue, 1, &plane, nullptr);
|
||||
count = 4;
|
||||
hr = stats(dev, token, kTypeFrameEvent | kTypePresent, &count, out);
|
||||
CHECK(hr == S_OK && count == 2, "FRAME_EVENT|PRESENT after PresentX: hr=0x%08lx count=%u",
|
||||
static_cast<unsigned long>(hr), count);
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
if (out[i].Type != kTypePresent) continue;
|
||||
const PresentStatistics& p = out[i].Present;
|
||||
CHECK(p.PresentCallTime && p.PresentReturnTime >= p.PresentCallTime && p.PlaneCount == 1,
|
||||
"PRESENT call=%llu return=%llu planes=%u", static_cast<unsigned long long>(p.PresentCallTime),
|
||||
static_cast<unsigned long long>(p.PresentReturnTime), p.PlaneCount);
|
||||
}
|
||||
// A size query (no list) reports how many are available; a short list gets what fits.
|
||||
count = 0;
|
||||
CHECK(stats(dev, token, kTypeFrameEvent | kTypePresent, &count, nullptr) == S_OK && count == 2, "size query: %u",
|
||||
count);
|
||||
count = 1;
|
||||
CHECK(stats(dev, token, kTypeFrameEvent | kTypePresent, &count, out) == S_OK && count == 1, "short list: %u",
|
||||
count);
|
||||
}
|
||||
|
||||
// Seventeen frames later the token has no statistics left.
|
||||
UINT64 later = token;
|
||||
for (int i = 0; i < 18; ++i) wait(dev, kOrigin, 2000, nullptr, 0, &later);
|
||||
count = 4;
|
||||
CHECK(stats(dev, token, kTypeFrameEvent, &count, out) == S_FALSE && count == 0, "token 18 frames old: S_FALSE");
|
||||
count = 4;
|
||||
CHECK(stats(dev, later, kTypeFrameEvent, &count, out) == S_OK && count == 1, "latest token: S_OK");
|
||||
|
||||
if (target) slot<ReleaseFn>(target, kRelease)(target);
|
||||
if (queue) slot<ReleaseFn>(queue, kRelease)(queue);
|
||||
slot<ReleaseFn>(dev, kRelease)(dev);
|
||||
if (g_failed) {
|
||||
std::printf("FAIL: test_d3d12_frame_statistics_x (%d of %d checks failed)\n", g_failed, g_checks);
|
||||
return 1;
|
||||
}
|
||||
std::printf("PASS: test_d3d12_frame_statistics_x (%d checks)\n", g_checks);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
# A stand-in for the GDK's XG library with known answers, built as xg_xs.dll in its own folder so
|
||||
# it never replaces the xg_xs shim beside the other DLLs. The test loads it by full path.
|
||||
add_library(test_gdk_xg_fake SHARED fake_xg.cpp)
|
||||
# Its import library goes to its own folder too, or it would replace the xg_xs shim's.
|
||||
set_target_properties(test_gdk_xg_fake PROPERTIES OUTPUT_NAME xg_xs PREFIX ""
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/gdk_xg_fake"
|
||||
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/gdk_xg_fake_lib")
|
||||
target_link_libraries(test_gdk_xg_fake PRIVATE kernel32)
|
||||
|
||||
add_executable(test_d3d12_gdk_xg_sizes main.cpp)
|
||||
target_compile_definitions(test_d3d12_gdk_xg_sizes PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_gdk_xg_sizes PRIVATE d3d12_xs kernel32 uuid)
|
||||
add_dependencies(test_d3d12_gdk_xg_sizes test_gdk_xg_fake)
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* A stand-in for the GDK's XG library (xg_xs.dll) with answers the test can compute. It has the
|
||||
* documented shape the shim relies on (GDK xg_xs.h): the exports XGComputeTexture2DLayout (whose
|
||||
* presence marks Microsoft's library), XGCreateTextureComputer and XGEnableExclusiveLocking, and a
|
||||
* texture computer whose vtable starts AddRef, Release, GetResourceLayout, GetResourceSizeBytes,
|
||||
* GetResourceBaseAlignmentBytes. It is not Microsoft's code and computes no real layout.
|
||||
*
|
||||
* Its answer for a texture: size = Width * Height * DepthOrArraySize * 16 + (Layout & 0xFF) * 0x1000,
|
||||
* alignment = 0x10000 when the layout is 0x109 (a 64 KB mode), otherwise 0x1000.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace {
|
||||
|
||||
struct Computer;
|
||||
struct Vtbl {
|
||||
ULONG(__cdecl* AddRef)(Computer*);
|
||||
ULONG(__cdecl* Release)(Computer*);
|
||||
HRESULT(__cdecl* GetResourceLayout)(Computer*, void*);
|
||||
UINT64 (*GetResourceSizeBytes)(Computer*);
|
||||
UINT64 (*GetResourceBaseAlignmentBytes)(Computer*);
|
||||
};
|
||||
struct Computer {
|
||||
const Vtbl* vtbl;
|
||||
LONG refs;
|
||||
UINT64 size;
|
||||
UINT64 alignment;
|
||||
};
|
||||
|
||||
ULONG __cdecl add_ref(Computer* c) { return static_cast<ULONG>(InterlockedIncrement(&c->refs)); }
|
||||
ULONG __cdecl release(Computer* c) {
|
||||
const LONG left = InterlockedDecrement(&c->refs);
|
||||
if (!left) HeapFree(GetProcessHeap(), 0, c);
|
||||
return static_cast<ULONG>(left);
|
||||
}
|
||||
HRESULT __cdecl layout(Computer*, void*) { return E_NOTIMPL; }
|
||||
UINT64 size_bytes(Computer* c) { return c->size; }
|
||||
UINT64 alignment_bytes(Computer* c) { return c->alignment; }
|
||||
const Vtbl kVtbl = {add_ref, release, layout, size_bytes, alignment_bytes};
|
||||
|
||||
LONG g_locking = 0;
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" __declspec(dllexport) HRESULT __cdecl XGComputeTexture2DLayout(const void*, void*) { return E_NOTIMPL; }
|
||||
|
||||
extern "C" __declspec(dllexport) HRESULT __cdecl XGCreateTextureComputer(const D3D12_RESOURCE_DESC* desc, Computer** out) {
|
||||
if (!desc || !out) return E_INVALIDARG;
|
||||
auto* c = static_cast<Computer*>(HeapAlloc(GetProcessHeap(), 0, sizeof(Computer)));
|
||||
if (!c) return E_OUTOFMEMORY;
|
||||
const UINT layout_value = static_cast<UINT>(desc->Layout);
|
||||
c->vtbl = &kVtbl;
|
||||
c->refs = 1;
|
||||
c->size = desc->Width * desc->Height * desc->DepthOrArraySize * 16ull + (layout_value & 0xFF) * 0x1000ull;
|
||||
c->alignment = layout_value == 0x109 ? 0x10000 : 0x1000;
|
||||
*out = c;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
extern "C" __declspec(dllexport) void __cdecl XGEnableExclusiveLocking(BOOL enabled) { g_locking = enabled ? 1 : 0; }
|
||||
|
||||
// For the test: whether the shim enabled XG's locking.
|
||||
extern "C" __declspec(dllexport) LONG __cdecl FakeXGLockingEnabled() { return g_locking; }
|
||||
@@ -0,0 +1,125 @@
|
||||
/*
|
||||
* GetResourceAllocationInfo for console texture layouts, answered by the GDK's XG library.
|
||||
*
|
||||
* Console textures carry a tiled layout (D3D12XBOX_TEXTURE_LAYOUT, 0x100 | swizzle mode), and a
|
||||
* title sizes its loads and placements from the allocation size the device reports. When the
|
||||
* GDK's XG library is the loaded xg_xs.dll, d3d12_xs answers console layouts with XG's size and
|
||||
* base alignment, and everything else with the host's answer; several descriptions are laid out
|
||||
* one after another at their alignments (Direct3D 12 rules), the total aligned to the largest.
|
||||
*
|
||||
* The library here is a stand-in with answers this test computes (fake_xg.cpp), not Microsoft's.
|
||||
* The test also checks that the shim enabled XG's exclusive locking at device creation.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
|
||||
void** ppv);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kRelease = 2, kDevGetResourceAllocationInfo = 25;
|
||||
int g_failed = 0;
|
||||
|
||||
template <typename Fn>
|
||||
Fn slot(void* object, int index) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
|
||||
}
|
||||
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
using AllocationInfoFn = D3D12_RESOURCE_ALLOCATION_INFO(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_RESOURCE_DESC*);
|
||||
|
||||
D3D12_RESOURCE_DESC texture(UINT64 w, UINT h, UINT16 slices, DXGI_FORMAT format, UINT layout) {
|
||||
D3D12_RESOURCE_DESC d{};
|
||||
d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
d.Width = w;
|
||||
d.Height = h;
|
||||
d.DepthOrArraySize = slices;
|
||||
d.MipLevels = 1;
|
||||
d.Format = format;
|
||||
d.SampleDesc.Count = 1;
|
||||
d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(layout);
|
||||
return d;
|
||||
}
|
||||
|
||||
// The stand-in library's answer (fake_xg.cpp), written out independently here.
|
||||
UINT64 fake_size(const D3D12_RESOURCE_DESC& d) {
|
||||
return d.Width * d.Height * d.DepthOrArraySize * 16ull + (static_cast<UINT>(d.Layout) & 0xFF) * 0x1000ull;
|
||||
}
|
||||
UINT64 fake_alignment(const D3D12_RESOURCE_DESC& d) { return static_cast<UINT>(d.Layout) == 0x109 ? 0x10000 : 0x1000; }
|
||||
|
||||
void expect(const char* what, UINT64 got, UINT64 want) {
|
||||
std::printf("%-52s got=0x%llx expected=0x%llx\n", what, static_cast<unsigned long long>(got),
|
||||
static_cast<unsigned long long>(want));
|
||||
if (got != want) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_gdk_xg_sizes: %s\n", what);
|
||||
++g_failed;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
// Load the stand-in as xg_xs.dll before the device exists, as bx-cli stages the GDK's.
|
||||
wchar_t path[MAX_PATH];
|
||||
const DWORD n = GetModuleFileNameW(nullptr, path, MAX_PATH);
|
||||
wchar_t* slash = n ? wcsrchr(path, L'\\') : nullptr;
|
||||
if (!slash || wcslen(path) + 32 >= MAX_PATH) return 1;
|
||||
wcscpy(slash + 1, L"gdk_xg_fake\\xg_xs.dll");
|
||||
HMODULE fake = LoadLibraryW(path);
|
||||
if (!fake) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_gdk_xg_sizes: the stand-in XG library did not load (error %lu)\n", GetLastError());
|
||||
return 1;
|
||||
}
|
||||
using LockingFn = LONG(__cdecl*)();
|
||||
auto locking = reinterpret_cast<LockingFn>(reinterpret_cast<void*>(GetProcAddress(fake, "FakeXGLockingEnabled")));
|
||||
|
||||
alignas(8) unsigned char title_params[80] = {};
|
||||
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
|
||||
std::memcpy(title_params, &version, sizeof(version));
|
||||
void* dev = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
|
||||
if (hr == E_NOINTERFACE) {
|
||||
std::printf("SKIP: test_d3d12_gdk_xg_sizes: host lacks the Xbox-layout device interface\n");
|
||||
return 77;
|
||||
}
|
||||
if (FAILED(hr) || !dev) {
|
||||
std::fprintf(stderr, "FAIL: device creation hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
expect("XG exclusive locking enabled at device creation", locking ? static_cast<UINT64>(locking()) : 0, 1);
|
||||
|
||||
const auto info = slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo);
|
||||
|
||||
// One console texture: XG's size and alignment.
|
||||
const D3D12_RESOURCE_DESC tiled = texture(128, 4, 1, DXGI_FORMAT_R16G16B16A16_UNORM, 0x105);
|
||||
D3D12_RESOURCE_ALLOCATION_INFO got = info(dev, 0, 1, &tiled);
|
||||
expect("128x4 RGBA16 layout 0x105: size", got.SizeInBytes, fake_size(tiled));
|
||||
expect("128x4 RGBA16 layout 0x105: alignment", got.Alignment, fake_alignment(tiled));
|
||||
|
||||
const D3D12_RESOURCE_DESC big = texture(256, 256, 6, DXGI_FORMAT_BC7_UNORM, 0x109);
|
||||
got = info(dev, 0, 1, &big);
|
||||
expect("256x256x6 BC7 layout 0x109: size", got.SizeInBytes, fake_size(big));
|
||||
expect("256x256x6 BC7 layout 0x109: alignment", got.Alignment, fake_alignment(big));
|
||||
|
||||
// A PC-layout texture keeps the host's answer.
|
||||
const D3D12_RESOURCE_DESC pc = texture(256, 256, 1, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_TEXTURE_LAYOUT_UNKNOWN);
|
||||
const D3D12_RESOURCE_ALLOCATION_INFO host = info(dev, 0, 1, &pc);
|
||||
expect("PC-layout texture: host size is answered", host.SizeInBytes != 0 && host.SizeInBytes != UINT64_MAX, 1);
|
||||
|
||||
// Console then PC texture: each at its alignment, in order; total alignment the largest.
|
||||
const D3D12_RESOURCE_DESC pair[2] = {tiled, pc};
|
||||
got = info(dev, 0, 2, pair);
|
||||
const UINT64 second = (fake_size(tiled) + host.Alignment - 1) / host.Alignment * host.Alignment;
|
||||
expect("console + PC texture: total size", got.SizeInBytes, second + host.SizeInBytes);
|
||||
expect("console + PC texture: total alignment", got.Alignment,
|
||||
host.Alignment > fake_alignment(tiled) ? host.Alignment : fake_alignment(tiled));
|
||||
|
||||
slot<ReleaseFn>(dev, kRelease)(dev);
|
||||
if (g_failed) return 1;
|
||||
std::puts("PASS: test_d3d12_gdk_xg_sizes");
|
||||
return 0;
|
||||
}
|
||||
@@ -31,16 +31,12 @@ __declspec(dllimport) VOID WINAPI XMemFree(PVOID address, uint64_t attributes);
|
||||
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR count, PULONG_PTR pages);
|
||||
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR pages);
|
||||
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID base, ULONG_PTR count, PULONG_PTR pages);
|
||||
__declspec(dllimport) BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size);
|
||||
__declspec(dllimport) BOOL WINAPI XMemGetWorkingSetStatistics(DWORD flags, PVOID statistics);
|
||||
}
|
||||
|
||||
struct bx_xmem_stats_t {
|
||||
uint64_t title_limit_bytes;
|
||||
uint64_t committed_virtual_bytes;
|
||||
uint64_t allocated_physical_bytes;
|
||||
uint64_t peak_committed_bytes;
|
||||
};
|
||||
static_assert(sizeof(bx_xmem_stats_t) == 32, "xmem stats struct is 32 bytes");
|
||||
/* XMEM_WORKING_SET_TITLE; XMEM_WORKING_SET_STATISTICS is 120 bytes on x64 (authorized GDK header). */
|
||||
constexpr DWORD kXMemWorkingSetTitle = 0x20000001;
|
||||
constexpr size_t kXMemWorkingSetStatisticsSize = 120;
|
||||
|
||||
/* D3D12XboxCreateDevice requires a D3D12XBOX_CREATE_DEVICE_PARAMETERS block (80 bytes on Xbox
|
||||
Series); a zeroed one asks for defaults. Only its Version field is read by the shim. */
|
||||
@@ -515,8 +511,8 @@ void check_graphics_xmem_pairing(ID3D12Device* device, uint64_t cap) {
|
||||
return;
|
||||
}
|
||||
|
||||
bx_xmem_stats_t stats{};
|
||||
check(XMemGetWorkingSetStatistics(&stats, sizeof(stats)) != 0, "pairing: xmem stats readable");
|
||||
alignas(8) unsigned char stats[kXMemWorkingSetStatisticsSize]{};
|
||||
check(XMemGetWorkingSetStatistics(kXMemWorkingSetTitle, stats) != 0, "pairing: xmem stats readable");
|
||||
|
||||
/* 300 MiB heap + 300 MiB xmem = 600 MiB > 512 MiB cap. */
|
||||
void* too_much = XMemAlloc(300ull << 20, 0);
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_d3d12_rect_list main.cpp)
|
||||
target_compile_definitions(test_d3d12_rect_list PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_rect_list PRIVATE d3d12_xs kernel32 uuid)
|
||||
@@ -0,0 +1,437 @@
|
||||
/*
|
||||
* Conformance test: console rectangle lists.
|
||||
*
|
||||
* Contract (Xbox Series GDK d3d12_xs.h): D3D_PRIMITIVE_TOPOLOGY_RECTLIST = 17 is an Xbox
|
||||
* extension that takes three vertices per rectangle, and a pipeline that draws it has topology
|
||||
* type D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT = 19. The fourth corner is v0 + v2 - v1, and
|
||||
* attributes are extended the same way (the convention of rectangle lists since Direct3D 9 on
|
||||
* Xbox; recorded here as the contract the shim implements).
|
||||
*
|
||||
* PC Direct3D 12 has neither value. The test renders into a 128x128 target through an
|
||||
* Xbox-layout device and reads the pixels back:
|
||||
* - top-left quadrant: one rectangle with three differently coloured vertices. Every pixel must
|
||||
* be covered (a single triangle covers half), and the corner that has no vertex of its own
|
||||
* must show v0 + v2 - v1;
|
||||
* - bottom-left quadrant: two rectangles in one draw that starts at a non-zero first vertex;
|
||||
* - top-right quadrant: an ordinary triangle list afterwards, which must still work;
|
||||
* - bottom-right quadrant: nothing drawn, including by an indexed rectangle-list draw, which
|
||||
* is not emulated and must be logged as unimplemented.
|
||||
*
|
||||
* Slots (Xbox-layout tables, ADR 0009): 2 Release; device 9 CreateCommandAllocator,
|
||||
* 10 CreateGraphicsPipelineState, 14 CreateDescriptorHeap, 16 CreateRootSignature,
|
||||
* 20 CreateRenderTargetView, 27 CreateCommittedResource, 36 CreateFence, 48 CreateCommandQueueX,
|
||||
* 73 CreateCommandListX; resource 8 Map, 11 GetGPUVirtualAddress; descriptor heap 9
|
||||
* GetCPUDescriptorHandleForHeapStart; command list 9 Close, 12 DrawInstanced,
|
||||
* 13 DrawIndexedInstanced, 16 CopyTextureRegion, 20 IASetPrimitiveTopology, 21 RSSetViewports,
|
||||
* 22 RSSetScissorRects, 25 SetPipelineState, 26 ResourceBarrier, 34 SetGraphicsRootSignature,
|
||||
* 48 IASetVertexBuffers, 50 OMSetRenderTargets, 52 ClearRenderTargetView; queue 10
|
||||
* ExecuteCommandLists, 16 Signal; fence 9 SetEventOnCompletion.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
|
||||
void** ppv);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kRelease = 2;
|
||||
constexpr int kDevCreateCommandAllocator = 9, kDevCreateGraphicsPipelineState = 10, kDevCreateDescriptorHeap = 14;
|
||||
constexpr int kDevCreateRootSignature = 16, kDevCreateRenderTargetView = 20, kDevCreateCommittedResource = 27;
|
||||
constexpr int kDevCreateFence = 36, kDevCreateCommandQueueX = 48, kDevCreateCommandListX = 73;
|
||||
constexpr int kResMap = 8, kResGetGpuVirtualAddress = 11, kHeapGetCpuStart = 9;
|
||||
constexpr int kListClose = 9, kListDrawInstanced = 12, kListDrawIndexedInstanced = 13, kListCopyTextureRegion = 16;
|
||||
constexpr int kListIASetPrimitiveTopology = 20, kListRSSetViewports = 21, kListRSSetScissorRects = 22;
|
||||
constexpr int kListSetPipelineState = 25, kListResourceBarrier = 26, kListSetGraphicsRootSignature = 34;
|
||||
constexpr int kListIASetVertexBuffers = 48, kListOMSetRenderTargets = 50, kListClearRenderTargetView = 52;
|
||||
constexpr int kQueueExecuteCommandLists = 10, kQueueSignal = 16, kFenceSetEventOnCompletion = 9;
|
||||
|
||||
constexpr auto kRectList = static_cast<D3D12_PRIMITIVE_TOPOLOGY>(17); // D3D_PRIMITIVE_TOPOLOGY_RECTLIST
|
||||
constexpr auto kTopologyTypeRect = static_cast<D3D12_PRIMITIVE_TOPOLOGY_TYPE>(19); // D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT
|
||||
constexpr UINT kSize = 128;
|
||||
|
||||
int g_checks = 0;
|
||||
int g_failed = 0;
|
||||
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
++g_checks; \
|
||||
if (!(cond)) { \
|
||||
++g_failed; \
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_rect_list:%d: ", __LINE__); \
|
||||
std::fprintf(stderr, __VA_ARGS__); \
|
||||
std::fprintf(stderr, "\n"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
template <typename Fn>
|
||||
Fn slot(void* object, int index) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
|
||||
}
|
||||
|
||||
struct QueueDescX {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
UINT Flags, EngineOrPipeIndex, QueueIndex;
|
||||
};
|
||||
struct ListDescX {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
UINT Flags, NodeMask, ResourceBarrierBatchSize;
|
||||
};
|
||||
|
||||
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const QueueDescX*, REFIID, void**);
|
||||
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
|
||||
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
|
||||
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
|
||||
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, REFIID, void**);
|
||||
using CreateFenceFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, D3D12_FENCE_FLAGS, REFIID, void**);
|
||||
using CreateHeapFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_DESCRIPTOR_HEAP_DESC*, REFIID, void**);
|
||||
using HeapStartFn = D3D12_CPU_DESCRIPTOR_HANDLE(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateRootFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const void*, SIZE_T, REFIID, void**);
|
||||
using CreateRtvFn = void(STDMETHODCALLTYPE*)(void*, void*, const D3D12_RENDER_TARGET_VIEW_DESC*, D3D12_CPU_DESCRIPTOR_HANDLE);
|
||||
using CreatePsoFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_GRAPHICS_PIPELINE_STATE_DESC*, REFIID, void**);
|
||||
using MapFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RANGE*, void**);
|
||||
using GetGpuVaFn = D3D12_GPU_VIRTUAL_ADDRESS(STDMETHODCALLTYPE*)(void*);
|
||||
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
|
||||
using DrawFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, UINT, UINT);
|
||||
using DrawIndexedFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, UINT, INT, UINT);
|
||||
using CopyTextureFn = void(STDMETHODCALLTYPE*)(void*, const D3D12_TEXTURE_COPY_LOCATION*, UINT, UINT, UINT,
|
||||
const D3D12_TEXTURE_COPY_LOCATION*, const D3D12_BOX*);
|
||||
using TopologyFn = void(STDMETHODCALLTYPE*)(void*, D3D12_PRIMITIVE_TOPOLOGY);
|
||||
using ViewportsFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_VIEWPORT*);
|
||||
using ScissorsFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RECT*);
|
||||
using SetObjectFn = void(STDMETHODCALLTYPE*)(void*, void*);
|
||||
using BarrierFn = UINT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RESOURCE_BARRIER*);
|
||||
using SetVbFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_VERTEX_BUFFER_VIEW*);
|
||||
using SetTargetsFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_CPU_DESCRIPTOR_HANDLE*, BOOL,
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE*);
|
||||
using ClearFn = void(STDMETHODCALLTYPE*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, const FLOAT*, UINT, const D3D12_RECT*);
|
||||
using ExecuteFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
|
||||
using QueueSignalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64);
|
||||
using FenceEventFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, HANDLE);
|
||||
|
||||
using D3DCompileFn = HRESULT(WINAPI*)(LPCVOID, SIZE_T, LPCSTR, const void*, void*, LPCSTR, LPCSTR, UINT, UINT, ID3DBlob**,
|
||||
ID3DBlob**);
|
||||
using SerializeRootFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
|
||||
|
||||
const char kShader[] =
|
||||
"struct V { float4 pos : SV_Position; float4 col : COLOR; };\n"
|
||||
"V vs(float2 p : POSITION, float4 c : COLOR) { V o; o.pos = float4(p, 0.0f, 1.0f); o.col = c; return o; }\n"
|
||||
"float4 ps(V i) : SV_Target0 { return i.col; }\n";
|
||||
|
||||
ID3DBlob* compile(const char* entry, const char* target) {
|
||||
HMODULE compiler = LoadLibraryA("d3dcompiler_47.dll");
|
||||
auto fn = compiler ? reinterpret_cast<D3DCompileFn>(reinterpret_cast<void*>(GetProcAddress(compiler, "D3DCompile"))) : nullptr;
|
||||
if (!fn) return nullptr;
|
||||
ID3DBlob* code = nullptr;
|
||||
ID3DBlob* errors = nullptr;
|
||||
const HRESULT hr = fn(kShader, sizeof(kShader) - 1, "rect_list", nullptr, nullptr, entry, target, 0, 0, &code, &errors);
|
||||
if (FAILED(hr) && errors) std::fprintf(stderr, "D3DCompile(%s): %s\n", entry, static_cast<const char*>(errors->GetBufferPointer()));
|
||||
if (errors) errors->Release();
|
||||
return SUCCEEDED(hr) ? code : nullptr;
|
||||
}
|
||||
|
||||
struct Vertex {
|
||||
float x, y;
|
||||
float r, g, b, a;
|
||||
};
|
||||
|
||||
std::string read_log() {
|
||||
char path[MAX_PATH];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (n == 0 || n >= sizeof(path)) return {};
|
||||
std::string text;
|
||||
if (FILE* f = std::fopen(path, "rb")) {
|
||||
char buffer[4096];
|
||||
size_t got;
|
||||
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
|
||||
std::fclose(f);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
size_t count_of(const std::string& text, const char* needle) {
|
||||
size_t n = 0;
|
||||
for (size_t pos = text.find(needle); pos != std::string::npos; pos = text.find(needle, pos + 1)) ++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
struct Pixel {
|
||||
int r, g, b;
|
||||
};
|
||||
|
||||
const uint8_t* g_pixels = nullptr;
|
||||
constexpr UINT kRowPitch = kSize * 4; // 512: a multiple of the 256-byte texture data pitch alignment
|
||||
|
||||
Pixel at(UINT x, UINT y) {
|
||||
const uint8_t* p = g_pixels + static_cast<size_t>(y) * kRowPitch + static_cast<size_t>(x) * 4;
|
||||
return {p[0], p[1], p[2]};
|
||||
}
|
||||
|
||||
bool is_clear(Pixel p) { return p.r < 40 && p.g > 215 && p.b < 40; } // the clear colour is green
|
||||
|
||||
/* Pixels of the half-open quadrant [x0, x0+64) x [y0, y0+64) that still show the clear colour. */
|
||||
unsigned clear_pixels(UINT x0, UINT y0) {
|
||||
unsigned n = 0;
|
||||
for (UINT y = y0; y < y0 + kSize / 2; ++y) {
|
||||
for (UINT x = x0; x < x0 + kSize / 2; ++x) n += is_clear(at(x, y)) ? 1 : 0;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
alignas(8) unsigned char title_params[80] = {};
|
||||
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
|
||||
std::memcpy(title_params, &version, sizeof(version));
|
||||
void* dev = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
|
||||
if (hr == E_NOINTERFACE) {
|
||||
std::printf("SKIP: test_d3d12_rect_list: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
|
||||
return 77;
|
||||
}
|
||||
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!dev) return 1;
|
||||
|
||||
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
|
||||
auto serialize = d3d12 ? reinterpret_cast<SerializeRootFn>(
|
||||
reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")))
|
||||
: nullptr;
|
||||
ID3DBlob* vs = compile("vs", "vs_5_0");
|
||||
ID3DBlob* ps = compile("ps", "ps_5_0");
|
||||
if (!serialize || !vs || !ps) {
|
||||
std::printf("SKIP: test_d3d12_rect_list: no shader compiler or root-signature serializer in this bottle\n");
|
||||
return 77;
|
||||
}
|
||||
|
||||
// Queue, allocator, list, fence.
|
||||
const QueueDescX qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
void* queue = nullptr;
|
||||
void* allocator = nullptr;
|
||||
void* list = nullptr;
|
||||
void* fence = nullptr;
|
||||
slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue);
|
||||
slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
|
||||
&allocator);
|
||||
slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr, __uuidof(ID3D12GraphicsCommandList), &list);
|
||||
slot<CreateFenceFn>(dev, kDevCreateFence)(dev, 0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &fence);
|
||||
|
||||
// Root signature (input assembler only) and the pipeline, created with the console's
|
||||
// rectangle topology type.
|
||||
D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
|
||||
root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
|
||||
root_desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
|
||||
ID3DBlob* root_blob = nullptr;
|
||||
hr = serialize(&root_desc, &root_blob, nullptr);
|
||||
void* root = nullptr;
|
||||
if (SUCCEEDED(hr) && root_blob) {
|
||||
hr = slot<CreateRootFn>(dev, kDevCreateRootSignature)(dev, 0, root_blob->GetBufferPointer(), root_blob->GetBufferSize(),
|
||||
__uuidof(ID3D12RootSignature), &root);
|
||||
}
|
||||
CHECK(hr == S_OK && root, "CreateRootSignature hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
const D3D12_INPUT_ELEMENT_DESC elements[] = {
|
||||
{"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
|
||||
{"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 8, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
|
||||
};
|
||||
auto pipeline_desc = [&](D3D12_PRIMITIVE_TOPOLOGY_TYPE type) {
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC d{};
|
||||
d.pRootSignature = static_cast<ID3D12RootSignature*>(root);
|
||||
d.VS = {vs->GetBufferPointer(), vs->GetBufferSize()};
|
||||
d.PS = {ps->GetBufferPointer(), ps->GetBufferSize()};
|
||||
d.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
|
||||
d.SampleMask = UINT_MAX;
|
||||
d.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
|
||||
d.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
|
||||
d.RasterizerState.DepthClipEnable = TRUE;
|
||||
d.InputLayout = {elements, 2};
|
||||
d.PrimitiveTopologyType = type;
|
||||
d.NumRenderTargets = 1;
|
||||
d.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
d.SampleDesc.Count = 1;
|
||||
return d;
|
||||
};
|
||||
void* rect_pipeline = nullptr;
|
||||
void* triangle_pipeline = nullptr;
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC pd = pipeline_desc(kTopologyTypeRect);
|
||||
hr = slot<CreatePsoFn>(dev, kDevCreateGraphicsPipelineState)(dev, &pd, __uuidof(ID3D12PipelineState), &rect_pipeline);
|
||||
CHECK(hr == S_OK && rect_pipeline, "CreateGraphicsPipelineState(topology type RECT) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
pd = pipeline_desc(D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE);
|
||||
hr = slot<CreatePsoFn>(dev, kDevCreateGraphicsPipelineState)(dev, &pd, __uuidof(ID3D12PipelineState), &triangle_pipeline);
|
||||
CHECK(hr == S_OK && triangle_pipeline, "CreateGraphicsPipelineState(TRIANGLE) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
// Render target, its view, the readback buffer and the vertex buffer.
|
||||
D3D12_HEAP_PROPERTIES default_heap{}, upload_heap{}, readback_heap{};
|
||||
default_heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
upload_heap.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
readback_heap.Type = D3D12_HEAP_TYPE_READBACK;
|
||||
D3D12_RESOURCE_DESC target_desc{};
|
||||
target_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
target_desc.Width = kSize;
|
||||
target_desc.Height = kSize;
|
||||
target_desc.DepthOrArraySize = 1;
|
||||
target_desc.MipLevels = 1;
|
||||
target_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
target_desc.SampleDesc.Count = 1;
|
||||
target_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
|
||||
D3D12_RESOURCE_DESC buffer_desc{};
|
||||
buffer_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
buffer_desc.Height = 1;
|
||||
buffer_desc.DepthOrArraySize = 1;
|
||||
buffer_desc.MipLevels = 1;
|
||||
buffer_desc.SampleDesc.Count = 1;
|
||||
buffer_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
void* target = nullptr;
|
||||
void* readback = nullptr;
|
||||
void* vertices = nullptr;
|
||||
auto committed = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource);
|
||||
hr = committed(dev, &default_heap, D3D12_HEAP_FLAG_NONE, &target_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
|
||||
__uuidof(ID3D12Resource), &target);
|
||||
CHECK(hr == S_OK && target, "render target hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
buffer_desc.Width = static_cast<UINT64>(kRowPitch) * kSize;
|
||||
hr = committed(dev, &readback_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
|
||||
__uuidof(ID3D12Resource), &readback);
|
||||
CHECK(hr == S_OK && readback, "readback buffer hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
buffer_desc.Width = 64 * 1024;
|
||||
hr = committed(dev, &upload_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
__uuidof(ID3D12Resource), &vertices);
|
||||
CHECK(hr == S_OK && vertices, "vertex buffer hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
D3D12_DESCRIPTOR_HEAP_DESC heap_desc{};
|
||||
heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
|
||||
heap_desc.NumDescriptors = 1;
|
||||
void* rtv_heap = nullptr;
|
||||
hr = slot<CreateHeapFn>(dev, kDevCreateDescriptorHeap)(dev, &heap_desc, __uuidof(ID3D12DescriptorHeap), &rtv_heap);
|
||||
CHECK(hr == S_OK && rtv_heap, "RTV heap hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!queue || !allocator || !list || !fence || !root || !rect_pipeline || !triangle_pipeline || !target || !readback ||
|
||||
!vertices || !rtv_heap) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_rect_list: setup\n");
|
||||
return 1;
|
||||
}
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE rtv = slot<HeapStartFn>(rtv_heap, kHeapGetCpuStart)(rtv_heap);
|
||||
slot<CreateRtvFn>(dev, kDevCreateRenderTargetView)(dev, target, nullptr, rtv);
|
||||
|
||||
const float R[4] = {1, 0, 0, 1}, K[4] = {0, 0, 0, 1}, B[4] = {0, 0, 1, 1}, W[4] = {1, 1, 1, 1}, Y[4] = {1, 1, 0, 1};
|
||||
auto v = [](float x, float y, const float* c) { return Vertex{x, y, c[0], c[1], c[2], c[3]}; };
|
||||
const Vertex data[] = {
|
||||
// 0..2: one rectangle over the top-left quadrant; the corner (0, 1) has no vertex.
|
||||
v(-1, 1, R), v(-1, 0, K), v(0, 0, B),
|
||||
// 3..8: two rectangles that together cover the bottom-left quadrant.
|
||||
v(-1, 0, W), v(-1, -1, W), v(-0.5f, -1, W),
|
||||
v(-0.5f, 0, W), v(-0.5f, -1, W), v(0, -1, W),
|
||||
// 9..11: a triangle inside the top-right quadrant, drawn as a triangle list.
|
||||
v(0.1f, 0.9f, Y), v(0.9f, 0.9f, Y), v(0.1f, 0.1f, Y),
|
||||
};
|
||||
void* mapped = nullptr;
|
||||
hr = slot<MapFn>(vertices, kResMap)(vertices, 0, nullptr, &mapped);
|
||||
CHECK(hr == S_OK && mapped, "vertex buffer Map hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!mapped) return 1;
|
||||
std::memcpy(mapped, data, sizeof(data));
|
||||
const D3D12_VERTEX_BUFFER_VIEW vbv{slot<GetGpuVaFn>(vertices, kResGetGpuVirtualAddress)(vertices), sizeof(data), sizeof(Vertex)};
|
||||
|
||||
const std::string before = read_log();
|
||||
const size_t stubs_before = count_of(before, "DrawIndexedInstanced(rectangle list)");
|
||||
|
||||
// Record.
|
||||
const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(kSize), static_cast<float>(kSize), 0, 1};
|
||||
const D3D12_RECT scissor{0, 0, static_cast<LONG>(kSize), static_cast<LONG>(kSize)};
|
||||
const FLOAT green[4] = {0, 1, 0, 1};
|
||||
slot<SetObjectFn>(list, kListSetGraphicsRootSignature)(list, root);
|
||||
slot<SetTargetsFn>(list, kListOMSetRenderTargets)(list, 1, &rtv, FALSE, nullptr);
|
||||
slot<ViewportsFn>(list, kListRSSetViewports)(list, 1, &viewport);
|
||||
slot<ScissorsFn>(list, kListRSSetScissorRects)(list, 1, &scissor);
|
||||
slot<ClearFn>(list, kListClearRenderTargetView)(list, rtv, green, 0, nullptr);
|
||||
slot<SetVbFn>(list, kListIASetVertexBuffers)(list, 0, 1, &vbv);
|
||||
|
||||
slot<SetObjectFn>(list, kListSetPipelineState)(list, rect_pipeline);
|
||||
slot<TopologyFn>(list, kListIASetPrimitiveTopology)(list, kRectList);
|
||||
slot<DrawFn>(list, kListDrawInstanced)(list, 3, 1, 0, 0); // one rectangle
|
||||
slot<DrawFn>(list, kListDrawInstanced)(list, 6, 1, 3, 0); // two rectangles from vertex 3
|
||||
slot<DrawIndexedFn>(list, kListDrawIndexedInstanced)(list, 3, 1, 0, 0, 0); // not emulated: logged, draws nothing
|
||||
|
||||
slot<SetObjectFn>(list, kListSetPipelineState)(list, triangle_pipeline);
|
||||
slot<TopologyFn>(list, kListIASetPrimitiveTopology)(list, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
|
||||
slot<DrawFn>(list, kListDrawInstanced)(list, 3, 1, 9, 0); // an ordinary triangle afterwards
|
||||
|
||||
D3D12_RESOURCE_BARRIER to_copy{};
|
||||
to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
to_copy.Transition.pResource = static_cast<ID3D12Resource*>(target);
|
||||
to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
|
||||
to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
slot<BarrierFn>(list, kListResourceBarrier)(list, 1, &to_copy);
|
||||
D3D12_TEXTURE_COPY_LOCATION dst{};
|
||||
dst.pResource = static_cast<ID3D12Resource*>(readback);
|
||||
dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
|
||||
dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSize, kSize, 1, kRowPitch};
|
||||
D3D12_TEXTURE_COPY_LOCATION src{};
|
||||
src.pResource = static_cast<ID3D12Resource*>(target);
|
||||
src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
|
||||
slot<CopyTextureFn>(list, kListCopyTextureRegion)(list, &dst, 0, 0, 0, &src, nullptr);
|
||||
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "list Close");
|
||||
|
||||
void* lists[] = {list};
|
||||
slot<ExecuteFn>(queue, kQueueExecuteCommandLists)(queue, 1, lists);
|
||||
CHECK(slot<QueueSignalFn>(queue, kQueueSignal)(queue, fence, 1) == S_OK, "queue Signal");
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
CHECK(slot<FenceEventFn>(fence, kFenceSetEventOnCompletion)(fence, 1, done) == S_OK, "fence event");
|
||||
CHECK(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0, "GPU work completes");
|
||||
CloseHandle(done);
|
||||
|
||||
void* result = nullptr;
|
||||
hr = slot<MapFn>(readback, kResMap)(readback, 0, nullptr, &result);
|
||||
CHECK(hr == S_OK && result, "readback Map hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!result) return 1;
|
||||
g_pixels = static_cast<const uint8_t*>(result);
|
||||
|
||||
// Control: the clear reached the target and the untouched quadrant kept it.
|
||||
const unsigned half = kSize / 2, quadrant = half * half;
|
||||
CHECK(clear_pixels(half, half) == quadrant, "bottom-right quadrant: %u of %u pixels show the clear colour", clear_pixels(half, half),
|
||||
quadrant);
|
||||
|
||||
// Top-left: the whole rectangle is covered, and the fourth corner is v0 + v2 - v1.
|
||||
CHECK(clear_pixels(0, 0) == 0, "top-left rectangle: %u pixel(s) are not covered (a single triangle leaves about %u)",
|
||||
clear_pixels(0, 0), quadrant / 2);
|
||||
Pixel p = at(2, 2);
|
||||
CHECK(p.r > 200 && p.g < 40 && p.b < 40, "corner v0 is red: (%d, %d, %d)", p.r, p.g, p.b);
|
||||
p = at(2, half - 3);
|
||||
CHECK(p.r < 40 && p.g < 40 && p.b < 40, "corner v1 is black: (%d, %d, %d)", p.r, p.g, p.b);
|
||||
p = at(half - 3, half - 3);
|
||||
CHECK(p.r < 40 && p.g < 40 && p.b > 200, "corner v2 is blue: (%d, %d, %d)", p.r, p.g, p.b);
|
||||
p = at(half - 3, 2);
|
||||
CHECK(p.r > 200 && p.g < 40 && p.b > 200, "the fourth corner is v0 + v2 - v1 = magenta: (%d, %d, %d)", p.r, p.g, p.b);
|
||||
|
||||
// Bottom-left: two rectangles from a non-zero first vertex cover the quadrant in white.
|
||||
CHECK(clear_pixels(0, half) == 0, "bottom-left (two rectangles in one draw): %u pixel(s) are not covered", clear_pixels(0, half));
|
||||
p = at(half - 3, half + 3);
|
||||
CHECK(p.r > 215 && p.g > 215 && p.b > 215, "second rectangle's fourth corner is white: (%d, %d, %d)", p.r, p.g, p.b);
|
||||
|
||||
// Top-right: the triangle list afterwards draws a triangle, and only a triangle.
|
||||
p = at(half + 13, 13); // near (0.2, 0.8): inside
|
||||
CHECK(p.r > 215 && p.g > 215 && p.b < 40, "the triangle drawn afterwards is yellow inside: (%d, %d, %d)", p.r, p.g, p.b);
|
||||
p = at(kSize - 8, half - 8); // near (0.88, 0.12): outside the triangle
|
||||
CHECK(is_clear(p), "the triangle list is not turned into a rectangle: (%d, %d, %d)", p.r, p.g, p.b);
|
||||
|
||||
const std::string after = read_log();
|
||||
if (!after.empty()) {
|
||||
CHECK(count_of(after, "DrawIndexedInstanced(rectangle list)") - stubs_before == 1,
|
||||
"the indexed rectangle-list draw is logged as unimplemented once (logged %zu time(s))",
|
||||
count_of(after, "DrawIndexedInstanced(rectangle list)") - stubs_before);
|
||||
} else {
|
||||
std::printf("note: no BX_LOG_FILE; the log check did not run\n");
|
||||
}
|
||||
|
||||
for (void* object : {rtv_heap, vertices, readback, target, triangle_pipeline, rect_pipeline, root, fence, list, allocator, queue,
|
||||
dev}) {
|
||||
slot<ReleaseFn>(object, kRelease)(object);
|
||||
}
|
||||
std::printf("%s: test_d3d12_rect_list (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS", g_checks - g_failed, g_checks);
|
||||
return g_failed ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_d3d12_serialized_pipelines main.cpp)
|
||||
target_compile_definitions(test_d3d12_serialized_pipelines PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_serialized_pipelines PRIVATE d3d12_xs kernel32 uuid)
|
||||
@@ -0,0 +1,198 @@
|
||||
/*
|
||||
* Conformance test for #669: serialized and derived Xbox pipeline-state calls must fail with
|
||||
* E_NOTIMPL and log `pipeline_refused` even when BX_NULL_RENDER=1 is active, so a title falls
|
||||
* back to creating pipelines from shader containers instead of silently receiving null pipelines.
|
||||
*
|
||||
* Slot numbers follow the Xbox Series ID3D12Device vtable layout (ADR 0009):
|
||||
* 2 = Release
|
||||
* 11 = CreateComputePipelineState
|
||||
* 55 = CreateDerivedGraphicsPipelineStateX
|
||||
* 57 = DeserializeGraphicsPipelineStateX
|
||||
* 63 = CreateDerivedComputePipelineStateX
|
||||
* 67 = DeserializeComputePipelineStateX
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
|
||||
void** ppv);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kRelease = 2;
|
||||
constexpr int kDevCreateComputePipelineState = 11;
|
||||
constexpr int kDevCreateDerivedGraphicsPipelineStateX = 55;
|
||||
constexpr int kDevDeserializeGraphicsPipelineStateX = 57;
|
||||
constexpr int kDevCreateDerivedComputePipelineStateX = 63;
|
||||
constexpr int kDevDeserializeComputePipelineStateX = 67;
|
||||
|
||||
int g_checks = 0;
|
||||
int g_failed = 0;
|
||||
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
++g_checks; \
|
||||
if (!(cond)) { \
|
||||
++g_failed; \
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_serialized_pipelines:%d: ", __LINE__); \
|
||||
std::fprintf(stderr, __VA_ARGS__); \
|
||||
std::fprintf(stderr, "\n"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
template <typename Fn>
|
||||
Fn slot(void* object, int index) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
|
||||
}
|
||||
|
||||
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateComputePsoFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, REFIID, void**);
|
||||
using DeserializePsoFn = HRESULT(STDMETHODCALLTYPE*)(void*, const void*, REFIID, void**);
|
||||
using CreateDerivedPsoFn = HRESULT(STDMETHODCALLTYPE*)(void*, ID3D12PipelineState*, UINT, const void*, REFIID, void**);
|
||||
|
||||
std::string read_log() {
|
||||
char path[MAX_PATH];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (n == 0 || n >= sizeof(path)) return {};
|
||||
std::string text;
|
||||
if (FILE* f = std::fopen(path, "rb")) {
|
||||
char buffer[4096];
|
||||
size_t got;
|
||||
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
|
||||
std::fclose(f);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
bool log_has_refusal_without_null(const std::string& log, const char* kind) {
|
||||
size_t pos = 0;
|
||||
while (pos < log.size()) {
|
||||
size_t end = log.find('\n', pos);
|
||||
if (end == std::string::npos) end = log.size();
|
||||
const std::string line = log.substr(pos, end - pos);
|
||||
if (line.find("\"event\":\"pipeline_refused\"") != std::string::npos && line.find(kind) != std::string::npos) {
|
||||
return line.find("null pipeline returned") == std::string::npos;
|
||||
}
|
||||
pos = end + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
// Enable null-render mode before any pipeline call so d3d12_xs caches BX_NULL_RENDER=1.
|
||||
SetEnvironmentVariableA("BX_NULL_RENDER", "1");
|
||||
|
||||
alignas(8) unsigned char title_params[80] = {};
|
||||
const UINT version = 0x20004;
|
||||
std::memcpy(title_params, &version, sizeof(version));
|
||||
|
||||
void* dev = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
|
||||
if (hr == E_NOINTERFACE) {
|
||||
std::printf("SKIP: test_d3d12_serialized_pipelines: host lacks Xbox-layout device interface (E_NOINTERFACE)\n");
|
||||
return 77;
|
||||
}
|
||||
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!dev) return 1;
|
||||
|
||||
// 1. Control check: a refused shader-container pipeline still becomes a null pipeline when
|
||||
// BX_NULL_RENDER=1, confirming null-render mode is active.
|
||||
static const uint8_t kBogusShader[16] = {0x44, 0x58, 0x42, 0x43};
|
||||
D3D12_COMPUTE_PIPELINE_STATE_DESC compute_desc{};
|
||||
compute_desc.CS.pShaderBytecode = kBogusShader;
|
||||
compute_desc.CS.BytecodeLength = sizeof(kBogusShader);
|
||||
void* null_pso = nullptr;
|
||||
hr = slot<CreateComputePsoFn>(dev, kDevCreateComputePipelineState)(
|
||||
dev, &compute_desc, __uuidof(ID3D12PipelineState), &null_pso);
|
||||
CHECK(hr == S_OK && null_pso != nullptr,
|
||||
"control: refused CreateComputePipelineState returns null pipeline in BX_NULL_RENDER=1 (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
|
||||
// 2. Serialized pipeline calls must fail with E_NOTIMPL and clear *ppv even with BX_NULL_RENDER=1.
|
||||
auto* sentinel = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
|
||||
void* out = sentinel;
|
||||
hr = slot<DeserializePsoFn>(dev, kDevDeserializeGraphicsPipelineStateX)(
|
||||
dev, nullptr, __uuidof(ID3D12PipelineState), &out);
|
||||
CHECK(hr == E_NOTIMPL && out == nullptr,
|
||||
"DeserializeGraphicsPipelineStateX must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
|
||||
static_cast<unsigned long>(hr), out);
|
||||
hr = slot<DeserializePsoFn>(dev, kDevDeserializeGraphicsPipelineStateX)(
|
||||
dev, nullptr, __uuidof(ID3D12PipelineState), nullptr);
|
||||
CHECK(hr == E_POINTER, "DeserializeGraphicsPipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
|
||||
out = sentinel;
|
||||
hr = slot<DeserializePsoFn>(dev, kDevDeserializeComputePipelineStateX)(
|
||||
dev, nullptr, __uuidof(ID3D12PipelineState), &out);
|
||||
CHECK(hr == E_NOTIMPL && out == nullptr,
|
||||
"DeserializeComputePipelineStateX must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
|
||||
static_cast<unsigned long>(hr), out);
|
||||
hr = slot<DeserializePsoFn>(dev, kDevDeserializeComputePipelineStateX)(
|
||||
dev, nullptr, __uuidof(ID3D12PipelineState), nullptr);
|
||||
CHECK(hr == E_POINTER, "DeserializeComputePipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
|
||||
// 3. Derived pipeline calls must also fail with E_NOTIMPL and clear *ppv (both from a null
|
||||
// pipeline source and from a nullptr source) even with BX_NULL_RENDER=1.
|
||||
auto* null_src = static_cast<ID3D12PipelineState*>(null_pso);
|
||||
out = sentinel;
|
||||
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedGraphicsPipelineStateX)(
|
||||
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
|
||||
CHECK(hr == E_NOTIMPL && out == nullptr,
|
||||
"CreateDerivedGraphicsPipelineStateX(null source) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
|
||||
static_cast<unsigned long>(hr), out);
|
||||
out = sentinel;
|
||||
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedGraphicsPipelineStateX)(
|
||||
dev, nullptr, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
|
||||
CHECK(hr == E_NOTIMPL && out == nullptr,
|
||||
"CreateDerivedGraphicsPipelineStateX(nullptr) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
|
||||
static_cast<unsigned long>(hr), out);
|
||||
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedGraphicsPipelineStateX)(
|
||||
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), nullptr);
|
||||
CHECK(hr == E_POINTER, "CreateDerivedGraphicsPipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
|
||||
out = sentinel;
|
||||
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedComputePipelineStateX)(
|
||||
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
|
||||
CHECK(hr == E_NOTIMPL && out == nullptr,
|
||||
"CreateDerivedComputePipelineStateX(null source) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
|
||||
static_cast<unsigned long>(hr), out);
|
||||
out = sentinel;
|
||||
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedComputePipelineStateX)(
|
||||
dev, nullptr, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
|
||||
CHECK(hr == E_NOTIMPL && out == nullptr,
|
||||
"CreateDerivedComputePipelineStateX(nullptr) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
|
||||
static_cast<unsigned long>(hr), out);
|
||||
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedComputePipelineStateX)(
|
||||
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), nullptr);
|
||||
CHECK(hr == E_POINTER, "CreateDerivedComputePipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
|
||||
// 4. When BX_LOG_FILE is active, verify each refusal was logged without "null pipeline returned".
|
||||
const std::string log = read_log();
|
||||
if (!log.empty()) {
|
||||
CHECK(log_has_refusal_without_null(log, "deserialized graphics (console code)"),
|
||||
"log must record deserialized graphics refusal without null pipeline");
|
||||
CHECK(log_has_refusal_without_null(log, "deserialized compute (console code)"),
|
||||
"log must record deserialized compute refusal without null pipeline");
|
||||
CHECK(log_has_refusal_without_null(log, "derived graphics"),
|
||||
"log must record derived graphics refusal without null pipeline");
|
||||
CHECK(log_has_refusal_without_null(log, "derived compute"),
|
||||
"log must record derived compute refusal without null pipeline");
|
||||
}
|
||||
|
||||
if (null_pso) slot<ReleaseFn>(null_pso, kRelease)(null_pso);
|
||||
slot<ReleaseFn>(dev, kRelease)(dev);
|
||||
|
||||
std::printf("%s: test_d3d12_serialized_pipelines (%d of %d checks passed)\n",
|
||||
g_failed ? "FAIL" : "PASS", g_checks - g_failed, g_checks);
|
||||
return g_failed ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_d3d12_title_memory_geometry main.cpp)
|
||||
target_compile_definitions(test_d3d12_title_memory_geometry PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_title_memory_geometry PRIVATE d3d12_xs kernel32 uuid)
|
||||
@@ -0,0 +1,447 @@
|
||||
/*
|
||||
* Conformance test: index and vertex data bound from plain title memory are drawn.
|
||||
*
|
||||
* Contract: on the console a GPU virtual address is the title's own address and the GPU reads
|
||||
* the memory when the commands execute. A title binds index and vertex data it keeps in plain
|
||||
* memory, with no Direct3D resource created for it, and may write that data after it has
|
||||
* recorded the draw (observed in a project-authorized target build: its UI layer draws from a
|
||||
* 1.1 MiB vertex ring and a 384 KiB index ring bound this way).
|
||||
*
|
||||
* The test renders into a 128x128 target through an Xbox-layout device and reads the pixels back:
|
||||
* - first submission: an indexed triangle whose vertices and indices live in VirtualAlloc
|
||||
* memory and are written only AFTER the draw was recorded, before the list is submitted;
|
||||
* - second submission (a second list): the same bindings after the vertex data changed, so
|
||||
* the copy must be made at every submission, not once when the buffer was created;
|
||||
* - a view that starts inside the first range and a non-indexed draw from it.
|
||||
* Without the fix the bindings are left empty (or, before that, crashed the host) and nothing
|
||||
* is drawn.
|
||||
*
|
||||
* Slots (Xbox-layout tables, ADR 0009): as in test_d3d12_rect_list, plus command list 47
|
||||
* IASetIndexBuffer.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
|
||||
void** ppv);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kRelease = 2;
|
||||
constexpr int kDevCreateCommandAllocator = 9, kDevCreateGraphicsPipelineState = 10, kDevCreateDescriptorHeap = 14;
|
||||
constexpr int kDevCreateRootSignature = 16, kDevCreateRenderTargetView = 20, kDevCreateCommittedResource = 27;
|
||||
constexpr int kDevCreateFence = 36, kDevCreateCommandQueueX = 48, kDevCreateCommandListX = 73;
|
||||
constexpr int kResMap = 8, kResGetGpuVirtualAddress = 11, kHeapGetCpuStart = 9;
|
||||
constexpr int kListClose = 9, kListDrawInstanced = 12, kListDrawIndexedInstanced = 13, kListCopyTextureRegion = 16;
|
||||
constexpr int kListIASetPrimitiveTopology = 20, kListRSSetViewports = 21, kListRSSetScissorRects = 22;
|
||||
constexpr int kListSetPipelineState = 25, kListResourceBarrier = 26, kListSetGraphicsRootSignature = 34;
|
||||
constexpr int kListIASetIndexBuffer = 47, kListIASetVertexBuffers = 48, kListOMSetRenderTargets = 50;
|
||||
constexpr int kListClearRenderTargetView = 52;
|
||||
constexpr int kQueueExecuteCommandLists = 10, kQueueSignal = 16, kFenceSetEventOnCompletion = 9;
|
||||
|
||||
constexpr UINT kSize = 128;
|
||||
|
||||
int g_checks = 0;
|
||||
int g_failed = 0;
|
||||
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
++g_checks; \
|
||||
if (!(cond)) { \
|
||||
++g_failed; \
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_title_memory_geometry:%d: ", __LINE__); \
|
||||
std::fprintf(stderr, __VA_ARGS__); \
|
||||
std::fprintf(stderr, "\n"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
template <typename Fn>
|
||||
Fn slot(void* object, int index) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
|
||||
}
|
||||
|
||||
struct QueueDescX {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
UINT Flags, EngineOrPipeIndex, QueueIndex;
|
||||
};
|
||||
struct ListDescX {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
UINT Flags, NodeMask, ResourceBarrierBatchSize;
|
||||
};
|
||||
|
||||
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const QueueDescX*, REFIID, void**);
|
||||
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
|
||||
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
|
||||
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
|
||||
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, REFIID, void**);
|
||||
using CreateFenceFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, D3D12_FENCE_FLAGS, REFIID, void**);
|
||||
using CreateHeapFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_DESCRIPTOR_HEAP_DESC*, REFIID, void**);
|
||||
using HeapStartFn = D3D12_CPU_DESCRIPTOR_HANDLE(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateRootFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const void*, SIZE_T, REFIID, void**);
|
||||
using CreateRtvFn = void(STDMETHODCALLTYPE*)(void*, void*, const D3D12_RENDER_TARGET_VIEW_DESC*, D3D12_CPU_DESCRIPTOR_HANDLE);
|
||||
using CreatePsoFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_GRAPHICS_PIPELINE_STATE_DESC*, REFIID, void**);
|
||||
using MapFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RANGE*, void**);
|
||||
using GetGpuVaFn = D3D12_GPU_VIRTUAL_ADDRESS(STDMETHODCALLTYPE*)(void*);
|
||||
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
|
||||
using DrawFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, UINT, UINT);
|
||||
using DrawIndexedFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, UINT, INT, UINT);
|
||||
using CopyTextureFn = void(STDMETHODCALLTYPE*)(void*, const D3D12_TEXTURE_COPY_LOCATION*, UINT, UINT, UINT,
|
||||
const D3D12_TEXTURE_COPY_LOCATION*, const D3D12_BOX*);
|
||||
using TopologyFn = void(STDMETHODCALLTYPE*)(void*, D3D12_PRIMITIVE_TOPOLOGY);
|
||||
using ViewportsFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_VIEWPORT*);
|
||||
using ScissorsFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RECT*);
|
||||
using SetObjectFn = void(STDMETHODCALLTYPE*)(void*, void*);
|
||||
using BarrierFn = UINT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RESOURCE_BARRIER*);
|
||||
using SetVbFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_VERTEX_BUFFER_VIEW*);
|
||||
using SetIbFn = void(STDMETHODCALLTYPE*)(void*, const D3D12_INDEX_BUFFER_VIEW*);
|
||||
using SetTargetsFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_CPU_DESCRIPTOR_HANDLE*, BOOL,
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE*);
|
||||
using ClearFn = void(STDMETHODCALLTYPE*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, const FLOAT*, UINT, const D3D12_RECT*);
|
||||
using ExecuteFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
|
||||
using QueueSignalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64);
|
||||
using FenceEventFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, HANDLE);
|
||||
|
||||
using D3DCompileFn = HRESULT(WINAPI*)(LPCVOID, SIZE_T, LPCSTR, const void*, void*, LPCSTR, LPCSTR, UINT, UINT, ID3DBlob**,
|
||||
ID3DBlob**);
|
||||
using SerializeRootFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
|
||||
|
||||
const char kShader[] =
|
||||
"struct V { float4 pos : SV_Position; float4 col : COLOR; };\n"
|
||||
"V vs(float2 p : POSITION, float4 c : COLOR) { V o; o.pos = float4(p, 0.0f, 1.0f); o.col = c; return o; }\n"
|
||||
"float4 ps(V i) : SV_Target0 { return i.col; }\n";
|
||||
|
||||
ID3DBlob* compile(const char* entry, const char* target) {
|
||||
HMODULE compiler = LoadLibraryA("d3dcompiler_47.dll");
|
||||
auto fn = compiler ? reinterpret_cast<D3DCompileFn>(reinterpret_cast<void*>(GetProcAddress(compiler, "D3DCompile"))) : nullptr;
|
||||
if (!fn) return nullptr;
|
||||
ID3DBlob* code = nullptr;
|
||||
ID3DBlob* errors = nullptr;
|
||||
const HRESULT hr = fn(kShader, sizeof(kShader) - 1, "title_memory_geometry", nullptr, nullptr, entry, target, 0, 0, &code, &errors);
|
||||
if (FAILED(hr) && errors) std::fprintf(stderr, "D3DCompile(%s): %s\n", entry, static_cast<const char*>(errors->GetBufferPointer()));
|
||||
if (errors) errors->Release();
|
||||
return SUCCEEDED(hr) ? code : nullptr;
|
||||
}
|
||||
|
||||
struct Vertex {
|
||||
float x, y;
|
||||
float r, g, b, a;
|
||||
};
|
||||
|
||||
std::string read_log() {
|
||||
char path[MAX_PATH];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (n == 0 || n >= sizeof(path)) return {};
|
||||
std::string text;
|
||||
if (FILE* f = std::fopen(path, "rb")) {
|
||||
char buffer[4096];
|
||||
size_t got;
|
||||
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
|
||||
std::fclose(f);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
size_t count_of(const std::string& text, const char* needle) {
|
||||
size_t n = 0;
|
||||
for (size_t pos = text.find(needle); pos != std::string::npos; pos = text.find(needle, pos + 1)) ++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
struct Pixel {
|
||||
int r, g, b;
|
||||
};
|
||||
|
||||
const uint8_t* g_pixels = nullptr;
|
||||
constexpr UINT kRowPitch = kSize * 4; // 512: a multiple of the 256-byte texture data pitch alignment
|
||||
|
||||
Pixel at(UINT x, UINT y) {
|
||||
const uint8_t* p = g_pixels + static_cast<size_t>(y) * kRowPitch + static_cast<size_t>(x) * 4;
|
||||
return {p[0], p[1], p[2]};
|
||||
}
|
||||
|
||||
bool is_clear(Pixel p) { return p.r < 40 && p.g > 215 && p.b < 40; } // the clear colour is green
|
||||
|
||||
/* Pixels of the half-open quadrant [x0, x0+64) x [y0, y0+64) that still show the clear colour. */
|
||||
unsigned clear_pixels(UINT x0, UINT y0) {
|
||||
unsigned n = 0;
|
||||
for (UINT y = y0; y < y0 + kSize / 2; ++y) {
|
||||
for (UINT x = x0; x < x0 + kSize / 2; ++x) n += is_clear(at(x, y)) ? 1 : 0;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
alignas(8) unsigned char title_params[80] = {};
|
||||
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
|
||||
std::memcpy(title_params, &version, sizeof(version));
|
||||
void* dev = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
|
||||
if (hr == E_NOINTERFACE) {
|
||||
std::printf("SKIP: test_d3d12_title_memory_geometry: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
|
||||
return 77;
|
||||
}
|
||||
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!dev) return 1;
|
||||
|
||||
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
|
||||
auto serialize = d3d12 ? reinterpret_cast<SerializeRootFn>(
|
||||
reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")))
|
||||
: nullptr;
|
||||
ID3DBlob* vs = compile("vs", "vs_5_0");
|
||||
ID3DBlob* ps = compile("ps", "ps_5_0");
|
||||
if (!serialize || !vs || !ps) {
|
||||
std::printf("SKIP: test_d3d12_title_memory_geometry: no shader compiler or root-signature serializer in this bottle\n");
|
||||
return 77;
|
||||
}
|
||||
|
||||
const QueueDescX qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
void* queue = nullptr;
|
||||
void* allocators[2] = {};
|
||||
void* lists[2] = {};
|
||||
void* fence = nullptr;
|
||||
slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue);
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT,
|
||||
__uuidof(ID3D12CommandAllocator), &allocators[i]);
|
||||
slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocators[i], nullptr, __uuidof(ID3D12GraphicsCommandList),
|
||||
&lists[i]);
|
||||
}
|
||||
slot<CreateFenceFn>(dev, kDevCreateFence)(dev, 0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &fence);
|
||||
|
||||
D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
|
||||
root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
|
||||
root_desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
|
||||
ID3DBlob* root_blob = nullptr;
|
||||
hr = serialize(&root_desc, &root_blob, nullptr);
|
||||
void* root = nullptr;
|
||||
if (SUCCEEDED(hr) && root_blob) {
|
||||
hr = slot<CreateRootFn>(dev, kDevCreateRootSignature)(dev, 0, root_blob->GetBufferPointer(), root_blob->GetBufferSize(),
|
||||
__uuidof(ID3D12RootSignature), &root);
|
||||
}
|
||||
CHECK(hr == S_OK && root, "CreateRootSignature hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
const D3D12_INPUT_ELEMENT_DESC elements[] = {
|
||||
{"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
|
||||
{"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 8, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
|
||||
};
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{};
|
||||
pd.pRootSignature = static_cast<ID3D12RootSignature*>(root);
|
||||
pd.VS = {vs->GetBufferPointer(), vs->GetBufferSize()};
|
||||
pd.PS = {ps->GetBufferPointer(), ps->GetBufferSize()};
|
||||
pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
|
||||
pd.SampleMask = UINT_MAX;
|
||||
pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
|
||||
pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
|
||||
pd.RasterizerState.DepthClipEnable = TRUE;
|
||||
pd.InputLayout = {elements, 2};
|
||||
pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
|
||||
pd.NumRenderTargets = 1;
|
||||
pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
pd.SampleDesc.Count = 1;
|
||||
void* pipeline = nullptr;
|
||||
hr = slot<CreatePsoFn>(dev, kDevCreateGraphicsPipelineState)(dev, &pd, __uuidof(ID3D12PipelineState), &pipeline);
|
||||
CHECK(hr == S_OK && pipeline, "CreateGraphicsPipelineState hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
D3D12_HEAP_PROPERTIES default_heap{}, readback_heap{};
|
||||
default_heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
readback_heap.Type = D3D12_HEAP_TYPE_READBACK;
|
||||
D3D12_RESOURCE_DESC target_desc{};
|
||||
target_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
target_desc.Width = kSize;
|
||||
target_desc.Height = kSize;
|
||||
target_desc.DepthOrArraySize = 1;
|
||||
target_desc.MipLevels = 1;
|
||||
target_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
target_desc.SampleDesc.Count = 1;
|
||||
target_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
|
||||
D3D12_RESOURCE_DESC buffer_desc{};
|
||||
buffer_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
buffer_desc.Width = static_cast<UINT64>(kRowPitch) * kSize;
|
||||
buffer_desc.Height = 1;
|
||||
buffer_desc.DepthOrArraySize = 1;
|
||||
buffer_desc.MipLevels = 1;
|
||||
buffer_desc.SampleDesc.Count = 1;
|
||||
buffer_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
void* target = nullptr;
|
||||
void* readbacks[2] = {};
|
||||
auto committed = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource);
|
||||
hr = committed(dev, &default_heap, D3D12_HEAP_FLAG_NONE, &target_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
|
||||
__uuidof(ID3D12Resource), &target);
|
||||
CHECK(hr == S_OK && target, "render target hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
hr = committed(dev, &readback_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
|
||||
__uuidof(ID3D12Resource), &readbacks[i]);
|
||||
CHECK(hr == S_OK && readbacks[i], "readback buffer %d hr=0x%08lx", i, static_cast<unsigned long>(hr));
|
||||
}
|
||||
D3D12_DESCRIPTOR_HEAP_DESC heap_desc{};
|
||||
heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
|
||||
heap_desc.NumDescriptors = 1;
|
||||
void* rtv_heap = nullptr;
|
||||
hr = slot<CreateHeapFn>(dev, kDevCreateDescriptorHeap)(dev, &heap_desc, __uuidof(ID3D12DescriptorHeap), &rtv_heap);
|
||||
CHECK(hr == S_OK && rtv_heap, "RTV heap hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
// Plain title memory for the geometry: no Direct3D resource is ever created for it.
|
||||
constexpr size_t kVertexBytes = 64 * 1024, kIndexBytes = 4096;
|
||||
auto* vertex_memory = static_cast<Vertex*>(VirtualAlloc(nullptr, kVertexBytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
auto* index_memory = static_cast<uint16_t*>(VirtualAlloc(nullptr, kIndexBytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
if (!queue || !allocators[0] || !allocators[1] || !lists[0] || !lists[1] || !fence || !root || !pipeline || !target ||
|
||||
!readbacks[0] || !readbacks[1] || !rtv_heap || !vertex_memory || !index_memory) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_title_memory_geometry: setup\n");
|
||||
return 1;
|
||||
}
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE rtv = slot<HeapStartFn>(rtv_heap, kHeapGetCpuStart)(rtv_heap);
|
||||
slot<CreateRtvFn>(dev, kDevCreateRenderTargetView)(dev, target, nullptr, rtv);
|
||||
|
||||
const std::string before = read_log();
|
||||
const size_t stubs_before = count_of(before, "title memory without a host buffer");
|
||||
|
||||
const auto vertex_va = reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(vertex_memory);
|
||||
const auto index_va = reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(index_memory);
|
||||
const D3D12_VERTEX_BUFFER_VIEW whole{vertex_va, static_cast<UINT>(kVertexBytes), sizeof(Vertex)};
|
||||
// A second view that starts 8 vertices into the same memory, as a ring allocator hands out.
|
||||
const D3D12_VERTEX_BUFFER_VIEW tail{vertex_va + 8 * sizeof(Vertex), static_cast<UINT>(kVertexBytes - 8 * sizeof(Vertex)),
|
||||
sizeof(Vertex)};
|
||||
const D3D12_INDEX_BUFFER_VIEW ibv{index_va, static_cast<UINT>(kIndexBytes), DXGI_FORMAT_R16_UINT};
|
||||
const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(kSize), static_cast<float>(kSize), 0, 1};
|
||||
const D3D12_RECT scissor{0, 0, static_cast<LONG>(kSize), static_cast<LONG>(kSize)};
|
||||
const FLOAT green[4] = {0, 1, 0, 1};
|
||||
|
||||
auto record = [&](void* list, void* readback, D3D12_RESOURCE_STATES target_state) {
|
||||
if (target_state != D3D12_RESOURCE_STATE_RENDER_TARGET) {
|
||||
D3D12_RESOURCE_BARRIER back{};
|
||||
back.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
back.Transition.pResource = static_cast<ID3D12Resource*>(target);
|
||||
back.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
back.Transition.StateBefore = target_state;
|
||||
back.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
|
||||
slot<BarrierFn>(list, kListResourceBarrier)(list, 1, &back);
|
||||
}
|
||||
slot<SetObjectFn>(list, kListSetGraphicsRootSignature)(list, root);
|
||||
slot<SetObjectFn>(list, kListSetPipelineState)(list, pipeline);
|
||||
slot<SetTargetsFn>(list, kListOMSetRenderTargets)(list, 1, &rtv, FALSE, nullptr);
|
||||
slot<ViewportsFn>(list, kListRSSetViewports)(list, 1, &viewport);
|
||||
slot<ScissorsFn>(list, kListRSSetScissorRects)(list, 1, &scissor);
|
||||
slot<ClearFn>(list, kListClearRenderTargetView)(list, rtv, green, 0, nullptr);
|
||||
slot<TopologyFn>(list, kListIASetPrimitiveTopology)(list, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
|
||||
// Indexed: indices 0..2 select vertices 2, 0, 1 of the whole view (the left triangle).
|
||||
slot<SetVbFn>(list, kListIASetVertexBuffers)(list, 0, 1, &whole);
|
||||
slot<SetIbFn>(list, kListIASetIndexBuffer)(list, &ibv);
|
||||
slot<DrawIndexedFn>(list, kListDrawIndexedInstanced)(list, 3, 1, 0, 0, 0);
|
||||
// Non-indexed from the view that starts inside the same memory (the right triangle).
|
||||
slot<SetVbFn>(list, kListIASetVertexBuffers)(list, 0, 1, &tail);
|
||||
slot<DrawFn>(list, kListDrawInstanced)(list, 3, 1, 0, 0);
|
||||
D3D12_RESOURCE_BARRIER to_copy{};
|
||||
to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
to_copy.Transition.pResource = static_cast<ID3D12Resource*>(target);
|
||||
to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
|
||||
to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
slot<BarrierFn>(list, kListResourceBarrier)(list, 1, &to_copy);
|
||||
D3D12_TEXTURE_COPY_LOCATION dst{};
|
||||
dst.pResource = static_cast<ID3D12Resource*>(readback);
|
||||
dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
|
||||
dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSize, kSize, 1, kRowPitch};
|
||||
D3D12_TEXTURE_COPY_LOCATION src{};
|
||||
src.pResource = static_cast<ID3D12Resource*>(target);
|
||||
src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
|
||||
slot<CopyTextureFn>(list, kListCopyTextureRegion)(list, &dst, 0, 0, 0, &src, nullptr);
|
||||
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "list Close");
|
||||
};
|
||||
UINT64 fence_value = 0;
|
||||
auto submit = [&](void* list) {
|
||||
void* one[] = {list};
|
||||
slot<ExecuteFn>(queue, kQueueExecuteCommandLists)(queue, 1, one);
|
||||
++fence_value;
|
||||
CHECK(slot<QueueSignalFn>(queue, kQueueSignal)(queue, fence, fence_value) == S_OK, "queue Signal");
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
CHECK(slot<FenceEventFn>(fence, kFenceSetEventOnCompletion)(fence, fence_value, done) == S_OK, "fence event");
|
||||
CHECK(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0, "GPU work completes");
|
||||
CloseHandle(done);
|
||||
};
|
||||
auto map = [&](void* readback) -> const uint8_t* {
|
||||
void* result = nullptr;
|
||||
const HRESULT map_hr = slot<MapFn>(readback, kResMap)(readback, 0, nullptr, &result);
|
||||
CHECK(map_hr == S_OK && result, "readback Map hr=0x%08lx", static_cast<unsigned long>(map_hr));
|
||||
return static_cast<const uint8_t*>(result);
|
||||
};
|
||||
const float R[4] = {1, 0, 0, 1}, B[4] = {0, 0, 1, 1}, W[4] = {1, 1, 1, 1}, Y[4] = {1, 1, 0, 1};
|
||||
auto v = [](float x, float y, const float* c) { return Vertex{x, y, c[0], c[1], c[2], c[3]}; };
|
||||
|
||||
// --- First submission: the data is written after the draws were recorded. ---------------
|
||||
std::memset(vertex_memory, 0, kVertexBytes);
|
||||
std::memset(index_memory, 0, kIndexBytes);
|
||||
record(lists[0], readbacks[0], D3D12_RESOURCE_STATE_RENDER_TARGET);
|
||||
// Left half: a red triangle over the top-left quadrant's lower-left half.
|
||||
vertex_memory[0] = v(-1, 1, R);
|
||||
vertex_memory[1] = v(-1, 0, R);
|
||||
vertex_memory[2] = v(0, 0, R);
|
||||
index_memory[0] = 2;
|
||||
index_memory[1] = 0;
|
||||
index_memory[2] = 1;
|
||||
// Right half, through the tail view (its vertex 0 is vertex 8 of the memory): blue.
|
||||
vertex_memory[8] = v(0, 1, B);
|
||||
vertex_memory[9] = v(1, 1, B);
|
||||
vertex_memory[10] = v(1, 0, B);
|
||||
submit(lists[0]);
|
||||
g_pixels = map(readbacks[0]);
|
||||
if (!g_pixels) return 1;
|
||||
const unsigned half = kSize / 2;
|
||||
CHECK(clear_pixels(0, half) == half * half && clear_pixels(half, half) == half * half,
|
||||
"control: the bottom half keeps the clear colour (%u and %u of %u)", clear_pixels(0, half), clear_pixels(half, half),
|
||||
half * half);
|
||||
Pixel p = at(8, half - 16); // near (-0.875, 0.25): inside the left triangle
|
||||
CHECK(p.r > 215 && p.g < 40 && p.b < 40,
|
||||
"indexed draw from plain title memory, written after recording, is red inside its triangle: (%d, %d, %d)", p.r, p.g, p.b);
|
||||
p = at(half - 8, 8); // near (-0.125, 0.875): outside the left triangle
|
||||
CHECK(is_clear(p), "and leaves the rest of its quadrant alone: (%d, %d, %d)", p.r, p.g, p.b);
|
||||
p = at(kSize - 16, 8); // near (0.75, 0.875): inside the right triangle
|
||||
CHECK(p.r < 40 && p.g < 40 && p.b > 215,
|
||||
"non-indexed draw through a view that starts inside the same memory is blue: (%d, %d, %d)", p.r, p.g, p.b);
|
||||
|
||||
// --- Second submission: the same bindings after the data changed. -----------------------
|
||||
vertex_memory[0] = v(-1, 1, W);
|
||||
vertex_memory[1] = v(0, 1, W);
|
||||
vertex_memory[2] = v(0, 0, W); // now the upper-right half of the top-left quadrant, white
|
||||
vertex_memory[8] = v(0, 0, Y);
|
||||
vertex_memory[9] = v(1, 0, Y);
|
||||
vertex_memory[10] = v(0, 1, Y); // now the lower-left half of the top-right quadrant, yellow
|
||||
record(lists[1], readbacks[1], D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
submit(lists[1]);
|
||||
g_pixels = map(readbacks[1]);
|
||||
if (!g_pixels) return 1;
|
||||
p = at(half - 8, 8);
|
||||
CHECK(p.r > 215 && p.g > 215 && p.b > 215, "second submission draws the changed vertices (white): (%d, %d, %d)", p.r, p.g, p.b);
|
||||
p = at(8, half - 16);
|
||||
CHECK(is_clear(p), "and no longer the first triangle: (%d, %d, %d)", p.r, p.g, p.b);
|
||||
p = at(half + 8, half - 8); // near (0.125, 0.125): inside the new right triangle
|
||||
CHECK(p.r > 215 && p.g > 215 && p.b < 40, "changed tail-view vertices are drawn (yellow): (%d, %d, %d)", p.r, p.g, p.b);
|
||||
|
||||
const std::string after = read_log();
|
||||
if (!after.empty()) {
|
||||
CHECK(count_of(after, "title memory without a host buffer") == stubs_before,
|
||||
"no binding is logged as unimplemented (%zu new)", count_of(after, "title memory without a host buffer") - stubs_before);
|
||||
CHECK(count_of(after, "host buffer for bound title memory") > count_of(before, "host buffer for bound title memory"),
|
||||
"the host buffers made for bound title memory are logged");
|
||||
} else {
|
||||
std::printf("note: no BX_LOG_FILE; the log checks did not run\n");
|
||||
}
|
||||
|
||||
VirtualFree(vertex_memory, 0, MEM_RELEASE);
|
||||
VirtualFree(index_memory, 0, MEM_RELEASE);
|
||||
for (void* object : {rtv_heap, readbacks[1], readbacks[0], target, pipeline, root, fence, lists[1], lists[0], allocators[1],
|
||||
allocators[0], queue, dev}) {
|
||||
slot<ReleaseFn>(object, kRelease)(object);
|
||||
}
|
||||
std::printf("%s: test_d3d12_title_memory_geometry (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS", g_checks - g_failed, g_checks);
|
||||
return g_failed ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_d3d12_unbacked_buffers main.cpp)
|
||||
target_compile_definitions(test_d3d12_unbacked_buffers PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_unbacked_buffers PRIVATE d3d12_xs kernel32 uuid)
|
||||
@@ -0,0 +1,229 @@
|
||||
/*
|
||||
* Conformance test: index and vertex bindings at a title address this layer cannot give a host
|
||||
* buffer must not reach the host Direct3D 12 implementation.
|
||||
*
|
||||
* Contract: on the console a GPU virtual address is the title's own address, so a title binds
|
||||
* index and vertex data that lives in plain title memory, with no Direct3D resource created for
|
||||
* it. BetterXen gives such memory a host buffer when it is bound (drawing from it is covered by
|
||||
* test_d3d12_title_memory_geometry). When it cannot, because the address is not readable memory,
|
||||
* the address must still not be passed through: it is not a host address, and D3DMetal
|
||||
* dereferences the buffer it fails to find (a null read inside IASetIndexBuffer). The binding is
|
||||
* then left empty (Direct3D 12 defines a null binding) and the call is logged as unimplemented.
|
||||
*
|
||||
* Checked here, recording into an Xbox-layout command list:
|
||||
* - bindings inside a buffer BetterXen created, and in plain committed title memory: accepted,
|
||||
* not logged;
|
||||
* - bindings in reserved but uncommitted address space: left empty, each logged exactly once;
|
||||
* - null bindings: unchanged, not logged;
|
||||
* - the list still closes.
|
||||
* Before either fix the failure mode was the null read.
|
||||
*
|
||||
* Slots (Xbox-layout tables, ADR 0009): 2 Release; device 9 CreateCommandAllocator,
|
||||
* 27 CreateCommittedResource, 48 CreateCommandQueueX, 73 CreateCommandListX; resource 11
|
||||
* GetGPUVirtualAddress; graphics command list 9 Close, 47 IASetIndexBuffer, 48 IASetVertexBuffers.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
|
||||
void** ppv);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kRelease = 2;
|
||||
constexpr int kDevCreateCommandAllocator = 9, kDevCreateCommittedResource = 27, kDevCreateCommandQueueX = 48;
|
||||
constexpr int kDevCreateCommandListX = 73;
|
||||
constexpr int kResGetGpuVirtualAddress = 11;
|
||||
constexpr int kListClose = 9, kListIASetIndexBuffer = 47, kListIASetVertexBuffers = 48;
|
||||
|
||||
int g_checks = 0;
|
||||
int g_failed = 0;
|
||||
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
++g_checks; \
|
||||
if (!(cond)) { \
|
||||
++g_failed; \
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_unbacked_buffers:%d: ", __LINE__); \
|
||||
std::fprintf(stderr, __VA_ARGS__); \
|
||||
std::fprintf(stderr, "\n"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
template <typename Fn>
|
||||
Fn slot(void* object, int index) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
|
||||
}
|
||||
|
||||
struct QueueDescX {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
UINT Flags, EngineOrPipeIndex, QueueIndex;
|
||||
};
|
||||
struct ListDescX {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
UINT Flags, NodeMask, ResourceBarrierBatchSize;
|
||||
};
|
||||
|
||||
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const QueueDescX*, REFIID, void**);
|
||||
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
|
||||
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
|
||||
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
|
||||
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, REFIID, void**);
|
||||
using GetGpuVaFn = D3D12_GPU_VIRTUAL_ADDRESS(STDMETHODCALLTYPE*)(void*);
|
||||
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
|
||||
using SetIndexFn = void(STDMETHODCALLTYPE*)(void*, const D3D12_INDEX_BUFFER_VIEW*);
|
||||
using SetVertexFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_VERTEX_BUFFER_VIEW*);
|
||||
|
||||
std::string read_log() {
|
||||
char path[MAX_PATH];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (n == 0 || n >= sizeof(path)) return {};
|
||||
std::string text;
|
||||
if (FILE* f = std::fopen(path, "rb")) {
|
||||
char buffer[4096];
|
||||
size_t got;
|
||||
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
|
||||
std::fclose(f);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
size_t count_of(const std::string& text, const char* needle) {
|
||||
size_t n = 0;
|
||||
for (size_t pos = text.find(needle); pos != std::string::npos; pos = text.find(needle, pos + 1)) ++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
constexpr const char* kIndexStub = "IASetIndexBuffer(title memory without a host buffer)";
|
||||
constexpr const char* kVertexStub = "IASetVertexBuffers(title memory without a host buffer)";
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
alignas(8) unsigned char title_params[80] = {};
|
||||
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
|
||||
std::memcpy(title_params, &version, sizeof(version));
|
||||
void* dev = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
|
||||
if (hr == E_NOINTERFACE) {
|
||||
std::printf("SKIP: test_d3d12_unbacked_buffers: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
|
||||
return 77;
|
||||
}
|
||||
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!dev) return 1;
|
||||
|
||||
const QueueDescX qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
void* queue = nullptr;
|
||||
void* allocator = nullptr;
|
||||
void* list = nullptr;
|
||||
CHECK(slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue) == S_OK,
|
||||
"CreateCommandQueueX");
|
||||
CHECK(slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT,
|
||||
__uuidof(ID3D12CommandAllocator), &allocator) == S_OK,
|
||||
"CreateCommandAllocator");
|
||||
hr = slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr, __uuidof(ID3D12GraphicsCommandList),
|
||||
&list);
|
||||
CHECK(hr == S_OK && list, "CreateCommandListX hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
// A buffer BetterXen created: its GPU address is a title address with a host buffer behind it.
|
||||
D3D12_HEAP_PROPERTIES upload{};
|
||||
upload.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
D3D12_RESOURCE_DESC desc{};
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
desc.Width = 64 * 1024;
|
||||
desc.Height = 1;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
void* backed = nullptr;
|
||||
hr = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &upload, D3D12_HEAP_FLAG_NONE, &desc,
|
||||
D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
__uuidof(ID3D12Resource), &backed);
|
||||
CHECK(hr == S_OK && backed, "CreateCommittedResource(64 KiB upload buffer) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
// Plain title memory: no Direct3D resource was created for it.
|
||||
auto* plain = static_cast<unsigned char*>(VirtualAlloc(nullptr, 64 * 1024, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
CHECK(plain != nullptr, "VirtualAlloc(64 KiB)");
|
||||
// Address space that is reserved but not committed: there is nothing to copy from.
|
||||
auto* unreadable = static_cast<unsigned char*>(VirtualAlloc(nullptr, 64 * 1024, MEM_RESERVE, PAGE_NOACCESS));
|
||||
CHECK(unreadable != nullptr, "VirtualAlloc(64 KiB, reserve only)");
|
||||
if (!queue || !allocator || !list || !backed || !plain || !unreadable) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_unbacked_buffers: setup\n");
|
||||
return 1;
|
||||
}
|
||||
const D3D12_GPU_VIRTUAL_ADDRESS backed_va = slot<GetGpuVaFn>(backed, kResGetGpuVirtualAddress)(backed);
|
||||
const auto plain_va = reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(plain);
|
||||
const auto unreadable_va = reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(unreadable);
|
||||
CHECK(backed_va != 0, "the committed buffer reports a GPU address");
|
||||
|
||||
const std::string before = read_log();
|
||||
const size_t index_before = count_of(before, kIndexStub);
|
||||
const size_t vertex_before = count_of(before, kVertexStub);
|
||||
|
||||
// 1. Bindings inside the buffer BetterXen created: translated, not logged.
|
||||
const D3D12_INDEX_BUFFER_VIEW backed_index{backed_va + 256, 4096, DXGI_FORMAT_R16_UINT};
|
||||
slot<SetIndexFn>(list, kListIASetIndexBuffer)(list, &backed_index);
|
||||
const D3D12_VERTEX_BUFFER_VIEW backed_vertex{backed_va + 8192, 4096, 16};
|
||||
slot<SetVertexFn>(list, kListIASetVertexBuffers)(list, 0, 1, &backed_vertex);
|
||||
CHECK(true, "bindings inside a created buffer returned");
|
||||
|
||||
// 2. Bindings in plain committed title memory: given a host buffer, not logged.
|
||||
const D3D12_INDEX_BUFFER_VIEW plain_index{plain_va, 4096, DXGI_FORMAT_R16_UINT};
|
||||
slot<SetIndexFn>(list, kListIASetIndexBuffer)(list, &plain_index);
|
||||
const D3D12_VERTEX_BUFFER_VIEW plain_vertex{plain_va + 4096, 4096, 16};
|
||||
slot<SetVertexFn>(list, kListIASetVertexBuffers)(list, 0, 1, &plain_vertex);
|
||||
CHECK(true, "bindings in plain title memory returned");
|
||||
{
|
||||
const std::string now = read_log();
|
||||
if (!now.empty()) {
|
||||
CHECK(count_of(now, kIndexStub) == index_before && count_of(now, kVertexStub) == vertex_before,
|
||||
"bindings in plain title memory are not logged as unimplemented");
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Bindings in address space with no memory behind it: the process must survive them.
|
||||
const D3D12_INDEX_BUFFER_VIEW unreadable_index{unreadable_va, 4096, DXGI_FORMAT_R16_UINT};
|
||||
slot<SetIndexFn>(list, kListIASetIndexBuffer)(list, &unreadable_index);
|
||||
CHECK(true, "IASetIndexBuffer at an unreadable title address returned");
|
||||
// Two vertex streams: the first backed, the second not. Only the second is emptied.
|
||||
const D3D12_VERTEX_BUFFER_VIEW streams[2] = {backed_vertex, {unreadable_va + 4096, 4096, 16}};
|
||||
slot<SetVertexFn>(list, kListIASetVertexBuffers)(list, 0, 2, streams);
|
||||
CHECK(true, "IASetVertexBuffers with one stream at an unreadable address returned");
|
||||
|
||||
// 4. Null bindings stay null bindings and are not logged.
|
||||
slot<SetIndexFn>(list, kListIASetIndexBuffer)(list, nullptr);
|
||||
const D3D12_INDEX_BUFFER_VIEW zero_index{0, 0, DXGI_FORMAT_R16_UINT};
|
||||
slot<SetIndexFn>(list, kListIASetIndexBuffer)(list, &zero_index);
|
||||
const D3D12_VERTEX_BUFFER_VIEW zero_vertex{0, 0, 0};
|
||||
slot<SetVertexFn>(list, kListIASetVertexBuffers)(list, 0, 1, &zero_vertex);
|
||||
|
||||
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "the list still closes");
|
||||
|
||||
const std::string after = read_log();
|
||||
if (!after.empty()) {
|
||||
CHECK(count_of(after, kIndexStub) - index_before == 1,
|
||||
"exactly the unreadable index binding is logged as unimplemented (logged %zu time(s))",
|
||||
count_of(after, kIndexStub) - index_before);
|
||||
CHECK(count_of(after, kVertexStub) - vertex_before == 1,
|
||||
"exactly the unreadable vertex stream is logged as unimplemented (logged %zu time(s))",
|
||||
count_of(after, kVertexStub) - vertex_before);
|
||||
} else {
|
||||
std::printf("note: no BX_LOG_FILE; the log checks did not run\n");
|
||||
}
|
||||
|
||||
VirtualFree(unreadable, 0, MEM_RELEASE);
|
||||
VirtualFree(plain, 0, MEM_RELEASE);
|
||||
for (void* object : {backed, list, allocator, queue, dev}) slot<ReleaseFn>(object, kRelease)(object);
|
||||
std::printf("%s: test_d3d12_unbacked_buffers (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS", g_checks - g_failed,
|
||||
g_checks);
|
||||
return g_failed ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# #671: D3DMetal capability checks for translated console shaders (SM 6.6 heap indexing,
|
||||
# 64-lane wave emulation, amplification and mesh shaders). Loads the host d3d12.dll at run time;
|
||||
# links no BetterXen shim. Shader headers are generated by shaders/compile.sh (DXC v1.9.2609)
|
||||
# and committed.
|
||||
add_executable(test_d3dmetal_translator_caps main.cpp)
|
||||
target_include_directories(test_d3dmetal_translator_caps PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
target_link_libraries(test_d3dmetal_translator_caps PRIVATE kernel32)
|
||||
@@ -0,0 +1,763 @@
|
||||
/*
|
||||
* #671: what D3DMetal does with the features translated console shaders need. Each check
|
||||
* ends in one result line, "RESULT: <check> runs-correctly | workaround | blocked", with the
|
||||
* observations it rests on:
|
||||
*
|
||||
* 1. heap_index SM 6.6 dynamic resources: a UAV, a raw SRV, a typed SRV, a texture and a
|
||||
* sampler all fetched from the descriptor heaps by index. runs-correctly when
|
||||
* every value matches.
|
||||
* 2. wave64 A 64-lane console wave on host hardware: the host's wave width, then two
|
||||
* routes over a 64-thread group, through groupshared memory and through the
|
||||
* host's own wave operations merged across waves (ballot, prefix sum, read
|
||||
* lane, active sum). workaround when a route gives the 64-lane answers; the
|
||||
* [WaveSize(64)] attribute itself is measured by test_d3dmetal_gpu_limits.
|
||||
* 3. atomic64 Measured by test_d3dmetal_gpu_limits (typed 64-bit atomics, lock emulation);
|
||||
* not repeated here.
|
||||
* 4. mesh Amplification -> mesh -> pixel into a 4x4 target: the reported mesh shader
|
||||
* tier, pipeline creation, and every pixel's value.
|
||||
*
|
||||
* Talks to the host d3d12.dll directly (no BetterXen shim in the path), so under
|
||||
* CrossOver/Wine with D3DMetal it measures D3DMetal. Expected values are computed here on
|
||||
* the CPU from the public HLSL/D3D12 semantics, never by the GPU.
|
||||
*
|
||||
* A check whose result is not runs-correctly is an observation, not a failure: the test exits
|
||||
* 0 when every result was reached, 1 when setup failed or the GPU hung, 77 without SM 6.6.
|
||||
*/
|
||||
#ifndef WIDL_EXPLICIT_AGGREGATE_RETURNS
|
||||
#define WIDL_EXPLICIT_AGGREGATE_RETURNS /* call struct-returning COM methods with the real x64 ABI */
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
#include <cstdarg>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
#include "shaders/heap_index.h"
|
||||
#include "shaders/mesh_as.h"
|
||||
#include "shaders/mesh_ms.h"
|
||||
#include "shaders/mesh_ps.h"
|
||||
#include "shaders/wave64_emulation.h"
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint32_t kSentinel = 0xA5A5A5A5u;
|
||||
constexpr DWORD kGpuTimeoutMs = 10000;
|
||||
int g_required = 0;
|
||||
int g_failures = 0;
|
||||
|
||||
__attribute__((format(gnu_printf, 2, 3)))
|
||||
bool require(bool ok, const char* fmt, ...) {
|
||||
g_required++;
|
||||
if (!ok) {
|
||||
g_failures++;
|
||||
char msg[320];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
std::vsnprintf(msg, sizeof(msg), fmt, ap);
|
||||
va_end(ap);
|
||||
std::fprintf(stderr, "FAIL: %s\n", msg);
|
||||
std::fflush(stderr);
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
__attribute__((format(gnu_printf, 1, 2)))
|
||||
void observed(const char* fmt, ...) {
|
||||
char msg[320];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
std::vsnprintf(msg, sizeof(msg), fmt, ap);
|
||||
va_end(ap);
|
||||
std::printf("OBSERVED: %s\n", msg);
|
||||
std::fflush(stdout);
|
||||
}
|
||||
|
||||
unsigned long ul(HRESULT hr) { return static_cast<unsigned long>(hr); }
|
||||
|
||||
template <typename T>
|
||||
void release(T*& p) {
|
||||
if (p) {
|
||||
p->Release();
|
||||
p = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- D3D12 plumbing ---- */
|
||||
|
||||
using PFN_CreateDevice = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**);
|
||||
using PFN_Serialize = HRESULT(WINAPI*)(const D3D12_ROOT_SIGNATURE_DESC*, D3D_ROOT_SIGNATURE_VERSION, ID3DBlob**,
|
||||
ID3DBlob**);
|
||||
|
||||
struct Gpu {
|
||||
ID3D12Device* dev = nullptr;
|
||||
ID3D12CommandQueue* queue = nullptr;
|
||||
ID3D12CommandAllocator* alloc = nullptr;
|
||||
ID3D12GraphicsCommandList* list = nullptr;
|
||||
ID3D12Fence* fence = nullptr;
|
||||
UINT64 fence_value = 0;
|
||||
HANDLE event = nullptr;
|
||||
PFN_Serialize serialize = nullptr;
|
||||
bool lost = false; /* a submission timed out or the device was removed */
|
||||
};
|
||||
|
||||
/* Close, submit, wait (bounded) and reopen the list. False on timeout or device removal. */
|
||||
bool submit(Gpu& g, const char* what) {
|
||||
if (g.lost) return false;
|
||||
HRESULT hr = g.list->Close();
|
||||
if (FAILED(hr)) {
|
||||
observed("%s command list Close failed hr=0x%08lx", what, ul(hr));
|
||||
return false;
|
||||
}
|
||||
ID3D12CommandList* lists[] = {g.list};
|
||||
g.queue->ExecuteCommandLists(1, lists);
|
||||
hr = g.queue->Signal(g.fence, ++g.fence_value);
|
||||
if (FAILED(hr)) {
|
||||
observed("%s queue Signal failed hr=0x%08lx", what, ul(hr));
|
||||
g.lost = true;
|
||||
return false;
|
||||
}
|
||||
if (g.fence->GetCompletedValue() < g.fence_value) {
|
||||
hr = g.fence->SetEventOnCompletion(g.fence_value, g.event);
|
||||
if (FAILED(hr) || WaitForSingleObject(g.event, kGpuTimeoutMs) != WAIT_OBJECT_0) {
|
||||
observed("%s GPU work did not finish within %lu ms (queue considered hung; later checks skipped)", what,
|
||||
static_cast<unsigned long>(kGpuTimeoutMs));
|
||||
g.lost = true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (g.fence->GetCompletedValue() == UINT64_MAX) {
|
||||
observed("%s device removed, reason hr=0x%08lx", what, ul(g.dev->GetDeviceRemovedReason()));
|
||||
g.lost = true;
|
||||
return false;
|
||||
}
|
||||
hr = g.alloc->Reset();
|
||||
if (SUCCEEDED(hr)) hr = g.list->Reset(g.alloc, nullptr);
|
||||
if (FAILED(hr)) {
|
||||
observed("%s allocator or command list Reset failed hr=0x%08lx", what, ul(hr));
|
||||
g.lost = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Discards whatever is recorded in the open list without executing it (used when a
|
||||
* check fails partway through recording), so the next check starts from an empty list. */
|
||||
void abandon(Gpu& g) {
|
||||
if (g.lost) return;
|
||||
g.list->Close();
|
||||
if (FAILED(g.alloc->Reset()) || FAILED(g.list->Reset(g.alloc, nullptr))) g.lost = true;
|
||||
}
|
||||
|
||||
/* Releases a resource the GPU may have used. After a hung or removed queue the GPU may
|
||||
* still reference it, so it is deliberately leaked instead. */
|
||||
template <typename T>
|
||||
void drop(const Gpu& g, T*& p) {
|
||||
if (g.lost) {
|
||||
p = nullptr;
|
||||
return;
|
||||
}
|
||||
release(p);
|
||||
}
|
||||
|
||||
ID3D12Resource* make_buffer(Gpu& g, D3D12_HEAP_TYPE heap, UINT64 size, D3D12_RESOURCE_STATES state,
|
||||
D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) {
|
||||
D3D12_HEAP_PROPERTIES hp = {};
|
||||
hp.Type = heap;
|
||||
D3D12_RESOURCE_DESC rd = {};
|
||||
rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
rd.Width = size;
|
||||
rd.Height = 1;
|
||||
rd.DepthOrArraySize = 1;
|
||||
rd.MipLevels = 1;
|
||||
rd.SampleDesc.Count = 1;
|
||||
rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
rd.Flags = flags;
|
||||
ID3D12Resource* r = nullptr;
|
||||
HRESULT hr = g.dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, state, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&r));
|
||||
return SUCCEEDED(hr) ? r : nullptr;
|
||||
}
|
||||
|
||||
ID3D12Resource* make_texture(Gpu& g, UINT width, UINT height, DXGI_FORMAT format) {
|
||||
D3D12_HEAP_PROPERTIES hp = {};
|
||||
hp.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
D3D12_RESOURCE_DESC rd = {};
|
||||
rd.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
rd.Width = width;
|
||||
rd.Height = height;
|
||||
rd.DepthOrArraySize = 1;
|
||||
rd.MipLevels = 1;
|
||||
rd.Format = format;
|
||||
rd.SampleDesc.Count = 1;
|
||||
rd.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
ID3D12Resource* r = nullptr;
|
||||
HRESULT hr = g.dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&r));
|
||||
return SUCCEEDED(hr) ? r : nullptr;
|
||||
}
|
||||
|
||||
void transition(Gpu& g, ID3D12Resource* r, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) {
|
||||
D3D12_RESOURCE_BARRIER b = {};
|
||||
b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
b.Transition.pResource = r;
|
||||
b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
b.Transition.StateBefore = before;
|
||||
b.Transition.StateAfter = after;
|
||||
g.list->ResourceBarrier(1, &b);
|
||||
}
|
||||
|
||||
bool map_write(ID3D12Resource* r, const void* src, size_t n) {
|
||||
void* p = nullptr;
|
||||
if (FAILED(r->Map(0, nullptr, &p)) || !p) return false;
|
||||
std::memcpy(p, src, n);
|
||||
r->Unmap(0, nullptr);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool map_read(ID3D12Resource* r, void* dst, size_t n) {
|
||||
void* p = nullptr;
|
||||
D3D12_RANGE range = {0, n};
|
||||
if (FAILED(r->Map(0, &range, &p)) || !p) return false;
|
||||
std::memcpy(dst, p, n);
|
||||
D3D12_RANGE none = {0, 0};
|
||||
r->Unmap(0, &none);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Root signature from parameters; logs and returns null on failure. */
|
||||
ID3D12RootSignature* make_root(Gpu& g, const char* what, const D3D12_ROOT_PARAMETER* params, UINT count) {
|
||||
D3D12_ROOT_SIGNATURE_DESC desc = {};
|
||||
desc.NumParameters = count;
|
||||
desc.pParameters = params;
|
||||
ID3DBlob* blob = nullptr;
|
||||
ID3DBlob* err = nullptr;
|
||||
HRESULT hr = g.serialize(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &err);
|
||||
release(err);
|
||||
if (FAILED(hr)) {
|
||||
observed("%s root signature serialization failed hr=0x%08lx", what, ul(hr));
|
||||
return nullptr;
|
||||
}
|
||||
ID3D12RootSignature* rs = nullptr;
|
||||
hr = g.dev->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), __uuidof(ID3D12RootSignature),
|
||||
reinterpret_cast<void**>(&rs));
|
||||
release(blob);
|
||||
if (FAILED(hr)) {
|
||||
observed("%s CreateRootSignature failed hr=0x%08lx", what, ul(hr));
|
||||
return nullptr;
|
||||
}
|
||||
return rs;
|
||||
}
|
||||
|
||||
ID3D12PipelineState* make_pipeline(Gpu& g, ID3D12RootSignature* rs, const unsigned char* code, size_t size,
|
||||
HRESULT* out_hr) {
|
||||
D3D12_COMPUTE_PIPELINE_STATE_DESC pd = {};
|
||||
pd.pRootSignature = rs;
|
||||
pd.CS.pShaderBytecode = code;
|
||||
pd.CS.BytecodeLength = size;
|
||||
ID3D12PipelineState* pso = nullptr;
|
||||
*out_hr = g.dev->CreateComputePipelineState(&pd, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(&pso));
|
||||
return SUCCEEDED(*out_hr) ? pso : nullptr;
|
||||
}
|
||||
|
||||
D3D12_ROOT_PARAMETER root_uav(UINT reg) {
|
||||
D3D12_ROOT_PARAMETER p = {};
|
||||
p.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
|
||||
p.Descriptor.ShaderRegister = reg;
|
||||
p.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
|
||||
return p;
|
||||
}
|
||||
|
||||
/* ---- buffer kernels: run one dispatch over a root-UAV buffer, return its words ---- */
|
||||
|
||||
bool run_buffer_kernel(Gpu& g, const char* what, ID3D12PipelineState* pso, ID3D12RootSignature* rs,
|
||||
const std::vector<uint32_t>& init, UINT groups, std::vector<uint32_t>& out) {
|
||||
const UINT64 bytes = init.size() * sizeof(uint32_t);
|
||||
ID3D12Resource* up = make_buffer(g, D3D12_HEAP_TYPE_UPLOAD, bytes, D3D12_RESOURCE_STATE_GENERIC_READ);
|
||||
ID3D12Resource* buf = make_buffer(g, D3D12_HEAP_TYPE_DEFAULT, bytes, D3D12_RESOURCE_STATE_COMMON,
|
||||
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
|
||||
ID3D12Resource* rb = make_buffer(g, D3D12_HEAP_TYPE_READBACK, bytes, D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
bool ok = up && buf && rb && map_write(up, init.data(), bytes);
|
||||
if (ok) {
|
||||
g.list->CopyBufferRegion(buf, 0, up, 0, bytes);
|
||||
transition(g, buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
|
||||
g.list->SetComputeRootSignature(rs);
|
||||
g.list->SetPipelineState(pso);
|
||||
g.list->SetComputeRootUnorderedAccessView(0, buf->GetGPUVirtualAddress());
|
||||
g.list->Dispatch(groups, 1, 1);
|
||||
transition(g, buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
g.list->CopyBufferRegion(rb, 0, buf, 0, bytes);
|
||||
ok = submit(g, what);
|
||||
out.assign(init.size(), 0);
|
||||
ok = ok && map_read(rb, out.data(), bytes);
|
||||
} else {
|
||||
observed("%s buffer creation or upload failed", what);
|
||||
}
|
||||
drop(g, up);
|
||||
drop(g, buf);
|
||||
drop(g, rb);
|
||||
return ok;
|
||||
}
|
||||
|
||||
struct TexCopy {
|
||||
D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp = {};
|
||||
UINT64 total = 0;
|
||||
};
|
||||
|
||||
TexCopy footprint(Gpu& g, ID3D12Resource* tex) {
|
||||
TexCopy t;
|
||||
D3D12_RESOURCE_DESC rd;
|
||||
tex->GetDesc(&rd);
|
||||
UINT rows = 0;
|
||||
UINT64 row_bytes = 0;
|
||||
g.dev->GetCopyableFootprints(&rd, 0, 1, 0, &t.fp, &rows, &row_bytes, &t.total);
|
||||
return t;
|
||||
}
|
||||
|
||||
void copy_to_texture(Gpu& g, ID3D12Resource* tex, ID3D12Resource* up, const TexCopy& t) {
|
||||
D3D12_TEXTURE_COPY_LOCATION dst = {};
|
||||
dst.pResource = tex;
|
||||
dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
|
||||
D3D12_TEXTURE_COPY_LOCATION src = {};
|
||||
src.pResource = up;
|
||||
src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
|
||||
src.PlacedFootprint = t.fp;
|
||||
g.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
|
||||
}
|
||||
|
||||
|
||||
void result(const char* check, const char* outcome, const char* why) {
|
||||
std::printf("RESULT: %s %s (%s)\n", check, outcome, why);
|
||||
}
|
||||
|
||||
ID3D12RootSignature* make_root_flags(Gpu& g, const char* what, const D3D12_ROOT_PARAMETER* params, UINT count,
|
||||
D3D12_ROOT_SIGNATURE_FLAGS flags) {
|
||||
D3D12_ROOT_SIGNATURE_DESC desc = {};
|
||||
desc.NumParameters = count;
|
||||
desc.pParameters = params;
|
||||
desc.Flags = flags;
|
||||
ID3DBlob* blob = nullptr;
|
||||
ID3DBlob* err = nullptr;
|
||||
HRESULT hr = g.serialize(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &err);
|
||||
if (FAILED(hr)) {
|
||||
observed("%s root signature serialization failed hr=0x%08lx %s", what, ul(hr),
|
||||
err ? static_cast<const char*>(err->GetBufferPointer()) : "");
|
||||
release(err);
|
||||
return nullptr;
|
||||
}
|
||||
release(err);
|
||||
ID3D12RootSignature* rs = nullptr;
|
||||
hr = g.dev->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), __uuidof(ID3D12RootSignature),
|
||||
reinterpret_cast<void**>(&rs));
|
||||
release(blob);
|
||||
if (FAILED(hr)) observed("%s CreateRootSignature failed hr=0x%08lx", what, ul(hr));
|
||||
return SUCCEEDED(hr) ? rs : nullptr;
|
||||
}
|
||||
|
||||
/* ---- 1. heap_index ---- */
|
||||
|
||||
void check_heap_index(Gpu& g) {
|
||||
D3D12_FEATURE_DATA_D3D12_OPTIONS o = {};
|
||||
if (SUCCEEDED(g.dev->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &o, sizeof(o)))) {
|
||||
observed("heap_index.resource_binding_tier %d", static_cast<int>(o.ResourceBindingTier));
|
||||
}
|
||||
D3D12_ROOT_PARAMETER constants = {};
|
||||
constants.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
|
||||
constants.Constants.ShaderRegister = 0;
|
||||
constants.Constants.Num32BitValues = 4;
|
||||
constants.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
|
||||
const auto flags = static_cast<D3D12_ROOT_SIGNATURE_FLAGS>(0x400 | 0x800); /* CBV_SRV_UAV_ and SAMPLER_HEAP_DIRECTLY_INDEXED */
|
||||
ID3D12RootSignature* rs = make_root_flags(g, "heap_index", &constants, 1, flags);
|
||||
if (!rs) {
|
||||
result("heap_index", "blocked", "root signature with directly indexed heaps refused");
|
||||
return;
|
||||
}
|
||||
HRESULT hr = S_OK;
|
||||
ID3D12PipelineState* pso = make_pipeline(g, rs, g_heap_index_cs, sizeof(g_heap_index_cs), &hr);
|
||||
if (!pso) {
|
||||
observed("heap_index CreateComputePipelineState hr=0x%08lx", ul(hr));
|
||||
result("heap_index", "blocked", "pipeline refused");
|
||||
release(rs);
|
||||
return;
|
||||
}
|
||||
|
||||
constexpr UINT kN = 64;
|
||||
std::vector<uint32_t> raw(kN), typed(kN);
|
||||
for (UINT i = 0; i < kN; ++i) {
|
||||
raw[i] = i * 5u + 1u;
|
||||
typed[i] = 1000u + i;
|
||||
}
|
||||
const float texels[4] = {1.0f, 2.5f, 3.0f, 4.0f}; /* 2x2, row-major; texel (1,0) is 2.5 */
|
||||
const UINT64 out_bytes = (kN + 1) * 4;
|
||||
ID3D12Resource* raw_up = make_buffer(g, D3D12_HEAP_TYPE_UPLOAD, kN * 4, D3D12_RESOURCE_STATE_GENERIC_READ);
|
||||
ID3D12Resource* typed_up = make_buffer(g, D3D12_HEAP_TYPE_UPLOAD, kN * 4, D3D12_RESOURCE_STATE_GENERIC_READ);
|
||||
ID3D12Resource* outb = make_buffer(g, D3D12_HEAP_TYPE_DEFAULT, out_bytes, D3D12_RESOURCE_STATE_COMMON,
|
||||
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
|
||||
ID3D12Resource* rb = make_buffer(g, D3D12_HEAP_TYPE_READBACK, out_bytes, D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
ID3D12Resource* tex = make_texture(g, 2, 2, DXGI_FORMAT_R32_FLOAT);
|
||||
TexCopy tc;
|
||||
ID3D12Resource* tex_up = nullptr;
|
||||
if (tex) {
|
||||
tc = footprint(g, tex);
|
||||
tex_up = make_buffer(g, D3D12_HEAP_TYPE_UPLOAD, tc.total, D3D12_RESOURCE_STATE_GENERIC_READ);
|
||||
}
|
||||
bool ok = raw_up && typed_up && outb && rb && tex && tex_up && map_write(raw_up, raw.data(), kN * 4) &&
|
||||
map_write(typed_up, typed.data(), kN * 4);
|
||||
if (ok) {
|
||||
std::vector<uint8_t> staging(tc.total, 0);
|
||||
for (UINT y = 0; y < 2; ++y) std::memcpy(&staging[tc.fp.Offset + y * tc.fp.Footprint.RowPitch], &texels[y * 2], 8);
|
||||
ok = map_write(tex_up, staging.data(), staging.size());
|
||||
}
|
||||
ID3D12DescriptorHeap* heap = nullptr;
|
||||
ID3D12DescriptorHeap* samplers = nullptr;
|
||||
if (ok) {
|
||||
D3D12_DESCRIPTOR_HEAP_DESC hd = {};
|
||||
hd.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
|
||||
hd.NumDescriptors = 4;
|
||||
hd.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
|
||||
D3D12_DESCRIPTOR_HEAP_DESC sd = hd;
|
||||
sd.Type = D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER;
|
||||
sd.NumDescriptors = 1;
|
||||
ok = SUCCEEDED(g.dev->CreateDescriptorHeap(&hd, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&heap))) &&
|
||||
SUCCEEDED(g.dev->CreateDescriptorHeap(&sd, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&samplers)));
|
||||
}
|
||||
if (ok) {
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE h;
|
||||
heap->GetCPUDescriptorHandleForHeapStart(&h);
|
||||
const UINT inc = g.dev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
|
||||
D3D12_UNORDERED_ACCESS_VIEW_DESC ud = {};
|
||||
ud.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
|
||||
ud.Buffer.NumElements = kN + 1;
|
||||
ud.Buffer.StructureByteStride = 4;
|
||||
g.dev->CreateUnorderedAccessView(outb, nullptr, &ud, h);
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC rd = {};
|
||||
rd.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
|
||||
rd.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
|
||||
rd.Format = DXGI_FORMAT_R32_TYPELESS;
|
||||
rd.Buffer.NumElements = kN;
|
||||
rd.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW;
|
||||
h.ptr += inc;
|
||||
g.dev->CreateShaderResourceView(raw_up, &rd, h);
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC td = rd;
|
||||
td.Format = DXGI_FORMAT_R32_UINT;
|
||||
td.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE;
|
||||
h.ptr += inc;
|
||||
g.dev->CreateShaderResourceView(typed_up, &td, h);
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC xd = {};
|
||||
xd.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
|
||||
xd.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
|
||||
xd.Format = DXGI_FORMAT_R32_FLOAT;
|
||||
xd.Texture2D.MipLevels = 1;
|
||||
h.ptr += inc;
|
||||
g.dev->CreateShaderResourceView(tex, &xd, h);
|
||||
D3D12_SAMPLER_DESC smp = {};
|
||||
smp.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
|
||||
smp.AddressU = smp.AddressV = smp.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
|
||||
smp.MaxLOD = 1000.0f;
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE sh;
|
||||
samplers->GetCPUDescriptorHandleForHeapStart(&sh);
|
||||
g.dev->CreateSampler(&smp, sh);
|
||||
|
||||
copy_to_texture(g, tex, tex_up, tc);
|
||||
transition(g, tex, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
|
||||
transition(g, outb, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
|
||||
ID3D12DescriptorHeap* heaps[] = {heap, samplers};
|
||||
g.list->SetDescriptorHeaps(2, heaps);
|
||||
g.list->SetComputeRootSignature(rs);
|
||||
g.list->SetPipelineState(pso);
|
||||
const UINT indices[4] = {0, 1, 2, 3};
|
||||
g.list->SetComputeRoot32BitConstants(0, 4, indices, 0);
|
||||
g.list->Dispatch(1, 1, 1);
|
||||
transition(g, outb, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
g.list->CopyBufferRegion(rb, 0, outb, 0, out_bytes);
|
||||
ok = submit(g, "heap_index");
|
||||
} else {
|
||||
observed("heap_index setup failed");
|
||||
abandon(g);
|
||||
}
|
||||
std::vector<uint32_t> out(kN + 1, kSentinel);
|
||||
if (ok) ok = map_read(rb, out.data(), out_bytes);
|
||||
if (!ok) {
|
||||
require(false, "heap_index: setup and GPU work must complete");
|
||||
} else {
|
||||
UINT wrong = 0;
|
||||
for (UINT i = 0; i < kN; ++i) wrong += out[i] != raw[i] * 3u + typed[i];
|
||||
float sampled = 0;
|
||||
std::memcpy(&sampled, &out[kN], 4);
|
||||
observed("heap_index buffers: %u of %u words wrong; first word 0x%08x (expected 0x%08x)", wrong, kN, out[0],
|
||||
raw[0] * 3u + typed[0]);
|
||||
observed("heap_index sampler+texture: got %g (expected 2.5)", static_cast<double>(sampled));
|
||||
const bool all = wrong == 0 && sampled == 2.5f;
|
||||
result("heap_index", all ? "runs-correctly" : "blocked",
|
||||
all ? "UAV, raw and typed SRVs, texture and sampler all fetched by heap index"
|
||||
: "values from heap-indexed descriptors are wrong");
|
||||
}
|
||||
drop(g, raw_up);
|
||||
drop(g, typed_up);
|
||||
drop(g, outb);
|
||||
drop(g, rb);
|
||||
drop(g, tex);
|
||||
drop(g, tex_up);
|
||||
drop(g, heap);
|
||||
drop(g, samplers);
|
||||
release(pso);
|
||||
release(rs);
|
||||
}
|
||||
|
||||
/* ---- 2. wave64 ---- */
|
||||
|
||||
uint32_t value_of(uint32_t lane) { return (lane * 7u + 3u) & 31u; }
|
||||
bool pred_of(uint32_t lane) { return ((lane * 13u + 5u) % 3u) == 0u; }
|
||||
|
||||
void check_wave64(Gpu& g) {
|
||||
D3D12_FEATURE_DATA_D3D12_OPTIONS1 o1 = {};
|
||||
if (SUCCEEDED(g.dev->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &o1, sizeof(o1)))) {
|
||||
observed("wave64.reported WaveOps=%d WaveLaneCountMin=%u WaveLaneCountMax=%u", o1.WaveOps ? 1 : 0,
|
||||
o1.WaveLaneCountMin, o1.WaveLaneCountMax);
|
||||
}
|
||||
D3D12_ROOT_PARAMETER params[] = {root_uav(0)};
|
||||
ID3D12RootSignature* rs = make_root(g, "wave64", params, 1);
|
||||
if (!require(rs != nullptr, "wave64 root signature")) return;
|
||||
HRESULT hr = S_OK;
|
||||
ID3D12PipelineState* pso = make_pipeline(g, rs, g_wave64_emulation_cs, sizeof(g_wave64_emulation_cs), &hr);
|
||||
if (!pso) {
|
||||
observed("wave64 CreateComputePipelineState hr=0x%08lx", ul(hr));
|
||||
result("wave64", "blocked", "emulation kernel refused");
|
||||
release(rs);
|
||||
return;
|
||||
}
|
||||
std::vector<uint32_t> out;
|
||||
const bool ran = run_buffer_kernel(g, "wave64", pso, rs, std::vector<uint32_t>(64 * 8, kSentinel), 1, out);
|
||||
release(pso);
|
||||
release(rs);
|
||||
if (!require(ran, "wave64: dispatch must complete")) return;
|
||||
|
||||
/* CPU reference for a 64-lane wave. */
|
||||
uint32_t lo = 0, hi = 0, total = 0;
|
||||
for (uint32_t i = 0; i < 64; ++i) {
|
||||
if (pred_of(i)) (i < 32 ? lo : hi) |= 1u << (i & 31u);
|
||||
total += value_of(i);
|
||||
}
|
||||
UINT shared_wrong = 0, native_wrong = 0;
|
||||
uint32_t prefix = 0;
|
||||
for (uint32_t lane = 0; lane < 64; ++lane) {
|
||||
const uint32_t* o = &out[lane * 8];
|
||||
shared_wrong += o[0] != lo || o[1] != hi || o[2] != prefix || o[3] != value_of(37) || o[4] != total;
|
||||
native_wrong += o[5] != lo || o[6] != hi || o[7] != prefix;
|
||||
prefix += value_of(lane);
|
||||
}
|
||||
observed("wave64 shared route: %u of 64 lanes wrong", shared_wrong);
|
||||
observed("wave64 native route: %u of 64 lanes wrong (ballot 0x%08x%08x, expected 0x%08x%08x)", native_wrong, out[6],
|
||||
out[5], hi, lo);
|
||||
if (shared_wrong == 0 && native_wrong == 0) {
|
||||
result("wave64", "workaround", "64-lane ballot, prefix sum, read lane and sum correct through groupshared memory and through merged host waves");
|
||||
} else if (shared_wrong == 0) {
|
||||
result("wave64", "workaround", "groupshared route correct; merged host waves wrong");
|
||||
} else {
|
||||
result("wave64", "blocked", "no route gave the 64-lane answers");
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- 4. mesh ---- */
|
||||
|
||||
struct alignas(void*) StreamRootSig { D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE; ID3D12RootSignature* rs; };
|
||||
struct alignas(void*) StreamShader { D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type; D3D12_SHADER_BYTECODE code; };
|
||||
struct alignas(void*) StreamRtFormats { D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS; D3D12_RT_FORMAT_ARRAY formats; };
|
||||
struct alignas(void*) StreamRasterizer { D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER; D3D12_RASTERIZER_DESC desc; };
|
||||
struct MeshStream {
|
||||
StreamRootSig rs;
|
||||
StreamShader as{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, {}};
|
||||
StreamShader ms{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, {}};
|
||||
StreamShader ps{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, {}};
|
||||
StreamRtFormats rt;
|
||||
StreamRasterizer raster;
|
||||
};
|
||||
|
||||
void check_mesh(Gpu& g) {
|
||||
D3D12_FEATURE_DATA_D3D12_OPTIONS7 o7 = {};
|
||||
const HRESULT qhr = g.dev->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &o7, sizeof(o7));
|
||||
observed("mesh.reported query hr=0x%08lx MeshShaderTier=%d", ul(qhr), SUCCEEDED(qhr) ? static_cast<int>(o7.MeshShaderTier) : -1);
|
||||
|
||||
ID3D12Device2* dev2 = nullptr;
|
||||
ID3D12GraphicsCommandList6* list6 = nullptr;
|
||||
g.dev->QueryInterface(__uuidof(ID3D12Device2), reinterpret_cast<void**>(&dev2));
|
||||
g.list->QueryInterface(__uuidof(ID3D12GraphicsCommandList6), reinterpret_cast<void**>(&list6));
|
||||
observed("mesh.interfaces ID3D12Device2=%d ID3D12GraphicsCommandList6=%d", dev2 ? 1 : 0, list6 ? 1 : 0);
|
||||
ID3D12RootSignature* rs = make_root(g, "mesh", nullptr, 0);
|
||||
ID3D12PipelineState* pso = nullptr;
|
||||
HRESULT hr = E_NOINTERFACE;
|
||||
if (dev2 && rs) {
|
||||
MeshStream s;
|
||||
s.rs.rs = rs;
|
||||
s.as.code = {g_mesh_as, sizeof(g_mesh_as)};
|
||||
s.ms.code = {g_mesh_ms, sizeof(g_mesh_ms)};
|
||||
s.ps.code = {g_mesh_ps, sizeof(g_mesh_ps)};
|
||||
s.rt.formats.NumRenderTargets = 1;
|
||||
s.rt.formats.RTFormats[0] = DXGI_FORMAT_R32_UINT;
|
||||
s.raster.desc.FillMode = D3D12_FILL_MODE_SOLID;
|
||||
s.raster.desc.CullMode = D3D12_CULL_MODE_NONE;
|
||||
s.raster.desc.DepthClipEnable = TRUE;
|
||||
D3D12_PIPELINE_STATE_STREAM_DESC sd = {sizeof(s), &s};
|
||||
hr = dev2->CreatePipelineState(&sd, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(&pso));
|
||||
}
|
||||
observed("mesh.pipeline CreatePipelineState hr=0x%08lx", ul(hr));
|
||||
if (!pso || !list6) {
|
||||
result("mesh", "blocked",
|
||||
SUCCEEDED(qhr) && o7.MeshShaderTier == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
|
||||
? "mesh shader tier not supported and the amplification+mesh pipeline is refused"
|
||||
: "the amplification+mesh pipeline is refused");
|
||||
release(pso);
|
||||
release(rs);
|
||||
release(list6);
|
||||
release(dev2);
|
||||
return;
|
||||
}
|
||||
|
||||
/* 4x4 R32_UINT target; group 0 covers the lower-left half, group 1 the upper-right. */
|
||||
D3D12_HEAP_PROPERTIES hp = {};
|
||||
hp.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
D3D12_RESOURCE_DESC rd = {};
|
||||
rd.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
rd.Width = 4;
|
||||
rd.Height = 4;
|
||||
rd.DepthOrArraySize = 1;
|
||||
rd.MipLevels = 1;
|
||||
rd.Format = DXGI_FORMAT_R32_UINT;
|
||||
rd.SampleDesc.Count = 1;
|
||||
rd.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
|
||||
D3D12_CLEAR_VALUE cv = {};
|
||||
cv.Format = DXGI_FORMAT_R32_UINT;
|
||||
ID3D12Resource* target = nullptr;
|
||||
g.dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_RENDER_TARGET, &cv,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&target));
|
||||
ID3D12DescriptorHeap* rtv = nullptr;
|
||||
D3D12_DESCRIPTOR_HEAP_DESC hd = {};
|
||||
hd.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
|
||||
hd.NumDescriptors = 1;
|
||||
g.dev->CreateDescriptorHeap(&hd, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&rtv));
|
||||
TexCopy tc;
|
||||
ID3D12Resource* rb = nullptr;
|
||||
if (target) {
|
||||
tc = footprint(g, target);
|
||||
rb = make_buffer(g, D3D12_HEAP_TYPE_READBACK, tc.total, D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
}
|
||||
bool ok = target && rtv && rb;
|
||||
if (ok) {
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE h;
|
||||
rtv->GetCPUDescriptorHandleForHeapStart(&h);
|
||||
g.dev->CreateRenderTargetView(target, nullptr, h);
|
||||
const float clear[4] = {0, 0, 0, 0};
|
||||
g.list->ClearRenderTargetView(h, clear, 0, nullptr);
|
||||
g.list->OMSetRenderTargets(1, &h, FALSE, nullptr);
|
||||
D3D12_VIEWPORT vp = {0, 0, 4, 4, 0, 1};
|
||||
D3D12_RECT sc = {0, 0, 4, 4};
|
||||
g.list->RSSetViewports(1, &vp);
|
||||
g.list->RSSetScissorRects(1, &sc);
|
||||
g.list->SetGraphicsRootSignature(rs);
|
||||
g.list->SetPipelineState(pso);
|
||||
list6->DispatchMesh(1, 1, 1);
|
||||
transition(g, target, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
D3D12_TEXTURE_COPY_LOCATION dst = {};
|
||||
dst.pResource = rb;
|
||||
dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
|
||||
dst.PlacedFootprint = tc.fp;
|
||||
D3D12_TEXTURE_COPY_LOCATION src = {};
|
||||
src.pResource = target;
|
||||
src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
|
||||
g.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
|
||||
ok = submit(g, "mesh");
|
||||
} else {
|
||||
observed("mesh render target setup failed");
|
||||
abandon(g);
|
||||
}
|
||||
std::vector<uint8_t> data(tc.total, 0);
|
||||
if (ok) ok = map_read(rb, data.data(), data.size());
|
||||
if (!ok) {
|
||||
require(false, "mesh: setup and GPU work must complete");
|
||||
} else {
|
||||
/* Pixel centre (x+0.5, y+0.5) in a 4x4 viewport; NDC y points up, so row y has
|
||||
* ndc_y = 1 - (y+0.5)/2. Group 0's triangle is x_ndc + y_ndc < 0 (payload 0x40),
|
||||
* group 1's is x_ndc + y_ndc > 0 (0x41); no pixel centre lies on the diagonal. */
|
||||
UINT wrong = 0, blank = 0;
|
||||
for (UINT y = 0; y < 4; ++y) {
|
||||
for (UINT x = 0; x < 4; ++x) {
|
||||
uint32_t v = 0;
|
||||
std::memcpy(&v, &data[tc.fp.Offset + y * tc.fp.Footprint.RowPitch + x * 4], 4);
|
||||
const double nx = (x + 0.5) / 2.0 - 1.0, ny = 1.0 - (y + 0.5) / 2.0;
|
||||
const uint32_t want = nx + ny < 0 ? 0x40u : 0x41u;
|
||||
blank += v == 0;
|
||||
wrong += v != want;
|
||||
}
|
||||
}
|
||||
observed("mesh pixels: %u of 16 wrong, %u left at the clear value", wrong, blank);
|
||||
result("mesh", wrong == 0 ? "runs-correctly" : "blocked",
|
||||
wrong == 0 ? "amplification payload and two mesh groups drawn as expected"
|
||||
: "the amplification+mesh pipeline did not draw the expected pixels");
|
||||
}
|
||||
drop(g, target);
|
||||
drop(g, rb);
|
||||
drop(g, rtv);
|
||||
release(pso);
|
||||
release(rs);
|
||||
release(list6);
|
||||
release(dev2);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
std::setvbuf(stdout, nullptr, _IONBF, 0);
|
||||
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
|
||||
auto create = d3d12 ? reinterpret_cast<PFN_CreateDevice>(reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice"))) : nullptr;
|
||||
Gpu g;
|
||||
g.serialize = d3d12 ? reinterpret_cast<PFN_Serialize>(
|
||||
reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12SerializeRootSignature"))) : nullptr;
|
||||
if (!create || !g.serialize) {
|
||||
std::printf("SKIP: d3d12.dll or its exports are unavailable\n");
|
||||
return 77;
|
||||
}
|
||||
HRESULT hr = create(nullptr, D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&g.dev));
|
||||
if (FAILED(hr) || !g.dev) {
|
||||
std::printf("SKIP: D3D12CreateDevice failed hr=0x%08lx\n", ul(hr));
|
||||
return 77;
|
||||
}
|
||||
D3D12_FEATURE_DATA_SHADER_MODEL sm = {D3D_SHADER_MODEL_6_6};
|
||||
if (FAILED(g.dev->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &sm, sizeof(sm))) ||
|
||||
sm.HighestShaderModel < D3D_SHADER_MODEL_6_6) {
|
||||
std::printf("SKIP: shader model 6.6 is not available\n");
|
||||
release(g.dev);
|
||||
return 77;
|
||||
}
|
||||
observed("device.shader_model 0x%x", static_cast<unsigned>(sm.HighestShaderModel));
|
||||
|
||||
D3D12_COMMAND_QUEUE_DESC qd = {};
|
||||
qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
|
||||
bool setup = SUCCEEDED(g.dev->CreateCommandQueue(&qd, __uuidof(ID3D12CommandQueue),
|
||||
reinterpret_cast<void**>(&g.queue))) &&
|
||||
SUCCEEDED(g.dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
|
||||
__uuidof(ID3D12CommandAllocator),
|
||||
reinterpret_cast<void**>(&g.alloc))) &&
|
||||
SUCCEEDED(g.dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g.alloc, nullptr,
|
||||
__uuidof(ID3D12GraphicsCommandList),
|
||||
reinterpret_cast<void**>(&g.list))) &&
|
||||
SUCCEEDED(g.dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence),
|
||||
reinterpret_cast<void**>(&g.fence)));
|
||||
g.event = CreateEventA(nullptr, FALSE, FALSE, nullptr);
|
||||
if (!require(setup && g.event, "queue, allocator, command list and fence creation")) return 1;
|
||||
|
||||
check_heap_index(g);
|
||||
check_wave64(g);
|
||||
std::printf("RESULT: atomic64 see-test_d3dmetal_gpu_limits (typed 64-bit atomics and their lock emulation are measured there)\n");
|
||||
check_mesh(g);
|
||||
if (g.lost) require(false, "GPU work must finish and the device must stay alive");
|
||||
|
||||
std::printf("SUMMARY: %d required checks, %d failed\n", g_required, g_failures);
|
||||
if (g.lost) return 1;
|
||||
release(g.fence);
|
||||
release(g.list);
|
||||
release(g.alloc);
|
||||
release(g.queue);
|
||||
release(g.dev);
|
||||
if (g.event) CloseHandle(g.event);
|
||||
return g_failures == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# Regenerates the committed *.h shader headers for test_d3dmetal_translator_caps (#671).
|
||||
# Needs Microsoft's official DXC release v1.9.2609 (dxc_2026_09_29.zip, SHA-256
|
||||
# ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1); it has no
|
||||
# macOS build, so bin/x64/dxc.exe runs under a Wine/CrossOver loader.
|
||||
#
|
||||
# WINE=/path/to/wine DXC=/path/to/dxc/bin/x64/dxc.exe ./compile.sh
|
||||
set -eu
|
||||
: "${WINE:?set WINE to a Wine or CrossOver wine loader}"
|
||||
: "${DXC:?set DXC to dxc.exe from the DXC v1.9.2609 release}"
|
||||
cd "$(dirname "$0")"
|
||||
dxc() { "$WINE" "$DXC" -nologo "$@"; }
|
||||
dxc -T cs_6_6 -E main -Vn g_heap_index_cs -Fh heap_index.h heap_index.hlsl
|
||||
dxc -T cs_6_6 -E main -Vn g_wave64_emulation_cs -Fh wave64_emulation.h wave64_emulation.hlsl
|
||||
dxc -T as_6_6 -E as_main -Vn g_mesh_as -Fh mesh_as.h mesh.hlsl
|
||||
dxc -T ms_6_6 -E ms_main -Vn g_mesh_ms -Fh mesh_ms.h mesh.hlsl
|
||||
dxc -T ps_6_6 -E ps_main -Vn g_mesh_ps -Fh mesh_ps.h mesh.hlsl
|
||||
for pair in heap_index:heap_index wave64_emulation:wave64_emulation mesh_as:mesh mesh_ms:mesh mesh_ps:mesh; do
|
||||
h=${pair%%:*} src=${pair#*:}
|
||||
{
|
||||
printf '// SPDX-License-Identifier: GPL-3.0-or-later\n//\n'
|
||||
printf '// GENERATED by DXC 1.9.2609 from %s.hlsl by compile.sh; do not edit.\n\n' "$src"
|
||||
tr -d '\r' < "$h.h"
|
||||
} > "$h.h.tmp" && mv "$h.h.tmp" "$h.h"
|
||||
done
|
||||
@@ -0,0 +1,517 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
// GENERATED by DXC 1.9.2609 from heap_index.hlsl by compile.sh; do not edit.
|
||||
|
||||
#if 0
|
||||
;
|
||||
; Note: shader requires additional functionality:
|
||||
; Resource descriptor heap indexing
|
||||
; Sampler descriptor heap indexing
|
||||
;
|
||||
;
|
||||
; Input signature:
|
||||
;
|
||||
; Name Index Mask Register SysValue Format Used
|
||||
; -------------------- ----- ------ -------- -------- ------- ------
|
||||
; no parameters
|
||||
;
|
||||
; Output signature:
|
||||
;
|
||||
; Name Index Mask Register SysValue Format Used
|
||||
; -------------------- ----- ------ -------- -------- ------- ------
|
||||
; no parameters
|
||||
; shader hash: b57f79fc70744ea5c2a5f08c555fc7c6
|
||||
;
|
||||
; Pipeline Runtime Information:
|
||||
;
|
||||
;PSVRuntimeInfo:
|
||||
; Compute Shader
|
||||
; NumThreads=(64,1,1)
|
||||
; MinimumExpectedWaveLaneCount: 0
|
||||
; MaximumExpectedWaveLaneCount: 4294967295
|
||||
; UsesViewID: false
|
||||
; SigInputElements: 0
|
||||
; SigOutputElements: 0
|
||||
; SigPatchConstOrPrimElements: 0
|
||||
; SigInputVectors: 0
|
||||
; SigOutputVectors[0]: 0
|
||||
; SigOutputVectors[1]: 0
|
||||
; SigOutputVectors[2]: 0
|
||||
; SigOutputVectors[3]: 0
|
||||
; EntryFunctionName: main
|
||||
;
|
||||
;
|
||||
; Buffer Definitions:
|
||||
;
|
||||
; cbuffer idx
|
||||
; {
|
||||
;
|
||||
; struct idx
|
||||
; {
|
||||
;
|
||||
; struct struct.Indices
|
||||
; {
|
||||
;
|
||||
; uint out_uav; ; Offset: 0
|
||||
; uint raw_srv; ; Offset: 4
|
||||
; uint typed_srv; ; Offset: 8
|
||||
; uint tex_srv; ; Offset: 12
|
||||
;
|
||||
; } idx; ; Offset: 0
|
||||
;
|
||||
;
|
||||
; } idx; ; Offset: 0 Size: 16
|
||||
;
|
||||
; }
|
||||
;
|
||||
;
|
||||
; Resource Bindings:
|
||||
;
|
||||
; Name Type Format Dim ID HLSL Bind Count
|
||||
; ------------------------------ ---------- ------- ----------- ------- -------------- ------
|
||||
; idx cbuffer NA NA CB0 cb0 1
|
||||
;
|
||||
target datalayout = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64"
|
||||
target triple = "dxil-ms-dx"
|
||||
|
||||
%dx.types.Handle = type { i8* }
|
||||
%dx.types.ResBind = type { i32, i32, i32, i8 }
|
||||
%dx.types.ResourceProperties = type { i32, i32 }
|
||||
%dx.types.CBufRet.i32 = type { i32, i32, i32, i32 }
|
||||
%dx.types.ResRet.i32 = type { i32, i32, i32, i32, i32 }
|
||||
%dx.types.ResRet.f32 = type { float, float, float, float, i32 }
|
||||
%idx = type { %struct.Indices }
|
||||
%struct.Indices = type { i32, i32, i32, i32 }
|
||||
|
||||
define void @main() {
|
||||
%1 = call %dx.types.Handle @dx.op.createHandleFromBinding(i32 217, %dx.types.ResBind { i32 0, i32 0, i32 0, i8 2 }, i32 0, i1 false) ; CreateHandleFromBinding(bind,index,nonUniformIndex)
|
||||
%2 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 13, i32 16 }) ; AnnotateHandle(res,props) resource: CBuffer
|
||||
%3 = call i32 @dx.op.threadId.i32(i32 93, i32 0) ; ThreadId(component)
|
||||
%4 = call %dx.types.CBufRet.i32 @dx.op.cbufferLoadLegacy.i32(i32 59, %dx.types.Handle %2, i32 0) ; CBufferLoadLegacy(handle,regIndex)
|
||||
%5 = extractvalue %dx.types.CBufRet.i32 %4, 0
|
||||
%6 = call %dx.types.Handle @dx.op.createHandleFromHeap(i32 218, i32 %5, i1 false, i1 false) ; CreateHandleFromHeap(index,samplerHeap,nonUniformIndex)
|
||||
%7 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %6, %dx.types.ResourceProperties { i32 4108, i32 4 }) ; AnnotateHandle(res,props) resource: RWStructuredBuffer<stride=4>
|
||||
%8 = extractvalue %dx.types.CBufRet.i32 %4, 1
|
||||
%9 = call %dx.types.Handle @dx.op.createHandleFromHeap(i32 218, i32 %8, i1 false, i1 false) ; CreateHandleFromHeap(index,samplerHeap,nonUniformIndex)
|
||||
%10 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %9, %dx.types.ResourceProperties { i32 11, i32 0 }) ; AnnotateHandle(res,props) resource: ByteAddressBuffer
|
||||
%11 = extractvalue %dx.types.CBufRet.i32 %4, 2
|
||||
%12 = call %dx.types.Handle @dx.op.createHandleFromHeap(i32 218, i32 %11, i1 false, i1 false) ; CreateHandleFromHeap(index,samplerHeap,nonUniformIndex)
|
||||
%13 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %12, %dx.types.ResourceProperties { i32 10, i32 261 }) ; AnnotateHandle(res,props) resource: TypedBuffer<U32>
|
||||
%14 = shl i32 %3, 2
|
||||
%15 = call %dx.types.ResRet.i32 @dx.op.rawBufferLoad.i32(i32 139, %dx.types.Handle %10, i32 %14, i32 undef, i8 1, i32 4) ; RawBufferLoad(srv,index,elementOffset,mask,alignment)
|
||||
%16 = extractvalue %dx.types.ResRet.i32 %15, 0
|
||||
%17 = mul i32 %16, 3
|
||||
%18 = call %dx.types.ResRet.i32 @dx.op.bufferLoad.i32(i32 68, %dx.types.Handle %13, i32 %3, i32 undef) ; BufferLoad(srv,index,wot)
|
||||
%19 = extractvalue %dx.types.ResRet.i32 %18, 0
|
||||
%20 = add i32 %17, %19
|
||||
call void @dx.op.rawBufferStore.i32(i32 140, %dx.types.Handle %7, i32 %3, i32 0, i32 %20, i32 undef, i32 undef, i32 undef, i8 1, i32 4) ; RawBufferStore(uav,index,elementOffset,value0,value1,value2,value3,mask,alignment)
|
||||
%21 = icmp eq i32 %3, 0
|
||||
br i1 %21, label %22, label %32
|
||||
|
||||
; <label>:22 ; preds = %0
|
||||
%23 = call %dx.types.CBufRet.i32 @dx.op.cbufferLoadLegacy.i32(i32 59, %dx.types.Handle %2, i32 0) ; CBufferLoadLegacy(handle,regIndex)
|
||||
%24 = extractvalue %dx.types.CBufRet.i32 %23, 3
|
||||
%25 = call %dx.types.Handle @dx.op.createHandleFromHeap(i32 218, i32 %24, i1 false, i1 false) ; CreateHandleFromHeap(index,samplerHeap,nonUniformIndex)
|
||||
%26 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %25, %dx.types.ResourceProperties { i32 2, i32 265 }) ; AnnotateHandle(res,props) resource: Texture2D<F32>
|
||||
%27 = call %dx.types.Handle @dx.op.createHandleFromHeap(i32 218, i32 0, i1 true, i1 false) ; CreateHandleFromHeap(index,samplerHeap,nonUniformIndex)
|
||||
%28 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %27, %dx.types.ResourceProperties { i32 14, i32 0 }) ; AnnotateHandle(res,props) resource: SamplerState
|
||||
%29 = call %dx.types.ResRet.f32 @dx.op.sampleLevel.f32(i32 62, %dx.types.Handle %26, %dx.types.Handle %28, float 7.500000e-01, float 2.500000e-01, float undef, float undef, i32 0, i32 0, i32 undef, float 0.000000e+00) ; SampleLevel(srv,sampler,coord0,coord1,coord2,coord3,offset0,offset1,offset2,LOD)
|
||||
%30 = extractvalue %dx.types.ResRet.f32 %29, 0
|
||||
%31 = bitcast float %30 to i32
|
||||
call void @dx.op.rawBufferStore.i32(i32 140, %dx.types.Handle %7, i32 64, i32 0, i32 %31, i32 undef, i32 undef, i32 undef, i8 1, i32 4) ; RawBufferStore(uav,index,elementOffset,value0,value1,value2,value3,mask,alignment)
|
||||
br label %32
|
||||
|
||||
; <label>:32 ; preds = %22, %0
|
||||
ret void
|
||||
}
|
||||
|
||||
; Function Attrs: nounwind readnone
|
||||
declare i32 @dx.op.threadId.i32(i32, i32) #0
|
||||
|
||||
; Function Attrs: nounwind readnone
|
||||
declare %dx.types.Handle @dx.op.createHandleFromHeap(i32, i32, i1, i1) #0
|
||||
|
||||
; Function Attrs: nounwind readonly
|
||||
declare %dx.types.ResRet.i32 @dx.op.rawBufferLoad.i32(i32, %dx.types.Handle, i32, i32, i8, i32) #1
|
||||
|
||||
; Function Attrs: nounwind
|
||||
declare void @dx.op.rawBufferStore.i32(i32, %dx.types.Handle, i32, i32, i32, i32, i32, i32, i8, i32) #2
|
||||
|
||||
; Function Attrs: nounwind readonly
|
||||
declare %dx.types.ResRet.i32 @dx.op.bufferLoad.i32(i32, %dx.types.Handle, i32, i32) #1
|
||||
|
||||
; Function Attrs: nounwind readonly
|
||||
declare %dx.types.ResRet.f32 @dx.op.sampleLevel.f32(i32, %dx.types.Handle, %dx.types.Handle, float, float, float, float, i32, i32, i32, float) #1
|
||||
|
||||
; Function Attrs: nounwind readonly
|
||||
declare %dx.types.CBufRet.i32 @dx.op.cbufferLoadLegacy.i32(i32, %dx.types.Handle, i32) #1
|
||||
|
||||
; Function Attrs: nounwind readnone
|
||||
declare %dx.types.Handle @dx.op.annotateHandle(i32, %dx.types.Handle, %dx.types.ResourceProperties) #0
|
||||
|
||||
; Function Attrs: nounwind readnone
|
||||
declare %dx.types.Handle @dx.op.createHandleFromBinding(i32, %dx.types.ResBind, i32, i1) #0
|
||||
|
||||
attributes #0 = { nounwind readnone }
|
||||
attributes #1 = { nounwind readonly }
|
||||
attributes #2 = { nounwind }
|
||||
|
||||
!llvm.ident = !{!0}
|
||||
!dx.version = !{!1}
|
||||
!dx.valver = !{!2}
|
||||
!dx.shaderModel = !{!3}
|
||||
!dx.resources = !{!4}
|
||||
!dx.entryPoints = !{!7}
|
||||
|
||||
!0 = !{!"dxcoob 1.9.2609.5 (01b62ad47)"}
|
||||
!1 = !{i32 1, i32 6}
|
||||
!2 = !{i32 1, i32 9}
|
||||
!3 = !{!"cs", i32 6, i32 6}
|
||||
!4 = !{null, null, !5, null}
|
||||
!5 = !{!6}
|
||||
!6 = !{i32 0, %idx* undef, !"", i32 0, i32 0, i32 1, i32 16, null}
|
||||
!7 = !{void ()* @main, !"main", null, !4, !8}
|
||||
!8 = !{i32 0, i64 3221225472, i32 4, !9}
|
||||
!9 = !{i32 64, i32 1, i32 1}
|
||||
|
||||
#endif
|
||||
|
||||
const unsigned char g_heap_index_cs[] = {
|
||||
0x44, 0x58, 0x42, 0x43, 0x6a, 0x10, 0xf2, 0x40, 0x08, 0xc9, 0x05, 0xa5,
|
||||
0xec, 0x67, 0xcc, 0x3b, 0xf4, 0x14, 0x30, 0xfb, 0x01, 0x00, 0x00, 0x00,
|
||||
0xc4, 0x0f, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00,
|
||||
0x4c, 0x00, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00, 0x6c, 0x00, 0x00, 0x00,
|
||||
0xdc, 0x00, 0x00, 0x00, 0xe4, 0x07, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00,
|
||||
0x53, 0x46, 0x49, 0x30, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06,
|
||||
0x00, 0x00, 0x00, 0x00, 0x49, 0x53, 0x47, 0x31, 0x08, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x4f, 0x53, 0x47, 0x31,
|
||||
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
|
||||
0x50, 0x53, 0x56, 0x30, 0x68, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
|
||||
0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x40, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
|
||||
0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
|
||||
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x08, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x53, 0x54, 0x41, 0x54, 0x00, 0x07, 0x00, 0x00,
|
||||
0x66, 0x00, 0x05, 0x00, 0xc0, 0x01, 0x00, 0x00, 0x44, 0x58, 0x49, 0x4c,
|
||||
0x06, 0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0xe8, 0x06, 0x00, 0x00,
|
||||
0x42, 0x43, 0xc0, 0xde, 0x21, 0x0c, 0x00, 0x00, 0xb7, 0x01, 0x00, 0x00,
|
||||
0x0b, 0x82, 0x20, 0x00, 0x02, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
|
||||
0x07, 0x81, 0x23, 0x91, 0x41, 0xc8, 0x04, 0x49, 0x06, 0x10, 0x32, 0x39,
|
||||
0x92, 0x01, 0x84, 0x0c, 0x25, 0x05, 0x08, 0x19, 0x1e, 0x04, 0x8b, 0x62,
|
||||
0x80, 0x18, 0x45, 0x02, 0x42, 0x92, 0x0b, 0x42, 0xc4, 0x10, 0x32, 0x14,
|
||||
0x38, 0x08, 0x18, 0x4b, 0x0a, 0x32, 0x62, 0x88, 0x48, 0x90, 0x14, 0x20,
|
||||
0x43, 0x46, 0x88, 0xa5, 0x00, 0x19, 0x32, 0x42, 0xe4, 0x48, 0x0e, 0x90,
|
||||
0x11, 0x23, 0xc4, 0x50, 0x41, 0x51, 0x81, 0x8c, 0xe1, 0x83, 0xe5, 0x8a,
|
||||
0x04, 0x31, 0x46, 0x06, 0x51, 0x18, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
|
||||
0x1b, 0x8c, 0xe0, 0xff, 0xff, 0xff, 0xff, 0x07, 0x40, 0x02, 0xa8, 0x0d,
|
||||
0x86, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x03, 0x20, 0x01, 0xd5, 0x06, 0x62,
|
||||
0xf8, 0xff, 0xff, 0xff, 0xff, 0x01, 0x90, 0x00, 0x49, 0x18, 0x00, 0x00,
|
||||
0x03, 0x00, 0x00, 0x00, 0x13, 0x82, 0x60, 0x42, 0x20, 0x4c, 0x08, 0x06,
|
||||
0x00, 0x00, 0x00, 0x00, 0x89, 0x20, 0x00, 0x00, 0x42, 0x00, 0x00, 0x00,
|
||||
0x32, 0x22, 0x88, 0x09, 0x20, 0x64, 0x85, 0x04, 0x13, 0x23, 0xa4, 0x84,
|
||||
0x04, 0x13, 0x23, 0xe3, 0x84, 0xa1, 0x90, 0x14, 0x12, 0x4c, 0x8c, 0x8c,
|
||||
0x0b, 0x84, 0xc4, 0x4c, 0x10, 0x94, 0xc1, 0x08, 0x40, 0x09, 0x00, 0x0a,
|
||||
0xe6, 0x08, 0xc0, 0xa0, 0x0c, 0xc3, 0x30, 0x10, 0x31, 0x47, 0x80, 0x90,
|
||||
0x71, 0xcf, 0x70, 0xf9, 0x13, 0xf6, 0x10, 0x92, 0x1f, 0x02, 0xcd, 0xb0,
|
||||
0x10, 0x28, 0x38, 0xe6, 0x08, 0x82, 0x52, 0x20, 0xc3, 0x90, 0x24, 0xa4,
|
||||
0xdc, 0x34, 0x5c, 0xfe, 0x84, 0x3d, 0x84, 0xe4, 0xaf, 0x84, 0xb4, 0x12,
|
||||
0x93, 0x8f, 0xdc, 0x36, 0x2a, 0x86, 0x61, 0x18, 0x86, 0x72, 0x30, 0x03,
|
||||
0x32, 0x0c, 0xc6, 0x40, 0x4d, 0x59, 0x80, 0x01, 0x19, 0x86, 0x61, 0x18,
|
||||
0x06, 0x63, 0xa0, 0xa7, 0x14, 0xcc, 0x80, 0x0c, 0x03, 0x45, 0x33, 0x00,
|
||||
0x37, 0x0d, 0x97, 0x3f, 0x61, 0x0f, 0x21, 0xf9, 0x2b, 0x21, 0xad, 0xc4,
|
||||
0xe4, 0x17, 0xb7, 0x8d, 0x8a, 0x69, 0x9a, 0xa6, 0xa1, 0x30, 0xd4, 0x80,
|
||||
0x20, 0xd3, 0x34, 0x4d, 0xc3, 0x30, 0x4c, 0x54, 0x1d, 0x35, 0x5c, 0xfe,
|
||||
0x84, 0x3d, 0x84, 0xe4, 0x73, 0x1b, 0x55, 0xac, 0xc4, 0xe4, 0x23, 0xb7,
|
||||
0x8d, 0x88, 0x61, 0x18, 0x86, 0x42, 0x5c, 0x03, 0x32, 0x10, 0x76, 0xdb,
|
||||
0x70, 0xf9, 0x13, 0xf6, 0x10, 0x92, 0xbf, 0x12, 0x92, 0x43, 0x45, 0x02,
|
||||
0x91, 0x46, 0xce, 0x43, 0x44, 0x13, 0x42, 0x48, 0x48, 0x18, 0x86, 0x42,
|
||||
0x20, 0x03, 0xa2, 0xd1, 0x76, 0xd0, 0x70, 0xf9, 0x13, 0xf6, 0x10, 0x92,
|
||||
0xbf, 0x12, 0xd2, 0x86, 0x34, 0x03, 0x22, 0x86, 0x61, 0x30, 0x4a, 0x81,
|
||||
0x0c, 0xdd, 0x90, 0x90, 0x37, 0x10, 0x70, 0x8e, 0x34, 0x45, 0x94, 0x30,
|
||||
0xf9, 0x62, 0x33, 0x20, 0x02, 0x21, 0x21, 0x62, 0x18, 0x86, 0xe1, 0x06,
|
||||
0x64, 0xb8, 0x50, 0x10, 0x92, 0x38, 0x47, 0x00, 0x0a, 0x00, 0x00, 0x00,
|
||||
0x13, 0x14, 0x72, 0xc0, 0x87, 0x74, 0x60, 0x87, 0x36, 0x68, 0x87, 0x79,
|
||||
0x68, 0x03, 0x72, 0xc0, 0x87, 0x0d, 0xaf, 0x50, 0x0e, 0x6d, 0xd0, 0x0e,
|
||||
0x7a, 0x50, 0x0e, 0x6d, 0x00, 0x0f, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07,
|
||||
0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x71, 0xa0, 0x07, 0x73, 0x20, 0x07,
|
||||
0x6d, 0x90, 0x0e, 0x78, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e,
|
||||
0x71, 0x60, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xd0, 0x06, 0xe9, 0x30, 0x07,
|
||||
0x72, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x76, 0x40, 0x07,
|
||||
0x7a, 0x60, 0x07, 0x74, 0xd0, 0x06, 0xe6, 0x10, 0x07, 0x76, 0xa0, 0x07,
|
||||
0x73, 0x20, 0x07, 0x6d, 0x60, 0x0e, 0x73, 0x20, 0x07, 0x7a, 0x30, 0x07,
|
||||
0x72, 0xd0, 0x06, 0xe6, 0x60, 0x07, 0x74, 0xa0, 0x07, 0x76, 0x40, 0x07,
|
||||
0x6d, 0xe0, 0x0e, 0x78, 0xa0, 0x07, 0x71, 0x60, 0x07, 0x7a, 0x30, 0x07,
|
||||
0x72, 0xa0, 0x07, 0x76, 0x40, 0x07, 0x43, 0x9e, 0x00, 0x08, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0x3c, 0x04, 0x10, 0x00,
|
||||
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x79, 0x14, 0x20,
|
||||
0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xf2, 0x34,
|
||||
0x40, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0xe4,
|
||||
0x79, 0x80, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60,
|
||||
0xc8, 0x13, 0x01, 0x01, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0xc0, 0x90, 0xa7, 0x02, 0x02, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x80, 0x21, 0x0f, 0x06, 0x04, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x43, 0x9e, 0x0d, 0x08, 0x80, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x86, 0x3c, 0x1e, 0x10, 0x00, 0x01, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x81, 0x00, 0x0e, 0x00, 0x00, 0x00,
|
||||
0x32, 0x1e, 0x98, 0x14, 0x19, 0x11, 0x4c, 0x90, 0x8c, 0x09, 0x26, 0x47,
|
||||
0xc6, 0x04, 0x43, 0x1a, 0x4a, 0xa0, 0x18, 0x46, 0x00, 0x0a, 0xa4, 0x0c,
|
||||
0xca, 0xa1, 0x14, 0x0a, 0xa1, 0x20, 0x0a, 0xa3, 0x00, 0x03, 0xca, 0xa8,
|
||||
0x08, 0x88, 0x2c, 0x40, 0x40, 0x40, 0x40, 0x0c, 0x12, 0x67, 0x00, 0x68,
|
||||
0x9c, 0x01, 0xa0, 0x70, 0x06, 0x00, 0x00, 0x00, 0x79, 0x18, 0x00, 0x00,
|
||||
0x75, 0x00, 0x00, 0x00, 0x1a, 0x03, 0x4c, 0x90, 0x46, 0x02, 0x13, 0xc4,
|
||||
0x8e, 0x0c, 0x6f, 0xec, 0xed, 0x4d, 0x0c, 0x24, 0xc6, 0x25, 0xc7, 0x45,
|
||||
0xc6, 0x06, 0x26, 0xc7, 0xa5, 0x06, 0x04, 0x05, 0x26, 0x46, 0xcc, 0x46,
|
||||
0x26, 0x8c, 0x8c, 0xe6, 0x26, 0x65, 0x43, 0x10, 0x4c, 0x10, 0x06, 0x65,
|
||||
0x82, 0x30, 0x2c, 0x1b, 0x84, 0x81, 0x98, 0x20, 0x0c, 0xcc, 0x06, 0xc1,
|
||||
0x30, 0x28, 0x8c, 0xcd, 0x6d, 0x18, 0x10, 0x82, 0x98, 0x20, 0x8c, 0x41,
|
||||
0xc6, 0x21, 0x8d, 0x0c, 0x6f, 0x82, 0x30, 0x34, 0x1b, 0x10, 0x43, 0x59,
|
||||
0x0c, 0x63, 0x60, 0x80, 0x0d, 0x41, 0xb3, 0x81, 0x00, 0x00, 0x07, 0x98,
|
||||
0x20, 0x84, 0x81, 0xc6, 0xe3, 0xad, 0x8e, 0xee, 0xab, 0x2e, 0xcc, 0x6e,
|
||||
0x82, 0x30, 0x38, 0x13, 0x84, 0xe1, 0x99, 0x20, 0x0c, 0xd0, 0x06, 0x83,
|
||||
0x88, 0x24, 0x63, 0xa2, 0x78, 0xc8, 0x85, 0xdd, 0x7d, 0xcd, 0xc9, 0xd9,
|
||||
0x4d, 0x10, 0x86, 0x68, 0x83, 0x41, 0x58, 0xd2, 0x35, 0x51, 0x4c, 0xe8,
|
||||
0xf2, 0xe0, 0xca, 0xc8, 0xbe, 0xe6, 0xe4, 0xec, 0x26, 0x08, 0x83, 0xb4,
|
||||
0xc1, 0x20, 0x32, 0x49, 0x9b, 0x28, 0x1e, 0x74, 0x65, 0x78, 0x5f, 0x73,
|
||||
0x72, 0x76, 0x13, 0x84, 0x61, 0xda, 0x60, 0x10, 0x9c, 0xd4, 0x4d, 0xd4,
|
||||
0x86, 0x82, 0xa9, 0xb0, 0xcd, 0x9b, 0x20, 0x88, 0x01, 0xb6, 0x81, 0x20,
|
||||
0x16, 0xc9, 0xd8, 0x20, 0x30, 0x61, 0xb0, 0xa1, 0x30, 0xa0, 0x0f, 0x0c,
|
||||
0xc4, 0x60, 0x82, 0x20, 0x00, 0x1b, 0x80, 0x0d, 0x83, 0x51, 0x06, 0x65,
|
||||
0xb0, 0x21, 0x30, 0x83, 0x0d, 0xc3, 0x40, 0x06, 0x67, 0x40, 0xa2, 0x2d,
|
||||
0x2c, 0xcd, 0x6d, 0x82, 0x40, 0x06, 0xd7, 0x04, 0x61, 0xa0, 0x36, 0x0c,
|
||||
0x6b, 0x30, 0x0c, 0x1b, 0x08, 0x43, 0x0d, 0x2e, 0x36, 0xd8, 0x50, 0x90,
|
||||
0x41, 0x1a, 0x00, 0x4f, 0x1b, 0x10, 0x11, 0x93, 0x0b, 0x73, 0x1b, 0x43,
|
||||
0x2b, 0x9b, 0x63, 0x91, 0xe6, 0x36, 0x47, 0x37, 0x37, 0x41, 0x18, 0x2a,
|
||||
0x12, 0x69, 0x6e, 0x74, 0x73, 0x44, 0xe8, 0xca, 0xf0, 0xbe, 0xd8, 0xde,
|
||||
0xc2, 0xc8, 0x26, 0x08, 0x83, 0x45, 0x84, 0xae, 0x0c, 0xef, 0xcb, 0xed,
|
||||
0x4d, 0xae, 0x8d, 0x09, 0x5d, 0x19, 0xde, 0xd7, 0x1c, 0xdd, 0x9b, 0x5c,
|
||||
0x19, 0x8b, 0xba, 0x34, 0x37, 0xba, 0xb9, 0x0d, 0xce, 0x1b, 0x0c, 0x70,
|
||||
0x10, 0x07, 0x72, 0x20, 0xcd, 0x01, 0x1d, 0xd4, 0xc1, 0x60, 0x07, 0x74,
|
||||
0x70, 0x07, 0x43, 0x15, 0x36, 0x36, 0xbb, 0x36, 0x97, 0x34, 0xb2, 0x32,
|
||||
0x37, 0xba, 0x29, 0x41, 0x50, 0x85, 0x0c, 0xcf, 0xc5, 0xae, 0x4c, 0x6e,
|
||||
0x2e, 0xed, 0xcd, 0x6d, 0x4a, 0x40, 0x34, 0x21, 0xc3, 0x73, 0xb1, 0x0b,
|
||||
0x63, 0xb3, 0x2b, 0x93, 0x9b, 0x12, 0x18, 0x75, 0xc8, 0xf0, 0x5c, 0xe6,
|
||||
0xd0, 0xc2, 0xc8, 0xca, 0xe4, 0x9a, 0xde, 0xc8, 0xca, 0xd8, 0xa6, 0x04,
|
||||
0x48, 0x19, 0x32, 0x3c, 0x17, 0xb9, 0xb2, 0xb9, 0xb7, 0x3a, 0xb9, 0xb1,
|
||||
0xb2, 0xb9, 0x29, 0x81, 0x53, 0x89, 0x0c, 0xcf, 0x85, 0x2e, 0x0f, 0xae,
|
||||
0x2c, 0xc8, 0xcd, 0xed, 0x8d, 0x2e, 0x8c, 0x2e, 0xed, 0xcd, 0x6d, 0x6e,
|
||||
0x8a, 0x20, 0x06, 0x67, 0x50, 0x87, 0x0c, 0xcf, 0xa5, 0xcc, 0x8d, 0x4e,
|
||||
0x2e, 0x0f, 0xea, 0x2d, 0xcd, 0x8d, 0x6e, 0x6e, 0x4a, 0xd0, 0x06, 0x5d,
|
||||
0xc8, 0xf0, 0x5c, 0xc6, 0xde, 0xea, 0xdc, 0xe8, 0xca, 0xe4, 0xe6, 0xa6,
|
||||
0x04, 0x77, 0x00, 0x00, 0x79, 0x18, 0x00, 0x00, 0x51, 0x00, 0x00, 0x00,
|
||||
0x33, 0x08, 0x80, 0x1c, 0xc4, 0xe1, 0x1c, 0x66, 0x14, 0x01, 0x3d, 0x88,
|
||||
0x43, 0x38, 0x84, 0xc3, 0x8c, 0x42, 0x80, 0x07, 0x79, 0x78, 0x07, 0x73,
|
||||
0x98, 0x71, 0x0c, 0xe6, 0x00, 0x0f, 0xed, 0x10, 0x0e, 0xf4, 0x80, 0x0e,
|
||||
0x33, 0x0c, 0x42, 0x1e, 0xc2, 0xc1, 0x1d, 0xce, 0xa1, 0x1c, 0x66, 0x30,
|
||||
0x05, 0x3d, 0x88, 0x43, 0x38, 0x84, 0x83, 0x1b, 0xcc, 0x03, 0x3d, 0xc8,
|
||||
0x43, 0x3d, 0x8c, 0x03, 0x3d, 0xcc, 0x78, 0x8c, 0x74, 0x70, 0x07, 0x7b,
|
||||
0x08, 0x07, 0x79, 0x48, 0x87, 0x70, 0x70, 0x07, 0x7a, 0x70, 0x03, 0x76,
|
||||
0x78, 0x87, 0x70, 0x20, 0x87, 0x19, 0xcc, 0x11, 0x0e, 0xec, 0x90, 0x0e,
|
||||
0xe1, 0x30, 0x0f, 0x6e, 0x30, 0x0f, 0xe3, 0xf0, 0x0e, 0xf0, 0x50, 0x0e,
|
||||
0x33, 0x10, 0xc4, 0x1d, 0xde, 0x21, 0x1c, 0xd8, 0x21, 0x1d, 0xc2, 0x61,
|
||||
0x1e, 0x66, 0x30, 0x89, 0x3b, 0xbc, 0x83, 0x3b, 0xd0, 0x43, 0x39, 0xb4,
|
||||
0x03, 0x3c, 0xbc, 0x83, 0x3c, 0x84, 0x03, 0x3b, 0xcc, 0xf0, 0x14, 0x76,
|
||||
0x60, 0x07, 0x7b, 0x68, 0x07, 0x37, 0x68, 0x87, 0x72, 0x68, 0x07, 0x37,
|
||||
0x80, 0x87, 0x70, 0x90, 0x87, 0x70, 0x60, 0x07, 0x76, 0x28, 0x07, 0x76,
|
||||
0xf8, 0x05, 0x76, 0x78, 0x87, 0x77, 0x80, 0x87, 0x5f, 0x08, 0x87, 0x71,
|
||||
0x18, 0x87, 0x72, 0x98, 0x87, 0x79, 0x98, 0x81, 0x2c, 0xee, 0xf0, 0x0e,
|
||||
0xee, 0xe0, 0x0e, 0xf5, 0xc0, 0x0e, 0xec, 0x30, 0x03, 0x62, 0xc8, 0xa1,
|
||||
0x1c, 0xe4, 0xa1, 0x1c, 0xcc, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c, 0xdc, 0x61,
|
||||
0x1c, 0xca, 0x21, 0x1c, 0xc4, 0x81, 0x1d, 0xca, 0x61, 0x06, 0xd6, 0x90,
|
||||
0x43, 0x39, 0xc8, 0x43, 0x39, 0x98, 0x43, 0x39, 0xc8, 0x43, 0x39, 0xb8,
|
||||
0xc3, 0x38, 0x94, 0x43, 0x38, 0x88, 0x03, 0x3b, 0x94, 0xc3, 0x2f, 0xbc,
|
||||
0x83, 0x3c, 0xfc, 0x82, 0x3b, 0xd4, 0x03, 0x3b, 0xb0, 0xc3, 0x0c, 0xc4,
|
||||
0x21, 0x07, 0x7c, 0x70, 0x03, 0x7a, 0x28, 0x87, 0x76, 0x80, 0x87, 0x19,
|
||||
0xd1, 0x43, 0x0e, 0xf8, 0xe0, 0x06, 0xe4, 0x20, 0x0e, 0xe7, 0xe0, 0x06,
|
||||
0xf6, 0x10, 0x0e, 0xf2, 0xc0, 0x0e, 0xe1, 0x90, 0x0f, 0xef, 0x50, 0x0f,
|
||||
0xf4, 0x30, 0x83, 0x81, 0xc8, 0x01, 0x1f, 0xdc, 0x40, 0x1c, 0xe4, 0xa1,
|
||||
0x1c, 0xc2, 0x61, 0x1d, 0xdc, 0x40, 0x1c, 0xe4, 0x01, 0x00, 0x00, 0x00,
|
||||
0x71, 0x20, 0x00, 0x00, 0x2e, 0x00, 0x00, 0x00, 0x86, 0x40, 0x0d, 0x97,
|
||||
0xef, 0x3c, 0x3e, 0xd0, 0x34, 0xce, 0x04, 0x4c, 0x44, 0x08, 0x34, 0xc3,
|
||||
0x42, 0x58, 0x01, 0x35, 0x5c, 0xbe, 0xf3, 0xf8, 0x01, 0x55, 0x14, 0x44,
|
||||
0x54, 0x3a, 0xc0, 0xe0, 0x23, 0xb7, 0x6d, 0x07, 0xdb, 0x70, 0xf9, 0xce,
|
||||
0xe3, 0x0b, 0x01, 0x55, 0x14, 0x44, 0x54, 0x3a, 0xc0, 0x50, 0x12, 0x06,
|
||||
0x20, 0x60, 0x3e, 0x72, 0xdb, 0x96, 0xd0, 0x0d, 0x97, 0xef, 0x3c, 0xbe,
|
||||
0x10, 0x11, 0xc0, 0x44, 0x84, 0x40, 0x33, 0x2c, 0xc4, 0x17, 0x39, 0xcc,
|
||||
0x86, 0x34, 0x03, 0xd2, 0x18, 0x26, 0xa0, 0x0d, 0x97, 0xef, 0x3c, 0xbe,
|
||||
0x10, 0x11, 0xc0, 0x44, 0x84, 0x40, 0x33, 0x2c, 0xc4, 0x17, 0x39, 0x4c,
|
||||
0x48, 0x00, 0x8f, 0x0d, 0x5c, 0xc3, 0xe5, 0x3b, 0x8f, 0x1f, 0x01, 0xd6,
|
||||
0x46, 0x15, 0x05, 0x11, 0x95, 0x0e, 0x30, 0xf8, 0xc8, 0x6d, 0x1b, 0x01,
|
||||
0x36, 0x5c, 0xbe, 0xf3, 0xf8, 0x11, 0x60, 0x6d, 0x54, 0x51, 0x10, 0x11,
|
||||
0x3b, 0x39, 0x11, 0xe1, 0x23, 0xb7, 0x6d, 0x06, 0xd5, 0x70, 0xf9, 0xce,
|
||||
0xe3, 0x4b, 0x00, 0xf3, 0x2c, 0x44, 0x49, 0x54, 0xc4, 0xe2, 0x17, 0xb7,
|
||||
0x6d, 0x01, 0xd2, 0x70, 0xf9, 0xce, 0xe3, 0x4f, 0x47, 0x44, 0x00, 0x83,
|
||||
0x38, 0xf8, 0xc8, 0x6d, 0x1b, 0x00, 0xc1, 0x00, 0x48, 0x03, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x48, 0x41, 0x53, 0x48, 0x14, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0xb5, 0x7f, 0x79, 0xfc, 0x70, 0x74, 0x4e, 0xa5,
|
||||
0xc2, 0xa5, 0xf0, 0x8c, 0x55, 0x5f, 0xc7, 0xc6, 0x44, 0x58, 0x49, 0x4c,
|
||||
0xbc, 0x07, 0x00, 0x00, 0x66, 0x00, 0x05, 0x00, 0xef, 0x01, 0x00, 0x00,
|
||||
0x44, 0x58, 0x49, 0x4c, 0x06, 0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
|
||||
0xa4, 0x07, 0x00, 0x00, 0x42, 0x43, 0xc0, 0xde, 0x21, 0x0c, 0x00, 0x00,
|
||||
0xe6, 0x01, 0x00, 0x00, 0x0b, 0x82, 0x20, 0x00, 0x02, 0x00, 0x00, 0x00,
|
||||
0x13, 0x00, 0x00, 0x00, 0x07, 0x81, 0x23, 0x91, 0x41, 0xc8, 0x04, 0x49,
|
||||
0x06, 0x10, 0x32, 0x39, 0x92, 0x01, 0x84, 0x0c, 0x25, 0x05, 0x08, 0x19,
|
||||
0x1e, 0x04, 0x8b, 0x62, 0x80, 0x18, 0x45, 0x02, 0x42, 0x92, 0x0b, 0x42,
|
||||
0xc4, 0x10, 0x32, 0x14, 0x38, 0x08, 0x18, 0x4b, 0x0a, 0x32, 0x62, 0x88,
|
||||
0x48, 0x90, 0x14, 0x20, 0x43, 0x46, 0x88, 0xa5, 0x00, 0x19, 0x32, 0x42,
|
||||
0xe4, 0x48, 0x0e, 0x90, 0x11, 0x23, 0xc4, 0x50, 0x41, 0x51, 0x81, 0x8c,
|
||||
0xe1, 0x83, 0xe5, 0x8a, 0x04, 0x31, 0x46, 0x06, 0x51, 0x18, 0x00, 0x00,
|
||||
0x08, 0x00, 0x00, 0x00, 0x1b, 0x8c, 0xe0, 0xff, 0xff, 0xff, 0xff, 0x07,
|
||||
0x40, 0x02, 0xa8, 0x0d, 0x86, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x03, 0x20,
|
||||
0x01, 0xd5, 0x06, 0x62, 0xf8, 0xff, 0xff, 0xff, 0xff, 0x01, 0x90, 0x00,
|
||||
0x49, 0x18, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x13, 0x82, 0x60, 0x42,
|
||||
0x20, 0x4c, 0x08, 0x06, 0x00, 0x00, 0x00, 0x00, 0x89, 0x20, 0x00, 0x00,
|
||||
0x42, 0x00, 0x00, 0x00, 0x32, 0x22, 0x88, 0x09, 0x20, 0x64, 0x85, 0x04,
|
||||
0x13, 0x23, 0xa4, 0x84, 0x04, 0x13, 0x23, 0xe3, 0x84, 0xa1, 0x90, 0x14,
|
||||
0x12, 0x4c, 0x8c, 0x8c, 0x0b, 0x84, 0xc4, 0x4c, 0x10, 0x98, 0xc1, 0x08,
|
||||
0x40, 0x09, 0x00, 0x0a, 0xe6, 0x08, 0xc0, 0xa0, 0x0c, 0xc3, 0x30, 0x10,
|
||||
0x31, 0x47, 0x80, 0x90, 0x71, 0xcf, 0x70, 0xf9, 0x13, 0xf6, 0x10, 0x92,
|
||||
0x1f, 0x02, 0xcd, 0xb0, 0x10, 0x28, 0x38, 0xe6, 0x08, 0x82, 0x52, 0x20,
|
||||
0xc3, 0x90, 0x24, 0xa4, 0xdc, 0x34, 0x5c, 0xfe, 0x84, 0x3d, 0x84, 0xe4,
|
||||
0xaf, 0x84, 0xb4, 0x12, 0x93, 0x8f, 0xdc, 0x36, 0x2a, 0x86, 0x61, 0x18,
|
||||
0x86, 0x72, 0x30, 0x03, 0x32, 0x0c, 0xc6, 0x40, 0x4d, 0x59, 0x80, 0x01,
|
||||
0x19, 0x86, 0x61, 0x18, 0x06, 0x63, 0xa0, 0xa7, 0x14, 0xcc, 0x80, 0x0c,
|
||||
0x03, 0x45, 0x33, 0x00, 0x37, 0x0d, 0x97, 0x3f, 0x61, 0x0f, 0x21, 0xf9,
|
||||
0x2b, 0x21, 0xad, 0xc4, 0xe4, 0x17, 0xb7, 0x8d, 0x8a, 0x69, 0x9a, 0xa6,
|
||||
0xa1, 0x30, 0xd4, 0x80, 0x20, 0xd3, 0x34, 0x4d, 0xc3, 0x30, 0x4c, 0x54,
|
||||
0x1d, 0x35, 0x5c, 0xfe, 0x84, 0x3d, 0x84, 0xe4, 0x73, 0x1b, 0x55, 0xac,
|
||||
0xc4, 0xe4, 0x23, 0xb7, 0x8d, 0x88, 0x61, 0x18, 0x86, 0x42, 0x5c, 0x03,
|
||||
0x32, 0x10, 0x76, 0xdb, 0x70, 0xf9, 0x13, 0xf6, 0x10, 0x92, 0xbf, 0x12,
|
||||
0x92, 0x43, 0x45, 0x02, 0x91, 0x46, 0xce, 0x43, 0x44, 0x13, 0x42, 0x48,
|
||||
0x48, 0x18, 0x86, 0x42, 0x20, 0x03, 0xa2, 0xd1, 0x76, 0xd0, 0x70, 0xf9,
|
||||
0x13, 0xf6, 0x10, 0x92, 0xbf, 0x12, 0xd2, 0x86, 0x34, 0x03, 0x22, 0x86,
|
||||
0x61, 0x30, 0x4a, 0x81, 0x0c, 0xdd, 0x90, 0x90, 0x37, 0x10, 0x70, 0x8e,
|
||||
0x34, 0x45, 0x94, 0x30, 0xf9, 0x62, 0x33, 0x20, 0x02, 0x21, 0x21, 0x62,
|
||||
0x18, 0x86, 0xe1, 0x06, 0x64, 0xb8, 0x50, 0x10, 0x92, 0x38, 0x47, 0x00,
|
||||
0x0a, 0x53, 0x00, 0x00, 0x13, 0x14, 0x72, 0xc0, 0x87, 0x74, 0x60, 0x87,
|
||||
0x36, 0x68, 0x87, 0x79, 0x68, 0x03, 0x72, 0xc0, 0x87, 0x0d, 0xaf, 0x50,
|
||||
0x0e, 0x6d, 0xd0, 0x0e, 0x7a, 0x50, 0x0e, 0x6d, 0x00, 0x0f, 0x7a, 0x30,
|
||||
0x07, 0x72, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x71, 0xa0,
|
||||
0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x78, 0xa0, 0x07, 0x73, 0x20,
|
||||
0x07, 0x6d, 0x90, 0x0e, 0x71, 0x60, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xd0,
|
||||
0x06, 0xe9, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90,
|
||||
0x0e, 0x76, 0x40, 0x07, 0x7a, 0x60, 0x07, 0x74, 0xd0, 0x06, 0xe6, 0x10,
|
||||
0x07, 0x76, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x60, 0x0e, 0x73, 0x20,
|
||||
0x07, 0x7a, 0x30, 0x07, 0x72, 0xd0, 0x06, 0xe6, 0x60, 0x07, 0x74, 0xa0,
|
||||
0x07, 0x76, 0x40, 0x07, 0x6d, 0xe0, 0x0e, 0x78, 0xa0, 0x07, 0x71, 0x60,
|
||||
0x07, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x76, 0x40, 0x07, 0x43, 0x9e,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86,
|
||||
0x3c, 0x04, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x0c, 0x79, 0x14, 0x20, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x18, 0xf2, 0x34, 0x40, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x30, 0xe4, 0x79, 0x80, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x60, 0xc8, 0x13, 0x01, 0x01, 0x20, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0xc0, 0x90, 0xa7, 0x02, 0x02, 0x40, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x21, 0x0f, 0x06, 0x04, 0x80, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43, 0x9e, 0x0d, 0x08, 0x80,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0x3c, 0x1e, 0x10,
|
||||
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x81, 0x00,
|
||||
0x0a, 0x00, 0x00, 0x00, 0x32, 0x1e, 0x98, 0x14, 0x19, 0x11, 0x4c, 0x90,
|
||||
0x8c, 0x09, 0x26, 0x47, 0xc6, 0x04, 0x43, 0x1a, 0x4a, 0xa0, 0x18, 0x4a,
|
||||
0x62, 0x04, 0xa0, 0x40, 0x0a, 0xa1, 0x00, 0x03, 0x88, 0x2c, 0x40, 0x40,
|
||||
0x40, 0x40, 0x0c, 0x1a, 0x67, 0x00, 0x00, 0x00, 0x79, 0x18, 0x00, 0x00,
|
||||
0x37, 0x00, 0x00, 0x00, 0x1a, 0x03, 0x4c, 0x90, 0x46, 0x02, 0x13, 0xc4,
|
||||
0x8e, 0x0c, 0x6f, 0xec, 0xed, 0x4d, 0x0c, 0x24, 0xc6, 0x25, 0xc7, 0x45,
|
||||
0xc6, 0x06, 0x26, 0xc7, 0xa5, 0x06, 0x04, 0x05, 0x26, 0x46, 0xcc, 0x46,
|
||||
0x26, 0x8c, 0x8c, 0xe6, 0x26, 0x65, 0x43, 0x10, 0x4c, 0x10, 0x06, 0x65,
|
||||
0x82, 0x30, 0x2c, 0x1b, 0x84, 0x81, 0x98, 0x20, 0x0c, 0xcc, 0x06, 0x61,
|
||||
0x30, 0x28, 0x8c, 0xcd, 0x6d, 0x18, 0x10, 0x82, 0x98, 0x20, 0x0c, 0xcd,
|
||||
0x04, 0x61, 0x0c, 0x24, 0x02, 0x13, 0x84, 0xc1, 0xd9, 0x80, 0x28, 0x0b,
|
||||
0xa3, 0x28, 0x43, 0x03, 0x6c, 0x08, 0x9c, 0x0d, 0x04, 0x00, 0x3c, 0xc0,
|
||||
0x04, 0x41, 0x00, 0x48, 0xb4, 0x85, 0xa5, 0xb9, 0x4d, 0x10, 0xc8, 0x20,
|
||||
0x9a, 0x20, 0x0c, 0xcf, 0x04, 0x61, 0x80, 0x36, 0x0c, 0xd5, 0x30, 0x6c,
|
||||
0x20, 0x94, 0x89, 0xb2, 0x36, 0x14, 0x91, 0x04, 0x40, 0x57, 0x15, 0x36,
|
||||
0x36, 0xbb, 0x36, 0x97, 0x34, 0xb2, 0x32, 0x37, 0xba, 0x29, 0x41, 0x50,
|
||||
0x85, 0x0c, 0xcf, 0xc5, 0xae, 0x4c, 0x6e, 0x2e, 0xed, 0xcd, 0x6d, 0x4a,
|
||||
0x40, 0x34, 0x21, 0xc3, 0x73, 0xb1, 0x0b, 0x63, 0xb3, 0x2b, 0x93, 0x9b,
|
||||
0x12, 0x18, 0x75, 0xc8, 0xf0, 0x5c, 0xe6, 0xd0, 0xc2, 0xc8, 0xca, 0xe4,
|
||||
0x9a, 0xde, 0xc8, 0xca, 0xd8, 0xa6, 0x04, 0x48, 0x19, 0x32, 0x3c, 0x17,
|
||||
0xb9, 0xb2, 0xb9, 0xb7, 0x3a, 0xb9, 0xb1, 0xb2, 0xb9, 0x29, 0xc1, 0x53,
|
||||
0x87, 0x0c, 0xcf, 0xa5, 0xcc, 0x8d, 0x4e, 0x2e, 0x0f, 0xea, 0x2d, 0xcd,
|
||||
0x8d, 0x6e, 0x6e, 0x4a, 0x70, 0x01, 0x00, 0x00, 0x79, 0x18, 0x00, 0x00,
|
||||
0x51, 0x00, 0x00, 0x00, 0x33, 0x08, 0x80, 0x1c, 0xc4, 0xe1, 0x1c, 0x66,
|
||||
0x14, 0x01, 0x3d, 0x88, 0x43, 0x38, 0x84, 0xc3, 0x8c, 0x42, 0x80, 0x07,
|
||||
0x79, 0x78, 0x07, 0x73, 0x98, 0x71, 0x0c, 0xe6, 0x00, 0x0f, 0xed, 0x10,
|
||||
0x0e, 0xf4, 0x80, 0x0e, 0x33, 0x0c, 0x42, 0x1e, 0xc2, 0xc1, 0x1d, 0xce,
|
||||
0xa1, 0x1c, 0x66, 0x30, 0x05, 0x3d, 0x88, 0x43, 0x38, 0x84, 0x83, 0x1b,
|
||||
0xcc, 0x03, 0x3d, 0xc8, 0x43, 0x3d, 0x8c, 0x03, 0x3d, 0xcc, 0x78, 0x8c,
|
||||
0x74, 0x70, 0x07, 0x7b, 0x08, 0x07, 0x79, 0x48, 0x87, 0x70, 0x70, 0x07,
|
||||
0x7a, 0x70, 0x03, 0x76, 0x78, 0x87, 0x70, 0x20, 0x87, 0x19, 0xcc, 0x11,
|
||||
0x0e, 0xec, 0x90, 0x0e, 0xe1, 0x30, 0x0f, 0x6e, 0x30, 0x0f, 0xe3, 0xf0,
|
||||
0x0e, 0xf0, 0x50, 0x0e, 0x33, 0x10, 0xc4, 0x1d, 0xde, 0x21, 0x1c, 0xd8,
|
||||
0x21, 0x1d, 0xc2, 0x61, 0x1e, 0x66, 0x30, 0x89, 0x3b, 0xbc, 0x83, 0x3b,
|
||||
0xd0, 0x43, 0x39, 0xb4, 0x03, 0x3c, 0xbc, 0x83, 0x3c, 0x84, 0x03, 0x3b,
|
||||
0xcc, 0xf0, 0x14, 0x76, 0x60, 0x07, 0x7b, 0x68, 0x07, 0x37, 0x68, 0x87,
|
||||
0x72, 0x68, 0x07, 0x37, 0x80, 0x87, 0x70, 0x90, 0x87, 0x70, 0x60, 0x07,
|
||||
0x76, 0x28, 0x07, 0x76, 0xf8, 0x05, 0x76, 0x78, 0x87, 0x77, 0x80, 0x87,
|
||||
0x5f, 0x08, 0x87, 0x71, 0x18, 0x87, 0x72, 0x98, 0x87, 0x79, 0x98, 0x81,
|
||||
0x2c, 0xee, 0xf0, 0x0e, 0xee, 0xe0, 0x0e, 0xf5, 0xc0, 0x0e, 0xec, 0x30,
|
||||
0x03, 0x62, 0xc8, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c, 0xcc, 0xa1, 0x1c, 0xe4,
|
||||
0xa1, 0x1c, 0xdc, 0x61, 0x1c, 0xca, 0x21, 0x1c, 0xc4, 0x81, 0x1d, 0xca,
|
||||
0x61, 0x06, 0xd6, 0x90, 0x43, 0x39, 0xc8, 0x43, 0x39, 0x98, 0x43, 0x39,
|
||||
0xc8, 0x43, 0x39, 0xb8, 0xc3, 0x38, 0x94, 0x43, 0x38, 0x88, 0x03, 0x3b,
|
||||
0x94, 0xc3, 0x2f, 0xbc, 0x83, 0x3c, 0xfc, 0x82, 0x3b, 0xd4, 0x03, 0x3b,
|
||||
0xb0, 0xc3, 0x0c, 0xc4, 0x21, 0x07, 0x7c, 0x70, 0x03, 0x7a, 0x28, 0x87,
|
||||
0x76, 0x80, 0x87, 0x19, 0xd1, 0x43, 0x0e, 0xf8, 0xe0, 0x06, 0xe4, 0x20,
|
||||
0x0e, 0xe7, 0xe0, 0x06, 0xf6, 0x10, 0x0e, 0xf2, 0xc0, 0x0e, 0xe1, 0x90,
|
||||
0x0f, 0xef, 0x50, 0x0f, 0xf4, 0x30, 0x83, 0x81, 0xc8, 0x01, 0x1f, 0xdc,
|
||||
0x40, 0x1c, 0xe4, 0xa1, 0x1c, 0xc2, 0x61, 0x1d, 0xdc, 0x40, 0x1c, 0xe4,
|
||||
0x01, 0x00, 0x00, 0x00, 0x71, 0x20, 0x00, 0x00, 0x2e, 0x00, 0x00, 0x00,
|
||||
0x86, 0x40, 0x0d, 0x97, 0xef, 0x3c, 0x3e, 0xd0, 0x34, 0xce, 0x04, 0x4c,
|
||||
0x44, 0x08, 0x34, 0xc3, 0x42, 0x58, 0x01, 0x35, 0x5c, 0xbe, 0xf3, 0xf8,
|
||||
0x01, 0x55, 0x14, 0x44, 0x54, 0x3a, 0xc0, 0xe0, 0x23, 0xb7, 0x6d, 0x07,
|
||||
0xdb, 0x70, 0xf9, 0xce, 0xe3, 0x0b, 0x01, 0x55, 0x14, 0x44, 0x54, 0x3a,
|
||||
0xc0, 0x50, 0x12, 0x06, 0x20, 0x60, 0x3e, 0x72, 0xdb, 0x96, 0xd0, 0x0d,
|
||||
0x97, 0xef, 0x3c, 0xbe, 0x10, 0x11, 0xc0, 0x44, 0x84, 0x40, 0x33, 0x2c,
|
||||
0xc4, 0x17, 0x39, 0xcc, 0x86, 0x34, 0x03, 0xd2, 0x18, 0x26, 0xa0, 0x0d,
|
||||
0x97, 0xef, 0x3c, 0xbe, 0x10, 0x11, 0xc0, 0x44, 0x84, 0x40, 0x33, 0x2c,
|
||||
0xc4, 0x17, 0x39, 0x4c, 0x48, 0x00, 0x8f, 0x0d, 0x5c, 0xc3, 0xe5, 0x3b,
|
||||
0x8f, 0x1f, 0x01, 0xd6, 0x46, 0x15, 0x05, 0x11, 0x95, 0x0e, 0x30, 0xf8,
|
||||
0xc8, 0x6d, 0x1b, 0x01, 0x36, 0x5c, 0xbe, 0xf3, 0xf8, 0x11, 0x60, 0x6d,
|
||||
0x54, 0x51, 0x10, 0x11, 0x3b, 0x39, 0x11, 0xe1, 0x23, 0xb7, 0x6d, 0x06,
|
||||
0xd5, 0x70, 0xf9, 0xce, 0xe3, 0x4b, 0x00, 0xf3, 0x2c, 0x44, 0x49, 0x54,
|
||||
0xc4, 0xe2, 0x17, 0xb7, 0x6d, 0x01, 0xd2, 0x70, 0xf9, 0xce, 0xe3, 0x4f,
|
||||
0x47, 0x44, 0x00, 0x83, 0x38, 0xf8, 0xc8, 0x6d, 0x1b, 0x00, 0xc1, 0x00,
|
||||
0x48, 0x03, 0x00, 0x00, 0x61, 0x20, 0x00, 0x00, 0x6f, 0x00, 0x00, 0x00,
|
||||
0x13, 0x04, 0x43, 0x2c, 0x10, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00,
|
||||
0x34, 0xcc, 0x00, 0x14, 0xec, 0x40, 0xd1, 0x0e, 0x94, 0x5d, 0x11, 0x14,
|
||||
0xa6, 0x40, 0xc9, 0x0e, 0x94, 0x46, 0xe9, 0x06, 0x14, 0x26, 0x50, 0x59,
|
||||
0x14, 0x45, 0x29, 0x12, 0x94, 0xa5, 0x40, 0x19, 0x14, 0x62, 0x40, 0x49,
|
||||
0x12, 0x14, 0x47, 0xf1, 0x91, 0x51, 0x02, 0x45, 0x40, 0xc9, 0x08, 0x40,
|
||||
0x0d, 0xd0, 0x34, 0x03, 0x30, 0x46, 0x00, 0x82, 0x20, 0x48, 0x7f, 0x63,
|
||||
0x04, 0x20, 0x08, 0x82, 0xe8, 0x37, 0x02, 0x40, 0xda, 0x1c, 0x82, 0xe6,
|
||||
0xcc, 0x21, 0x70, 0xcf, 0x1c, 0x42, 0xd7, 0xcc, 0x21, 0x78, 0xdf, 0x1c,
|
||||
0xc2, 0x35, 0x06, 0x73, 0x08, 0x64, 0xd0, 0x50, 0x37, 0x07, 0xd1, 0x34,
|
||||
0xcd, 0x19, 0x00, 0x00, 0x23, 0x06, 0x08, 0x00, 0x82, 0x60, 0xe0, 0xb1,
|
||||
0x01, 0x17, 0xa0, 0x41, 0x33, 0x62, 0x70, 0x00, 0x20, 0x08, 0x06, 0x9b,
|
||||
0x1b, 0x88, 0x41, 0x80, 0x8c, 0x18, 0x18, 0x00, 0x08, 0x82, 0x01, 0x61,
|
||||
0x07, 0x9c, 0x1a, 0x8c, 0x18, 0x1c, 0x00, 0x08, 0x82, 0x01, 0x16, 0x07,
|
||||
0x62, 0x20, 0xac, 0xc1, 0x68, 0x42, 0x00, 0x8c, 0x18, 0x20, 0x00, 0x08,
|
||||
0x82, 0x81, 0x82, 0x07, 0x65, 0x10, 0x48, 0xd2, 0x88, 0xc1, 0x01, 0x80,
|
||||
0x20, 0x18, 0x6c, 0x73, 0x70, 0x06, 0x01, 0x33, 0x9a, 0x40, 0x04, 0x23,
|
||||
0x06, 0x08, 0x00, 0x82, 0x60, 0xa0, 0xec, 0x01, 0x1a, 0x04, 0x55, 0x35,
|
||||
0x62, 0x70, 0x00, 0x20, 0x08, 0x06, 0x9b, 0x1d, 0xa8, 0x41, 0xe0, 0x8c,
|
||||
0x26, 0x1c, 0xc2, 0x88, 0x01, 0x02, 0x80, 0x20, 0x18, 0x28, 0x7e, 0xb0,
|
||||
0x06, 0x01, 0x86, 0x8d, 0x18, 0x1c, 0x00, 0x08, 0x82, 0xc1, 0x96, 0x07,
|
||||
0x6d, 0x10, 0x40, 0xb5, 0xac, 0xc1, 0x8d, 0x18, 0x28, 0x00, 0x08, 0x82,
|
||||
0x41, 0x03, 0x0a, 0x63, 0x50, 0x04, 0x70, 0xd0, 0xd1, 0xc1, 0x68, 0x42,
|
||||
0x00, 0x54, 0x40, 0x06, 0x32, 0x62, 0x80, 0x00, 0x20, 0x08, 0x06, 0x51,
|
||||
0x28, 0x90, 0x41, 0xf1, 0xcc, 0xc1, 0x68, 0x42, 0x00, 0xd4, 0x10, 0xc0,
|
||||
0x88, 0x81, 0x03, 0x80, 0x20, 0x18, 0x3c, 0xa5, 0x10, 0x07, 0x8e, 0xc4,
|
||||
0x07, 0x81, 0x1d, 0xd8, 0x81, 0x1d, 0x8c, 0x81, 0x1e, 0x0c, 0x37, 0x48,
|
||||
0x7c, 0x00, 0x06, 0xb3, 0x0c, 0x81, 0x10, 0x8c, 0x18, 0x1c, 0x00, 0x08,
|
||||
0x82, 0x01, 0x36, 0x0a, 0x74, 0x40, 0xf5, 0xc1, 0x68, 0x42, 0x30, 0x8c,
|
||||
0x18, 0x20, 0x00, 0x08, 0x82, 0x81, 0xa2, 0x0a, 0x77, 0x10, 0x90, 0x01,
|
||||
0x19, 0x8c, 0x18, 0x1c, 0x00, 0x08, 0x82, 0xc1, 0x56, 0x0a, 0x79, 0x10,
|
||||
0x6c, 0x23, 0x06, 0x08, 0x00, 0x82, 0x60, 0xa0, 0xb0, 0x42, 0x1e, 0x84,
|
||||
0x42, 0x19, 0x98, 0xc1, 0x88, 0xc1, 0x01, 0x80, 0x20, 0x18, 0x6c, 0xa7,
|
||||
0xb0, 0x07, 0x01, 0x37, 0x62, 0xf0, 0x00, 0x20, 0x08, 0x06, 0x95, 0x2a,
|
||||
0xac, 0xc1, 0x10, 0x94, 0x01, 0x19, 0x98, 0x81, 0x19, 0x8c, 0xc2, 0x28,
|
||||
0xf4, 0xc1, 0x18, 0x8c, 0x26, 0x04, 0xc0, 0x05, 0xc3, 0x8e, 0x18, 0x38,
|
||||
0x00, 0x08, 0x82, 0xc1, 0xf3, 0x0a, 0x7b, 0x80, 0x8d, 0x82, 0x29, 0x04,
|
||||
0xa0, 0x00, 0x0a, 0xa0, 0xd0, 0x06, 0xa4, 0x30, 0x4b, 0x20, 0x20, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00
|
||||
};
|
||||
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user