Android: track disjoint mip layouts and add Vulkan validation tools

This commit is contained in:
shen
2026-10-15 18:53:45 -07:00
parent 8eb294e7e0
commit a6c3655e21
12 changed files with 546 additions and 47 deletions
+3 -1
View File
@@ -22,6 +22,8 @@ headless:
$(MAKE) -C $(HOST) -f $(CURDIR)/build.mk $(B)/dmhost
tests:
$(MAKE) -C tests
host-tests:
python3 tests/run_checks.py --host-only $(if $(NDK),--ndk "$(NDK)") --output $(B)/checks-$(shell date +%Y%m%d-%H%M%S)
clean:
rm -rf $(B)
.PHONY: apk lib install headless tests clean
.PHONY: apk lib install headless tests host-tests clean
+27 -3
View File
@@ -12,7 +12,7 @@ Layout (a sibling of `dm/ios/`):
| `tests/` | Vulkan backend device test `t_vk_perf` |
| `../gfx/vulkan/` | The Vulkan graphics backend `nvn_vk.c` (counterpart of the Metal backend `gfx/nvn/nvn_mtl.m`) |
The backend (`gfx/vulkan/nvn_vk.c`) retains the NVN recorder's `mtl_*` interface. Headless rendering is verified on OnePlus 13 / Adreno 830. A minimal GameActivity app (window, raw touch, gamepad, text input) is in `app/`; AAudio and the touch HUD remain subsequent work.
The backend (`gfx/vulkan/nvn_vk.c`) retains the NVN recorder's `mtl_*` interface. Headless rendering is verified on OnePlus 13 / Adreno 830. The app includes window management, a touch HUD, gamepad and text input, AAudio and lifecycle suspend/resume. Integration does not establish validation on every device.
## Build and test
@@ -32,6 +32,7 @@ Use `NDK=...` or `ANDROID_NDK_HOME` to override the newest local SDK NDK. The de
| `DM_VK_SHADERS` | Vulkan shader pack generated by `dmsh_vk.py` |
| `DM_VK_PIPELINE_CACHE` | Driver cache file; defaults to the shader directory with vendor / device / driver version in its name |
| `DM_DISABLE_PIPELINE_CACHE=1` | Disable the driver cache; the state-to-pipeline memory cache remains active |
| `DM_VK_SUBRES=0` | Disable disjoint-mip layouts and use the original whole-image path for device A/B; enabled by default |
| `DM_VK_SYNC=1` | Submit and wait at every logical commit for comparison |
| `DM_FRAME_DIR` | Existing PPM frame capture and requested diagnostics |
| `DM_VULKAN_VALIDATION=1` | Request the Khronos layer, which must be discoverable by Android's loader |
@@ -59,7 +60,7 @@ adb shell am start -n org.d2rmobile.app/.GameActivity
adb shell run-as org.d2rmobile.app cat files/d2r/run.log
```
The data root is `files/d2r` (`dm/main.patched.bin`, `romfs`, `rt64` required). stderr goes to `run.log`; optional `env.txt` lines `KEY=VALUE` are exported before start (e.g. `DM_VK_VRS=2x2`). Audio is off (`DM_AUDIO=0`) until AAudio lands. Render resolution is 720 lines times the screen aspect (`DM_GAME_RES` overrides). Without a window (app in background) the render thread holds at Present and resumes when a new surface arrives. On front-end pages (main menu, character select / creation) the first finger becomes UI mouse clicks via `dm_ui_touch` (tap = click at the lift point, vertical drag = scroll), as on iOS; in a run touch goes to the game's raw touchscreen until the touch HUD is ported. Gamepad buttons and sticks go to the pad.
The data root is `files/d2r` (`dm/main.patched.bin`, `romfs`, `rt64` required). stderr goes to `run.log`; optional `env.txt` lines `KEY=VALUE` are exported before start (e.g. `DM_VK_VRS=2x2`). AAudio is on by default (`DM_AUDIO=0` mutes). UI output follows screen aspect and native height (900–1080 lines); the default 3D target is approximately 720 lines (`DM_GAME_RES` / `DM_3D_SCALE` override). Without a window (app in background) the render thread holds at Present and resumes when a new surface arrives. On front-end pages (main menu, character select / creation) the first finger becomes UI mouse clicks via `dm_ui_touch` (tap = click at the lift point, vertical drag = scroll), as on iOS; in a run the touch HUD and game-state bridge handle gestures, with unclaimed touches available to the raw touchscreen. Gamepad buttons and sticks go to the pad.
## Implementation and boundaries
@@ -70,9 +71,32 @@ The data root is `files/d2r` (`dm/main.patched.bin`, `romfs`, `rt64` required).
- Build the shader pack with `SB_ALIGN=64` (the `dmsh_vk.py` default). Shaders then derive SSBO offsets from `base & -64`, and vkmeta flag bit 1 lets the host bind storage buffers directly from `addr & -64` with no copy. vkmeta storage flag bit 0 means writable. Packs built with `SB_ALIGN=16` still work through the copy path.
- CPU inputs use immutable snapshots. GPU-authored inputs stay in shared GPU buffers; ordered staging copies supply uncovered CPU bytes. Each batch snapshots its GPU writebacks to prevent subsequent batches contaminating earlier results.
- Capacity splits retain the logical fence until the final piece completes. Explicit Flush / wait boundaries prevent a strict one-submit-per-frame guarantee.
- The current real-window path still waits for presentation and queue idle to preserve temporary WSI semaphore lifetimes. This performance work targets headless rendering.
- Windowed present does not drain: each batch slot reuses its acquire semaphore and each swapchain image has its own present semaphore. `VK_ERROR_OUT_OF_DATE_KHR` on acquire recreates the swapchain and retries; on present it marks the swapchain for recreation at the next frame. Surface changes wait for the queue to idle before the swapchain is dropped.
`RENDER_PROFILE` counts actual Vulkan submissions including Present; the old counter excluded Present. `RENDER_CACHE_PROFILE` records cache reuse, pass count, pass breaks, transient buffer use and `gpu_ms` (GPU time of the interval from timestamp queries). `RENDER_INPUT_PROFILE` records uploads and shared GPU reads. `WAIT_PROFILE` splits CPU-side GPU wait time by origin (sync / event / present / slot / readtex / texrel / sampler / pooldel / finish / capture, as `ms/count`), plus `sync_lag_max` and `event_queued` / `event_blocked`.
See [PERFORMANCE.md](PERFORMANCE.md) for measurements and validation limits. Keep binaries, caches, logs and game screenshots under ignored `dm/android/build/` or device test directories.
## Subresource layouts and cross-GPU verification
See [VALIDATION.md](VALIDATION.md) for this change's completed checks and outstanding device/package validation.
Inspired by [dodola/d2r-mobile at 642480b](https://github.com/dodola/d2r-mobile/blob/642480b7606cf4adda30bcf009eb56f87745c908/dm/gfx/nvn/nvn_vk.c), this backend tracks per-mip layouts for disjoint sampling/rendering on drivers without feedback-layout support. The bounded path covers single-layer 2D color images with 2–16 mips. Every sampled view in both graphics stages must avoid every attachment mip. Overlap, storage images, comparison sampling, depth/stencil, arrays and volumes retain the original path. Whole-image operations consolidate each run using its actual old layout, preserving pixels during upload, copies and readback.
No build91738 addresses, resource paths or input services were imported. The build94012 HUD/save/build integration remains in place. **Existing Adreno validation remains the supported scope. Mali requires device validation; a successful capability probe does not prove game compatibility.**
Game-free checks (each output directory must be new):
```sh
# Host layout regression + ASan/UBSan + NDK test binary build; no device access
python3 dm/android/tests/run_checks.py --output dm/android/build/checks-local
# Host checks only; NDK Vulkan headers are still required
make -C dm/android host-tests
# Explicit device opt-in: runs test binaries, does not install/start the game
python3 dm/android/tests/run_checks.py --output dm/android/build/checks-device --run-device --serial DEVICE_SERIAL
```
Use `--ndk /path/to/ndk` and `HOST_CC` to select toolchains. `result.json` records commands, exit codes, source/binary SHA-256 and whether device/GPU checks actually ran. `t_vk_caps` emits system-driver GPU/features/extensions/formats/memory JSON; it does not inspect the app's private driver. `t_vk_perf` includes cross-stage overlap checks and real GPU multi-mip readback. Run `t_vk_perf mips` for only the added cases.
Compare `DM_VK_SUBRES=0` / `1` on the same build94012 game, character, location, output extent and fixed 3D scale. Record driver, actual refresh rate, SurfaceFlinger display intervals and temperature. Check pixels and save/resume before evaluating speed. Different builds/drivers and submission-only FPS are not controlled comparisons.
+27 -3
View File
@@ -12,7 +12,7 @@ English: [README.md](README.md)
| `tests/` | Vulkan 后端设备测试 `t_vk_perf` |
| `../gfx/vulkan/` | Vulkan 图形后端 `nvn_vk.c`(与 Metal 后端 `gfx/nvn/nvn_mtl.m` 对应) |
`gfx/vulkan/nvn_vk.c` 保留 NVN 记录器的 `mtl_*` 接口。目前在 OnePlus 13 / Adreno 830 上验证无头渲染。`app/` 是最小 GameActivity 应用(窗口、原始触摸、手柄、文字输入);AAudio 与触屏 HUD 是后续步骤。
`gfx/vulkan/nvn_vk.c` 保留 NVN 记录器的 `mtl_*` 接口。目前在 OnePlus 13 / Adreno 830 上验证无头渲染。`app/` 已接入窗口、触屏 HUD、手柄、文字输入、AAudio 及前后台挂起 / 恢复。功能接入不代表所有机型已完成验证。
## 构建与回归
@@ -34,6 +34,7 @@ NDK 默认取 `ANDROID_NDK_HOME`,否则使用本机 Android SDK 中最新的 N
| `DM_VK_SHADERS` | `dmsh_vk.py` 生成的 Vulkan 着色器包目录 |
| `DM_VK_PIPELINE_CACHE` | 驱动缓存文件路径;默认放在着色器包目录,文件名包含 vendor / device / driver 版本 |
| `DM_DISABLE_PIPELINE_CACHE=1` | 关闭驱动缓存,状态到 pipeline 的内存缓存仍启用 |
| `DM_VK_SUBRES=0` | 关闭不重叠 mip 的独立布局,恢复整图布局路径,用于真机 A/B;默认开启 |
| `DM_VK_SYNC=1` | 每次逻辑提交立即提交并等待,用于异步行为对照 |
| `DM_FRAME_DIR` | 按现有规则抓取 PPM 帧与按需诊断数据 |
| `DM_VULKAN_VALIDATION=1` | 请求 Khronos validation layer;需要 Android loader 能发现该 layer |
@@ -61,7 +62,7 @@ adb shell am start -n org.d2rmobile.app/.GameActivity
adb shell run-as org.d2rmobile.app cat files/d2r/run.log
```
数据根目录是 `files/d2r`(必须有 `dm/main.patched.bin`、`romfs`、`rt64`)。stderr 写入 `run.log`;可选的 `env.txt` 每行 `KEY=VALUE`,启动前导出(例如 `DM_VK_VRS=2x2`)。接入 AAudio 前声音关闭(`DM_AUDIO=0`)。渲染分辨率为 720 行乘屏幕宽高比(`DM_GAME_RES` 可覆盖)。没有窗口(应用在后台)时渲染线程停在 Present,新 surface 到来后继续。前端页(主菜单、选角 / 建角)上第一根手指经 `dm_ui_touch` 变成界面鼠标点击(点按 = 抬起处点击,纵向拖 = 滚动),与 iOS 相同;局内在触屏 HUD 移植前送到游戏的原始触摸屏。手柄按键与摇杆送到 pad。
数据根目录是 `files/d2r`(必须有 `dm/main.patched.bin`、`romfs`、`rt64`)。stderr 写入 `run.log`;可选的 `env.txt` 每行 `KEY=VALUE`,启动前导出(例如 `DM_VK_VRS=2x2`)。AAudio 默认启用,`DM_AUDIO=0` 可静音。界面输出按屏幕比例和原生高度(900–1080 行),默认 3D 目标约 720 行,`DM_GAME_RES` / `DM_3D_SCALE` 可覆盖。没有窗口(应用在后台)时渲染线程停在 Present,新 surface 到来后继续。前端页(主菜单、选角 / 建角)上第一根手指经 `dm_ui_touch` 变成界面鼠标点击(点按 = 抬起处点击,纵向拖 = 滚动),与 iOS 相同;局内由触屏 HUD 和游戏状态桥接处理,未消费触点仍可交给原始触摸屏。手柄按键与摇杆送到 pad。
## 性能实现与边界
@@ -72,9 +73,32 @@ adb shell run-as org.d2rmobile.app cat files/d2r/run.log
- 着色器包用 `SB_ALIGN=64` 构建(`dmsh_vk.py` 默认值):着色器按 `base & -64` 计算 SSBO 偏移,vkmeta 标志 bit 1 让宿主直接从 `addr & -64` 绑定存储缓冲区,无需拷贝;bit 0 表示可写。`SB_ALIGN=16` 的旧包仍走拷贝路径。
- CPU 输入使用不可变上传快照。GPU 生成的输入直接读共享 GPU 缓冲区,未覆盖的 CPU 数据通过有序 staging copy 上传。每批 GPU 写回先拷到独立读回副本,防止后批写入污染前批结果。
- 容量不足可在一个逻辑提交内分批,逻辑 fence 在最后一批完成后才可见。显式 Flush / 等待仍会打断合帧,因此不能保证所有游戏路径严格每帧一次提交。
- 当前真实窗口路径仍等待 present 并保留 queue idle,以确保临时 WSI semaphore 生命周期;本次性能验收针对无头路径。
- 有窗口时 Present 不再 Drain:每个批次槽位复用自己的 acquire 信号量,每张 swapchain 图像有独立的 present 信号量。acquire 遇到 `VK_ERROR_OUT_OF_DATE_KHR` 时重建 swapchain 并重试一次;present 遇到时标记,在下一帧重建。surface 变化时先等队列空闲再销毁 swapchain。
`RENDER_PROFILE` 计时并统计实际 Vulkan 提交(包括 Present);`RENDER_CACHE_PROFILE` 记录 pipeline 命中、pass / framebuffer 复用、pass 次数与打断次数、临时缓冲区用量,以及 `gpu_ms`(时间戳查询得到的区间 GPU 时间);`RENDER_INPUT_PROFILE` 记录上传和共享 GPU 输入;`WAIT_PROFILE` 按来源拆分 CPU 等待 GPU 的时间(sync / event / present / slot / readtex / texrel / sampler / pooldel / finish / capture,格式 `毫秒/次数`),并给出 `sync_lag_max` 与 `event_queued` / `event_blocked`。旧后端的提交统计不包含 Present,比较时需注意口径。
2026-10-13 的实测和限制见 [PERFORMANCE.md](PERFORMANCE.md)。构建文件、缓存、日志、游戏截图均留在 `dm/android/build/` 或设备测试目录,不入库。
## 子资源布局与跨 GPU 验证
本次实现、已通过检查及尚未执行的真机项目见 [VALIDATION.md](VALIDATION.md)。
参考 [dodola/d2r-mobile 的 Vulkan 实现(642480b)](https://github.com/dodola/d2r-mobile/blob/642480b7606cf4adda30bcf009eb56f87745c908/dm/gfx/nvn/nvn_vk.c),本分支增加按 mip 跟踪布局。在不提供反馈布局扩展的驱动上,单层 2D 颜色纹理的 2–16 级 mip 链可以在不重叠的级别上同时采样与渲染,避免把这类操作误当作整张图像的反馈。两个图形着色阶段的所有采样范围都参与判断;存在任一重叠、存储图像或比较采样时继续采用原来的整图路径。深度 / 模板、数组和体纹理也沿用原路径。复制、上传、清屏和读回前会按每段实际旧布局合并整图状态。
没有移植 build91738 的游戏地址、资源路径或输入服务。现有 build94012 的 HUD、存档和构建入口保留。**目前支持范围仍以原有 Adreno 验证为准,Mali 需要真机验证;能力探针成功不等于游戏兼容。**
不依赖游戏资源的检查(输出目录必须不存在):
```sh
# 本机布局回归 + ASan/UBSan + NDK 编译设备测试程序;不连接设备
python3 dm/android/tests/run_checks.py --output dm/android/build/checks-local
# 仅本机回归,仍需 NDK 提供 Vulkan 头文件
make -C dm/android host-tests
# 指定设备后才推送测试程序并执行;不安装 APK,不访问游戏与存档
python3 dm/android/tests/run_checks.py --output dm/android/build/checks-device --run-device --serial DEVICE_SERIAL
```
`--ndk /path/to/ndk` 可指定 NDK,`HOST_CC` 可指定本机编译器。`result.json` 记录每条命令的退出状态、日志、源文件 / 设备产物 SHA-256,以及是否连接设备、是否执行 GPU。`t_vk_caps` 输出系统 Vulkan 驱动的 GPU、特性、扩展、格式及内存类型 JSON,不代表 App 选择的私有驱动。`t_vk_perf` 新增跨着色阶段重叠判断和真实 GPU 多 mip 像素读回检查;单独执行 `t_vk_perf mips` 可只跑新增用例。
后续 Mali / Adreno 验收应使用相同 build94012 游戏文件、角色、位置、输出尺寸和固定 3D 比例,分别测试 `DM_VK_SUBRES=0` / `1`。同时记录驱动、实际屏幕刷新率、SurfaceFlinger 显示间隔和温度。先过像素及存档 / 恢复检查,再判断性能;旧版游戏、不同驱动或只统计提交帧的 FPS 不作直接比较。
+58
View File
@@ -0,0 +1,58 @@
# Android subresource-layout validation
Local validation date: 2026-10-15 (America/Los_Angeles).
This change retains `android-port` and its build94012 game integration. The
per-mip approach is adapted from [dodola/d2r-mobile at 642480b](https://github.com/dodola/d2r-mobile/blob/642480b7606cf4adda30bcf009eb56f87745c908/dm/gfx/nvn/nvn_vk.c).
No build91738 game addresses or platform/input services were imported.
## Implemented scope
- Track independent layouts for single-layer 2D color mip chains (2–16 levels)
when sampled mips do not intersect any attachment mip in either graphics stage.
- Retain the existing path for storage/comparison images, overlapping views,
depth/stencil, arrays, volumes and devices using feedback-layout support.
- Consolidate mixed layouts using the actual old layout of each mip run before
whole-image operations; restore individual layouts after diagnostic captures.
- Allow device A/B with `DM_VK_SUBRES=0` / `1`, without replacing the current
pipeline cache, input, audio, save or APK packaging implementations.
- Add a game-free system Vulkan capability probe, GPU readback fixture and a
host/NDK/device test runner with explicit device opt-in and JSON receipts.
## Completed checks
| Check | Result |
| --- | --- |
| Production layout tracker vs independent per-level oracle | 320,000 deterministic random transitions; 407,319 emitted barriers checked |
| Same regression with AddressSanitizer + UndefinedBehaviorSanitizer | Passed |
| Invalid ranges, no-op transitions, mixed-to-uniform transitions, >16-level whole-image fallback | Passed in both host builds |
| NDK 28.2.13676358 / API 33 / arm64 device test binaries | `t_vk_perf` and `t_vk_caps` built and linked |
| Production Vulkan App object, `-fPIC -ffixed-x18 -O2` | Built successfully |
| Diff whitespace and Python syntax | Passed |
Reproduction:
```sh
python3 dm/android/tests/run_checks.py --output dm/android/build/checks-new
```
Local receipts and compiler logs are under ignored
`dm/android/build/checks-mip-final/`. The JSON explicitly records
`device_contacted: false`, `gpu_executed: false` and `game_tested: false`.
## Outstanding device and package checks
No Android device was attached. The new cross-stage binding-policy and real
Vulkan mip pixel-readback fixtures were compiled, **not executed**. No Mali game
compatibility, validation-layer cleanliness, improved FPS, display cadence,
thermal behavior or power result is claimed.
The full App native-library build was attempted but stopped at the missing
generated `dm_hud_exp.h` included by `dm/host/diag.c`. Generate the host headers
from the player's own resources before validating the complete library/APK.
The modified production Vulkan object builds independently of that header.
Use the explicit `--run-device --serial DEVICE_SERIAL` runner option for GPU
checks, then perform the controlled game A/B described in the Android README.
The capability probe reports the system driver; an app using a private Turnip
driver requires separate testing with that driver.
+1
View File
@@ -47,6 +47,7 @@ $(OUT)/libd2r.so: $(OBJ)
# 图形回放(gfx/,含 Vulkan 后端 gfx/vulkan/)是逐绘制热路径,用 -O2;其余宿主代码保持 -O1,与 Mac 构建一致
# Graphics replay (gfx/, including the Vulkan backend gfx/vulkan/) is the per-draw hot path, built at -O2; the rest of the host stays at -O1 like the Mac build
$(OUT)/obj/up/gfx/%.o: CFLAGS += -O2
$(OUT)/obj/up/gfx/vulkan/nvn_vk.o: ../gfx/vulkan/nvn_vk_mip_layout.h ../gfx/vulkan/nvn_vk_dispatch.h
$(OUT)/obj/up/%.o: ../%.c
@mkdir -p $(dir $@)
+6 -2
View File
@@ -1,9 +1,13 @@
NDK ?= $(or $(ANDROID_NDK_HOME),$(lastword $(sort $(wildcard $(HOME)/Library/Android/sdk/ndk/*))))
.DEFAULT_GOAL := all
CC := $(wildcard $(NDK)/toolchains/llvm/prebuilt/*/bin)/aarch64-linux-android33-clang
OUT ?= ../build/tests
CFLAGS = -O1 -g -Wall -Wno-unused-function -ffunction-sections -fdata-sections -I../../gfx/nvn -I../../gfx/nvn/include -include ../../host/compat/linux/compat_linux.h -I../../host/compat/linux/include -I../../host
$(OUT)/t_vk_perf: t_vk_perf.c ../../gfx/vulkan/nvn_vk.c ../../gfx/vulkan/nvn_vk_dispatch.h
$(OUT)/t_vk_perf: t_vk_perf.c ../../gfx/vulkan/nvn_vk.c ../../gfx/vulkan/nvn_vk_dispatch.h ../../gfx/vulkan/nvn_vk_mip_layout.h
@mkdir -p $(OUT)
$(CC) $(CFLAGS) -Wl,--gc-sections -Wl,-z,max-page-size=16384 $< -o $@ -landroid -ldl -lm -lz
$(OUT)/t_vk_caps: t_vk_caps.c
@mkdir -p $(OUT)
$(CC) -O2 -g -Wall -Wextra -Werror -Wl,-z,max-page-size=16384 $< -o $@ -lvulkan
.PHONY: all
all: $(OUT)/t_vk_perf
all: $(OUT)/t_vk_perf $(OUT)/t_vk_caps
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""Game-free host checks, NDK build, and optional real-device Vulkan regression.
Default: host + ASan/UBSan + Android test binaries, without contacting a device.
--run-device requires an explicit serial; it only pushes these test binaries to
a unique /data/local/tmp directory. It does not install/start the game app.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import time
import uuid
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--ndk', type=Path)
parser.add_argument('--host-only', action='store_true')
parser.add_argument('--run-device', action='store_true')
parser.add_argument('--serial')
args = parser.parse_args()
if args.run_device and (args.host_only or not args.serial):
parser.error('--run-device requires --serial and an Android build')
repo = Path(__file__).resolve().parents[3]
out = args.output.resolve()
out.mkdir(parents=True, exist_ok=False)
report = {'schema': 1, 'passed': False, 'device_contacted': False,
'gpu_executed': False, 'game_tested': False, 'steps': []}
def save():
(out / 'result.json').write_text(json.dumps(report, indent=2) + '\n')
def run(name, command, timeout=120):
print(name, flush=True)
start = time.monotonic()
process = subprocess.run(command, cwd=repo, capture_output=True, text=True, timeout=timeout)
(out / (name + '.log')).write_text(process.stdout + process.stderr)
report['steps'].append({'name': name, 'command': command, 'exit_code': process.returncode,
'elapsed_seconds': round(time.monotonic() - start, 3)})
save()
process.check_returncode()
return process.stdout
save()
try:
candidates = sorted((Path.home() / 'Library/Android/sdk/ndk').glob('*'),
key=lambda p: tuple(int(v) for v in p.name.split('.') if v.isdigit()))
ndk = args.ndk or (Path(os.environ['ANDROID_NDK_HOME']) if os.environ.get('ANDROID_NDK_HOME') else None)
if ndk is None and candidates:
ndk = candidates[-1]
if ndk is None:
raise RuntimeError('Specify --ndk (Vulkan headers are needed even for host-only checks)')
ndk = ndk.resolve()
headers = list(ndk.glob('toolchains/llvm/prebuilt/*/sysroot/usr/include'))
if len(headers) != 1:
raise RuntimeError('Expected one NDK host toolchain under ' + str(ndk))
cc = shlex.split(os.environ.get('HOST_CC', 'clang'))
common = cc + ['-std=c11', '-O1', '-g', '-Wall', '-Wextra', '-Werror', '-idirafter', str(headers[0]),
'dm/android/tests/t_vk_mip_layout.c']
for mode, flags in [('normal', []), ('sanitized', ['-fsanitize=address,undefined', '-fno-omit-frame-pointer'])]:
binary = out / ('mip-' + mode)
run('build-' + mode, common + flags + ['-o', str(binary)])
run('run-' + mode, [str(binary)])
if not args.host_only:
binaries = out / 'android'
run('ndk-build', ['make', '-C', 'dm/android/tests', 'all', 'NDK=' + str(ndk), 'OUT=' + str(binaries)], 180)
report['artifacts_sha256'] = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(binaries.iterdir())}
sources = ['dm/gfx/vulkan/nvn_vk.c', 'dm/gfx/vulkan/nvn_vk_mip_layout.h',
'dm/android/tests/t_vk_perf.c', 'dm/android/tests/t_vk_caps.c',
'dm/android/tests/t_vk_mip_layout.c', 'dm/android/tests/Makefile', 'dm/android/tests/run_checks.py']
report['source_sha256'] = {p: hashlib.sha256((repo / p).read_bytes()).hexdigest() for p in sources}
if args.run_device:
adb = shutil.which('adb')
if not adb:
raise RuntimeError('adb is not available')
device = [adb, '-s', args.serial]
report['device_contacted'] = True
run('device-state', device + ['get-state'])
remote = '/data/local/tmp/d2r-checks-' + uuid.uuid4().hex
run('device-mkdir', device + ['shell', 'mkdir', remote])
try:
for name in ('t_vk_caps', 't_vk_perf'):
run('push-' + name, device + ['push', str(binaries / name), remote + '/' + name])
run('chmod-' + name, device + ['shell', 'chmod', '700', remote + '/' + name])
caps = run('device-caps', device + ['shell', remote + '/t_vk_caps'])
report['capabilities'] = json.loads(caps)
report['gpu_executed'] = True
run('device-regression', device + ['shell', remote + '/t_vk_perf'], 180)
finally:
run('device-cleanup', device + ['shell', 'rm', '-rf', remote])
report['passed'] = True
except Exception as exc:
report['error'] = str(exc)
raise
finally:
save()
print('ANDROID_CHECKS_PASS ' + str(out / 'result.json'))
if __name__ == '__main__':
main()
+44
View File
@@ -0,0 +1,44 @@
/* Standalone, game-free Vulkan capability receipt. No private driver, layer,
* window, pipeline, game file or application setting is changed by this probe. */
#include <vulkan/vulkan.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void json_string(const char *s) {
putchar('"');
for(const unsigned char *p=(const unsigned char *)s;*p;p++) {
if(*p=='"'||*p=='\\')printf("\\%c",*p);
else if(*p<32)printf("\\u%04x",*p);
else putchar(*p);
}
putchar('"');
}
int main(void) {
VkApplicationInfo app={.sType=VK_STRUCTURE_TYPE_APPLICATION_INFO,.pApplicationName="D2R capability probe",.apiVersion=VK_API_VERSION_1_1};
VkInstanceCreateInfo ci={.sType=VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,.pApplicationInfo=&app};VkInstance instance;
VkResult rc=vkCreateInstance(&ci,NULL,&instance);
if(rc!=VK_SUCCESS){fprintf(stderr,"vkCreateInstance: %d\n",rc);return 1;}
uint32_t n=0;rc=vkEnumeratePhysicalDevices(instance,&n,NULL);
if(rc!=VK_SUCCESS||!n){fprintf(stderr,"no physical devices: %d\n",rc);vkDestroyInstance(instance,NULL);return 1;}
VkPhysicalDevice *devices=calloc(n,sizeof *devices);if(!devices)return 1;
rc=vkEnumeratePhysicalDevices(instance,&n,devices);if(rc!=VK_SUCCESS){free(devices);vkDestroyInstance(instance,NULL);return 1;}
printf("{\"schema\":1,\"game_compatibility_verified\":false,\"devices\":[");
for(uint32_t i=0;i<n;i++) {
VkPhysicalDeviceProperties p;VkPhysicalDeviceFeatures f;VkPhysicalDeviceMemoryProperties m;
vkGetPhysicalDeviceProperties(devices[i],&p);vkGetPhysicalDeviceFeatures(devices[i],&f);vkGetPhysicalDeviceMemoryProperties(devices[i],&m);
if(i)putchar(',');printf("{\"name\":");json_string(p.deviceName);
printf(",\"vendor_id\":%u,\"device_id\":%u,\"api_version\":%u,\"driver_version\":%u",p.vendorID,p.deviceID,p.apiVersion,p.driverVersion);
printf(",\"independent_blend\":%u,\"draw_storage\":%u,\"storage_read_without_format\":%u,\"storage_write_without_format\":%u,\"gather_extended\":%u",f.independentBlend,f.fragmentStoresAndAtomics,f.shaderStorageImageReadWithoutFormat,f.shaderStorageImageWriteWithoutFormat,f.shaderImageGatherExtended);
printf(",\"memory_types\":[");
for(uint32_t j=0;j<m.memoryTypeCount;j++){if(j)putchar(',');printf("{\"flags\":%u,\"heap\":%u}",m.memoryTypes[j].propertyFlags,m.memoryTypes[j].heapIndex);}printf("]");
uint32_t ne=0;rc=vkEnumerateDeviceExtensionProperties(devices[i],NULL,&ne,NULL);if(rc!=VK_SUCCESS)return 1;
VkExtensionProperties *e=calloc(ne?ne:1,sizeof *e);if(!e)return 1;
rc=vkEnumerateDeviceExtensionProperties(devices[i],NULL,&ne,e);if(rc!=VK_SUCCESS){free(e);return 1;}
printf(",\"extensions\":[");for(uint32_t j=0;j<ne;j++){if(j)putchar(',');json_string(e[j].extensionName);}printf("]");free(e);
const VkFormat formats[]={VK_FORMAT_R8G8B8A8_UNORM,VK_FORMAT_R16G16B16A16_SFLOAT,VK_FORMAT_D16_UNORM,VK_FORMAT_D24_UNORM_S8_UINT,VK_FORMAT_D32_SFLOAT,VK_FORMAT_D32_SFLOAT_S8_UINT};
printf(",\"formats\":[");
for(unsigned j=0;j<sizeof formats/sizeof *formats;j++){VkFormatProperties fp;vkGetPhysicalDeviceFormatProperties(devices[i],formats[j],&fp);if(j)putchar(',');printf("{\"format\":%u,\"optimal_features\":%u}",formats[j],fp.optimalTilingFeatures);}printf("]}");
}
printf("]}\n");free(devices);vkDestroyInstance(instance,NULL);return 0;
}
+73
View File
@@ -0,0 +1,73 @@
/* Host regression: compare production barriers with an independent per-level
* oracle. A barrier whose oldLayout is stale fails before the oracle updates. */
#include "../../gfx/vulkan/nvn_vk_mip_layout.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
typedef struct {
VkImageLayout actual[64], next;
unsigned base, count, barriers;
} Oracle;
static void barrier(void *ctx,VkImageLayout old,VkImageLayout next,unsigned base,unsigned count) {
Oracle *o=ctx;
assert(count && base>=o->base && base+count<=o->base+o->count && next==o->next);
for(unsigned i=base;i<base+count;i++) {
assert(o->actual[i]==old && old!=next);
o->actual[i]=next;
}
o->barriers++;
}
static void transition(NvnVkMipLayouts *s,Oracle *o,unsigned total,unsigned base,unsigned count,VkImageLayout next) {
VkImageLayout expected[64];memcpy(expected,o->actual,sizeof expected);
for(unsigned i=base;i<base+count;i++)expected[i]=next;
o->base=base;o->count=count;o->next=next;
assert(nvn_vk_mip_transition(s,total,base,count,next,barrier,o));
assert(!memcmp(expected,o->actual,sizeof expected));
for(unsigned i=0;i<total;i++)assert((s->mixed?s->levels[i]:s->uniform)==expected[i]);
}
static unsigned rng=0x91738940;
static unsigned random_u32(void) { rng^=rng<<13;rng^=rng>>17;rng^=rng<<5;return rng; }
int main(void) {
unsigned mask=0;
assert(nvn_vk_mip_mask(16,0,16,&mask)&&mask==65535);
assert(nvn_vk_mip_mask(16,15,1,&mask)&&mask==32768);
assert(!nvn_vk_mip_mask(17,0,1,&mask));
assert(!nvn_vk_mip_mask(16,16,1,&mask));
assert(!nvn_vk_mip_mask(16,1,~0u,&mask));
assert(!nvn_vk_mip_mask(0,0,0,&mask));
const VkImageLayout layouts[]={VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,VK_IMAGE_LAYOUT_GENERAL};
unsigned runs=0,emitted=0;
for(unsigned total=1;total<=16;total++) {
NvnVkMipLayouts s={0};Oracle o={0};
transition(&s,&o,total,0,total,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
if(total>1) {
transition(&s,&o,total,0,1,VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
transition(&s,&o,total,1,1,VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
assert(s.mixed);
}
transition(&s,&o,total,0,total,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
assert(!s.mixed);
unsigned before=o.barriers;
transition(&s,&o,total,0,total,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
assert(o.barriers==before);
for(unsigned i=0;i<20000;i++) {
unsigned base=random_u32()%total,count=1+random_u32()%(total-base);
transition(&s,&o,total,base,count,layouts[random_u32()%5]);runs++;
}
NvnVkMipLayouts saved=s;
before=o.barriers;
assert(!nvn_vk_mip_transition(&s,total,total,1,VK_IMAGE_LAYOUT_GENERAL,barrier,&o));
assert(!nvn_vk_mip_transition(&s,total,0,~0u,VK_IMAGE_LAYOUT_GENERAL,barrier,&o));
assert(!nvn_vk_mip_transition(&s,total,0,0,VK_IMAGE_LAYOUT_GENERAL,barrier,&o));
assert(!memcmp(&saved,&s,sizeof s)&&o.barriers==before);
emitted+=o.barriers;
}
NvnVkMipLayouts large={0};Oracle o={0};
transition(&large,&o,32,0,32,VK_IMAGE_LAYOUT_GENERAL);
assert(!nvn_vk_mip_transition(&large,32,0,1,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,barrier,&o));
transition(&large,&o,32,0,32,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
printf("VK_MIP_LAYOUT_PASS random_transitions=%u barriers=%u invalid_ranges large_image_fallback\n",runs,emitted);
return 0;
}
+63 -1
View File
@@ -4,6 +4,66 @@
#include <assert.h>
static void wait_current(void) { uint64_t ticket=mtl_sub_commit();assert(mtl_wait(ticket,UINT64_MAX)); }
static void mip_policy_checks(void) {
int feedback=G.feedback_layout;G.feedback_layout=0;
int subresources=G.subresources;G.subresources=1;
VTexture t={.serial=9001,.format=VK_FORMAT_R8G8B8A8_UNORM};
t.source.serial=t.serial;t.source.d.target=NVN_TEXTURE_TARGET_2D;t.source.d.levels=4;t.source.L.layers=1;
G.state.rt.n=1;G.state.rt.color[0]=&t.source;G.state.rt.has_cview[0]=1;
G.state.rt.cview[0]=(view_t){.set_levels=1,.base_level=1,.nlevels=1};
TSlot *slots=G.tslot;size_t capacity=G.texture_slots;int pool_n=G.texture_pool_n;
G.tslot=calloc(2,sizeof *G.tslot);assert(G.tslot);G.texture_slots=2;G.texture_pool_n=2;
G.tslot[1]=(TSlot){.live=1,.texture=t.source,.has_view=1,.view={.set_levels=1,.base_level=0,.nlevels=1}};
VShader vs={0},ps={0};vs.h.nb=ps.h.nb=1;ps.h.stage=1;vs.b[0].kind=ps.b[0].kind=4;
G.state.tex[0][0]=G.state.tex[1][0]=1;G.nimage_uses=0;
collect_image_uses(&vs);assert(disjoint_mip_sampling(&t));
/* Another stage's overlapping view must disable the optimization for both. */
G.tslot[1].view.base_level=1;collect_image_uses(&ps);assert(!disjoint_mip_sampling(&t));
G.nimage_uses=0;G.tslot[1].view.base_level=0;collect_image_uses(&vs);
G.image_uses[0].roles|=2;assert(!disjoint_mip_sampling(&t));G.image_uses[0].roles=1;
G.image_uses[0].roles|=4;assert(!disjoint_mip_sampling(&t));G.image_uses[0].roles=1;
G.feedback_layout=1;assert(!disjoint_mip_sampling(&t));G.feedback_layout=0;
G.tslot[1].has_view=0;G.nimage_uses=0;collect_image_uses(&vs);assert(!disjoint_mip_sampling(&t));
G.tslot[1].has_view=1;G.nimage_uses=0;collect_image_uses(&vs);assert(disjoint_mip_sampling(&t));
G.state.rt.n=2;G.state.rt.color[1]=&t.source;G.state.rt.has_cview[1]=0;assert(!disjoint_mip_sampling(&t));G.state.rt.n=1;
t.source.L.layers=2;assert(!disjoint_mip_sampling(&t));t.source.L.layers=1;
G.subresources=0;assert(!disjoint_mip_sampling(&t));G.subresources=subresources;
free(G.tslot);G.tslot=slots;G.texture_slots=capacity;G.texture_pool_n=pool_n;
memset(&G.state.rt,0,sizeof G.state.rt);G.state.tex[0][0]=G.state.tex[1][0]=0;G.nimage_uses=0;G.feedback_layout=feedback;
}
/* Real GPU readback verifies both mips survive split layouts and a later
* whole-image copy transition; this fixture needs no game/shader assets. */
static void mip_gpu_checks(void) {
mip_policy_checks();
VTexture t={.serial=9002,.format=VK_FORMAT_R8G8B8A8_UNORM,.width=8,.height=8,.depth=1};
t.source.d.levels=4;t.source.L.layers=1;
VkImageCreateInfo ci={.sType=VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,.imageType=VK_IMAGE_TYPE_2D,.format=t.format,
.extent={8,8,1},.mipLevels=4,.arrayLayers=1,.samples=VK_SAMPLE_COUNT_1_BIT,.tiling=VK_IMAGE_TILING_OPTIMAL,
.usage=VK_IMAGE_USAGE_TRANSFER_SRC_BIT|VK_IMAGE_USAGE_TRANSFER_DST_BIT|VK_IMAGE_USAGE_SAMPLED_BIT|VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT};
CHECK(vkCreateImage(G.device,&ci,NULL,&t.image));VkMemoryRequirements req;vkGetImageMemoryRequirements(G.device,t.image,&req);
VkMemoryAllocateInfo ai={.sType=VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,.allocationSize=req.size,.memoryTypeIndex=memory_type(req.memoryTypeBits,VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)};
CHECK(vkAllocateMemory(G.device,&ai,NULL,&t.memory));CHECK(vkBindImageMemory(G.device,t.image,t.memory,0));
VBuffer readback=buffer_make(320,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
mtl_sub_begin();texture_transition(&t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
for(unsigned i=0;i<4;i++) {
VkClearColorValue value={.float32={i==0?1:0,i==1?1:0,0,1}};
VkImageSubresourceRange range={VK_IMAGE_ASPECT_COLOR_BIT,i,1,0,1};
vkCmdClearColorImage(G.batch->command,t.image,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,&value,1,&range);
}
texture_transition_levels(&t,0,1,VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
texture_transition_levels(&t,1,1,VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);assert(t.layouts.mixed);
texture_transition_levels(&t,0,1,VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
texture_transition_levels(&t,1,1,VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
texture_transition(&t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);assert(!t.layouts.mixed);
for(unsigned i=0;i<2;i++) {
VkBufferImageCopy copy={.bufferOffset=i?256:0,.imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,i,0,1},.imageExtent={8>>i,8>>i,1}};
vkCmdCopyImageToBuffer(G.batch->command,t.image,t.layouts.uniform,readback.b,1,&copy);
}
wait_current();
for(unsigned i=0;i<80;i++){const uint8_t *p=readback.map+4*i;assert(p[0]==(i<64?255:0)&&p[1]==(i<64?0:255)&&p[2]==0&&p[3]==255);}
buffer_free(&readback);vkDestroyImage(G.device,t.image,NULL);vkFreeMemory(G.device,t.memory,NULL);
fprintf(stderr,"VK_MIP_GPU_PASS disjoint_views cross_stage_overlap storage_fallback split_layouts preserved_pixels\n");
}
static void copy_input(uint32_t *guest,VBuffer *readback) {
uint64_t offset=0;VPool *input=input_read((uint64_t)(uintptr_t)guest,16,&offset);
all_barrier();VkBufferCopy copy={offset,0,16};vkCmdCopyBuffer(G.batch->command,input->v.b,readback->b,1,&copy);
@@ -83,6 +143,7 @@ static double input_frames(int frames) {
mtl_finish();double ms=ms_since(t);mtl_pool_del(guest);free(guest);return ms;
}
int main(int argc,char **argv) {
if(argc>1 && !strcmp(argv[1],"mips")){mtl_init();mip_gpu_checks();return 0;}
if(argc>1 && !strcmp(argv[1],"bench"))return bench_main();
if(argc>1 && !strcmp(argv[1],"input")){setenv("DM_VK_POOL_COPY","1",1);mtl_init();
double recycled=input_frames(60);temporary_keep_bytes=0;double fresh=input_frames(60);
@@ -143,5 +204,6 @@ int main(int argc,char **argv) {
mtl_finish();mtl_sub_begin();VBuffer *recycled=temporary(5000,VK_BUFFER_USAGE_TRANSFER_SRC_BIT);VkBuffer handle=recycled->b;assert(recycled->size==8192);wait_current();
mtl_finish();mtl_sub_begin();assert(temporary(8192,VK_BUFFER_USAGE_TRANSFER_DST_BIT)->b==handle);wait_current();mtl_finish();
mtl_pool_del(guest);mtl_finish();buffer_free(&first);buffer_free(&second);free(guest);
fprintf(stderr,"VK_PERF_TEST_PASS snapshots collisions GPU_writebacks fences ring_rotation gpu_timestamps events descriptor_chunks capacity_split temporary_recycle\n");return 0;
mip_gpu_checks();
fprintf(stderr,"VK_PERF_TEST_PASS snapshots collisions GPU_writebacks fences ring_rotation gpu_timestamps events descriptor_chunks capacity_split temporary_recycle mip_layouts\n");return 0;
}