// retroDE_ps2 — tb_gs_textured_sprite (Brick 1)
//
// FIRST textured-sprite test: drives a PSMCT32 DECAL textured SPRITE
// through gs_stub's raster pipeline and verifies the framebuffer
// pixels equal the preloaded texture texels.
//
// Datapath under test (Brick 1):
//   PRIM.TME=1 + TEX0_1(texture-side) + UV per-vertex + SPRITE
//     -> per-pixel linear (u,v) interpolation
//     -> gs_texture_unit (gs_texel_addr + PSMCT32 DECAL sample)
//     -> texel REPLACES the flat sprite color at emit.
//
// To isolate the sampling datapath from the texture-UPLOAD path, the
// texture is PRELOADED DIRECTLY into vram_stub at the TBP0-derived
// base (TBP0*256, the convention gs_stub documents + the upload path
// uses). A follow-on chapter reconciles the BITBLT/TRX upload path.
//
// Geometry / mapping (chosen so the mapping is the identity texel(x,y)):
//   SPRITE endpoints (0,0)->(3,3)  => 4x4 fill.
//   UV endpoints (0,0)->(3,3)      => u=x, v=y across the sprite.
//   Framebuffer: FBP=0, FBW=1, PSM=PSMCT32. Stride = 64*4 = 256 B/row.
//   Texture: TBP0=8 (base 2048 B), TBW=1 (64 texels/row), PSM=PSMCT32.
//
// PASS criteria:
//   - 16 raster_pixel_emit pulses.
//   - Each framebuffer pixel (x,y) == preloaded texel(x,y).
//   - A NON-textured control SPRITE (TME=0) at a different FB region
//     still emits the FLAT color (proves the TME=0 path is unchanged).

`timescale 1ns/1ps

module tb_gs_textured_sprite;

    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 [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_fifo_full;
    logic                raster_degenerate;
    logic                tex_rd_en;
    logic [31:0]         tex_rd_addr;
    logic [31:0]         tex_rd_data;
    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_fifo_full(raster_fifo_full),
        .raster_degenerate(raster_degenerate),
        .tex_rd_en(tex_rd_en),
        .tex_rd_addr(tex_rd_addr),
        .tex_rd_data(tex_rd_data),
        .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. Port 0 = raster write + TB readback. Port 1 (read2) =
    // texel fetch. In a full integration read2 is muxed between
    // clut_loader_stub (CLUT load at TEX0 commit) and gs_stub's texel
    // fetch (during the scan); clut_loader is not instantiated here,
    // so read2 is dedicated to the texel port. The mux is documented
    // in gs_stub's tex_rd_* port comment.
    logic [31:0] vram_read_addr;
    logic [31:0] vram_read_data;

    localparam int VRAM_BYTES = 8192;

    vram_stub #(.BYTES(VRAM_BYTES)) 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(tex_rd_addr),
        .read2_data(tex_rd_data)
    );

    int errors;
    int textured_emit_seen;

    initial begin
        errors = 0;
        textured_emit_seen = 0;
    end

    // ----- GIF register numbers -----
    localparam logic [7:0] R_PRIM    = 8'h00;
    localparam logic [7:0] R_RGBAQ   = 8'h01;
    localparam logic [7:0] R_UV      = 8'h03;
    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;

    // PRIM: type=6 (SPRITE) at [2:0]; TME at bit 4.
    localparam logic [63:0] PRIM_SPRITE_TEX  = 64'd6 | (64'd1 << 4);  // SPRITE + TME
    localparam logic [63:0] PRIM_SPRITE_FLAT = 64'd6;                 // SPRITE, no TME

    // FRAME_1: FBP[8:0]=0, FBW[21:16]=1, PSM[29:24]=PSMCT32(0x00).
    localparam logic [63:0] FRAME_1_FB0 = 64'h0000_0000_0001_0000;
    // A second FB region for the flat control sprite: FBP=1 (2048 B).
    localparam logic [63:0] FRAME_1_FB1 = 64'h0000_0000_0001_0001;

    // TEX0_1 texture-side: TBP0[13:0]=8, TBW[19:14]=1, PSM[25:20]=0.
    //   TBP0=8 -> base bytes = 8*256 = 2048.
    localparam logic [13:0] TEX_TBP0 = 14'd8;
    localparam logic [5:0]  TEX_TBW  = 6'd1;
    localparam logic [63:0] TEX0_VAL = {30'd0, 6'd0 /*TH*/, 4'd0 /*TW*/,
                                        6'd0 /*PSM*/, TEX_TBW, TEX_TBP0};
    localparam logic [31:0] TEX_BASE_BYTES = 32'd8 * 32'd256;         // 2048
    localparam int          TEX_ROW_TEXELS = 64;                     // TBW*64

    // Flat control color.
    localparam logic [63:0] FLAT_RGBAQ = 64'h0000_0000_8011_2233;    // ABGR=0x80112233

    localparam int SPRITE_W = 4;
    localparam int SPRITE_H = 4;
    localparam int FB0_STRIDE = 64 * 4;     // FBW=1 -> 64 px/row * 4 B
    localparam int FB1_BASE   = 2048;       // FBP=1 -> 1*2048

    // Expected texel for (x,y): a recognizable pattern.
    function automatic logic [31:0] texel(input int x, input int y);
        return 32'hFF000000 | (x << 8) | (y << 16) | 32'h00000040;
    endfunction

    // ----- 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

    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

    // UV reg: U=[13:0], V=[27:14], 10.4 fixed-point. Integer u,v.
    function automatic logic [63:0] uv_data(input int ui, input int vi);
        logic [13:0] u_fp, v_fp;
        u_fp = 14'(ui) << 4;
        v_fp = 14'(vi) << 4;
        return {36'd0, v_fp, u_fp};
    endfunction

    // Read a 32-bit word from VRAM port 0 (combinational read). The
    // settle delay lives in the caller (a task), not in a function.
    task automatic vram_word(input  logic [31:0] byte_addr,
                             output logic [31:0] word);
        vram_read_addr = byte_addr;
        #1;
        word = vram_read_data;
    endtask

    // Preload a 32-bit little-endian word directly into the VRAM
    // backing store (raster is idle during preload, so a direct mem
    // poke is the simplest texture-upload bypass). Static task: a
    // hierarchical force/poke on automatic-task locals is illegal in
    // iverilog 12, and a direct mem write needs no force at all.
    task automatic force_word(input logic [31:0] addr, input logic [31:0] data);
        u_vram.mem[addr + 0] = data[7:0];
        u_vram.mem[addr + 1] = data[15:8];
        u_vram.mem[addr + 2] = data[23:16];
        u_vram.mem[addr + 3] = data[31:24];
    endtask

    // ----- observer: count textured emits -----
    always_ff @(posedge clk) begin
        if (rst_n && raster_pixel_emit && (raster_pixel_psm_q == 6'h00)
                  && (raster_pixel_fb_addr_q < FB1_BASE)) begin
            textured_emit_seen <= textured_emit_seen + 1;
        end
    end

    integer x, y;
    logic [31:0] got, exp;

    initial begin
        rst_n          = 1'b0;
        gif_reg_wr_en  = 1'b0;
        gif_reg_num    = 8'd0;
        gif_reg_data   = 64'd0;
        vram_read_addr = 32'd0;

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

        // --- Preload the texture DIRECTLY into VRAM at TBP0*256. ---
        // (Bypasses BITBLT/TRX upload — see header + gs_stub TODO.)
        for (y = 0; y < SPRITE_H; y++) begin
            for (x = 0; x < SPRITE_W; x++) begin
                logic [31:0] addr;
                addr = TEX_BASE_BYTES + ((y * TEX_ROW_TEXELS + x) * 4);
                // poke 4 bytes little-endian via the write port
                force_word(addr, texel(x, y));
            end
        end

        // ===========================================================
        // 1) TEXTURED SPRITE
        // ===========================================================
        drive_reg(R_PRIM,    PRIM_SPRITE_TEX);
        drive_reg(R_FRAME_1, FRAME_1_FB0);
        drive_reg(R_TEX0_1,  TEX0_VAL);
        drive_reg(R_RGBAQ,   FLAT_RGBAQ);            // would-be flat color (must be overridden)
        // vertex 0: UV(0,0) at screen (0,0)
        drive_reg(R_UV,      uv_data(0, 0));
        drive_reg(R_XYZ2,    xyz2_data(12'd0, 12'd0));
        // vertex 1 (closing): UV(3,3) at screen (3,3)
        drive_reg(R_UV,      uv_data(SPRITE_W - 1, SPRITE_H - 1));
        drive_reg(R_XYZ2,    xyz2_data(12'(SPRITE_W - 1), 12'(SPRITE_H - 1)));
        drive_idle();

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

        if (raster_pixel_emit_count != 32'(SPRITE_W * SPRITE_H)) begin
            $error("textured sprite: expected %0d emits, got %0d",
                   SPRITE_W * SPRITE_H, raster_pixel_emit_count);
            errors = errors + 1;
        end
        if (textured_emit_seen != SPRITE_W * SPRITE_H) begin
            $error("textured emit observer count=%0d (expected %0d)",
                   textured_emit_seen, SPRITE_W * SPRITE_H);
            errors = errors + 1;
        end

        // Verify each FB pixel == preloaded texel(x,y).
        for (y = 0; y < SPRITE_H; y++) begin
            for (x = 0; x < SPRITE_W; x++) begin
                logic [31:0] addr;
                addr = (y * FB0_STRIDE) + (x * 4);
                vram_word(addr, got);
                exp = texel(x, y);
                if (got !== exp) begin
                    $error("textured FB(%0d,%0d)@0x%08x got 0x%08x expected 0x%08x",
                           x, y, addr, got, exp);
                    errors = errors + 1;
                end
            end
        end

        // ===========================================================
        // 2) FLAT CONTROL SPRITE (TME=0) — proves unchanged path.
        // ===========================================================
        drive_reg(R_PRIM,    PRIM_SPRITE_FLAT);
        drive_reg(R_FRAME_1, FRAME_1_FB1);
        drive_reg(R_RGBAQ,   FLAT_RGBAQ);
        drive_reg(R_XYZ2,    xyz2_data(12'd0, 12'd0));
        drive_reg(R_XYZ2,    xyz2_data(12'(SPRITE_W - 1), 12'(SPRITE_H - 1)));
        drive_idle();

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

        // Flat sprite landed in FB1 — every pixel == FLAT color low32.
        for (y = 0; y < SPRITE_H; y++) begin
            for (x = 0; x < SPRITE_W; x++) begin
                logic [31:0] addr;
                addr = FB1_BASE + (y * FB0_STRIDE) + (x * 4);
                vram_word(addr, got);
                exp = FLAT_RGBAQ[31:0];
                if (got !== exp) begin
                    $error("flat FB(%0d,%0d)@0x%08x got 0x%08x expected 0x%08x",
                           x, y, addr, got, exp);
                    errors = errors + 1;
                end
            end
        end

        $display("[tb_gs_textured_sprite] sprite=%0dx%0d tex_base=0x%08x emits=%0d textured=%0d",
                 SPRITE_W, SPRITE_H, TEX_BASE_BYTES,
                 raster_pixel_emit_count, textured_emit_seen);

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

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

endmodule : tb_gs_textured_sprite
