A performant, zero-dependency ECS library with a nice API written in Rust.
Usage
# Cargo.toml
[dependecies]
kiwi-ecs = "1.1"
// lib.rs
use kiwi_ecs::*;
The world
To start, create a new World
. This is the starting point of the ecs.
The program can have multiple independent worlds.
pub fn main() {
let mut world = World::new();
}
Components
Components are defined as follows:
#[derive(Component)]
struct Position {
x: u32,
y: u32
}
Entities
To spawn a new entity with the given ids:
// spawn_entity macro accepts the world as the first parameter, and the
// components to add to the entity as the other parameters
let id = spawn_entity!(world, Pos { x: 0, y: 0 });
Systems
There are two ways to define systems.
system
macro:
The first is using the // immutable system
#[system(pos: Position)]
fn print_positions(world: &World) {
println!("{:?}", pos);
}
// mutable system
#[system(pos: Pos, vel: Vel)]
fn move_entities(world: &mut World) {
pos.x += vel.x;
pos.y += vel.y
}
// query entity ids as well
#[system(id: EntityId, pos: Position)]
/// prints all entities ids having the position component
fn print_entity_ids(world: &World) {
println!("{id}");
}
pub fn main() {
let mut world = World::new();
//--snip
// Call the systems
print_positions(&world);
move_entities(&mut world);
print_entity_ids(&world);
}
To create a mutable system, the function should contain world: &mut World
as its first argument,
for an immutable one, add world: &World
.
The function can contain any number of arguments you can pass to it when calling.
The function can return any type of Result<(), Any>
. If this function has the given result
return type, Ok(())
will be returned at the end of the system.
query
and query_mut
macros:
The second is using the pub fn main() {
let mut world = World::new();
//--snip
let query_result = query!(world, Position);
let query_result = query_mut!(world, Position, Vel);
let query_result = query!(world, EntityId, Position);
// You can now loop over the components
query_result.for_each(|components| {
// ...
});
}
License
Licensed under the MIT license.