// retroDE_ps2 — tb_gs_image_xfer_swizzle_psmct32 (Ch121)
//
// Write-side wiring of the Ch119 PSMCT32 swizzle math into
// gif_image_xfer_stub. PSMCT32 TRXDIR uploads now route their
// per-pixel VRAM byte address through gs_swizzle_psmct32_stub
// when the new `PSMCT32_SWIZZLE=1` parameter is set. PSMCT16 /
// PSMT8 / PSMT4 uploads always take the linear path (their
// swizzle math is a future chapter), so the existing 109+
// linear-path TBs are unaffected (default parameter is 0).
//
// Topology — keeps the proof end-to-end:
//
//   TB.gif_reg_wr_*  →  gs_stub (TRX latches only)
//                     → gif_image_xfer_stub#(PSMCT32_SWIZZLE=1)
//                     → vram_stub
//                     → gs_pcrtc_stub#(PSMCT32_SWIZZLE=1) → r/g/b
//
// Phase 1 (write-side lock): TRXDIR upload of a 16×4 PSMCT32
// image. Each pixel has a unique 32-bit color. After the upload
// completes, the TB reads VRAM via the second read port at the
// SWIZZLED byte address (computed by an in-TB ref_addr() that
// mirrors gs_swizzle_psmct32_stub) and asserts each pixel
// landed where the swizzle says it should. As strict separators
// against a hypothetical fall-through to the linear path, the
// TB also asserts that bytes 512 and 768 stay 0: under the
// LINEAR formula, those would hold pixels (0, 2) and (0, 3) of
// row-stride FBW*64*4 = 256, but under SWIZZLED with FBP=0 +
// FBW=1 the 16×4 image only writes blocks (0,0) and (1,0),
// which together occupy bytes [0..127] ∪ [256..383] — bytes
// past 511 are strictly untouched.
//
// Phase 2 (end-to-end agreement): without changing VRAM, enable
// the scanout path (PMODE/DISPFB1/DISPLAY1) and capture a full
// 16×4 frame. Both the upload (Ch121) and the scanout (Ch120)
// instantiate the same gs_swizzle_psmct32_stub, so this phase
// proves the two integrations agree at byte level — what was
// uploaded comes out on r/g/b at the same (x, y) position. This
// is the "compare against scanout" cross-check Codex called out
// when greenlighting the chapter.
//
// Phase 3 (non-origin transfer): re-arm the engine with NONZERO
// DBP, DSAX, and DSAY (DBP=8, DSAX=4, DSAY=2) and verify each
// uploaded pixel lands at `DBP*256 + swizzle(0, DBW, DSAX+x_local,
// DSAY+y_local)`. This pins TWO contracts the origin transfer
// can't distinguish from a buggy implementation: (a) `dest_base_q
// (= DBP*256)` is correctly ADDED ON TOP of the swizzle output
// (with DBP=0 a missing-add regression would still pass), and
// (b) the swizzle is fed the FULL effective coords (with DSAX=
// DSAY=0 a "feeds only cur_x/cur_y" regression would still
// pass). Phase 3 places its image one page after Phase 1's so
// the two regions don't overlap.

`timescale 1ns/1ps

module tb_gs_image_xfer_swizzle_psmct32;

    localparam int PCRTC_H_ACTIVE = 16;
    localparam int PCRTC_V_ACTIVE = 4;

    logic clk;
    logic rst_n;
    initial clk = 1'b0;
    always #5 clk = ~clk;

    // ------------------------------------------------------------
    // gs_stub — only used here for its TRX-register latches +
    // trxdir_wr_q pulse. Everything else (raster, prim, scanout)
    // is unused.
    // ------------------------------------------------------------
    logic        gif_reg_wr_en;
    logic [7:0]  gif_reg_num;
    logic [63:0] gif_reg_data;

    // PCRTC feeds — driven by the TB directly. Separate from
    // gs_stub's pmode_q / dispfb1_q / display1_q outputs (which
    // reflect gs_stub's priv-MMIO latches) because we don't drive
    // priv MMIO writes here; we just need pcrtc to see a valid
    // scanout config in Phase 2.
    logic [63:0] tb_pmode_q;
    logic [63:0] tb_dispfb1_q;
    logic [63:0] tb_display1_q;

    logic [7:0]          bg_r, bg_g, bg_b;
    logic [63:0]         pmode_q, dispfb1_q, display1_q;
    logic [63:0]         prim_q, rgbaq_q, xyz2_q, xyzf2_q, frame_1_q, zbuf_1_q;
    logic [63:0]         tex0_1_q;
    logic [13:0]         tex0_1_cbp_q;
    logic [3:0]          tex0_1_cpsm_q;
    logic                tex0_1_csm_q;
    logic [4:0]          tex0_1_csa_q;
    logic [2:0]          tex0_1_cld_q;
    logic                tex0_1_wr_q;
    logic [63:0]         bitbltbuf_q, trxpos_q, trxreg_q, trxdir_q;
    logic                trxdir_wr_q;
    logic                prim_complete;
    logic [31:0]         prim_complete_count;
    logic [63:0]         prim_v0_q, prim_v1_q, prim_v2_q;
    logic [63:0]         prim_color_q;
    logic [63:0]         prim_color_v0_q, prim_color_v1_q, prim_color_v2_q;
    trace_pkg::vertex_t  prim_v0_decoded_q, prim_v1_decoded_q, prim_v2_decoded_q;
    trace_pkg::color_t   prim_v0_color_decoded_q, prim_v1_color_decoded_q, prim_v2_color_decoded_q;
    logic                pixel_emit;
    logic [31:0]         pixel_emit_count;
    logic [11:0]         pixel_x_q, pixel_y_q;
    logic [63:0]         pixel_color_q;
    logic [8:0]          pixel_fbp_q;
    logic [5:0]          pixel_fbw_q, pixel_psm_q;
    logic [31:0]         pixel_fb_addr_q;
    logic                raster_pixel_emit;
    logic [31:0]         raster_pixel_emit_count;
    logic [11:0]         raster_pixel_x_q, raster_pixel_y_q;
    logic [63:0]         raster_pixel_color_q;
    logic [31:0]         raster_pixel_fb_addr_q;
    logic [3:0]          raster_pixel_be_q;
    logic [31:0]         raster_pixel_mask_q;
    logic [5:0]          raster_pixel_psm_q;
    logic                raster_active;
    logic                raster_overflow;
    logic                raster_degenerate;
    logic                gs_ev_valid;
    trace_pkg::subsys_e  gs_ev_subsys;
    trace_pkg::event_e   gs_ev_event;
    logic [63:0]         gs_ev_arg0, gs_ev_arg1, gs_ev_arg2, gs_ev_arg3;
    logic [31:0]         gs_ev_flags;

    gs_stub u_gs (
        .clk(clk), .rst_n(rst_n),
        .reg_wr_en(1'b0), .reg_wr_addr(16'd0), .reg_wr_data(64'd0),
        .gif_reg_wr_en(gif_reg_wr_en),
        .gif_reg_num(gif_reg_num),
        .gif_reg_data(gif_reg_data),
        .bg_r(bg_r), .bg_g(bg_g), .bg_b(bg_b),
        .pmode_q(pmode_q), .dispfb1_q(dispfb1_q), .display1_q(display1_q),
        .prim_q(prim_q), .rgbaq_q(rgbaq_q),
        .xyz2_q(xyz2_q), .xyzf2_q(xyzf2_q),
        .frame_1_q(frame_1_q), .zbuf_1_q(zbuf_1_q),
        .tex0_1_q(tex0_1_q),
        .tex0_1_cbp_q(tex0_1_cbp_q),
        .tex0_1_cpsm_q(tex0_1_cpsm_q),
        .tex0_1_csm_q(tex0_1_csm_q),
        .tex0_1_csa_q(tex0_1_csa_q),
        .tex0_1_cld_q(tex0_1_cld_q),
        .tex0_1_wr_q(tex0_1_wr_q),
        .bitbltbuf_q(bitbltbuf_q),
        .trxpos_q(trxpos_q),
        .trxreg_q(trxreg_q),
        .trxdir_q(trxdir_q),
        .trxdir_wr_q(trxdir_wr_q),
        .prim_complete(prim_complete),
        .prim_complete_count(prim_complete_count),
        .prim_v0_q(prim_v0_q), .prim_v1_q(prim_v1_q), .prim_v2_q(prim_v2_q),
        .prim_color_q(prim_color_q),
        .prim_color_v0_q(prim_color_v0_q),
        .prim_color_v1_q(prim_color_v1_q),
        .prim_color_v2_q(prim_color_v2_q),
        .prim_v0_decoded_q(prim_v0_decoded_q),
        .prim_v1_decoded_q(prim_v1_decoded_q),
        .prim_v2_decoded_q(prim_v2_decoded_q),
        .prim_v0_color_decoded_q(prim_v0_color_decoded_q),
        .prim_v1_color_decoded_q(prim_v1_color_decoded_q),
        .prim_v2_color_decoded_q(prim_v2_color_decoded_q),
        .pixel_emit(pixel_emit),
        .pixel_emit_count(pixel_emit_count),
        .pixel_x_q(pixel_x_q), .pixel_y_q(pixel_y_q),
        .pixel_color_q(pixel_color_q),
        .pixel_fbp_q(pixel_fbp_q),
        .pixel_fbw_q(pixel_fbw_q),
        .pixel_psm_q(pixel_psm_q),
        .pixel_fb_addr_q(pixel_fb_addr_q),
        .raster_pixel_emit(raster_pixel_emit),
        .raster_pixel_emit_count(raster_pixel_emit_count),
        .raster_pixel_x_q(raster_pixel_x_q),
        .raster_pixel_y_q(raster_pixel_y_q),
        .raster_pixel_color_q(raster_pixel_color_q),
        .raster_pixel_fb_addr_q(raster_pixel_fb_addr_q),
        .raster_pixel_be_q(raster_pixel_be_q),
        .raster_pixel_mask_q(raster_pixel_mask_q),
        .raster_pixel_psm_q(raster_pixel_psm_q),
        .raster_active(raster_active),
        .raster_overflow(raster_overflow),
        .raster_degenerate(raster_degenerate),
        .ev_valid(gs_ev_valid),
        .ev_subsys(gs_ev_subsys),
        .ev_event(gs_ev_event),
        .ev_arg0(gs_ev_arg0), .ev_arg1(gs_ev_arg1),
        .ev_arg2(gs_ev_arg2), .ev_arg3(gs_ev_arg3),
        .ev_flags(gs_ev_flags)
    );

    // ------------------------------------------------------------
    // gif_image_xfer_stub with the new Ch121 swizzle gate ON.
    // ------------------------------------------------------------
    logic         xfer_data_valid;
    logic [127:0] xfer_data_qword;
    logic         xfer_data_last;
    logic         xfer_data_ready;
    logic         xfer_we;
    logic [31:0]  xfer_waddr;
    logic [31:0]  xfer_wdata;
    logic [3:0]   xfer_wbe;
    logic [31:0]  xfer_wmask;
    logic         xfer_busy;

    gif_image_xfer_stub #(
        .PSMCT32_SWIZZLE(1'b1)
    ) u_xfer (
        .clk(clk), .rst_n(rst_n),
        .trxdir_wr_pulse(trxdir_wr_q),
        .trxdir(trxdir_q),
        .bitbltbuf(bitbltbuf_q),
        .trxpos(trxpos_q),
        .trxreg(trxreg_q),
        .data_valid(xfer_data_valid),
        .data_qword(xfer_data_qword),
        .data_last (xfer_data_last),
        .data_ready(xfer_data_ready),
        .vram_we   (xfer_we),
        .vram_waddr(xfer_waddr),
        .vram_wdata(xfer_wdata),
        .vram_wbe  (xfer_wbe),
        .vram_wmask(xfer_wmask),
        .busy      (xfer_busy)
    );

    // ------------------------------------------------------------
    // vram_stub. Two readers in this TB:
    //   read_addr/data  → driven by pcrtc (Phase 2 scanout)
    //   read2_addr/data → driven by TB    (Phase 1 byte readback)
    // ------------------------------------------------------------
    logic [31:0] vram_raddr;
    logic [31:0] vram_rdata;
    logic [31:0] vram_raddr2;
    logic [31:0] vram_rdata2;

    vram_stub #(.BYTES(16384)) u_vram (
        .clk(clk), .rst_n(rst_n),
        .write_en  (xfer_we),
        .write_addr(xfer_waddr),
        .write_data(xfer_wdata),
        .write_be  (xfer_wbe),
        .write_mask(xfer_wmask),
        .read_addr (vram_raddr),
        .read_data (vram_rdata),
        .read2_addr(vram_raddr2),
        .read2_data(vram_rdata2)
    );

    // ------------------------------------------------------------
    // gs_pcrtc_stub with Ch120 swizzle gate ON. Drives vram_raddr.
    // ------------------------------------------------------------
    logic       hsync_o, vsync_o, de_o;
    logic [7:0] r_o, g_o, b_o;
    logic                pcrtc_ev_valid;
    trace_pkg::subsys_e  pcrtc_ev_subsys;
    trace_pkg::event_e   pcrtc_ev_event;
    logic [63:0]         pcrtc_ev_arg0, pcrtc_ev_arg1;
    logic [63:0]         pcrtc_ev_arg2, pcrtc_ev_arg3;
    logic [31:0]         pcrtc_ev_flags;

    gs_pcrtc_stub #(
        .H_ACTIVE(PCRTC_H_ACTIVE), .H_FRONT(1), .H_SYNC(1), .H_BACK(1),
        .V_ACTIVE(PCRTC_V_ACTIVE), .V_FRONT(1), .V_SYNC(1), .V_BACK(1),
        .PSMCT32_SWIZZLE(1'b1)
    ) u_pcrtc (
        .clk(clk), .rst_n(rst_n),
        .pmode_q       (tb_pmode_q),
        .dispfb1_q     (tb_dispfb1_q),
        .display1_q    (tb_display1_q),
        .vram_read_addr(vram_raddr),
        .vram_read_data(vram_rdata),
        .clut_enable   (1'b0),
        .clut_csa      (5'd0),
        .clut_read_idx (),
        .clut_read_data(32'd0),
        .hsync(hsync_o), .vsync(vsync_o), .de(de_o),
        .r(r_o), .g(g_o), .b(b_o),
        .ev_valid(pcrtc_ev_valid),
        .ev_subsys(pcrtc_ev_subsys),
        .ev_event(pcrtc_ev_event),
        .ev_arg0(pcrtc_ev_arg0), .ev_arg1(pcrtc_ev_arg1),
        .ev_arg2(pcrtc_ev_arg2), .ev_arg3(pcrtc_ev_arg3),
        .ev_flags(pcrtc_ev_flags)
    );

    // ------------------------------------------------------------
    // Counters + invariants observers.
    // ------------------------------------------------------------
    int  errors;
    int  xfer_writes_seen;
    int  trxdir_arms_seen;

    initial begin
        errors           = 0;
        xfer_writes_seen = 0;
        trxdir_arms_seen = 0;
    end

    always_ff @(posedge clk) begin
        if (rst_n && trxdir_wr_q)
            trxdir_arms_seen <= trxdir_arms_seen + 1;
        if (rst_n && xfer_we) begin
            xfer_writes_seen <= xfer_writes_seen + 1;
            if (xfer_wbe !== 4'b1111) begin
                $error("xfer write %0d: be=%b (expected 4'b1111 for PSMCT32)",
                       xfer_writes_seen, xfer_wbe);
                errors <= errors + 1;
            end
            if (xfer_wmask !== 32'hFFFF_FFFF) begin
                $error("xfer write %0d: mask=0x%08x (expected 0xFFFFFFFF)",
                       xfer_writes_seen, xfer_wmask);
                errors <= errors + 1;
            end
        end
    end

    // ------------------------------------------------------------
    // Frame capture (mirrors Ch120 pattern).
    // ------------------------------------------------------------
    logic [7:0] cap_r [0:PCRTC_V_ACTIVE-1][0:PCRTC_H_ACTIVE-1];
    logic [7:0] cap_g [0:PCRTC_V_ACTIVE-1][0:PCRTC_H_ACTIVE-1];
    logic [7:0] cap_b [0:PCRTC_V_ACTIVE-1][0:PCRTC_H_ACTIVE-1];
    logic       cap_de[0:PCRTC_V_ACTIVE-1][0:PCRTC_H_ACTIVE-1];
    bit         capture_armed;

    initial begin
        for (int y = 0; y < PCRTC_V_ACTIVE; y++)
            for (int x = 0; x < PCRTC_H_ACTIVE; x++) begin
                cap_r[y][x]  = 8'd0;
                cap_g[y][x]  = 8'd0;
                cap_b[y][x]  = 8'd0;
                cap_de[y][x] = 1'b0;
            end
        capture_armed = 1'b0;
    end

    always_ff @(posedge clk) begin
        if (rst_n && capture_armed && de_o
            && (u_pcrtc.vcnt < PCRTC_V_ACTIVE)
            && (u_pcrtc.hcnt < PCRTC_H_ACTIVE)) begin
            cap_r [u_pcrtc.vcnt][u_pcrtc.hcnt] <= r_o;
            cap_g [u_pcrtc.vcnt][u_pcrtc.hcnt] <= g_o;
            cap_b [u_pcrtc.vcnt][u_pcrtc.hcnt] <= b_o;
            cap_de[u_pcrtc.vcnt][u_pcrtc.hcnt] <= 1'b1;
        end
    end

    // ------------------------------------------------------------
    // GIF / TRX register helpers.
    // ------------------------------------------------------------
    task automatic step_drive(input logic        wr_en,
                              input logic [7:0]  num,
                              input logic [63:0] data);
        @(negedge clk);
        gif_reg_wr_en = wr_en;
        gif_reg_num   = num;
        gif_reg_data  = data;
        @(posedge clk);
    endtask

    task automatic drive_reg(input logic [7:0] num, input logic [63:0] data);
        step_drive(1'b1, num, data);
    endtask

    task automatic drive_idle();
        step_drive(1'b0, 8'd0, 64'd0);
    endtask

    function automatic logic [63:0] bitbltbuf_pack(
        input logic [13:0] dbp_v,
        input logic [5:0]  dbw_v,
        input logic [5:0]  dpsm_v);
        logic [63:0] v;
        v = 64'd0;
        v[45:32] = dbp_v;
        v[53:48] = dbw_v;
        v[61:56] = dpsm_v;
        return v;
    endfunction
    function automatic logic [63:0] trxpos_pack(
        input logic [10:0] dsax_v,
        input logic [10:0] dsay_v);
        logic [63:0] v;
        v = 64'd0;
        v[42:32] = dsax_v;
        v[58:48] = dsay_v;
        return v;
    endfunction
    function automatic logic [63:0] trxreg_pack(
        input logic [11:0] rrw_v,
        input logic [11:0] rrh_v);
        logic [63:0] v;
        v = 64'd0;
        v[11:0]  = rrw_v;
        v[43:32] = rrh_v;
        return v;
    endfunction
    function automatic logic [63:0] trxdir_pack(input logic [1:0] xdir_v);
        return {62'd0, xdir_v};
    endfunction

    task automatic push_image_qword(input logic [127:0] qword,
                                    input logic         last);
        @(negedge clk);
        wait (xfer_data_ready == 1'b1);
        @(negedge clk);
        xfer_data_valid = 1'b1;
        xfer_data_qword = qword;
        xfer_data_last  = last;
        @(posedge clk);
        @(negedge clk);
        xfer_data_valid = 1'b0;
        xfer_data_qword = 128'd0;
        xfer_data_last  = 1'b0;
    endtask

    // ------------------------------------------------------------
    // PSMCT32 swizzle reference — taken VERBATIM from PCSX2's
    // GSLocalMemoryFunctions.cpp psmt32 block table. (Same
    // function body Ch119 + Ch120 use; reused here so any
    // mistranscription would also trip those TBs.)
    // ------------------------------------------------------------
    function automatic int ref_block_idx(input int by, input int bx);
        case ({by[1:0], bx[2:0]})
            5'd0:  return 0;   5'd1:  return 1;   5'd2:  return 4;
            5'd3:  return 5;   5'd4:  return 16;  5'd5:  return 17;
            5'd6:  return 20;  5'd7:  return 21;  5'd8:  return 2;
            5'd9:  return 3;   5'd10: return 6;   5'd11: return 7;
            5'd12: return 18;  5'd13: return 19;  5'd14: return 22;
            5'd15: return 23;  5'd16: return 8;   5'd17: return 9;
            5'd18: return 12;  5'd19: return 13;  5'd20: return 24;
            5'd21: return 25;  5'd22: return 28;  5'd23: return 29;
            5'd24: return 10;  5'd25: return 11;  5'd26: return 14;
            5'd27: return 15;  5'd28: return 26;  5'd29: return 27;
            5'd30: return 30;  default: return 31;
        endcase
    endfunction

    function automatic logic [31:0] ref_addr(
        input int fbp_v, input int fbw_v, input int x_v, input int y_v);
        int page_x, page_y, page_idx, page_base;
        int by, bx, blk_idx, xb, yb;
        int addr_v;
        page_x   = x_v / 64;
        page_y   = y_v / 32;
        page_idx = page_y * fbw_v + page_x;
        page_base = fbp_v * 2048 + page_idx * 8192;
        by  = (y_v % 32) / 8;
        bx  = (x_v % 64) / 8;
        blk_idx = ref_block_idx(by, bx);
        xb = x_v % 8;
        yb = y_v % 8;
        addr_v = page_base + blk_idx * 256 + yb * 32 + xb * 4;
        return addr_v[31:0];
    endfunction

    // pixel(x, y) = {A=0xFF, B=y[3:0]<<4, G=x[3:0]<<4,
    //                R=0x10 | (y*16+x)} — every pixel in the
    // 16×4 image has a unique (R, G, B) triple so any
    // misaddressed write surfaces immediately.
    function automatic logic [31:0] pixel_at(input int x, input int y);
        logic [7:0] r;
        logic [7:0] g;
        logic [7:0] b;
        r = 8'h10 | 8'(y*16 + x);
        g = 8'((x[3:0] << 4) & 8'hFF);
        b = 8'((y[3:0] << 4) & 8'hFF);
        return {8'hFF, b, g, r};
    endfunction

    // 4 PSMCT32 pixels per IMAGE qword.
    function automatic logic [127:0] qword_for_pixels(
        input int x_base, input int y);
        logic [127:0] q;
        q = 128'd0;
        for (int i = 0; i < 4; i++) begin
            q[i*32 +: 32] = pixel_at(x_base + i, y);
        end
        return q;
    endfunction

    // Phase 3 distinct-color pattern. R upper bit set so it can't
    // collide with Phase 1's R range [0x10..0x3F]; A=0xAA so any
    // alpha-channel mismatch surfaces too.
    function automatic logic [31:0] p3_pixel_at(input int x, input int y);
        logic [7:0] r;
        logic [7:0] g;
        logic [7:0] b;
        r = 8'h80 | 8'(y*8 + x);
        g = 8'(8'hC0 | 8'((x[2:0] << 4) & 8'hFF));
        b = 8'(8'hC0 | 8'((y[2:0] << 4) & 8'hFF));
        return {8'hAA, b, g, r};
    endfunction

    function automatic logic [127:0] p3_qword_for_pixels(
        input int x_base, input int y);
        logic [127:0] q;
        q = 128'd0;
        for (int i = 0; i < 4; i++) begin
            q[i*32 +: 32] = p3_pixel_at(x_base + i, y);
        end
        return q;
    endfunction

    // ------------------------------------------------------------
    // TB-side byte readback via the 2nd VRAM read port.
    // ------------------------------------------------------------
    task automatic check_pixel_at_swizzled(input int x, input int y);
        logic [31:0] addr;
        logic [31:0] expected;
        logic [31:0] got;
        addr     = ref_addr(0, DBW, x, y);
        expected = pixel_at(x, y);
        vram_raddr2 = addr & ~32'd3;
        #1;
        got = vram_rdata2;
        if (got !== expected) begin
            $error("[swizzled-byte] (%0d,%0d) @addr 0x%08x got 0x%08x expected 0x%08x",
                   x, y, addr, got, expected);
            errors = errors + 1;
        end
    endtask

    task automatic check_byte_zero(input logic [31:0] byte_addr,
                                   input string       tag);
        logic [31:0] got;
        vram_raddr2 = byte_addr & ~32'd3;
        #1;
        got = vram_rdata2;
        if (got !== 32'd0) begin
            $error("[%s] @byte 0x%08x got 0x%08x expected 0x00000000",
                   tag, byte_addr, got);
            errors = errors + 1;
        end
    endtask

    // Phase 3: verify a pixel uploaded with non-origin DBP/DSAX/DSAY
    // landed at `DBP*256 + swizzle(0, DBW, DSAX+x, DSAY+y)`. The
    // (x, y) here is the upload-LOCAL coordinate (cur_x, cur_y in
    // the engine); the swizzle's input is the EFFECTIVE coord.
    task automatic check_p3_pixel(input int x_local, input int y_local);
        logic [31:0] addr;
        logic [31:0] expected;
        logic [31:0] got;
        addr     = 32'(P3_DBP * 256)
                 + ref_addr(0, DBW,
                            P3_DSAX + x_local,
                            P3_DSAY + y_local);
        expected = p3_pixel_at(x_local, y_local);
        vram_raddr2 = addr & ~32'd3;
        #1;
        got = vram_rdata2;
        if (got !== expected) begin
            $error("[p3-swizzled-byte] (%0d,%0d) @addr 0x%08x got 0x%08x expected 0x%08x",
                   x_local, y_local, addr, got, expected);
            errors = errors + 1;
        end
    endtask

    // ------------------------------------------------------------
    // Constants.
    // ------------------------------------------------------------
    localparam logic [7:0] R_BITBLTBUF = 8'h50;
    localparam logic [7:0] R_TRXPOS    = 8'h51;
    localparam logic [7:0] R_TRXREG    = 8'h52;
    localparam logic [7:0] R_TRXDIR    = 8'h53;

    // ------------------------------------------------------------
    // Phase 1/2 transfer parameters (origin: DBP=DSAX=DSAY=0).
    // The swizzle output from gs_swizzle_psmct32_stub IS the
    // absolute byte address (FBP=0 input + dest_base_q=0 added).
    // ------------------------------------------------------------
    localparam int IMG_DBP = 0;
    localparam int DBW     = 1;
    localparam int RRW     = 16;
    localparam int RRH     = 4;
    localparam int NUM_PIXELS = RRW * RRH;     // 64
    localparam int NUM_QWORDS = NUM_PIXELS / 4; // 16

    // ------------------------------------------------------------
    // Phase 3 transfer parameters (non-origin: nonzero DBP +
    // nonzero DSAX/DSAY). This pins TWO contracts of the Ch121
    // wiring: (a) `dest_base_q (= DBP*256)` is correctly added to
    // the swizzle output, and (b) the swizzle module sees the FULL
    // effective coordinates `(DSAX+cur_x, DSAY+cur_y)`, not just
    // (cur_x, cur_y). A regression that dropped dest_base_q would
    // miss bytes 2048+ entirely; a regression that fed only cur_x/
    // cur_y would land pixels at the wrong block.
    //
    //   DBP=8 → dest_base_q = 2048 (= one page after the Phase 1
    //           write region; no overlap).
    //   DSAX=4, DSAY=2 → upload starts at sub-block offset within
    //           block (0,0); effective_x range = [4..11] crosses
    //           block (0,0) → block (1,0) at the per-pixel level
    //           inside the upload.
    //   DBW=1, RRW=8, RRH=4 → 32 PSMCT32 pixels = 8 IMAGE qwords.
    // ------------------------------------------------------------
    localparam int P3_DBP    = 8;
    localparam int P3_DSAX   = 4;
    localparam int P3_DSAY   = 2;
    localparam int P3_RRW    = 8;
    localparam int P3_RRH    = 4;
    localparam int P3_PIXELS = P3_RRW * P3_RRH; // 32

    initial begin
        rst_n            = 1'b0;
        gif_reg_wr_en    = 1'b0;
        gif_reg_num      = 8'd0;
        gif_reg_data     = 64'd0;
        xfer_data_valid  = 1'b0;
        xfer_data_qword  = 128'd0;
        xfer_data_last   = 1'b0;
        vram_raddr2      = 32'd0;
        tb_pmode_q       = 64'd0;
        tb_dispfb1_q     = 64'd0;
        tb_display1_q    = 64'd0;

        repeat (4) @(posedge clk);
        rst_n = 1'b1;
        repeat (2) @(posedge clk);

        // ------------------------------------------------------------
        // Drive TRX setup via GIF A+D register writes.
        // ------------------------------------------------------------
        drive_reg(R_BITBLTBUF, bitbltbuf_pack(14'(IMG_DBP), 6'(DBW), 6'h00)); // PSMCT32
        drive_reg(R_TRXPOS,    trxpos_pack(11'd0, 11'd0));
        drive_reg(R_TRXREG,    trxreg_pack(12'(RRW), 12'(RRH)));
        // TRXDIR = host→local. trxdir_wr_q pulses next cycle, arms
        // gif_image_xfer_stub.
        drive_reg(R_TRXDIR,    trxdir_pack(2'd0));
        drive_idle();

        // Wait for the engine to enter S_RUN.
        @(posedge clk);
        @(posedge clk);

        // ------------------------------------------------------------
        // Push 16 IMAGE qwords (4 PSMCT32 pixels each, row-major).
        // ------------------------------------------------------------
        for (int yy = 0; yy < RRH; yy++) begin
            for (int qi = 0; qi < (RRW / 4); qi++) begin
                logic [127:0] q;
                bit           is_last;
                q       = qword_for_pixels(qi * 4, yy);
                is_last = (yy == RRH - 1) && (qi == (RRW / 4) - 1);
                push_image_qword(q, is_last);
            end
        end

        // Drain.
        wait (xfer_busy == 1'b0);
        repeat (10) @(posedge clk);

        // ------------------------------------------------------------
        // Phase 1 count check (origin transfer only — Phase 3 will
        // add another arm + writes, asserted separately below).
        // ------------------------------------------------------------
        if (trxdir_arms_seen != 1) begin
            $error("after P1: trxdir_wr_q pulses=%0d (expected 1)",
                   trxdir_arms_seen);
            errors = errors + 1;
        end
        if (xfer_writes_seen != NUM_PIXELS) begin
            $error("after P1: xfer VRAM writes=%0d (expected %0d)",
                   xfer_writes_seen, NUM_PIXELS);
            errors = errors + 1;
        end

        // ------------------------------------------------------------
        // Phase 1 — write-side lock.
        // Verify each pixel landed at its SWIZZLED byte address.
        // ------------------------------------------------------------
        for (int yy = 0; yy < RRH; yy++)
            for (int xx = 0; xx < RRW; xx++)
                check_pixel_at_swizzled(xx, yy);

        // Strict separator: pick a byte address that the LINEAR
        // formula WOULD write but the SWIZZLED formula does NOT,
        // for our 16×4 image at FBW=1, FBP=0.
        //
        //   Linear addresses span:
        //     y=0  → bytes 0..63
        //     y=1  → bytes 256..319    (stride = FBW*64*4 = 256)
        //     y=2  → bytes 512..575
        //     y=3  → bytes 768..831
        //
        //   Swizzled addresses span only blocks (0,0) and (1,0)
        //   inside page 0 (since the image is 16 px wide × 4 px
        //   tall, all in by=0, bx∈{0,1}):
        //     block (0,0) → bytes 0..127  (4 of 8 in-block rows)
        //     block (1,0) → bytes 256..383
        //   Specifically swizzled writes bytes [0..127] ∪ [256..383].
        //
        //   Bytes that linear hits but swizzled does NOT:
        //     {512..575} (linear y=2)  AND  {768..831} (linear y=3).
        //
        // If the upload had silently fallen through to the linear
        // path, byte 512 would hold pixel(0,2)'s color. Assert it
        // stays 0 — strict proof the swizzle gate is live.
        check_byte_zero(32'd512, "linear-y2-byte-still-zero");
        check_byte_zero(32'd768, "linear-y3-byte-still-zero");

        // ------------------------------------------------------------
        // Phase 3 — non-origin transfer. Re-arm the engine with
        // nonzero DBP + nonzero DSAX/DSAY and verify the readback
        // formula `DBP*256 + swizzle(0, DBW, DSAX+x, DSAY+y)`.
        //
        // Rationale: the Ch121 RTL adds two new contracts the Phase-1
        // origin transfer can't distinguish from a buggy version.
        // (a) `dest_base_q = DBP*256` is added on top of the swizzle
        //     output. With DBP=0 in Phase 1, dest_base_q=0, so a
        //     regression that dropped that addition wouldn't surface.
        // (b) The swizzle module is fed the FULL effective
        //     coordinates `(DSAX+cur_x, DSAY+cur_y)`. With
        //     DSAX=DSAY=0 in Phase 1, effective coords equal cur_*,
        //     so a regression that fed only cur_x/cur_y wouldn't
        //     surface. Phase 3 makes both contracts load-bearing.
        //
        // P3 transfer: DBP=8 (= 2048 byte base, page after Phase 1's
        // region — no overlap), DBW=1, DSAX=4, DSAY=2, RRW=8, RRH=4.
        // Effective coords range x∈[4..11], y∈[2..5] — crosses the
        // block (0,0) → block (1,0) boundary at the per-pixel level
        // inside this single upload.
        // ------------------------------------------------------------
        drive_reg(R_BITBLTBUF, bitbltbuf_pack(14'(P3_DBP), 6'(DBW), 6'h00));
        drive_reg(R_TRXPOS,    trxpos_pack(11'(P3_DSAX), 11'(P3_DSAY)));
        drive_reg(R_TRXREG,    trxreg_pack(12'(P3_RRW), 12'(P3_RRH)));
        drive_reg(R_TRXDIR,    trxdir_pack(2'd0));
        drive_idle();

        @(posedge clk);
        @(posedge clk);

        for (int yy = 0; yy < P3_RRH; yy++) begin
            for (int qi = 0; qi < (P3_RRW / 4); qi++) begin
                logic [127:0] q;
                bit           is_last;
                q       = p3_qword_for_pixels(qi * 4, yy);
                is_last = (yy == P3_RRH - 1) && (qi == (P3_RRW / 4) - 1);
                push_image_qword(q, is_last);
            end
        end

        wait (xfer_busy == 1'b0);
        repeat (10) @(posedge clk);

        // Total counts after Phase 3: 2 arms, 64+32=96 writes.
        if (trxdir_arms_seen != 2) begin
            $error("after P3: trxdir_wr_q pulses=%0d (expected 2)",
                   trxdir_arms_seen);
            errors = errors + 1;
        end
        if (xfer_writes_seen != (NUM_PIXELS + P3_PIXELS)) begin
            $error("after P3: xfer VRAM writes=%0d (expected %0d)",
                   xfer_writes_seen, NUM_PIXELS + P3_PIXELS);
            errors = errors + 1;
        end

        // Per-pixel readback for Phase 3.
        for (int yy = 0; yy < P3_RRH; yy++)
            for (int xx = 0; xx < P3_RRW; xx++)
                check_p3_pixel(xx, yy);

        // P3 strict separator: the LINEAR formula for P3 would
        // place pixel(0, 2) at byte:
        //   dest_base + (DSAY+2)*row_stride + (DSAX+0)*4
        //   = 2048 + 4*256 + 16
        //   = 3088
        // The SWIZZLED formula touches only bytes [2048..2431] for
        // this transfer (block (0,0) at base 2048..2175 + block
        // (1,0) at 2304..2431, with parts of each filled). Byte 3088
        // is strictly outside the swizzled range — if a regression
        // dropped dest_base_q, byte 3088 would still stay zero (the
        // engine would write byte 3088-2048=1040 from the swizzle
        // alone, also outside swizzled's range). But a regression
        // that fell through to the LINEAR formula entirely would
        // place P3-pixel(0,2)'s color (R=0x80|16=0x90) at byte 3088.
        // Asserting it stays zero is a strict proof Phase 3 is on
        // the swizzled path.
        check_byte_zero(32'd3088, "p3-linear-y2-byte-still-zero");

        // ------------------------------------------------------------
        // Phase 2 — end-to-end agreement: enable scanout (Ch120's
        // PSMCT32_SWIZZLE=1 path), capture the frame, assert each
        // visible pixel matches its uploaded color. Both modules
        // instantiate the same swizzle module, so a successful
        // capture proves their integrations agree at byte level.
        // ------------------------------------------------------------
        // DISPFB1: FBP=0, FBW=1, PSM=PSMCT32 (=0).
        //   FBW [14:9] = 1 → 0x0200
        //   PSM [19:15] = 0
        tb_dispfb1_q = 64'h0000_0000_0000_0200;
        // DISPLAY1: DX=0, DY=0, DW=15, DH=3, MAGH=MAGV=0
        tb_display1_q = 64'h0030_000F_0000_0000;
        // PMODE.EN1=1
        tb_pmode_q = 64'h0000_0000_0000_0001;

        repeat (40) @(posedge clk);
        capture_armed = 1'b1;
        repeat (300) @(posedge clk);

        for (int yy = 0; yy < PCRTC_V_ACTIVE; yy++) begin
            for (int xx = 0; xx < PCRTC_H_ACTIVE; xx++) begin
                logic [31:0] expected;
                logic [7:0]  exp_r, exp_g, exp_b;
                if (!cap_de[yy][xx]) begin
                    $error("[scanout] (%0d,%0d) DE never asserted", xx, yy);
                    errors = errors + 1;
                end else begin
                    expected = pixel_at(xx, yy);
                    exp_r = expected[7:0];
                    exp_g = expected[15:8];
                    exp_b = expected[23:16];
                    if (cap_r[yy][xx] !== exp_r
                        || cap_g[yy][xx] !== exp_g
                        || cap_b[yy][xx] !== exp_b) begin
                        $error("[scanout] (%0d,%0d) got R=%02x G=%02x B=%02x expected R=%02x G=%02x B=%02x",
                               xx, yy,
                               cap_r[yy][xx], cap_g[yy][xx], cap_b[yy][xx],
                               exp_r, exp_g, exp_b);
                        errors = errors + 1;
                    end
                end
            end
        end

        $display("[tb_gs_image_xfer_swizzle_psmct32] arms=%0d writes=%0d errors=%0d",
                 trxdir_arms_seen, xfer_writes_seen, errors);
        if (errors == 0) $display("[tb_gs_image_xfer_swizzle_psmct32] PASS");
        else             $display("[tb_gs_image_xfer_swizzle_psmct32] FAIL");
        $finish;
    end

    initial begin
        #1000000;
        $error("[tb_gs_image_xfer_swizzle_psmct32] timeout");
        $finish;
    end

endmodule : tb_gs_image_xfer_swizzle_psmct32
