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
use std::{
any::{Any, TypeId},
fmt::Display,
};
use edict::{component::Component, query::Entities, world::World};
#[derive(Component)]
#[edict(borrow(dyn Display))]
struct A;
impl Display for A {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("A")
}
}
#[derive(Component)]
#[edict(borrow(dyn Display))]
struct B;
impl Display for B {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("B")
}
}
fn main() {
let mut world = World::new();
// Spawn pair of entities.
let _ = world.spawn((A,));
let _ = world.spawn((B,));
// Spawn entity with both.
let _ = world.spawn((A, B));
// Borrow any component that exposes `Display` trait.
// Skips entities without such component.
for display in world.new_view().borrow_any_mut::<dyn Display + Send>() {
println!("{}", display);
}
// Borrow component with specific `TypeId` as `Any` trait object.
// Current behavior is to panic if component with that type id is found
// and it doesn't exposes `Any` trait.
for a in world
.new_view()
.borrow_one::<dyn Any + Sync>(TypeId::of::<A>())
.iter()
{
println!("{}", (a as &dyn Any).downcast_ref::<A>().unwrap());
}
// Borrow all components that expose `Display` trait.
// This query yields vector of `&dyn Display` trait objects for each entity.
// Current behavior is to skip entities with no such components.
for (e, a) in world
.view::<Entities>()
.borrow_all::<dyn Display + Sync>()
.iter()
{
print!("{}", e);
for a in a {
print!(" {}", a);
}
println!();
}
}