From 34ccbafa9221066cf0ebcad8596404bbc2048302 Mon Sep 17 00:00:00 2001 From: quou Date: Fri, 28 Apr 2023 22:24:08 +1000 Subject: Improve the C++ ECS demo by making it respect alignment with the allocation. --- ecs2.cpp | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/ecs2.cpp b/ecs2.cpp index 2b2ac66..28f88ae 100644 --- a/ecs2.cpp +++ b/ecs2.cpp @@ -2,15 +2,12 @@ #include #include +#include +#include #include /* So it's like the other ECS example with a bunch of academic masturbation - * See https://git.quou.xyz/samples/tree/ecs.c - * - * Areas for improvement: - * - Should really respect alignment. - * - Entity destruction - */ + * See https://git.quou.xyz/samples/tree/ecs.c */ #define max_entities 256 /* If you want more than 32 component types then you'll have to @@ -22,6 +19,20 @@ typedef int Entity; unsigned get_new_component_id(); +void* aligned_malloc(size_t size, size_t alignment) { + size_t offset = alignment - 1 + sizeof(void*); + void* p1 = malloc(size + offset); + void** p2 = (void**)(((uintptr_t)(p1) + offset) & ~(alignment - 1)); + p2[-1] = p1; + return p2; +} + +void aligned_free(void* ptr) { + if (ptr) { + free(((void**)ptr)[-1]); + } +} + /* DO NOT make either of these functions static. That will break stuff. */ template unsigned get_component_id() { @@ -45,13 +56,13 @@ struct Component_Pool { Component_Pool(): data(0) {} - void init(int es) { + void init(int es, int alignment) { element_size = es; - data = malloc(element_size * max_entities); + data = aligned_malloc(element_size * max_entities, alignment); } void deinit() { - free(data); + aligned_free(data); } bool isinit() { @@ -61,10 +72,9 @@ struct Component_Pool { struct World { Component_Pool pools[max_component_types]; + unsigned bitset[max_entities]; int entity_count; - int bitset[max_entities]; - World(): entity_count(0) {} void deinit() { @@ -77,7 +87,7 @@ struct World { template void register_component_type() { - pools[get_component_id()].init(sizeof(T)); + pools[get_component_id()].init(sizeof(T), alignof(T)); } Entity create_entity() { -- cgit v1.2.3-54-g00ecf