// ============================================================================
// neighbor_counter_incremental.v - 增量式邻居计数器
// 利用相邻元胞的邻域重叠，减少计算量
// ============================================================================
module neighbor_counter_incremental #(
    parameter WIDTH = 640
)(
    input  wire             clk,
    input  wire [WIDTH-1:0] row_above,   // 上一行
    input  wire [WIDTH-1:0] row_curr,    // 当前行
    input  wire [WIDTH-1:0] row_below,   // 下一行
    output wire [WIDTH-1:0] next_row     // 下一状态行
);

    // 对每个元胞，用3位列计数器
    // col_sum[x] = row_above[x] + row_curr[x] + row_below[x]
    wire [1:0] col_sum [0:WIDTH-1];
    genvar i;
    generate
        for (i = 0; i < WIDTH; i = i + 1) begin : gen_colsum
            assign col_sum[i] = row_above[i] + row_curr[i] + row_below[i];
        end
    endgenerate

    // 滑动窗口：ncount[x] = col_sum[x-1] + col_sum[x] + col_sum[x+1] - self
    generate
        for (i = 0; i < WIDTH; i = i + 1) begin : gen_count
            wire [1:0] cl = (i == 0) ? col_sum[WIDTH-1] : col_sum[i-1];
            wire [1:0] cc = col_sum[i];
            wire [1:0] cr = (i == WIDTH-1) ? col_sum[0] : col_sum[i+1];
            wire [3:0] raw_count = cl + cc + cr;
            wire [3:0] ncount = raw_count - {3'd0, row_curr[i]}; // 减去自身

            wire self = row_curr[i];
            assign next_row[i] = self ? (ncount==4'd2 || ncount==4'd3) :
                                       (ncount==4'd3);
        end
    endgenerate

endmodule