// retroDE_ps2 — tb_top_psmct32_feeder_zpersist_demo (Ch338)
//
// CROSS-BATCH Z ORDERING for >FIFO_DEPTH scenes. A NEAR (RED) and a FAR (BLUE) triangle occupy the
// SAME tile (tile 5) but are SPLIT across FIFO batches. ZBUF clear = 0x4000, TEST = GEQUAL (higher Z
// = nearer wins). With PERSISTENT cross-batch Z (TILE_Z_PERSIST, on with FEEDER_ENABLE) the NEAR
// triangle wins the overlap regardless of which batch it is in — the Ch338 acceptance:
//   NEAR_FIRST (near RED in batch0, far BLUE in batch1):  tile5 = RED   (far is Z-rejected)
//   FAR_FIRST  (far BLUE in batch0, near RED in batch1):  tile5 = RED   (near wins on submit too)
// With per-batch Z (the Ch336 v1 limit) NEAR_FIRST would wrongly show BLUE (the later batch starts
// from a fresh Z and overwrites the nearer earlier prim). Identical final overlap pixel regardless of
// the batch boundary == correct GS depth semantics preserved across the FIFO split.

`timescale 1ns/1ps

module tb_top_psmct32_feeder_zpersist_demo;

    localparam int H_ACTIVE = 64, V_ACTIVE = 64;

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

    logic        core_go;
    logic [7:0]  r, g, b;
    logic        hsync, vsync, de;
    logic        core_halt, dma_done_seen, frame_seen, raster_overflow;
    logic        frame_toggle, dma_done_toggle;
    logic        feeder_go_tb, feeder_ready_tb;

    top_psmct32_raster_demo_bram #(
        .H_ACTIVE(H_ACTIVE), .V_ACTIVE(V_ACTIVE),
        .VRAM_BYTES(32*1024), .PSMCT32_SWIZZLE(1'b0),
        .COMBINED_TAZ(1'b1), .TILE_LOCAL(1'b1), .TILE_COLS(4), .TILE_ROWS(4),
        .TILE_MULTIPRIM(1'b1), .TILE_PRIM_COUNT(4), .TILE_FIFO_DEPTH(8),
        .BIN_BUFFER_ENABLE(1'b1), .HEARTBEAT_SPLICE_ENABLE(1'b0),
        .FEEDER_ENABLE(1'b1), .FEEDER_STG_WORDS(256)
    ) dut (
        .clk(clk), .rst_n(rst_n), .core_go(core_go),
        .r(r), .g(g), .b(b), .hsync(hsync), .vsync(vsync), .de(de),
        .core_halt(core_halt), .dma_done_seen(dma_done_seen),
        .frame_seen(frame_seen), .raster_overflow(raster_overflow),
        .frame_toggle(frame_toggle), .dma_done_toggle(dma_done_toggle),
        .joy_a_pressed_i(1'b0), .joy_b_pressed_i(1'b0),
        .feeder_stg_we_i(1'b0), .feeder_stg_waddr_i(12'd0), .feeder_stg_wdata_i(64'd0),
        .feeder_go_i(feeder_go_tb),
        .feeder_ready_o(feeder_ready_tb), .feeder_records_o(), .feeder_waits_o()
    );

    logic [7:0] cap_r[0:V_ACTIVE-1][0:H_ACTIVE-1], cap_g[0:V_ACTIVE-1][0:H_ACTIVE-1], cap_b[0:V_ACTIVE-1][0:H_ACTIVE-1];
    logic       cap_de[0:V_ACTIVE-1][0:H_ACTIVE-1];
    bit capture_armed;
    task automatic clear_cap;
        for (int y=0;y<V_ACTIVE;y++) for (int x=0;x<H_ACTIVE;x++) begin
            cap_r[y][x]=0; cap_g[y][x]=0; cap_b[y][x]=0; cap_de[y][x]=0; end
    endtask
    initial begin clear_cap(); capture_armed=1'b0; end
    logic [31:0] hcnt_d, vcnt_d;
    always_ff @(posedge clk) begin
        if (!rst_n) begin hcnt_d<=0; vcnt_d<=0; end
        else begin hcnt_d<=32'(dut.u_pcrtc.hcnt); vcnt_d<=32'(dut.u_pcrtc.vcnt); end
    end
    always_ff @(posedge clk)
        if (rst_n && capture_armed && de && (vcnt_d<V_ACTIVE) && (hcnt_d<H_ACTIVE)) begin
            cap_r[vcnt_d][hcnt_d]<=r; cap_g[vcnt_d][hcnt_d]<=g; cap_b[vcnt_d][hcnt_d]<=b; cap_de[vcnt_d][hcnt_d]<=1'b1; end

    function automatic int color_in_box(input int bx0, input int by0, input logic [7:0] er, eg, eb);
        int n; begin n=0;
            for (int y=by0;y<by0+16;y++) for (int x=bx0;x<bx0+16;x++)
                if (cap_de[y][x] && cap_r[y][x]===er && cap_g[y][x]===eg && cap_b[y][x]===eb) n++;
            color_in_box = n;
        end
    endfunction
    function automatic int tx(input int t); tx = (t%4)*16; endfunction
    function automatic int ty(input int t); ty = (t/4)*16; endfunction
    // count of any DRAWN (de) pixel in a tile box — used for the gradient overlap (its colors vary).
    function automatic int drawn_in_box(input int bx0, input int by0);
        int n; begin n=0;
            for (int y=by0;y<by0+16;y++) for (int x=bx0;x<bx0+16;x++) if (cap_de[y][x]) n++;
            drawn_in_box = n;
        end
    endfunction

    int errors;
    localparam logic [7:0] FF=8'hFF, ZZ=8'h00;

    task automatic recapture;
        repeat(200000) @(posedge clk);
        @(posedge dut.u_pcrtc.end_of_frame); @(posedge clk); clear_cap(); capture_armed=1'b1;
        @(posedge dut.u_pcrtc.end_of_frame); @(posedge clk); capture_armed=1'b0;
    endtask

    // The overlap tile (5) must show NEAR=RED with NO far BLUE bleed-through, in BOTH orderings.
    task automatic check_overlap(input string label);
        if (color_in_box(tx(5),ty(5),FF,ZZ,ZZ) < 15) begin
            $error("[%s] overlap tile 5 not RED (near) — %0d red px (cross-batch Z lost)", label, color_in_box(tx(5),ty(5),FF,ZZ,ZZ)); errors++; end
        if (color_in_box(tx(5),ty(5),ZZ,ZZ,FF) != 0) begin
            $error("[%s] overlap tile 5 has %0d BLUE (far) px — later batch overwrote the nearer prim!", label, color_in_box(tx(5),ty(5),ZZ,ZZ,FF)); errors++; end
    endtask

    initial begin
        errors=0; feeder_go_tb=1'b0;
        $readmemh(`FEEDER_ZPN_FILE, dut.g_feeder.feeder_stg);   // boot scene = NEAR_FIRST

        rst_n=1'b0; core_go=1'b0;
        repeat(4) @(posedge clk); rst_n=1'b1; repeat(8) @(posedge clk);
        @(negedge clk); core_go=1'b1; @(negedge clk); core_go=1'b0;
        wait (core_halt==1'b1); repeat(4) @(posedge clk);
        wait (dma_done_seen==1'b1); repeat(10) @(posedge clk);
        if (dut.xfer_busy==1'b1) wait (dut.xfer_busy==1'b0);
        wait (feeder_ready_tb==1'b1);

        // ---- NEAR_FIRST : near RED (batch0) + far BLUE (batch1) overlap tile 5 ----
        recapture();
        check_overlap("NEAR_FIRST");
        // sanity: batch0 filler tile 0 RED, batch1 filler tile 8 BLUE
        if (color_in_box(tx(0),ty(0),FF,ZZ,ZZ) < 15) begin $error("[NEAR_FIRST] tile0 not RED"); errors++; end
        if (color_in_box(tx(8),ty(8),ZZ,ZZ,FF) < 15) begin $error("[NEAR_FIRST] tile8 not BLUE"); errors++; end
        if (int'(dut.feeder_records) != 14) begin $error("[NEAR_FIRST] records=%0d (want 14)", int'(dut.feeder_records)); errors++; end
        $display("[zpersist NEAR_FIRST] tile5 RED=%0d BLUE=%0d | t0 RED=%0d t8 BLUE=%0d | records=%0d",
                 color_in_box(tx(5),ty(5),FF,ZZ,ZZ), color_in_box(tx(5),ty(5),ZZ,ZZ,FF),
                 color_in_box(tx(0),ty(0),FF,ZZ,ZZ), color_in_box(tx(8),ty(8),ZZ,ZZ,FF), int'(dut.feeder_records));

        // ---- FAR_FIRST (retrigger) : far BLUE (batch0) + near RED (batch1) overlap tile 5 ----
        wait (feeder_ready_tb==1'b1);
        $readmemh(`FEEDER_ZPF_FILE, dut.g_feeder.feeder_stg);
        @(negedge clk); feeder_go_tb=1'b1; @(negedge clk); feeder_go_tb=1'b0;
        recapture();
        check_overlap("FAR_FIRST");
        // sanity: batch0 filler tile 0 BLUE, batch1 filler tile 8 RED (colors reversed vs NEAR_FIRST)
        if (color_in_box(tx(0),ty(0),ZZ,ZZ,FF) < 15) begin $error("[FAR_FIRST] tile0 not BLUE"); errors++; end
        if (color_in_box(tx(8),ty(8),FF,ZZ,ZZ) < 15) begin $error("[FAR_FIRST] tile8 not RED"); errors++; end
        if (raster_overflow) begin $error("[FAR_FIRST] raster_overflow set"); errors++; end
        $display("[zpersist FAR_FIRST] tile5 RED=%0d BLUE=%0d | t0 BLUE=%0d t8 RED=%0d | records=%0d",
                 color_in_box(tx(5),ty(5),FF,ZZ,ZZ), color_in_box(tx(5),ty(5),ZZ,ZZ,FF),
                 color_in_box(tx(0),ty(0),ZZ,ZZ,FF), color_in_box(tx(8),ty(8),FF,ZZ,ZZ), int'(dut.feeder_records));

        // ---- GRADIENT (retrigger) : NEAR gouraud RGB (batch0) + FAR flat WHITE (batch1) overlap ----
        // Mixed colored/gradient scene: the near GRADIENT must win the overlap, so tile 5 is drawn with
        // interpolated colors and ZERO white (the far flat prim is Z-rejected across the batch split).
        wait (feeder_ready_tb==1'b1);
        $readmemh(`FEEDER_ZPG_FILE, dut.g_feeder.feeder_stg);
        @(negedge clk); feeder_go_tb=1'b1; @(negedge clk); feeder_go_tb=1'b0;
        recapture();
        if (color_in_box(tx(5),ty(5),FF,FF,FF) != 0) begin
            $error("[GRAD] overlap tile 5 has %0d WHITE (far) px — far overwrote the near gradient!", color_in_box(tx(5),ty(5),FF,FF,FF)); errors++; end
        if (drawn_in_box(tx(5),ty(5)) < 60) begin
            $error("[GRAD] overlap tile 5 only %0d drawn px — near gradient missing", drawn_in_box(tx(5),ty(5))); errors++; end
        if (int'(dut.feeder_records) != 14) begin $error("[GRAD] records=%0d (want 14)", int'(dut.feeder_records)); errors++; end
        $display("[zpersist GRAD] tile5 WHITE=%0d drawn=%0d (gradient near wins, no far white) | records=%0d",
                 color_in_box(tx(5),ty(5),FF,FF,FF), drawn_in_box(tx(5),ty(5)), int'(dut.feeder_records));

        $display("[tb_top_psmct32_feeder_zpersist_demo] errors=%0d", errors);
        if (errors==0) $display("[tb_top_psmct32_feeder_zpersist_demo] PASS");
        else           $display("[tb_top_psmct32_feeder_zpersist_demo] FAIL");
        $finish;
    end
    initial begin #2500000000; $error("[tb_top_psmct32_feeder_zpersist_demo] TIMEOUT"); $finish; end
endmodule : tb_top_psmct32_feeder_zpersist_demo
