mirror of
https://github.com/seedds/nxnative.git
synced 2026-11-23 11:39:42 -10:00
opengl: preserve validation, context ownership and clear semantics
Fix the five semantic issues found while reviewing the PR #2819 rework.
Program validation now records the executable and sampler checks, its result
and its log. EGL rejects a conflicting bind with EGL_BAD_ACCESS, leaves the
owner's binding intact, and releases ownership when its thread exits.
Shader rewrites keep a per-translation map and choose unused identifiers,
preserving genuine game names and matching varyings across stages. Texture
clears convert the source value to the destination format without unpack
state and encode earlier deferred framebuffer clears before their writes.
These are general GL fixes, with no game or build gates and no stopgaps.
Extend regress.py to compare GL translations, MSL and table fields, including
runtime captures and compiler fingerprints. Add reusable smoke routes for
Well Dweller and DOOM 3; DOOM's screenshots wait for standing gameplay because
the moving intro cutscene is unsuitable for timed image comparisons.
Checked: 93 focused Python/docs tests; t_gl_imports in both stub modes; Mac
and iPhone source compilation without warnings; Ruff; clang-tidy at baseline.
Full Python lint has identical unrelated environment findings on the baseline.
Full regressions against ba9ce212 on M4 Pro, macOS 27.2.1: Fate and Well
Dweller PASS at 59.9 fps; DOOM 3 PASS at 59.8 -> 59.7 fps, with no new shader
failures or red messages. Fate's three sampler-slot failures remain in both.
iPhone gameplay, combat and later DOOM levels were not tested.
Co-authored-by: Beeven <[email protected]>
This commit is contained in:
1 parent
2d601a4db3
commit
5d54b885ec
13 files changed
+402
-58
No files matched your search
@@ -27,6 +27,10 @@ On the Mac: the language list, the title screen, the opening story and the first
|
||||
|
||||
- **Current:** 93 sources in [`gl_capture.tsv`](gl_capture.tsv) — the runner's sprite, text, lighting, fog and outline programs and their variants — captured on the Mac with `DM_GL_CAPTURE` and translated to one `.metallib` by `gl_shaders.py`. The set is stable from boot through the first room's dialog; a room with an effect no earlier scene used would add one, which the capture table makes the build report.
|
||||
|
||||
## Regression coverage
|
||||
|
||||
[`smoke.tsv`](smoke.tsv) starts from an empty save and advances through language selection and the opening into the first room's dialogue. Checked on update v196608 on an M4 Pro (macOS 27.2.1), comparing the GL host and shaders before and after the general name-restoration, validation, texture-clear and EGL-ownership fixes: both runs reached 6,901 frames in 120 s at 59.9 fps, with matching screenshots and no new red-log messages. The shader table and MSL stayed the same (93 shaders). Later rooms remain unverified.
|
||||
|
||||
## Audio
|
||||
|
||||
- With `DM_AUDIO=1` on the Mac the first room's music plays: 0 underruns after the boot's first 194 padded callbacks.
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Fresh language selection, title and opening story into the first room (GameMaker's ES 1.00 shaders and framebuffer composite).
|
||||
save new
|
||||
keys 10:a,14:a,18:a,22:a,26:a,30:a,34:a,38:a,42:a,46:a,50:a,54:a,58:a,62:a,66:a,70:a,74:a,78:a,82:a,86:a,90:a,94:a,98:a,102:a,106:a,110:a
|
||||
secs 120
|
||||
quick 60
|
||||
reach 1800@100
|
||||
shots 100,115
|
||||
window 90 25
|
||||
hang 30
|
||||
prebuild off
|
||||
|
@@ -34,6 +34,8 @@ No rewriter cut, build-keyed host row or profile switch: everything below is the
|
||||
|
||||
Work folder `<NSP folder>/010029D00E740000-work`: `host.sh` builds the host from a worktree into `d3host` (`REPO=`), `boot.sh <run> [seconds] [VAR=value …]` boots with window and HUD (`SAVE=<dir>` copies a save in, `D3HOST=` another host; every shader it compiles goes to the build's capture folder), `ctl.sh <run> <line> …` drives it through `DM_CTL` (`shot <name>`, `wait <s>`).
|
||||
|
||||
The [`smoke.tsv`](smoke.tsv) regression route starts a new game and waits for the opening cutscene to finish before comparing the standing hangar view at 190 and 205 s. Shots at 120 and 140 s compared different moments of the moving camera and were unsuitable for regression comparisons. On an M4 Pro (macOS 27.2.1), update v327680 reached 12,301 frames in 210 s on both the baseline and the host with the general GL validation, clear, name-restoration and EGL-ownership fixes: 59.8 versus 59.7 fps, matching standing screenshots, no new red-log messages, and the same 66 translated shaders and MSL. Combat and later levels remain unverified.
|
||||
|
||||
- From a fresh save: A at the title (about 18 s), A Campaign, A New Game, A Doom 3, A Marine; A about 25 s later skips the intro movie; the hangar has loaded and its cutscene plays about 30 s after that. Plus is the pause menu (Save Game, Load Game).
|
||||
- `save_ref` in the work folder: a save and the autosave in Mars City Hangar. Its campaign menu has Continue Game first; d-pad Up moves the cursor (the left stick does not), Load Game lists the autosave first.
|
||||
- Play: the left stick moves, the right stick turns.
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Title -> Campaign -> New Game -> Doom 3 -> Marine, skip the intro movie, then wait for the hangar cutscene to finish before comparing the standing view.
|
||||
save new
|
||||
keys 18:a,22:a,26:a,30:a,34:a,60:a
|
||||
secs 210
|
||||
quick 60
|
||||
reach 5400@180
|
||||
shots 190,205
|
||||
window 180 25
|
||||
hang 45
|
||||
prebuild off
|
||||
|
+156
-25
@@ -355,7 +355,7 @@ typedef struct { char name[48]; int slot[2]; uint32_t size, binding; } pblk_t;
|
||||
// vs, fs: the attached shaders, each counted in its refs; deleted: glDeleteProgram flagged it while current (it goes at the next glUseProgram of another);
|
||||
// what the link took from them (si, fn, the uniform table) is the program's own, so attaching, detaching or deleting a shader later leaves the linked program as it is
|
||||
typedef struct {
|
||||
GLuint vs, fs; int linked, deleted; const shinfo *si[2]; __strong id<MTLFunction> fn[2];
|
||||
GLuint vs, fs; int linked, deleted, validated; char validation_log[160]; const shinfo *si[2]; __strong id<MTLFunction> fn[2];
|
||||
int nu; puni_t *u; uint8_t *ub[2]; uint64_t ub_gen[2]; uint32_t serial;
|
||||
pent_t *pc; int npc, cappc;
|
||||
abind_t bind[16]; int nbind; int8_t amap[16];
|
||||
@@ -1727,23 +1727,122 @@ static void tex_storage(GLenum target, GLsizei levels, GLenum ifmt, GLsizei w, G
|
||||
if (t->made || t->defined) tex_drop(t);
|
||||
t->fmt = f; t->w = w; t->h = h; t->d = d; t->slevels = levels; t->smp_dirty = 1;
|
||||
}
|
||||
// glClearTexImage (GL 4.4): every texel of a level, every face, layer and slice, set to one value given in format and type (none: zeros). The value is converted as glTexSubImage2D
|
||||
// converts its data, without the unpack state; Fate/hollow ataraxia REMASTERED clears its new textures so
|
||||
// One scalar of pixel-transfer data. Integer colour/depth components are normalized; stencil indices are integers. memcpy permits unaligned guest data.
|
||||
static double pixel_scalar(const uint8_t *p, GLenum type, int normalized) {
|
||||
switch (type) {
|
||||
case GL_UNSIGNED_BYTE: return normalized ? *p / 255.0 : *p;
|
||||
case GL_BYTE: { int8_t v; memcpy(&v, p, 1); return normalized ? fmax(-1, v / 127.0) : v; }
|
||||
case GL_UNSIGNED_SHORT: { uint16_t v; memcpy(&v, p, 2); return normalized ? v / 65535.0 : v; }
|
||||
case GL_SHORT: { int16_t v; memcpy(&v, p, 2); return normalized ? fmax(-1, v / 32767.0) : v; }
|
||||
case GL_UNSIGNED_INT: { uint32_t v; memcpy(&v, p, 4); return normalized ? v / 4294967295.0 : v; }
|
||||
case GL_INT: { int32_t v; memcpy(&v, p, 4); return normalized ? fmax(-1, v / 2147483647.0) : v; }
|
||||
case GL_HALF_FLOAT: { _Float16 v; memcpy(&v, p, 2); return (double)v; }
|
||||
case GL_FLOAT: { float v; memcpy(&v, p, 4); return v; }
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
static uint32_t pixel_unorm(double v, uint32_t max) { return (uint32_t)llround(fmax(0, fmin(1, v)) * max); }
|
||||
// An unsigned floating component (R11F_G11F_B10F): five exponent bits, six or five fraction bits, including subnormal and non-finite values.
|
||||
static uint32_t pixel_ufloat(double v, int bits) {
|
||||
if (isnan(v)) return (31u << bits) | 1;
|
||||
if (v <= 0) return 0;
|
||||
if (isinf(v)) return 31u << bits;
|
||||
int exp; double frac = frexp(v, &exp); exp += 14;
|
||||
if (exp <= 0) return (uint32_t)llrint(ldexp(v, bits + 14));
|
||||
uint32_t m = (uint32_t)llrint(ldexp(frac, bits + 1));
|
||||
if (m == 2u << bits) { m >>= 1; exp++; }
|
||||
return exp >= 31 ? 31u << bits : ((uint32_t)exp << bits) | (m - (1u << bits));
|
||||
}
|
||||
// Convert one clear value into the actual texture format. Unlike an upload, this consumes no unpack state and never treats differently typed data as storage bytes.
|
||||
static GLenum clear_pixel(int f, GLenum format, GLenum type, const void *data, uint8_t out[16]) {
|
||||
int n;
|
||||
switch (format) {
|
||||
case GL_RED: case GL_GREEN: case GL_BLUE: case GL_ALPHA: case GL_DEPTH_COMPONENT: case GL_STENCIL_INDEX: n = 1; break;
|
||||
case GL_RG: case GL_DEPTH_STENCIL: n = 2; break;
|
||||
case GL_RGB: case 0x80e0 /* BGR */: n = 3; break;
|
||||
case GL_RGBA: case GL_BGRA: n = 4; break;
|
||||
default: return GL_INVALID_ENUM;
|
||||
}
|
||||
if ((g_fmt[f].kind == K_DEPTH) != (format == GL_DEPTH_COMPONENT) || (f == F_D32FS8) != (format == GL_DEPTH_STENCIL) ||
|
||||
(f == F_S8) != (format == GL_STENCIL_INDEX)) return GL_INVALID_OPERATION;
|
||||
static const struct { GLenum type; uint8_t n, bytes, bits[4], rev; } packed[] = {
|
||||
{0x8032, 3, 1, {3, 3, 2}, 0}, {0x8362, 3, 1, {3, 3, 2}, 1},
|
||||
{GL_UNSIGNED_SHORT_5_6_5, 3, 2, {5, 6, 5}, 0}, {0x8364, 3, 2, {5, 6, 5}, 1},
|
||||
{GL_UNSIGNED_SHORT_4_4_4_4, 4, 2, {4, 4, 4, 4}, 0}, {0x8365, 4, 2, {4, 4, 4, 4}, 1},
|
||||
{GL_UNSIGNED_SHORT_5_5_5_1, 4, 2, {5, 5, 5, 1}, 0}, {0x8366, 4, 2, {5, 5, 5, 1}, 1},
|
||||
{0x8035, 4, 4, {8, 8, 8, 8}, 0}, {0x8367, 4, 4, {8, 8, 8, 8}, 1},
|
||||
{0x8036, 4, 4, {10, 10, 10, 2}, 0}, {0x8368, 4, 4, {10, 10, 10, 2}, 1},
|
||||
};
|
||||
int pk = -1, bytes = 0;
|
||||
for (unsigned i = 0; i < sizeof packed / sizeof *packed; i++) if (packed[i].type == type) pk = (int)i;
|
||||
if (pk >= 0) { if (n != packed[pk].n || format == GL_DEPTH_STENCIL) return GL_INVALID_OPERATION; }
|
||||
else {
|
||||
switch (type) {
|
||||
case GL_BYTE: case GL_UNSIGNED_BYTE: bytes = 1; break;
|
||||
case GL_SHORT: case GL_UNSIGNED_SHORT: case GL_HALF_FLOAT: bytes = 2; break;
|
||||
case GL_INT: case GL_UNSIGNED_INT: case GL_FLOAT: bytes = 4; break;
|
||||
case GL_UNSIGNED_INT_24_8: case 0x8dad /* FLOAT_32_UNSIGNED_INT_24_8_REV */: if (format != GL_DEPTH_STENCIL) return GL_INVALID_OPERATION; break;
|
||||
case 0x8c3b /* UNSIGNED_INT_10F_11F_11F_REV */: case 0x8c3e /* UNSIGNED_INT_5_9_9_9_REV */: if (n != 3) return GL_INVALID_OPERATION; break;
|
||||
default: return GL_INVALID_ENUM;
|
||||
}
|
||||
}
|
||||
if (format == GL_DEPTH_STENCIL && type != GL_UNSIGNED_INT_24_8 && type != 0x8dad) return GL_INVALID_OPERATION;
|
||||
memset(out, 0, 16); if (!data) return GL_NO_ERROR;
|
||||
double c[4] = {0, 0, 0, 1}; uint32_t stencil = 0;
|
||||
if (format == GL_DEPTH_STENCIL) {
|
||||
uint32_t v; memcpy(&v, data, 4);
|
||||
if (type == GL_UNSIGNED_INT_24_8) { c[0] = (v >> 8) / 16777215.0; stencil = v & 255; }
|
||||
else { float d; memcpy(&d, data, 4); c[0] = d; memcpy(&stencil, (const uint8_t *)data + 4, 4); stencil &= 255; }
|
||||
} else if (pk >= 0) {
|
||||
uint32_t v = 0; memcpy(&v, data, packed[pk].bytes); int off = packed[pk].rev ? 0 : packed[pk].bytes * 8;
|
||||
for (int i = 0; i < n; i++) { int b = packed[pk].bits[i]; if (!packed[pk].rev) off -= b; c[i] = (double)(v >> off & ((1u << b) - 1)) / ((1u << b) - 1); if (packed[pk].rev) off += b; }
|
||||
} else if (type == 0x8c3b || type == 0x8c3e) {
|
||||
uint32_t v; memcpy(&v, data, 4);
|
||||
if (type == 0x8c3e) for (int i = 0; i < 3; i++) c[i] = ldexp(v >> (i * 9) & 511, (int)(v >> 27) - 24);
|
||||
else for (int i = 0; i < 3; i++) { int b = i == 2 ? 10 : 11; uint16_t h = (uint16_t)((v >> (i * 11) & ((1u << b) - 1)) << (15 - b)); _Float16 a; memcpy(&a, &h, 2); c[i] = (double)a; }
|
||||
} else for (int i = 0; i < n; i++) c[i] = pixel_scalar((const uint8_t *)data + i * bytes, type, format != GL_STENCIL_INDEX);
|
||||
if (format == GL_STENCIL_INDEX) stencil = (uint32_t)(int64_t)c[0] & 255;
|
||||
if (format == GL_GREEN) { c[1] = c[0]; c[0] = 0; } else if (format == GL_BLUE) { c[2] = c[0]; c[0] = 0; }
|
||||
else if (format == GL_ALPHA) { c[3] = c[0]; c[0] = 0; }
|
||||
else if (format == GL_BGRA || format == 0x80e0) { double keep = c[0]; c[0] = c[2]; c[2] = keep; }
|
||||
if (f == F_BGRA8) { double keep = c[0]; c[0] = c[2]; c[2] = keep; }
|
||||
switch (f) {
|
||||
case F_RGBA8: case F_BGRA8: case F_SRGBA8: for (int i = 0; i < 4; i++) out[i] = (uint8_t)pixel_unorm(c[i], 255); break;
|
||||
case F_R8: case F_L8: out[0] = (uint8_t)pixel_unorm(c[0], 255); break;
|
||||
case F_A8: out[0] = (uint8_t)pixel_unorm(c[3], 255); break;
|
||||
case F_RG8: case F_LA8: out[0] = (uint8_t)pixel_unorm(c[0], 255); out[1] = (uint8_t)pixel_unorm(c[f == F_LA8 ? 3 : 1], 255); break;
|
||||
case F_RGBA16F: case F_R16F: case F_RG16F:
|
||||
for (int i = 0; i < g_fmt[f].bytes / 2; i++) { _Float16 v = (_Float16)c[i]; memcpy(out + 2 * i, &v, 2); } break;
|
||||
case F_RGBA32F: case F_R32F: case F_RG32F:
|
||||
for (int i = 0; i < g_fmt[f].bytes / 4; i++) { float v = (float)c[i]; memcpy(out + 4 * i, &v, 4); } break;
|
||||
case F_RGBA16: for (int i = 0; i < 4; i++) { uint16_t v = (uint16_t)pixel_unorm(c[i], 65535); memcpy(out + 2 * i, &v, 2); } break;
|
||||
case F_RGB10A2: { uint32_t v = pixel_unorm(c[0], 1023) | pixel_unorm(c[1], 1023) << 10 | pixel_unorm(c[2], 1023) << 20 | pixel_unorm(c[3], 3) << 30; memcpy(out, &v, 4); break; }
|
||||
case F_RG11B10F: { uint32_t v = pixel_ufloat(c[0], 6) | pixel_ufloat(c[1], 6) << 11 | pixel_ufloat(c[2], 5) << 22; memcpy(out, &v, 4); break; }
|
||||
case F_D16: { uint16_t v = (uint16_t)pixel_unorm(c[0], 65535); memcpy(out, &v, 2); break; }
|
||||
case F_D32F: case F_D32FS8: { float v = (float)fmax(0, fmin(1, c[0])); memcpy(out, &v, 4); if (f == F_D32FS8) memcpy(out + 4, &stencil, 4); break; }
|
||||
case F_S8: out[0] = (uint8_t)stencil; break;
|
||||
default: return GL_INVALID_OPERATION;
|
||||
}
|
||||
return GL_NO_ERROR;
|
||||
}
|
||||
// glClearTexImage (GL 4.4): convert one value, then fill every face, layer and slice in command order. NULL data means storage zeroes, including alpha.
|
||||
GLB(glClearTexImage, void, GLuint name, GLint level, GLenum format, GLenum type, const void *data) {
|
||||
tex_t *t = tex_of(name);
|
||||
if (!t || level < 0 || level >= MAXLV) { gl_error(GL_INVALID_OPERATION); return; }
|
||||
if (t->fmt < 0 || g_fmt[t->fmt].kind == K_BLOCK) { if (t->fmt >= 0) gl_error(GL_INVALID_OPERATION); else RED1("glClearTexImage of texture %u, which has no format yet", name); return; }
|
||||
if (t->fmt < 0 || g_fmt[t->fmt].kind == K_BLOCK) { gl_error(GL_INVALID_OPERATION); return; }
|
||||
uint8_t one[16]; GLenum error = clear_pixel(t->fmt, format, type, data, one);
|
||||
if (error) { gl_error(error); return; }
|
||||
@autoreleasepool {
|
||||
if (g_pend_clear.bits) clears_flush();
|
||||
if (!t->made) tex_make(t, 0);
|
||||
if (!t->tex || level >= t->levels) { gl_error(GL_INVALID_OPERATION); return; }
|
||||
int f = t->fmt, swap = S.unpack_swap; size_t pitch, bytes = g_fmt[f].bytes;
|
||||
S.unpack_swap = 0; uint8_t *one = pixels_convert(data, 1, 1, format, type, f, sub_cv(f, format, type), &pitch); S.unpack_swap = swap;
|
||||
int f = t->fmt; size_t bytes = g_fmt[f].bytes;
|
||||
uint32_t w = umax(1, t->w >> level), h = umax(1, (t->target == GL_TEXTURE_CUBE_MAP ? t->w : t->h) >> level);
|
||||
uint32_t slices = t->target == GL_TEXTURE_3D ? umax(1, t->d >> level) : 1, layers = t->target == GL_TEXTURE_2D_ARRAY ? t->d : (uint32_t)tex_faces(t);
|
||||
size_t lp = fmt_pitch(f, w); uint8_t *img = zalloc(lp * h);
|
||||
for (uint32_t y = 0; y < h; y++) for (uint32_t x = 0; x < w; x++) memcpy(img + y * lp + x * bytes, one, bytes);
|
||||
for (uint32_t k = 0; k < layers; k++) for (uint32_t z = 0; z < slices; z++) tex_write(t, (int)k, level, 0, 0, z, w, h, img, lp);
|
||||
free(one); free(img);
|
||||
free(img);
|
||||
}
|
||||
}
|
||||
GL(glTexStorage2D, void, GLenum target, GLsizei levels, GLenum ifmt, GLsizei w, GLsizei h) { tex_storage(target, levels, ifmt, w, h, 1); }
|
||||
@@ -2140,6 +2239,7 @@ GL(glDetachShader, void, GLuint pr, GLuint sh) {
|
||||
if (p->vs == sh) shader_release(&p->vs); else if (p->fs == sh) shader_release(&p->fs); else gl_error(GL_INVALID_OPERATION); // not attached to it
|
||||
}
|
||||
static void prog_clear(prog_t *p) {
|
||||
p->validated = 0; p->validation_log[0] = 0;
|
||||
for (int i = 0; i < p->npc; i++) if (p->pc[i].pso) CFRelease(p->pc[i].pso);
|
||||
free(p->pc); p->pc = NULL; p->npc = p->cappc = 0;
|
||||
free(p->u); p->u = NULL; p->nu = 0; free(p->ub[0]); free(p->ub[1]); p->ub[0] = p->ub[1] = NULL; p->fn[0] = p->fn[1] = nil; p->linked = 0;
|
||||
@@ -2200,14 +2300,28 @@ GL(glBindAttribLocation, void, GLuint pr, GLuint index, const GLchar *name) {
|
||||
if (j == p->nbind) { strlcpy(p->bind[j].name, name, sizeof p->bind[j].name); p->nbind++; }
|
||||
p->bind[j].index = (int)index;
|
||||
}
|
||||
// A program that links validates (GL_VALIDATE_STATUS, as its link status): Fate/hollow ataraxia REMASTERED validates each program after linking it
|
||||
GL(glValidateProgram, void, GLuint pr) { (void)SP_CHECK(pr, 1); }
|
||||
// Validation is a snapshot of the linked executable and its active samplers' current units. Different sampler types cannot share a unit, and each stage must fit its limits.
|
||||
GL(glValidateProgram, void, GLuint pr) {
|
||||
if (!SP_CHECK(pr, 1)) return;
|
||||
prog_t *p = prog_of(pr); p->validated = 0; p->validation_log[0] = 0;
|
||||
const char *why = p->linked ? NULL : "program has no linked executable";
|
||||
uint8_t types[NUNITS] = {0}; int counts[2] = {0};
|
||||
for (int i = 0; !why && i < p->nu; i++) {
|
||||
const puni_t *u = &p->u[i]; if (!is_samp(u->type)) continue;
|
||||
if (u->unit < 0 || u->unit >= NUNITS) why = "sampler unit is outside GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS";
|
||||
else if (types[u->unit] && types[u->unit] != u->type) why = "samplers of different types use the same texture unit";
|
||||
else { types[u->unit] = u->type; for (int st = 0; st < 2; st++) counts[st] += u->slot[st] >= 0; }
|
||||
}
|
||||
if (!why && (counts[0] > 16 || counts[1] > 32 || counts[0] + counts[1] > NUNITS)) why = "active samplers exceed the texture image unit limits";
|
||||
if (why) strlcpy(p->validation_log, why, sizeof p->validation_log); else p->validated = 1;
|
||||
}
|
||||
GL(glGetProgramiv, void, GLuint pr, GLenum p, GLint *v) {
|
||||
if (!SP_CHECK(pr, 1)) { *v = 0; return; }
|
||||
prog_t *x = prog_of(pr);
|
||||
switch (p) {
|
||||
case GL_LINK_STATUS: case GL_VALIDATE_STATUS: *v = 1; return; // as glGetShaderiv's compile status
|
||||
case GL_INFO_LOG_LENGTH: *v = 0; return;
|
||||
case GL_LINK_STATUS: *v = 1; return; // as glGetShaderiv's compile status
|
||||
case GL_VALIDATE_STATUS: *v = x->validated; return;
|
||||
case GL_INFO_LOG_LENGTH: *v = x->validation_log[0] ? (GLint)strlen(x->validation_log) + 1 : 0; return;
|
||||
case GL_ACTIVE_UNIFORMS: *v = x->nu; return;
|
||||
case GL_ACTIVE_UNIFORM_MAX_LENGTH: { int m = 0; for (int i = 0; i < x->nu; i++) m = (int)umax(m, (uint32_t)strlen(x->u[i].name) + 4); *v = m; return; }
|
||||
case GL_ATTACHED_SHADERS: *v = (x->vs != 0) + (x->fs != 0); return;
|
||||
@@ -2237,7 +2351,12 @@ GL(glGetAttribLocation, GLint, GLuint pr, const GLchar *name) {
|
||||
for (int i = 0; i < p->si[0]->na; i++) if (!strcmp(p->si[0]->a[i].name, name)) return p->amap[p->si[0]->a[i].slot];
|
||||
return -1;
|
||||
}
|
||||
GL(glGetProgramInfoLog, void, GLuint pr, GLsizei size, GLsizei *len, GLchar *log) { (void)pr; if (len) *len = 0; if (log && size > 0) log[0] = 0; }
|
||||
GL(glGetProgramInfoLog, void, GLuint pr, GLsizei size, GLsizei *len, GLchar *log) {
|
||||
if (len) *len = 0;
|
||||
prog_t *p = prog_of(pr); if (!p) { (void)SP_CHECK(pr, 1); return; }
|
||||
if (size < 0) { gl_error(GL_INVALID_VALUE); return; }
|
||||
if (log && size > 0) { strlcpy(log, p->validation_log, (size_t)size); if (len) *len = (GLsizei)strlen(log); }
|
||||
}
|
||||
// The uniforms in the order of the program's table (both stages merged, samplers among them): an array's name ends in [0], as GL reports it (LÖVE's mapActiveUniforms)
|
||||
GL(glGetActiveUniform, void, GLuint pr, GLuint index, GLsizei size, GLsizei *len, GLint *count, GLenum *type, GLchar *name) {
|
||||
prog_t *p = prog_of(pr);
|
||||
@@ -2388,6 +2507,7 @@ GL(glGetUniformuiv, void, GLuint pr, GLint loc, GLuint *v) { uni_read(pr, loc, v
|
||||
|
||||
// ---------- EGL ----------
|
||||
#define EGL_TRUE 1
|
||||
#define EGL_FALSE 0
|
||||
static struct { int init; int surface; uint32_t w, h; } g_egl;
|
||||
static uint64_t g_frames;
|
||||
// Every 300 frames: draws, passes, uploads; every 1800: memory (the process footprint, Metal's allocations, the GL objects alive), as the NVN layer's memory report
|
||||
@@ -2451,7 +2571,8 @@ EGL(eglQueryString, const char *, EGLDisplay d, EGLint name) {
|
||||
switch (name) { case 0x3053: return "NVIDIA"; case 0x3054: return "1.5"; case 0x3055: return "EGL_KHR_create_context"; case 0x308d: return "OpenGL"; } // VENDOR, VERSION, EXTENSIONS, CLIENT_APIS
|
||||
return NULL;
|
||||
}
|
||||
EGL(eglGetError, EGLint, void) { return 0x3000; } // SUCCESS
|
||||
static __thread EGLint t_egl_error = 0x3000; // SUCCESS: EGL errors belong to the calling thread and clear when read
|
||||
EGL(eglGetError, EGLint, void) { EGLint e = t_egl_error; t_egl_error = 0x3000; return e; }
|
||||
EGL(eglQueryAPI, EGLenum, void) { return 0x30a2; } // OPENGL_API
|
||||
EGL(eglWaitNative, EGLBoolean, EGLint engine) { (void)engine; return EGL_TRUE; }
|
||||
EGL(eglWaitGL, EGLBoolean, void) { return EGL_TRUE; }
|
||||
@@ -2474,25 +2595,35 @@ EGL(eglCreateWindowSurface, EGLSurface, EGLDisplay d, EGLConfig cfg, void *win,
|
||||
return (EGLSurface)(uintptr_t)3;
|
||||
}
|
||||
EGL(eglDestroySurface, EGLBoolean, EGLDisplay d, EGLSurface s) { (void)d; (void)s; return EGL_TRUE; }
|
||||
// What a thread made current, which EGL keeps per thread (eglGetCurrentContext, eglGetCurrentDisplay, eglGetCurrentSurface answer it; a glad loader asks for them through
|
||||
// eglGetProcAddress). The layer has one context: a thread that makes it current takes it from the thread it was current on (EGL would refuse with EGL_BAD_ACCESS), which
|
||||
// then has none. gen: the binding's number (g_cur_gen when it was made); an older one has been taken. eglMakeCurrent with no context and eglReleaseThread release the thread's binding
|
||||
static __thread struct { EGLDisplay dpy; EGLContext ctx; EGLSurface draw, read; uint64_t gen; } t_cur;
|
||||
static _Atomic uint64_t g_cur_gen;
|
||||
static int cur_held(void) { return t_cur.ctx && t_cur.gen == atomic_load(&g_cur_gen); }
|
||||
// The one context has one owner. A conflicting bind fails without changing either thread's binding; an explicit release or thread exit permits a transfer.
|
||||
static __thread struct { EGLDisplay dpy; EGLContext ctx; EGLSurface draw, read; } t_cur;
|
||||
static pthread_mutex_t g_cur_mu = PTHREAD_MUTEX_INITIALIZER;
|
||||
static void *g_cur_owner;
|
||||
static pthread_key_t g_cur_key;
|
||||
static pthread_once_t g_cur_once = PTHREAD_ONCE_INIT;
|
||||
static int g_cur_key_ok;
|
||||
static void cur_release(void *binding) { pthread_mutex_lock(&g_cur_mu); if (g_cur_owner == binding) g_cur_owner = NULL; pthread_mutex_unlock(&g_cur_mu); }
|
||||
static void cur_key_init(void) { g_cur_key_ok = pthread_key_create(&g_cur_key, cur_release) == 0; }
|
||||
EGL(eglMakeCurrent, EGLBoolean, EGLDisplay d, EGLSurface dr, EGLSurface rd, EGLContext c) {
|
||||
static pthread_t th; static int known, sized;
|
||||
if (c) { t_cur.dpy = d; t_cur.ctx = c; t_cur.draw = dr; t_cur.read = rd; t_cur.gen = atomic_fetch_add(&g_cur_gen, 1) + 1; }
|
||||
else memset(&t_cur, 0, sizeof t_cur);
|
||||
pthread_once(&g_cur_once, cur_key_init);
|
||||
if (!g_cur_key_ok) { t_egl_error = 0x3003; return EGL_FALSE; } // BAD_ALLOC
|
||||
pthread_mutex_lock(&g_cur_mu);
|
||||
if (c && g_cur_owner && g_cur_owner != &t_cur) { pthread_mutex_unlock(&g_cur_mu); t_egl_error = 0x3002; return EGL_FALSE; } // BAD_ACCESS
|
||||
if (c) {
|
||||
if (pthread_setspecific(g_cur_key, &t_cur)) { pthread_mutex_unlock(&g_cur_mu); t_egl_error = 0x3003; return EGL_FALSE; }
|
||||
g_cur_owner = &t_cur; t_cur.dpy = d; t_cur.ctx = c; t_cur.draw = dr; t_cur.read = rd;
|
||||
} else { if (g_cur_owner == &t_cur) g_cur_owner = NULL; pthread_setspecific(g_cur_key, NULL); memset(&t_cur, 0, sizeof t_cur); }
|
||||
if (c && dr) { pthread_t me = pthread_self(); if (!known || !pthread_equal(th, me)) { th = me; known = 1; OLOG("context current on a new thread"); } }
|
||||
// a context's viewport and scissor box start as its first drawable's size (LÖVE reads them back at start)
|
||||
if (c && dr && !sized && g_win.made) { sized = 1; if (!S.vp[2] && !S.vp[3]) { S.vp[2] = S.sc[2] = g_win.w; S.vp[3] = S.sc[3] = g_win.h; } }
|
||||
pthread_mutex_unlock(&g_cur_mu);
|
||||
return EGL_TRUE;
|
||||
}
|
||||
EGL(eglReleaseThread, EGLBoolean, void) { memset(&t_cur, 0, sizeof t_cur); return EGL_TRUE; }
|
||||
EGL(eglGetCurrentContext, EGLContext, void) { return cur_held() ? t_cur.ctx : NULL; }
|
||||
EGL(eglGetCurrentDisplay, EGLDisplay, void) { return cur_held() ? t_cur.dpy : NULL; }
|
||||
EGL(eglGetCurrentSurface, EGLSurface, EGLint which) { return !cur_held() ? NULL : which == 0x3059 ? t_cur.draw : which == 0x305a ? t_cur.read : NULL; } // DRAW, READ
|
||||
EGL(eglReleaseThread, EGLBoolean, void) { if (t_cur.ctx) h_eglMakeCurrent(NULL, NULL, NULL, NULL); t_egl_error = 0x3000; return EGL_TRUE; }
|
||||
EGL(eglGetCurrentContext, EGLContext, void) { return t_cur.ctx; }
|
||||
EGL(eglGetCurrentDisplay, EGLDisplay, void) { return t_cur.dpy; }
|
||||
EGL(eglGetCurrentSurface, EGLSurface, EGLint which) { return which == 0x3059 ? t_cur.draw : which == 0x305a ? t_cur.read : NULL; } // DRAW, READ
|
||||
EGL(eglSwapInterval, EGLBoolean, EGLDisplay d, EGLint n) { (void)d; if (n != S.swap_interval) { GLOG("swap interval %d", n); S.swap_interval = n; } return EGL_TRUE; }
|
||||
// DM_GL_RENDERPROGS=<job file> (the NSP script's shader capture, dm/gfx/tools/idtech4_programs.py): id Tech 4's BFG renderer converts a render program to GLSL only when it first uses
|
||||
// it, so a capture run that only plays the game gets the ones it drew with. The job names the renderer's own FindVertexShader / FindFragmentShader (this, name) in main, the slot
|
||||
|
||||
@@ -491,9 +491,11 @@ static void test_sampler_objects(void) {
|
||||
|
||||
// Extension names by gl_aliases.h (Fate/hollow ataraxia REMASTERED asks for its framebuffer functions by their EXT names, issue #2818), never by a stripped suffix; binds that
|
||||
// make a name glGen* never gave; EGL's current context, display and surfaces, per thread
|
||||
typedef struct { void *before, *after; EGLBoolean bound; EGLint error, next_error; } egl_attempt;
|
||||
static void *other_thread(void *arg) {
|
||||
void **seen = arg; seen[0] = h_eglGetCurrentContext(); // current on the main thread, not here
|
||||
h_eglMakeCurrent((EGLDisplay)&g_egl, (EGLSurface)3, (EGLSurface)3, (EGLContext)2); seen[1] = h_eglGetCurrentContext(); // taken here
|
||||
egl_attempt *seen = arg; seen->before = h_eglGetCurrentContext();
|
||||
seen->bound = h_eglMakeCurrent((EGLDisplay)&g_egl, (EGLSurface)3, (EGLSurface)3, (EGLContext)2);
|
||||
seen->after = h_eglGetCurrentContext(); seen->error = h_eglGetError(); seen->next_error = h_eglGetError();
|
||||
return NULL;
|
||||
}
|
||||
static void test_extension_names_and_egl(void) {
|
||||
@@ -516,18 +518,43 @@ static void test_extension_names_and_egl(void) {
|
||||
h_eglMakeCurrent(d, (EGLSurface)3, (EGLSurface)4, (EGLContext)2);
|
||||
assert(h_eglGetCurrentContext() == (EGLContext)2 && h_eglGetCurrentDisplay() == d);
|
||||
assert(h_eglGetCurrentSurface(0x3059) == (EGLSurface)3 && h_eglGetCurrentSurface(0x305a) == (EGLSurface)4 && !h_eglGetCurrentSurface(0x3000));
|
||||
void *seen[2]; pthread_t th; pthread_create(&th, NULL, other_thread, seen); pthread_join(th, NULL);
|
||||
assert(!seen[0] && seen[1] == (EGLContext)2 && !h_eglGetCurrentContext()); // the other thread took the context: none here
|
||||
h_eglMakeCurrent(d, (EGLSurface)3, (EGLSurface)3, (EGLContext)2); assert(h_eglGetCurrentContext() == (EGLContext)2);
|
||||
egl_attempt seen = {0}; pthread_t th; pthread_create(&th, NULL, other_thread, &seen); pthread_join(th, NULL);
|
||||
assert(!seen.before && !seen.bound && !seen.after && seen.error == 0x3002 && seen.next_error == 0x3000); // BAD_ACCESS, cleared on read
|
||||
assert(h_eglGetCurrentContext() == (EGLContext)2 && h_eglGetCurrentSurface(0x305a) == (EGLSurface)4 && h_eglGetError() == 0x3000);
|
||||
h_eglMakeCurrent(d, NULL, NULL, NULL); assert(!h_eglGetCurrentContext() && !h_eglGetCurrentDisplay() && !h_eglGetCurrentSurface(0x3059));
|
||||
pthread_create(&th, NULL, other_thread, &seen); pthread_join(th, NULL);
|
||||
assert(!seen.before && seen.bound && seen.after == (EGLContext)2 && seen.error == 0x3000); // released here, acquired there; thread exit releases it too
|
||||
h_eglMakeCurrent(d, (EGLSurface)3, (EGLSurface)3, (EGLContext)2); h_eglReleaseThread(); assert(!h_eglGetCurrentContext());
|
||||
}
|
||||
|
||||
// The other calls Fate/hollow ataraxia REMASTERED makes that the layer lacked (issue #2818): glValidateProgram after each link, glLineWidth, glClearTexImage on its new textures
|
||||
static void test_program_validation(void) {
|
||||
static shsamp samplers[] = {{"flat", 0, T_SAMP2D}, {"cube", 1, T_SAMPCUBE}};
|
||||
static shinfo vsi = {.ub_slot = -1}, fsi = {.frag = 1, .ub_slot = -1, .nt = 2, .t = samplers};
|
||||
GLuint pr = h_glCreateProgram(), vs = h_glCreateShader(GL_VERTEX_SHADER), fs = h_glCreateShader(GL_FRAGMENT_SHADER), was = S.prog;
|
||||
shader_of(vs)->si = &vsi; shader_of(vs)->fn = (id)[NSObject new]; shader_of(fs)->si = &fsi; shader_of(fs)->fn = (id)[NSObject new];
|
||||
h_glAttachShader(pr, vs); h_glAttachShader(pr, fs); h_glLinkProgram(pr); h_glUseProgram(pr);
|
||||
GLint v; h_glGetProgramiv(pr, GL_VALIDATE_STATUS, &v); assert(v == 0); // no validation yet
|
||||
h_glValidateProgram(pr); h_glGetProgramiv(pr, GL_VALIDATE_STATUS, &v); assert(v == 0); // both types start at unit 0
|
||||
char log[160] = {0}; GLsizei len = 0; h_glGetProgramInfoLog(pr, sizeof log, &len, log); assert(strstr(log, "different types"));
|
||||
h_glGetProgramiv(pr, GL_INFO_LOG_LENGTH, &v); assert(v == len + 1);
|
||||
GLint cube = h_glGetUniformLocation(pr, "cube"); h_glUniform1i(cube, 1);
|
||||
h_glValidateProgram(pr); h_glGetProgramiv(pr, GL_VALIDATE_STATUS, &v); assert(v == 1);
|
||||
h_glUniform1i(cube, NUNITS); h_glGetProgramiv(pr, GL_VALIDATE_STATUS, &v); assert(v == 1); // the previous validation's snapshot
|
||||
h_glValidateProgram(pr); h_glGetProgramiv(pr, GL_VALIDATE_STATUS, &v); assert(v == 0);
|
||||
h_glGetProgramInfoLog(pr, sizeof log, &len, log); assert(strstr(log, "outside"));
|
||||
h_glUniform1i(cube, -1); h_glValidateProgram(pr); h_glGetProgramiv(pr, GL_VALIDATE_STATUS, &v); assert(v == 0);
|
||||
h_glUniform1i(cube, 1); h_glValidateProgram(pr); h_glGetProgramiv(pr, GL_VALIDATE_STATUS, &v); assert(v == 1);
|
||||
h_glGetProgramInfoLog(pr, sizeof log, &len, log); assert(len == 0 && !log[0]);
|
||||
h_glLinkProgram(pr); h_glGetProgramiv(pr, GL_VALIDATE_STATUS, &v); assert(v == 0); // relinking invalidates validation
|
||||
h_glUseProgram(was); h_glDeleteProgram(pr); h_glDeleteShader(vs); h_glDeleteShader(fs); assert(h_glGetError() == GL_NO_ERROR);
|
||||
}
|
||||
|
||||
static void test_fate_calls(void) {
|
||||
assert(import("glValidateProgram") == (void *)h_glValidateProgram && import("glLineWidth") == (void *)h_glLineWidth);
|
||||
assert(import("glClearTexImage") == (void *)h_glClearTexImage_bs);
|
||||
GLuint pr = h_glCreateProgram(); h_glValidateProgram(pr); GLint v = 0; h_glGetProgramiv(pr, GL_VALIDATE_STATUS, &v); assert(v == 1 && h_glGetError() == GL_NO_ERROR);
|
||||
GLuint pr = h_glCreateProgram(); h_glValidateProgram(pr); GLint v = 0; h_glGetProgramiv(pr, GL_VALIDATE_STATUS, &v); assert(v == 0 && h_glGetError() == GL_NO_ERROR);
|
||||
char log[160]; GLsizei len; h_glGetProgramInfoLog(pr, sizeof log, &len, log); assert(len > 0 && strstr(log, "linked"));
|
||||
h_glDeleteProgram(pr); h_glLineWidth(1);
|
||||
// a 4x2 RGBA8 texture of two levels: level 0 cleared to one RGBA value, level 1 to one RGB value (alpha 1), then to zeros (no data)
|
||||
GLuint t; h_glGenTextures(1, &t); h_glBindTexture(GL_TEXTURE_2D, t); h_glTexStorage2D(GL_TEXTURE_2D, 2, GL_RGBA8, 4, 2);
|
||||
@@ -540,6 +567,31 @@ static void test_fate_calls(void) {
|
||||
h_glClearTexImage(t, 1, GL_RGBA, GL_UNSIGNED_BYTE, NULL); [x->tex getBytes:px bytesPerRow:8 fromRegion:MTLRegionMake2D(0, 0, 2, 1) mipmapLevel:1]; assert(!px[0] && !px[1]);
|
||||
h_glClearTexImage(t, 2, GL_RGBA, GL_UNSIGNED_BYTE, rgba); assert(h_glGetError() == GL_INVALID_OPERATION); // a level the texture does not have
|
||||
h_glClearTexImage(t + 100, 0, GL_RGBA, GL_UNSIGNED_BYTE, rgba); assert(h_glGetError() == GL_INVALID_OPERATION); // no such texture
|
||||
const float red[4] = {1, 0, 0, 1};
|
||||
h_glPixelStorei(0xcf0, 1); h_glPixelStorei(GL_UNPACK_ROW_LENGTH, 99); // clear values have no unpack state
|
||||
h_glClearTexImage(t, 0, GL_RGBA, GL_FLOAT, red);
|
||||
assert(S.unpack_swap == 1 && S.unpack_row == 99); h_glPixelStorei(0xcf0, 0); h_glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
|
||||
[x->tex getBytes:px bytesPerRow:16 fromRegion:MTLRegionMake2D(0, 0, 4, 2) mipmapLevel:0];
|
||||
for (int i = 0; i < 8; i++) assert(px[i] == 0xff0000ffu);
|
||||
const uint8_t bgra[4] = {255, 128, 0, 255}; h_glClearTexImage(t, 0, GL_BGRA, GL_UNSIGNED_BYTE, bgra);
|
||||
[x->tex getBytes:px bytesPerRow:16 fromRegion:MTLRegionMake2D(0, 0, 4, 2) mipmapLevel:0];
|
||||
for (int i = 0; i < 8; i++) assert(px[i] == 0xffff8000u);
|
||||
uint16_t half_red = 32768; h_glClearTexImage(t, 0, GL_RED, GL_UNSIGNED_SHORT, &half_red);
|
||||
[x->tex getBytes:px bytesPerRow:16 fromRegion:MTLRegionMake2D(0, 0, 4, 2) mipmapLevel:0];
|
||||
for (int i = 0; i < 8; i++) assert(px[i] == 0xff000080u);
|
||||
h_glClearTexImage(t, 0, GL_DEPTH_COMPONENT, GL_FLOAT, red); assert(h_glGetError() == GL_INVALID_OPERATION);
|
||||
GLuint fb; h_glGenFramebuffers(1, &fb); h_glBindFramebuffer(GL_FRAMEBUFFER, fb);
|
||||
h_glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, t, 0);
|
||||
h_glClearColor(1, 0, 0, 1); h_glClear(GL_COLOR_BUFFER_BIT);
|
||||
const uint8_t blue[4] = {0, 0, 255, 255}; h_glClearTexImage(t, 0, GL_RGBA, GL_UNSIGNED_BYTE, blue); h_glFinish();
|
||||
[x->tex getBytes:px bytesPerRow:16 fromRegion:MTLRegionMake2D(0, 0, 4, 2) mipmapLevel:0];
|
||||
for (int i = 0; i < 8; i++) assert(px[i] == 0xffff0000u); // the later texture clear wins
|
||||
h_glBindFramebuffer(GL_FRAMEBUFFER, 0); h_glDeleteFramebuffers(1, &fb);
|
||||
h_glDeleteTextures(1, &t);
|
||||
h_glGenTextures(1, &t); h_glBindTexture(GL_TEXTURE_2D, t); h_glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA16F, 1, 1);
|
||||
h_glClearTexImage(t, 0, GL_BGRA, GL_UNSIGNED_BYTE, bgra);
|
||||
_Float16 fp[4]; [tex_of(t)->tex getBytes:fp bytesPerRow:8 fromRegion:MTLRegionMake2D(0, 0, 1, 1) mipmapLevel:0];
|
||||
assert(fp[0] == 0 && fabs((double)fp[1] - 128.0 / 255) < 0.001 && fp[2] == 1 && fp[3] == 1);
|
||||
h_glDeleteTextures(1, &t);
|
||||
}
|
||||
|
||||
@@ -651,6 +703,7 @@ int main(int argc, char **argv) {
|
||||
test_doom3();
|
||||
test_sampler_objects();
|
||||
test_extension_names_and_egl();
|
||||
test_program_validation();
|
||||
test_fate_calls();
|
||||
|
||||
unsigned long sz;
|
||||
|
||||
+24
-14
@@ -126,11 +126,22 @@ def function_semicolons(t):
|
||||
k += 1
|
||||
return ''.join(out) + t[i:]
|
||||
|
||||
def fixups(t, stage):
|
||||
def rename_identifier(t, name, base, renamed, keep_calls=False):
|
||||
"""Rename an identifier into a free name, recording only replacements made in this translation."""
|
||||
pattern = r'\b' + re.escape(name) + r'\b' + (r'(?!\s*\()' if keep_calls else '')
|
||||
if not re.search(pattern, t): return t
|
||||
used = set(re.findall(r'\b\w+\b', t))
|
||||
new, i = base, 0
|
||||
while new in used: i += 1; new = f'{base}_{i}'
|
||||
renamed[new] = name
|
||||
return re.sub(pattern, new, t)
|
||||
|
||||
def fixups(t, stage, renamed=None):
|
||||
if renamed is None: renamed = {}
|
||||
t = function_semicolons(t)
|
||||
for a, b in OLD_TEX: t = re.sub(a, b, t)
|
||||
t = re.sub(BUILTIN_DECL, '', t, flags=re.M)
|
||||
t = re.sub(r'\bsampler\b', 'dm_sampler', t)
|
||||
t = rename_identifier(t, 'sampler', 'dm_sampler', renamed)
|
||||
if stage == 'vert': t = own_name(t, r'^[ \t]*out\s+vec4\s+gl_FrontColor\s*;', 'gl_FrontColor', 'dm_Color', 'out vec4 dm_Color;')
|
||||
else:
|
||||
t = own_name(t, r'^[ \t]*in\s+vec4\s+gl_Color\s*;', 'gl_Color', 'dm_Color', 'in vec4 dm_Color;')
|
||||
@@ -167,40 +178,39 @@ def uni_members(refl, ms, prefix, base, f, bools):
|
||||
# GLSL ES 1.00, with its version statement (#version 100) or, as GameMaker's runner writes it, without one (Well Dweller's 93 run-time shaders): `attribute`, `varying`, `texture2D`, `gl_FragColor`, precision statements and
|
||||
# lowp / mediump / highp qualifiers. SPIR-V needs ES 3.10 or newer, so the text is rewritten before preprocessing (glslang rejects those keywords in 310). Metal has no use for the precision qualifiers;
|
||||
# the texture functions stay for fixups(), which renames them after preprocessing (a macro could hide one)
|
||||
def es100(t, stage):
|
||||
def es100(t, stage, renamed=None):
|
||||
if renamed is None: renamed = {}
|
||||
t = re.sub(r'^[ \t]*precision[ \t]+\w+[ \t]+\w+[ \t]*;\r?[ \t]*\r?\n', '', t, flags=re.M)
|
||||
t = re.sub(r'\b(?:lowp|mediump|highp)\b[ \t]*', '', t)
|
||||
t = re.sub(r'\battribute\b', 'in', t)
|
||||
t = re.sub(r'\bvarying\b', 'out' if stage == 'vert' else 'in', t)
|
||||
if stage == 'frag' and 'gl_FragColor' in t:
|
||||
t = 'out vec4 gm_FragColor;\n' + t.replace('gl_FragColor', 'gm_FragColor')
|
||||
t = re.sub(r'\bsample\b', 'gm_sample', t) # `sample` became a reserved word after ES 1.00 (GameMaker's sprite shaders use it as a variable)
|
||||
t = rename_identifier(t, 'sample', 'gm_sample', renamed) # `sample` became a reserved word after ES 1.00 (GameMaker's sprite shaders use it as a variable)
|
||||
# `texture` became a built-in function after ES 1.00, and a name declared `texture` redefines it (Fate/hollow ataraxia REMASTERED: `uniform sampler2D texture;`); a call stays
|
||||
t = re.sub(r'\btexture\b(?!\s*\()', 'dm_texture', t)
|
||||
t = rename_identifier(t, 'texture', 'dm_texture', renamed, keep_calls=True)
|
||||
return '#version 310 es\nprecision highp float;\nprecision highp int;\n' + t
|
||||
|
||||
# The game's names that the rewrite renames (es100, fixups): the table rows give them back as the game wrote them, since the host finds attributes, uniforms and samplers by the
|
||||
# game's name (glGetAttribLocation, glGetUniformLocation); the key is the hash of the game's own source
|
||||
RENAMED = {'gm_sample': 'sample', 'dm_texture': 'texture', 'dm_sampler': 'sampler'}
|
||||
|
||||
def game_names(f):
|
||||
def game_names(f, renamed):
|
||||
"""table fields with the renamed names in their name part (a:, o:, u:, t:, n: up to the '=') given back"""
|
||||
def back(x):
|
||||
k, sep, rest = x.partition('=')
|
||||
return re.sub(r'\b(' + '|'.join(RENAMED) + r')\b', lambda m: RENAMED[m.group(1)], k) + sep + rest
|
||||
return re.sub(r'\b\w+\b', lambda m: renamed.get(m.group(0), m.group(0)), k) + sep + rest
|
||||
return [back(x) for x in f]
|
||||
|
||||
def translate(src, stage, key, tmp):
|
||||
"""GLSL → MSL; returns (msl path, table fields) or an error string"""
|
||||
t = src.decode('latin1')
|
||||
t = src.decode('latin1'); renamed = {}
|
||||
v = re.search(r'^[ \t]*#version[ \t]+(\d+)[^\n]*\n?', t, re.M)
|
||||
if not v or v.group(1) == '100': src = es100(t.replace(v.group(0), '', 1) if v else t, stage).encode('latin1')
|
||||
if not v or v.group(1) == '100': src = es100(t.replace(v.group(0), '', 1) if v else t, stage, renamed).encode('latin1')
|
||||
g = os.path.join(tmp, f'{key}.{stage}'); spv = g + '.spv'; msl = os.path.join(tmp, f'{key}_{stage[0]}.metal')
|
||||
open(g + '.in', 'wb').write(src)
|
||||
r = subprocess.run(['glslangValidator', '-E', '-S', stage, g + '.in'], capture_output=True, text=True)
|
||||
if r.returncode: return 'glslang -E: ' + ' | '.join(l for l in (r.stdout + r.stderr).splitlines() if 'ERROR' in l and 'compilation' not in l)[:400]
|
||||
pre = r.stdout[r.stdout.find('#version'):] # warnings come first
|
||||
open(g, 'w').write(fixups(pre, stage))
|
||||
open(g, 'w').write(fixups(pre, stage, renamed))
|
||||
r = subprocess.run(['glslangValidator', '-V', '-R', '--aml', '--amb', '-S', stage, g, '-o', spv], capture_output=True, text=True)
|
||||
if r.returncode: return 'glslang: ' + ' | '.join(l for l in (r.stdout + r.stderr).splitlines() if 'ERROR' in l and 'compilation' not in l)[:400]
|
||||
refl = json.loads(subprocess.run([SPIRV_CROSS, spv, '--reflect'], capture_output=True, text=True, check=True).stdout)
|
||||
@@ -210,7 +220,7 @@ def translate(src, stage, key, tmp):
|
||||
if r.returncode: return 'spirv-cross: ' + r.stderr.strip()[:300]
|
||||
m = open(msl).read()
|
||||
# Varyings by name: the out struct of a vertex shader and the in struct of a fragment shader (stage_in members of a vertex shader are [[attribute(n)]])
|
||||
m = re.sub(r'(\b(\w+)\s+\[\[)user\(locn\d+\)', lambda x: f'{x.group(1)}user({x.group(2)})', m)
|
||||
m = re.sub(r'(\b(\w+)\s+\[\[)user\(locn\d+\)', lambda x: f'{x.group(1)}user({renamed.get(x.group(2), x.group(2))})', m)
|
||||
m = re.sub(r'\bfast::(min|max|clamp)\(', r'precise::\1(', m) # a NaN operand gives the other one, as on the Switch's GPU (vk_shaders.py PRECISE)
|
||||
open(msl, 'w').write(m)
|
||||
f = []
|
||||
@@ -238,7 +248,7 @@ def translate(src, stage, key, tmp):
|
||||
for k in ('separate_images', 'separate_samplers', 'images', 'ssbos', 'push_constants'):
|
||||
if refl.get(k): return f'{k} are not implemented'
|
||||
if any(int(x) > 15 for x in re.findall(r'\[\[(?:sampler|buffer)\((\d+)\)\]\]', m)): return 'a buffer or sampler slot above 15'
|
||||
return msl, game_names(f)
|
||||
return msl, game_names(f, renamed)
|
||||
|
||||
def one(item, tmp):
|
||||
"""[(key, stage, fields, msl, where)], or [(key, None, errors, None, where)] when no stage translates"""
|
||||
|
||||
@@ -69,7 +69,8 @@ class GameNames(unittest.TestCase):
|
||||
|
||||
def test_table_rows_give_the_names_back(self):
|
||||
rows = ['t:dm_texture=0:sampler2D', 'u:L.gm_sample=16:float:0:0', 'a:dm_sampler=1:vec4', 'b:0:32', 'o:gm_FragColor=0', 'u:dm_texture_scale=0:float:0:0']
|
||||
self.assertEqual(gl_shaders.game_names(rows), ['t:texture=0:sampler2D', 'u:L.sample=16:float:0:0', 'a:sampler=1:vec4', 'b:0:32', 'o:gm_FragColor=0',
|
||||
self.assertEqual(gl_shaders.game_names(rows, {'dm_texture': 'texture', 'gm_sample': 'sample', 'dm_sampler': 'sampler'}),
|
||||
['t:texture=0:sampler2D', 'u:L.sample=16:float:0:0', 'a:sampler=1:vec4', 'b:0:32', 'o:gm_FragColor=0',
|
||||
'u:dm_texture_scale=0:float:0:0'])
|
||||
|
||||
|
||||
@@ -85,6 +86,32 @@ class Sources(unittest.TestCase):
|
||||
|
||||
@unittest.skipUnless(shutil.which('glslangValidator'), 'glslangValidator is not installed')
|
||||
class Translate(unittest.TestCase):
|
||||
def test_original_names_that_resemble_rewrite_names(self):
|
||||
src = (b'#version 320 es\nprecision highp float;\nuniform sampler2D dm_texture;\nuniform float gm_sample;\n'
|
||||
b'out vec4 color;\nvoid main() { color = texture(dm_texture, vec2(0.5)) * gm_sample; }\n')
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
r = gl_shaders.translate(src, 'frag', '0' * 16, tmp)
|
||||
self.assertIsInstance(r, tuple, r)
|
||||
self.assertIn('t:dm_texture=0:sampler2D', r[1])
|
||||
self.assertTrue(any(x.startswith('u:gm_sample=') for x in r[1]), r[1])
|
||||
|
||||
def test_rewritten_names_do_not_collide_with_original_names(self):
|
||||
src = (b'precision highp float;\nuniform sampler2D texture;\nuniform sampler2D dm_texture;\n'
|
||||
b'void main() { gl_FragColor = texture2D(texture, vec2(0.5)) + texture2D(dm_texture, vec2(0.5)); }\n')
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
r = gl_shaders.translate(src, 'frag', '1' * 16, tmp)
|
||||
self.assertIsInstance(r, tuple, r)
|
||||
self.assertEqual({x.split('=')[0] for x in r[1] if x.startswith('t:')}, {'t:texture', 't:dm_texture'})
|
||||
|
||||
def test_varyings_keep_the_same_name_across_stages_with_different_collisions(self):
|
||||
vert = b'attribute vec4 p; uniform float dm_texture; varying float texture; void main() { gl_Position = p; texture = dm_texture; }\n'
|
||||
frag = b'precision highp float;\nvarying float texture; void main() { gl_FragColor = vec4(texture); }\n'
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for src, stage, key in [(vert, 'vert', '2'), (frag, 'frag', '3')]:
|
||||
r = gl_shaders.translate(src, stage, key * 16, tmp)
|
||||
self.assertIsInstance(r, tuple, r)
|
||||
self.assertIn('[[user(texture)]]', Path(r[0]).read_text())
|
||||
|
||||
def test_doom3_style_pair(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
v = gl_shaders.translate(VERT.encode(), 'vert', 'v' * 16, tmp)
|
||||
|
||||
@@ -50,6 +50,43 @@ fragment main0_out main0(main0_in in [[stage_in]], constant spvDescriptorSetBuff
|
||||
|
||||
|
||||
class Regress(unittest.TestCase):
|
||||
def test_gl_chain_key_tracks_the_glsl_compiler(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root = Path(d); compiler = root / 'glslangValidator'; compiler.write_bytes(b'compiler version one')
|
||||
tree = NS(path=root)
|
||||
g = NS(kind='gl', ver='v0', shader_roots=list)
|
||||
gl = NS(sources=lambda roots: [(b'void main() {}', 'frag', 'synthetic')])
|
||||
with patch.dict(os.environ, {}, clear=True), patch.object(regress, 'load_module', return_value=gl), \
|
||||
patch.object(regress.shutil, 'which', return_value=str(compiler)):
|
||||
before = regress.chain_key(tree, g, 'other tools')
|
||||
self.assertEqual(before, regress.chain_key(tree, g, 'other tools'))
|
||||
compiler.write_bytes(b'compiler version two')
|
||||
self.assertNotEqual(before, regress.chain_key(tree, g, 'other tools'))
|
||||
|
||||
def test_gl_manifest_preserves_translation_failures(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p = Path(d) / 'translations.json'
|
||||
p.write_text(json.dumps({'a_frag': {'st': 'ok', 'msl': 'abc', 'refl': 'def'}, 'b_frag': {'st': 'translation failed', 'err': 'sampler limit'}}))
|
||||
built = regress.gl_manifest(p, True, Path(d) / 'log')
|
||||
self.assertEqual((built['a_frag']['st'], built['b_frag']['st']), ('ok', 'translation failed'))
|
||||
failed = regress.gl_manifest(p, False, Path(d) / 'log')
|
||||
self.assertEqual((failed['a_frag']['st'], failed['b_frag']['st']), ('library failed', 'translation failed'))
|
||||
p.write_text('{}')
|
||||
with self.assertRaises(regress.HarnessError): regress.gl_manifest(p, True, Path(d) / 'log')
|
||||
|
||||
def test_gl_game_capture_roots_and_provisional_route(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root = Path(d); build = root / '0100000000000000_build'
|
||||
(build / 'patched_v0').mkdir(parents=True); (build / 'shader/gl').mkdir(parents=True)
|
||||
capture = build / 'extract/v0/gl_capture'; capture.mkdir(parents=True)
|
||||
profile = build / 'profile/0100000000000000'; profile.mkdir(parents=True)
|
||||
(profile / 'game.tsv').write_text('name\tSynthetic GL game\n')
|
||||
(profile / 'smoke.tsv').write_text('secs\t120\nsave\tnew\n')
|
||||
g = regress.Game(root, build)
|
||||
self.assertEqual(g.kind, 'gl'); self.assertEqual(g.route()['secs'], 120)
|
||||
with patch.object(regress.Game, 'romfs', return_value=root / 'romfs'):
|
||||
self.assertEqual(g.shader_roots(), [root / 'romfs', capture, build / 'extract/v0/ExeFS/main'])
|
||||
|
||||
def test_run_env_cloud_saves_off(self): # an inherited DM_SAVE_SYNC would sync a route's scratch save with the player's cloud save (docs/reference/services.md)
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root = Path(d)
|
||||
|
||||
@@ -1058,6 +1058,8 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- the NSP script took the game for an OpenGL one (`main imports EGL and names glShaderSource`), the GL shader capture found no shader, and the capture boot stopped with `[nvn-mtl] FATAL cannot read the shader map` from `h_nvnQueueSubmitCommands` called in an NRO (`nro8+0xc10d0`). → [NVN in NROs under an SDL main that names GL](../reference/rendering.md#nvn-in-nros-under-an-sdl-main-that-names-gl)
|
||||
- the NSP script took the game for an OpenGL one (`main imports EGL and names glShaderSource`) and translated 2 GL shaders; the game boots with sound and answers input, but the window stays black, and the log has `[nvn-mtl] [RED] shader … is not in the shader map` for every shader it makes, with no EGL call at all. → [NVN and its own GLSLC under a main that also links EGL](../reference/rendering.md#nvn-and-its-own-glslc-under-a-main-that-also-links-egl)
|
||||
- a jump to address 0 right after `glGetFloatv(0xb12)` (`lr=main+0x2d58c4`). → [Which GL functions a game calls](../reference/rendering.md#which-gl-functions-a-game-calls)
|
||||
- `glValidateProgram` reports success for a program that has never linked, or for differently typed samplers assigned to one texture unit. → [GL program validation records the result](../reference/rendering.md#gl-program-validation-records-the-result)
|
||||
- clearing RGBA8 with float RGBA `{1, 0, 0, 1}` gives the first float's bytes instead of opaque red; clearing an attached framebuffer red and then its texture blue leaves it red. → [GL texture clears convert values and keep command order](../reference/rendering.md#gl-texture-clears-convert-values-and-keep-command-order)
|
||||
- every draw is skipped: `[RED] … shader <key> (<n> bytes of GLSL) is not in the library (DM_GL_CAPTURE collects it)`, `program <n>: a shader is missing from the library, its draws are skipped`, `draw with no usable program`, and frame records of `draws 0`. The NSP script translated only `main`'s strings and planned no capture, since those count as the game's GLSL. → [GLSL source files named `.glsl`](../reference/rendering.md#glsl-source-files-named-glsl)
|
||||
- `gl_shaders.py` reports `does not translate: vert: glslang: ERROR: …: 'extraneous semicolon' : not supported with this profile: es`, and the host skips that program's draws. → [A function body closed with `};`](../reference/rendering.md#a-function-body-closed-with-)
|
||||
- every sprite of a program samples black, while the textures are there; the shader's table row lists two samplers at one slot, such as `t:T0=0:sampler2D t:T1=0:sampler2D`. → [A sampler the shader never reads](../reference/rendering.md#a-sampler-the-shader-never-reads)
|
||||
|
||||
+2
-2
@@ -517,12 +517,12 @@ python3 scripts/regress.py replay # replay those captures against t
|
||||
|
||||
`--games <id>,…` selects games, `--baseline` / `--candidate` take any revision (`worktree` is this checkout), `--lock` (or `DM_MEASURE_LOCK`) is the measuring lock `bench.py --lock` shares, held only while a game runs, and `REGRESS_SKIP=<id>,…` leaves out a game someone else is working on. Source trees and public reports go under `--root` (`REGRESS_ROOT`), the games' NSP folders are found under `--games-dir` (`REGRESS_GAMES`); both have no default, since they depend on the machine, and go before the command (`regress.py --root <drive>/harness --games-dir <drive>/nsp check …`). All commands except `impact` require both paths; `impact` reads only git and committed manifests, prints its report without either path, and saves it with `--out` or under an existing configured root. Each revision is checked out once into `trees/`, and its chain, host and rewriter come from there. Game-derived files (shader libraries, rewritten modules, profile copies, saves, screenshots and baselines) stay in the game's NSP folder at `<id>-work/regress/`. Shader tools write generated tables only into those profile copies. The games are the NSP folders under `--games-dir` (`REGRESS_GAMES`). The exit status is 0 without a regression, 1 with one, and 2 when the harness could not check a game.
|
||||
|
||||
The default selection keeps every local build for the chain checks; games with a `smoke.tsv` also run its route. A game without a route does not build a host or run. Each revision runs its own `dm/games/<id>` profile; the build's `<id>_build/profile/<id>` runs instead only when it is derived (`<id>.derived.key` beside it) or the game has no profile in `dm/games` (the games line says `the build profile`), so a provisional profile left from before the game's profile was added is not tested in its place. `check --no-smoke` and `baseline --no-smoke` perform only the chain and interface checks. The chain cache includes the shader package's contents and the split's fallback `pso_pairs.tsv`; Vulkan builds include captured SPIR-V from the packed version's `vk_capture` folder. Interface checks run again with each revision's archive planner and profile even when the libraries are reused. Stored smoke baselines are reused only while the route, save bytes, build artifacts, compilers, machine and run settings match; older records are recorded again. Each candidate run must supply its scheduled screenshots, and a prebuild that crashes or times out fails the run. With repeated runs, every candidate screenshot is compared with its closest baseline screenshot.
|
||||
The default selection keeps every local build for the chain checks; games with a `smoke.tsv` also run its route. A game without a route does not build a host or run. Each revision runs its own `dm/games/<id>` profile; the build's `<id>_build/profile/<id>` runs instead only when it is derived (`<id>.derived.key` beside it) or the game has no profile in `dm/games` (the games line says `the build profile`), so a provisional profile left from before the game's profile was added is not tested in its place. `check --no-smoke` and `baseline --no-smoke` perform only the chain and interface checks. The chain cache includes the shader package's contents and the split's fallback `pso_pairs.tsv`; Vulkan builds include captured SPIR-V from the packed version's `vk_capture` folder. OpenGL builds use GLSL from the RomFS, `main`, and that version's `gl_capture`, fingerprint the GLSL compiler and translator, and compare each source/stage's translation outcome, MSL and host table fields. A provisional game may keep its smoke route beside its build profile when no repository route exists. Interface checks run again with each revision's archive planner and profile even when the libraries are reused. Stored smoke baselines are reused only while the route, save bytes, build artifacts, compilers, machine and run settings match; older records are recorded again. Each candidate run must supply its scheduled screenshots, and a prebuild that crashes or times out fails the run. With repeated runs, every candidate screenshot is compared with its closest baseline screenshot.
|
||||
|
||||
Regression compile caches are separate from normal build caches and shared across runs of one game. The automatic per-game limit is at least 8 GiB or four times the largest retained shader-library image; `--shader-cache-gb N` sets a fixed limit in GiB. Cleanup waits until the cache is idle, so builds may temporarily exceed it. [Cache ownership, read-only reuse and eviction](reference/packing.md#regression-shader-compilations-grow-the-normal-build-cache).
|
||||
|
||||
Per game it checks:
|
||||
- **Chain** (no GPU): the shaders built by each revision's `dmsh_build.py` (a Vulkan game: `vk_shaders.py`), shader by shader: built or failed (newly failing by the rule of `shader_regressions.py`, which it imports; a new shader that fails is listed apart), and the SHA-256 of the MSL, of the reflection without its chain fields and of the variant libraries. A build is kept per chain version, profile inputs and compilers (`<NSP folder>/<id>-work/regress/chain/`), so a revision that did not change the chain reuses it, and the build uses its game's regression cache, `<id>-work/regress/cas.db` (`DMSH_CAS`), with read-only reuse of `shader/cache/cas.db` from the normal build, so unchanged MSL is not compiled again. A changed chain still translates every shader: Breath of the Wild's 19,592 took 14 minutes on an M2 Max.
|
||||
- **Chain** (no GPU): the shaders built by each revision's `dmsh_build.py` (a Vulkan game: `vk_shaders.py`; an OpenGL game: `gl_shaders.py`), shader by shader: built or failed (newly failing by the rule of `shader_regressions.py`, which it imports; a new shader that fails is listed apart), and the SHA-256 of the MSL, of the reflection without its chain fields and of the variant libraries. A build is kept per chain version, profile inputs and compilers (`<NSP folder>/<id>-work/regress/chain/`), so a revision that did not change the chain reuses it, and the build uses its game's regression cache, `<id>-work/regress/cas.db` (`DMSH_CAS`), with read-only reuse of `shader/cache/cas.db` from the normal build, so unchanged MSL is not compiled again. A changed chain still translates every shader: Breath of the Wild's 19,592 took 14 minutes on an M2 Max.
|
||||
- **Interface** (no GPU): every pipeline base `pso_offline.py` would put into the archive, from `shader_pairs.tsv` and `pso_pairs.tsv`, whose pixel shader reads a `[[user(locnN)]]` input the vertex shader does not write or writes with another type. `metal-tt` refuses such a pipeline and with it the whole archive (GitHub issue #283).
|
||||
- **Replay** (`replay`, an NVN game with a capture; GPU, no game run): the game's current capture ([Frame capture and replay](#frame-capture-and-replay)) replayed by each revision's `nvn_replay`, built from that revision's tree, with that revision's shader libraries given on its command line, a few times each (`--repeat`, default 3), each replay compared with the live frame. A candidate replay that differs from the live frame in more pixels than the tolerance, twice the capture's measured noise (a few replays see less than the whole spread: Breath of the Wild measured 154, then gave 157), while the baseline's stay within it, is a `REGRESSION`; with both beyond it, `CHANGED` with the baseline's failure as known. A capture that replays exactly has no tolerance: any other frame is a `REGRESSION`. A capture the candidate cannot replay (the record layout changed, or a translated shader now takes other bindings or inputs than the records were made for) is an `ERROR` that asks for a new capture: the replay accepts another chain version as long as every program's bindings still match. `capture` runs the route of each game whose `smoke.tsv` has a `capture` frame with the given revision (wall clock, `DM_PSO_HYBRID=0`, no prebuild), stops once the frame is written, then replays it `--repeat` times (default 8): the largest number of pixels any of them differs from the live frame is the capture's noise, kept with it in `<NSP folder>/<id>-work/regress/captures/` (Super Mario Bros. Wonder 0, Pokemon Scarlet 7, Breath of the Wild 122: its depth-EQUAL variation, Tears of the Kingdom 163: its early fragment tests, each game's note, Open; 2026-10-30, chain `f3ceca86cac5`). A replay takes seconds where a route takes minutes, and checks the replay layer only: the guest, the host's services and frame pacing do not run.
|
||||
- **Smoke** (Mac host, window, no audio): the route `dm/games/<id>/smoke.tsv` from a copy of its save, under a watchdog: the frame it must reach, a crash, a hang (no frame for `hang` seconds), the prepare step's time, `[RED]` lines the baseline did not print (numbers, addresses and paths normalized), frame times from `DM_NVN_TSV` (a Vulkan or GL game: presents counted from the log), the peak memory footprint, and perceptual hashes of screenshots at fixed times. The full mode first runs the pipeline prebuild (`DM_PSO_PREBUILD=tool`) under a watchdog and starts the game on its archive; `--quick` skips it (`DM_PSO_PREBUILD=0`).
|
||||
|
||||
@@ -2021,7 +2021,7 @@ Digimon Story Cyber Sleuth: Complete Edition (Media.Vision's MVGL engine, SDK 6.
|
||||
|
||||
- **Symptom:** a jump to address 0 after `eglGetProcAddress("eglGetCurrentDisplay")`, or a loader that takes the context for lost.
|
||||
- **Cause:** a glad loader asks `eglGetProcAddress` for EGL functions too, and calls `eglGetCurrentDisplay`; the layer answered only `gl` names and had no `eglGetCurrent*`.
|
||||
- **Fix:** `eglGetProcAddress` answers `egl` names from the same table. `eglMakeCurrent` records what the calling thread made current, the display, the context and the draw and read surfaces, in thread-local state; `eglGetCurrentContext`, `eglGetCurrentDisplay` and `eglGetCurrentSurface` (`EGL_DRAW`, `EGL_READ`) answer it, and a make-current of no context or `eglReleaseThread` clears it. The layer has one context: a thread that makes it current takes it from the thread it was current on (EGL would refuse with `EGL_BAD_ACCESS`), which then has none.
|
||||
- **Fix:** `eglGetProcAddress` answers `egl` names from the same table. `eglMakeCurrent` records the calling thread's display, context and draw/read surfaces; `eglGetCurrentContext`, `eglGetCurrentDisplay` and `eglGetCurrentSurface` (`EGL_DRAW`, `EGL_READ`) answer that binding. The layer's one context has one owner, protected by a mutex. A conflicting bind returns false with `EGL_BAD_ACCESS` and leaves both threads' bindings unchanged. Making no context current, `eglReleaseThread`, or the owning thread's exit releases it for another thread. `eglGetError` returns and clears only the calling thread's error.
|
||||
- **Check:** `t_gl_imports` (`test_extension_names_and_egl`).
|
||||
- **Found on:** Fate/hollow ataraxia REMASTERED, [issue #2818](https://github.com/seedds/nxnative/issues/2818).
|
||||
|
||||
@@ -2112,7 +2112,23 @@ Digimon Story Cyber Sleuth: Complete Edition (Media.Vision's MVGL engine, SDK 6.
|
||||
- **Symptom:** a jump to address 0 right after `glGetFloatv(0xb12)` (`lr=main+0x2d58c4`).
|
||||
- **Cause:** a GL function the layer did not have (here `glVertexAttrib4fv`, LÖVE's default colours). glad asks `eglGetProcAddress` for every name it knows; the functions the game really calls come from a census of the code's loads outside the loader (`dm/tools/loader_census.py`). Every other name gets a null pointer, and a jump to address 0 names nothing.
|
||||
- **Fix:** `DM_GL_STUBS=1` gives every name the layer lacks a stub of its own that reports its first call instead; `loader_census.py` lists what the code calls before the first boot. The stubs and `DM_GL_MISSES` keep a copy of each name, since a loader may put every name together in one buffer: with the game's pointer, every stub reported the last name asked.
|
||||
- **Found on:** [Digimon Story Cyber Sleuth: Complete Edition](../../dm/games/010014E00DB56000/README.md): glad asks for 2,956 names and stores each in a global its code reaches through the GOT; a census of the GOT slots the code loads outside the loader gives the 79 functions the game calls: buffers, vertex arrays, textures (2D and cube, S3TC), framebuffers and renderbuffers, programs with plain `glUniform*`, `glDrawElements` / `glDrawArrays`, and three compatibility calls (`glTexEnvi`, `glColorTable`, `glPixelTransferi`). No uniform buffers, instancing or buffer mapping. [Balatro](../../dm/games/0100CD801CE5E000/README.md) (SDK 18.3.2; one boot; the missing `glVertexAttrib4fv` above): LÖVE's glad stores each pointer straight into a global of its own (no GOT slot per name), and the code reaches those globals through GOT entries that hold their addresses, which it often keeps in callee-saved registers across a loop, or picks between with `csel` (`glEnableVertexAttribArray` or `glDisableVertexAttribArray`). `loader_census.py` follows registers in a straight line for that (adrp, add, loads through relocated GOT entries, `mov`, `csel`): 2,133 names asked, about 150 called. Fate/hollow ataraxia REMASTERED ([issue #2818](https://github.com/seedds/nxnative/issues/2818)): `CRASH sig=11 addr=0 pc=0 lr=main+0x3bab70c` when a new game starts is `glValidateProgram`, which the game calls through its pointer at `main+0x7317660` right after `glLinkProgram` (`main+0x3bab6ec`); the stubs named it, `glLineWidth`, which it calls before its draws, and `glClearTexImage` (GL 4.4), with which it clears a new texture to one value (`lr=main+0x934f48`, about 15 s in). The layer has all three: a program that links validates, lines stay one pixel wide (a red line for any other width), and a clear converts its value as `glTexSubImage2D` converts data and writes it to every face, layer and slice of the level. The census finds no loader in its `main`; it puts its names together in one buffer.
|
||||
- **Found on:** [Digimon Story Cyber Sleuth: Complete Edition](../../dm/games/010014E00DB56000/README.md): glad asks for 2,956 names and stores each in a global its code reaches through the GOT; a census of the GOT slots the code loads outside the loader gives the 79 functions the game calls: buffers, vertex arrays, textures (2D and cube, S3TC), framebuffers and renderbuffers, programs with plain `glUniform*`, `glDrawElements` / `glDrawArrays`, and three compatibility calls (`glTexEnvi`, `glColorTable`, `glPixelTransferi`). No uniform buffers, instancing or buffer mapping. [Balatro](../../dm/games/0100CD801CE5E000/README.md) (SDK 18.3.2; one boot; the missing `glVertexAttrib4fv` above): LÖVE's glad stores each pointer straight into a global of its own (no GOT slot per name), and the code reaches those globals through GOT entries that hold their addresses, which it often keeps in callee-saved registers across a loop, or picks between with `csel` (`glEnableVertexAttribArray` or `glDisableVertexAttribArray`). `loader_census.py` follows registers in a straight line for that (adrp, add, loads through relocated GOT entries, `mov`, `csel`): 2,133 names asked, about 150 called. Fate/hollow ataraxia REMASTERED ([issue #2818](https://github.com/seedds/nxnative/issues/2818)): `CRASH sig=11 addr=0 pc=0 lr=main+0x3bab70c` when a new game starts is `glValidateProgram`, which the game calls through its pointer at `main+0x7317660` right after `glLinkProgram` (`main+0x3bab6ec`); the stubs named it, `glLineWidth`, which it calls before its draws, and `glClearTexImage` (GL 4.4), with which it clears a new texture to one value (`lr=main+0x934f48`, about 15 s in). The layer has all three: [program validation](#gl-program-validation-records-the-result), lines that stay one pixel wide (a red line for any other width), and [texture clears](#gl-texture-clears-convert-values-and-keep-command-order) of every face, layer and slice of the level. The census finds no loader in its `main`; it puts its names together in one buffer.
|
||||
|
||||
### GL program validation records the result
|
||||
|
||||
- **Symptom:** `glValidateProgram` reports success for a program that has never linked, or for differently typed samplers assigned to one texture unit.
|
||||
- **Cause:** the entry checked only the object name, and `GL_VALIDATE_STATUS` always returned true.
|
||||
- **Fix:** validation records a snapshot on the program: it needs a linked executable, valid active sampler units, compatible sampler types on each unit, and sampler counts within the advertised stage and combined limits. A failed validation explains why through `glGetProgramInfoLog`; successful validation clears that log. Relinking resets validation, and changing uniforms does not change the last recorded result until the next validation.
|
||||
- **Check:** `t_gl_imports` (`test_program_validation`, `test_fate_calls`): unlinked programs, sampler conflicts, valid and out-of-range units, the result's lifetime and the log.
|
||||
- **Found on:** synthetic cases while reviewing [Fate/hollow ataraxia REMASTERED's missing entry](https://github.com/seedds/nxnative/pull/2819).
|
||||
|
||||
### GL texture clears convert values and keep command order
|
||||
|
||||
- **Symptom:** clearing RGBA8 with float RGBA `{1, 0, 0, 1}` gives the first float's bytes instead of opaque red; clearing an attached framebuffer red and then its texture blue leaves it red.
|
||||
- **Cause:** `glClearTexImage` used the upload converter's byte-copy path for unlike source and destination types, and wrote the texture while an earlier framebuffer clear was still deferred.
|
||||
- **Fix:** `clear_pixel` decodes the source format/type into components and encodes the texture's storage format, including normalization, missing components, channel order, packed and floating formats, and depth/stencil. This single value has no unpack state. NULL means storage zeroes, including alpha. Earlier framebuffer clears are encoded before texture writes, which then use the existing ordered upload path.
|
||||
- **Check:** `t_gl_imports` (`test_fate_calls`): Metal readback of float-to-RGBA8, BGRA ordering, normalized single-channel data, byte-to-half-float, NULL, unpack-state independence and the two ordered clears.
|
||||
- **Found on:** synthetic readback cases while reviewing [Fate/hollow ataraxia REMASTERED's new texture-clear entry](https://github.com/seedds/nxnative/pull/2819).
|
||||
|
||||
### GLSL source translated offline and found by hash
|
||||
|
||||
@@ -2153,7 +2169,7 @@ Digimon Story Cyber Sleuth: Complete Edition (Media.Vision's MVGL engine, SDK 6.
|
||||
|
||||
- **Symptom:** `gl_shaders.py` reports `does not translate: frag: glslang: ERROR: …: 'texture' : redefinition`, and the scenes those shaders draw are black.
|
||||
- **Cause:** GLSL ES 1.00 shaders go through glslang as ES 3.10, where `texture` is a built-in function and `sample` a reserved word; ES 1.00 leaves both free as names (`uniform sampler2D texture;`).
|
||||
- **Fix:** `es100()` renames them (`dm_texture`, `gm_sample`; a `texture(` call stays, since NVIDIA's compiler takes one in ES 1.00 too), and the table rows give every name the rewrite renamed (`dm_texture`, `gm_sample`, `dm_sampler`) back as the game wrote it: the host finds attributes, uniforms and samplers by the game's names, and the shader's key is the hash of the game's own source.
|
||||
- **Fix:** `es100()` renames them (`dm_texture`, `gm_sample`; a `texture(` call stays, since NVIDIA's compiler takes one in ES 1.00 too). Each translation records only the names it actually rewrites, including `sampler` in `fixups()`, and chooses a free generated name if the source already uses its preferred one. Table fields and Metal varying tags restore the original names through that map; genuine game identifiers such as `dm_texture` stay unchanged, including in versioned shaders. The host finds attributes, uniforms and samplers by the game's names, and the shader's key is the hash of the game's own source.
|
||||
- **Check:** `test_gl_shaders.py`.
|
||||
- **Found on:** Fate/hollow ataraxia REMASTERED, [issue #2818](https://github.com/seedds/nxnative/issues/2818): 16 of its 78 captured fragment shaders; 13 of them translate now (62 shaders → 75), and the other 3 need a sampler slot above 15, which the table cannot name. The tables of Well Dweller (93 shaders) and Balatro (35) are the same row for row.
|
||||
|
||||
|
||||
+49
-7
@@ -27,7 +27,7 @@
|
||||
# --lock FILE (DM_MEASURE_LOCK): the measuring lock bench.py --lock shares, held only while a game runs.
|
||||
#
|
||||
# What it checks, per game:
|
||||
# 1. Chain (static): the game's shaders translated by each revision's chain (dmsh_build.py through own_compilers.py; a Vulkan game: vk_shaders.py), compared shader by shader: built or failed
|
||||
# 1. Chain (static): the game's shaders translated by each revision's chain (dmsh_build.py through own_compilers.py; Vulkan: vk_shaders.py; OpenGL: gl_shaders.py), compared shader by shader: built or failed
|
||||
# (newly failing by the rule of dm/gfx/tools/shader_regressions.py, which the NSP script applies to one game's previous build; a new shader that fails is listed apart),
|
||||
# the SHA-256 of the MSL (<key>_b.metal), of the reflection (<key>_b.json without its chain fields) and of the variant libraries (_bf, _bv, _bp, _bg*). A build is kept per chain version,
|
||||
# shader package, profile inputs and compilers (<NSP folder>/<id>-work/regress/chain/<key>/; only the few used last stay, prune_chains), so a revision whose chain did not change costs nothing, and dmsh_build.py uses a bounded per-game regression cache with read-only reuse of the player's cache (DMSH_CAS), so MSL
|
||||
@@ -55,7 +55,7 @@
|
||||
# {"schema": "nxnative-regress/1", "command", "mode": "quick"|"full", "status", "exit", "started", "secs", "machine": {model, gpu, macos, xcode},
|
||||
# "baseline": {"rev", "sha"}, "candidate": {"rev", "sha", "dirty"},
|
||||
# "games": {<title ID>: {"name", "status", "reasons": [text], "known": [text], "secs": {"chain", "smoke"},
|
||||
# "chain": {"kind": "nvn"|"vk", "baseline": BUILD, "candidate": BUILD, "newly_failing": [{"key", "status", "error"}], "added_failing": [same],
|
||||
# "chain": {"kind": "nvn"|"vk"|"gl", "baseline": BUILD, "candidate": BUILD, "newly_failing": [{"key", "status", "error"}], "added_failing": [same],
|
||||
# "newly_passing": [key],
|
||||
# "changed": {"msl", "reflection", "variants", "shaders", "keys": [key, at most 200]}, "added": n, "removed": n,
|
||||
# "interface": {"baseline": n, "candidate": n, "new": [PAIR], "known": [PAIR, at most 50]}},
|
||||
@@ -265,6 +265,7 @@ class Game:
|
||||
|
||||
def route(self):
|
||||
f = REPO / 'dm/games' / self.id / 'smoke.tsv'
|
||||
if not f.is_file() and self.derived: f = self.build / 'profile' / self.id / 'smoke.tsv'
|
||||
return read_route(f) if f.is_file() else None
|
||||
|
||||
def env(self, tree): # shader tools write profile tables: use a copy in the game's work folder, keeping the revision tree and the player's build untouched
|
||||
@@ -289,8 +290,9 @@ class Game:
|
||||
|
||||
def shader_roots(self):
|
||||
roots = [self.romfs()]
|
||||
capture = self.build / 'extract' / self.ver / 'vk_capture'
|
||||
capture = self.build / 'extract' / self.ver / ('gl_capture' if self.kind == 'gl' else 'vk_capture')
|
||||
if capture.is_dir(): roots.append(capture)
|
||||
if self.kind == 'gl': roots.append(self.build / 'extract' / self.ver / 'ExeFS/main')
|
||||
return roots
|
||||
|
||||
|
||||
@@ -358,9 +360,16 @@ def chain_key(tree, g, tools):
|
||||
side = ''
|
||||
vk = load_module('regress_vk_sources', REPO / 'dm/gfx/tools/vk_shaders.py')
|
||||
sources = digest(sorted(Path(p) for root in g.shader_roots() for p in vk.spirv_files(root)), root=g.build)
|
||||
elif g.kind == 'gl':
|
||||
v, inp = digest([tree.path / 'dm/gfx/tools/gl_shaders.py'])[:12], g.ver
|
||||
side = digest([tree.path / p for p in ('dm/gfx/tools/mvgl.py', 'dm/gfx/tools/dmsh_chain.py', 'dm/ios/tools/ios_metal.py')])
|
||||
compiler = shutil.which('glslangValidator')
|
||||
side += digest([Path(compiler)]) if compiler else 'glslangValidator missing'
|
||||
gl = load_module('regress_gl_sources', REPO / 'dm/gfx/tools/gl_shaders.py')
|
||||
sources = hashlib.sha256(repr(sorted({(hashlib.sha256(s).hexdigest(), st or '') for s, st, _ in gl.sources(g.shader_roots())})).encode()).hexdigest()
|
||||
else: raise HarnessError(f'{g.id}: the chain check does not cover {g.kind} games yet')
|
||||
sc = tree.path / 'dm/gfx/tools/spirv_cross_bin/spirv-cross'
|
||||
if sc.is_file(): # earlier revisions use PATH, already covered by tools; pinned revisions also honor SPIRV_CROSS
|
||||
if sc.is_file() or os.environ.get('SPIRV_CROSS'): # earlier revisions use PATH, already covered by tools; pinned revisions also honor SPIRV_CROSS
|
||||
env = dotnet_env(g.env(tree))
|
||||
selected = env.get('SPIRV_CROSS', str(sc))
|
||||
side += digest([Path(shutil.which(selected, path=env.get('PATH')) or selected)])
|
||||
@@ -512,7 +521,7 @@ def chain_build_locked(tree, g, a, v, inp, key, out):
|
||||
if cas.suffix != '.db': tree_tar.pack(cas, say)
|
||||
say(f' {g.id}: hashing the outputs of chain {v}')
|
||||
shaders = nvn_manifest(shader_lib.view(lib), jobs)
|
||||
else:
|
||||
elif g.kind == 'vk':
|
||||
say(f' {g.id}: vk_shaders.py {v} of {tree.id} → {out}')
|
||||
msl = out / 'msl'; shutil.rmtree(msl, ignore_errors=True); msl.mkdir()
|
||||
# vk_shaders.py writes its MSL into a temporary folder; this keeps it (the script itself is unchanged)
|
||||
@@ -523,10 +532,32 @@ def chain_build_locked(tree, g, a, v, inp, key, out):
|
||||
'runpy.run_path(sys.argv[0], run_name="__main__")\n')
|
||||
rc, paused = run_heavy([sys.executable, '-c', wrap], log, tree.path, env, a, f'{g.id} shader build'); t0 += paused
|
||||
shaders = vk_manifest(msl, out / 'vk/vk_shaders.tsv', rc == 0, log)
|
||||
else:
|
||||
say(f' {g.id}: gl_shaders.py {v} of {tree.id} → {out}')
|
||||
msl = out / 'msl'; shutil.rmtree(msl, ignore_errors=True); msl.mkdir()
|
||||
# Record the translator's actual outcomes, including rejected sources; failed stage guesses of a source that translated successfully are not failures.
|
||||
wrap = ('import sys, json, hashlib, contextlib, tempfile\n'
|
||||
f'sys.path.insert(0, {str(tree.path / "dm/gfx/tools")!r})\nimport gl_shaders as gl\n'
|
||||
f'@contextlib.contextmanager\ndef keep(*a, **k): yield {str(msl)!r}\n'
|
||||
'tempfile.TemporaryDirectory = keep\noriginal = gl.one\nresults = {}\n'
|
||||
'def one(item, tmp):\n'
|
||||
' rows = original(item, tmp)\n'
|
||||
' for key, stage, fields, path, where in rows:\n'
|
||||
' entry = {"st": "ok" if stage else "translation failed"}\n'
|
||||
' if stage:\n'
|
||||
' entry["msl"] = hashlib.sha256(open(path, "rb").read()).hexdigest()[:16]\n'
|
||||
' entry["refl"] = hashlib.sha256(" ".join(fields).encode()).hexdigest()[:16]\n'
|
||||
' else: entry["err"] = " / ".join(fields)[:400]\n'
|
||||
' results[key + "_" + (stage or item[1] or "unknown")] = entry\n'
|
||||
' return rows\n'
|
||||
f'gl.one = one\nsys.argv = {[str(tree.path / "dm/gfx/tools/gl_shaders.py"), *map(str, g.shader_roots()), str(out)]!r}\n'
|
||||
f'try: gl.main()\nfinally: open({str(out / "translations.json")!r}, "w").write(json.dumps(results))\n')
|
||||
rc, paused = run_heavy([sys.executable, '-c', wrap], log, tree.path, env, a, f'{g.id} shader build'); t0 += paused
|
||||
shaders = gl_manifest(out / 'translations.json', rc == 0 and (out / 'gl/gl_shaders.metallib').is_file(), log)
|
||||
st = collections.Counter(s['st'] for s in shaders.values())
|
||||
m = {'key': key, 'kind': g.kind, 'chain': v, 'inputs': inp, 'tree': tree.id, 'game': g.id, 'total': len(shaders), 'ok': st['ok'], 'failed': len(shaders) - st['ok'],
|
||||
'failed_by_status': {k: n for k, n in st.items() if k != 'ok'}, 'build_secs': round(time.time() - t0, 1), 'shaders': shaders}
|
||||
if g.kind == 'vk': m['build_failed'] = rc != 0
|
||||
if g.kind in ('vk', 'gl'): m['build_failed'] = rc != 0
|
||||
if g.kind == 'nvn': m['interface'] = interface_check(tree, g, out); m['hashes'] = NVN_HASHES
|
||||
mf.write_text(json.dumps(m, indent=0))
|
||||
if g.kind == 'nvn': pack_chain(tree, out / f'b-{v}')
|
||||
@@ -594,6 +625,17 @@ def vk_manifest(msl, table, ok, log):
|
||||
return keys
|
||||
|
||||
|
||||
def gl_manifest(translations, ok, log):
|
||||
"""The GL builder's per-source/stage outcomes, with a failed Metal library distinguished from a translation failure."""
|
||||
if not translations.is_file(): raise HarnessError(f'GL shader build produced no translation results (see {log})')
|
||||
entries = json.loads(translations.read_text())
|
||||
if not entries: raise HarnessError(f'GL shader build found no sources (see {log})')
|
||||
if not ok:
|
||||
for e in entries.values():
|
||||
if e['st'] == 'ok': e.update(st='library failed', err='GL Metal library build failed')
|
||||
return entries
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the vertex / pixel interface of the archive's pipeline bases (GitHub issue #283)
|
||||
|
||||
STRUCT = re.compile(r'struct\s+(\w+)\s*\{(.*?)\n\};', re.S)
|
||||
@@ -1358,7 +1400,7 @@ def cmd_check(a, smoke=True):
|
||||
cd = chain_diff(bm, cm)
|
||||
gr['chain'] = {'kind': cm['kind'], 'baseline': build_summary(bm), 'candidate': build_summary(cm), **cd}
|
||||
if cm.get('build_failed'):
|
||||
(gr['known'] if bm.get('build_failed') else levels['NEW-FAIL']).append('Vulkan shader build failed')
|
||||
(gr['known'] if bm.get('build_failed') else levels['NEW-FAIL']).append(f'{cm["kind"].upper()} shader build failed')
|
||||
if cd['newly_failing']: levels['NEW-FAIL'].append(f"{len(cd['newly_failing'])} shaders newly fail to build (shader_regressions.py's rule)")
|
||||
if cd['added_failing']: levels['NEW-FAIL'].append(f"{len(cd['added_failing'])} shaders new in the candidate fail to build")
|
||||
both = cm['failed'] - len(cd['newly_failing']) - len(cd['added_failing'])
|
||||
|
||||
Reference in new issue
Block a user