Skip to content

Commit cebb553

Browse files
NiklasEicart
andcommitted
Add a readme to bevy_ecs (#2028)
[RENDERED](https://github.com/NiklasEi/bevy/blob/ecs_readme/crates/bevy_ecs/README.md) Since I am trying to learn more about Bevy ECS at the moment, I thought this issue is a perfect fit. This PR adds a readme to the `bevy_ecs` crate containing a minimal running example of stand alone `bevy_ecs`. Unique features like customizable component storage, Resources or change detection are introduced. For each of these features the readme links to an example in a newly created examples directory inside the `bevy_esc` crate. Resolves #2008 Co-authored-by: Carter Anderson <[email protected]>
1 parent 21330a7 commit cebb553

File tree

6 files changed

+540
-0
lines changed

6 files changed

+540
-0
lines changed

crates/bevy_ecs/Cargo.toml

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,19 @@ downcast-rs = "1.2"
3232
parking_lot = "0.11"
3333
rand = "0.8"
3434
serde = "1"
35+
36+
[[example]]
37+
name = "events"
38+
path = "examples/events.rs"
39+
40+
[[example]]
41+
name = "component_storage"
42+
path = "examples/component_storage.rs"
43+
44+
[[example]]
45+
name = "resources"
46+
path = "examples/resources.rs"
47+
48+
[[example]]
49+
name = "change_detection"
50+
path = "examples/change_detection.rs"

crates/bevy_ecs/README.md

Lines changed: 248 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,248 @@
1+
# Bevy ECS
2+
3+
[![Crates.io](https://img.shields.io/crates/v/bevy_ecs.svg)](https://crates.io/crates/bevy_ecs)
4+
[![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/bevyengine/bevy/blob/HEAD/LICENSE)
5+
[![Discord](https://img.shields.io/discord/691052431525675048.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/gMUk5Ph)
6+
7+
## What is Bevy ECS?
8+
9+
Bevy ECS is an Entity Component System custom-built for the [Bevy][bevy] game engine. It aims to be simple to use, ergonomic, fast, massively parallel, opinionated, and featureful. It was created specifically for Bevy's needs, but it can easily be used as a standalone crate in other projects.
10+
11+
## ECS
12+
13+
All app logic in Bevy uses the Entity Component System paradigm, which is often shortened to ECS. ECS is a software pattern that involves breaking your program up into Entities, Components, and Systems. Entities are unique "things" that are assigned groups of Components, which are then processed using Systems.
14+
15+
For example, one entity might have a `Position` and `Velocity` component, whereas another entity might have a `Position` and `UI` component. You might have a movement system that runs on all entities with a Position and Velocity component.
16+
17+
The ECS pattern encourages clean, decoupled designs by forcing you to break up your app data and logic into its core components. It also helps make your code faster by optimizing memory access patterns and making parallelism easier.
18+
19+
## Concepts
20+
21+
Bevy ECS is Bevy's implementation of the ECS pattern. Unlike other Rust ECS implementations, which often require complex lifetimes, traits, builder patterns, or macros, Bevy ECS uses normal Rust data types for all of these concepts:
22+
23+
### Components
24+
25+
Components are normal Rust structs. They are data stored in a `World` and specific instances of Components correlate to Entities.
26+
27+
```rust
28+
struct Position { x: f32, y: f32 }
29+
```
30+
31+
### Worlds
32+
33+
Entities, Components, and Resources are stored in a `World`. Worlds, much like Rust std collections like HashSet and Vec, expose operations to insert, read, write, and remove the data they store.
34+
35+
```rust
36+
let world = World::default();
37+
```
38+
39+
### Entities
40+
41+
Entities are unique identifiers that correlate to zero or more Components.
42+
43+
```rust
44+
let entity = world.spawn()
45+
.insert(Position { x: 0.0, y: 0.0 })
46+
.insert(Velocity { x: 1.0, y: 0.0 })
47+
.id();
48+
49+
let entity_ref = world.entity(entity);
50+
let position = entity_ref.get::<Position>().unwrap();
51+
let velocity = entity_ref.get::<Velocity>().unwrap();
52+
```
53+
54+
### Systems
55+
56+
Systems are normal Rust functions. Thanks to the Rust type system, Bevy ECS can use function parameter types to determine what data needs to be sent to the system. It also uses this "data access" information to determine what Systems can run in parallel with each other.
57+
58+
```rust
59+
fn print_position(query: Query<(Entity, &Position)>) {
60+
for (entity, position) in query.iter() {
61+
println!("Entity {:?} is at position: x {}, y {}", entity, position.x, position.y);
62+
}
63+
}
64+
```
65+
66+
### Resources
67+
68+
Apps often require unique resources, such as asset collections, renderers, audio servers, time, etc. Bevy ECS makes this pattern a first class citizen. `Resource` is a special kind of component that does not belong to any entity. Instead, it is identified uniquely by its type:
69+
70+
```rust
71+
#[derive(Default)]
72+
struct Time {
73+
seconds: f32,
74+
}
75+
76+
world.insert_resource(Time::default());
77+
78+
let time = world.get_resource::<Time>().unwrap();
79+
80+
// You can also access resources from Systems
81+
fn print_time(time: Res<Time>) {
82+
println!("{}", time.seconds);
83+
}
84+
```
85+
86+
The [`resources.rs`](examples/resources.rs) example illustrates how to read and write a Counter resource from Systems.
87+
88+
### Schedules
89+
90+
Schedules consist of zero or more Stages, which run a set of Systems according to some execution strategy. Bevy ECS provides a few built in Stage implementations (ex: parallel, serial), but you can also implement your own! Schedules run Stages one-by-one in an order defined by the user.
91+
92+
The built in "parallel stage" considers dependencies between systems and (by default) run as many of them in parallel as possible. This maximizes performance, while keeping the system execution safe. You can also define explicit dependencies between systems.
93+
94+
## Using Bevy ECS
95+
96+
Bevy ECS should feel very natural for those familiar with Rust syntax:
97+
98+
```rust
99+
use bevy_ecs::prelude::*;
100+
101+
struct Velocity {
102+
x: f32,
103+
y: f32,
104+
}
105+
106+
struct Position {
107+
x: f32,
108+
y: f32,
109+
}
110+
111+
// This system moves each entity with a Position and Velocity component
112+
fn movement(query: Query<(&mut Position, &Velocity)>) {
113+
for (mut position, velocity) in query.iter_mut() {
114+
position.x += velocity.x;
115+
position.y += velocity.y;
116+
}
117+
}
118+
119+
fn main() {
120+
// Create a new empty World to hold our Entities and Components
121+
let mut world = World::new();
122+
123+
// Spawn an entity with Position and Velocity components
124+
world.spawn()
125+
.insert(Position { x: 0.0, y: 0.0 })
126+
.insert(Velocity { x: 1.0, y: 0.0 });
127+
128+
// Create a new Schedule, which defines an execution strategy for Systems
129+
let mut schedule = Schedule::default();
130+
131+
// Add a Stage to our schedule. Each Stage in a schedule runs all of its systems
132+
// before moving on to the next Stage
133+
schedule.add_stage("update", SystemStage::parallel()
134+
.with_system(movement.system())
135+
);
136+
137+
// Run the schedule once. If your app has a "loop", you would run this once per loop
138+
schedule.run(&mut world);
139+
}
140+
```
141+
142+
## Features
143+
144+
### Query Filters
145+
146+
```rust
147+
// Gets the Position component of all Entities with Player component and without the RedTeam component
148+
fn system(query: Query<&Position, (With<Player>, Without<RedTeam>)>) {
149+
for position in query.iter() {
150+
}
151+
}
152+
```
153+
154+
### Change Detection
155+
156+
Bevy ECS tracks _all_ changes to Components and Resources.
157+
158+
Queries can filter for changed Components:
159+
160+
```rust
161+
// Gets the Position component of all Entities whose Velocity has changed since the last run of the System
162+
fn system(query: Query<&Position, Changed<Velocity>>) {
163+
for position in query.iter() {
164+
}
165+
}
166+
167+
// Gets the Position component of all Entities that had a Velocity component added since the last run of the System
168+
fn system(query: Query<&Position, Added<Velocity>>) {
169+
for position in query.iter() {
170+
}
171+
}
172+
```
173+
174+
Resources also expose change state:
175+
176+
```rust
177+
// Prints "time changed!" if the Time resource has changed since the last run of the System
178+
fn system(time: Res<Time>) {
179+
if time.is_changed() {
180+
println!("time changed!");
181+
}
182+
}
183+
```
184+
185+
The [`change_detection.rs`](examples/change_detection.rs) example shows how to query only for updated entities and react on changes in resources.
186+
187+
### Component Storage
188+
189+
Bevy ECS supports multiple component storage types.
190+
191+
Components can be stored in:
192+
193+
* **Tables**: Fast and cache friendly iteration, but slower adding and removing of components. This is the default storage type.
194+
* **Sparse Sets**: Fast adding and removing of components, but slower iteration.
195+
196+
Component storage types are configurable, and they default to table storage if the storage is not manually defined. The [`component_storage.rs`](examples/component_storage.rs) example shows how to configure the storage type for a component.
197+
198+
```rust
199+
// store Position components in Sparse Sets
200+
world.register_component(ComponentDescriptor::new::<Position>(StorageType::SparseSet));
201+
```
202+
203+
### Component Bundles
204+
205+
Define sets of Components that should be added together.
206+
207+
```rust
208+
#[derive(Bundle, Default)]
209+
struct PlayerBundle {
210+
player: Player,
211+
position: Position,
212+
velocity: Velocity,
213+
}
214+
215+
// Spawn a new entity and insert the default PlayerBundle
216+
world.spawn().insert_bundle(PlayerBundle::default());
217+
218+
// Bundles play well with Rust's struct update syntax
219+
world.spawn().insert_bundle(PlayerBundle {
220+
position: Position { x: 1.0, y: 1.0 },
221+
..Default::default()
222+
});
223+
```
224+
225+
### Events
226+
227+
Events offer a communication channel between one or more systems. Events can be sent using the system parameter `EventWriter` and received with `EventReader`.
228+
229+
```rust
230+
struct MyEvent {
231+
message: String,
232+
}
233+
234+
fn writer(mut writer: EventWriter<MyEvent>) {
235+
writer.send(MyEvent {
236+
message: "hello!".to_string(),
237+
});
238+
}
239+
240+
fn reader(mut reader: EventReader<MyEvent>) {
241+
for event in reader.iter() {
242+
}
243+
}
244+
```
245+
246+
A minimal set up using events can be seen in [`events.rs`](examples/events.rs).
247+
248+
[bevy]: https://bevyengine.org/
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
use bevy_ecs::prelude::*;
2+
use rand::Rng;
3+
use std::ops::Deref;
4+
5+
// In this example we will simulate a population of entities. In every tick we will:
6+
// 1. spawn a new entity with a certain possibility
7+
// 2. age all entities
8+
// 3. despawn entities with age > 2
9+
//
10+
// To demonstrate change detection, there are some console outputs based on changes in
11+
// the EntityCounter resource and updated Age components
12+
fn main() {
13+
// Create a new empty World to hold our Entities, Components and Resources
14+
let mut world = World::new();
15+
16+
// Add the counter resource to remember how many entities where spawned
17+
world.insert_resource(EntityCounter { value: 0 });
18+
19+
// Create a new Schedule, which defines an execution strategy for Systems
20+
let mut schedule = Schedule::default();
21+
// Create a Stage to add to our Schedule. Each Stage in a schedule runs all of its systems
22+
// before moving on to the next Stage
23+
let mut update = SystemStage::parallel();
24+
25+
// Add systems to the Stage to execute our app logic
26+
// We can label our systems to force a specific run-order between some of them
27+
update.add_system(spawn_entities.system().label(SimulationSystem::Spawn));
28+
update.add_system(
29+
print_counter_when_changed
30+
.system()
31+
.after(SimulationSystem::Spawn),
32+
);
33+
update.add_system(age_all_entities.system().label(SimulationSystem::Age));
34+
update.add_system(remove_old_entities.system().after(SimulationSystem::Age));
35+
update.add_system(print_changed_entities.system().after(SimulationSystem::Age));
36+
// Add the Stage with our systems to the Schedule
37+
schedule.add_stage("update", update);
38+
39+
// Simulate 10 frames in our world
40+
for iteration in 1..=10 {
41+
println!("Simulating frame {}/10", iteration);
42+
schedule.run(&mut world);
43+
}
44+
}
45+
46+
// This struct will be used as a Resource keeping track of the total amount of spawned entities
47+
#[derive(Debug)]
48+
struct EntityCounter {
49+
pub value: i32,
50+
}
51+
52+
// This struct represents a Component and holds the age in frames of the entity it gets assigned to
53+
#[derive(Default, Debug)]
54+
struct Age {
55+
frames: i32,
56+
}
57+
58+
// System labels to enforce a run order of our systems
59+
#[derive(SystemLabel, Debug, Clone, PartialEq, Eq, Hash)]
60+
enum SimulationSystem {
61+
Spawn,
62+
Age,
63+
}
64+
65+
// This system randomly spawns a new entity in 60% of all frames
66+
// The entity will start with an age of 0 frames
67+
// If an entity gets spawned, we increase the counter in the EntityCounter resource
68+
fn spawn_entities(mut commands: Commands, mut entity_counter: ResMut<EntityCounter>) {
69+
if rand::thread_rng().gen_bool(0.6) {
70+
let entity_id = commands.spawn().insert(Age::default()).id();
71+
println!(" spawning {:?}", entity_id);
72+
entity_counter.value += 1;
73+
}
74+
}
75+
76+
// This system prints out changes in our entity collection
77+
// For every entity that just got the Age component added we will print that it's the
78+
// entities first birthday. These entities where spawned in the previous frame.
79+
// For every entity with a changed Age component we will print the new value.
80+
// In this example the Age component is changed in every frame, so we don't actually
81+
// need the `Changed` here, but it is still used for the purpose of demonstration.
82+
fn print_changed_entities(
83+
entity_with_added_component: Query<Entity, Added<Age>>,
84+
entity_with_mutated_component: Query<(Entity, &Age), Changed<Age>>,
85+
) {
86+
for entity in entity_with_added_component.iter() {
87+
println!(" {:?} has it's first birthday!", entity);
88+
}
89+
for (entity, value) in entity_with_mutated_component.iter() {
90+
println!(" {:?} is now {:?} frames old", entity, value);
91+
}
92+
}
93+
94+
// This system iterates over all entities and increases their age in every frame
95+
fn age_all_entities(mut entities: Query<&mut Age>) {
96+
for mut age in entities.iter_mut() {
97+
age.frames += 1;
98+
}
99+
}
100+
101+
// This system iterates over all entities in every frame and despawns entities older than 2 frames
102+
fn remove_old_entities(mut commands: Commands, entities: Query<(Entity, &Age)>) {
103+
for (entity, age) in entities.iter() {
104+
if age.frames > 2 {
105+
println!(" despawning {:?} due to age > 2", entity);
106+
commands.entity(entity).despawn();
107+
}
108+
}
109+
}
110+
111+
// This system will print the new counter value everytime it was changed since
112+
// the last execution of the system.
113+
fn print_counter_when_changed(entity_counter: Res<EntityCounter>) {
114+
if entity_counter.is_changed() {
115+
println!(
116+
" total number of entities spawned: {}",
117+
entity_counter.deref().value
118+
);
119+
}
120+
}

0 commit comments

Comments
 (0)