jecs/README.md
2024-05-11 02:12:47 +02:00

2.4 KiB

License: Apache 2.0 Wally

Just an ECS

jecs is a stupidly fast Entity Component System (ECS).

  • Entity Relationships as first class citizens
  • Process tens of thousands of entities with ease every frame
  • Type-safe Luau API
  • Zero-dependency package
  • Optimized for column-major operations
  • Cache friendly archetype/SoA storage
  • Unit tested for stability

Example

local world = World.new()

local player = world:entity()
local opponent = world:entity()

local Health = world:component()
local Position = world:component()
-- Notice how components can just be entities as well?
-- It allows you to model relationships easily!
local Damage = world:entity()
local DamagedBy = world:entity()

world:set(player, Health, 100)
world:set(player, Damage, 8)
world:set(player, Position, Vector3.new(0, 5, 0))

world:set(opponent, Health, 100)
world:set(opponent, Damage, 21)
world:set(opponent, Position, Vector3.new(0, 5, 3))

for playerId, playerPosition, health in world:query(Position, Health) do
    local totalDamage = 0
    for opponentId, opponentPosition, damage in world:query(Position, Damage) do
        if playerId == opponentId then 
            continue
        end
        if (playerPosition - opponentPosition).Magnitude < 5 then
            totalDamage += damage
        end
        -- We create a pair between the relation component `DamagedBy` and the entity id of the opponent. 
        -- This will allow us to specifically query for damage exerted by a specific opponent.
        world:set(playerId, ECS_PAIR(DamagedBy, opponentId), totalDamage)
    end
end

-- Gets the damage inflicted by our specific opponent!
for playerId, health, inflicted in world:query(Health, ECS_PAIR(DamagedBy, opponent)) do 
    world:set(playerId, health - inflicted)
end

assert(world:get(player, Health) == 79)

125 archetypes, 4 random components queried. Queries Can be found under /benches/query.lua

Inserting 8 components to an entity and updating them over 50 times. Insertions Can be found under /benches/insertions.lua