summaryrefslogtreecommitdiff
path: root/ecs/examples/component_events.rs
blob: 4e7335f9883b870757e191b2833dab40f6c0468a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use ecs::actions::Actions;
use ecs::component::Component;
use ecs::event::component::{Changed, Removed};
use ecs::pair::Pair;
use ecs::phase::UPDATE;
use ecs::system::observer::Observe;
use ecs::{Component, Query, World};

#[derive(Debug, Component)]
struct CheeseCrumbs
{
    cnt: usize,
}

#[derive(Debug, Component)]
struct Cheese
{
    name: &'static str,
}

fn eat_cheese(query: Query<(&Cheese, &mut CheeseCrumbs)>, mut actions: Actions)
{
    for (cheese_ent_id, (_, mut cheese_crumbs)) in query.iter_with_euids() {
        println!("Eating cheese!");

        cheese_crumbs.cnt += 40;
        cheese_crumbs.set_changed();

        actions.remove_components(cheese_ent_id, [Cheese::id()]);
    }
}

fn on_cheese_removed(observe: Observe<Pair<Removed, Cheese>>)
{
    for evt_match in &observe {
        let ent = evt_match.get_entity().unwrap();

        let cheese = ent.get::<Cheese>().unwrap();

        println!("{} cheese was eaten", cheese.name);
    }
}

fn on_cheese_crumbs_changed(observe: Observe<Pair<Changed, CheeseCrumbs>>)
{
    for evt_match in &observe {
        let ent = evt_match.get_entity().unwrap();

        let cheese_crumbs = ent.get::<CheeseCrumbs>().unwrap();

        println!("Cheese crumbs count changed to {}", cheese_crumbs.cnt);
    }
}

fn main()
{
    let mut world = World::new();

    world.register_system(*UPDATE, eat_cheese);
    world.register_observer(on_cheese_removed);
    world.register_observer(on_cheese_crumbs_changed);

    world.create_entity((Cheese { name: "Brie" }, CheeseCrumbs { cnt: 0 }));
    world.create_entity((Cheese { name: "Parmesan" }, CheeseCrumbs { cnt: 0 }));
    world.create_entity((Cheese { name: "Gouda" }, CheeseCrumbs { cnt: 0 }));

    world.step();
}