Created
April 21, 2025 11:07
-
-
Save abradley2/6f0a0206bc39ef369eeb6e3911010b27 to your computer and use it in GitHub Desktop.
Zig ECS Archetypes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const Vector2 = @import("raylib").Vector2; | |
pub const Velocity = Component(0x00000001, "velocity", Vector2); | |
pub const Position = Component(0x00000002, "position", struct { | |
x_y: Vector2, | |
z: f32, | |
}); | |
pub const Collision = Component(0x00000004, "collision", struct { | |
offset: Vector2, | |
width: f32, | |
height: f32, | |
}); | |
fn Component(comptime _bit_flag: u32, comptime _name: [:0]const u8, comptime T: type) type { | |
return struct { | |
const Self = @This(); | |
pub const bit_flag = _bit_flag; | |
pub const Type: type = T; | |
pub const name: [:0]const u8 = _name; | |
}; | |
} | |
pub fn Bundle(comptime w: anytype, comptime components: anytype) struct { u16, type, type } { | |
var fields: [components.len]std.builtin.Type.StructField = undefined; | |
const decls: [0]std.builtin.Type.Declaration = .{}; | |
comptime var bundle_bit: u32 = 0x00000000; | |
inline for (components, 0..) |comp, idx| { | |
bundle_bit = bundle_bit | comp.bit_flag; | |
fields[idx] = std.builtin.Type.StructField{ | |
.alignment = @alignOf(comp.Type), | |
.type = comp.Type, | |
.is_comptime = false, | |
.name = comp.name, | |
.default_value_ptr = null, | |
}; | |
} | |
const entity_type: std.builtin.Type.Struct = .{ | |
.layout = .auto, | |
.is_tuple = false, | |
.fields = &fields, | |
.decls = &decls, | |
}; | |
const EntityType: type = @Type(.{ .@"struct" = entity_type }); | |
const Builder: type = struct { | |
// pub fn createEntity(_w: w, entity: EntityType) void { | |
// inline for (components) |comp| { | |
// @field(_w, comp.name)[entity_id] = @field(entity, comp.name); | |
// } | |
// } | |
pub fn getEntity(_w: w, comptime b: u32, entity_id: usize) EntityType { | |
if (b != bundle_bit) { | |
@compileError("Incorrect bitset for entity"); | |
} | |
var entity: EntityType = undefined; | |
inline for (components) |comp| { | |
@field(entity, comp.name) = @field(_w, comp.name)[entity_id].?; | |
} | |
return entity; | |
} | |
}; | |
return .{ bundle_bit, EntityType, Builder }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment