examples/queries/query_component_inheritance.rs
1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4// This example shows how queries can be used to match simple inheritance trees.
5
6#[derive(Component)]
7struct Unit;
8
9#[derive(Component)]
10struct CombatUnit;
11
12#[derive(Component)]
13struct MeleeUnit;
14
15#[derive(Component)]
16struct RangedUnit;
17
18#[derive(Component)]
19struct Warrior;
20
21#[derive(Component)]
22struct Wizard;
23
24#[derive(Component)]
25struct Marksman;
26
27#[derive(Component)]
28struct BuilderX;
29
30fn main() {
31 let world = World::new();
32
33 // Make the ECS aware of the inheritance relationships. Note that IsA
34 // relationship used here is the same as in the prefab example.
35 world.component::<CombatUnit>().is_a::<Unit>();
36 world.component::<MeleeUnit>().is_a::<CombatUnit>();
37 world.component::<RangedUnit>().is_a::<CombatUnit>();
38
39 world.component::<Warrior>().is_a::<MeleeUnit>();
40 world.component::<Wizard>().is_a::<RangedUnit>();
41 world.component::<Marksman>().is_a::<RangedUnit>();
42 world.component::<BuilderX>().is_a::<Unit>();
43
44 // Create a few units
45 world.entity_named("warrior_1").add::<Warrior>();
46 world.entity_named("warrior_2").add::<Warrior>();
47
48 world.entity_named("marksman_1").add::<Marksman>();
49 world.entity_named("marksman_2").add::<Marksman>();
50
51 world.entity_named("wizard_1").add::<Wizard>();
52 world.entity_named("wizard_2").add::<Wizard>();
53
54 world.entity_named("builder_1").add::<BuilderX>();
55 world.entity_named("builder_2").add::<BuilderX>();
56
57 // Create a rule to find all ranged units
58 let r = world.query::<&RangedUnit>().build();
59
60 // Iterate the rule
61 r.each_entity(|e, rangedunit| {
62 println!("Unit {} found", e.name());
63 });
64
65 // Output:
66 // Unit wizard_1 found
67 // Unit wizard_2 found
68 // Unit marksman_1 found
69 // Unit marksman_2 found
70}
71
72#[cfg(feature = "flecs_nightly_tests")]
73#[test]
74fn test() {
75 let output_capture = OutputCapture::capture().unwrap();
76 main();
77 output_capture.test("query_component_inheritance".to_string());
78}