Deletion implemented

This commit is contained in:
2026-04-29 15:52:33 +02:00
parent 750bad7f83
commit db16bafd6c
8 changed files with 171 additions and 22 deletions

View File

@@ -1,28 +1,33 @@
const std = @import("std");
const e = @import("../errors.zig");
const Road = @import("road.zig").Road;
const Node = @import("node.zig").Node;
pub const RoadManager = struct {
next_id: usize,
roads: std.ArrayList(*Road),
highlighted_road: ?*Road,
pub fn init() RoadManager {
return .{
.next_id = 0,
.roads = .empty,
.highlighted_road = null,
};
}
pub fn deinit(self: *RoadManager, allocator: std.mem.Allocator) void {
for (self.roads.items) |road| {
allocator.destroy(road);
road.deinit(allocator);
}
self.roads.deinit(allocator);
}
pub fn draw(self: *const RoadManager) void {
pub fn draw(self: *const RoadManager, delete_mode: bool) void {
for (self.roads.items) |road| {
road.draw();
const is_highlighted = delete_mode and self.highlighted_road != null and self.highlighted_road.? == road;
road.draw(is_highlighted);
}
}
@@ -46,11 +51,40 @@ pub const RoadManager = struct {
pub fn clear(self: *RoadManager, allocator: std.mem.Allocator) void {
for (self.roads.items) |road| {
allocator.destroy(road);
road.deinit(allocator);
}
self.roads.clearRetainingCapacity();
self.next_id = 0;
}
pub fn deleteRoad(self: *RoadManager, allocator: std.mem.Allocator, road_to_delete: *Road) !void {
// unreference the road from its bounding functions
road_to_delete.unreferenceNodes() catch |err| {
std.debug.panic("Failed to unreference the road from its nodes: {}\n", .{err});
};
for (0..self.roads.items.len) |i| {
if (self.roads.items[i] != road_to_delete) continue;
road_to_delete.deinit(allocator);
_ = self.roads.swapRemove(i);
return;
}
return e.Entity.NotFound;
}
/// Sets the pointer to the road that is intersection with pos coordinate
pub fn update_highlighted_road(self: *RoadManager, pos: Vector2) void {
for (self.roads.items) |road| {
if (!road.isHighlighted(pos)) continue;
self.highlighted_road = road;
return;
}
self.highlighted_road = null;
}
};
const Vector2 = @import("raylib").Vector2;
@@ -91,4 +125,5 @@ test "id tracking" {
// TODO tests
// force resize pointer test
// add, remove road
// destroy road and then verify the nodes do not have a pointer to it