// retroDE_ps2 — tb_gs_raster_swizzle_psmct32 (Ch122)
//
// Third write-side wiring of the Ch119 PSMCT32 swizzle math —
// this time into gs_stub's raster emit channel (the per-pixel
// store path that backs SPRITE/TRI primitives). With the new
// `PSMCT32_SWIZZLE=1` parameter on gs_stub, the per-pixel VRAM
// byte address goes through `gs_swizzle_psmct32_stub` instead of
// the legacy linear formula `(FBW*64*y + x) * 4`. PSMCT16 / PSMT8
// / PSMT4 raster emits stay on the linear path. Default off →
// every existing PSMCT32 raster TB (Ch82..Ch118) is unaffected.
//
// Topology — keeps the proof end-to-end (mirrors Ch121's
// cross-check pattern):
//
//   TB drives PRIM/FRAME_1/RGBAQ/XYZ2 via gif_reg_wr_*
//        →  gs_stub#(PSMCT32_SWIZZLE=1)         (raster emit)
//        →  vram_stub                            (PSMCT32 store)
//        →  gs_pcrtc_stub#(PSMCT32_SWIZZLE=1)   (swizzled scanout)
//        →  r/g/b
//
// Phase 1 (write-side lock): drive a 16×4 SPRITE that fills the
// rect (0,0)..(15,3) — 64 PSMCT32 pixels covering blocks (0,0)
// AND (1,0) horizontally (so the per-pixel block-index lookup
// is exercised, not just within-block row stride). Single
// per-primitive RGBAQ color is enough to lock the address layout:
// every byte the swizzle says should be written is verified to
// hold that color; bytes outside the 16×4 swizzled write set
// (notably the linear-y2 row at byte 512 and the linear-y3 row
// at byte 768) stay 0 — proves the gate is live since a fall-
// through to linear addressing would put the sprite color there.
//
// Phase 2 (end-to-end agreement): without redrawing, enable the
// Ch120 swizzled-pcrtc path, capture the full 16×4 frame, assert
// every visible pixel reads back the SPRITE's RGB. Both gs_stub
// (Ch122) and gs_pcrtc_stub (Ch120) instantiate the same swizzle
// module; a successful capture proves the two integrations agree
// at byte level — what raster wrote at swizzled addresses comes
// out on r/g/b at the same (x, y).
//
// Phase 3 (non-origin raster): re-arm gs_stub with FRAME_1 set
// to FBP=4, FBW=2 and draw an 8×2 SPRITE at (60, 4)..(67, 5).
// This pins three contracts the origin transfer can't:
// (a) `ras_fbp` reaches the swizzle's `fbp` input (FBP=0 in
// Phase 1 would have masked a tied-zero regression),
// (b) `ras_fbw` reaches the swizzle's `fbw` input (FBW=1 would
// have masked a tied-one regression),
// (c) the swizzle gets the FULL absolute pixel coords (s2_x_q,
// s2_y_q) rather than bbox-local — Phase 1's sprite started
// at (0,0), so absolute and local were equal there. The Phase 3
// rect crosses the page-x boundary at x=64 (page (0,0) for
// x∈[60..63], page (1,0) for x∈[64..67]) so page_index actually
// changes mid-row. Strict linear-vs-swizzled separator at byte
// 10480 (where the linear formula's (60, 4) would land) stays 0.

`timescale 1ns/1ps

module tb_gs_raster_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 I/O
    // ------------------------------------------------------------
    logic        gif_reg_wr_en;
    logic [7:0]  gif_reg_num;
    logic [63:0] gif_reg_data;

    logic        priv_reg_wr_en;
    logic [15:0] priv_reg_wr_addr;
    logic [63:0] priv_reg_wr_data;

    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 #(
        .PSMCT32_SWIZZLE(1'b1)
    ) u_gs (
        .clk(clk), .rst_n(rst_n),
        .reg_wr_en  (priv_reg_wr_en),
        .reg_wr_addr(priv_reg_wr_addr),
        .reg_wr_data(priv_reg_wr_data),
        .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)
    );

    // ------------------------------------------------------------
    // vram_stub. Two readers:
    //   read  → driven by pcrtc (Phase 2 scanout)
    //   read2 → driven by TB    (Phase 1 byte readback)
    // ------------------------------------------------------------
    logic [31:0] vram_read_addr;
    logic [31:0] vram_read_data;
    logic [31:0] vram_read2_addr;
    logic [31:0] vram_read2_data;

    vram_stub #(.BYTES(32768)) u_vram (
        .clk(clk), .rst_n(rst_n),
        .write_en  (raster_pixel_emit),
        .write_addr(raster_pixel_fb_addr_q),
        .write_data(raster_pixel_color_q[31:0]),
        .write_be  (raster_pixel_be_q),
        .write_mask(raster_pixel_mask_q),
        .read_addr (vram_read_addr),
        .read_data (vram_read_data),
        .read2_addr(vram_read2_addr),
        .read2_data(vram_read2_data)
    );

    // ------------------------------------------------------------
    // gs_pcrtc_stub with the Ch120 swizzle gate ON.
    // ------------------------------------------------------------
    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       (pmode_q),
        .dispfb1_q     (dispfb1_q),
        .display1_q    (display1_q),
        .vram_read_addr(vram_read_addr),
        .vram_read_data(vram_read_data),
        .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)
    );

    // ------------------------------------------------------------
    // Frame capture (mirrors Ch120 / Ch121 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];

    int errors;
    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
        errors        = 0;
        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 / priv reg drive 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

    task automatic drive_priv(input logic [15:0] addr,
                              input logic [63:0] data);
        @(negedge clk);
        priv_reg_wr_en   = 1'b1;
        priv_reg_wr_addr = addr;
        priv_reg_wr_data = data;
        @(posedge clk);
        @(negedge clk);
        priv_reg_wr_en   = 1'b0;
        priv_reg_wr_addr = 16'd0;
        priv_reg_wr_data = 64'd0;
    endtask

    function automatic logic [63:0] xyz2_data(input logic [11:0] x_int,
                                              input logic [11:0] y_int);
        return {32'd0, y_int, 4'd0, x_int, 4'd0};
    endfunction

    // ------------------------------------------------------------
    // PSMCT32 swizzle reference (mirrors Ch119 / Ch120 / Ch121).
    // ------------------------------------------------------------
    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

    // ------------------------------------------------------------
    // Constants — single-color 16×4 SPRITE.
    //
    //  RGBAQ field layout (low 32 bits): R[7:0], G[15:8],
    //  B[23:16], A[31:24]. PSMCT32 store in vram_stub is little-
    //  endian, so the 32-bit word at byte_addr equals
    //  {A, B, G, R}.
    // ------------------------------------------------------------
    localparam logic [7:0]  R_PRIM     = 8'h00;
    localparam logic [7:0]  R_RGBAQ    = 8'h01;
    localparam logic [7:0]  R_XYZ2     = 8'h05;
    localparam logic [7:0]  R_FRAME_1  = 8'h4C;

    localparam logic [63:0] PRIM_SPRITE = 64'd6;
    // FRAME_1: FBP[8:0]=0, FBW[5:0]=1 (at bit 16), PSM=PSMCT32(0).
    localparam logic [63:0] FRAME_1_VAL = 64'h0000_0000_0001_0000;
    // RGBAQ: R=0x55, G=0xAA, B=0xCC, A=0x77.
    localparam logic [63:0] RGBAQ_VAL   = 64'h0000_0000_77CC_AA55;
    // PSMCT32 word at byte_addr: {A=0x77, B=0xCC, G=0xAA, R=0x55}.
    localparam logic [31:0] PSMCT32_WORD = 32'h77CC_AA55;
    localparam logic [7:0]  EXP_R = 8'h55;
    localparam logic [7:0]  EXP_G = 8'hAA;
    localparam logic [7:0]  EXP_B = 8'hCC;

    localparam int IMG_W = 16;
    localparam int IMG_H = 4;

    // ------------------------------------------------------------
    // Phase 3 — non-origin SPRITE.
    //
    // FRAME_1 changes:  FBP=4 (= 8192-byte base, one page after
    //   FBP=0 — no overlap with Phase 1's image), FBW=2 (= 128 px
    //   per row, so each page-row holds 2 horizontal pages of
    //   PSMCT32 page-width 64). PSMCT32 unchanged.
    //   FRAME_1 layout: FBP[8:0], FBW[5:0] @bit 16, PSM[5:0] @24.
    //   FBP=4 → bits[8:0]=0x004; FBW=2 → bits[21:16]=0x02 → 0x0002_0000.
    //
    // SPRITE rect: v1=(60, 4), v2=(67, 5) — 8×2 = 16 pixels.
    //   Crosses the page-x boundary at x=64 (page (0,0) for x∈
    //   [60..63], page (1,0) for x∈[64..67]). Lands in by=0,
    //   bx∈{7, 0} for the two pages. Strict non-origin coords —
    //   makes ras_fbp / ras_fbw / s2_x_q / s2_y_q all load-bearing
    //   in the swizzle's input mux.
    //
    // RGBAQ for Phase 3: distinct color so a wrong-byte commit
    // can be told apart from Phase 1's sprite.
    //   R=0x33, G=0xCC, B=0x99, A=0xEE → word = 0xEE99_CC33.
    // ------------------------------------------------------------
    localparam logic [63:0] P3_FRAME_1_VAL = 64'h0000_0000_0002_0004;
    localparam logic [63:0] P3_RGBAQ_VAL   = 64'h0000_0000_EE99_CC33;
    localparam logic [31:0] P3_PSMCT32_WORD = 32'hEE99_CC33;
    localparam logic [7:0]  P3_EXP_R = 8'h33;
    localparam logic [7:0]  P3_EXP_G = 8'hCC;
    localparam logic [7:0]  P3_EXP_B = 8'h99;
    localparam int P3_FBP = 4;
    localparam int P3_FBW = 2;
    localparam int P3_X0  = 60;
    localparam int P3_Y0  = 4;
    localparam int P3_X1  = 67;
    localparam int P3_Y1  = 5;
    localparam int P3_W   = (P3_X1 - P3_X0 + 1);  // 8
    localparam int P3_H   = (P3_Y1 - P3_Y0 + 1);  // 2
    localparam int P3_PIXELS = P3_W * P3_H;       // 16

    initial begin
        rst_n            = 1'b0;
        gif_reg_wr_en    = 1'b0;
        gif_reg_num      = 8'd0;
        gif_reg_data     = 64'd0;
        priv_reg_wr_en   = 1'b0;
        priv_reg_wr_addr = 16'd0;
        priv_reg_wr_data = 64'd0;
        vram_read2_addr  = 32'd0;

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

        // ------------------------------------------------------------
        // Drive the 16×4 SPRITE. PRIM=SPRITE → v1+v2 define rect.
        // v1=(0,0), v2=(IMG_W-1, IMG_H-1) covers all 64 pixels
        // (inclusive bounding box). FBP=0, FBW=1, PSMCT32.
        // ------------------------------------------------------------
        drive_reg(R_PRIM,    PRIM_SPRITE);
        drive_reg(R_FRAME_1, FRAME_1_VAL);
        drive_reg(R_RGBAQ,   RGBAQ_VAL);
        drive_reg(R_XYZ2,    xyz2_data(12'd0, 12'd0));            // v1
        drive_reg(R_XYZ2,    xyz2_data(12'(IMG_W - 1),
                                       12'(IMG_H - 1)));          // v2 — close
        drive_idle();

        // Wait for raster to start, then drain.
        wait (raster_active == 1'b1);
        wait (raster_active == 1'b0);
        repeat (10) @(posedge clk);

        if (raster_pixel_emit_count != 32'(IMG_W * IMG_H)) begin
            $error("expected %0d raster emits, got %0d",
                   IMG_W * IMG_H, raster_pixel_emit_count);
            errors = errors + 1;
        end

        // ------------------------------------------------------------
        // Phase 1 — write-side lock. Verify each sprite pixel landed
        // at its SWIZZLED byte address.
        // ------------------------------------------------------------
        for (int yy = 0; yy < IMG_H; yy++) begin
            for (int xx = 0; xx < IMG_W; xx++) begin
                logic [31:0] addr;
                logic [31:0] got;
                addr = ref_addr(0, 1, xx, yy);
                vram_read2_addr = addr & ~32'd3;
                #1;
                got = vram_read2_data;
                if (got !== PSMCT32_WORD) begin
                    $error("[swizzled-byte] (%0d,%0d) @addr 0x%08x got 0x%08x expected 0x%08x",
                           xx, yy, addr, got, PSMCT32_WORD);
                    errors = errors + 1;
                end
            end
        end

        // ------------------------------------------------------------
        // Strict linear-vs-swizzled separators.
        //
        //   Linear addresses for a 16×4 sprite at FBW=1, FBP=0:
        //     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 (image is 16 wide × 4 tall, all in
        //   by=0, bx∈{0,1}): swizzled writes [0..127] ∪ [256..383].
        //
        //   Bytes that linear hits but swizzled does NOT:
        //     {512..575} (linear y=2)  AND  {768..831} (linear y=3).
        //
        // If raster had silently fallen through to the linear path,
        // byte 512 would hold the SPRITE word. Assert it stays 0.
        // ------------------------------------------------------------
        vram_read2_addr = 32'd512;
        #1;
        if (vram_read2_data !== 32'd0) begin
            $error("[linear-y2-byte-still-zero] @byte 0x200 got 0x%08x expected 0",
                   vram_read2_data);
            errors = errors + 1;
        end
        vram_read2_addr = 32'd768;
        #1;
        if (vram_read2_data !== 32'd0) begin
            $error("[linear-y3-byte-still-zero] @byte 0x300 got 0x%08x expected 0",
                   vram_read2_data);
            errors = errors + 1;
        end

        // ------------------------------------------------------------
        // Phase 2 — end-to-end agreement: enable swizzled scanout,
        // capture the frame, assert each visible pixel matches the
        // sprite RGB.
        //
        //   DISPFB1: FBP=0, FBW=1, PSM=PSMCT32 (=0).
        //     FBW [14:9] = 1 → 0x0200
        //   DISPLAY1: DX=0, DY=0, DW=15, DH=3, MAGH=MAGV=0.
        //     DW [43:32] = 15 → 0x0000_000F_0000_0000
        //     DH [54:44] = 3  → 0x0030_0000_0000_0000
        //   PMODE.EN1 = 1.
        // ------------------------------------------------------------
        drive_priv(16'h0070, 64'h0000_0000_0000_0200);
        drive_priv(16'h0080, 64'h0030_000F_0000_0000);
        drive_priv(16'h0000, 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
                if (!cap_de[yy][xx]) begin
                    $error("[scanout] (%0d,%0d) DE never asserted", xx, yy);
                    errors = errors + 1;
                end else 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

        // ------------------------------------------------------------
        // Phase 3 — non-origin SPRITE.
        //
        // Re-arms gs_stub raster with FBP=4, FBW=2, and a sprite at
        // (60, 4)..(67, 5). This pins THREE contracts of the Ch122
        // wiring that the Phase 1 origin transfer can't distinguish
        // from a buggy implementation:
        //   (a) `ras_fbp` reaches the swizzle module's `fbp` port
        //       (Phase 1 used FBP=0, so a regression that tied
        //       fbp=0 would still pass).
        //   (b) `ras_fbw` reaches the swizzle module's `fbw` port
        //       (Phase 1 used FBW=1; a regression that tied fbw=1
        //       would still pass).
        //   (c) The swizzle gets the FULL absolute pixel coords
        //       `(s2_x_q, s2_y_q)`, not bbox-local ones — Phase 1's
        //       sprite started at (0,0) so absolute and local
        //       agree; a regression that fed bbox-local coords
        //       would land Phase 3's pixels at wrong addresses.
        //
        // Page-x boundary crossing: x∈[60..63] is in page (0,0);
        // x∈[64..67] is in page (1,0). page_index changes mid-row
        // — a regression that drops `ras_fbw` from page_index would
        // collapse both halves to the same page.
        // ------------------------------------------------------------
        drive_reg(R_PRIM,    PRIM_SPRITE);
        drive_reg(R_FRAME_1, P3_FRAME_1_VAL);
        drive_reg(R_RGBAQ,   P3_RGBAQ_VAL);
        drive_reg(R_XYZ2,    xyz2_data(12'(P3_X0), 12'(P3_Y0)));   // v1
        drive_reg(R_XYZ2,    xyz2_data(12'(P3_X1), 12'(P3_Y1)));   // v2 — close
        drive_idle();

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

        // Total emit count after Phase 3: 64 (Phase 1) + 16 (Phase 3).
        if (raster_pixel_emit_count != 32'(IMG_W * IMG_H + P3_PIXELS)) begin
            $error("after P3: expected %0d raster emits, got %0d",
                   IMG_W * IMG_H + P3_PIXELS, raster_pixel_emit_count);
            errors = errors + 1;
        end

        // Phase 3 per-pixel readback at swizzled byte addresses.
        for (int yy = P3_Y0; yy <= P3_Y1; yy++) begin
            for (int xx = P3_X0; xx <= P3_X1; xx++) begin
                logic [31:0] addr;
                logic [31:0] got;
                addr = ref_addr(P3_FBP, P3_FBW, xx, yy);
                vram_read2_addr = addr & ~32'd3;
                #1;
                got = vram_read2_data;
                if (got !== P3_PSMCT32_WORD) begin
                    $error("[p3-swizzled-byte] (%0d,%0d) @addr 0x%08x got 0x%08x expected 0x%08x",
                           xx, yy, addr, got, P3_PSMCT32_WORD);
                    errors = errors + 1;
                end
            end
        end

        // P3 strict separator: the LINEAR formula for P3 places
        //   pixel(60, 4) at byte:
        //     FBP*2048 + (FBW*64*4)*y + x*4
        //     = 8192 + 512*4 + 60*4
        //     = 8192 + 2048 + 240
        //     = 10480
        // This byte is NOT touched by any swizzled write in P3 —
        // the swizzled set lands in non-overlapping block-keyed
        // ranges (page (0,0) block (0,7) at bytes 8192+5376.. and
        // page (1,0) block (0,0) at bytes 16384..). If raster had
        // fallen through to the linear path, byte 10480 would hold
        // P3's color. Asserting it stays zero strictly proves the
        // Ch122 gate is live for non-origin transfers too.
        vram_read2_addr = 32'd10480;
        #1;
        if (vram_read2_data !== 32'd0) begin
            $error("[p3-linear-y0-byte-still-zero] @byte 0x%08x got 0x%08x expected 0",
                   32'd10480, vram_read2_data);
            errors = errors + 1;
        end

        $display("[tb_gs_raster_swizzle_psmct32] emits=%0d errors=%0d",
                 raster_pixel_emit_count, errors);
        if (errors == 0) $display("[tb_gs_raster_swizzle_psmct32] PASS");
        else             $display("[tb_gs_raster_swizzle_psmct32] FAIL");
        $finish;
    end

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

endmodule : tb_gs_raster_swizzle_psmct32
