Initial public release

This commit is contained in:
jhaizhou
2026-10-12 16:51:08 +08:00
commit 46578a2b5d
997 changed files with 218713 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
test_offscreen
*.o
+23
View File
@@ -0,0 +1,23 @@
CC = clang
CFLAGS = -O2 -Wall -Wextra -std=c11
OBJCFLAGS = -O2 -Wall -Wextra -fobjc-arc
LDLIBS = -framework Metal -framework Foundation
all: test_offscreen
mtl_backend.o: mtl_backend.m mtl_backend.h
$(CC) $(OBJCFLAGS) -c -o $@ $<
test_offscreen.o: test_offscreen.c mtl_backend.h
$(CC) $(CFLAGS) -c -o $@ $<
test_offscreen: test_offscreen.o mtl_backend.o
$(CC) -o $@ $^ $(LDLIBS)
run: test_offscreen
./test_offscreen
clean:
rm -f test_offscreen *.o
.PHONY: all run clean
+60
View File
@@ -0,0 +1,60 @@
# dm/gfx/metal — minimal Metal offscreen example
中文:[README.zh-CN.md](README.zh-CN.md)
A standalone small module: it wraps Metal in a pure C interface, renders the picture to an offscreen texture and reads it back to the CPU, without putting anything on screen. It is not compiled into the host (`dm/host/Makefile` does not include this directory); the Metal replay layer the game actually uses is in `../nvn/nvn_mtl.m`. This is kept as a reference that compiles on its own and can be understood in a few dozen lines, and as a small probe for verifying Metal behavior.
## Interface (`mtl_backend.h`)
| Interface | Effect |
|---|---|
| `mtlb_init()` / `mtlb_shutdown(ctx)` | Create / release the context: device, command queue, the current frame's command buffer, pipeline cache |
| `mtlb_target(ctx, w, h, fmt)` / `mtlb_target_free(rt)` | Create / release an offscreen render target, with format `MTLB_FMT_BGRA8` or `MTLB_FMT_RGBA8` |
| `mtlb_clear(ctx, rt, r, g, b, a)` | Records a render pass into the current frame that clears the target to the given color |
| `mtlb_triangle(ctx, rt)` | Records another render pass into the current frame (keeping existing contents) that draws a three-color triangle |
| `mtlb_readback(ctx, rt, buf, size)` | Submits the current frame, waits for the GPU to complete, and reads the pixels back into `buf` tightly packed by row (row 0 is the top of the image) |
Functions return 0 for success and -1 for failure, and the failure reason is printed to standard error. The implementation is in `mtl_backend.m` (Objective-C, ARC).
Design points:
- **One command buffer per frame**: it is created only when a pass is first recorded; subsequent clears and triangles are appended to the same command buffer, and it is submitted only at readback.
- **Render targets are not global variables**: the context and each target are opaque pointers.
- **Storage mode is Shared**: on unified-memory devices a Shared texture can be used directly as a render attachment, and after the GPU completes the CPU reads it directly, with no intermediate buffer needed. On non-unified-memory devices `mtlb_init` reports an error outright.
- The triangle's shader is inline MSL, compiled at run time.
## Building and running
```sh
make -C dm/gfx/metal # produces test_offscreen
make -C dm/gfx/metal run # runs the self-test; exit code 0 means all passed
make -C dm/gfx/metal clean
```
Only Xcode's command-line tools are needed; no game files are needed. The build products are already listed in this directory's `.gitignore`.
## Self-test (`test_offscreen.c`)
All expected values are computed independently in the test, without reading the backend's internal data:
- the triangle vertices are copied separately in the test;
- normalized coordinates are converted to pixels: `px = (x + 1) / 2 · W`, `py = (1 − y) / 2 · H`;
- the color at a pixel center is the linear interpolation of the three vertex colors by barycentric coordinates.
The two tests are each run once for both formats, BGRA8 and RGBA8:
1. Clear to a solid color and compare pixel by pixel.
2. Clear the screen and then draw the triangle: pixels inside the triangle (more than 1 pixel from an edge) are compared with the interpolated value, with the tolerance given by `TOL` in the source; pixels outside are compared with the clear color; the 1-pixel band right along the edges is skipped, since rasterization edge rules are outside the scope of this test.
Before readback the buffer is first filled with 0x5a, to prevent "passing even though the backend wrote nothing".
## Probe (`probe/p_nocopy.m`)
A single-file program with no build target; compile it manually with clang when needed. It verifies one thing that the replay layer's memory pool approach depends on: on a piece of memory that is not page-aligned, after extending its start and end outward to page boundaries, a zero-copy `MTLBuffer` can be created; two such buffers are allowed to overlap; and what the GPU writes can be read by the CPU through the original pointer.
## Limitations
- The triangle vertices are hard-coded in `mtl_backend.m`; there is no configurable state such as vertex buffers, shaders or viewports.
- `mtlb_readback` waits synchronously for the whole frame to complete and blocks the calling thread.
- Only a single color attachment and two 8-bit formats are supported; there is no depth / stencil, multisampling or multiple attachments.
- Not thread-safe; only unified-memory devices are supported.
+60
View File
@@ -0,0 +1,60 @@
# dm/gfx/metal — 最小 Metal 离屏示例
English: [README.md](README.md)
一个独立的小模块:用纯 C 接口包住 Metal,把画面渲到离屏纹理再读回 CPU,不上屏。它不编进宿主(`dm/host/Makefile` 不收本目录),游戏实际用的 Metal 回放层在 `../nvn/nvn_mtl.m`。这里留作一个能独立编译、几十行就能看懂的参照,以及验证 Metal 行为的小探针。
## 接口(`mtl_backend.h`)
| 接口 | 作用 |
|---|---|
| `mtlb_init()` / `mtlb_shutdown(ctx)` | 建 / 释放上下文:设备、命令队列、当前帧的命令缓冲、管线缓存 |
| `mtlb_target(ctx, w, h, fmt)` / `mtlb_target_free(rt)` | 建 / 释放一个离屏渲染目标,格式为 `MTLB_FMT_BGRA8` 或 `MTLB_FMT_RGBA8` |
| `mtlb_clear(ctx, rt, r, g, b, a)` | 往当前帧录一个渲染通道,把目标清成指定颜色 |
| `mtlb_triangle(ctx, rt)` | 往当前帧再录一个渲染通道(保留已有内容),画一个三色三角形 |
| `mtlb_readback(ctx, rt, buf, size)` | 提交当前帧、等 GPU 完成,把像素按行紧排读回 `buf`(第 0 行是图像顶部) |
函数返回 0 表示成功、-1 表示失败,失败原因打到标准错误。实现在 `mtl_backend.m`(Objective-C,ARC)。
设计要点:
- **一帧一个命令缓冲**:第一次录通道时才创建,之后的清除、三角形都追加进同一个命令缓冲,读回时才提交。
- **渲染目标不是全局变量**:上下文与每个目标都是不透明指针。
- **存储模式用 Shared**:在统一内存设备上,Shared 纹理可以直接当渲染附件,GPU 完成后 CPU 直接读,不需要中转缓冲。非统一内存设备上 `mtlb_init` 直接报错。
- 三角形的着色器是内联的 MSL,运行时编译。
## 编译与运行
```sh
make -C dm/gfx/metal # 产出 test_offscreen
make -C dm/gfx/metal run # 跑自测,退出码 0 表示全过
make -C dm/gfx/metal clean
```
只需要 Xcode 的命令行工具,不需要游戏文件。编译产物已列入本目录的 `.gitignore`。
## 自测(`test_offscreen.c`)
期望值全部在测试里独立算出,不读后端内部数据:
- 三角形顶点在测试里另抄一份;
- 归一化坐标换算到像素:`px = (x + 1) / 2 · W`,`py = (1 − y) / 2 · H`;
- 像素中心的颜色按重心坐标对三个顶点颜色线性插值。
两个测试对 BGRA8、RGBA8 两种格式各跑一遍:
1. 清成纯色,逐像素比。
2. 清屏后画三角形:三角形内侧(离边超过 1 像素)的像素与插值值比,容差见源码里的 `TOL`;外侧像素与清屏色比;紧贴边的 1 像素带跳过,光栅化的边缘规则不在本测试范围内。
读回前先把缓冲填成 0x5a,防止「后端什么都没写也判过」。
## 探针(`probe/p_nocopy.m`)
单文件程序,没有构建目标,需要时手动用 clang 编译。它验证回放层内存池做法所依赖的一件事:在一段不按页对齐的内存上,把首尾外扩到页边界后可以建成零拷贝的 `MTLBuffer`,两个这样的缓冲允许重叠,GPU 写入的内容 CPU 经原指针能读到。
## 局限
- 三角形顶点写死在 `mtl_backend.m`,没有顶点缓冲、着色器、视口等可配置状态。
- `mtlb_readback` 同步等整帧完成,会阻塞调用线程。
- 只支持单个颜色附件、两种 8 位格式;没有深度 / 模板、多重采样、多附件。
- 非线程安全;只支持统一内存设备。
+55
View File
@@ -0,0 +1,55 @@
/* mtl_backend.h —— 最小 Metal 离屏后端(纯 C 接口,NVN→Metal 后端底座)
*
* 调用模型:
* ctx = mtlb_init();
* rt = mtlb_target(ctx, w, h, MTLB_FMT_BGRA8);
* mtlb_clear(ctx, rt, ...); // 录一个 pass 进「当前帧」的命令缓冲
* mtlb_triangle(ctx, rt); // 再录一个 pass,同一命令缓冲
* mtlb_readback(ctx, rt, buf, n);// 提交当前帧、等 GPU 完成、读回像素
*
* 一帧 = 一个 MTLCommandBuffer,在第一次录 pass 时创建,readback 时提交。
* 所有函数返回 0 成功 / -1 失败(失败原因打到 stderr)。非线程安全。
* mtl_backend.h - minimal Metal offscreen backend (pure C interface, the base of the NVN→Metal backend)
* Call model:
* ctx = mtlb_init();
* rt = mtlb_target(ctx, w, h, MTLB_FMT_BGRA8);
* mtlb_clear(ctx, rt, ...); // record a pass into the "current frame" command buffer
* mtlb_triangle(ctx, rt); // record another pass, same command buffer
* mtlb_readback(ctx, rt, buf, n);// commit the current frame, wait for the GPU to finish, read back pixels
* One frame = one MTLCommandBuffer, created when the first pass is recorded and committed at readback.
* All functions return 0 on success / -1 on failure (the failure reason is printed to stderr). Not thread-safe.
*/
#ifndef MTL_BACKEND_H
#define MTL_BACKEND_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct mtlb_ctx mtlb_ctx; /* 设备 + 命令队列 + 当前帧命令缓冲 + 管线缓存 | device + command queue + current-frame command buffer + pipeline cache */
typedef struct mtlb_rt mtlb_rt; /* 一个离屏渲染目标 | an offscreen render target */
typedef enum {
MTLB_FMT_BGRA8 = 0, /* 内存字节序 B,G,R,A(unorm) | byte order in memory B,G,R,A (unorm) */
MTLB_FMT_RGBA8 = 1, /* 内存字节序 R,G,B,A(unorm) | byte order in memory R,G,B,A (unorm) */
} mtlb_fmt;
mtlb_ctx *mtlb_init(void);
void mtlb_shutdown(mtlb_ctx *ctx);
mtlb_rt *mtlb_target(mtlb_ctx *ctx, uint32_t w, uint32_t h, mtlb_fmt fmt);
void mtlb_target_free(mtlb_rt *rt);
int mtlb_clear(mtlb_ctx *ctx, mtlb_rt *rt, float r, float g, float b, float a);
int mtlb_triangle(mtlb_ctx *ctx, mtlb_rt *rt);
/* buf 至少 w*h*4 字节;按行紧排、第 0 行是图像顶部,字节序同 rt 的格式。 | buf is at least w*h*4 bytes; rows tightly packed, row 0 is the top of the image, byte order same as rt's format. */
int mtlb_readback(mtlb_ctx *ctx, mtlb_rt *rt, void *buf, size_t buf_size);
#ifdef __cplusplus
}
#endif
#endif
+210
View File
@@ -0,0 +1,210 @@
// mtl_backend.m —— mtl_backend.h 的实现(ObjC,-fobjc-arc)
//
// 渲染目标存储模式取 MTLStorageModeShared:本机是 Apple Silicon 统一内存,
// Shared 纹理可直接当渲染附件,GPU 完成后 CPU 用 getBytes 直接读,无需额外的
// blit 拷贝与中转缓冲,回读路径最短。代价:Shared 纹理不能做无损帧缓冲压缩,
// 将来走性能路线时再换 Private + blit 回读(只影响 mtlb_target / mtlb_readback)。
// mtl_backend.m - implementation of mtl_backend.h (ObjC, -fobjc-arc)
// Render targets use storage mode MTLStorageModeShared: this machine is Apple Silicon with unified memory,
// a Shared texture can be used directly as a render attachment, and once the GPU is done the CPU reads it directly with getBytes, with no extra
// blit copy or staging buffer, so the readback path is the shortest. Cost: Shared textures cannot use lossless framebuffer compression;
// when taking the performance route later, switch to Private + blit readback (only affects mtlb_target / mtlb_readback).
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#include <stdio.h>
#include "mtl_backend.h"
// ---- 内部对象(用 ObjC 类承载,ARC 管理 Metal 对象生命周期;对外是不透明 C 指针)----
// ---- Internal objects (held in ObjC classes, ARC manages Metal object lifetimes; exposed as opaque C pointers) ----
@interface MTLBCtx : NSObject
@property(nonatomic, strong) id<MTLDevice> dev;
@property(nonatomic, strong) id<MTLCommandQueue> queue;
@property(nonatomic, strong) id<MTLCommandBuffer> frame; // 当前帧,懒建,readback 时提交 | current frame, created lazily, committed at readback
@property(nonatomic, strong) id<MTLLibrary> triLib;
@property(nonatomic, strong) NSMutableDictionary<NSNumber *, id<MTLRenderPipelineState>> *triPso; // 按像素格式缓存 | cached by pixel format
@end
@implementation MTLBCtx
@end
@interface MTLBRt : NSObject
@property(nonatomic, strong) id<MTLTexture> tex;
@property(nonatomic) uint32_t w, h;
@end
@implementation MTLBRt
@end
#define CTX(p) ((__bridge MTLBCtx *)(void *)(p))
#define RT(p) ((__bridge MTLBRt *)(void *)(p))
static void err(const char *where, NSError *e) {
fprintf(stderr, "[mtlb] %s 失败%s%s\n", where, e ? ":" : "",
e ? e.localizedDescription.UTF8String : "");
}
static id<MTLCommandBuffer> frame_cb(MTLBCtx *c) {
if (!c.frame) c.frame = [c.queue commandBuffer];
return c.frame;
}
// ---- 设备 ----
// ---- Device ----
mtlb_ctx *mtlb_init(void) {
@autoreleasepool {
id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
if (!dev) { err("MTLCreateSystemDefaultDevice", nil); return NULL; }
if (!dev.hasUnifiedMemory) { err("需要统一内存设备(Shared 渲染目标)", nil); return NULL; }
MTLBCtx *c = [MTLBCtx new];
c.dev = dev;
c.queue = [dev newCommandQueue];
if (!c.queue) { err("newCommandQueue", nil); return NULL; }
c.triPso = [NSMutableDictionary dictionary];
return (mtlb_ctx *)CFBridgingRetain(c);
}
}
void mtlb_shutdown(mtlb_ctx *ctx) {
if (!ctx) return;
@autoreleasepool {
MTLBCtx *c = CTX(ctx);
if (c.frame) { [c.frame commit]; [c.frame waitUntilCompleted]; c.frame = nil; }
CFBridgingRelease(ctx);
}
}
// ---- 渲染目标 ----
// ---- Render targets ----
static MTLPixelFormat pixfmt(mtlb_fmt f) {
switch (f) {
case MTLB_FMT_BGRA8: return MTLPixelFormatBGRA8Unorm;
case MTLB_FMT_RGBA8: return MTLPixelFormatRGBA8Unorm;
}
return MTLPixelFormatInvalid;
}
mtlb_rt *mtlb_target(mtlb_ctx *ctx, uint32_t w, uint32_t h, mtlb_fmt fmt) {
@autoreleasepool {
MTLPixelFormat pf = pixfmt(fmt);
if (!ctx || !w || !h || pf == MTLPixelFormatInvalid) { err("mtlb_target 参数", nil); return NULL; }
MTLTextureDescriptor *d =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:pf width:w height:h mipmapped:NO];
d.storageMode = MTLStorageModeShared;
d.usage = MTLTextureUsageRenderTarget;
MTLBRt *r = [MTLBRt new];
r.tex = [CTX(ctx).dev newTextureWithDescriptor:d];
if (!r.tex) { err("newTextureWithDescriptor", nil); return NULL; }
r.w = w; r.h = h;
return (mtlb_rt *)CFBridgingRetain(r);
}
}
void mtlb_target_free(mtlb_rt *rt) {
if (rt) CFBridgingRelease(rt);
}
// ---- pass 录制 ----
// ---- Pass recording ----
static MTLRenderPassDescriptor *pass_desc(MTLBRt *r, MTLLoadAction load, MTLClearColor cc) {
MTLRenderPassDescriptor *p = [MTLRenderPassDescriptor renderPassDescriptor];
p.colorAttachments[0].texture = r.tex;
p.colorAttachments[0].loadAction = load;
p.colorAttachments[0].storeAction = MTLStoreActionStore;
p.colorAttachments[0].clearColor = cc;
return p;
}
int mtlb_clear(mtlb_ctx *ctx, mtlb_rt *rt, float r, float g, float b, float a) {
if (!ctx || !rt) return -1;
@autoreleasepool {
MTLRenderPassDescriptor *p =
pass_desc(RT(rt), MTLLoadActionClear, MTLClearColorMake(r, g, b, a));
id<MTLRenderCommandEncoder> e = [frame_cb(CTX(ctx)) renderCommandEncoderWithDescriptor:p];
if (!e) { err("renderCommandEncoder(clear)", nil); return -1; }
[e endEncoding];
return 0;
}
}
static NSString *const kTriMSL =
@"#include <metal_stdlib>\n"
"using namespace metal;\n"
"struct V { float4 pos; float4 col; };\n"
"struct O { float4 pos [[position]]; float4 col; };\n"
"vertex O tri_vs(uint vid [[vertex_id]], constant V *v [[buffer(0)]]) {\n"
" O o; o.pos = v[vid].pos; o.col = v[vid].col; return o;\n"
"}\n"
"fragment float4 tri_fs(O in [[stage_in]]) { return in.col; }\n";
// 与 kTriMSL 中 struct V 布局一致(两个 float4,32 字节)
// Matches the layout of struct V in kTriMSL (two float4, 32 bytes)
typedef struct { float pos[4]; float col[4]; } TriVert;
// 顶点(NDC):上红、左下绿、右下蓝
// Vertices (NDC): top red, bottom-left green, bottom-right blue
static const TriVert kTri[3] = {
{{ 0.0f, 0.5f, 0.0f, 1.0f}, {1, 0, 0, 1}},
{{-0.5f, -0.5f, 0.0f, 1.0f}, {0, 1, 0, 1}},
{{ 0.5f, -0.5f, 0.0f, 1.0f}, {0, 0, 1, 1}},
};
static id<MTLRenderPipelineState> tri_pso(MTLBCtx *c, MTLPixelFormat pf) {
id<MTLRenderPipelineState> pso = c.triPso[@(pf)];
if (pso) return pso;
NSError *e = nil;
if (!c.triLib) {
c.triLib = [c.dev newLibraryWithSource:kTriMSL options:nil error:&e];
if (!c.triLib) { err("newLibraryWithSource", e); return nil; }
}
MTLRenderPipelineDescriptor *d = [MTLRenderPipelineDescriptor new];
d.vertexFunction = [c.triLib newFunctionWithName:@"tri_vs"];
d.fragmentFunction = [c.triLib newFunctionWithName:@"tri_fs"];
d.colorAttachments[0].pixelFormat = pf;
pso = [c.dev newRenderPipelineStateWithDescriptor:d error:&e];
if (!pso) { err("newRenderPipelineState", e); return nil; }
c.triPso[@(pf)] = pso;
return pso;
}
int mtlb_triangle(mtlb_ctx *ctx, mtlb_rt *rt) {
if (!ctx || !rt) return -1;
@autoreleasepool {
MTLBCtx *c = CTX(ctx);
MTLBRt *r = RT(rt);
id<MTLRenderPipelineState> pso = tri_pso(c, r.tex.pixelFormat);
if (!pso) return -1;
MTLRenderPassDescriptor *p = pass_desc(r, MTLLoadActionLoad, MTLClearColorMake(0, 0, 0, 0));
id<MTLRenderCommandEncoder> e = [frame_cb(c) renderCommandEncoderWithDescriptor:p];
if (!e) { err("renderCommandEncoder(triangle)", nil); return -1; }
[e setRenderPipelineState:pso];
[e setVertexBytes:kTri length:sizeof kTri atIndex:0];
[e drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
[e endEncoding];
return 0;
}
}
// ---- 提交与回读 ----
// ---- Commit and readback ----
int mtlb_readback(mtlb_ctx *ctx, mtlb_rt *rt, void *buf, size_t buf_size) {
if (!ctx || !rt || !buf) return -1;
@autoreleasepool {
MTLBCtx *c = CTX(ctx);
MTLBRt *r = RT(rt);
size_t row = (size_t)r.w * 4;
if (buf_size < row * r.h) { err("mtlb_readback 缓冲太小", nil); return -1; }
if (c.frame) {
id<MTLCommandBuffer> cb = c.frame;
c.frame = nil;
[cb commit];
[cb waitUntilCompleted];
if (cb.status != MTLCommandBufferStatusCompleted) { err("commandBuffer 执行", cb.error); return -1; }
}
[r.tex getBytes:buf bytesPerRow:row fromRegion:MTLRegionMake2D(0, 0, r.w, r.h) mipmapLevel:0];
return 0;
}
}
+1
View File
@@ -0,0 +1 @@
p_nocopy
+38
View File
@@ -0,0 +1,38 @@
// 探针:游戏内存上建零拷贝 MTLBuffer(边界外扩到 16 KiB 页、允许重叠),GPU 写 / CPU 读互通。
// Probe: create zero-copy MTLBuffers over game memory (boundaries expanded outward to 16 KiB pages, overlap allowed), with GPU writes / CPU reads visible to each other.
#import <Metal/Metal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
size_t pg = getpagesize();
uint8_t *mem; posix_memalign((void **)&mem, pg, 8 * pg);
memset(mem, 0, 8 * pg);
// 两个「池」:A = [pg+0x1000, 3pg+0x800)、B = [2pg+0x2000, 5pg),都不按页对齐,且外扩后重叠于第 2–3 页
// Two "pools": A = [pg+0x1000, 3pg+0x800), B = [2pg+0x2000, 5pg), neither page-aligned, and after expanding outward they overlap on pages 2–3
uint8_t *a0 = mem + pg + 0x1000, *a1 = mem + 3 * pg + 0x800, *b0 = mem + 2 * pg + 0x2000, *b1 = mem + 5 * pg;
#define DOWN(p) ((uint8_t *)((uintptr_t)(p) & ~(uintptr_t)(pg - 1)))
#define UP(p) ((uint8_t *)(((uintptr_t)(p) + pg - 1) & ~(uintptr_t)(pg - 1)))
id<MTLBuffer> A = [dev newBufferWithBytesNoCopy:DOWN(a0) length:UP(a1) - DOWN(a0) options:MTLResourceStorageModeShared deallocator:nil];
id<MTLBuffer> B = [dev newBufferWithBytesNoCopy:DOWN(b0) length:UP(b1) - DOWN(b0) options:MTLResourceStorageModeShared deallocator:nil];
id<MTLBuffer> bad = [dev newBufferWithBytesNoCopy:a0 length:pg options:MTLResourceStorageModeShared deallocator:nil];
printf("页大小 %zu;A %s B %s;未对齐起点建缓冲 %s\n", pg, A ? "成功" : "失败", B ? "成功" : "失败", bad ? "成功(与预期不符)" : "失败(符合预期)");
// GPU:从 A 的 a0 处拷 4096 字节到 B 的 b0 处(两块的落点都在重叠页之外/之内各一)
// GPU: copy 4096 bytes from a0 in A to b0 in B (of the two blocks' landing points, one is outside and one is inside the overlapping pages)
for (int i = 0; i < 4096; i++) a0[i] = (uint8_t)(i * 7 + 3);
id<MTLCommandQueue> q = [dev newCommandQueue];
id<MTLCommandBuffer> cb = [q commandBuffer];
id<MTLBlitCommandEncoder> bl = [cb blitCommandEncoder];
[bl copyFromBuffer:A sourceOffset:a0 - DOWN(a0) toBuffer:B destinationOffset:b0 - DOWN(b0) size:4096];
// 再在重叠区内:经 B 写、经 A 读——把 B 中 b0+0x1000 起 256 字节填 0xAB
// Then within the overlap region: write through B, read through A - fill 256 bytes of B starting at b0+0x1000 with 0xAB
[bl fillBuffer:B range:NSMakeRange(b0 - DOWN(b0) + 0x1000, 256) value:0xAB];
[bl endEncoding]; [cb commit]; [cb waitUntilCompleted];
int ok1 = !memcmp(a0, b0, 4096), ok2 = 1;
for (int i = 0; i < 256; i++) ok2 &= b0[0x1000 + i] == 0xAB;
uint8_t *viaA = (uint8_t *)A.contents + (b0 + 0x1000 - DOWN(a0));
int ok3 = viaA[0] == 0xAB && viaA[255] == 0xAB;
printf("GPU 拷贝 A→B 4096 B 全等:期望 1 → 真结果 %d\nGPU 填充经 CPU 原指针读到:期望 1 → 真结果 %d\n同一字节经 A 的 contents 读到:期望 1 → 真结果 %d\n", ok1, ok2, ok3);
return !(A && B && !bad && ok1 && ok2 && ok3);
}
+168
View File
@@ -0,0 +1,168 @@
/* test_offscreen.c —— mtl_backend 自测
*
* 期望值全部在本文件里独立算出,不读后端内部数据:
* - 三角形顶点(NDC)在下方 TRI 里手抄一份(与 mtl_backend.m 的 kTri 同值);
* - NDC→像素:px = (x+1)/2*W,py = (1-y)/2*H(Metal 视口原点在左上,回读第 0 行是顶部);
* - 像素中心 (i+0.5, j+0.5) 的颜色 = 三顶点颜色按重心坐标线性插值(w=1,无透视)。
* 每个测试对 BGRA8、RGBA8 两种格式各跑一遍。
* test_offscreen.c - self-test for mtl_backend
* All expected values are computed independently in this file, without reading backend internals:
* - the triangle vertices (NDC) are hand-copied into TRI below (same values as kTri in mtl_backend.m);
* - NDC→pixel: px = (x+1)/2*W, py = (1-y)/2*H (Metal's viewport origin is top-left, readback row 0 is the top);
* - the color at pixel center (i+0.5, j+0.5) = linear interpolation of the three vertex colors by barycentric coordinates (w=1, no perspective).
* Each test is run once for each of the two formats BGRA8 and RGBA8.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mtl_backend.h"
#define W 256
#define H 256
#define TOL 2 /* unorm8 量化与光栅插值精度容差(单通道) | Tolerance for unorm8 quantization and raster interpolation precision (per channel) */
static const float TRI[3][2] = {{0.0f, 0.5f}, {-0.5f, -0.5f}, {0.5f, -0.5f}};
static const float TRI_COL[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
static int fails = 0;
typedef struct { int r, g, b, a; } px_t;
static px_t get_px(const uint8_t *buf, mtlb_fmt fmt, int x, int y) {
const uint8_t *p = buf + ((size_t)y * W + x) * 4;
px_t o;
if (fmt == MTLB_FMT_BGRA8) { o.b = p[0]; o.g = p[1]; o.r = p[2]; o.a = p[3]; }
else { o.r = p[0]; o.g = p[1]; o.b = p[2]; o.a = p[3]; }
return o;
}
static int near(px_t a, px_t b, int tol) {
return abs(a.r - b.r) <= tol && abs(a.g - b.g) <= tol && abs(a.b - b.b) <= tol && abs(a.a - b.a) <= tol;
}
static void report(const char *name, px_t want, px_t got, int ok) {
printf(" %-34s 期望 (%3d,%3d,%3d,%3d) → 真结果 (%3d,%3d,%3d,%3d) %s\n", name,
want.r, want.g, want.b, want.a, got.r, got.g, got.b, got.a, ok ? "过" : "【不符】");
if (!ok) fails++;
}
/* 顶点像素坐标 | Vertex pixel coordinates */
static void vert_px(int i, double *x, double *y) {
*x = (TRI[i][0] + 1.0) * 0.5 * W;
*y = (1.0 - TRI[i][1]) * 0.5 * H;
}
/* 点 (x,y) 到三条边的有符号距离(像素,内侧为正)与重心坐标 | Signed distances from point (x,y) to the three edges (in pixels, positive inside) and barycentric coordinates */
static void bary(double x, double y, double l[3], double dist[3]) {
double vx[3], vy[3];
for (int i = 0; i < 3; i++) vert_px(i, &vx[i], &vy[i]);
double area = (vx[1] - vx[0]) * (vy[2] - vy[0]) - (vy[1] - vy[0]) * (vx[2] - vx[0]);
for (int i = 0; i < 3; i++) {
int a = (i + 1) % 3, b = (i + 2) % 3; /* 顶点 i 的对边 | The edge opposite vertex i */
double e = (vx[b] - vx[a]) * (y - vy[a]) - (vy[b] - vy[a]) * (x - vx[a]);
l[i] = e / area;
dist[i] = e / (area > 0 ? 1 : -1) / hypot(vx[b] - vx[a], vy[b] - vy[a]);
}
}
static px_t tri_expect(int i, int j) {
double l[3], d[3];
bary(i + 0.5, j + 0.5, l, d);
double c[3] = {0, 0, 0};
for (int v = 0; v < 3; v++)
for (int k = 0; k < 3; k++) c[k] += l[v] * TRI_COL[v][k];
px_t o = {(int)lround(c[0] * 255), (int)lround(c[1] * 255), (int)lround(c[2] * 255), 255};
return o;
}
static const char *fmt_name(mtlb_fmt f) { return f == MTLB_FMT_BGRA8 ? "BGRA8" : "RGBA8"; }
static void test_clear(mtlb_ctx *ctx, mtlb_fmt fmt, uint8_t *buf) {
printf("[测试1 清屏纯红 %s %dx%d]\n", fmt_name(fmt), W, H);
mtlb_rt *rt = mtlb_target(ctx, W, H, fmt);
memset(buf, 0x5a, W * H * 4); /* 先填垃圾,防止「没写也判过」 | Fill with garbage first, to prevent "passes even though nothing was written" */
if (!rt || mtlb_clear(ctx, rt, 1, 0, 0, 1) || mtlb_readback(ctx, rt, buf, W * H * 4)) {
printf(" 后端调用失败\n"); fails++; mtlb_target_free(rt); return;
}
px_t want = {255, 0, 0, 255};
int bad = 0; px_t first_bad = {0};
for (int y = 0; y < H; y++)
for (int x = 0; x < W; x++) {
px_t g = get_px(buf, fmt, x, y);
if (!near(g, want, 0)) { if (!bad) first_bad = g; bad++; }
}
printf(" 全部 %d 像素逐个比:期望 (255,0,0,255) 全等 → 真结果 不符 %d 个%s\n", W * H, bad,
bad ? "【不符】" : " 过");
if (bad) { printf(" 首个不符像素 (%d,%d,%d,%d)\n", first_bad.r, first_bad.g, first_bad.b, first_bad.a); fails++; }
mtlb_target_free(rt);
}
static void test_triangle(mtlb_ctx *ctx, mtlb_fmt fmt, uint8_t *buf) {
printf("[测试2 黑底三色三角形 %s %dx%d,清屏+三角形两个 pass 同一帧]\n", fmt_name(fmt), W, H);
mtlb_rt *rt = mtlb_target(ctx, W, H, fmt);
memset(buf, 0x5a, W * H * 4);
if (!rt || mtlb_clear(ctx, rt, 0, 0, 0, 1) || mtlb_triangle(ctx, rt) ||
mtlb_readback(ctx, rt, buf, W * H * 4)) {
printf(" 后端调用失败\n"); fails++; mtlb_target_free(rt); return;
}
px_t clear = {0, 0, 0, 255};
/* 1) 四个角点 = 清屏色 | 1) The four corner points = clear color */
const int corners[4][2] = {{0, 0}, {W - 1, 0}, {0, H - 1}, {W - 1, H - 1}};
for (int k = 0; k < 4; k++) {
char name[64]; snprintf(name, sizeof name, "角点 (%d,%d) 清屏色", corners[k][0], corners[k][1]);
px_t g = get_px(buf, fmt, corners[k][0], corners[k][1]);
report(name, clear, g, near(g, clear, 0));
}
/* 2) 重心:NDC (0,-1/6) → 像素 (128, 149.33),取像素 (128,149),不是清屏色且≈插值值 | 2) Centroid: NDC (0,-1/6) → pixel (128, 149.33); take pixel (128,149), which is not the clear color and ≈ the interpolated value */
{
px_t want = tri_expect(128, 149), g = get_px(buf, fmt, 128, 149);
report("重心 (128,149) 非清屏、≈1/3 混色", want, g, !near(g, clear, 0) && near(g, want, TOL));
}
/* 3) 三顶点附近:顶点像素 v0(128,64) v1(64,192) v2(192,192),各向重心内移若干像素取样 | 3) Near the three vertices: vertex pixels v0(128,64) v1(64,192) v2(192,192), each sampled a few pixels inward toward the centroid */
const struct { int x, y, ch; const char *name; } vs[3] = {
{128, 72, 0, "近上顶点 (128,72) 偏红"},
{72, 188, 1, "近左下顶点 (72,188) 偏绿"},
{183, 188, 2, "近右下顶点 (183,188) 偏蓝"},
};
for (int k = 0; k < 3; k++) {
px_t want = tri_expect(vs[k].x, vs[k].y), g = get_px(buf, fmt, vs[k].x, vs[k].y);
int ch[3] = {g.r, g.g, g.b};
int dom = ch[vs[k].ch] >= 200 && ch[(vs[k].ch + 1) % 3] <= 30 && ch[(vs[k].ch + 2) % 3] <= 30;
report(vs[k].name, want, g, dom && near(g, want, TOL));
}
/* 4) 全图:离边 >1 像素的内侧像素 ≈ 插值值(±TOL),外侧像素 = 清屏色;边带 ±1 像素跳过 | 4) Whole image: interior pixels more than 1 pixel from an edge ≈ interpolated value (±TOL), exterior pixels = clear color; the ±1 pixel edge band is skipped */
int n_in = 0, bad_in = 0, n_out = 0, bad_out = 0, n_edge = 0;
for (int y = 0; y < H; y++)
for (int x = 0; x < W; x++) {
double l[3], d[3];
bary(x + 0.5, y + 0.5, l, d);
double dmin = fmin(d[0], fmin(d[1], d[2]));
px_t g = get_px(buf, fmt, x, y);
if (dmin > 1.0) { n_in++; if (!near(g, tri_expect(x, y), TOL)) bad_in++; }
else if (dmin < -1.0) { n_out++; if (!near(g, clear, 0)) bad_out++; }
else n_edge++;
}
printf(" 全图内侧 %d 像素:期望 ≈插值(±%d) → 真结果 不符 %d 个%s\n", n_in, TOL, bad_in, bad_in ? "【不符】" : " 过");
printf(" 全图外侧 %d 像素:期望 =清屏色 → 真结果 不符 %d 个%s\n", n_out, bad_out, bad_out ? "【不符】" : " 过");
printf(" 边带跳过 %d 像素(合计 %d)\n", n_edge, n_in + n_out + n_edge);
if (bad_in || bad_out) fails++;
mtlb_target_free(rt);
}
int main(void) {
mtlb_ctx *ctx = mtlb_init();
if (!ctx) { printf("mtlb_init 失败\n"); return 1; }
uint8_t *buf = malloc(W * H * 4);
const mtlb_fmt fmts[2] = {MTLB_FMT_BGRA8, MTLB_FMT_RGBA8};
for (int i = 0; i < 2; i++) test_clear(ctx, fmts[i], buf);
for (int i = 0; i < 2; i++) test_triangle(ctx, fmts[i], buf);
free(buf);
mtlb_shutdown(ctx);
printf("%s:不符项 %d\n", fails ? "【失败】" : "全部通过", fails);
return fails ? 1 : 0;
}