examples/observers/observer_monitor.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// A monitor observer triggers when an entity starts/stop matching the observer
18// query. The observer communicates whether an entity is "entering/leaving" the
19// monitor by setting ecs_iter_t::event to EcsOnAdd (for entering) or
20// EcsOnRemove (for leaving).
21//
22// To specify that an observer is a monitor observer, the EcsMonitor tag must be
23// provided as event. No additional event kinds should be provided for a monitor
24// observer.
25
26fn main() {
27 let world = World::new();
28
29 // Create observer for custom event
30 world
31 .observer::<flecs::Monitor, (&Position, &Velocity)>()
32 .each_iter(|it, index, (_pos, _vel)| {
33 if it.event() == flecs::OnAdd::ID {
34 println!(
35 " - Enter: {}: {}",
36 it.event_id().to_str(),
37 it.entity(index).name()
38 );
39 } else if it.event() == flecs::OnRemove::ID {
40 println!(
41 " - Leave: {}: {}",
42 it.event_id().to_str(),
43 it.entity(index).name()
44 );
45 }
46 });
47
48 // Create entity
49 let entity = world.entity_named("e");
50
51 // This does not yet trigger the monitor, as the entity does not yet match.
52 entity.set(Position { x: 10.0, y: 20.0 });
53
54 // This triggers the monitor with EcsOnAdd, as the entity now matches.
55 entity.set(Velocity { x: 1.0, y: 2.0 });
56
57 // This triggers the monitor with EcsOnRemove, as the entity no longer matches.
58 entity.remove(Position::id());
59
60 // Output:
61 // - Enter: Velocity: e
62 // - Leave: Position: e
63}
64
65#[cfg(feature = "flecs_nightly_tests")]
66#[test]
67fn test() {
68 let output_capture = OutputCapture::capture().unwrap();
69 main();
70 output_capture.test("observer_monitor".to_string());
71}