{"repo_name": "ZCS", "file_name": "/ZCS/src/subcmd.zig", "inference_info": {"prefix_code": "const std = @import(\"std\");\nconst assert = std.debug.assert;\n\nconst zcs = @import(\"root.zig\");\nconst typeId = zcs.typeId;\nconst Entity = zcs.Entity;\nconst Any = zcs.Any;\nconst TypeId = zcs.TypeId;\nconst CmdBuf = zcs.CmdBuf;\nconst Entities = zcs.Entities;\n\n/// An unencoded representation of command buffer commands.\npub const Subcmd = union(enum) {\n /// Binds an existing entity.\n bind_entity: Entity,\n /// Destroys the bound entity.\n destroy: void,\n /// Queues a component to be added by value. The type ID is passed as an argument, component\n /// data is passed via any bytes.\n add_val: Any,\n /// Queues a component to be added by pointer. The type ID and a pointer to the component data\n /// are passed as arguments.\n add_ptr: Any,\n /// Queues an extension command to be added by value. The type ID is passed as an argument, the\n /// payload is passed via any bytes.\n ext_val: Any,\n /// Queues an extension command to be added by pointer. The type ID and a pointer to the\n /// component data are passed as arguments.\n ext_ptr: Any,\n /// Queues a component to be removed.\n remove: TypeId,\n\n /// If a new worst case command is introduced, also update the tests!\n pub const rename_when_changing_encoding = {};\n\n pub const Tag = @typeInfo(@This()).@\"union\".tag_type.?;\n\n /// Decodes encoded commands.\n pub const Decoder = struct {\n cb: *const CmdBuf,\n tag_index: usize = 0,\n arg_index: usize = 0,\n comp_bytes_index: usize = 0,\n\n pub inline fn next(self: *@This()) ?Subcmd {\n _ = rename_when_changing_encoding;\n\n // Decode the next command\n if (self.nextTag()) |tag| {\n switch (tag) {\n .bind_entity => {\n const entity: Entity = @bitCast(self.nextArg().?);\n return .{ .bind_entity = entity };\n },\n inline .add_val, .ext_val => |add| {\n @setEvalBranchQuota(2000);\n const id: TypeId = @ptrFromInt(self.nextArg().?);\n const ptr = self.nextAny(id);\n const any: Any = .{\n .id = id,\n .ptr = ptr,\n };\n return switch (add) {\n .add_val => .{ .add_val = any },\n .ext_val => .{ .ext_val = any },\n else => comptime unreachable,\n };\n },\n inline .add_ptr, .ext_ptr => |add| {\n const id: TypeId = @ptrFromInt(self.nextArg().?);\n const ptr: *const anyopaque = @ptrFromInt(self.nextArg().?);\n const any: Any = .{\n .id = id,\n .ptr = ptr,\n };\n switch (add) {\n .add_ptr => return .{ .add_ptr = any },\n .ext_ptr => return .{ .ext_ptr = any },\n else => comptime unreachable,\n }\n },\n .remove => {\n const id: TypeId = @ptrFromInt(self.nextArg().?);\n return .{ .remove = id };\n },\n .destroy => return .destroy,\n }\n }\n\n // Assert that we're fully empty, and return null\n assert(self.tag_index == self.cb.tags.items.len);\n assert(self.arg_index == self.cb.args.items.len);\n assert(self.comp_bytes_index == self.cb.data.items.len);\n return null;\n }\n\n pub inline fn peekTag(self: *@This()) ?Subcmd.Tag {\n if (self.tag_index < self.cb.tags.items.len) {\n return self.cb.tags.items[self.tag_index];\n } else {\n @branchHint(.unlikely);\n return null;\n }\n }\n\n pub inline fn nextTag(self: *@This()) ?Subcmd.Tag {\n const tag = self.peekTag() orelse return null;\n self.tag_index += 1;\n return tag;\n }\n\n pub inline fn nextArg(self: *@This()) ?u64 {\n if (self.arg_index < self.cb.args.items.len) {\n const arg = self.cb.args.items[self.arg_index];\n self.arg_index += 1;\n return arg;\n } else {\n return null;\n }\n }\n\n pub ", "suffix_code": "\n };\n\n /// Encode adding a component to an entity by value.\n pub fn encodeAddVal(cb: *CmdBuf, entity: Entity, T: type, comp: T) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeBind(cb, entity);\n try Subcmd.encodeVal(cb, .add_val, T, comp);\n }\n\n /// Encode adding a component to an entity by pointer.\n pub fn encodeAddPtr(cb: *CmdBuf, entity: Entity, T: type, comp: *const T) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeBind(cb, entity);\n try Subcmd.encodePtr(cb, .add_ptr, T, comp);\n }\n\n /// Encode an extension command by value.\n pub fn encodeExtVal(cb: *CmdBuf, T: type, payload: T) error{ZcsCmdBufOverflow}!void {\n // Clear the binding. Archetype changes must start with a bind so we don't want it to be\n // cached across other commands.\n cb.binding = .none;\n try Subcmd.encodeVal(cb, .ext_val, T, payload);\n }\n\n /// Encode an extension command by pointer.\n pub fn encodeExtPtr(cb: *CmdBuf, T: type, payload: *const T) error{ZcsCmdBufOverflow}!void {\n // Clear the binding. Archetype changes must start with a bind so we don't want it to be\n // cached across other commands.\n cb.binding = .none;\n try Subcmd.encodePtr(cb, .ext_ptr, T, payload);\n }\n\n /// Encode removing a component from an entity.\n pub fn encodeRemove(cb: *CmdBuf, entity: Entity, id: TypeId) error{ZcsCmdBufOverflow}!void {\n errdefer if (std.debug.runtime_safety) {\n cb.invalid = true;\n };\n try Subcmd.encodeBind(cb, entity);\n if (cb.binding.destroyed) return;\n if (cb.tags.items.len >= cb.tags.capacity) return error.ZcsCmdBufOverflow;\n if (cb.args.items.len >= cb.args.capacity) return error.ZcsCmdBufOverflow;\n cb.tags.appendAssumeCapacity(.remove);\n cb.args.appendAssumeCapacity(@intFromPtr(id));\n }\n\n /// Encode committing an entity.\n pub fn encodeCommit(cb: *CmdBuf, entity: Entity) error{ZcsCmdBufOverflow}!void {\n try encodeBind(cb, entity);\n }\n\n /// Encode destroying an entity.\n pub fn encodeDestroy(cb: *CmdBuf, entity: Entity) error{ZcsCmdBufOverflow}!void {\n errdefer if (std.debug.runtime_safety) {\n cb.invalid = true;\n };\n try Subcmd.encodeBind(cb, entity);\n if (cb.binding.destroyed) return;\n if (cb.tags.items.len >= cb.tags.capacity) return error.ZcsCmdBufOverflow;\n cb.tags.appendAssumeCapacity(.destroy);\n cb.binding.destroyed = true;\n }\n\n /// Encode binding an entity as part of a subcommand.\n fn encodeBind(cb: *CmdBuf, entity: Entity) error{ZcsCmdBufOverflow}!void {\n errdefer if (std.debug.runtime_safety) {\n cb.invalid = true;\n };\n if (cb.binding.entity != entity.toOptional()) {\n if (cb.tags.items.len >= cb.tags.capacity) return error.ZcsCmdBufOverflow;\n cb.binding = .{ .entity = entity.toOptional() };\n cb.tags.appendAssumeCapacity(.bind_entity);\n cb.args.appendAssumeCapacity(@bitCast(entity));\n }\n }\n\n /// Encode a value as part of a subcommand.\n fn encodeVal(cb: *CmdBuf, tag: Tag, T: type, val: T) error{ZcsCmdBufOverflow}!void {\n errdefer if (std.debug.runtime_safety) {\n cb.invalid = true;\n };\n\n if (cb.binding.destroyed) return;\n\n const aligned = std.mem.alignForward(usize, cb.data.items.len, @alignOf(T));\n if (cb.tags.items.len >= cb.tags.capacity) return error.ZcsCmdBufOverflow;\n if (aligned + @sizeOf(T) > cb.data.capacity) return error.ZcsCmdBufOverflow;\n cb.tags.appendAssumeCapacity(tag);\n cb.args.appendAssumeCapacity(@intFromPtr(typeId(T)));\n\n cb.data.items.len = aligned;\n cb.data.appendSliceAssumeCapacity(std.mem.asBytes(&val));\n }\n\n /// Encode a pointer as part of a subcommand.\n fn encodePtr(cb: *CmdBuf, tag: Tag, T: type, ptr: *const T) error{ZcsCmdBufOverflow}!void {\n errdefer if (std.debug.runtime_safety) {\n cb.invalid = true;\n };\n\n if (cb.binding.destroyed) return;\n\n if (cb.tags.items.len >= cb.tags.capacity) return error.ZcsCmdBufOverflow;\n if (cb.args.items.len + 2 > cb.args.capacity) return error.ZcsCmdBufOverflow;\n\n cb.tags.appendAssumeCapacity(tag);\n cb.args.appendAssumeCapacity(@intFromPtr(typeId(T)));\n cb.args.appendAssumeCapacity(@intFromPtr(ptr));\n }\n};\n", "middle_code": "inline fn nextAny(self: *@This(), id: TypeId) *const anyopaque {\n self.comp_bytes_index = std.mem.alignForward(\n usize,\n self.comp_bytes_index,\n id.alignment,\n );\n const bytes = &self.cb.data.items[self.comp_bytes_index..][0..id.size];\n self.comp_bytes_index += id.size;\n return bytes.ptr;\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "zig", "sub_task_type": null}, "context_code": [["/ZCS/src/CmdBuf.zig", "//! Buffers ECS commands for later execution.\n//!\n//! This allows queuing destructive operations while iterating, or from multiple threads safely by\n//! assigning each thread its own command buffer. All commands are noops if the entity in question\n//! is destroyed before the time of execution.\n//!\n//! `CmdBuf` allocates at init time, and then never again. It should be cleared and reused when\n//! possible.\n//!\n//! All exec methods may invalidate iterators, but by convention only the high level\n//! `execImmediate*` explicitly calls `es.pointer_generation.increment()`. If you are writing your\n//! own exec function, you should call this yourself.\n//!\n//! Some command buffer modifications leave the command buffer in an undefined state on failure, this\n//! is documented on the relevant functions. Trying to execute a command buffer invalidated in this\n//! way results in safety checked illegal behavior. This design means that these functions are\n//! typically not useful in real applications since you can't recover the CB after the error, rather\n//! they're intended for tests. While it would be possible to preserve valid state by restoring the\n//! lengths, this doesn't tend to be useful for real applications and substantially affects\n//! performance in benchmarks.\n\nconst std = @import(\"std\");\nconst tracy = @import(\"tracy\");\nconst zcs = @import(\"root.zig\");\n\nconst log = std.log;\n\nconst meta = zcs.meta;\n\nconst assert = std.debug.assert;\nconst Allocator = std.mem.Allocator;\n\nconst Zone = tracy.Zone;\n\nconst Entities = zcs.Entities;\nconst Entity = zcs.Entity;\nconst Any = zcs.Any;\nconst TypeId = zcs.TypeId;\nconst CompFlag = zcs.CompFlag;\n\nconst CmdBuf = @This();\nconst Subcmd = @import(\"subcmd.zig\").Subcmd;\n\nconst Binding = struct {\n pub const none: @This() = .{ .entity = .none };\n entity: Entity.Optional = .none,\n destroyed: bool = false,\n};\n\nname: ?[:0]const u8,\ntags: std.ArrayListUnmanaged(Subcmd.Tag),\nargs: std.ArrayListUnmanaged(u64),\ndata: std.ArrayListAlignedUnmanaged(u8, zcs.TypeInfo.max_align),\nbinding: Binding = .{ .entity = .none },\nreserved: std.ArrayListUnmanaged(Entity),\ninvalid: if (std.debug.runtime_safety) bool else void,\nwarn_ratio: f32,\n\n/// Options for `init`.\npub const InitOptions = struct {\n /// The debug name for this command buffer.\n ///\n /// Used in warnings and plots, see `updateStats`.\n name: ?[:0]const u8,\n /// Used to allocate the command buffer.\n gpa: Allocator,\n /// Entities are reserved from here.\n es: *Entities,\n /// The capacity of the buffer.\n cap: Capacity = .{},\n /// If more than this ratio of the command buffer is used as measured by `worstCaseUsage`, a\n /// warning will be emitted by `Exec.checkStats`.\n warn_ratio: f32 = 0.2,\n};\n\n/// The capacity of a command buffer.\npub const Capacity = struct {\n /// The default number of commands to reserve.\n pub const default_cmds = 100000;\n /// By default, `cmds / entities_ratio` commands are reserved.\n pub const entities_ratio = 4;\n\n /// Space for at least this many commands will be reserved. If `null`, allocates `default_cmds`.\n ///\n /// Being optional allows `CmdPool` to override this default with a lower value.\n cmds: ?usize = null,\n /// Space for at least this much command data will be reserved. Keep in mind that padding may\n /// vary per platform.\n data: union(enum) {\n bytes: usize,\n bytes_per_cmd: u32,\n } = .{ .bytes_per_cmd = 2 * 16 * @sizeOf(f32) },\n /// Sets the number of entities to reserve up front. See `entities_ratio` for the `null` case.\n reserved_entities: ?usize = null,\n\n /// Returns the number of reserved commands requested.\n fn getCmds(self: @This()) usize {\n return self.cmds orelse default_cmds;\n }\n\n /// Returns the number of data bytes requested.\n fn dataBytes(self: @This()) usize {\n return switch (self.data) {\n .bytes => |bytes| bytes,\n .bytes_per_cmd => |bytes_per_cmd| self.getCmds() * bytes_per_cmd,\n };\n }\n\n /// Returns the number of reserved entities requested.\n fn reservedEntities(self: @This()) usize {\n return self.reserved_entities orelse self.getCmds() / entities_ratio;\n }\n};\n\n/// Initializes a command buffer.\npub fn init(options: InitOptions) error{ OutOfMemory, ZcsEntityOverflow }!@This() {\n const zone = Zone.begin(.{ .src = @src() });\n defer zone.end();\n comptime assert(CompFlag.max < std.math.maxInt(u64));\n\n // Each command can have at most two tags\n _ = Subcmd.rename_when_changing_encoding;\n const cmds_cap = options.cap.getCmds() * 2;\n const tags_zone = Zone.begin(.{ .name = \"tags\", .src = @src() });\n var tags: std.ArrayListUnmanaged(Subcmd.Tag) = try .initCapacity(options.gpa, cmds_cap);\n errdefer tags.deinit(options.gpa);\n tags_zone.end();\n\n // Each command can have at most 3 args (the add ptr subcommand does a bind which has one\n // arg if it's not skipped, and then it also passes the component ID and pointer as args as\n // well.\n _ = Subcmd.rename_when_changing_encoding;\n const args_zone = Zone.begin(.{ .name = \"args\", .src = @src() });\n const args_cap = cmds_cap * 3;\n var args: std.ArrayListUnmanaged(u64) = try .initCapacity(options.gpa, args_cap);\n errdefer args.deinit(options.gpa);\n args_zone.end();\n\n const any_bytes_zone = Zone.begin(.{ .name = \"any bytes\", .src = @src() });\n var data: std.ArrayListAlignedUnmanaged(u8, zcs.TypeInfo.max_align) = try .initCapacity(\n options.gpa,\n options.cap.dataBytes(),\n );\n errdefer data.deinit(options.gpa);\n any_bytes_zone.end();\n\n const reserved_zone = Zone.begin(.{ .name = \"reserved\", .src = @src() });\n var reserved: std.ArrayListUnmanaged(Entity) = try .initCapacity(\n options.gpa,\n options.cap.reservedEntities(),\n );\n errdefer reserved.deinit(options.gpa);\n for (0..reserved.capacity) |_| {\n reserved.appendAssumeCapacity(try Entity.reserveImmediateOrErr(options.es));\n }\n reserved_zone.end();\n\n if (tracy.enabled) {\n if (options.name) |name| {\n tracy.plotConfig(.{\n .name = name,\n .format = .percentage,\n .mode = .line,\n .fill = true,\n });\n }\n }\n\n return .{\n .name = options.name,\n .reserved = reserved,\n .tags = tags,\n .args = args,\n .data = data,\n .invalid = if (std.debug.runtime_safety) false else {},\n .warn_ratio = options.warn_ratio,\n };\n}\n\n/// Destroys the command buffer.\npub fn deinit(self: *@This(), gpa: Allocator, es: *Entities) void {\n for (self.reserved.items) |entity| assert(entity.destroyImmediate(es));\n self.reserved.deinit(gpa);\n self.data.deinit(gpa);\n self.args.deinit(gpa);\n self.tags.deinit(gpa);\n self.* = undefined;\n}\n\n/// Appends an extension command to the buffer.\n///\n/// See notes on `Entity.add` with regards to performance and pass by value vs pointer.\npub inline fn ext(self: *@This(), T: type, payload: T) void {\n // Don't get tempted to remove inline from here! It's required for `isComptimeKnown`.\n comptime assert(@typeInfo(@TypeOf(ext)).@\"fn\".calling_convention == .@\"inline\");\n self.extOrErr(T, payload) catch |err|\n @panic(@errorName(err));\n}\n\n/// Similar to `ext`, but returns an error on failure instead of panicking. The command buffer is\n/// left in an undefined state on error, see the top level documentation for more detail.\npub inline fn extOrErr(self: *@This(), T: type, payload: T) error{ZcsCmdBufOverflow}!void {\n // Don't get tempted to remove inline from here! It's required for `isComptimeKnown`.\n comptime assert(@typeInfo(@TypeOf(extOrErr)).@\"fn\".calling_convention == .@\"inline\");\n if (@sizeOf(T) > @sizeOf(*T) and meta.isComptimeKnown(payload)) {\n const Interned = struct {\n const value = payload;\n };\n try self.extPtr(T, comptime &Interned.value);\n } else {\n try self.extVal(T, payload);\n }\n}\n\n/// Similar to `extOrErr`, but forces the command to be copied by value to the command buffer.\n/// Prefer `ext`.\npub fn extVal(self: *@This(), T: type, payload: T) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeExtVal(self, T, payload);\n}\n\n/// Similar to `extOrErr`, but forces the command to be copied by pointer to the command buffer.\n/// Prefer `ext`.\npub fn extPtr(self: *@This(), T: type, payload: *const T) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeExtPtr(self, T, payload);\n}\n\n/// Clears the command buffer for reuse and then refills the reserved entity list to capacity.\n/// Called automatically from `Exec.immediate`.\npub fn clear(self: *@This(), es: *Entities) void {\n self.clearOrErr(es) catch |err|\n @panic(@errorName(err));\n}\n\n/// Similar to `clear`, but returns `error.ZcsEntityOverflow` when failing to refill the reserved\n/// entity list instead of panicking.\npub fn clearOrErr(self: *@This(), es: *Entities) error{ZcsEntityOverflow}!void {\n const zone = Zone.begin(.{ .src = @src() });\n defer zone.end();\n self.data.clearRetainingCapacity();\n self.args.clearRetainingCapacity();\n self.tags.clearRetainingCapacity();\n self.binding = .none;\n while (self.reserved.items.len < self.reserved.capacity) {\n self.reserved.appendAssumeCapacity(try Entity.reserveImmediateOrErr(es));\n }\n}\n\n/// Returns true if this command buffer is empty.\npub fn isEmpty(self: @This()) bool {\n return self.tags.items.len == 0 and self.reserved.items.len == self.reserved.capacity;\n}\n\n/// Returns the ratio of length to capacity for the internal buffer that is the nearest to being\n/// full. Ignores buffers explicitly initialized with 0 capacity.\npub fn worstCaseUsage(self: @This()) f32 {\n const reserved_used: f32 = @floatFromInt(self.reserved.capacity - self.reserved.items.len);\n const reserved_usage = if (self.reserved.capacity == 0)\n 0.0\n else\n reserved_used / @as(f32, @floatFromInt(self.reserved.capacity));\n return @max(\n usage(self.data),\n usage(self.args),\n usage(self.tags),\n reserved_usage,\n );\n}\n\n/// Calculates the usage of a list as a ratio.\nfn usage(list: anytype) f32 {\n if (list.capacity == 0) return 0.0;\n return @as(f32, @floatFromInt(list.items.len)) / @as(f32, @floatFromInt(list.capacity));\n}\n\n/// Returns an iterator over the encoded commands.\npub fn iterator(self: *const @This()) Iterator {\n if (std.debug.runtime_safety) assert(!self.invalid);\n return .{ .decoder = .{ .cb = self } };\n}\n\n/// Emits a warning if over `warn_ratio`. If Tracy is enabled and this command buffer has a name,\n/// update its plots. Called automatically by `Exec`.\npub fn updateStats(self: *const CmdBuf) void {\n const currentUsage = self.worstCaseUsage();\n\n if (tracy.enabled) {\n if (self.name) |name| {\n tracy.plot(.{\n .name = name,\n .value = .{ .f32 = currentUsage * 100.0 },\n });\n }\n }\n\n if (currentUsage > self.warn_ratio) {\n log.warn(\"command buffer past 50% capacity (buffer name = {?s})\", .{self.name});\n }\n}\n\npub const Exec = struct {\n zone: Zone,\n zone_cmd_exec: zcs.ext.ZoneCmd.Exec = .{},\n\n pub fn init() @This() {\n return .{\n .zone = Zone.begin(.{\n .src = @src(),\n }),\n };\n }\n\n /// Executes the command buffer and then clears it.\n ///\n /// Invalidates pointers.\n pub fn immediate(es: *Entities, cb: *CmdBuf) void {\n immediateOrErr(es, cb) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `execImmediate`, but returns an error on failure instead of panicking. On error, the\n /// command buffer will be partially executed.\n pub fn immediateOrErr(\n es: *Entities,\n cb: *CmdBuf,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow, ZcsEntityOverflow }!void {\n var self: @This() = .init();\n\n es.pointer_generation.increment();\n var iter = cb.iterator();\n while (iter.next()) |batch| {\n switch (batch) {\n .arch_change => |arch_change| {\n const delta = arch_change.deltaImmediate();\n _ = try arch_change.execImmediateOrErr(es, delta);\n },\n .ext => |payload| self.extImmediateOrErr(payload),\n }\n }\n\n try self.finish(cb, es);\n }\n\n pub fn extImmediateOrErr(self: *@This(), payload: Any) void {\n self.zone_cmd_exec.extImmediate(payload);\n }\n\n pub fn finish(self: *@This(), cb: *CmdBuf, es: *Entities) error{ZcsEntityOverflow}!void {\n cb.updateStats();\n cb.clear(es);\n self.zone_cmd_exec.finish();\n self.zone.end();\n }\n};\n\n/// A batch of sequential commands that all have the same entity bound.\npub const Batch = union(enum) {\n ext: Any,\n arch_change: ArchChange,\n\n pub const ArchChange = struct {\n /// A description of delta over all archetype change operations.\n pub const Delta = struct {\n add: CompFlag.Set = .{},\n remove: CompFlag.Set = .{},\n destroy: bool = false,\n\n /// Updates the delta for a given operation.\n pub inline fn updateImmediate(self: *@This(), op: Op) void {\n switch (op) {\n .add => |comp| {\n const flag = CompFlag.registerImmediate(comp.id);\n self.add.insert(flag);\n self.remove.remove(flag);\n },\n .remove => |id| {\n const flag = CompFlag.registerImmediate(id);\n self.add.remove(flag);\n self.remove.insert(flag);\n },\n .destroy => self.destroy = true,\n }\n }\n };\n\n /// The bound entity.\n entity: Entity,\n decoder: Subcmd.Decoder,\n\n /// Returns the delta over all archetype change operations.\n pub inline fn deltaImmediate(self: @This()) Delta {\n var delta: Delta = .{};\n var ops = self.iterator();\n while (ops.next()) |op| delta.updateImmediate(op);\n return delta;\n }\n\n /// An iterator over this batch's commands.\n pub inline fn iterator(self: @This()) @This().Iterator {\n return .{\n .decoder = self.decoder,\n };\n }\n\n /// Executes the batch. Returns true if the entity exists before the command is run, false\n /// otherwise.\n ///\n /// See `getArchChangeImmediate` to get the default archetype change argument.\n pub fn execImmediate(self: @This(), es: *Entities, delta: Delta) bool {\n return self.execImmediateOrErr(es, delta) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `execImmediate`, but returns an error on overflow instead of panicking.\n pub inline fn execImmediateOrErr(\n self: @This(),\n es: *Entities,\n delta: Delta,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!bool {\n if (delta.destroy) return self.entity.destroyImmediate(es);\n\n // Issue the change archetype command. If no changes were requested, this will\n // still commit the entity. If the entity doesn't exist, early out.\n if (!try self.entity.changeArchUninitImmediateOrErr(es, .{\n .add = delta.add,\n .remove = delta.remove,\n })) {\n return false;\n }\n\n // Initialize any new components. Note that we check for existence on each because they\n // could have been subsequently removed.\n {\n // Unwrapping these is fine since we just committed the entity if it wasn't\n // committed, or earlied out if it doesn't exist\n const entity_loc = es.handle_tab.get(self.entity.key).?;\n const chunk = entity_loc.chunk.get(&es.chunk_pool).?;\n var ops = self.iterator();\n while (ops.next()) |op| {\n switch (op) {\n .add => |comp| if (comp.id.comp_flag) |flag| {\n const offset = chunk.header()\n .comp_buf_offsets.values[@intFromEnum(flag)];\n if (offset != 0) {\n assert(offset != 0);\n const dest_unsized: [*]u8 = @ptrFromInt(@intFromPtr(chunk) +\n offset +\n @intFromEnum(entity_loc.index_in_chunk) * comp.id.size);\n const dest = dest_unsized[0..comp.id.size];\n @memcpy(dest, comp.bytes());\n }\n },\n .remove,\n .destroy,\n => {},\n }\n }\n }\n\n return true;\n }\n\n /// An archetype change operation.\n pub const Op = union(enum) {\n add: Any,\n remove: TypeId,\n destroy: void,\n };\n\n /// An iterator over this batch's commands.\n ///\n /// Note that the encoder will elide operations immediately following a destroy. This is\n /// intended to simplify writing extensions.\n pub const Iterator = struct {\n decoder: Subcmd.Decoder,\n\n /// Returns the next operation, or `null` if there are none.\n pub inline fn next(self: *@This()) ?Op {\n while (self.decoder.peekTag()) |tag| {\n const op: Op = switch (tag) {\n .add_val => .{ .add = self.decoder.next().?.add_val },\n .add_ptr => .{ .add = self.decoder.next().?.add_ptr },\n .remove => .{ .remove = self.decoder.next().?.remove },\n .destroy => b: {\n _ = self.decoder.next().?.destroy;\n break :b .destroy;\n },\n .bind_entity, .ext_val, .ext_ptr => break,\n };\n\n // Return the operation.\n return op;\n }\n return null;\n }\n };\n };\n};\n\n/// An iterator over batches of encoded commands.\npub const Iterator = struct {\n decoder: Subcmd.Decoder,\n\n /// Returns the next command batch, or `null` if there is none.\n pub inline fn next(self: *@This()) ?Batch {\n _ = Subcmd.rename_when_changing_encoding;\n\n // We just return bind operations here, `Subcmd` handles the add/remove commands.\n while (self.decoder.next()) |cmd| {\n switch (cmd) {\n // We buffer all ops on a given entity into a single command\n .bind_entity => |entity| return .{ .arch_change = .{\n .entity = entity,\n .decoder = self.decoder,\n } },\n .ext_val, .ext_ptr => |payload| return .{ .ext = payload },\n // These are handled by archetype change. We always start archetype change with a\n // bind so this will never miss ops.\n .add_ptr,\n .add_val,\n .remove,\n .destroy,\n => {},\n }\n }\n\n return null;\n }\n};\n"], ["/ZCS/src/entity.zig", "const std = @import(\"std\");\nconst assert = std.debug.assert;\n\nconst zcs = @import(\"root.zig\");\n\nconst typeId = zcs.typeId;\n\nconst Subcmd = @import(\"subcmd.zig\").Subcmd;\n\nconst Entities = zcs.Entities;\nconst PointerLock = zcs.PointerLock;\nconst Any = zcs.Any;\nconst CompFlag = zcs.CompFlag;\nconst CmdBuf = zcs.CmdBuf;\nconst TypeId = zcs.TypeId;\nconst HandleTab = zcs.HandleTab;\nconst Chunk = zcs.Chunk;\nconst ChunkPool = zcs.ChunkPool;\nconst ChunkList = zcs.storage.ChunkList;\nconst meta = zcs.meta;\n\n/// An entity.\n///\n/// Entity handles are persistent, you can check if an entity has been destroyed via\n/// `Entity.exists`. This is useful for dynamic systems like games where object lifetime may depend\n/// on user input.\n///\n/// Methods that take a command buffer append the command to a command buffer for execution at a\n/// later time. Methods with `immediate` in the name are executed immediately, usage of these is\n/// discouraged as they are not valid while iterating unless otherwise noted and are not thread\n/// safe.\npub const Entity = packed struct {\n /// An entity without its generation. Used by some lower level APIs to save space where the\n /// safety of the generation is not needed, should not be stored long term outside of the ECS.\n pub const Index = enum(@FieldType(HandleTab.Key, \"index\")) {\n _,\n\n /// Converts the entity index to an `Entity` with the corresponding generation. Assumes that\n /// the index is not dangling, this cannot be reliably enforced without the generation.\n pub fn toEntity(self: @This(), es: *const Entities) Entity {\n const result: Entity = .{ .key = .{\n .index = @intFromEnum(self),\n .generation = es.handle_tab.slots[@intFromEnum(self)].generation,\n } };\n assert(result.key.generation != .invalid);\n assert(result.key.index < es.handle_tab.next_index);\n return result;\n }\n };\n\n /// The location an entity is stored.\n ///\n /// This indirection allows entities to be relocated without invalidating their handles.\n pub const Location = struct {\n /// The index of an entity in a chunk.\n pub const IndexInChunk = enum(u32) { _ };\n\n /// A handle that's been reserved but not committed.\n pub const reserved: @This() = .{\n .chunk = .none,\n .index_in_chunk = if (std.debug.runtime_safety)\n @enumFromInt(std.math.maxInt(@typeInfo(IndexInChunk).@\"enum\".tag_type))\n else\n undefined,\n };\n\n /// The chunk where this entity is stored, or `null` if it hasn't been committed.\n chunk: Chunk.Index = .none,\n /// The entity's index in the chunk, value is unspecified if not committed.\n index_in_chunk: IndexInChunk,\n\n /// Returns the archetype for this entity, or the empty archetype if it hasn't been\n /// committed.\n pub fn arch(self: @This(), es: *const Entities) CompFlag.Set {\n const chunk = self.chunk.get(&es.chunk_pool) orelse return .{};\n const header = chunk.header();\n return header.arch(&es.arches);\n }\n };\n\n pub const Optional = packed struct {\n pub const none: @This() = .{ .key = .none };\n\n key: HandleTab.Key.Optional,\n\n /// Unwraps the optional entity into `Entity`, or returns `null` if it is `.none`.\n pub fn unwrap(self: @This()) ?Entity {\n if (self.key.unwrap()) |key| return .{ .key = key };\n return null;\n }\n\n /// Default formatting.\n pub fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void {\n return self.key.format(writer);\n }\n };\n\n key: HandleTab.Key,\n\n /// Pops a reserved entity.\n ///\n /// A reserved entity is given a persistent key, but no storage. As such, it will behave like\n /// an empty entity, but not show up in iteration.\n ///\n /// You can commit a reserved entity explicitly with `commit`, but this isn't usually\n /// necessary as adding or attempting to remove a component implicitly commits the entity.\n pub fn reserve(cb: *CmdBuf) Entity {\n return reserveOrErr(cb) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `reserve`, but returns an error on failure instead of panicking.\n pub fn reserveOrErr(cb: *CmdBuf) error{ZcsReservedEntityUnderflow}!Entity {\n return cb.reserved.pop() orelse error.ZcsReservedEntityUnderflow;\n }\n\n /// Similar to `reserve`, but reserves a new entity instead of popping one from a command\n /// buffers reserve. Prefer `reserve`.\n ///\n /// This does not invalidate pointers, but it's not thread safe.\n pub fn reserveImmediate(es: *Entities) Entity {\n return reserveImmediateOrErr(es) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `reserveImmediate`, but returns `error.ZcsEntityOverflow` on failure instead of\n /// panicking.\n ///\n /// This does not invalidate pointers, but it's not thread safe.\n pub fn reserveImmediateOrErr(es: *Entities) error{ZcsEntityOverflow}!Entity {\n const pointer_lock = es.pointer_generation.lock();\n defer pointer_lock.check(es.pointer_generation);\n\n const key = es.handle_tab.put(.reserved) catch |err| switch (err) {\n error.Overflow => return error.ZcsEntityOverflow,\n };\n es.reserved_entities += 1;\n return .{ .key = key };\n }\n\n /// Queues an entity for destruction.\n ///\n /// Destroying an entity that no longer exists has no effect.\n pub fn destroy(self: @This(), cb: *CmdBuf) void {\n self.destroyOrErr(cb) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `destroy`, but returns `error.ZcsCmdBufOverflow` on failure instead of\n /// panicking. The command buffer is left in an undefined state on error, see the top level\n /// documentation on `CmdBuf` for more info.\n pub fn destroyOrErr(self: @This(), cb: *CmdBuf) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeDestroy(cb, self);\n }\n\n /// Similar to `destroy`, but destroys the entity immediately. Prefer `destroy`.\n ///\n /// Invalidates pointers.\n pub fn destroyImmediate(self: @This(), es: *Entities) bool {\n es.pointer_generation.increment();\n if (es.handle_tab.get(self.key)) |entity_loc| {\n if (entity_loc.chunk.get(&es.chunk_pool)) |chunk| {\n chunk.swapRemove(es, entity_loc.index_in_chunk);\n } else {\n es.reserved_entities -= 1;\n }\n es.handle_tab.remove(self.key);\n entity_loc.* = undefined;\n return true;\n } else {\n return false;\n }\n }\n\n /// Returns true if the entity has not been destroyed.\n pub fn exists(self: @This(), es: *const Entities) bool {\n return es.handle_tab.containsKey(self.key);\n }\n\n /// Returns true if the entity exists and has been committed, otherwise returns false.\n pub fn committed(self: @This(), es: *const Entities) bool {\n const entity_loc = es.handle_tab.get(self.key) orelse return false;\n return entity_loc.chunk != .none;\n }\n\n /// Returns true if the entity has the given component type, false otherwise or if the entity\n /// has been destroyed.\n pub fn has(self: @This(), es: *const Entities, T: type) bool {\n return self.hasId(es, typeId(T));\n }\n\n /// Similar to `has`, but operates on component IDs instead of types.\n pub fn hasId(self: @This(), es: *const Entities, id: TypeId) bool {\n const flag = id.comp_flag orelse return false;\n return self.arch(es).contains(flag);\n }\n\n /// Retrieves the given component type. Returns null if the entity does not have this component\n /// or has been destroyed. See also `Entities.getComp`.\n pub fn get(self: @This(), es: *const Entities, T: type) ?*T {\n // We could use `compsFromId` here, but we a measurable performance improvement in\n // benchmarks by calculating the result directly\n const entity_loc = es.handle_tab.get(self.key) orelse return null;\n const chunk = entity_loc.chunk.get(&es.chunk_pool) orelse return null;\n const flag = typeId(T).comp_flag orelse return null;\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const offset = chunk.header().comp_buf_offsets.values[@intFromEnum(flag)];\n if (offset == 0) return null;\n const comps_addr = @intFromPtr(chunk) + offset;\n const comp_addr = comps_addr + @sizeOf(T) * @intFromEnum(entity_loc.index_in_chunk);\n return @ptrFromInt(comp_addr);\n }\n\n /// Similar to `get`, but operates on component IDs instead of types.\n pub fn getId(self: @This(), es: *const Entities, id: TypeId) ?[]u8 {\n const entity_loc = es.handle_tab.get(self.key) orelse return null;\n const chunk = entity_loc.chunk.get(&es.chunk_pool) orelse return null;\n const comps = chunk.compsFromId(id) orelse return null;\n return comps[@intFromEnum(entity_loc.index_in_chunk) * id.size ..][0..id.size];\n }\n\n /// Queues a component to be added.\n ///\n /// Batching add/removes on the same entity in sequence is more efficient than alternating\n /// between operations on different entities.\n ///\n /// Will automatically pass the data by pointer if it's comptime known, and larger than pointer\n /// sized.\n ///\n /// Adding components to an entity that no longer exists has no effect.\n pub inline fn add(self: @This(), cb: *CmdBuf, T: type, comp: T) void {\n // Don't get tempted to remove inline from here! It's required for `isComptimeKnown`.\n comptime assert(@typeInfo(@TypeOf(add)).@\"fn\".calling_convention == .@\"inline\");\n self.addOrErr(cb, T, comp) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `add`, but returns an error on failure instead of panicking. The command buffer\n /// is left in an undefined state on error, see the top level documentation on `CmdBuf` for more\n /// info.\n pub inline fn addOrErr(\n self: @This(),\n cb: *CmdBuf,\n T: type,\n comp: T,\n ) error{ZcsCmdBufOverflow}!void {\n // Don't get tempted to remove inline from here! It's required for `isComptimeKnown`.\n comptime assert(@typeInfo(@TypeOf(addOrErr)).@\"fn\".calling_convention == .@\"inline\");\n if (@sizeOf(T) > @sizeOf(*T) and meta.isComptimeKnown(comp)) {\n const Interned = struct {\n const value = comp;\n };\n try self.addPtr(cb, T, comptime &Interned.value);\n } else {\n try self.addVal(cb, T, comp);\n }\n }\n\n /// Similar to `addOrErr`, but forces the component to be copied by value to the command buffer.\n /// Prefer `add`.\n pub fn addVal(self: @This(), cb: *CmdBuf, T: type, comp: T) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeAddVal(cb, self, T, comp);\n }\n\n /// Similar to `addOrErr`, forces the component to be copied by pointer to the command buffer.\n /// Prefer `add`.\n pub fn addPtr(\n self: @This(),\n cb: *CmdBuf,\n T: type,\n comp: *const T,\n ) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeAddPtr(cb, self, T, comp);\n }\n\n /// Queues the given component to be removed. Has no effect if the component is not present, or\n /// the entity no longer exists.\n ///\n /// See note on `add` with regards to performance.\n pub fn remove(self: @This(), cb: *CmdBuf, T: type) void {\n self.removeId(cb, typeId(T)) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `remove`, but doesn't require compile time types and returns an error on failure\n /// instead of panicking on failure. The command buffer is left in an undefined state on error,\n /// see the top level documentation on `CmdBuf` for more info.\n pub fn removeId(self: @This(), cb: *CmdBuf, id: TypeId) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeRemove(cb, self, id);\n }\n\n /// Queues the entity to be committed. Has no effect if it has already been committed, called\n /// implicitly on add/remove/cmd. In practice only necessary when creating an empty entity.\n pub fn commit(self: @This(), cb: *CmdBuf) void {\n self.commitOrErr(cb) catch |err|\n @panic(@errorName(err));\n }\n /// Similar to `commit`, but returns `error.ZcsCmdBufOverflow` on failure instead of\n /// panicking. The command buffer is left in an undefined state on error, see the top level\n /// documentation on `CmdBuf` for more info.\n pub fn commitOrErr(self: @This(), cb: *CmdBuf) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeCommit(cb, self);\n }\n\n /// Options for `changeArchImmediate`.\n pub fn ChangeArchImmediateOptions(Add: type) type {\n comptime var has_defaults = true;\n for (@typeInfo(Add).@\"struct\".fields) |field| {\n if (field.default_value_ptr == null) {\n has_defaults = false;\n break;\n }\n }\n if (has_defaults) {\n return struct {\n add: Add = .{},\n remove: CompFlag.Set = .{},\n };\n } else {\n return struct {\n add: Add,\n remove: CompFlag.Set = .{},\n };\n }\n }\n\n /// Adds the listed components and then removes the listed component IDs.\n ///\n /// `Add` is a tuple or struct of components that may be added by `changes`. They may be\n /// optional types to allow deciding whether or not to add them at runtime.\n ///\n /// Returns `true` if the change was made, returns `false` if it couldn't be made because the\n /// entity doesn't exist.\n ///\n /// Invalidates pointers.\n pub fn changeArchImmediate(\n self: @This(),\n es: *Entities,\n Add: type,\n changes: ChangeArchImmediateOptions(Add),\n ) bool {\n return self.changeArchImmediateOrErr(es, Add, changes) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `changeArchImmediate`, but returns an error on failure instead of panicking.\n pub fn changeArchImmediateOrErr(\n self: @This(),\n es: *Entities,\n Add: type,\n changes: ChangeArchImmediateOptions(Add),\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!bool {\n es.pointer_generation.increment();\n\n // Build a set of component types to add/remove\n var add_comps: CompFlag.Set = .{};\n inline for (@typeInfo(Add).@\"struct\".fields) |field| {\n const Comp = zcs.view.Unwrap(field.type);\n if (@typeInfo(field.type) != .optional or @field(changes.add, field.name) != null) {\n add_comps.insert(CompFlag.registerImmediate(typeId(Comp)));\n }\n }\n\n // Apply the archetype change, early out if the entity doesn't exist\n if (!try self.changeArchUninitImmediateOrErr(es, .{\n .add = add_comps,\n .remove = changes.remove,\n })) return false;\n\n const entity_loc = es.handle_tab.get(self.key).?;\n const new_chunk = entity_loc.chunk.get(&es.chunk_pool).?;\n inline for (@typeInfo(Add).@\"struct\".fields) |field| {\n const Comp = zcs.view.Unwrap(field.type);\n if (@typeInfo(field.type) != .optional or @field(changes.add, field.name) != null) {\n // Unwrapping the flag is safe because we already registered it above\n const flag = typeId(Comp).comp_flag.?;\n if (!changes.remove.contains(flag)) {\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const offset = new_chunk.header().comp_buf_offsets.values[@intFromEnum(flag)];\n // Safe because we added it above\n assert(offset != 0);\n const comp: *Comp = @ptrFromInt(@intFromPtr(new_chunk) +\n offset +\n @intFromEnum(entity_loc.index_in_chunk) * @sizeOf(Comp));\n comp.* = @as(?Comp, @field(changes.add, field.name)).?;\n }\n }\n }\n\n return true;\n }\n\n /// Options for `changeArchAnyImmediate`.\n pub const ChangeArchAnyImmediateOptions = struct {\n add: []const Any = &.{},\n remove: CompFlag.Set = .initEmpty(),\n };\n\n /// Similar to `changeArchImmediateOrErr`, but doesn't require comptime types.\n pub fn changeArchAnyImmediate(\n self: @This(),\n es: *Entities,\n changes: ChangeArchAnyImmediateOptions,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!bool {\n es.pointer_generation.increment();\n\n // Build a set of component types to add/remove\n var add_comps: CompFlag.Set = .{};\n for (changes.add) |comp| {\n add_comps.insert(CompFlag.registerImmediate(comp.id));\n }\n\n // Apply the archetype change, early out if the entity doesn't exist\n if (!try self.changeArchUninitImmediateOrErr(es, .{\n .add = add_comps,\n .remove = changes.remove,\n })) return false;\n\n // Initialize the components\n const entity_loc = es.handle_tab.get(self.key).?;\n const chunk = entity_loc.chunk.get(&es.chunk_pool).?;\n for (changes.add) |comp| {\n // Unwrapping the flag is safe because we already registered it above\n const flag = comp.id.comp_flag.?;\n if (!changes.remove.contains(flag)) {\n // Unwrap okay because registered above\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const offset = chunk.header().comp_buf_offsets.values[@intFromEnum(flag)];\n assert(offset != 0);\n const dest_unsized: [*]u8 = @ptrFromInt(@intFromPtr(chunk) +\n offset +\n @intFromEnum(entity_loc.index_in_chunk) * comp.id.size);\n const dest = dest_unsized[0..comp.id.size];\n @memcpy(dest, comp.bytes());\n }\n }\n\n return true;\n }\n\n /// Options for the uninitialized variants of change archetype.\n pub const ChangeArchUninitImmediateOptions = struct {\n /// Component types to remove.\n remove: CompFlag.Set = .{},\n /// Component types to add.\n add: CompFlag.Set = .{},\n };\n\n /// Similar to `changeArchetypeOrErr`, but does not initialize the components. Furthermore, any\n /// added component's values are considered undefined after this call, even if they were\n /// previously initialized.\n ///\n /// May change internal allocator state even on failure, chunk lists are not destroyed even if\n /// no chunks could be allocated for them at this time.\n ///\n /// Technically we could go slightly faster with compile time known types, similar to\n /// `changeArchImmediate` vs `changeArchAnyImmediate`. This works because `@memcpy` with a\n /// comptime known length tends to be a bit faster. However, in practice, these sorts of\n /// immediate arch changes are only done (or only done in bulk) when loading a level, which\n /// means this function is essentially a noop anyway since there won't be any data to move.\n pub fn changeArchUninitImmediateOrErr(\n self: @This(),\n es: *Entities,\n options: ChangeArchUninitImmediateOptions,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!bool {\n es.pointer_generation.increment();\n\n // Get the handle value and figure out the new arch\n const entity_loc = es.handle_tab.get(self.key) orelse return false;\n const old_chunk = entity_loc.chunk.get(&es.chunk_pool);\n const prev_arch = entity_loc.arch(es);\n var new_arch = prev_arch;\n new_arch = new_arch.unionWith(options.add);\n new_arch = new_arch.differenceWith(options.remove);\n\n // If the entity is committed and the arch hasn't changed, early out\n if (old_chunk) |chunk| {\n const chunk_header = chunk.header();\n if (chunk_header.arch(&es.arches).eql(new_arch)) {\n @branchHint(.unlikely);\n return true;\n }\n }\n\n // Get the new location. As mentioned in the doc comment, it's possible that we'll end up\n // creating a new chunk list but not be able to allocate any chunks for it.\n const chunk_list = try es.arches.getOrPut(&es.chunk_pool, new_arch);\n const new_loc = try chunk_list.append(es, self);\n const new_chunk = new_loc.chunk.get(&es.chunk_pool).?;\n errdefer comptime unreachable;\n\n // Initialize the new components to undefined\n if (std.debug.runtime_safety) {\n var added = options.add.differenceWith(options.remove).iterator();\n while (added.next()) |flag| {\n const id = flag.getId();\n const comp_buffer = new_chunk.compsFromId(id).?;\n const comp_offset = @intFromEnum(new_loc.index_in_chunk) * id.size;\n const comp = comp_buffer[comp_offset..][0..id.size];\n @memset(comp, undefined);\n }\n }\n\n // Copy components that aren't being overwritten from the old arch to the new one\n if (old_chunk) |prev_chunk| {\n var move = prev_arch.differenceWith(options.remove)\n .differenceWith(options.add).iterator();\n while (move.next()) |flag| {\n const id = flag.getId();\n\n const new_comp_buffer = new_chunk.compsFromId(id).?;\n const new_comp_offset = @intFromEnum(new_loc.index_in_chunk) * id.size;\n const new_comp = new_comp_buffer[new_comp_offset..][0..id.size];\n\n const prev_comp_buffer = prev_chunk.compsFromId(id).?;\n const prev_comp_offset = @intFromEnum(entity_loc.index_in_chunk) * id.size;\n const prev_comp = prev_comp_buffer[prev_comp_offset..][0..id.size];\n\n @memcpy(new_comp, prev_comp);\n }\n }\n\n // Commit the entity to the new location\n if (old_chunk) |chunk| {\n chunk.swapRemove(es, entity_loc.index_in_chunk);\n } else {\n es.reserved_entities -= 1;\n }\n entity_loc.* = new_loc;\n\n return true;\n }\n\n /// Returns this entity as an optional.\n pub fn toOptional(self: @This()) Optional {\n return .{ .key = self.key.toOptional() };\n }\n\n /// Initializes a `view`, returning `null` if this entity does not exist or is missing any\n /// required components.\n pub fn view(self: @This(), es: *const Entities, View: type) ?View {\n // Check if the entity has the requested components. If the number of components in the view\n // is very large, this measurably improves performance. The cost of the check when not\n // necessary doesn't appear to be measurable.\n const entity_loc = es.handle_tab.get(self.key) orelse return null;\n const chunk = entity_loc.chunk.get(&es.chunk_pool) orelse return null;\n const view_arch = zcs.view.comps(View, .{ .size = .one }) orelse return null;\n const entity_arch = chunk.header().list.arch(&es.arches);\n if (!entity_arch.supersetOf(view_arch)) return null;\n\n // Fill in the view and return it\n var result: View = undefined;\n inline for (@typeInfo(View).@\"struct\".fields) |field| {\n const Unwrapped = zcs.view.UnwrapField(field.type, .{ .size = .one });\n if (Unwrapped == Entity) {\n @field(result, field.name) = self;\n } else {\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const offset = if (typeId(Unwrapped).comp_flag) |flag|\n chunk.header().comp_buf_offsets.values[@intFromEnum(flag)]\n else\n 0;\n if (@typeInfo(field.type) == .optional and offset == 0) {\n @field(result, field.name) = null;\n } else {\n assert(offset != 0); // Archetype already checked\n const comps_addr = @intFromPtr(chunk) + offset;\n const comp_addr = comps_addr +\n @intFromEnum(entity_loc.index_in_chunk) * @sizeOf(Unwrapped);\n @field(result, field.name) = @ptrFromInt(comp_addr);\n }\n }\n }\n return result;\n }\n\n /// Similar to `viewOrAddImmediate`, but for a single component.\n pub fn getOrAddImmediate(\n self: @This(),\n es: *Entities,\n T: type,\n default: T,\n ) ?T {\n return self.getOrAddImmediateOrErr(es, T, default) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `getOrAddImmediate`, but for a single component.\n pub fn getOrAddImmediateOrErr(\n self: @This(),\n es: *Entities,\n T: type,\n default: T,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!?*T {\n const result = try self.viewOrAddImmediateOrErr(es, struct { *T }, .{&default}) orelse\n return null;\n return result[0];\n }\n\n /// Similar to `view`, but will attempt to fill in any non-optional missing components with\n /// the defaults from the `comps` view if present.\n ///\n /// Invalidates pointers.\n pub fn viewOrAddImmediate(\n self: @This(),\n es: *Entities,\n View: type,\n comps: anytype,\n ) ?View {\n return self.viewOrAddImmediateOrErr(es, View, comps) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `viewOrAddImmediate` but returns, but returns an error on failure instead of\n /// panicking.\n pub fn viewOrAddImmediateOrErr(\n self: @This(),\n es: *Entities,\n View: type,\n comps: anytype,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!?View {\n // Create the view, possibly leaving some components uninitialized\n const result = (try self.viewOrAddUninitImmediateOrErr(es, View)) orelse return null;\n\n // Fill in any uninitialized components and return the view\n inline for (@typeInfo(View).@\"struct\".fields) |field| {\n const Unwrapped = zcs.view.UnwrapField(field.type, .{ .size = .one });\n if (@hasField(@TypeOf(comps), field.name) and\n result.uninitialized.contains(typeId(Unwrapped).comp_flag.?))\n {\n @field(result.view, field.name).* = @field(comps, field.name).*;\n }\n }\n return result.view;\n }\n\n /// The result of a `viewOrAddUninit*` call.\n pub fn VoaUninitResult(View: type) type {\n return struct {\n uninitialized: CompFlag.Set,\n view: View,\n };\n }\n\n /// Similar to `viewOrAddImmediate`, but leaves the added components uninitialized.\n pub fn viewOrAddUninitImmediate(\n self: @This(),\n es: *Entities,\n View: type,\n ) ?VoaUninitResult(View) {\n return self.viewOrAddUninitImmediate(es, View) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `viewOrAddImmediate`, but returns an error on failure instead of panicking.\n pub fn viewOrAddUninitImmediateOrErr(\n self: @This(),\n es: *Entities,\n View: type,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!?VoaUninitResult(View) {\n es.pointer_generation.increment();\n\n // Figure out which components are missing\n const entity_loc = es.handle_tab.get(self.key) orelse return null;\n var view_arch: CompFlag.Set = .{};\n inline for (@typeInfo(View).@\"struct\".fields) |field| {\n if (field.type != Entity and @typeInfo(field.type) != .optional) {\n const Unwrapped = zcs.view.UnwrapField(field.type, .{ .size = .one });\n const flag = CompFlag.registerImmediate(typeId(Unwrapped));\n view_arch.insert(flag);\n }\n }\n const curr_arch = entity_loc.arch(es);\n const uninitialized = view_arch.differenceWith(curr_arch);\n if (!curr_arch.supersetOf(view_arch)) {\n assert(try self.changeArchUninitImmediateOrErr(es, .{ .add = uninitialized }));\n }\n\n // Create and return the view\n return .{\n .view = self.view(es, View).?,\n .uninitialized = uninitialized,\n };\n }\n\n /// Default formatting.\n pub fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void {\n return self.key.format(writer);\n }\n\n /// Returns the archetype of the entity. If it has been destroyed or is not yet committed, the\n /// empty archetype will be returned.\n pub fn arch(self: @This(), es: *const Entities) CompFlag.Set {\n const entity_loc = es.handle_tab.get(self.key) orelse return .{};\n return entity_loc.arch(es);\n }\n};\n"], ["/ZCS/src/ext/Node.zig", "//! A component that tracks parent child relationships.\n//!\n//! Node fields must be kept logically consistent. The recommended approach is to only modify nodes\n//! through command buffers, and then use the provided command buffer processing to synchronize\n//! your changes.\n\nconst std = @import(\"std\");\nconst tracy = @import(\"tracy\");\n\nconst assert = std.debug.assert;\n\nconst zcs = @import(\"../root.zig\");\nconst typeId = zcs.typeId;\nconst TypeId = zcs.TypeId;\nconst Entities = zcs.Entities;\nconst Entity = zcs.Entity;\nconst CmdBuf = zcs.CmdBuf;\nconst CompFlag = zcs.CompFlag;\nconst Any = zcs.Any;\n\nconst Zone = tracy.Zone;\n\nconst Node = @This();\n\nparent: Entity.Optional = .none,\nfirst_child: Entity.Optional = .none,\nprev_sib: Entity.Optional = .none,\nnext_sib: Entity.Optional = .none,\n\n/// Returns the parent node, or null if none exists.\npub fn getParent(self: *const @This(), es: *const Entities) ?*Node {\n const parent = self.parent.unwrap() orelse return null;\n return parent.get(es, Node).?;\n}\n\n/// Returns the first child, or null if none exists.\npub fn getFirstChild(self: *const @This(), es: *const Entities) ?*Node {\n const first_child = self.first_child.unwrap() orelse return null;\n return first_child.get(es, Node).?;\n}\n\n/// Returns the previous sibling, or null if none exists.\npub fn getPrevSib(self: *const @This(), es: *const Entities) ?*Node {\n const prev_sib = self.prev_sib.unwrap() orelse return null;\n return prev_sib.get(es, Node).?;\n}\n\n/// Returns the next sibling, or null if none exists.\npub fn getNextSib(self: *const @This(), es: *const Entities) ?*Node {\n const next_sib = self.next_sib.unwrap() orelse return null;\n return next_sib.get(es, Node).?;\n}\n\n/// Similar to the `SetParent` command, but sets the parent immediately.\npub fn setParentImmediate(self: *Node, es: *Entities, parent_opt: ?*Node) void {\n const pointer_lock = es.pointer_generation.lock();\n defer pointer_lock.check(es.pointer_generation);\n\n // If the relationship would result in a cycle, or parent and child are equal, early out.\n if (parent_opt) |parent| {\n if (self == parent) return;\n if (self.isAncestorOf(es, parent)) return;\n }\n\n // Unparent the child\n if (self.getParent(es)) |curr_parent| {\n if (self.getPrevSib(es)) |prev_sib| {\n prev_sib.next_sib = self.next_sib;\n } else {\n curr_parent.first_child = self.next_sib;\n }\n if (self.next_sib.unwrap()) |next_sib| {\n next_sib.get(es, Node).?.prev_sib = self.prev_sib;\n self.next_sib = .none;\n }\n self.prev_sib = .none;\n self.parent = .none;\n }\n\n // Set the new parent\n if (parent_opt) |parent| {\n self.parent = es.getEntity(parent).toOptional();\n self.next_sib = parent.first_child;\n const child_entity = es.getEntity(self);\n if (parent.first_child.unwrap()) |first_child| {\n first_child.get(es, Node).?.prev_sib = child_entity.toOptional();\n }\n parent.first_child = child_entity.toOptional();\n }\n}\n\n/// Destroys a node, its entity, and all of its children. This behavior occurs automatically via\n/// `exec` when an entity with an entity with a node is destroyed.\n///\n/// Invalidates pointers.\npub fn destroyImmediate(unstable_ptr: *@This(), es: *Entities) void {\n // Cache the entity handle since we're about to invalidate pointers\n const e = es.getEntity(unstable_ptr);\n\n // Destroy the children and unparent this node\n unstable_ptr.destroyChildrenAndUnparentImmediate(es);\n\n // Destroy the entity\n assert(e.destroyImmediate(es));\n}\n\n/// Destroys a node's children and then unparents it. This behavior occurs automatically via `exec`\n/// when a node is removed from an entity.\n///\n/// Invalidates pointers.\npub fn destroyChildrenAndUnparentImmediate(unstable_ptr: *@This(), es: *Entities) void {\n const pointer_lock = es.pointer_generation.lock();\n\n // Get an iterator over the node's children and then destroy it\n var children = b: {\n defer pointer_lock.check(es.pointer_generation);\n const self = unstable_ptr; // Not yet disturbed\n\n const iter = self.postOrderIterator(es);\n self.setParentImmediate(es, null);\n self.first_child = .none;\n\n break :b iter;\n };\n\n // Iterate over the children and destroy them, this will invalidate `unstable_ptr`\n es.pointer_generation.increment();\n while (children.next(es)) |curr| {\n assert(es.getEntity(curr).destroyImmediate(es));\n }\n}\n\n/// Returns true if an ancestor of `descendant`, false otherwise. Entities are not ancestors of\n/// themselves.\npub fn isAncestorOf(self: *const @This(), es: *const Entities, descendant: *const Node) bool {\n var curr = descendant.getParent(es) orelse return false;\n while (true) {\n if (curr == self) return true;\n curr = curr.getParent(es) orelse return false;\n }\n}\n\n/// Returns an iterator over the node's immediate children.\npub fn childIterator(self: *const @This()) ChildIterator {\n return .{ .curr = self.first_child };\n}\n\n/// An iterator over a node's immediate children.\nconst ChildIterator = struct {\n curr: Entity.Optional,\n\n /// Returns the next child, or `null` if there are none.\n pub fn next(self: *@This(), es: *const Entities) ?*Node {\n const entity = self.curr.unwrap() orelse return null;\n const node = entity.get(es, Node).?;\n self.curr = node.next_sib;\n return node;\n }\n};\n\n/// Returns an iterator over the node's ancestors. The iterator starts at the parent, if any, and\n/// then, follows the parent chain until it hits a node with no parent.\npub fn ancestorIterator(self: *const @This()) AncestorIterator {\n return .{ .curr = self.parent };\n}\n\n/// An iterator over a node's ancestors.\nconst AncestorIterator = struct {\n curr: Entity.Optional,\n\n /// Returns the next ancestor, or `null` if there are none.\n pub fn next(self: *@This(), es: *const Entities) ?*Node {\n const entity = self.curr.unwrap() orelse return null;\n const node = entity.get(es, Node).?;\n self.curr = node.parent;\n return node;\n }\n};\n\n/// Returns a pre-order iterator over a node's children. Pre-order traversal visits parents before\n/// children.\npub fn preOrderIterator(self: *const @This(), es: *const Entities) PreOrderIterator {\n return .{\n .start = es.getEntity(self).toOptional(),\n .curr = self.first_child,\n };\n}\n\n/// A pre-order iterator over `(start, ...]`.\npub const PreOrderIterator = struct {\n start: Entity.Optional,\n curr: Entity.Optional,\n\n /// An empty pre-order iterator.\n pub const empty: @This() = .{\n .start = .none,\n .curr = .none,\n };\n\n /// Returns the next child, or `null` if there are none.\n pub fn next(self: *@This(), es: *const Entities) ?*Node {\n const pre_entity = self.curr.unwrap() orelse return null;\n const pre = pre_entity.get(es, Node).?;\n if (pre.first_child != Entity.Optional.none) {\n self.curr = pre.first_child;\n } else {\n var has_next_sib = pre;\n while (has_next_sib.next_sib.unwrap() == null) {\n if (has_next_sib.parent.unwrap().? == self.start.unwrap().?) {\n self.curr = .none;\n return pre;\n }\n has_next_sib = has_next_sib.getParent(es).?;\n }\n self.curr = has_next_sib.next_sib.unwrap().?.toOptional();\n }\n return pre;\n }\n\n /// Fast forward the iterator to just after the given subtree.\n ///\n /// Asserts that `subtree` is a subtree of this iterator.\n pub fn skipSubtree(self: *@This(), es: *const Entities, subtree: *const Node) void {\n // Assert that subtree is contained by this iterator. If it isn't, we'd end up with an\n // infinite loop.\n if (self.start.unwrap()) |start| {\n assert(start.get(es, Node).?.isAncestorOf(es, subtree));\n }\n\n var has_next_sib = subtree;\n while (has_next_sib.next_sib.unwrap() == null) {\n if (has_next_sib.parent.unwrap().? == self.start.unwrap().?) {\n self.curr = .none;\n return;\n }\n has_next_sib = has_next_sib.getParent(es).?;\n }\n self.curr = has_next_sib.next_sib.unwrap().?.toOptional();\n }\n};\n\n/// Returns a post-order iterator over a node's children. Post-order traversal visits parents after\n/// children.\npub fn postOrderIterator(self: *const @This(), es: *const Entities) PostOrderIterator {\n return .{\n // We start on the leftmost leaf\n .curr = b: {\n var curr = self.first_child.unwrap() orelse break :b .none;\n while (curr.get(es, Node).?.first_child.unwrap()) |fc| curr = fc;\n break :b curr.toOptional();\n },\n // And we end when we reach the given entity\n .end = es.getEntity(self),\n };\n}\n\n/// A post-order iterator over `[curr, end)`.\npub const PostOrderIterator = struct {\n curr: Entity.Optional,\n end: Entity,\n\n /// Returns the next child, or `null` if there are none.\n pub fn next(self: *@This(), es: *const Entities) ?*Node {\n const post_entity = self.curr.unwrap() orelse return null;\n if (post_entity == self.end) return null;\n const post = post_entity.get(es, Node).?;\n if (post.next_sib.unwrap()) |next_sib| {\n var curr = next_sib;\n while (curr.get(es, Node).?.first_child.unwrap()) |fc| curr = fc;\n self.curr = curr.toOptional();\n } else {\n self.curr = self.curr.unwrap().?.get(es, Node).?.parent.unwrap().?.toOptional();\n }\n return post;\n }\n};\n\n/// Encodes a command that requests to parent `child` and `parent`.\n///\n/// * If the relationship would result in a cycle, parent and child are equal, or child no longer\n/// exists, then no change is made.\n/// * If parent is `.none`, child is unparented.\n/// * If parent no longer exists, child is destroyed.\npub const SetParent = struct {\n child: Entity,\n parent: Entity.Optional,\n};\n\n/// `Exec` provides helpers for processing hierarchy changes via the command buffer.\n///\n/// By convention, `exec` only calls into the stable public interface of the types it's working\n/// with. As such, documentation is sparse. You are welcome to call these methods directly, or\n/// use them as reference for implementing your own command buffer iterator.\npub const Exec = struct {\n /// Provided as reference. Executes a command buffer, maintaining the hierarchy and reacting to\n /// related events along the way. In practice, you likely want to call the finer grained\n /// functions provided directly, so that other libraries you use can also hook into the command\n /// buffer iterator.\n pub fn immediate(es: *Entities, cb: *CmdBuf) void {\n immediateOrErr(es, cb) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `immediate`, but returns an error on failure instead of panicking. On error the\n /// commands are left partially evaluated.\n ///\n /// Invalidates pointers.\n pub fn immediateOrErr(\n es: *Entities,\n cb: *CmdBuf,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow, ZcsEntityOverflow }!void {\n var default_exec: CmdBuf.Exec = .init();\n\n es.pointer_generation.increment();\n\n var batches = cb.iterator();\n while (batches.next()) |batch| {\n switch (batch) {\n .arch_change => |arch_change| {\n var delta: CmdBuf.Batch.ArchChange.Delta = .{};\n var ops = arch_change.iterator();\n while (ops.next()) |op| {\n beforeArchChangeImmediate(es, arch_change, op);\n delta.updateImmediate(op);\n }\n\n _ = try arch_change.execImmediateOrErr(es, delta);\n },\n .ext => |ext| {\n try extImmediateOrErr(es, ext);\n default_exec.extImmediateOrErr(ext);\n },\n }\n }\n\n try default_exec.finish(cb, es);\n }\n\n /// Executes an extension command.\n pub inline fn extImmediateOrErr(\n es: *Entities,\n payload: Any,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!void {\n if (payload.as(SetParent)) |set_parent| {\n const child = set_parent.child;\n if (set_parent.parent.unwrap()) |parent| {\n if (try child.getOrAddImmediateOrErr(es, Node, .{})) |child_node| {\n if (try parent.getOrAddImmediateOrErr(es, Node, .{})) |parent_node| {\n // If a parent that exists is assigned, set it as the parent\n child_node.setParentImmediate(es, parent_node);\n } else {\n // Otherwise destroy the child\n child_node.destroyImmediate(es);\n }\n }\n } else {\n // If our parent is being cleared and we have a node, clear it. If not leave\n // it alone since it's implicitly clear.\n if (child.get(es, Node)) |node| {\n node.setParentImmediate(es, null);\n }\n }\n }\n }\n\n /// Call this before executing a command.\n pub inline fn beforeArchChangeImmediate(\n es: *Entities,\n arch_change: CmdBuf.Batch.ArchChange,\n op: CmdBuf.Batch.ArchChange.Op,\n ) void {\n switch (op) {\n .destroy => if (arch_change.entity.get(es, Node)) |node| {\n _ = node.destroyChildrenAndUnparentImmediate(es);\n },\n .remove => |id| if (id == typeId(Node)) {\n if (arch_change.entity.get(es, Node)) |node| {\n _ = node.destroyChildrenAndUnparentImmediate(es);\n }\n },\n .add => {},\n }\n }\n};\n"], ["/ZCS/src/CmdPool.zig", "//! A pool of command buffers. Intended for multithreaded use cases where each thread needs its own\n//! command buffer.\n//!\n//! # Problem Statement\n//!\n//! The key issue this abstraction solves is how much space to allocate per command buffer.\n//!\n//! The naive approach of dividing the capacity evenly across the threads will fail if the workload\n//! is lopsided or the users machine has more cores than expected.\n//!\n//! The alternative naive approach of allocating a fixed command buffer size per thread will\n//! increase the likelihood of overflowing command buffers on machines with low core counts, or\n//! overflowing entities on machines with high core counts.\n//!\n//! # Solution\n//!\n//! `CmdPool` allocates a fixed number of command buffers of fixed sizes. Once per chunk, you call\n//! `acquire` to get a command buffer with more than `headroom` capacity`. When done processing a\n//! chunk, you call `release`.\n//!\n//! This distribution of load results in comparable command buffer usage regardless of core counts,\n//! lessening the Q&A burden when tuning your game.\n\nconst std = @import(\"std\");\nconst zcs = @import(\"root.zig\");\nconst tracy = @import(\"tracy\");\n\nconst log = std.log;\nconst assert = std.debug.assert;\n\nconst Mutex = std.Thread.Mutex;\nconst Condition = std.Thread.Condition;\n\nconst CmdBuf = zcs.CmdBuf;\nconst Entities = zcs.Entities;\n\nconst Allocator = std.mem.Allocator;\nconst ArrayListUnmanaged = std.ArrayListUnmanaged;\n\n/// The debug name for this command pool. See `InitOptions.name`.\nname: ?[:0]const u8,\n/// Reserved command buffers that have not yet been acquired.\nbuffers: ArrayListUnmanaged(CmdBuf),\n/// Locked when modifying internal state.\nmutex: Mutex,\n/// Signaled when command buffers are returned, broadcasted when all command buffers have been\n/// retired.\ncondition: Condition,\n/// Command buffers that have been released.\nreleased: ArrayListUnmanaged(*CmdBuf),\n/// The number of retired command buffers. Command buffers are retired when they are returned with\n/// with less than the requested headroom available.\nretired: usize,\n/// Measured in units of `CmdBuf.worstCastUsage`, ranges from `0` to `1`.\nheadroom: f32,\n/// See `InitOptions.warn_ratio`.\nwarn_ratio: f32,\n\n/// The capacity of a command pool.\npub const Capacity = struct {\n /// The default number of commands to reserve.\n pub const default_cmds = CmdBuf.Capacity.default_cmds / 256;\n\n /// The capacity of a single command buffer. Note that `default_cmds` is overridden to a lower\n /// value than when creating a `CmdBuf` directly.\n buffer: CmdBuf.Capacity = .{},\n /// The total number of command buffers to reserve.\n buffers: usize = 256,\n};\n\n/// Options for `init`.\npub const InitOptions = struct {\n /// The debug name for this command pool.\n ///\n /// If non-null and Tracy is enabled, this command pool's usage is graphed under this name on\n /// reset.\n name: ?[:0]const u8,\n /// Used to allocate the command pool.\n gpa: Allocator,\n /// Entities are reserved from here.\n es: *Entities,\n /// The capacity.\n cap: Capacity = .{},\n /// `acquire` only returns command buffers with a `worstCaseUsage` greater than this value.\n headroom: f32 = 0.5,\n /// Warn if a single acquire exceeds this ratio of the headroom, or if more than this ratio of the\n /// total command buffers are written.\n warn_ratio: f32 = 0.2,\n};\n\n/// Initializes a command pool.\npub fn init(options: InitOptions) error{ OutOfMemory, ZcsEntityOverflow }!@This() {\n // Reserve the command buffers\n var buffers: ArrayListUnmanaged(CmdBuf) = try .initCapacity(options.gpa, options.cap.buffers);\n errdefer buffers.deinit(options.gpa);\n errdefer for (buffers.items) |*cb| cb.deinit(options.gpa, options.es);\n var buffer_cap = options.cap.buffer;\n buffer_cap.cmds = buffer_cap.cmds orelse Capacity.default_cmds;\n for (0..options.cap.buffers) |_| {\n const cb: CmdBuf = try .init(.{\n .name = null,\n .gpa = options.gpa,\n .es = options.es,\n .cap = buffer_cap,\n // We handle the warnings ourselves\n .warn_ratio = 1.0,\n });\n buffers.appendAssumeCapacity(cb);\n }\n\n // Reserve the released list\n var released: ArrayListUnmanaged(*CmdBuf) = try .initCapacity(options.gpa, options.cap.buffers);\n errdefer released.deinit(options.gpa);\n\n // If Tracy is enabled and we have a name, configure our plot.\n if (tracy.enabled) {\n if (options.name) |name| {\n tracy.plotConfig(.{\n .name = name,\n .format = .percentage,\n .mode = .line,\n .fill = true,\n });\n }\n }\n\n return .{\n .buffers = buffers,\n .mutex = .{},\n .condition = .{},\n .released = released,\n .retired = 0,\n .headroom = options.headroom,\n .name = options.name,\n .warn_ratio = options.warn_ratio,\n };\n}\n\n/// Destroys the command pool.\npub fn deinit(self: *@This(), gpa: Allocator, es: *Entities) void {\n self.checkAssertions();\n self.buffers.items.len = self.buffers.capacity;\n for (self.buffers.items) |*cb| cb.deinit(gpa, es);\n self.buffers.deinit(gpa);\n self.released.deinit(gpa);\n}\n\n/// The result of `acquire`.\npub const AcquireResult = struct {\n /// The initial usage ratio.\n usage: f32,\n /// The command buffer.\n cb: *CmdBuf,\n\n /// Initializes an acquire result with the starting usage.\n fn init(cb: *CmdBuf) @This() {\n return .{\n .usage = cb.worstCaseUsage(),\n .cb = cb,\n };\n }\n};\n\n/// Acquire a command buffer with at least `Capacity.headroom` capacity remaining. Call `release`\n/// when done. Thread safe.\n///\n/// This function may block if all command buffers are currently in use. You can mitigate this by\n/// reserving more command buffers up front.\npub fn acquire(self: *@This()) AcquireResult {\n return self.acquireOrErr() catch |err|\n @panic(@errorName(err));\n}\n\n/// Similar to `acquire`, but returns an error when out of command buffers.\npub fn acquireOrErr(self: *@This()) error{ZcsCmdPoolUnderflow}!AcquireResult {\n self.mutex.lock();\n defer self.mutex.unlock();\n\n // Try to get a recently released command buffer\n if (self.released.pop()) |popped| return .init(popped);\n\n // Try to get a reserved command buffer\n if (self.buffers.items.len > 0) {\n const new_len = self.buffers.items.len - 1;\n const result = &self.buffers.items[new_len];\n self.buffers.items.len = new_len;\n return .init(result);\n }\n\n // There are no command buffers available. Wait until one becomes available, or all are\n // retired.\n while (self.released.items.len == 0 and self.retired < self.buffers.capacity) {\n self.condition.wait(&self.mutex);\n }\n\n // Try to reacquire the released command buffer\n if (self.released.pop()) |cb| {\n assert(self.retired < self.buffers.capacity);\n return .init(cb);\n }\n\n // If no command buffer was released, we're out of command buffers, return an error\n assert(self.retired == self.buffers.capacity);\n return error.ZcsCmdPoolUnderflow;\n}\n\n/// Releases a previously acquired command buffer. Thread safe.\npub fn release(self: *@This(), ar: AcquireResult) void {\n self.mutex.lock();\n defer self.mutex.unlock();\n\n // Optionally warn if a single acquire used too much headroom, this is a sign that the command\n // buffers are too small\n const usage = ar.cb.worstCaseUsage();\n if (ar.cb.worstCaseUsage() - ar.usage > (1.0 - self.headroom) * self.warn_ratio) {\n log.warn(\n \"acquire used > {d}% headroom, consider increasing command buffer size\",\n .{self.warn_ratio * 100.0},\n );\n }\n\n // Release the command buffer if it has enough headroom left, otherwise retire it\n if (usage < self.headroom) {\n self.released.appendAssumeCapacity(ar.cb);\n } else {\n self.retired += 1;\n }\n\n // If all command buffers are retired, broadcast our condition so all pending acquires return an\n // error. Otherwise signal at least one pending acquire to continue.\n if (self.retired == self.buffers.capacity) {\n self.condition.broadcast();\n } else {\n self.condition.signal();\n }\n}\n\n/// Gets a slice of all command buffers that may have been written to since the last reset.\npub fn written(self: *@This()) []CmdBuf {\n self.checkAssertions();\n return self.buffers.items.ptr[self.buffers.items.len..self.buffers.capacity];\n}\n\n/// Resets the command pool. Asserts that all command buffers have already been reset.\npub fn reset(self: *@This()) void {\n // Check assertions\n self.checkAssertions();\n if (std.debug.runtime_safety) for (self.written()) |cb| assert(cb.isEmpty());\n\n // Warn if we used too many command buffers\n const cap: f32 = @floatFromInt(self.buffers.capacity);\n const used: f32 = @floatFromInt(self.written().len);\n const usage = used / cap;\n if (usage > self.warn_ratio) {\n log.warn(\n \"more than {d}% command pool buffers used, consider incresing reserved count\",\n .{self.warn_ratio},\n );\n }\n\n // If a name is configured, emit a Tracy plot\n if (self.name) |name| {\n tracy.plot(.{\n .name = name,\n .value = .{ .f32 = usage * 100.0 },\n });\n }\n\n // Reset the command pool\n self.buffers.items.len = self.buffers.capacity;\n self.released.items.len = 0;\n self.retired = 0;\n}\n\n/// Asserts that all command buffers have been released.\npub fn checkAssertions(self: *@This()) void {\n assert(self.released.items.len + self.retired == self.buffers.capacity - self.buffers.items.len);\n}\n"], ["/ZCS/src/ext/Transform2D.zig", "//! A component that tracks the position and orientation of an entity in 2D. Hierarchical\n//! relationships formed by the `Node` component are respected if present.\n//!\n//! You can synchronize a transform's `world_from_model` field, and the `world_from_model` fields of\n//! all its relative children by calling `sync`. This is necessary when modifying the transform, or\n//! changing the hierarchy by adding or removing a transform.\n//!\n//! To alleviate this burden, a number of setters are provided that call `sync` for you, and command\n//! buffer integration is provided for automatically calling sync when transforms are added and\n//! removed.\n//!\n//! For more information on command buffer integration, see `exec`.\n//!\n//! If you need features not provided by this implementation, for example a third dimension, you're\n//! encouraged to use this as a reference for your own transform component.\n\nconst std = @import(\"std\");\nconst zcs = @import(\"../root.zig\");\nconst tracy = @import(\"tracy\");\n\nconst math = std.math;\nconst assert = std.debug.assert;\nconst typeId = zcs.typeId;\n\nconst Entity = zcs.Entity;\nconst Entities = zcs.Entities;\nconst CmdBuf = zcs.CmdBuf;\nconst Any = zcs.Any;\nconst PointerLock = zcs.PointerLock;\nconst Node = zcs.ext.Node;\nconst Vec2 = zcs.ext.geom.Vec2;\nconst Rotor2 = zcs.ext.geom.Rotor2;\nconst Mat2x3 = zcs.ext.geom.Mat2x3;\n\nconst Zone = tracy.Zone;\n\nconst Transform2D = @This();\n\n/// The transform's local position.\npos: Vec2 = .zero,\n/// The transform's local orientation.\nrot: Rotor2 = .identity,\n/// The transform's world from model matrix.\nworld_from_model: Mat2x3 = .identity,\n/// Whether or not this transform's space is relative to its parent.\nrelative: bool = true,\n\n/// Move the transform in local space by `delta` and then calls `sync`.\npub fn move(self: *@This(), es: *const Entities, delta: Vec2) void {\n self.pos.add(delta);\n self.sync(es);\n}\n\n/// Set the local position to `pos` and then calls `sync`.\npub fn setPos(self: *@This(), es: *const Entities, pos: Vec2) void {\n self.pos = pos;\n self.sync(es);\n}\n\n/// Rotates the local space and then calls `sync`.\npub fn rotate(self: *@This(), es: *const Entities, rotation: Rotor2) void {\n self.rot.mul(rotation);\n self.sync(es);\n}\n\n/// Sets the local orientation to `rot` and then calls `sync`.\npub fn setRot(self: *@This(), es: *const Entities, rot: Rotor2) void {\n self.rot = rot;\n self.sync(es);\n}\n\n/// Returns the world space position.\npub inline fn getWorldPos(self: @This()) Vec2 {\n return self.world_from_model.getTranslation();\n}\n\n/// Updates the `world_from_model` matrix on this transform, and all of its transitive relative\n/// children.\npub fn sync(self: *@This(), es: *const Entities) void {\n var transforms = self.preOrderIterator(es);\n while (transforms.next(es)) |transform| {\n const translation: Mat2x3 = .translation(transform.pos);\n const rotation: Mat2x3 = .rotation(transform.rot);\n const parent_world_from_model = transform.getRelativeWorldFromModel(es);\n transform.world_from_model = rotation.applied(translation).applied(parent_world_from_model);\n }\n}\n\n/// Returns the parent's world form model matrix, or identity if not relative.\npub inline fn getRelativeWorldFromModel(self: *const @This(), es: *const Entities) Mat2x3 {\n if (!self.relative) return .identity;\n const node = es.getComp(self, Node) orelse return .identity;\n const parent = node.parent.unwrap() orelse return .identity;\n const parent_transform = parent.get(es, Transform2D) orelse return .identity;\n return parent_transform.world_from_model;\n}\n\n/// Returns the forward direction of this transform.\npub fn getForward(self: *const @This()) Vec2 {\n return self.world_from_model.timesDir(.y_pos);\n}\n\n/// Returns a pre-order iterator over the subtree of relative transforms starting at `self`. This\n/// will visit parents before children, and it will include `self`.\npub fn preOrderIterator(self: *@This(), es: *const Entities) PreOrderIterator {\n return .{\n .parent = self,\n .children = if (es.getComp(self, Node)) |node| node.preOrderIterator(es) else .empty,\n .pointer_lock = es.pointer_generation.lock(),\n };\n}\n\n/// A pre-order iterator over relative transforms.\npub const PreOrderIterator = struct {\n parent: ?*Transform2D,\n children: Node.PreOrderIterator,\n pointer_lock: PointerLock,\n\n /// Returns the next transform.\n pub fn next(self: *@This(), es: *const Entities) ?*Transform2D {\n self.pointer_lock.check(es.pointer_generation);\n\n if (self.parent) |parent| {\n self.parent = null;\n return parent;\n }\n\n while (self.children.next(es)) |node| {\n // If the next child has a transform and that transform is relative to its parent,\n // return it.\n if (es.getComp(node, Transform2D)) |transform| {\n if (transform.relative) {\n return transform;\n }\n }\n // Otherwise, skip this subtree.\n self.children.skipSubtree(es, node);\n }\n\n return null;\n }\n};\n\n/// `Exec` provides helpers for processing hierarchy changes via the command buffer.\n///\n/// By convention, `Exec` only calls into the stable public interface of the types it's working\n/// with. As such, documentation is sparse. You are welcome to call these methods directly, or\n/// use them as reference for implementing your own command buffer iterator.\npub const Exec = struct {\n /// Similar to `Node.Exec.immediate`, but marks transforms as dirty as needed.\n pub fn immediate(es: *Entities, cb: *CmdBuf) void {\n immediateOrErr(es, cb) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `immediate`, but returns an error on failure instead of panicking. On error the\n /// commands are left partially evaluated.\n pub fn immediateOrErr(\n es: *Entities,\n cb: *CmdBuf,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow, ZcsEntityOverflow }!void {\n var default_exec: CmdBuf.Exec = .init();\n\n es.pointer_generation.increment();\n\n var batches = cb.iterator();\n while (batches.next()) |batch| {\n switch (batch) {\n .arch_change => |arch_change| {\n {\n var delta: CmdBuf.Batch.ArchChange.Delta = .{};\n var ops = arch_change.iterator();\n while (ops.next()) |op| {\n Node.Exec.beforeArchChangeImmediate(es, arch_change, op);\n delta.updateImmediate(op);\n }\n\n _ = arch_change.execImmediate(es, delta);\n }\n\n {\n var ops = arch_change.iterator();\n while (ops.next()) |op| {\n afterArchChangeImmediate(es, arch_change, op);\n }\n }\n },\n .ext => |ext| {\n try extImmediateOrErr(es, ext);\n default_exec.extImmediateOrErr(ext);\n },\n }\n }\n\n try default_exec.finish(cb, es);\n }\n\n /// Call this after executing a command.\n pub inline fn afterArchChangeImmediate(\n es: *Entities,\n batch: CmdBuf.Batch.ArchChange,\n op: CmdBuf.Batch.ArchChange.Op,\n ) void {\n switch (op) {\n .add => |comp| if (comp.id == typeId(Transform2D)) {\n if (batch.entity.get(es, Transform2D)) |transform| {\n transform.sync(es);\n }\n },\n .remove => |id| {\n if (id == typeId(Node)) {\n if (batch.entity.get(es, Transform2D)) |transform| {\n transform.sync(es);\n }\n } else if (id == typeId(Transform2D)) {\n if (batch.entity.get(es, Node)) |node| {\n var children = node.childIterator();\n while (children.next(es)) |child| {\n if (es.getComp(child, Transform2D)) |child_transform| {\n child_transform.sync(es);\n }\n }\n }\n }\n },\n else => {},\n }\n }\n\n /// Call this to process an extension command.\n pub inline fn extImmediateOrErr(\n es: *Entities,\n payload: Any,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!void {\n try Node.Exec.extImmediateOrErr(es, payload);\n if (payload.as(Node.SetParent)) |set_parent| {\n if (set_parent.child.get(es, Transform2D)) |transform| {\n transform.sync(es);\n }\n }\n }\n};\n"], ["/ZCS/bench/main.zig", "const std = @import(\"std\");\nconst zcs = @import(\"zcs\");\nconst tracy = @import(\"tracy\");\n\nconst assert = std.debug.assert;\n\nconst Entities = zcs.Entities;\nconst Entity = zcs.Entity;\nconst CmdBuf = zcs.CmdBuf;\nconst Transform2D = zcs.ext.Transform2D;\nconst ZoneCmd = zcs.ext.ZoneCmd;\n\nconst Zone = tracy.Zone;\n\nconst max_entities = 1000000;\nconst iterations = 10;\n\npub const std_options: std.Options = .{\n .log_level = .info,\n};\n\npub const tracy_impl = @import(\"tracy_impl\");\npub const tracy_options: tracy.Options = .{\n .default_callstack_depth = 8,\n};\n\nconst small = false;\nconst A = if (small) u2 else u64;\nconst B = if (small) u4 else u128;\nconst C = if (small) u8 else u256;\n\n// Eventually we may make reusable benchmarks for comparing releases. Right now this is just a\n// dumping ground for testing performance tweaks.\npub fn main() !void {\n var gpa = std.heap.GeneralPurposeAllocator(.{ .thread_safe = false }){};\n const allocator = gpa.allocator();\n\n var expected_total: ?u256 = null;\n var expected_ra_total: ?u256 = null;\n\n for (0..iterations) |_| {\n var es: Entities = try .init(.{\n .gpa = allocator,\n .cap = .{\n .entities = max_entities,\n .arches = 1,\n .chunks = 4096,\n .chunk = 65536,\n },\n .warn_ratio = 1.0,\n });\n defer es.deinit(allocator);\n\n // also compare interning vs not etc\n {\n const fill_zone = Zone.begin(.{ .name = \"fill immediate any\", .src = @src() });\n for (0..max_entities) |i| {\n const e = Entity.reserveImmediate(&es);\n const a: A = @intCast(i);\n const b: B = @intCast(i);\n const c: C = @intCast(i);\n assert(e.changeArchAnyImmediate(&es, .{ .add = &.{\n .init(A, &a),\n .init(B, &b),\n .init(C, &c),\n } }) catch |err| @panic(@errorName(err)));\n }\n fill_zone.end();\n }\n }\n\n for (0..iterations) |_| {\n var es: Entities = try .init(.{\n .gpa = allocator,\n .cap = .{\n .entities = max_entities,\n .arches = 1,\n .chunks = 4096,\n .chunk = 65536,\n },\n .warn_ratio = 1.0,\n });\n defer es.deinit(allocator);\n\n // also compare interning vs not etc\n {\n es.updateStats();\n const fill_zone = Zone.begin(.{ .name = \"fill immediate\", .src = @src() });\n for (0..max_entities) |i| {\n const e = Entity.reserveImmediate(&es);\n assert(e.changeArchImmediate(\n &es,\n struct { A, B, C },\n .{\n .add = .{ @intCast(i), @intCast(i), @intCast(i) },\n },\n ));\n }\n fill_zone.end();\n es.updateStats();\n }\n }\n\n for (0..iterations) |_| {\n var tags: std.ArrayListUnmanaged(u8) = try .initCapacity(allocator, max_entities * 4);\n defer tags.deinit(allocator);\n var args: std.ArrayListUnmanaged(u64) = try .initCapacity(allocator, max_entities * 4);\n defer args.deinit(allocator);\n var bytes: std.ArrayListUnmanaged(u8) = try .initCapacity(allocator, max_entities * @sizeOf(C) * 3);\n defer bytes.deinit(allocator);\n\n {\n var last: ?usize = null;\n const fill_zone = Zone.begin(.{ .name = \"baseline fill separate\", .src = @src() });\n for (0..max_entities) |i| {\n const a: A = @intCast(i);\n const b: B = @intCast(i);\n const c: C = @intCast(i);\n\n if (i != last) {\n // assert(args.items.len < args.capacity) implied by tags check\n if (tags.items.len >= tags.capacity) @panic(\"OOB\");\n last = i;\n tags.appendAssumeCapacity(10);\n args.appendAssumeCapacity(i);\n }\n\n if (tags.items.len >= tags.capacity) @panic(\"OOB\");\n tags.appendAssumeCapacity(0);\n // if (args.items.len >= args.capacity) @panic(\"OOB\"); // Implied by tags check\n args.appendAssumeCapacity(@intFromPtr(zcs.typeId(A)));\n bytes.items.len = std.mem.alignForward(\n usize,\n bytes.items.len,\n @alignOf(A),\n );\n if (bytes.items.len + @sizeOf(A) > bytes.capacity) @panic(\"OOB\");\n bytes.appendSliceAssumeCapacity(std.mem.asBytes(&a));\n\n if (tags.items.len >= tags.capacity) @panic(\"OOB\");\n tags.appendAssumeCapacity(0);\n // if (args.items.len >= args.capacity) @panic(\"OOB\"); // Implied by tags check\n args.appendAssumeCapacity(@intFromPtr(zcs.typeId(B)));\n bytes.items.len = std.mem.alignForward(\n usize,\n bytes.items.len,\n @alignOf(B),\n );\n if (bytes.items.len + @sizeOf(B) > bytes.capacity) @panic(\"OOB\");\n bytes.appendSliceAssumeCapacity(std.mem.asBytes(&b));\n\n if (tags.items.len >= tags.capacity) @panic(\"OOB\");\n tags.appendAssumeCapacity(0);\n // if (args.items.len >= args.capacity) @panic(\"OOB\"); // Implied by tags check\n args.appendAssumeCapacity(@intFromPtr(zcs.typeId(C)));\n bytes.items.len = std.mem.alignForward(\n usize,\n bytes.items.len,\n @alignOf(C),\n );\n if (bytes.items.len + @sizeOf(C) > bytes.capacity) @panic(\"OOB\");\n bytes.appendSliceAssumeCapacity(std.mem.asBytes(&c));\n }\n fill_zone.end();\n }\n }\n\n for (0..iterations) |_| {\n var es: Entities = try .init(.{\n .gpa = allocator,\n .cap = .{\n .entities = max_entities,\n .arches = 64,\n .chunks = 4096,\n .chunk = 65536,\n },\n .warn_ratio = 1.0,\n });\n defer es.deinit(allocator);\n\n var cb: CmdBuf = try .init(.{\n .name = \"cmd buf\",\n .gpa = allocator,\n .es = &es,\n .cap = .{\n .cmds = max_entities * 3,\n .reserved_entities = max_entities,\n },\n });\n defer cb.deinit(allocator, &es);\n\n {\n const fill_fast_zone = Zone.begin(.{ .name = \"fill cb\", .src = @src() });\n defer fill_fast_zone.end();\n for (0..max_entities) |i| {\n const e = Entity.reserve(&cb);\n e.add(&cb, A, @intCast(i));\n e.add(&cb, B, @intCast(i));\n e.add(&cb, C, @intCast(i));\n }\n }\n }\n\n for (0..iterations) |_| {\n const alloc_zone = Zone.begin(.{ .name = \"alloc\", .src = @src() });\n\n const alloc_es_zone = Zone.begin(.{ .name = \"es\", .src = @src() });\n var es: Entities = try .init(.{\n .gpa = allocator,\n .cap = .{\n .entities = max_entities * 2,\n .arches = 64,\n .chunks = 4096,\n .chunk = 65536,\n },\n .warn_ratio = 1.0,\n });\n defer es.deinit(allocator);\n alloc_es_zone.end();\n\n const alloc_cb_zone = Zone.begin(.{ .name = \"cb\", .src = @src() });\n var cb: CmdBuf = try .init(.{\n .name = \"cmd buf\",\n .gpa = allocator,\n .es = &es,\n .cap = .{\n .cmds = max_entities * 4,\n .reserved_entities = max_entities,\n },\n .warn_ratio = 1.0,\n });\n defer cb.deinit(allocator, &es);\n alloc_cb_zone.end();\n\n alloc_zone.end();\n\n {\n const cmdbuf_zone = Zone.begin(.{ .name = \"cb\", .src = @src() });\n defer cmdbuf_zone.end();\n {\n const fill_zone = Zone.begin(.{ .name = \"fill\", .src = @src() });\n defer fill_zone.end();\n\n // Divided into two parts to test exec zones\n const exec_zone = ZoneCmd.begin(&cb, .{\n .src = @src(),\n .name = \"exec zone\",\n });\n defer exec_zone.end(&cb);\n\n {\n const first_half_zone = ZoneCmd.begin(&cb, .{\n .src = @src(),\n .name = \"first half\",\n });\n defer first_half_zone.end(&cb);\n for (0..max_entities / 2) |i| {\n const e = Entity.reserve(&cb);\n e.add(&cb, A, @intCast(i));\n e.add(&cb, B, @intCast(i));\n e.add(&cb, C, @intCast(i));\n }\n }\n {\n const second_half_zone = ZoneCmd.begin(&cb, .{\n .src = @src(),\n .name = \"second half\",\n });\n defer second_half_zone.end(&cb);\n for (max_entities / 2..max_entities) |i| {\n const e = Entity.reserve(&cb);\n e.add(&cb, A, @intCast(i));\n e.add(&cb, B, @intCast(i));\n e.add(&cb, C, @intCast(i));\n }\n }\n }\n CmdBuf.Exec.immediate(&es, &cb);\n }\n\n {\n var total: u256 = 0;\n {\n const iter_zone = Zone.begin(.{ .name = \"iter.fast\", .src = @src() });\n defer iter_zone.end();\n var iter = es.iterator(struct { a: *const A, b: *const B, c: *const C });\n while (iter.next(&es)) |vw| {\n total +%= vw.a.*;\n total +%= vw.b.*;\n total +%= vw.c.*;\n }\n }\n std.debug.print(\"{}\\n\", .{total});\n if (expected_total == null) expected_total = total;\n if (expected_total != total) @panic(\"inconsistent result\");\n }\n\n {\n var total: u256 = 0;\n es.forEach(\"sum\", sum, .{ .total = &total });\n std.debug.print(\"{}\\n\", .{total});\n if (expected_total == null) expected_total = total;\n if (expected_total != total) @panic(\"inconsistent result\");\n }\n\n {\n const zone = Zone.begin(.{ .src = @src(), .name = \"sum threaded\" });\n defer zone.end();\n\n var tp: std.Thread.Pool = undefined;\n try std.Thread.Pool.init(&tp, .{\n .allocator = allocator,\n });\n defer tp.deinit();\n var wg: std.Thread.WaitGroup = .{};\n es.forEachThreaded(\"sum threaded\", sumThreaded, .{\n .tp = &tp,\n .wg = &wg,\n .ctx = .{},\n .cp = null,\n });\n tp.waitAndWork(&wg);\n }\n\n {\n var total: u256 = 0;\n {\n const iter_zone = Zone.begin(.{ .name = \"iter.view\", .src = @src() });\n defer iter_zone.end();\n var iter = es.iterator(struct { e: Entity });\n while (iter.next(&es)) |vw| {\n const comps = vw.e.view(&es, struct {\n a: *const A,\n b: *const B,\n c: *const C,\n }).?;\n total +%= comps.a.*;\n total +%= comps.b.*;\n total +%= comps.c.*;\n }\n }\n std.debug.print(\"{}\\n\", .{total});\n if (expected_total == null) expected_total = total;\n if (expected_total != total) @panic(\"inconsistent result\");\n }\n\n {\n var total: u256 = 0;\n {\n const iter_zone = Zone.begin(.{ .name = \"iter.get\", .src = @src() });\n defer iter_zone.end();\n var iter = es.iterator(struct { e: Entity });\n while (iter.next(&es)) |vw| {\n total +%= vw.e.get(&es, A).?.*;\n total +%= vw.e.get(&es, B).?.*;\n total +%= vw.e.get(&es, C).?.*;\n }\n }\n std.debug.print(\"{}\\n\", .{total});\n if (expected_total == null) expected_total = total;\n if (expected_total != total) @panic(\"inconsistent result\");\n }\n\n {\n var total: u256 = 0;\n var default_rng: std.Random.DefaultPrng = .init(0);\n const rand = default_rng.random();\n {\n const iter_zone = Zone.begin(.{ .name = \"es.random access\", .src = @src() });\n defer iter_zone.end();\n for (0..max_entities / 2) |_| {\n const ei: Entity.Index = @enumFromInt(rand.uintLessThan(u32, max_entities));\n const e = ei.toEntity(&es);\n const comps = e.view(&es, struct {\n a: *const A,\n b: *const B,\n c: *const C,\n }).?;\n total +%= comps.a.*;\n total +%= comps.b.*;\n total +%= comps.c.*;\n }\n }\n std.debug.print(\"ecs ra: {}\\n\", .{total});\n if (expected_ra_total == null) expected_ra_total = total;\n if (expected_ra_total != total) @panic(\"inconsistent result\");\n }\n }\n\n for (0..iterations) |_| {\n const zone = Zone.begin(.{ .name = \"transform\", .src = @src() });\n defer zone.end();\n\n const es_init_zone = Zone.begin(.{ .name = \"es init\", .src = @src() });\n var es: Entities = try .init(.{\n .gpa = allocator,\n .cap = .{\n .entities = max_entities,\n .arches = 64,\n .chunks = 4096,\n .chunk = 65536,\n },\n .warn_ratio = 1.0,\n });\n defer es.deinit(allocator);\n es_init_zone.end();\n\n {\n const entity_init_zone = Zone.begin(.{ .name = \"entity init\", .src = @src() });\n defer entity_init_zone.end();\n for (0..max_entities) |_| {\n assert(Entity.reserveImmediate(&es).changeArchImmediate(\n &es,\n struct { Transform2D },\n .{ .add = .{.{}} },\n ));\n }\n }\n\n {\n const queue_zone = Zone.begin(.{ .name = \"move\", .src = @src() });\n defer queue_zone.end();\n var iter = es.iterator(struct { transform: *Transform2D });\n var f: f32 = 0;\n while (iter.next(&es)) |vw| {\n vw.transform.move(&es, .{ .x = f, .y = f });\n f += 0.01;\n }\n }\n }\n\n for (0..iterations) |_| {\n const alloc_zone = Zone.begin(.{ .name = \"mal.alloc\", .src = @src() });\n var es: std.MultiArrayList(struct {\n a: A,\n b: B,\n c: C,\n }) = .empty;\n defer es.deinit(std.heap.page_allocator);\n try es.setCapacity(std.heap.page_allocator, max_entities);\n alloc_zone.end();\n\n {\n const fill_zone = Zone.begin(.{ .name = \"mal.fill\", .src = @src() });\n defer fill_zone.end();\n for (0..max_entities) |i| {\n es.appendAssumeCapacity(.{\n .a = @intCast(i),\n .b = @intCast(i),\n .c = @intCast(i),\n });\n }\n }\n\n {\n var total: u256 = 0;\n {\n const iter_zone = Zone.begin(.{ .name = \"mal.iter\", .src = @src() });\n defer iter_zone.end();\n for (es.items(.a), es.items(.b), es.items(.c)) |*a, *b, *c| {\n total +%= a.*;\n total +%= b.*;\n total +%= c.*;\n }\n }\n std.debug.print(\"{}\\n\", .{total});\n if (expected_total == null) expected_total = total;\n if (expected_total != total) @panic(\"inconsistent result\");\n }\n\n {\n var total: u256 = 0;\n var default_rng: std.Random.DefaultPrng = .init(0);\n const rand = default_rng.random();\n {\n const iter_zone = Zone.begin(.{ .name = \"mal.random access\", .src = @src() });\n defer iter_zone.end();\n for (0..max_entities) |_| {\n const i = max_entities - rand.uintLessThan(u32, max_entities);\n const comps = es.get(i);\n total +%= comps.a;\n total +%= comps.b;\n total +%= comps.c;\n }\n }\n std.debug.print(\"mal ra: {}\\n\", .{total});\n }\n }\n}\n\nfn sum(ctx: struct { total: *u256 }, a: *const A, b: *const B, c: *const C) void {\n const total = ctx.total;\n total.* += a.*;\n total.* += b.*;\n total.* += c.*;\n}\n\n// This isn't expensive enough to be worth threading, but when you modify it to do more work it becomes worth it\nthreadlocal var thread_sum: u256 = 0;\nfn sumThreaded(_: struct {}, a: *const A, b: *const B, c: *const C) void {\n thread_sum += a.*;\n thread_sum += b.*;\n thread_sum += c.*;\n}\n"], ["/ZCS/src/Entities.zig", "//! Storage for entities.\n//!\n//! See `SlotMap` for how handle safety works.\n//!\n//! See `README.md` for more information.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\nconst tracy = @import(\"tracy\");\n\nconst Allocator = std.mem.Allocator;\n\nconst Zone = tracy.Zone;\n\nconst log = std.log;\n\nconst zcs = @import(\"root.zig\");\nconst typeId = zcs.typeId;\nconst Any = zcs.Any;\nconst CompFlag = zcs.CompFlag;\nconst Entity = zcs.Entity;\nconst PointerLock = zcs.PointerLock;\nconst TypeId = zcs.TypeId;\nconst ChunkList = zcs.ChunkList;\nconst ChunkPool = zcs.ChunkPool;\nconst Chunk = zcs.Chunk;\nconst HandleTab = zcs.HandleTab;\nconst Arches = zcs.Arches;\nconst CmdBuf = zcs.CmdBuf;\nconst CmdPool = zcs.CmdPool;\nconst view = zcs.view;\n\nconst Entities = @This();\n\nhandle_tab: HandleTab,\narches: Arches,\npointer_generation: PointerLock.Generation = .{},\nreserved_entities: usize = 0,\nchunk_pool: ChunkPool,\nwarned_saturated: u64 = 0,\nwarned_capacity: bool = false,\nwarned_chunk_pool: bool = false,\nwarned_arches: bool = false,\nwarn_ratio: f32,\n\nconst tracy_es_committed = \"zcs: committed entities\";\nconst tracy_es_reserved = \"zcs: reserved entities\";\nconst tracy_es_saturated = \"zcs: saturated entities\";\nconst tracy_chunks = \"zcs: reserved chunks\";\nconst tracy_arches = \"zcs: archetypes\";\n\n/// Options for `init`.\npub const InitOptions = struct {\n /// Used to allocate the entity storage.\n gpa: Allocator,\n /// The capacity of the entity storage.\n cap: Capacity = .{},\n /// When usage of preallocated buffers exceeds this ratio of full capacity, emit a warning.\n warn_ratio: f32 = 0.2,\n};\n\n/// The capacity of `Entities`.\npub const Capacity = struct {\n /// The max number of entities.\n entities: u32 = 1000000,\n /// The max number of archetypes.\n arches: u32 = 64,\n /// The number of chunks to allocate.\n chunks: u16 = 4096,\n /// The size of a single chunk in bytes.\n chunk: u32 = 65536,\n};\n\n/// Initializes the entity storage with the given capacity.\npub fn init(options: InitOptions) Allocator.Error!@This() {\n const zone = Zone.begin(.{ .src = @src() });\n defer zone.end();\n\n var handle_tab: HandleTab = try .init(options.gpa, options.cap.entities);\n errdefer handle_tab.deinit(options.gpa);\n\n var chunk_pool: ChunkPool = try .init(options.gpa, .{\n .chunks = options.cap.chunks,\n .chunk = options.cap.chunk,\n });\n errdefer chunk_pool.deinit(options.gpa);\n\n var arches: Arches = try .init(options.gpa, options.cap.arches);\n errdefer arches.deinit(options.gpa);\n\n if (tracy.enabled) {\n var buf: [1024]u8 = undefined;\n const info = std.fmt.bufPrintZ(\n &buf,\n \"{}\",\n .{options},\n ) catch @panic(\"OOB\");\n tracy.appInfo(info);\n\n for ([_][:0]const u8{\n tracy_es_committed,\n tracy_es_reserved,\n tracy_es_saturated,\n tracy_chunks,\n tracy_arches,\n }) |name| {\n tracy.plotConfig(.{\n .name = name,\n .format = .number,\n .mode = .line,\n .fill = true,\n });\n }\n }\n\n return .{\n .handle_tab = handle_tab,\n .arches = arches,\n .chunk_pool = chunk_pool,\n .warn_ratio = options.warn_ratio,\n };\n}\n\n/// Destroys the entity storage.\npub fn deinit(self: *@This(), gpa: Allocator) void {\n self.arches.deinit(gpa);\n self.chunk_pool.deinit(gpa);\n self.handle_tab.deinit(gpa);\n self.* = undefined;\n}\n\n/// Destroys all entities matching the given arch immediately.\npub fn destroyArchImmediate(self: *@This(), arch: CompFlag.Set) void {\n self.pointer_generation.increment();\n var chunk_lists_iter = self.arches.iterator(self, arch);\n while (chunk_lists_iter.next(self)) |chunk_list| {\n var chunk_list_iter = chunk_list.iterator(self);\n while (chunk_list_iter.next(self)) |chunk| {\n var chunk_iter = chunk.iterator(self);\n while (chunk_iter.next(self)) |entity| {\n self.handle_tab.remove(entity.key);\n }\n chunk.clear(self);\n }\n }\n}\n\n/// Recycles all entities compatible with the given archetype. This causes their handles to be\n/// dangling, prefer `destroyArchImmediate` unless you're implementing a high throughput event\n/// system.\n///\n/// Invalidates pointers.\npub fn recycleArchImmediate(self: *@This(), arch: CompFlag.Set) void {\n self.pointer_generation.increment();\n var chunk_lists_iter = self.arches.iterator(self, arch);\n while (chunk_lists_iter.next(self)) |chunk_list| {\n var chunk_list_iter = chunk_list.iterator(self);\n while (chunk_list_iter.next(self)) |chunk| {\n var chunk_iter = chunk.iterator(self);\n while (chunk_iter.next(self)) |entity| {\n self.handle_tab.recycle(entity.key);\n }\n chunk.clear(self);\n }\n }\n}\n\n/// Recycles all entities.\n///\n/// Invalidates pointers.\npub fn recycleImmediate(self: *@This()) void {\n self.pointer_generation.increment();\n self.handle_tab.recycleAll();\n self.reserved_entities = 0;\n}\n\n/// Returns the current number of entities.\npub fn count(self: *const @This()) usize {\n return self.handle_tab.count() - self.reserved_entities;\n}\n\n/// Returns the number of reserved but not committed entities that currently exist.\npub fn reserved(self: *const @This()) usize {\n return self.reserved_entities;\n}\n\n/// Given a pointer to a non zero sized component, returns the corresponding entity.\npub fn getEntity(es: *const Entities, from_comp: anytype) Entity {\n const T = @typeInfo(@TypeOf(from_comp)).pointer.child;\n\n // We could technically pack the entity into the pointer value since both are typically 64\n // bits. However, this would break support for getting a slice of zero sized components from\n // a chunk since all would have the same address.\n //\n // I've chosen to support the slice use case and not this one as it's simpler and seems\n // slightly more likely to come up in generic code. I don't expect either to come up\n // particularly often, this decision can be reversed in the future if one or the other turns\n // out to be desirable. If we do this, make sure to have an assertion/test that valid\n // entities are never fully zero since non optional pointers can't be zero unless explicitly\n // annotated as such.\n comptime assert(@sizeOf(T) != 0);\n\n return getEntityFromAny(es, .init(T, from_comp));\n}\n\n/// Similar to `getEntity`, but does not require compile time types. Assumes a valid pointer to a\n/// non zero sized component.\npub fn getEntityFromAny(es: *const Entities, from_comp: Any) Entity {\n // Get the entity index from the chunk\n const loc = getLoc(es, from_comp);\n const indices = loc.chunk.view(es, struct { indices: []const Entity.Index }).?.indices;\n const entity_index = indices[@intFromEnum(loc.index_in_chunk)];\n\n // Get the entity handle\n assert(@intFromEnum(entity_index) < es.handle_tab.next_index);\n const entity = entity_index.toEntity(es);\n\n // Assert that the entity has been committed and return it\n assert(entity.committed(es));\n return entity;\n}\n\n/// Given a valid pointer to a non zero sized component `from`, returns the corresponding\n/// component `Result`, or `null` if there isn't one attached to the same entity. See also\n/// `Entity.get`.\npub fn getComp(es: *const Entities, from: anytype, Result: type) ?*Result {\n const T = @typeInfo(@TypeOf(from)).pointer.child;\n // See `from` for why this isn't allowed.\n comptime assert(@sizeOf(T) != 0);\n const slice = getCompFromAny(es, .init(T, from), typeId(Result));\n return @ptrCast(@alignCast(slice));\n}\n\n/// Similar to `getComp`, but does not require compile time types.\npub fn getCompFromAny(self: *const Entities, from_comp: Any, get_comp_id: TypeId) ?[]u8 {\n // Check assertions\n if (std.debug.runtime_safety) {\n _ = self.getEntityFromAny(from_comp);\n }\n\n // Get the component\n const flag = get_comp_id.comp_flag orelse return null;\n const loc = self.getLoc(from_comp);\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const comp_buf_offset = loc.chunk.header().comp_buf_offsets.values[@intFromEnum(flag)];\n if (comp_buf_offset == 0) return null;\n const unsized: [*]u8 = @ptrFromInt(@intFromPtr(loc.chunk) +\n comp_buf_offset +\n get_comp_id.size * @intFromEnum(loc.index_in_chunk));\n return unsized[0..get_comp_id.size];\n}\n\n/// Looks up the location of an entity from a component.\nfn getLoc(self: *const Entities, from_comp: Any) struct {\n chunk: *Chunk,\n index_in_chunk: Entity.Location.IndexInChunk,\n} {\n // See `from` for why this isn't allowed\n assert(from_comp.id.size != 0);\n\n const pool = &self.chunk_pool;\n const flag = from_comp.id.comp_flag.?;\n\n // Make sure this component is actually in the chunk pool\n assert(@intFromPtr(from_comp.ptr) >= @intFromPtr(pool.buf.ptr));\n assert(@intFromPtr(from_comp.ptr) <= @intFromPtr(&pool.buf[pool.buf.len - 1]));\n\n // Get the corresponding chunk by rounding down to the chunk alignment. This works as chunks\n // are aligned to their size, in part to support this operation.\n const chunk: *Chunk = @ptrFromInt(pool.size_align.backward(@intFromPtr(from_comp.ptr)));\n\n // Calculate the index in this chunk that this component is at\n assert(chunk.header().arch(&self.arches).contains(flag));\n const comp_offset = @intFromPtr(from_comp.ptr) - @intFromPtr(chunk);\n assert(comp_offset != 0); // Zero when missing\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const comp_buf_offset = chunk.header().comp_buf_offsets.values[@intFromEnum(flag)];\n const index_in_chunk = @divExact(comp_offset - comp_buf_offset, from_comp.id.size);\n\n return .{\n .chunk = chunk,\n .index_in_chunk = @enumFromInt(index_in_chunk),\n };\n}\n\n/// Calls `updateEntity` on each compatible entity in an implementation defined order.\n/// See also `forEachChunk`.\n///\n/// `updateEntity` should take `ctx` as an argument, followed by any number of component pointers,\n/// optional component pointers, or `Entity`s.\n///\n/// Invalidating pointers from the update function results in safety checked illegal behavior.\n///\n/// Note that the implementation only relies on ZCS's public interface. If you have a use case that\n/// isn't served well by `forEach`, you can fork it into your code base and modify it as needed.\npub fn forEach(\n self: *@This(),\n comptime name: [:0]const u8,\n comptime updateEntity: anytype,\n ctx: view.params(@TypeOf(updateEntity))[0],\n) void {\n const zone = Zone.begin(.{ .src = @src(), .name = name });\n defer zone.end();\n const params = view.params(@TypeOf(updateEntity));\n const View = view.Tuple(params[1..]);\n var iter = self.iterator(View);\n while (iter.next(self)) |vw| {\n @call(.auto, updateEntity, .{ctx} ++ vw);\n }\n}\n\n/// Prefer `forEach`. Calls `updateChunk` on each compatible chunk in an implementation\n/// defined order, may be useful for batch optimizations.\n///\n/// `updateChunk` should take `ctx` as an argument, followed by any number of component slices,\n/// optional component slices, or const slices of `Entity.Index`.\n///\n/// Invalidating pointers from the update function results in safety checked illegal behavior.\npub fn forEachChunk(\n self: *@This(),\n comptime name: [:0]const u8,\n comptime updateChunk: anytype,\n ctx: view.params(@TypeOf(updateChunk))[0],\n) void {\n const zone = Zone.begin(.{ .src = @src(), .name = name });\n defer zone.end();\n const params = view.params(@TypeOf(updateChunk));\n const required_comps = view.comps(view.Tuple(params[1..]), .{ .size = .slice }) orelse return;\n var chunks = self.chunkIterator(required_comps);\n while (chunks.next(self)) |chunk| {\n const chunk_view = chunk.view(self, view.Tuple(params[1..])).?;\n @call(.auto, updateChunk, .{ctx} ++ chunk_view);\n }\n}\n\n/// Options for `forEachThreaded`.\npub fn ForEachThreadedOptions(f: type) type {\n return struct {\n const acquire_cb = view.params(f)[1] == *CmdBuf;\n const Ctx = view.params(f)[0];\n const Comps = view.Tuple(view.params(f)[if (acquire_cb) 2 else 1..]);\n\n ctx: Ctx,\n tp: *std.Thread.Pool,\n wg: *std.Thread.WaitGroup,\n cp: ?*CmdPool,\n };\n}\n\n/// Similar to `forEach`, but spawns each chunk's work as a thread pool task. Optionally, you may\n/// add an argument of type `*CmdBuf` as the second argument to get a command buffer if `cp` is set\n/// in `options`.\n///\n/// Each chunk may be given its own command buffer in an arbitrary order. As such, the order of\n/// commands within a chunk (and therefore within an `updateEntity` callback) are guaranteed to be\n/// serial, but no guarantees are made about command execution order between chunks.\n///\n/// Keep in mind that this is unlikely to be a performance win unless your update function is very\n/// expensive. Iteration is cheap.\npub fn forEachThreaded(\n self: *@This(),\n comptime name: [:0]const u8,\n comptime updateEntity: anytype,\n options: ForEachThreadedOptions(@TypeOf(updateEntity)),\n) void {\n const zone = Zone.begin(.{ .src = @src(), .name = name });\n defer zone.end();\n\n const Opt = @TypeOf(options);\n\n assert(!Opt.acquire_cb or options.cp != null);\n\n const Wrapped = struct {\n fn processChunk(\n es: *const Entities,\n chunk: *Chunk,\n ctx: @FieldType(@TypeOf(options), \"ctx\"),\n ) void {\n const batch_zone = Zone.begin(.{ .src = @src(), .name = name });\n defer batch_zone.end();\n\n const slices = chunk.view(es, view.Slice(Opt.Comps)).?;\n for (0..chunk.header().len) |i| {\n const vw = view.index(Opt.Comps, es, slices, @intCast(i));\n @call(.auto, updateEntity, .{ctx} ++ vw);\n }\n }\n\n fn processChunkCb(\n es: *const Entities,\n cp: *CmdPool,\n chunk: *Chunk,\n ctx: @FieldType(@TypeOf(options), \"ctx\"),\n ) void {\n const batch_zone = Zone.begin(.{ .src = @src(), .name = name });\n defer batch_zone.end();\n\n const ar = cp.acquire();\n defer cp.release(ar);\n\n const slices = chunk.view(es, view.Slice(Opt.Comps)).?;\n for (0..chunk.header().len) |i| {\n const vw = view.index(Opt.Comps, es, slices, @intCast(i));\n @call(.auto, updateEntity, .{ ctx, ar.cb } ++ vw);\n }\n }\n };\n\n const required_comps = view.comps(Opt.Comps, .{ .size = .one }) orelse return;\n var chunks = self.chunkIterator(required_comps);\n while (chunks.next(self)) |chunk| {\n if (Opt.acquire_cb) {\n options.tp.spawnWg(options.wg, Wrapped.processChunkCb, .{\n self,\n options.cp.?,\n chunk,\n options.ctx,\n });\n } else {\n options.tp.spawnWg(options.wg, Wrapped.processChunk, .{\n self,\n chunk,\n options.ctx,\n });\n }\n }\n}\n\n/// Options for `forEachChunkThreaded`.\npub fn ForEachChunkThreadedOptions(f: type) type {\n return struct {\n const Ctx = view.params(f)[0];\n const Comps = view.Tuple(view.params(f)[1..]);\n\n ctx: Ctx,\n tp: *std.Thread.Pool,\n wg: *std.Thread.WaitGroup,\n };\n}\n\n/// Similar to `forEach`, but with the threading model from `forEachThreaded`.\npub fn forEachChunkThreaded(\n self: *@This(),\n comptime name: [:0]const u8,\n comptime updateChunk: anytype,\n options: ForEachChunkThreadedOptions(@TypeOf(updateChunk)),\n) void {\n const zone = Zone.begin(.{ .src = @src(), .name = name });\n defer zone.end();\n\n const Opt = @TypeOf(options);\n\n const Wrapped = struct {\n fn processChunk(\n es: *const Entities,\n chunk: *Chunk,\n ctx: @FieldType(@TypeOf(options), \"ctx\"),\n ) void {\n const batch_zone = Zone.begin(.{ .src = @src(), .name = name });\n defer batch_zone.end();\n\n const slices = chunk.view(es, view.Slice(Opt.Comps)).?;\n @call(.auto, updateChunk, .{ctx} ++ slices);\n }\n };\n\n const required_comps = view.comps(Opt.Comps, .{ .size = .slice }) orelse return;\n var chunks = self.chunkIterator(required_comps);\n while (chunks.next(self)) |chunk| {\n std.Thread.Pool.spawnWg(options.tp, options.wg, Wrapped.processChunk, .{\n self,\n chunk,\n options.ctx,\n });\n }\n}\n\n/// Emits a warning if any preallocated buffers are past `warn_ratio` capacity, or if any entity\n/// slots have become saturated. If Tracy is enabled, sends usage statistics to Tracy.\n///\n/// It's recommended that you call this once a frame.\npub fn updateStats(self: *@This()) void {\n if (tracy.enabled) {\n tracy.plot(.{\n .name = tracy_es_committed,\n .value = .{ .i64 = @intCast(self.count()) },\n });\n tracy.plot(.{\n .name = tracy_es_reserved,\n .value = .{ .i64 = @intCast(self.reserved()) },\n });\n tracy.plot(.{\n .name = tracy_es_saturated,\n .value = .{ .i64 = @intCast(self.handle_tab.saturated) },\n });\n tracy.plot(.{\n .name = tracy_chunks,\n .value = .{ .i64 = @intCast(self.chunk_pool.reserved) },\n });\n tracy.plot(.{\n .name = tracy_arches,\n .value = .{ .i64 = @intCast(self.arches.map.count()) },\n });\n }\n\n if (self.warn_ratio < 1.0) {\n if (self.handle_tab.saturated > self.warned_saturated) {\n self.warned_saturated = self.handle_tab.saturated;\n log.warn(\"{} entity slots have been saturated\", .{self.warned_saturated});\n }\n\n const handles: f32 = @floatFromInt(self.handle_tab.count());\n const handles_cap: f32 = @floatFromInt(self.handle_tab.capacity);\n if (!self.warned_capacity and handles > handles_cap * self.warn_ratio) {\n self.warned_capacity = true;\n log.warn(\"entities past {d}% capacity\", .{self.warn_ratio * 100.0});\n }\n\n const chunks: f32 = @floatFromInt(self.chunk_pool.reserved);\n const chunks_cap_int = self.chunk_pool.buf.len / self.chunk_pool.size_align.toByteUnits();\n const chunks_cap: f32 = @floatFromInt(chunks_cap_int);\n if (!self.warned_chunk_pool and chunks > chunks_cap * self.warn_ratio) {\n self.warned_chunk_pool = true;\n log.warn(\"chunk pool past {d}% capacity\", .{self.warn_ratio * 100.0});\n }\n\n const arches: f32 = @floatFromInt(self.arches.map.count());\n const arhces_cap: f32 = @floatFromInt(self.arches.map.capacity());\n if (!self.warned_arches and arches > arhces_cap * self.warn_ratio) {\n self.warned_arches = true;\n log.warn(\"archetypes past {d}% capacity\", .{self.warn_ratio * 100.0});\n }\n }\n}\n\n/// Returns an iterator over all the chunks with at least the components in `required_comps` in\n/// an implementation defined order.\n///\n/// Invalidating pointers while iterating results in safety checked illegal behavior.\npub fn chunkIterator(\n self: *const @This(),\n required_comps: CompFlag.Set,\n) ChunkIterator {\n var lists = self.arches.iterator(self, required_comps);\n const chunks: ChunkList.Iterator = if (lists.next(self)) |l| l.iterator(self) else .empty(self);\n var result: ChunkIterator = .{\n .lists = lists,\n .chunks = chunks,\n };\n result.catchUp(self);\n return result;\n}\n\n/// See `chunkIterator`.\npub const ChunkIterator = struct {\n lists: Arches.Iterator,\n chunks: ChunkList.Iterator,\n\n /// Returns the pointer lock.\n pub fn pointerLock(self: *const ChunkIterator) PointerLock {\n return self.lists.pointer_lock;\n }\n\n /// Returns an empty iterator.\n pub fn empty(es: *const Entities) @This() {\n return .{\n .lists = .empty(es),\n .chunks = .empty(es),\n };\n }\n\n /// Advance the internal state so that `peek` is in sync.\n fn catchUp(self: *@This(), es: *const Entities) void {\n while (self.chunks.chunk == null) {\n if (self.lists.next(es)) |chunk_list| {\n self.chunks = chunk_list.iterator(es);\n } else {\n break;\n }\n }\n }\n\n /// Returns the current chunk without advancing.\n pub fn peek(self: *const @This(), es: *const Entities) ?*Chunk {\n return self.chunks.peek(es);\n }\n\n /// Advances the iterator, returning the next entity.\n pub fn next(self: *@This(), es: *const Entities) ?*Chunk {\n self.pointerLock().check(es.pointer_generation);\n\n // We need to loop here because while chunks can't be empty, chunk lists can\n const chunk = while (true) {\n // Get the next chunk in this list\n if (self.chunks.next(es)) |chunk| break chunk;\n\n // If that fails, get the next list and try again\n if (self.lists.next(es)) |chunk_list| {\n @branchHint(.likely);\n self.chunks = chunk_list.iterator(es);\n continue;\n }\n\n // If that fails, return null\n return null;\n };\n\n // Catch up the peek state.\n self.catchUp(es);\n\n return chunk;\n }\n};\n\n/// Returns an iterator over all entities that have at least the components in `required_comps` in\n/// chunk order. The results are of type `View` which is a struct where each field is either a\n/// pointer to a component, an optional pointer to a component, or `Entity`.\n///\n/// In the general case, it's simplest to consider chunk order to be implementation defined.\n/// However, chunk order does have the useful guarantee that entities added to an archetype that\n/// starts out empty with no intermittent deletions will always be iterated in order. This can be\n/// useful for preserving order of transient events which are always cleared in one go.\n///\n/// Invalidating pointers while iterating results in safety checked illegal behavior.\npub fn iterator(self: *const @This(), View: type) Iterator(View) {\n const required_comps: CompFlag.Set = view.comps(View, .{ .size = .one }) orelse\n return .empty(self);\n const chunks = self.chunkIterator(required_comps);\n const slices = if (chunks.peek(self)) |c| c.view(self, view.Slice(View)).? else undefined;\n return .{\n .chunks = chunks,\n .slices = slices,\n .index_in_chunk = 0,\n };\n}\n\n/// See `Entities.iterator`.\npub fn Iterator(View: type) type {\n return struct {\n const Slices = view.Slice(View);\n\n chunks: ChunkIterator,\n slices: Slices,\n index_in_chunk: u32,\n\n /// Returns an empty iterator.\n pub fn empty(es: *const Entities) @This() {\n return .{\n .chunks = .empty(es),\n .slices = undefined,\n .index_in_chunk = 0,\n };\n }\n\n /// Advances the iterator, returning the next view.\n pub fn next(self: *@This(), es: *const Entities) ?View {\n // Check for pointer invalidation\n self.chunks.pointerLock().check(es.pointer_generation);\n\n // Get the current chunk\n var chunk = self.chunks.peek(es) orelse {\n @branchHint(.unlikely);\n return null;\n };\n assert(chunk.header().len > 0); // Free chunks are returned to the chunk pool\n\n // If we're done with the current chunk, advance to the next one\n if (self.index_in_chunk >= chunk.header().len) {\n _ = self.chunks.next(es).?;\n chunk = self.chunks.peek(es) orelse {\n @branchHint(.unlikely);\n return null;\n };\n self.index_in_chunk = 0;\n assert(chunk.header().len > 0); // Free chunks are returned to the chunk pool\n self.slices = chunk.view(es, Slices).?;\n }\n\n // Get the entity and advance the index, this can't overflow the counter since we can't\n // have as many entities as bytes in a chunk since the space would be used up by the\n // entity indices\n const result = view.index(View, es, self.slices, self.index_in_chunk);\n self.index_in_chunk += 1;\n return result;\n }\n };\n}\n"], ["/ZCS/src/ChunkList.zig", "//! A list of all chunks with a given archetype.\n\nconst std = @import(\"std\");\nconst zcs = @import(\"root.zig\");\nconst tracy = @import(\"tracy\");\n\nconst ChunkPool = zcs.ChunkPool;\nconst CompFlag = zcs.CompFlag;\nconst Chunk = zcs.Chunk;\nconst Entities = zcs.Entities;\nconst PointerLock = zcs.PointerLock;\nconst Arches = zcs.Arches;\nconst Entity = zcs.Entity;\n\nconst Zone = tracy.Zone;\n\nconst typeId = zcs.typeId;\n\nconst assert = std.debug.assert;\nconst alignForward = std.mem.alignForward;\nconst math = std.math;\n\nconst ChunkList = @This();\n\n/// The chunks in this chunk list, connected via the `next` and `prev` fields.\nhead: Chunk.Index,\n/// The final chunk in this chunk list.\ntail: Chunk.Index,\n/// The chunks in this chunk list that have space available, connected via the `next_avail`\n/// and `prev_avail` fields.\navail: Chunk.Index,\n/// The offset to the entity index buffer.\nindex_buf_offset: u32,\n/// A map from component flags to the byte offset of their arrays. Components that aren't\n/// present or are zero sized have undefined offsets. It's generally faster to read this from\n/// the chunk instead of the chunk list to avoid the extra cache miss.\ncomp_buf_offsets_cold: std.enums.EnumArray(CompFlag, u32),\n/// The number of entities that can be stored in a single chunk from this list.\nchunk_capacity: u32,\n\n/// The index of a `ChunkList` in the `Arches` that owns it.\npub const Index = enum(u32) {\n /// Gets a chunk list from a chunk list ID.\n pub fn get(self: @This(), arches: *const Arches) *ChunkList {\n return &arches.map.values()[@intFromEnum(self)];\n }\n\n /// Gets the archetype for a chunk list.\n pub fn arch(self: Index, arches: *const Arches) CompFlag.Set {\n return arches.map.keys()[@intFromEnum(self)];\n }\n\n _,\n};\n\n/// Initializes a chunk list.\npub fn init(pool: *const ChunkPool, arch: CompFlag.Set) error{ZcsChunkOverflow}!@This() {\n const zone = Zone.begin(.{ .src = @src() });\n defer zone.end();\n\n // Sort the components from greatest to least alignment.\n const sorted = sortCompsByAlignment(arch);\n\n // Get the max alignment required by any component or entity index\n var max_align: u32 = @alignOf(Entity.Index);\n if (sorted.len > 0) max_align = @max(max_align, sorted.get(0).getId().alignment);\n\n // Initialize the offset to the start of the data\n const data_offset: u32 = alignForward(u32, @sizeOf(Chunk.Header), max_align);\n\n // Calculate how many bytes of data there are\n const bytes = math.sub(\n u32,\n @intCast(pool.size_align.toByteUnits()),\n data_offset,\n ) catch return error.ZcsChunkOverflow;\n\n // Calculate how much space one entity takes\n var entity_size: u32 = @sizeOf(Entity.Index);\n for (sorted.constSlice()) |comp| {\n const comp_size = math.cast(u32, comp.getId().size) orelse\n return error.ZcsChunkOverflow;\n entity_size = math.add(u32, entity_size, comp_size) catch\n return error.ZcsChunkOverflow;\n }\n\n // Calculate the capacity in entities\n const chunk_capacity: u32 = bytes / entity_size;\n\n // Check that we have enough space for at least one entity\n if (chunk_capacity <= 0) return error.ZcsChunkOverflow;\n\n // Calculate the offsets for each component\n var offset: u32 = data_offset;\n var comp_buf_offsets: std.enums.EnumArray(CompFlag, u32) = .initFill(0);\n var index_buf_offset: u32 = 0;\n for (sorted.constSlice()) |comp| {\n const id = comp.getId();\n\n // If we haven't found a place for the index buffer, check if it can go here\n if (index_buf_offset == 0 and id.alignment <= @alignOf(Entity.Index)) {\n assert(offset % @alignOf(Entity.Index) == 0);\n index_buf_offset = offset;\n const buf_size = math.mul(u32, @sizeOf(Entity.Index), chunk_capacity) catch\n return error.ZcsChunkOverflow;\n offset = math.add(u32, offset, buf_size) catch\n return error.ZcsChunkOverflow;\n }\n\n // Store the offset to this component type\n assert(offset % id.alignment == 0);\n comp_buf_offsets.set(comp, offset);\n const comp_size = math.cast(u32, id.size) orelse\n return error.ZcsChunkOverflow;\n const buf_size = math.mul(u32, comp_size, chunk_capacity) catch\n return error.ZcsChunkOverflow;\n offset = math.add(u32, offset, buf_size) catch\n return error.ZcsChunkOverflow;\n }\n\n // If we haven't found a place for the index buffer, place it at the end\n if (index_buf_offset == 0) {\n index_buf_offset = offset;\n const buf_size = math.mul(u32, @sizeOf(Entity.Index), chunk_capacity) catch\n return error.ZcsChunkOverflow;\n offset = math.add(u32, offset, buf_size) catch\n return error.ZcsChunkOverflow;\n }\n\n assert(offset <= pool.size_align.toByteUnits());\n\n return .{\n .head = .none,\n .tail = .none,\n .avail = .none,\n .comp_buf_offsets_cold = comp_buf_offsets,\n .index_buf_offset = index_buf_offset,\n .chunk_capacity = chunk_capacity,\n };\n}\n\n/// Adds an entity to the chunk list.\npub fn append(\n self: *@This(),\n es: *Entities,\n e: Entity,\n) error{ZcsChunkPoolOverflow}!Entity.Location {\n const pool = &es.chunk_pool;\n const arches = &es.arches;\n\n // Ensure there's a chunk with space available\n if (self.avail == .none) {\n // Allocate a new chunk\n const new = try pool.reserve(es, arches.indexOf(self));\n const new_index = pool.indexOf(new);\n\n // Point the available list to the new chunk\n self.avail = new_index;\n\n // Add the new chunk to the end of the chunk list\n if (self.tail.get(pool)) |tail| {\n new.header().prev = self.tail;\n tail.header().next = new_index;\n self.tail = new_index;\n } else {\n self.head = new_index;\n self.tail = new_index;\n }\n }\n\n // Get the next chunk with space available\n const chunk = self.avail.get(pool).?;\n const header = chunk.header();\n assert(header.len < self.chunk_capacity);\n chunk.checkAssertions(es, .allow_empty);\n\n // Append the entity. This const cast is okay since the chunk was originally mutable, we\n // just don't expose mutable pointers to the index buf publicly.\n const index_in_chunk: Entity.Location.IndexInChunk = @enumFromInt(header.len);\n header.len += 1;\n const index_buf = @constCast(chunk.view(es, struct {\n indices: []const Entity.Index,\n }).?.indices);\n index_buf[@intFromEnum(index_in_chunk)] = @enumFromInt(e.key.index);\n\n // If the chunk is now full, remove it from the available list\n if (header.len == self.chunk_capacity) {\n @branchHint(.unlikely);\n assert(self.avail.get(pool) == chunk);\n self.avail = chunk.header().next_avail;\n header.next_avail = .none;\n if (self.avail.get(pool)) |avail| {\n const available_header = avail.header();\n assert(available_header.prev_avail.get(pool) == chunk);\n available_header.prev_avail = .none;\n }\n }\n\n self.checkAssertions(es);\n\n // Return the location we stored the entity\n return .{\n .chunk = es.chunk_pool.indexOf(chunk),\n .index_in_chunk = index_in_chunk,\n };\n}\n\n// Checks internal consistency.\npub fn checkAssertions(self: *const @This(), es: *const Entities) void {\n if (!std.debug.runtime_safety) return;\n\n const pool = &es.chunk_pool;\n\n if (self.head.get(pool)) |head| {\n const header = head.header();\n head.checkAssertions(es, .default);\n self.tail.get(pool).?.checkAssertions(es, .default);\n assert(@intFromBool(header.next != .none) ^\n @intFromBool(head == self.tail.get(pool)) != 0);\n assert(self.tail != .none);\n } else {\n assert(self.tail == .none);\n assert(self.avail == .none);\n }\n\n if (self.avail.get(pool)) |avail| {\n const header = avail.header();\n avail.checkAssertions(es, .default);\n assert(header.prev_avail == .none);\n }\n}\n\n/// Returns an iterator over this chunk list's chunks.\n///\n/// Invalidating pointers while iterating results in safety checked illegal behavior.\npub fn iterator(self: *const @This(), es: *const Entities) Iterator {\n self.checkAssertions(es);\n return .{\n .chunk = self.head.get(&es.chunk_pool),\n .pointer_lock = es.pointer_generation.lock(),\n };\n}\n\n/// An iterator over a chunk list's chunks.\npub const Iterator = struct {\n /// Returns an empty iterator.\n pub fn empty(es: *const Entities) @This() {\n return .{\n .chunk = null,\n .pointer_lock = es.pointer_generation.lock(),\n };\n }\n\n chunk: ?*Chunk,\n pointer_lock: PointerLock,\n\n /// Returns the next chunk and advances.\n pub fn next(self: *@This(), es: *const Entities) ?*Chunk {\n self.pointer_lock.check(es.pointer_generation);\n const chunk = self.chunk orelse {\n @branchHint(.unlikely);\n return null;\n };\n chunk.checkAssertions(es, .default);\n const header = chunk.header();\n self.chunk = header.next.get(&es.chunk_pool);\n return chunk;\n }\n\n /// Peeks at the next chunk.\n pub fn peek(self: @This(), es: *const Entities) ?*Chunk {\n self.pointer_lock.check(es.pointer_generation);\n return self.chunk;\n }\n};\n\n/// Compares the alignment of two component types.\nfn alignmentGte(_: void, lhs: CompFlag, rhs: CompFlag) bool {\n const lhs_alignment = lhs.getId().alignment;\n const rhs_alignment = rhs.getId().alignment;\n return lhs_alignment >= rhs_alignment;\n}\n\n/// Returns a list of the components in this set sorted from greatest to least alignment. This\n/// is an optimization to reduce padding, but also necessary to get consistent cutoffs for how\n/// much data fits in a chunk regardless of registration order.\ninline fn sortCompsByAlignment(set: CompFlag.Set) std.BoundedArray(CompFlag, CompFlag.max) {\n const zone = Zone.begin(.{ .src = @src() });\n defer zone.end();\n var comps: std.BoundedArray(CompFlag, CompFlag.max) = .{};\n var iter = set.iterator();\n while (iter.next()) |flag| comps.appendAssumeCapacity(flag);\n std.sort.pdq(CompFlag, comps.slice(), {}, alignmentGte);\n return comps;\n}\n\ntest sortCompsByAlignment {\n defer CompFlag.unregisterAll();\n\n // Register various components with different alignments in an arbitrary order\n const a_1 = CompFlag.registerImmediate(typeId(struct { x: u8 align(1) }));\n const e_2 = CompFlag.registerImmediate(typeId(struct { x: u8 align(16) }));\n const d_2 = CompFlag.registerImmediate(typeId(struct { x: u8 align(8) }));\n const e_0 = CompFlag.registerImmediate(typeId(struct { x: u8 align(16) }));\n const b_2 = CompFlag.registerImmediate(typeId(struct { x: u8 align(2) }));\n const d_0 = CompFlag.registerImmediate(typeId(struct { x: u8 align(8) }));\n const a_2 = CompFlag.registerImmediate(typeId(struct { x: u8 align(1) }));\n const e_1 = CompFlag.registerImmediate(typeId(struct { x: u8 align(16) }));\n const c_0 = CompFlag.registerImmediate(typeId(struct { x: u8 align(4) }));\n const b_0 = CompFlag.registerImmediate(typeId(struct { x: u8 align(2) }));\n const b_1 = CompFlag.registerImmediate(typeId(struct { x: u8 align(2) }));\n const a_0 = CompFlag.registerImmediate(typeId(struct { x: u8 align(1) }));\n const c_2 = CompFlag.registerImmediate(typeId(struct { x: u8 align(4) }));\n const c_1 = CompFlag.registerImmediate(typeId(struct { x: u8 align(4) }));\n const d_1 = CompFlag.registerImmediate(typeId(struct { x: u8 align(8) }));\n\n // Test sorting all of them\n {\n // Sort them\n const sorted = sortCompsByAlignment(.initMany(&.{\n e_0,\n c_1,\n d_0,\n e_1,\n a_1,\n b_1,\n b_0,\n a_0,\n d_1,\n c_0,\n c_2,\n e_2,\n a_2,\n b_2,\n d_2,\n }));\n try std.testing.expectEqual(15, sorted.len);\n var prev: usize = math.maxInt(usize);\n for (sorted.constSlice()) |flag| {\n const curr = flag.getId().alignment;\n try std.testing.expect(curr <= prev);\n prev = curr;\n }\n }\n\n // Test sorting a subset of them\n {\n // Sort them\n const sorted = sortCompsByAlignment(.initMany(&.{\n e_0,\n d_0,\n c_0,\n a_0,\n b_0,\n }));\n try std.testing.expectEqual(5, sorted.len);\n try std.testing.expectEqual(e_0, sorted.get(0));\n try std.testing.expectEqual(d_0, sorted.get(1));\n try std.testing.expectEqual(c_0, sorted.get(2));\n try std.testing.expectEqual(b_0, sorted.get(3));\n try std.testing.expectEqual(a_0, sorted.get(4));\n }\n}\n"], ["/ZCS/src/chunk.zig", "const std = @import(\"std\");\nconst zcs = @import(\"root.zig\");\n\nconst assert = std.debug.assert;\n\nconst typeId = zcs.typeId;\n\nconst Entity = zcs.Entity;\nconst Entities = zcs.Entities;\nconst PointerLock = zcs.PointerLock;\nconst TypeId = zcs.TypeId;\nconst CompFlag = zcs.CompFlag;\nconst ChunkList = zcs.ChunkList;\nconst Arches = zcs.Arches;\nconst ChunkPool = zcs.ChunkPool;\n\n/// A chunk of entity data where each entity has the same archetype. This type is mostly used\n/// internally, you should prefer the higher level API in most cases.\npub const Chunk = opaque {\n /// A chunk's index in its `ChunkPool`.\n pub const Index = enum(u32) {\n /// The none index. The capacity is always less than this value, so there's no overlap.\n none = std.math.maxInt(u32),\n _,\n\n /// Gets a chunk from the chunk ID.\n pub fn get(self: Index, pool: *const ChunkPool) ?*Chunk {\n if (self == .none) return null;\n const byte_idx = @shlExact(\n @intFromEnum(self),\n @intCast(@intFromEnum(pool.size_align)),\n );\n const result: *Chunk = @ptrCast(&pool.buf[byte_idx]);\n assert(@intFromEnum(self) < pool.reserved);\n assert(pool.indexOf(result) == self);\n return result;\n }\n };\n\n /// Meta information for a chunk.\n pub const Header = struct {\n /// The offsets to each component, or 0 for each that is missing.\n ///\n /// This is also stored on the chunk list, but duplicating this state to the chunk\n /// measurably improves benchmarks, likely due to reducing cache misses.\n comp_buf_offsets: std.enums.EnumArray(CompFlag, u32),\n /// The chunk list this chunk is part of, if any.\n list: ChunkList.Index,\n /// The next chunk, if any.\n next: Index = .none,\n /// The previous chunk, if any.\n prev: Index = .none,\n /// The next chunk with available space, if any.\n next_avail: Index = .none,\n /// The previous chunk with available space, if any.\n prev_avail: Index = .none,\n /// The number of entities in this chunk.\n len: u32,\n\n /// Returns this chunk's archetype. When checking for individual components, prefer checking\n /// `comp_buf_offsets`. This value larger but nearer in memory.\n pub fn arch(self: *const @This(), lists: *const Arches) CompFlag.Set {\n return self.list.arch(lists);\n }\n };\n\n /// An offset from the start of a chunk to a component buffer.\n pub const CompBufOffset = enum(u32) {\n none = 0,\n _,\n\n pub inline fn unwrap(self: @This()) ?u32 {\n const result = @intFromEnum(self);\n if (result == 0) return null;\n return result;\n }\n };\n\n /// Checks for self consistency.\n pub fn checkAssertions(\n self: *Chunk,\n es: *const Entities,\n mode: enum {\n /// By default, chunks may not be empty since if they were they'd have been returned to\n /// the chunk pool.\n default,\n /// However if we're checking a just allocated chunk, or one we're about to clear, we\n /// can skip this check.\n allow_empty,\n },\n ) void {\n if (!std.debug.runtime_safety) return;\n\n const list = self.header().list.get(&es.arches);\n const pool = &es.chunk_pool;\n\n // Validate next/prev\n if (self.header().next.get(pool)) |next_chunk| {\n assert(next_chunk.header().prev.get(pool) == self);\n }\n\n if (self.header().prev.get(pool)) |prev_chunk| {\n assert(prev_chunk.header().next.get(pool) == self);\n }\n\n if (self == list.head.get(pool)) assert(self.header().prev == .none);\n if (self == list.tail.get(pool)) assert(self.header().next == .none);\n\n if (self.header().len >= list.chunk_capacity) {\n // Validate full chunks\n assert(self.header().len == list.chunk_capacity);\n assert(self.header().next_avail == .none);\n assert(self.header().prev_avail == .none);\n } else {\n // Available chunks shouldn't be empty, since empty chunks are returned to the chunk\n // pool. `allow_empty` is set to true when checking a chunk that's about to be returned\n // to the chunk pool.\n assert(mode == .allow_empty or self.header().len > 0);\n\n // Validate next/prev available\n if (self.header().next_avail.get(pool)) |next_available_chunk| {\n assert(next_available_chunk.header().prev_avail.get(pool) == self);\n }\n\n if (self.header().prev_avail.get(pool)) |prev_available_chunk| {\n assert(prev_available_chunk.header().next_avail.get(pool) == self);\n }\n\n if (self == list.avail.get(pool)) {\n assert(self.header().prev_avail == .none);\n }\n }\n }\n\n /// Returns a pointer to the chunk header.\n pub inline fn header(self: *Chunk) *Header {\n return @alignCast(@ptrCast(self));\n }\n\n /// Clears the chunk's entity data.\n pub fn clear(self: *Chunk, es: *Entities) void {\n // Get the header and chunk list\n const pool = &es.chunk_pool;\n const index = pool.indexOf(self);\n const list = self.header().list.get(&es.arches);\n\n // Validate this chunk\n self.checkAssertions(es, .allow_empty);\n\n // Remove this chunk from the chunk list head/tail\n if (list.head == index) list.head = self.header().next;\n if (list.tail == index) list.tail = self.header().prev;\n if (list.avail == index) list.avail = self.header().next_avail;\n\n // Remove this chunk from the chunk list normal and available linked lists\n if (self.header().prev.get(pool)) |prev| prev.header().next = self.header().next;\n if (self.header().next.get(pool)) |next| next.header().prev = self.header().prev;\n if (self.header().prev_avail.get(pool)) |prev| prev.header().next_avail = self.header().next_avail;\n if (self.header().next_avail.get(pool)) |next| next.header().prev_avail = self.header().prev_avail;\n\n // Reset this chunk, and add it to the pool's free list\n self.header().* = undefined;\n self.header().next = es.chunk_pool.free;\n es.chunk_pool.free = index;\n\n // Validate the chunk list\n list.checkAssertions(es);\n }\n\n /// Returns an entity slice view of type `View` into this chunk. See `zcs.view`.\n pub fn view(self: *@This(), es: *const Entities, View: type) ?View {\n const list = self.header().list.get(&es.arches);\n\n const view_arch = zcs.view.comps(View, .{ .size = .slice }) orelse return null;\n const chunk_arch = self.header().arch(&es.arches);\n if (!chunk_arch.supersetOf(view_arch)) return null;\n\n var result: View = undefined;\n inline for (@typeInfo(View).@\"struct\".fields) |field| {\n const As = zcs.view.UnwrapField(field.type, .{ .size = .slice });\n if (As == Entity.Index) {\n const unsized: [*]As = @ptrFromInt(@intFromPtr(self) + list.index_buf_offset);\n const sized = unsized[0..self.header().len];\n @field(result, field.name) = sized;\n } else {\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const offset = if (typeId(As).comp_flag) |flag|\n self.header().comp_buf_offsets.values[@intFromEnum(flag)]\n else\n 0;\n if (@typeInfo(field.type) == .optional and offset == 0) {\n @field(result, field.name) = null;\n } else {\n assert(offset != 0); // Arch checked above\n const unsized: [*]As = @ptrFromInt(@intFromPtr(self) + offset);\n const sized = unsized[0..self.header().len];\n @field(result, field.name) = sized;\n }\n }\n }\n return result;\n }\n\n /// Similar to `view`, but only gets a single component slice and doesn't require comptime\n /// types.\n pub fn compsFromId(self: *Chunk, id: TypeId) ?[]u8 {\n const flag = id.comp_flag orelse return null;\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const offset = self.header().comp_buf_offsets.values[@intFromEnum(flag)];\n if (offset == 0) return null;\n const ptr: [*]u8 = @ptrFromInt(@intFromPtr(self) + offset);\n return ptr[0 .. self.header().len * id.size];\n }\n\n /// Swap removes an entity from the chunk, updating the location of the moved entity. This is\n /// typically used internally, for external uses you're likely looking for\n /// `Entity.destroy` or `Entity.destroyImmediate`.\n pub fn swapRemove(\n self: *@This(),\n es: *Entities,\n index_in_chunk: Entity.Location.IndexInChunk,\n ) void {\n const pool = &es.chunk_pool;\n const index = pool.indexOf(self);\n const list = self.header().list.get(&es.arches);\n const was_full = self.header().len >= list.chunk_capacity;\n\n // Get the last entity\n const indices = @constCast(self.view(es, struct {\n indices: []const Entity.Index,\n }).?.indices);\n const new_len = self.header().len - 1;\n const moved = indices[new_len];\n\n // Early out if we're popping the end of the list\n if (@intFromEnum(index_in_chunk) == new_len) {\n // Clear the previous entity data\n if (std.debug.runtime_safety) {\n indices[@intFromEnum(index_in_chunk)] = undefined;\n var it = self.header().arch(&es.arches).iterator();\n while (it.next()) |flag| {\n const id = flag.getId();\n const comp_buffer = self.compsFromId(id).?;\n const comp_offset = new_len * id.size;\n const comp = comp_buffer[comp_offset..][0..id.size];\n @memset(comp, undefined);\n }\n }\n\n // Update the chunk's length, possibly returning it to the chunk pool\n if (new_len == 0) {\n self.clear(es);\n } else {\n self.header().len = new_len;\n }\n\n // Early out\n return;\n }\n\n // Overwrite the removed entity index with the popped entity index\n indices[@intFromEnum(index_in_chunk)] = moved;\n\n // Move the moved entity's components\n {\n var move = self.header().arch(&es.arches).iterator();\n while (move.next()) |flag| {\n const id = flag.getId();\n\n const comp_buffer = self.compsFromId(id).?;\n const new_comp_offset = @intFromEnum(index_in_chunk) * id.size;\n const new_comp = comp_buffer[new_comp_offset..][0..id.size];\n\n const prev_comp_offset = new_len * id.size;\n const prev_comp = comp_buffer[prev_comp_offset..][0..id.size];\n\n @memcpy(new_comp, prev_comp);\n @memset(prev_comp, undefined);\n }\n }\n\n // Pop the last entity\n self.header().len = new_len;\n\n // Update the location of the moved entity in the handle table\n const moved_loc = &es.handle_tab.slots[@intFromEnum(moved)].value;\n assert(moved_loc.chunk.get(&es.chunk_pool) == self);\n moved_loc.index_in_chunk = index_in_chunk;\n\n // If this chunk was previously full, add it to this chunk list's available list\n if (was_full) {\n if (list.avail.get(pool)) |head| {\n // Don't disturb the front of the available list if there is one, this decreases\n // fragmentation by guaranteeing that we fill one chunk at a time.\n self.header().next_avail = head.header().next_avail;\n if (self.header().next_avail.get(pool)) |next_avail| {\n next_avail.header().prev_avail = index;\n }\n self.header().prev_avail = list.avail;\n head.header().next_avail = index;\n } else {\n // If the available list is empty, set it to this chunk\n list.avail = index;\n }\n }\n\n list.checkAssertions(es);\n self.checkAssertions(es, .default);\n }\n\n /// Returns an iterator over this chunk's entities.\n ///\n /// Invalidating pointers while iterating results in safety checked illegal behavior.\n pub fn iterator(self: *@This(), es: *const Entities) Iterator {\n return .{\n .chunk = self,\n .index_in_chunk = @enumFromInt(0),\n .pointer_lock = es.pointer_generation.lock(),\n };\n }\n\n /// An iterator over a chunk's entities.\n pub const Iterator = struct {\n chunk: *Chunk,\n index_in_chunk: Entity.Location.IndexInChunk,\n pointer_lock: PointerLock,\n\n pub fn next(self: *@This(), es: *const Entities) ?Entity {\n self.pointer_lock.check(es.pointer_generation);\n if (@intFromEnum(self.index_in_chunk) >= self.chunk.header().len) {\n @branchHint(.unlikely);\n return null;\n }\n const indices = self.chunk.view(es, struct { indices: []const Entity.Index }).?.indices;\n const entity_index = indices[@intFromEnum(self.index_in_chunk)];\n self.index_in_chunk = @enumFromInt(@intFromEnum(self.index_in_chunk) + 1);\n return entity_index.toEntity(es);\n }\n };\n};\n"], ["/ZCS/src/Arches.zig", "//! A map from archetypes to their chunk lists.\n\nconst std = @import(\"std\");\nconst zcs = @import(\"root.zig\");\nconst tracy = @import(\"tracy\");\n\nconst Zone = tracy.Zone;\n\nconst assert = std.debug.assert;\n\nconst Entities = zcs.Entities;\nconst CompFlag = zcs.CompFlag;\nconst PointerLock = zcs.PointerLock;\nconst ChunkList = zcs.ChunkList;\nconst ChunkPool = zcs.ChunkPool;\n\nconst Allocator = std.mem.Allocator;\n\npub const Arches = @This();\n\ncapacity: u32,\nmap: std.ArrayHashMapUnmanaged(\n CompFlag.Set,\n ChunkList,\n struct {\n pub fn eql(_: @This(), lhs: CompFlag.Set, rhs: CompFlag.Set, _: usize) bool {\n return lhs.eql(rhs);\n }\n pub fn hash(_: @This(), key: CompFlag.Set) u32 {\n return @truncate(std.hash.int(key.bits.mask));\n }\n },\n false,\n),\n\n/// Initializes the chunk lists.\npub fn init(gpa: Allocator, capacity: u32) Allocator.Error!@This() {\n const zone = Zone.begin(.{ .src = @src() });\n defer zone.end();\n\n var map: @FieldType(@This(), \"map\") = .{};\n errdefer map.deinit(gpa);\n // We reserve one extra to work around a slightly the slightly awkward get or put API.\n try map.ensureTotalCapacity(gpa, @as(u32, capacity) + 1);\n map.lockPointers();\n return .{\n .capacity = capacity,\n .map = map,\n };\n}\n\n/// Frees the chunk lists.\npub fn deinit(self: *@This(), gpa: Allocator) void {\n self.map.unlockPointers();\n self.map.deinit(gpa);\n self.* = undefined;\n}\n\n/// Resets arches back to its initial state.\npub fn clear(self: *@This()) void {\n self.map.unlockPointers();\n self.map.clearRetainingCapacity();\n self.map.lockPointers();\n}\n\n/// Gets the chunk list for the given archetype, initializing it if it doesn't exist.\npub fn getOrPut(\n self: *@This(),\n pool: *const ChunkPool,\n arch: CompFlag.Set,\n) error{ ZcsChunkOverflow, ZcsArchOverflow }!*ChunkList {\n // This is a bit awkward, but works around there not being a get or put variation\n // that fails when allocation is needed.\n //\n // In practice this code path will only be executed when we're about to fail in a likely\n // fatal way, so the mild amount of extra work isn't worth creating a whole new gop\n // variant over.\n //\n // Note that we reserve space for the requested capacity + 1 in `init` to make this\n // work.\n const gop = self.map.getOrPutAssumeCapacity(arch);\n errdefer if (!gop.found_existing) {\n @branchHint(.cold);\n // We have to unlock pointers to do this, but we're just doing a swap remove so the\n // indices that we already store into the array won't change.\n self.map.unlockPointers();\n assert(self.map.swapRemove(arch));\n self.map.lockPointers();\n };\n if (!gop.found_existing) {\n @branchHint(.unlikely);\n if (self.map.count() > self.capacity) return error.ZcsArchOverflow;\n gop.value_ptr.* = try .init(pool, arch);\n }\n return gop.value_ptr;\n}\n\n/// Gets the index of a chunk list.\npub fn indexOf(lists: *const @This(), self: *const ChunkList) ChunkList.Index {\n const vals = lists.map.values();\n\n assert(@intFromPtr(self) >= @intFromPtr(vals.ptr));\n assert(@intFromPtr(self) < @intFromPtr(vals.ptr) + vals.len * @sizeOf(ChunkList));\n\n const offset = @intFromPtr(self) - @intFromPtr(vals.ptr);\n const index = offset / @sizeOf(ChunkList);\n return @enumFromInt(index);\n}\n\n/// Returns an iterator over the chunk lists that have the given components.\n///\n/// Invalidating pointers while iterating results in safety checked illegal behavior.\npub fn iterator(self: @This(), es: *const Entities, required_comps: CompFlag.Set) Iterator {\n return .{\n .required_comps = required_comps,\n .all = self.map.iterator(),\n .pointer_lock = es.pointer_generation.lock(),\n };\n}\n\n/// An iterator over chunk lists that have the given components.\npub const Iterator = struct {\n required_comps: CompFlag.Set,\n all: @FieldType(Arches, \"map\").Iterator,\n pointer_lock: PointerLock,\n\n /// Returns an empty iterator.\n pub fn empty(es: *const Entities) @This() {\n return .{\n .required_comps = .{},\n .all = b: {\n const map: @FieldType(Arches, \"map\") = .{};\n break :b map.iterator();\n },\n .pointer_lock = es.pointer_generation.lock(),\n };\n }\n\n pub fn next(self: *@This(), es: *const Entities) ?*const ChunkList {\n self.pointer_lock.check(es.pointer_generation);\n while (self.all.next()) |item| {\n if (item.key_ptr.*.supersetOf(self.required_comps)) {\n return item.value_ptr;\n }\n }\n return null;\n }\n};\n"], ["/ZCS/src/view.zig", "//! An entity view is a user defined struct or tuple used as a temporary view of an entity. It may\n//! contain any number of fields, where each field is either of type `Entity`, an optional single\n//! item pointer to a component, or a single item pointer to a component.\n//!\n//! Additionally, entity slice views are views over multiple entities. Slice views are similar to\n//! normal entity views, but instead of single item pointers they have slices, and `Entity.Index` is\n//! used in place of `Entity`.\n//!\n//! These views are temporary, as immediate operations on entity's are allowed to move component\n//! memory.\n//!\n//! This file provides infrastructure to support entity views and entity slice views.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\nconst zcs = @import(\"root.zig\");\nconst typeId = zcs.typeId;\nconst Entities = zcs.Entities;\nconst Entity = zcs.Entity;\nconst Any = zcs.Any;\nconst CompFlag = zcs.CompFlag;\n\n/// Options for a view.\npub const ViewOptions = struct {\n /// The pointer type for the view's components.\n size: std.builtin.Type.Pointer.Size,\n};\n\n/// Given a field type from an entity view or entity slice view, returns the underlying component\n/// type or `Entity`/`Entity.Index` as appropriate.\n///\n/// For entity views, `size` should be set to `.one`. Otherwise it should be set to `.slice` (or the\n/// desired pointer size.)\n///\n/// If `track_ids` is `true`, `ThreadId` is also allowed as a parameter.\npub fn UnwrapField(T: type, options: ViewOptions) type {\n // If we're looking for a single element and `T` is an entity, return it directly\n if (options.size == .one and T == Entity) {\n return Entity;\n }\n\n // Get the component pointer\n const SomePtr = Unwrap(T);\n comptime assert(@typeInfo(SomePtr).pointer.size == options.size);\n const Result = @typeInfo(SomePtr).pointer.child;\n\n // If we're looking for multiple elements and `T` points to entity indices, return it directly\n if (options.size != .one and Result == Entity.Index) {\n comptime assert(@typeInfo(T) != .optional);\n comptime assert(@typeInfo(T).pointer.is_const == true);\n return Result;\n }\n\n // Check that we have a valid component type, and then return it\n zcs.TypeInfo.checkType(Result);\n return Result;\n}\n\n/// Indexes an entity slice view, returning an entity view.\npub fn index(View: type, es: *const Entities, slices: anytype, i: u32) View {\n var view: View = undefined;\n inline for (@typeInfo(View).@\"struct\".fields, slices) |field, slice| {\n if (UnwrapField(@TypeOf(slice), .{ .size = .slice }) == Entity.Index) {\n const entity_index = slice[i];\n @field(view, field.name) = entity_index.toEntity(es);\n } else {\n @field(view, field.name) = switch (@typeInfo(@TypeOf(slice))) {\n .optional => if (slice) |unwrapped| &unwrapped[i] else null,\n else => &slice[i],\n };\n }\n }\n return view;\n}\n\n/// Converts an entity view or entity slice view into a comp flag set, or `null` if any of the\n/// component fields are unregistered. Size should be set to `.one` for entity views, and `.slice`\n/// or the desired pointer size for entity slice views.\npub inline fn comps(T: type, options: ViewOptions) ?CompFlag.Set {\n var arch: CompFlag.Set = .{};\n inline for (@typeInfo(T).@\"struct\".fields) |field| {\n if (field.type != Entity and @typeInfo(field.type) != .optional) {\n const Unwrapped = zcs.view.UnwrapField(field.type, options);\n if (Unwrapped == Entity.Index) continue;\n const flag = typeId(Unwrapped).comp_flag orelse return null;\n arch.insert(flag);\n }\n }\n return arch;\n}\n\n/// Converts an entity view type into an entity slice view type.\npub fn Slice(EntityView: type) type {\n const entity_view_fields = @typeInfo(EntityView).@\"struct\".fields;\n comptime var fields: [entity_view_fields.len]std.builtin.Type.StructField = undefined;\n inline for (&fields, entity_view_fields, 0..) |*field, entity_view_field, i| {\n const T = entity_view_field.type;\n const S = b: {\n if (T == Entity) break :b []const Entity.Index;\n\n const Ptr = switch (@typeInfo(T)) {\n .optional => |optional| optional.child,\n .pointer => T,\n else => @compileError(\"expected pointer, found \" ++ @typeName(T)),\n };\n if (@typeInfo(Ptr) != .pointer) {\n @compileError(\"expected pointer, found \" ++ @typeName(T));\n }\n const Child = @typeInfo(Ptr).pointer.child;\n const S = if (@typeInfo(Ptr).pointer.is_const) []const Child else []Child;\n break :b if (@typeInfo(T) == .optional) ?S else S;\n };\n field.* = .{\n .name = std.fmt.comptimePrint(\"{}\", .{i}),\n .type = S,\n .default_value_ptr = null,\n .is_comptime = false,\n .alignment = @alignOf(S),\n };\n }\n return @Type(.{ .@\"struct\" = .{\n .layout = .auto,\n .fields = &fields,\n .decls = &.{},\n .is_tuple = true,\n } });\n}\n\n/// Returns the list of parameter types for a function type.\npub fn params(T: type) [@typeInfo(T).@\"fn\".params.len]type {\n var results: [@typeInfo(T).@\"fn\".params.len]type = undefined;\n inline for (&results, @typeInfo(T).@\"fn\".params) |*result, param| {\n result.* = if (param.type) |Param| Param else {\n @compileError(\"cannot get type of `anytype` parameter\");\n };\n }\n return results;\n}\n\n/// Generates a tuple from a list of types. Similar to `std.meta.Tuple`, but does not call\n/// `@setEvalBranchQuota`.\npub fn Tuple(types: []const type) type {\n comptime var fields: [types.len]std.builtin.Type.StructField = undefined;\n inline for (&fields, types, 0..) |*field, param, i| {\n field.* = .{\n .name = std.fmt.comptimePrint(\"{}\", .{i}),\n .type = param,\n .default_value_ptr = null,\n .is_comptime = false,\n .alignment = @alignOf(param),\n };\n }\n return @Type(.{ .@\"struct\" = .{\n .layout = .auto,\n .fields = &fields,\n .decls = &.{},\n .is_tuple = true,\n } });\n}\n\n/// If `T` is an optional type, returns its child. Otherwise returns it unchanged.\npub fn Unwrap(T: type) type {\n return switch (@typeInfo(T)) {\n .optional => |optional| optional.child,\n else => T,\n };\n}\n"], ["/ZCS/src/ext/ZoneCmd.zig", "//! A Tracy Zone that begins/ends inside of a command buffer. Unlike most extensions, this\n//! extension's `Exec` is automatically called from the default exec implementation provided that\n//! Tracy is enabled.\n\nconst std = @import(\"std\");\nconst zcs = @import(\"../root.zig\");\nconst tracy = @import(\"tracy\");\n\nconst assert = std.debug.assert;\n\nconst Zone = tracy.Zone;\n\nconst CmdBuf = zcs.CmdBuf;\nconst Entities = zcs.Entities;\nconst Any = zcs.Any;\n\nconst SourceLocation = tracy.SourceLocation;\n\nloc: *const SourceLocation,\n\npub const BeginOptions = Zone.BeginOptions;\n\n/// Emits a begin zone command to the command buffer if Tracy is enabled.\npub fn begin(cb: *CmdBuf, comptime opt: SourceLocation.InitOptions) @This() {\n if (tracy.enabled) {\n const loc: *const SourceLocation = .init(opt);\n cb.ext(BeginCmd, .{ .loc = loc });\n return .{ .loc = loc };\n }\n}\n\n/// Emits an end zone command to the command buffer if Tracy is enabled.\npub fn end(self: @This(), cb: *CmdBuf) void {\n if (tracy.enabled) {\n cb.ext(EndCmd, .{ .loc = self.loc });\n }\n}\n\n/// A begin zone command.\npub const BeginCmd = struct { loc: *const SourceLocation };\n\n/// An end zone command.\npub const EndCmd = struct { loc: *const SourceLocation };\n\n/// `Exec` provides helpers for beginning/ending Tracy zones while executing the command buffer.\n/// Unlike most extensions this extension is called automatically by the default exec, provided that\n/// Tracy is enabled.\n///\n/// By convention, `exec` only calls into the stable public interface of the types it's working\n/// with. As such, documentation is sparse. You are welcome to call these methods directly, or\n/// use them as reference for implementing your own command buffer iterator.\npub const Exec = struct {\n const Stack = if (tracy.enabled) b: {\n break :b std.BoundedArray(struct { zone: Zone, loc: *const SourceLocation }, 32);\n } else struct {};\n\n stack: Stack = .{},\n\n /// Executes an extension command.\n pub inline fn extImmediate(self: *@This(), payload: Any) void {\n if (tracy.enabled) {\n if (payload.as(BeginCmd)) |b| {\n const zone = Zone.beginFromPtr(b.loc);\n self.stack.append(.{ .zone = zone, .loc = b.loc }) catch @panic(\"OOB\");\n } else if (payload.as(EndCmd)) |e| {\n const frame = self.stack.pop() orelse @panic(\"OOB\");\n assert(frame.loc == e.loc);\n frame.zone.end();\n }\n }\n }\n\n pub fn finish(self: *@This()) void {\n if (tracy.enabled) {\n assert(self.stack.len == 0);\n }\n }\n};\n"], ["/ZCS/src/ChunkPool.zig", "//! A pool of `Chunk`s.\n\nconst std = @import(\"std\");\nconst zcs = @import(\"root.zig\");\nconst tracy = @import(\"tracy\");\n\nconst Chunk = zcs.Chunk;\nconst Entities = zcs.Entities;\nconst ChunkList = zcs.ChunkList;\nconst Entity = zcs.Entity;\n\nconst assert = std.debug.assert;\nconst math = std.math;\n\nconst Alignment = std.mem.Alignment;\nconst Allocator = std.mem.Allocator;\n\nconst Zone = tracy.Zone;\n\nconst ChunkPool = @This();\n\n/// Memory reserved for chunks\nbuf: []u8,\n/// The number of unique chunks that have ever been reserved.\nreserved: u32,\n/// The chunk size and alignment are both set to this value. This is done for a couple reasons:\n/// 1. It makes `Entity.from` slightly cheaper\n/// 2. It reduces false sharing\n/// 3. We need to be aligned by more than `TypeInfo.max_align` so that the place our allocation\n/// ends up doesn't change how much stuff can fit in it.\n///\n/// If this becomes an issue, we stop doing this by giving up 1 as long as we set the alignment\n/// to at least a cache line and assert 3. However seeing as it only adds padding before the\n/// first chunk, this is unlikely to ever matter.\nsize_align: Alignment,\n/// Freed chunks, connected by the `next` field. All other fields are undefined.\nfree: Chunk.Index = .none,\n\n/// The pool's capcity.\npub const Capacity = struct {\n /// The number of chunks to reserve. Supports the range `[0, math.maxInt(u32))`, max int\n /// is reserved for the none index.\n chunks: u16,\n /// The size of each chunk.\n chunk: u32,\n};\n\n/// Allocates a chunk pool.\npub fn init(gpa: Allocator, cap: Capacity) Allocator.Error!@This() {\n const zone = Zone.begin(.{ .src = @src() });\n defer zone.end();\n\n // The max size is reserved for invalid indices.\n assert(cap.chunks < math.maxInt(u32));\n assert(cap.chunk >= zcs.TypeInfo.max_align.toByteUnits());\n\n // Allocate the chunk data, aligned to the size of a chunk\n const alignment = Alignment.fromByteUnits(cap.chunk);\n const len = @as(usize, cap.chunk) * @as(usize, cap.chunks);\n const buf = (gpa.rawAlloc(\n len,\n alignment,\n @returnAddress(),\n ) orelse return error.OutOfMemory)[0..len];\n errdefer comptime unreachable;\n\n return .{\n .buf = buf,\n .reserved = 0,\n .size_align = alignment,\n };\n}\n\n/// Frees a chunk pool.\npub fn deinit(self: *@This(), gpa: Allocator) void {\n gpa.rawFree(self.buf, self.size_align, @returnAddress());\n self.* = undefined;\n}\n\n/// Resets the chunk pool back to its initial state.\npub fn clear(self: *@This()) void {\n self.reserved = 0;\n self.free = .none;\n}\n\n/// Reserves a chunk from the chunk pool\npub fn reserve(\n self: *@This(),\n es: *const Entities,\n list: ChunkList.Index,\n) error{ZcsChunkPoolOverflow}!*Chunk {\n // Get a free chunk. Try the free list first, then fall back to bump allocation from the\n // preallocated buffer.\n const chunk = if (self.free.get(self)) |free| b: {\n // Pop the next chunk from the free list\n self.free = free.header().next;\n break :b free;\n } else b: {\n // Pop the next chunk from the preallocated buffer\n const byte_idx = @shlExact(self.reserved, @intCast(@intFromEnum(self.size_align)));\n if (byte_idx >= self.buf.len) return error.ZcsChunkPoolOverflow;\n const chunk: *Chunk = @ptrCast(&self.buf[byte_idx]);\n self.reserved = self.reserved + 1;\n break :b chunk;\n };\n errdefer comptime unreachable; // Already modified the free list!\n\n // Check the alignment\n assert(self.size_align.check(@intFromPtr(chunk)));\n\n // Initialize the chunk and return it\n const header = chunk.header();\n header.* = .{\n .comp_buf_offsets = list.get(&es.arches).comp_buf_offsets_cold,\n .list = list,\n .len = 0,\n };\n return chunk;\n}\n\n/// Gets the index of a chunk.\npub fn indexOf(self: *const @This(), chunk: *const Chunk) Chunk.Index {\n assert(@intFromPtr(chunk) >= @intFromPtr(self.buf.ptr));\n assert(@intFromPtr(chunk) < @intFromPtr(self.buf.ptr) + self.buf.len);\n const offset = @intFromPtr(chunk) - @intFromPtr(self.buf.ptr);\n assert(offset < self.buf.len);\n return @enumFromInt(@shrExact(offset, @intFromEnum(self.size_align)));\n}\n"], ["/ZCS/src/type_id.zig", "//! Runtime type information.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\n\nconst zcs = @import(\"root.zig\");\nconst CompFlag = zcs.CompFlag;\n\n/// Runtime information for a type.\npub const TypeInfo = struct {\n /// The maximum allowed alignment.\n pub const max_align: std.mem.Alignment = .@\"16\";\n\n /// The component's type name.\n name: []const u8,\n /// The component type's size.\n size: usize,\n /// The component type's alignment.\n alignment: u8,\n /// If this type has been registered as a component, this holds the component flag. Component\n /// types are registered as they become needed.\n comp_flag: ?CompFlag = null,\n\n /// Returns the type ID for the given type.\n pub inline fn init(comptime T: type) *@This() {\n comptime checkType(T);\n\n return &struct {\n var info: TypeInfo = .{\n .name = @typeName(T),\n .size = @sizeOf(T),\n .alignment = @alignOf(T),\n };\n }.info;\n }\n\n /// Asserts at compile time that ZCS's runtime type information supports this type.\n pub fn checkType(T: type) void {\n // Storing optionals, pointers, and `Entity` directly as components would create\n // ambiguities when creating entity views. It's unfortunate that we have to disallow\n // them, but the extra typing to wrap them in the rare case that you need this ability\n // is expected to be well worth it for the convenience views provide.\n //\n // There's no reason these couldn't be allowed for `Any` in general, but we want to get\n // compile time errors when trying to use bad types, so we just rule them out for any use of\n // `Any` instead.\n //\n // `Entity.Index` and `CmdBuf` are likely indicative of a mistake and so are ruled\n // out.\n if (@typeInfo(T) == .optional or\n T == zcs.Entity or\n T == zcs.Entity.Index or\n T == zcs.CmdBuf)\n {\n @compileError(\"unsupported component type '\" ++ @typeName(T) ++ \"'; consider wrapping in struct\");\n }\n\n comptime assert(@alignOf(T) <= max_align.toByteUnits());\n }\n};\n\n/// This pointer can be used as a unique ID identifying a component type.\npub const TypeId = *TypeInfo;\n"], ["/ZCS/src/comp_flag.zig", "//! See `CompFlag`.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\n\nconst zcs = @import(\"root.zig\");\nconst Any = zcs.Any;\nconst TypeId = zcs.TypeId;\nconst Meta = Any.Meta;\n\n/// The tag type for `Flag`.\nconst FlagInt = u6;\n\n/// A tightly packed index for each registered component type.\npub const CompFlag = enum(FlagInt) {\n /// The maximum registered component flags.\n pub const max = std.math.maxInt(FlagInt);\n\n /// A set of component flags.\n pub const Set = std.enums.EnumSet(CompFlag);\n\n /// The list of registered components.\n var registered: std.BoundedArray(TypeId, CompFlag.max) = .{};\n\n /// Assigns the given ID the next flag index if it doesn't have one, and then returns its flag.\n /// Not thread safe.\n pub fn registerImmediate(id: TypeId) CompFlag {\n // Early out if we're already registered\n if (id.comp_flag) |f| {\n @branchHint(.likely);\n return f;\n }\n\n // Debug log that we're registering the component\n std.log.scoped(.zcs).debug(\"register comp: {s}\", .{id.name});\n\n // Warn if we've registered a large number of components\n if (registered.len == CompFlag.max / 2) {\n std.log.warn(\n \"{} component types registered, you're at 50% the fatal capacity!\",\n .{registered.len},\n );\n }\n\n // Fail if we're out of component types\n if (registered.len > registered.buffer.len) {\n @panic(\"component type overflow\");\n }\n\n // Pick the next sequential flag\n const flag: CompFlag = @enumFromInt(registered.len);\n id.comp_flag = flag;\n\n // This function is not thread safe, but reading from `registered` is, so we update the\n // registered list, and then increment the counter atomically.\n registered.buffer[registered.len] = id;\n _ = @atomicRmw(usize, ®istered.len, .Add, 1, .release);\n\n // Return the registered flag\n return flag;\n }\n\n /// Gets the list of registered component types for introspection purposes. Components are\n /// registered lazily, this list will grow over time. Thread safe.\n pub fn getAll() []const TypeId {\n return registered.constSlice();\n }\n\n /// This function is intended to be used only in tests. Unregisters all component types.\n pub fn unregisterAll() void {\n for (registered.slice()) |id| id.comp_flag = null;\n registered.clear();\n }\n\n /// Returns the ID for this flag.\n pub fn getId(self: @This()) TypeId {\n return registered.get(@intFromEnum(self));\n }\n\n _,\n};\n"], ["/ZCS/src/Any.zig", "//! A pointer to arbitrary data with a runtime known type.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\n\nconst zcs = @import(\"root.zig\");\n\nconst typeId = zcs.typeId;\n\nconst Entities = zcs.Entities;\nconst CompFlag = zcs.CompFlag;\nconst TypeId = zcs.TypeId;\n\nid: TypeId,\nptr: *const anyopaque,\n\n/// Initialize a component from a pointer to a component type.\npub fn init(T: type, ptr: *const T) @This() {\n return .{\n .id = typeId(T),\n .ptr = ptr,\n };\n}\n\n/// Returns the component as the given type if it matches its ID, or null otherwise.\npub fn as(self: @This(), T: anytype) ?*const T {\n if (self.id != typeId(T)) {\n @branchHint(.unlikely);\n return null;\n }\n return @alignCast(@ptrCast(self.ptr));\n}\n\n/// Returns the component as a constant slice of `u8`s.\npub fn constSlice(self: @This()) []const u8 {\n return self.bytes()[0..self.id.size];\n}\n\n/// Similar to `constSlice`, but returns the data as a many item pointer.\npub fn bytes(self: @This()) [*]const u8 {\n return @ptrCast(self.ptr);\n}\n"], ["/ZCS/src/PointerLock.zig", "/// Pointer stability assertions for builds with runtime safety enabled.\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\n\nconst PointerLock = @This();\n\nconst enabled = std.debug.runtime_safety;\n\n/// The current pointer generation.\npub const Generation = struct {\n n: if (enabled) u64 else u0 = 0,\n\n /// Increments the pointer generation.\n pub inline fn increment(self: *@This()) void {\n if (enabled) {\n self.n +%= 1;\n }\n }\n\n /// Returns a pointer lock with the current generation.\n pub inline fn lock(self: @This()) PointerLock {\n return .{ .generation = self };\n }\n};\n\n/// The pointer generation from when this lock was created.\ngeneration: Generation,\n\n/// Asserts that pointers have not been invalidated since this lock was created.\npub fn check(self: @This(), generation: Generation) void {\n if (self.generation.n != generation.n) {\n @panic(\"pointers invalidated\");\n }\n}\n"], ["/ZCS/src/root.zig", "//! An entity component system.\n//!\n//! See `Entities` for entity storage and iteration, `Entity` for entity creation and modification,\n//! and `CmdBuf` for queuing commands during iteration or from multiple threads.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\nconst Allocator = std.mem.Allocator;\nconst slot_map = @import(\"slot_map\");\n\npub const Entities = @import(\"Entities.zig\");\npub const Entity = @import(\"entity.zig\").Entity;\npub const Any = @import(\"Any.zig\");\npub const CompFlag = @import(\"comp_flag.zig\").CompFlag;\npub const CmdBuf = @import(\"CmdBuf.zig\");\npub const CmdPool = @import(\"CmdPool.zig\");\npub const TypeInfo = @import(\"type_id.zig\").TypeInfo;\npub const TypeId = @import(\"type_id.zig\").TypeId;\npub const PointerLock = @import(\"PointerLock.zig\");\npub const Chunk = @import(\"chunk.zig\").Chunk;\npub const ChunkList = @import(\"ChunkList.zig\");\npub const ChunkPool = @import(\"ChunkPool.zig\");\npub const Arches = @import(\"Arches.zig\");\npub const view = @import(\"view.zig\");\npub const ext = @import(\"ext.zig\");\npub const meta = @import(\"meta.zig\");\n\n/// Returns the component ID for the given type.\npub const typeId = TypeInfo.init;\n\n/// A handle table that associates persistent entity keys with values that point to their storage.\npub const HandleTab = slot_map.SlotMap(Entity.Location, .{});\n\ntest {\n std.testing.refAllDecls(@This());\n}\n"], ["/ZCS/src/meta.zig", "//! Metaprogramming helpers. See also `view`.\n\nconst std = @import(\"std\");\n\n/// Returns true if the given value is comptime known, false otherwise.\npub inline fn isComptimeKnown(value: anytype) bool {\n return @typeInfo(@TypeOf(.{value})).@\"struct\".fields[0].is_comptime;\n}\n\ntest isComptimeKnown {\n try std.testing.expect(isComptimeKnown(123));\n const foo = 456;\n try std.testing.expect(isComptimeKnown(foo));\n var bar: u8 = 123;\n bar += 1;\n try std.testing.expect(!isComptimeKnown(bar));\n}\n"], ["/ZCS/src/ext.zig", "//! Optional extensions not part of the core ECS.\n\nconst std = @import(\"std\");\n\npub const Node = @import(\"ext/Node.zig\");\npub const Transform2D = @import(\"ext/Transform2D.zig\");\npub const ZoneCmd = @import(\"ext/ZoneCmd.zig\");\npub const geom = @import(\"geom\");\n\ntest {\n std.testing.refAllDecls(@This());\n}\n"], ["/ZCS/src/docs.zig", "/// See build.zig.\npub fn main() void {}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:44:23", "created_task_model": "DeepSeek-R1", "function_skeleton": "inline fn nextAny(self: *@This(), id: TypeId) *const anyopaque { }", "code_description": "This code segment functions to: Adjust the current buffer position to meet alignment requirements and retrieve a specific-sized data block from a contiguous storage area."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```zig\n[TASK_BEGIN]\n pub inline fn nextAny(self: *@This(), id: TypeId) *const anyopaque {\n const alignment = id.getAlignment();\n const size = id.getSize();\n const aligned = std.mem.alignForward(usize, self.comp_bytes_index, alignment);\n const ptr = @ptrCast(self.cb.data.items.ptr + aligned);\n self.comp_bytes_index = aligned + size;\n return ptr;\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 03-44-47"}, "editdistance_info": {"edit_distance": 36.9048, "calculate_time": "2025-08-21 03:44:47", "true_code_clean": "inline fn nextAny(self: *@This(), id: TypeId) *const anyopaque {\n self.comp_bytes_index = std.mem.alignForward(\n usize,\n self.comp_bytes_index,\n id.alignment,\n );\n const bytes = &self.cb.data.items[self.comp_bytes_index..][0..id.size];\n self.comp_bytes_index += id.size;\n return bytes.ptr;\n }", "predict_code_clean": "pub inline fn nextAny(self: *@This(), id: TypeId) *const anyopaque {\n const alignment = id.getAlignment();\n const size = id.getSize();\n const aligned = std.mem.alignForward(usize, self.comp_bytes_index, alignment);\n const ptr = @ptrCast(self.cb.data.items.ptr + aligned);\n self.comp_bytes_index = aligned + size;\n return ptr;\n }"}} {"repo_name": "ZCS", "file_name": "/ZCS/src/view.zig", "inference_info": {"prefix_code": "//! An entity view is a user defined struct or tuple used as a temporary view of an entity. It may\n//! contain any number of fields, where each field is either of type `Entity`, an optional single\n//! item pointer to a component, or a single item pointer to a component.\n//!\n//! Additionally, entity slice views are views over multiple entities. Slice views are similar to\n//! normal entity views, but instead of single item pointers they have slices, and `Entity.Index` is\n//! used in place of `Entity`.\n//!\n//! These views are temporary, as immediate operations on entity's are allowed to move component\n//! memory.\n//!\n//! This file provides infrastructure to support entity views and entity slice views.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\nconst zcs = @import(\"root.zig\");\nconst typeId = zcs.typeId;\nconst Entities = zcs.Entities;\nconst Entity = zcs.Entity;\nconst Any = zcs.Any;\nconst CompFlag = zcs.CompFlag;\n\n/// Options for a view.\npub const ViewOptions = struct {\n /// The pointer type for the view's components.\n size: std.builtin.Type.Pointer.Size,\n};\n\n/// Given a field type from an entity view or entity slice view, returns the underlying component\n/// type or `Entity`/`Entity.Index` as appropriate.\n///\n/// For entity views, `size` should be set to `.one`. Otherwise it should be set to `.slice` (or the\n/// desired pointer size.)\n///\n/// If `track_ids` is `true`, `ThreadId` is also allowed as a parameter.\npub fn UnwrapField(T: type, options: ViewOptions) type {\n // If we're looking for a single element and `T` is an entity, return it directly\n if (options.size == .one and T == Entity) {\n return Entity;\n }\n\n // Get the component pointer\n const SomePtr = Unwrap(T);\n comptime assert(@typeInfo(SomePtr).pointer.size == options.size);\n const Result = @typeInfo(SomePtr).pointer.child;\n\n // If we're looking for multiple elements and `T` points to entity indices, return it directly\n if (options.size != .one and Result == Entity.Index) {\n comptime assert(@typeInfo(T) != .optional);\n comptime assert(@typeInfo(T).pointer.is_const == true);\n return Result;\n }\n\n // Check that we have a valid component type, and then return it\n zcs.TypeInfo.checkType(Result);\n return Result;\n}\n\n/// Indexes an entity slice view, returning an entity view.\npub fn index(View: type, es: *const Entities, slices: anytype, i: u32) View {\n var view: View = undefined;\n inline for (@typeInfo(View).@\"struct\".fields, slices) |field, slice| {\n if (UnwrapField(@TypeOf(slice), .{ .size = .slice }) == Entity.Index) {\n const entity_index = slice[i];\n @field(view, field.name) = entity_index.toEntity(es);\n } else {\n @field(view, field.name) = switch (@typeInfo(@TypeOf(slice))) {\n .optional => if (slice) |unwrapped| &unwrapped[i] else null,\n else => &slice[i],\n };\n }\n }\n return view;\n}\n\n/// Converts an entity view or entity slice view into a comp flag set, or `null` if any of the\n/// component fields are unregistered. Size should be set to `.one` for entity views, and `.slice`\n/// or the desired pointer size for entity slice views.\npub ", "suffix_code": "\n\n/// Converts an entity view type into an entity slice view type.\npub fn Slice(EntityView: type) type {\n const entity_view_fields = @typeInfo(EntityView).@\"struct\".fields;\n comptime var fields: [entity_view_fields.len]std.builtin.Type.StructField = undefined;\n inline for (&fields, entity_view_fields, 0..) |*field, entity_view_field, i| {\n const T = entity_view_field.type;\n const S = b: {\n if (T == Entity) break :b []const Entity.Index;\n\n const Ptr = switch (@typeInfo(T)) {\n .optional => |optional| optional.child,\n .pointer => T,\n else => @compileError(\"expected pointer, found \" ++ @typeName(T)),\n };\n if (@typeInfo(Ptr) != .pointer) {\n @compileError(\"expected pointer, found \" ++ @typeName(T));\n }\n const Child = @typeInfo(Ptr).pointer.child;\n const S = if (@typeInfo(Ptr).pointer.is_const) []const Child else []Child;\n break :b if (@typeInfo(T) == .optional) ?S else S;\n };\n field.* = .{\n .name = std.fmt.comptimePrint(\"{}\", .{i}),\n .type = S,\n .default_value_ptr = null,\n .is_comptime = false,\n .alignment = @alignOf(S),\n };\n }\n return @Type(.{ .@\"struct\" = .{\n .layout = .auto,\n .fields = &fields,\n .decls = &.{},\n .is_tuple = true,\n } });\n}\n\n/// Returns the list of parameter types for a function type.\npub fn params(T: type) [@typeInfo(T).@\"fn\".params.len]type {\n var results: [@typeInfo(T).@\"fn\".params.len]type = undefined;\n inline for (&results, @typeInfo(T).@\"fn\".params) |*result, param| {\n result.* = if (param.type) |Param| Param else {\n @compileError(\"cannot get type of `anytype` parameter\");\n };\n }\n return results;\n}\n\n/// Generates a tuple from a list of types. Similar to `std.meta.Tuple`, but does not call\n/// `@setEvalBranchQuota`.\npub fn Tuple(types: []const type) type {\n comptime var fields: [types.len]std.builtin.Type.StructField = undefined;\n inline for (&fields, types, 0..) |*field, param, i| {\n field.* = .{\n .name = std.fmt.comptimePrint(\"{}\", .{i}),\n .type = param,\n .default_value_ptr = null,\n .is_comptime = false,\n .alignment = @alignOf(param),\n };\n }\n return @Type(.{ .@\"struct\" = .{\n .layout = .auto,\n .fields = &fields,\n .decls = &.{},\n .is_tuple = true,\n } });\n}\n\n/// If `T` is an optional type, returns its child. Otherwise returns it unchanged.\npub fn Unwrap(T: type) type {\n return switch (@typeInfo(T)) {\n .optional => |optional| optional.child,\n else => T,\n };\n}\n", "middle_code": "inline fn comps(T: type, options: ViewOptions) ?CompFlag.Set {\n var arch: CompFlag.Set = .{};\n inline for (@typeInfo(T).@\"struct\".fields) |field| {\n if (field.type != Entity and @typeInfo(field.type) != .optional) {\n const Unwrapped = zcs.view.UnwrapField(field.type, options);\n if (Unwrapped == Entity.Index) continue;\n const flag = typeId(Unwrapped).comp_flag orelse return null;\n arch.insert(flag);\n }\n }\n return arch;\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "zig", "sub_task_type": null}, "context_code": [["/ZCS/src/entity.zig", "const std = @import(\"std\");\nconst assert = std.debug.assert;\n\nconst zcs = @import(\"root.zig\");\n\nconst typeId = zcs.typeId;\n\nconst Subcmd = @import(\"subcmd.zig\").Subcmd;\n\nconst Entities = zcs.Entities;\nconst PointerLock = zcs.PointerLock;\nconst Any = zcs.Any;\nconst CompFlag = zcs.CompFlag;\nconst CmdBuf = zcs.CmdBuf;\nconst TypeId = zcs.TypeId;\nconst HandleTab = zcs.HandleTab;\nconst Chunk = zcs.Chunk;\nconst ChunkPool = zcs.ChunkPool;\nconst ChunkList = zcs.storage.ChunkList;\nconst meta = zcs.meta;\n\n/// An entity.\n///\n/// Entity handles are persistent, you can check if an entity has been destroyed via\n/// `Entity.exists`. This is useful for dynamic systems like games where object lifetime may depend\n/// on user input.\n///\n/// Methods that take a command buffer append the command to a command buffer for execution at a\n/// later time. Methods with `immediate` in the name are executed immediately, usage of these is\n/// discouraged as they are not valid while iterating unless otherwise noted and are not thread\n/// safe.\npub const Entity = packed struct {\n /// An entity without its generation. Used by some lower level APIs to save space where the\n /// safety of the generation is not needed, should not be stored long term outside of the ECS.\n pub const Index = enum(@FieldType(HandleTab.Key, \"index\")) {\n _,\n\n /// Converts the entity index to an `Entity` with the corresponding generation. Assumes that\n /// the index is not dangling, this cannot be reliably enforced without the generation.\n pub fn toEntity(self: @This(), es: *const Entities) Entity {\n const result: Entity = .{ .key = .{\n .index = @intFromEnum(self),\n .generation = es.handle_tab.slots[@intFromEnum(self)].generation,\n } };\n assert(result.key.generation != .invalid);\n assert(result.key.index < es.handle_tab.next_index);\n return result;\n }\n };\n\n /// The location an entity is stored.\n ///\n /// This indirection allows entities to be relocated without invalidating their handles.\n pub const Location = struct {\n /// The index of an entity in a chunk.\n pub const IndexInChunk = enum(u32) { _ };\n\n /// A handle that's been reserved but not committed.\n pub const reserved: @This() = .{\n .chunk = .none,\n .index_in_chunk = if (std.debug.runtime_safety)\n @enumFromInt(std.math.maxInt(@typeInfo(IndexInChunk).@\"enum\".tag_type))\n else\n undefined,\n };\n\n /// The chunk where this entity is stored, or `null` if it hasn't been committed.\n chunk: Chunk.Index = .none,\n /// The entity's index in the chunk, value is unspecified if not committed.\n index_in_chunk: IndexInChunk,\n\n /// Returns the archetype for this entity, or the empty archetype if it hasn't been\n /// committed.\n pub fn arch(self: @This(), es: *const Entities) CompFlag.Set {\n const chunk = self.chunk.get(&es.chunk_pool) orelse return .{};\n const header = chunk.header();\n return header.arch(&es.arches);\n }\n };\n\n pub const Optional = packed struct {\n pub const none: @This() = .{ .key = .none };\n\n key: HandleTab.Key.Optional,\n\n /// Unwraps the optional entity into `Entity`, or returns `null` if it is `.none`.\n pub fn unwrap(self: @This()) ?Entity {\n if (self.key.unwrap()) |key| return .{ .key = key };\n return null;\n }\n\n /// Default formatting.\n pub fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void {\n return self.key.format(writer);\n }\n };\n\n key: HandleTab.Key,\n\n /// Pops a reserved entity.\n ///\n /// A reserved entity is given a persistent key, but no storage. As such, it will behave like\n /// an empty entity, but not show up in iteration.\n ///\n /// You can commit a reserved entity explicitly with `commit`, but this isn't usually\n /// necessary as adding or attempting to remove a component implicitly commits the entity.\n pub fn reserve(cb: *CmdBuf) Entity {\n return reserveOrErr(cb) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `reserve`, but returns an error on failure instead of panicking.\n pub fn reserveOrErr(cb: *CmdBuf) error{ZcsReservedEntityUnderflow}!Entity {\n return cb.reserved.pop() orelse error.ZcsReservedEntityUnderflow;\n }\n\n /// Similar to `reserve`, but reserves a new entity instead of popping one from a command\n /// buffers reserve. Prefer `reserve`.\n ///\n /// This does not invalidate pointers, but it's not thread safe.\n pub fn reserveImmediate(es: *Entities) Entity {\n return reserveImmediateOrErr(es) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `reserveImmediate`, but returns `error.ZcsEntityOverflow` on failure instead of\n /// panicking.\n ///\n /// This does not invalidate pointers, but it's not thread safe.\n pub fn reserveImmediateOrErr(es: *Entities) error{ZcsEntityOverflow}!Entity {\n const pointer_lock = es.pointer_generation.lock();\n defer pointer_lock.check(es.pointer_generation);\n\n const key = es.handle_tab.put(.reserved) catch |err| switch (err) {\n error.Overflow => return error.ZcsEntityOverflow,\n };\n es.reserved_entities += 1;\n return .{ .key = key };\n }\n\n /// Queues an entity for destruction.\n ///\n /// Destroying an entity that no longer exists has no effect.\n pub fn destroy(self: @This(), cb: *CmdBuf) void {\n self.destroyOrErr(cb) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `destroy`, but returns `error.ZcsCmdBufOverflow` on failure instead of\n /// panicking. The command buffer is left in an undefined state on error, see the top level\n /// documentation on `CmdBuf` for more info.\n pub fn destroyOrErr(self: @This(), cb: *CmdBuf) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeDestroy(cb, self);\n }\n\n /// Similar to `destroy`, but destroys the entity immediately. Prefer `destroy`.\n ///\n /// Invalidates pointers.\n pub fn destroyImmediate(self: @This(), es: *Entities) bool {\n es.pointer_generation.increment();\n if (es.handle_tab.get(self.key)) |entity_loc| {\n if (entity_loc.chunk.get(&es.chunk_pool)) |chunk| {\n chunk.swapRemove(es, entity_loc.index_in_chunk);\n } else {\n es.reserved_entities -= 1;\n }\n es.handle_tab.remove(self.key);\n entity_loc.* = undefined;\n return true;\n } else {\n return false;\n }\n }\n\n /// Returns true if the entity has not been destroyed.\n pub fn exists(self: @This(), es: *const Entities) bool {\n return es.handle_tab.containsKey(self.key);\n }\n\n /// Returns true if the entity exists and has been committed, otherwise returns false.\n pub fn committed(self: @This(), es: *const Entities) bool {\n const entity_loc = es.handle_tab.get(self.key) orelse return false;\n return entity_loc.chunk != .none;\n }\n\n /// Returns true if the entity has the given component type, false otherwise or if the entity\n /// has been destroyed.\n pub fn has(self: @This(), es: *const Entities, T: type) bool {\n return self.hasId(es, typeId(T));\n }\n\n /// Similar to `has`, but operates on component IDs instead of types.\n pub fn hasId(self: @This(), es: *const Entities, id: TypeId) bool {\n const flag = id.comp_flag orelse return false;\n return self.arch(es).contains(flag);\n }\n\n /// Retrieves the given component type. Returns null if the entity does not have this component\n /// or has been destroyed. See also `Entities.getComp`.\n pub fn get(self: @This(), es: *const Entities, T: type) ?*T {\n // We could use `compsFromId` here, but we a measurable performance improvement in\n // benchmarks by calculating the result directly\n const entity_loc = es.handle_tab.get(self.key) orelse return null;\n const chunk = entity_loc.chunk.get(&es.chunk_pool) orelse return null;\n const flag = typeId(T).comp_flag orelse return null;\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const offset = chunk.header().comp_buf_offsets.values[@intFromEnum(flag)];\n if (offset == 0) return null;\n const comps_addr = @intFromPtr(chunk) + offset;\n const comp_addr = comps_addr + @sizeOf(T) * @intFromEnum(entity_loc.index_in_chunk);\n return @ptrFromInt(comp_addr);\n }\n\n /// Similar to `get`, but operates on component IDs instead of types.\n pub fn getId(self: @This(), es: *const Entities, id: TypeId) ?[]u8 {\n const entity_loc = es.handle_tab.get(self.key) orelse return null;\n const chunk = entity_loc.chunk.get(&es.chunk_pool) orelse return null;\n const comps = chunk.compsFromId(id) orelse return null;\n return comps[@intFromEnum(entity_loc.index_in_chunk) * id.size ..][0..id.size];\n }\n\n /// Queues a component to be added.\n ///\n /// Batching add/removes on the same entity in sequence is more efficient than alternating\n /// between operations on different entities.\n ///\n /// Will automatically pass the data by pointer if it's comptime known, and larger than pointer\n /// sized.\n ///\n /// Adding components to an entity that no longer exists has no effect.\n pub inline fn add(self: @This(), cb: *CmdBuf, T: type, comp: T) void {\n // Don't get tempted to remove inline from here! It's required for `isComptimeKnown`.\n comptime assert(@typeInfo(@TypeOf(add)).@\"fn\".calling_convention == .@\"inline\");\n self.addOrErr(cb, T, comp) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `add`, but returns an error on failure instead of panicking. The command buffer\n /// is left in an undefined state on error, see the top level documentation on `CmdBuf` for more\n /// info.\n pub inline fn addOrErr(\n self: @This(),\n cb: *CmdBuf,\n T: type,\n comp: T,\n ) error{ZcsCmdBufOverflow}!void {\n // Don't get tempted to remove inline from here! It's required for `isComptimeKnown`.\n comptime assert(@typeInfo(@TypeOf(addOrErr)).@\"fn\".calling_convention == .@\"inline\");\n if (@sizeOf(T) > @sizeOf(*T) and meta.isComptimeKnown(comp)) {\n const Interned = struct {\n const value = comp;\n };\n try self.addPtr(cb, T, comptime &Interned.value);\n } else {\n try self.addVal(cb, T, comp);\n }\n }\n\n /// Similar to `addOrErr`, but forces the component to be copied by value to the command buffer.\n /// Prefer `add`.\n pub fn addVal(self: @This(), cb: *CmdBuf, T: type, comp: T) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeAddVal(cb, self, T, comp);\n }\n\n /// Similar to `addOrErr`, forces the component to be copied by pointer to the command buffer.\n /// Prefer `add`.\n pub fn addPtr(\n self: @This(),\n cb: *CmdBuf,\n T: type,\n comp: *const T,\n ) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeAddPtr(cb, self, T, comp);\n }\n\n /// Queues the given component to be removed. Has no effect if the component is not present, or\n /// the entity no longer exists.\n ///\n /// See note on `add` with regards to performance.\n pub fn remove(self: @This(), cb: *CmdBuf, T: type) void {\n self.removeId(cb, typeId(T)) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `remove`, but doesn't require compile time types and returns an error on failure\n /// instead of panicking on failure. The command buffer is left in an undefined state on error,\n /// see the top level documentation on `CmdBuf` for more info.\n pub fn removeId(self: @This(), cb: *CmdBuf, id: TypeId) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeRemove(cb, self, id);\n }\n\n /// Queues the entity to be committed. Has no effect if it has already been committed, called\n /// implicitly on add/remove/cmd. In practice only necessary when creating an empty entity.\n pub fn commit(self: @This(), cb: *CmdBuf) void {\n self.commitOrErr(cb) catch |err|\n @panic(@errorName(err));\n }\n /// Similar to `commit`, but returns `error.ZcsCmdBufOverflow` on failure instead of\n /// panicking. The command buffer is left in an undefined state on error, see the top level\n /// documentation on `CmdBuf` for more info.\n pub fn commitOrErr(self: @This(), cb: *CmdBuf) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeCommit(cb, self);\n }\n\n /// Options for `changeArchImmediate`.\n pub fn ChangeArchImmediateOptions(Add: type) type {\n comptime var has_defaults = true;\n for (@typeInfo(Add).@\"struct\".fields) |field| {\n if (field.default_value_ptr == null) {\n has_defaults = false;\n break;\n }\n }\n if (has_defaults) {\n return struct {\n add: Add = .{},\n remove: CompFlag.Set = .{},\n };\n } else {\n return struct {\n add: Add,\n remove: CompFlag.Set = .{},\n };\n }\n }\n\n /// Adds the listed components and then removes the listed component IDs.\n ///\n /// `Add` is a tuple or struct of components that may be added by `changes`. They may be\n /// optional types to allow deciding whether or not to add them at runtime.\n ///\n /// Returns `true` if the change was made, returns `false` if it couldn't be made because the\n /// entity doesn't exist.\n ///\n /// Invalidates pointers.\n pub fn changeArchImmediate(\n self: @This(),\n es: *Entities,\n Add: type,\n changes: ChangeArchImmediateOptions(Add),\n ) bool {\n return self.changeArchImmediateOrErr(es, Add, changes) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `changeArchImmediate`, but returns an error on failure instead of panicking.\n pub fn changeArchImmediateOrErr(\n self: @This(),\n es: *Entities,\n Add: type,\n changes: ChangeArchImmediateOptions(Add),\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!bool {\n es.pointer_generation.increment();\n\n // Build a set of component types to add/remove\n var add_comps: CompFlag.Set = .{};\n inline for (@typeInfo(Add).@\"struct\".fields) |field| {\n const Comp = zcs.view.Unwrap(field.type);\n if (@typeInfo(field.type) != .optional or @field(changes.add, field.name) != null) {\n add_comps.insert(CompFlag.registerImmediate(typeId(Comp)));\n }\n }\n\n // Apply the archetype change, early out if the entity doesn't exist\n if (!try self.changeArchUninitImmediateOrErr(es, .{\n .add = add_comps,\n .remove = changes.remove,\n })) return false;\n\n const entity_loc = es.handle_tab.get(self.key).?;\n const new_chunk = entity_loc.chunk.get(&es.chunk_pool).?;\n inline for (@typeInfo(Add).@\"struct\".fields) |field| {\n const Comp = zcs.view.Unwrap(field.type);\n if (@typeInfo(field.type) != .optional or @field(changes.add, field.name) != null) {\n // Unwrapping the flag is safe because we already registered it above\n const flag = typeId(Comp).comp_flag.?;\n if (!changes.remove.contains(flag)) {\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const offset = new_chunk.header().comp_buf_offsets.values[@intFromEnum(flag)];\n // Safe because we added it above\n assert(offset != 0);\n const comp: *Comp = @ptrFromInt(@intFromPtr(new_chunk) +\n offset +\n @intFromEnum(entity_loc.index_in_chunk) * @sizeOf(Comp));\n comp.* = @as(?Comp, @field(changes.add, field.name)).?;\n }\n }\n }\n\n return true;\n }\n\n /// Options for `changeArchAnyImmediate`.\n pub const ChangeArchAnyImmediateOptions = struct {\n add: []const Any = &.{},\n remove: CompFlag.Set = .initEmpty(),\n };\n\n /// Similar to `changeArchImmediateOrErr`, but doesn't require comptime types.\n pub fn changeArchAnyImmediate(\n self: @This(),\n es: *Entities,\n changes: ChangeArchAnyImmediateOptions,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!bool {\n es.pointer_generation.increment();\n\n // Build a set of component types to add/remove\n var add_comps: CompFlag.Set = .{};\n for (changes.add) |comp| {\n add_comps.insert(CompFlag.registerImmediate(comp.id));\n }\n\n // Apply the archetype change, early out if the entity doesn't exist\n if (!try self.changeArchUninitImmediateOrErr(es, .{\n .add = add_comps,\n .remove = changes.remove,\n })) return false;\n\n // Initialize the components\n const entity_loc = es.handle_tab.get(self.key).?;\n const chunk = entity_loc.chunk.get(&es.chunk_pool).?;\n for (changes.add) |comp| {\n // Unwrapping the flag is safe because we already registered it above\n const flag = comp.id.comp_flag.?;\n if (!changes.remove.contains(flag)) {\n // Unwrap okay because registered above\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const offset = chunk.header().comp_buf_offsets.values[@intFromEnum(flag)];\n assert(offset != 0);\n const dest_unsized: [*]u8 = @ptrFromInt(@intFromPtr(chunk) +\n offset +\n @intFromEnum(entity_loc.index_in_chunk) * comp.id.size);\n const dest = dest_unsized[0..comp.id.size];\n @memcpy(dest, comp.bytes());\n }\n }\n\n return true;\n }\n\n /// Options for the uninitialized variants of change archetype.\n pub const ChangeArchUninitImmediateOptions = struct {\n /// Component types to remove.\n remove: CompFlag.Set = .{},\n /// Component types to add.\n add: CompFlag.Set = .{},\n };\n\n /// Similar to `changeArchetypeOrErr`, but does not initialize the components. Furthermore, any\n /// added component's values are considered undefined after this call, even if they were\n /// previously initialized.\n ///\n /// May change internal allocator state even on failure, chunk lists are not destroyed even if\n /// no chunks could be allocated for them at this time.\n ///\n /// Technically we could go slightly faster with compile time known types, similar to\n /// `changeArchImmediate` vs `changeArchAnyImmediate`. This works because `@memcpy` with a\n /// comptime known length tends to be a bit faster. However, in practice, these sorts of\n /// immediate arch changes are only done (or only done in bulk) when loading a level, which\n /// means this function is essentially a noop anyway since there won't be any data to move.\n pub fn changeArchUninitImmediateOrErr(\n self: @This(),\n es: *Entities,\n options: ChangeArchUninitImmediateOptions,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!bool {\n es.pointer_generation.increment();\n\n // Get the handle value and figure out the new arch\n const entity_loc = es.handle_tab.get(self.key) orelse return false;\n const old_chunk = entity_loc.chunk.get(&es.chunk_pool);\n const prev_arch = entity_loc.arch(es);\n var new_arch = prev_arch;\n new_arch = new_arch.unionWith(options.add);\n new_arch = new_arch.differenceWith(options.remove);\n\n // If the entity is committed and the arch hasn't changed, early out\n if (old_chunk) |chunk| {\n const chunk_header = chunk.header();\n if (chunk_header.arch(&es.arches).eql(new_arch)) {\n @branchHint(.unlikely);\n return true;\n }\n }\n\n // Get the new location. As mentioned in the doc comment, it's possible that we'll end up\n // creating a new chunk list but not be able to allocate any chunks for it.\n const chunk_list = try es.arches.getOrPut(&es.chunk_pool, new_arch);\n const new_loc = try chunk_list.append(es, self);\n const new_chunk = new_loc.chunk.get(&es.chunk_pool).?;\n errdefer comptime unreachable;\n\n // Initialize the new components to undefined\n if (std.debug.runtime_safety) {\n var added = options.add.differenceWith(options.remove).iterator();\n while (added.next()) |flag| {\n const id = flag.getId();\n const comp_buffer = new_chunk.compsFromId(id).?;\n const comp_offset = @intFromEnum(new_loc.index_in_chunk) * id.size;\n const comp = comp_buffer[comp_offset..][0..id.size];\n @memset(comp, undefined);\n }\n }\n\n // Copy components that aren't being overwritten from the old arch to the new one\n if (old_chunk) |prev_chunk| {\n var move = prev_arch.differenceWith(options.remove)\n .differenceWith(options.add).iterator();\n while (move.next()) |flag| {\n const id = flag.getId();\n\n const new_comp_buffer = new_chunk.compsFromId(id).?;\n const new_comp_offset = @intFromEnum(new_loc.index_in_chunk) * id.size;\n const new_comp = new_comp_buffer[new_comp_offset..][0..id.size];\n\n const prev_comp_buffer = prev_chunk.compsFromId(id).?;\n const prev_comp_offset = @intFromEnum(entity_loc.index_in_chunk) * id.size;\n const prev_comp = prev_comp_buffer[prev_comp_offset..][0..id.size];\n\n @memcpy(new_comp, prev_comp);\n }\n }\n\n // Commit the entity to the new location\n if (old_chunk) |chunk| {\n chunk.swapRemove(es, entity_loc.index_in_chunk);\n } else {\n es.reserved_entities -= 1;\n }\n entity_loc.* = new_loc;\n\n return true;\n }\n\n /// Returns this entity as an optional.\n pub fn toOptional(self: @This()) Optional {\n return .{ .key = self.key.toOptional() };\n }\n\n /// Initializes a `view`, returning `null` if this entity does not exist or is missing any\n /// required components.\n pub fn view(self: @This(), es: *const Entities, View: type) ?View {\n // Check if the entity has the requested components. If the number of components in the view\n // is very large, this measurably improves performance. The cost of the check when not\n // necessary doesn't appear to be measurable.\n const entity_loc = es.handle_tab.get(self.key) orelse return null;\n const chunk = entity_loc.chunk.get(&es.chunk_pool) orelse return null;\n const view_arch = zcs.view.comps(View, .{ .size = .one }) orelse return null;\n const entity_arch = chunk.header().list.arch(&es.arches);\n if (!entity_arch.supersetOf(view_arch)) return null;\n\n // Fill in the view and return it\n var result: View = undefined;\n inline for (@typeInfo(View).@\"struct\".fields) |field| {\n const Unwrapped = zcs.view.UnwrapField(field.type, .{ .size = .one });\n if (Unwrapped == Entity) {\n @field(result, field.name) = self;\n } else {\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const offset = if (typeId(Unwrapped).comp_flag) |flag|\n chunk.header().comp_buf_offsets.values[@intFromEnum(flag)]\n else\n 0;\n if (@typeInfo(field.type) == .optional and offset == 0) {\n @field(result, field.name) = null;\n } else {\n assert(offset != 0); // Archetype already checked\n const comps_addr = @intFromPtr(chunk) + offset;\n const comp_addr = comps_addr +\n @intFromEnum(entity_loc.index_in_chunk) * @sizeOf(Unwrapped);\n @field(result, field.name) = @ptrFromInt(comp_addr);\n }\n }\n }\n return result;\n }\n\n /// Similar to `viewOrAddImmediate`, but for a single component.\n pub fn getOrAddImmediate(\n self: @This(),\n es: *Entities,\n T: type,\n default: T,\n ) ?T {\n return self.getOrAddImmediateOrErr(es, T, default) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `getOrAddImmediate`, but for a single component.\n pub fn getOrAddImmediateOrErr(\n self: @This(),\n es: *Entities,\n T: type,\n default: T,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!?*T {\n const result = try self.viewOrAddImmediateOrErr(es, struct { *T }, .{&default}) orelse\n return null;\n return result[0];\n }\n\n /// Similar to `view`, but will attempt to fill in any non-optional missing components with\n /// the defaults from the `comps` view if present.\n ///\n /// Invalidates pointers.\n pub fn viewOrAddImmediate(\n self: @This(),\n es: *Entities,\n View: type,\n comps: anytype,\n ) ?View {\n return self.viewOrAddImmediateOrErr(es, View, comps) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `viewOrAddImmediate` but returns, but returns an error on failure instead of\n /// panicking.\n pub fn viewOrAddImmediateOrErr(\n self: @This(),\n es: *Entities,\n View: type,\n comps: anytype,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!?View {\n // Create the view, possibly leaving some components uninitialized\n const result = (try self.viewOrAddUninitImmediateOrErr(es, View)) orelse return null;\n\n // Fill in any uninitialized components and return the view\n inline for (@typeInfo(View).@\"struct\".fields) |field| {\n const Unwrapped = zcs.view.UnwrapField(field.type, .{ .size = .one });\n if (@hasField(@TypeOf(comps), field.name) and\n result.uninitialized.contains(typeId(Unwrapped).comp_flag.?))\n {\n @field(result.view, field.name).* = @field(comps, field.name).*;\n }\n }\n return result.view;\n }\n\n /// The result of a `viewOrAddUninit*` call.\n pub fn VoaUninitResult(View: type) type {\n return struct {\n uninitialized: CompFlag.Set,\n view: View,\n };\n }\n\n /// Similar to `viewOrAddImmediate`, but leaves the added components uninitialized.\n pub fn viewOrAddUninitImmediate(\n self: @This(),\n es: *Entities,\n View: type,\n ) ?VoaUninitResult(View) {\n return self.viewOrAddUninitImmediate(es, View) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `viewOrAddImmediate`, but returns an error on failure instead of panicking.\n pub fn viewOrAddUninitImmediateOrErr(\n self: @This(),\n es: *Entities,\n View: type,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!?VoaUninitResult(View) {\n es.pointer_generation.increment();\n\n // Figure out which components are missing\n const entity_loc = es.handle_tab.get(self.key) orelse return null;\n var view_arch: CompFlag.Set = .{};\n inline for (@typeInfo(View).@\"struct\".fields) |field| {\n if (field.type != Entity and @typeInfo(field.type) != .optional) {\n const Unwrapped = zcs.view.UnwrapField(field.type, .{ .size = .one });\n const flag = CompFlag.registerImmediate(typeId(Unwrapped));\n view_arch.insert(flag);\n }\n }\n const curr_arch = entity_loc.arch(es);\n const uninitialized = view_arch.differenceWith(curr_arch);\n if (!curr_arch.supersetOf(view_arch)) {\n assert(try self.changeArchUninitImmediateOrErr(es, .{ .add = uninitialized }));\n }\n\n // Create and return the view\n return .{\n .view = self.view(es, View).?,\n .uninitialized = uninitialized,\n };\n }\n\n /// Default formatting.\n pub fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void {\n return self.key.format(writer);\n }\n\n /// Returns the archetype of the entity. If it has been destroyed or is not yet committed, the\n /// empty archetype will be returned.\n pub fn arch(self: @This(), es: *const Entities) CompFlag.Set {\n const entity_loc = es.handle_tab.get(self.key) orelse return .{};\n return entity_loc.arch(es);\n }\n};\n"], ["/ZCS/src/Entities.zig", "//! Storage for entities.\n//!\n//! See `SlotMap` for how handle safety works.\n//!\n//! See `README.md` for more information.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\nconst tracy = @import(\"tracy\");\n\nconst Allocator = std.mem.Allocator;\n\nconst Zone = tracy.Zone;\n\nconst log = std.log;\n\nconst zcs = @import(\"root.zig\");\nconst typeId = zcs.typeId;\nconst Any = zcs.Any;\nconst CompFlag = zcs.CompFlag;\nconst Entity = zcs.Entity;\nconst PointerLock = zcs.PointerLock;\nconst TypeId = zcs.TypeId;\nconst ChunkList = zcs.ChunkList;\nconst ChunkPool = zcs.ChunkPool;\nconst Chunk = zcs.Chunk;\nconst HandleTab = zcs.HandleTab;\nconst Arches = zcs.Arches;\nconst CmdBuf = zcs.CmdBuf;\nconst CmdPool = zcs.CmdPool;\nconst view = zcs.view;\n\nconst Entities = @This();\n\nhandle_tab: HandleTab,\narches: Arches,\npointer_generation: PointerLock.Generation = .{},\nreserved_entities: usize = 0,\nchunk_pool: ChunkPool,\nwarned_saturated: u64 = 0,\nwarned_capacity: bool = false,\nwarned_chunk_pool: bool = false,\nwarned_arches: bool = false,\nwarn_ratio: f32,\n\nconst tracy_es_committed = \"zcs: committed entities\";\nconst tracy_es_reserved = \"zcs: reserved entities\";\nconst tracy_es_saturated = \"zcs: saturated entities\";\nconst tracy_chunks = \"zcs: reserved chunks\";\nconst tracy_arches = \"zcs: archetypes\";\n\n/// Options for `init`.\npub const InitOptions = struct {\n /// Used to allocate the entity storage.\n gpa: Allocator,\n /// The capacity of the entity storage.\n cap: Capacity = .{},\n /// When usage of preallocated buffers exceeds this ratio of full capacity, emit a warning.\n warn_ratio: f32 = 0.2,\n};\n\n/// The capacity of `Entities`.\npub const Capacity = struct {\n /// The max number of entities.\n entities: u32 = 1000000,\n /// The max number of archetypes.\n arches: u32 = 64,\n /// The number of chunks to allocate.\n chunks: u16 = 4096,\n /// The size of a single chunk in bytes.\n chunk: u32 = 65536,\n};\n\n/// Initializes the entity storage with the given capacity.\npub fn init(options: InitOptions) Allocator.Error!@This() {\n const zone = Zone.begin(.{ .src = @src() });\n defer zone.end();\n\n var handle_tab: HandleTab = try .init(options.gpa, options.cap.entities);\n errdefer handle_tab.deinit(options.gpa);\n\n var chunk_pool: ChunkPool = try .init(options.gpa, .{\n .chunks = options.cap.chunks,\n .chunk = options.cap.chunk,\n });\n errdefer chunk_pool.deinit(options.gpa);\n\n var arches: Arches = try .init(options.gpa, options.cap.arches);\n errdefer arches.deinit(options.gpa);\n\n if (tracy.enabled) {\n var buf: [1024]u8 = undefined;\n const info = std.fmt.bufPrintZ(\n &buf,\n \"{}\",\n .{options},\n ) catch @panic(\"OOB\");\n tracy.appInfo(info);\n\n for ([_][:0]const u8{\n tracy_es_committed,\n tracy_es_reserved,\n tracy_es_saturated,\n tracy_chunks,\n tracy_arches,\n }) |name| {\n tracy.plotConfig(.{\n .name = name,\n .format = .number,\n .mode = .line,\n .fill = true,\n });\n }\n }\n\n return .{\n .handle_tab = handle_tab,\n .arches = arches,\n .chunk_pool = chunk_pool,\n .warn_ratio = options.warn_ratio,\n };\n}\n\n/// Destroys the entity storage.\npub fn deinit(self: *@This(), gpa: Allocator) void {\n self.arches.deinit(gpa);\n self.chunk_pool.deinit(gpa);\n self.handle_tab.deinit(gpa);\n self.* = undefined;\n}\n\n/// Destroys all entities matching the given arch immediately.\npub fn destroyArchImmediate(self: *@This(), arch: CompFlag.Set) void {\n self.pointer_generation.increment();\n var chunk_lists_iter = self.arches.iterator(self, arch);\n while (chunk_lists_iter.next(self)) |chunk_list| {\n var chunk_list_iter = chunk_list.iterator(self);\n while (chunk_list_iter.next(self)) |chunk| {\n var chunk_iter = chunk.iterator(self);\n while (chunk_iter.next(self)) |entity| {\n self.handle_tab.remove(entity.key);\n }\n chunk.clear(self);\n }\n }\n}\n\n/// Recycles all entities compatible with the given archetype. This causes their handles to be\n/// dangling, prefer `destroyArchImmediate` unless you're implementing a high throughput event\n/// system.\n///\n/// Invalidates pointers.\npub fn recycleArchImmediate(self: *@This(), arch: CompFlag.Set) void {\n self.pointer_generation.increment();\n var chunk_lists_iter = self.arches.iterator(self, arch);\n while (chunk_lists_iter.next(self)) |chunk_list| {\n var chunk_list_iter = chunk_list.iterator(self);\n while (chunk_list_iter.next(self)) |chunk| {\n var chunk_iter = chunk.iterator(self);\n while (chunk_iter.next(self)) |entity| {\n self.handle_tab.recycle(entity.key);\n }\n chunk.clear(self);\n }\n }\n}\n\n/// Recycles all entities.\n///\n/// Invalidates pointers.\npub fn recycleImmediate(self: *@This()) void {\n self.pointer_generation.increment();\n self.handle_tab.recycleAll();\n self.reserved_entities = 0;\n}\n\n/// Returns the current number of entities.\npub fn count(self: *const @This()) usize {\n return self.handle_tab.count() - self.reserved_entities;\n}\n\n/// Returns the number of reserved but not committed entities that currently exist.\npub fn reserved(self: *const @This()) usize {\n return self.reserved_entities;\n}\n\n/// Given a pointer to a non zero sized component, returns the corresponding entity.\npub fn getEntity(es: *const Entities, from_comp: anytype) Entity {\n const T = @typeInfo(@TypeOf(from_comp)).pointer.child;\n\n // We could technically pack the entity into the pointer value since both are typically 64\n // bits. However, this would break support for getting a slice of zero sized components from\n // a chunk since all would have the same address.\n //\n // I've chosen to support the slice use case and not this one as it's simpler and seems\n // slightly more likely to come up in generic code. I don't expect either to come up\n // particularly often, this decision can be reversed in the future if one or the other turns\n // out to be desirable. If we do this, make sure to have an assertion/test that valid\n // entities are never fully zero since non optional pointers can't be zero unless explicitly\n // annotated as such.\n comptime assert(@sizeOf(T) != 0);\n\n return getEntityFromAny(es, .init(T, from_comp));\n}\n\n/// Similar to `getEntity`, but does not require compile time types. Assumes a valid pointer to a\n/// non zero sized component.\npub fn getEntityFromAny(es: *const Entities, from_comp: Any) Entity {\n // Get the entity index from the chunk\n const loc = getLoc(es, from_comp);\n const indices = loc.chunk.view(es, struct { indices: []const Entity.Index }).?.indices;\n const entity_index = indices[@intFromEnum(loc.index_in_chunk)];\n\n // Get the entity handle\n assert(@intFromEnum(entity_index) < es.handle_tab.next_index);\n const entity = entity_index.toEntity(es);\n\n // Assert that the entity has been committed and return it\n assert(entity.committed(es));\n return entity;\n}\n\n/// Given a valid pointer to a non zero sized component `from`, returns the corresponding\n/// component `Result`, or `null` if there isn't one attached to the same entity. See also\n/// `Entity.get`.\npub fn getComp(es: *const Entities, from: anytype, Result: type) ?*Result {\n const T = @typeInfo(@TypeOf(from)).pointer.child;\n // See `from` for why this isn't allowed.\n comptime assert(@sizeOf(T) != 0);\n const slice = getCompFromAny(es, .init(T, from), typeId(Result));\n return @ptrCast(@alignCast(slice));\n}\n\n/// Similar to `getComp`, but does not require compile time types.\npub fn getCompFromAny(self: *const Entities, from_comp: Any, get_comp_id: TypeId) ?[]u8 {\n // Check assertions\n if (std.debug.runtime_safety) {\n _ = self.getEntityFromAny(from_comp);\n }\n\n // Get the component\n const flag = get_comp_id.comp_flag orelse return null;\n const loc = self.getLoc(from_comp);\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const comp_buf_offset = loc.chunk.header().comp_buf_offsets.values[@intFromEnum(flag)];\n if (comp_buf_offset == 0) return null;\n const unsized: [*]u8 = @ptrFromInt(@intFromPtr(loc.chunk) +\n comp_buf_offset +\n get_comp_id.size * @intFromEnum(loc.index_in_chunk));\n return unsized[0..get_comp_id.size];\n}\n\n/// Looks up the location of an entity from a component.\nfn getLoc(self: *const Entities, from_comp: Any) struct {\n chunk: *Chunk,\n index_in_chunk: Entity.Location.IndexInChunk,\n} {\n // See `from` for why this isn't allowed\n assert(from_comp.id.size != 0);\n\n const pool = &self.chunk_pool;\n const flag = from_comp.id.comp_flag.?;\n\n // Make sure this component is actually in the chunk pool\n assert(@intFromPtr(from_comp.ptr) >= @intFromPtr(pool.buf.ptr));\n assert(@intFromPtr(from_comp.ptr) <= @intFromPtr(&pool.buf[pool.buf.len - 1]));\n\n // Get the corresponding chunk by rounding down to the chunk alignment. This works as chunks\n // are aligned to their size, in part to support this operation.\n const chunk: *Chunk = @ptrFromInt(pool.size_align.backward(@intFromPtr(from_comp.ptr)));\n\n // Calculate the index in this chunk that this component is at\n assert(chunk.header().arch(&self.arches).contains(flag));\n const comp_offset = @intFromPtr(from_comp.ptr) - @intFromPtr(chunk);\n assert(comp_offset != 0); // Zero when missing\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const comp_buf_offset = chunk.header().comp_buf_offsets.values[@intFromEnum(flag)];\n const index_in_chunk = @divExact(comp_offset - comp_buf_offset, from_comp.id.size);\n\n return .{\n .chunk = chunk,\n .index_in_chunk = @enumFromInt(index_in_chunk),\n };\n}\n\n/// Calls `updateEntity` on each compatible entity in an implementation defined order.\n/// See also `forEachChunk`.\n///\n/// `updateEntity` should take `ctx` as an argument, followed by any number of component pointers,\n/// optional component pointers, or `Entity`s.\n///\n/// Invalidating pointers from the update function results in safety checked illegal behavior.\n///\n/// Note that the implementation only relies on ZCS's public interface. If you have a use case that\n/// isn't served well by `forEach`, you can fork it into your code base and modify it as needed.\npub fn forEach(\n self: *@This(),\n comptime name: [:0]const u8,\n comptime updateEntity: anytype,\n ctx: view.params(@TypeOf(updateEntity))[0],\n) void {\n const zone = Zone.begin(.{ .src = @src(), .name = name });\n defer zone.end();\n const params = view.params(@TypeOf(updateEntity));\n const View = view.Tuple(params[1..]);\n var iter = self.iterator(View);\n while (iter.next(self)) |vw| {\n @call(.auto, updateEntity, .{ctx} ++ vw);\n }\n}\n\n/// Prefer `forEach`. Calls `updateChunk` on each compatible chunk in an implementation\n/// defined order, may be useful for batch optimizations.\n///\n/// `updateChunk` should take `ctx` as an argument, followed by any number of component slices,\n/// optional component slices, or const slices of `Entity.Index`.\n///\n/// Invalidating pointers from the update function results in safety checked illegal behavior.\npub fn forEachChunk(\n self: *@This(),\n comptime name: [:0]const u8,\n comptime updateChunk: anytype,\n ctx: view.params(@TypeOf(updateChunk))[0],\n) void {\n const zone = Zone.begin(.{ .src = @src(), .name = name });\n defer zone.end();\n const params = view.params(@TypeOf(updateChunk));\n const required_comps = view.comps(view.Tuple(params[1..]), .{ .size = .slice }) orelse return;\n var chunks = self.chunkIterator(required_comps);\n while (chunks.next(self)) |chunk| {\n const chunk_view = chunk.view(self, view.Tuple(params[1..])).?;\n @call(.auto, updateChunk, .{ctx} ++ chunk_view);\n }\n}\n\n/// Options for `forEachThreaded`.\npub fn ForEachThreadedOptions(f: type) type {\n return struct {\n const acquire_cb = view.params(f)[1] == *CmdBuf;\n const Ctx = view.params(f)[0];\n const Comps = view.Tuple(view.params(f)[if (acquire_cb) 2 else 1..]);\n\n ctx: Ctx,\n tp: *std.Thread.Pool,\n wg: *std.Thread.WaitGroup,\n cp: ?*CmdPool,\n };\n}\n\n/// Similar to `forEach`, but spawns each chunk's work as a thread pool task. Optionally, you may\n/// add an argument of type `*CmdBuf` as the second argument to get a command buffer if `cp` is set\n/// in `options`.\n///\n/// Each chunk may be given its own command buffer in an arbitrary order. As such, the order of\n/// commands within a chunk (and therefore within an `updateEntity` callback) are guaranteed to be\n/// serial, but no guarantees are made about command execution order between chunks.\n///\n/// Keep in mind that this is unlikely to be a performance win unless your update function is very\n/// expensive. Iteration is cheap.\npub fn forEachThreaded(\n self: *@This(),\n comptime name: [:0]const u8,\n comptime updateEntity: anytype,\n options: ForEachThreadedOptions(@TypeOf(updateEntity)),\n) void {\n const zone = Zone.begin(.{ .src = @src(), .name = name });\n defer zone.end();\n\n const Opt = @TypeOf(options);\n\n assert(!Opt.acquire_cb or options.cp != null);\n\n const Wrapped = struct {\n fn processChunk(\n es: *const Entities,\n chunk: *Chunk,\n ctx: @FieldType(@TypeOf(options), \"ctx\"),\n ) void {\n const batch_zone = Zone.begin(.{ .src = @src(), .name = name });\n defer batch_zone.end();\n\n const slices = chunk.view(es, view.Slice(Opt.Comps)).?;\n for (0..chunk.header().len) |i| {\n const vw = view.index(Opt.Comps, es, slices, @intCast(i));\n @call(.auto, updateEntity, .{ctx} ++ vw);\n }\n }\n\n fn processChunkCb(\n es: *const Entities,\n cp: *CmdPool,\n chunk: *Chunk,\n ctx: @FieldType(@TypeOf(options), \"ctx\"),\n ) void {\n const batch_zone = Zone.begin(.{ .src = @src(), .name = name });\n defer batch_zone.end();\n\n const ar = cp.acquire();\n defer cp.release(ar);\n\n const slices = chunk.view(es, view.Slice(Opt.Comps)).?;\n for (0..chunk.header().len) |i| {\n const vw = view.index(Opt.Comps, es, slices, @intCast(i));\n @call(.auto, updateEntity, .{ ctx, ar.cb } ++ vw);\n }\n }\n };\n\n const required_comps = view.comps(Opt.Comps, .{ .size = .one }) orelse return;\n var chunks = self.chunkIterator(required_comps);\n while (chunks.next(self)) |chunk| {\n if (Opt.acquire_cb) {\n options.tp.spawnWg(options.wg, Wrapped.processChunkCb, .{\n self,\n options.cp.?,\n chunk,\n options.ctx,\n });\n } else {\n options.tp.spawnWg(options.wg, Wrapped.processChunk, .{\n self,\n chunk,\n options.ctx,\n });\n }\n }\n}\n\n/// Options for `forEachChunkThreaded`.\npub fn ForEachChunkThreadedOptions(f: type) type {\n return struct {\n const Ctx = view.params(f)[0];\n const Comps = view.Tuple(view.params(f)[1..]);\n\n ctx: Ctx,\n tp: *std.Thread.Pool,\n wg: *std.Thread.WaitGroup,\n };\n}\n\n/// Similar to `forEach`, but with the threading model from `forEachThreaded`.\npub fn forEachChunkThreaded(\n self: *@This(),\n comptime name: [:0]const u8,\n comptime updateChunk: anytype,\n options: ForEachChunkThreadedOptions(@TypeOf(updateChunk)),\n) void {\n const zone = Zone.begin(.{ .src = @src(), .name = name });\n defer zone.end();\n\n const Opt = @TypeOf(options);\n\n const Wrapped = struct {\n fn processChunk(\n es: *const Entities,\n chunk: *Chunk,\n ctx: @FieldType(@TypeOf(options), \"ctx\"),\n ) void {\n const batch_zone = Zone.begin(.{ .src = @src(), .name = name });\n defer batch_zone.end();\n\n const slices = chunk.view(es, view.Slice(Opt.Comps)).?;\n @call(.auto, updateChunk, .{ctx} ++ slices);\n }\n };\n\n const required_comps = view.comps(Opt.Comps, .{ .size = .slice }) orelse return;\n var chunks = self.chunkIterator(required_comps);\n while (chunks.next(self)) |chunk| {\n std.Thread.Pool.spawnWg(options.tp, options.wg, Wrapped.processChunk, .{\n self,\n chunk,\n options.ctx,\n });\n }\n}\n\n/// Emits a warning if any preallocated buffers are past `warn_ratio` capacity, or if any entity\n/// slots have become saturated. If Tracy is enabled, sends usage statistics to Tracy.\n///\n/// It's recommended that you call this once a frame.\npub fn updateStats(self: *@This()) void {\n if (tracy.enabled) {\n tracy.plot(.{\n .name = tracy_es_committed,\n .value = .{ .i64 = @intCast(self.count()) },\n });\n tracy.plot(.{\n .name = tracy_es_reserved,\n .value = .{ .i64 = @intCast(self.reserved()) },\n });\n tracy.plot(.{\n .name = tracy_es_saturated,\n .value = .{ .i64 = @intCast(self.handle_tab.saturated) },\n });\n tracy.plot(.{\n .name = tracy_chunks,\n .value = .{ .i64 = @intCast(self.chunk_pool.reserved) },\n });\n tracy.plot(.{\n .name = tracy_arches,\n .value = .{ .i64 = @intCast(self.arches.map.count()) },\n });\n }\n\n if (self.warn_ratio < 1.0) {\n if (self.handle_tab.saturated > self.warned_saturated) {\n self.warned_saturated = self.handle_tab.saturated;\n log.warn(\"{} entity slots have been saturated\", .{self.warned_saturated});\n }\n\n const handles: f32 = @floatFromInt(self.handle_tab.count());\n const handles_cap: f32 = @floatFromInt(self.handle_tab.capacity);\n if (!self.warned_capacity and handles > handles_cap * self.warn_ratio) {\n self.warned_capacity = true;\n log.warn(\"entities past {d}% capacity\", .{self.warn_ratio * 100.0});\n }\n\n const chunks: f32 = @floatFromInt(self.chunk_pool.reserved);\n const chunks_cap_int = self.chunk_pool.buf.len / self.chunk_pool.size_align.toByteUnits();\n const chunks_cap: f32 = @floatFromInt(chunks_cap_int);\n if (!self.warned_chunk_pool and chunks > chunks_cap * self.warn_ratio) {\n self.warned_chunk_pool = true;\n log.warn(\"chunk pool past {d}% capacity\", .{self.warn_ratio * 100.0});\n }\n\n const arches: f32 = @floatFromInt(self.arches.map.count());\n const arhces_cap: f32 = @floatFromInt(self.arches.map.capacity());\n if (!self.warned_arches and arches > arhces_cap * self.warn_ratio) {\n self.warned_arches = true;\n log.warn(\"archetypes past {d}% capacity\", .{self.warn_ratio * 100.0});\n }\n }\n}\n\n/// Returns an iterator over all the chunks with at least the components in `required_comps` in\n/// an implementation defined order.\n///\n/// Invalidating pointers while iterating results in safety checked illegal behavior.\npub fn chunkIterator(\n self: *const @This(),\n required_comps: CompFlag.Set,\n) ChunkIterator {\n var lists = self.arches.iterator(self, required_comps);\n const chunks: ChunkList.Iterator = if (lists.next(self)) |l| l.iterator(self) else .empty(self);\n var result: ChunkIterator = .{\n .lists = lists,\n .chunks = chunks,\n };\n result.catchUp(self);\n return result;\n}\n\n/// See `chunkIterator`.\npub const ChunkIterator = struct {\n lists: Arches.Iterator,\n chunks: ChunkList.Iterator,\n\n /// Returns the pointer lock.\n pub fn pointerLock(self: *const ChunkIterator) PointerLock {\n return self.lists.pointer_lock;\n }\n\n /// Returns an empty iterator.\n pub fn empty(es: *const Entities) @This() {\n return .{\n .lists = .empty(es),\n .chunks = .empty(es),\n };\n }\n\n /// Advance the internal state so that `peek` is in sync.\n fn catchUp(self: *@This(), es: *const Entities) void {\n while (self.chunks.chunk == null) {\n if (self.lists.next(es)) |chunk_list| {\n self.chunks = chunk_list.iterator(es);\n } else {\n break;\n }\n }\n }\n\n /// Returns the current chunk without advancing.\n pub fn peek(self: *const @This(), es: *const Entities) ?*Chunk {\n return self.chunks.peek(es);\n }\n\n /// Advances the iterator, returning the next entity.\n pub fn next(self: *@This(), es: *const Entities) ?*Chunk {\n self.pointerLock().check(es.pointer_generation);\n\n // We need to loop here because while chunks can't be empty, chunk lists can\n const chunk = while (true) {\n // Get the next chunk in this list\n if (self.chunks.next(es)) |chunk| break chunk;\n\n // If that fails, get the next list and try again\n if (self.lists.next(es)) |chunk_list| {\n @branchHint(.likely);\n self.chunks = chunk_list.iterator(es);\n continue;\n }\n\n // If that fails, return null\n return null;\n };\n\n // Catch up the peek state.\n self.catchUp(es);\n\n return chunk;\n }\n};\n\n/// Returns an iterator over all entities that have at least the components in `required_comps` in\n/// chunk order. The results are of type `View` which is a struct where each field is either a\n/// pointer to a component, an optional pointer to a component, or `Entity`.\n///\n/// In the general case, it's simplest to consider chunk order to be implementation defined.\n/// However, chunk order does have the useful guarantee that entities added to an archetype that\n/// starts out empty with no intermittent deletions will always be iterated in order. This can be\n/// useful for preserving order of transient events which are always cleared in one go.\n///\n/// Invalidating pointers while iterating results in safety checked illegal behavior.\npub fn iterator(self: *const @This(), View: type) Iterator(View) {\n const required_comps: CompFlag.Set = view.comps(View, .{ .size = .one }) orelse\n return .empty(self);\n const chunks = self.chunkIterator(required_comps);\n const slices = if (chunks.peek(self)) |c| c.view(self, view.Slice(View)).? else undefined;\n return .{\n .chunks = chunks,\n .slices = slices,\n .index_in_chunk = 0,\n };\n}\n\n/// See `Entities.iterator`.\npub fn Iterator(View: type) type {\n return struct {\n const Slices = view.Slice(View);\n\n chunks: ChunkIterator,\n slices: Slices,\n index_in_chunk: u32,\n\n /// Returns an empty iterator.\n pub fn empty(es: *const Entities) @This() {\n return .{\n .chunks = .empty(es),\n .slices = undefined,\n .index_in_chunk = 0,\n };\n }\n\n /// Advances the iterator, returning the next view.\n pub fn next(self: *@This(), es: *const Entities) ?View {\n // Check for pointer invalidation\n self.chunks.pointerLock().check(es.pointer_generation);\n\n // Get the current chunk\n var chunk = self.chunks.peek(es) orelse {\n @branchHint(.unlikely);\n return null;\n };\n assert(chunk.header().len > 0); // Free chunks are returned to the chunk pool\n\n // If we're done with the current chunk, advance to the next one\n if (self.index_in_chunk >= chunk.header().len) {\n _ = self.chunks.next(es).?;\n chunk = self.chunks.peek(es) orelse {\n @branchHint(.unlikely);\n return null;\n };\n self.index_in_chunk = 0;\n assert(chunk.header().len > 0); // Free chunks are returned to the chunk pool\n self.slices = chunk.view(es, Slices).?;\n }\n\n // Get the entity and advance the index, this can't overflow the counter since we can't\n // have as many entities as bytes in a chunk since the space would be used up by the\n // entity indices\n const result = view.index(View, es, self.slices, self.index_in_chunk);\n self.index_in_chunk += 1;\n return result;\n }\n };\n}\n"], ["/ZCS/src/chunk.zig", "const std = @import(\"std\");\nconst zcs = @import(\"root.zig\");\n\nconst assert = std.debug.assert;\n\nconst typeId = zcs.typeId;\n\nconst Entity = zcs.Entity;\nconst Entities = zcs.Entities;\nconst PointerLock = zcs.PointerLock;\nconst TypeId = zcs.TypeId;\nconst CompFlag = zcs.CompFlag;\nconst ChunkList = zcs.ChunkList;\nconst Arches = zcs.Arches;\nconst ChunkPool = zcs.ChunkPool;\n\n/// A chunk of entity data where each entity has the same archetype. This type is mostly used\n/// internally, you should prefer the higher level API in most cases.\npub const Chunk = opaque {\n /// A chunk's index in its `ChunkPool`.\n pub const Index = enum(u32) {\n /// The none index. The capacity is always less than this value, so there's no overlap.\n none = std.math.maxInt(u32),\n _,\n\n /// Gets a chunk from the chunk ID.\n pub fn get(self: Index, pool: *const ChunkPool) ?*Chunk {\n if (self == .none) return null;\n const byte_idx = @shlExact(\n @intFromEnum(self),\n @intCast(@intFromEnum(pool.size_align)),\n );\n const result: *Chunk = @ptrCast(&pool.buf[byte_idx]);\n assert(@intFromEnum(self) < pool.reserved);\n assert(pool.indexOf(result) == self);\n return result;\n }\n };\n\n /// Meta information for a chunk.\n pub const Header = struct {\n /// The offsets to each component, or 0 for each that is missing.\n ///\n /// This is also stored on the chunk list, but duplicating this state to the chunk\n /// measurably improves benchmarks, likely due to reducing cache misses.\n comp_buf_offsets: std.enums.EnumArray(CompFlag, u32),\n /// The chunk list this chunk is part of, if any.\n list: ChunkList.Index,\n /// The next chunk, if any.\n next: Index = .none,\n /// The previous chunk, if any.\n prev: Index = .none,\n /// The next chunk with available space, if any.\n next_avail: Index = .none,\n /// The previous chunk with available space, if any.\n prev_avail: Index = .none,\n /// The number of entities in this chunk.\n len: u32,\n\n /// Returns this chunk's archetype. When checking for individual components, prefer checking\n /// `comp_buf_offsets`. This value larger but nearer in memory.\n pub fn arch(self: *const @This(), lists: *const Arches) CompFlag.Set {\n return self.list.arch(lists);\n }\n };\n\n /// An offset from the start of a chunk to a component buffer.\n pub const CompBufOffset = enum(u32) {\n none = 0,\n _,\n\n pub inline fn unwrap(self: @This()) ?u32 {\n const result = @intFromEnum(self);\n if (result == 0) return null;\n return result;\n }\n };\n\n /// Checks for self consistency.\n pub fn checkAssertions(\n self: *Chunk,\n es: *const Entities,\n mode: enum {\n /// By default, chunks may not be empty since if they were they'd have been returned to\n /// the chunk pool.\n default,\n /// However if we're checking a just allocated chunk, or one we're about to clear, we\n /// can skip this check.\n allow_empty,\n },\n ) void {\n if (!std.debug.runtime_safety) return;\n\n const list = self.header().list.get(&es.arches);\n const pool = &es.chunk_pool;\n\n // Validate next/prev\n if (self.header().next.get(pool)) |next_chunk| {\n assert(next_chunk.header().prev.get(pool) == self);\n }\n\n if (self.header().prev.get(pool)) |prev_chunk| {\n assert(prev_chunk.header().next.get(pool) == self);\n }\n\n if (self == list.head.get(pool)) assert(self.header().prev == .none);\n if (self == list.tail.get(pool)) assert(self.header().next == .none);\n\n if (self.header().len >= list.chunk_capacity) {\n // Validate full chunks\n assert(self.header().len == list.chunk_capacity);\n assert(self.header().next_avail == .none);\n assert(self.header().prev_avail == .none);\n } else {\n // Available chunks shouldn't be empty, since empty chunks are returned to the chunk\n // pool. `allow_empty` is set to true when checking a chunk that's about to be returned\n // to the chunk pool.\n assert(mode == .allow_empty or self.header().len > 0);\n\n // Validate next/prev available\n if (self.header().next_avail.get(pool)) |next_available_chunk| {\n assert(next_available_chunk.header().prev_avail.get(pool) == self);\n }\n\n if (self.header().prev_avail.get(pool)) |prev_available_chunk| {\n assert(prev_available_chunk.header().next_avail.get(pool) == self);\n }\n\n if (self == list.avail.get(pool)) {\n assert(self.header().prev_avail == .none);\n }\n }\n }\n\n /// Returns a pointer to the chunk header.\n pub inline fn header(self: *Chunk) *Header {\n return @alignCast(@ptrCast(self));\n }\n\n /// Clears the chunk's entity data.\n pub fn clear(self: *Chunk, es: *Entities) void {\n // Get the header and chunk list\n const pool = &es.chunk_pool;\n const index = pool.indexOf(self);\n const list = self.header().list.get(&es.arches);\n\n // Validate this chunk\n self.checkAssertions(es, .allow_empty);\n\n // Remove this chunk from the chunk list head/tail\n if (list.head == index) list.head = self.header().next;\n if (list.tail == index) list.tail = self.header().prev;\n if (list.avail == index) list.avail = self.header().next_avail;\n\n // Remove this chunk from the chunk list normal and available linked lists\n if (self.header().prev.get(pool)) |prev| prev.header().next = self.header().next;\n if (self.header().next.get(pool)) |next| next.header().prev = self.header().prev;\n if (self.header().prev_avail.get(pool)) |prev| prev.header().next_avail = self.header().next_avail;\n if (self.header().next_avail.get(pool)) |next| next.header().prev_avail = self.header().prev_avail;\n\n // Reset this chunk, and add it to the pool's free list\n self.header().* = undefined;\n self.header().next = es.chunk_pool.free;\n es.chunk_pool.free = index;\n\n // Validate the chunk list\n list.checkAssertions(es);\n }\n\n /// Returns an entity slice view of type `View` into this chunk. See `zcs.view`.\n pub fn view(self: *@This(), es: *const Entities, View: type) ?View {\n const list = self.header().list.get(&es.arches);\n\n const view_arch = zcs.view.comps(View, .{ .size = .slice }) orelse return null;\n const chunk_arch = self.header().arch(&es.arches);\n if (!chunk_arch.supersetOf(view_arch)) return null;\n\n var result: View = undefined;\n inline for (@typeInfo(View).@\"struct\".fields) |field| {\n const As = zcs.view.UnwrapField(field.type, .{ .size = .slice });\n if (As == Entity.Index) {\n const unsized: [*]As = @ptrFromInt(@intFromPtr(self) + list.index_buf_offset);\n const sized = unsized[0..self.header().len];\n @field(result, field.name) = sized;\n } else {\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const offset = if (typeId(As).comp_flag) |flag|\n self.header().comp_buf_offsets.values[@intFromEnum(flag)]\n else\n 0;\n if (@typeInfo(field.type) == .optional and offset == 0) {\n @field(result, field.name) = null;\n } else {\n assert(offset != 0); // Arch checked above\n const unsized: [*]As = @ptrFromInt(@intFromPtr(self) + offset);\n const sized = unsized[0..self.header().len];\n @field(result, field.name) = sized;\n }\n }\n }\n return result;\n }\n\n /// Similar to `view`, but only gets a single component slice and doesn't require comptime\n /// types.\n pub fn compsFromId(self: *Chunk, id: TypeId) ?[]u8 {\n const flag = id.comp_flag orelse return null;\n // https://github.com/Games-by-Mason/ZCS/issues/24\n const offset = self.header().comp_buf_offsets.values[@intFromEnum(flag)];\n if (offset == 0) return null;\n const ptr: [*]u8 = @ptrFromInt(@intFromPtr(self) + offset);\n return ptr[0 .. self.header().len * id.size];\n }\n\n /// Swap removes an entity from the chunk, updating the location of the moved entity. This is\n /// typically used internally, for external uses you're likely looking for\n /// `Entity.destroy` or `Entity.destroyImmediate`.\n pub fn swapRemove(\n self: *@This(),\n es: *Entities,\n index_in_chunk: Entity.Location.IndexInChunk,\n ) void {\n const pool = &es.chunk_pool;\n const index = pool.indexOf(self);\n const list = self.header().list.get(&es.arches);\n const was_full = self.header().len >= list.chunk_capacity;\n\n // Get the last entity\n const indices = @constCast(self.view(es, struct {\n indices: []const Entity.Index,\n }).?.indices);\n const new_len = self.header().len - 1;\n const moved = indices[new_len];\n\n // Early out if we're popping the end of the list\n if (@intFromEnum(index_in_chunk) == new_len) {\n // Clear the previous entity data\n if (std.debug.runtime_safety) {\n indices[@intFromEnum(index_in_chunk)] = undefined;\n var it = self.header().arch(&es.arches).iterator();\n while (it.next()) |flag| {\n const id = flag.getId();\n const comp_buffer = self.compsFromId(id).?;\n const comp_offset = new_len * id.size;\n const comp = comp_buffer[comp_offset..][0..id.size];\n @memset(comp, undefined);\n }\n }\n\n // Update the chunk's length, possibly returning it to the chunk pool\n if (new_len == 0) {\n self.clear(es);\n } else {\n self.header().len = new_len;\n }\n\n // Early out\n return;\n }\n\n // Overwrite the removed entity index with the popped entity index\n indices[@intFromEnum(index_in_chunk)] = moved;\n\n // Move the moved entity's components\n {\n var move = self.header().arch(&es.arches).iterator();\n while (move.next()) |flag| {\n const id = flag.getId();\n\n const comp_buffer = self.compsFromId(id).?;\n const new_comp_offset = @intFromEnum(index_in_chunk) * id.size;\n const new_comp = comp_buffer[new_comp_offset..][0..id.size];\n\n const prev_comp_offset = new_len * id.size;\n const prev_comp = comp_buffer[prev_comp_offset..][0..id.size];\n\n @memcpy(new_comp, prev_comp);\n @memset(prev_comp, undefined);\n }\n }\n\n // Pop the last entity\n self.header().len = new_len;\n\n // Update the location of the moved entity in the handle table\n const moved_loc = &es.handle_tab.slots[@intFromEnum(moved)].value;\n assert(moved_loc.chunk.get(&es.chunk_pool) == self);\n moved_loc.index_in_chunk = index_in_chunk;\n\n // If this chunk was previously full, add it to this chunk list's available list\n if (was_full) {\n if (list.avail.get(pool)) |head| {\n // Don't disturb the front of the available list if there is one, this decreases\n // fragmentation by guaranteeing that we fill one chunk at a time.\n self.header().next_avail = head.header().next_avail;\n if (self.header().next_avail.get(pool)) |next_avail| {\n next_avail.header().prev_avail = index;\n }\n self.header().prev_avail = list.avail;\n head.header().next_avail = index;\n } else {\n // If the available list is empty, set it to this chunk\n list.avail = index;\n }\n }\n\n list.checkAssertions(es);\n self.checkAssertions(es, .default);\n }\n\n /// Returns an iterator over this chunk's entities.\n ///\n /// Invalidating pointers while iterating results in safety checked illegal behavior.\n pub fn iterator(self: *@This(), es: *const Entities) Iterator {\n return .{\n .chunk = self,\n .index_in_chunk = @enumFromInt(0),\n .pointer_lock = es.pointer_generation.lock(),\n };\n }\n\n /// An iterator over a chunk's entities.\n pub const Iterator = struct {\n chunk: *Chunk,\n index_in_chunk: Entity.Location.IndexInChunk,\n pointer_lock: PointerLock,\n\n pub fn next(self: *@This(), es: *const Entities) ?Entity {\n self.pointer_lock.check(es.pointer_generation);\n if (@intFromEnum(self.index_in_chunk) >= self.chunk.header().len) {\n @branchHint(.unlikely);\n return null;\n }\n const indices = self.chunk.view(es, struct { indices: []const Entity.Index }).?.indices;\n const entity_index = indices[@intFromEnum(self.index_in_chunk)];\n self.index_in_chunk = @enumFromInt(@intFromEnum(self.index_in_chunk) + 1);\n return entity_index.toEntity(es);\n }\n };\n};\n"], ["/ZCS/src/CmdBuf.zig", "//! Buffers ECS commands for later execution.\n//!\n//! This allows queuing destructive operations while iterating, or from multiple threads safely by\n//! assigning each thread its own command buffer. All commands are noops if the entity in question\n//! is destroyed before the time of execution.\n//!\n//! `CmdBuf` allocates at init time, and then never again. It should be cleared and reused when\n//! possible.\n//!\n//! All exec methods may invalidate iterators, but by convention only the high level\n//! `execImmediate*` explicitly calls `es.pointer_generation.increment()`. If you are writing your\n//! own exec function, you should call this yourself.\n//!\n//! Some command buffer modifications leave the command buffer in an undefined state on failure, this\n//! is documented on the relevant functions. Trying to execute a command buffer invalidated in this\n//! way results in safety checked illegal behavior. This design means that these functions are\n//! typically not useful in real applications since you can't recover the CB after the error, rather\n//! they're intended for tests. While it would be possible to preserve valid state by restoring the\n//! lengths, this doesn't tend to be useful for real applications and substantially affects\n//! performance in benchmarks.\n\nconst std = @import(\"std\");\nconst tracy = @import(\"tracy\");\nconst zcs = @import(\"root.zig\");\n\nconst log = std.log;\n\nconst meta = zcs.meta;\n\nconst assert = std.debug.assert;\nconst Allocator = std.mem.Allocator;\n\nconst Zone = tracy.Zone;\n\nconst Entities = zcs.Entities;\nconst Entity = zcs.Entity;\nconst Any = zcs.Any;\nconst TypeId = zcs.TypeId;\nconst CompFlag = zcs.CompFlag;\n\nconst CmdBuf = @This();\nconst Subcmd = @import(\"subcmd.zig\").Subcmd;\n\nconst Binding = struct {\n pub const none: @This() = .{ .entity = .none };\n entity: Entity.Optional = .none,\n destroyed: bool = false,\n};\n\nname: ?[:0]const u8,\ntags: std.ArrayListUnmanaged(Subcmd.Tag),\nargs: std.ArrayListUnmanaged(u64),\ndata: std.ArrayListAlignedUnmanaged(u8, zcs.TypeInfo.max_align),\nbinding: Binding = .{ .entity = .none },\nreserved: std.ArrayListUnmanaged(Entity),\ninvalid: if (std.debug.runtime_safety) bool else void,\nwarn_ratio: f32,\n\n/// Options for `init`.\npub const InitOptions = struct {\n /// The debug name for this command buffer.\n ///\n /// Used in warnings and plots, see `updateStats`.\n name: ?[:0]const u8,\n /// Used to allocate the command buffer.\n gpa: Allocator,\n /// Entities are reserved from here.\n es: *Entities,\n /// The capacity of the buffer.\n cap: Capacity = .{},\n /// If more than this ratio of the command buffer is used as measured by `worstCaseUsage`, a\n /// warning will be emitted by `Exec.checkStats`.\n warn_ratio: f32 = 0.2,\n};\n\n/// The capacity of a command buffer.\npub const Capacity = struct {\n /// The default number of commands to reserve.\n pub const default_cmds = 100000;\n /// By default, `cmds / entities_ratio` commands are reserved.\n pub const entities_ratio = 4;\n\n /// Space for at least this many commands will be reserved. If `null`, allocates `default_cmds`.\n ///\n /// Being optional allows `CmdPool` to override this default with a lower value.\n cmds: ?usize = null,\n /// Space for at least this much command data will be reserved. Keep in mind that padding may\n /// vary per platform.\n data: union(enum) {\n bytes: usize,\n bytes_per_cmd: u32,\n } = .{ .bytes_per_cmd = 2 * 16 * @sizeOf(f32) },\n /// Sets the number of entities to reserve up front. See `entities_ratio` for the `null` case.\n reserved_entities: ?usize = null,\n\n /// Returns the number of reserved commands requested.\n fn getCmds(self: @This()) usize {\n return self.cmds orelse default_cmds;\n }\n\n /// Returns the number of data bytes requested.\n fn dataBytes(self: @This()) usize {\n return switch (self.data) {\n .bytes => |bytes| bytes,\n .bytes_per_cmd => |bytes_per_cmd| self.getCmds() * bytes_per_cmd,\n };\n }\n\n /// Returns the number of reserved entities requested.\n fn reservedEntities(self: @This()) usize {\n return self.reserved_entities orelse self.getCmds() / entities_ratio;\n }\n};\n\n/// Initializes a command buffer.\npub fn init(options: InitOptions) error{ OutOfMemory, ZcsEntityOverflow }!@This() {\n const zone = Zone.begin(.{ .src = @src() });\n defer zone.end();\n comptime assert(CompFlag.max < std.math.maxInt(u64));\n\n // Each command can have at most two tags\n _ = Subcmd.rename_when_changing_encoding;\n const cmds_cap = options.cap.getCmds() * 2;\n const tags_zone = Zone.begin(.{ .name = \"tags\", .src = @src() });\n var tags: std.ArrayListUnmanaged(Subcmd.Tag) = try .initCapacity(options.gpa, cmds_cap);\n errdefer tags.deinit(options.gpa);\n tags_zone.end();\n\n // Each command can have at most 3 args (the add ptr subcommand does a bind which has one\n // arg if it's not skipped, and then it also passes the component ID and pointer as args as\n // well.\n _ = Subcmd.rename_when_changing_encoding;\n const args_zone = Zone.begin(.{ .name = \"args\", .src = @src() });\n const args_cap = cmds_cap * 3;\n var args: std.ArrayListUnmanaged(u64) = try .initCapacity(options.gpa, args_cap);\n errdefer args.deinit(options.gpa);\n args_zone.end();\n\n const any_bytes_zone = Zone.begin(.{ .name = \"any bytes\", .src = @src() });\n var data: std.ArrayListAlignedUnmanaged(u8, zcs.TypeInfo.max_align) = try .initCapacity(\n options.gpa,\n options.cap.dataBytes(),\n );\n errdefer data.deinit(options.gpa);\n any_bytes_zone.end();\n\n const reserved_zone = Zone.begin(.{ .name = \"reserved\", .src = @src() });\n var reserved: std.ArrayListUnmanaged(Entity) = try .initCapacity(\n options.gpa,\n options.cap.reservedEntities(),\n );\n errdefer reserved.deinit(options.gpa);\n for (0..reserved.capacity) |_| {\n reserved.appendAssumeCapacity(try Entity.reserveImmediateOrErr(options.es));\n }\n reserved_zone.end();\n\n if (tracy.enabled) {\n if (options.name) |name| {\n tracy.plotConfig(.{\n .name = name,\n .format = .percentage,\n .mode = .line,\n .fill = true,\n });\n }\n }\n\n return .{\n .name = options.name,\n .reserved = reserved,\n .tags = tags,\n .args = args,\n .data = data,\n .invalid = if (std.debug.runtime_safety) false else {},\n .warn_ratio = options.warn_ratio,\n };\n}\n\n/// Destroys the command buffer.\npub fn deinit(self: *@This(), gpa: Allocator, es: *Entities) void {\n for (self.reserved.items) |entity| assert(entity.destroyImmediate(es));\n self.reserved.deinit(gpa);\n self.data.deinit(gpa);\n self.args.deinit(gpa);\n self.tags.deinit(gpa);\n self.* = undefined;\n}\n\n/// Appends an extension command to the buffer.\n///\n/// See notes on `Entity.add` with regards to performance and pass by value vs pointer.\npub inline fn ext(self: *@This(), T: type, payload: T) void {\n // Don't get tempted to remove inline from here! It's required for `isComptimeKnown`.\n comptime assert(@typeInfo(@TypeOf(ext)).@\"fn\".calling_convention == .@\"inline\");\n self.extOrErr(T, payload) catch |err|\n @panic(@errorName(err));\n}\n\n/// Similar to `ext`, but returns an error on failure instead of panicking. The command buffer is\n/// left in an undefined state on error, see the top level documentation for more detail.\npub inline fn extOrErr(self: *@This(), T: type, payload: T) error{ZcsCmdBufOverflow}!void {\n // Don't get tempted to remove inline from here! It's required for `isComptimeKnown`.\n comptime assert(@typeInfo(@TypeOf(extOrErr)).@\"fn\".calling_convention == .@\"inline\");\n if (@sizeOf(T) > @sizeOf(*T) and meta.isComptimeKnown(payload)) {\n const Interned = struct {\n const value = payload;\n };\n try self.extPtr(T, comptime &Interned.value);\n } else {\n try self.extVal(T, payload);\n }\n}\n\n/// Similar to `extOrErr`, but forces the command to be copied by value to the command buffer.\n/// Prefer `ext`.\npub fn extVal(self: *@This(), T: type, payload: T) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeExtVal(self, T, payload);\n}\n\n/// Similar to `extOrErr`, but forces the command to be copied by pointer to the command buffer.\n/// Prefer `ext`.\npub fn extPtr(self: *@This(), T: type, payload: *const T) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeExtPtr(self, T, payload);\n}\n\n/// Clears the command buffer for reuse and then refills the reserved entity list to capacity.\n/// Called automatically from `Exec.immediate`.\npub fn clear(self: *@This(), es: *Entities) void {\n self.clearOrErr(es) catch |err|\n @panic(@errorName(err));\n}\n\n/// Similar to `clear`, but returns `error.ZcsEntityOverflow` when failing to refill the reserved\n/// entity list instead of panicking.\npub fn clearOrErr(self: *@This(), es: *Entities) error{ZcsEntityOverflow}!void {\n const zone = Zone.begin(.{ .src = @src() });\n defer zone.end();\n self.data.clearRetainingCapacity();\n self.args.clearRetainingCapacity();\n self.tags.clearRetainingCapacity();\n self.binding = .none;\n while (self.reserved.items.len < self.reserved.capacity) {\n self.reserved.appendAssumeCapacity(try Entity.reserveImmediateOrErr(es));\n }\n}\n\n/// Returns true if this command buffer is empty.\npub fn isEmpty(self: @This()) bool {\n return self.tags.items.len == 0 and self.reserved.items.len == self.reserved.capacity;\n}\n\n/// Returns the ratio of length to capacity for the internal buffer that is the nearest to being\n/// full. Ignores buffers explicitly initialized with 0 capacity.\npub fn worstCaseUsage(self: @This()) f32 {\n const reserved_used: f32 = @floatFromInt(self.reserved.capacity - self.reserved.items.len);\n const reserved_usage = if (self.reserved.capacity == 0)\n 0.0\n else\n reserved_used / @as(f32, @floatFromInt(self.reserved.capacity));\n return @max(\n usage(self.data),\n usage(self.args),\n usage(self.tags),\n reserved_usage,\n );\n}\n\n/// Calculates the usage of a list as a ratio.\nfn usage(list: anytype) f32 {\n if (list.capacity == 0) return 0.0;\n return @as(f32, @floatFromInt(list.items.len)) / @as(f32, @floatFromInt(list.capacity));\n}\n\n/// Returns an iterator over the encoded commands.\npub fn iterator(self: *const @This()) Iterator {\n if (std.debug.runtime_safety) assert(!self.invalid);\n return .{ .decoder = .{ .cb = self } };\n}\n\n/// Emits a warning if over `warn_ratio`. If Tracy is enabled and this command buffer has a name,\n/// update its plots. Called automatically by `Exec`.\npub fn updateStats(self: *const CmdBuf) void {\n const currentUsage = self.worstCaseUsage();\n\n if (tracy.enabled) {\n if (self.name) |name| {\n tracy.plot(.{\n .name = name,\n .value = .{ .f32 = currentUsage * 100.0 },\n });\n }\n }\n\n if (currentUsage > self.warn_ratio) {\n log.warn(\"command buffer past 50% capacity (buffer name = {?s})\", .{self.name});\n }\n}\n\npub const Exec = struct {\n zone: Zone,\n zone_cmd_exec: zcs.ext.ZoneCmd.Exec = .{},\n\n pub fn init() @This() {\n return .{\n .zone = Zone.begin(.{\n .src = @src(),\n }),\n };\n }\n\n /// Executes the command buffer and then clears it.\n ///\n /// Invalidates pointers.\n pub fn immediate(es: *Entities, cb: *CmdBuf) void {\n immediateOrErr(es, cb) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `execImmediate`, but returns an error on failure instead of panicking. On error, the\n /// command buffer will be partially executed.\n pub fn immediateOrErr(\n es: *Entities,\n cb: *CmdBuf,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow, ZcsEntityOverflow }!void {\n var self: @This() = .init();\n\n es.pointer_generation.increment();\n var iter = cb.iterator();\n while (iter.next()) |batch| {\n switch (batch) {\n .arch_change => |arch_change| {\n const delta = arch_change.deltaImmediate();\n _ = try arch_change.execImmediateOrErr(es, delta);\n },\n .ext => |payload| self.extImmediateOrErr(payload),\n }\n }\n\n try self.finish(cb, es);\n }\n\n pub fn extImmediateOrErr(self: *@This(), payload: Any) void {\n self.zone_cmd_exec.extImmediate(payload);\n }\n\n pub fn finish(self: *@This(), cb: *CmdBuf, es: *Entities) error{ZcsEntityOverflow}!void {\n cb.updateStats();\n cb.clear(es);\n self.zone_cmd_exec.finish();\n self.zone.end();\n }\n};\n\n/// A batch of sequential commands that all have the same entity bound.\npub const Batch = union(enum) {\n ext: Any,\n arch_change: ArchChange,\n\n pub const ArchChange = struct {\n /// A description of delta over all archetype change operations.\n pub const Delta = struct {\n add: CompFlag.Set = .{},\n remove: CompFlag.Set = .{},\n destroy: bool = false,\n\n /// Updates the delta for a given operation.\n pub inline fn updateImmediate(self: *@This(), op: Op) void {\n switch (op) {\n .add => |comp| {\n const flag = CompFlag.registerImmediate(comp.id);\n self.add.insert(flag);\n self.remove.remove(flag);\n },\n .remove => |id| {\n const flag = CompFlag.registerImmediate(id);\n self.add.remove(flag);\n self.remove.insert(flag);\n },\n .destroy => self.destroy = true,\n }\n }\n };\n\n /// The bound entity.\n entity: Entity,\n decoder: Subcmd.Decoder,\n\n /// Returns the delta over all archetype change operations.\n pub inline fn deltaImmediate(self: @This()) Delta {\n var delta: Delta = .{};\n var ops = self.iterator();\n while (ops.next()) |op| delta.updateImmediate(op);\n return delta;\n }\n\n /// An iterator over this batch's commands.\n pub inline fn iterator(self: @This()) @This().Iterator {\n return .{\n .decoder = self.decoder,\n };\n }\n\n /// Executes the batch. Returns true if the entity exists before the command is run, false\n /// otherwise.\n ///\n /// See `getArchChangeImmediate` to get the default archetype change argument.\n pub fn execImmediate(self: @This(), es: *Entities, delta: Delta) bool {\n return self.execImmediateOrErr(es, delta) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `execImmediate`, but returns an error on overflow instead of panicking.\n pub inline fn execImmediateOrErr(\n self: @This(),\n es: *Entities,\n delta: Delta,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!bool {\n if (delta.destroy) return self.entity.destroyImmediate(es);\n\n // Issue the change archetype command. If no changes were requested, this will\n // still commit the entity. If the entity doesn't exist, early out.\n if (!try self.entity.changeArchUninitImmediateOrErr(es, .{\n .add = delta.add,\n .remove = delta.remove,\n })) {\n return false;\n }\n\n // Initialize any new components. Note that we check for existence on each because they\n // could have been subsequently removed.\n {\n // Unwrapping these is fine since we just committed the entity if it wasn't\n // committed, or earlied out if it doesn't exist\n const entity_loc = es.handle_tab.get(self.entity.key).?;\n const chunk = entity_loc.chunk.get(&es.chunk_pool).?;\n var ops = self.iterator();\n while (ops.next()) |op| {\n switch (op) {\n .add => |comp| if (comp.id.comp_flag) |flag| {\n const offset = chunk.header()\n .comp_buf_offsets.values[@intFromEnum(flag)];\n if (offset != 0) {\n assert(offset != 0);\n const dest_unsized: [*]u8 = @ptrFromInt(@intFromPtr(chunk) +\n offset +\n @intFromEnum(entity_loc.index_in_chunk) * comp.id.size);\n const dest = dest_unsized[0..comp.id.size];\n @memcpy(dest, comp.bytes());\n }\n },\n .remove,\n .destroy,\n => {},\n }\n }\n }\n\n return true;\n }\n\n /// An archetype change operation.\n pub const Op = union(enum) {\n add: Any,\n remove: TypeId,\n destroy: void,\n };\n\n /// An iterator over this batch's commands.\n ///\n /// Note that the encoder will elide operations immediately following a destroy. This is\n /// intended to simplify writing extensions.\n pub const Iterator = struct {\n decoder: Subcmd.Decoder,\n\n /// Returns the next operation, or `null` if there are none.\n pub inline fn next(self: *@This()) ?Op {\n while (self.decoder.peekTag()) |tag| {\n const op: Op = switch (tag) {\n .add_val => .{ .add = self.decoder.next().?.add_val },\n .add_ptr => .{ .add = self.decoder.next().?.add_ptr },\n .remove => .{ .remove = self.decoder.next().?.remove },\n .destroy => b: {\n _ = self.decoder.next().?.destroy;\n break :b .destroy;\n },\n .bind_entity, .ext_val, .ext_ptr => break,\n };\n\n // Return the operation.\n return op;\n }\n return null;\n }\n };\n };\n};\n\n/// An iterator over batches of encoded commands.\npub const Iterator = struct {\n decoder: Subcmd.Decoder,\n\n /// Returns the next command batch, or `null` if there is none.\n pub inline fn next(self: *@This()) ?Batch {\n _ = Subcmd.rename_when_changing_encoding;\n\n // We just return bind operations here, `Subcmd` handles the add/remove commands.\n while (self.decoder.next()) |cmd| {\n switch (cmd) {\n // We buffer all ops on a given entity into a single command\n .bind_entity => |entity| return .{ .arch_change = .{\n .entity = entity,\n .decoder = self.decoder,\n } },\n .ext_val, .ext_ptr => |payload| return .{ .ext = payload },\n // These are handled by archetype change. We always start archetype change with a\n // bind so this will never miss ops.\n .add_ptr,\n .add_val,\n .remove,\n .destroy,\n => {},\n }\n }\n\n return null;\n }\n};\n"], ["/ZCS/src/type_id.zig", "//! Runtime type information.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\n\nconst zcs = @import(\"root.zig\");\nconst CompFlag = zcs.CompFlag;\n\n/// Runtime information for a type.\npub const TypeInfo = struct {\n /// The maximum allowed alignment.\n pub const max_align: std.mem.Alignment = .@\"16\";\n\n /// The component's type name.\n name: []const u8,\n /// The component type's size.\n size: usize,\n /// The component type's alignment.\n alignment: u8,\n /// If this type has been registered as a component, this holds the component flag. Component\n /// types are registered as they become needed.\n comp_flag: ?CompFlag = null,\n\n /// Returns the type ID for the given type.\n pub inline fn init(comptime T: type) *@This() {\n comptime checkType(T);\n\n return &struct {\n var info: TypeInfo = .{\n .name = @typeName(T),\n .size = @sizeOf(T),\n .alignment = @alignOf(T),\n };\n }.info;\n }\n\n /// Asserts at compile time that ZCS's runtime type information supports this type.\n pub fn checkType(T: type) void {\n // Storing optionals, pointers, and `Entity` directly as components would create\n // ambiguities when creating entity views. It's unfortunate that we have to disallow\n // them, but the extra typing to wrap them in the rare case that you need this ability\n // is expected to be well worth it for the convenience views provide.\n //\n // There's no reason these couldn't be allowed for `Any` in general, but we want to get\n // compile time errors when trying to use bad types, so we just rule them out for any use of\n // `Any` instead.\n //\n // `Entity.Index` and `CmdBuf` are likely indicative of a mistake and so are ruled\n // out.\n if (@typeInfo(T) == .optional or\n T == zcs.Entity or\n T == zcs.Entity.Index or\n T == zcs.CmdBuf)\n {\n @compileError(\"unsupported component type '\" ++ @typeName(T) ++ \"'; consider wrapping in struct\");\n }\n\n comptime assert(@alignOf(T) <= max_align.toByteUnits());\n }\n};\n\n/// This pointer can be used as a unique ID identifying a component type.\npub const TypeId = *TypeInfo;\n"], ["/ZCS/src/subcmd.zig", "const std = @import(\"std\");\nconst assert = std.debug.assert;\n\nconst zcs = @import(\"root.zig\");\nconst typeId = zcs.typeId;\nconst Entity = zcs.Entity;\nconst Any = zcs.Any;\nconst TypeId = zcs.TypeId;\nconst CmdBuf = zcs.CmdBuf;\nconst Entities = zcs.Entities;\n\n/// An unencoded representation of command buffer commands.\npub const Subcmd = union(enum) {\n /// Binds an existing entity.\n bind_entity: Entity,\n /// Destroys the bound entity.\n destroy: void,\n /// Queues a component to be added by value. The type ID is passed as an argument, component\n /// data is passed via any bytes.\n add_val: Any,\n /// Queues a component to be added by pointer. The type ID and a pointer to the component data\n /// are passed as arguments.\n add_ptr: Any,\n /// Queues an extension command to be added by value. The type ID is passed as an argument, the\n /// payload is passed via any bytes.\n ext_val: Any,\n /// Queues an extension command to be added by pointer. The type ID and a pointer to the\n /// component data are passed as arguments.\n ext_ptr: Any,\n /// Queues a component to be removed.\n remove: TypeId,\n\n /// If a new worst case command is introduced, also update the tests!\n pub const rename_when_changing_encoding = {};\n\n pub const Tag = @typeInfo(@This()).@\"union\".tag_type.?;\n\n /// Decodes encoded commands.\n pub const Decoder = struct {\n cb: *const CmdBuf,\n tag_index: usize = 0,\n arg_index: usize = 0,\n comp_bytes_index: usize = 0,\n\n pub inline fn next(self: *@This()) ?Subcmd {\n _ = rename_when_changing_encoding;\n\n // Decode the next command\n if (self.nextTag()) |tag| {\n switch (tag) {\n .bind_entity => {\n const entity: Entity = @bitCast(self.nextArg().?);\n return .{ .bind_entity = entity };\n },\n inline .add_val, .ext_val => |add| {\n @setEvalBranchQuota(2000);\n const id: TypeId = @ptrFromInt(self.nextArg().?);\n const ptr = self.nextAny(id);\n const any: Any = .{\n .id = id,\n .ptr = ptr,\n };\n return switch (add) {\n .add_val => .{ .add_val = any },\n .ext_val => .{ .ext_val = any },\n else => comptime unreachable,\n };\n },\n inline .add_ptr, .ext_ptr => |add| {\n const id: TypeId = @ptrFromInt(self.nextArg().?);\n const ptr: *const anyopaque = @ptrFromInt(self.nextArg().?);\n const any: Any = .{\n .id = id,\n .ptr = ptr,\n };\n switch (add) {\n .add_ptr => return .{ .add_ptr = any },\n .ext_ptr => return .{ .ext_ptr = any },\n else => comptime unreachable,\n }\n },\n .remove => {\n const id: TypeId = @ptrFromInt(self.nextArg().?);\n return .{ .remove = id };\n },\n .destroy => return .destroy,\n }\n }\n\n // Assert that we're fully empty, and return null\n assert(self.tag_index == self.cb.tags.items.len);\n assert(self.arg_index == self.cb.args.items.len);\n assert(self.comp_bytes_index == self.cb.data.items.len);\n return null;\n }\n\n pub inline fn peekTag(self: *@This()) ?Subcmd.Tag {\n if (self.tag_index < self.cb.tags.items.len) {\n return self.cb.tags.items[self.tag_index];\n } else {\n @branchHint(.unlikely);\n return null;\n }\n }\n\n pub inline fn nextTag(self: *@This()) ?Subcmd.Tag {\n const tag = self.peekTag() orelse return null;\n self.tag_index += 1;\n return tag;\n }\n\n pub inline fn nextArg(self: *@This()) ?u64 {\n if (self.arg_index < self.cb.args.items.len) {\n const arg = self.cb.args.items[self.arg_index];\n self.arg_index += 1;\n return arg;\n } else {\n return null;\n }\n }\n\n pub inline fn nextAny(self: *@This(), id: TypeId) *const anyopaque {\n // Align the read\n self.comp_bytes_index = std.mem.alignForward(\n usize,\n self.comp_bytes_index,\n id.alignment,\n );\n\n // Get the pointer as a slice, this way we don't fail on zero sized types\n const bytes = &self.cb.data.items[self.comp_bytes_index..][0..id.size];\n\n // Update the offset and return the pointer\n self.comp_bytes_index += id.size;\n return bytes.ptr;\n }\n };\n\n /// Encode adding a component to an entity by value.\n pub fn encodeAddVal(cb: *CmdBuf, entity: Entity, T: type, comp: T) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeBind(cb, entity);\n try Subcmd.encodeVal(cb, .add_val, T, comp);\n }\n\n /// Encode adding a component to an entity by pointer.\n pub fn encodeAddPtr(cb: *CmdBuf, entity: Entity, T: type, comp: *const T) error{ZcsCmdBufOverflow}!void {\n try Subcmd.encodeBind(cb, entity);\n try Subcmd.encodePtr(cb, .add_ptr, T, comp);\n }\n\n /// Encode an extension command by value.\n pub fn encodeExtVal(cb: *CmdBuf, T: type, payload: T) error{ZcsCmdBufOverflow}!void {\n // Clear the binding. Archetype changes must start with a bind so we don't want it to be\n // cached across other commands.\n cb.binding = .none;\n try Subcmd.encodeVal(cb, .ext_val, T, payload);\n }\n\n /// Encode an extension command by pointer.\n pub fn encodeExtPtr(cb: *CmdBuf, T: type, payload: *const T) error{ZcsCmdBufOverflow}!void {\n // Clear the binding. Archetype changes must start with a bind so we don't want it to be\n // cached across other commands.\n cb.binding = .none;\n try Subcmd.encodePtr(cb, .ext_ptr, T, payload);\n }\n\n /// Encode removing a component from an entity.\n pub fn encodeRemove(cb: *CmdBuf, entity: Entity, id: TypeId) error{ZcsCmdBufOverflow}!void {\n errdefer if (std.debug.runtime_safety) {\n cb.invalid = true;\n };\n try Subcmd.encodeBind(cb, entity);\n if (cb.binding.destroyed) return;\n if (cb.tags.items.len >= cb.tags.capacity) return error.ZcsCmdBufOverflow;\n if (cb.args.items.len >= cb.args.capacity) return error.ZcsCmdBufOverflow;\n cb.tags.appendAssumeCapacity(.remove);\n cb.args.appendAssumeCapacity(@intFromPtr(id));\n }\n\n /// Encode committing an entity.\n pub fn encodeCommit(cb: *CmdBuf, entity: Entity) error{ZcsCmdBufOverflow}!void {\n try encodeBind(cb, entity);\n }\n\n /// Encode destroying an entity.\n pub fn encodeDestroy(cb: *CmdBuf, entity: Entity) error{ZcsCmdBufOverflow}!void {\n errdefer if (std.debug.runtime_safety) {\n cb.invalid = true;\n };\n try Subcmd.encodeBind(cb, entity);\n if (cb.binding.destroyed) return;\n if (cb.tags.items.len >= cb.tags.capacity) return error.ZcsCmdBufOverflow;\n cb.tags.appendAssumeCapacity(.destroy);\n cb.binding.destroyed = true;\n }\n\n /// Encode binding an entity as part of a subcommand.\n fn encodeBind(cb: *CmdBuf, entity: Entity) error{ZcsCmdBufOverflow}!void {\n errdefer if (std.debug.runtime_safety) {\n cb.invalid = true;\n };\n if (cb.binding.entity != entity.toOptional()) {\n if (cb.tags.items.len >= cb.tags.capacity) return error.ZcsCmdBufOverflow;\n cb.binding = .{ .entity = entity.toOptional() };\n cb.tags.appendAssumeCapacity(.bind_entity);\n cb.args.appendAssumeCapacity(@bitCast(entity));\n }\n }\n\n /// Encode a value as part of a subcommand.\n fn encodeVal(cb: *CmdBuf, tag: Tag, T: type, val: T) error{ZcsCmdBufOverflow}!void {\n errdefer if (std.debug.runtime_safety) {\n cb.invalid = true;\n };\n\n if (cb.binding.destroyed) return;\n\n const aligned = std.mem.alignForward(usize, cb.data.items.len, @alignOf(T));\n if (cb.tags.items.len >= cb.tags.capacity) return error.ZcsCmdBufOverflow;\n if (aligned + @sizeOf(T) > cb.data.capacity) return error.ZcsCmdBufOverflow;\n cb.tags.appendAssumeCapacity(tag);\n cb.args.appendAssumeCapacity(@intFromPtr(typeId(T)));\n\n cb.data.items.len = aligned;\n cb.data.appendSliceAssumeCapacity(std.mem.asBytes(&val));\n }\n\n /// Encode a pointer as part of a subcommand.\n fn encodePtr(cb: *CmdBuf, tag: Tag, T: type, ptr: *const T) error{ZcsCmdBufOverflow}!void {\n errdefer if (std.debug.runtime_safety) {\n cb.invalid = true;\n };\n\n if (cb.binding.destroyed) return;\n\n if (cb.tags.items.len >= cb.tags.capacity) return error.ZcsCmdBufOverflow;\n if (cb.args.items.len + 2 > cb.args.capacity) return error.ZcsCmdBufOverflow;\n\n cb.tags.appendAssumeCapacity(tag);\n cb.args.appendAssumeCapacity(@intFromPtr(typeId(T)));\n cb.args.appendAssumeCapacity(@intFromPtr(ptr));\n }\n};\n"], ["/ZCS/src/ext/Node.zig", "//! A component that tracks parent child relationships.\n//!\n//! Node fields must be kept logically consistent. The recommended approach is to only modify nodes\n//! through command buffers, and then use the provided command buffer processing to synchronize\n//! your changes.\n\nconst std = @import(\"std\");\nconst tracy = @import(\"tracy\");\n\nconst assert = std.debug.assert;\n\nconst zcs = @import(\"../root.zig\");\nconst typeId = zcs.typeId;\nconst TypeId = zcs.TypeId;\nconst Entities = zcs.Entities;\nconst Entity = zcs.Entity;\nconst CmdBuf = zcs.CmdBuf;\nconst CompFlag = zcs.CompFlag;\nconst Any = zcs.Any;\n\nconst Zone = tracy.Zone;\n\nconst Node = @This();\n\nparent: Entity.Optional = .none,\nfirst_child: Entity.Optional = .none,\nprev_sib: Entity.Optional = .none,\nnext_sib: Entity.Optional = .none,\n\n/// Returns the parent node, or null if none exists.\npub fn getParent(self: *const @This(), es: *const Entities) ?*Node {\n const parent = self.parent.unwrap() orelse return null;\n return parent.get(es, Node).?;\n}\n\n/// Returns the first child, or null if none exists.\npub fn getFirstChild(self: *const @This(), es: *const Entities) ?*Node {\n const first_child = self.first_child.unwrap() orelse return null;\n return first_child.get(es, Node).?;\n}\n\n/// Returns the previous sibling, or null if none exists.\npub fn getPrevSib(self: *const @This(), es: *const Entities) ?*Node {\n const prev_sib = self.prev_sib.unwrap() orelse return null;\n return prev_sib.get(es, Node).?;\n}\n\n/// Returns the next sibling, or null if none exists.\npub fn getNextSib(self: *const @This(), es: *const Entities) ?*Node {\n const next_sib = self.next_sib.unwrap() orelse return null;\n return next_sib.get(es, Node).?;\n}\n\n/// Similar to the `SetParent` command, but sets the parent immediately.\npub fn setParentImmediate(self: *Node, es: *Entities, parent_opt: ?*Node) void {\n const pointer_lock = es.pointer_generation.lock();\n defer pointer_lock.check(es.pointer_generation);\n\n // If the relationship would result in a cycle, or parent and child are equal, early out.\n if (parent_opt) |parent| {\n if (self == parent) return;\n if (self.isAncestorOf(es, parent)) return;\n }\n\n // Unparent the child\n if (self.getParent(es)) |curr_parent| {\n if (self.getPrevSib(es)) |prev_sib| {\n prev_sib.next_sib = self.next_sib;\n } else {\n curr_parent.first_child = self.next_sib;\n }\n if (self.next_sib.unwrap()) |next_sib| {\n next_sib.get(es, Node).?.prev_sib = self.prev_sib;\n self.next_sib = .none;\n }\n self.prev_sib = .none;\n self.parent = .none;\n }\n\n // Set the new parent\n if (parent_opt) |parent| {\n self.parent = es.getEntity(parent).toOptional();\n self.next_sib = parent.first_child;\n const child_entity = es.getEntity(self);\n if (parent.first_child.unwrap()) |first_child| {\n first_child.get(es, Node).?.prev_sib = child_entity.toOptional();\n }\n parent.first_child = child_entity.toOptional();\n }\n}\n\n/// Destroys a node, its entity, and all of its children. This behavior occurs automatically via\n/// `exec` when an entity with an entity with a node is destroyed.\n///\n/// Invalidates pointers.\npub fn destroyImmediate(unstable_ptr: *@This(), es: *Entities) void {\n // Cache the entity handle since we're about to invalidate pointers\n const e = es.getEntity(unstable_ptr);\n\n // Destroy the children and unparent this node\n unstable_ptr.destroyChildrenAndUnparentImmediate(es);\n\n // Destroy the entity\n assert(e.destroyImmediate(es));\n}\n\n/// Destroys a node's children and then unparents it. This behavior occurs automatically via `exec`\n/// when a node is removed from an entity.\n///\n/// Invalidates pointers.\npub fn destroyChildrenAndUnparentImmediate(unstable_ptr: *@This(), es: *Entities) void {\n const pointer_lock = es.pointer_generation.lock();\n\n // Get an iterator over the node's children and then destroy it\n var children = b: {\n defer pointer_lock.check(es.pointer_generation);\n const self = unstable_ptr; // Not yet disturbed\n\n const iter = self.postOrderIterator(es);\n self.setParentImmediate(es, null);\n self.first_child = .none;\n\n break :b iter;\n };\n\n // Iterate over the children and destroy them, this will invalidate `unstable_ptr`\n es.pointer_generation.increment();\n while (children.next(es)) |curr| {\n assert(es.getEntity(curr).destroyImmediate(es));\n }\n}\n\n/// Returns true if an ancestor of `descendant`, false otherwise. Entities are not ancestors of\n/// themselves.\npub fn isAncestorOf(self: *const @This(), es: *const Entities, descendant: *const Node) bool {\n var curr = descendant.getParent(es) orelse return false;\n while (true) {\n if (curr == self) return true;\n curr = curr.getParent(es) orelse return false;\n }\n}\n\n/// Returns an iterator over the node's immediate children.\npub fn childIterator(self: *const @This()) ChildIterator {\n return .{ .curr = self.first_child };\n}\n\n/// An iterator over a node's immediate children.\nconst ChildIterator = struct {\n curr: Entity.Optional,\n\n /// Returns the next child, or `null` if there are none.\n pub fn next(self: *@This(), es: *const Entities) ?*Node {\n const entity = self.curr.unwrap() orelse return null;\n const node = entity.get(es, Node).?;\n self.curr = node.next_sib;\n return node;\n }\n};\n\n/// Returns an iterator over the node's ancestors. The iterator starts at the parent, if any, and\n/// then, follows the parent chain until it hits a node with no parent.\npub fn ancestorIterator(self: *const @This()) AncestorIterator {\n return .{ .curr = self.parent };\n}\n\n/// An iterator over a node's ancestors.\nconst AncestorIterator = struct {\n curr: Entity.Optional,\n\n /// Returns the next ancestor, or `null` if there are none.\n pub fn next(self: *@This(), es: *const Entities) ?*Node {\n const entity = self.curr.unwrap() orelse return null;\n const node = entity.get(es, Node).?;\n self.curr = node.parent;\n return node;\n }\n};\n\n/// Returns a pre-order iterator over a node's children. Pre-order traversal visits parents before\n/// children.\npub fn preOrderIterator(self: *const @This(), es: *const Entities) PreOrderIterator {\n return .{\n .start = es.getEntity(self).toOptional(),\n .curr = self.first_child,\n };\n}\n\n/// A pre-order iterator over `(start, ...]`.\npub const PreOrderIterator = struct {\n start: Entity.Optional,\n curr: Entity.Optional,\n\n /// An empty pre-order iterator.\n pub const empty: @This() = .{\n .start = .none,\n .curr = .none,\n };\n\n /// Returns the next child, or `null` if there are none.\n pub fn next(self: *@This(), es: *const Entities) ?*Node {\n const pre_entity = self.curr.unwrap() orelse return null;\n const pre = pre_entity.get(es, Node).?;\n if (pre.first_child != Entity.Optional.none) {\n self.curr = pre.first_child;\n } else {\n var has_next_sib = pre;\n while (has_next_sib.next_sib.unwrap() == null) {\n if (has_next_sib.parent.unwrap().? == self.start.unwrap().?) {\n self.curr = .none;\n return pre;\n }\n has_next_sib = has_next_sib.getParent(es).?;\n }\n self.curr = has_next_sib.next_sib.unwrap().?.toOptional();\n }\n return pre;\n }\n\n /// Fast forward the iterator to just after the given subtree.\n ///\n /// Asserts that `subtree` is a subtree of this iterator.\n pub fn skipSubtree(self: *@This(), es: *const Entities, subtree: *const Node) void {\n // Assert that subtree is contained by this iterator. If it isn't, we'd end up with an\n // infinite loop.\n if (self.start.unwrap()) |start| {\n assert(start.get(es, Node).?.isAncestorOf(es, subtree));\n }\n\n var has_next_sib = subtree;\n while (has_next_sib.next_sib.unwrap() == null) {\n if (has_next_sib.parent.unwrap().? == self.start.unwrap().?) {\n self.curr = .none;\n return;\n }\n has_next_sib = has_next_sib.getParent(es).?;\n }\n self.curr = has_next_sib.next_sib.unwrap().?.toOptional();\n }\n};\n\n/// Returns a post-order iterator over a node's children. Post-order traversal visits parents after\n/// children.\npub fn postOrderIterator(self: *const @This(), es: *const Entities) PostOrderIterator {\n return .{\n // We start on the leftmost leaf\n .curr = b: {\n var curr = self.first_child.unwrap() orelse break :b .none;\n while (curr.get(es, Node).?.first_child.unwrap()) |fc| curr = fc;\n break :b curr.toOptional();\n },\n // And we end when we reach the given entity\n .end = es.getEntity(self),\n };\n}\n\n/// A post-order iterator over `[curr, end)`.\npub const PostOrderIterator = struct {\n curr: Entity.Optional,\n end: Entity,\n\n /// Returns the next child, or `null` if there are none.\n pub fn next(self: *@This(), es: *const Entities) ?*Node {\n const post_entity = self.curr.unwrap() orelse return null;\n if (post_entity == self.end) return null;\n const post = post_entity.get(es, Node).?;\n if (post.next_sib.unwrap()) |next_sib| {\n var curr = next_sib;\n while (curr.get(es, Node).?.first_child.unwrap()) |fc| curr = fc;\n self.curr = curr.toOptional();\n } else {\n self.curr = self.curr.unwrap().?.get(es, Node).?.parent.unwrap().?.toOptional();\n }\n return post;\n }\n};\n\n/// Encodes a command that requests to parent `child` and `parent`.\n///\n/// * If the relationship would result in a cycle, parent and child are equal, or child no longer\n/// exists, then no change is made.\n/// * If parent is `.none`, child is unparented.\n/// * If parent no longer exists, child is destroyed.\npub const SetParent = struct {\n child: Entity,\n parent: Entity.Optional,\n};\n\n/// `Exec` provides helpers for processing hierarchy changes via the command buffer.\n///\n/// By convention, `exec` only calls into the stable public interface of the types it's working\n/// with. As such, documentation is sparse. You are welcome to call these methods directly, or\n/// use them as reference for implementing your own command buffer iterator.\npub const Exec = struct {\n /// Provided as reference. Executes a command buffer, maintaining the hierarchy and reacting to\n /// related events along the way. In practice, you likely want to call the finer grained\n /// functions provided directly, so that other libraries you use can also hook into the command\n /// buffer iterator.\n pub fn immediate(es: *Entities, cb: *CmdBuf) void {\n immediateOrErr(es, cb) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `immediate`, but returns an error on failure instead of panicking. On error the\n /// commands are left partially evaluated.\n ///\n /// Invalidates pointers.\n pub fn immediateOrErr(\n es: *Entities,\n cb: *CmdBuf,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow, ZcsEntityOverflow }!void {\n var default_exec: CmdBuf.Exec = .init();\n\n es.pointer_generation.increment();\n\n var batches = cb.iterator();\n while (batches.next()) |batch| {\n switch (batch) {\n .arch_change => |arch_change| {\n var delta: CmdBuf.Batch.ArchChange.Delta = .{};\n var ops = arch_change.iterator();\n while (ops.next()) |op| {\n beforeArchChangeImmediate(es, arch_change, op);\n delta.updateImmediate(op);\n }\n\n _ = try arch_change.execImmediateOrErr(es, delta);\n },\n .ext => |ext| {\n try extImmediateOrErr(es, ext);\n default_exec.extImmediateOrErr(ext);\n },\n }\n }\n\n try default_exec.finish(cb, es);\n }\n\n /// Executes an extension command.\n pub inline fn extImmediateOrErr(\n es: *Entities,\n payload: Any,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!void {\n if (payload.as(SetParent)) |set_parent| {\n const child = set_parent.child;\n if (set_parent.parent.unwrap()) |parent| {\n if (try child.getOrAddImmediateOrErr(es, Node, .{})) |child_node| {\n if (try parent.getOrAddImmediateOrErr(es, Node, .{})) |parent_node| {\n // If a parent that exists is assigned, set it as the parent\n child_node.setParentImmediate(es, parent_node);\n } else {\n // Otherwise destroy the child\n child_node.destroyImmediate(es);\n }\n }\n } else {\n // If our parent is being cleared and we have a node, clear it. If not leave\n // it alone since it's implicitly clear.\n if (child.get(es, Node)) |node| {\n node.setParentImmediate(es, null);\n }\n }\n }\n }\n\n /// Call this before executing a command.\n pub inline fn beforeArchChangeImmediate(\n es: *Entities,\n arch_change: CmdBuf.Batch.ArchChange,\n op: CmdBuf.Batch.ArchChange.Op,\n ) void {\n switch (op) {\n .destroy => if (arch_change.entity.get(es, Node)) |node| {\n _ = node.destroyChildrenAndUnparentImmediate(es);\n },\n .remove => |id| if (id == typeId(Node)) {\n if (arch_change.entity.get(es, Node)) |node| {\n _ = node.destroyChildrenAndUnparentImmediate(es);\n }\n },\n .add => {},\n }\n }\n};\n"], ["/ZCS/src/ChunkList.zig", "//! A list of all chunks with a given archetype.\n\nconst std = @import(\"std\");\nconst zcs = @import(\"root.zig\");\nconst tracy = @import(\"tracy\");\n\nconst ChunkPool = zcs.ChunkPool;\nconst CompFlag = zcs.CompFlag;\nconst Chunk = zcs.Chunk;\nconst Entities = zcs.Entities;\nconst PointerLock = zcs.PointerLock;\nconst Arches = zcs.Arches;\nconst Entity = zcs.Entity;\n\nconst Zone = tracy.Zone;\n\nconst typeId = zcs.typeId;\n\nconst assert = std.debug.assert;\nconst alignForward = std.mem.alignForward;\nconst math = std.math;\n\nconst ChunkList = @This();\n\n/// The chunks in this chunk list, connected via the `next` and `prev` fields.\nhead: Chunk.Index,\n/// The final chunk in this chunk list.\ntail: Chunk.Index,\n/// The chunks in this chunk list that have space available, connected via the `next_avail`\n/// and `prev_avail` fields.\navail: Chunk.Index,\n/// The offset to the entity index buffer.\nindex_buf_offset: u32,\n/// A map from component flags to the byte offset of their arrays. Components that aren't\n/// present or are zero sized have undefined offsets. It's generally faster to read this from\n/// the chunk instead of the chunk list to avoid the extra cache miss.\ncomp_buf_offsets_cold: std.enums.EnumArray(CompFlag, u32),\n/// The number of entities that can be stored in a single chunk from this list.\nchunk_capacity: u32,\n\n/// The index of a `ChunkList` in the `Arches` that owns it.\npub const Index = enum(u32) {\n /// Gets a chunk list from a chunk list ID.\n pub fn get(self: @This(), arches: *const Arches) *ChunkList {\n return &arches.map.values()[@intFromEnum(self)];\n }\n\n /// Gets the archetype for a chunk list.\n pub fn arch(self: Index, arches: *const Arches) CompFlag.Set {\n return arches.map.keys()[@intFromEnum(self)];\n }\n\n _,\n};\n\n/// Initializes a chunk list.\npub fn init(pool: *const ChunkPool, arch: CompFlag.Set) error{ZcsChunkOverflow}!@This() {\n const zone = Zone.begin(.{ .src = @src() });\n defer zone.end();\n\n // Sort the components from greatest to least alignment.\n const sorted = sortCompsByAlignment(arch);\n\n // Get the max alignment required by any component or entity index\n var max_align: u32 = @alignOf(Entity.Index);\n if (sorted.len > 0) max_align = @max(max_align, sorted.get(0).getId().alignment);\n\n // Initialize the offset to the start of the data\n const data_offset: u32 = alignForward(u32, @sizeOf(Chunk.Header), max_align);\n\n // Calculate how many bytes of data there are\n const bytes = math.sub(\n u32,\n @intCast(pool.size_align.toByteUnits()),\n data_offset,\n ) catch return error.ZcsChunkOverflow;\n\n // Calculate how much space one entity takes\n var entity_size: u32 = @sizeOf(Entity.Index);\n for (sorted.constSlice()) |comp| {\n const comp_size = math.cast(u32, comp.getId().size) orelse\n return error.ZcsChunkOverflow;\n entity_size = math.add(u32, entity_size, comp_size) catch\n return error.ZcsChunkOverflow;\n }\n\n // Calculate the capacity in entities\n const chunk_capacity: u32 = bytes / entity_size;\n\n // Check that we have enough space for at least one entity\n if (chunk_capacity <= 0) return error.ZcsChunkOverflow;\n\n // Calculate the offsets for each component\n var offset: u32 = data_offset;\n var comp_buf_offsets: std.enums.EnumArray(CompFlag, u32) = .initFill(0);\n var index_buf_offset: u32 = 0;\n for (sorted.constSlice()) |comp| {\n const id = comp.getId();\n\n // If we haven't found a place for the index buffer, check if it can go here\n if (index_buf_offset == 0 and id.alignment <= @alignOf(Entity.Index)) {\n assert(offset % @alignOf(Entity.Index) == 0);\n index_buf_offset = offset;\n const buf_size = math.mul(u32, @sizeOf(Entity.Index), chunk_capacity) catch\n return error.ZcsChunkOverflow;\n offset = math.add(u32, offset, buf_size) catch\n return error.ZcsChunkOverflow;\n }\n\n // Store the offset to this component type\n assert(offset % id.alignment == 0);\n comp_buf_offsets.set(comp, offset);\n const comp_size = math.cast(u32, id.size) orelse\n return error.ZcsChunkOverflow;\n const buf_size = math.mul(u32, comp_size, chunk_capacity) catch\n return error.ZcsChunkOverflow;\n offset = math.add(u32, offset, buf_size) catch\n return error.ZcsChunkOverflow;\n }\n\n // If we haven't found a place for the index buffer, place it at the end\n if (index_buf_offset == 0) {\n index_buf_offset = offset;\n const buf_size = math.mul(u32, @sizeOf(Entity.Index), chunk_capacity) catch\n return error.ZcsChunkOverflow;\n offset = math.add(u32, offset, buf_size) catch\n return error.ZcsChunkOverflow;\n }\n\n assert(offset <= pool.size_align.toByteUnits());\n\n return .{\n .head = .none,\n .tail = .none,\n .avail = .none,\n .comp_buf_offsets_cold = comp_buf_offsets,\n .index_buf_offset = index_buf_offset,\n .chunk_capacity = chunk_capacity,\n };\n}\n\n/// Adds an entity to the chunk list.\npub fn append(\n self: *@This(),\n es: *Entities,\n e: Entity,\n) error{ZcsChunkPoolOverflow}!Entity.Location {\n const pool = &es.chunk_pool;\n const arches = &es.arches;\n\n // Ensure there's a chunk with space available\n if (self.avail == .none) {\n // Allocate a new chunk\n const new = try pool.reserve(es, arches.indexOf(self));\n const new_index = pool.indexOf(new);\n\n // Point the available list to the new chunk\n self.avail = new_index;\n\n // Add the new chunk to the end of the chunk list\n if (self.tail.get(pool)) |tail| {\n new.header().prev = self.tail;\n tail.header().next = new_index;\n self.tail = new_index;\n } else {\n self.head = new_index;\n self.tail = new_index;\n }\n }\n\n // Get the next chunk with space available\n const chunk = self.avail.get(pool).?;\n const header = chunk.header();\n assert(header.len < self.chunk_capacity);\n chunk.checkAssertions(es, .allow_empty);\n\n // Append the entity. This const cast is okay since the chunk was originally mutable, we\n // just don't expose mutable pointers to the index buf publicly.\n const index_in_chunk: Entity.Location.IndexInChunk = @enumFromInt(header.len);\n header.len += 1;\n const index_buf = @constCast(chunk.view(es, struct {\n indices: []const Entity.Index,\n }).?.indices);\n index_buf[@intFromEnum(index_in_chunk)] = @enumFromInt(e.key.index);\n\n // If the chunk is now full, remove it from the available list\n if (header.len == self.chunk_capacity) {\n @branchHint(.unlikely);\n assert(self.avail.get(pool) == chunk);\n self.avail = chunk.header().next_avail;\n header.next_avail = .none;\n if (self.avail.get(pool)) |avail| {\n const available_header = avail.header();\n assert(available_header.prev_avail.get(pool) == chunk);\n available_header.prev_avail = .none;\n }\n }\n\n self.checkAssertions(es);\n\n // Return the location we stored the entity\n return .{\n .chunk = es.chunk_pool.indexOf(chunk),\n .index_in_chunk = index_in_chunk,\n };\n}\n\n// Checks internal consistency.\npub fn checkAssertions(self: *const @This(), es: *const Entities) void {\n if (!std.debug.runtime_safety) return;\n\n const pool = &es.chunk_pool;\n\n if (self.head.get(pool)) |head| {\n const header = head.header();\n head.checkAssertions(es, .default);\n self.tail.get(pool).?.checkAssertions(es, .default);\n assert(@intFromBool(header.next != .none) ^\n @intFromBool(head == self.tail.get(pool)) != 0);\n assert(self.tail != .none);\n } else {\n assert(self.tail == .none);\n assert(self.avail == .none);\n }\n\n if (self.avail.get(pool)) |avail| {\n const header = avail.header();\n avail.checkAssertions(es, .default);\n assert(header.prev_avail == .none);\n }\n}\n\n/// Returns an iterator over this chunk list's chunks.\n///\n/// Invalidating pointers while iterating results in safety checked illegal behavior.\npub fn iterator(self: *const @This(), es: *const Entities) Iterator {\n self.checkAssertions(es);\n return .{\n .chunk = self.head.get(&es.chunk_pool),\n .pointer_lock = es.pointer_generation.lock(),\n };\n}\n\n/// An iterator over a chunk list's chunks.\npub const Iterator = struct {\n /// Returns an empty iterator.\n pub fn empty(es: *const Entities) @This() {\n return .{\n .chunk = null,\n .pointer_lock = es.pointer_generation.lock(),\n };\n }\n\n chunk: ?*Chunk,\n pointer_lock: PointerLock,\n\n /// Returns the next chunk and advances.\n pub fn next(self: *@This(), es: *const Entities) ?*Chunk {\n self.pointer_lock.check(es.pointer_generation);\n const chunk = self.chunk orelse {\n @branchHint(.unlikely);\n return null;\n };\n chunk.checkAssertions(es, .default);\n const header = chunk.header();\n self.chunk = header.next.get(&es.chunk_pool);\n return chunk;\n }\n\n /// Peeks at the next chunk.\n pub fn peek(self: @This(), es: *const Entities) ?*Chunk {\n self.pointer_lock.check(es.pointer_generation);\n return self.chunk;\n }\n};\n\n/// Compares the alignment of two component types.\nfn alignmentGte(_: void, lhs: CompFlag, rhs: CompFlag) bool {\n const lhs_alignment = lhs.getId().alignment;\n const rhs_alignment = rhs.getId().alignment;\n return lhs_alignment >= rhs_alignment;\n}\n\n/// Returns a list of the components in this set sorted from greatest to least alignment. This\n/// is an optimization to reduce padding, but also necessary to get consistent cutoffs for how\n/// much data fits in a chunk regardless of registration order.\ninline fn sortCompsByAlignment(set: CompFlag.Set) std.BoundedArray(CompFlag, CompFlag.max) {\n const zone = Zone.begin(.{ .src = @src() });\n defer zone.end();\n var comps: std.BoundedArray(CompFlag, CompFlag.max) = .{};\n var iter = set.iterator();\n while (iter.next()) |flag| comps.appendAssumeCapacity(flag);\n std.sort.pdq(CompFlag, comps.slice(), {}, alignmentGte);\n return comps;\n}\n\ntest sortCompsByAlignment {\n defer CompFlag.unregisterAll();\n\n // Register various components with different alignments in an arbitrary order\n const a_1 = CompFlag.registerImmediate(typeId(struct { x: u8 align(1) }));\n const e_2 = CompFlag.registerImmediate(typeId(struct { x: u8 align(16) }));\n const d_2 = CompFlag.registerImmediate(typeId(struct { x: u8 align(8) }));\n const e_0 = CompFlag.registerImmediate(typeId(struct { x: u8 align(16) }));\n const b_2 = CompFlag.registerImmediate(typeId(struct { x: u8 align(2) }));\n const d_0 = CompFlag.registerImmediate(typeId(struct { x: u8 align(8) }));\n const a_2 = CompFlag.registerImmediate(typeId(struct { x: u8 align(1) }));\n const e_1 = CompFlag.registerImmediate(typeId(struct { x: u8 align(16) }));\n const c_0 = CompFlag.registerImmediate(typeId(struct { x: u8 align(4) }));\n const b_0 = CompFlag.registerImmediate(typeId(struct { x: u8 align(2) }));\n const b_1 = CompFlag.registerImmediate(typeId(struct { x: u8 align(2) }));\n const a_0 = CompFlag.registerImmediate(typeId(struct { x: u8 align(1) }));\n const c_2 = CompFlag.registerImmediate(typeId(struct { x: u8 align(4) }));\n const c_1 = CompFlag.registerImmediate(typeId(struct { x: u8 align(4) }));\n const d_1 = CompFlag.registerImmediate(typeId(struct { x: u8 align(8) }));\n\n // Test sorting all of them\n {\n // Sort them\n const sorted = sortCompsByAlignment(.initMany(&.{\n e_0,\n c_1,\n d_0,\n e_1,\n a_1,\n b_1,\n b_0,\n a_0,\n d_1,\n c_0,\n c_2,\n e_2,\n a_2,\n b_2,\n d_2,\n }));\n try std.testing.expectEqual(15, sorted.len);\n var prev: usize = math.maxInt(usize);\n for (sorted.constSlice()) |flag| {\n const curr = flag.getId().alignment;\n try std.testing.expect(curr <= prev);\n prev = curr;\n }\n }\n\n // Test sorting a subset of them\n {\n // Sort them\n const sorted = sortCompsByAlignment(.initMany(&.{\n e_0,\n d_0,\n c_0,\n a_0,\n b_0,\n }));\n try std.testing.expectEqual(5, sorted.len);\n try std.testing.expectEqual(e_0, sorted.get(0));\n try std.testing.expectEqual(d_0, sorted.get(1));\n try std.testing.expectEqual(c_0, sorted.get(2));\n try std.testing.expectEqual(b_0, sorted.get(3));\n try std.testing.expectEqual(a_0, sorted.get(4));\n }\n}\n"], ["/ZCS/src/ext/Transform2D.zig", "//! A component that tracks the position and orientation of an entity in 2D. Hierarchical\n//! relationships formed by the `Node` component are respected if present.\n//!\n//! You can synchronize a transform's `world_from_model` field, and the `world_from_model` fields of\n//! all its relative children by calling `sync`. This is necessary when modifying the transform, or\n//! changing the hierarchy by adding or removing a transform.\n//!\n//! To alleviate this burden, a number of setters are provided that call `sync` for you, and command\n//! buffer integration is provided for automatically calling sync when transforms are added and\n//! removed.\n//!\n//! For more information on command buffer integration, see `exec`.\n//!\n//! If you need features not provided by this implementation, for example a third dimension, you're\n//! encouraged to use this as a reference for your own transform component.\n\nconst std = @import(\"std\");\nconst zcs = @import(\"../root.zig\");\nconst tracy = @import(\"tracy\");\n\nconst math = std.math;\nconst assert = std.debug.assert;\nconst typeId = zcs.typeId;\n\nconst Entity = zcs.Entity;\nconst Entities = zcs.Entities;\nconst CmdBuf = zcs.CmdBuf;\nconst Any = zcs.Any;\nconst PointerLock = zcs.PointerLock;\nconst Node = zcs.ext.Node;\nconst Vec2 = zcs.ext.geom.Vec2;\nconst Rotor2 = zcs.ext.geom.Rotor2;\nconst Mat2x3 = zcs.ext.geom.Mat2x3;\n\nconst Zone = tracy.Zone;\n\nconst Transform2D = @This();\n\n/// The transform's local position.\npos: Vec2 = .zero,\n/// The transform's local orientation.\nrot: Rotor2 = .identity,\n/// The transform's world from model matrix.\nworld_from_model: Mat2x3 = .identity,\n/// Whether or not this transform's space is relative to its parent.\nrelative: bool = true,\n\n/// Move the transform in local space by `delta` and then calls `sync`.\npub fn move(self: *@This(), es: *const Entities, delta: Vec2) void {\n self.pos.add(delta);\n self.sync(es);\n}\n\n/// Set the local position to `pos` and then calls `sync`.\npub fn setPos(self: *@This(), es: *const Entities, pos: Vec2) void {\n self.pos = pos;\n self.sync(es);\n}\n\n/// Rotates the local space and then calls `sync`.\npub fn rotate(self: *@This(), es: *const Entities, rotation: Rotor2) void {\n self.rot.mul(rotation);\n self.sync(es);\n}\n\n/// Sets the local orientation to `rot` and then calls `sync`.\npub fn setRot(self: *@This(), es: *const Entities, rot: Rotor2) void {\n self.rot = rot;\n self.sync(es);\n}\n\n/// Returns the world space position.\npub inline fn getWorldPos(self: @This()) Vec2 {\n return self.world_from_model.getTranslation();\n}\n\n/// Updates the `world_from_model` matrix on this transform, and all of its transitive relative\n/// children.\npub fn sync(self: *@This(), es: *const Entities) void {\n var transforms = self.preOrderIterator(es);\n while (transforms.next(es)) |transform| {\n const translation: Mat2x3 = .translation(transform.pos);\n const rotation: Mat2x3 = .rotation(transform.rot);\n const parent_world_from_model = transform.getRelativeWorldFromModel(es);\n transform.world_from_model = rotation.applied(translation).applied(parent_world_from_model);\n }\n}\n\n/// Returns the parent's world form model matrix, or identity if not relative.\npub inline fn getRelativeWorldFromModel(self: *const @This(), es: *const Entities) Mat2x3 {\n if (!self.relative) return .identity;\n const node = es.getComp(self, Node) orelse return .identity;\n const parent = node.parent.unwrap() orelse return .identity;\n const parent_transform = parent.get(es, Transform2D) orelse return .identity;\n return parent_transform.world_from_model;\n}\n\n/// Returns the forward direction of this transform.\npub fn getForward(self: *const @This()) Vec2 {\n return self.world_from_model.timesDir(.y_pos);\n}\n\n/// Returns a pre-order iterator over the subtree of relative transforms starting at `self`. This\n/// will visit parents before children, and it will include `self`.\npub fn preOrderIterator(self: *@This(), es: *const Entities) PreOrderIterator {\n return .{\n .parent = self,\n .children = if (es.getComp(self, Node)) |node| node.preOrderIterator(es) else .empty,\n .pointer_lock = es.pointer_generation.lock(),\n };\n}\n\n/// A pre-order iterator over relative transforms.\npub const PreOrderIterator = struct {\n parent: ?*Transform2D,\n children: Node.PreOrderIterator,\n pointer_lock: PointerLock,\n\n /// Returns the next transform.\n pub fn next(self: *@This(), es: *const Entities) ?*Transform2D {\n self.pointer_lock.check(es.pointer_generation);\n\n if (self.parent) |parent| {\n self.parent = null;\n return parent;\n }\n\n while (self.children.next(es)) |node| {\n // If the next child has a transform and that transform is relative to its parent,\n // return it.\n if (es.getComp(node, Transform2D)) |transform| {\n if (transform.relative) {\n return transform;\n }\n }\n // Otherwise, skip this subtree.\n self.children.skipSubtree(es, node);\n }\n\n return null;\n }\n};\n\n/// `Exec` provides helpers for processing hierarchy changes via the command buffer.\n///\n/// By convention, `Exec` only calls into the stable public interface of the types it's working\n/// with. As such, documentation is sparse. You are welcome to call these methods directly, or\n/// use them as reference for implementing your own command buffer iterator.\npub const Exec = struct {\n /// Similar to `Node.Exec.immediate`, but marks transforms as dirty as needed.\n pub fn immediate(es: *Entities, cb: *CmdBuf) void {\n immediateOrErr(es, cb) catch |err|\n @panic(@errorName(err));\n }\n\n /// Similar to `immediate`, but returns an error on failure instead of panicking. On error the\n /// commands are left partially evaluated.\n pub fn immediateOrErr(\n es: *Entities,\n cb: *CmdBuf,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow, ZcsEntityOverflow }!void {\n var default_exec: CmdBuf.Exec = .init();\n\n es.pointer_generation.increment();\n\n var batches = cb.iterator();\n while (batches.next()) |batch| {\n switch (batch) {\n .arch_change => |arch_change| {\n {\n var delta: CmdBuf.Batch.ArchChange.Delta = .{};\n var ops = arch_change.iterator();\n while (ops.next()) |op| {\n Node.Exec.beforeArchChangeImmediate(es, arch_change, op);\n delta.updateImmediate(op);\n }\n\n _ = arch_change.execImmediate(es, delta);\n }\n\n {\n var ops = arch_change.iterator();\n while (ops.next()) |op| {\n afterArchChangeImmediate(es, arch_change, op);\n }\n }\n },\n .ext => |ext| {\n try extImmediateOrErr(es, ext);\n default_exec.extImmediateOrErr(ext);\n },\n }\n }\n\n try default_exec.finish(cb, es);\n }\n\n /// Call this after executing a command.\n pub inline fn afterArchChangeImmediate(\n es: *Entities,\n batch: CmdBuf.Batch.ArchChange,\n op: CmdBuf.Batch.ArchChange.Op,\n ) void {\n switch (op) {\n .add => |comp| if (comp.id == typeId(Transform2D)) {\n if (batch.entity.get(es, Transform2D)) |transform| {\n transform.sync(es);\n }\n },\n .remove => |id| {\n if (id == typeId(Node)) {\n if (batch.entity.get(es, Transform2D)) |transform| {\n transform.sync(es);\n }\n } else if (id == typeId(Transform2D)) {\n if (batch.entity.get(es, Node)) |node| {\n var children = node.childIterator();\n while (children.next(es)) |child| {\n if (es.getComp(child, Transform2D)) |child_transform| {\n child_transform.sync(es);\n }\n }\n }\n }\n },\n else => {},\n }\n }\n\n /// Call this to process an extension command.\n pub inline fn extImmediateOrErr(\n es: *Entities,\n payload: Any,\n ) error{ ZcsArchOverflow, ZcsChunkOverflow, ZcsChunkPoolOverflow }!void {\n try Node.Exec.extImmediateOrErr(es, payload);\n if (payload.as(Node.SetParent)) |set_parent| {\n if (set_parent.child.get(es, Transform2D)) |transform| {\n transform.sync(es);\n }\n }\n }\n};\n"], ["/ZCS/src/CmdPool.zig", "//! A pool of command buffers. Intended for multithreaded use cases where each thread needs its own\n//! command buffer.\n//!\n//! # Problem Statement\n//!\n//! The key issue this abstraction solves is how much space to allocate per command buffer.\n//!\n//! The naive approach of dividing the capacity evenly across the threads will fail if the workload\n//! is lopsided or the users machine has more cores than expected.\n//!\n//! The alternative naive approach of allocating a fixed command buffer size per thread will\n//! increase the likelihood of overflowing command buffers on machines with low core counts, or\n//! overflowing entities on machines with high core counts.\n//!\n//! # Solution\n//!\n//! `CmdPool` allocates a fixed number of command buffers of fixed sizes. Once per chunk, you call\n//! `acquire` to get a command buffer with more than `headroom` capacity`. When done processing a\n//! chunk, you call `release`.\n//!\n//! This distribution of load results in comparable command buffer usage regardless of core counts,\n//! lessening the Q&A burden when tuning your game.\n\nconst std = @import(\"std\");\nconst zcs = @import(\"root.zig\");\nconst tracy = @import(\"tracy\");\n\nconst log = std.log;\nconst assert = std.debug.assert;\n\nconst Mutex = std.Thread.Mutex;\nconst Condition = std.Thread.Condition;\n\nconst CmdBuf = zcs.CmdBuf;\nconst Entities = zcs.Entities;\n\nconst Allocator = std.mem.Allocator;\nconst ArrayListUnmanaged = std.ArrayListUnmanaged;\n\n/// The debug name for this command pool. See `InitOptions.name`.\nname: ?[:0]const u8,\n/// Reserved command buffers that have not yet been acquired.\nbuffers: ArrayListUnmanaged(CmdBuf),\n/// Locked when modifying internal state.\nmutex: Mutex,\n/// Signaled when command buffers are returned, broadcasted when all command buffers have been\n/// retired.\ncondition: Condition,\n/// Command buffers that have been released.\nreleased: ArrayListUnmanaged(*CmdBuf),\n/// The number of retired command buffers. Command buffers are retired when they are returned with\n/// with less than the requested headroom available.\nretired: usize,\n/// Measured in units of `CmdBuf.worstCastUsage`, ranges from `0` to `1`.\nheadroom: f32,\n/// See `InitOptions.warn_ratio`.\nwarn_ratio: f32,\n\n/// The capacity of a command pool.\npub const Capacity = struct {\n /// The default number of commands to reserve.\n pub const default_cmds = CmdBuf.Capacity.default_cmds / 256;\n\n /// The capacity of a single command buffer. Note that `default_cmds` is overridden to a lower\n /// value than when creating a `CmdBuf` directly.\n buffer: CmdBuf.Capacity = .{},\n /// The total number of command buffers to reserve.\n buffers: usize = 256,\n};\n\n/// Options for `init`.\npub const InitOptions = struct {\n /// The debug name for this command pool.\n ///\n /// If non-null and Tracy is enabled, this command pool's usage is graphed under this name on\n /// reset.\n name: ?[:0]const u8,\n /// Used to allocate the command pool.\n gpa: Allocator,\n /// Entities are reserved from here.\n es: *Entities,\n /// The capacity.\n cap: Capacity = .{},\n /// `acquire` only returns command buffers with a `worstCaseUsage` greater than this value.\n headroom: f32 = 0.5,\n /// Warn if a single acquire exceeds this ratio of the headroom, or if more than this ratio of the\n /// total command buffers are written.\n warn_ratio: f32 = 0.2,\n};\n\n/// Initializes a command pool.\npub fn init(options: InitOptions) error{ OutOfMemory, ZcsEntityOverflow }!@This() {\n // Reserve the command buffers\n var buffers: ArrayListUnmanaged(CmdBuf) = try .initCapacity(options.gpa, options.cap.buffers);\n errdefer buffers.deinit(options.gpa);\n errdefer for (buffers.items) |*cb| cb.deinit(options.gpa, options.es);\n var buffer_cap = options.cap.buffer;\n buffer_cap.cmds = buffer_cap.cmds orelse Capacity.default_cmds;\n for (0..options.cap.buffers) |_| {\n const cb: CmdBuf = try .init(.{\n .name = null,\n .gpa = options.gpa,\n .es = options.es,\n .cap = buffer_cap,\n // We handle the warnings ourselves\n .warn_ratio = 1.0,\n });\n buffers.appendAssumeCapacity(cb);\n }\n\n // Reserve the released list\n var released: ArrayListUnmanaged(*CmdBuf) = try .initCapacity(options.gpa, options.cap.buffers);\n errdefer released.deinit(options.gpa);\n\n // If Tracy is enabled and we have a name, configure our plot.\n if (tracy.enabled) {\n if (options.name) |name| {\n tracy.plotConfig(.{\n .name = name,\n .format = .percentage,\n .mode = .line,\n .fill = true,\n });\n }\n }\n\n return .{\n .buffers = buffers,\n .mutex = .{},\n .condition = .{},\n .released = released,\n .retired = 0,\n .headroom = options.headroom,\n .name = options.name,\n .warn_ratio = options.warn_ratio,\n };\n}\n\n/// Destroys the command pool.\npub fn deinit(self: *@This(), gpa: Allocator, es: *Entities) void {\n self.checkAssertions();\n self.buffers.items.len = self.buffers.capacity;\n for (self.buffers.items) |*cb| cb.deinit(gpa, es);\n self.buffers.deinit(gpa);\n self.released.deinit(gpa);\n}\n\n/// The result of `acquire`.\npub const AcquireResult = struct {\n /// The initial usage ratio.\n usage: f32,\n /// The command buffer.\n cb: *CmdBuf,\n\n /// Initializes an acquire result with the starting usage.\n fn init(cb: *CmdBuf) @This() {\n return .{\n .usage = cb.worstCaseUsage(),\n .cb = cb,\n };\n }\n};\n\n/// Acquire a command buffer with at least `Capacity.headroom` capacity remaining. Call `release`\n/// when done. Thread safe.\n///\n/// This function may block if all command buffers are currently in use. You can mitigate this by\n/// reserving more command buffers up front.\npub fn acquire(self: *@This()) AcquireResult {\n return self.acquireOrErr() catch |err|\n @panic(@errorName(err));\n}\n\n/// Similar to `acquire`, but returns an error when out of command buffers.\npub fn acquireOrErr(self: *@This()) error{ZcsCmdPoolUnderflow}!AcquireResult {\n self.mutex.lock();\n defer self.mutex.unlock();\n\n // Try to get a recently released command buffer\n if (self.released.pop()) |popped| return .init(popped);\n\n // Try to get a reserved command buffer\n if (self.buffers.items.len > 0) {\n const new_len = self.buffers.items.len - 1;\n const result = &self.buffers.items[new_len];\n self.buffers.items.len = new_len;\n return .init(result);\n }\n\n // There are no command buffers available. Wait until one becomes available, or all are\n // retired.\n while (self.released.items.len == 0 and self.retired < self.buffers.capacity) {\n self.condition.wait(&self.mutex);\n }\n\n // Try to reacquire the released command buffer\n if (self.released.pop()) |cb| {\n assert(self.retired < self.buffers.capacity);\n return .init(cb);\n }\n\n // If no command buffer was released, we're out of command buffers, return an error\n assert(self.retired == self.buffers.capacity);\n return error.ZcsCmdPoolUnderflow;\n}\n\n/// Releases a previously acquired command buffer. Thread safe.\npub fn release(self: *@This(), ar: AcquireResult) void {\n self.mutex.lock();\n defer self.mutex.unlock();\n\n // Optionally warn if a single acquire used too much headroom, this is a sign that the command\n // buffers are too small\n const usage = ar.cb.worstCaseUsage();\n if (ar.cb.worstCaseUsage() - ar.usage > (1.0 - self.headroom) * self.warn_ratio) {\n log.warn(\n \"acquire used > {d}% headroom, consider increasing command buffer size\",\n .{self.warn_ratio * 100.0},\n );\n }\n\n // Release the command buffer if it has enough headroom left, otherwise retire it\n if (usage < self.headroom) {\n self.released.appendAssumeCapacity(ar.cb);\n } else {\n self.retired += 1;\n }\n\n // If all command buffers are retired, broadcast our condition so all pending acquires return an\n // error. Otherwise signal at least one pending acquire to continue.\n if (self.retired == self.buffers.capacity) {\n self.condition.broadcast();\n } else {\n self.condition.signal();\n }\n}\n\n/// Gets a slice of all command buffers that may have been written to since the last reset.\npub fn written(self: *@This()) []CmdBuf {\n self.checkAssertions();\n return self.buffers.items.ptr[self.buffers.items.len..self.buffers.capacity];\n}\n\n/// Resets the command pool. Asserts that all command buffers have already been reset.\npub fn reset(self: *@This()) void {\n // Check assertions\n self.checkAssertions();\n if (std.debug.runtime_safety) for (self.written()) |cb| assert(cb.isEmpty());\n\n // Warn if we used too many command buffers\n const cap: f32 = @floatFromInt(self.buffers.capacity);\n const used: f32 = @floatFromInt(self.written().len);\n const usage = used / cap;\n if (usage > self.warn_ratio) {\n log.warn(\n \"more than {d}% command pool buffers used, consider incresing reserved count\",\n .{self.warn_ratio},\n );\n }\n\n // If a name is configured, emit a Tracy plot\n if (self.name) |name| {\n tracy.plot(.{\n .name = name,\n .value = .{ .f32 = usage * 100.0 },\n });\n }\n\n // Reset the command pool\n self.buffers.items.len = self.buffers.capacity;\n self.released.items.len = 0;\n self.retired = 0;\n}\n\n/// Asserts that all command buffers have been released.\npub fn checkAssertions(self: *@This()) void {\n assert(self.released.items.len + self.retired == self.buffers.capacity - self.buffers.items.len);\n}\n"], ["/ZCS/src/ChunkPool.zig", "//! A pool of `Chunk`s.\n\nconst std = @import(\"std\");\nconst zcs = @import(\"root.zig\");\nconst tracy = @import(\"tracy\");\n\nconst Chunk = zcs.Chunk;\nconst Entities = zcs.Entities;\nconst ChunkList = zcs.ChunkList;\nconst Entity = zcs.Entity;\n\nconst assert = std.debug.assert;\nconst math = std.math;\n\nconst Alignment = std.mem.Alignment;\nconst Allocator = std.mem.Allocator;\n\nconst Zone = tracy.Zone;\n\nconst ChunkPool = @This();\n\n/// Memory reserved for chunks\nbuf: []u8,\n/// The number of unique chunks that have ever been reserved.\nreserved: u32,\n/// The chunk size and alignment are both set to this value. This is done for a couple reasons:\n/// 1. It makes `Entity.from` slightly cheaper\n/// 2. It reduces false sharing\n/// 3. We need to be aligned by more than `TypeInfo.max_align` so that the place our allocation\n/// ends up doesn't change how much stuff can fit in it.\n///\n/// If this becomes an issue, we stop doing this by giving up 1 as long as we set the alignment\n/// to at least a cache line and assert 3. However seeing as it only adds padding before the\n/// first chunk, this is unlikely to ever matter.\nsize_align: Alignment,\n/// Freed chunks, connected by the `next` field. All other fields are undefined.\nfree: Chunk.Index = .none,\n\n/// The pool's capcity.\npub const Capacity = struct {\n /// The number of chunks to reserve. Supports the range `[0, math.maxInt(u32))`, max int\n /// is reserved for the none index.\n chunks: u16,\n /// The size of each chunk.\n chunk: u32,\n};\n\n/// Allocates a chunk pool.\npub fn init(gpa: Allocator, cap: Capacity) Allocator.Error!@This() {\n const zone = Zone.begin(.{ .src = @src() });\n defer zone.end();\n\n // The max size is reserved for invalid indices.\n assert(cap.chunks < math.maxInt(u32));\n assert(cap.chunk >= zcs.TypeInfo.max_align.toByteUnits());\n\n // Allocate the chunk data, aligned to the size of a chunk\n const alignment = Alignment.fromByteUnits(cap.chunk);\n const len = @as(usize, cap.chunk) * @as(usize, cap.chunks);\n const buf = (gpa.rawAlloc(\n len,\n alignment,\n @returnAddress(),\n ) orelse return error.OutOfMemory)[0..len];\n errdefer comptime unreachable;\n\n return .{\n .buf = buf,\n .reserved = 0,\n .size_align = alignment,\n };\n}\n\n/// Frees a chunk pool.\npub fn deinit(self: *@This(), gpa: Allocator) void {\n gpa.rawFree(self.buf, self.size_align, @returnAddress());\n self.* = undefined;\n}\n\n/// Resets the chunk pool back to its initial state.\npub fn clear(self: *@This()) void {\n self.reserved = 0;\n self.free = .none;\n}\n\n/// Reserves a chunk from the chunk pool\npub fn reserve(\n self: *@This(),\n es: *const Entities,\n list: ChunkList.Index,\n) error{ZcsChunkPoolOverflow}!*Chunk {\n // Get a free chunk. Try the free list first, then fall back to bump allocation from the\n // preallocated buffer.\n const chunk = if (self.free.get(self)) |free| b: {\n // Pop the next chunk from the free list\n self.free = free.header().next;\n break :b free;\n } else b: {\n // Pop the next chunk from the preallocated buffer\n const byte_idx = @shlExact(self.reserved, @intCast(@intFromEnum(self.size_align)));\n if (byte_idx >= self.buf.len) return error.ZcsChunkPoolOverflow;\n const chunk: *Chunk = @ptrCast(&self.buf[byte_idx]);\n self.reserved = self.reserved + 1;\n break :b chunk;\n };\n errdefer comptime unreachable; // Already modified the free list!\n\n // Check the alignment\n assert(self.size_align.check(@intFromPtr(chunk)));\n\n // Initialize the chunk and return it\n const header = chunk.header();\n header.* = .{\n .comp_buf_offsets = list.get(&es.arches).comp_buf_offsets_cold,\n .list = list,\n .len = 0,\n };\n return chunk;\n}\n\n/// Gets the index of a chunk.\npub fn indexOf(self: *const @This(), chunk: *const Chunk) Chunk.Index {\n assert(@intFromPtr(chunk) >= @intFromPtr(self.buf.ptr));\n assert(@intFromPtr(chunk) < @intFromPtr(self.buf.ptr) + self.buf.len);\n const offset = @intFromPtr(chunk) - @intFromPtr(self.buf.ptr);\n assert(offset < self.buf.len);\n return @enumFromInt(@shrExact(offset, @intFromEnum(self.size_align)));\n}\n"], ["/ZCS/bench/main.zig", "const std = @import(\"std\");\nconst zcs = @import(\"zcs\");\nconst tracy = @import(\"tracy\");\n\nconst assert = std.debug.assert;\n\nconst Entities = zcs.Entities;\nconst Entity = zcs.Entity;\nconst CmdBuf = zcs.CmdBuf;\nconst Transform2D = zcs.ext.Transform2D;\nconst ZoneCmd = zcs.ext.ZoneCmd;\n\nconst Zone = tracy.Zone;\n\nconst max_entities = 1000000;\nconst iterations = 10;\n\npub const std_options: std.Options = .{\n .log_level = .info,\n};\n\npub const tracy_impl = @import(\"tracy_impl\");\npub const tracy_options: tracy.Options = .{\n .default_callstack_depth = 8,\n};\n\nconst small = false;\nconst A = if (small) u2 else u64;\nconst B = if (small) u4 else u128;\nconst C = if (small) u8 else u256;\n\n// Eventually we may make reusable benchmarks for comparing releases. Right now this is just a\n// dumping ground for testing performance tweaks.\npub fn main() !void {\n var gpa = std.heap.GeneralPurposeAllocator(.{ .thread_safe = false }){};\n const allocator = gpa.allocator();\n\n var expected_total: ?u256 = null;\n var expected_ra_total: ?u256 = null;\n\n for (0..iterations) |_| {\n var es: Entities = try .init(.{\n .gpa = allocator,\n .cap = .{\n .entities = max_entities,\n .arches = 1,\n .chunks = 4096,\n .chunk = 65536,\n },\n .warn_ratio = 1.0,\n });\n defer es.deinit(allocator);\n\n // also compare interning vs not etc\n {\n const fill_zone = Zone.begin(.{ .name = \"fill immediate any\", .src = @src() });\n for (0..max_entities) |i| {\n const e = Entity.reserveImmediate(&es);\n const a: A = @intCast(i);\n const b: B = @intCast(i);\n const c: C = @intCast(i);\n assert(e.changeArchAnyImmediate(&es, .{ .add = &.{\n .init(A, &a),\n .init(B, &b),\n .init(C, &c),\n } }) catch |err| @panic(@errorName(err)));\n }\n fill_zone.end();\n }\n }\n\n for (0..iterations) |_| {\n var es: Entities = try .init(.{\n .gpa = allocator,\n .cap = .{\n .entities = max_entities,\n .arches = 1,\n .chunks = 4096,\n .chunk = 65536,\n },\n .warn_ratio = 1.0,\n });\n defer es.deinit(allocator);\n\n // also compare interning vs not etc\n {\n es.updateStats();\n const fill_zone = Zone.begin(.{ .name = \"fill immediate\", .src = @src() });\n for (0..max_entities) |i| {\n const e = Entity.reserveImmediate(&es);\n assert(e.changeArchImmediate(\n &es,\n struct { A, B, C },\n .{\n .add = .{ @intCast(i), @intCast(i), @intCast(i) },\n },\n ));\n }\n fill_zone.end();\n es.updateStats();\n }\n }\n\n for (0..iterations) |_| {\n var tags: std.ArrayListUnmanaged(u8) = try .initCapacity(allocator, max_entities * 4);\n defer tags.deinit(allocator);\n var args: std.ArrayListUnmanaged(u64) = try .initCapacity(allocator, max_entities * 4);\n defer args.deinit(allocator);\n var bytes: std.ArrayListUnmanaged(u8) = try .initCapacity(allocator, max_entities * @sizeOf(C) * 3);\n defer bytes.deinit(allocator);\n\n {\n var last: ?usize = null;\n const fill_zone = Zone.begin(.{ .name = \"baseline fill separate\", .src = @src() });\n for (0..max_entities) |i| {\n const a: A = @intCast(i);\n const b: B = @intCast(i);\n const c: C = @intCast(i);\n\n if (i != last) {\n // assert(args.items.len < args.capacity) implied by tags check\n if (tags.items.len >= tags.capacity) @panic(\"OOB\");\n last = i;\n tags.appendAssumeCapacity(10);\n args.appendAssumeCapacity(i);\n }\n\n if (tags.items.len >= tags.capacity) @panic(\"OOB\");\n tags.appendAssumeCapacity(0);\n // if (args.items.len >= args.capacity) @panic(\"OOB\"); // Implied by tags check\n args.appendAssumeCapacity(@intFromPtr(zcs.typeId(A)));\n bytes.items.len = std.mem.alignForward(\n usize,\n bytes.items.len,\n @alignOf(A),\n );\n if (bytes.items.len + @sizeOf(A) > bytes.capacity) @panic(\"OOB\");\n bytes.appendSliceAssumeCapacity(std.mem.asBytes(&a));\n\n if (tags.items.len >= tags.capacity) @panic(\"OOB\");\n tags.appendAssumeCapacity(0);\n // if (args.items.len >= args.capacity) @panic(\"OOB\"); // Implied by tags check\n args.appendAssumeCapacity(@intFromPtr(zcs.typeId(B)));\n bytes.items.len = std.mem.alignForward(\n usize,\n bytes.items.len,\n @alignOf(B),\n );\n if (bytes.items.len + @sizeOf(B) > bytes.capacity) @panic(\"OOB\");\n bytes.appendSliceAssumeCapacity(std.mem.asBytes(&b));\n\n if (tags.items.len >= tags.capacity) @panic(\"OOB\");\n tags.appendAssumeCapacity(0);\n // if (args.items.len >= args.capacity) @panic(\"OOB\"); // Implied by tags check\n args.appendAssumeCapacity(@intFromPtr(zcs.typeId(C)));\n bytes.items.len = std.mem.alignForward(\n usize,\n bytes.items.len,\n @alignOf(C),\n );\n if (bytes.items.len + @sizeOf(C) > bytes.capacity) @panic(\"OOB\");\n bytes.appendSliceAssumeCapacity(std.mem.asBytes(&c));\n }\n fill_zone.end();\n }\n }\n\n for (0..iterations) |_| {\n var es: Entities = try .init(.{\n .gpa = allocator,\n .cap = .{\n .entities = max_entities,\n .arches = 64,\n .chunks = 4096,\n .chunk = 65536,\n },\n .warn_ratio = 1.0,\n });\n defer es.deinit(allocator);\n\n var cb: CmdBuf = try .init(.{\n .name = \"cmd buf\",\n .gpa = allocator,\n .es = &es,\n .cap = .{\n .cmds = max_entities * 3,\n .reserved_entities = max_entities,\n },\n });\n defer cb.deinit(allocator, &es);\n\n {\n const fill_fast_zone = Zone.begin(.{ .name = \"fill cb\", .src = @src() });\n defer fill_fast_zone.end();\n for (0..max_entities) |i| {\n const e = Entity.reserve(&cb);\n e.add(&cb, A, @intCast(i));\n e.add(&cb, B, @intCast(i));\n e.add(&cb, C, @intCast(i));\n }\n }\n }\n\n for (0..iterations) |_| {\n const alloc_zone = Zone.begin(.{ .name = \"alloc\", .src = @src() });\n\n const alloc_es_zone = Zone.begin(.{ .name = \"es\", .src = @src() });\n var es: Entities = try .init(.{\n .gpa = allocator,\n .cap = .{\n .entities = max_entities * 2,\n .arches = 64,\n .chunks = 4096,\n .chunk = 65536,\n },\n .warn_ratio = 1.0,\n });\n defer es.deinit(allocator);\n alloc_es_zone.end();\n\n const alloc_cb_zone = Zone.begin(.{ .name = \"cb\", .src = @src() });\n var cb: CmdBuf = try .init(.{\n .name = \"cmd buf\",\n .gpa = allocator,\n .es = &es,\n .cap = .{\n .cmds = max_entities * 4,\n .reserved_entities = max_entities,\n },\n .warn_ratio = 1.0,\n });\n defer cb.deinit(allocator, &es);\n alloc_cb_zone.end();\n\n alloc_zone.end();\n\n {\n const cmdbuf_zone = Zone.begin(.{ .name = \"cb\", .src = @src() });\n defer cmdbuf_zone.end();\n {\n const fill_zone = Zone.begin(.{ .name = \"fill\", .src = @src() });\n defer fill_zone.end();\n\n // Divided into two parts to test exec zones\n const exec_zone = ZoneCmd.begin(&cb, .{\n .src = @src(),\n .name = \"exec zone\",\n });\n defer exec_zone.end(&cb);\n\n {\n const first_half_zone = ZoneCmd.begin(&cb, .{\n .src = @src(),\n .name = \"first half\",\n });\n defer first_half_zone.end(&cb);\n for (0..max_entities / 2) |i| {\n const e = Entity.reserve(&cb);\n e.add(&cb, A, @intCast(i));\n e.add(&cb, B, @intCast(i));\n e.add(&cb, C, @intCast(i));\n }\n }\n {\n const second_half_zone = ZoneCmd.begin(&cb, .{\n .src = @src(),\n .name = \"second half\",\n });\n defer second_half_zone.end(&cb);\n for (max_entities / 2..max_entities) |i| {\n const e = Entity.reserve(&cb);\n e.add(&cb, A, @intCast(i));\n e.add(&cb, B, @intCast(i));\n e.add(&cb, C, @intCast(i));\n }\n }\n }\n CmdBuf.Exec.immediate(&es, &cb);\n }\n\n {\n var total: u256 = 0;\n {\n const iter_zone = Zone.begin(.{ .name = \"iter.fast\", .src = @src() });\n defer iter_zone.end();\n var iter = es.iterator(struct { a: *const A, b: *const B, c: *const C });\n while (iter.next(&es)) |vw| {\n total +%= vw.a.*;\n total +%= vw.b.*;\n total +%= vw.c.*;\n }\n }\n std.debug.print(\"{}\\n\", .{total});\n if (expected_total == null) expected_total = total;\n if (expected_total != total) @panic(\"inconsistent result\");\n }\n\n {\n var total: u256 = 0;\n es.forEach(\"sum\", sum, .{ .total = &total });\n std.debug.print(\"{}\\n\", .{total});\n if (expected_total == null) expected_total = total;\n if (expected_total != total) @panic(\"inconsistent result\");\n }\n\n {\n const zone = Zone.begin(.{ .src = @src(), .name = \"sum threaded\" });\n defer zone.end();\n\n var tp: std.Thread.Pool = undefined;\n try std.Thread.Pool.init(&tp, .{\n .allocator = allocator,\n });\n defer tp.deinit();\n var wg: std.Thread.WaitGroup = .{};\n es.forEachThreaded(\"sum threaded\", sumThreaded, .{\n .tp = &tp,\n .wg = &wg,\n .ctx = .{},\n .cp = null,\n });\n tp.waitAndWork(&wg);\n }\n\n {\n var total: u256 = 0;\n {\n const iter_zone = Zone.begin(.{ .name = \"iter.view\", .src = @src() });\n defer iter_zone.end();\n var iter = es.iterator(struct { e: Entity });\n while (iter.next(&es)) |vw| {\n const comps = vw.e.view(&es, struct {\n a: *const A,\n b: *const B,\n c: *const C,\n }).?;\n total +%= comps.a.*;\n total +%= comps.b.*;\n total +%= comps.c.*;\n }\n }\n std.debug.print(\"{}\\n\", .{total});\n if (expected_total == null) expected_total = total;\n if (expected_total != total) @panic(\"inconsistent result\");\n }\n\n {\n var total: u256 = 0;\n {\n const iter_zone = Zone.begin(.{ .name = \"iter.get\", .src = @src() });\n defer iter_zone.end();\n var iter = es.iterator(struct { e: Entity });\n while (iter.next(&es)) |vw| {\n total +%= vw.e.get(&es, A).?.*;\n total +%= vw.e.get(&es, B).?.*;\n total +%= vw.e.get(&es, C).?.*;\n }\n }\n std.debug.print(\"{}\\n\", .{total});\n if (expected_total == null) expected_total = total;\n if (expected_total != total) @panic(\"inconsistent result\");\n }\n\n {\n var total: u256 = 0;\n var default_rng: std.Random.DefaultPrng = .init(0);\n const rand = default_rng.random();\n {\n const iter_zone = Zone.begin(.{ .name = \"es.random access\", .src = @src() });\n defer iter_zone.end();\n for (0..max_entities / 2) |_| {\n const ei: Entity.Index = @enumFromInt(rand.uintLessThan(u32, max_entities));\n const e = ei.toEntity(&es);\n const comps = e.view(&es, struct {\n a: *const A,\n b: *const B,\n c: *const C,\n }).?;\n total +%= comps.a.*;\n total +%= comps.b.*;\n total +%= comps.c.*;\n }\n }\n std.debug.print(\"ecs ra: {}\\n\", .{total});\n if (expected_ra_total == null) expected_ra_total = total;\n if (expected_ra_total != total) @panic(\"inconsistent result\");\n }\n }\n\n for (0..iterations) |_| {\n const zone = Zone.begin(.{ .name = \"transform\", .src = @src() });\n defer zone.end();\n\n const es_init_zone = Zone.begin(.{ .name = \"es init\", .src = @src() });\n var es: Entities = try .init(.{\n .gpa = allocator,\n .cap = .{\n .entities = max_entities,\n .arches = 64,\n .chunks = 4096,\n .chunk = 65536,\n },\n .warn_ratio = 1.0,\n });\n defer es.deinit(allocator);\n es_init_zone.end();\n\n {\n const entity_init_zone = Zone.begin(.{ .name = \"entity init\", .src = @src() });\n defer entity_init_zone.end();\n for (0..max_entities) |_| {\n assert(Entity.reserveImmediate(&es).changeArchImmediate(\n &es,\n struct { Transform2D },\n .{ .add = .{.{}} },\n ));\n }\n }\n\n {\n const queue_zone = Zone.begin(.{ .name = \"move\", .src = @src() });\n defer queue_zone.end();\n var iter = es.iterator(struct { transform: *Transform2D });\n var f: f32 = 0;\n while (iter.next(&es)) |vw| {\n vw.transform.move(&es, .{ .x = f, .y = f });\n f += 0.01;\n }\n }\n }\n\n for (0..iterations) |_| {\n const alloc_zone = Zone.begin(.{ .name = \"mal.alloc\", .src = @src() });\n var es: std.MultiArrayList(struct {\n a: A,\n b: B,\n c: C,\n }) = .empty;\n defer es.deinit(std.heap.page_allocator);\n try es.setCapacity(std.heap.page_allocator, max_entities);\n alloc_zone.end();\n\n {\n const fill_zone = Zone.begin(.{ .name = \"mal.fill\", .src = @src() });\n defer fill_zone.end();\n for (0..max_entities) |i| {\n es.appendAssumeCapacity(.{\n .a = @intCast(i),\n .b = @intCast(i),\n .c = @intCast(i),\n });\n }\n }\n\n {\n var total: u256 = 0;\n {\n const iter_zone = Zone.begin(.{ .name = \"mal.iter\", .src = @src() });\n defer iter_zone.end();\n for (es.items(.a), es.items(.b), es.items(.c)) |*a, *b, *c| {\n total +%= a.*;\n total +%= b.*;\n total +%= c.*;\n }\n }\n std.debug.print(\"{}\\n\", .{total});\n if (expected_total == null) expected_total = total;\n if (expected_total != total) @panic(\"inconsistent result\");\n }\n\n {\n var total: u256 = 0;\n var default_rng: std.Random.DefaultPrng = .init(0);\n const rand = default_rng.random();\n {\n const iter_zone = Zone.begin(.{ .name = \"mal.random access\", .src = @src() });\n defer iter_zone.end();\n for (0..max_entities) |_| {\n const i = max_entities - rand.uintLessThan(u32, max_entities);\n const comps = es.get(i);\n total +%= comps.a;\n total +%= comps.b;\n total +%= comps.c;\n }\n }\n std.debug.print(\"mal ra: {}\\n\", .{total});\n }\n }\n}\n\nfn sum(ctx: struct { total: *u256 }, a: *const A, b: *const B, c: *const C) void {\n const total = ctx.total;\n total.* += a.*;\n total.* += b.*;\n total.* += c.*;\n}\n\n// This isn't expensive enough to be worth threading, but when you modify it to do more work it becomes worth it\nthreadlocal var thread_sum: u256 = 0;\nfn sumThreaded(_: struct {}, a: *const A, b: *const B, c: *const C) void {\n thread_sum += a.*;\n thread_sum += b.*;\n thread_sum += c.*;\n}\n"], ["/ZCS/src/Arches.zig", "//! A map from archetypes to their chunk lists.\n\nconst std = @import(\"std\");\nconst zcs = @import(\"root.zig\");\nconst tracy = @import(\"tracy\");\n\nconst Zone = tracy.Zone;\n\nconst assert = std.debug.assert;\n\nconst Entities = zcs.Entities;\nconst CompFlag = zcs.CompFlag;\nconst PointerLock = zcs.PointerLock;\nconst ChunkList = zcs.ChunkList;\nconst ChunkPool = zcs.ChunkPool;\n\nconst Allocator = std.mem.Allocator;\n\npub const Arches = @This();\n\ncapacity: u32,\nmap: std.ArrayHashMapUnmanaged(\n CompFlag.Set,\n ChunkList,\n struct {\n pub fn eql(_: @This(), lhs: CompFlag.Set, rhs: CompFlag.Set, _: usize) bool {\n return lhs.eql(rhs);\n }\n pub fn hash(_: @This(), key: CompFlag.Set) u32 {\n return @truncate(std.hash.int(key.bits.mask));\n }\n },\n false,\n),\n\n/// Initializes the chunk lists.\npub fn init(gpa: Allocator, capacity: u32) Allocator.Error!@This() {\n const zone = Zone.begin(.{ .src = @src() });\n defer zone.end();\n\n var map: @FieldType(@This(), \"map\") = .{};\n errdefer map.deinit(gpa);\n // We reserve one extra to work around a slightly the slightly awkward get or put API.\n try map.ensureTotalCapacity(gpa, @as(u32, capacity) + 1);\n map.lockPointers();\n return .{\n .capacity = capacity,\n .map = map,\n };\n}\n\n/// Frees the chunk lists.\npub fn deinit(self: *@This(), gpa: Allocator) void {\n self.map.unlockPointers();\n self.map.deinit(gpa);\n self.* = undefined;\n}\n\n/// Resets arches back to its initial state.\npub fn clear(self: *@This()) void {\n self.map.unlockPointers();\n self.map.clearRetainingCapacity();\n self.map.lockPointers();\n}\n\n/// Gets the chunk list for the given archetype, initializing it if it doesn't exist.\npub fn getOrPut(\n self: *@This(),\n pool: *const ChunkPool,\n arch: CompFlag.Set,\n) error{ ZcsChunkOverflow, ZcsArchOverflow }!*ChunkList {\n // This is a bit awkward, but works around there not being a get or put variation\n // that fails when allocation is needed.\n //\n // In practice this code path will only be executed when we're about to fail in a likely\n // fatal way, so the mild amount of extra work isn't worth creating a whole new gop\n // variant over.\n //\n // Note that we reserve space for the requested capacity + 1 in `init` to make this\n // work.\n const gop = self.map.getOrPutAssumeCapacity(arch);\n errdefer if (!gop.found_existing) {\n @branchHint(.cold);\n // We have to unlock pointers to do this, but we're just doing a swap remove so the\n // indices that we already store into the array won't change.\n self.map.unlockPointers();\n assert(self.map.swapRemove(arch));\n self.map.lockPointers();\n };\n if (!gop.found_existing) {\n @branchHint(.unlikely);\n if (self.map.count() > self.capacity) return error.ZcsArchOverflow;\n gop.value_ptr.* = try .init(pool, arch);\n }\n return gop.value_ptr;\n}\n\n/// Gets the index of a chunk list.\npub fn indexOf(lists: *const @This(), self: *const ChunkList) ChunkList.Index {\n const vals = lists.map.values();\n\n assert(@intFromPtr(self) >= @intFromPtr(vals.ptr));\n assert(@intFromPtr(self) < @intFromPtr(vals.ptr) + vals.len * @sizeOf(ChunkList));\n\n const offset = @intFromPtr(self) - @intFromPtr(vals.ptr);\n const index = offset / @sizeOf(ChunkList);\n return @enumFromInt(index);\n}\n\n/// Returns an iterator over the chunk lists that have the given components.\n///\n/// Invalidating pointers while iterating results in safety checked illegal behavior.\npub fn iterator(self: @This(), es: *const Entities, required_comps: CompFlag.Set) Iterator {\n return .{\n .required_comps = required_comps,\n .all = self.map.iterator(),\n .pointer_lock = es.pointer_generation.lock(),\n };\n}\n\n/// An iterator over chunk lists that have the given components.\npub const Iterator = struct {\n required_comps: CompFlag.Set,\n all: @FieldType(Arches, \"map\").Iterator,\n pointer_lock: PointerLock,\n\n /// Returns an empty iterator.\n pub fn empty(es: *const Entities) @This() {\n return .{\n .required_comps = .{},\n .all = b: {\n const map: @FieldType(Arches, \"map\") = .{};\n break :b map.iterator();\n },\n .pointer_lock = es.pointer_generation.lock(),\n };\n }\n\n pub fn next(self: *@This(), es: *const Entities) ?*const ChunkList {\n self.pointer_lock.check(es.pointer_generation);\n while (self.all.next()) |item| {\n if (item.key_ptr.*.supersetOf(self.required_comps)) {\n return item.value_ptr;\n }\n }\n return null;\n }\n};\n"], ["/ZCS/src/comp_flag.zig", "//! See `CompFlag`.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\n\nconst zcs = @import(\"root.zig\");\nconst Any = zcs.Any;\nconst TypeId = zcs.TypeId;\nconst Meta = Any.Meta;\n\n/// The tag type for `Flag`.\nconst FlagInt = u6;\n\n/// A tightly packed index for each registered component type.\npub const CompFlag = enum(FlagInt) {\n /// The maximum registered component flags.\n pub const max = std.math.maxInt(FlagInt);\n\n /// A set of component flags.\n pub const Set = std.enums.EnumSet(CompFlag);\n\n /// The list of registered components.\n var registered: std.BoundedArray(TypeId, CompFlag.max) = .{};\n\n /// Assigns the given ID the next flag index if it doesn't have one, and then returns its flag.\n /// Not thread safe.\n pub fn registerImmediate(id: TypeId) CompFlag {\n // Early out if we're already registered\n if (id.comp_flag) |f| {\n @branchHint(.likely);\n return f;\n }\n\n // Debug log that we're registering the component\n std.log.scoped(.zcs).debug(\"register comp: {s}\", .{id.name});\n\n // Warn if we've registered a large number of components\n if (registered.len == CompFlag.max / 2) {\n std.log.warn(\n \"{} component types registered, you're at 50% the fatal capacity!\",\n .{registered.len},\n );\n }\n\n // Fail if we're out of component types\n if (registered.len > registered.buffer.len) {\n @panic(\"component type overflow\");\n }\n\n // Pick the next sequential flag\n const flag: CompFlag = @enumFromInt(registered.len);\n id.comp_flag = flag;\n\n // This function is not thread safe, but reading from `registered` is, so we update the\n // registered list, and then increment the counter atomically.\n registered.buffer[registered.len] = id;\n _ = @atomicRmw(usize, ®istered.len, .Add, 1, .release);\n\n // Return the registered flag\n return flag;\n }\n\n /// Gets the list of registered component types for introspection purposes. Components are\n /// registered lazily, this list will grow over time. Thread safe.\n pub fn getAll() []const TypeId {\n return registered.constSlice();\n }\n\n /// This function is intended to be used only in tests. Unregisters all component types.\n pub fn unregisterAll() void {\n for (registered.slice()) |id| id.comp_flag = null;\n registered.clear();\n }\n\n /// Returns the ID for this flag.\n pub fn getId(self: @This()) TypeId {\n return registered.get(@intFromEnum(self));\n }\n\n _,\n};\n"], ["/ZCS/src/Any.zig", "//! A pointer to arbitrary data with a runtime known type.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\n\nconst zcs = @import(\"root.zig\");\n\nconst typeId = zcs.typeId;\n\nconst Entities = zcs.Entities;\nconst CompFlag = zcs.CompFlag;\nconst TypeId = zcs.TypeId;\n\nid: TypeId,\nptr: *const anyopaque,\n\n/// Initialize a component from a pointer to a component type.\npub fn init(T: type, ptr: *const T) @This() {\n return .{\n .id = typeId(T),\n .ptr = ptr,\n };\n}\n\n/// Returns the component as the given type if it matches its ID, or null otherwise.\npub fn as(self: @This(), T: anytype) ?*const T {\n if (self.id != typeId(T)) {\n @branchHint(.unlikely);\n return null;\n }\n return @alignCast(@ptrCast(self.ptr));\n}\n\n/// Returns the component as a constant slice of `u8`s.\npub fn constSlice(self: @This()) []const u8 {\n return self.bytes()[0..self.id.size];\n}\n\n/// Similar to `constSlice`, but returns the data as a many item pointer.\npub fn bytes(self: @This()) [*]const u8 {\n return @ptrCast(self.ptr);\n}\n"], ["/ZCS/src/ext/ZoneCmd.zig", "//! A Tracy Zone that begins/ends inside of a command buffer. Unlike most extensions, this\n//! extension's `Exec` is automatically called from the default exec implementation provided that\n//! Tracy is enabled.\n\nconst std = @import(\"std\");\nconst zcs = @import(\"../root.zig\");\nconst tracy = @import(\"tracy\");\n\nconst assert = std.debug.assert;\n\nconst Zone = tracy.Zone;\n\nconst CmdBuf = zcs.CmdBuf;\nconst Entities = zcs.Entities;\nconst Any = zcs.Any;\n\nconst SourceLocation = tracy.SourceLocation;\n\nloc: *const SourceLocation,\n\npub const BeginOptions = Zone.BeginOptions;\n\n/// Emits a begin zone command to the command buffer if Tracy is enabled.\npub fn begin(cb: *CmdBuf, comptime opt: SourceLocation.InitOptions) @This() {\n if (tracy.enabled) {\n const loc: *const SourceLocation = .init(opt);\n cb.ext(BeginCmd, .{ .loc = loc });\n return .{ .loc = loc };\n }\n}\n\n/// Emits an end zone command to the command buffer if Tracy is enabled.\npub fn end(self: @This(), cb: *CmdBuf) void {\n if (tracy.enabled) {\n cb.ext(EndCmd, .{ .loc = self.loc });\n }\n}\n\n/// A begin zone command.\npub const BeginCmd = struct { loc: *const SourceLocation };\n\n/// An end zone command.\npub const EndCmd = struct { loc: *const SourceLocation };\n\n/// `Exec` provides helpers for beginning/ending Tracy zones while executing the command buffer.\n/// Unlike most extensions this extension is called automatically by the default exec, provided that\n/// Tracy is enabled.\n///\n/// By convention, `exec` only calls into the stable public interface of the types it's working\n/// with. As such, documentation is sparse. You are welcome to call these methods directly, or\n/// use them as reference for implementing your own command buffer iterator.\npub const Exec = struct {\n const Stack = if (tracy.enabled) b: {\n break :b std.BoundedArray(struct { zone: Zone, loc: *const SourceLocation }, 32);\n } else struct {};\n\n stack: Stack = .{},\n\n /// Executes an extension command.\n pub inline fn extImmediate(self: *@This(), payload: Any) void {\n if (tracy.enabled) {\n if (payload.as(BeginCmd)) |b| {\n const zone = Zone.beginFromPtr(b.loc);\n self.stack.append(.{ .zone = zone, .loc = b.loc }) catch @panic(\"OOB\");\n } else if (payload.as(EndCmd)) |e| {\n const frame = self.stack.pop() orelse @panic(\"OOB\");\n assert(frame.loc == e.loc);\n frame.zone.end();\n }\n }\n }\n\n pub fn finish(self: *@This()) void {\n if (tracy.enabled) {\n assert(self.stack.len == 0);\n }\n }\n};\n"], ["/ZCS/src/meta.zig", "//! Metaprogramming helpers. See also `view`.\n\nconst std = @import(\"std\");\n\n/// Returns true if the given value is comptime known, false otherwise.\npub inline fn isComptimeKnown(value: anytype) bool {\n return @typeInfo(@TypeOf(.{value})).@\"struct\".fields[0].is_comptime;\n}\n\ntest isComptimeKnown {\n try std.testing.expect(isComptimeKnown(123));\n const foo = 456;\n try std.testing.expect(isComptimeKnown(foo));\n var bar: u8 = 123;\n bar += 1;\n try std.testing.expect(!isComptimeKnown(bar));\n}\n"], ["/ZCS/src/root.zig", "//! An entity component system.\n//!\n//! See `Entities` for entity storage and iteration, `Entity` for entity creation and modification,\n//! and `CmdBuf` for queuing commands during iteration or from multiple threads.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\nconst Allocator = std.mem.Allocator;\nconst slot_map = @import(\"slot_map\");\n\npub const Entities = @import(\"Entities.zig\");\npub const Entity = @import(\"entity.zig\").Entity;\npub const Any = @import(\"Any.zig\");\npub const CompFlag = @import(\"comp_flag.zig\").CompFlag;\npub const CmdBuf = @import(\"CmdBuf.zig\");\npub const CmdPool = @import(\"CmdPool.zig\");\npub const TypeInfo = @import(\"type_id.zig\").TypeInfo;\npub const TypeId = @import(\"type_id.zig\").TypeId;\npub const PointerLock = @import(\"PointerLock.zig\");\npub const Chunk = @import(\"chunk.zig\").Chunk;\npub const ChunkList = @import(\"ChunkList.zig\");\npub const ChunkPool = @import(\"ChunkPool.zig\");\npub const Arches = @import(\"Arches.zig\");\npub const view = @import(\"view.zig\");\npub const ext = @import(\"ext.zig\");\npub const meta = @import(\"meta.zig\");\n\n/// Returns the component ID for the given type.\npub const typeId = TypeInfo.init;\n\n/// A handle table that associates persistent entity keys with values that point to their storage.\npub const HandleTab = slot_map.SlotMap(Entity.Location, .{});\n\ntest {\n std.testing.refAllDecls(@This());\n}\n"], ["/ZCS/src/PointerLock.zig", "/// Pointer stability assertions for builds with runtime safety enabled.\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\n\nconst PointerLock = @This();\n\nconst enabled = std.debug.runtime_safety;\n\n/// The current pointer generation.\npub const Generation = struct {\n n: if (enabled) u64 else u0 = 0,\n\n /// Increments the pointer generation.\n pub inline fn increment(self: *@This()) void {\n if (enabled) {\n self.n +%= 1;\n }\n }\n\n /// Returns a pointer lock with the current generation.\n pub inline fn lock(self: @This()) PointerLock {\n return .{ .generation = self };\n }\n};\n\n/// The pointer generation from when this lock was created.\ngeneration: Generation,\n\n/// Asserts that pointers have not been invalidated since this lock was created.\npub fn check(self: @This(), generation: Generation) void {\n if (self.generation.n != generation.n) {\n @panic(\"pointers invalidated\");\n }\n}\n"], ["/ZCS/src/ext.zig", "//! Optional extensions not part of the core ECS.\n\nconst std = @import(\"std\");\n\npub const Node = @import(\"ext/Node.zig\");\npub const Transform2D = @import(\"ext/Transform2D.zig\");\npub const ZoneCmd = @import(\"ext/ZoneCmd.zig\");\npub const geom = @import(\"geom\");\n\ntest {\n std.testing.refAllDecls(@This());\n}\n"], ["/ZCS/src/docs.zig", "/// See build.zig.\npub fn main() void {}\n"]], "task_instance_info": {"created_time": "2025-08-21 03:44:23", "created_task_model": "DeepSeek-R1", "function_skeleton": "inline fn comps(T: type, options: ViewOptions) ?CompFlag.Set { }", "code_description": "This code segment functions to: Aggregate and validate component dependencies by collecting registration flags for each required data type within a structural definition, returning a consolidated set or indicating invalid configurations."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```zig\n[TASK_BEGIN]\npub inline fn comps(T: type, options: ViewOptions) ?CompFlag.Set {\n var mask: u32 = 0;\n inline for (@typeInfo(T).Struct.fields) |field| {\n const component_type = UnwrapField(field.type, options);\n if (component_type == Entity or component_type == Entity.Index) continue;\n const id = zcs.TypeInfo.typeId(component_type) orelse return null;\n mask |= CompFlag.bit(id).mask();\n }\n return CompFlag.Set{ .mask = mask };\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 03-44-58"}, "editdistance_info": {"edit_distance": 36.6667, "calculate_time": "2025-08-21 03:44:58", "true_code_clean": "inline fn comps(T: type, options: ViewOptions) ?CompFlag.Set {\n var arch: CompFlag.Set = .{};\n inline for (@typeInfo(T).@\"struct\".fields) |field| {\n if (field.type != Entity and @typeInfo(field.type) != .optional) {\n const Unwrapped = zcs.view.UnwrapField(field.type, options);\n if (Unwrapped == Entity.Index) continue;\n const flag = typeId(Unwrapped).comp_flag orelse return null;\n arch.insert(flag);\n }\n }\n return arch;\n}", "predict_code_clean": "pub inline fn comps(T: type, options: ViewOptions) ?CompFlag.Set {\n var mask: u32 = 0;\n inline for (@typeInfo(T).Struct.fields) |field| {\n const component_type = UnwrapField(field.type, options);\n if (component_type == Entity or component_type == Entity.Index) continue;\n const id = zcs.TypeInfo.typeId(component_type) orelse return null;\n mask |= CompFlag.bit(id).mask();\n }\n return CompFlag.Set{ .mask = mask };\n}"}}