examples/systems/
system_custom_runner.rs

1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4
5#[derive(Debug, Component)]
6pub struct Position {
7    pub x: f32,
8    pub y: f32,
9}
10
11#[derive(Debug, Component)]
12pub struct Velocity {
13    pub x: f32,
14    pub y: f32,
15}
16
17// Systems can be created with a custom run function that takes control over the
18// entire iteration. By  a system is invoked once per matched table,
19// which means the function can be called multiple times per frame. In some
20// cases that's inconvenient, like when a system has things it needs to do only
21// once per frame. For these use cases, the run callback can be used which is
22// called once per frame per system.
23
24fn main() {
25    let world = World::new();
26
27    let system = world
28        .system::<(&mut Position, &Velocity)>()
29        // Forward each result from the run callback to the each callback.
30        .run_each_entity(
31            |mut iter| {
32                println!("Move begin");
33
34                while iter.next() {
35                    iter.each();
36                }
37
38                println!("Move end");
39            },
40            |e, (pos, vel)| {
41                pos.x += vel.x;
42                pos.y += vel.y;
43                println!("{}: {{ {}, {} }}", e.name(), pos.x, pos.y);
44            },
45        );
46
47    // Create a few test entities for a Position, Velocity query
48    world
49        .entity_named("e1")
50        .set(Position { x: 10.0, y: 20.0 })
51        .set(Velocity { x: 1.0, y: 2.0 });
52
53    world
54        .entity_named("e2")
55        .set(Position { x: 10.0, y: 20.0 })
56        .set(Velocity { x: 3.0, y: 4.0 });
57
58    // This entity will not match as it does not have Position, Velocity
59    world.entity_named("e3").set(Position { x: 10.0, y: 20.0 });
60
61    // Run the system
62    system.run();
63
64    // Output:
65    //  Move begin
66    //  e1: {11, 22}
67    //  e2: {13, 24}
68    //  Move end
69}
70
71#[cfg(feature = "flecs_nightly_tests")]
72#[test]
73fn test() {
74    let output_capture = OutputCapture::capture().unwrap();
75    main();
76    output_capture.test("system_custom_runner".to_string());
77}