dakies/OSS_Verilog huggingface dataset:
module top
# (
    parameter X_WIDTH = 10,
              Y_WIDTH = 10,
              clk_mhz = 50
)
(
    input         clk,
    input  [ 3:0] key,
    input  [ 3:0] sw,
    output [ 7:0] led,

    output [ 7:0] abcdefgh,
    output [ 7:0] digit,

    output        vsync,
    output        hsync,
    output [ 2:0] rgb,

    output        buzzer,
    inout  [15:0] gpio
);

    wire   reset       =   ~ sw [0];

    assign led         =   { sw, key };
    assign abcdefgh    =   { sw, key };
    assign digit       =   { sw, key };
    assign buzzer      =   ~ reset;

    //------------------------------------------------------------------------

    wire                 display_on;
    wire [X_WIDTH - 1:0] pixel_x;
    wire [Y_WIDTH - 1:0] pixel_y;
 
    vga
    # (
        .HPOS_WIDTH ( X_WIDTH    ),
        .VPOS_WIDTH ( Y_WIDTH    ),
        
        .CLK_MHZ    ( clk_mhz    )
    )
    i_vga
    (
        .clk        ( clk        ), 
        .reset      ( reset      ),
        .hsync      ( hsync      ),
        .vsync      ( vsync      ),
        .display_on ( display_on ),
        .hpos       ( pixel_x    ),
        .vpos       ( pixel_y    )
    );

    //------------------------------------------------------------------------

    color_square 
    # (
       .HPOS_WIDTH  ( X_WIDTH    ),
       .VPOS_WIDTH  ( Y_WIDTH    )
    )
    i_color_square
    (
        .clk        (   clk        ),
        .reset      (   reset      ),
        .display_on (   display_on ),
        .key_sw     ( ~ key        ),
        .hpos       (   pixel_x    ),
        .vpos       (   pixel_y    ),
        .rgb        (   rgb        )
    );

endmodule
module top
(
    input             clk,
    input      [ 3:0] key,
    input      [ 3:0] sw,
    output     [ 7:0] led,

    output reg [ 7:0] abcdefgh,
    output     [ 7:0] digit,

    inout      [15:0] gpio
);
    wire   reset  = ~ key [3];

    wire  [2:0] octave = ~ key [2:0];
    wire  [3:0] note   = sw [3:0];

    assign led  = { 5'b11111, ~ octave };

    wire mclk;
    wire bclk;
    wire lrclk;
    wire sdata;

    assign gpio [1]     = lrclk;
    assign gpio [3]     = sdata;
    assign gpio [5]     = mclk;
    assign gpio [7]     = bclk;

    i2s i2s
    (
        .clk    ( clk       ),
        .reset  ( reset     ),
        .octave ( octave    ),
        .note   ( note      ),
        .mclk   ( mclk      ),
        .bclk   ( bclk      ),
        .lrclk  ( lrclk     ),
        .sdata  ( sdata     )
    );

    assign digit = 8'b1111_1110;

    always @ (posedge clk or posedge reset)
        if (reset)
            abcdefgh <= 8'b11111111;
        else
            case (note)
            4'd0:    abcdefgh <= 8'b01100011;  // C   // abcdefgh
            4'd1:    abcdefgh <= 8'b01100010;  // C#
            4'd2:    abcdefgh <= 8'b10000101;  // D   //   --a--
            4'd3:    abcdefgh <= 8'b10000100;  // D#  //  |     |
            4'd4:    abcdefgh <= 8'b01100001;  // E   //  f     b
            4'd5:    abcdefgh <= 8'b01110001;  // F   //  |     |
            4'd6:    abcdefgh <= 8'b01110000;  // F#  //   --g--
            4'd7:    abcdefgh <= 8'b01000011;  // G   //  |     |
            4'd8:    abcdefgh <= 8'b01000010;  // G#  //  e     c
            4'd9:    abcdefgh <= 8'b00010001;  // A   //  |     |
            4'd10:   abcdefgh <= 8'b00010000;  // A#  //   --d--  h
            4'd11:   abcdefgh <= 8'b11000001;  // B
            default: abcdefgh <= 8'b11111111;
            endcase

endmodule
module testbench;

    reg       clk;
    reg [1:0] key;
    reg [9:0] sw;

    top
    # (
        .clk_mhz (1),
        .strobe_to_update_xy_counter_width (1)
    )
    i_top
    (
        .clk ( clk ),
        .key ( key ),
        .sw  ( sw  )
    );

    initial
    begin
        clk = 1'b0;

        forever
            # 10 clk = ! clk;
    end

    reg reset;
    
    always @*
        sw [9] = reset;

    initial
    begin
        reset <= 'bx;
        repeat (2) @ (posedge clk);
        reset <= 1;
        repeat (2) @ (posedge clk);
        reset <= 0;
    end

    initial
    begin
        #0
        $dumpvars;

        key       <= 'b0;
        sw  [8:0] <= 'b0;

        @ (negedge reset);

        repeat (1000)
        begin
            @ (posedge clk);

            key       <= $random;
            sw  [8:0] <= $random;
        end

        `ifdef MODEL_TECH  // Mentor ModelSim and Questa
            $stop;
        `else
            $finish;
        `endif
    end

endmodule
module top
# (
    parameter clk_mhz = 50,
              strobe_to_update_xy_counter_width = 20
)
(
    input           adc_clk_10,
    input           max10_clk1_50,
    input           max10_clk2_50,

    input   [ 1:0]  key,
    input   [ 9:0]  sw,
    output  [ 9:0]  led,

    output  [ 7:0]  hex0,
    output  [ 7:0]  hex1,
    output  [ 7:0]  hex2,
    output  [ 7:0]  hex3,
    output  [ 7:0]  hex4,
    output  [ 7:0]  hex5,

    output          vga_hs,
    output          vga_vs,
    output  [ 3:0]  vga_r,
    output  [ 3:0]  vga_g,
    output  [ 3:0]  vga_b,

    inout   [35:0]  gpio
);

    assign led  = 10'b0;

    assign hex0 = 8'hff;
    assign hex1 = 8'hff;
    assign hex2 = 8'hff;
    assign hex3 = 8'hff;
    assign hex4 = 8'hff;
    assign hex5 = 8'hff;

    wire clk   = max10_clk1_50;
    wire reset = sw [9];

    wire [2:0] rgb;

    assign vga_r = { 4 { rgb [2] } };
    assign vga_g = { 4 { rgb [1] } };
    assign vga_b = { 4 { rgb [0] } };

    wire left_key   = ~ key [1];
    wire right_key  = ~ key [0];
    wire launch_key = left_key | right_key;

    game_top
    # (
        .clk_mhz (clk_mhz),

        .strobe_to_update_xy_counter_width
        (strobe_to_update_xy_counter_width)
    )
    i_game_top
    (
        .clk              (   clk                   ),
        .reset            (   reset                 ),

        .launch_key       (   launch_key            ),
        .left_right_keys  ( { left_key, right_key } ),

        .hsync            (   vga_hs                ),
        .vsync            (   vga_vs                ),
        .rgb              (   rgb                   )
    );

endmodule
module top
# (
    parameter clk_mhz = 50
)
(
    input           adc_clk_10,
    input           max10_clk1_50,
    input           max10_clk2_50,

    input   [ 1:0]  key,
    input   [ 9:0]  sw,
    output  [ 9:0]  led,

    output  [ 7:0]  hex0,
    output  [ 7:0]  hex1,
    output  [ 7:0]  hex2,
    output  [ 7:0]  hex3,
    output  [ 7:0]  hex4,
    output  [ 7:0]  hex5,

    output          vga_hs,
    output          vga_vs,
    output  [ 3:0]  vga_r,
    output  [ 3:0]  vga_g,
    output  [ 3:0]  vga_b

);


    assign hex0       = 8'hff;
    assign hex1       = 8'hff;
    assign hex2       = 8'hff;
    assign hex3       = 8'hff;
    assign hex4       = 8'hff;
    assign hex5       = 8'hff;
    assign led [9:1]  = 9'b0;
    assign led [0]    = sw [0];

    wire       reset  = sw [0];

    wire       display_on;
    wire [9:0] hpos;
    wire [9:0] vpos;

    vga i_vga
    (
        .clk        ( max10_clk1_50 ),
        .reset      ( reset         ),
        .hsync      ( vga_hs        ),
        .vsync      ( vga_vs        ),
        .display_on ( display_on    ),
        .hpos       ( hpos          ),
        .vpos       ( vpos          )
    );

    wire [2:0] rgb_squares
        = hpos ==  0 || hpos == 639 || vpos ==  0 || vpos == 479 ? 3'b100 :
          hpos ==  5 || hpos == 634 || vpos ==  5 || vpos == 474 ? 3'b010 :
          hpos == 10 || hpos == 629 || vpos == 10 || vpos == 469 ? 3'b001 :
          hpos <  20 || hpos >  619 || vpos <  20 || vpos >= 459 ? 3'b000 :
          { 1'b0, vpos [4], hpos [3] ^ vpos [3] };
			 
    wire        lfsr_enable = ! hpos [9:8] & ! vpos [9:8];
    wire [15:0] lfsr_out;

//    select Fibonacci or Galois lfsr
//    uncomment one string and comment other

    lfsr_fibonacci #(16, 16'b1000000001011, 0) i_lfsr_fibonacci   
//    lfsr_galois #(16, 16'b1000000001011, 0) i_lfsr_galois
    (
        .clk    ( max10_clk1_50 ),
        .reset  ( reset         ),
        .enable ( lfsr_enable   ),
        .out    ( lfsr_out      )
    );

    wire star_on = & lfsr_out [15:9];
    wire [2:0] rgb = lfsr_enable ? (star_on ? lfsr_out [2:0] : 3'b0) : rgb_squares;

    assign vga_r = { 4 { rgb [2] } };
    assign vga_g = { 4 { rgb [1] } };
    assign vga_b = { 4 { rgb [0] } };

endmodule
module top
# (
    parameter X_WIDTH = 10,
              Y_WIDTH = 10,
              clk_mhz = 50
)
(
    input           adc_clk_10,
    input           max10_clk1_50,
    input           max10_clk2_50,

    input   [ 1:0]  key,
    input   [ 9:0]  sw,
    output  [ 9:0]  led,

    output  [ 7:0]  hex0,
    output  [ 7:0]  hex1,
    output  [ 7:0]  hex2,
    output  [ 7:0]  hex3,
    output  [ 7:0]  hex4,
    output  [ 7:0]  hex5,

    output          vga_hs,
    output          vga_vs,
    output  [ 3:0]  vga_r,
    output  [ 3:0]  vga_g,
    output  [ 3:0]  vga_b,

    inout   [35:0]  gpio
);

    assign led  = 10'b0;

    assign hex0 = 8'hff;
    assign hex1 = 8'hff;
    assign hex2 = 8'hff;
    assign hex3 = 8'hff;
    assign hex4 = 8'hff;
    assign hex5 = 8'hff;

    wire clk   = max10_clk1_50;
    wire reset = sw [9];

    wire [2:0] rgb;

    assign vga_r = { 4 { rgb [2] } };
    assign vga_g = { 4 { rgb [1] } };
    assign vga_b = { 4 { rgb [0] } };

    //------------------------------------------------------------------------

    wire                 display_on;
    wire [X_WIDTH - 1:0] pixel_x;
    wire [Y_WIDTH - 1:0] pixel_y;
 
    vga
    # (
        .HPOS_WIDTH ( X_WIDTH    ),
        .VPOS_WIDTH ( Y_WIDTH    ),
        
        .CLK_MHZ    ( clk_mhz    )
    )
    i_vga
    (
        .clk        ( clk        ), 
        .reset      ( reset      ),
        .hsync      ( vga_hs     ),
        .vsync      ( vga_vs     ),
        .display_on ( display_on ),
        .hpos       ( pixel_x    ),
        .vpos       ( pixel_y    )
    );

    //------------------------------------------------------------------------

    color_square 
    # (
       .HPOS_WIDTH  ( X_WIDTH    ),
       .VPOS_WIDTH  ( Y_WIDTH    )
    )

    color_square
    (
        .clk        ( clk                  ),
        .reset      ( reset                ),
        .display_on ( display_on           ),
        .key_sw     ( sw | { 2'b0, ~ key } ),
        .hpos       ( pixel_x              ),
        .vpos       ( pixel_y              ),
        .rgb        ( rgb                  )
    );

endmodule
module testbench;

    reg       clk;
    reg [1:0] key;
    reg [9:0] sw;

    top
    # (
        .clk_mhz (1)
    )
    i_top
    (
        .clk ( clk ),
        .key ( key ),
        .sw  ( sw  )
    );

    initial
    begin
        clk = 1'b0;

        forever
            # 10 clk = ! clk;
    end

    reg reset;
    
    always @*
        sw [9] = reset;

    initial
    begin
        reset <= 'bx;
        repeat (2) @ (posedge clk);
        reset <= 1;
        repeat (2) @ (posedge clk);
        reset <= 0;
    end

    initial
    begin
        #0
        $dumpvars;

        key       <= 'b0;
        sw  [8:0] <= 'b0;

        @ (negedge reset);

        repeat (1000)
        begin
            @ (posedge clk);

            key       <= $random;
            sw  [8:0] <= $random;
        end

        `ifdef MODEL_TECH  // Mentor ModelSim and Questa
            $stop;
        `else
            $finish;
        `endif
    end

endmodule
module top
# (
    parameter clk_mhz = 50
)
(
    input           adc_clk_10,
    input           max10_clk1_50,
    input           max10_clk2_50,

    input   [ 1:0]  key,
    input   [ 9:0]  sw,
    output  [ 9:0]  led,

    output  [ 7:0]  hex0,
    output  [ 7:0]  hex1,
    output  [ 7:0]  hex2,
    output  [ 7:0]  hex3,
    output  [ 7:0]  hex4,
    output  [ 7:0]  hex5,

    output          vga_hs,
    output          vga_vs,
    output  [ 3:0]  vga_r,
    output  [ 3:0]  vga_g,
    output  [ 3:0]  vga_b,

    inout   [35:0]  gpio
);

    assign vga_hs = 1'b0;
    assign vga_vs = 1'b0;
    assign vga_r  = 4'b0;
    assign vga_g  = 4'b0;
    assign vga_b  = 4'b0;

    //------------------------------------------------------------------------

    wire clk   = max10_clk1_50;
    wire reset = sw [9];

    //------------------------------------------------------------------------

    wire [15:0] value;

    pmod_als_spi_receiver i_light_sensor
    (
        .clock ( clk        ),
        .reset ( reset      ),
        .cs    ( gpio  [34] ),
        .sck   ( gpio  [28] ),
        .sdo   ( gpio  [30] ),
        .value ( value      )
    );

    assign gpio [26] = 1'b0;  // GND for Pmod ALS

    //------------------------------------------------------------------------

    assign led = value [15:6];

    //------------------------------------------------------------------------

    reg [15:0] prev_value;
    reg [23:0] counter;
    reg [23:0] distance;

    localparam [15:0] threshold = 16'h1000;

    always @ (posedge clk or posedge reset)
        if (reset)
        begin
            prev_value <= 16'h0;
            counter    <= 16'h0;
            distance   <= 16'h0;
        end
        else
        begin
            prev_value <= value;

            if (  value      > threshold
                & prev_value < threshold)
            begin
               distance <= counter;
               counter  <= 23'h0;
            end
            else
            begin
               counter <= counter + 23'h1;
            end
        end

    //------------------------------------------------------------------------

    wire [23:0] number_to_display = distance;

    seven_segment_digit i_digit_0 ( number_to_display [ 3: 0], hex0 [6:0]);
    seven_segment_digit i_digit_1 ( number_to_display [ 7: 4], hex1 [6:0]);
    seven_segment_digit i_digit_2 ( number_to_display [11: 8], hex2 [6:0]);
    seven_segment_digit i_digit_3 ( number_to_display [15:12], hex3 [6:0]);
    seven_segment_digit i_digit_4 ( number_to_display [19:16], hex4 [6:0]);
    seven_segment_digit i_digit_5 ( number_to_display [23:20], hex5 [6:0]);

    assign { hex0 [7], hex1 [7], hex2 [7], hex3 [7], hex4 [7], hex5 [7] } = 6'b0;

endmodule
module testbench;

    reg       clk;
    reg [3:0] key;
    reg [7:0] sw;

    top
    # (
        .clk_mhz (1),
        .strobe_to_update_xy_counter_width (1)
    )
    i_top
    (
        .clk ( clk ),
        .key ( key ),
        .sw  ( sw  )
    );

    initial
    begin
        clk = 1'b0;

        forever
            # 10 clk = ! clk;
    end

    reg reset;
    
    always @*
        key [3] = ~ reset;

    initial
    begin
        reset <= 'bx;
        repeat (2) @ (posedge clk);
        reset <= 1;
        repeat (2) @ (posedge clk);
        reset <= 0;
    end

    initial
    begin
        #0
        $dumpvars;

        key [2:0] <= 'b0;
        sw        <= 'b0;

        @ (negedge reset);

        repeat (1000)
        begin
            @ (posedge clk);

            key [2:0] <= $random;
            sw        <= $random;
        end

        `ifdef MODEL_TECH  // Mentor ModelSim and Questa
            $stop;
        `else
            $finish;
        `endif
    end

endmodule
module top
# (
    parameter clk_mhz = 50,
              strobe_to_update_xy_counter_width = 20
)
(
    input         clk,
    input  [ 3:0] key,
    input  [ 7:0] sw,
    output [11:0] led,

    output [ 7:0] abcdefgh,
    output [ 7:0] digit,

    output        vsync,
    output        hsync,
    output [ 2:0] rgb,

    inout  [18:0] gpio
);

    wire reset = ~ key [3];

    assign led       = { key, sw };
    assign abcdefgh  = sw;
    assign digit     = 8'b1;

    wire launch_key = ~ key [1] | ~ key [0];
    wire left_key   = ~ key [1];
    wire right_key  = ~ key [0];

    game_top
    # (
        .clk_mhz (clk_mhz),

        .strobe_to_update_xy_counter_width
        (strobe_to_update_xy_counter_width)
    )
    i_game_top
    (
        .clk              (   clk                   ),
        .reset            (   reset                 ),

        .launch_key       (   launch_key            ),
        .left_right_keys  ( { left_key, right_key } ),

        .hsync            (   hsync                 ),
        .vsync            (   vsync                 ),
        .rgb              (   rgb                   )
    );

endmodule
module top
# (
    parameter clk_mhz = 50
)
(
    input         clk,
    input  [ 3:0] key,
    input  [ 7:0] sw,
    output [11:0] led,

    output [ 7:0] abcdefgh,
    output [ 7:0] digit,

    output        vsync,
    output        hsync,
    output [ 2:0] rgb,

    inout  [18:0] gpio
);

    wire reset = ~ key [3];

    assign led       = { key, sw };
    assign abcdefgh  = 8'b1;
    assign digit     = 8'b1;

    wire       display_on;
    wire [9:0] hpos;
    wire [9:0] vpos;

    vga i_vga
    (
        .clk        ( clk           ),
        .reset      ( reset         ),
        .hsync      ( hsync         ),
        .vsync      ( vsync         ),
        .display_on ( display_on    ),
        .hpos       ( hpos          ),
        .vpos       ( vpos          )
    );

    wire [2:0] rgb_squares
        = hpos ==  0 || hpos == 639 || vpos ==  0 || vpos == 479 ? 3'b100 :
          hpos ==  5 || hpos == 634 || vpos ==  5 || vpos == 474 ? 3'b010 :
          hpos == 10 || hpos == 629 || vpos == 10 || vpos == 469 ? 3'b001 :
          hpos <  20 || hpos >  619 || vpos <  20 || vpos >= 459 ? 3'b000 :
          { 1'b0, vpos [4], hpos [3] ^ vpos [3] };
			 
    wire        lfsr_enable = ! hpos [9:8] & ! vpos [9:8];
    wire [15:0] lfsr_out;

//    select Fibonacci or Galois lfsr
//    uncomment one string and comment other

    lfsr_fibonacci #(16, 16'b1000000001011, 0) i_lfsr_fibonacci   
//    lfsr_galois #(16, 16'b1000000001011, 0) i_lfsr_galois
    (
        .clk    ( clk           ),
        .reset  ( reset         ),
        .enable ( lfsr_enable   ),
        .out    ( lfsr_out      )
    );

    wire star_on = & lfsr_out [15:9];
    assign rgb = lfsr_enable ? (star_on ? lfsr_out [2:0] : 3'b0) : rgb_squares;

endmodule
module top
# (
    parameter X_WIDTH = 10,
              Y_WIDTH = 10,
              clk_mhz = 50
)
(
    input         clk,
    input  [ 3:0] key,
    input  [ 7:0] sw,
    output [11:0] led,

    output [ 7:0] abcdefgh,
    output [ 7:0] digit,

    output        vsync,
    output        hsync,
    output [ 2:0] rgb,

    inout  [18:0] gpio
);

    wire   reset    = ~ key [3];

    assign led      = { key, sw };    
    assign abcdefgh = 8'b1;
    assign digit    = 8'b1;

    //------------------------------------------------------------------------

    wire                 display_on;
    wire [X_WIDTH - 1:0] pixel_x;
    wire [Y_WIDTH - 1:0] pixel_y;
	
    vga
    # (
        .HPOS_WIDTH ( X_WIDTH    ),
        .VPOS_WIDTH ( Y_WIDTH    ),
        
        .CLK_MHZ    ( clk_mhz    )
    )
    i_vga
    (
        .clk        ( clk        ), 
        .reset      ( reset      ),
        .hsync      ( hsync      ),
        .vsync      ( vsync      ),
        .display_on ( display_on ),
        .hpos       ( pixel_x    ),
        .vpos       ( pixel_y    )
    );

    //------------------------------------------------------------------------

    wire [3:0] key_sw = ~ key;

    color_square 
    # (
       .HPOS_WIDTH  ( X_WIDTH    ),
       .VPOS_WIDTH  ( Y_WIDTH    )
    )
    i_color_square
    (
        .clk        ( clk        ),
        .reset      ( reset      ),
        .display_on ( display_on ),
        .key_sw     ( key_sw     ),
        .hpos       ( pixel_x    ),
        .vpos       ( pixel_y    ),
        .rgb        ( rgb        )
    );

endmodule
module  pll_altpll
	( 
	areset,
	clk,
	inclk) /* synthesis synthesis_clearbox=1 */;
	input   areset;
	output   [4:0]  clk;
	input   [1:0]  inclk;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_off
`endif
	tri0   areset;
	tri0   [1:0]  inclk;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_on
`endif

	wire  [4:0]   wire_pll1_clk;
	wire  wire_pll1_fbout;

	cycloneive_pll   pll1
	( 
	.activeclock(),
	.areset(areset),
	.clk(wire_pll1_clk),
	.clkbad(),
	.fbin(wire_pll1_fbout),
	.fbout(wire_pll1_fbout),
	.inclk(inclk),
	.locked(),
	.phasedone(),
	.scandataout(),
	.scandone(),
	.vcooverrange(),
	.vcounderrange()
	`ifndef FORMAL_VERIFICATION
	// synopsys translate_off
	`endif
	,
	.clkswitch(1'b0),
	.configupdate(1'b0),
	.pfdena(1'b1),
	.phasecounterselect({3{1'b0}}),
	.phasestep(1'b0),
	.phaseupdown(1'b0),
	.scanclk(1'b0),
	.scanclkena(1'b1),
	.scandata(1'b0)
	`ifndef FORMAL_VERIFICATION
	// synopsys translate_on
	`endif
	);
	defparam
		pll1.bandwidth_type = "auto",
		pll1.clk0_divide_by = 25,
		pll1.clk0_duty_cycle = 50,
		pll1.clk0_multiply_by = 51,
		pll1.clk0_phase_shift = "0",
		pll1.compensate_clock = "clk0",
		pll1.inclk0_input_frequency = 20000,
		pll1.operation_mode = "normal",
		pll1.pll_type = "auto",
		pll1.lpm_type = "cycloneive_pll";
	assign
		clk = {wire_pll1_clk[4:0]};
endmodule //pll_altpll
module pll (
	areset,
	inclk0,
	c0)/* synthesis synthesis_clearbox = 1 */;

	input	  areset;
	input	  inclk0;
	output	  c0;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_off
`endif
	tri0	  areset;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_on
`endif

	wire [0:0] sub_wire2 = 1'h0;
	wire [4:0] sub_wire3;
	wire  sub_wire0 = inclk0;
	wire [1:0] sub_wire1 = {sub_wire2, sub_wire0};
	wire [0:0] sub_wire4 = sub_wire3[0:0];
	wire  c0 = sub_wire4;

	pll_altpll	pll_altpll_component (
				.areset (areset),
				.inclk (sub_wire1),
				.clk (sub_wire3));

endmodule
module pll (
	areset,
	inclk0,
	c0);

	input	  areset;
	input	  inclk0;
	output	  c0;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_off
`endif
	tri0	  areset;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_on
`endif

endmodule
module vga
# (
    parameter N_MIXER_PIPE_STAGES = 0,

              HPOS_WIDTH=0,
              VPOS_WIDTH=0,

              // Horizontal constants

              H_DISPLAY=0,  // Horizontal display width
              H_FRONT=0,  // Horizontal right border (front porch)
              H_SYNC=0,  // Horizontal sync width
              H_BACK=0,  // Horizontal left border (back porch)

              // Vertical constants

              V_DISPLAY=0,  // Vertical display height
              V_BOTTOM=0,  // Vertical bottom border
              V_SYNC=0,  // Vertical sync # lines
              V_TOP=0  // Vertical top border
)
(
    input                         clk,
    input                         reset,
	 input								 enable,
    output reg                    hsync,
    output reg                    vsync,
    output reg                    display_on,
    output reg [HPOS_WIDTH - 1:0] hpos,
    output reg [VPOS_WIDTH - 1:0] vpos
);

    

    localparam H_SYNC_START  = H_DISPLAY    + H_FRONT + N_MIXER_PIPE_STAGES,
               H_SYNC_END    = H_SYNC_START + H_SYNC  - 1,
               H_MAX         = H_SYNC_END   + H_BACK,

               V_SYNC_START  = V_DISPLAY    + V_BOTTOM,
               V_SYNC_END    = V_SYNC_START + V_SYNC  - 1,
               V_MAX         = V_SYNC_END   + V_TOP;

    
    reg [HPOS_WIDTH - 1:0] d_hpos;
    reg [VPOS_WIDTH - 1:0] d_vpos;

    always @*
    begin
        if (hpos == H_MAX)
        begin
            d_hpos = 1'd0;

            if (vpos == V_MAX)
                d_vpos = 1'd0;
            else
                d_vpos = vpos + 1'd1;
        end
        else
        begin
          d_hpos = hpos + 1'd1;
          d_vpos = vpos;
        end
    end

	 //!!!I replaced the clock divider with pll.
	 
   

    always @ (posedge clk or posedge reset)
    begin
        if (reset)
        begin
            hsync       <= 1'b0;
            vsync       <= 1'b0;
            display_on  <= 1'b0;
            hpos        <= 1'b0;
            vpos        <= 1'b0;
        end
        else if (enable)
        begin
            hsync       <= ~ (    d_hpos >= H_SYNC_START
                               && d_hpos <= H_SYNC_END   );

            vsync       <= ~ (    d_vpos >= V_SYNC_START
                               && d_vpos <= V_SYNC_END   );

            display_on  <=   (    d_hpos <  H_DISPLAY
                               && d_vpos <  V_DISPLAY    );

            hpos        <= d_hpos;
            vpos        <= d_vpos;
        end
    end
	 
	 

endmodule
module memsyncreset
#( parameter ADDR_WIDTH=0,
				 RAMLENGTH=0
)
(
	input clk, memreset,
	output [ADDR_WIDTH:0] resetcnt,
	output reg memenable
); 

reg [1:0]               stp;
//counter for syncronyous memreset
reg [ADDR_WIDTH:0]  counter;//='d800;


    always @(posedge clk) begin
        
        case( stp )

        0: begin
            memenable <= 0;
            counter <= '0;
            stp <= 1;
        end

        1: begin
            counter <= counter + 1;
            if( counter == RAMLENGTH )
                stp <= 2;
        end

        2: begin
          
            memenable <= 1;
        end

        endcase

        if( memreset )
            stp <= 0;

    end
	 
	 assign resetcnt=counter;

endmodule
module mem_coder_decoder 
#(
	parameter 	 RES_MULTIPLIER=8,
				 BANKS_NUMBER=10,
				 RESOLUTION_H=80,
				 RESOLUTION_V=60,
				 DATA_WIDTH = 6,
				 RAM_INITIAL_VALUE=6'b111111
)
(input clk,
 input reset,
 input [9:0] hpos ,
 input [9:0] vpos ,
 input [9:0] paintpos_h ,
 input [9:0] paintpos_v ,
 input [DATA_WIDTH-1:0] datafrommem,
 input rin,
 input we,
		 
 output rout,
 output [DATA_WIDTH-1:0] datatomem,
 output [10:0] addr
);

reg [3:0] bankselect=0;
reg [6:0] regselect=0; 
reg [2:0] dataselect_r=0;
reg [2:0] dataselect_w=0;
reg [5:0] databuf=RAM_INITIAL_VALUE;
reg webuf;
reg [7:0]bankchange=0;

//Read from memory
always@ (posedge clk) begin
if(reset) begin 
databuf=RAM_INITIAL_VALUE;
bankselect=0;
regselect=0;
dataselect_r=0;
dataselect_w=0;
webuf=0;
bankchange=0;
end
else begin
	if(~we) begin
		bankselect<=vpos/(DATA_WIDTH*RES_MULTIPLIER);

		regselect<=hpos/RES_MULTIPLIER;

		if (vpos!=0) dataselect_r <=vpos%DATA_WIDTH;
		else dataselect_r <=0;
		
		end
	else if(we) begin
		webuf<=we;
		//Write to memory
		bankselect<=paintpos_v/(DATA_WIDTH*RES_MULTIPLIER);

		regselect<=paintpos_h/RES_MULTIPLIER;
		
		if (paintpos_v!=0) dataselect_w <=(paintpos_v/RES_MULTIPLIER)%DATA_WIDTH;
		else dataselect_w <=3'd6;
		
		
		bankchange <= bankselect;
		
		if(bankchange!=bankselect)databuf<=RAM_INITIAL_VALUE;
		else begin
			if(webuf) begin
				case (dataselect_w) 
					0:databuf[0]<= rin;
					3'd1:databuf [1]<= rin;
					3'd2:databuf [2]<= rin;
					3'd3:databuf [3]<= rin;
					3'd4:databuf [4]<= rin;
					3'd5: databuf [5]<= rin;
					default databuf<= RAM_INITIAL_VALUE;
				endcase
			end
			else databuf<= RAM_INITIAL_VALUE;
		end

	end
end
end




//addr to memory
assign addr = {bankchange,regselect};

//Read from memory
//data from memory, then rout to vga
assign rout = datafrommem[dataselect_r];

//Write to memory
//rin from brush, then data to memory
assign datatomem = databuf;

endmodule
module brush
# (
    parameter HPOS_WIDTH=0,
              VPOS_WIDTH=0,
				  INITIAL_VALUE=0,
				  SQUARE_CURSOR=0,
				  CIRCLE_CURSOR=1,
				  CURSOR_SIZE=4,
              // Display constants
              H_DISPLAY=0,  // Horizontal display width
              V_DISPLAY=0,   // Vertical display height
				  //cursor sprites rows		cursorsprite looks like:
				 PIX0='b1,//		
				 PIX1='b1,//		|PIX0	|PIX1	|PIX2	|PIX3	|
				 PIX2='b1,//			
				 PIX3='b1,//		
				 PIX4='b1,//		|PIX4	|PIX5	|PIX6	|PIX7	|
				 PIX5='b1,//		
				 PIX6='b1,//		
				 PIX7='b1,//		|PIX8	|PIX9	|PIX10|PIX11|
				 PIX8='b1,//		
				 PIX9='b1,//	
				 PIX10='b1,//	|PIX12|PIX13|PIX14|PIX15|
				 PIX11='b1,//
				 PIX12='b1,//
				 PIX13='b1,//
				 PIX14='b1,//
				 PIX15='b1//
)

(	
	input clk,reset,enable,key_sw,display_on, empty, full,
	input [HPOS_WIDTH - 1:0] cursor_xpos,
   input [VPOS_WIDTH - 1:0] cursor_ypos,
	
	output webuf,
	output reg push,pop,
	output [HPOS_WIDTH+VPOS_WIDTH+2:0] tofifo // fifo data structure:{[XPOS][YPOS][RGB]}
);

localparam PAINTCNT_WIDTH = $clog2 (CURSOR_SIZE*CURSOR_SIZE);

wire [HPOS_WIDTH - 1:0] pixel_xpos;
wire [VPOS_WIDTH - 1:0] pixel_ypos;
reg [2:0]rgbdata;

reg cursorpaint [CURSOR_SIZE*CURSOR_SIZE-1:0];
reg [PAINTCNT_WIDTH-1:0] paintcnt=0;

	other_computer
	#(
	  .CURSOR_SIZE(CURSOR_SIZE),
	  .HPOS_WIDTH(HPOS_WIDTH),
     .VPOS_WIDTH(VPOS_WIDTH)
	  )
	computer
	(
	  .clk(clk),
	  .reset(reset),
	   .we(key_sw), //write enable is driven by key_sw[3]
		.enable(enable),
	  .cursor_xpos(cursor_xpos),
	  .cursor_ypos(cursor_ypos),
	  .pixel_xpos(pixel_xpos),
	  .pixel_ypos(pixel_ypos)
	);
	
	always@(posedge clk) begin
	if (reset) begin
	cursorpaint[0]<=PIX0;
	cursorpaint[1]<=PIX1;
	cursorpaint[2]<=PIX2;
	cursorpaint[3]<=PIX3;
	cursorpaint[4]<=PIX4;
	cursorpaint[5]<=PIX5;
	cursorpaint[6]<=PIX6;
	cursorpaint[7]<=PIX7;
	cursorpaint[8]<=PIX8;
	cursorpaint[9]<=PIX9;
	cursorpaint[10]<=PIX10;
	cursorpaint[11]<=PIX11;
	cursorpaint[12]<=PIX12;
	cursorpaint[13]<=PIX13;
	cursorpaint[14]<=PIX14;
	cursorpaint[15]<=PIX15;
	end else if (enable&&key_sw) begin
	rgbdata<=cursorpaint[paintcnt];
	paintcnt<=paintcnt+1;
	end
		
	end
	
	assign tofifo={pixel_xpos,pixel_ypos,rgbdata};
	
	
	
	always@(posedge clk) begin
	
	push <= (display_on&&key_sw&&~full);
	pop <= (~display_on&&~empty);
	
//	push<= (display_on && ~full) ? 1 : 0;
//	pop<= (~display_on && ~empty) ? 1 : 0;
	
	end

	assign webuf = push;
	
endmodule
module vgasprites
#(parameter CURSOR_SIZE=4,
					H_DISPLAY=0,  // Horizontal display width
              V_DISPLAY=0,   // Vertical display height
				  HPOS_WIDTH=0,
				  VPOS_WIDTH=0
)
( 
	input clk, reset, enable, display_on,
	input [HPOS_WIDTH - 1:0] hpos,
   input [VPOS_WIDTH - 1:0] vpos,
	input [2:0] key_sw,
	input rfromFB,
	output reg [2:0] rgbout,
	output [HPOS_WIDTH-1:0]cursor_xpos,
	output [VPOS_WIDTH-1:0]cursor_ypos
);
reg cursorenable;
reg [1:0] gb_canvas=2'b11;
wire [HPOS_WIDTH-1:0]cursor_x; // current x coordinate of cursor
wire [VPOS_WIDTH-1:0]cursor_y; // current y coordinate of cursor
wire [2:0] cursor_rgb;
wire [2:0] cursordirection;		 


	cursor
	#(
	.HPOS_WIDTH(HPOS_WIDTH),
	.VPOS_WIDTH(VPOS_WIDTH)
	)	
	cursor
	(
	.clk(clk),
	.reset(reset),
	.movedirection(cursordirection),
	.init_xpos(H_DISPLAY/2), //cursor x position after startup or reset
	.init_ypos(V_DISPLAY/2), //cursor y position after startup or reset
	.cursor_xpos(cursor_x),
   .cursor_ypos(cursor_y),
	.cursor_rgb(cursor_rgb),
	.enable(enable),
	.cursorenable(cursorenable)
	);

always @ (posedge clk or posedge reset)
   if (reset) begin
            rgbout <= 3'b000;
//				paintpos_h<=0;
//				paintpos_v<=0;
//				rwrite<=INITIAL_VALUE;
	end else if (display_on) begin
//		if((hpos<H_DISPLAY)&&(vpos<V_DISPLAY))begin 
			if ((hpos >= cursor_x-CURSOR_SIZE/2)&&(hpos <= cursor_x+CURSOR_SIZE/2)&&(vpos >= cursor_y-CURSOR_SIZE/2)&&(vpos <= cursor_y+CURSOR_SIZE/2)) begin 
			cursorenable<=1;
			rgbout<=cursor_rgb;
			end
			else begin 
			cursorenable<=0;
			rgbout[2]<=rfromFB;
			rgbout[1:0]<=gb_canvas;
			end
					//When VGA scans the position of cursor, its color is completely constant,
					//without requesting memory
//			else begin
//			rgbout[2:2]<=rfrommem;
//			rgbout[1:0]<=gb_canvas;
//			end
//		end
	end else rgbout <= 3'b000;

assign cursor_xpos=cursor_x;
assign cursor_ypos=cursor_y;
assign cursordirection=key_sw[2:0]; // cursor movement control
			
endmodule
module other_computer
#(
	parameter HPOS_WIDTH=0,
				 VPOS_WIDTH=0,
				 CURSOR_SIZE=4
	
)
(
	input clk,reset,enable,we,
	input [HPOS_WIDTH - 1:0] cursor_xpos,
   input [VPOS_WIDTH - 1:0] cursor_ypos,
	output reg [HPOS_WIDTH - 1:0] pixel_xpos,
	output reg [VPOS_WIDTH - 1:0] pixel_ypos
);
	localparam CNT_SIZE=$clog2 (CURSOR_SIZE);

	reg [HPOS_WIDTH - 1:0] paint_x [CURSOR_SIZE:0] ; // all points, including central one
	reg [VPOS_WIDTH - 1:0] paint_y [CURSOR_SIZE:0] ;
	reg [CNT_SIZE:0] counterout=0;
	
	//x computing
	always@(posedge clk) begin
	if (reset) begin 
	paint_x[0]<=0;
	paint_x[1]<=0;
	paint_x[2]<=0;
	paint_x[3]<=0;
	paint_x[4]<=0;
	end else if(enable) begin
	paint_x[0]<=cursor_xpos-CURSOR_SIZE/2;
	paint_x[1]<=cursor_xpos-CURSOR_SIZE/2+1;
	paint_x[2]<=cursor_xpos-CURSOR_SIZE/2+2;
	paint_x[3]<=cursor_xpos-CURSOR_SIZE/2+3;
	paint_x[4]<=cursor_xpos-CURSOR_SIZE/2+4;
	end
	end
	
	//y computing
	always@(posedge clk) begin
	if (reset) begin 
	paint_y[0]<=0;
	paint_y[1]<=0;
	paint_y[2]<=0;
	paint_y[3]<=0;
	paint_y[4]<=0;
	end else if(enable) begin
	paint_y[0]<=cursor_ypos-CURSOR_SIZE/2;
	paint_y[1]<=cursor_ypos-CURSOR_SIZE/2+1;
	paint_y[2]<=cursor_ypos-CURSOR_SIZE/2+2;
	paint_y[3]<=cursor_ypos-CURSOR_SIZE/2+3;
	paint_y[4]<=cursor_ypos-CURSOR_SIZE/2+4;
	end
	end
	
	//serial output
	always@(posedge clk) begin
	if (reset) begin 
	pixel_xpos<=0;
	pixel_ypos<=0;
	counterout<=0;
	end else if(enable&&we) begin
	counterout<=counterout+1;
	pixel_xpos<=paint_x[counterout];
	pixel_ypos<=paint_y[counterout];
	end
	end
	
endmodule
module cursor
# (
	parameter SLOWNESS = 18,//number of position of counter clock divider
	//cursor moving speed is  CLK/2^SLOWNESS
//			    COLOR = 3, //color of cursor_rgb
				 HPOS_WIDTH=0, //coordinate wires width
				 VPOS_WIDTH=0,
				 CURSOR_SIZE=4,
	//cursor sprites rows		cursorsprite looks like:
				 PIX0='b111,//		
				 PIX1='b111,//		|PIX0	|PIX1	|PIX2	|PIX3	|
				 PIX2='b111,//			
				 PIX3='b111,//		
				 PIX4='b111,//		|PIX4	|PIX5	|PIX6	|PIX7	|
				 PIX5='b111,//		
				 PIX6='b111,//		
				 PIX7='b111,//		|PIX8	|PIX9	|PIX10|PIX11|
				 PIX8='b111,//		
				 PIX9='b111,//	
				 PIX10='b111,//	|PIX12|PIX13|PIX14|PIX15|
				 PIX11='b111,//
				 PIX12='b111,//
				 PIX13='b111,//
				 PIX14='b111,//
				 PIX15='b111//

)
(
	input clk,
	input reset,
	input [2:0] movedirection, // [2:0]movedirection=[2:0]key_sw
	input [HPOS_WIDTH - 1:0] init_xpos,
	input [VPOS_WIDTH - 1:0] init_ypos,
	input enable,cursorenable,
	output reg [HPOS_WIDTH - 1:0] cursor_xpos,
   output reg [VPOS_WIDTH - 1:0] cursor_ypos,
	output reg [2:0] cursor_rgb
);

reg [1:0] sw_cntclk=0;

localparam SPRITECNT_WIDTH = $clog2 (CURSOR_SIZE*CURSOR_SIZE);

reg [31:0] counterclk=0; //clkdiv counter

reg [2:0] cursorsprite [CURSOR_SIZE*CURSOR_SIZE-1:0];

reg [SPRITECNT_WIDTH-1:0] spritecounter=0;

//reg [2:0] resetstage;
//reg [RESETCNT_WIDTH-1:0] resetcnt = 0;

always@(posedge clk)
if(reset) begin
counterclk<=0;
end
else 
begin
counterclk<=counterclk+1;
sw_cntclk<={sw_cntclk[0],counterclk[SLOWNESS]};
//case (COLOR)	//color of cursor_rgb
// 1: cursor_rgb<=3'b001;
// 2: cursor_rgb<=3'b010;
// 3: cursor_rgb<=3'b100;
//endcase 
end

wire cntclkenable = (sw_cntclk[0]&&~sw_cntclk[1]) ? 1 : 0;
//cursor movement

always@(posedge clk or posedge reset)
if(reset) begin
	cursor_xpos<=init_xpos;
	cursor_ypos<=init_ypos;
end else if(enable && cntclkenable) begin
	if (movedirection[2]) begin //key_sw[2] is responsible for forward/backward mode of cursor movement
		if(movedirection[0]) cursor_xpos<=cursor_xpos+'b1; // key_sw[0] drives x-coordinate move
		if(movedirection[1]) cursor_ypos<=cursor_ypos+'b1; // key_sw[1] drives y-coordinate move
		end
	else if (~movedirection[2]) begin
		if(movedirection[0]) cursor_xpos<=cursor_xpos-'b1;
		if(movedirection[1]) cursor_ypos<=cursor_ypos-'b1;
	end
end

//cursorsprite

always@(posedge clk) begin
	if (reset) begin
	cursorsprite[0]<=PIX0;
	cursorsprite[1]<=PIX1;
	cursorsprite[2]<=PIX2;
	cursorsprite[3]<=PIX3;
	cursorsprite[4]<=PIX4;
	cursorsprite[5]<=PIX5;
	cursorsprite[6]<=PIX6;
	cursorsprite[7]<=PIX7;
	cursorsprite[8]<=PIX8;
	cursorsprite[9]<=PIX9;
	cursorsprite[10]<=PIX10;
	cursorsprite[11]<=PIX11;
	cursorsprite[12]<=PIX12;
	cursorsprite[13]<=PIX13;
	cursorsprite[14]<=PIX14;
	cursorsprite[15]<=PIX15;
	cursor_rgb<=0;
	end else if (cursorenable) begin
	cursor_rgb<=cursorsprite[spritecounter];
	spritecounter<=spritecounter+1;
	end
		
end

endmodule
module RGBMemory_top
#(
	parameter  RAMLENGTH=800, //RAMLENGTH*DATAWIDTH = 4800 = 80x60 RAM RESOLUTION
				  DATA_WIDTH=6,
				  V_BOTTOM = 1,
              V_SYNC   = 3,
              V_TOP    = 30,
				  H_FRONT  =  80,
              H_SYNC   =  136,
              H_BACK   =  216,
				  RESOLUTION_H = 1280,
				  RESOLUTION_V = 960,
				  X_WIRE_WIDTH = $clog2 (RESOLUTION_H+H_FRONT+H_SYNC+H_BACK),
				  Y_WIRE_WIDTH = $clog2 (RESOLUTION_V+V_BOTTOM+V_SYNC+V_TOP),
				  ADDR_WIDTH	= $clog2 (RAMLENGTH)
)
(
//input we,
input display_on,clk, memreset, reset_n,
input [ADDR_WIDTH-1:0] resetcnt,
input [2:0]RGBin,
input [X_WIRE_WIDTH-1:0] hpos ,
input [Y_WIRE_WIDTH-1:0] vpos ,
input fifoempty,

output [2:0] RGB
);

wire [DATA_WIDTH-1:0] writeR_data, writeG_data, writeB_data, R_data, G_data, B_data;
wire [ADDR_WIDTH-1:0] addrbuf_wire;
wire we;
				  
RGBmemcoderdecoderv2  // module for interpreting requests to memory
#(
.RESOLUTION_H(RESOLUTION_H),
.DATA_WIDTH(DATA_WIDTH),
.X_WIDTH(X_WIRE_WIDTH),
.Y_WIDTH(Y_WIRE_WIDTH),
.ADDR_WIDTH(ADDR_WIDTH)
)
FBCODEC
(
.clk (clk),
.reset(reset_n),
.hpos (hpos),
.vpos (vpos),
.datafromR(R_data),
.datafromG(G_data),
.datafromB(B_data),
.RGBin(RGBin),
.display_on(display_on),
.we(we),
.RGB(RGB),
.Rdatatomem(writeR_data),
.Gdatatomem(writeG_data),
.Bdatatomem(writeB_data),
.addr(addrbuf_wire),
.memenable(memreset),
.fifoempty(fifoempty)
);


single_port_ram 
#(
.RAMLENGTH(RAMLENGTH),
.DATA_WIDTH(DATA_WIDTH),
.ADDR_WIDTH(ADDR_WIDTH)
)
R_MEMORY
(
.we(we), .clk(clk),
.memenable(memreset),
.data(writeR_data),
.addr(addrbuf_wire),
.resetcnt(resetcnt),
.q(R_data)
);



single_port_ram 
#(
.RAMLENGTH(RAMLENGTH),
.DATA_WIDTH(DATA_WIDTH),
.ADDR_WIDTH(ADDR_WIDTH)
)
G_MEMORY
(
.we(we), .clk(clk),
.memenable(memreset),
.data(writeG_data),
.addr(addrbuf_wire),
.resetcnt(resetcnt),
.q(G_data)
);



single_port_ram 
#(
.RAMLENGTH(RAMLENGTH),
.DATA_WIDTH(DATA_WIDTH),
.ADDR_WIDTH(ADDR_WIDTH)
)
B_MEMORY
(
.we(we), .clk(clk),
.memenable(memreset),
.data(writeB_data),
.addr(addrbuf_wire),
.resetcnt(resetcnt),
.q(B_data)
);

endmodule
module single_port_ram
#( parameter  RAMLENGTH=800, //RAMLENGTH*DATAWIDTH = 4800 = 80x60 RAM RESOLUTION
				  DATA_WIDTH=6,
				  ADDR_WIDTH=10
 )
(
	input [DATA_WIDTH-1:0]data,		//RAM words' write input			
	input [ADDR_WIDTH-1:0] addr,				 //ln(RAMLENGTH)/ln(2)
	input we, clk, memenable,
	input [ADDR_WIDTH-1:0] resetcnt,
	output reg [DATA_WIDTH-1:0]q	//RAM words' read input
);

	(* ramstyle = "M9K" *) reg  [DATA_WIDTH-1:0]ramblock[RAMLENGTH-1:0] ;
	//(* ramstyle = "M9K" *) - synthesis attribute for making ramblocks of Altera M9K memory blocks
	// !!! Not sure in its usefullness
	
	// Variable to hold the registered read address, write data, and we
	//reg [ADDR_WIDTH-1:0] addr_reg;
	//reg [DATA_WIDTH-1:0] data_reg;
	//reg we_reg;

    wire [ADDR_WIDTH-1:0] addr_x;
    wire [DATA_WIDTH-1:0] data_x;
    wire                  we_x;

    assign addr_x = (memenable) ? addr : resetcnt;
    assign data_x = (memenable) ? data : '0;
    assign we_x   = (memenable) ? we   : 1;
	 
	always @ (posedge clk)begin
	//addr_reg <= addr_x;
	//we_reg<=we_x;
	//data_reg <= data_x;
	if (we_x) ramblock[addr_x]<=data_x;
	else q <= ramblock[addr_x];
	end
	
	// Continuous assignment implies read returns NEW data.
	// This is the natural behavior of the TriMatrix memory
	// blocks in Single Port mode.  
	//assign q = ramblock[addr_reg];
	
endmodule
module  pll_altpll
	( 
	areset,
	clk,
	inclk) /* synthesis synthesis_clearbox=1 */;
	input   areset;
	output   [4:0]  clk;
	input   [1:0]  inclk;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_off
`endif
	tri0   areset;
	tri0   [1:0]  inclk;
`ifndef ALTERA_RESERVED_QIS
// synopsys translate_on
`endif

	wire  [4:0]   wire_pll1_clk;
	wire  wire_pll1_fbout;

	cycloneive_pll   pll1
	( 
	.activeclock(),
	.areset(areset),
	.clk(wire_pll1_clk),
	.clkbad(),
	.fbin(wire_pll1_fbout),
	.fbout(wire_pll1_fbout),
	.inclk(inclk),
	.locked(),
	.phasedone(),
	.scandataout(),
	.scandone(),
	.vcooverrange(),
	.vcounderrange()
	`ifndef FORMAL_VERIFICATION
	// synopsys translate_off
	`endif
	,
	.clkswitch(1'b0),
	.configupdate(1'b0),
	.pfdena(1'b1),
	.phasecounterselect({3{1'b0}}),
	.phasestep(1'b0),
	.phaseupdown(1'b0),
	.scanclk(1'b0),
	.scanclkena(1'b1),
	.scandata(1'b0)
	`ifndef FORMAL_VERIFICATION
	// synopsys translate_on
	`endif
	);
	defparam
		pll1.bandwidth_type = "auto",
		pll1.clk0_divide_by = 2,
		pll1.clk0_duty_cycle = 50,
		pll1.clk0_multiply_by = 1,
		pll1.clk0_phase_shift = "0",
		pll1.compensate_clock = "clk0",
		pll1.inclk0_input_frequency = 20000,
		pll1.operation_mode = "normal",
		pll1.pll_type = "auto",
		pll1.lpm_type = "cycloneive_pll";
	assign
		clk = {wire_pll1_clk[4:0]};
endmodule //pll_altpll
module ROM_topTestBench();

reg clk,rst, display_on, fifofull;

ROM_top DUT(.clk(clk),.rst(~rst),.display_on(display_on),.fifofull(fifofull));

always #5 clk=~clk;

initial begin
clk=0;
rst=0;
display_on=1;
fifofull=0;
#10
rst=1;
display_on=1;
#10;
display_on=0;
end
endmodule
module ROM_top
#(
	parameter RAMLENGTH=800, //количество строк памяти ФреймБуфера
	RAM_DATAWIDTH=6, //ширина строки памяти ФБ
	RESOLUTION_H = 1280,
	RESOLUTION_V = 960,
	V_BOTTOM = 1, //vga-тайминги. Типа нематериальные дополнительные пиксели по вертикали и по горизонтали.
   V_SYNC   = 3, //берутся из интернета
   V_TOP    = 30,
	H_FRONT  =  80, 
   H_SYNC   =  136,
   H_BACK   =  216,
	X_WIRE_WIDTH = $clog2 (RESOLUTION_H+H_FRONT+H_SYNC+H_BACK), //логарифм по основанию 2 с округлением в большую сторону. 
	//Считает минимальное количество битов для двоичной кодировки координат без потерь.
	Y_WIRE_WIDTH = $clog2 (RESOLUTION_V+V_BOTTOM+V_SYNC+V_TOP),
	ROM_LENGTH = RAMLENGTH*RAM_DATAWIDTH, //4800. По умолчанию считается,что соотношение сторон экрана будет 4:3. 
	//Так что это обьем картинки разрешением 80*60.
	CNT_WIDTH = $clog2 (ROM_LENGTH)
)
(
  input clk,rst, fifofull, enable, display_on,
  output reg [X_WIRE_WIDTH-1:0]hpos,
  output reg [Y_WIRE_WIDTH-1:0]vpos,
  output reg [2:0]RGB,
  output reg ROMready
);
	reg [CNT_WIDTH-1:0] counter;

	reg [X_WIRE_WIDTH-1:0]hposROM[0:ROM_LENGTH-1]; //массив длинной 4800 и шириной X_WIRE_WIDTH-1. Хранит координату X.
	
	reg [Y_WIRE_WIDTH-1:0]vposROM[0:ROM_LENGTH-1]; //Хранит координату Y.
	
	reg [2:0]RGBROM[0:ROM_LENGTH-1]; //Хранит цвет пикселя, расположенного в точке (X,Y)
	
	initial begin
	$readmemh("hex_hposes.txt",hposROM); //копирование данных из файла hex_hposes.txt в память в виде шестнадцатеричных чисел. 
	//В процессе, компилятор сам переводит их в двоичные. Делается до синтеза.
	$readmemh("hex_vposes.txt", vposROM);
	//$readmemh("hex_RGB_ALLRed.txt", RGBROM);
	//$readmemh("hex_RGB_ALLGreen.txt", RGBROM);
	//$readmemh("hex_RGB_ALLBlue.txt", RGBROM);
	//$readmemh("hex_RGB_ALLWhite.txt", RGBROM);
	//$readmemh("hex_RGB_Checkmates.txt", RGBROM);
	//$readmemh("hex_RGB_TestPicture1.txt", RGBROM);
	//$readmemh("hex_RGB_TestPicture2.txt", RGBROM);
	//$readmemh("hex_RGB_TestPicture3.txt", RGBROM);
	$readmemh("hex_RGB_Working.txt", RGBROM);
	end
	
	
	always@(posedge clk)
	if(rst) begin counter<=0;
	ROMready<=0;
	end else if(enable&~fifofull&display_on) begin
	if(counter==ROM_LENGTH) ROMready<=0;
	else begin 
	counter<=counter+1;
	ROMready<=1;
	end
	end
	
	always@(posedge clk)
	if(rst) begin
	hpos<=0;
	vpos<=0;
	RGB<=0;
	end else if (enable&~fifofull&display_on) begin
	hpos<=hposROM[counter];
	vpos<=vposROM[counter];
	RGB<=RGBROM[counter];
	end
	
endmodule
module FIFO_top
#(
	parameter RESOLUTION_H = 1280,
				 RESOLUTION_V = 960,
				 V_BOTTOM = 1,
             V_SYNC   = 3,
             V_TOP    = 30,
				 H_FRONT  =  80,
             H_SYNC   =  136,
             H_BACK   =  216,
				 HPOS_WIDTH = $clog2 (RESOLUTION_H+H_FRONT+H_SYNC+H_BACK),
				 VPOS_WIDTH = $clog2 (RESOLUTION_V+V_BOTTOM+V_SYNC+V_TOP),
				 FIFODEPTH=30
)
(
  input                clk,
  input                rst,
  input                push,
  input                toppop,
  input  [HPOS_WIDTH-1:0] hpos_write,
  input  [VPOS_WIDTH-1:0] vpos_write,
  input  [2:0] RGB_write,
  output [HPOS_WIDTH-1:0] hpos_read,
  output [VPOS_WIDTH-1:0] vpos_read,
  output [2:0] RGB_read,
  output               empty,
  output               full
);
reg [2:0] counter = 0;
reg pop=0;
wire hposempty,vposempty,RGBempty,hposfull,vposfull,RGBfull;

flip_flop_fifo
#(
	.width(HPOS_WIDTH),
	.depth(FIFODEPTH)
)
HPOS_FIFO
(
	.clk			(clk),
	.rst			(rst),
	.push			(push),
	.pop			(pop),
	.write_data	(hpos_write),
	.read_data	(hpos_read),
	.empty		(hposempty),
	.full			(hposfull)
);

flip_flop_fifo
#(
	.width(VPOS_WIDTH),
	.depth(FIFODEPTH)
)
VPOS_FIFO
(
	.clk			(clk),
	.rst			(rst),
	.push			(push),
	.pop			(pop),
	.write_data	(vpos_write),
	.read_data	(vpos_read),
	.empty		(vposempty),
	.full			(vposfull)
);

flip_flop_fifo
#(
	.width(3),
	.depth(FIFODEPTH)
)
RGB_FIFO
(
	.clk			(clk),
	.rst			(rst),
	.push			(push),
	.pop			(pop),
	.write_data	(RGB_write),
	.read_data	(RGB_read),
	.empty		(RGBempty),
	.full			(RGBfull)
);

always@(posedge clk) begin
if(toppop) begin 
counter <= counter + 1;
if(counter == 1) pop <= 1;
else pop <= 0;
if(counter == 'd4) counter <= 0;
end
end
assign empty=hposempty&vposempty&RGBempty;
assign full=hposfull&vposfull&RGBfull;


endmodule
module button_debouncer
#( parameter DEBOUNCE_TIMER = 10
)
(
	input clk, reset,
	input [3:0] RAW_BTN,
	output [3:0] BTN,
	output [3:0] BTN_POSEDGE,
	output [3:0] BTN_NEGEDGE
);

reg [3:0] states_of_button_0, states_of_button_1, states_of_button_2,states_of_button_3;
reg [DEBOUNCE_TIMER:0] counter [3:0];
wire [3:0] state_changed;
//wire [1:0] key_states_0, key_states_1, key_states_2, key_states_3;

//fetching raw button state
always@(posedge clk) begin
states_of_button_0[1:0]<= {states_of_button_0[0],RAW_BTN[0]};
states_of_button_1[1:0]<= {states_of_button_1[0],RAW_BTN[1]};
states_of_button_2[1:0]<= {states_of_button_2[0],RAW_BTN[2]};
states_of_button_3[1:0]<= {states_of_button_3[0],RAW_BTN[3]};
end

//waiting bounce to finish
always@(posedge clk) begin
if(reset) begin
counter[0]<=0;
counter[1]<=0;
counter[2]<=0;
counter[3]<=0;
end else begin
if(!state_changed[0]) counter[0]<=counter[0]+1;
else if(state_changed[0]) counter[0]<=0;

if(!state_changed[1]) counter[1]<=counter[1]+1;
else if(state_changed[1]) counter[1]<=0;

if(!state_changed[2]) counter[2]<=counter[2]+1;
else if(state_changed[2]) counter[2]<=0;

if(!state_changed[3]) counter[3]<=counter[3]+1;
else if(state_changed[3]) counter[3]<=0;
end
end

//fetching debounced state
always@(posedge clk) begin
if(&counter[0]) states_of_button_0[2]<= states_of_button_0[1];
if(&counter[1]) states_of_button_1[2]<= states_of_button_1[1];
if(&counter[2]) states_of_button_2[2]<= states_of_button_2[1];
if(&counter[3])states_of_button_3[2]<= states_of_button_3[1];
end

//fetching debounced posedge or negedge
always@(posedge clk) begin
states_of_button_0[3]<=states_of_button_0[2];
states_of_button_1[3]<=states_of_button_1[2];
states_of_button_2[3]<=states_of_button_2[2];
states_of_button_3[3]<=states_of_button_3[2];
end

//assign key_states_0={states_of_button_0[2],states_of_button_0[1]};
//assign key_states_1={states_of_button_1[2],states_of_button_1[1]};
//assign key_states_2={states_of_button_2[2],states_of_button_2[1]};
//assign key_states_3={states_of_button_0[2],states_of_button_3[1]};

assign state_changed[0] = (states_of_button_0[1]!=states_of_button_0[0]);
assign state_changed[1] = (states_of_button_1[1]!=states_of_button_1[0]);
assign state_changed[2] = (states_of_button_2[1]!=states_of_button_2[0]);
assign state_changed[3] = (states_of_button_3[1]!=states_of_button_3[0]);

assign BTN[0] = states_of_button_0[2];
assign BTN[1] = states_of_button_1[2];
assign BTN[2] = states_of_button_2[2];
assign BTN[3] = states_of_button_3[2];

assign BTN_POSEDGE[0] = ~states_of_button_0[3]&states_of_button_0[2];
assign BTN_POSEDGE[1] = ~states_of_button_1[3]&states_of_button_1[2];
assign BTN_POSEDGE[2] = ~states_of_button_2[3]&states_of_button_2[2];
assign BTN_POSEDGE[3] = ~states_of_button_3[3]&states_of_button_3[2];

assign BTN_NEGEDGE[0] = states_of_button_0[3]&~states_of_button_0[2];
assign BTN_NEGEDGE[1] = states_of_button_1[3]&~states_of_button_1[2];
assign BTN_NEGEDGE[2] = states_of_button_2[3]&~states_of_button_2[2];
assign BTN_NEGEDGE[3] = states_of_button_3[3]&~states_of_button_3[2];

endmodule