Compare commits

..

6 Commits

10 changed files with 363 additions and 41 deletions

View File

@@ -130,6 +130,20 @@ pub fn build(b: *std.Build) void {
run_cmd.addArgs(args); run_cmd.addArgs(args);
} }
const tests = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/test.zig"),
.target = target,
.optimize = optimize,
.imports = &.{
.{ .name = "raylib", .module = raylib },
},
}),
});
tests.root_module.linkLibrary(raylib_artifact);
const run_tests = b.addRunArtifact(tests);
// Creates an executable that will run `test` blocks from the provided module. // Creates an executable that will run `test` blocks from the provided module.
// Here `mod` needs to define a target, which is why earlier we made sure to // Here `mod` needs to define a target, which is why earlier we made sure to
// set the releative field. // set the releative field.
@@ -156,6 +170,7 @@ pub fn build(b: *std.Build) void {
const test_step = b.step("test", "Run tests"); const test_step = b.step("test", "Run tests");
// test_step.dependOn(&run_mod_tests.step); // test_step.dependOn(&run_mod_tests.step);
test_step.dependOn(&run_exe_tests.step); test_step.dependOn(&run_exe_tests.step);
test_step.dependOn(&run_tests.step);
// Just like flags, top level steps are also listed in the `--help` menu. // Just like flags, top level steps are also listed in the `--help` menu.
// //

View File

@@ -4,8 +4,7 @@ const clr = @import("raylib").Color;
pub const WIDTH = 1366; pub const WIDTH = 1366;
/// Screen Height /// Screen Height
pub const HEIGHT = 768; pub const HEIGHT = 768;
pub const BACKGROUND_COLOR = clr.dark_gray; pub const BACKGROUND_COLOR = clr.light_gray;
pub const ALLOC_SIZE = 50;
/// Base node radius /// Base node radius
pub const NODE_RADIUS = 20; pub const NODE_RADIUS = 20;

6
src/errors.zig Normal file
View File

@@ -0,0 +1,6 @@
/// Contains collection of errors connected with an entity (road, node, car, etc.)
pub const Entity = error {
AlreadyReferenced,
NotFound,
HasReferences,
};

View File

@@ -2,13 +2,18 @@ const std = @import("std");
const rl = @import("raylib"); const rl = @import("raylib");
const c = @import("../constants.zig"); const c = @import("../constants.zig");
const e = @import("../errors.zig");
const Road = @import("road.zig").Road; const Road = @import("road.zig").Road;
pub const Node = struct { pub const Node = struct {
/// Possibly unnecessary, but for now it's good as a secondary mean of identification
id: usize, id: usize,
/// Node's position on the simulation 'field'
pos: rl.Vector2, pos: rl.Vector2,
/// Contains references of all the roads this node is connected to
roads: std.ArrayList(*Road), roads: std.ArrayList(*Road),
/// Simple constructor
pub fn init(new_id: usize, new_pos: rl.Vector2) Node { pub fn init(new_id: usize, new_pos: rl.Vector2) Node {
return .{ return .{
.id = new_id, .id = new_id,
@@ -17,26 +22,59 @@ pub const Node = struct {
}; };
} }
pub fn deinit(self: *Node, allocator: std.mem.Allocator) void { /// This function frees the list that holds road references that are connected to this node
///
/// Next it invalidates itself (the pointer), making it invalid
pub fn deinit(self: *Node, allocator: std.mem.Allocator) !void {
if (self.roads.items.len != 0) return e.Entity.AlreadyReferenced;
self.roads.deinit(allocator); self.roads.deinit(allocator);
allocator.destroy(self);
} }
/// Simple function which draws the node
pub fn draw(self: *const Node, direct_colour: ?rl.Color) void { pub fn draw(self: *const Node, direct_colour: ?rl.Color) void {
const colour = if (direct_colour) |clr| clr else c.NODE_COLOUR; const colour = if (direct_colour) |clr| clr else c.NODE_COLOUR;
rl.drawCircleV(self.pos, c.NODE_RADIUS, colour); rl.drawCircleV(self.pos, c.NODE_RADIUS, colour);
} }
/// Identifies whether the pos (location) is within the snapping radius of the node
pub fn posWithinRadius(self: *const Node, pos: rl.Vector2) bool { pub fn posWithinRadius(self: *const Node, pos: rl.Vector2) bool {
return rl.checkCollisionPointCircle(pos, self.pos, c.NODE_SNAP_RADIUS); return rl.checkCollisionPointCircle(pos, self.pos, c.NODE_SNAP_RADIUS);
} }
/// Tries to reference the passed road to self
///
/// Returns an error if the passed road cannot be appended to the list or if said road is already in the list
pub fn referenceRoad(self: *Node, allocator: std.mem.Allocator, road_to_add: *Road) !void { pub fn referenceRoad(self: *Node, allocator: std.mem.Allocator, road_to_add: *Road) !void {
// Note the road_to_add pointer must be one from the roads list as otherwise the pointer is dangling one // Note the road_to_add pointer must be one from the roads list as otherwise the pointer is dangling one
for (self.roads.items) |road| { for (self.roads.items) |road| {
if (road.*.id == road_to_add.*.id) return error.RoadAlreadyReferenced; if (road == road_to_add) return e.Entity.AlreadyReferenced;
} }
try self.roads.append(allocator, road_to_add); try self.roads.append(allocator, road_to_add);
} }
/// Attempts to unreference the passed road from self (node)
///
/// Returns whether the node still has node references (true) or not (false)
///
/// Returns an error if the road is not referenced to self in the first place
pub fn unreferenceRoad(self: *Node, road_to_remove: *const Road) !void {
for (0..self.roads.items.len) |i| {
if (self.roads.items[i] != road_to_remove) continue;
_ = self.roads.swapRemove(i);
return;
}
return e.Entity.NotFound;
}
}; };
// TODO tests
// road reference test
// pos within node test
// deinit test
// roads ptr list test

View File

@@ -2,14 +2,19 @@ const std = @import("std");
const Vector2 = @import("raylib").Vector2; const Vector2 = @import("raylib").Vector2;
const c = @import("../constants.zig"); const c = @import("../constants.zig");
const e = @import("../errors.zig");
const Node = @import("node.zig").Node; const Node = @import("node.zig").Node;
const Road = @import("road.zig").Road; const Road = @import("road.zig").Road;
pub const NodeManager = struct { pub const NodeManager = struct {
/// Tracks which ID the next added node will get
next_id: usize, next_id: usize,
nodes: std.ArrayList(Node), /// Tracks all the node (pointers)
nodes: std.ArrayList(*Node),
/// Tracks the temporary node, being part of the newly built road
temp_node: ?*Node, temp_node: ?*Node,
/// Constructor (for convenience)
pub fn init() NodeManager { pub fn init() NodeManager {
return .{ return .{
.next_id = 0, .next_id = 0,
@@ -18,13 +23,15 @@ pub const NodeManager = struct {
}; };
} }
pub fn deinit(self: *NodeManager, allocator: std.mem.Allocator) void { /// Deinitialises every node (pointer) within the list and then deinits the list containing the nodes itself
for (self.nodes.items) |*node| { pub fn deinit(self: *NodeManager, allocator: std.mem.Allocator) !void {
node.deinit(allocator); for (self.nodes.items) |node| {
try node.deinit(allocator);
} }
self.nodes.deinit(allocator); self.nodes.deinit(allocator);
} }
/// Regular draw function
pub fn draw(self: *const NodeManager, pos: Vector2) void { pub fn draw(self: *const NodeManager, pos: Vector2) void {
for (self.nodes.items) |node| { for (self.nodes.items) |node| {
node.draw(null); node.draw(null);
@@ -35,25 +42,30 @@ pub const NodeManager = struct {
var cur_node = Node.init(0, pos); var cur_node = Node.init(0, pos);
// Temporary road that is to be drawn as one in the making // Temporary road that is to be drawn as one in the making
const road: Road = .init(0, node, &cur_node); const road: Road = .init(0, node, &cur_node);
road.draw(); road.draw(false);
node.*.draw(c.NODE_TEMP_COLOUR); node.*.draw(c.NODE_TEMP_COLOUR);
cur_node.draw(c.NODE_CURSOR_COLOUR); cur_node.draw(c.NODE_CURSOR_COLOUR);
} }
} }
/// Checks if there is a node pointer within the snap radius of pos coordinate;
/// otherwise creates a new node and returns its pointer
pub fn getSelectedNode(self: *NodeManager, allocator: std.mem.Allocator, pos: Vector2) !*Node { pub fn getSelectedNode(self: *NodeManager, allocator: std.mem.Allocator, pos: Vector2) !*Node {
for (self.nodes.items) |*node| { for (self.nodes.items) |node| {
if (node.posWithinRadius(pos)) return node; if (node.posWithinRadius(pos)) return node;
} }
// No node is within that position, so we must create a new one // No node is within that position, so we must create a new one
const node: Node = .init(self.getNextID(), pos); const node: Node = .init(self.getNextID(), pos);
try self.nodes.append(allocator, node); const node_ptr = try allocator.create(Node);
node_ptr.* = node;
try self.nodes.append(allocator, node_ptr);
return &self.nodes.items[self.nodes.items.len - 1]; return self.nodes.items[self.nodes.items.len - 1];
} }
/// Gets next id, resets only on clear()
fn getNextID(self: *NodeManager) usize { fn getNextID(self: *NodeManager) usize {
const id = self.next_id; const id = self.next_id;
self.next_id += 1; self.next_id += 1;
@@ -61,12 +73,57 @@ pub const NodeManager = struct {
return id; return id;
} }
pub fn clear(self: *NodeManager, allocator: std.mem.Allocator) void { /// Clears all existing nodes connected, not deinitialisation
pub fn clear(self: *NodeManager, allocator: std.mem.Allocator) !void {
self.temp_node = null; self.temp_node = null;
for (self.nodes.items) |*node| { for (self.nodes.items) |node| {
node.deinit(allocator); try node.deinit(allocator);
} }
self.nodes.clearRetainingCapacity(); self.nodes.clearRetainingCapacity();
self.next_id = 0; self.next_id = 0;
} }
/// Deletes node, returns error if node still has road references
pub fn deleteNode(self: *NodeManager, allocator: std.mem.Allocator, node_to_delete: *Node) !void {
if (node_to_delete.roads.items.len != 0) return e.Entity.HasReferences;
for (0..self.nodes.items.len) |i| {
if (self.nodes.items[i] != node_to_delete) continue;
try node_to_delete.deinit(allocator);
_ = self.nodes.swapRemove(i);
return;
}
return e.Entity.NotFound;
}
}; };
const expect = std.testing.expect;
test "id tracking" {
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var node_man: NodeManager = .init();
defer node_man.deinit(allocator);
const n = 5;
for (0..n) |_| {
const node: Node = .init(node_man.getNextID(), Vector2 {
.x = 500,
.y = 500,
});
const node_ptr = try allocator.create(Node);
node_ptr.* = node;
try node_man.nodes.append(allocator, node_ptr);
}
try expect(node_man.next_id == n);
try expect(node_man.nodes.items.len == n);
}
// TODO tests
// force resize pointer test
// deleting nodes

View File

@@ -11,6 +11,7 @@ pub const Road = struct {
/// Calculated road length /// Calculated road length
length: f32, length: f32,
/// Constructor, which sets nodes for the road and calculates its length
pub fn init(new_id: usize, start: *Node, end: *Node) Road { pub fn init(new_id: usize, start: *Node, end: *Node) Road {
var road: Road = .{ var road: Road = .{
.id = new_id, .id = new_id,
@@ -22,6 +23,11 @@ pub const Road = struct {
return road; return road;
} }
/// This makes the road ptr DEAD
pub fn deinit(self: *Road, allocator: std.mem.Allocator) void {
allocator.destroy(self);
}
/// Calculates length of the road by taking its two nodes /// Calculates length of the road by taking its two nodes
fn calculate_length(self: *const Road) f32 { fn calculate_length(self: *const Road) f32 {
const start = self.nodes[0]; const start = self.nodes[0];
@@ -34,7 +40,55 @@ pub const Road = struct {
return @sqrt(square_diff); return @sqrt(square_diff);
} }
pub fn draw(self: *const Road) void { /// Simple function which draws the node
rl.drawLineEx(self.nodes[0].*.pos, self.nodes[1].*.pos, c.ROAD_SIZE, c.ROAD_COLOUR); ///
/// In the future as we improve and make roads more complex with multiple lanes and such
/// it will gradually become more complex
pub fn draw(self: *const Road, highlighted: bool) void {
const colour = if (highlighted) c.ROAD_HIGHLIGHTED_COLOUR else c.ROAD_COLOUR;
rl.drawLineEx(self.nodes[0].*.pos, self.nodes[1].*.pos, c.ROAD_SIZE, colour);
}
/// Important: after this function executes, this road is no longer reachable from its bounding nodes
///
/// The function unreferences self (road) from its bounding nodes
pub fn unreferenceNodes(self: *const Road) !void {
try self.nodes[0].unreferenceRoad(self);
try self.nodes[1].unreferenceRoad(self);
}
/// Checks whether pos coordinate is on the referenced road
pub fn isHighlighted(self: *const Road, pos: rl.Vector2) bool {
return rl.checkCollisionPointLine(pos, self.nodes[0].*.pos, self.nodes[1].*.pos, c.ROAD_SIZE);
} }
}; };
const std = @import("std");
const expect = std.testing.expect;
test "valid road nodes" {
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const start: Node = .init(34, .{.x = 500, .y = 500});
const start_ptr = try allocator.create(Node);
defer {
start_ptr.*.deinit(allocator);
allocator.destroy(start_ptr);
}
start_ptr.* = start;
const end: Node = .init(227, .{.x = 600, .y = 500});
const end_ptr = try allocator.create(Node);
defer {
end_ptr.*.deinit(allocator);
allocator.destroy(end_ptr);
}
end_ptr.* = end;
const road: Road = .init(11, start_ptr, end_ptr);
try expect(road.nodes[0].id == 34);
try expect(road.nodes[1].id == 227);
}

View File

@@ -1,37 +1,52 @@
const std = @import("std"); const std = @import("std");
const e = @import("../errors.zig");
const Road = @import("road.zig").Road; const Road = @import("road.zig").Road;
const Node = @import("node.zig").Node; const Node = @import("node.zig").Node;
pub const RoadManager = struct { pub const RoadManager = struct {
next_id: usize, next_id: usize,
roads: std.ArrayList(Road), roads: std.ArrayList(*Road),
highlighted_road: ?*Road,
pub fn init() RoadManager { pub fn init() RoadManager {
return .{ return .{
.next_id = 0, .next_id = 0,
.roads = .empty, .roads = .empty,
.highlighted_road = null,
}; };
} }
/// Deinitialises every road (pointer) and then the list itself
pub fn deinit(self: *RoadManager, allocator: std.mem.Allocator) void { pub fn deinit(self: *RoadManager, allocator: std.mem.Allocator) void {
for (self.roads.items) |road| {
road.deinit(allocator);
}
self.roads.deinit(allocator); self.roads.deinit(allocator);
} }
pub fn draw(self: *const RoadManager) void { /// Draws all the roads in the list, sends the information ahead whether the road drawn should be highlighted
pub fn draw(self: *const RoadManager, delete_mode: bool) void {
for (self.roads.items) |road| { 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);
} }
} }
/// Function which creates the road object, its pointer, adds it to the list
/// and then also references that same road to the bounding nodes
pub fn addRoad(self: *RoadManager, allocator: std.mem.Allocator, start: *Node, end: *Node) !void { pub fn addRoad(self: *RoadManager, allocator: std.mem.Allocator, start: *Node, end: *Node) !void {
const road: Road = .init(self.getNextID(), start, end); const road: Road = .init(self.getNextID(), start, end);
try self.roads.append(allocator, road); const road_ptr = try allocator.create(Road);
road_ptr.* = road;
try self.roads.append(allocator, road_ptr);
const ref = &self.roads.items[self.roads.items.len - 1]; const ref = self.roads.items[self.roads.items.len - 1];
try start.referenceRoad(allocator, ref); try start.referenceRoad(allocator, ref);
try end.referenceRoad(allocator, ref); try end.referenceRoad(allocator, ref);
} }
/// Returns the id, and increases it by one; used for generating ID's for new entities
fn getNextID(self: *RoadManager) usize { fn getNextID(self: *RoadManager) usize {
const id = self.next_id; const id = self.next_id;
self.next_id += 1; self.next_id += 1;
@@ -39,8 +54,87 @@ pub const RoadManager = struct {
return id; return id;
} }
pub fn clear(self: *RoadManager) void { /// Deinits all the roads, clears them but not deiniting the list itself; also resets the next ID var
pub fn clear(self: *RoadManager, allocator: std.mem.Allocator) void {
for (self.roads.items) |road| {
road.deinit(allocator);
}
self.roads.clearRetainingCapacity(); self.roads.clearRetainingCapacity();
self.next_id = 0; self.next_id = 0;
} }
/// Removes the references of the road, from the nodes that bound that road
///
/// Then it deinitialises the road and removes it from the list
///
/// Will return an error if the road itself is not present in the list
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;
const expect = std.testing.expect;
test "id tracking" {
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var road_man: RoadManager = .init();
defer road_man.deinit(allocator);
const n = 5;
const start: Node = .init(0, .{.x = 0, .y = 0});
const start_ptr = try allocator.create(Node);
start_ptr.* = start;
const end: Node = .init(1, .{.x = 100, .y = 100});
const end_ptr = try allocator.create(Node);
end_ptr.* = end;
defer {
start_ptr.deinit(allocator);
end_ptr.deinit(allocator);
allocator.destroy(start_ptr);
allocator.destroy(end_ptr);
}
for (0..n) |_| {
try road_man.addRoad(allocator, start_ptr, end_ptr);
}
try expect(road_man.next_id == n);
try expect(road_man.roads.items.len == n);
}
// TODO tests
// force resize pointer test
// add, remove road
// destroy road and then verify the nodes do not have a pointer to it

View File

@@ -4,12 +4,6 @@ const rl = @import("raylib");
const c = @import("constants.zig"); const c = @import("constants.zig");
const Simulator = @import("simulator.zig").Simulator; const Simulator = @import("simulator.zig").Simulator;
// TODO PLANS
// Implement that roads, nodes in managers will be stored as pointers (allocated in heap)
// So when appending causes the list to relocate, nothing will have to change
// since the allocated nodes/roads will remain where they were
// Additionally add more robust error and test handling
pub fn main(init: std.process.Init) !void { pub fn main(init: std.process.Init) !void {
const allocator = init.gpa; const allocator = init.gpa;
@@ -25,7 +19,9 @@ pub fn main(init: std.process.Init) !void {
rl.setTargetFPS(rl.getMonitorRefreshRate(monitor)); rl.setTargetFPS(rl.getMonitorRefreshRate(monitor));
var sim: Simulator = .init(allocator); var sim: Simulator = .init(allocator);
defer sim.deinit(); defer sim.deinit() catch |err| {
std.debug.panic("Failed to deinitialise the sim: {}\n", .{err});
};
while (!rl.windowShouldClose()) { while (!rl.windowShouldClose()) {
rl.beginDrawing(); rl.beginDrawing();
@@ -33,6 +29,7 @@ pub fn main(init: std.process.Init) !void {
const pos = rl.getMousePosition(); const pos = rl.getMousePosition();
sim.handleInput(pos); sim.handleInput(pos);
sim.update(pos);
sim.draw(pos); sim.draw(pos);
} }

View File

@@ -6,49 +6,83 @@ const NodeManager = @import("infrastructure/node_manager.zig").NodeManager;
const RoadManager = @import("infrastructure/road_manager.zig").RoadManager; const RoadManager = @import("infrastructure/road_manager.zig").RoadManager;
pub const Simulator = struct { pub const Simulator = struct {
/// allocator for convenience
allocator: std.mem.Allocator, allocator: std.mem.Allocator,
/// 'class' tracking all the nodes (and appropriate functions)
node_man: NodeManager, node_man: NodeManager,
/// 'class' tracking all the roads (and appropriate functions)
road_man: RoadManager, road_man: RoadManager,
// vars // vars
/// Tracks whether next road will start building from the node the last road was built at
auto_continue: bool, auto_continue: bool,
/// Tracks whether the system will delete the road cursor is pointed at
/// (in such case, the road-to-be-deleted will also be highlighted)
delete_mode: bool,
/// Constructor for convenience
pub fn init(new_allocator: std.mem.Allocator) Simulator { pub fn init(new_allocator: std.mem.Allocator) Simulator {
return .{ return .{
.allocator = new_allocator, .allocator = new_allocator,
.node_man = .init(), .node_man = .init(),
.road_man = .init(), .road_man = .init(),
.auto_continue = false, .auto_continue = false,
.delete_mode = false,
}; };
} }
pub fn deinit(self: *Simulator) void { /// Deinitialisation of node and road objects
pub fn deinit(self: *Simulator) !void {
self.road_man.deinit(self.allocator); self.road_man.deinit(self.allocator);
self.node_man.deinit(self.allocator); try self.node_man.deinit(self.allocator);
} }
/// Main draw function exposed to RayLib's loop
pub fn draw(self: *const Simulator, pos: rl.Vector2) void { pub fn draw(self: *const Simulator, pos: rl.Vector2) void {
rl.clearBackground(c.BACKGROUND_COLOR); rl.clearBackground(c.BACKGROUND_COLOR);
self.road_man.draw(); self.road_man.draw(self.delete_mode);
self.node_man.draw(pos); self.node_man.draw(pos);
} }
/// Update tick
pub fn update(self: *Simulator, pos: rl.Vector2) void {
self.road_man.update_highlighted_road(pos);
}
/// Exposed input handling function exposed to raylib
pub fn handleInput(self: *Simulator, pos: rl.Vector2) void { pub fn handleInput(self: *Simulator, pos: rl.Vector2) void {
self.handleKeyboardInput(); self.handleKeyboardInput();
self.handleMouseInput(pos); self.handleMouseInput(pos);
} }
/// Sub input handling function for keyboard input only
fn handleKeyboardInput(self: *Simulator) void { fn handleKeyboardInput(self: *Simulator) void {
self.auto_continue = rl.isKeyDown(.left_control); self.auto_continue = rl.isKeyDown(.left_control);
self.delete_mode = rl.isKeyDown(.left_shift);
if (rl.isKeyReleased(.c)) self.clear(); if (rl.isKeyReleased(.c)) self.clear() catch |err| {
std.debug.panic("Failed to clear the entities: {}\n", .{err});
};
} }
/// Sub input handling function for mouse input only
fn handleMouseInput(self: *Simulator, pos: rl.Vector2) void { fn handleMouseInput(self: *Simulator, pos: rl.Vector2) void {
if (rl.isMouseButtonReleased(.left)) self.leftClickEvent(pos); if (rl.isMouseButtonReleased(.left)) self.leftClickEvent(pos);
} }
/// Function that handles functionality that executes upon left click
fn leftClickEvent(self: *Simulator, pos: rl.Vector2) void { fn leftClickEvent(self: *Simulator, pos: rl.Vector2) void {
if (self.delete_mode) {
self.delete_road() catch |err| {
std.debug.panic("Failed to delete the road: {}\n", .{err});
};
return;
}
self.new_road(pos);
}
/// User initiated road building functionality
fn new_road(self: *Simulator, pos: rl.Vector2) void {
const cur_node = self.node_man.getSelectedNode(self.allocator, pos) catch |err| { const cur_node = self.node_man.getSelectedNode(self.allocator, pos) catch |err| {
std.debug.panic("Failed to append the newly created node at pos ({d}, {d}) to node list: {}\n", .{ std.debug.panic("Failed to append the newly created node at pos ({d}, {d}) to node list: {}\n", .{
pos.x, pos.y, err pos.x, pos.y, err
@@ -56,6 +90,7 @@ pub const Simulator = struct {
}; };
if (self.node_man.temp_node) |temp| { if (self.node_man.temp_node) |temp| {
if (temp.*.id == cur_node.*.id) return;
self.road_man.addRoad(self.allocator, temp, cur_node) catch |err| { self.road_man.addRoad(self.allocator, temp, cur_node) catch |err| {
std.debug.panic("Failed to add a new road or assigning its nodes: {}\n", .{err}); std.debug.panic("Failed to add a new road or assigning its nodes: {}\n", .{err});
}; };
@@ -67,8 +102,29 @@ pub const Simulator = struct {
self.node_man.temp_node = cur_node; self.node_man.temp_node = cur_node;
} }
fn clear(self: *Simulator) void { /// User initiated road destroying functionality
self.road_man.clear(); fn delete_road(self: *Simulator) !void {
self.node_man.clear(self.allocator); if (self.road_man.highlighted_road == null) return;
const h_road = self.road_man.highlighted_road.?;
const start_node = h_road.*.nodes[0];
const end_node = h_road.*.nodes[1];
self.road_man.deleteRoad(self.allocator, h_road) catch |err| {
std.debug.panic("Road deletion failed: {}\n", .{err});
};
self.road_man.highlighted_road = null;
if (start_node.roads.items.len == 0)
try self.node_man.deleteNode(self.allocator, start_node);
if (end_node.roads.items.len == 0)
try self.node_man.deleteNode(self.allocator, end_node);
}
/// Clearing node and road lists without deinitialising them (only the children)
fn clear(self: *Simulator) !void {
self.road_man.clear(self.allocator);
try self.node_man.clear(self.allocator);
} }
}; };

6
src/test.zig Normal file
View File

@@ -0,0 +1,6 @@
// Main test file that imports all files that have testing blocks in them
test {
_ = @import("infrastructure/road.zig");
_ = @import("infrastructure/node_manager.zig");
_ = @import("infrastructure/road_manager.zig");
}