From f834d31d46290115c9548da8f847b42f0351578d Mon Sep 17 00:00:00 2001 From: jonathan santis Date: Wed, 23 Oct 2024 13:51:33 +0200 Subject: [PATCH] Add bresenham variants --- main.zig | 61 +++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 38 insertions(+), 23 deletions(-) diff --git a/main.zig b/main.zig index 63513ac..a8cf970 100644 --- a/main.zig +++ b/main.zig @@ -136,7 +136,11 @@ fn fillBuffer() !void { }; _ = vec; //triangle(vec); - _ = try bresenham(buffer, w, Point{ .x = 10, .y = 40, .z = 0 }, Point{ .x = 30, .y = 10, .z = 0 }); + _ = try bresenham(buffer, w, Point{ .x = 10, .y = 10, .z = 0 }, Point{ .x = 30, .y = 12, .z = 0 }); + _ = try bresenham(buffer, w, Point{ .x = 10, .y = 10, .z = 0 }, Point{ .x = 30, .y = 28, .z = 0 }); + _ = try bresenham(buffer, w, Point{ .x = 10, .y = 10, .z = 0 }, Point{ .x = 30, .y = 30, .z = 0 }); + _ = try bresenham(buffer, w, Point{ .x = 10, .y = 10, .z = 0 }, Point{ .x = 30, .y = 40, .z = 0 }); + _ = try bresenham(buffer, w, Point{ .x = 30, .y = 30, .z = 0 }, Point{ .x = 60, .y = 10, .z = 0 }); try file.writeAll(buffer); } fn pixel(buffer: []u8, w: Winsize, x: i64, y: i64, symbol: u21) !void { @@ -152,33 +156,44 @@ fn pixel(buffer: []u8, w: Winsize, x: i64, y: i64, symbol: u21) !void { } } fn bresenham(buf: []u8, w: Winsize, p1: Point, p2: Point) !void { - const x1: i32 = p1.x; - const y1: i32 = p1.y; - var x: i32 = 0; - var y: i32 = 0; + var x: i32 = p1.x; + var y: i32 = p1.y; + //var x: i32 = 0; + //var y: i32 = 0; const dx = (p2.x - p1.x); print("p2: {} - {},{}\n", .{ p2.y, p1.y, p2.y - p1.y }); const dy: i64 = (p2.y - p1.y); //const slope = dx/dy; var er: i64 = 0; - - if (dy > 0 and dy <= dx) { - x = x1; - y = y1; - } - if (dy < 0 and @abs(dy) > dx) { - print("octant2\n", .{}); - x = y1; - y = x1; - } - - while (x <= p2.x) : (x += 1) { - print("[bresenham]x:{},y:{},er:{},dx:{},dy:{}\n", .{ x, y, er, dx, dy }); - _ = try pixel(buf, w, x, y, '.'); - er += dy; - if (2 * er >= dx) { - y += 1; - er -= dx; + if (dx >= dy and dy > 0) { + while (x <= p2.x) : (x += 1) { + print("[bresenham]x:{},y:{},er:{},dx:{},dy:{}\n", .{ x, y, er, dx, dy }); + _ = try pixel(buf, w, x, y, '.'); + er += dy; + if (2 * er >= dx) { + y += 1; + er -= dx; + } + } + } else if (dx < dy and dy > 0) { + while (y <= p2.y) : (y += 1) { + print("[bresenham2]x:{},y:{},er:{},dx:{},dy:{}\n", .{ x, y, er, dx, dy }); + _ = try pixel(buf, w, x, y, ','); + er += dx; + if (2 * er >= dy) { + x += 1; + er -= dy; + } + } + } else if (@abs(dy) < dx and dy < 0) { + while (x <= p2.x) : (x += 1) { + print("[bresenham3]x:{},y:{},er:{},dx:{},dy:{}\n", .{ x, y, er, dx, dy }); + _ = try pixel(buf, w, x, y, 'x'); + er -= dy; + if (2 * er >= dx) { + y -= 1; + er -= dx; + } } } }