diff --git a/benches/visual/remove.bench.luau b/benches/visual/remove.bench.luau index 5af2a17..a7082a8 100644 --- a/benches/visual/remove.bench.luau +++ b/benches/visual/remove.bench.luau @@ -1,49 +1,49 @@ ---!optimize 2 ---!native - -local ReplicatedStorage = game:GetService("ReplicatedStorage") -local Matter = require(ReplicatedStorage.DevPackages.Matter) -local ecr = require(ReplicatedStorage.DevPackages.ecr) -local jecs = require(ReplicatedStorage.Lib) -local pair = jecs.pair -local ecs = jecs.World.new() -local mirror = require(ReplicatedStorage.mirror) -local mcs = mirror.World.new() - -local C1 = ecs:component() -local C2 = ecs:entity() -ecs:add(C2, pair(jecs.OnDeleteTarget, jecs.Delete)) -local C3 = ecs:entity() -ecs:add(C3, pair(jecs.OnDeleteTarget, jecs.Delete)) -local C4 = ecs:entity() -ecs:add(C4, pair(jecs.OnDeleteTarget, jecs.Delete)) -local E1 = mcs:component() -local E2 = mcs:entity() -mcs:add(E2, pair(jecs.OnDeleteTarget, jecs.Delete)) -local E3 = mcs:entity() -mcs:add(E3, pair(jecs.OnDeleteTarget, jecs.Delete)) -local E4 = mcs:entity() -mcs:add(E4, pair(jecs.OnDeleteTarget, jecs.Delete)) - -return { - ParameterGenerator = function() - end, - - Functions = { - Mirror = function() - local m = mcs:entity() - for i = 1, 100 do - mcs:add(m, E3) - mcs:remove(m, E3) - end - end, - - Jecs = function() - local j = ecs:entity() - for i = 1, 100 do - ecs:add(j, C3) - ecs:remove(j, C3) - end - end, - }, -} +--!optimize 2 +--!native + +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local Matter = require(ReplicatedStorage.DevPackages.Matter) +local ecr = require(ReplicatedStorage.DevPackages.ecr) +local jecs = require(ReplicatedStorage.Lib) +local pair = jecs.pair +local ecs = jecs.World.new() +local mirror = require(ReplicatedStorage.mirror) +local mcs = mirror.World.new() + +local C1 = ecs:component() +local C2 = ecs:entity() +ecs:add(C2, pair(jecs.OnDeleteTarget, jecs.Delete)) +local C3 = ecs:entity() +ecs:add(C3, pair(jecs.OnDeleteTarget, jecs.Delete)) +local C4 = ecs:entity() +ecs:add(C4, pair(jecs.OnDeleteTarget, jecs.Delete)) +local E1 = mcs:component() +local E2 = mcs:entity() +mcs:add(E2, pair(jecs.OnDeleteTarget, jecs.Delete)) +local E3 = mcs:entity() +mcs:add(E3, pair(jecs.OnDeleteTarget, jecs.Delete)) +local E4 = mcs:entity() +mcs:add(E4, pair(jecs.OnDeleteTarget, jecs.Delete)) + +return { + ParameterGenerator = function() + end, + + Functions = { + Mirror = function() + local m = mcs:entity() + for i = 1, 100 do + mcs:add(m, E3) + mcs:remove(m, E3) + end + end, + + Jecs = function() + local j = ecs:entity() + for i = 1, 100 do + ecs:add(j, C3) + ecs:remove(j, C3) + end + end, + }, +} diff --git a/demo/src/ReplicatedStorage/collect.luau b/demo/src/ReplicatedStorage/collect.luau index d6df981..9ec3bdd 100644 --- a/demo/src/ReplicatedStorage/collect.luau +++ b/demo/src/ReplicatedStorage/collect.luau @@ -1,28 +1,28 @@ -local function collect( - signal: { - Connect: (RBXScriptSignal, fn: (T...) -> ()) -> RBXScriptConnection - } -): () -> (T...) - local enqueued = {} - - local i = 0 - - local connection = (signal :: any):Connect(function(...) - table.insert(enqueued, { ... }) - i += 1 - end) - - return function(): any - if i == 0 then - return - end - - i -= 1 - - local args: any = table.remove(enqueued, 1) - - return unpack(args) - end, connection -end - -return collect +local function collect( + signal: { + Connect: (RBXScriptSignal, fn: (T...) -> ()) -> RBXScriptConnection + } +): () -> (T...) + local enqueued = {} + + local i = 0 + + local connection = (signal :: any):Connect(function(...) + table.insert(enqueued, { ... }) + i += 1 + end) + + return function(): any + if i == 0 then + return + end + + i -= 1 + + local args: any = table.remove(enqueued, 1) + + return unpack(args) + end, connection +end + +return collect diff --git a/demo/src/ReplicatedStorage/components.luau b/demo/src/ReplicatedStorage/components.luau index 5bb3225..f9fb0c4 100644 --- a/demo/src/ReplicatedStorage/components.luau +++ b/demo/src/ReplicatedStorage/components.luau @@ -1,36 +1,36 @@ -local ReplicatedStorage = game:GetService("ReplicatedStorage") -local jecs = require(ReplicatedStorage.ecs) -local types = require("./types") - -local Networked = jecs.tag() -local NetworkedPair = jecs.tag() - -local Renderable = jecs.component() :: jecs.Id -jecs.meta(Renderable, Networked) - - -local Poison = jecs.component() :: jecs.Id -jecs.meta(Poison, Networked) - -local Health = jecs.component() :: jecs.Id -jecs.meta(Health, Networked) - -local Player = jecs.component() :: jecs.Id -jecs.meta(Player, Networked) - - -local components = { - Renderable = Renderable, - Player = Player, - Poison = Poison, - Health = Health, - - Networked = Networked, - NetworkedPair = NetworkedPair, -} - -for name, component in components do - jecs.meta(component, jecs.Name, name) -end - -return components +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local jecs = require(ReplicatedStorage.ecs) +local types = require("./types") + +local Networked = jecs.tag() +local NetworkedPair = jecs.tag() + +local Renderable = jecs.component() :: jecs.Id +jecs.meta(Renderable, Networked) + + +local Poison = jecs.component() :: jecs.Id +jecs.meta(Poison, Networked) + +local Health = jecs.component() :: jecs.Id +jecs.meta(Health, Networked) + +local Player = jecs.component() :: jecs.Id +jecs.meta(Player, Networked) + + +local components = { + Renderable = Renderable, + Player = Player, + Poison = Poison, + Health = Health, + + Networked = Networked, + NetworkedPair = NetworkedPair, +} + +for name, component in components do + jecs.meta(component, jecs.Name, name) +end + +return components diff --git a/demo/src/ReplicatedStorage/observers_add.luau b/demo/src/ReplicatedStorage/observers_add.luau index c959b88..b310ab1 100644 --- a/demo/src/ReplicatedStorage/observers_add.luau +++ b/demo/src/ReplicatedStorage/observers_add.luau @@ -1,190 +1,190 @@ -local ReplicatedStorage = game:GetService("ReplicatedStorage") -local jecs = require(ReplicatedStorage.ecs) - -type Observer = { - callback: (jecs.Entity) -> (), - query: jecs.Query, -} - -export type PatchedWorld = jecs.World & { - added: (PatchedWorld, jecs.Id, (e: jecs.Entity, id: jecs.Id, value: T) -> ()) -> (), - removed: (PatchedWorld, jecs.Id, (e: jecs.Entity, id: jecs.Id) -> ()) -> (), - changed: (PatchedWorld, jecs.Id, (e: jecs.Entity, id: jecs.Id, value: T) -> ()) -> (), - -- deleted: (PatchedWorld, () -> ()) -> () -> (), - observer: (PatchedWorld, Observer) -> (), - monitor: (PatchedWorld, Observer) -> (), -} - -local function observers_new(world, description) - local query = description.query - local callback = description.callback - local terms = query.filter_with :: { jecs.Id } - if not terms then - local ids = query.ids - query.filter_with = ids - terms = ids - end - - local entity_index = world.entity_index :: any - local function emplaced(entity: jecs.Entity) - local r = jecs.entity_index_try_get_fast( - entity_index, entity :: any) - - if not r then - return - end - - local archetype = r.archetype - - if jecs.query_match(query, archetype) then - callback(entity) - end - end - - for _, term in terms do - world:added(term, emplaced) - world:changed(term, emplaced) - end -end - -local function monitors_new(world, description) - local query = description.query - local callback = description.callback - local terms = query.filter_with :: { jecs.Id } - if not terms then - local ids = query.ids - query.filter_with = ids - terms = ids - end - - local entity_index = world.entity_index :: any - local function emplaced(entity: jecs.Entity) - local r = jecs.entity_index_try_get_fast( - entity_index, entity :: any) - - if not r then - return - end - - local archetype = r.archetype - - if jecs.query_match(query, archetype) then - callback(entity, jecs.OnAdd) - end - end - - local function removed(entity: jecs.Entity, component: jecs.Id) - local r = jecs.entity_index_try_get_fast( - entity_index, entity :: any) - - if not r then - return - end - - local archetype = r.archetype - - if jecs.query_match(query, archetype) then - callback(entity, jecs.OnRemove) - end - end - - for _, term in terms do - world:added(term, emplaced) - world:removed(term, removed) - end -end - -local function observers_add(world: jecs.World): PatchedWorld - local signals = { - added = {}, - emplaced = {}, - removed = {}, - deleted = {} - } - - world = world :: jecs.World & {[string]: any} - - world.added = function(_, component, fn) - local listeners = signals.added[component] - if not listeners then - listeners = {} - signals.added[component] = listeners - - local idr = jecs.id_record_ensure(world :: any, component :: any) - local rw = jecs.pair(component, jecs.Wildcard) - local idr_r = jecs.id_record_ensure(world :: any, rw :: any) - local function on_add(entity: number, id: number, value: any) - for _, listener in listeners do - listener(entity, id, value) - end - end - world:set(component, jecs.OnAdd, on_add) - idr.hooks.on_add = on_add :: any - idr_r.hooks.on_add = on_add :: any - end - table.insert(listeners, fn) - end - - world.changed = function(_, component, fn) - local listeners = signals.emplaced[component] - if not listeners then - listeners = {} - signals.emplaced[component] = listeners - local idr = jecs.id_record_ensure(world :: any, component :: any) - local rw = jecs.pair(component, jecs.Wildcard) - local idr_r = jecs.id_record_ensure(world :: any, rw :: any) - local function on_change(entity: number, id: number, value: any) - for _, listener in listeners do - listener(entity, id, value) - end - end - world:set(component, jecs.OnChange, on_change) - idr.hooks.on_change = on_change :: any - idr_r.hooks.on_change = on_change :: any - end - table.insert(listeners, fn) - end - - world.removed = function(_, component, fn) - local listeners = signals.removed[component] - if not listeners then - listeners = {} - signals.removed[component] = listeners - local idr = jecs.id_record_ensure(world :: any, component :: any) - local rw = jecs.pair(component, jecs.Wildcard) - local idr_r = jecs.id_record_ensure(world :: any, rw :: any) - local function on_remove(entity: number, id: number, value: any) - for _, listener in listeners do - listener(entity, id, value) - end - end - world:set(component, jecs.OnRemove, on_remove) - idr.hooks.on_remove = on_remove :: any - idr_r.hooks.on_remove = on_remove :: any - end - table.insert(listeners, fn) - end - - world.signals = signals - - world.observer = observers_new - - world.monitor = monitors_new - - -- local world_delete = world.delete - - -- world.deleted = function(_, fn) - -- local listeners = signals.deleted - -- table.insert(listeners, fn) - -- end - -- world.delete = function(world, entity) - -- world_delete(world, entity) - -- for _, fn in signals.deleted do - -- fn(entity) - -- end - -- end - - return world :: PatchedWorld -end - -return observers_add +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local jecs = require(ReplicatedStorage.ecs) + +type Observer = { + callback: (jecs.Entity) -> (), + query: jecs.Query, +} + +export type PatchedWorld = jecs.World & { + added: (PatchedWorld, jecs.Id, (e: jecs.Entity, id: jecs.Id, value: T) -> ()) -> (), + removed: (PatchedWorld, jecs.Id, (e: jecs.Entity, id: jecs.Id) -> ()) -> (), + changed: (PatchedWorld, jecs.Id, (e: jecs.Entity, id: jecs.Id, value: T) -> ()) -> (), + -- deleted: (PatchedWorld, () -> ()) -> () -> (), + observer: (PatchedWorld, Observer) -> (), + monitor: (PatchedWorld, Observer) -> (), +} + +local function observers_new(world, description) + local query = description.query + local callback = description.callback + local terms = query.filter_with :: { jecs.Id } + if not terms then + local ids = query.ids + query.filter_with = ids + terms = ids + end + + local entity_index = world.entity_index :: any + local function emplaced(entity: jecs.Entity) + local r = jecs.entity_index_try_get_fast( + entity_index, entity :: any) + + if not r then + return + end + + local archetype = r.archetype + + if jecs.query_match(query, archetype) then + callback(entity) + end + end + + for _, term in terms do + world:added(term, emplaced) + world:changed(term, emplaced) + end +end + +local function monitors_new(world, description) + local query = description.query + local callback = description.callback + local terms = query.filter_with :: { jecs.Id } + if not terms then + local ids = query.ids + query.filter_with = ids + terms = ids + end + + local entity_index = world.entity_index :: any + local function emplaced(entity: jecs.Entity) + local r = jecs.entity_index_try_get_fast( + entity_index, entity :: any) + + if not r then + return + end + + local archetype = r.archetype + + if jecs.query_match(query, archetype) then + callback(entity, jecs.OnAdd) + end + end + + local function removed(entity: jecs.Entity, component: jecs.Id) + local r = jecs.entity_index_try_get_fast( + entity_index, entity :: any) + + if not r then + return + end + + local archetype = r.archetype + + if jecs.query_match(query, archetype) then + callback(entity, jecs.OnRemove) + end + end + + for _, term in terms do + world:added(term, emplaced) + world:removed(term, removed) + end +end + +local function observers_add(world: jecs.World): PatchedWorld + local signals = { + added = {}, + emplaced = {}, + removed = {}, + deleted = {} + } + + world = world :: jecs.World & {[string]: any} + + world.added = function(_, component, fn) + local listeners = signals.added[component] + if not listeners then + listeners = {} + signals.added[component] = listeners + + local idr = jecs.id_record_ensure(world :: any, component :: any) + local rw = jecs.pair(component, jecs.Wildcard) + local idr_r = jecs.id_record_ensure(world :: any, rw :: any) + local function on_add(entity: number, id: number, value: any) + for _, listener in listeners do + listener(entity, id, value) + end + end + world:set(component, jecs.OnAdd, on_add) + idr.hooks.on_add = on_add :: any + idr_r.hooks.on_add = on_add :: any + end + table.insert(listeners, fn) + end + + world.changed = function(_, component, fn) + local listeners = signals.emplaced[component] + if not listeners then + listeners = {} + signals.emplaced[component] = listeners + local idr = jecs.id_record_ensure(world :: any, component :: any) + local rw = jecs.pair(component, jecs.Wildcard) + local idr_r = jecs.id_record_ensure(world :: any, rw :: any) + local function on_change(entity: number, id: number, value: any) + for _, listener in listeners do + listener(entity, id, value) + end + end + world:set(component, jecs.OnChange, on_change) + idr.hooks.on_change = on_change :: any + idr_r.hooks.on_change = on_change :: any + end + table.insert(listeners, fn) + end + + world.removed = function(_, component, fn) + local listeners = signals.removed[component] + if not listeners then + listeners = {} + signals.removed[component] = listeners + local idr = jecs.id_record_ensure(world :: any, component :: any) + local rw = jecs.pair(component, jecs.Wildcard) + local idr_r = jecs.id_record_ensure(world :: any, rw :: any) + local function on_remove(entity: number, id: number, value: any) + for _, listener in listeners do + listener(entity, id, value) + end + end + world:set(component, jecs.OnRemove, on_remove) + idr.hooks.on_remove = on_remove :: any + idr_r.hooks.on_remove = on_remove :: any + end + table.insert(listeners, fn) + end + + world.signals = signals + + world.observer = observers_new + + world.monitor = monitors_new + + -- local world_delete = world.delete + + -- world.deleted = function(_, fn) + -- local listeners = signals.deleted + -- table.insert(listeners, fn) + -- end + -- world.delete = function(world, entity) + -- world_delete(world, entity) + -- for _, fn in signals.deleted do + -- fn(entity) + -- end + -- end + + return world :: PatchedWorld +end + +return observers_add diff --git a/demo/src/ReplicatedStorage/remotes.luau b/demo/src/ReplicatedStorage/remotes.luau index 4838770..64f87e6 100644 --- a/demo/src/ReplicatedStorage/remotes.luau +++ b/demo/src/ReplicatedStorage/remotes.luau @@ -1,50 +1,50 @@ -local ReplicatedStorage = game:GetService("ReplicatedStorage") -local types = require("../ReplicatedStorage/types") - -type Signal = { - Connect: (Signal, fn: (T...) -> ()) -> RBXScriptConnection -} -type Remote = { - FireClient: (Remote, T...) -> (), - FireAllClients: (Remote, T...) -> (), - FireServer: (Remote) -> (), - OnServerEvent: { - Connect: (any, fn: (Player, T...) -> () ) -> () - }, - OnClientEvent: { - Connect: (any, fn: (T...) -> () ) -> () - } - -} - -local function stream_ensure(name): Remote - local remote = ReplicatedStorage:FindFirstChild(name) - if not remote then - remote = Instance.new("RemoteEvent") - remote.Name = name - remote.Parent = ReplicatedStorage - end - return remote :: any -end - -local function datagram_ensure(name): Remote - local remote = ReplicatedStorage:FindFirstChild(name) - if not remote then - remote = Instance.new("UnreliableRemoteEvent") - remote.Name = name - remote.Parent = ReplicatedStorage - end - return remote :: any -end - -return { - input = datagram_ensure("input") :: Remote, - replication = stream_ensure("replication") :: Remote<{ - [string]: { - set: { types.Entity }?, - values: { any }?, - removed: { types.Entity }? - } - }>, - -} +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local types = require("../ReplicatedStorage/types") + +type Signal = { + Connect: (Signal, fn: (T...) -> ()) -> RBXScriptConnection +} +type Remote = { + FireClient: (Remote, T...) -> (), + FireAllClients: (Remote, T...) -> (), + FireServer: (Remote) -> (), + OnServerEvent: { + Connect: (any, fn: (Player, T...) -> () ) -> () + }, + OnClientEvent: { + Connect: (any, fn: (T...) -> () ) -> () + } + +} + +local function stream_ensure(name): Remote + local remote = ReplicatedStorage:FindFirstChild(name) + if not remote then + remote = Instance.new("RemoteEvent") + remote.Name = name + remote.Parent = ReplicatedStorage + end + return remote :: any +end + +local function datagram_ensure(name): Remote + local remote = ReplicatedStorage:FindFirstChild(name) + if not remote then + remote = Instance.new("UnreliableRemoteEvent") + remote.Name = name + remote.Parent = ReplicatedStorage + end + return remote :: any +end + +return { + input = datagram_ensure("input") :: Remote, + replication = stream_ensure("replication") :: Remote<{ + [string]: { + set: { types.Entity }?, + values: { any }?, + removed: { types.Entity }? + } + }>, + +} diff --git a/demo/src/ReplicatedStorage/schedule.luau b/demo/src/ReplicatedStorage/schedule.luau index 7030bbe..14652f3 100644 --- a/demo/src/ReplicatedStorage/schedule.luau +++ b/demo/src/ReplicatedStorage/schedule.luau @@ -1,136 +1,136 @@ -local ReplicatedStorage = game:GetService("ReplicatedStorage") -local jabby = require(ReplicatedStorage.Packages.jabby) -local jecs = require(ReplicatedStorage.ecs) - -jabby.set_check_function(function() return true end) - -local scheduler = jabby.scheduler.create("jabby scheduler") - -jabby.register({ - applet = jabby.applets.scheduler, - name = "Scheduler", - configuration = { - scheduler = scheduler, - }, -}) - -local ContextActionService = game:GetService("ContextActionService") - -local function create_widget(_, state: Enum.UserInputState) - local client = jabby.obtain_client() - if state ~= Enum.UserInputState.Begin then return end - client.spawn_app(client.apps.home, nil) -end - -local RunService = game:GetService("RunService") - -local System = jecs.component() :: jecs.Id<{ - fn: () -> (), - name: string, -}> -local DependsOn = jecs.component() -local Phase = jecs.tag() -local Event = jecs.component() :: jecs.Id - -local pair = jecs.pair - -local types = require(ReplicatedStorage.types) - -local function ECS_PHASE(world, after: types.Entity) - local phase = world:entity() - world:add(phase, Phase) - if after then - local dependency = pair(DependsOn, after) - world:add(phase, dependency) - end - - return phase -end - -local Heartbeat = jecs.tag() -jecs.meta(Heartbeat, Phase) -jecs.meta(Heartbeat, Event, RunService.Heartbeat) - -local PreSimulation = jecs.tag() -jecs.meta(PreSimulation, Phase) -jecs.meta(PreSimulation, Event, RunService.PreSimulation) - -local PreAnimation = jecs.tag() -jecs.meta(PreAnimation, Phase) -jecs.meta(PreAnimation, Event, RunService.PreAnimation) - -local PreRender = jecs.tag() -jecs.meta(PreRender, Phase) -jecs.meta(PreRender, Event, RunService.PreRender) - -local function ECS_SYSTEM(world: types.World, mod: ModuleScript, phase: types.Entity?) - local system = world:entity() - local p = phase or Heartbeat - local fn = require(mod) :: (...any) -> () - world:set(system, System, { - fn = fn(world, 0) or fn, - name = mod.Name, - }) - - local depends_on = DependsOn :: jecs.Entity - world:add(system, pair(depends_on, p)) -end -local function find_systems_w_phase(world: types.World, systems, phase: types.Entity) - local phase_name = world:get(phase, jecs.Name) :: string - for _, s in world:query(System):with(pair(DependsOn, phase)) do - table.insert(systems, { - id = scheduler:register_system({ - phase = phase_name, - name = s.name, - }), - fn = s.fn - }) - end - for after in world:query(Phase, pair(DependsOn, phase)) do - find_systems_w_phase(world, systems, after) - end - return systems -end - -local function ECS_RUN(world: types.World) - - jabby.register({ - applet = jabby.applets.world, - name = "MyWorld", - configuration = { - world = world, - }, - }) - - if RunService:IsClient() then - ContextActionService:BindAction("Open Jabby Home", create_widget, false, Enum.KeyCode.F4) - end - - for phase, event in world:query(Event, Phase) do - local systems = find_systems_w_phase(world, {}, phase) - event:Connect(function(...) - for _, system in systems do - scheduler:run(system.id, system.fn, world, ...) - end - end) - end - -end - -return { - PHASE = ECS_PHASE, - SYSTEM = ECS_SYSTEM, - RUN = ECS_RUN, - phases = { - Heartbeat = Heartbeat, - PreSimulation = PreSimulation, - PreAnimation = PreAnimation, - PreRender = PreRender - }, - components = { - System = System, - DependsOn = DependsOn, - Phase = Phase, - Event = Event, - } -} +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local jabby = require(ReplicatedStorage.Packages.jabby) +local jecs = require(ReplicatedStorage.ecs) + +jabby.set_check_function(function() return true end) + +local scheduler = jabby.scheduler.create("jabby scheduler") + +jabby.register({ + applet = jabby.applets.scheduler, + name = "Scheduler", + configuration = { + scheduler = scheduler, + }, +}) + +local ContextActionService = game:GetService("ContextActionService") + +local function create_widget(_, state: Enum.UserInputState) + local client = jabby.obtain_client() + if state ~= Enum.UserInputState.Begin then return end + client.spawn_app(client.apps.home, nil) +end + +local RunService = game:GetService("RunService") + +local System = jecs.component() :: jecs.Id<{ + fn: () -> (), + name: string, +}> +local DependsOn = jecs.component() +local Phase = jecs.tag() +local Event = jecs.component() :: jecs.Id + +local pair = jecs.pair + +local types = require(ReplicatedStorage.types) + +local function ECS_PHASE(world, after: types.Entity) + local phase = world:entity() + world:add(phase, Phase) + if after then + local dependency = pair(DependsOn, after) + world:add(phase, dependency) + end + + return phase +end + +local Heartbeat = jecs.tag() +jecs.meta(Heartbeat, Phase) +jecs.meta(Heartbeat, Event, RunService.Heartbeat) + +local PreSimulation = jecs.tag() +jecs.meta(PreSimulation, Phase) +jecs.meta(PreSimulation, Event, RunService.PreSimulation) + +local PreAnimation = jecs.tag() +jecs.meta(PreAnimation, Phase) +jecs.meta(PreAnimation, Event, RunService.PreAnimation) + +local PreRender = jecs.tag() +jecs.meta(PreRender, Phase) +jecs.meta(PreRender, Event, RunService.PreRender) + +local function ECS_SYSTEM(world: types.World, mod: ModuleScript, phase: types.Entity?) + local system = world:entity() + local p = phase or Heartbeat + local fn = require(mod) :: (...any) -> () + world:set(system, System, { + fn = fn(world, 0) or fn, + name = mod.Name, + }) + + local depends_on = DependsOn :: jecs.Entity + world:add(system, pair(depends_on, p)) +end +local function find_systems_w_phase(world: types.World, systems, phase: types.Entity) + local phase_name = world:get(phase, jecs.Name) :: string + for _, s in world:query(System):with(pair(DependsOn, phase)) do + table.insert(systems, { + id = scheduler:register_system({ + phase = phase_name, + name = s.name, + }), + fn = s.fn + }) + end + for after in world:query(Phase, pair(DependsOn, phase)) do + find_systems_w_phase(world, systems, after) + end + return systems +end + +local function ECS_RUN(world: types.World) + + jabby.register({ + applet = jabby.applets.world, + name = "MyWorld", + configuration = { + world = world, + }, + }) + + if RunService:IsClient() then + ContextActionService:BindAction("Open Jabby Home", create_widget, false, Enum.KeyCode.F4) + end + + for phase, event in world:query(Event, Phase) do + local systems = find_systems_w_phase(world, {}, phase) + event:Connect(function(...) + for _, system in systems do + scheduler:run(system.id, system.fn, world, ...) + end + end) + end + +end + +return { + PHASE = ECS_PHASE, + SYSTEM = ECS_SYSTEM, + RUN = ECS_RUN, + phases = { + Heartbeat = Heartbeat, + PreSimulation = PreSimulation, + PreAnimation = PreAnimation, + PreRender = PreRender + }, + components = { + System = System, + DependsOn = DependsOn, + Phase = Phase, + Event = Event, + } +} diff --git a/demo/src/ReplicatedStorage/systems/receive_replication.luau b/demo/src/ReplicatedStorage/systems/receive_replication.luau index 68376f8..c2b090d 100644 --- a/demo/src/ReplicatedStorage/systems/receive_replication.luau +++ b/demo/src/ReplicatedStorage/systems/receive_replication.luau @@ -1,71 +1,86 @@ -local types = require("../types") -local jecs = require(game:GetService("ReplicatedStorage").ecs) -local remotes = require("../remotes") -local collect = require("../collect") -local client_ids = {} - -local function ecs_map_get(world: types.World, id: types.Entity) - local deserialised_id = client_ids[id] - if not deserialised_id then - if world:has(id, jecs.Name) then - deserialised_id = world:entity(id) - else - if world:exists(id) then - deserialised_id = world:entity() - else - deserialised_id = world:entity(id) - end - end - client_ids[id] = deserialised_id - end - return deserialised_id -end - -local function ecs_make_alive_id(world: types.World, id: jecs.Id) - local rel = jecs.ECS_PAIR_FIRST(id) - local tgt = jecs.ECS_PAIR_SECOND(id) - - ecs_map_get(world, rel) - ecs_map_get(world, tgt) -end - -local snapshots = collect(remotes.replication.OnClientEvent) - -return function(world: types.World) - return function() - for snapshot in snapshots do - for key, map in snapshot do - local id = (tonumber(key) :: any) :: jecs.Id - if jecs.IS_PAIR(id) then - ecs_make_alive_id(world, id) - end - - local set = map.set - if set then - if jecs.is_tag(world, id) then - for _, entity in set do - entity = ecs_map_get(world, entity) - world:add(entity, id) - end - else - local values = map.values :: { any } - for i, entity in set do - entity = ecs_map_get(world, entity) - world:set(entity, id, values[i]) - end - end - end - - local removed = map.removed - if removed then - for i, e in removed do - if not world:contains(e) then - continue - end - world:remove(e, id) - end - end - end - end - end -end +local types = require("../types") +local jecs = require(game:GetService("ReplicatedStorage").ecs) +local remotes = require("../remotes") +local collect = require("../collect") +local client_ids = {} + + +local function ecs_map_get(world, id) + local deserialised_id = client_ids[id] + + if not deserialised_id then + if world:has(id, jecs.Name) then + deserialised_id = world:entity(id) + else + deserialised_id = world:entity() + end + + client_ids[id] = deserialised_id + end + + -- local deserialised_id = client_ids[id] + -- if not deserialised_id then + -- if world:has(id, jecs.Name) then + -- deserialised_id = world:entity(id) + -- else + -- if world:exists(id) then + -- deserialised_id = world:entity() + -- else + -- deserialised_id = world:entity(id) + -- end + -- end + -- client_ids[id] = deserialised_id + -- end + + return deserialised_id +end + +local function ecs_make_alive_id(world, id) + local rel = jecs.ECS_PAIR_FIRST(id) + local tgt = jecs.ECS_PAIR_SECOND(id) + + rel = ecs_map_get(world, rel) + tgt = ecs_map_get(world, tgt) + + return jecs.pair(rel, tgt) +end + +local snapshots = collect(remotes.replication.OnClientEvent) + +return function(world: types.World) + for snapshot in snapshots do + for id, map in snapshot do + id = tonumber(id) + if jecs.IS_PAIR(id) then + id = ecs_make_alive_id(world, id) + end + + local set = map.set + if set then + if jecs.is_tag(world, id) then + for _, entity in set do + entity = ecs_map_get(world, entity) + world:add(entity, id) + end + else + local values = map.values + for i, entity in set do + entity = ecs_map_get(world, entity) + world:set(entity, id, values[i]) + end + end + end + + local removed = map.removed + + if removed then + for i, e in removed do + if not world:contains(e) then + continue + end + world:remove(e, id) + end + end + end + end +end diff --git a/demo/src/ReplicatedStorage/types.luau b/demo/src/ReplicatedStorage/types.luau index 678fb71..ae585e7 100644 --- a/demo/src/ReplicatedStorage/types.luau +++ b/demo/src/ReplicatedStorage/types.luau @@ -1,8 +1,15 @@ -local jecs = require(game:GetService("ReplicatedStorage").ecs) -local observers_add = require("../ReplicatedStorage/observers_add") - -export type World = typeof(observers_add(jecs.world())) -export type Entity = jecs.Entity -export type Id = jecs.Id - -return {} +local jecs = require(game:GetService("ReplicatedStorage").ecs) +local observers_add = require("../ReplicatedStorage/observers_add") + +export type World = typeof(observers_add(jecs.world())) +export type Entity = jecs.Entity +export type Id = jecs.Id +export type Snapshot = { + [string]: { + set: { jecs.Entity }?, + values: { any }?, + removed: { jecs.Entity }? + } +} + +return {} diff --git a/demo/src/ServerScriptService/systems/life_is_painful.luau b/demo/src/ServerScriptService/systems/life_is_painful.luau index 333e64b..d68dd9e 100644 --- a/demo/src/ServerScriptService/systems/life_is_painful.luau +++ b/demo/src/ServerScriptService/systems/life_is_painful.luau @@ -1,12 +1,12 @@ -local ReplicatedStorage = game:GetService("ReplicatedStorage") -local ct = require(ReplicatedStorage.components) -local types = require(ReplicatedStorage.types) - -return function(world: types.World, dt: number) - for e in world:query(ct.Player):without(ct.Health) do - world:set(e, ct.Health, 100) - end - for e in world:query(ct.Player, ct.Health):without(ct.Poison) do - world:set(e, ct.Poison, 10) - end -end +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local ct = require(ReplicatedStorage.components) +local types = require(ReplicatedStorage.types) + +return function(world: types.World, dt: number) + for e in world:query(ct.Player):without(ct.Health) do + world:set(e, ct.Health, 100) + end + for e in world:query(ct.Player, ct.Health):without(ct.Poison) do + world:set(e, ct.Poison, 10) + end +end diff --git a/demo/src/ServerScriptService/systems/players_added.luau b/demo/src/ServerScriptService/systems/players_added.luau index 46b1ab1..a611e8b 100644 --- a/demo/src/ServerScriptService/systems/players_added.luau +++ b/demo/src/ServerScriptService/systems/players_added.luau @@ -1,20 +1,20 @@ -local collect = require("../../ReplicatedStorage/collect") -local types = require("../../ReplicatedStorage/types") -local ct = require("../../ReplicatedStorage/components") -local Players = game:GetService("Players") - -local player_added = collect(Players.PlayerAdded) -return function(world: types.World, dt: number) - for player in player_added do - local entity = world:entity() - world:set(entity, ct.Player, player) - end - - for entity, player in world:query(ct.Player):without(ct.Renderable) do - local character = player.Character - if character then - if not character.Parent then - world:set(entity, ct.Renderable, character) - end - end -end +local collect = require("../../ReplicatedStorage/collect") +local types = require("../../ReplicatedStorage/types") +local ct = require("../../ReplicatedStorage/components") +local Players = game:GetService("Players") + +local player_added = collect(Players.PlayerAdded) +return function(world: types.World, dt: number) + for player in player_added do + local entity = world:entity() + world:set(entity, ct.Player, player) + end + + for entity, player in world:query(ct.Player):without(ct.Renderable) do + local character = player.Character + if character then + if not character.Parent then + world:set(entity, ct.Renderable, character) + end + end +end diff --git a/demo/src/ServerScriptService/systems/poison_hurts.luau b/demo/src/ServerScriptService/systems/poison_hurts.luau index a7e1f3e..f5ae04c 100644 --- a/demo/src/ServerScriptService/systems/poison_hurts.luau +++ b/demo/src/ServerScriptService/systems/poison_hurts.luau @@ -1,12 +1,12 @@ -local ReplicatedStorage = game:GetService("ReplicatedStorage") -local ct = require(ReplicatedStorage.components) -return function(world, dt) - for e, poison, health in world:query(ct.Poison, ct.Health) do - local health_after_tick = health - poison * dt * 0.05 - if health_after_tick < 0 then - world:remove(e, ct.Health) - continue - end - world:set(e, ct.Health, health_after_tick) - end -end +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local ct = require(ReplicatedStorage.components) +return function(world, dt) + for e, poison, health in world:query(ct.Poison, ct.Health) do + local health_after_tick = health - poison * dt * 0.05 + if health_after_tick < 0 then + world:remove(e, ct.Health) + continue + end + world:set(e, ct.Health, health_after_tick) + end +end diff --git a/demo/src/ServerScriptService/systems/replication.luau b/demo/src/ServerScriptService/systems/replication.luau index fa9f27b..d18b6de 100644 --- a/demo/src/ServerScriptService/systems/replication.luau +++ b/demo/src/ServerScriptService/systems/replication.luau @@ -1,122 +1,190 @@ -local ReplicatedStorage = game:GetService("ReplicatedStorage") -local types = require("../../ReplicatedStorage/types") -local ct = require("../../ReplicatedStorage/components") -local jecs = require(ReplicatedStorage.ecs) -local remotes = require("../../ReplicatedStorage/remotes") - -return function(world: types.World) - local storages = {} - - for component in world:query(ct.Networked) do - local is_tag = jecs.is_tag(world, component) - local storage = {} :: { [types.Entity]: any } - storages[component] = storage - - if is_tag then - world:added(component, function(entity) - storage[entity] = true - end) - else - world:added(component, function(entity, _, value) - storage[entity] = value - end) - world:changed(component, function(entity, _, value) - storage[entity] = value - end) - end - - world:removed(component, function(entity) - storage[entity] = "jecs.Remove" - end) - end - - for relation in world:query(ct.NetworkedPair) do - world:added(relation, function(entity, id, value) - local is_tag = jecs.is_tag(world, id) - local storage = storages[id] - if not storage then - storage = {} - storages[id] = storage - end - if is_tag then - storage[entity] = true - else - storage[entity] = value - end - end) - - world:changed(relation, function(entity, id, value) - local is_tag = jecs.is_tag(world, id) - if is_tag then - return - end - - local storage = storages[id] - if not storage then - storage = {} - storages[id] = storage - end - - storage[entity] = value - end :: (types.Entity, types.Id, T) -> ()) - - world:removed(relation, function(entity, id) - local storage = storages[id] - if not storage then - storage = {} - storages[id] = storage - end - - storage[entity] = "jecs.Remove" - end) - end - - return function() - local snapshot = {} :: { - [string]: { - set: { types.Entity }?, - values: { any }?, - removed: { types.Entity }? - } - } - - local set_ids = {} :: { types.Entity } - local removed_ids = {} :: { types.Entity } - - for component, storage in storages do - local set_values = {} - local set_n = 0 - local removed_n = 0 - for e, v in storage do - if v ~= "jecs.Remove" then - set_n += 1 - set_ids[set_n] = e - set_values[set_n] = v or true - elseif world:contains(e) then - removed_n += 1 - removed_ids[removed_n] = e - end - end - - table.clear(storage) - - local dirty = false - - if set_n > 0 or removed_n > 0 then - dirty = true - end - - if dirty then - snapshot[tostring(component)] = { - set = if set_n > 0 then table.move(set_ids, 1, set_n, 1, {}) else nil, - values = if set_n > 0 then set_values else nil, - removed = if removed_n > 0 then table.move(removed_ids, 1, removed_n, 1, {} :: { types.Entity }) else nil - } :: any - end - end - - if next(snapshot) ~= nil then - remotes.replication:FireAllClients(snapshot) - end - end -end +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local types = require("../../ReplicatedStorage/types") +local ct = require("../../ReplicatedStorage/components") +local jecs = require(ReplicatedStorage.ecs) +local remotes = require("../../ReplicatedStorage/remotes") +local components = ct :: {[string]: jecs.Entity } + +return function(world: ty.World) + + --- integration test + + -- for _ = 1, 10 do + -- local e = world:entity() + -- world:set(e, ct.TestA, true) + -- end + + local storages = {} :: { [jecs.Entity]: {[jecs.Entity]: any }} + local networked_components = {} + local networked_pairs = {} + + for component in world:each(ct.Networked) do + local name = world:get(component, jecs.Name) :: string + if components[name] == nil then + continue + end + + storages[component] = {} + + table.insert(networked_components, component) + end + + for relation in world:each(ct.NetworkedPair) do + local name = world:get(relation, jecs.Name) :: string + if not components[name] then + continue + end + table.insert(networked_pairs, relation) + end + + for _, component in networked_components do + local name = world:get(component, jecs.Name) :: string + if not components[name] then + error(`Networked Component (%id{component}%name{name})`) + end + local is_tag = jecs.is_tag(world, component) + local storage = storages[component] + if is_tag then + world:added(component, function(entity) + storage[entity] = true + end) + else + world:added(component, function(entity, _, value) + storage[entity] = value + end) + world:changed(component, function(entity, _, value) + storage[entity] = value + end) + end + + world:removed(component, function(entity) + storage[entity] = "jecs.Remove" + end) + end + + for _, relation in networked_pairs do + world:added(relation, function(entity, id, value) + local is_tag = jecs.is_tag(world, id) + local storage = storages[id] + if not storage then + storage = {} + storages[id] = storage + end + if is_tag then + storage[entity] = true + else + storage[entity] = value + end + end) + + world:changed(relation, function(entity, id, value) + local is_tag = jecs.is_tag(world, id) + if is_tag then + return + end + + local storage = storages[id] + if not storage then + storage = {} + storages[id] = storage + end + + storage[entity] = value + end) + + world:removed(relation, function(entity, id) + local storage = storages[id] + if not storage then + storage = {} + storages[id] = storage + end + + storage[entity] = "jecs.Remove" + end) + end + + local players_added = collect(Players.PlayerAdded) + + return function() + local snapshot_lazy: ty.Snapshot + local set_ids_lazy: { jecs.Entity } + + for player in players_added do + if not snapshot_lazy then + snapshot_lazy, set_ids_lazy = {}, {} + + for component, storage in storages do + local set_values = {} + local set_n = 0 + + local q = world:query(component) + local is_tag = jecs.is_tag(world, component) + for _, archetype in q:archetypes() do + local entities = archetype.entities + local entities_len = #entities + table.move(entities, 1, entities_len, set_n + 1, set_ids_lazy) + if is_tag then + set_values = table.create(entities_len, true) + else + local column = archetype.columns[archetype.records[component]] + table.move(column, 1, entities_len, set_n + 1, set_values) + end + + set_n += entities_len + end + + local set = table.move(set_ids_lazy, 1, set_n, 1, {}) + + snapshot_lazy[tostring(component)] = { + set = if set_n > 0 then set else nil, + values = if set_n > 0 then set_values else nil, + } + end + end + + remotes.replication:FireClient(player, snapshot_lazy) + end + + local snapshot = {} :: ty.Snapshot + + local set_ids = {} + local removed_ids = {} + + for component, storage in storages do + local set_values = {} :: { any } + local set_n = 0 + local removed_n = 0 + for e, v in storage do + if v ~= "jecs.Remove" then + set_n += 1 + set_ids[set_n] = e + set_values[set_n] = v or true + elseif not world:contains(e) then + removed_n += 1 + removed_ids[removed_n] = e + end + end + + table.clear(storage) + + local dirty = false + + if set_n > 0 or removed_n > 0 then + dirty = true + end + + if dirty then + local removed = table.move(removed_ids, 1, removed_n, 1, {}) :: { jecs.Entity } + local set = table.move(set_ids, 1, set_n, 1, {}) :: { jecs.Entity } + snapshot[tostring(component)] = { + set = if set_n > 0 then set else nil, + values = if set_n > 0 then set_values else nil, + removed = if removed_n > 0 then removed else nil + } + end + end + if next(snapshot) ~= nil then + remotes.replication:FireAllClients(snapshot) + end + end +end diff --git a/docs/learn/contributing/guidelines.md b/docs/learn/contributing/guidelines.md index d8dfda6..9cb71d4 100644 --- a/docs/learn/contributing/guidelines.md +++ b/docs/learn/contributing/guidelines.md @@ -1,21 +1,21 @@ -# Contribution Guidelines - -Whether you found an issue, or want to make a change to jecs, we'd love to hear back from the community on what features you want or bugs you've run into. - -There's a few different ways you can go about this. - -## Creating an Issue - -This is what you should be filing if you have a bug you want to report. - -[Click here](https://github.com/Ukendio/jecs/issues/new/choose) to file a bug report. We have a few templates ready for the most common issue types. - -Additionally, see the [Submitting Issues](../contributing/issues) page for more information. - -## Creating a Pull Request - -This is what you should be filing if you have a change you want to merge into the main project. - -[Click here](https://github.com/Ukendio/jecs/compare) to select the branch you want to merge from. - -Additionally, see the [Submitting Pull Requests](../contributing/pull-requests) page for more information. +# Contribution Guidelines + +Whether you found an issue, or want to make a change to jecs, we'd love to hear back from the community on what features you want or bugs you've run into. + +There's a few different ways you can go about this. + +## Creating an Issue + +This is what you should be filing if you have a bug you want to report. + +[Click here](https://github.com/Ukendio/jecs/issues/new/choose) to file a bug report. We have a few templates ready for the most common issue types. + +Additionally, see the [Submitting Issues](../contributing/issues) page for more information. + +## Creating a Pull Request + +This is what you should be filing if you have a change you want to merge into the main project. + +[Click here](https://github.com/Ukendio/jecs/compare) to select the branch you want to merge from. + +Additionally, see the [Submitting Pull Requests](../contributing/pull-requests) page for more information. diff --git a/docs/learn/contributing/issues.md b/docs/learn/contributing/issues.md index 58a9543..982273a 100644 --- a/docs/learn/contributing/issues.md +++ b/docs/learn/contributing/issues.md @@ -1,24 +1,24 @@ -# Submitting Issues - -When you're submitting an issue, generally they fall into a few categories: - -## Bug - -We need some information to figure out what's going wrong. At a minimum, you need to tell us: - - (1) What's supposed to happen - - (2) What actually happened - - (3) Steps to reproduce - - -Stack traces and other useful information that you find make a bug report more likely to be fixed. - -Consult the template for a bug report if you don't know or have questions about how to format this. - -## Documentation - -Depending on how you go about it, this can be done as a [Pull Request](../contributing/pull-requests) instead of an issue. Generally, we need to know what was wrong, what you changed, and how it improved the documentation if it isn't obvious. - -We just need to know what's wrong. You should fill out a [PR](../contributing/pull-requests) if you know what should be there instead. +# Submitting Issues + +When you're submitting an issue, generally they fall into a few categories: + +## Bug + +We need some information to figure out what's going wrong. At a minimum, you need to tell us: + + (1) What's supposed to happen + + (2) What actually happened + + (3) Steps to reproduce + + +Stack traces and other useful information that you find make a bug report more likely to be fixed. + +Consult the template for a bug report if you don't know or have questions about how to format this. + +## Documentation + +Depending on how you go about it, this can be done as a [Pull Request](../contributing/pull-requests) instead of an issue. Generally, we need to know what was wrong, what you changed, and how it improved the documentation if it isn't obvious. + +We just need to know what's wrong. You should fill out a [PR](../contributing/pull-requests) if you know what should be there instead. diff --git a/docs/learn/contributing/pull-requests.md b/docs/learn/contributing/pull-requests.md index 0f15a46..ea57692 100644 --- a/docs/learn/contributing/pull-requests.md +++ b/docs/learn/contributing/pull-requests.md @@ -1,77 +1,77 @@ -# Submitting Pull Requests - -When submitting a Pull Request, there's a few reasons to do so: - - -## Documentation - -If there's something to change with the documentation, you should follow a similar format to this example: - -An example of an appropriate typo-fixing PR would be: - ->**Brief Description of your Changes** -> ->I fixed a couple of typos found in the /contributing/issues.md file. -> ->**Impact of your Changes** -> ->- Documentation is more clear and readable for the users. -> ->**Tests Performed** -> ->Ran `vitepress dev docs` and verified it was built successfully. -> ->**Additional Comments** -> ->[At Discretion] - -## Change in Behavior - -An example of an appropriate PR that adds a new feature would be: - -> ->**Brief Description of your Changes** -> ->I added `jecs.best_function`, which gives everyone who uses the module an immediate boost in concurrent player counts. (this is a joke) -> ->**Impact of your Changes** -> ->- jecs functionality is extended to better fit the needs of the community [explain why]. -> ->**Tests Performed** -> ->Added a few test cases to ensure the function runs as expected [link to changes]. -> ->**Additional Comments** -> ->[At Discretion] - -## Addons - -If you made something you think should be included into the [resources page](../../resources), let us know! - -We have tons of examples of libraries and other tools which can be used in conjunction with jecs on this page. - -One example of a PR that would be accepted is: - ->**Brief Description of your Changes** -> ->I added `jecs observers` to the addons page. -> ->**Impact of your Changes** -> ->- jecs observers are a different and important way of handling queries which benefit the users of jecs by [explain why your tool benefits users here] -> ->- [talk about why you went with this design instead of maybe an alternative] -> ->**Tests Performed** -> -> I used this tool in conjunction with jecs and ensured it works as expected. -> -> [If you wrote unit tests for your tool, mention it here.] -> ->**Additional Comments** -> ->[At Discretion] - -Keep in mind the list on the addons page is *not* exhaustive. If you came up with a tool that doesn't fit into any of the categories listed, we still want to hear from you! +# Submitting Pull Requests + +When submitting a Pull Request, there's a few reasons to do so: + + +## Documentation + +If there's something to change with the documentation, you should follow a similar format to this example: + +An example of an appropriate typo-fixing PR would be: + +>**Brief Description of your Changes** +> +>I fixed a couple of typos found in the /contributing/issues.md file. +> +>**Impact of your Changes** +> +>- Documentation is more clear and readable for the users. +> +>**Tests Performed** +> +>Ran `vitepress dev docs` and verified it was built successfully. +> +>**Additional Comments** +> +>[At Discretion] + +## Change in Behavior + +An example of an appropriate PR that adds a new feature would be: + +> +>**Brief Description of your Changes** +> +>I added `jecs.best_function`, which gives everyone who uses the module an immediate boost in concurrent player counts. (this is a joke) +> +>**Impact of your Changes** +> +>- jecs functionality is extended to better fit the needs of the community [explain why]. +> +>**Tests Performed** +> +>Added a few test cases to ensure the function runs as expected [link to changes]. +> +>**Additional Comments** +> +>[At Discretion] + +## Addons + +If you made something you think should be included into the [resources page](../../resources), let us know! + +We have tons of examples of libraries and other tools which can be used in conjunction with jecs on this page. + +One example of a PR that would be accepted is: + +>**Brief Description of your Changes** +> +>I added `jecs observers` to the addons page. +> +>**Impact of your Changes** +> +>- jecs observers are a different and important way of handling queries which benefit the users of jecs by [explain why your tool benefits users here] +> +>- [talk about why you went with this design instead of maybe an alternative] +> +>**Tests Performed** +> +> I used this tool in conjunction with jecs and ensured it works as expected. +> +> [If you wrote unit tests for your tool, mention it here.] +> +>**Additional Comments** +> +>[At Discretion] + +Keep in mind the list on the addons page is *not* exhaustive. If you came up with a tool that doesn't fit into any of the categories listed, we still want to hear from you! diff --git a/docs/learn/overview.md b/docs/learn/overview.md index 9047a01..bed6945 100644 --- a/docs/learn/overview.md +++ b/docs/learn/overview.md @@ -1,680 +1,680 @@ -# Introduction -Jecs is a standalone entity-component-system module written in Luau. -ECS ("entity-component-system") describes one way to write games in a more data oriented design. - -## Hello World, Entity and Component -It all has to start somewhere. A world stores entities and their components, and manages them. This tour will reference it for every operation. -:::code-group -```luau [luau] -local jecs = require(path/to/jecs) -local world = jecs.world() -``` -```typescript [typescript] -import { World } from "@rbxts/jecs" -const world = new World() -// creates a new entity with no components and returns its identifier -const entity = world.entity() - -// deletes an entity and all its components -world.delete(entity) -``` -::: - -## Entities - -Entities represent things in a game. In a game there may be entities of characters, buildings, projectiles, particle effects etc. - -By itself, an entity is just an unique entity identifier without any data. An entity identifier contains information about the entity itself and its generation. - -:::code-group -```luau [luau] --- creates a new entity with no components and returns its identifier -local entity = world:entity() - --- deletes an entity and all its components -world:delete(entity) -``` -```typescript [typescript] -// creates a new entity with no components and returns its identifier -const entity = world.entity() - -// deletes an entity and all its components -world.delete(entity) -``` -::: - -The `entity` member function also accepts an overload that allows you to create an entity with a desired id which bypasses the [`entity range`](#Entity-Ranges). - -## Components - -A component is something that is added to an entity. Components can simply tag an entity ("this entity is an `Npc`"), attach data to an entity ("this entity is at `Position` `Vector3.new(10, 20, 30)`") and create relationships between entities ("bob `Likes` alice") that may also contain data ("bob `Eats` `10` apples"). - -## Operations - -| Operation | Description | -| --------- | ---------------------------------------------------------------------------------------------- | -| `get` | Get a specific component or set of components from an entity. | -| `add` | Adds component to an entity. If entity already has the component, `add` does nothing. | -| `set` | Sets the value of a component for an entity. `set` behaves as a combination of `add` and `get` | -| `remove` | Removes component from entity. If entity doesn't have the component, `remove` does nothing. | -| `clear` | Remove all components from an entity. Clearing is more efficient than removing one by one. | - -## Components are entities - -In an ECS, components need to be uniquely identified. In Jecs this is done by making each component its own unique entity. This means that everything is customizable. Components are no exception -and all of the APIs that apply to regular entities also apply to component entities. - -If a game has a component Position and Velocity, there will be two entities, one for each component. Component entities can be distinguished from "regular" entities as they have a `Component` component trait. - -::: code-group -```luau [luau] -local Position = world:component() :: jecs.Entity -world:set(Position, jecs.Name, "Position") -- Using regular apis to set metadata on component entities! - -print(`{world:get(Position, jecs.Name)} is a Component: {world:has(Position, jecs.Component)}`); - --- Output: --- Position is a Component: true -``` -```typescript [typescript] -const Position = world.component(); -world.set(Position, jecs.Name, "Position") // Using regular apis to set metadata on component entities! - -print(`${world.get(Position, jecs.Name)} is a Component: ${world.has(Position, jecs.Component)}`); -// Output: -// Position is a Component: true -``` -::: - -### Entity ranges -Jecs reserves entity ids under a threshold (HI_COMPONENT_ID, default is 256) for components. That means that regular entities will start after this number. This number can be further specified via the `range` member function. - -::: code-group -```luau [luau] -world:range(1000, 5000) -- Defines the lower and upper bounds of the entity range respectively - -local e = world:entity() -print(e) --- Output: --- 1000 -``` -```typescript [typescript] -world.range(1000, 5000) // Defines the lower and upper bounds of the entity range respectively - -const e = world.entity() -print(e) -// Output: -// 1000 -``` -::: - -### Hooks - -Component data generally need to adhere to a specific interface, and sometimes requires side effects to run upon certain lifetime cycles. In `jecs`, there are hooks which are `component traits`, that can define the behaviour of a component and enforce invariants, but can only be invoked through mutations on the component data. You can only configure a single `OnAdd`, `OnRemove` and `OnChange` hook per component, just like you can only have a single constructor and destructor. - -::: code-group -```luau [luau] -local Transform = world:component() -world:set(Transform, OnAdd, function(entity) - -- A transform component has been added to an entity -end) -world:set(Transform, OnRemove, function(entity) - -- A transform component has been removed from the entity -end) -world:set(Transform, OnChange, function(entity, value) - -- A transform component has been changed to value on the entity -end) -``` -```typescript [typescript] -const Transform = world.component(); -world.set(Transform, OnAdd, (entity) => { - // A transform component has been added to an entity -}); -world.set(Transform, OnRemove, (entity) => { - // A transform component has been removed from the entity -}); -world.set(Transform, OnChange, (entity, value) => { - // A transform component has been changed to value on the entity -}); -``` -::: - -### Cleanup Traits - -When entities that are used as tags, components, relationships or relationship targets are deleted, cleanup traits ensure that the store does not contain any dangling references. Any cleanup policy provides this guarantee, so while they are configurable, games cannot configure traits that allows for dangling references. - -We also want to specify this per relationship. If an entity has `(Likes, parent)` we may not want to delete that entity, meaning the cleanup we want to perform for `Likes` and `ChildOf` may not be the same. - -This is what cleanup traits are for: to specify which action needs to be executed under which condition. They are applied to entities that have a reference to the entity being deleted: if I delete the `Archer` tag I remove the tag from all entities that have it. - -To configure a cleanup policy for an entity, a `(Condition, Action)` pair can be added to it. If no policy is specified, the default cleanup action (`Remove`) is performed. - -There are two cleanup actions: - -- `Remove`: removes instances of the specified (component) id from all entities (default) -- `Delete`: deletes all entities with specified id - -There are two cleanup conditions: - -- `OnDelete`: the component, tag or relationship is deleted -- `OnDeleteTarget`: a target used with the relationship is deleted - -#### (OnDelete, Remove) -::: code-group -```luau [luau] -local Archer = world:component() -world:add(Archer, pair(jecs.OnDelete, jecs.Remove)) - -local e = world:entity() -world:add(e, Archer) - --- This will remove Archer from e -world:delete(Archer) -``` -```typescript [typescript] -const Archer = world.component(); -world.add(Archer, pair(jecs.OnDelete, jecs.Remove)); - -const e = world.entity(); -world.add(e, Archer); - -// This will remove Archer from e -world.delete(Archer); -``` -::: - -#### (OnDelete, Delete) -::: code-group -```luau [luau] -local Archer = world:component() -world:add(Archer, pair(jecs.OnDelete, jecs.Delete)) - -local e = world:entity() -world:add(e, Archer) - --- This will delete entity e because the Archer component has a (OnDelete, Delete) cleanup trait -world:delete(Archer) -``` -```typescript [typescript] -const Archer = world.component(); -world.add(Archer, pair(jecs.OnDelete, jecs.Delete)); - -const e = world.entity(); -world.add(e, Archer); - -// This will delete entity e because the Archer component has a (OnDelete, Delete) cleanup trait -world.delete(Archer); -``` -::: - -#### (OnDeleteTarget, Remove) -::: code-group -```luau [luau] -local OwnedBy = world:component() -world:add(OwnedBy, pair(jecs.OnDeleteTarget, jecs.Remove)) -local loot = world:entity() -local player = world:entity() -world:add(loot, pair(OwnedBy, player)) - --- This will remove (OwnedBy, player) from loot -world:delete(player) -``` -```typescript [typescript] -const OwnedBy = world.component(); -world.add(OwnedBy, pair(jecs.OnDeleteTarget, jecs.Remove)); -const loot = world.entity(); -const player = world.entity(); -world.add(loot, pair(OwnedBy, player)); - -// This will remove (OwnedBy, player) from loot -world.delete(player); -``` -::: -#### (OnDeleteTarget, Delete) -::: code-group -```luau [luau] -local ChildOf = world:component() -world:add(ChildOf, pair(jecs.OnDeleteTarget, jecs.Delete)) - -local parent = world:entity() -local child = world:entity() -world:add(child, pair(ChildOf, parent)) - --- This will delete both parent and child -world:delete(parent) -``` -```typescript [typescript] -const ChildOf = world.component(); -world.add(ChildOf, pair(jecs.OnDeleteTarget, jecs.Delete)); - -const parent = world.entity(); -const child = world.entity(); -world.add(child, pair(ChildOf, parent)); - -// This will delete both parent and child -world.delete(parent); -``` -::: - -## Preregistration - -By default, components being registered on runtime is useful for how dynamic it can be. But, sometimes being able to register components without having the world instance is useful. - -::: code-group -```luau [luau] -local Position = jecs.component() :: jecs.Entity - -jecs.world() -- Position gets registered here -``` - -```typescript [typescript] -const Position = jecs.component(); - -new World() // Position gets registered here -``` -::: - -However, if you try to set metadata, you will find that this doesn't work without the world instance. Instead, jecs offers a `meta` member function that can forward declare its metadata. - -::: code-group -```luau [luau] -jecs.meta(Position, jecs.Name, "Position") - -jecs.world() -- Position gets registered here with its name "Position" -``` - -```typescript [typescript] -jecs.meta(Position, jecs.Name, "Position") - -new World() // Position gets registered here with its name "Position" -``` -::: - -### Singletons - -Singletons are components for which only a single instance -exists on the world. They can be accessed on the -world directly and do not require providing an entity. -Singletons are useful for global game resources, such as -game state, a handle to a physics engine or a network socket. An example: - -::: code-group -```luau [luau] -local TimeOfDay = world:component() :: jecs.Entity -world:set(TimeOfDay, TimeOfDay, 0.5) -local t = world:get(TimeOfDay, TimeOfDay) -``` - -```typescript [typescript] -const TimeOfDay = world.component(); -world.set(TimeOfDay, TimeOfDay, 0.5); -const t = world.get(TimeOfDay, TimeOfDay); -``` -::: - -# Queries - -Queries enable games to quickly find entities that satifies provided conditions. -:::code-group - -```luau [luau] -for _ in world:query(Position, Velocity) do end -``` - -```typescript [typescript] -for (const [_] of world.query(Position, Velocity)) { -} -``` -::: - -In `jecs`, queries can do anything from returning entities that match a simple list of components, to matching against entity graphs. - -This manual contains a full overview of the query features available in Jecs. Some of the features of Jecs queries are: - -- Queries have support for relationships pairs which allow for matching against entity graphs without having to build complex data structures for it. -- Queries support filters such as [`query:with(...)`](../api/query.md#with) if entities are required to have the components but you don’t actually care about components value. And [`query:without(...)`](../api/query.md#without) which selects entities without the components. -- Queries can be drained or reset on when called, which lets you choose iterator behaviour. -- Queries can be called with any ID, including entities created dynamically, this is useful for pairs. -- Queries are already fast but can be futher inlined via [`query:archetypes()`](../api/query.md#archetypes) for maximum performance to eliminate function call overhead which is roughly 60-80% of the cost for iteration. - -## Performance and Caching - -Understanding the basic architecture of queries helps to make the right tradeoffs when using queries in games. -The biggest impact on query performance is whether a query is cached or not. -This section goes over what caching is, how it can be used and when it makes sense to use it. - -### Caching: what is it? - -Jecs is an archetype ECS, which means that entities with exactly the same components are -grouped together in an "archetype". Archetypes are created on the fly -whenever a new component combination is created in the ECS. For example: - -:::code-group - -```luau [luau] -local e1 = world:entity() -world:set(e1, Position, Vector3.new(10, 20, 30)) -- create archetype [Position] -world:set(e1, Velocity, Vector3.new(1, 2, 3)) -- create archetype [Position, Velocity] - -local e2 = world:entity() -world:set(e2, Position, Vector3.new(10, 20, 30)) -- archetype [Position] already exists -world:set(e2, Velocity, Vector3.new(1, 2, 3)) -- archetype [Position, Velocity] already exists -world:set(e3, Mass, 100) -- create archetype [Position, Velocity, Mass] - --- e1 is now in archetype [Position, Velocity] --- e2 is now in archetype [Position, Velocity, Mass] -``` - -```typescript [typescript] -const e1 = world.entity(); -world.set(e1, Position, new Vector3(10, 20, 30)); // create archetype [Position] -world.set(e1, Velocity, new Vector3(1, 2, 3)); // create archetype [Position, Velocity] - -const e2 = world.entity(); -world.set(e2, Position, new Vector3(10, 20, 30)); // archetype [Position] already exists -world.set(e2, Velocity, new Vector3(1, 2, 3)); // archetype [Position, Velocity] already exists -world.set(e3, Mass, 100); // create archetype [Position, Velocity, Mass] - -// e1 is now in archetype [Position, Velocity] -// e2 is now in archetype [Position, Velocity, Mass] -``` - -::: - -Archetypes are important for queries. Since all entities in an archetype have the same components, and a query matches entities with specific components, a query can often match entire archetypes instead of individual entities. This is one of the main reasons why queries in an archetype ECS are fast. - -The second reason that queries in an archetype ECS are fast is that they are cheap to cache. While an archetype is created for each unique component combination, games typically only use a finite set of component combinations which are created quickly after game assets are loaded. - -This means that instead of searching for archetypes each time a query is evaluated, a query can instead cache the list of matching archetypes. This is a cheap cache to maintain: even though entities can move in and out of archetypes, the archetypes themselves are often stable. - -If none of that made sense, the main thing to remember is that a cached query does not actually have to search for entities. Iterating a cached query just means iterating a list of prematched results, and this is really, really fast. - -### Tradeoffs - -Jecs has both cached and uncached queries. If cached queries are so fast, why even bother with uncached queries? There are four main reasons: - -- Cached queries are really fast to iterate, but take more time to create because the cache must be initialized first. -- Cached queries add overhead to archetype creation/deletion, as these changes have to get propagated to caches. -- While caching archetypes is fast, some query features require matching individual entities, which are not efficient to cache (and aren't cached). - -As a rule of thumb, if you have a query that is evaluated each frame (as is typically the case with systems), they will benefit from being cached. If you need to create a query ad-hoc, an uncached query makes more sense. - -Ad-hoc queries are often necessary when a game needs to find entities that match a condition that is only known at runtime, for example to find all child entities for a specific parent. - -### Components - -A component is any single ID that can be added to an entity. This includes tags and regular entities, which are IDs that do not have the builtin `Component` component. To match a query, an entity must have all the requested components. An example: - -```luau -local e1 = world:entity() -world:add(e1, Position) - -local e2 = world:entity() -world:add(e2, Position) -world:add(e2, Velocity) - -local e3 = world:entity() -world:add(e3, Position) -world:add(e3, Velocity) -world:add(e3, Mass) - -``` - -Only entities `e2` and `e3` match the query Position, Velocity. - -### Wildcards - -Jecs currently only supports the `Any` type of wildcards which a single result for the first component that it matches. - -When using the `Any` type wildcard it is undefined which component will be matched, as this can be influenced by other parts of the query. It is guaranteed that iterating the same query twice on the same dataset will produce the same result. - -If you want to iterate multiple targets for the same relation on a pair, then use [`world:target`](../api/world.md#target) - -Wildcards are particularly useful when used in combination with pairs (next section). - -### Pairs - -A pair is an ID that encodes two elements. Pairs, like components, can be added to entities and are the foundation for [`Relationships`](#relationships). - -The elements of a pair are allowed to be wildcards. When a query pair returns an `Any` type wildcard, the query returns at most a single matching pair on an entity. - -The following sections describe how to create queries for pairs in the different language bindings. - -:::code-group - -```luau [luau] -local Likes = world:entity() -local bob = world:entity() -for _ in world:query(pair(Likes, bob)) do end -``` - -```typescript [typescript] -const Likes = world.entity(); -const bob = world.entity(); -for (const [_] of world.query(pair(Likes, bob))) { -} -``` - -::: - -When a query pair contains a wildcard, the `world:target()` function can be used to determine the target of the pair element that matched the query: - -:::code-group - -```luau [luau] -for id in world:query(pair(Likes, jecs.Wildcard)) do - print(`entity {getName(id)} likes {getName(world, world:target(id, Likes))}`) -end -``` - -```typescript [typescript] -const Likes = world.entity(); -const bob = world.entity(); -for (const [_] of world.query(pair(Likes, jecs.Wildcard))) { - print(`entity ${getName(id)} likes ${getName(world.target(id, Likes))}`); -} -``` - -::: - -### Filters - -Filters are extensions to queries which allow you to select entities from a more complex pattern but you don't actually care about the component values. - -The following filters are supported by queries: - -| Identifier | Description | -| ---------- | ----------------------------------- | -| With | Must match with all terms. | -| Without | Must not match with provided terms. | - -## Relationships -Relationships makes it possible to describe entity graphs natively in ECS. - -Adding/removing relationships is similar to adding/removing regular components, with as difference that instead of a single component id, a relationship adds a pair of two things to an entity. In this pair, the first element represents the relationship (e.g. "Eats"), and the second element represents the relationship target (e.g. "Apples"). - -Relationships can be used to describe many things, from hierarchies to inventory systems to trade relationships between players in a game. The following sections go over how to use relationships, and what features they support. - -### Definitions - -Name | Description -----------|------------ -Id | An id that can be added and removed -Component | Id with a single element (same as an entity id) -Relationship | Used to refer to first element of a pair -Target | Used to refer to second element of a pair -Source | Entity to which an id is added - -### Relationship queries -There are a number of ways a game can query for relationships. The following kinds of queries are available for all (unidirectional) relationships, and are all constant time: - -Test if entity has a relationship pair - -:::code-group -```luau [luau] -world:has(bob, pair(Eats, Apples)) -``` -```typescript [typescript] -world.has(bob, pair(Eats, Apples)) -``` -::: - -Test if entity has a relationship wildcard - -:::code-group -```luau [luau] -world:has(bob, pair(Eats, jecs.Wildcard) -``` -```typescript [typescript] -world.has(bob, pair(Eats, jecs.Wildcard) -``` -::: - -Get parent for entity - -:::code-group -```luau [luau] -world:parent(bob) -``` -```typescript [typescript] -world.parent(bob) -``` -::: - -Find first target of a relationship for entity - -:::code-group -```luau [luau] -world:target(bob, Eats) -``` -```typescript [typescript] -world.target(bob, Eats) -``` -::: - -Find all entities with a pair - -:::code-group -```luau [luau] -for id in world:query(pair(Eats, Apples)) do - -- ... -end -``` -```typescript [typescript] -for (const [id] of world.query(pair(Eats, Apples)) { - // ... -} -``` -::: - -Find all entities with a pair wildcard - -:::code-group -```luau [luau] -for id in world:query(pair(Eats, jecs.Wildcard)) do - local food = world:target(id, Eats) -- Apples, ... -end -``` -```typescript [typescript] -for (const [id] of world.query(pair(Eats, jecs.Wildcard)) { - const food = world.target(id, Eats) // Apples, ... -} -``` -::: - -Iterate all children for a parent - -:::code-group -```luau [luau] -for child in world:query(pair(jecs.ChildOf, parent)) do - -- ... -end -``` -```typescript [typescript] -for (const [child] of world.query(pair(jecs.ChildOf, parent)) { - // ... -} -``` -::: - -### Relationship components - -Relationship pairs, just like regular component, can be associated with data. - -:::code-group -```luau [luau] -local Position = world:component() -local Eats = world:component() -local Apples = world:entity() -local Begin = world:entity() -local End = world:entity() - -local e = world:entity() -world:set(e, pair(Eats, Apples), { amount = 1 }) - -world:set(e, pair(Begin, Position), Vector3.new(0, 0, 0)) -world:set(e, pair(End, Position), Vector3.new(10, 20, 30)) - -world:add(e, jecs.ChildOf, Position) - -``` -```typescript [typescript] -const Position = world.component() -const Eats = world.component() -const Apples = world.entity() -const Begin = world.entity() -const End = world.entity() - -const e = world.entity() -world.set(e, pair(Eats, Apples), { amount: 1 }) - -world.set(e, pair(Begin, Position), new Vector3(0, 0, 0)) -world.set(e, pair(End, Position), new Vector3(10, 20, 30)) - -world.add(e, jecs.ChildOf, Position) -``` -::: - -### Relationship wildcards - -When querying for relationship pairs, it is often useful to be able to find all instances for a given relationship or target. To accomplish this, an game can use wildcard expressions. - -Wildcards may used for the relationship or target part of a pair - -```luau -pair(Likes, jecs.Wildcard) -- Matches all Likes relationships -pair(jecs.Wildcard, Alice) -- Matches all relationships with Alice as target -``` - -### Relationship performance -The ECS storage needs to know two things in order to store components for entities: -- Which IDs are associated with an entity -- Which types are associated with those ids -Ids represent anything that can be added to an entity. An ID that is not associated with a type is called a tag. An ID associated with a type is a component. For regular components, the ID is a regular entity that has the builtin `Component` component. - -### Storing relationships -Relationships do not fundamentally change or extend the capabilities of the storage. Relationship pairs are two elements encoded into a single 53-bit ID, which means that on the storage level they are treated the same way as regular component IDs. What changes is the function that determines which type is associated with an id. For regular components this is simply a check on whether an entity has `Component`. To support relationships, new rules are added to determine the type of an id. - -Because of this, adding/removing relationships to entities has the same performance as adding/removing regular components. This becomes more obvious when looking more closely at a function that adds a relationship pair. - -### Fragmentation -Fragmentation is a property of archetype-based ECS implementations where entities are spread out over more archetypes as the number of different component combinations increases. The overhead of fragmentation is visible in two areas: -- Archetype creation -- Queries (queries have to match & iterate more archetypes) -Games that make extensive use of relationships might observe high levels of fragmentation, as relationships can introduce many different combinations of components. While the Jecs storage is optimized for supporting large amounts (hundreds of thousands) of archetypes, fragmentation is a factor to consider when using relationships. - -Union relationships are planned along with other improvements to decrease the overhead of fragmentation introduced by relationships. - -### Archetype Creation - -When an ID added to an entity is deleted, all references to that ID are deleted from the storage. For example, when the component Position is deleted it is removed from all entities, and all archetypes with the Position component are deleted. While not unique to relationships, it is more common for relationships to trigger cleanup actions, as relationship pairs contain regular entities. - -The opposite is also true. Because relationship pairs can contain regular entities which can be created on the fly, archetype creation is more common than in games that do not use relationships. While Jecs is optimized for fast archetypes creation, creating and cleaning up archetypes is inherently more expensive than creating/deleting an entity. Therefore archetypes creation is a factor to consider, especially for games that make extensive use of relationships. - -### Indexing - -To improve the speed of evaluating queries, Jecs has indices that store all archetypes for a given component ID. Whenever a new archetype is created, it is registered with the indices for the IDs the archetype has, including IDs for relationship pairs. - -While registering an archetype for a relationship index is not more expensive than registering an archetype for a regular index, an archetype with relationships has to also register itself with the appropriate wildcard indices for its relationships. For example, an archetype with relationship `pair(Likes, Apples)` registers itself with the `pair(Likes, Apples)`, `pair(Likes, jecs.Wildcard)` and `pair(jecs.Wildcard, Apples)` indices. For this reason, creating new archetypes with relationships has a higher overhead than an archetype without relationships. - -This page takes wording and terminology directly from Flecs, the first ECS with full support for [Entity Relationships](https://www.flecs.dev/flecs/md_docs_2Relationships.html). +# Introduction +Jecs is a standalone entity-component-system module written in Luau. +ECS ("entity-component-system") describes one way to write games in a more data oriented design. + +## Hello World, Entity and Component +It all has to start somewhere. A world stores entities and their components, and manages them. This tour will reference it for every operation. +:::code-group +```luau [luau] +local jecs = require(path/to/jecs) +local world = jecs.world() +``` +```typescript [typescript] +import { World } from "@rbxts/jecs" +const world = new World() +// creates a new entity with no components and returns its identifier +const entity = world.entity() + +// deletes an entity and all its components +world.delete(entity) +``` +::: + +## Entities + +Entities represent things in a game. In a game there may be entities of characters, buildings, projectiles, particle effects etc. + +By itself, an entity is just an unique entity identifier without any data. An entity identifier contains information about the entity itself and its generation. + +:::code-group +```luau [luau] +-- creates a new entity with no components and returns its identifier +local entity = world:entity() + +-- deletes an entity and all its components +world:delete(entity) +``` +```typescript [typescript] +// creates a new entity with no components and returns its identifier +const entity = world.entity() + +// deletes an entity and all its components +world.delete(entity) +``` +::: + +The `entity` member function also accepts an overload that allows you to create an entity with a desired id which bypasses the [`entity range`](#Entity-Ranges). + +## Components + +A component is something that is added to an entity. Components can simply tag an entity ("this entity is an `Npc`"), attach data to an entity ("this entity is at `Position` `Vector3.new(10, 20, 30)`") and create relationships between entities ("bob `Likes` alice") that may also contain data ("bob `Eats` `10` apples"). + +## Operations + +| Operation | Description | +| --------- | ---------------------------------------------------------------------------------------------- | +| `get` | Get a specific component or set of components from an entity. | +| `add` | Adds component to an entity. If entity already has the component, `add` does nothing. | +| `set` | Sets the value of a component for an entity. `set` behaves as a combination of `add` and `get` | +| `remove` | Removes component from entity. If entity doesn't have the component, `remove` does nothing. | +| `clear` | Remove all components from an entity. Clearing is more efficient than removing one by one. | + +## Components are entities + +In an ECS, components need to be uniquely identified. In Jecs this is done by making each component its own unique entity. This means that everything is customizable. Components are no exception +and all of the APIs that apply to regular entities also apply to component entities. + +If a game has a component Position and Velocity, there will be two entities, one for each component. Component entities can be distinguished from "regular" entities as they have a `Component` component trait. + +::: code-group +```luau [luau] +local Position = world:component() :: jecs.Entity +world:set(Position, jecs.Name, "Position") -- Using regular apis to set metadata on component entities! + +print(`{world:get(Position, jecs.Name)} is a Component: {world:has(Position, jecs.Component)}`); + +-- Output: +-- Position is a Component: true +``` +```typescript [typescript] +const Position = world.component(); +world.set(Position, jecs.Name, "Position") // Using regular apis to set metadata on component entities! + +print(`${world.get(Position, jecs.Name)} is a Component: ${world.has(Position, jecs.Component)}`); +// Output: +// Position is a Component: true +``` +::: + +### Entity ranges +Jecs reserves entity ids under a threshold (HI_COMPONENT_ID, default is 256) for components. That means that regular entities will start after this number. This number can be further specified via the `range` member function. + +::: code-group +```luau [luau] +world:range(1000, 5000) -- Defines the lower and upper bounds of the entity range respectively + +local e = world:entity() +print(e) +-- Output: +-- 1000 +``` +```typescript [typescript] +world.range(1000, 5000) // Defines the lower and upper bounds of the entity range respectively + +const e = world.entity() +print(e) +// Output: +// 1000 +``` +::: + +### Hooks + +Component data generally need to adhere to a specific interface, and sometimes requires side effects to run upon certain lifetime cycles. In `jecs`, there are hooks which are `component traits`, that can define the behaviour of a component and enforce invariants, but can only be invoked through mutations on the component data. You can only configure a single `OnAdd`, `OnRemove` and `OnChange` hook per component, just like you can only have a single constructor and destructor. + +::: code-group +```luau [luau] +local Transform = world:component() +world:set(Transform, OnAdd, function(entity) + -- A transform component has been added to an entity +end) +world:set(Transform, OnRemove, function(entity) + -- A transform component has been removed from the entity +end) +world:set(Transform, OnChange, function(entity, value) + -- A transform component has been changed to value on the entity +end) +``` +```typescript [typescript] +const Transform = world.component(); +world.set(Transform, OnAdd, (entity) => { + // A transform component has been added to an entity +}); +world.set(Transform, OnRemove, (entity) => { + // A transform component has been removed from the entity +}); +world.set(Transform, OnChange, (entity, value) => { + // A transform component has been changed to value on the entity +}); +``` +::: + +### Cleanup Traits + +When entities that are used as tags, components, relationships or relationship targets are deleted, cleanup traits ensure that the store does not contain any dangling references. Any cleanup policy provides this guarantee, so while they are configurable, games cannot configure traits that allows for dangling references. + +We also want to specify this per relationship. If an entity has `(Likes, parent)` we may not want to delete that entity, meaning the cleanup we want to perform for `Likes` and `ChildOf` may not be the same. + +This is what cleanup traits are for: to specify which action needs to be executed under which condition. They are applied to entities that have a reference to the entity being deleted: if I delete the `Archer` tag I remove the tag from all entities that have it. + +To configure a cleanup policy for an entity, a `(Condition, Action)` pair can be added to it. If no policy is specified, the default cleanup action (`Remove`) is performed. + +There are two cleanup actions: + +- `Remove`: removes instances of the specified (component) id from all entities (default) +- `Delete`: deletes all entities with specified id + +There are two cleanup conditions: + +- `OnDelete`: the component, tag or relationship is deleted +- `OnDeleteTarget`: a target used with the relationship is deleted + +#### (OnDelete, Remove) +::: code-group +```luau [luau] +local Archer = world:component() +world:add(Archer, pair(jecs.OnDelete, jecs.Remove)) + +local e = world:entity() +world:add(e, Archer) + +-- This will remove Archer from e +world:delete(Archer) +``` +```typescript [typescript] +const Archer = world.component(); +world.add(Archer, pair(jecs.OnDelete, jecs.Remove)); + +const e = world.entity(); +world.add(e, Archer); + +// This will remove Archer from e +world.delete(Archer); +``` +::: + +#### (OnDelete, Delete) +::: code-group +```luau [luau] +local Archer = world:component() +world:add(Archer, pair(jecs.OnDelete, jecs.Delete)) + +local e = world:entity() +world:add(e, Archer) + +-- This will delete entity e because the Archer component has a (OnDelete, Delete) cleanup trait +world:delete(Archer) +``` +```typescript [typescript] +const Archer = world.component(); +world.add(Archer, pair(jecs.OnDelete, jecs.Delete)); + +const e = world.entity(); +world.add(e, Archer); + +// This will delete entity e because the Archer component has a (OnDelete, Delete) cleanup trait +world.delete(Archer); +``` +::: + +#### (OnDeleteTarget, Remove) +::: code-group +```luau [luau] +local OwnedBy = world:component() +world:add(OwnedBy, pair(jecs.OnDeleteTarget, jecs.Remove)) +local loot = world:entity() +local player = world:entity() +world:add(loot, pair(OwnedBy, player)) + +-- This will remove (OwnedBy, player) from loot +world:delete(player) +``` +```typescript [typescript] +const OwnedBy = world.component(); +world.add(OwnedBy, pair(jecs.OnDeleteTarget, jecs.Remove)); +const loot = world.entity(); +const player = world.entity(); +world.add(loot, pair(OwnedBy, player)); + +// This will remove (OwnedBy, player) from loot +world.delete(player); +``` +::: +#### (OnDeleteTarget, Delete) +::: code-group +```luau [luau] +local ChildOf = world:component() +world:add(ChildOf, pair(jecs.OnDeleteTarget, jecs.Delete)) + +local parent = world:entity() +local child = world:entity() +world:add(child, pair(ChildOf, parent)) + +-- This will delete both parent and child +world:delete(parent) +``` +```typescript [typescript] +const ChildOf = world.component(); +world.add(ChildOf, pair(jecs.OnDeleteTarget, jecs.Delete)); + +const parent = world.entity(); +const child = world.entity(); +world.add(child, pair(ChildOf, parent)); + +// This will delete both parent and child +world.delete(parent); +``` +::: + +## Preregistration + +By default, components being registered on runtime is useful for how dynamic it can be. But, sometimes being able to register components without having the world instance is useful. + +::: code-group +```luau [luau] +local Position = jecs.component() :: jecs.Entity + +jecs.world() -- Position gets registered here +``` + +```typescript [typescript] +const Position = jecs.component(); + +new World() // Position gets registered here +``` +::: + +However, if you try to set metadata, you will find that this doesn't work without the world instance. Instead, jecs offers a `meta` member function that can forward declare its metadata. + +::: code-group +```luau [luau] +jecs.meta(Position, jecs.Name, "Position") + +jecs.world() -- Position gets registered here with its name "Position" +``` + +```typescript [typescript] +jecs.meta(Position, jecs.Name, "Position") + +new World() // Position gets registered here with its name "Position" +``` +::: + +### Singletons + +Singletons are components for which only a single instance +exists on the world. They can be accessed on the +world directly and do not require providing an entity. +Singletons are useful for global game resources, such as +game state, a handle to a physics engine or a network socket. An example: + +::: code-group +```luau [luau] +local TimeOfDay = world:component() :: jecs.Entity +world:set(TimeOfDay, TimeOfDay, 0.5) +local t = world:get(TimeOfDay, TimeOfDay) +``` + +```typescript [typescript] +const TimeOfDay = world.component(); +world.set(TimeOfDay, TimeOfDay, 0.5); +const t = world.get(TimeOfDay, TimeOfDay); +``` +::: + +# Queries + +Queries enable games to quickly find entities that satifies provided conditions. +:::code-group + +```luau [luau] +for _ in world:query(Position, Velocity) do end +``` + +```typescript [typescript] +for (const [_] of world.query(Position, Velocity)) { +} +``` +::: + +In `jecs`, queries can do anything from returning entities that match a simple list of components, to matching against entity graphs. + +This manual contains a full overview of the query features available in Jecs. Some of the features of Jecs queries are: + +- Queries have support for relationships pairs which allow for matching against entity graphs without having to build complex data structures for it. +- Queries support filters such as [`query:with(...)`](../api/query.md#with) if entities are required to have the components but you don’t actually care about components value. And [`query:without(...)`](../api/query.md#without) which selects entities without the components. +- Queries can be drained or reset on when called, which lets you choose iterator behaviour. +- Queries can be called with any ID, including entities created dynamically, this is useful for pairs. +- Queries are already fast but can be futher inlined via [`query:archetypes()`](../api/query.md#archetypes) for maximum performance to eliminate function call overhead which is roughly 60-80% of the cost for iteration. + +## Performance and Caching + +Understanding the basic architecture of queries helps to make the right tradeoffs when using queries in games. +The biggest impact on query performance is whether a query is cached or not. +This section goes over what caching is, how it can be used and when it makes sense to use it. + +### Caching: what is it? + +Jecs is an archetype ECS, which means that entities with exactly the same components are +grouped together in an "archetype". Archetypes are created on the fly +whenever a new component combination is created in the ECS. For example: + +:::code-group + +```luau [luau] +local e1 = world:entity() +world:set(e1, Position, Vector3.new(10, 20, 30)) -- create archetype [Position] +world:set(e1, Velocity, Vector3.new(1, 2, 3)) -- create archetype [Position, Velocity] + +local e2 = world:entity() +world:set(e2, Position, Vector3.new(10, 20, 30)) -- archetype [Position] already exists +world:set(e2, Velocity, Vector3.new(1, 2, 3)) -- archetype [Position, Velocity] already exists +world:set(e3, Mass, 100) -- create archetype [Position, Velocity, Mass] + +-- e1 is now in archetype [Position, Velocity] +-- e2 is now in archetype [Position, Velocity, Mass] +``` + +```typescript [typescript] +const e1 = world.entity(); +world.set(e1, Position, new Vector3(10, 20, 30)); // create archetype [Position] +world.set(e1, Velocity, new Vector3(1, 2, 3)); // create archetype [Position, Velocity] + +const e2 = world.entity(); +world.set(e2, Position, new Vector3(10, 20, 30)); // archetype [Position] already exists +world.set(e2, Velocity, new Vector3(1, 2, 3)); // archetype [Position, Velocity] already exists +world.set(e3, Mass, 100); // create archetype [Position, Velocity, Mass] + +// e1 is now in archetype [Position, Velocity] +// e2 is now in archetype [Position, Velocity, Mass] +``` + +::: + +Archetypes are important for queries. Since all entities in an archetype have the same components, and a query matches entities with specific components, a query can often match entire archetypes instead of individual entities. This is one of the main reasons why queries in an archetype ECS are fast. + +The second reason that queries in an archetype ECS are fast is that they are cheap to cache. While an archetype is created for each unique component combination, games typically only use a finite set of component combinations which are created quickly after game assets are loaded. + +This means that instead of searching for archetypes each time a query is evaluated, a query can instead cache the list of matching archetypes. This is a cheap cache to maintain: even though entities can move in and out of archetypes, the archetypes themselves are often stable. + +If none of that made sense, the main thing to remember is that a cached query does not actually have to search for entities. Iterating a cached query just means iterating a list of prematched results, and this is really, really fast. + +### Tradeoffs + +Jecs has both cached and uncached queries. If cached queries are so fast, why even bother with uncached queries? There are four main reasons: + +- Cached queries are really fast to iterate, but take more time to create because the cache must be initialized first. +- Cached queries add overhead to archetype creation/deletion, as these changes have to get propagated to caches. +- While caching archetypes is fast, some query features require matching individual entities, which are not efficient to cache (and aren't cached). + +As a rule of thumb, if you have a query that is evaluated each frame (as is typically the case with systems), they will benefit from being cached. If you need to create a query ad-hoc, an uncached query makes more sense. + +Ad-hoc queries are often necessary when a game needs to find entities that match a condition that is only known at runtime, for example to find all child entities for a specific parent. + +### Components + +A component is any single ID that can be added to an entity. This includes tags and regular entities, which are IDs that do not have the builtin `Component` component. To match a query, an entity must have all the requested components. An example: + +```luau +local e1 = world:entity() +world:add(e1, Position) + +local e2 = world:entity() +world:add(e2, Position) +world:add(e2, Velocity) + +local e3 = world:entity() +world:add(e3, Position) +world:add(e3, Velocity) +world:add(e3, Mass) + +``` + +Only entities `e2` and `e3` match the query Position, Velocity. + +### Wildcards + +Jecs currently only supports the `Any` type of wildcards which a single result for the first component that it matches. + +When using the `Any` type wildcard it is undefined which component will be matched, as this can be influenced by other parts of the query. It is guaranteed that iterating the same query twice on the same dataset will produce the same result. + +If you want to iterate multiple targets for the same relation on a pair, then use [`world:target`](../api/world.md#target) + +Wildcards are particularly useful when used in combination with pairs (next section). + +### Pairs + +A pair is an ID that encodes two elements. Pairs, like components, can be added to entities and are the foundation for [`Relationships`](#relationships). + +The elements of a pair are allowed to be wildcards. When a query pair returns an `Any` type wildcard, the query returns at most a single matching pair on an entity. + +The following sections describe how to create queries for pairs in the different language bindings. + +:::code-group + +```luau [luau] +local Likes = world:entity() +local bob = world:entity() +for _ in world:query(pair(Likes, bob)) do end +``` + +```typescript [typescript] +const Likes = world.entity(); +const bob = world.entity(); +for (const [_] of world.query(pair(Likes, bob))) { +} +``` + +::: + +When a query pair contains a wildcard, the `world:target()` function can be used to determine the target of the pair element that matched the query: + +:::code-group + +```luau [luau] +for id in world:query(pair(Likes, jecs.Wildcard)) do + print(`entity {getName(id)} likes {getName(world, world:target(id, Likes))}`) +end +``` + +```typescript [typescript] +const Likes = world.entity(); +const bob = world.entity(); +for (const [_] of world.query(pair(Likes, jecs.Wildcard))) { + print(`entity ${getName(id)} likes ${getName(world.target(id, Likes))}`); +} +``` + +::: + +### Filters + +Filters are extensions to queries which allow you to select entities from a more complex pattern but you don't actually care about the component values. + +The following filters are supported by queries: + +| Identifier | Description | +| ---------- | ----------------------------------- | +| With | Must match with all terms. | +| Without | Must not match with provided terms. | + +## Relationships +Relationships makes it possible to describe entity graphs natively in ECS. + +Adding/removing relationships is similar to adding/removing regular components, with as difference that instead of a single component id, a relationship adds a pair of two things to an entity. In this pair, the first element represents the relationship (e.g. "Eats"), and the second element represents the relationship target (e.g. "Apples"). + +Relationships can be used to describe many things, from hierarchies to inventory systems to trade relationships between players in a game. The following sections go over how to use relationships, and what features they support. + +### Definitions + +Name | Description +----------|------------ +Id | An id that can be added and removed +Component | Id with a single element (same as an entity id) +Relationship | Used to refer to first element of a pair +Target | Used to refer to second element of a pair +Source | Entity to which an id is added + +### Relationship queries +There are a number of ways a game can query for relationships. The following kinds of queries are available for all (unidirectional) relationships, and are all constant time: + +Test if entity has a relationship pair + +:::code-group +```luau [luau] +world:has(bob, pair(Eats, Apples)) +``` +```typescript [typescript] +world.has(bob, pair(Eats, Apples)) +``` +::: + +Test if entity has a relationship wildcard + +:::code-group +```luau [luau] +world:has(bob, pair(Eats, jecs.Wildcard) +``` +```typescript [typescript] +world.has(bob, pair(Eats, jecs.Wildcard) +``` +::: + +Get parent for entity + +:::code-group +```luau [luau] +world:parent(bob) +``` +```typescript [typescript] +world.parent(bob) +``` +::: + +Find first target of a relationship for entity + +:::code-group +```luau [luau] +world:target(bob, Eats) +``` +```typescript [typescript] +world.target(bob, Eats) +``` +::: + +Find all entities with a pair + +:::code-group +```luau [luau] +for id in world:query(pair(Eats, Apples)) do + -- ... +end +``` +```typescript [typescript] +for (const [id] of world.query(pair(Eats, Apples)) { + // ... +} +``` +::: + +Find all entities with a pair wildcard + +:::code-group +```luau [luau] +for id in world:query(pair(Eats, jecs.Wildcard)) do + local food = world:target(id, Eats) -- Apples, ... +end +``` +```typescript [typescript] +for (const [id] of world.query(pair(Eats, jecs.Wildcard)) { + const food = world.target(id, Eats) // Apples, ... +} +``` +::: + +Iterate all children for a parent + +:::code-group +```luau [luau] +for child in world:query(pair(jecs.ChildOf, parent)) do + -- ... +end +``` +```typescript [typescript] +for (const [child] of world.query(pair(jecs.ChildOf, parent)) { + // ... +} +``` +::: + +### Relationship components + +Relationship pairs, just like regular component, can be associated with data. + +:::code-group +```luau [luau] +local Position = world:component() +local Eats = world:component() +local Apples = world:entity() +local Begin = world:entity() +local End = world:entity() + +local e = world:entity() +world:set(e, pair(Eats, Apples), { amount = 1 }) + +world:set(e, pair(Begin, Position), Vector3.new(0, 0, 0)) +world:set(e, pair(End, Position), Vector3.new(10, 20, 30)) + +world:add(e, jecs.ChildOf, Position) + +``` +```typescript [typescript] +const Position = world.component() +const Eats = world.component() +const Apples = world.entity() +const Begin = world.entity() +const End = world.entity() + +const e = world.entity() +world.set(e, pair(Eats, Apples), { amount: 1 }) + +world.set(e, pair(Begin, Position), new Vector3(0, 0, 0)) +world.set(e, pair(End, Position), new Vector3(10, 20, 30)) + +world.add(e, jecs.ChildOf, Position) +``` +::: + +### Relationship wildcards + +When querying for relationship pairs, it is often useful to be able to find all instances for a given relationship or target. To accomplish this, an game can use wildcard expressions. + +Wildcards may used for the relationship or target part of a pair + +```luau +pair(Likes, jecs.Wildcard) -- Matches all Likes relationships +pair(jecs.Wildcard, Alice) -- Matches all relationships with Alice as target +``` + +### Relationship performance +The ECS storage needs to know two things in order to store components for entities: +- Which IDs are associated with an entity +- Which types are associated with those ids +Ids represent anything that can be added to an entity. An ID that is not associated with a type is called a tag. An ID associated with a type is a component. For regular components, the ID is a regular entity that has the builtin `Component` component. + +### Storing relationships +Relationships do not fundamentally change or extend the capabilities of the storage. Relationship pairs are two elements encoded into a single 53-bit ID, which means that on the storage level they are treated the same way as regular component IDs. What changes is the function that determines which type is associated with an id. For regular components this is simply a check on whether an entity has `Component`. To support relationships, new rules are added to determine the type of an id. + +Because of this, adding/removing relationships to entities has the same performance as adding/removing regular components. This becomes more obvious when looking more closely at a function that adds a relationship pair. + +### Fragmentation +Fragmentation is a property of archetype-based ECS implementations where entities are spread out over more archetypes as the number of different component combinations increases. The overhead of fragmentation is visible in two areas: +- Archetype creation +- Queries (queries have to match & iterate more archetypes) +Games that make extensive use of relationships might observe high levels of fragmentation, as relationships can introduce many different combinations of components. While the Jecs storage is optimized for supporting large amounts (hundreds of thousands) of archetypes, fragmentation is a factor to consider when using relationships. + +Union relationships are planned along with other improvements to decrease the overhead of fragmentation introduced by relationships. + +### Archetype Creation + +When an ID added to an entity is deleted, all references to that ID are deleted from the storage. For example, when the component Position is deleted it is removed from all entities, and all archetypes with the Position component are deleted. While not unique to relationships, it is more common for relationships to trigger cleanup actions, as relationship pairs contain regular entities. + +The opposite is also true. Because relationship pairs can contain regular entities which can be created on the fly, archetype creation is more common than in games that do not use relationships. While Jecs is optimized for fast archetypes creation, creating and cleaning up archetypes is inherently more expensive than creating/deleting an entity. Therefore archetypes creation is a factor to consider, especially for games that make extensive use of relationships. + +### Indexing + +To improve the speed of evaluating queries, Jecs has indices that store all archetypes for a given component ID. Whenever a new archetype is created, it is registered with the indices for the IDs the archetype has, including IDs for relationship pairs. + +While registering an archetype for a relationship index is not more expensive than registering an archetype for a regular index, an archetype with relationships has to also register itself with the appropriate wildcard indices for its relationships. For example, an archetype with relationship `pair(Likes, Apples)` registers itself with the `pair(Likes, Apples)`, `pair(Likes, jecs.Wildcard)` and `pair(jecs.Wildcard, Apples)` indices. For this reason, creating new archetypes with relationships has a higher overhead than an archetype without relationships. + +This page takes wording and terminology directly from Flecs, the first ECS with full support for [Entity Relationships](https://www.flecs.dev/flecs/md_docs_2Relationships.html). diff --git a/jecs.luau b/jecs.luau index 0270110..7531134 100644 --- a/jecs.luau +++ b/jecs.luau @@ -1,3 +1,4 @@ + --!optimize 2 --!native --!strict @@ -117,6 +118,7 @@ local ECS_ID_MASK = 0b00 local ECS_ENTITY_MASK = bit32.lshift(1, 24) local ECS_GENERATION_MASK = bit32.lshift(1, 16) +local ECS_PAIR_OFFSET = 2^48 local NULL_ARRAY = table.freeze({}) :: Column local NULL = newproxy(false) @@ -168,7 +170,6 @@ end local function ECS_COMBINE(id: number, generation: number): i53 return id + (generation * ECS_ENTITY_MASK) end -local ECS_PAIR_OFFSET = 2^48 local function ECS_IS_PAIR(e: number): boolean return e > ECS_PAIR_OFFSET @@ -2576,40 +2577,40 @@ export type World = { component: (self: World) -> Entity, --- Gets the target of an relationship. For example, when a user calls --- `world:target(id, ChildOf(parent), 0)`, you will obtain the parent entity. - target: (self: World, id: Entity, relation: Id, index: number?) -> Entity?, + target: (self: World, id: Entity, relation: Id, index: number?) -> Entity?, --- Deletes an entity and all it's related components and relationships. - delete: (self: World, id: Entity) -> (), + delete: (self: World, id: Entity) -> (), --- Adds a component to the entity with no value - add: (self: World, id: Entity, component: Id) -> (), + add: (self: World, id: Entity, component: Id) -> (), --- Assigns a value to a component on the given entity - set: (self: World, id: Entity, component: Id, data: T) -> (), + set: (self: World, id: Entity, component: Id, data: a) -> (), cleanup: (self: World) -> (), -- Clears an entity from the world - clear: (self: World, id: Id) -> (), + clear: (self: World, id: Id) -> (), --- Removes a component from the given entity - remove: (self: World, id: Entity, component: Id) -> (), + remove: (self: World, id: Entity, component: Id) -> (), --- Retrieves the value of up to 4 components. These values may be nil. - get: ((self: World, id: Entity, Id) -> A?) - & ((self: World, id: Entity, Id, Id) -> (A?, B?)) - & ((self: World, id: Entity, Id, Id, Id) -> (A?, B?, C?)) - & (self: World, id: Entity, Id, Id, Id, Id) -> (A?, B?, C?, D?), + get: & ((World, Entity, Id) -> a?) + & ((World, Entity, Id, Id) -> (a?, b?)) + & ((World, Entity, Id, Id, Id) -> (a?, b?, c?)) + & ((World, Entity, Id, Id, Id, Id) -> (a?, b?, c?, d?)), --- Returns whether the entity has the ID. - has: ((World, Entity, A) -> boolean) - & ((World, Entity, A, B) -> boolean) - & ((World, Entity, A, B, C) -> boolean) - & (World, Entity, A, B, C, D) -> boolean, + has: ((World, Entity, Id) -> boolean) + & ((World, Entity, Id, Id) -> boolean) + & ((World, Entity, Id, Id, Id) -> boolean) + & (World, Entity, Id, Id, Id, Id) -> boolean, --- Get parent (target of ChildOf relationship) for entity. If there is no ChildOf relationship pair, it will return nil. - parent:(self: World, entity: Entity) -> Entity, + parent: (self: World, entity: Entity) -> Entity, --- Checks if the world contains the given entity - contains:(self: World, entity: Entity) -> boolean, + contains: (self: World, entity: Entity) -> boolean, --- Checks if the entity exists - exists: (self: World, entity: Entity) -> boolean, + exists: (self: World, entity: Entity) -> boolean, each: (self: World, id: Id) -> () -> Entity, diff --git a/test/lol.luau b/test/lol.luau index 0749543..0be2c57 100644 --- a/test/lol.luau +++ b/test/lol.luau @@ -1,158 +1,158 @@ -local c = { - white_underline = function(s: any) - return `\27[1;4m{s}\27[0m` - end, - - white = function(s: any) - return `\27[37;1m{s}\27[0m` - end, - - green = function(s: any) - return `\27[32;1m{s}\27[0m` - end, - - red = function(s: any) - return `\27[31;1m{s}\27[0m` - end, - - yellow = function(s: any) - return `\27[33;1m{s}\27[0m` - end, - - red_highlight = function(s: any) - return `\27[41;1;30m{s}\27[0m` - end, - - green_highlight = function(s: any) - return `\27[42;1;30m{s}\27[0m` - end, - - gray = function(s: any) - return `\27[30;1m{s}\27[0m` - end, -} - - -local ECS_PAIR_FLAG = 0x8 -local ECS_ID_FLAGS_MASK = 0x10 -local ECS_ENTITY_MASK = bit32.lshift(1, 24) -local ECS_GENERATION_MASK = bit32.lshift(1, 16) - -type i53 = number -type i24 = number - -local function ECS_ENTITY_T_LO(e: i53): i24 - return if e > ECS_ENTITY_MASK then (e // ECS_ID_FLAGS_MASK) // ECS_ENTITY_MASK else e -end - -local function ECS_GENERATION(e: i53): i24 - return if e > ECS_ENTITY_MASK then (e // ECS_ID_FLAGS_MASK) % ECS_GENERATION_MASK else 0 -end - -local ECS_ID = ECS_ENTITY_T_LO - -local function ECS_COMBINE(source: number, target: number): i53 - return (source * 268435456) + (target * ECS_ID_FLAGS_MASK) -end - -local function ECS_GENERATION_INC(e: i53) - if e > ECS_ENTITY_MASK then - local flags = e // ECS_ID_FLAGS_MASK - local id = flags // ECS_ENTITY_MASK - local generation = flags % ECS_GENERATION_MASK - - local next_gen = generation + 1 - if next_gen > ECS_GENERATION_MASK then - return id - end - - return ECS_COMBINE(id, next_gen) + flags - end - return ECS_COMBINE(e, 1) -end - -local function bl() - print("") -end - -local function pe(e) - local gen = ECS_GENERATION(e) - return c.green(`e{ECS_ID(e)}`)..c.yellow(`v{gen}`) -end - -local function dprint(tbl: { [number]: number }) - bl() - print("--------") - for i, e in tbl do - print("| "..pe(e).." |") - print("--------") - end - bl() -end - -local max_id = 0 -local alive_count = 0 -local dense = {} -local sparse = {} -local function alloc() - if alive_count ~= #dense then - alive_count += 1 - print("*recycled", pe(dense[alive_count])) - return dense[alive_count] - end - max_id += 1 - local id = max_id - alive_count += 1 - dense[alive_count] = id - sparse[id] = { - dense = alive_count - } - print("*allocated", pe(id)) - return id -end - -local function remove(entity) - local id = ECS_ID(entity) - local r = sparse[id] - local index_of_deleted_entity = r.dense - local last_entity_alive_at_index = alive_count -- last entity alive - alive_count -= 1 - local last_alive_entity = dense[last_entity_alive_at_index] - local r_swap = sparse[ECS_ID(last_alive_entity)] - r_swap.dense = r.dense - r.dense = last_entity_alive_at_index - dense[index_of_deleted_entity] = last_alive_entity - dense[last_entity_alive_at_index] = ECS_GENERATION_INC(entity) - print("*dellocated", pe(id)) -end - -local function alive(e) - local r = sparse[ECS_ID(e)] - - return dense[r.dense] == e -end - -local function pa(e) - print(`{pe(e)} is {if alive(e) then "alive" else "not alive"}`) -end - -local tprint = require("@testkit").print -local e1v0 = alloc() -local e2v0 = alloc() -local e3v0 = alloc() -local e4v0 = alloc() -local e5v0 = alloc() -pa(e1v0) -pa(e4v0) -remove(e5v0) -pa(e5v0) - -local e5v1 = alloc() -pa(e5v0) -pa(e5v1) -pa(e2v0) -print(ECS_ID(e2v0)) - -dprint(dense) -remove(e2v0) -dprint(dense) +local c = { + white_underline = function(s: any) + return `\27[1;4m{s}\27[0m` + end, + + white = function(s: any) + return `\27[37;1m{s}\27[0m` + end, + + green = function(s: any) + return `\27[32;1m{s}\27[0m` + end, + + red = function(s: any) + return `\27[31;1m{s}\27[0m` + end, + + yellow = function(s: any) + return `\27[33;1m{s}\27[0m` + end, + + red_highlight = function(s: any) + return `\27[41;1;30m{s}\27[0m` + end, + + green_highlight = function(s: any) + return `\27[42;1;30m{s}\27[0m` + end, + + gray = function(s: any) + return `\27[30;1m{s}\27[0m` + end, +} + + +local ECS_PAIR_FLAG = 0x8 +local ECS_ID_FLAGS_MASK = 0x10 +local ECS_ENTITY_MASK = bit32.lshift(1, 24) +local ECS_GENERATION_MASK = bit32.lshift(1, 16) + +type i53 = number +type i24 = number + +local function ECS_ENTITY_T_LO(e: i53): i24 + return if e > ECS_ENTITY_MASK then (e // ECS_ID_FLAGS_MASK) // ECS_ENTITY_MASK else e +end + +local function ECS_GENERATION(e: i53): i24 + return if e > ECS_ENTITY_MASK then (e // ECS_ID_FLAGS_MASK) % ECS_GENERATION_MASK else 0 +end + +local ECS_ID = ECS_ENTITY_T_LO + +local function ECS_COMBINE(source: number, target: number): i53 + return (source * 268435456) + (target * ECS_ID_FLAGS_MASK) +end + +local function ECS_GENERATION_INC(e: i53) + if e > ECS_ENTITY_MASK then + local flags = e // ECS_ID_FLAGS_MASK + local id = flags // ECS_ENTITY_MASK + local generation = flags % ECS_GENERATION_MASK + + local next_gen = generation + 1 + if next_gen > ECS_GENERATION_MASK then + return id + end + + return ECS_COMBINE(id, next_gen) + flags + end + return ECS_COMBINE(e, 1) +end + +local function bl() + print("") +end + +local function pe(e) + local gen = ECS_GENERATION(e) + return c.green(`e{ECS_ID(e)}`)..c.yellow(`v{gen}`) +end + +local function dprint(tbl: { [number]: number }) + bl() + print("--------") + for i, e in tbl do + print("| "..pe(e).." |") + print("--------") + end + bl() +end + +local max_id = 0 +local alive_count = 0 +local dense = {} +local sparse = {} +local function alloc() + if alive_count ~= #dense then + alive_count += 1 + print("*recycled", pe(dense[alive_count])) + return dense[alive_count] + end + max_id += 1 + local id = max_id + alive_count += 1 + dense[alive_count] = id + sparse[id] = { + dense = alive_count + } + print("*allocated", pe(id)) + return id +end + +local function remove(entity) + local id = ECS_ID(entity) + local r = sparse[id] + local index_of_deleted_entity = r.dense + local last_entity_alive_at_index = alive_count -- last entity alive + alive_count -= 1 + local last_alive_entity = dense[last_entity_alive_at_index] + local r_swap = sparse[ECS_ID(last_alive_entity)] + r_swap.dense = r.dense + r.dense = last_entity_alive_at_index + dense[index_of_deleted_entity] = last_alive_entity + dense[last_entity_alive_at_index] = ECS_GENERATION_INC(entity) + print("*dellocated", pe(id)) +end + +local function alive(e) + local r = sparse[ECS_ID(e)] + + return dense[r.dense] == e +end + +local function pa(e) + print(`{pe(e)} is {if alive(e) then "alive" else "not alive"}`) +end + +local tprint = require("@testkit").print +local e1v0 = alloc() +local e2v0 = alloc() +local e3v0 = alloc() +local e4v0 = alloc() +local e5v0 = alloc() +pa(e1v0) +pa(e4v0) +remove(e5v0) +pa(e5v0) + +local e5v1 = alloc() +pa(e5v0) +pa(e5v1) +pa(e2v0) +print(ECS_ID(e2v0)) + +dprint(dense) +remove(e2v0) +dprint(dense) diff --git a/test/stress.client.luau b/test/stress.client.luau index 9bc7775..13b5e86 100644 --- a/test/stress.client.luau +++ b/test/stress.client.luau @@ -1,122 +1,122 @@ -local RunService = game:GetService("RunService") -local ReplicatedStorage = game:GetService("ReplicatedStorage") -_G.__JECS_HI_COMPONENT_ID = 300 -local ecs = require(ReplicatedStorage.ecs) - --- 500 entities --- 2-30 components on each entity --- 300 unique components --- 200 systems --- 1-10 components to query per system - -local startTime = os.clock() - -local world = ecs.World.new() - -local components = {} - -for i = 1, 300 do -- 300 components - components[i] = world:component() -end - -local archetypes = {} -for i = 1, 50 do -- 50 archetypes - local archetype = {} - - for _ = 1, math.random(2, 30) do - local componentId = math.random(1, #components) - - table.insert(archetype, components[componentId]) - end - - archetypes[i] = archetype -end - -for _ = 1, 1000 do -- 1000 entities in the world - local componentsToAdd = {} - - local archetypeId = math.random(1, #archetypes) - local e = world:entity() - for _, component in ipairs(archetypes[archetypeId]) do - world:set(e, component, { - DummyData = math.random(1, 5000), - }) - end -end - -local function values(t) - local array = {} - for _, v in t do - table.insert(array, v) - end - return array -end - -local contiguousComponents = values(components) -local systemComponentsToQuery = {} - -for _ = 1, 200 do -- 200 systems - local numComponentsToQuery = math.random(1, 10) - local componentsToQuery = {} - - for _ = 1, numComponentsToQuery do - table.insert(componentsToQuery, contiguousComponents[math.random(1, #contiguousComponents)]) - end - - table.insert(systemComponentsToQuery, componentsToQuery) -end - -local worldCreateTime = os.clock() - startTime -local results = {} -startTime = os.clock() - -RunService.Heartbeat:Connect(function() - local added = 0 - local systemStartTime = os.clock() - debug.profilebegin("systems") - for _, componentsToQuery in ipairs(systemComponentsToQuery) do - debug.profilebegin("system") - for entityId, firstComponent in world:query(unpack(componentsToQuery)) do - world:set( - entityId, - { - DummyData = firstComponent.DummyData + 1, - } - ) - added += 1 - end - debug.profileend() - end - debug.profileend() - - if os.clock() - startTime < 4 then - -- discard first 4 seconds - return - end - - if results == nil then - return - elseif #results < 1000 then - table.insert(results, os.clock() - systemStartTime) - else - print("added", added) - print("World created in", worldCreateTime * 1000, "ms") - local sum = 0 - for _, result in ipairs(results) do - sum += result - end - print(("Average frame time: %fms"):format((sum / #results) * 1000)) - - results = nil - - local n = #world.archetypes - - print( - ("X entities\n%d components\n%d systems\n%d archetypes"):format( - #components, - #systemComponentsToQuery, - n - ) - ) - end -end) +local RunService = game:GetService("RunService") +local ReplicatedStorage = game:GetService("ReplicatedStorage") +_G.__JECS_HI_COMPONENT_ID = 300 +local ecs = require(ReplicatedStorage.ecs) + +-- 500 entities +-- 2-30 components on each entity +-- 300 unique components +-- 200 systems +-- 1-10 components to query per system + +local startTime = os.clock() + +local world = ecs.World.new() + +local components = {} + +for i = 1, 300 do -- 300 components + components[i] = world:component() +end + +local archetypes = {} +for i = 1, 50 do -- 50 archetypes + local archetype = {} + + for _ = 1, math.random(2, 30) do + local componentId = math.random(1, #components) + + table.insert(archetype, components[componentId]) + end + + archetypes[i] = archetype +end + +for _ = 1, 1000 do -- 1000 entities in the world + local componentsToAdd = {} + + local archetypeId = math.random(1, #archetypes) + local e = world:entity() + for _, component in ipairs(archetypes[archetypeId]) do + world:set(e, component, { + DummyData = math.random(1, 5000), + }) + end +end + +local function values(t) + local array = {} + for _, v in t do + table.insert(array, v) + end + return array +end + +local contiguousComponents = values(components) +local systemComponentsToQuery = {} + +for _ = 1, 200 do -- 200 systems + local numComponentsToQuery = math.random(1, 10) + local componentsToQuery = {} + + for _ = 1, numComponentsToQuery do + table.insert(componentsToQuery, contiguousComponents[math.random(1, #contiguousComponents)]) + end + + table.insert(systemComponentsToQuery, componentsToQuery) +end + +local worldCreateTime = os.clock() - startTime +local results = {} +startTime = os.clock() + +RunService.Heartbeat:Connect(function() + local added = 0 + local systemStartTime = os.clock() + debug.profilebegin("systems") + for _, componentsToQuery in ipairs(systemComponentsToQuery) do + debug.profilebegin("system") + for entityId, firstComponent in world:query(unpack(componentsToQuery)) do + world:set( + entityId, + { + DummyData = firstComponent.DummyData + 1, + } + ) + added += 1 + end + debug.profileend() + end + debug.profileend() + + if os.clock() - startTime < 4 then + -- discard first 4 seconds + return + end + + if results == nil then + return + elseif #results < 1000 then + table.insert(results, os.clock() - systemStartTime) + else + print("added", added) + print("World created in", worldCreateTime * 1000, "ms") + local sum = 0 + for _, result in ipairs(results) do + sum += result + end + print(("Average frame time: %fms"):format((sum / #results) * 1000)) + + results = nil + + local n = #world.archetypes + + print( + ("X entities\n%d components\n%d systems\n%d archetypes"):format( + #components, + #systemComponentsToQuery, + n + ) + ) + end +end) diff --git a/test/tools/entity_visualiser.luau b/test/tools/entity_visualiser.luau index 9698939..1df9dc0 100644 --- a/test/tools/entity_visualiser.luau +++ b/test/tools/entity_visualiser.luau @@ -1,24 +1,24 @@ -local jecs = require("@jecs") -local pair = jecs.pair -local ChildOf = jecs.ChildOf -local lifetime_tracker_add = require("@tools/lifetime_tracker") -local world = lifetime_tracker_add(jecs.world(), {padding_enabled=false}) -local FriendsWith = world:component() -world:print_snapshot() -local e1 = world:entity() -local e2 = world:entity() -world:delete(e2) - -world:print_snapshot() -local e3 = world:entity() -world:add(e3, pair(ChildOf, e1)) -local e4 = world:entity() -world:add(e4, pair(FriendsWith, e3)) -world:print_snapshot() -world:delete(e1) -world:delete(e3) -world:print_snapshot() -world:print_entity_index() -world:entity() -world:entity() -world:print_snapshot() +local jecs = require("@jecs") +local pair = jecs.pair +local ChildOf = jecs.ChildOf +local lifetime_tracker_add = require("@tools/lifetime_tracker") +local world = lifetime_tracker_add(jecs.world(), {padding_enabled=false}) +local FriendsWith = world:component() +world:print_snapshot() +local e1 = world:entity() +local e2 = world:entity() +world:delete(e2) + +world:print_snapshot() +local e3 = world:entity() +world:add(e3, pair(ChildOf, e1)) +local e4 = world:entity() +world:add(e4, pair(FriendsWith, e3)) +world:print_snapshot() +world:delete(e1) +world:delete(e3) +world:print_snapshot() +world:print_entity_index() +world:entity() +world:entity() +world:print_snapshot() diff --git a/tools/read_lcov.py b/tools/read_lcov.py index b93592e..cee7733 100644 --- a/tools/read_lcov.py +++ b/tools/read_lcov.py @@ -1,153 +1,153 @@ -import os - -LCOV_FILE = "coverage.out" -OUTPUT_DIR = "coverage" - -os.makedirs(OUTPUT_DIR, exist_ok=True) - -def parse_lcov(content): - """Parses LCOV data from a single string.""" - files = {} - current_file = None - - for line in content.splitlines(): - if line.startswith("SF:"): - current_file = line[3:].strip() - files[current_file] = {"coverage": {}, "functions": []} - elif line.startswith("DA:") and current_file: - parts = line[3:].split(",") - line_num = int(parts[0]) - execution_count = int(parts[1]) - files[current_file]["coverage"][line_num] = execution_count - elif line.startswith("FN:") and current_file: - parts = line[3:].split(",") - line_num = int(parts[0]) - function_name = parts[1].strip() - files[current_file]["functions"].append({"name": function_name, "line": line_num, "hits": 0}) - elif line.startswith("FNDA:") and current_file: - parts = line[5:].split(",") - hit_count = int(parts[0]) - function_name = parts[1].strip() - for func in files[current_file]["functions"]: - if func["name"] == function_name: - func["hits"] = hit_count - break - - return files - -def read_source_file(filepath): - """Reads source file content if available.""" - if not os.path.exists(filepath): - return [] - - with open(filepath, "r", encoding="utf-8") as f: - return f.readlines() - -def generate_file_html(filepath, coverage_data, functions_data): - """Generates an HTML file for a specific source file.""" - filename = os.path.basename(filepath) - source_code = read_source_file(filepath) - html_path = os.path.join(OUTPUT_DIR, f"{filename}.html") - - total_hits = sum(func["hits"] for func in functions_data) - max_hits = max((func["hits"] for func in functions_data), default=0) - - total_functions = len(functions_data) - covered_functions = sum(1 for func in functions_data if func["hits"] > 0) - function_coverage_percent = (covered_functions / total_functions * 100) if total_functions > 0 else 0 - - lines = [ - "", - '', - '', - "", - f'

{filename} Coverage

', - f'

Total Execution Hits: {total_hits}

', - f'

Function Coverage Overview: {function_coverage_percent:.2f}%

', - - '', - - '
', - '

Function Coverage:

' - ] - - longest_name = max((len(func["name"]) for func in functions_data), default=0) - - for func in functions_data: - hit_color = "red" if func["hits"] == 0 else "green" - lines.append( - f'' - f'' - ) - - lines.append('
FunctionHits
{func["name"]}{func["hits"]}
') # Close collapsible div - - lines.append('

Source Code:

') - - for i, line in enumerate(source_code, start=1): - stripped_line = line.strip() - class_name = "text-muted" - if not stripped_line or stripped_line.startswith("end") or stripped_line.startswith("--"): - count_display = "N/A" - lines.append(f'>') - else: - count = coverage_data.get(i, 0) - class_name = "zero-hits" if count == 0 else "low-hits" if count < max_hits * 0.3 else "high-hits" - count_display = f'{count}' - marked_text = f'{line.strip()}' - lines.append(f'') - - lines.append("
LineHitsCode
{i}{count_display}{line.strip()}
{i}{count_display}{marked_text}
") - - with open(html_path, "w", encoding="utf-8") as f: - f.write("\n".join(lines)) - -def generate_index(files): - """Generates an index.html summarizing the coverage.""" - index_html = [ - "", - '', - "", - '

Coverage Report

', - '' - ] - - for filepath, data in files.items(): - filename = os.path.basename(filepath) - total_hits = sum(func["hits"] for func in data["functions"]) - total_functions = len(data["functions"]) - - index_html.append(f'') - - index_html.append("
FileTotal HitsFunctions
{filename}{total_hits}{total_functions}
") - - with open(os.path.join(OUTPUT_DIR, "index.html"), "w", encoding="utf-8") as f: - f.write("\n".join(index_html)) - -with open(LCOV_FILE, "r", encoding="utf-8") as f: - lcov_content = f.read() - -files_data = parse_lcov(lcov_content) - -for file_path, data in files_data.items(): - generate_file_html(file_path, data["coverage"], data["functions"]) - -generate_index(files_data) - -print(f"Coverage report generated in {OUTPUT_DIR}/index.html") +import os + +LCOV_FILE = "coverage.out" +OUTPUT_DIR = "coverage" + +os.makedirs(OUTPUT_DIR, exist_ok=True) + +def parse_lcov(content): + """Parses LCOV data from a single string.""" + files = {} + current_file = None + + for line in content.splitlines(): + if line.startswith("SF:"): + current_file = line[3:].strip() + files[current_file] = {"coverage": {}, "functions": []} + elif line.startswith("DA:") and current_file: + parts = line[3:].split(",") + line_num = int(parts[0]) + execution_count = int(parts[1]) + files[current_file]["coverage"][line_num] = execution_count + elif line.startswith("FN:") and current_file: + parts = line[3:].split(",") + line_num = int(parts[0]) + function_name = parts[1].strip() + files[current_file]["functions"].append({"name": function_name, "line": line_num, "hits": 0}) + elif line.startswith("FNDA:") and current_file: + parts = line[5:].split(",") + hit_count = int(parts[0]) + function_name = parts[1].strip() + for func in files[current_file]["functions"]: + if func["name"] == function_name: + func["hits"] = hit_count + break + + return files + +def read_source_file(filepath): + """Reads source file content if available.""" + if not os.path.exists(filepath): + return [] + + with open(filepath, "r", encoding="utf-8") as f: + return f.readlines() + +def generate_file_html(filepath, coverage_data, functions_data): + """Generates an HTML file for a specific source file.""" + filename = os.path.basename(filepath) + source_code = read_source_file(filepath) + html_path = os.path.join(OUTPUT_DIR, f"{filename}.html") + + total_hits = sum(func["hits"] for func in functions_data) + max_hits = max((func["hits"] for func in functions_data), default=0) + + total_functions = len(functions_data) + covered_functions = sum(1 for func in functions_data if func["hits"] > 0) + function_coverage_percent = (covered_functions / total_functions * 100) if total_functions > 0 else 0 + + lines = [ + "", + '', + '', + "", + f'

{filename} Coverage

', + f'

Total Execution Hits: {total_hits}

', + f'

Function Coverage Overview: {function_coverage_percent:.2f}%

', + + '', + + '
', + '

Function Coverage:

' + ] + + longest_name = max((len(func["name"]) for func in functions_data), default=0) + + for func in functions_data: + hit_color = "red" if func["hits"] == 0 else "green" + lines.append( + f'' + f'' + ) + + lines.append('
FunctionHits
{func["name"]}{func["hits"]}
') # Close collapsible div + + lines.append('

Source Code:

') + + for i, line in enumerate(source_code, start=1): + stripped_line = line.strip() + class_name = "text-muted" + if not stripped_line or stripped_line.startswith("end") or stripped_line.startswith("--"): + count_display = "N/A" + lines.append(f'>') + else: + count = coverage_data.get(i, 0) + class_name = "zero-hits" if count == 0 else "low-hits" if count < max_hits * 0.3 else "high-hits" + count_display = f'{count}' + marked_text = f'{line.strip()}' + lines.append(f'') + + lines.append("
LineHitsCode
{i}{count_display}{line.strip()}
{i}{count_display}{marked_text}
") + + with open(html_path, "w", encoding="utf-8") as f: + f.write("\n".join(lines)) + +def generate_index(files): + """Generates an index.html summarizing the coverage.""" + index_html = [ + "", + '', + "", + '

Coverage Report

', + '' + ] + + for filepath, data in files.items(): + filename = os.path.basename(filepath) + total_hits = sum(func["hits"] for func in data["functions"]) + total_functions = len(data["functions"]) + + index_html.append(f'') + + index_html.append("
FileTotal HitsFunctions
{filename}{total_hits}{total_functions}
") + + with open(os.path.join(OUTPUT_DIR, "index.html"), "w", encoding="utf-8") as f: + f.write("\n".join(index_html)) + +with open(LCOV_FILE, "r", encoding="utf-8") as f: + lcov_content = f.read() + +files_data = parse_lcov(lcov_content) + +for file_path, data in files_data.items(): + generate_file_html(file_path, data["coverage"], data["functions"]) + +generate_index(files_data) + +print(f"Coverage report generated in {OUTPUT_DIR}/index.html")