// retroDE_ps2 — tb_gs_textured_triangle (textured-triangle rung)
//
// FIRST textured-TRIANGLE test: drives a PSMCT32 DECAL textured,
// NON-axis-aligned TRIANGLE (PRIM type 3, TME=1) through gs_stub and
// verifies the framebuffer pixels equal the texel sampled at the
// per-pixel AFFINE-interpolated (u,v).
//
// Datapath under test:
//   PRIM.TRI+TME + TEX0_1 + per-vertex UV
//     -> shared-divider gradient engine solves dU/dx,dU/dy,dV/dx,dV/dy
//        (steps 10..13) alongside R/G/B/A/Z
//     -> per-pixel affine (u,v) via interp_affine_uv (reuses the 32x16
//        interp multipliers)
//     -> gs_texture_unit (gs_texel_addr + PSMCT32 DECAL sample)
//     -> texel REPLACES the Gouraud color at emit.
//
// ZTE=0, ABE=0 for this rung (read2's only consumer is the texel fetch).
//
// Mapping trick (so the expected texel is exactly texel(x,y)): each
// vertex's UV is set EQUAL to its screen (x,y). Both UV and screen XY
// are then the SAME affine function of barycentric coords, so the
// interpolated (u,v) == (x,y) at every interior pixel. The expected FB
// pixel is therefore the preloaded texel(x,y).
//
// The texture is PRELOADED directly into vram_stub at TBP0*256 (same
// upload bypass as tb_gs_textured_sprite) to isolate the sampling path.

`timescale 1ns/1ps

module tb_gs_textured_triangle;

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

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

    logic [31:0] vram_read_addr;
    logic [31:0] vram_read_data;

    localparam int VRAM_BYTES = 16384;

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

    // ----- 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=3 (TRIANGLE) at [2:0]; TME at bit 4.
    localparam logic [63:0] PRIM_TRI_TEX = 64'd3 | (64'd1 << 4);

    // FRAME_1: FBP=0, FBW=1, PSM=PSMCT32.
    localparam logic [63:0] FRAME_1_FB0 = 64'h0000_0000_0001_0000;

    // TEX0_1: TBP0=8 (base 2048 B), TBW=1 (64 texels/row), PSM=PSMCT32.
    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

    localparam int FB0_STRIDE = 64 * 4;     // FBW=1 -> 64 px/row * 4 B

    // Recognizable texel pattern (distinct per (x,y)).
    function automatic logic [31:0] texel(input int x, input int y);
        return 32'hFF000000 | (x << 8) | (y << 16) | 32'h00000050;
    endfunction

    // ----- drive helpers -----
    task automatic drive_reg(input logic [7:0] num, input logic [63:0] data);
        @(negedge clk);
        gif_reg_wr_en = 1'b1; gif_reg_num = num; gif_reg_data = data;
        @(posedge clk);
    endtask
    task automatic drive_idle();
        @(negedge clk);
        gif_reg_wr_en = 1'b0; gif_reg_num = 8'd0; gif_reg_data = 64'd0;
        @(posedge clk);
    endtask

    function automatic logic [63:0] xyz2_data(input int x, input int y);
        return {32'd0, 12'(y), 4'd0, 12'(x), 4'd0};
    endfunction
    function automatic logic [63:0] rgbaq(input int r, input int g, input int b);
        return {32'd0, 8'hFF, 8'(b), 8'(g), 8'(r)};
    endfunction
    // UV reg: U=[13:0], V=[27:14], 10.4 fixed-point (integer << 4).
    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

    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

    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

    // ----- Independent reference: triangle inside test (matches DUT) -----
    int vx0, vy0, vx1, vy1, vx2, vy2;
    int sx1, sy1, sx2, sy2;
    function automatic int edge_f(input int px, input int py,
                                  input int ax, input int ay,
                                  input int bx, input int by);
        return (px - ax) * (by - ay) - (py - ay) * (bx - ax);
    endfunction
    function automatic bit tol(input int ax, input int ay, input int bx, input int by);
        int dx, dy; dx = bx - ax; dy = by - ay;
        return (dy > 0) || ((dy == 0) && (dx > 0));
    endfunction
    task automatic setup_ref();
        int sa;
        sa = (vx1 - vx0) * (vy2 - vy0) - (vy1 - vy0) * (vx2 - vx0);
        if (sa < 0) begin sx1 = vx2; sy1 = vy2; sx2 = vx1; sy2 = vy1; end
        else        begin sx1 = vx1; sy1 = vy1; sx2 = vx2; sy2 = vy2; end
    endtask
    function automatic bit ref_inside(input int px, input int py);
        int e0, e1, e2, b0, b1, b2;
        e0 = edge_f(px, py, vx0, vy0, sx1, sy1);
        e1 = edge_f(px, py, sx1, sy1, sx2, sy2);
        e2 = edge_f(px, py, sx2, sy2, vx0, vy0);
        b0 = tol(vx0, vy0, sx1, sy1) ? 0 : 1;
        b1 = tol(sx1, sy1, sx2, sy2) ? 0 : 1;
        b2 = tol(sx2, sy2, vx0, vy0) ? 0 : 1;
        return ((e0 + b0) <= 0) && ((e1 + b1) <= 0) && ((e2 + b2) <= 0);
    endfunction

    int errors;
    int inside_ok, missing, outside_bad;

    // Coverage + captured color from raster emits.
    bit          covered [0:15][0:15];
    logic [31:0] cap_px  [0:15][0:15];

    bit cap_armed;
    always_ff @(posedge clk) begin
        if (rst_n && cap_armed && raster_pixel_emit
            && raster_pixel_x_q < 16 && raster_pixel_y_q < 16) begin
            covered[raster_pixel_y_q][raster_pixel_x_q] <= 1'b1;
            cap_px [raster_pixel_y_q][raster_pixel_x_q] <= raster_pixel_color_q[31:0];
        end
    end

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

    initial begin
        errors = 0; inside_ok = 0; missing = 0; outside_bad = 0;
        cap_armed = 1'b0;
        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;
        for (y = 0; y < 16; y++)
            for (x = 0; x < 16; x++) begin
                covered[y][x] = 1'b0; cap_px[y][x] = 32'd0;
            end

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

        // --- Preload a 16x16 texture region directly into VRAM. ---
        for (y = 0; y < 16; y++)
            for (x = 0; x < 16; x++) begin
                logic [31:0] addr;
                addr = TEX_BASE_BYTES + ((y * TEX_ROW_TEXELS + x) * 4);
                force_word(addr, texel(x, y));
            end

        // --- Triangle: UV == screen XY at each vertex, so the affine
        //     (u,v) == (x,y) at every interior pixel. Non-axis-aligned. ---
        vx0 = 2;  vy0 = 1;
        vx1 = 13; vy1 = 2;
        vx2 = 5;  vy2 = 7;
        setup_ref();

        cap_armed = 1'b1;
        drive_reg(R_PRIM,    PRIM_TRI_TEX);
        drive_reg(R_FRAME_1, FRAME_1_FB0);
        drive_reg(R_TEX0_1,  TEX0_VAL);
        // v0
        drive_reg(R_RGBAQ,   rgbaq(8'hFF, 0, 0));
        drive_reg(R_UV,      uv_data(vx0, vy0));
        drive_reg(R_XYZ2,    xyz2_data(vx0, vy0));
        // v1
        drive_reg(R_RGBAQ,   rgbaq(0, 8'hFF, 0));
        drive_reg(R_UV,      uv_data(vx1, vy1));
        drive_reg(R_XYZ2,    xyz2_data(vx1, vy1));
        // v2 (closes)
        drive_reg(R_RGBAQ,   rgbaq(0, 0, 8'hFF));
        drive_reg(R_UV,      uv_data(vx2, vy2));
        drive_reg(R_XYZ2,    xyz2_data(vx2, vy2));
        drive_idle();

        repeat (300) @(posedge clk);
        cap_armed = 1'b0;
        @(posedge clk);

        if (raster_overflow)   begin $error("raster_overflow"); errors = errors + 1; end
        if (raster_degenerate) begin $error("raster_degenerate"); errors = errors + 1; end

        // Coverage + texel-sample check across the triangle interior.
        for (y = 0; y < 16; y++) begin
            for (x = 0; x < 16; x++) begin
                bit want;
                want = ref_inside(x, y);
                if (want && !covered[y][x]) begin
                    $error("[coverage] inside (%0d,%0d) NOT drawn", x, y);
                    missing = missing + 1; errors = errors + 1;
                end else if (!want && covered[y][x]) begin
                    $error("[coverage] outside (%0d,%0d) WAS drawn", x, y);
                    outside_bad = outside_bad + 1; errors = errors + 1;
                end else if (want && covered[y][x]) begin
                    // affine (u,v) == (x,y) here -> texel(x,y) exactly.
                    exp = texel(x, y);
                    got = cap_px[y][x];
                    if (got !== exp) begin
                        $error("[texel] (%0d,%0d) got 0x%08x expected 0x%08x",
                               x, y, got, exp);
                        errors = errors + 1;
                    end else begin
                        inside_ok = inside_ok + 1;
                    end
                end
            end
        end

        // Also confirm the framebuffer landed the sampled texels.
        for (y = 0; y < 16; y++) begin
            for (x = 0; x < 16; x++) begin
                if (ref_inside(x, y)) begin
                    logic [31:0] addr;
                    addr = (y * FB0_STRIDE) + (x * 4);
                    vram_word(addr, got);
                    exp = texel(x, y);
                    if (got !== exp) begin
                        $error("[FB] (%0d,%0d)@0x%08x got 0x%08x expected 0x%08x",
                               x, y, addr, got, exp);
                        errors = errors + 1;
                    end
                end
            end
        end

        if (inside_ok < 4) begin
            $error("too few interior textured pixels checked (%0d)", inside_ok);
            errors = errors + 1;
        end

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

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

endmodule : tb_gs_textured_triangle
