- Notifications
You must be signed in to change notification settings - Fork6
License
zakarumych/edict
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Edict is a fast, powerful and ergonomic ECS crate that expands traditional ECS feature set.Written in Rust by your fellow 🦀
use edict::prelude::*;// Create world instance.letmut world =World::new();// Declare some components.#[derive(Component)]structPos(f32,f32);// Declare some more.#[derive(Component)]structVel(f32,f32);// Spawn entity with components.world.spawn((Pos(0.0,0.0),Vel(1.0,1.0)));// Query components and iterate over views.for(pos, vel)in world.view::<(&mutPos,&Vel)>(){ pos.0 += vel.0; pos.1 += vel.1;}// Define functions that will be used as systems.#[edict::system::system]// This attribute is optional, but it catches if function is not a system.fnmove_system(pos_vel:View<(&mutPos,&Vel)>){for(pos, vel)in pos_vel{ pos.0 += vel.0; pos.1 += vel.1;}}// Create scheduler to run systems. Requires "scheduler" feature.use edict::scheduler::Scheduler;letmut scheduler =Scheduler::new();scheduler.add_system(move_system);// Run systems without parallelism.scheduler.run_sequential(&mut world);// Run systems using threads. Requires "std" feature.scheduler.run_threaded(&mut world);// Or use custom thread pool.
InEntity Component Systems we create entities and address them to fetch associated data.Edict providesEntityId
type to address entities.
EntityId
as a world-unique identifier of an entity.Edict uses IDs without generation and recycling, for this purpose it employsu64
underlying type with a few niches.It is enough to create IDs non-stop for hundreds of years before running out of them.This greatly simplifying serialization of theWorld
's state as it doesn't require any processing of entity IDs.
By default entity IDs are unique only within oneWorld
.For multi-world scenarios Edict provides a way to make entity IDs unique between any required combination of worlds.
IDs are allocated in sequence fromIdRange
s that are allocated byIdRangeAllocator
.By defaultIdRange
that spans from 1 tou64::MAX - 1
is used. This makes default ID allocation extremely fast.CustomIdRangeAllocator
can be provided toWorldBuilder
to use custom ID ranges.
For example in client-server architecture, server and client may use non-overlapping ID ranges.Thus allowing state serialized on server to be transferred to client without ID mapping,which can be cumbersome when components reference entities.
In multi-server or p2p architectureIdRangeAllocator
would need to communicate to allocate disjoint ID ranges for each server.
Using ECS may lead to lots of.unwrap()
calls or excessive error handling.There a lot of situations when entity is guaranteed to exist (for example it just returned from a view).To avoid handlingNoSuchEntity
error when it is unreachable, Edict providesAliveEntity
trait that extendsEntity
trait.Various methods requireAliveEntity
handle and skip existence check.
Entity
andAliveEntity
traits implemented for number of entity types.
EntityId
implements onlyEntity
as it doesn't provide any guaranties.
EntityBound
is guaranteed to be alive, allowing using it in methods that doesn't handle entity absence.It keeps lifetime ofWorld
borrow, making it impossible to despawn any entity from the world.Using it with wrongWorld
may cause panic.EntityBound
can be acquire from relation queries.
EntityLoc
not only guarantees entity existence but also contains location of the entity in the archetypes,allowing to skip lookup step when accessing its components.Similarly toEntityBound
, it keeps lifetime ofWorld
borrow, making it impossible to despawn any entity from the world.Using it with wrongWorld
may cause panic.EntityLoc
can be acquire fromEntities
query.
EntityRef
is special.It doesn't implementEntity
orAliveEntity
traits since it should not be used in world methods.Instead it provides direct access to entity's data and allows mutations such as inserting/removing components.
Support for!Send
and!Sync
components and resources with some limitations.
World
itself is not sendable but shareable between threads.Thread owningWorld
is referred as "main" thread in documentation.
Components and resources that are!Send
can be fetched mutably only from "main" thread.Components and resources that are!Sync
can be fetched immutably only from "main" thread.Since reference toWorld
may exist outside "main" thread,WorldLocal
reference should be used,it can be created using mutable reference toWorld
.
OptionalComponent
trait that allows implicit component type registration when component is inserted first time.Implicit registration uses behavior defined byComponent
implementation as-is.When needed, explicit registration can be done usingWorldBuilder
to override component behavior.
NonComponent
types require explicit registration andfew methods with_external
suffix is used with them instead of normal ones.Only default registration is possible whenWorld
is already built.When needed, explicit registration can be done usingWorldBuilder
to override component behavior.
A relation can be added to pair of entities, binding them together.Queries may fetch relations and filter entities by their relations to other entities.When either of the two entities is despawned, relation is dropped.Relation
type may further configure behavior of the bounded entities.
PowerfulQuery
mechanism that can filter entities by components, relations and other criteria and fetch entity data.Queries can be mutable or immutable, sendable or non-sendable, stateful or stateless.
Using query onWorld
creates Views.Views can be used to iterate over entities that match the query yielding query items.Or fetch single entity data.
ViewRef
andViewMut
are convenient type aliases to view types returned fromWorld
methods.
Runtime checks are available for query mutable aliasing avoidance.
ViewRef
andViewCell
do runtime checks allowing multiple views with aliased access coexist,deferring checks to runtime that prevents invalid aliasing to occur.
When this is not required,ViewMut
andView
s with compile time checks should be used instead.
WhenView
is expectedViewRef
andViewCell
can be locked to make aView
.
Component type may define borrowing operations to borrow another type from it.Borrowed type may be not sized, allowing slices and dyn traits to be borrowed.A macro to help define borrowing operations is provided.Queries that tries to borrow type from suitable components are provided:
BorrowAll
borrows from all components that implement borrowing requested type.Yields aVec
with borrowed values since multiple components of the entity may provide it.Skips entities if none of the components provide the requested type.BorrowAny
borrows from first suitable component that implements borrowing requested type.Yields a single value.Skips entities if none of the components provide the requested type.BorrowOne
is configured withTypeId
of component from which it should borrow requested type.Panics if component doesn't provide the requested type.Skips entities without the component.
Built-in type-map for singleton values called "resources".Resources can be inserted into/fetched fromWorld
.Resources live separately from entities and their components.
UseActionEncoder
for recording actions and run them later with mutable access toWorld
.OrLocalActionEncoder
instead when action is notSend
.Or convenientWorldLocal::defer*
methods to defer actions to internalLocalActionEncoder
.
Each component instance is equipped with epoch counter that tracks last potential mutation of the component.Queries may read and update components epoch to track changes.Queries to filter recently changed components are provided withModified
type.Last epoch can be obtained withWorld::epoch
.
Systems is convenient way to build logic that operates onWorld
.Edict definesSystem
trait to run logic onWorld
.AndIntoSystem
trait for types convertible toSystem
.
Functions may implementIntoSystem
automatically -it is required to return()
and accept arguments that implementFnArg
trait.There areFnArg
implementations:
View
andViewCell
to iterate over entities and their components.UseView
unlessViewCell
is required to handle intra-system views conflict.Res
andResMut
to access resources.ResLocal
andResMutLocal
to access no-thread-safe resources.This will make system non-sendable and force it to run on main thread.ActionEncoder
to record actions that mutateWorld
state, such as entity spawning, inserting and removing components or resources.State
to store system's local state between runs.
Scheduler
is provided to runSystem
s.Systems added to theScheduler
run in parallel where possible,however they actas if executed sequentially in order they were added.
If systems do not conflict they may be executed in parallel.
If systems conflict, the one added first will be executed before the one added later can start.
std
threads orrayon
can be used as an executor.User may provide custom executor by implementingScopedExecutor
trait.
Requires"scheduler"
feature which is enabled by default.
Component replace/drop hooks are called automatically when component is replaced or dropped.
When component is registered it can be equipped with hooks to be called when component value is replaced or dropped.Implicit registration ofComponent
types will register hooks defined on the trait impl.
Drop hook is called when component is dropped viaWorld::drop
or entity is despawned and is notcalled when component is removed from entity.
Replace hook is called when component is replaced e.g. component is inserted into entityand entity already has component of the same type.Replace hook returns boolean value that indicates if drop hook should be called for replaced component.
Hooks can record actions into providedLocalActionEncoder
that will be executedbeforeWorld
method that caused the hook to be called returns.
When component implementsComponent
trait, hooks defined on the trait impl are registered automatically to callComponent::on_drop
andComponent::on_replace
methods.They may be overridden with custom hooks usingWorldBuilder
.For nonComponent
types hooks can be registered only viaWorldBuilder
.Default registration withWorld
will not register any hooks.
Futures executor to run logic that requires waiting for certain conditions or eventsor otherwise spans for multiple ticks.
Logic that requires waiting can be complex to implement using systems.Systems run in loop and usually work on every entity with certain components.Implementing waiting logic would require adding waiting state to existing or new components andlogic would be spread across many system runs or even many systems.
Futures may useawait
syntax to wait for certain conditions or events.Futures that can access ECS data are referred in Edict as "flows".
Flows can be spawned in theWorld
usingWorld::spawn_flow
orFlowWorld::spawn_flow
method.Flows
type is used as an executor to run spawned flows.
Flows can be bound to an entity and spawned usingWorld::spawn_flow_for
,FlowWorld::spawn_flow_for
,EntityRef::spawn_flow
orFlowEntity::spawn_flow
method.Such flows will be cancelled if entity is despawned.
Functions that return futures may serve as flows.ForWorld::spawn_flow
use function or closure with signatureFnOnce(FlowWorld) -> Future
ForWorld::spawn_flow_for
use function or closure with signatureFnOnce(FlowEntity) -> Future
User may implement low-level futures usingpoll*
methods ofFlowWorld
andFlowEntity
to access tasksContext
.Edict provides only a couple of low-level futures that will do the waiting:
yield_now!
yields control to the executor once and resumes on next execution.FlowEntity::wait_despawned
waits until entity is despawned.FlowEntity::wait_has_component
waits until entity get a component.
WakeOnDrop
component can be used when despawning entity should wake a task.
It is recommended to use flows for high-level logic that spans multiple ticksand use systems to do low-level logic that runs every tick.Flows may request systems to perform operations by adding special components to entities.And systems may spawn flows to do long-running operations.
Requires"flow"
feature which is enabled by default.
Edict can be used inno_std
environment but requiresalloc
crate."std"
feature is enabled by default.
If "std" feature is not enabled error types will not implementstd::error::Error
.
When "flow" feature is enabled and "std" is not, extern functions are used to implement TLS.Application must provide implementation for these functions or linking will fail.
When "scheduler" feature is enabled and "std" is not, external functions are used to implement thread parking.Application must provide implementation for these functions or linking will fail.
Licensed under either of
- Apache License, Version 2.0, (license/APACHE orhttp://www.apache.org/licenses/LICENSE-2.0)
- MIT license (license/MIT orhttp://opensource.org/licenses/MIT)
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.