diff --git a/dm/android/Makefile b/dm/android/Makefile index a6ea12e..708b330 100644 --- a/dm/android/Makefile +++ b/dm/android/Makefile @@ -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 diff --git a/dm/android/README.md b/dm/android/README.md index d95cc83..0a66ffb 100644 --- a/dm/android/README.md +++ b/dm/android/README.md @@ -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. diff --git a/dm/android/README.zh-CN.md b/dm/android/README.zh-CN.md index 6ef896c..b2048c9 100644 --- a/dm/android/README.zh-CN.md +++ b/dm/android/README.zh-CN.md @@ -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 不作直接比较。 diff --git a/dm/android/VALIDATION.md b/dm/android/VALIDATION.md new file mode 100644 index 0000000..65273ba --- /dev/null +++ b/dm/android/VALIDATION.md @@ -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. diff --git a/dm/android/build.mk b/dm/android/build.mk index fb6afd5..b41590e 100644 --- a/dm/android/build.mk +++ b/dm/android/build.mk @@ -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 $@) diff --git a/dm/android/tests/Makefile b/dm/android/tests/Makefile index 2df7ac1..8d938b3 100644 --- a/dm/android/tests/Makefile +++ b/dm/android/tests/Makefile @@ -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 diff --git a/dm/android/tests/run_checks.py b/dm/android/tests/run_checks.py new file mode 100644 index 0000000..1b79310 --- /dev/null +++ b/dm/android/tests/run_checks.py @@ -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() diff --git a/dm/android/tests/t_vk_caps.c b/dm/android/tests/t_vk_caps.c new file mode 100644 index 0000000..2a4472f --- /dev/null +++ b/dm/android/tests/t_vk_caps.c @@ -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 +#include +#include +#include + +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 +#include +#include + +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;iactual[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;ibase=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;imixed?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; +} diff --git a/dm/android/tests/t_vk_perf.c b/dm/android/tests/t_vk_perf.c index 11ce8af..c88dade 100644 --- a/dm/android/tests/t_vk_perf.c +++ b/dm/android/tests/t_vk_perf.c @@ -4,6 +4,66 @@ #include 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,©); + } + 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,©); @@ -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; } diff --git a/dm/gfx/vulkan/nvn_vk.c b/dm/gfx/vulkan/nvn_vk.c index c6e76de..30aa40c 100644 --- a/dm/gfx/vulkan/nvn_vk.c +++ b/dm/gfx/vulkan/nvn_vk.c @@ -2,7 +2,7 @@ * This file preserves the recorder's mtl_* C interface to avoid guest changes. * Unsupported semantics abort with a named boundary; no draw/dispatch is dropped. * Logical NVN submissions are batched until present, wait or a CPU-visible write. - * Three fence slots own immutable uploads and transient resources until completion. + * Eight fence slots own immutable uploads and transient resources until completion. */ #define VK_USE_PLATFORM_ANDROID_KHR #include @@ -11,6 +11,7 @@ #include #include "nvn_obj.h" #include "vk_platform.h" +#include "nvn_vk_mip_layout.h" #include "nvn_mtl.h" #include "nvn_dirty.h" #include "../tex/nvn_deswizzle.h" @@ -67,7 +68,7 @@ typedef struct { VkDescriptorSetLayout dyn_layout; VkDescriptorSet set,dyn_set; uint64_t dyn_epoch,dyn_words[2*LIMIT_BINDINGS]; } VShader; typedef struct { uint64_t serial; tex_t source; VkImage image; VkDeviceMemory memory; - VkImageView view; VkFormat format; VkImageLayout layout; uint32_t width,height,depth,bpp; int cpu_owned; uint64_t upload_stamp,version,clean_now,clean_pools; + VkImageView view; VkFormat format; NvnVkMipLayouts layouts; uint32_t width,height,depth,bpp; int cpu_owned; uint64_t upload_stamp,version,clean_now,clean_pools; uint8_t *cpu_snapshot; VkImage shadow;VkDeviceMemory shadow_memory;VkImageView shadow_view;VkFormat shadow_format;VkImageLayout shadow_layout;uint64_t shadow_version; } VTexture; typedef struct { int live; tex_t texture; view_t view; uint8_t has_view; } TSlot; @@ -76,7 +77,7 @@ typedef struct { uint64_t addr,size; } Range; typedef struct { volatile uint32_t *addr; uint32_t mode,value; } Event; typedef struct { uint32_t kind,query; uint64_t address; } CounterOp; typedef struct { Range range; VBuffer *buffer; int written; } AlignedBinding; -typedef struct { uint64_t serial; unsigned roles; } ImageUse; +typedef struct { uint64_t serial; unsigned roles,sampled_mips; } ImageUse; typedef struct { const uint8_t *entry;uint64_t hash;int shader; } ShaderEntry; /* shader:G.shaders 下标 + 1,0 = 未加载 | index into G.shaders + 1, 0 = not loaded */ typedef struct { VBuffer *buffer;uint64_t bytes,offset;char path[1400]; } TraceCapture; /* Keys contain effective Vulkan state only; addresses and dynamic state are excluded. @@ -134,7 +135,7 @@ static struct { uint32_t timestamp_bits; int precise_occlusion; uint64_t samples_passed; Pso *pso[4096]; PassEntry *passes; FramebufferEntry *framebuffers,*current_fb; char cache_path[1200]; uint64_t pso_hits,pso_misses,pass_hits,fb_hits,pso_made,pso_made_ns; _Atomic int cache_dirty; - int in_pass,active,feedback_layout,null_descriptor,depth_sampled,general_feedback; VkPipelineCreateFlags feedback_flags; ReplayState state; VkPhysicalDeviceSubgroupProperties subgroup; + int in_pass,active,feedback_layout,null_descriptor,depth_sampled,general_feedback,subresources; VkPipelineCreateFlags feedback_flags; ReplayState state; VkPhysicalDeviceSubgroupProperties subgroup; uint8_t *shader_index; size_t index_bytes; char shader_root[1024]; ANativeWindow *window; int gather_extended,draw_parameters,vrs; int wait_site;uint64_t wait_ns[10],wait_n[10],sync_lag_max,sync_cur_frame,event_queued,event_blocked; ShaderEntry *shader_entries;size_t shader_entry_capacity; @@ -155,7 +156,7 @@ static struct { int host_import; uint64_t import_align; PFN_vkGetMemoryHostPointerPropertiesEXT get_host_pointer_properties; uint64_t direct_bytes; PFN_vkGetMemoryFdKHR get_memory_fd; PFN_vkGetAndroidHardwareBufferPropertiesANDROID get_ahb_properties; int counting; int32_t query_active; uint64_t profile_barriers,profile_pass_breaks,profile_pipeline_binds,profile_set_binds,profile_set_writes,profile_temp_new,profile_gpu_ns,gpu_last_end,profile_temp_new_bytes,profile_temp_drop,profile_temp_max; -} G={.lock=PTHREAD_MUTEX_INITIALIZER,.completion=PTHREAD_COND_INITIALIZER}; +} G={.lock=PTHREAD_MUTEX_INITIALIZER,.completion=PTHREAD_COND_INITIALIZER,.subresources=1}; /* 阻塞等待按来源记账(WAIT_PROFILE 行):查 CPU 为何停下来等 GPU。| Blocking waits accounted by origin (WAIT_PROFILE line): why the CPU stops for the GPU. */ enum { WAIT_SYNC,WAIT_EVENT,WAIT_PRESENT,WAIT_SLOT,WAIT_READTEX,WAIT_TEXREL,WAIT_SAMPLER,WAIT_POOLDEL,WAIT_FINISH,WAIT_CAPTURE,WAIT_SITES }; static const char *const wait_names[WAIT_SITES]={"sync","event","present","slot","readtex","texrel","sampler","pooldel","finish","capture"}; @@ -483,6 +484,8 @@ static void backend_init(void) { G.state.stencil_compare[0]=G.state.stencil_compare[1]=G.state.stencil_write[0]=G.state.stencil_write[1]=UINT32_MAX; fprintf(stderr,"[nvn-vulkan] initialized %s\n",G.properties.deviceName); G.synchronous=getenv("DM_VK_SYNC")!=NULL; + const char *subres=getenv("DM_VK_SUBRES");G.subresources=!(subres&&*subres=='0'); + fprintf(stderr,"[nvn-vulkan] disjoint_mip_layouts=%d\n",G.subresources); pthread_t worker;if(pthread_create(&worker,NULL,completion_worker,NULL))die("GPU completion worker",0);pthread_detach(worker); G.profile_start_ns=dm_android_nvn_clock_ns(); } @@ -1028,15 +1031,28 @@ static VkImageAspectFlags aspect(VkFormat f) { if(f==VK_FORMAT_D24_UNORM_S8_UINT || f==VK_FORMAT_D32_SFLOAT_S8_UINT) return VK_IMAGE_ASPECT_DEPTH_BIT|VK_IMAGE_ASPECT_STENCIL_BIT; return VK_IMAGE_ASPECT_COLOR_BIT; } -static void texture_transition(VTexture *t,VkImageLayout layout) { - if(t->layout==layout) return; pass_end(); +static void texture_mip_barrier(void *ctx,VkImageLayout old,VkImageLayout layout,unsigned base,unsigned count) { + VTexture *t=ctx;pass_end(); VkImageMemoryBarrier b={.sType=VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, - .srcAccessMask=t->layout==VK_IMAGE_LAYOUT_UNDEFINED?0:VK_ACCESS_MEMORY_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT, - .dstAccessMask=VK_ACCESS_MEMORY_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT,.oldLayout=t->layout,.newLayout=layout, + .srcAccessMask=old==VK_IMAGE_LAYOUT_UNDEFINED?0:VK_ACCESS_MEMORY_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT, + .dstAccessMask=VK_ACCESS_MEMORY_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT,.oldLayout=old,.newLayout=layout, .srcQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED,.dstQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED,.image=t->image, - .subresourceRange={aspect(t->format),0,t->source.d.levels,0,t->source.L.layers}}; + .subresourceRange={aspect(t->format),base,count,0,t->source.L.layers}}; vkCmdPipelineBarrier(G.batch->command,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,0,0,NULL,0,NULL,1,&b); - t->layout=layout; +} +static void texture_transition_levels(VTexture *t,unsigned base,unsigned count,VkImageLayout layout) { + if(!nvn_vk_mip_transition(&t->layouts,t->source.d.levels,base,count,layout,texture_mip_barrier,t)) + die("texture mip transition bounds",t->serial); +} +static void texture_transition(VTexture *t,VkImageLayout layout) { + texture_transition_levels(t,0,t->source.d.levels,layout); +} +/* Start with the bounded, color-only 2D path used by dodola. Depth/stencil, + * arrays, volume textures and devices with feedback layouts keep the old path. */ +static int texture_range_ok(const VTexture *t) { + return G.subresources && !G.feedback_layout && t->source.d.levels>1 && + t->source.d.levels<=NVN_VK_TRACKED_MIPS && t->source.L.layers==1 && + t->source.d.target==NVN_TEXTURE_TARGET_2D && aspect(t->format)==VK_IMAGE_ASPECT_COLOR_BIT; } /* GPU transfers and CPU streaming can update different compression blocks of * one NVN allocation. Compare actual block bytes to the last CPU snapshot so @@ -1070,7 +1086,7 @@ static void refresh_compressed_cpu(VTexture *t,const tex_t *source) { .imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,level,layer,1},.imageOffset={px,py,z},.imageExtent={w,h,1}}; } } - all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);vkCmdCopyBufferToImage(G.batch->command,staging->b,t->image,t->layout,count,regions);changed_regions+=count; + all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);vkCmdCopyBufferToImage(G.batch->command,staging->b,t->image,t->layouts.uniform,count,regions);changed_regions+=count; free(regions);free(old);free(next); } free(t->cpu_snapshot);t->cpu_snapshot=snapshot;t->upload_stamp=stamp;t->clean_now=0; @@ -1111,7 +1127,7 @@ static VTexture *texture_get(const tex_t *source,int upload) { die("texture target/layers/MSAA",source->d.target); hint[h]=(uint16_t)G.ntexture; t=&G.textures[G.ntexture++];memset(t,0,sizeof(*t));t->serial=source->serial; t->source=*source;t->version=1; - t->width=source->d.width; t->height=one?1:source->d.height;t->depth=volume?source->d.depth:1;t->layout=VK_IMAGE_LAYOUT_UNDEFINED; + t->width=source->d.width; t->height=one?1:source->d.height;t->depth=volume?source->d.depth:1;t->layouts.uniform=VK_IMAGE_LAYOUT_UNDEFINED; uint32_t metal_format=0; int decompressed_bpp=0; int bc=nvn_bc_unpacked(source->d.format,&metal_format,&decompressed_bpp); if(bc) { @@ -1471,9 +1487,16 @@ static void collect_image_uses(VShader *s) { if(b->slot<0 || b->slot>=(b->kind==6?32:128))die("image-use shader slot",b->slot); uint64_t handle=b->kind==6?G.state.img[s->h.stage][b->slot]:G.state.tex[s->h.stage][b->slot];unsigned tid=handle&0xfffff; if(texture_unbound(tid,s,b,"image-use texture descriptor"))continue; - uint64_t serial=G.tslot[tid].texture.serial;unsigned j=0;while(jtexture.serial;unsigned j=0;while(jkind==6?2u:1u; + if(b->kind==4) { + unsigned mask=0,base=slot->has_view&&slot->view.set_levels?(unsigned)slot->view.base_level:0; + unsigned count=slot->has_view&&slot->view.set_levels?(unsigned)slot->view.nlevels:slot->texture.d.levels; + if(!nvn_vk_mip_mask(slot->texture.d.levels,base,count,&mask))mask=~0u; + G.image_uses[j].sampled_mips|=mask; + if(s->dref_bindings&(1ull<serial){use=&G.image_uses[i];break;} + if(!use || use->roles!=1u)return 0; /* storage/comparison views retain whole-image layouts */ + unsigned attachments=0; + for(int i=0;iserial==t->serial) { + const view_t *v=G.state.rt.has_cview[i]?&G.state.rt.cview[i]:NULL; + unsigned mask=0,level=v&&v->set_levels?(unsigned)v->base_level:0; + if((v&&v->set_levels&&v->nlevels!=1) || (v&&v->set_layers&&(v->min_layer!=0||v->nlayers!=1)) || + !nvn_vk_mip_mask(t->source.d.levels,level,1,&mask))return 0; + attachments|=mask; + } + return attachments && !(attachments&use->sampled_mips); +} static VkImageLayout sampled_layout(VTexture *t,unsigned stage) { if(storage_image_use(t->serial))return VK_IMAGE_LAYOUT_GENERAL; if(stage!=5){ @@ -1538,7 +1579,7 @@ static void comparison_image(VTexture *t) { uint64_t bytes=(uint64_t)width*height*t->source.L.layers*(f==VK_FORMAT_D16_UNORM?2:4); VBuffer *bridge=temporary((bytes+3)&~3ULL,VK_BUFFER_USAGE_TRANSFER_SRC_BIT|VK_BUFFER_USAGE_TRANSFER_DST_BIT); VkBufferImageCopy region={.imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,level,0,t->source.L.layers},.imageExtent={width,height,1}}; - vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layout,bridge->b,1,®ion); + vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layouts.uniform,bridge->b,1,®ion); VkBufferMemoryBarrier bb={.sType=VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,.srcAccessMask=VK_ACCESS_TRANSFER_WRITE_BIT,.dstAccessMask=VK_ACCESS_TRANSFER_READ_BIT, .srcQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED,.dstQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED,.buffer=bridge->b,.offset=0,.size=VK_WHOLE_SIZE}; vkCmdPipelineBarrier(G.batch->command,VK_PIPELINE_STAGE_TRANSFER_BIT,VK_PIPELINE_STAGE_TRANSFER_BIT,0,0,NULL,1,&bb,0,NULL); @@ -1565,7 +1606,7 @@ static void trace_texture(VTexture *t,const VShader *s,const RBinding *binding) uint64_t bytes=(uint64_t)t->width*t->height*t->source.L.layers*t->bpp; if(bytes>32*1024*1024)return; G.trace_texture_serials[G.ntrace_textures++]=t->serial; - all_barrier();VkImageLayout layout=t->layout;texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + all_barrier();NvnVkMipLayouts saved=t->layouts;texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); VkImageAspectFlags flags=aspect(t->format)&VK_IMAGE_ASPECT_DEPTH_BIT?VK_IMAGE_ASPECT_DEPTH_BIT:VK_IMAGE_ASPECT_COLOR_BIT; unsigned bpp=flags==VK_IMAGE_ASPECT_DEPTH_BIT?(t->format==VK_FORMAT_D16_UNORM?2:4):t->bpp; for(unsigned level=0;levelsource.d.levels;level++){ @@ -1573,7 +1614,7 @@ static void trace_texture(VTexture *t,const VShader *s,const RBinding *binding) bytes=(uint64_t)width*height*t->source.L.layers*bpp; VBuffer *capture=temporary((bytes+3)&~3ULL,VK_BUFFER_USAGE_TRANSFER_DST_BIT); VkBufferImageCopy region={.imageSubresource={flags,level,0,t->source.L.layers},.imageExtent={width,height,1}}; - vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layout,capture->b,1,®ion); + vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layouts.uniform,capture->b,1,®ion); char name[160];snprintf(name,sizeof(name),"texture-%04llu-%llu-mip%u",(unsigned long long)G.present_count+1,(unsigned long long)t->serial,level); trace_capture_queue(capture,bytes,name); fprintf(stderr,"[nvn-vulkan] GPU_TEXTURE_CAPTURE name=%s draw=%llu serial=%llu slot=%d binding=%u format=%u nvn_format=%u extent=%u,%u layers=%u levels=%u mip=%u bpp=%u cpu_owned=%d\n",name,(unsigned long long)G.draws,(unsigned long long)t->serial,binding->slot,binding->binding,t->format,t->source.d.format,width,height,t->source.L.layers,t->source.d.levels,level,bpp,t->cpu_owned); @@ -1589,7 +1630,10 @@ static void trace_texture(VTexture *t,const VShader *s,const RBinding *binding) fprintf(stderr,"[nvn-vulkan] CPU_TEXTURE_CAPTURE bytes=%llu path=%s\n",(unsigned long long)cpu_bytes,path); } } - texture_transition(t,layout); + if(saved.mixed) { + for(unsigned level=0;levelsource.d.levels;level++) + if(saved.levels[level]!=VK_IMAGE_LAYOUT_UNDEFINED)texture_transition_levels(t,level,1,saved.levels[level]); + } else if(saved.uniform!=VK_IMAGE_LAYOUT_UNDEFINED)texture_transition(t,saved.uniform); } static VkDescriptorSet shader_set_allocate(VShader *shader,unsigned dyn) { unsigned need[DESCRIPTOR_TYPES]={0};for(unsigned binding=0;bindingh.nb;binding++)if((shader->dyn_mask>>binding&1)==dyn) @@ -1714,10 +1758,15 @@ static VkDescriptorSet bind_shader(VShader *s) { VTexture *t=texture_get(&slot->texture,1); trace_texture(t,s,b); int alias=b->kind==4&&(s->dref_bindings&(1ull<format)==VK_IMAGE_ASPECT_COLOR_BIT; - if(!alias)texture_transition(t,storage_image_use(t->serial)?VK_IMAGE_LAYOUT_GENERAL:sampled_layout(t,s->h.stage)); + int ranged=b->kind==4 && !alias && s->h.stage!=5 && disjoint_mip_sampling(t); + if(ranged) { + unsigned base=slot->has_view&&slot->view.set_levels?(unsigned)slot->view.base_level:0; + unsigned count=slot->has_view&&slot->view.set_levels?(unsigned)slot->view.nlevels:t->source.d.levels; + texture_transition_levels(t,base,count,VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + } else if(!alias)texture_transition(t,storage_image_use(t->serial)?VK_IMAGE_LAYOUT_GENERAL:sampled_layout(t,s->h.stage)); if(alias&&!t->shadow_view){fprintf(stderr,"[nvn-vulkan] missing comparison view shader=%s binding=%u slot=%d serial=%llu stage=%u\n",s->key,b->binding,b->slot,(unsigned long long)t->serial,s->h.stage);die("comparison image preparation",t->serial);} VkImage selected_image=alias?t->shadow:t->image;VkFormat selected_format=alias?t->shadow_format:t->format; - ii[i].imageView=alias?t->shadow_view:t->view;ii[i].imageLayout=alias?t->shadow_layout:t->layout; + ii[i].imageView=alias?t->shadow_view:t->view;ii[i].imageLayout=alias?t->shadow_layout:ranged?VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:t->layouts.uniform; if(slot->has_view) { view_t *v=&slot->view; uint32_t level=v->set_levels?v->base_level:0,levels=v->set_levels?v->nlevels:t->source.d.levels; @@ -1874,8 +1923,8 @@ static void pending_drop(int i){pending[i]=pending[--npending];} static void pending_flush_one(int i) { PendingClear c=pending[i];pending_drop(i);pending_flushed++; all_barrier();texture_transition(c.t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); - if(c.range.aspectMask&VK_IMAGE_ASPECT_COLOR_BIT)vkCmdClearColorImage(G.batch->command,c.t->image,c.t->layout,&c.value.color,1,&c.range); - else vkCmdClearDepthStencilImage(G.batch->command,c.t->image,c.t->layout,&c.value.depthStencil,1,&c.range); + if(c.range.aspectMask&VK_IMAGE_ASPECT_COLOR_BIT)vkCmdClearColorImage(G.batch->command,c.t->image,c.t->layouts.uniform,&c.value.color,1,&c.range); + else vkCmdClearDepthStencilImage(G.batch->command,c.t->image,c.t->layouts.uniform,&c.value.depthStencil,1,&c.range); } static void pending_flush(void){while(npending)pending_flush_one(npending-1);} static void pending_add(VTexture *t,VkImageSubresourceRange range,const VkClearValue *value) { @@ -1936,10 +1985,11 @@ static VkRenderPass render_begin(void) { t->cpu_owned=0;t->version++; VkImageLayout attachment_layout=is_depth?VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; if(is_depth&&G.depth_sampled&&depth_read_only())attachment_layout=VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; - else if(G.general_feedback&&image_sampled(source->serial))attachment_layout=VK_IMAGE_LAYOUT_GENERAL; + else if(G.general_feedback&&image_sampled(source->serial)&&!disjoint_mip_sampling(t))attachment_layout=VK_IMAGE_LAYOUT_GENERAL; else if(G.feedback_flags&(is_depth?VK_PIPELINE_CREATE_DEPTH_STENCIL_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT:VK_PIPELINE_CREATE_COLOR_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT))attachment_layout=VK_IMAGE_LAYOUT_ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT; - texture_transition(t,attachment_layout); - VkImageLayout layout=t->layout; + if(disjoint_mip_sampling(t))texture_transition_levels(t,range.baseMipLevel,range.levelCount,attachment_layout); + else texture_transition(t,attachment_layout); + VkImageLayout layout=attachment_layout; attachments[n]=(VkAttachmentDescription){.format=t->format,.samples=VK_SAMPLE_COUNT_1_BIT,.loadOp=VK_ATTACHMENT_LOAD_OP_LOAD, .storeOp=VK_ATTACHMENT_STORE_OP_STORE,.stencilLoadOp=VK_ATTACHMENT_LOAD_OP_LOAD,.stencilStoreOp=VK_ATTACHMENT_STORE_OP_STORE, .initialLayout=layout,.finalLayout=layout}; @@ -2153,7 +2203,7 @@ static void draw(const p_draw *a,const p_draw_idx *idx) { VTexture *t=texture_get(G.state.rt.color[0],0);if(t->bpp!=4||aspect(t->format)!=VK_IMAGE_ASPECT_COLOR_BIT)die("UI result capture format",t->format); all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);uint64_t bytes=(uint64_t)t->width*t->height*4; VBuffer *capture=temporary(bytes,VK_BUFFER_USAGE_TRANSFER_DST_BIT);VkBufferImageCopy copy={.imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,0,0,1},.imageExtent={t->width,t->height,1}}; - vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layout,capture->b,1,©);char name[160];snprintf(name,sizeof(name),"ui-result-%04llu-%llu-%ux%u",(unsigned long long)G.present_count+1,(unsigned long long)G.draws,t->width,t->height);trace_capture_queue(capture,bytes,name); + vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layouts.uniform,capture->b,1,©);char name[160];snprintf(name,sizeof(name),"ui-result-%04llu-%llu-%ux%u",(unsigned long long)G.present_count+1,(unsigned long long)G.draws,t->width,t->height);trace_capture_queue(capture,bytes,name); } if(!pp_ps)pp_ps=ps?ps->key:"-"; G.draws++;G.batch->draws++;aligned_writeback(); @@ -2225,14 +2275,14 @@ static void copy_b2t(const p_copy_b2t *p) { all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); VkBufferImageCopy c={.imageSubresource={aspect(t->format),level,volume?0:layer,volume?1:p->r.depth}, .imageOffset={p->r.xoffset,p->r.yoffset,volume?p->r.zoffset:0},.imageExtent={p->r.width,p->r.height,volume?p->r.depth:1}}; - vkCmdCopyBufferToImage(G.batch->command,staging->b,t->image,t->layout,1,&c);t->cpu_owned=0;t->version++;return; + vkCmdCopyBufferToImage(G.batch->command,staging->b,t->image,t->layouts.uniform,1,&c);t->cpu_owned=0;t->version++;return; } if(row%t->bpp || row<(uint64_t)p->r.width*t->bpp || (uint64_t)p->r.xoffset+p->r.width>width || (uint64_t)p->r.yoffset+p->r.height>height) die("buffer-to-texture extent/stride",row); uint64_t offset=0;VPool *src=pool_read(p->src,row*p->r.height*p->r.depth,&offset);all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); VkBufferImageCopy c={.bufferOffset=offset,.bufferRowLength=(uint32_t)(row/t->bpp),.imageSubresource={aspect(t->format),level,volume?0:layer,volume?1:p->r.depth}, .imageOffset={p->r.xoffset,p->r.yoffset,volume?p->r.zoffset:0},.imageExtent={p->r.width,p->r.height,volume?p->r.depth:1}}; - vkCmdCopyBufferToImage(G.batch->command,src->v.b,t->image,t->layout,1,&c);t->cpu_owned=0;t->version++; + vkCmdCopyBufferToImage(G.batch->command,src->v.b,t->image,t->layouts.uniform,1,&c);t->cpu_owned=0;t->version++; } static void clear_color(const p_clear_color *p) { if(p->mask!=15 || p->index<0 || p->index>=G.state.rt.n)die("clear-color target/mask/view",p->mask); @@ -2309,7 +2359,7 @@ static void clear_tex(const p_clear_tex *p) { all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); VkBufferImageCopy c={.imageSubresource={aspect(t->format),level,volume?0:layer+p->r.zoffset,volume?1:p->r.depth}, .imageOffset={p->r.xoffset,p->r.yoffset,volume?p->r.zoffset:0},.imageExtent={p->r.width,p->r.height,volume?p->r.depth:1}}; - vkCmdCopyBufferToImage(G.batch->command,staging->b,t->image,t->layout,1,&c); + vkCmdCopyBufferToImage(G.batch->command,staging->b,t->image,t->layouts.uniform,1,&c); t->cpu_owned=0;t->version++; /* GPU now owns the image; sampled access must preserve it. */ } static VkImageSubresourceLayers copy_layers(const tex_t *t,VkFormat gpu_format,const view_t *v,const NVNcopyRegion *r) { @@ -2341,7 +2391,7 @@ static void copy_t2t(const p_copy_t2t *p) { VkOffset3D so={p->sr.xoffset,p->sr.yoffset,sv?p->sr.zoffset:0},doff={p->dr.xoffset,p->dr.yoffset,dv?p->dr.zoffset:0}; if(p->sr.width==p->dr.width&&p->sr.height==p->dr.height&&p->sr.depth==p->dr.depth) { VkImageCopy c={.srcSubresource=sl,.srcOffset=so,.dstSubresource=dl,.dstOffset=doff,.extent={p->sr.width,p->sr.height,sv?p->sr.depth:1}}; - vkCmdCopyImage(G.batch->command,s->image,s->layout,d->image,d->layout,1,&c); + vkCmdCopyImage(G.batch->command,s->image,s->layouts.uniform,d->image,d->layouts.uniform,1,&c); }else { VkFormatProperties fp;vkGetPhysicalDeviceFormatProperties(G.physical,s->format,&fp); if(aspect(s->format)!=VK_IMAGE_ASPECT_COLOR_BIT || !(p->flags&NVN_COPY_FLAGS_ENGINE_2D_BIT) || (!sv&&p->sr.depth!=p->dr.depth) || @@ -2350,7 +2400,7 @@ static void copy_t2t(const p_copy_t2t *p) { if(filter==VK_FILTER_LINEAR&&!(fp.optimalTilingFeatures&VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT))die("texture blit linear feature",s->format); VkImageBlit c={.srcSubresource=sl,.srcOffsets={so,{so.x+p->sr.width,so.y+p->sr.height,so.z+(sv?p->sr.depth:1)}}, .dstSubresource=dl,.dstOffsets={doff,{doff.x+p->dr.width,doff.y+p->dr.height,doff.z+(dv?p->dr.depth:1)}}}; - vkCmdBlitImage(G.batch->command,s->image,s->layout,d->image,d->layout,1,&c,filter); + vkCmdBlitImage(G.batch->command,s->image,s->layouts.uniform,d->image,d->layouts.uniform,1,&c,filter); } d->cpu_owned=0;d->version++;all_barrier(); } @@ -2757,7 +2807,7 @@ static void nan_snap(const char *tag) { for(unsigned lv=0;lvsource.d.levels && lv<4 && g_nnanwidth>>lv?u->width>>lv:1,h=u->height>>lv?u->height>>lv:1; g_nan[g_nnan].buf=buffer_make((uint64_t)w*h*nan_bpp(u->format),VK_BUFFER_USAGE_TRANSFER_DST_BIT); VkBufferImageCopy c={.imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,lv,0,1},.imageExtent={w,h,1}}; - vkCmdCopyImageToBuffer(G.batch->command,u->image,u->layout,g_nan[g_nnan].buf.b,1,&c); + vkCmdCopyImageToBuffer(G.batch->command,u->image,u->layouts.uniform,g_nan[g_nnan].buf.b,1,&c); g_nan[g_nnan].t=u;g_nan[g_nnan].serial=u->serial;g_nan[g_nnan].lv=lv;g_nan[g_nnan].x=g_nan[g_nnan].y=0;g_nan[g_nnan].w=w;g_nan[g_nnan].h=h;snprintf(g_nan[g_nnan++].tag,40,"%s",tag);}} } /* 只拷一张目标 0 级里的一个小框(DM_VK_NANSCAN_BOX=x,y,w,h:追踪帧里每次绘制前拍当前 0 号颜色目标,用来二分出第一次写出 NaN 的绘制) @@ -2768,7 +2818,7 @@ static void nan_snap_box(VTexture *u,const unsigned box[4],const char *tag) { pass_end();texture_transition(u,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); g_nan[g_nnan].buf=buffer_make((uint64_t)box[2]*box[3]*nan_bpp(u->format),VK_BUFFER_USAGE_TRANSFER_DST_BIT); VkBufferImageCopy c={.imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,0,0,1},.imageOffset={(int)box[0],(int)box[1],0},.imageExtent={box[2],box[3],1}}; - vkCmdCopyImageToBuffer(G.batch->command,u->image,u->layout,g_nan[g_nnan].buf.b,1,&c); + vkCmdCopyImageToBuffer(G.batch->command,u->image,u->layouts.uniform,g_nan[g_nnan].buf.b,1,&c); g_nan[g_nnan].t=u;g_nan[g_nnan].serial=u->serial;g_nan[g_nnan].lv=0;g_nan[g_nnan].x=box[0];g_nan[g_nnan].y=box[1];g_nan[g_nnan].w=box[2];g_nan[g_nnan].h=box[3];snprintf(g_nan[g_nnan++].tag,40,"%s",tag); } static void nan_report(void) { @@ -2805,7 +2855,7 @@ uint64_t mtl_present(const tex_t *source,double period,const int crop[4]) { int capture_frame=shot || burst || (capture_root && (G.trace_frame || G.present_count<4 || (G.present_count%120==0 && G.present_count<1000))); if(capture_frame && t->bpp==4){capture=buffer_make((uint64_t)t->width*t->height*4,VK_BUFFER_USAGE_TRANSFER_DST_BIT); texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);VkBufferImageCopy c={.imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,0,0,1},.imageExtent={t->width,t->height,1}}; - vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layout,capture.b,1,&c);} + vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layouts.uniform,capture.b,1,&c);} else if(capture_frame)fprintf(stderr,"[nvn-vulkan] readback skipped: present texture bpp=%u format=%u\n",t->bpp,t->format); if(G.trace_frame && capture.b)nan_snap("present"); G.batch->ticket=++G.fence;VkFence fence=G.batch->fence; @@ -2925,7 +2975,7 @@ void mtl_read_texels(const tex_t *source,unsigned level,unsigned layer,const NVN size_t pitch=(size_t)region->width*t->bpp;if(rowheight))die("CPU texture read stride",row); VBuffer readback=buffer_make(pitch*region->height,VK_BUFFER_USAGE_TRANSFER_DST_BIT);texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); VkBufferImageCopy copy={.imageSubresource={aspect(t->format),level,layer,1},.imageOffset={region->xoffset,region->yoffset,region->zoffset},.imageExtent={region->width,region->height,1}}; - vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layout,readback.b,1,©);uint64_t ticket=mtl_sub_commit();wait_at(ticket,UINT64_MAX,WAIT_READTEX); + vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layouts.uniform,readback.b,1,©);uint64_t ticket=mtl_sub_commit();wait_at(ticket,UINT64_MAX,WAIT_READTEX); for(int y=0;yheight;y++)memcpy(dst+y*row,readback.map+y*pitch,pitch);buffer_free(&readback); } #ifdef DM_VK_COPY_TEST @@ -2941,7 +2991,7 @@ void dm_vk_copy_test_read(const tex_t *source,unsigned level,unsigned layer,uint VBuffer readback=buffer_make((uint64_t)w*h*t->bpp,VK_BUFFER_USAGE_TRANSFER_DST_BIT); texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); VkBufferImageCopy c={.imageSubresource={aspect(t->format),level,layer,1},.imageExtent={w,h,1}}; - vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layout,readback.b,1,&c);uint64_t ticket=mtl_sub_commit();wait_at(ticket,UINT64_MAX,WAIT_READTEX); + vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layouts.uniform,readback.b,1,&c);uint64_t ticket=mtl_sub_commit();wait_at(ticket,UINT64_MAX,WAIT_READTEX); memcpy(dst,readback.map,(size_t)w*h*t->bpp);buffer_free(&readback); } #endif diff --git a/dm/gfx/vulkan/nvn_vk_mip_layout.h b/dm/gfx/vulkan/nvn_vk_mip_layout.h new file mode 100644 index 0000000..4823655 --- /dev/null +++ b/dm/gfx/vulkan/nvn_vk_mip_layout.h @@ -0,0 +1,50 @@ +/* Per-mip layout tracking, inspired by dodola/d2r-mobile's Vulkan backend + * (642480b). Keep the current backend's conservative synchronization masks. + * No game addresses, platform services or shader metadata are shared. */ +#ifndef NVN_VK_MIP_LAYOUT_H +#define NVN_VK_MIP_LAYOUT_H +#include + +#define NVN_VK_TRACKED_MIPS 16 +typedef struct { + /* uniform is only usable as an image-wide layout when mixed == 0. */ + VkImageLayout uniform, levels[NVN_VK_TRACKED_MIPS]; + unsigned mixed; +} NvnVkMipLayouts; +typedef void (*NvnVkMipBarrier)(void *, VkImageLayout, VkImageLayout, unsigned, unsigned); + +static inline int nvn_vk_mip_mask(unsigned total, unsigned base, unsigned count, unsigned *mask) { + if (!total || total > NVN_VK_TRACKED_MIPS || base >= total || !count || count > total - base) return 0; + *mask = ((1u << count) - 1u) << base; + return 1; +} + +/* Validate before changing state or emitting barriers. Whole-image transitions + * remain supported for images outside the bounded per-mip tracking path. */ +static inline int nvn_vk_mip_transition(NvnVkMipLayouts *s, unsigned total, + unsigned base, unsigned count, VkImageLayout next, NvnVkMipBarrier emit, void *ctx) { + if (!total || base >= total || !count || count > total - base || + (total > NVN_VK_TRACKED_MIPS && (base || count != total || s->mixed))) return 0; + if (!s->mixed) { + if (s->uniform == next) return 1; + if (!base && count == total) { + emit(ctx, s->uniform, next, 0, total); s->uniform = next; return 1; + } + for (unsigned i = 0; i < total; i++) s->levels[i] = s->uniform; + s->mixed = 1; + } + for (unsigned i = base; i < base + count;) { + VkImageLayout old = s->levels[i]; + if (old == next) { i++; continue; } + unsigned end = i + 1; + while (end < base + count && s->levels[end] == old) end++; + emit(ctx, old, next, i, end - i); + for (unsigned k = i; k < end; k++) s->levels[k] = next; + i = end; + } + unsigned i = 1; + while (i < total && s->levels[i] == s->levels[0]) i++; + if (i == total) { s->uniform = s->levels[0]; s->mixed = 0; } + return 1; +} +#endif