diff --git a/primitives.zig b/primitives.zig index 5e581cd..49ca297 100644 --- a/primitives.zig +++ b/primitives.zig @@ -11,7 +11,7 @@ pub const Point = struct { x: i32 = 0, y: i32 = 0, z: i32 = 0, - direction: Direction, //for movement state + direction: Direction = .{ .x = 1, .y = 1, .z = 1 }, //for movement state }; pub const Vec3 = struct { a: Point = .{ .x = 0, .y = 0, .z = 0, .direction = .{ .x = 0, .y = 0, .z = 0 } }, @@ -24,14 +24,67 @@ pub const Triangle = struct { bufc: *i32, }; -pub const Polygon = struct{ - const Node = struct{point:Point,*Node}; +pub fn LinkedList() type { + return struct { + const Self = @This(); //means this struc,ref to the most inner scope - head: *Node; - length: u32; + const Node = struct { point: Point, next: ?*Node }; + head: ?*Node, + length: u32, - pub fn new() Node { - return Node + pub fn new() Self { + return .{ + .head = null, + .length = 0, + }; + } + pub fn add(self: *Self, allocator: std.mem.Allocator, point: Point) void { + var newNode = allocator.create(Node) catch |err| { + std.debug.print("error allocation, {}", .{err}); + return; + }; + + newNode.point = point; + newNode.next = self.head; + + self.head = newNode; + self.length += 1; + } + pub fn dump(self: *Self) ![]Point { + const allocator = std.heap.page_allocator; + var node = self.head; + var point: []Point = &.{}; //empty slice + var i: usize = 0; + + while (node != null) : (i += 1) { + point = allocator.realloc(point, i + 1) catch |err| { + std.debug.print("error allocation for slice:{}\n", .{err}); + return err; + }; + point[i] = node.?.point; + node = node.?.next; + } + //TODO: free memory but how to?, when out of scope or dont use slices? or copy them, or outsource allocation? + return point; + } + }; +} +test "test linked list" { + var polygon = LinkedList().new(); + polygon.add(std.heap.page_allocator, .{ .x = 10, .y = 11, .z = 0 }); + polygon.add(std.heap.page_allocator, .{ .x = 11, .y = 12, .z = 0 }); + polygon.add(std.heap.page_allocator, .{ .x = 12, .y = 13, .z = 0 }); + polygon.add(std.heap.page_allocator, .{ .x = 12, .y = 14, .z = 0 }); + polygon.add(std.heap.page_allocator, .{ .x = 12, .y = 15, .z = 0 }); + polygon.add(std.heap.page_allocator, .{ .x = 12, .y = 16, .z = 0 }); + const points: []Point = try polygon.dump(); + for (points) |point| { + std.debug.print("x:{}\n", .{point.x}); + std.debug.print("y:{}\n", .{point.y}); + std.debug.print("z:{}\n", .{point.z}); + } + std.heap.page_allocator.free(points); +} pub fn pixel(buffer: []u8, w: Winsize, x: i64, y: i64, symbol: u21) !void { const i: usize = @intCast(4 * (x + y * w.ws_col));