diff options
Diffstat (limited to 'honey/ecs.lua')
-rw-r--r-- | honey/ecs.lua | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/honey/ecs.lua b/honey/ecs.lua index 39f1c77..d544a37 100644 --- a/honey/ecs.lua +++ b/honey/ecs.lua @@ -1,5 +1,7 @@ math.randomseed(os.time()) +local glm = require 'honey.glm' + local module = {} setmetatable(module, {__index=_G}) setfenv(1, module) @@ -28,6 +30,71 @@ end setmetatable(EntityDb, {__call=EntityDb.new}) +local function serialize(tbl) + local tostr = function(x, value) + if type(x) == "table" then + if x.__tostring then + return tostring(x) + else + return serialize(x) + end + elseif type(x) == "string" then + if value then + return string.format("\"%s\"", x) + else + return x + end + else + return tostring(x) + end + end + local str = "{" + for key, value in pairs(tbl) do + if type(key) == "string" and string.match(key, "^_") then + -- ignore keys starting with an underscore + else + str = str .. string.format("%s=%s,", tostr(key), tostr(value, true)) + end + end + str = string.sub(str, 1, -2) .. "}" + return str +end + + +-- save current database to file +function EntityDb.save(self, filename) + local file, err = io.open(filename, "w") + if not file then error(err) end + + for entity in pairs(self.entities) do + local components = self:queryEntity(entity) + file:write(string.format("Entity(\"%s\", %s)\n", entity, serialize(components))) + end + + file:close() +end + + +-- load database from file +function EntityDb.load(self, filename) + self.entities = {} + self.components = {} + local env = { + Entity = function(id, components) + print("add entity:", id) + self:createEntity(id) + self:addComponents(id, components) + end, + Vec3 = glm.Vec3, + Mat4 = glm.Mat4, + } + local f, err = loadfile(filename) + if not f then error(err) end + setfenv(f, env) + f() +end + + -- check if a given entity id is legitimate function EntityDb.checkIsValid(self, id) if not self.entities[id] then |