// retroDE_ps2 — tb_gs_fog
//
// Focused white-box TB for GS per-vertex FOG in the reduced rasterizer.
//
// PS2 GS fog: final_color_channel = (C * F + FOGCOL * (255 - F)) >> 8, per
// RGB channel, where F is the 8-bit per-vertex fog coefficient (XYZF2 bits
// [63:56]) interpolated affinely across the primitive (flat for a SPRITE),
// gated on PRIM.FGE (bit 5). FOGCOL is GIF reg 0x3D (low 24 bits = 0xBBGGRR).
// Alpha is NOT fogged. When FGE=0 the emit is byte-identical to the no-fog
// path — the hard invariant.
//
// Tests:
//   T1 — FGE=1 triangle, FLAT color, FLAT F. Assert the emitted RGB equals the
//        EXACT hand-computed fog blend at several interior pixels, and the
//        alpha is preserved unchanged.
//   T2 — FGE=1 triangle, FLAT color, DISTINCT per-vertex F. Probe the white-box
//        s2_fog_f at interior S2 pixels and assert it matches the barycentric
//        (ground-truth) interpolated F within 1 LSB — proving F rides the
//        shared affine gradient engine like the colour/Z attributes.
//   T3 — FGE=0 triangle, SAME geometry/color as T1 with FOGCOL still set.
//        Assert the emitted color is BYTE-IDENTICAL to the raw vertex color
//        (no fog applied) — the non-negotiable invariant.
//   T4 — FGE=1 SPRITE, flat color, flat F. Assert the exact fog blend on the
//        flat-sprite emit path (s2_sprite_color64 chokepoint).

`timescale 1ns/1ps

module tb_gs_fog;

    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]         prim_q, rgbaq_q, xyz2_q, xyzf2_q, frame_1_q, zbuf_1_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                fb_rd_en;   logic [31:0] fb_rd_addr;
    logic                z_rd_en;    logic [31:0] z_rd_addr;
    logic                ev_valid;
    trace_pkg::subsys_e  ev_subsys;
    trace_pkg::event_e   ev_event;
    logic [63:0]         ev_arg0, ev_arg1, ev_arg2, ev_arg3;
    logic [31:0]         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),
        .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),
        .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(32'd0),
        .fb_rd_en(fb_rd_en), .fb_rd_addr(fb_rd_addr), .fb_rd_data(32'd0),
        .z_rd_en(z_rd_en), .z_rd_addr(z_rd_addr), .z_rd_data(32'd0),
        .ev_valid(ev_valid), .ev_subsys(ev_subsys), .ev_event(ev_event),
        .ev_arg0(ev_arg0), .ev_arg1(ev_arg1),
        .ev_arg2(ev_arg2), .ev_arg3(ev_arg3),
        .ev_flags(ev_flags)
    );

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

    // XYZF2 (reg 0x04): X=[15:0] (12.4), Y=[31:16] (12.4), Z=[55:32] (24b),
    // F=[63:56] (8b fog). Screen coords carry no fractional bits here.
    function automatic logic [63:0] xyzf2(input int x, input int y,
                                          input int z, input int f);
        return {8'(f), 24'(z), 12'(y), 4'd0, 12'(x), 4'd0};
    endfunction
    function automatic logic [63:0] rgbaq(input int r, input int g, input int b, input int a);
        return {32'd0, 8'(a), 8'(b), 8'(g), 8'(r)};
    endfunction

    localparam logic [7:0] R_PRIM    = 8'h00;
    localparam logic [7:0] R_RGBAQ   = 8'h01;
    localparam logic [7:0] R_XYZF2   = 8'h04;
    localparam logic [7:0] R_FOGCOL  = 8'h3D;
    localparam logic [7:0] R_FRAME_1 = 8'h4C;
    localparam logic [63:0] PRIM_TRI          = 64'd3;             // TRI
    localparam logic [63:0] PRIM_TRI_FGE      = 64'd3 | (64'd1 << 5);  // TRI + FGE
    localparam logic [63:0] PRIM_SPRITE_FGE   = 64'd6 | (64'd1 << 5);  // SPRITE + FGE
    localparam logic [63:0] FRAME_1_VAL       = 64'h0000_0000_0001_0000;  // FBW=1, PSMCT32

    // FOGCOL = 0xBBGGRR
    localparam int FOG_R = 8'h20;
    localparam int FOG_G = 8'h40;
    localparam int FOG_B = 8'h60;
    localparam logic [63:0] FOGCOL_VAL = {40'd0, 8'(FOG_B), 8'(FOG_G), 8'(FOG_R)};

    // Reference fog blend (matches RTL fog_blend_abgr exactly).
    function automatic int fog_ch(input int c, input int f, input int fc);
        return (c * f + fc * (255 - f)) >> 8;
    endfunction

    function automatic int absdiff(input int a, input int b);
        return (a > b) ? (a - b) : (b - a);
    endfunction

    // ----- Independent triangle reference (edge fn, fill rule, barycentric) -----
    int vx0, vy0, vx1, vy1, vx2, vy2;
    int vf0, vf1, vf2;
    int ref_det;
    int sx1, sy1, sx2, sy2, sf1, sf2;

    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

    task automatic setup_ref();
        int sa;
        sa = (vx1 - vx0) * (vy2 - vy0) - (vy1 - vy0) * (vx2 - vx0);
        if (sa < 0) begin
            sx1 = vx2; sy1 = vy2; sf1 = vf2;
            sx2 = vx1; sy2 = vy1; sf2 = vf1;
            ref_det = -sa;
        end else begin
            sx1 = vx1; sy1 = vy1; sf1 = vf1;
            sx2 = vx2; sy2 = vy2; sf2 = vf2;
            ref_det = sa;
        end
    endtask

    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

    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

    function automatic int ref_attr(input int px, input int py,
                                    input int a0, input int a1, input int a2);
        int L0, L1, L2, num;
        L0 = -edge_f(px, py, sx1, sy1, sx2, sy2);
        L1 = -edge_f(px, py, sx2, sy2, vx0, vy0);
        L2 = -edge_f(px, py, vx0, vy0, sx1, sy1);
        num = L0 * a0 + L1 * a1 + L2 * a2;
        if (ref_det == 0) return 0;
        return num / ref_det;
    endfunction

    int errors;

    // ----- Emit capture (full 32-bit ABGR) -----
    bit         covered [0:15][0:15];
    logic [31:0] cap_c  [0:15][0:15];
    bit cap_armed;
    task automatic clear_cov();
        for (int y = 0; y < 16; y++)
            for (int x = 0; x < 16; x++) begin
                covered[y][x] = 1'b0; cap_c[y][x] = 32'd0;
            end
    endtask
    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_c  [raster_pixel_y_q][raster_pixel_x_q] <= raster_pixel_color_q[31:0];
        end
    end

    // ----- T2 F-interpolation probe: white-box s2_fog_f at interior pixels -----
    int f_probe_checks;
    bit f_probe_armed;
    always_ff @(posedge clk) begin
        if (rst_n && f_probe_armed
            && u_gs.s2_valid_q && u_gs.s2_inside_q && u_gs.ras_tri_active) begin
            int px, py, ef;
            px = int'(u_gs.s2_x_q);
            py = int'(u_gs.s2_y_q);
            if (px < 16 && py < 16 && ref_inside(px, py)) begin
                ef = ref_attr(px, py, vf0, sf1, sf2);
                if (absdiff(int'(u_gs.s2_fog_f), ef) > 1) begin
                    $error("[T2 F] (%0d,%0d) s2_fog_f=%0d expected ~%0d",
                           px, py, u_gs.s2_fog_f, ef);
                    errors = errors + 1;
                end else begin
                    f_probe_checks = f_probe_checks + 1;
                end
            end
        end
    end

    // Exact fog-blend spot check on a captured emitted pixel.
    task automatic chk_fog(input int x, input int y,
                           input int cr, input int cg, input int cb, input int ca,
                           input int f);
        int er, eg, eb;
        er = fog_ch(cr, f, FOG_R);
        eg = fog_ch(cg, f, FOG_G);
        eb = fog_ch(cb, f, FOG_B);
        if (!covered[y][x]) begin
            $error("[fog] (%0d,%0d) expected covered but was not", x, y);
            errors = errors + 1;
        end else if (cap_c[y][x][7:0] !== er[7:0] ||
                     cap_c[y][x][15:8] !== eg[7:0] ||
                     cap_c[y][x][23:16] !== eb[7:0]) begin
            $error("[fog] (%0d,%0d) got (%0d,%0d,%0d) expected EXACT (%0d,%0d,%0d)",
                   x, y, cap_c[y][x][7:0], cap_c[y][x][15:8], cap_c[y][x][23:16], er, eg, eb);
            errors = errors + 1;
        end else if (cap_c[y][x][31:24] !== ca[7:0]) begin
            $error("[fog] (%0d,%0d) alpha fogged: got %0d expected %0d (unchanged)",
                   x, y, cap_c[y][x][31:24], ca);
            errors = errors + 1;
        end else begin
            $display("[fog] (%0d,%0d) got (%0d,%0d,%0d,a=%0d) EXACT OK",
                     x, y, cap_c[y][x][7:0], cap_c[y][x][15:8], cap_c[y][x][23:16],
                     cap_c[y][x][31:24]);
        end
    endtask

    // Exact no-fog (FGE=0 invariant): emitted RGB == raw color, alpha == raw.
    task automatic chk_nofog(input int x, input int y,
                             input int cr, input int cg, input int cb, input int ca);
        if (!covered[y][x]) begin
            $error("[nofog] (%0d,%0d) expected covered but was not", x, y);
            errors = errors + 1;
        end else if (cap_c[y][x][7:0] !== cr[7:0] ||
                     cap_c[y][x][15:8] !== cg[7:0] ||
                     cap_c[y][x][23:16] !== cb[7:0] ||
                     cap_c[y][x][31:24] !== ca[7:0]) begin
            $error("[nofog] (%0d,%0d) FGE=0 NOT byte-identical: got %08x expected raw (%0d,%0d,%0d,a=%0d)",
                   x, y, cap_c[y][x], cr, cg, cb, ca);
            errors = errors + 1;
        end else begin
            $display("[nofog] (%0d,%0d) FGE=0 byte-identical raw color OK", x, y);
        end
    endtask

    // Flat triangle constants.
    localparam int TC_R = 8'hC0, TC_G = 8'h80, TC_B = 8'h30, TC_A = 8'hFF;

    initial begin
        errors = 0; f_probe_checks = 0; cap_armed = 1'b0; f_probe_armed = 1'b0;
        rst_n = 1'b0; gif_reg_wr_en = 1'b0; gif_reg_num = 8'd0; gif_reg_data = 64'd0;
        clear_cov();

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

        // ================================================================
        // T1 — FGE=1 triangle, FLAT color, FLAT F. Exact fog blend.
        // ================================================================
        vx0=2; vy0=1; vf0=8'h40;
        vx1=13;vy1=2; vf1=8'h40;
        vx2=5; vy2=7; vf2=8'h40;
        setup_ref();

        clear_cov(); cap_armed = 1'b1;
        drive_reg(R_FOGCOL,  FOGCOL_VAL);
        drive_reg(R_PRIM,    PRIM_TRI_FGE);
        drive_reg(R_FRAME_1, FRAME_1_VAL);
        drive_reg(R_RGBAQ,   rgbaq(TC_R,TC_G,TC_B,TC_A));
        drive_reg(R_XYZF2,   xyzf2(vx0,vy0,0,vf0));
        drive_reg(R_RGBAQ,   rgbaq(TC_R,TC_G,TC_B,TC_A));
        drive_reg(R_XYZF2,   xyzf2(vx1,vy1,0,vf1));
        drive_reg(R_RGBAQ,   rgbaq(TC_R,TC_G,TC_B,TC_A));
        drive_reg(R_XYZF2,   xyzf2(vx2,vy2,0,vf2));  // closes
        drive_idle();
        repeat (300) @(posedge clk);
        cap_armed = 1'b0;
        @(posedge clk);

        chk_fog(7, 3, TC_R, TC_G, TC_B, TC_A, 8'h40);
        chk_fog(5, 4, TC_R, TC_G, TC_B, TC_A, 8'h40);
        chk_fog(6, 2, TC_R, TC_G, TC_B, TC_A, 8'h40);
        if (raster_overflow || raster_degenerate) begin
            $error("[T1] raster anomaly"); errors = errors + 1;
        end

        // ================================================================
        // T2 — FGE=1 triangle, FLAT color, DISTINCT per-vertex F. Probe the
        //      white-box interpolated s2_fog_f vs barycentric ground truth.
        // ================================================================
        vx0=2; vy0=1; vf0=8'h10;
        vx1=13;vy1=2; vf1=8'hF0;
        vx2=5; vy2=7; vf2=8'h80;
        setup_ref();

        f_probe_armed = 1'b1;
        drive_reg(R_PRIM,    PRIM_TRI_FGE);
        drive_reg(R_FRAME_1, FRAME_1_VAL);
        drive_reg(R_RGBAQ,   rgbaq(TC_R,TC_G,TC_B,TC_A));
        drive_reg(R_XYZF2,   xyzf2(vx0,vy0,0,vf0));
        drive_reg(R_RGBAQ,   rgbaq(TC_R,TC_G,TC_B,TC_A));
        drive_reg(R_XYZF2,   xyzf2(vx1,vy1,0,vf1));
        drive_reg(R_RGBAQ,   rgbaq(TC_R,TC_G,TC_B,TC_A));
        drive_reg(R_XYZF2,   xyzf2(vx2,vy2,0,vf2));  // closes
        drive_idle();
        repeat (320) @(posedge clk);
        f_probe_armed = 1'b0;
        @(posedge clk);
        if (f_probe_checks == 0) begin
            $error("[T2] no interior F pixels observed"); errors = errors + 1;
        end

        // ================================================================
        // T3 — FGE=0 triangle, SAME geometry/color as T1, FOGCOL still set.
        //      Emitted color MUST be byte-identical to the raw vertex color.
        // ================================================================
        vx0=2; vy0=1; vf0=8'h40;
        vx1=13;vy1=2; vf1=8'h40;
        vx2=5; vy2=7; vf2=8'h40;
        setup_ref();

        clear_cov(); cap_armed = 1'b1;
        drive_reg(R_PRIM,    PRIM_TRI);              // FGE = 0
        drive_reg(R_FRAME_1, FRAME_1_VAL);
        drive_reg(R_RGBAQ,   rgbaq(TC_R,TC_G,TC_B,TC_A));
        drive_reg(R_XYZF2,   xyzf2(vx0,vy0,0,vf0));
        drive_reg(R_RGBAQ,   rgbaq(TC_R,TC_G,TC_B,TC_A));
        drive_reg(R_XYZF2,   xyzf2(vx1,vy1,0,vf1));
        drive_reg(R_RGBAQ,   rgbaq(TC_R,TC_G,TC_B,TC_A));
        drive_reg(R_XYZF2,   xyzf2(vx2,vy2,0,vf2));  // closes
        drive_idle();
        repeat (300) @(posedge clk);
        cap_armed = 1'b0;
        @(posedge clk);

        chk_nofog(7, 3, TC_R, TC_G, TC_B, TC_A);
        chk_nofog(5, 4, TC_R, TC_G, TC_B, TC_A);
        chk_nofog(6, 2, TC_R, TC_G, TC_B, TC_A);

        // ================================================================
        // T4 — FGE=1 SPRITE, flat color, flat F. Exact fog blend on the
        //      sprite emit chokepoint (s2_sprite_color64).
        // ================================================================
        clear_cov(); cap_armed = 1'b1;
        drive_reg(R_PRIM,    PRIM_SPRITE_FGE);
        drive_reg(R_FRAME_1, FRAME_1_VAL);
        drive_reg(R_RGBAQ,   rgbaq(TC_R,TC_G,TC_B,TC_A));
        drive_reg(R_XYZF2,   xyzf2(1, 1, 0, 8'hA0));   // sprite origin vertex
        drive_reg(R_XYZF2,   xyzf2(5, 5, 0, 8'hA0));   // closing vertex -> flat F=0xA0
        drive_idle();
        repeat (200) @(posedge clk);
        cap_armed = 1'b0;
        @(posedge clk);

        // Interior sprite pixels (rect [1,5)x[1,5)).
        chk_fog(2, 2, TC_R, TC_G, TC_B, TC_A, 8'hA0);
        chk_fog(3, 4, TC_R, TC_G, TC_B, TC_A, 8'hA0);
        chk_fog(4, 1, TC_R, TC_G, TC_B, TC_A, 8'hA0);

        $display("[tb_gs_fog] T2 f_checks=%0d errors=%0d", f_probe_checks, errors);
        if (errors == 0) $display("[tb_gs_fog] PASS");
        else             $display("[tb_gs_fog] FAIL");
        $finish;
    end

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

endmodule : tb_gs_fog
