Advertisement
Guest User

Untitled

a guest
Jul 8th, 2019
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.63 KB | None | 0 0
  1. const std = @import("std");
  2. const mem = std.mem;
  3. const warn = std.debug.warn;
  4. const ArrayList = std.ArrayList;
  5. const HashMap = std.AutoHashMap;
  6.  
  7. const Position = struct {
  8.     x: f32,
  9.     y: f32,
  10. };
  11.  
  12. const Velocity = struct {
  13.     vel: f32,
  14. };
  15.  
  16. const Any = struct {
  17.     type_name: []const u8,    
  18.     data: usize,
  19. };
  20.  
  21. const Entity = struct {
  22.     components: HashMap([]const u8, Any),
  23.     allocator: *mem.Allocator,
  24.  
  25.     pub fn init(allocator: *mem.Allocator) Entity {
  26.         return Entity{
  27.             .components = HashMap([]const u8, Any).init(allocator),
  28.             .allocator = allocator,
  29.         };
  30.     }
  31.  
  32.     pub fn add_component(self: *Entity, component: var) !void {
  33.         const type_name = @typeName(@typeOf(component));
  34.  
  35.         var copy = try self.allocator.create(@typeOf(component));
  36.         copy.* = component;
  37.         _ = try self.components.put(type_name, Any{
  38.             .type_name = type_name,
  39.             .data = @ptrToInt(@ptrCast(*u8, copy)),
  40.         });
  41.     }
  42.  
  43.     pub fn get_component(self: *Entity, comptime T: type) *T {
  44.         var type_name = @typeName(T);
  45.         var component = self.components.getValue(type_name) orelse unreachable;
  46.  
  47.         return @ptrCast(*T, @intToPtr(*T, component.data));
  48.     }
  49. };
  50.  
  51. pub fn main() !void {
  52.     var entity = Entity.init(std.debug.global_allocator);
  53.  
  54.     _ = try entity.add_component(Position{
  55.         .x = 5,
  56.         .y = 5,
  57.     });
  58.     _ = try entity.add_component(Velocity{
  59.         .vel = 1,
  60.     });
  61.  
  62.     entity.get_component(Position).x += entity.get_component(Velocity).vel;
  63.  
  64.     warn("ok {}\n", entity.get_component(Position).x);
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement