Initial public release
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
# dm/gfx/tex — texture format mapping, block-linear deswizzling, BC decompression
|
||||
|
||||
中文:[README.zh-CN.md](README.zh-CN.md)
|
||||
|
||||
The part of the graphics layer that deals with texture data, called by the replay layer `../nvn/nvn_mtl.m`. It does three things:
|
||||
|
||||
1. converts NVN texture format numbers to Metal pixel formats;
|
||||
2. unpacks the Switch's "block-linear" layout into an ordinary row-by-row layout;
|
||||
3. decompresses BC textures on GPUs that do not support BC compressed textures.
|
||||
|
||||
Block linear is how the Tegra X1 GPU stores textures: the data is not one row after another, but interleaved in small blocks of 64 bytes × 8 rows (GOBs), and several GOBs are then stacked into larger blocks according to a "block height" and a "block depth". The game's packaged texture files are in exactly this layout, and it must be undone before uploading to Metal.
|
||||
|
||||
## Files
|
||||
|
||||
| File | Contents |
|
||||
|---|---|
|
||||
| `nvn_fmt_mtl.h`, `nvn_fmt_mtl.c` | `nvn_fmt_to_mtl()`: NVN format (0x01–0x9C) → Metal pixel format + component remapping. Returns 1 for an exact match, 2 for a substitute (precision, bit order or interpretation differs and a conversion is needed), 0 when Metal has no corresponding format. How each format is handled is written in the comments inside the table. Pure C, no dependency on Metal headers |
|
||||
| `nvn_deswizzle.h`, `nvn_deswizzle.c` | `nvn_deswizzle()`: deswizzles one level and one layer from block linear to linear; `nvn_swizzle()`: the reverse, used for round trips in unit tests; `nvn_bl_offset()`: the block-linear address of a single point. Pure C |
|
||||
| `nvn_deswizzle_gpu.h`, `nvn_deswizzle_gpu.m` | A Metal compute shader version of the same deswizzling algorithm, used by the replay layer when uploading packaged textures; when initialization fails or an unsupported format is encountered, the replay layer falls back to the CPU version |
|
||||
| `nvn_bcdec.h`, `nvn_bcdec.c` | `nvn_bc_unpacked()` / `nvn_bc_decode()`: decompress BC textures on the CPU into uncompressed formats; decoding uses `dm/third_party/bcdec` |
|
||||
| `tests/` | Unit tests |
|
||||
|
||||
The offsets of each level and layer within the storage, and the block height and block depth actually used by each level, are all taken from `../nvn/nvn_tex.c` (`nvn_tex_layout`, `nvn_tex_level_offset`, `nvn_tex_level_tiles`); this directory only does addressing and moving within a level. The game's packaged textures carry their own layout parameters, whose byte 0 is the log2 of the level 0 block height; when it is present it takes precedence (the `pkg_block_h` field of `nvn_texdesc`).
|
||||
|
||||
## Devices without BC support
|
||||
|
||||
Some older Apple GPUs do not support BC compressed textures (determined by `supportsBCTextureCompression` of `MTLDevice`). On these devices:
|
||||
|
||||
- the game's textures can be converted to ASTC format offline in advance with an optional supplementary pack (`dm/tools/astc_pack.py`; for dependencies see the "Optional" section of `docs/DEPENDENCIES.md`);
|
||||
- the remaining BC textures are created by the replay layer in their decompressed format and decompressed at upload; decompression on the CPU goes through `nvn_bcdec.c` in this directory.
|
||||
|
||||
The environment variable `DM_TEST_NO_BC=1` forces this path on any machine.
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
make -C dm/gfx/tex/tests samples # fetch real-data samples (see below)
|
||||
make -C dm/gfx/tex/tests run # run t_fmt_mtl and t_tex
|
||||
```
|
||||
|
||||
- **`t_fmt_mtl`**: takes the mapping for every NVN format in 0x01–0x9C and, for every one whose mapping is not 0, actually creates a texture on the local Metal device; all of them must be created successfully. It also checks that every NVN format with sRGB in its name lands on a Metal sRGB format. No game files needed.
|
||||
- **`t_tex`**: the deswizzling tests, in several groups:
|
||||
|
||||
| Group | Criterion |
|
||||
|---|---|
|
||||
| A round trip | Writes random data into each level and layer and reads it back out; must be byte-for-byte equal. Covers 2D, 2D array and 3D, several bytes-per-block values and non-power-of-two sizes |
|
||||
| B address formula | The result of `nvn_bl_offset()` equals the address computed by hand from the public layout rules |
|
||||
| E hand-made 3D | Places markers at hand-computed addresses, checks where they land after deswizzling, and checks block height, block depth and storage size |
|
||||
| C real data | The Switch version (block linear) of a texture, after deswizzling, is compared with the PC version (linear) of the same texture: those at the same resolution must be byte-for-byte equal; those whose Switch version was reduced in resolution were recompressed, so the comparison is instead that the PSNR after decoding (peak signal-to-noise ratio, a measure of how alike two images are) is not below 22 dB. It also checks that the per-level offsets in the file agree with `nvn_tex_level_offset` |
|
||||
| D negative control | Deliberately deswizzles with the block height off by one step; the result must no longer be byte-for-byte equal and the PSNR must be below 22 dB, proving that the criterion of group C can tell a wrong layout apart |
|
||||
|
||||
The A round trip can only prove "one-to-one and within bounds"; it cannot prove that the layout formula is right. What really backs it up is the hand-computed addresses of group B and the byte-for-byte equality of the same-resolution samples of group C.
|
||||
|
||||
**About the real-data samples**: groups C and D need one copy each of the Switch version and the PC version of the same texture. `tests/fetch_samples.py` takes samples from the game files in your workspace: the Switch version is read from `$DM_ROOT/data/switch/3.3.94012/Update/RomFS/data`, the PC version from `$DM_ROOT/data/assets-src/raw`, and the output goes to `$DM_ROOT/build/cache/dm/tex_samples`. When there are no samples, the real-data items of `t_tex` count as failed and are not skipped; groups A, B and E need no game files. The samples do not go into the repository.
|
||||
|
||||
## Layout-related fields in the texture file header
|
||||
|
||||
Facts used by `t_tex.c` when parsing the game's `.texture` files:
|
||||
|
||||
- The file begins with `<DE(`; the Switch version and the PC version use the same container.
|
||||
- In files that went through the Switch conversion, the four bytes starting at offset 0x14 are `00 00 00 07` (0 in the PC version), which indicates that the pixel area is in block-linear layout; offset 0x13 is the log2 of the level 0 block height, with the same meaning as byte 0 of the layout parameters the game passes to `SetPackagedTextureLayout` at run time.
|
||||
- Files without this marker are stored linearly and are byte-for-byte identical to the PC version.
|
||||
|
||||
## Limitations
|
||||
|
||||
- `nvn_deswizzle()` does not support multisampled textures, textures with the LINEAR flag (which are linear to begin with) or the BUFFER target; it returns -1 when it encounters them.
|
||||
- Cubes and cube arrays are handled as layered textures and have not been separately checked with real data.
|
||||
- 3D textures have only the round-trip and hand-computed address checks; there are no real-data samples.
|
||||
- The component bit order of the 16-bit packed formats (565 / 5551 / 4444) is mapped according to the format names and has not been checked with real data; they are marked as "substitute" in the format table.
|
||||
- The real-data sample set is small, covering the four formats RGBA8, BC1, BC3 and BC4.
|
||||
@@ -0,0 +1,70 @@
|
||||
# dm/gfx/tex — 贴图格式映射、块线性解排布、BC 解压
|
||||
|
||||
English: [README.md](README.md)
|
||||
|
||||
图形层里和贴图数据打交道的部分,供回放层 `../nvn/nvn_mtl.m` 调用。做三件事:
|
||||
|
||||
1. 把 NVN 的贴图格式号换成 Metal 的像素格式;
|
||||
2. 把 Switch 的「块线性」排布解成普通的逐行排布;
|
||||
3. 在不支持 BC 压缩贴图的显卡上把 BC 贴图解压。
|
||||
|
||||
块线性(block linear)是 Tegra X1 显卡存贴图的方式:数据不是一行接一行,而是按 64 字节 × 8 行的小块(GOB)交错排列,再按「块高」「块深」把若干 GOB 叠成更大的块。游戏打包好的贴图文件里就是这种排布,上传给 Metal 之前必须先解开。
|
||||
|
||||
## 文件
|
||||
|
||||
| 文件 | 内容 |
|
||||
|---|---|
|
||||
| `nvn_fmt_mtl.h`、`nvn_fmt_mtl.c` | `nvn_fmt_to_mtl()`:NVN 格式(0x01–0x9C)→ Metal 像素格式 + 分量重映射。返回 1 表示精确对应,2 表示替代(精度、位序或读法不同,需要转换),0 表示 Metal 没有对应格式。每个格式的处理办法写在表内注释里。纯 C,不依赖 Metal 头文件 |
|
||||
| `nvn_deswizzle.h`、`nvn_deswizzle.c` | `nvn_deswizzle()`:把某一级、某一层从块线性解到线性;`nvn_swizzle()`:反向,单测往返用;`nvn_bl_offset()`:单点的块线性地址。纯 C |
|
||||
| `nvn_deswizzle_gpu.h`、`nvn_deswizzle_gpu.m` | 同一个解排布算法的 Metal 计算着色器版本,回放层上传打包贴图时用;初始化失败或遇到不支持的格式时回放层退回 CPU 版 |
|
||||
| `nvn_bcdec.h`、`nvn_bcdec.c` | `nvn_bc_unpacked()` / `nvn_bc_decode()`:BC 贴图在 CPU 上解压成不压缩格式,解码用 `dm/third_party/bcdec` |
|
||||
| `tests/` | 单元测试 |
|
||||
|
||||
各级、各层在存储里的偏移,以及每一级实际使用的块高、块深,一律取自 `../nvn/nvn_tex.c`(`nvn_tex_layout`、`nvn_tex_level_offset`、`nvn_tex_level_tiles`),这里只做级内的寻址与搬运。游戏的打包贴图自带布局参数,其第 0 字节是第 0 级块高的 log2,有它时以它为准(`nvn_texdesc` 的 `pkg_block_h` 字段)。
|
||||
|
||||
## 不支持 BC 的设备
|
||||
|
||||
一部分较老的苹果显卡不支持 BC 压缩贴图(由 `MTLDevice` 的 `supportsBCTextureCompression` 判断)。在这些设备上:
|
||||
|
||||
- 游戏贴图可以用可选的补充包事先离线换成 ASTC 格式(`dm/tools/astc_pack.py`,依赖见 `docs/DEPENDENCIES.zh-CN.md` 的「可选」一节);
|
||||
- 剩下的 BC 贴图由回放层建成解压后的格式,上传时解压,CPU 上的解压走本目录的 `nvn_bcdec.c`。
|
||||
|
||||
环境变量 `DM_TEST_NO_BC=1` 可以在任何机器上强制走这条路径。
|
||||
|
||||
## 测试
|
||||
|
||||
```sh
|
||||
make -C dm/gfx/tex/tests samples # 取真数据样本(见下)
|
||||
make -C dm/gfx/tex/tests run # 跑 t_fmt_mtl 与 t_tex
|
||||
```
|
||||
|
||||
- **`t_fmt_mtl`**:对 0x01–0x9C 每个 NVN 格式取映射,凡映射不为 0 的,都在本机的 Metal 设备上真建一张贴图,必须全部建成;另核名字带 sRGB 的 NVN 格式都落到 Metal 的 sRGB 格式。不需要游戏文件。
|
||||
- **`t_tex`**:解排布的测试,分几组:
|
||||
|
||||
| 组 | 判据 |
|
||||
|---|---|
|
||||
| A 往返 | 往各级、各层写入随机数据再解出,逐字节相等。覆盖 2D、2D 数组、3D,多种每块字节数与非 2 的幂尺寸 |
|
||||
| B 地址公式 | `nvn_bl_offset()` 的结果与按公开排布规则手算的地址相等 |
|
||||
| E 手工 3D | 在手算地址放标记,解排布后核对落点,并核块高、块深与存储尺寸 |
|
||||
| C 真数据 | 同一张贴图的 Switch 版(块线性)解排布后与 PC 版(线性)比:同分辨率的逐字节相等;Switch 版降了分辨率的是重新压缩过的,改比解码后的 PSNR(峰值信噪比,衡量两张图有多像)不低于 22 dB。同时核文件里的逐级偏移与 `nvn_tex_level_offset` 一致 |
|
||||
| D 负对照 | 故意把块高错一级再解,结果必须不再逐字节相等、PSNR 低于 22 dB,证明 C 组的判据能分辨错误的排布 |
|
||||
|
||||
A 往返只能证明「一一对应、不越界」,证明不了排布公式是对的;真正兜底的是 B 组的手算地址与 C 组同分辨率样本的逐字节相等。
|
||||
|
||||
**关于真数据样本**:C、D 两组需要同一张贴图的 Switch 版与 PC 版各一份。`tests/fetch_samples.py` 从你工作区里的游戏文件取样,Switch 版读 `$DM_ROOT/data/switch/3.3.94012/Update/RomFS/data`,PC 版读 `$DM_ROOT/data/assets-src/raw`,输出到 `$DM_ROOT/build/cache/dm/tex_samples`。没有样本时 `t_tex` 的真数据项算失败,不会跳过;A、B、E 三组不需要游戏文件。样本不进仓库。
|
||||
|
||||
## 贴图文件头里与排布有关的字段
|
||||
|
||||
`t_tex.c` 解析游戏的 `.texture` 文件时用到的事实:
|
||||
|
||||
- 文件以 `<DE(` 开头,Switch 版与 PC 版是同一种容器。
|
||||
- 经过 Switch 转换的文件,偏移 0x14 起的四个字节是 `00 00 00 07`(PC 版为 0),表示像素区是块线性排布;偏移 0x13 是第 0 级块高的 log2,与游戏运行时传给 `SetPackagedTextureLayout` 的布局参数第 0 字节含义相同。
|
||||
- 没有这个标记的文件是线性存放的,与 PC 版逐字节相同。
|
||||
|
||||
## 局限
|
||||
|
||||
- `nvn_deswizzle()` 不支持多重采样贴图、带 LINEAR 标志的贴图(本来就是线性的)和 BUFFER 目标,遇到返回 -1。
|
||||
- 立方体与立方体数组按分层贴图处理,没有单独用真数据核对。
|
||||
- 3D 贴图只有往返与手算地址的核对,没有真数据样本。
|
||||
- 16 位打包格式(565 / 5551 / 4444)的分量位序是按格式名对应的,没有用真数据核过,在格式表里标为「替代」。
|
||||
- 真数据样本集小,覆盖 RGBA8、BC1、BC3、BC4 四种格式。
|
||||
@@ -0,0 +1,58 @@
|
||||
// 见 nvn_bcdec.h。解码用 bcdec(dm/third_party/bcdec,单头文件,MIT / 公有领域)。
|
||||
// See nvn_bcdec.h. Decoding uses bcdec (dm/third_party/bcdec, single header, MIT / public domain).
|
||||
#define BCDEC_IMPLEMENTATION
|
||||
#define BCDEC_BC4BC5_PRECISE // BC4 / BC5 带有符号版本的接口 | interface with signed variants of BC4 / BC5
|
||||
#include "../../third_party/bcdec/bcdec.h"
|
||||
#include "nvn_bcdec.h"
|
||||
#include <string.h>
|
||||
|
||||
enum { R8Unorm = 10, R8Snorm = 12, RG8Unorm = 30, RG8Snorm = 32, RGBA8Unorm = 70, RGBA8Unorm_sRGB = 71, RGBA16Float = 115 };
|
||||
// NVN:0x41 RGB_DXT1、0x42 RGBA_DXT1、0x43 DXT3、0x44 DXT5、0x45–0x48 同上 sRGB、0x49 / 0x4a BC4 无 / 有符号、0x4b / 0x4c BC5、0x4d / 0x4e BC7(sRGB)、0x4f / 0x50 BC6H 有 / 无符号
|
||||
// NVN: 0x41 RGB_DXT1, 0x42 RGBA_DXT1, 0x43 DXT3, 0x44 DXT5, 0x45–0x48 the same in sRGB, 0x49 / 0x4a BC4 unsigned / signed, 0x4b / 0x4c BC5, 0x4d / 0x4e BC7 (sRGB), 0x4f / 0x50 BC6H signed / unsigned
|
||||
int nvn_bc_unpacked(uint32_t f, uint32_t *pf, int *bpp) {
|
||||
switch (f) {
|
||||
case 0x41: case 0x42: case 0x43: case 0x44: case 0x4d: *pf = RGBA8Unorm; *bpp = 4; return 1;
|
||||
case 0x45: case 0x46: case 0x47: case 0x48: case 0x4e: *pf = RGBA8Unorm_sRGB; *bpp = 4; return 1;
|
||||
case 0x49: *pf = R8Unorm; *bpp = 1; return 1;
|
||||
case 0x4a: *pf = R8Snorm; *bpp = 1; return 1;
|
||||
case 0x4b: *pf = RG8Unorm; *bpp = 2; return 1;
|
||||
case 0x4c: *pf = RG8Snorm; *bpp = 2; return 1;
|
||||
case 0x4f: case 0x50: *pf = RGBA16Float; *bpp = 8; return 1;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static void block(uint32_t f, const uint8_t *b, uint8_t *o, int op) { // 一块 → 4×4 像素(o 每行 op 字节) | one block → 4×4 pixels (o has op bytes per row)
|
||||
switch (f) {
|
||||
case 0x41: case 0x42: case 0x45: case 0x46: bcdec_bc1(b, o, op); break;
|
||||
case 0x43: case 0x47: bcdec_bc2(b, o, op); break;
|
||||
case 0x44: case 0x48: bcdec_bc3(b, o, op); break;
|
||||
case 0x49: bcdec_bc4(b, o, op, 0); break;
|
||||
case 0x4a: bcdec_bc4(b, o, op, 1); break;
|
||||
case 0x4b: bcdec_bc5(b, o, op, 0); break;
|
||||
case 0x4c: bcdec_bc5(b, o, op, 1); break;
|
||||
case 0x4d: case 0x4e: bcdec_bc7(b, o, op); break;
|
||||
case 0x4f: case 0x50: { // bcdec 出 RGB 半精度,补 alpha = 1.0 | bcdec outputs RGB half-float; add alpha = 1.0
|
||||
uint16_t rgb[16 * 3]; bcdec_bc6h_half(b, rgb, 4 * 3, f == 0x4f);
|
||||
for (int y = 0; y < 4; y++) for (int x = 0; x < 4; x++) {
|
||||
uint16_t *d = (uint16_t *)(o + y * op) + x * 4; const uint16_t *s = rgb + (y * 4 + x) * 3;
|
||||
d[0] = s[0]; d[1] = s[1]; d[2] = s[2]; d[3] = 0x3c00;
|
||||
}
|
||||
break; }
|
||||
}
|
||||
}
|
||||
|
||||
int nvn_bc_decode(uint32_t f, const uint8_t *src, size_t pitch, uint32_t w, uint32_t h, uint8_t *dst, size_t dpitch) {
|
||||
uint32_t pf; int bpp; if (!nvn_bc_unpacked(f, &pf, &bpp)) return -1;
|
||||
int bb = (f == 0x41 || f == 0x42 || f == 0x45 || f == 0x46 || f == 0x49 || f == 0x4a) ? 8 : 16; // 每块字节 | bytes per block
|
||||
uint8_t tmp[4 * 4 * 8];
|
||||
for (uint32_t by = 0; by * 4 < h; by++) for (uint32_t bx = 0; bx * 4 < w; bx++) {
|
||||
const uint8_t *b = src + by * pitch + bx * bb;
|
||||
uint32_t cw = w - bx * 4 < 4 ? w - bx * 4 : 4, ch = h - by * 4 < 4 ? h - by * 4 : 4;
|
||||
uint8_t *o = dst + (size_t)by * 4 * dpitch + (size_t)bx * 4 * bpp;
|
||||
if (cw == 4 && ch == 4) { block(f, b, o, (int)dpitch); continue; }
|
||||
block(f, b, tmp, 4 * bpp); // 边上不满 4×4 的块:先解到临时块再拷需要的部分 | blocks at the edge that are not a full 4×4: decode into a temporary block first, then copy the needed part
|
||||
for (uint32_t y = 0; y < ch; y++) memcpy(o + y * dpitch, tmp + y * 4 * bpp, cw * bpp);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// 不支持 BC 压缩格式的显卡(A15 / A16 等,苹果 GPU 族 Apple8 及以下):BC 贴图在 CPU 上解压成不压缩格式。
|
||||
// 游戏贴图里的 BC3 由老机型补充包离线换成 ASTC(dm/tools/astc_pack.py);剩下的 BC(精灵图里的 BC3、少量 BC1 / BC4 / BC5 / BC6H)走这里。
|
||||
// GPUs without BC compressed format support (A15 / A16 etc., Apple GPU family Apple8 and below): BC textures are decompressed on the CPU into uncompressed formats.
|
||||
// BC3 in game textures is converted offline to ASTC by the Legacy Device Pack (dm/tools/astc_pack.py); the remaining BC (BC3 in sprites, a few BC1 / BC4 / BC5 / BC6H) goes through here.
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
// NVN 格式是 BC → 返回 1,*mtl_pf = 解压后的 Metal 像素格式、*bpp = 解压后每像素字节;不是 BC 返回 0
|
||||
// NVN format is BC → returns 1, *mtl_pf = Metal pixel format after decompression, *bpp = bytes per pixel after decompression; returns 0 if not BC
|
||||
int nvn_bc_unpacked(uint32_t nvn_fmt, uint32_t *mtl_pf, int *bpp);
|
||||
// 解一片 w×h 像素:src 按块行排(每块行 pitch 字节),dst 每像素行 dpitch 字节。成功 0
|
||||
// Decode a w×h pixel region: src is laid out by block rows (pitch bytes per block row), dst has dpitch bytes per pixel row. Returns 0 on success
|
||||
int nvn_bc_decode(uint32_t nvn_fmt, const uint8_t *src, size_t pitch, uint32_t w, uint32_t h, uint8_t *dst, size_t dpitch);
|
||||
@@ -0,0 +1,71 @@
|
||||
// Tegra X1 块线性排布(公开描述见 deko3d / Ryujinx BlockLinearLayout):
|
||||
// GOB = 64 字节 × 8 行 = 512 字节;GOB 内 (x 字节, y 行) 的偏移 =
|
||||
// (x%64/32)·256 + (y%8/2)·64 + (x%32/16)·32 + (y%2)·16 + x%16
|
||||
// 块 = 1 个 GOB 宽 × 2^tileH 个 GOB 高 × 2^tileD 个 GOB 深,块内先排 y 再排 z;块按 x → y → z 行优先铺满本级。
|
||||
// 级 / 层起点与本级实际块高块深取自 nvn_tex.c,这里只做级内寻址与搬运。
|
||||
// Tegra X1 block-linear layout (public descriptions: deko3d / Ryujinx BlockLinearLayout):
|
||||
// GOB = 64 bytes × 8 rows = 512 bytes; offset of (x byte, y row) within a GOB =
|
||||
// (x%64/32)·256 + (y%8/2)·64 + (x%32/16)·32 + (y%2)·16 + x%16
|
||||
// block = 1 GOB wide × 2^tileH GOBs high × 2^tileD GOBs deep, ordered y first then z within a block; blocks fill the level in x → y → z row-major order.
|
||||
// Level / layer start offsets and the actual block height and block depth of this level come from nvn_tex.c; here we only do intra-level addressing and copying.
|
||||
#include "nvn_deswizzle.h"
|
||||
#include <string.h>
|
||||
|
||||
static uint32_t gob_off(uint32_t x, uint32_t y) {
|
||||
return (x % 64 / 32) * 256 + (y % 8 / 2) * 64 + (x % 32 / 16) * 32 + (y % 2) * 16 + x % 16;
|
||||
}
|
||||
|
||||
uint64_t nvn_bl_offset(uint32_t x, uint32_t y, uint32_t z, uint32_t row_bytes, uint32_t rows, unsigned th, unsigned td) {
|
||||
uint32_t bh = 1u << th, bd = 1u << td;
|
||||
uint64_t gobs_x = (row_bytes + 63) / 64, blocks_y = (rows + 8 * bh - 1) / (8 * bh);
|
||||
uint64_t block = 512ull * bh * bd; // 一个块的字节 | bytes in one block
|
||||
return (z / bd) * gobs_x * blocks_y * block // 第几层块(深度方向) | which block layer (along depth)
|
||||
+ (y / (8 * bh)) * gobs_x * block // 第几行块 | which block row
|
||||
+ (x / 64) * block // 第几列块 | which block column
|
||||
+ ((z % bd) * bh + (y % (8 * bh)) / 8) * 512ull // 块内第几个 GOB | which GOB within the block
|
||||
+ gob_off(x, y);
|
||||
}
|
||||
|
||||
static uint32_t mip(uint32_t s, unsigned l) { s >>= l; return s ? s : 1; }
|
||||
|
||||
// 本级几何:块宽字节数、块行数、切片数,以及本级本层在存储里的起点;不支持的贴图返回 -1
|
||||
// Geometry of this level: width-in-blocks byte count, block row count, slice count, and where this level and layer starts in storage; returns -1 for unsupported textures
|
||||
int nvn_deswizzle_geom(const nvn_texdesc *d, unsigned level, unsigned layer,
|
||||
uint32_t *row_bytes, uint32_t *rows, uint32_t *slices, uint64_t *base, unsigned *th, unsigned *td, uint32_t *bpb) {
|
||||
if (d->target == 5 || d->target == 6 || d->target == 10 || (d->flags & 0x10) || d->samples > 1) return -1; // MS / BUFFER / LINEAR
|
||||
int bw, bh; *bpb = (uint32_t)nvn_fmt_bpb(d->format, &bw, &bh);
|
||||
if (!*bpb || level >= (d->levels ? d->levels : 1)) return -1;
|
||||
nvn_texlayout L; nvn_tex_layout(d, &L);
|
||||
if (layer >= L.layers) return -1;
|
||||
int one_d = d->target == 0 || d->target == 3;
|
||||
uint32_t w = mip(d->width, level), h = one_d ? 1 : mip(d->height, level);
|
||||
*slices = d->target == 2 ? mip(d->depth ? d->depth : 1, level) : 1;
|
||||
*row_bytes = (w + bw - 1) / bw * *bpb; *rows = (h + bh - 1) / bh;
|
||||
*base = (uint64_t)layer * L.layer_size + nvn_tex_level_offset(d, level);
|
||||
nvn_tex_level_tiles(d, level, th, td);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int move(const nvn_texdesc *d, unsigned level, unsigned layer, uint8_t *bl, uint8_t *lin, size_t pitch, int to_linear) {
|
||||
uint32_t row_bytes, rows, slices, bpb; uint64_t base; unsigned th, td;
|
||||
if (nvn_deswizzle_geom(d, level, layer, &row_bytes, &rows, &slices, &base, &th, &td, &bpb)) return -1;
|
||||
if (pitch < row_bytes) return -1;
|
||||
bl += base;
|
||||
for (uint32_t z = 0; z < slices; z++)
|
||||
for (uint32_t y = 0; y < rows; y++) {
|
||||
uint8_t *row = lin + ((size_t)z * rows + y) * pitch;
|
||||
for (uint32_t x = 0; x < row_bytes; x += 16) { // 16 字节一段:GOB 内 16 字节连续,且整除所有块宽 | 16-byte segments: 16 bytes are contiguous within a GOB, and 16 divides all block widths
|
||||
uint32_t n = row_bytes - x < 16 ? row_bytes - x : 16;
|
||||
uint8_t *p = bl + nvn_bl_offset(x, y, z, row_bytes, rows, th, td);
|
||||
if (to_linear) memcpy(row + x, p, n); else memcpy(p, row + x, n);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int nvn_deswizzle(const nvn_texdesc *d, unsigned level, unsigned layer, const void *src, void *dst, size_t dst_pitch) {
|
||||
return move(d, level, layer, (uint8_t *)src, (uint8_t *)dst, dst_pitch, 1);
|
||||
}
|
||||
int nvn_swizzle(const nvn_texdesc *d, unsigned level, unsigned layer, const void *src, size_t src_pitch, void *dst) {
|
||||
return move(d, level, layer, (uint8_t *)dst, (uint8_t *)src, src_pitch, 0);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Tegra 块线性 ↔ 线性。级 / 层偏移与逐级块高块深一律取 nvn/nvn_tex.c(nvn_tex_level_offset / nvn_tex_layout / nvn_tex_level_tiles)。
|
||||
// Tegra block-linear ↔ linear. Level / layer offsets and per-level block height and block depth always come from nvn/nvn_tex.c (nvn_tex_level_offset / nvn_tex_layout / nvn_tex_level_tiles).
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include "../nvn/nvn_tex.h"
|
||||
|
||||
// 把第 level 级、第 layer 层(数组 / 立方体的层;非分层贴图取 0)从整张贴图存储 src_storage 解到线性 dst_linear。
|
||||
// dst 按块行排:每行 dst_pitch 字节(≥ 本级块宽 × 每块字节),压缩格式一行 = 一行块。
|
||||
// 3D 贴图:一次解出本级全部深度切片,切片 k 位于 dst_linear + k × dst_pitch × 本级块行数。
|
||||
// 不支持:多重采样、LINEAR 标志(本就线性)、BUFFER;遇到返回 -1,成功返回 0。
|
||||
// Decode level number level, layer number layer (layer of an array / cube; 0 for non-layered textures) from the whole-texture storage src_storage into linear dst_linear.
|
||||
// dst is laid out by block rows: dst_pitch bytes per row (≥ width in blocks of this level × bytes per block); for compressed formats one row = one row of blocks.
|
||||
// 3D textures: all depth slices of this level are decoded at once; slice k is at dst_linear + k × dst_pitch × block row count of this level.
|
||||
// Not supported: multisampling, the LINEAR flag (already linear), BUFFER; returns -1 on these, 0 on success.
|
||||
int nvn_deswizzle(const nvn_texdesc *d, unsigned level, unsigned layer, const void *src_storage, void *dst_linear, size_t dst_pitch);
|
||||
// 反向(单测往返用):线性 src_linear → 写进整张贴图存储 dst_storage 的对应级 / 层
|
||||
// Reverse (for unit test round trips): linear src_linear → written into the corresponding level / layer of the whole-texture storage dst_storage
|
||||
int nvn_swizzle(const nvn_texdesc *d, unsigned level, unsigned layer, const void *src_linear, size_t src_pitch, void *dst_storage);
|
||||
// 单点地址:本级本层内,线性 (x 字节, y 块行, z 切片) → 相对本级本层起点的块线性字节偏移(单测按手算核)
|
||||
// Single-point address: within this level and layer, linear (x byte, y block row, z slice) → block-linear byte offset relative to the start of this level and layer (unit tests verify against hand calculation)
|
||||
uint64_t nvn_bl_offset(uint32_t x, uint32_t y, uint32_t z, uint32_t row_bytes, uint32_t rows, unsigned tileH, unsigned tileD);
|
||||
|
||||
int nvn_deswizzle_geom(const nvn_texdesc *d, unsigned level, unsigned layer,
|
||||
uint32_t *row_bytes, uint32_t *rows, uint32_t *slices,
|
||||
uint64_t *base, unsigned *tileH, unsigned *tileD, uint32_t *bpb);
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#import <Metal/Metal.h>
|
||||
#include "nvn_deswizzle.h"
|
||||
|
||||
int nvn_deswz_gpu_init(id<MTLDevice> dev);
|
||||
int nvn_deswz_gpu_encode(id<MTLComputeCommandEncoder> enc, id<MTLBuffer> src, uint64_t src_off,
|
||||
const nvn_texdesc *d, unsigned level, unsigned layer,
|
||||
id<MTLBuffer> dst, uint64_t dst_off, size_t dst_pitch);
|
||||
int nvn_deswz_gpu_encode_m4(id<MTL4ComputeCommandEncoder> enc, id<MTL4ArgumentTable> table,
|
||||
id<MTLBuffer> params, size_t params_off, id<MTLBuffer> src, uint64_t src_off,
|
||||
const nvn_texdesc *d, unsigned level, unsigned layer,
|
||||
id<MTLBuffer> dst, uint64_t dst_off, size_t dst_pitch);
|
||||
@@ -0,0 +1,73 @@
|
||||
#import "nvn_deswizzle_gpu.h"
|
||||
|
||||
static id<MTLComputePipelineState> g_nvn_deswz_pipeline;
|
||||
|
||||
static const char *const k_nvn_deswz_msl =
|
||||
"#include <metal_stdlib>\n"
|
||||
"using namespace metal;\n"
|
||||
"struct P { ulong src_off, dst_off, base, pitch; uint row_bytes, rows, slices, th, td; };\n"
|
||||
"kernel void deswz(device const uchar *src [[buffer(0)]], device uchar *dst [[buffer(1)]], constant P& p [[buffer(2)]], uint3 id [[thread_position_in_grid]]) {\n"
|
||||
" uint bh = 1u << p.th, bd = 1u << p.td, gobs_x = (p.row_bytes + 63u) >> 6, blocks_y = (p.rows + (8u * bh) - 1u) >> (3u + p.th);\n"
|
||||
" uint tid = id.x & 31u, gob_x = id.x >> 5, gob_y = id.y, z = id.z; uint xseg = ((tid >> 4) << 1) | ((tid >> 1) & 1u), y = (gob_y << 3) | (((tid >> 2) & 3u) << 1) | (tid & 1u), x = (gob_x << 6) | (xseg << 4);\n"
|
||||
" if (x >= p.row_bytes || y >= p.rows || z >= p.slices) return;\n"
|
||||
" uint n = min(16u, p.row_bytes - x); ulong block = 512ul * bh * bd; ulong gob_in_block = ((ulong)(z & (bd - 1u)) << p.th) + (gob_y & (bh - 1u)); ulong so = p.src_off + p.base + ((ulong)(z >> p.td) * gobs_x * blocks_y + (gob_y >> p.th) * gobs_x + gob_x) * block + gob_in_block * 512ul + (ulong)tid * 16ul; ulong doff = p.dst_off + ((ulong)z * p.rows + y) * p.pitch + x;\n"
|
||||
" if (n == 16u && ((so | doff) & 15ul) == 0ul) *(device uint4 *)(dst + doff) = *(device const uint4 *)(src + so);\n"
|
||||
" else for (uint i = 0; i < n; i++) dst[doff + i] = src[so + i];\n"
|
||||
"}\n";
|
||||
|
||||
int nvn_deswz_gpu_init(id<MTLDevice> dev) {
|
||||
if (g_nvn_deswz_pipeline) return 0;
|
||||
if (!dev) return -1;
|
||||
NSError *error = nil;
|
||||
id<MTLLibrary> library = [dev newLibraryWithSource:@(k_nvn_deswz_msl) options:nil error:&error];
|
||||
if (!library) return -1;
|
||||
id<MTLFunction> function = [library newFunctionWithName:@"deswz"];
|
||||
if (!function) return -1;
|
||||
g_nvn_deswz_pipeline = [dev newComputePipelineStateWithFunction:function error:&error];
|
||||
return g_nvn_deswz_pipeline ? 0 : -1;
|
||||
}
|
||||
|
||||
int nvn_deswz_gpu_encode(id<MTLComputeCommandEncoder> enc, id<MTLBuffer> src, uint64_t src_off,
|
||||
const nvn_texdesc *d, unsigned level, unsigned layer,
|
||||
id<MTLBuffer> dst, uint64_t dst_off, size_t dst_pitch) {
|
||||
if (!g_nvn_deswz_pipeline || !enc || !src || !dst || !d) return -1;
|
||||
uint32_t row_bytes, rows, slices, bpb;
|
||||
uint64_t base;
|
||||
unsigned th, td;
|
||||
if (nvn_deswizzle_geom(d, level, layer, &row_bytes, &rows, &slices, &base, &th, &td, &bpb) || dst_pitch < row_bytes) return -1;
|
||||
struct { uint64_t src_off, dst_off, base, pitch; uint32_t row_bytes, rows, slices, th, td; } p = {
|
||||
src_off, dst_off, base, dst_pitch, row_bytes, rows, slices, th, td
|
||||
};
|
||||
[enc setComputePipelineState:g_nvn_deswz_pipeline];
|
||||
[enc setBuffer:src offset:0 atIndex:0];
|
||||
[enc setBuffer:dst offset:0 atIndex:1];
|
||||
[enc setBytes:&p length:sizeof p atIndex:2];
|
||||
NSUInteger gobs_x = (row_bytes + 63u) >> 6;
|
||||
NSUInteger gobs_y = (rows + 7u) >> 3;
|
||||
[enc dispatchThreadgroups:MTLSizeMake(gobs_x, gobs_y, slices) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)];
|
||||
return 0;
|
||||
}
|
||||
|
||||
int nvn_deswz_gpu_encode_m4(id<MTL4ComputeCommandEncoder> enc, id<MTL4ArgumentTable> table,
|
||||
id<MTLBuffer> params, size_t params_off, id<MTLBuffer> src, uint64_t src_off,
|
||||
const nvn_texdesc *d, unsigned level, unsigned layer,
|
||||
id<MTLBuffer> dst, uint64_t dst_off, size_t dst_pitch) {
|
||||
if (!g_nvn_deswz_pipeline || !enc || !table || !params || !src || !dst || !d) return -1;
|
||||
uint32_t row_bytes, rows, slices, bpb;
|
||||
uint64_t base;
|
||||
unsigned th, td;
|
||||
if (nvn_deswizzle_geom(d, level, layer, &row_bytes, &rows, &slices, &base, &th, &td, &bpb) || dst_pitch < row_bytes) return -1;
|
||||
struct { uint64_t src_off, dst_off, base, pitch; uint32_t row_bytes, rows, slices, th, td; } p = {
|
||||
src_off, dst_off, base, dst_pitch, row_bytes, rows, slices, th, td
|
||||
};
|
||||
memcpy((uint8_t *)params.contents + params_off, &p, sizeof p);
|
||||
[enc setArgumentTable:table];
|
||||
[enc setComputePipelineState:g_nvn_deswz_pipeline];
|
||||
[table setAddress:src.gpuAddress atIndex:0];
|
||||
[table setAddress:dst.gpuAddress atIndex:1];
|
||||
[table setAddress:params.gpuAddress + params_off atIndex:2];
|
||||
NSUInteger gobs_x = (row_bytes + 63u) >> 6;
|
||||
NSUInteger gobs_y = (rows + 7u) >> 3;
|
||||
[enc dispatchThreadgroups:MTLSizeMake(gobs_x, gobs_y, slices) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)];
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// NVNformat(nvn.h 0x01–0x9C)→ Metal。表按 NVN 枚举顺序逐项写,未列的格式(含 0、越界)返回 0。
|
||||
// 分量重映射:RGBX / RGB_DXT1 一类「无 alpha」格式 a 取 1;RGB 系 16 位打包格式交换 r/b;其余恒等。
|
||||
// BC1–7 在 iOS 上需 GPU 支持 BC(MTLDevice.supportsBCTextureCompression,iOS 16.4+;A19 已支持,未在本表核设备能力)。
|
||||
// NVNformat (nvn.h 0x01–0x9C) → Metal. The table is written entry by entry in NVN enum order; unlisted formats (including 0 and out of range) return 0.
|
||||
// Component remapping: "no alpha" formats such as RGBX / RGB_DXT1 read a as 1; RGB-family 16-bit packed formats swap r/b; all others are identity.
|
||||
// BC1–7 on iOS require GPU BC support (MTLDevice.supportsBCTextureCompression, iOS 16.4+; A19 supports it; device capability is not checked in this table).
|
||||
#include "nvn_fmt_mtl.h"
|
||||
|
||||
enum { // MTLPixelFormat
|
||||
R8Unorm = 10, R8Snorm = 12, R8Uint = 13, R8Sint = 14, R16Unorm = 20, R16Snorm = 22, R16Uint = 23, R16Sint = 24, R16Float = 25,
|
||||
RG8Unorm = 30, RG8Snorm = 32, RG8Uint = 33, RG8Sint = 34, B5G6R5Unorm = 40, A1BGR5Unorm = 41, ABGR4Unorm = 42, BGR5A1Unorm = 43,
|
||||
R32Uint = 53, R32Sint = 54, R32Float = 55, RG16Unorm = 60, RG16Snorm = 62, RG16Uint = 63, RG16Sint = 64, RG16Float = 65,
|
||||
RGBA8Unorm = 70, RGBA8Unorm_sRGB = 71, RGBA8Snorm = 72, RGBA8Uint = 73, RGBA8Sint = 74, BGRA8Unorm = 80, BGRA8Unorm_sRGB = 81,
|
||||
RGB10A2Unorm = 90, RGB10A2Uint = 91, RG11B10Float = 92, RGB9E5Float = 93, RG32Uint = 103, RG32Sint = 104, RG32Float = 105,
|
||||
RGBA16Unorm = 110, RGBA16Snorm = 112, RGBA16Uint = 113, RGBA16Sint = 114, RGBA16Float = 115, RGBA32Uint = 123, RGBA32Sint = 124,
|
||||
RGBA32Float = 125, BC1 = 130, BC1_sRGB = 131, BC2 = 132, BC2_sRGB = 133, BC3 = 134, BC3_sRGB = 135, BC4_U = 140, BC4_S = 141,
|
||||
BC5_U = 142, BC5_S = 143, BC6H_S = 150, BC6H_U = 151, BC7 = 152, BC7_sRGB = 153,
|
||||
ASTC_SRGB0 = 186, ASTC_LDR0 = 204, // 4x4 起;7x? 不存在,故 8x5 起跳一号(见 astc_off) | starting at 4x4; 7x? does not exist, so one number is skipped from 8x5 on (see astc_off)
|
||||
Depth16Unorm = 250, Depth32Float = 252, Stencil8 = 253, Depth32Float_Stencil8 = 260,
|
||||
};
|
||||
|
||||
typedef struct { uint16_t mtl; uint8_t kind, noalpha, rb; } ent; // kind 1 精确 2 替代;noalpha:a 取 1;rb:交换 r/b | kind: 1 exact, 2 substitute; noalpha: a reads as 1; rb: swap r/b
|
||||
#define E(m) {m, 1, 0, 0}
|
||||
#define X(m) {m, 1, 1, 0} // 精确,无 alpha | exact, no alpha
|
||||
#define S(m) {m, 2, 0, 0} // 替代 | substitute
|
||||
#define SX(m) {m, 2, 1, 0}
|
||||
#define N {0, 0, 0, 0} // 无对应 | no counterpart
|
||||
#define SR(m) {m, 2, 0, 1} // 替代,交换 r/b | substitute, swap r/b
|
||||
#define SXR(m) {m, 2, 1, 1}
|
||||
|
||||
static const ent T[0x9D] = {
|
||||
[0x01] = E(R8Unorm), E(R8Snorm), E(R8Uint), E(R8Sint),
|
||||
[0x05] = E(R16Float), E(R16Unorm), E(R16Snorm), E(R16Uint), E(R16Sint),
|
||||
[0x0A] = E(R32Float), E(R32Uint), E(R32Sint),
|
||||
[0x0D] = E(RG8Unorm), E(RG8Snorm), E(RG8Uint), E(RG8Sint),
|
||||
[0x11] = E(RG16Float), E(RG16Unorm), E(RG16Snorm), E(RG16Uint), E(RG16Sint),
|
||||
[0x16] = E(RG32Float), E(RG32Uint), E(RG32Sint),
|
||||
// 0x19–0x24 RGB8 / RGB16 / RGB32 三分量:Metal 无 3 分量像素格式 → 返回 0。
|
||||
// 处理:上传时逐像素扩成同类 4 分量(RGBA8 / RGBA16 / RGBA32,a = 1,整数类 a = 1 原值),按 RGBX 采样;
|
||||
// 作缓冲贴图(target BUFFER)时改由着色器按 3 分量手读。
|
||||
// 0x19–0x24 RGB8 / RGB16 / RGB32 three-component: Metal has no 3-component pixel formats → return 0.
|
||||
// Handling: on upload expand per pixel to the 4-component format of the same kind (RGBA8 / RGBA16 / RGBA32, a = 1; for integer kinds a = raw value 1), sampled as RGBX;
|
||||
// when used as a buffer texture (target BUFFER), the shader reads the 3 components manually instead.
|
||||
[0x19] = N, N, N, N, N, N, N, N, N, N, N, N,
|
||||
[0x25] = E(RGBA8Unorm), E(RGBA8Snorm), E(RGBA8Uint), E(RGBA8Sint),
|
||||
[0x29] = E(RGBA16Float), E(RGBA16Unorm), E(RGBA16Snorm), E(RGBA16Uint), E(RGBA16Sint),
|
||||
[0x2E] = E(RGBA32Float), E(RGBA32Uint), E(RGBA32Sint),
|
||||
[0x31] = E(Stencil8), E(Depth16Unorm),
|
||||
// DEPTH24:Apple GPU 无 Depth24(Depth24Unorm_Stencil8 iOS 不可用)→ Depth32Float:作渲染目标精度升级、行为等价;
|
||||
// 标替代只因上传现成 24 位深度数据时需转浮点(渲染目标不涉及)
|
||||
// DEPTH24: Apple GPUs have no Depth24 (Depth24Unorm_Stencil8 is unavailable on iOS) → Depth32Float: as a render target this is a precision upgrade with equivalent behavior;
|
||||
// marked substitute only because uploading existing 24-bit depth data requires conversion to float (render targets are not affected)
|
||||
[0x33] = S(Depth32Float), E(Depth32Float),
|
||||
// DEPTH24_STENCIL8 → Depth32Float_Stencil8(同上:渲染目标精度升级、行为等价;上传数据需转换故标替代);DEPTH32F_STENCIL8 精确
|
||||
// DEPTH24_STENCIL8 → Depth32Float_Stencil8 (as above: precision upgrade as a render target, equivalent behavior; marked substitute because uploaded data needs conversion); DEPTH32F_STENCIL8 is exact
|
||||
[0x35] = S(Depth32Float_Stencil8), E(Depth32Float_Stencil8),
|
||||
[0x37] = X(RGBA8Unorm_sRGB), E(RGBA8Unorm_sRGB),
|
||||
// 16 位打包格式:按名字对应——BGR 系(0x95–0x98)直接对 Metal 同名,RGB 系用同一 Metal 格式并交换 r/b。
|
||||
// NVN 与 Metal 的实际位序未用真数据核 → 全部标替代,首次遇到真贴图时核位序再升精确
|
||||
// 16-bit packed formats: matched by name - the BGR family (0x95–0x98) maps directly to the same-named Metal format, the RGB family uses the same Metal format with r/b swapped.
|
||||
// The actual bit order of NVN vs Metal has not been verified with real data → all marked substitute; verify the bit order when a real texture is first encountered, then upgrade to exact
|
||||
[0x39] = S(ABGR4Unorm), SXR(BGR5A1Unorm), SR(BGR5A1Unorm), SR(B5G6R5Unorm),
|
||||
[0x3D] = E(RGB10A2Unorm), E(RGB10A2Uint), E(RG11B10Float), E(RGB9E5Float),
|
||||
// DXT / RGTC / BPTC = BC1–7;RGB_DXT1 无 alpha
|
||||
// DXT / RGTC / BPTC = BC1–7; RGB_DXT1 has no alpha
|
||||
[0x41] = X(BC1), E(BC1), E(BC2), E(BC3), X(BC1_sRGB), E(BC1_sRGB), E(BC2_sRGB), E(BC3_sRGB),
|
||||
[0x49] = E(BC4_U), E(BC4_S), E(BC5_U), E(BC5_S), E(BC7), E(BC7_sRGB), E(BC6H_S), E(BC6H_U),
|
||||
// *_UI2F / *_I2F:整数存储、按浮点读(不归一化转换)。Metal 无此读法 → 替代为同宽整数格式,着色器按整数采样后转 float;
|
||||
// 3 分量的同 0x19 组处理(返回 0)
|
||||
// *_UI2F / *_I2F: integer storage, read as float (conversion without normalization). Metal has no such read mode → substituted with the same-width integer format; the shader samples as integer and then converts to float;
|
||||
// 3-component ones are handled like the 0x19 group (return 0)
|
||||
[0x51] = S(R8Uint), S(R8Sint), S(R16Uint), S(R16Sint), S(R32Uint), S(R32Sint),
|
||||
[0x57] = S(RG8Uint), S(RG8Sint), S(RG16Uint), S(RG16Sint), S(RG32Uint), S(RG32Sint),
|
||||
[0x5D] = N, N, N, N, N, N,
|
||||
[0x63] = S(RGBA8Uint), S(RGBA8Sint), S(RGBA16Uint), S(RGBA16Sint), S(RGBA32Uint), S(RGBA32Sint),
|
||||
// RGB10A2 有符号 / 有符号整数:Metal 只有 Unorm / Uint → 0;处理:上传时解包到 RGBA16Snorm / RGBA16Sint
|
||||
// RGB10A2_UI2F → RGB10A2Uint 着色器转 float(替代);RGB10A2_I2F → 0(同上解包到 RGBA16Sint)
|
||||
// RGB10A2 signed / signed integer: Metal only has Unorm / Uint → 0; handling: unpack to RGBA16Snorm / RGBA16Sint on upload
|
||||
// RGB10A2_UI2F → RGB10A2Uint with the shader converting to float (substitute); RGB10A2_I2F → 0 (unpacked to RGBA16Sint as above)
|
||||
[0x69] = N, N, S(RGB10A2Uint), N,
|
||||
[0x6D] = X(RGBA8Unorm), X(RGBA8Snorm), X(RGBA8Uint), X(RGBA8Sint),
|
||||
[0x71] = X(RGBA16Float), X(RGBA16Unorm), X(RGBA16Snorm), X(RGBA16Uint), X(RGBA16Sint),
|
||||
[0x76] = X(RGBA32Float), X(RGBA32Uint), X(RGBA32Sint),
|
||||
// 0x79–0x94 ASTC 由 astc_off 计算(LDR / sRGB 两组各 14 种)
|
||||
// 0x79–0x94 ASTC is computed by astc_off (two groups, LDR / sRGB, 14 each)
|
||||
[0x95] = S(B5G6R5Unorm), SX(BGR5A1Unorm), S(BGR5A1Unorm), S(A1BGR5Unorm),
|
||||
[0x99] = X(BGRA8Unorm), E(BGRA8Unorm), X(BGRA8Unorm_sRGB), E(BGRA8Unorm_sRGB),
|
||||
};
|
||||
|
||||
// NVN ASTC 序:4x4 5x4 5x5 6x5 6x6 8x5 8x6 8x8 10x5 10x6 10x8 10x10 12x10 12x12;Metal 在 6x6 与 8x5 之间空一号
|
||||
// NVN ASTC order: 4x4 5x4 5x5 6x5 6x6 8x5 8x6 8x8 10x5 10x6 10x8 10x10 12x10 12x12; Metal skips one number between 6x6 and 8x5
|
||||
static const uint8_t astc_off[14] = {0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14};
|
||||
|
||||
int nvn_fmt_to_mtl(int f, uint32_t *mtl, uint8_t swz[4]) {
|
||||
ent e = {0, 0, 0, 0};
|
||||
if (f >= 0x79 && f <= 0x94) { int k = (f - 0x79) % 14; e = (ent){(uint16_t)((f < 0x87 ? ASTC_LDR0 : ASTC_SRGB0) + astc_off[k]), 1, 0, 0}; }
|
||||
else if (f > 0 && f < (int)(sizeof T / sizeof *T)) e = T[f];
|
||||
if (mtl) *mtl = e.kind ? e.mtl : 0;
|
||||
if (swz) { swz[0] = e.rb ? NVN_SWZ_B : NVN_SWZ_R; swz[1] = NVN_SWZ_G; swz[2] = e.rb ? NVN_SWZ_R : NVN_SWZ_B; swz[3] = e.noalpha ? NVN_SWZ_ONE : NVN_SWZ_A; }
|
||||
return e.kind;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// NVNformat → Metal 像素格式 + 分量重映射。纯 C,不依赖 Metal 头(数值取自 SDK MTLPixelFormat.h / MTLTexture.h,iOS 26.5 SDK)。
|
||||
// NVNformat → Metal pixel format + component remapping. Pure C, no dependency on Metal headers (values taken from the SDK's MTLPixelFormat.h / MTLTexture.h, iOS 26.5 SDK).
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
|
||||
// MTLTextureSwizzle 数值
|
||||
// MTLTextureSwizzle values
|
||||
enum { NVN_SWZ_ZERO = 0, NVN_SWZ_ONE = 1, NVN_SWZ_R = 2, NVN_SWZ_G = 3, NVN_SWZ_B = 4, NVN_SWZ_A = 5 };
|
||||
|
||||
// 返回:1 = 精确对应(数据原样上传);
|
||||
// 2 = 替代(精度 / 位序 / 读法不同:上传需转换或着色器需改读法,每个格式的办法见 nvn_fmt_mtl.c 表内注释);
|
||||
// 0 = Metal 无对应(*mtl 写 0;处理办法见表内注释,主要是 3 分量格式上传时扩成 4 分量)。
|
||||
// swz 为 r/g/b/a 四个输出分量各取哪个源分量(MTLTextureSwizzleChannels 顺序);可为 NULL。
|
||||
// Returns: 1 = exact match (data uploaded as is);
|
||||
// 2 = substitute (precision / bit order / read mode differs: upload needs conversion or the shader must read differently; per-format handling is in the table comments in nvn_fmt_mtl.c);
|
||||
// 0 = no Metal counterpart (*mtl is set to 0; handling is in the table comments, mainly expanding 3-component formats to 4 components on upload).
|
||||
// swz gives, for each of the four output components r/g/b/a, which source component to take (MTLTextureSwizzleChannels order); may be NULL.
|
||||
int nvn_fmt_to_mtl(int nvn_format, uint32_t *mtl_pixel_format, uint8_t swz[4]);
|
||||
@@ -0,0 +1,3 @@
|
||||
t_tex
|
||||
t_fmt_mtl
|
||||
*.dSYM
|
||||
@@ -0,0 +1,15 @@
|
||||
DM_ROOT ?= $(HOME)/dm-work
|
||||
# 贴图子块单测(秒级):make run。真数据样本 make samples 取到 $(SAMPLES)(构建缓存,不进仓)
|
||||
# Texture sub-module unit tests (seconds): make run. Real-data samples: make samples fetches them into $(SAMPLES) (build cache, not in the repo)
|
||||
SAMPLES ?= $(DM_ROOT)/build/cache/dm/tex_samples
|
||||
PY ?= $(DM_ROOT)/build/cache/dm/venv/bin/python
|
||||
CFLAGS = -O2 -g -Wall -Wextra
|
||||
t_tex: t_tex.c ../nvn_deswizzle.c ../nvn_deswizzle.h ../../nvn/nvn_tex.c ../../nvn/nvn_tex.h
|
||||
clang $(CFLAGS) -o $@ t_tex.c ../nvn_deswizzle.c ../../nvn/nvn_tex.c -lm
|
||||
t_fmt_mtl: t_fmt_mtl.m ../nvn_fmt_mtl.c ../nvn_fmt_mtl.h
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_fmt_mtl.m ../nvn_fmt_mtl.c -framework Metal -framework Foundation
|
||||
samples:
|
||||
$(PY) fetch_samples.py $(SAMPLES)
|
||||
run: t_tex t_fmt_mtl
|
||||
./t_fmt_mtl && ./t_tex $(SAMPLES)
|
||||
.PHONY: samples run
|
||||
@@ -0,0 +1,29 @@
|
||||
# 取真数据对拍样本:Switch 包(RomFS,块线性)与 PC 包(已提取原件,线性)同名 .texture 各一份。
|
||||
# 用法:fetch_samples.py <输出目录> → <输出目录>/{dm,pc}/<序号>.texture + list.tsv(序号 路径 说明)
|
||||
# 选样:覆盖 RGBA8 / BC1 / BC3 / BC4,大小从 32² 到 2048²、含非方形;同分辨率的逐字节比,降分辨率的比解码 PSNR。
|
||||
# Fetch real-data samples for cross-checking: one copy each of the same-named .texture from the Switch package (RomFS, block-linear) and the PC package (extracted originals, linear).
|
||||
# Usage: fetch_samples.py <output dir> → <output dir>/{dm,pc}/<index>.texture + list.tsv (index, path, note)
|
||||
# Sample selection: covers RGBA8 / BC1 / BC3 / BC4, sizes from 32² to 2048², including non-square; same-resolution ones are compared byte for byte, reduced-resolution ones by decoded PSNR.
|
||||
import os, sys
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../../tools'))
|
||||
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # 工作区根目录(游戏文件、产物、运行现场都在它下面) | Workspace root (game files, build outputs and run artifacts are all under it)
|
||||
os.environ.setdefault('DMX_ROOT', os.path.join(DM_ROOT, 'data/switch/3.3.94012/Update/RomFS/data'))
|
||||
import dmx
|
||||
PC = os.path.join(DM_ROOT, 'data/assets-src/raw')
|
||||
SAMPLES = [
|
||||
('hd/vfx/textures/gradient/T_FX_perlin_wipe_03.texture', 'RGBA8 256² 同分辨率'),
|
||||
('hd/vfx/textures/gradient/T_FX_portal_gradient.texture', 'RGBA8 256×16 非方形 同分辨率'),
|
||||
('hd/env/texture/terrain/path/066_PATH.texture', 'BC4 32² 同分辨率'),
|
||||
('hd/debug/wasted_mip_size_2048.texture', 'BC3 sRGB 2048² 12 级 同分辨率'),
|
||||
('hd/items/armor/armor/plate_mail/textures/armor_plate_mail_alb.texture', 'BC3 sRGB 256²(PC 1024²)降分辨率'),
|
||||
('hd/env/texture/global/flow/act4/lava/lava_lavaNS_FLOW.texture', 'BC1 64²(PC 256²)降分辨率'),
|
||||
('hd/character/enemy/fingermage1/Textures/fingermage_KTINT.texture', 'BC3 256²(PC 1024²)降分辨率'),
|
||||
]
|
||||
out = sys.argv[1]
|
||||
os.makedirs(f'{out}/dm', exist_ok=True); os.makedirs(f'{out}/pc', exist_ok=True)
|
||||
with open(f'{out}/list.tsv', 'w') as f:
|
||||
for i, (p, why) in enumerate(SAMPLES):
|
||||
open(f'{out}/dm/{i}.texture', 'wb').write(dmx.get('data:data/' + p))
|
||||
open(f'{out}/pc/{i}.texture', 'wb').write(open(os.path.join(PC, p), 'rb').read())
|
||||
f.write(f'{i}\t{p}\t{why}\n')
|
||||
print(len(SAMPLES), '对样本 →', out)
|
||||
@@ -0,0 +1,35 @@
|
||||
// 格式表实建核对:对 0x01–0x9C 每个 NVN 格式取映射,用本机 MTLDevice 真建一张 2D 贴图(带分量重映射),统计能建成的条数。
|
||||
// 判据:映射非 0 的格式全部建成(newTextureWithDescriptor 非 nil);另核 sRGB 名的 NVN 格式全部落到 Metal _sRGB 格式。
|
||||
// Format table verification by actual creation: for every NVN format 0x01–0x9C take the mapping and actually create a 2D texture (with component remapping) on the local MTLDevice, counting how many can be created.
|
||||
// Criterion: every format with a non-zero mapping is created (newTextureWithDescriptor non-nil); also verify that every NVN format with sRGB in its name lands on a Metal _sRGB format.
|
||||
#import <Metal/Metal.h>
|
||||
#include <stdio.h>
|
||||
#include "../nvn_fmt_mtl.h"
|
||||
int main(void) {
|
||||
@autoreleasepool {
|
||||
id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
|
||||
printf("设备 %s\n", dev.name.UTF8String);
|
||||
int mapped = 0, ok = 0, exact = 0, sub = 0, none = 0, bad_srgb = 0;
|
||||
static const int srgb[] = {0x37, 0x38, 0x45, 0x46, 0x47, 0x48, 0x4E, 0x9B, 0x9C};
|
||||
for (int f = 0x01; f <= 0x9C; f++) {
|
||||
uint32_t m; uint8_t s[4]; int k = nvn_fmt_to_mtl(f, &m, s);
|
||||
if (!k) { none++; continue; }
|
||||
mapped++; k == 1 ? exact++ : sub++;
|
||||
MTLTextureDescriptor *d = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:(MTLPixelFormat)m width:120 height:120 mipmapped:NO];
|
||||
d.swizzle = MTLTextureSwizzleChannelsMake(s[0], s[1], s[2], s[3]);
|
||||
BOOL depth = m >= 250 && m <= 262;
|
||||
d.storageMode = depth ? MTLStorageModePrivate : MTLStorageModeShared;
|
||||
d.usage = MTLTextureUsageShaderRead | (depth ? MTLTextureUsageRenderTarget : 0);
|
||||
if (depth) d.swizzle = MTLTextureSwizzleChannelsDefault; // 深度格式不允许重映射 | remapping is not allowed for depth formats
|
||||
id<MTLTexture> t = [dev newTextureWithDescriptor:d];
|
||||
if (t) ok++; else printf("建不成 NVN %#x → MTL %u\n", f, m);
|
||||
}
|
||||
for (unsigned i = 0; i < sizeof srgb / sizeof *srgb; i++) {
|
||||
uint32_t m; nvn_fmt_to_mtl(srgb[i], &m, NULL);
|
||||
if (!(m == 71 || m == 81 || m == 131 || m == 133 || m == 135 || m == 153)) { printf("sRGB 未落到 _sRGB:%#x → %u\n", srgb[i], m); bad_srgb++; }
|
||||
}
|
||||
for (int f = 0x87; f <= 0x94; f++) { uint32_t m; nvn_fmt_to_mtl(f, &m, NULL); if (m < 186 || m > 200) { printf("ASTC sRGB 未落到 _sRGB:%#x → %u\n", f, m); bad_srgb++; } }
|
||||
printf("映射非 0:%d(精确 %d、替代 %d),无对应 %d,共 %d;实建成 %d/%d;sRGB 违例 %d\n", mapped, exact, sub, none, 0x9C, ok, mapped, bad_srgb);
|
||||
return (ok == mapped && !bad_srgb) ? 0 : 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
// 块线性解排布单测(秒级)。A 往返;B 手算地址;C 真数据对拍(Switch 块线性 vs PC 线性,含逐级偏移核对);D 错块高负对照。
|
||||
// 用法:t_tex <样本目录>(fetch_samples.py 产出)。样本缺失算红,不跳过。
|
||||
// Block-linear deswizzle unit tests (seconds). A round trip; B hand-calculated addresses; C real-data cross-check (Switch block-linear vs PC linear, including per-level offset verification); D wrong-block-height negative control.
|
||||
// Usage: t_tex <sample dir> (produced by fetch_samples.py). Missing samples count as red, not skipped.
|
||||
#include "../nvn_deswizzle.h"
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static int checks, fails;
|
||||
#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; printf(" ✗ "); printf(__VA_ARGS__); printf("\n"); } } while (0)
|
||||
static uint32_t mipd(uint32_t s, unsigned l) { s >>= l; return s ? s : 1; }
|
||||
static uint64_t rng = 0x9E3779B97F4A7C15ull;
|
||||
static uint8_t rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (uint8_t)rng; }
|
||||
|
||||
// 本级线性尺寸(测试侧独立算:块宽字节、块行、切片)
|
||||
// Linear size of this level (computed independently on the test side: width-in-blocks bytes, block rows, slices)
|
||||
static void dims(const nvn_texdesc *d, unsigned l, uint32_t *rb, uint32_t *rows, uint32_t *sl) {
|
||||
int bw, bh, bpb = nvn_fmt_bpb(d->format, &bw, &bh);
|
||||
*rb = (mipd(d->width, l) + bw - 1) / bw * bpb; *rows = (mipd(d->height, l) + bh - 1) / bh;
|
||||
*sl = d->target == 2 ? mipd(d->depth, l) : 1;
|
||||
}
|
||||
|
||||
// ---------- A 往返:全部级 / 层先各写入不同随机数据,再全部解出比对(级间、层间重叠或越界都会红)----------
|
||||
// ---------- A round trip: first write different random data into every level / layer, then decode them all and compare (overlap between levels or between layers, or out-of-bounds, all fail) ----------
|
||||
static void roundtrip(const char *tag, int target, int fmt, uint32_t w, uint32_t h, uint32_t depth, uint32_t levels) {
|
||||
nvn_texdesc d = {target, fmt, 0, 0, w, h, depth, levels, 0};
|
||||
nvn_texlayout L; nvn_tex_layout(&d, &L);
|
||||
size_t guard = 4096; uint8_t *st = malloc(L.size + guard); memset(st, 0, L.size); memset(st + L.size, 0xAB, guard);
|
||||
uint8_t *ref[64][16] = {{0}}; uint64_t bytes = 0;
|
||||
for (unsigned y = 0; y < L.layers; y++) for (unsigned l = 0; l < levels; l++) {
|
||||
uint32_t rb, rows, sl; dims(&d, l, &rb, &rows, &sl);
|
||||
size_t n = (size_t)rb * rows * sl; ref[y][l] = malloc(n); for (size_t i = 0; i < n; i++) ref[y][l][i] = rnd();
|
||||
CHECK(!nvn_swizzle(&d, l, y, ref[y][l], rb, st), "%s 写入失败 层%u 级%u", tag, y, l);
|
||||
}
|
||||
int guard_ok = 1; for (size_t i = 0; i < guard; i++) guard_ok &= st[L.size + i] == 0xAB;
|
||||
CHECK(guard_ok, "%s 写出存储末尾(越界)", tag);
|
||||
int ok = 1;
|
||||
for (unsigned y = 0; y < L.layers; y++) for (unsigned l = 0; l < levels; l++) {
|
||||
uint32_t rb, rows, sl; dims(&d, l, &rb, &rows, &sl);
|
||||
size_t n = (size_t)rb * rows * sl; uint8_t *out = malloc(n);
|
||||
CHECK(!nvn_deswizzle(&d, l, y, st, out, rb), "%s 解出失败", tag);
|
||||
if (memcmp(out, ref[y][l], n)) { ok = 0; printf(" ✗ %s 层%u 级%u 往返不等\n", tag, y, l); }
|
||||
bytes += n; free(out); free(ref[y][l]);
|
||||
}
|
||||
checks++; if (!ok) fails++;
|
||||
printf(" A %-34s 层%u × 级%u,往返 %llu 字节 %s\n", tag, L.layers, levels, (unsigned long long)bytes, ok ? "全等" : "不等");
|
||||
free(st);
|
||||
}
|
||||
|
||||
// ---------- 真数据 ----------
|
||||
// ---------- Real data ----------
|
||||
static uint8_t *slurp(const char *p, size_t *n) {
|
||||
FILE *f = fopen(p, "rb"); if (!f) return NULL;
|
||||
fseek(f, 0, SEEK_END); *n = (size_t)ftell(f); fseek(f, 0, SEEK_SET);
|
||||
uint8_t *b = malloc(*n); if (fread(b, 1, *n, f) != *n) { free(b); b = NULL; } fclose(f); return b;
|
||||
}
|
||||
// Switch 转换过的文件:0x14 四字节 = 00 00 00 07(PC 为 0),0x13 = 第 0 级块高 log2(与游戏 SetPackagedTextureLayout 第 0 字节同义)。
|
||||
// 未转换的(如 hd/debug 下的)与 PC 文件逐字节相同、线性存放。
|
||||
// Files converted for Switch: the four bytes at 0x14 = 00 00 00 07 (0 on PC), 0x13 = log2 of the level-0 block height (same meaning as byte 0 of the game's SetPackagedTextureLayout).
|
||||
// Unconverted ones (e.g. those under hd/debug) are byte-identical to the PC files and stored linearly.
|
||||
typedef struct { int code, nvn, bl, th_hdr; uint32_t w, h, mips, hdr; uint32_t size[16]; uint64_t off[16]; const uint8_t *px; } tex_t;
|
||||
static int d2r_nvn(int code) { // D2R .texture 格式码 → NVNformat | D2R .texture format code → NVNformat
|
||||
switch (code) { case 0x1F: return 0x25; case 0x39: return 0x42; case 0x3A: return 0x46; case 0x3D: return 0x44;
|
||||
case 0x3E: return 0x48; case 0x3F: return 0x49; case 0x41: return 0x4B; }
|
||||
return 0;
|
||||
}
|
||||
static int parse(const uint8_t *b, size_t n, tex_t *t) {
|
||||
if (n < 0x24 || memcmp(b, "<DE(", 4)) return -1;
|
||||
t->code = b[4]; t->nvn = d2r_nvn(t->code); t->bl = b[0x14] == 0 && b[0x15] == 0 && b[0x16] == 0 && b[0x17] == 7; t->th_hdr = b[0x13];
|
||||
memcpy(&t->w, b + 8, 4); memcpy(&t->h, b + 12, 4); memcpy(&t->mips, b + 0x1C, 4);
|
||||
if (!t->nvn || t->mips == 0 || t->mips > 16) return -1;
|
||||
t->hdr = 36 + 8 * t->mips; uint64_t o = 0;
|
||||
for (unsigned i = 0; i < t->mips; i++) { memcpy(&t->size[i], b + 0x24 + 8 * i, 4); t->off[i] = o; o += t->size[i]; }
|
||||
if (t->hdr + o != n) return -1;
|
||||
t->px = b + t->hdr; return 0;
|
||||
}
|
||||
|
||||
// 解码成 8 位 RGB(BC1 / BC3 取颜色块,BC4 取单通道铺三份,RGBA8 取 RGB)。行 = 块行,按 4×4 展开
|
||||
// Decode to 8-bit RGB (BC1 / BC3 take the color block, BC4 takes the single channel replicated three times, RGBA8 takes RGB). Row = block row, expanded as 4×4
|
||||
static void bc1(const uint8_t *b, uint8_t out[16][3]) {
|
||||
unsigned c0 = b[0] | b[1] << 8, c1 = b[2] | b[3] << 8; uint32_t bits = b[4] | b[5] << 8 | b[6] << 16 | (uint32_t)b[7] << 24;
|
||||
int p[4][3];
|
||||
for (int k = 0; k < 2; k++) { unsigned c = k ? c1 : c0; p[k][0] = (c >> 11 & 31) * 255 / 31; p[k][1] = (c >> 5 & 63) * 255 / 63; p[k][2] = (c & 31) * 255 / 31; }
|
||||
for (int j = 0; j < 3; j++) {
|
||||
if (c0 > c1) { p[2][j] = (2 * p[0][j] + p[1][j]) / 3; p[3][j] = (p[0][j] + 2 * p[1][j]) / 3; }
|
||||
else { p[2][j] = (p[0][j] + p[1][j]) / 2; p[3][j] = 0; }
|
||||
}
|
||||
for (int i = 0; i < 16; i++) for (int j = 0; j < 3; j++) out[i][j] = (uint8_t)p[bits >> (2 * i) & 3][j];
|
||||
}
|
||||
static void bc4(const uint8_t *b, uint8_t out[16][3]) {
|
||||
int a0 = b[0], a1 = b[1], v[8] = {a0, a1};
|
||||
for (int k = 2; k < 8; k++) v[k] = a0 > a1 ? ((8 - k) * a0 + (k - 1) * a1) / 7 : k < 6 ? ((6 - k) * a0 + (k - 1) * a1) / 5 : (k == 6 ? 0 : 255);
|
||||
uint64_t bits = 0; for (int k = 0; k < 6; k++) bits |= (uint64_t)b[2 + k] << (8 * k);
|
||||
for (int i = 0; i < 16; i++) out[i][0] = out[i][1] = out[i][2] = (uint8_t)v[bits >> (3 * i) & 7];
|
||||
}
|
||||
static uint8_t *decode(int nvn, const uint8_t *lin, uint32_t w, uint32_t h) { // → w×h×3
|
||||
uint8_t *img = calloc((size_t)w * h, 3);
|
||||
if (nvn == 0x25) { for (size_t i = 0; i < (size_t)w * h; i++) memcpy(img + 3 * i, lin + 4 * i, 3); return img; }
|
||||
uint32_t bwn = (w + 3) / 4, bhn = (h + 3) / 4, bpb = (nvn == 0x42 || nvn == 0x46 || nvn == 0x49) ? 8 : 16;
|
||||
for (uint32_t by = 0; by < bhn; by++) for (uint32_t bx = 0; bx < bwn; bx++) {
|
||||
const uint8_t *b = lin + ((size_t)by * bwn + bx) * bpb; uint8_t px[16][3];
|
||||
if (nvn == 0x49) bc4(b, px); else bc1(bpb == 16 ? b + 8 : b, px);
|
||||
for (int i = 0; i < 16; i++) { uint32_t x = bx * 4 + i % 4, y = by * 4 + i / 4; if (x < w && y < h) memcpy(img + 3 * ((size_t)y * w + x), px[i], 3); }
|
||||
}
|
||||
return img;
|
||||
}
|
||||
static double psnr(const uint8_t *a, const uint8_t *b, size_t n) {
|
||||
double e = 0; for (size_t i = 0; i < n; i++) { double d = (double)a[i] - b[i]; e += d * d; }
|
||||
return e == 0 ? 99 : 10 * log10(255.0 * 255.0 / (e / n));
|
||||
}
|
||||
// 用指定块高解一级(负对照用;越过存储的地址按 0 读)
|
||||
// Decode one level with a specified block height (for the negative control; addresses beyond the storage read as 0)
|
||||
static void deswz_tile(const uint8_t *st, uint64_t st_size, uint64_t base, uint32_t rb, uint32_t rows, unsigned th, uint8_t *out) {
|
||||
for (uint32_t y = 0; y < rows; y++) for (uint32_t x = 0; x < rb; x++) {
|
||||
uint64_t a = base + nvn_bl_offset(x, y, 0, rb, rows, th, 0);
|
||||
out[(size_t)y * rb + x] = a < st_size ? st[a] : 0;
|
||||
}
|
||||
}
|
||||
|
||||
// 判据阈值:正确块高须 ≥、错块高须 < 此值。实测:正确 28.45–38.90 dB(降分辨率重压缩的 3 张;同分辨率的逐字节全等),
|
||||
// 错一级块高 6.94–16.64 dB ⇒ 取两侧中点 22 dB,两边各留约 6 dB
|
||||
// Criterion threshold: the correct block height must be ≥ this value and a wrong block height must be < it. Measured: correct 28.45–38.90 dB (the 3 reduced-resolution recompressed ones; same-resolution ones are byte-identical),
|
||||
// block height off by one step 6.94–16.64 dB ⇒ take the midpoint of the two sides, 22 dB, leaving about 6 dB on each side
|
||||
#define PSNR_PASS 22.0
|
||||
|
||||
static void real_pair(const char *dir, int i, const char *why) {
|
||||
char p[1024]; size_t ns, np;
|
||||
snprintf(p, sizeof p, "%s/dm/%d.texture", dir, i); uint8_t *sb = slurp(p, &ns);
|
||||
snprintf(p, sizeof p, "%s/pc/%d.texture", dir, i); uint8_t *pb = slurp(p, &np);
|
||||
tex_t s, c;
|
||||
CHECK(sb && pb && !parse(sb, ns, &s) && !parse(pb, np, &c), "样本 %d 读取 / 解析失败(%s)", i, why);
|
||||
if (!sb || !pb || parse(sb, ns, &s) || parse(pb, np, &c)) return;
|
||||
if (!s.bl) { // 未经 Switch 转换:线性,应与 PC 原件逐字节相同 | not converted for Switch: linear, should be byte-identical to the PC original
|
||||
CHECK(ns == np && !memcmp(sb, pb, ns), "样本%d 无块线性标记但与 PC 原件不同", i);
|
||||
printf(" C %d %-30s 无 Switch 块线性标记(0x14 = 0)→ 线性存放,与 PC 原件 %s(%zu 字节)\n", i, why, ns == np && !memcmp(sb, pb, ns) ? "逐字节全等" : "不等", ns);
|
||||
free(sb); free(pb); return;
|
||||
}
|
||||
nvn_texdesc d = {1, s.nvn, 0, 0, s.w, s.h, 1, s.mips, 0, s.th_hdr + 1}; // 块高以文件头为准(同游戏传入的预排布参数) | block height follows the file header (same as the packaged layout parameters the game passes in)
|
||||
unsigned th_auto, td_auto; { nvn_texdesc a = d; a.pkg_block_h = 0; nvn_tex_level_tiles(&a, 0, &th_auto, &td_auto); }
|
||||
// ③ 文件里的逐级偏移(mip 表累加)对 nvn_tex_level_offset
|
||||
// ③ Per-level offsets in the file (cumulative mip table) vs nvn_tex_level_offset
|
||||
int off_ok = 1;
|
||||
for (unsigned l = 0; l < s.mips; l++)
|
||||
if (s.off[l] != nvn_tex_level_offset(&d, l)) { off_ok = 0; printf(" ✗ 样本%d 级%u 文件偏移 %llu ≠ nvn_tex %llu\n", i, l, (unsigned long long)s.off[l], (unsigned long long)nvn_tex_level_offset(&d, l)); }
|
||||
nvn_texlayout L; nvn_tex_layout(&d, &L);
|
||||
uint64_t file_total = s.off[s.mips - 1] + s.size[s.mips - 1];
|
||||
checks++; if (!off_ok) fails++;
|
||||
CHECK(file_total == L.size, "样本%d 文件像素区 %llu ≠ nvn_tex 总尺寸 %llu", i, (unsigned long long)file_total, (unsigned long long)L.size);
|
||||
// 对应 PC 级:PC 边长 = Switch × 2^k
|
||||
// Corresponding PC level: PC side length = Switch × 2^k
|
||||
unsigned k = 0; while ((s.w << k) < c.w) k++;
|
||||
if ((s.w << k) != c.w || (s.h << k) != c.h) { CHECK(0, "样本%d 尺寸比非 2 的幂", i); return; }
|
||||
unsigned nl = s.mips < c.mips - k ? s.mips : c.mips - k;
|
||||
uint64_t eq = 0, tot = 0; double ps = 0, ps_bad = 99; unsigned th0, td0;
|
||||
nvn_tex_level_tiles(&d, 0, &th0, &td0);
|
||||
for (unsigned l = 0; l < nl; l++) {
|
||||
uint32_t rb, rows, sl; dims(&d, l, &rb, &rows, &sl);
|
||||
uint8_t *lin = malloc((size_t)rb * rows);
|
||||
CHECK(!nvn_deswizzle(&d, l, 0, s.px, lin, rb), "样本%d 级%u 解排布失败", i, l);
|
||||
const uint8_t *pcl = c.px + c.off[l + k];
|
||||
CHECK(c.size[l + k] >= (uint64_t)rb * rows, "样本%d 级%u PC 级尺寸不足", i, l);
|
||||
if (!k) { for (size_t j = 0; j < (size_t)rb * rows; j++) eq += lin[j] == pcl[j]; tot += (uint64_t)rb * rows; }
|
||||
if (l == 0) {
|
||||
uint32_t w = s.w, h = s.h;
|
||||
uint8_t *a = decode(s.nvn, lin, w, h), *b = decode(c.nvn, pcl, w, h); ps = psnr(a, b, (size_t)w * h * 3);
|
||||
for (int dt = -1; dt <= 1; dt += 2) { // D:块高错一级(只有 1 个 GOB 高时块高不影响排布,不适用) | D: block height off by one step (when only 1 GOB high, block height does not affect the layout; not applicable)
|
||||
if ((int)th0 + dt < 0 || rows <= 8) continue;
|
||||
uint8_t *bad = malloc((size_t)rb * rows); deswz_tile(s.px, ns - s.hdr, 0, rb, rows, th0 + dt, bad);
|
||||
uint8_t *e = decode(s.nvn, bad, w, h); double q = psnr(e, b, (size_t)w * h * 3); if (q < ps_bad) ps_bad = q;
|
||||
if (!k) CHECK(memcmp(bad, pcl, (size_t)rb * rows), "样本%d 块高 %+d 仍逐字节相等(负对照失效)", i, dt);
|
||||
free(bad); free(e);
|
||||
}
|
||||
free(a); free(b);
|
||||
}
|
||||
free(lin);
|
||||
}
|
||||
if (!k) CHECK(eq == tot, "样本%d 逐字节 %llu/%llu", i, (unsigned long long)eq, (unsigned long long)tot);
|
||||
CHECK(ps >= PSNR_PASS, "样本%d 正确块高 PSNR %.2f < %.0f", i, ps, PSNR_PASS);
|
||||
uint32_t rows0 = (s.h + 3) / 4; if (s.nvn == 0x25) rows0 = s.h;
|
||||
if (rows0 > 8) CHECK(ps_bad < PSNR_PASS, "样本%d 错块高 PSNR %.2f ≥ %.0f(负对照失效)", i, ps_bad, PSNR_PASS);
|
||||
char neg[48]; if (rows0 > 8) snprintf(neg, sizeof neg, "%.2f", ps_bad); else snprintf(neg, sizeof neg, "不适用(1 个 GOB 高)");
|
||||
printf(" C %d %-30s %4u×%-4u→PC 级%u 头块高 %d(自动 %u)偏移%s %s PSNR 正确 %.2f / 错块高 %s dB\n", i, why, s.w, s.h, k,
|
||||
s.th_hdr, th_auto, off_ok ? "✓" : "✗", k ? "(降分辨率,不比字节)" : (eq == tot ? "逐字节全等" : "逐字节不等"), ps, neg);
|
||||
if (!k) printf(" 逐字节 %llu/%llu\n", (unsigned long long)eq, (unsigned long long)tot);
|
||||
free(sb); free(pb);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
printf("A 往返(随机数据,非 2 的幂尺寸)\n");
|
||||
roundtrip("2D 100×37 R8 4 级", 1, 0x01, 100, 37, 1, 4);
|
||||
roundtrip("2D 100×37 RG8 4 级", 1, 0x0D, 100, 37, 1, 4);
|
||||
roundtrip("2D 100×37 RGBA8 4 级", 1, 0x25, 100, 37, 1, 4);
|
||||
roundtrip("2D 100×37 RGBA16F 4 级", 1, 0x29, 100, 37, 1, 4);
|
||||
roundtrip("2D 100×37 RGBA32F 4 级", 1, 0x2E, 100, 37, 1, 4);
|
||||
roundtrip("2D 100×37 BC3(16B/块) 4 级", 1, 0x44, 100, 37, 1, 4);
|
||||
roundtrip("2D 300×300 BC1(8B/块) 5 级", 1, 0x42, 300, 300, 1, 5);
|
||||
roundtrip("2D 数组 100×37×3 层 RGBA8 3 级", 4, 0x25, 100, 37, 3, 3);
|
||||
roundtrip("2D 数组 64×64×2 层 BC3 4 级", 4, 0x44, 64, 64, 2, 4);
|
||||
roundtrip("3D 100×37×5 RGBA8 3 级", 2, 0x25, 100, 37, 5, 3);
|
||||
roundtrip("3D 64×64×20 R8 4 级", 2, 0x01, 64, 64, 20, 4);
|
||||
roundtrip("3D 40×30×9 RGBA32F 3 级", 2, 0x2E, 40, 30, 9, 3);
|
||||
|
||||
printf("B 地址公式(期望值按 GOB 64B×8 行公开排布手算)\n");
|
||||
struct { uint32_t x, y, z, rb, rows; unsigned th, td; uint64_t want; const char *how; } B[] = {
|
||||
{0, 0, 0, 64, 8, 0, 0, 0, "原点"},
|
||||
{17, 3, 0, 64, 8, 0, 0, 113, "GOB 内:(3/2)·64 + (17%32/16)·32 + (3%2)·16 + 17%16 = 64+32+16+1"},
|
||||
{70, 9, 0, 128, 32, 1, 0, 1558, "块高 2:第 1 列块 1024 + 块内第 1 个 GOB 512 + GOB 内 (9%2)·16 + 6 = 22"},
|
||||
{0, 0, 1, 64, 8, 0, 1, 512, "块深 2:块内第 1 个 GOB(z%2·块高1)= 512"},
|
||||
{0, 0, 2, 64, 8, 0, 1, 1024, "块深 2:第 1 层块 = 1 列 × 1 行 × 1024"},
|
||||
{200, 40, 0, 256, 64, 2, 0, 9284, "块高 4(32 行):第 1 行块 4·2048=8192 + 第 3 列块 3·2048=6144?见下"},
|
||||
};
|
||||
// 最后一例手算:rb=256 → 4 个 GOB 宽;块高 4 GOB = 32 行、块 2048 字节;y=40 → 第 1 行块:4×2048 = 8192;
|
||||
// x=200 → 第 3 列块:3×2048 = 6144;块内 GOB = (40%32)/8 = 1 → 512;GOB 内 x%64=8、y%8=0 → 8。合计 8192+6144+512+8 = 14856
|
||||
// Last hand-calculated case: rb=256 → 4 GOBs wide; block height 4 GOBs = 32 rows, block 2048 bytes; y=40 → block row 1: 4×2048 = 8192;
|
||||
// x=200 → block column 3: 3×2048 = 6144; GOB within the block = (40%32)/8 = 1 → 512; within the GOB x%64=8, y%8=0 → 8. Total 8192+6144+512+8 = 14856
|
||||
B[5].want = 14856; B[5].how = "块高 4:行块 8192 + 列块 6144 + 块内 GOB 512 + GOB 内 8";
|
||||
for (unsigned i = 0; i < sizeof B / sizeof *B; i++) {
|
||||
uint64_t got = nvn_bl_offset(B[i].x, B[i].y, B[i].z, B[i].rb, B[i].rows, B[i].th, B[i].td);
|
||||
CHECK(got == B[i].want, "B%u 得 %llu 期望 %llu", i, (unsigned long long)got, (unsigned long long)B[i].want);
|
||||
printf(" B%u (%u,%u,%u) → %llu %s %s\n", i, B[i].x, B[i].y, B[i].z, (unsigned long long)got, got == B[i].want ? "✓" : "✗", B[i].how);
|
||||
}
|
||||
|
||||
// ---------- E 手工 3D:按手算地址往块线性存储里放标记,解出后核标记落点(往返 A 只证自洽,证不了排布对不对)----------
|
||||
// 块高块深规则出处:deko3d dk_image.cpp —— 3D 贴图块高固定 1 个 GOB,块深 = pickTileSize(深度 + 深度/2)。
|
||||
// ---------- E hand-built 3D: place markers into block-linear storage at hand-calculated addresses, decode, and verify where the markers land (round trip A only proves self-consistency, not whether the layout is right) ----------
|
||||
// Source of the block height / block depth rule: deko3d dk_image.cpp - for 3D textures block height is fixed at 1 GOB, block depth = pickTileSize(depth + depth/2).
|
||||
printf("E 手工 3D 块线性(标记放在手算地址,解排布后核落点)\n");
|
||||
{
|
||||
nvn_texdesc d = {2, 0x25, 0, 0, 32, 16, 20, 1, 0, 0}; // 3D RGBA8 32×16×20:行 128 字节 = 2 个 GOB 宽,16 行 = 2 个 GOB 高 | 3D RGBA8 32×16×20: row 128 bytes = 2 GOBs wide, 16 rows = 2 GOBs high
|
||||
nvn_texlayout L; nvn_tex_layout(&d, &L);
|
||||
// 块深:20 + 10 = 30 ≥ 16 → 16 片(log2 = 4);块 = 512 × 16 = 8192 字节;一层块 = 2 列 × 2 行 × 8192 = 32768;ceil(20/16) = 2 层 → 65536
|
||||
// Block depth: 20 + 10 = 30 ≥ 16 → 16 slices (log2 = 4); block = 512 × 16 = 8192 bytes; one block layer = 2 columns × 2 rows × 8192 = 32768; ceil(20/16) = 2 layers → 65536
|
||||
CHECK(L.tileH == 0 && L.tileD == 4, "E 32×16×20 块高/块深 = %u/%u,期望 0/4", L.tileH, L.tileD);
|
||||
CHECK(L.size == 65536, "E 32×16×20 存储 %llu 期望 65536", (unsigned long long)L.size);
|
||||
struct { uint32_t x, y, z; uint64_t addr; const char *how; } V[] = {
|
||||
{0, 0, 0, 0, "原点"},
|
||||
{20, 11, 3, 26224, "行块 1·2·8192=16384 + 列块(80/64=1)·8192 + 块内 GOB z%16=3·512=1536 + GOB 内 (x80%64=16,y3) 64+32+16 = 112"},
|
||||
{31, 15, 17, 58364, "深块 1·32768 + 行块 16384 + 列块 8192 + 块内 GOB 1·512 + GOB 内 (x60,y7) 256+192+32+16+12 = 508"},
|
||||
{5, 2, 19, 34404, "深块 32768 + 块内 GOB 3·512=1536 + GOB 内 (x20,y2) 64+32+4 = 100"},
|
||||
};
|
||||
uint8_t *st = calloc(L.size, 1), *lin = calloc(128 * 16 * 20, 1);
|
||||
for (unsigned i = 0; i < 4; i++) for (int k = 0; k < 4; k++) st[V[i].addr + k] = (uint8_t)(0x10 * (i + 1) + k + 1);
|
||||
CHECK(!nvn_deswizzle(&d, 0, 0, st, lin, 128), "E 解排布失败");
|
||||
for (unsigned i = 0; i < 4; i++) {
|
||||
const uint8_t *p = lin + ((size_t)V[i].z * 16 + V[i].y) * 128 + V[i].x * 4; int ok = 1;
|
||||
for (int k = 0; k < 4; k++) ok &= p[k] == (uint8_t)(0x10 * (i + 1) + k + 1);
|
||||
CHECK(ok, "E 体素 (%u,%u,%u) 未在手算地址 %llu 处取到标记", V[i].x, V[i].y, V[i].z, (unsigned long long)V[i].addr);
|
||||
printf(" E (%2u,%2u,%2u) ← 存储 %5llu %s %s\n", V[i].x, V[i].y, V[i].z, (unsigned long long)V[i].addr, ok ? "✓" : "✗", V[i].how);
|
||||
}
|
||||
size_t nz = 0; for (size_t j = 0; j < 128 * 16 * 20; j++) nz += lin[j] != 0;
|
||||
CHECK(nz == 16, "E 解出非零字节 %zu 期望 16(标记外不该有数据)", nz);
|
||||
free(st); free(lin);
|
||||
// 选角页真调色表的形态:32³ RGBA16F(ser 17 / 16)。块深 32 + 16 = 48 ≥ 16 → 16 片;行 256 字节 = 4 GOB 宽、32 行 = 4 GOB 高、2 层块 → 4·4·2·8192 = 262144
|
||||
// Shape of the real color lookup table on the character select screen: 32³ RGBA16F (ser 17 / 16). Block depth 32 + 16 = 48 ≥ 16 → 16 slices; row 256 bytes = 4 GOBs wide, 32 rows = 4 GOBs high, 2 block layers → 4·4·2·8192 = 262144
|
||||
nvn_texdesc lut = {2, 0x29, 0, 0, 32, 32, 32, 1, 0, 0}; nvn_tex_layout(&lut, &L);
|
||||
CHECK(L.tileH == 0 && L.tileD == 4 && L.size == 4 * 4 * 2 * 8192ull, "E 32³ RGBA16F 块高/块深 %u/%u 存储 %llu,期望 0/4、262144", L.tileH, L.tileD, (unsigned long long)L.size);
|
||||
printf(" E 32³ RGBA16F(选角页调色表形态)块高/块深 %u/%u、存储 %llu(期望 0/4、262144)\n", L.tileH, L.tileD, (unsigned long long)L.size);
|
||||
}
|
||||
|
||||
printf("C/D 真数据对拍(Switch 块线性 vs PC 线性)+ 错块高负对照,阈值 %.0f dB\n", PSNR_PASS);
|
||||
const char *dir = argc > 1 ? argv[1] : getenv("DM_TEX_SAMPLES");
|
||||
char lp[1024]; snprintf(lp, sizeof lp, "%s/list.tsv", dir ? dir : "."); FILE *f = dir ? fopen(lp, "r") : NULL;
|
||||
CHECK(f, "缺样本目录(先 make samples)"); int npair = 0;
|
||||
if (f) { char line[1024]; while (fgets(line, sizeof line, f)) { int i; char path[512], why[256];
|
||||
if (sscanf(line, "%d\t%511[^\t]\t%255[^\n]", &i, path, why) == 3) { real_pair(dir, i, why); npair++; } } fclose(f); }
|
||||
CHECK(npair >= 3, "真数据样本不足 3 对(%d)", npair);
|
||||
printf("%s:%d/%d 项通过(真数据 %d 对)\n", fails ? "红" : "全过", checks - fails, checks, npair);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
Reference in New Issue
Block a user