// retroDE_ps2 — tb_gs_demo_psmt4_e2e_packed (Ch108)
//
// Same demo as Ch107's tb_gs_demo_psmt4_e2e but routed through
// the GIFtag / PACKED A+D front-end (`gif_packed_stub` with
// REAL_AD_REG_MAP=1). Closes the last bit of GS-side sideband
// from Ch107: instead of TB-driving `gs_stub.gif_reg_*` directly,
// the TB pushes raw 128-bit GIFtag + PACKED A+D quadwords into
// `gif_packed_stub.in_*` exactly the way the real GIF would
// receive them from PATH3 (DMAC channel 2).
//
// Scope: GIF + GS + PCRTC stack. Modelling a DMAC channel-2
// burst that delivers these qwords is intentionally still out of
// scope here — that requires a DMAC-driven `dmac→ram→gif` path
// and is what the integration-tier `tb_ee_core_gif_*` family
// covers. Here the TB drives `gif_packed_stub.in_valid/in_data/
// in_last` directly so the demo stays narrow and deterministic.
//
// Privileged-block MMIO (PMODE/DISPFB1/DISPLAY1) and the palette
// pre-stage in VRAM still happen via TB-direct writes, exactly
// as in Ch107: those paths are NOT GIF-side. The palette source
// upload via real PS2 TRXDIR/TRXPOS/TRXREG/HWREG image-transfer
// packets is a separate future chapter.
//
// What this TB locks (vs Ch107):
//   - The post-GIF register-write cadence into gs_stub.gif_reg_*
//     can be produced by a real GIFtag + PACKED A+D stream, NOT
//     just by TB direct writes. Same captured frame.
//   - GIFtag accept count, PACKED A+D write count, and reg-num
//     dispatch all align with the per-primitive sequence.
//
// "Program" sequence:
//   1. TB-direct stage 16 PSMCT32 palette entries in VRAM.
//   2. Push GIFtag + 5×A+D PACKED qwords for each of the 4
//      SPRITEs (PRIM, FRAME_1=PSMT4, RGBAQ, XYZ2, XYZ2).
//      4 tags × (1 GIFtag + 5 data) = 24 qwords.
//   3. Push GIFtag + 1×A+D PACKED for TEX0_1 (CLD=4 load).
//      1 tag × (1 GIFtag + 1 data) = 2 qwords.
//   4. Privileged MMIO: DISPFB1, DISPLAY1, PMODE.EN1.
//   5. Capture full frame; assert each pixel = CLUT[quadrant_idx]
//      inside the 8×4 image, CLUT[0] outside (16×8 active).
//
// PASS criteria:
//   - 32 raster_pixel_emit pulses (4 SPRITEs × 8 PSMT4 pixels).
//   - All emits PSM=0x14, BE=0001, mask ∈ {0x0F, 0xF0}.
//   - 5 GIFtag accepts seen at gif_packed_stub trace.
//   - 4*5 + 1*1 = 21 PACKED A+D writes seen at gs_stub.gif_reg_*.
//   - 1 loader_busy rising edge.
//   - Captured 16×8 frame matches expected CLUT-decoded RGB.

`timescale 1ns/1ps

module tb_gs_demo_psmt4_e2e_packed;

    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;

    // gif_packed_stub upstream
    logic         gif_in_valid;
    logic [127:0] gif_in_data;
    logic         gif_in_last;
    logic         gif_in_ready;

    // gif_packed_stub downstream → gs_stub.gif_reg_*
    logic        gif_gs_wr_en;     // legacy 16-bit-offset port (unused)
    logic [15:0] gif_gs_wr_addr;
    logic [63:0] gif_gs_wr_data;
    logic        gif_gif_reg_wr_en;
    logic [7:0]  gif_gif_reg_num;
    logic [63:0] gif_gif_reg_data;

    logic                gif_ev_valid;
    trace_pkg::subsys_e  gif_ev_subsys;
    trace_pkg::event_e   gif_ev_event;
    logic [63:0]         gif_ev_arg0, gif_ev_arg1, gif_ev_arg2, gif_ev_arg3;
    logic [31:0]         gif_ev_flags;

    gif_packed_stub #(.REAL_AD_REG_MAP(1'b1)) u_gif (
        .clk(clk), .rst_n(rst_n),
        .in_valid(gif_in_valid), .in_data(gif_in_data),
        .in_last(gif_in_last), .in_ready(gif_in_ready),
        .image_data_ready(1'b1),
        .raster_fifo_full(1'b0),
        .gs_wr_en(gif_gs_wr_en), .gs_wr_addr(gif_gs_wr_addr),
        .gs_wr_data(gif_gs_wr_data),
        .gif_reg_wr_en(gif_gif_reg_wr_en),
        .gif_reg_num(gif_gif_reg_num),
        .gif_reg_data(gif_gif_reg_data),
        .ev_valid(gif_ev_valid), .ev_subsys(gif_ev_subsys),
        .ev_event(gif_ev_event),
        .ev_arg0(gif_ev_arg0), .ev_arg1(gif_ev_arg1),
        .ev_arg2(gif_ev_arg2), .ev_arg3(gif_ev_arg3),
        .ev_flags(gif_ev_flags)
    );

    // Privileged-block MMIO into gs_stub (PMODE/DISPFB1/DISPLAY1).
    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 [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),
        // Privileged-block MMIO (TB-direct).
        .reg_wr_en  (priv_reg_wr_en),
        .reg_wr_addr(priv_reg_wr_addr),
        .reg_wr_data(priv_reg_wr_data),
        // GIF A+D path — driven by gif_packed_stub.
        .gif_reg_wr_en(gif_gif_reg_wr_en),
        .gif_reg_num  (gif_gif_reg_num),
        .gif_reg_data (gif_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_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 with TB-side palette-staging mux (palette pre-stage
    // only — framebuffer comes from raster_pixel_emit).
    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;

    logic        tb_palette_active;
    logic        write_en_mux;
    logic [31:0] write_addr_mux;
    logic [31:0] write_data_mux;
    logic [3:0]  write_be_mux;
    logic [31:0] write_mask_mux;

    assign write_en_mux   = tb_palette_active ? vram_we    : raster_pixel_emit;
    assign write_addr_mux = tb_palette_active ? vram_waddr : raster_pixel_fb_addr_q;
    assign write_data_mux = tb_palette_active ? vram_wdata : raster_pixel_color_q[31:0];
    assign write_be_mux   = tb_palette_active ? vram_wbe   : raster_pixel_be_q;
    assign write_mask_mux = tb_palette_active ? 32'hFFFF_FFFF : raster_pixel_mask_q;

    vram_stub #(.BYTES(8192)) u_vram (
        .clk(clk), .rst_n(rst_n),
        .write_en  (write_en_mux),
        .write_addr(write_addr_mux),
        .write_data(write_data_mux),
        .write_be  (write_be_mux),
        .write_mask(write_mask_mux),
        .read_addr (vram_raddr),
        .read_data (vram_rdata),
        .read2_addr(vram_raddr2),
        .read2_data(vram_rdata2)
    );

    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)
    );

    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)
    );

    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)
    );

    // ----------------------------------------------------------------
    // Capture + observers.
    // ----------------------------------------------------------------
    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;
    int  loader_starts;
    int  raster_psmt4_emits;
    int  giftag_seen;
    int  packed_ad_writes_seen;
    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;
        loader_starts         = 0;
        raster_psmt4_emits    = 0;
        giftag_seen           = 0;
        packed_ad_writes_seen = 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

    // GIFtag accept observer: count EV_GIFTAG events from
    // gif_packed_stub.
    always_ff @(posedge clk) begin
        if (rst_n && gif_ev_valid && gif_ev_event == trace_pkg::EV_GIFTAG)
            giftag_seen <= giftag_seen + 1;
    end

    // PACKED A+D dispatch observer: count register writes that
    // gs_stub sees on its gif_reg_wr_en line, AND lock the
    // exact reg-num sequence. Expected order:
    //   per SPRITE × 4: PRIM, FRAME_1, RGBAQ, XYZ2, XYZ2
    //   then         : TEX0_1
    // → 21 entries total. A divergence catches GIFtag REGS-nibble
    // misorder, NREG/NLOOP miscount, or any front-end reg# scramble.
    logic [7:0] expected_regnums [0:20];
    int         regnum_observer_idx;
    int         regnum_seq_errors;

    initial begin
        // SPRITE template repeats 4 times.
        for (int s = 0; s < 4; s++) begin
            expected_regnums[s*5 + 0] = 8'h00;  // PRIM
            expected_regnums[s*5 + 1] = 8'h4C;  // FRAME_1
            expected_regnums[s*5 + 2] = 8'h01;  // RGBAQ
            expected_regnums[s*5 + 3] = 8'h05;  // XYZ2 v0
            expected_regnums[s*5 + 4] = 8'h05;  // XYZ2 v1
        end
        expected_regnums[20] = 8'h06;           // TEX0_1
        regnum_observer_idx = 0;
        regnum_seq_errors   = 0;
    end

    always_ff @(posedge clk) begin
        if (rst_n && gif_gif_reg_wr_en) begin
            packed_ad_writes_seen <= packed_ad_writes_seen + 1;
            if (regnum_observer_idx < 21) begin
                if (gif_gif_reg_num !== expected_regnums[regnum_observer_idx]) begin
                    $error("packed-A+D dispatch %0d: reg=0x%02x (expected 0x%02x)",
                           regnum_observer_idx, gif_gif_reg_num,
                           expected_regnums[regnum_observer_idx]);
                    regnum_seq_errors <= regnum_seq_errors + 1;
                end
                regnum_observer_idx <= regnum_observer_idx + 1;
            end else begin
                $error("packed-A+D dispatch %0d: unexpected extra write (reg=0x%02x)",
                       regnum_observer_idx, gif_gif_reg_num);
                regnum_seq_errors <= regnum_seq_errors + 1;
            end
        end
    end

    // Loader-start (rising edge of load_busy).
    logic loader_busy_d;
    always_ff @(posedge clk) begin
        if (!rst_n) loader_busy_d <= 1'b0;
        else begin
            loader_busy_d <= loader_busy;
            if (loader_busy && !loader_busy_d)
                loader_starts <= loader_starts + 1;
        end
    end

    // Raster emit invariants (PSM/BE/MASK).
    always_ff @(posedge clk) begin
        if (rst_n && raster_pixel_emit) begin
            raster_psmt4_emits <= raster_psmt4_emits + 1;
            if (raster_pixel_psm_q !== 6'h14) begin
                $error("emit %0d: psm=0x%02x (expected 0x14)",
                       raster_psmt4_emits, raster_pixel_psm_q);
                errors <= errors + 1;
            end
            if (raster_pixel_be_q !== 4'b0001) begin
                $error("emit %0d: be=%b (expected 4'b0001)",
                       raster_psmt4_emits, raster_pixel_be_q);
                errors <= errors + 1;
            end
            if (raster_pixel_mask_q !== 32'h0000_000F &&
                raster_pixel_mask_q !== 32'h0000_00F0) begin
                $error("emit %0d: mask=0x%08x (expected 0x0F or 0xF0)",
                       raster_psmt4_emits, raster_pixel_mask_q);
                errors <= errors + 1;
            end
        end
    end

    // ----------------------------------------------------------------
    // Helpers.
    // ----------------------------------------------------------------
    task automatic push_qword(input logic [127:0] data, input logic last);
        @(negedge clk);
        gif_in_valid = 1'b1;
        gif_in_data  = data;
        gif_in_last  = last;
        @(posedge clk);
        @(negedge clk);
        gif_in_valid = 1'b0;
        gif_in_data  = 128'd0;
        gif_in_last  = 1'b0;
    endtask

    function automatic logic [127:0] giftag(
        input logic [14:0] nloop,
        input logic        eop,
        input logic [1:0]  flg,
        input logic [3:0]  nreg,
        input logic [63:0] regs);
        logic [63:0] lower;
        // GIFtag layout (per PCSX2 GS GIFtag): [63:0] = NLOOP[14:0],
        // EOP[15], reserved[57:16], FLG[59:58], NREG[63:60].
        lower = {nreg, flg, 42'd0, eop, nloop};
        return {regs, lower};
    endfunction

    // Real-PS2 PACKED A+D entry: bits[63:0] = data, bits[71:64] =
    // 8-bit GIF A+D register #, bits[127:72] = reserved.
    function automatic logic [127:0] aplusd(input logic [7:0]  reg_num,
                                            input logic [63:0] data64);
        return {56'd0, reg_num, data64};
    endfunction

    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 palette_write32(input logic [31:0] addr,
                                   input logic [31:0] data);
        @(negedge clk);
        tb_palette_active = 1'b1;
        vram_we    = 1'b1;
        vram_waddr = addr;
        vram_wdata = data;
        vram_wbe   = 4'b1111;
        @(posedge clk);
        @(negedge clk);
        vram_we    = 1'b0;
        vram_waddr = 32'd0;
        vram_wdata = 32'd0;
        vram_wbe   = 4'b0000;
        tb_palette_active = 1'b0;
    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

    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

    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

    // Push a single SPRITE as a GIFtag + 5×A+D PACKED packet.
    task automatic gif_sprite_packet(input logic [7:0]  rgbaq_r,
                                     input logic [11:0] x0,
                                     input logic [11:0] y0,
                                     input logic [11:0] x1,
                                     input logic [11:0] y1,
                                     input logic        eop);
        // REGS: 5 nibbles of 0xE (A+D) in the low 5 nibble slots.
        // Nibble 0 = REG 0, nibble 1 = REG 1, ... = order of
        // PACKED entries below.
        push_qword(giftag(15'd1, eop, 2'd0, 4'd5, 64'h00000000_000E_EEEE), 1'b0);
        push_qword(aplusd(R_PRIM,    PRIM_SPRITE),                          1'b0);
        push_qword(aplusd(R_FRAME_1, FRAME_1_PSMT4),                        1'b0);
        push_qword(aplusd(R_RGBAQ,   {32'd0, 8'hCC, 8'hBB, 8'hAA, rgbaq_r}),1'b0);
        push_qword(aplusd(R_XYZ2,    xyz2_data(x0, y0)),                    1'b0);
        push_qword(aplusd(R_XYZ2,    xyz2_data(x1, y1)),                    eop);
    endtask

    // ----------------------------------------------------------------
    // GIF A+D register numbers (per PCSX2 GSRegs.h).
    // ----------------------------------------------------------------
    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_TEX0_1    = 8'h06;
    localparam logic [7:0] R_FRAME_1   = 8'h4C;

    localparam logic [63:0] PRIM_SPRITE   = 64'd6;
    localparam logic [63:0] FRAME_1_PSMT4 = 64'h0000_0000_1401_0000;

    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          PALETTE_CBP  = 4;
    localparam logic [4:0]  CSA          = 5'd0;

    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;

    function automatic logic [3:0] quad_idx_at(input int x, input int y);
        if (y <= 1 && x <= 3)                  return 4'h5;
        if (y <= 1 && x >= 4 && x <= 7)        return 4'h7;
        if (y >= 2 && y <= 3 && x <= 3)        return 4'hA;
        if (y >= 2 && y <= 3 && x >= 4 && x <= 7) return 4'hC;
        return 4'h0;
    endfunction

    initial begin
        rst_n             = 1'b0;
        gif_in_valid      = 1'b0;
        gif_in_data       = 128'd0;
        gif_in_last       = 1'b0;
        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;
        tb_palette_active = 1'b0;

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

        // Step 1 — palette pre-stage (TB-direct VRAM writes).
        for (int i = 0; i < 16; i++) begin
            logic [7:0]  ii;
            logic [31:0] addr;
            ii   = i[7:0];
            addr = 32'(PALETTE_CBP * 256) + 32'(i * 4);
            palette_write32(addr, pattern_a(ii));
        end

        // Step 2 — push 4 SPRITE packets through gif_packed_stub.
        // Each packet: 1 GIFtag + 5 PACKED A+D qwords. EOP=0 on
        // all but the last so the front-end knows the PATH3
        // burst continues; the last packet sets EOP=1.
        gif_sprite_packet(8'h05, 12'd0, 12'd0, 12'd3, 12'd1, 1'b0);  // TL
        gif_sprite_packet(8'h07, 12'd4, 12'd0, 12'd7, 12'd1, 1'b0);  // TR
        gif_sprite_packet(8'h0A, 12'd0, 12'd2, 12'd3, 12'd3, 1'b0);  // BL
        gif_sprite_packet(8'h0C, 12'd4, 12'd2, 12'd7, 12'd3, 1'b1);  // BR (EOP)

        // Wait for the raster pipeline to fully drain.
        wait (raster_active == 1'b1);
        wait (raster_active == 1'b0);
        repeat (10) @(posedge clk);

        // Step 3 — TEX0_1 load via a separate GIFtag + 1×A+D packet.
        push_qword(giftag(15'd1, 1'b1, 2'd0, 4'd1, 64'h00000000_0000_000E), 1'b0);
        push_qword(aplusd(R_TEX0_1,
                          tex0_pack(14'(PALETTE_CBP), 4'd0, 1'b1, CSA, 3'd4)),
                   1'b1);

        wait (loader_busy == 1'b1);
        wait (loader_busy == 1'b0);
        repeat (4) @(posedge clk);

        // Step 4 — privileged-block bring-up (TB-direct, NOT GIF).
        drive_priv(DISPFB1_OFF,  DISPFB1_VAL);
        drive_priv(DISPLAY1_OFF, DISPLAY1_VAL);
        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;

        // Step 5 — full-frame assertion.
        for (int y = 0; y < PCRTC_V_ACTIVE; y++) begin
            for (int x = 0; x < PCRTC_H_ACTIVE; x++) begin
                logic [3:0]  expected_idx;
                logic [7:0]  effective_idx;
                logic [31:0] entry;
                logic [7:0]  er, eg, eb;

                expected_idx  = quad_idx_at(x, y);
                effective_idx = {4'd0, expected_idx} + 8'(CSA) * 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("(%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("(%0d,%0d) got (%02x,%02x,%02x) expected (%02x,%02x,%02x) idx=0x%01x",
                           x, y, cap_r[y][x], cap_g[y][x], cap_b[y][x],
                           er, eg, eb, expected_idx);
                    errors = errors + 1;
                end
            end
        end

        // Aggregate counts.
        if (raster_pixel_emit_count != 32'd32) begin
            $error("expected 32 PSMT4 emits, got %0d", raster_pixel_emit_count);
            errors = errors + 1;
        end
        if (raster_psmt4_emits != 32) begin
            $error("PSMT4 emit observer count=%0d (expected 32)", raster_psmt4_emits);
            errors = errors + 1;
        end
        if (giftag_seen != 5) begin
            $error("GIFtag accept count=%0d (expected 5: 4 sprites + 1 TEX0_1)",
                   giftag_seen);
            errors = errors + 1;
        end
        if (packed_ad_writes_seen != 21) begin
            $error("PACKED A+D dispatch count=%0d (expected 21: 4*5 + 1*1)",
                   packed_ad_writes_seen);
            errors = errors + 1;
        end
        if (regnum_observer_idx != 21) begin
            $error("PACKED A+D reg-num sequence stopped at idx %0d (expected 21)",
                   regnum_observer_idx);
            errors = errors + 1;
        end
        if (regnum_seq_errors != 0) begin
            $error("PACKED A+D reg-num sequence had %0d divergences", regnum_seq_errors);
            errors = errors + regnum_seq_errors;
        end
        if (loader_starts != 1) begin
            $error("loader fired %0d times (expected 1)", loader_starts);
            errors = errors + 1;
        end
        if (raster_overflow) begin
            $error("raster_overflow asserted");
            errors = errors + 1;
        end
        if (raster_degenerate) begin
            $error("raster_degenerate asserted");
            errors = errors + 1;
        end

        $display("[tb_gs_demo_psmt4_e2e_packed] giftags=%0d ad_writes=%0d emits=%0d loader_starts=%0d frame=%0dx%0d",
                 giftag_seen, packed_ad_writes_seen,
                 raster_pixel_emit_count, loader_starts,
                 PCRTC_H_ACTIVE, PCRTC_V_ACTIVE);

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

    initial begin
        #20000000;
        $error("[tb_gs_demo_psmt4_e2e_packed] timeout");
        $finish;
    end

endmodule : tb_gs_demo_psmt4_e2e_packed
