-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblogpost.rs
95 lines (81 loc) · 2.04 KB
/
blogpost.rs
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#![allow(dead_code)]
use stecs::{
prelude::*,
storage::arena::{Arena, ArenaId},
};
// Define an Archetype
#[derive(SplitFields)]
#[split(debug, clone)] // derive Debug and Clone for generated reference types
struct Monster {
position: (f32, f32),
health: f32,
tick: usize,
damage: Option<f32>,
}
#[derive(SplitFields)]
struct Corpse {
#[split(nested)]
monster: Monster,
time: f32,
}
struct World {
monsters: StructOf<Arena<Monster>>,
corpses: StructOf<Arena<Corpse>>,
}
fn main() {
let mut world = World {
monsters: Default::default(),
corpses: Default::default(),
};
// Insert a new Monster
let id = world.monsters.insert(Monster {
position: (0.0, 0.0),
health: 10.0,
tick: 7,
damage: None,
});
// Remove a Monster by id
let monster: Monster = world.monsters.remove(id).unwrap();
world.monsters.insert(monster);
world.monsters.insert(Monster {
position: (1.0, 3.0),
health: 5.0,
tick: 5,
damage: Some(1.0),
});
world.corpses.insert(Corpse {
monster: Monster {
position: (-5.0, 0.0),
health: 0.0,
tick: 10,
damage: None,
},
time: 5.0,
});
// Query monsters' positions and damage (only Some variants)
for (id, position, damage) in query!(world.monsters, (id, &mut position, &damage.Get.Some)) {
println!("[{:?}] at {:?}, dealing {} damage", id, position, damage);
}
// Querying into a struct
// 1. define the struct
#[derive(Debug)]
struct MonsterRef<'a> {
id: ArenaId,
position: &'a (f32, f32),
damage: &'a f32,
}
// 2. query
for monster in query!(
world.monsters,
MonsterRef {
id,
position,
damage: &damage.Get.Some,
}
) {
println!("{:?}", monster);
}
for (time, position) in query!(world.corpses, (&time, &monster.position)) {
println!("{} - {:?}", time, position)
}
}