Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const std = @import("std");
- const mem = std.mem;
- const warn = std.debug.warn;
- const ArrayList = std.ArrayList;
- const HashMap = std.AutoHashMap;
- const Position = struct {
- x: f32,
- y: f32,
- };
- const Velocity = struct {
- vel: f32,
- };
- const Any = struct {
- type_name: []const u8,
- data: usize,
- };
- const Entity = struct {
- components: HashMap([]const u8, Any),
- allocator: *mem.Allocator,
- pub fn init(allocator: *mem.Allocator) Entity {
- return Entity{
- .components = HashMap([]const u8, Any).init(allocator),
- .allocator = allocator,
- };
- }
- pub fn add_component(self: *Entity, component: var) !void {
- const type_name = @typeName(@typeOf(component));
- var copy = try self.allocator.create(@typeOf(component));
- copy.* = component;
- _ = try self.components.put(type_name, Any{
- .type_name = type_name,
- .data = @ptrToInt(@ptrCast(*u8, copy)),
- });
- }
- pub fn get_component(self: *Entity, comptime T: type) *T {
- var type_name = @typeName(T);
- var component = self.components.getValue(type_name) orelse unreachable;
- return @ptrCast(*T, @intToPtr(*T, component.data));
- }
- };
- pub fn main() !void {
- var entity = Entity.init(std.debug.global_allocator);
- _ = try entity.add_component(Position{
- .x = 5,
- .y = 5,
- });
- _ = try entity.add_component(Velocity{
- .vel = 1,
- });
- entity.get_component(Position).x += entity.get_component(Velocity).vel;
- warn("ok {}\n", entity.get_component(Position).x);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement