cmake_minimum_required(VERSION 3.20)
project(ShaolinLocalBuild LANGUAGES C CXX)
# Shaolin Recomp: the native game, built on the player's PC from their own disc
# (install_game.py). No recomp-ui: the Shaolin launcher (launcher.c) is the front end.
set(PSX_RECOMP_UI OFF CACHE BOOL "" FORCE)
set(PSX_NETPLAY OFF CACHE BOOL "" FORCE)
set(PSX_REWIND OFF CACHE BOOL "" FORCE)
set(PSX_OPENXR OFF CACHE BOOL "" FORCE)
set(PSX_EXECUTION_PROFILE REFERENCE CACHE STRING "" FORCE)
set(PSX_DEBUG_TOOLS ON CACHE BOOL "" FORCE)
file(TO_CMAKE_PATH "${PSXRECOMP_ROOT}" PSXRECOMP_ROOT)
file(TO_CMAKE_PATH "${SH_PRIVATE_ROOT}" SH_PRIVATE_ROOT)
include("${PSXRECOMP_ROOT}/runtime/runtime.cmake")
set(_sh_overlay_args)
if(EXISTS "${SH_PRIVATE_ROOT}/stage2/overlays/overlays_static.c")
  set(_sh_overlay_args GAME_OVERLAY_STATIC_C "${SH_PRIVATE_ROOT}/stage2/overlays/overlays_static.c")
endif()
psxrecomp_add_game_runtime(sh-game PRELOADED_MODS_DIR NONE
 WINDOW_TITLE "Shaolin"
 DEFAULT_GAME_CONFIG_PATH "game.toml"
 MAX_PLAYERS 2
 ${_sh_overlay_args}
 GEN_MARKER "${SH_PRIVATE_ROOT}/framework-generated/SLES_016.58_dispatch.c"
 GEN_FULL_GLOB "${SH_PRIVATE_ROOT}/framework-generated/SLES_016.58_full_*.c")
set_target_properties(sh-game PROPERTIES OUTPUT_NAME "ShaolinNative")
# Fast loading: during a load the runtime runs the game faster than real time (turbo loads)
# and shows one frame in 30. Shaolin's loading screens are animated, so they show every
# third frame instead (smooth enough, and the load still ends 2-3x sooner). main.cpp is compiled
# from a copy with that one constant changed; the copy fails the configure if it moves.
get_target_property(_sh_srcs sh-game SOURCES)
list(FILTER _sh_srcs EXCLUDE REGEX "[/\]runtime[/\]src[/\]main[.]cpp$")
set_property(TARGET sh-game PROPERTY SOURCES "${_sh_srcs}")
file(READ "${PSXRECOMP_ROOT}/runtime/src/main.cpp" _sh_main)
string(FIND "${_sh_main}" "const int TL_PRESENT_EVERY = 30;" _sh_at)
if(_sh_at LESS 0)
  message(FATAL_ERROR "Shaolin: runtime main.cpp changed (TL_PRESENT_EVERY)")
endif()
string(REPLACE "const int TL_PRESENT_EVERY = 30;" "const int TL_PRESENT_EVERY = 3;" _sh_main "${_sh_main}")
# Player builds (SH_DEV_BUILD off, the default; private/dev.sh turns it on): no localhost debug
# port (debug_server_init returns where it would if the port were taken, the path a second
# game instance takes) and the runtime's live rendering A/B keys 0-9 are not read (the number
# keys did nothing a player would want: they changed the render scale, filters and more).
option(SH_DEV_BUILD "Developer build: debug port 4370 and the renderer's A/B keys 0-9" OFF)
if(NOT SH_DEV_BUILD)
  set(_sh_keys "debug_toggles_on() && debug_toggle_key((int)key, nullptr, 0))")
  string(FIND "${_sh_main}" "${_sh_keys}" _sh_at)
  if(_sh_at LESS 0)
    message(FATAL_ERROR "Shaolin: runtime main.cpp changed (debug toggle keys)")
  endif()
  string(REPLACE "${_sh_keys}" "0 && debug_toggle_key((int)key, nullptr, 0))" _sh_main "${_sh_main}")
  list(FILTER _sh_srcs EXCLUDE REGEX "[/\]runtime[/\]src[/\]debug_server[.]c$")
  set_property(TARGET sh-game PROPERTY SOURCES "${_sh_srcs}")
  file(READ "${PSXRECOMP_ROOT}/runtime/src/debug_server.c" _sh_dbg)
  set(_sh_listen "    s_listen = socket(AF_INET, SOCK_STREAM, 0);")
  string(FIND "${_sh_dbg}" "${_sh_listen}" _sh_at)
  if(_sh_at LESS 0)
    message(FATAL_ERROR "Shaolin: runtime debug_server.c changed (listen socket)")
  endif()
  string(REPLACE "${_sh_listen}" "    fprintf(stdout, \"psxrecomp: debug server off in this release\\n\"); return;\n${_sh_listen}" _sh_dbg "${_sh_dbg}")
  file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/shaolin_debug_server.c" "${_sh_dbg}")
  target_sources(sh-game PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/shaolin_debug_server.c")
  set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/shaolin_debug_server.c" PROPERTIES
    INCLUDE_DIRECTORIES "${PSXRECOMP_ROOT}/runtime/src")
  message(STATUS "Shaolin: player build (no debug port, no A/B keys)")
endif()
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/shaolin_main.cpp" "${_sh_main}")
target_sources(sh-game PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/shaolin_main.cpp")
set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/shaolin_main.cpp" PROPERTIES
  INCLUDE_DIRECTORIES "${PSXRECOMP_ROOT}/runtime/src")
# HD HUD and text: the OpenGL renderer is compiled from a copy with one more sampling mode
# (5) for 2D primitives (sprites, HUD, text, menus): Hyllian's xBR level-2 rules (MIT, already
# credited by the runtime) on all four corners of each texel, with transparency treated as a
# colour so the outlines of letters and icons are rounded too, and an edge one output pixel
# wide. 3D world polygons keep the player's texture filter. g_sh_hud_upscale (shaolin_pc.c)
# turns it on. Each anchor must match once or the configure fails.
function(sh_patch var anchor replacement)
  string(FIND "${${var}}" "${anchor}" _at)
  if(_at LESS 0)
    message(FATAL_ERROR "Shaolin: runtime gpu_gl_renderer.c changed (HD HUD patch anchor missing)")
  endif()
  string(REPLACE "${anchor}" "${replacement}" _out "${${var}}")
  set(${var} "${_out}" PARENT_SCOPE)
endfunction()
get_target_property(_sh_srcs sh-game SOURCES)
list(FILTER _sh_srcs EXCLUDE REGEX "[/\]runtime[/\]src[/\]gpu_gl_renderer[.]c$")
set_property(TARGET sh-game PROPERTY SOURCES "${_sh_srcs}")
file(READ "${PSXRECOMP_ROOT}/runtime/src/gpu_gl_renderer.c" _sh_gl)
sh_patch(_sh_gl [==[static int s_tex_filter = 0;]==] [==[static int s_tex_filter = 0;
extern int g_sh_hud_upscale;   /* Shaolin Recomp: HD HUD and text (sampling mode 5) */
extern int g_sh_smooth_shadows; /* Shaolin Recomp: smooth shadows (sampling mode 6) */
static int s_sh_rect;          /* set while gpu_textured_rect draws: a 2D sprite or tile */
/* Shaolin Recomp: the shadow blobs (story and fights): 4-bit page (960,256), CLUT (928,511). */
static int sh_is_shadow(uint16_t tp, uint16_t cx, uint16_t cy) {
    return (tp & 0x19Fu) == 0x01Fu && cx == 928u && cy == 511u;
}]==])
sh_patch(_sh_gl [==[((s_tex_filter==2 && untracked ? 0 : s_tex_filter) |]==]
  [==[((s_sh_rect && g_sh_hud_upscale ? (((texpage >> 7) & 3) == 0 ? 5 : 6) :
          g_sh_smooth_shadows && sh_is_shadow(texpage, clut_x, clut_y) ? 6 :
          s_tex_filter==2 && untracked ? 0 : s_tex_filter) |]==])
# Smooth shadows (SHAOLIN_SHADOWS, launcher Story and view): characters' shadows are textured
# quads, one per limb, with a 16 x 32 4-bit black blob; at the PC's resolution its texels showed as
# stair steps. Those quads (sh_is_shadow) get mode 6, whose cut-out edge is the bilinear coverage
# of the blob at one half: smooth, rounded outlines in the same place.
# Only sprites and screen-aligned rectangles: 4-bit ones (letters, HUD frames, icons, buttons)
# get mode 5 (xBR); 8/16-bit ones (painted portraits, menu and battle backdrops) get mode 6
# (Catmull-Rom, cr_sample below: xBR suits pixel art, not painting). The field ground is 3D
# polygons without GTE provenance ("untracked") and keeps the player's texture filter.
sh_patch(_sh_gl [==[    gpu_textured_triangle(xs1,ys1,us1,vs1,col,tp,clut_x,clut_y,s_mod_raw,semi,lim);]==]
  [==[    s_sh_rect = 1;
    gpu_textured_triangle(xs1,ys1,us1,vs1,col,tp,clut_x,clut_y,s_mod_raw,semi,lim);]==])
sh_patch(_sh_gl [==[    gpu_textured_triangle(xs2,ys2,us2,vs2,col,tp,clut_x,clut_y,s_mod_raw,semi,lim);]==]
  [==[    gpu_textured_triangle(xs2,ys2,us2,vs2,col,tp,clut_x,clut_y,s_mod_raw,semi,lim);
    s_sh_rect = 0;]==])
sh_patch(_sh_gl [==[    "  return mix(xbr_c(E), xbr_c(px), a);\n"
    "}\n"]==] [==[    "  return mix(xbr_c(E), xbr_c(px), a);\n"
    "}\n"
    /* Shaolin Recomp, HD HUD and text: xBR level 2 on all four corners of the texel,
     * transparency (0) taking part as a colour, edges one output pixel wide. */
    "int hq[25];\n"
    "int hq_n(int x, int y){ return hq[(y+2)*5 + x+2]; }\n"
    "void hq_corner(int sx, int sy, vec2 f, vec2 fw, inout float best, inout int bc){\n"
    "  int E=hq[12], F=hq_n(sx,0), H=hq_n(0,sy);\n"
    "  if (E==F || E==H) return;\n"
    "  int I=hq_n(sx,sy), B=hq_n(0,-sy), C=hq_n(sx,-sy), D=hq_n(-sx,0), G=hq_n(-sx,sy);\n"
    "  int F4=hq_n(2*sx,0), I4=hq_n(2*sx,sy), H5=hq_n(0,2*sy), I5=hq_n(sx,2*sy);\n"
    "  float we = xbr_d(E,C)+xbr_d(E,G)+xbr_d(I,H5)+xbr_d(I,F4)+4.0*xbr_d(H,F);\n"
    "  float wi = xbr_d(H,D)+xbr_d(H,I5)+xbr_d(F,I4)+xbr_d(F,B)+4.0*xbr_d(E,I);\n"
    "  if (!(we < wi)) return;\n"
    "  float x = sx > 0 ? f.x : 1.0 - f.x, y = sy > 0 ? f.y : 1.0 - f.y;\n"
    "  float a = smoothstep(-0.5, 0.5, (x + y - 1.5) / max(fw.x + fw.y, 1e-3));\n"
    "  float dfg = xbr_d(F,G), dhc = xbr_d(H,C);\n"
    "  if (2.0*dfg <= dhc && E!=G && D!=G)\n"
    "    a = max(a, smoothstep(-0.5, 0.5, (y + 0.5*x - 1.0) / max(fw.y + 0.5*fw.x, 1e-3)));\n"
    "  if (dfg >= 2.0*dhc && E!=C && B!=C)\n"
    "    a = max(a, smoothstep(-0.5, 0.5, (0.5*y + x - 1.0) / max(0.5*fw.y + fw.x, 1e-3)));\n"
    "  if (a > best) { best = a; bc = xbr_d(E,F) <= xbr_d(E,H) ? F : H; }\n"
    "}\n"
    "vec3 hq_sample(vec2 uv, vec2 fw, out int stp){\n"
    "  ivec2 e = ivec2(floor(uv)); vec2 f = fract(uv);\n"
    "  for (int y=-2; y<=2; ++y) for (int x=-2; x<=2; ++x)\n"
    "    hq[(y+2)*5 + x+2] = (abs(x)==2 && abs(y)==2) ? 0 : stable_texel(e + ivec2(x, y));\n"
    "  int E = hq[12]; float best = 0.0; int P = E;\n"
    "  hq_corner( 1, 1, f, fw, best, P); hq_corner(-1, 1, f, fw, best, P);\n"
    "  hq_corner( 1,-1, f, fw, best, P); hq_corner(-1,-1, f, fw, best, P);\n"
    "  if (best < 0.5 ? E == 0 : P == 0) discard;\n"
    "  if (E == 0 || P == 0) { int c = E == 0 ? P : E; stp = (c >> 15) & 1; return col5(c); }\n"
    "  stp = ((best < 0.5 ? E : P) >> 15) & 1;\n"
    "  return mix(col5(E), col5(P), best);\n"
    "}\n"
    /* Shaolin Recomp, painted 2D art (8/16-bit sprites: portraits, menu and battle backdrops):
     * Catmull-Rom over 4x4 texels, which keeps the drawing as painted and only removes the
     * pixel steps. Transparent texels borrow the nearest opaque colour so outlines get no dark
     * fringe; the cut-out edge is the bilinear coverage of the opaque texels at one half. */
    "vec4 cr_w(float t){ float t2=t*t, t3=t2*t;\n"
    "  return vec4(-0.5*t3+t2-0.5*t, 1.5*t3-2.5*t2+1.0, -1.5*t3+2.0*t2+0.5*t, 0.5*t3-0.5*t2); }\n"
    "vec3 cr_sample(vec2 uv, out int stp){\n"
    "  vec2 p = uv - 0.5; ivec2 b = ivec2(floor(p)); vec2 f = p - floor(p);\n"
    "  int q00=stable_texel(b), q10=stable_texel(b+ivec2(1,0)), q01=stable_texel(b+ivec2(0,1)), q11=stable_texel(b+ivec2(1,1));\n"
    "  float cov = mix(mix(q00!=0?1.0:0.0, q10!=0?1.0:0.0, f.x), mix(q01!=0?1.0:0.0, q11!=0?1.0:0.0, f.x), f.y);\n"
    "  if (cov < 0.5) discard;\n"
    "  int N = stable_texel(ivec2(floor(uv)));\n"
    "  if (N == 0) N = q11 != 0 ? q11 : q10 != 0 ? q10 : q01 != 0 ? q01 : q00;\n"
    "  stp = (N >> 15) & 1;\n"
    "  vec3 fill = col5(N);\n"
    "  vec4 wx = cr_w(f.x), wy = cr_w(f.y); vec3 acc = vec3(0.0);\n"
    "  for (int j=0; j<4; ++j) { vec3 row = vec3(0.0);\n"
    "    for (int i=0; i<4; ++i) { int t = stable_texel(b + ivec2(i-1, j-1));\n"
    "      row += wx[i] * (t != 0 ? col5(t) : fill); }\n"
    "    acc += wy[j] * row; }\n"
    "  return clamp(acc, 0.0, 1.0);\n"
    "}\n"]==])
sh_patch(_sh_gl [==[    "  } else if (fmode == 3) {\n"]==] [==[    "  } else if (fmode == 5) {\n"
    "    vec2 fw5 = abs(dx) + abs(dy);\n"
    "    if (max(fw5.x, fw5.y) >= 0.5) {\n"
    "      int raw = fetch_texel(int(floor(uv.x)), int(floor(uv.y)));\n"
    "      if (raw == 0) discard;\n"
    "      rgb = col5(raw); stp = (raw >> 15) & 1;\n"
    "    } else rgb = hq_sample(uv, fw5, stp);\n"
    "  } else if (fmode == 6) {\n"
    "    vec2 fw6 = abs(dx) + abs(dy);\n"
    "    if (max(fw6.x, fw6.y) >= 0.75) {\n"
    "      int raw = fetch_texel(int(floor(uv.x)), int(floor(uv.y)));\n"
    "      if (raw == 0) discard;\n"
    "      rgb = col5(raw); stp = (raw >> 15) & 1;\n"
    "    } else rgb = cr_sample(uv, stp);\n"
    "  } else if (fmode == 3) {\n"]==])
# See-through walls (sh_ghost.c): a primitive drawn while g_sh_ghost_now is set carries flag bit
# 0x8000 through the render thread (or reads it directly when nothing is recorded), and its
# textured triangles get filter bit 32: a one-pixel checker cut-out, so what is behind shows.
sh_patch(_sh_gl [==[static int s_sh_rect;          /* set while gpu_textured_rect draws: a 2D sprite or tile */]==]
  [==[static int s_sh_rect;          /* set while gpu_textured_rect draws: a 2D sprite or tile */
extern int g_sh_ghost_now;      /* Shaolin Recomp: see-through walls (sh_ghost.c) */
static int s_sh_ghost;          /* the primitive being drawn is in the way of the player */]==])
sh_patch(_sh_gl [==[(s_tex_lod && !untracked ? 16 : 0));]==]
  [==[(s_tex_lod && !untracked ? 16 : 0) | (s_sh_ghost && !s_sh_rect ? 32 : 0));]==])
sh_patch(_sh_gl [==[static uint16_t rth_prim_flags(void) {]==]
  [==[static uint16_t rth_prim_flags_ws(void);
static uint16_t rth_prim_flags(void) { return (uint16_t)(rth_prim_flags_ws() | (g_sh_ghost_now ? 0x8000u : 0u)); }
static uint16_t rth_prim_flags_ws(void) {]==])
sh_patch(_sh_gl [==[s_rthx_backdrop = (h.flags >> RTHF_BD_SHIFT) & 3;]==]
  [==[s_rthx_backdrop = (h.flags >> RTHF_BD_SHIFT) & 3; s_sh_ghost = (h.flags & 0x8000u) != 0;]==])
sh_patch(_sh_gl [==[s_rthx_backdrop = (c->flags >> RTHF_BD_SHIFT) & 3;]==]
  [==[s_rthx_backdrop = (c->flags >> RTHF_BD_SHIFT) & 3; s_sh_ghost = (c->flags & 0x8000u) != 0;]==])
sh_patch(_sh_gl [==[#define RTH_DIRECT_OR(rec) do { if (rth_record_mode()) { rec; return; } } while (0)]==]
  [==[#define RTH_DIRECT_OR(rec) do { if (rth_record_mode()) { rec; return; } s_sh_ghost = g_sh_ghost_now; } while (0)]==])
sh_patch(_sh_gl [==["  int fmode = v_filter & 15;\n"]==]
  [==["  int fmode = v_filter & 15;\n"
    "  if ((v_filter & 32) != 0 && ((int(gl_FragCoord.x) + int(gl_FragCoord.y)) & 1) == 0) discard;\n"]==])
# Smooth motion: in a fight the fighters fill the screen and the arena is the minority of the
# paired vertices (about an eighth), so the camera fit is accepted when 5% (and at least 24) agree (the renderer's
# own bar is half). Paired vertices that move on their own are placed along their own path.
sh_patch(_sh_gl [==[    if (s_fg_reproject) cp.min_inliers = 0.3f;]==]
  [==[    cp.min_inliers = s_fg_reproject ? 0.3f : 0.05f;   /* Shaolin: fighters fill the view */]==])
# Smooth motion ghosting (sixth session): an in-between frame starts as a copy of the newer real
# frame and the runtime skipped the game's clears before drawing, so where the background is the
# clear colour (the grey beyond doorways and above walls in third person, the sky) the newer
# frame's people and pillars stayed visible beside their redrawn in-between selves: doubled
# faces and pillars. The clears are redrawn now; the strips a moving camera uncovers at the
# view's edges are still filled from the newer frame afterwards (fg_generate's margin copy).
sh_patch(_sh_gl [==[            if (drawn && !s_fg_replay_objects_only && fg_rect_meets(v[0], v[1], v[2], v[3], disp))]==]
  [==[            if (!s_fg_replay_objects_only && fg_rect_meets(v[0], v[1], v[2], v[3], disp))]==])
# A triangle with a vertex the in-between camera passes (a wall beside the third-person camera)
# was left out of that frame: with the clears redrawn it showed as a hole for one frame. It is
# drawn where the redrawn real frame has it instead.
sh_patch(_sh_gl [==[                if (gone) {   /* crossed the camera plane: not in this frame */
                    pc_pending = 0;
                    precise_consumed();
                    break;
                }]==]
  [==[                if (gone)   /* Shaolin: crossed the camera plane: as the real frame has it */
                    for (int k = 0; k < 3; k++) { x[k] = pb->x[k]; y[k] = pb->y[k]; }]==])
sh_patch(_sh_gl [==[            if (a) fg_hud_lerp(&b->prims, &a->prims, 1.0 - t, s_fg_px, s_fg_py, 24.0f);
            placed = 1;]==]
  [==[            if (a) fg_hud_lerp(&b->prims, &a->prims, 1.0 - t, s_fg_px, s_fg_py, 24.0f);
            placed = 1;
            {   /* Diagnostic (SH_FG_DUMP): each in-between frame's phase and vertex offsets. */
                static int sh_gl = 0; static FILE *sh_gf = NULL;
                const char *sd = getenv("SH_FG_DUMP");
                if (sd && sh_gl < 6000) {
                    if (!sh_gf) { char fn[512]; snprintf(fn, sizeof fn, "%s_gen.txt", sd); sh_gf = fopen(fn, "w"); }
                    double sum[4] = {0, 0, 0, 0}; uint32_t cnt[4] = {0, 0, 0, 0};
                    for (uint32_t j = 0; j < b->prims.n; j++)
                        for (int k = 0; k < 3; k++) {
                            const int md = s_fg_verts[3 * j + k].mode & 3;
                            const float px = s_fg_px[3 * j + k], py = s_fg_py[3 * j + k];
                            if (isnan(px)) continue;
                            sum[md] += hypot(px - b->prims.v[j].x[k], py - b->prims.v[j].y[k]); cnt[md]++;
                        }
                    if (sh_gf) {
                        fprintf(sh_gf, "flip %llu t %.3f src_older %d inl %u/%u camt %.0f %.0f %.0f q %.4f %.4f %.4f | from-src px: cam %.2f (%u) obj %.2f (%u) nb %.2f (%u)\n",
                                (unsigned long long)s_fg_flips, t, s_fg_src_older, s_fg_fit.v[0].inliers, s_fg_fit.v[0].pairs,
                                s_fg_fit.v[0].t[0], s_fg_fit.v[0].t[1], s_fg_fit.v[0].t[2], s_fg_fit.v[0].q[1], s_fg_fit.v[0].q[2], s_fg_fit.v[0].q[3],
                                cnt[1] ? sum[1] / cnt[1] : 0, cnt[1], cnt[2] ? sum[2] / cnt[2] : 0, cnt[2],
                                cnt[3] ? sum[3] / cnt[3] : 0, cnt[3]);
                        fflush(sh_gf);
                    }
                    sh_gl++;
                }
            }]==])
# Smooth motion pacing (sixth session). With the wall-clock pacer (driver V-Sync off, e.g. a
# 200 Hz panel) a swap shows at once, but the in-between frames were timed one display interval
# ahead and went out every refresh from the start: with fewer planned than refreshes (5 of 6 on
# 200 Hz) the last in-between landed at phase 0.75 and the real frame followed one refresh later,
# so each game frame crawled, then leapt a quarter of its motion in 5 ms (slow-then-jump 30
# times a second, read as ghosting). Now the planned in-betweens are spread evenly over the game
# frame (one every flip / (n + 1)), the first one a step after the arrival, each at the phase its
# own present time gives, and the real frame goes at the end of the interval (or when the next
# game frame arrives): phases 0, 1/(n+1), ..., 1 at even times.
sh_patch(_sh_gl [==[    s_fg_step_ns = (uint64_t)(fg_step_s(flip_s, rhz, n) * 1e9);
    if (s_fg_due < s_fg_t0 || s_fg_due > s_fg_t0 + s_fg_step_ns) s_fg_due = s_fg_t0;]==]
  [==[    s_fg_step_ns = (uint64_t)(flip_s / (double)(n + 1) * 1e9);   /* Shaolin: even spacing */
    s_fg_due = s_fg_t0 + s_fg_step_ns;]==])
sh_patch(_sh_gl [==[        const double t = fg_clock_phase(now - s_fg_t0, s_fg_step_ns, s_fg_flip_ns);]==]
  [==[        const double t = fg_clock_phase(now - s_fg_t0, 0, s_fg_flip_ns);   /* Shaolin: shown now */]==])
# Smooth motion torn frame (sixth session): an in-between frame starts as a copy of the newer
# real frame's buffer and fills the strips a moving camera uncovers at the edges from it, both
# read from the live surface when the in-between is drawn. Shaolin draws its next frame into
# that buffer from about the middle of the game frame (the reprojection path's comment says the
# same of other games), so the in-between nearest that moment showed the next frame half drawn
# in its top strip: the clear colour and far beams where the near wall belongs, once per game
# frame (the 4th of 6 on a 200 Hz panel). The buffer is now snapshotted when the real frame
# arrives (the reprojection path's snapshot, taken in redraw mode too) and both copies read it.
sh_patch(_sh_gl [==[    if (li < 0 || li >= 4 || !s_fg_reproject || !s_raster_ok || !s_fg_on) return;]==]
  [==[    if (li < 0 || li >= 4 || !s_raster_ok || !s_fg_on) return;   /* Shaolin: redraw mode too */]==])
sh_patch(_sh_gl [==[    if (s_fg_reproject && B) rp_snapshot_list((int)(B - s_fg_l), B->disp);]==]
  [==[    if (B) rp_snapshot_list((int)(B - s_fg_l), B->disp);   /* Shaolin: redraw mode too */]==])
sh_patch(_sh_gl [==[        fg_blit2(s_hr_fbo, s_fg_hr_fbo, b->disp[0] * S, dy * S, L->disp[0] * S, ly * S, b->disp[2] * S, dh * S);
        if (iw >= 0) fg_blit2(s_wide_fbo[iw], s_fg_w_fbo, 0, dy * S, 0, ly * S, g_wide_w * S, dh * S);]==]
  [==[        const int sk = sh_fg_snap(b, iw, S, dh);   /* Shaolin: the buffer as it arrived */
        if (sk >= 0) {
            fg_blit2(s_rp_ls_fbo[sk], iw >= 0 ? s_fg_w_fbo : s_fg_hr_fbo, 0, 0,
                     iw >= 0 ? 0 : L->disp[0] * S, ly * S, (iw >= 0 ? g_wide_w : b->disp[2]) * S, dh * S);
            if (iw >= 0) fg_blit2(s_hr_fbo, s_fg_hr_fbo, b->disp[0] * S, dy * S, L->disp[0] * S, ly * S, b->disp[2] * S, dh * S);
        } else {
        fg_blit2(s_hr_fbo, s_fg_hr_fbo, b->disp[0] * S, dy * S, L->disp[0] * S, ly * S, b->disp[2] * S, dh * S);
        if (iw >= 0) fg_blit2(s_wide_fbo[iw], s_fg_w_fbo, 0, dy * S, 0, ly * S, g_wide_w * S, dh * S);
        }]==])
sh_patch(_sh_gl [==[        const GLuint src = iw >= 0 ? wf : f0, dst = iw >= 0 ? s_fg_w_fbo : s_fg_hr_fbo;]==]
  [==[        const int sks = sh_fg_snap(b, iw, S, dh);   /* Shaolin: the strips from the snapshot */
        const GLuint src = sks >= 0 ? s_rp_ls_fbo[sks] : iw >= 0 ? wf : f0, dst = iw >= 0 ? s_fg_w_fbo : s_fg_hr_fbo;
        const int sxo = sks >= 0 && iw < 0 ? b->disp[0] : 0, syo = sks >= 0 ? dy : 0;]==])
sh_patch(_sh_gl [==[            if (ml) fg_blit2(src, dst, (bx0 + x1) * S, (y1 + sdy) * S, (bx0 + x1) * S, y1 * S, ml * S, h * S);
            if (mr) fg_blit2(src, dst, (bx0 + x2 - mr) * S, (y1 + sdy) * S, (bx0 + x2 - mr) * S, y1 * S, mr * S, h * S);
            if (mt) fg_blit2(src, dst, (bx0 + x1) * S, (y1 + sdy) * S, (bx0 + x1) * S, y1 * S, w * S, mt * S);
            if (mb) fg_blit2(src, dst, (bx0 + x1) * S, (y2 - mb + sdy) * S, (bx0 + x1) * S, (y2 - mb) * S, w * S, mb * S);]==]
  [==[            if (ml) fg_blit2(src, dst, (bx0 + x1 - sxo) * S, (y1 + sdy - syo) * S, (bx0 + x1) * S, y1 * S, ml * S, h * S);
            if (mr) fg_blit2(src, dst, (bx0 + x2 - mr - sxo) * S, (y1 + sdy - syo) * S, (bx0 + x2 - mr) * S, y1 * S, mr * S, h * S);
            if (mt) fg_blit2(src, dst, (bx0 + x1 - sxo) * S, (y1 + sdy - syo) * S, (bx0 + x1) * S, y1 * S, w * S, mt * S);
            if (mb) fg_blit2(src, dst, (bx0 + x1 - sxo) * S, (y2 - mb + sdy - syo) * S, (bx0 + x1) * S, (y2 - mb) * S, w * S, mb * S);]==])
sh_patch(_sh_gl [==[static int fg_generate(double t, int swap) {]==]
  [==[/* Shaolin: the snapshot slot of list b's buffer at this scale, -1 when there is none. */
static int sh_fg_snap(const FgList *b, int iw, int S, int dh) {
    const int k = rp_snap_slot((int)(b - s_fg_l));
    if (k < 0 || s_rp_ls_S[k] != S || !s_rp_ls_fbo[k]) return -1;
    if (s_rp_ls_w[k] != (iw >= 0 ? g_wide_w : b->disp[2]) * S || s_rp_ls_h[k] != dh * S) return -1;
    return k;
}
static int fg_generate(double t, int swap) {]==])
# Diagnostic (SH_FG_DUMP): a timeline of presents (real / generated with its phase).
sh_patch(_sh_gl [==[static void fg_present_real(void) {]==]
  [==[static void sh_fg_tl(char kind, double t) {
    static FILE *f = NULL; static int lines = 0; static int init = 0;
    if (!init) { init = 1; const char *sd = getenv("SH_FG_DUMP");
        if (sd) { char fn[512]; snprintf(fn, sizeof fn, "%s_tl.txt", sd); f = fopen(fn, "w"); } }
    if (!f || lines > 3000) return;
    fprintf(f, "%.3f %c %.3f %llu\n", (double)rt_now_ns() * 1e-6, kind, t, (unsigned long long)s_fg_flips);
    lines++;
}
static void fg_present_real(void) {]==])
sh_patch(_sh_gl [==[    gl_swap_now(0);
    s_fg_real_presents++;]==]
  [==[    gl_swap_now(0);
    sh_fg_tl('r', 1.0);
    s_fg_real_presents++;]==])
sh_patch(_sh_gl [==[            fg_generate_timed(t);
            s_fg_k++;]==]
  [==[            fg_generate_timed(t);
            sh_fg_tl('g', t);
            s_fg_k++;]==])
# Diagnostic (SH_FG_DUMP=path prefix): the two matched lists and the fit of a few flips.
sh_patch(_sh_gl [==[    s_fg_src_older = src == A;]==]
  [==[    s_fg_src_older = src == A;
    {
        static int sh_dumps = 0; static uint64_t sh_flipn = 0;
        const char *sd = getenv("SH_FG_DUMP");
        if (sd && ++sh_flipn > 90 && sh_dumps < 3) {
            char fn[512]; snprintf(fn, sizeof fn, "%s_%d.txt", sd, sh_dumps++);
            FILE *df = fopen(fn, "w");
            if (df) {
                fprintf(df, "fit ok %d why %s src_older %d nviews %u n %d\n", s_fg_fit.ok,
                        s_fg_fit.why ? s_fg_fit.why : "", s_fg_src_older, s_fg_fit.nviews, n);
                for (uint32_t vi = 0; vi < s_fg_fit.nviews; vi++) {
                    const FgView *fv = &s_fg_fit.v[vi];
                    fprintf(df, "view %u %08x ok %d src %u pairs %u inl %u q %g %g %g %g t %g %g %g why %s\n", vi,
                            fv->view, fv->ok, fv->sources, fv->pairs, fv->inliers, fv->q[0], fv->q[1], fv->q[2], fv->q[3],
                            fv->t[0], fv->t[1], fv->t[2], fv->why ? fv->why : "");
                }
                for (int li = 0; li < 2; li++) {
                    const FgList *Lx = li ? B : A;
                    fprintf(df, "list %c %u\n", li ? 'B' : 'A', Lx->prims.n);
                    for (uint32_t j = 0; j < Lx->prims.n; j++) {
                        const FgPrim *pr = &Lx->prims.v[j];
                        fprintf(df, "%c %u %08x %08x", li ? 'B' : 'A', j, pr->view, pr->key);
                        for (int k = 0; k < 3; k++)
                            fprintf(df, " | %08x %.1f %.1f %.1f %.1f %.1f %.0f", pr->vid[k], pr->x[k], pr->y[k],
                                    pr->p[k][0], pr->p[k][1], pr->p[k][2], pr->h[k]);
                        if (Lx == src)
                            for (int k = 0; k < 3; k++)
                                fprintf(df, " m%d%d", s_fg_verts[3 * j + k].mode, s_fg_verts[3 * j + k].paired);
                        fputc('\n', df);
                    }
                }
                fclose(df);
            }
        }
    }]==])
# Widescreen menus: the title and menus are 4:3 paintings with nothing past their edges, so at a
# wide aspect they stay 4:3 in the middle. Instead of black bars, the side space shows the frame
# itself, scaled to fill the width, blurred and darkened (sh_ws_fill): shrunk to a small image
# (16 taps a texel), Gaussian-blurred both ways (13 taps, sigma 2.5 texels) and drawn over the
# window at 55% brightness before the frame. Only 4:3-pinned VRAM presents at a wide aspect, and
# never when bezel art is loaded. Movies (the CPU present) keep black bars: they are letterboxed
# inside their own picture, and blurred panels beside a black-banded movie looked boxed in.
sh_patch(_sh_gl [==[static void present_bezel(int ww, int wh, int lx, int ly, int lw, int lh);]==]
  [==[static void present_bezel(int ww, int wh, int lx, int ly, int lw, int lh);
static void sh_ws_fill(GLuint tex, float u0, float v0, float u1, float v1, int ww, int wh, int lx);]==])
sh_patch(_sh_gl [==[        present_target_quad(src_tex, tw, th,
                            src_x, disp_y, w, h, linear, lx, ly, lw, lh, 1, 1, src_scale);]==]
  [==[        if (force_4_3)
            sh_ws_fill(src_tex, (float)src_x / tw, (float)disp_y / th,
                       (float)(src_x + w) / tw, (float)(disp_y + h) / th, ww, wh, lx);
        present_target_quad(src_tex, tw, th,
                            src_x, disp_y, w, h, linear, lx, ly, lw, lh, 1, 1, src_scale);]==])
sh_patch(_sh_gl [==[int gl_renderer_present_hold_last(void) {]==]
  [==[static const char *SH_FILL_FS =
    "#version 330\n"
    "in vec2 v_uv; out vec4 frag;\n"
    "uniform sampler2D u_tex; uniform int u_pass; uniform vec2 u_step; uniform float u_dim;\n"
    "void main(){\n"
    "  vec3 c = vec3(0.0);\n"
    "  if (u_pass == 0) {\n"            /* shrink: 4x4 taps over one output texel */
    "    for (int j = 0; j < 4; j++) for (int i = 0; i < 4; i++)\n"
    "      c += texture(u_tex, v_uv + (vec2(i, j) - 1.5) * 0.25 * u_step).rgb;\n"
    "    c /= 16.0;\n"
    "  } else if (u_pass == 1) {\n"     /* one Gaussian direction */
    "    float ws = 0.0;\n"
    "    for (int k = -6; k <= 6; k++) { float w = exp(-float(k * k) / 12.5);\n"
    "      c += w * texture(u_tex, v_uv + float(k) * u_step).rgb; ws += w; }\n"
    "    c /= ws;\n"
    "  } else {\n"
    "    c = texture(u_tex, v_uv).rgb * u_dim;\n"
    "  }\n"
    "  frag = vec4(c, 1.0);\n"
    "}\n";
static GLuint s_sh_fill_prog, s_sh_fill_tex[2], s_sh_fill_fbo[2];
static GLint s_sh_fill_uTex, s_sh_fill_uPass, s_sh_fill_uStep, s_sh_fill_uDim, s_sh_fill_uRect;
static int s_sh_fill_w, s_sh_fill_h;
static void *s_sh_fill_ctx;
static void sh_fill_pass(int pass, GLuint src, GLuint dst_fbo, int vw, int vh,
                         float u0, float v0, float u1, float v1, float sx, float sy) {
    p_glBindFramebuffer(PSXGL_FRAMEBUFFER, dst_fbo);
    glViewport(0, 0, vw, vh);
    glBindTexture(GL_TEXTURE_2D, src);
    p_glUniform1i(s_sh_fill_uPass, pass);
    p_glUniform2f(s_sh_fill_uStep, sx, sy);
    p_glUniform4f(s_sh_fill_uRect, u0, v0, u1, v1);
    glDrawArrays(GL_TRIANGLES, 0, 3);
}
/* The blurred backdrop behind a pillarboxed 4:3 frame. (u0,v0)-(u1,v1): the frame in tex, top
 * row first, as present_target_quad samples it. Leaves GL state for the caller to set again. */
static void sh_ws_fill(GLuint tex, float u0, float v0, float u1, float v1, int ww, int wh, int lx) {
    if (s_bezel_tex || lx <= 0 || ww <= 0 || wh <= 0 || !tex) return;
    if (s_aspect_num * 3 <= s_aspect_den * 4) return;      /* the 4:3 setting keeps its bars */
    if (s_sh_fill_ctx != (void *)s_ctx) {                   /* names belong to one context */
        s_sh_fill_ctx = (void *)s_ctx;
        s_sh_fill_prog = build_program(PRESENT_VS, SH_FILL_FS);
        s_sh_fill_w = s_sh_fill_h = 0;
        s_sh_fill_tex[0] = s_sh_fill_tex[1] = 0;
        if (s_sh_fill_prog) {
            s_sh_fill_uTex = p_glGetUniformLocation(s_sh_fill_prog, "u_tex");
            s_sh_fill_uPass = p_glGetUniformLocation(s_sh_fill_prog, "u_pass");
            s_sh_fill_uStep = p_glGetUniformLocation(s_sh_fill_prog, "u_step");
            s_sh_fill_uDim = p_glGetUniformLocation(s_sh_fill_prog, "u_dim");
            s_sh_fill_uRect = p_glGetUniformLocation(s_sh_fill_prog, "u_uv_rect");
        }
    }
    if (!s_sh_fill_prog) return;
    const int bw = 128;
    int bh = (int)((int64_t)bw * wh / ww); if (bh < 8) bh = 8; if (bh > 512) bh = 512;
    if (bh != s_sh_fill_h || !s_sh_fill_tex[0]) {
        if (!s_sh_fill_tex[0]) {
            glGenTextures(2, s_sh_fill_tex);
            p_glGenFramebuffers(2, s_sh_fill_fbo);
        }
        for (int i = 0; i < 2; i++) {
            p_glActiveTexture(PSXGL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, s_sh_fill_tex[i]);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, bw, bh, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
            p_glBindFramebuffer(PSXGL_FRAMEBUFFER, s_sh_fill_fbo[i]);
            p_glFramebufferTexture2D(PSXGL_FRAMEBUFFER, PSXGL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                                     s_sh_fill_tex[i], 0);
            if (p_glCheckFramebufferStatus(PSXGL_FRAMEBUFFER) != PSXGL_FRAMEBUFFER_COMPLETE) {
                p_glBindFramebuffer(PSXGL_FRAMEBUFFER, 0);
                s_sh_fill_prog = 0;
                return;
            }
        }
        s_sh_fill_w = bw; s_sh_fill_h = bh;
    }
    /* The frame scaled to the window's width covers it; keep the middle rows that show. */
    const float show = (float)wh / ((float)ww * 0.75f);
    const float fv = show < 1.f ? show : 1.f;
    const float vm = 0.5f * (v0 + v1), vh2 = 0.5f * (v1 - v0) * fv;
    const float sv0 = vm - vh2, sv1 = vm + vh2;
    GLint mn = 0, mg = 0;
    glDisable(GL_SCISSOR_TEST);
    glDisable(GL_BLEND);
    p_glActiveTexture(PSXGL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, tex);
    glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, &mn);
    glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, &mg);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    p_glUseProgram(s_sh_fill_prog);
    p_glUniform1i(s_sh_fill_uTex, 0);
    p_glUniform1f(s_sh_fill_uDim, 0.55f);
    p_glBindVertexArray(s_present_vao);
    /* Shrink: the bottom row of the small image is the frame's bottom (GL order). */
    sh_fill_pass(0, tex, s_sh_fill_fbo[0], bw, bh, u0, sv0, u1, sv1,
                 (u1 - u0) / (float)bw, (sv1 - sv0) / (float)bh);
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, mn);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mg);
    sh_fill_pass(1, s_sh_fill_tex[0], s_sh_fill_fbo[1], bw, bh, 0.f, 1.f, 1.f, 0.f,
                 1.f / (float)bw, 0.f);
    sh_fill_pass(1, s_sh_fill_tex[1], s_sh_fill_fbo[0], bw, bh, 0.f, 1.f, 1.f, 0.f,
                 0.f, 1.f / (float)bh);
    sh_fill_pass(2, s_sh_fill_tex[0], 0, ww, wh, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f);
    p_glBindVertexArray(0);
    p_glUseProgram(0);
}

int gl_renderer_present_hold_last(void) {]==])
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/shaolin_gpu_gl_renderer.c" "${_sh_gl}")
target_sources(sh-game PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/shaolin_gpu_gl_renderer.c")
set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/shaolin_gpu_gl_renderer.c" PROPERTIES
  INCLUDE_DIRECTORIES "${PSXRECOMP_ROOT}/runtime/src")
# Widescreen HUD in the field (gpu.c copy). The runtime squashes HUD pieces back to their 4:3
# shape from a prepass over each frame's ordering table, keeping only the frontmost populated
# rank (plus small attached pieces one rank back). Two things broke the field HUD at 16:9:
#   1. the prepass list (2048) filled with the town's quads before the HUD, which the field draws
#      last, so every HUD piece was refused ("cap"): when full, items of deeper ranks are
#      dropped now instead of the new ones;
#   2. the field HUD spans three ranks: 1097 frames (status panel, Vitality/Endurance sprite),
#      1098 bars and numbers, 1099 letters; in the field (sh_ws_hud_ranks, shaolin_pc.c) the
#      three frontmost ranks are all HUD. The town reaches those ranks only within ~100 units
#      of the camera, and such geometry is too big or not axis-aligned to be admitted.
get_target_property(_sh_srcs sh-game SOURCES)
list(FILTER _sh_srcs EXCLUDE REGEX "[/\]runtime[/\]src[/\]gpu[.]c$")
set_property(TARGET sh-game PROPERTY SOURCES "${_sh_srcs}")
file(READ "${PSXRECOMP_ROOT}/runtime/src/gpu.c" _sh_gpu)
sh_patch(_sh_gpu [==[static void ws_ui_prepass_add(const uint32_t *words, uint32_t word_count,]==]
  [==[int sh_ws_hud_ranks(void);   /* Shaolin Recomp (shaolin_pc.c): HUD ranks at the front */
/* Shaolin Recomp: room in a full prepass list for a primitive of `rank` (ranks arrive in
 * increasing order): keep only the ranks that can still be HUD. */
static void sh_ws_ui_compact(uint16_t rank) {
    const int keep_ranks = sh_ws_hud_ranks();
    uint16_t prev = 0xFFFFu;   /* the populated rank just below this one */
    for (uint32_t i = 0; i < ws_ui_prepass_count; i++) {
        const uint16_t r = ws_ui_prepass[i].ot_rank;
        if (r < rank && (prev == 0xFFFFu || r > prev)) prev = r;
    }
    uint32_t lo = prev == 0xFFFFu ? rank : prev;
    if (rank + 1u >= (uint32_t)keep_ranks && rank + 1u - (uint32_t)keep_ranks < lo)
        lo = rank + 1u - (uint32_t)keep_ranks;
    uint32_t out = 0;
    for (uint32_t i = 0; i < ws_ui_prepass_count; i++)
        if (ws_ui_prepass[i].ot_rank >= lo) ws_ui_prepass[out++] = ws_ui_prepass[i];
    ws_ui_prepass_count = out;
}
static void ws_ui_prepass_add(const uint32_t *words, uint32_t word_count,]==])
sh_patch(_sh_gpu [==[    if (rank == 0xFFFFu) return;
    if (ws_ui_prepass_count >= WS_UI_PREPASS_MAX) { ws_ui_reject.cap++; return; }]==]
  [==[    if (rank == 0xFFFFu) return;
    if (ws_ui_prepass_count >= WS_UI_PREPASS_MAX) sh_ws_ui_compact(rank);
    if (ws_ui_prepass_count >= WS_UI_PREPASS_MAX) { ws_ui_reject.cap++; return; }]==])
sh_patch(_sh_gpu [==[        keep[i] = ws_ui_prepass[i].ot_rank == max_rank &&
                  !ws_ui_prepass[i].enclosed_only;]==]
  [==[        keep[i] = (ws_ui_prepass[i].ot_rank == max_rank ||
                   (uint32_t)ws_ui_prepass[i].ot_rank + (uint32_t)sh_ws_hud_ranks() > max_rank) &&
                  !ws_ui_prepass[i].enclosed_only;]==])
# Loading cards at 16:9 (seventh session). The fight module is already resident (module 4, a
# gameplay value) while its NOW LOADING card shows, so the card was presented wide: the 4:3
# painting stretched and its two-layer title text half squashed (two copies of the letters at
# different widths). A gameplay-state frame that has projected nothing through the GTE for 6
# VBlanks (a 30 Hz game projects every 2) is a flat 2D screen: 4:3 with the blurred sides.
# The field's save screen keeps the GTE busy behind it, so a frame that has drawn no world
# polygons for 6 VBlanks counts too (sh_ws_no_world, sh_ghost.c).
sh_patch(_sh_gpu [==[    int state_match = ws_gameplay_state_matches();
    if (state_match >= 0) return state_match;]==]
  [==[    extern int sh_ws_no_world(void);   /* Shaolin Recomp (sh_ghost.c) */
    int state_match = ws_gameplay_state_matches();
    if (state_match > 0 && ws_gte_game_mode_cfg &&
        ((uint32_t)s_frame_count - ws_last_gte_stamp > 6u || sh_ws_no_world())) return 0;   /* Shaolin: 2D screen */
    if (state_match >= 0) return state_match;]==])
# Field boxes at 16:9 (sixth session). The pause box's white frame is drawn with GP0 lines, which
# the runtime never squashes, so it stayed wide around its squashed fill: lines (mono 0x40-0x47,
# shaded 0x50-0x57) are admitted to the prepass by their bounding box and squashed with their
# widget like a triangle part. The dialogue box fill (470 x 106) is wider than half and taller
# than a quarter of the screen, which the runtime treats as a background overlay and leaves wide
# while the frame sprites around it squash: in the field (sh_ws_big_ui) such panels are HUD unless
# they span the whole width (fades still widen).
sh_patch(_sh_gpu [==[static const WsUiPrepassItem *ws_auto_ui_item(void) {]==]
  [==[int sh_ws_big_ui(void);   /* Shaolin Recomp (shaolin_pc.c): big panels are HUD (the field) */
/* Shaolin Recomp: the admitted item for a polyline (no packet guard: its body streams in). */
static const WsUiPrepassItem *s_sh_pl_item;
static const WsUiPrepassItem *sh_ws_item_at(uint32_t key) {
    if (!ws_auto_ui_squash || !ws_active() || key == GPU_RAM_KEY(0xFFFFFFFFu)) return NULL;
    for (uint32_t i = 0; i < ws_ui_prepass_count; i++)
        if (ws_ui_prepass[i].src_addr == key) return &ws_ui_prepass[i];
    return NULL;
}
/* Words of the mono polyline at word `offset` of a node (command, vertices, terminator), or -1. */
static int sh_polyline_words(uint32_t word_addr, uint32_t offset, uint32_t num_words, uint8_t op) {
    if (op < 0x48u || op > 0x4Fu) return -1;
    for (uint32_t i = 3; i < 12u && offset + i < num_words; i++) {
        uint32_t w = psx_read_word(psx_mod_gpu_dma_resolve_address(word_addr + (offset + i) * 4u));
        if ((w & 0xF000F000u) == 0x50005000u) return (int)i + 1;
    }
    return -1;
}
static const WsUiPrepassItem *ws_auto_ui_item(void) {]==])
sh_patch(_sh_gpu [==[                int count = gp0_command_word_count(op);
]==]
  [==[                int count = gp0_command_word_count(op);
                if (count < 0) count = sh_polyline_words(word_addr, offset, num_words, op);
]==])
sh_patch(_sh_gpu [==[        gp0_state = shaded ? GP0_POLYLINE_SHADED : GP0_POLYLINE_MONO;]==]
  [==[        gp0_state = shaded ? GP0_POLYLINE_SHADED : GP0_POLYLINE_MONO;
        s_sh_pl_item = shaded ? NULL : sh_ws_item_at(GPU_RAM_KEY(gp0_next_source_addr));]==])
sh_patch(_sh_gpu [==[        parse_vertex(val, &x, &y);
        x += draw_offset_x; y += draw_offset_y;
        if (polyline_has_prev &&]==]
  [==[        parse_vertex(val, &x, &y);
        if (s_sh_pl_item) {   /* Shaolin Recomp: a box frame polyline squashes with its widget */
            const double s = ws_auto_ui_size();
            x = ws_ui_x(x, s_sh_pl_item->group.anchor, s) + ws_shared_ui_delta();
            y = ws_ui_y(y, s_sh_pl_item->anchor_y, s);
        }
        x += draw_offset_x; y += draw_offset_y;
        if (polyline_has_prev &&]==])
sh_patch(_sh_gpu [==[(width > W / 2 && height > H / 4)) {
        ws_ui_reject.too_big++;]==]
  [==[(width > W / 2 && height > H / 4 && !sh_ws_big_ui())) {
        ws_ui_reject.too_big++;]==])
sh_patch(_sh_gpu [==[(width > W / 2 && height > H / 4))
        return 0;]==]
  [==[(width > W / 2 && height > H / 4 && !sh_ws_big_ui()))
        return 0;]==])
sh_patch(_sh_gpu [==[(*w > W / 2 && *h > H / 4))
        return 0;]==]
  [==[(*w > W / 2 && *h > H / 4 && !sh_ws_big_ui()))
        return 0;]==])
sh_patch(_sh_gpu [==[    } else if (op >= 0x60u && op <= 0x7Fu) {
        /* GP0 rectangle / sprite.]==]
  [==[    } else if ((op >= 0x40u && op <= 0x4Fu && (op < 0x48u || word_count >= 4u)) ||
               (op >= 0x50u && op <= 0x57u)) {
        /* Shaolin Recomp: a line or mono polyline (a box frame); squashed with its widget.
         * A polyline's words end with its terminator. */
        const uint32_t last = op >= 0x48u ? word_count - 2u : (op >= 0x50u ? 3u : 2u);
        parse_vertex(words[1], &min_x, &min_y);
        max_x = min_x; max_y = min_y;
        for (uint32_t k = 2; k <= last && k < 12u; k++) {
            if (op >= 0x50u && k != 3u) continue;
            int32_t vx, vy;
            parse_vertex(words[k], &vx, &vy);
            if (vx < min_x) min_x = vx;
            if (vx > max_x) max_x = vx;
            if (vy < min_y) min_y = vy;
            if (vy > max_y) max_y = vy;
        }
        max_x++; max_y++;
    } else if (op >= 0x60u && op <= 0x7Fu) {
        /* GP0 rectangle / sprite.]==])
sh_patch(_sh_gpu [==[    int32_t vx[2] = { x0, x1 };
    ws_nw_hud_shift_vertices(vx, 2);
    x0 = vx[0]; x1 = vx[1];
]==]
  [==[    int32_t vx[2] = { x0, x1 };
    ws_nw_hud_shift_vertices(vx, 2);
    if (ws_active()) {   /* Shaolin Recomp: a box frame line squashes with its widget */
        int32_t sh_vy[2] = { y0, y1 };
        if (ws_auto_ui_transform_part(vx, sh_vy, 2)) { y0 = sh_vy[0]; y1 = sh_vy[1]; }
    }
    x0 = vx[0]; x1 = vx[1];
]==])
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/shaolin_gpu.c" "${_sh_gpu}")
target_sources(sh-game PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/shaolin_gpu.c")
set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/shaolin_gpu.c" PROPERTIES
  INCLUDE_DIRECTORIES "${PSXRECOMP_ROOT}/runtime/src")
# Smooth motion (frame generation): its vertex identity asks sh_fgkey.c for the address the
# GTE input vertex was loaded from, so a vertex the game re-transforms every frame (fighters,
# sets) keeps one identity from frame to frame. gte.cpp is compiled from a copy with that call.
get_target_property(_sh_srcs sh-game SOURCES)
list(FILTER _sh_srcs EXCLUDE REGEX "[/\]runtime[/\]src[/\]gte[.]cpp$")
set_property(TARGET sh-game PROPERTY SOURCES "${_sh_srcs}")
file(READ "${PSXRECOMP_ROOT}/runtime/src/gte.cpp" _sh_gte)
sh_patch(_sh_gte [==[static void fgsrc_note(const GTEState *g, int32_t packed, uint32_t ra, const int16_t v[3]) {]==]
  [==[extern "C" uint32_t sh_fg_vertex_key(int k, int16_t x, int16_t y, int16_t z);   /* Shaolin: sh_fgkey.c */
static void fgsrc_note(const GTEState *g, int32_t packed, uint32_t ra, const int16_t v[3]) {]==])
sh_patch(_sh_gte [==[    const uint32_t w[4] = { ra, (uint16_t)v[0], (uint16_t)v[1], (uint16_t)v[2] };]==]
  [==[    uint32_t w[4] = { ra, (uint16_t)v[0], (uint16_t)v[1], (uint16_t)v[2] };
    {   /* Shaolin: the input vertex's load address, when known, instead of its value */
        const uint32_t key = sh_fg_vertex_key(v == g->V0 ? 0 : v == g->V1 ? 1 : 2, v[0], v[1], v[2]);
        if (key) { w[1] = key; w[2] = 0x5348u; w[3] = 0u; }
    }]==])
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/shaolin_gte.cpp" "${_sh_gte}")
target_sources(sh-game PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/shaolin_gte.cpp")
set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/shaolin_gte.cpp" PROPERTIES
  INCLUDE_DIRECTORIES "${PSXRECOMP_ROOT}/runtime/src")
# Generated game and overlay code without the per-block debug hooks (call logging, cycle
# observers, write traces): the player build's main CPU saving. No struct layout depends on
# PSX_NO_DEBUG_TOOLS, so these objects link with the debug-tools runtime as before.
get_target_property(_sh_sources sh-game SOURCES)
set(_sh_generated ${_sh_sources})
list(FILTER _sh_generated INCLUDE REGEX "framework-generated[/\]|overlays_static")
# SH_DEBUG_TOOLS (developer builds only, off by default): keep the write traces for reverse
# engineering (write_trace on the debug port).
option(SH_DEBUG_TOOLS "Shaolin developer build with the debug hooks" OFF)
if(SH_DEBUG_TOOLS)
  set(_sh_nodbg "")
else()
  set(_sh_nodbg "PSX_NO_DEBUG_TOOLS=1")
endif()
set_source_files_properties(${_sh_generated} PROPERTIES COMPILE_DEFINITIONS "${_sh_nodbg}")
# Perspective-correct textures, the PC way: the game projects every 3D vertex in a handful of
# main-executable routines (0x80025000-0x8002B000: GTE projection into a vertex table, then
# copies into GPU packets). Only the generated files holding those routines report their
# loads and stores to the runtime's precision tracker (PSX_PGXP=1), so each packet vertex keeps
# its exact depth and the renderer maps textures with true perspective. The rest of the game,
# fight logic included, compiles as before. Files are picked by the routines they contain.
set(_sh_render_markers "/* 0x8002550C:" "/* 0x80026660:" "/* 0x80027FE0:" "/* 0x80029880:" "/* 0x8002A0F0:" "/* 0x8002BD74:" "/* 0x80042288:" "/* 0x800436E8:")
set(_sh_render_files)
foreach(_f ${_sh_generated})
  if(_f MATCHES "framework-generated[/\\]SLES_016[.]58_full_[0-9]+[.]c$")
    file(READ "${_f}" _txt)
    foreach(_m ${_sh_render_markers})
      string(FIND "${_txt}" "${_m}" _at)
      if(_at GREATER -1)
        list(APPEND _sh_render_files "${_f}")
        break()
      endif()
    endforeach()
  endif()
endforeach()
list(REMOVE_DUPLICATES _sh_render_files)
list(LENGTH _sh_render_files _sh_render_n)
if(_sh_render_n EQUAL 0)
  message(FATAL_ERROR "Shaolin: the 3D drawing routines were not found in the generated code")
endif()
message(STATUS "Shaolin: precise 3D vertices from ${_sh_render_n} generated file(s)")
set_source_files_properties(${_sh_render_files} PROPERTIES COMPILE_DEFINITIONS "${_sh_nodbg};PSX_PGXP=1")
# memory.c too: its per-store write-trace check is a debugger feature (about 6% of a field
# frame). The debug server and its read-only commands keep working.
set_source_files_properties("${PSXRECOMP_ROOT}/runtime/src/memory.c" PROPERTIES COMPILE_DEFINITIONS "${_sh_nodbg}")
set(SH_PREFIX_MAPS "-ffile-prefix-map=${PSXRECOMP_ROOT}=psxrecomp" "-ffile-prefix-map=${SH_PRIVATE_ROOT}=game"
  "-ffile-prefix-map=${CMAKE_CURRENT_BINARY_DIR}=build" "-ffile-prefix-map=${CMAKE_CURRENT_SOURCE_DIR}=source")
target_compile_options(sh-game PRIVATE ${SH_PREFIX_MAPS})
if(WIN32)
  target_link_options(sh-game PRIVATE "-Wl,--no-insert-timestamp" "-Wl,--build-id=none")
endif()
# 60 FPS (shaolin_pc.c): 60 Hz guest timing, the battle engine's own every-VBlank mode,
# and the cycle-scale gate. Generated callers of the frame-interval setter live in other
# objects (overlays, dispatch), so --wrap reaches them.
target_sources(sh-game PRIVATE shaolin_pc.c pc_menu.c sh_window.cpp sh_camera.c sh_ghost.c sh_fgkey.c sh_hdart.c sh_villagers.c sh_mainmenu.c)
target_include_directories(sh-game PRIVATE "${PSXRECOMP_ROOT}/runtime/include")
target_link_options(sh-game PRIVATE "-Wl,--wrap=psx_video_timing_set_pal"
  "-Wl,--wrap=func_8003AD9C" "-Wl,--wrap=func_8003F920" "-Wl,--wrap=psx_guest_cycle_scale_vblank"
  "-Wl,--wrap=func_80020AB0" "-Wl,--wrap=sio_set_pad_state_slot" "-Wl,--wrap=func_8001DADC" "-Wl,--wrap=gpu_set_gp0_linked_list_node" "-Wl,--wrap=gpu_ws_end_linked_list" "-Wl,--wrap=psx_pgxp_load" "-Wl,--wrap=psx_pgxp_cop2" "-Wl,--wrap=func_800406D8" "-Wl,--wrap=func_80020910")
