From 385ca6511a8de0a4cc1dca774a3c743422c3d6be Mon Sep 17 00:00:00 2001 From: jjanzen Date: Tue, 21 Jan 2025 22:39:11 -0600 Subject: refactor ecs for better genericism --- src/ecs/ecs.zig | 40 ++++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 18 deletions(-) (limited to 'src/ecs/ecs.zig') diff --git a/src/ecs/ecs.zig b/src/ecs/ecs.zig index 919587a..d1341bf 100644 --- a/src/ecs/ecs.zig +++ b/src/ecs/ecs.zig @@ -8,6 +8,12 @@ pub const EntityComponentSystem = struct { available_ids: std.ArrayList(usize), next_id: usize, + fn nullEntity(self: *EntityComponentSystem, entity: usize) void { + inline for (std.enums.valuesFromFields(ComponentType, std.meta.fields(ComponentType))) |comp| { + self.componentRemoveEntity(comp, entity); + } + } + pub fn init(allocator: std.mem.Allocator) EntityComponentSystem { return EntityComponentSystem{ .allocator = allocator, @@ -23,16 +29,13 @@ pub const EntityComponentSystem = struct { } pub fn createEntity(self: *EntityComponentSystem) !usize { - const reuse_id = self.available_ids.popOrNull(); - if (reuse_id != null and reuse_id.? < self.components.items(.component_stub).len) { - return reuse_id.?; - } - - const id = self.next_id; - try self.components.append(self.allocator, .{ - .component_stub = null, - }); - self.next_id += 1; + const id = self.available_ids.popOrNull() orelse noroom: { + const id = self.next_id; + try self.components.append(self.allocator, undefined); + self.next_id += 1; + break :noroom id; + }; + self.nullEntity(id); return id; } @@ -48,23 +51,24 @@ pub const EntityComponentSystem = struct { } pub fn deleteEntity(self: *EntityComponentSystem, entity: usize) !void { - inline for (std.enums.valuesFromFields(ComponentType, std.meta.fields(ComponentType))) |comp| { - self.componentRemoveEntity(comp, entity); - } + self.nullEntity(entity); try self.available_ids.append(entity); } + fn componentRemoveEntityGeneric(comp: anytype, entity: usize) void { + var fixed_comp = comp[entity] orelse return; + fixed_comp.deinit(); + comp[entity] = null; + } + pub fn componentRemoveEntity( self: *EntityComponentSystem, comp: component.ComponentType, entity: usize, ) void { + var components = self.components; switch (comp) { - ComponentType.component_stub => { - var comp_opt = self.components.items(.component_stub)[entity]; - if (comp_opt != null) comp_opt.?.deinit(); - self.components.items(.component_stub)[entity] = null; - }, + ComponentType.component_stub => componentRemoveEntityGeneric(components.items(.component_stub), entity), } } }; -- cgit v1.2.3