engine/lib/engine/init.lua

98 lines
2.4 KiB
Lua

local engine = {}
function engine.null() end
engine.elements = {}
engine.elementTypes = {}
engine.element = {}
engine.paths = { mainScriptPath .. "/engine" }
function engine.path(path)
for i,v in pairs(engine.paths) do
local fpath = v .. "/" .. path
local f = io.open(fpath)
if f ~= nil then
io.close(f)
return fpath
end
end
error("File not found: " .. path)
end
function engine.element.create(elementType)
if engine.elementTypes[elementType] == nil then
engine.elementTypes[elementType] = {
_type = elementType,
_references = 0
}
assert(loadfile(engine.path(elementType.. ".lua")))(engine.elementTypes[elementType])
end
engine.elementTypes[elementType]._references = engine.elementTypes[elementType]._references + 1
local id = 1
while true do
id = math.random(1,2147483647)
if engine.elements[id] == nil then break end
end
local element = {
memlo = {
_children = {}
},
memhi = {
_id = id,
_type = elementType,
_children = {},
_childrenCount = 0
}
}
engine.elementTypes[elementType].create(element)
engine.elements[id] = element
return element
end
function engine.element.attach(child,parent)
if child.memlo._parent ~= nil then
child.memlo._parent.memlo._children[child.memhi._id] = nil
child.memlo._parent.memhi._children[child.memhi._id] = nil
child.memlo._parent.memhi._childrenCount = child.memlo._parent.memhi._childrenCount - 1
end
child.memlo._parent = parent
if parent == nil then
child.memhi._parent = nil
return
end
child.memhi._parent = parent.memhi._id
parent.memhi._children[child.memhi._id] = true
parent.memlo._children[child.memhi._id] = child
parent.memhi._childrenCount = parent.memhi._childrenCount + 1
end
function engine.element.destroy(element,destroyChildren)
if destroyChildren == nil then destroyChildren = true end
engine.element.attach(element)
if destroyChildren == true then
if element.memhi._childrenCount > 0 then
for i,v in pairs(element.memlo._children) do
engine.element.destroy(v)
end
end
end
engine.elementTypes[element.memhi._type].destroy(element)
engine.elements[element.memhi._id] = nil
engine.elementTypes[element.memhi._type]._references = engine.elementTypes[element.memhi._type]._references - 1
if engine.elementTypes[element.memhi._type]._references == 0 then
engine.elementTypes[element.memhi._type].unload()
engine.elementTypes[element.memhi._type] = nil
end
end
return engine