// retroDE_ps2 — tb_gs_scanout_magh_magv (Ch93)
//
// Locks the contract for DISPLAY1.MAGH / MAGV — the per-axis
// magnification factors. Real PS2 PCRTC scans the display
// window in VCK pulses (H) and raster lines (V); MAGH+1 says
// how many VCK pulses each VRAM column occupies, MAGV+1 says
// how many raster lines each VRAM line occupies. Concretely,
// a 4-pixel-wide VRAM sprite with MAGH=1 (2×) appears 8 pixels
// wide on the displayed frame, with each VRAM column shown
// twice in succession.
//
// Setup:
//   Sprite at VRAM (0,0)..(3,3) — 4×4 pixels at color 0xFF30.
//   FBP=0, FBW=1, PSM=PSMCT32, DBX=0, DBY=0.
//   DISPLAY1: DX=4, DY=2, DW=7 (8 wide), DH=7 (8 tall),
//             MAGH=1 (2× horizontal), MAGV=1 (2× vertical).
//   PCRTC active 16×12 — leaves room for "outside the window"
//   pixels above / below / left / right of the 8×8 window.
//
// Expected frame (16 cols × 12 rows):
//   - displayed (4..11, 2..9): sprite color (4×4 VRAM × 2× = 8×8 displayed)
//   - all other displayed pixels: 0
// At a finer level, displayed (4, 2) reads VRAM (0, 0); (5, 2)
// reads VRAM (0, 0) again (2× horizontal); (6, 2) reads (1, 0);
// (4, 3) reads VRAM (0, 0) again (2× vertical).
//
// PASS criterion: every captured pixel in the 16×12 active area
// matches the expected (R, G, B) per the math above.

`timescale 1ns/1ps

module tb_gs_scanout_magh_magv;

    localparam int PCRTC_H_ACTIVE = 16;
    localparam int PCRTC_V_ACTIVE = 12;

    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        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                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 [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),
        .reg_wr_en  (priv_reg_wr_en),
        .reg_wr_addr(priv_reg_wr_addr),
        .reg_wr_data(priv_reg_wr_data),
        .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),
        .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_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)
    );

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

    vram_stub #(.BYTES(4096)) 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(32'hFFFF_FFFF),
        .read_addr (vram_read_addr),
        .read_data (vram_read_data),
        .read2_addr(32'd0),
        .read2_data()
    );

    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_read_addr),
        .vram_read_data(vram_read_data),
        .clut_enable   (1'b0),
        .clut_csa      (5'd0),
        .clut_read_idx (),
        .clut_read_data(32'd0),
        .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)
    );

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

    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

    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

    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

    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_FRAME_1  = 8'h4C;

    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 logic [63:0] PRIM_SPRITE  = 64'd6;
    localparam logic [63:0] FRAME_1_VAL  = 64'h0000_0000_0001_0000;
    localparam logic [63:0] RGBAQ_VAL    = 64'h0000_0000_0000_FF30;
    localparam logic [63:0] DISPFB1_VAL  = 64'h0000_0000_0000_0200;
    // DISPLAY1: DX=4, DY=2, DW=7 (8 wide), DH=7 (8 tall),
    // MAGH=1 (2×), MAGV=1 (2×).
    //   DX   [11:0]   = 4
    //   DY   [22:12]  = 2 → bit 12
    //   MAGH [26:23]  = 1 → bit 23
    //   MAGV [28:27]  = 1 → bit 27
    //   DW   [43:32]  = 7 → bit 32
    //   DH   [54:44]  = 7 → bit 44
    localparam logic [63:0] DISPLAY1_VAL =
          64'(12'd4)
        | (64'(11'd2) << 12)
        | (64'(4'd1)  << 23)
        | (64'(2'd1)  << 27)
        | (64'(12'd7) << 32)
        | (64'(11'd7) << 44);
    localparam logic [63:0] PMODE_EN1    = 64'h0000_0000_0000_0001;

    localparam int WIN_DX   = 4;
    localparam int WIN_DY   = 2;
    localparam int WIN_W    = 8;   // DW + 1
    localparam int WIN_H    = 8;   // DH + 1
    localparam int MAGH_FAC = 2;   // MAGH + 1
    localparam int MAGV_FAC = 2;   // MAGV + 1

    localparam int SPRITE_W = 4;   // VRAM cols
    localparam int SPRITE_H = 4;   // VRAM rows

    localparam logic [7:0] EXP_R = 8'h30;
    localparam logic [7:0] EXP_G = 8'hFF;
    localparam logic [7:0] EXP_B = 8'h00;

    initial begin
        rst_n            = 1'b0;
        gif_reg_wr_en    = 1'b0;
        gif_reg_num      = 8'd0;
        gif_reg_data     = 64'd0;
        priv_reg_wr_en   = 1'b0;
        priv_reg_wr_addr = 16'd0;
        priv_reg_wr_data = 64'd0;

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

        drive_priv(DISPFB1_OFF,  DISPFB1_VAL);
        drive_priv(DISPLAY1_OFF, DISPLAY1_VAL);

        // Sprite at VRAM (0..3, 0..3).
        drive_reg(R_PRIM,    PRIM_SPRITE);
        drive_reg(R_FRAME_1, FRAME_1_VAL);
        drive_reg(R_RGBAQ,   RGBAQ_VAL);
        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);

        if (raster_pixel_emit_count != 32'(SPRITE_W * SPRITE_H)) begin
            $error("expected %0d emits, got %0d",
                   SPRITE_W * SPRITE_H, raster_pixel_emit_count);
            errors = errors + 1;
        end

        // Confirm DISPLAY1 latched MAGH/MAGV at the right bit positions.
        if (display1_q[26:23] !== 4'd1) begin
            $error("MAGH=%0d (expected 1)", display1_q[26:23]);
            errors = errors + 1;
        end
        if (display1_q[28:27] !== 2'd1) begin
            $error("MAGV=%0d (expected 1)", display1_q[28:27]);
            errors = errors + 1;
        end

        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;

        // Verify per-pixel scanout.
        for (int y = 0; y < PCRTC_V_ACTIVE; y++) begin
            for (int x = 0; x < PCRTC_H_ACTIVE; x++) begin
                logic [7:0] er, eg, eb;
                bit         in_window;
                int         hwin_rel;
                int         vwin_rel;
                int         vram_x;
                int         vram_y;
                bit         in_sprite;

                in_window = (x >= WIN_DX) && (x < WIN_DX + WIN_W)
                         && (y >= WIN_DY) && (y < WIN_DY + WIN_H);

                if (in_window) begin
                    hwin_rel  = x - WIN_DX;
                    vwin_rel  = y - WIN_DY;
                    vram_x    = hwin_rel / MAGH_FAC;
                    vram_y    = vwin_rel / MAGV_FAC;
                    in_sprite = (vram_x < SPRITE_W) && (vram_y < SPRITE_H);
                end else begin
                    in_sprite = 1'b0;
                end

                if (in_sprite) begin
                    er = EXP_R; eg = EXP_G; eb = EXP_B;
                end else begin
                    er = 8'd0; eg = 8'd0; eb = 8'd0;
                end

                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) in_window=%0d",
                           x, y, cap_r[y][x], cap_g[y][x], cap_b[y][x],
                           er, eg, eb, in_window);
                    errors = errors + 1;
                end
            end
        end

        $display("[tb_gs_scanout_magh_magv] window=(DX=%0d DY=%0d %0dx%0d) MAGH=%0d MAGV=%0d (factors %0dx %0dx)",
                 WIN_DX, WIN_DY, WIN_W, WIN_H, 1, 1, MAGH_FAC, MAGV_FAC);

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

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

endmodule : tb_gs_scanout_magh_magv
