Files
traffic-simulator/src/simulator.zig

298 lines
11 KiB
Zig

const std = @import("std");
const rl = @import("raylib");
const c = @import("common/constants.zig");
const st = @import("common/structures.zig");
const ut = @import("common/utils.zig");
const Road = @import("infrastructure/road.zig").Road;
const Node = @import("infrastructure/node.zig").Node;
const NodeManager = @import("infrastructure/node_manager.zig").NodeManager;
const RoadManager = @import("infrastructure/road_manager.zig").RoadManager;
pub const Simulator = struct {
/// allocator for convenience
allocator: std.mem.Allocator,
/// 'class' tracking all the nodes (and appropriate functions)
node_man: NodeManager,
/// 'class' tracking all the roads (and appropriate functions)
road_man: RoadManager,
// vars
/// Tracks whether next road will start building from the node the last road was built at
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,
/// Tracks whether highlighting all entities that are connected to hovered entity is enabled
///
/// For example, if I hover over a node it will highlight all roads that are connected to it;
/// Same goes for hovering over a road or in the future, a car (might show destination and path to it)
///
/// Note: It only works outside of the delete mode
show_connections: bool,
highlighted_entity: ?st.Entity,
/// Constructor for convenience
pub fn init(new_allocator: std.mem.Allocator) Simulator {
return .{
.allocator = new_allocator,
.node_man = .init(),
.road_man = .init(),
.auto_continue = false,
.delete_mode = false,
.show_connections = false,
.highlighted_entity = null,
};
}
/// Deinitialisation of node and road objects
pub fn deinit(self: *Simulator) !void {
self.road_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 {
rl.clearBackground(c.BACKGROUND_COLOR);
var highlighted_road: ?*Road = null;
if (self.delete_mode) {
if (self.highlighted_entity) |entity| {
if (entity == .road) highlighted_road = entity.road;
}
}
self.road_man.draw(highlighted_road);
self.node_man.draw(pos);
self.drawRelatedSelectedEntities();
}
fn drawRelatedSelectedEntities(self: *const Simulator) void {
if (!self.show_connections or self.highlighted_entity == null) return;
const h_entity = self.highlighted_entity.?;
switch (h_entity) {
.node => {
const node = h_entity.node;
for (node.roads.items) |road| {
road.draw(true);
}
node.draw(c.NODE_RELATED_COLOUR);
},
.road => {
const road = h_entity.road;
road.draw(true);
road.nodes[0].draw(c.NODE_RELATED_COLOUR);
road.nodes[1].draw(c.NODE_RELATED_COLOUR);
},
}
}
/// Update tick
pub fn update(self: *Simulator, pos: rl.Vector2) void {
self.updateHighlightedEntity(pos);
}
/// Exposed input handling function exposed to raylib
pub fn handleInput(self: *Simulator, pos: rl.Vector2) void {
self.handleKeyboardInput();
self.handleMouseInput(pos);
}
/// Sub input handling function for keyboard input only
fn handleKeyboardInput(self: *Simulator) void {
self.auto_continue = rl.isKeyDown(.left_control);
self.delete_mode = rl.isKeyDown(.left_shift);
self.show_connections = rl.isKeyDown(.left_alt) and !self.delete_mode;
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 {
if (rl.isMouseButtonReleased(.left)) {
self.leftClickEvent(pos);
return;
}
if (rl.isMouseButtonReleased(.right)) self.node_man.deleteTempNode(self.allocator);
}
/// Function that handles functionality that executes upon left click
fn leftClickEvent(self: *Simulator, pos: rl.Vector2) void {
if (self.delete_mode and self.highlighted_entity != null and self.highlighted_entity.? == .road) {
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 {
if (self.show_connections) return;
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", .{
pos.x, pos.y, err
});
};
if (self.node_man.temp_node) |temp| {
// Prevents the road from being attached to 2 identical nodes (0 length road)
if (temp.id == cur_node.id) return;
// TODO replace with road splitting
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});
};
const intersections = self.getIntersectingRoads(self.allocator, temp, cur_node) catch |err| {
std.debug.panic("Intersection selection failure: {}\n", .{err});
};
defer self.allocator.free(intersections);
// DEBUG TODO REMOVE
std.debug.print("Displaying intersection position and the intersected road:\n", .{});
for (0..intersections.len) |i| {
const int = intersections[i];
std.debug.print("Road ID={d} Pos: ({d}, {d})\n", .{int.road.id, int.pos.x, int.pos.y});
}
self.node_man.temp_node = if (self.auto_continue) cur_node else null;
return;
}
self.node_man.temp_node = cur_node;
}
/// User initiated road destroying functionality
fn delete_road(self: *Simulator) !void {
// We can trust this because this only gets called if valid and if type is road
std.debug.assert(self.highlighted_entity != null and self.highlighted_entity.? == .road);
const h_road = self.highlighted_entity.?.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});
};
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.highlighted_entity = null;
self.road_man.clear(self.allocator);
try self.node_man.clear(self.allocator);
}
/// Updates the variable that tracks the highlighted entity
fn updateHighlightedEntity(self: *Simulator, pos: rl.Vector2) void {
if (self.node_man.getHighlightedNode(pos)) |node| {
self.highlighted_entity = .{ .node = node };
return;
}
if (self.road_man.getHighlightedRoad(pos)) |road| {
self.highlighted_entity = .{ .road = road };
return;
}
self.highlighted_entity = null;
}
fn getIntersectingRoads(self: *const Simulator, allocator: std.mem.Allocator, start: *const Node, end: *const Node) ![]st.IntersectionData {
var intersections: std.ArrayList(st.IntersectionData) = .empty;
var collision_point: rl.Vector2 = undefined;
var start_node_collision: ?*Road = null;
var end_node_collision: ?*Road = null;
// Here we will check if any road collides with start and end node
for (self.road_man.roads.items) |road| {
if (start_node_collision == null and road.collides(start.pos) and !start.roadsContains(road))
start_node_collision = road;
if (end_node_collision == null and road.collides(end.pos) and !end.roadsContains(road))
end_node_collision = road;
if (start_node_collision != null and end_node_collision != null) break;
}
// if road node is placed on the road it is added as a collision with said road
if (start_node_collision) |road| {
try intersections.append(self.allocator, .{
.road = road,
.pos = start.pos,
});
}
outer: for (self.road_man.roads.items) |road| {
if (!rl.checkCollisionLines(
start.pos,end.pos,
road.nodes[0].pos, road.nodes[1].pos,
&collision_point))
continue;
const intersection = st.IntersectionData {
.road = road,
.pos = collision_point,
};
// We put a 0 here, just to satisfy the constructor function,
// it is not getting appended to the node list anyways
const node: Node = .init(0, intersection.pos);
// If the newly acquired intersection node is within the snapping radius of already existing nodes,
// we don't add it to the list
for (intersections.items) |inter_collision| {
if (node.withinSnapRadius(inter_collision.pos)) continue :outer;
}
// If there is an existing node that covers our position within its snapping radius,
// then such position will not be saved as intersection
if (self.node_man.getNodeIfExists(node.pos) != null) continue;
try intersections.append(allocator, intersection);
}
// if end node is placed on the road it is added as a collision with said road
if (end_node_collision) |road| {
try intersections.append(self.allocator, .{
.road = road,
.pos = end.pos,
});
}
const sorted_intersection = try intersections.toOwnedSlice(allocator);
std.sort.block(st.IntersectionData, sorted_intersection, start, ut.compareIntersections);
return sorted_intersection;
}
fn splitRoadsByIntersections(self: *Simulator, intersections: []st.IntersectionData, start: *Node, end: *Node) void {
if (intersections.len == 0) {
self.road_man.addRoad(self.allocator, start, end) catch |err| {
std.debug.panic("Failed to create a road connecting the origin nodes: {}\n", .{err});
};
return;
}
for (0..intersections.len) |i| {
_ = i; // autofix
}
}
};