// retroDE_ps2 — tb_gs_psmt4_round_trip (Ch104)
//
// Driver-shaped end-to-end PSMT4 round trip stitching together
// every chapter from Ch97 onward into one integration test:
//
//   GIF TEX0_1 write    →  gs_stub field decode (Ch98)
//                       →  clut_loader_stub policy (Ch99..Ch102)
//                       →  vram_stub port-1 read   (Ch99)
//                       →  clut_stub partial write (Ch102)
//   DISPFB1.PSM=PSMT4   →  gs_pcrtc_stub PSMT4 lookup (Ch103)
//                       →  clut_stub read at idx + (CSA<<4)
//                       →  visible RGB on r/g/b
//
// The point: same sprite, same DISPFB1/DISPLAY1/PMODE config, two
// different TEX0_1 writes with different CBP + CSA → two
// completely different rendered frames. That proves the loader
// policy, CLUT contents, and PCRTC lookup all agree on which
// 16-entry palette window applies — the canonical PSMT4
// "swap palette" driver pattern.
//
// Setup:
//   - VRAM at CBP_A*256 holds 16 PSMCT32 entries of pattern_a.
//   - VRAM at CBP_B*256 holds 16 different PSMCT32 entries of
//     pattern_b.
//   - VRAM at byte 0 holds a 4×4 PSMT4 sprite of indices
//     0x0..0xF (row-major).
//   - DISPFB1.PSM=PSMT4, FBP=0, FBW=1.
//   - DISPLAY1 covers the full active area; MAGH=MAGV=0.
//   - pcrtc.clut_csa is wired from gs_stub.tex0_1_csa_q so any
//     CSA change in TEX0_1 immediately retargets the lookup.
//
// Phase 1:
//   - drive TEX0_1 with CBP=CBP_A, CPSM=0, CSM=1, CSA=0, CLD=4.
//   - loader writes clut_stub[0..15] = pattern_a.
//   - pcrtc.clut_csa = 0 → reads clut_stub[nibble] = pattern_a.
//   - Assert: each in-sprite pixel reads pattern_a(nibble);
//     non-sprite (nibble=0) reads pattern_a(0).
//
// Phase 2:
//   - drive TEX0_1 with CBP=CBP_B, CPSM=0, CSM=1, CSA=4, CLD=4.
//   - loader writes clut_stub[64..79] = pattern_b.
//   - pcrtc.clut_csa = 4 → reads clut_stub[nibble + 64].
//   - Assert: each in-sprite pixel reads pattern_b(nibble);
//     non-sprite (nibble=0) reads pattern_b(0). The phase-1
//     entries (0..15) still hold pattern_a but pcrtc no longer
//     reads them — they're invisible at CSA=4.

`timescale 1ns/1ps

module tb_gs_psmt4_round_trip;

    localparam int PCRTC_H_ACTIVE = 16;
    localparam int PCRTC_V_ACTIVE = 8;

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

    // gs_stub IO
    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                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 [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  (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),
        .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_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 with TB-direct write port (sprite + 2 CLUT-source
    // regions). pcrtc reads via port 0; loader reads via port 1.
    logic        vram_we;
    logic [31:0] vram_waddr;
    logic [31:0] vram_wdata;
    logic [3:0]  vram_wbe;
    logic [31:0] vram_raddr;
    logic [31:0] vram_rdata;
    logic [31:0] vram_raddr2;
    logic [31:0] vram_rdata2;

    vram_stub #(.BYTES(8192)) u_vram (
        .clk(clk), .rst_n(rst_n),
        .write_en  (vram_we),
        .write_addr(vram_waddr),
        .write_data(vram_wdata),
        .write_be  (vram_wbe),
        .write_mask(32'hFFFF_FFFF),
        .read_addr (vram_raddr),
        .read_data (vram_rdata),
        .read2_addr(vram_raddr2),
        .read2_data(vram_rdata2)
    );

    // CLUT
    logic        clut_we;
    logic [7:0]  clut_widx;
    logic [31:0] clut_wdata;
    logic [7:0]  clut_ridx;
    logic [31:0] clut_rdata;

    clut_stub u_clut (
        .clk(clk), .rst_n(rst_n),
        .write_en  (clut_we),
        .write_idx (clut_widx),
        .write_data(clut_wdata),
        .read_idx  (clut_ridx),
        .read_data (clut_rdata)
    );

    // Loader — driven by gs_stub TEX0_1 fields + tex0_1_wr_q.
    logic loader_busy;

    clut_loader_stub u_loader (
        .clk(clk), .rst_n(rst_n),
        .tex0_wr_pulse  (tex0_1_wr_q),
        .tex0_cbp       (tex0_1_cbp_q),
        .tex0_cpsm      (tex0_1_cpsm_q),
        .tex0_csm       (tex0_1_csm_q),
        .tex0_csa       (tex0_1_csa_q),
        .tex0_cld       (tex0_1_cld_q),
        .vram_read_addr (vram_raddr2),
        .vram_read_data (vram_rdata2),
        .clut_write_en  (clut_we),
        .clut_write_idx (clut_widx),
        .clut_write_data(clut_wdata),
        .load_busy      (loader_busy)
    );

    // PCRTC — clut_csa wired from gs_stub.tex0_1_csa_q so a
    // TEX0_1 write that changes CSA immediately retargets the
    // lookup window.
    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)
    ) u_pcrtc (
        .clk(clk), .rst_n(rst_n),
        .pmode_q       (pmode_q),
        .dispfb1_q     (dispfb1_q),
        .display1_q    (display1_q),
        .vram_read_addr(vram_raddr),
        .vram_read_data(vram_rdata),
        .clut_enable   (1'b1),
        .clut_csa      (tex0_1_csa_q),
        .clut_read_idx (clut_ridx),
        .clut_read_data(clut_rdata),
        .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)
    );

    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

    task automatic clear_capture();
        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
    endtask

    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

    task automatic vram_write32(input logic [31:0] addr,
                                input logic [31:0] data,
                                input logic [3:0]  be);
        @(negedge clk);
        vram_we    = 1'b1;
        vram_waddr = addr;
        vram_wdata = data;
        vram_wbe   = be;
        @(posedge clk);
        @(negedge clk);
        vram_we    = 1'b0;
        vram_waddr = 32'd0;
        vram_wdata = 32'd0;
        vram_wbe   = 4'b0000;
    endtask

    function automatic logic [63:0] tex0_pack(
        input logic [13:0] cbp,
        input logic [3:0]  cpsm,
        input logic        csm,
        input logic [4:0]  csa,
        input logic [2:0]  cld);
        logic [63:0] v;
        v = 64'd0;
        v[50:37] = cbp;
        v[54:51] = cpsm;
        v[55]    = csm;
        v[60:56] = csa;
        v[63:61] = cld;
        return v;
    endfunction

    // Phase 1 palette pattern — same as Ch97/Ch99/Ch102.
    function automatic logic [31:0] pattern_a(input logic [7:0] i);
        logic [7:0] r8, g8, b8, a8;
        r8 = i; g8 = i + 8'h40; b8 = i + 8'h80; a8 = 8'hFF;
        return {a8, b8, g8, r8};
    endfunction

    // Phase 2 palette pattern — visibly distinct so a stale
    // phase 1 lookup would fail.
    function automatic logic [31:0] pattern_b(input logic [7:0] i);
        logic [7:0] r8, g8, b8, a8;
        r8 = i ^ 8'hAA;
        g8 = i ^ 8'h55;
        b8 = i ^ 8'hCC;
        a8 = 8'h80;
        return {a8, b8, g8, r8};
    endfunction

    // Sprite indices: row-major, 0x0..0xF.
    function automatic logic [3:0] sprite_idx(input int x, input int y);
        return 4'(y * 4 + x);
    endfunction

    localparam logic [7:0]  GIF_TEX0_1   = 8'h06;
    localparam logic [15:0] PMODE_OFF    = 16'h0000;
    localparam logic [15:0] DISPFB1_OFF  = 16'h0070;
    localparam logic [15:0] DISPLAY1_OFF = 16'h0080;

    localparam int          CBP_A      = 4;       // 1024 bytes
    localparam logic [4:0]  CSA_A      = 5'd0;
    localparam int          CBP_B      = 8;       // 2048 bytes
    localparam logic [4:0]  CSA_B      = 5'd4;    // window 64..79
    localparam int          SPRITE_W   = 4;
    localparam int          SPRITE_H   = 4;

    // DISPFB1: FBP=0, FBW=1, PSM=PSMT4 (0x14) → 0x000A_0200.
    localparam logic [63:0] DISPFB1_VAL  = 64'h0000_0000_000A_0200;
    localparam logic [63:0] DISPLAY1_VAL =
          (64'(PCRTC_H_ACTIVE - 1) << 32)
        | (64'(PCRTC_V_ACTIVE - 1) << 44);
    localparam logic [63:0] PMODE_EN1    = 64'h0000_0000_0000_0001;

    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_we          = 1'b0;
        vram_waddr       = 32'd0;
        vram_wdata       = 32'd0;
        vram_wbe         = 4'b0000;

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

        // Stage CLUT pattern A at CBP_A*256 (16 PSMCT32 entries).
        for (int i = 0; i < 16; i++) begin
            logic [7:0]  ii;
            logic [31:0] addr;
            ii   = i[7:0];
            addr = 32'(CBP_A * 256) + 32'(i * 4);
            vram_write32(addr, pattern_a(ii), 4'b1111);
        end

        // Stage CLUT pattern B at CBP_B*256 (16 PSMCT32 entries).
        for (int i = 0; i < 16; i++) begin
            logic [7:0]  ii;
            logic [31:0] addr;
            ii   = i[7:0];
            addr = 32'(CBP_B * 256) + 32'(i * 4);
            vram_write32(addr, pattern_b(ii), 4'b1111);
        end

        // Stage 4×4 PSMT4 sprite at byte 0 (FBW=1 → 32-byte rows).
        // Each row holds 4 nibbles in 2 bytes; one 32-bit aligned
        // write covers it (upper 16 bits zero so non-sprite
        // columns stay nibble=0).
        for (int y = 0; y < SPRITE_H; y++) begin
            logic [3:0]  i0, i1, i2, i3;
            logic [7:0]  byte0, byte1;
            logic [31:0] data;
            int          row_byte;
            i0 = sprite_idx(0, y);
            i1 = sprite_idx(1, y);
            i2 = sprite_idx(2, y);
            i3 = sprite_idx(3, y);
            byte0 = {i1, i0};
            byte1 = {i3, i2};
            data  = {16'd0, byte1, byte0};
            row_byte = y * 32;
            vram_write32(row_byte, data, 4'b1111);
        end

        // Configure DISPFB1 + DISPLAY1 once (does not change
        // between phases). PMODE.EN1 last so any partial-load
        // state during the first TEX0 write doesn't surface.
        drive_priv(DISPFB1_OFF,  DISPFB1_VAL);
        drive_priv(DISPLAY1_OFF, DISPLAY1_VAL);

        // ----------------------------------------------------------------
        // Phase 1 — load pattern A into clut_stub[0..15] via
        // CLD=4 + CSA=0; capture frame; assert palette A in use.
        // ----------------------------------------------------------------
        drive_reg(GIF_TEX0_1, tex0_pack(14'(CBP_A), 4'd0, 1'b1, CSA_A, 3'd4));
        drive_idle();
        wait (loader_busy == 1'b1);
        wait (loader_busy == 1'b0);
        repeat (4) @(posedge clk);

        drive_priv(PMODE_OFF, PMODE_EN1);

        @(posedge u_pcrtc.end_of_frame);
        @(posedge clk);
        capture_armed = 1'b1;
        @(posedge u_pcrtc.end_of_frame);
        @(posedge clk);
        capture_armed = 1'b0;

        for (int y = 0; y < PCRTC_V_ACTIVE; y++) begin
            for (int x = 0; x < PCRTC_H_ACTIVE; x++) begin
                logic [3:0]  nibble;
                logic [7:0]  effective_idx;
                logic [31:0] entry;
                logic [7:0]  er, eg, eb;

                if (x < SPRITE_W && y < SPRITE_H)
                    nibble = sprite_idx(x, y);
                else
                    nibble = 4'd0;
                effective_idx = {4'd0, nibble} + 8'(CSA_A) * 8'd16;
                entry = pattern_a(effective_idx);
                er    = entry[7:0];
                eg    = entry[15:8];
                eb    = entry[23:16];

                if (!cap_de[y][x]) begin
                    $error("[phase1] (%0d,%0d) DE never asserted", x, y);
                    errors = errors + 1;
                end
                if (cap_r[y][x] !== er || cap_g[y][x] !== eg || cap_b[y][x] !== eb) begin
                    $error("[phase1] (%0d,%0d) got (%02x,%02x,%02x) expected (%02x,%02x,%02x) nibble=0x%01x",
                           x, y, cap_r[y][x], cap_g[y][x], cap_b[y][x],
                           er, eg, eb, nibble);
                    errors = errors + 1;
                end
            end
        end

        $display("[tb_gs_psmt4_round_trip] phase 1 (CBP=%0d, CSA=%0d → window 0..15, pattern_a) done",
                 CBP_A, CSA_A);

        // ----------------------------------------------------------------
        // Phase 2 — re-issue TEX0_1 with NEW CBP and CSA. Loader
        // refills clut_stub[64..79] from pattern_b; pcrtc.clut_csa
        // (wired from gs_stub.tex0_1_csa_q) flips to 4 the cycle
        // TEX0_1 commits, so the next captured frame uses the new
        // window. Same VRAM sprite, same DISPFB1/DISPLAY1/PMODE.
        // ----------------------------------------------------------------
        drive_reg(GIF_TEX0_1, tex0_pack(14'(CBP_B), 4'd0, 1'b1, CSA_B, 3'd4));
        drive_idle();
        wait (loader_busy == 1'b1);
        wait (loader_busy == 1'b0);
        repeat (4) @(posedge clk);

        clear_capture();
        @(posedge u_pcrtc.end_of_frame);
        @(posedge clk);
        capture_armed = 1'b1;
        @(posedge u_pcrtc.end_of_frame);
        @(posedge clk);
        capture_armed = 1'b0;

        for (int y = 0; y < PCRTC_V_ACTIVE; y++) begin
            for (int x = 0; x < PCRTC_H_ACTIVE; x++) begin
                logic [3:0]  nibble;
                logic [7:0]  effective_idx;
                logic [7:0]  pattern_b_arg;
                logic [31:0] entry;
                logic [7:0]  er, eg, eb;

                if (x < SPRITE_W && y < SPRITE_H)
                    nibble = sprite_idx(x, y);
                else
                    nibble = 4'd0;
                // pcrtc.clut_csa = CSA_B = 4 → effective_idx =
                // nibble + 64. clut_stub[64..79] holds pattern_b
                // staged at vram source index 0..15 — so the
                // *content* lookup uses pattern_b(idx_in_window)
                // where idx_in_window = effective_idx - 64.
                effective_idx = {4'd0, nibble} + 8'(CSA_B) * 8'd16;
                pattern_b_arg = effective_idx - 8'(CSA_B) * 8'd16;
                entry = pattern_b(pattern_b_arg);
                er    = entry[7:0];
                eg    = entry[15:8];
                eb    = entry[23:16];

                if (!cap_de[y][x]) begin
                    $error("[phase2] (%0d,%0d) DE never asserted", x, y);
                    errors = errors + 1;
                end
                if (cap_r[y][x] !== er || cap_g[y][x] !== eg || cap_b[y][x] !== eb) begin
                    $error("[phase2] (%0d,%0d) got (%02x,%02x,%02x) expected (%02x,%02x,%02x) nibble=0x%01x effective_idx=0x%02x",
                           x, y, cap_r[y][x], cap_g[y][x], cap_b[y][x],
                           er, eg, eb, nibble, effective_idx);
                    errors = errors + 1;
                end
            end
        end

        $display("[tb_gs_psmt4_round_trip] phase 2 (CBP=%0d, CSA=%0d → window 64..79, pattern_b) done",
                 CBP_B, CSA_B);

        if (errors == 0) $display("[tb_gs_psmt4_round_trip] PASS");
        else             $display("[tb_gs_psmt4_round_trip] FAIL");
        $finish;
    end

    initial begin
        #5000000;
        $error("[tb_gs_psmt4_round_trip] timeout");
        $finish;
    end

endmodule : tb_gs_psmt4_round_trip
