optimize hook calls and add tests

This commit is contained in:
Ukendio 2024-08-11 04:03:18 +02:00
parent a0935fe0f1
commit b57239fac2
2 changed files with 38 additions and 3 deletions

View file

@ -520,7 +520,7 @@ local function world_set(world: World, entity: i53, id: i53, data: unknown)
local tr = to.records[id] local tr = to.records[id]
to.columns[tr.column][record.row] = data to.columns[tr.column][record.row] = data
invoke_hook(world, EcsOnAdd, id, entity, data) invoke_hook(world, EcsOnSet, id, entity, data)
end end
local function world_component(world: World): i53 local function world_component(world: World): i53
@ -556,8 +556,6 @@ local function archetype_traverse_remove(world: World, id: i53, from: Archetype)
end end
local function world_remove(world: World, entity: i53, id: i53) local function world_remove(world: World, entity: i53, id: i53)
invoke_hook(world, EcsOnRemove, id, entity)
local entity_index = world.entityIndex local entity_index = world.entityIndex
local record = entity_index.sparse[entity] local record = entity_index.sparse[entity]
local from = record.archetype local from = record.archetype
@ -567,6 +565,7 @@ local function world_remove(world: World, entity: i53, id: i53)
local to = archetype_traverse_remove(world, id, from) local to = archetype_traverse_remove(world, id, from)
if from and not (from == to) then if from and not (from == to) then
invoke_hook(world, EcsOnRemove, id, entity)
entity_move(entity_index, entity, record, to) entity_move(entity_index, entity, record, to)
end end
end end

View file

@ -172,6 +172,7 @@ TEST("world:remove()", function()
end) end)
TEST("world:add()", function() TEST("world:add()", function()
do CASE "idempotent" do CASE "idempotent"
local world = jecs.World.new() local world = jecs.World.new()
local d = debug_world_inspect(world) local d = debug_world_inspect(world)
@ -968,4 +969,39 @@ TEST("changetracker:track()", function()
end) end)
TEST("Hooks", function()
do CASE "OnAdd"
local world = jecs.World.new()
local Transform = world:component()
local e1 = world:entity()
world:set(Transform, jecs.OnAdd, function(entity)
CHECK(e1 == entity)
end)
world:add(e1, Transform)
end
do CASE "OnSet"
local world = jecs.World.new()
local Number = world:component()
local e1 = world:entity()
world:set(Number, jecs.OnSet, function(entity, data)
CHECK(e1 == entity)
CHECK(data == 1)
end)
world:set(e1, Number, 1)
end
do CASE "OnRemove"
local world = jecs.World.new()
local A = world:component()
local e1 = world:entity()
world:add(e1, A)
world:set(A, jecs.OnRemove, function(entity)
CHECK(e1 == entity)
CHECK(world:has(e1, A))
end)
world:remove(e1, A)
end
end)
FINISH() FINISH()