examples/queries/
query_sorting.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
11fn compare_position(_e1: Entity, p1: &Position, _e2: Entity, p2: &Position) -> i32 {
12    (p1.x > p2.x) as i32 - (p1.x < p2.x) as i32
13}
14
15fn print_query(query: &Query<&Position>) {
16    query.each_entity(|entity, pos| println!("{:?}", pos));
17}
18
19fn main() {
20    let world = World::new();
21
22    // Create entities, set position in random order
23    let entity = world.entity().set(Position { x: 1.0, y: 0.0 });
24    world.entity().set(Position { x: 6.0, y: 0.0 });
25    world.entity().set(Position { x: 2.0, y: 0.0 });
26    world.entity().set(Position { x: 5.0, y: 0.0 });
27    world.entity().set(Position { x: 4.0, y: 0.0 });
28
29    // Create a sorted query
30    let query = world
31        .query::<&Position>()
32        .order_by::<Position>(|_e1, p1: &Position, _e2, p2: &Position| -> i32 {
33            (p1.x > p2.x) as i32 - (p1.x < p2.x) as i32
34        })
35        .build();
36
37    // Create a sorted system
38    let sys = world
39        .system::<&Position>()
40        .order_by(compare_position)
41        .each_entity(|entity, pos| {
42            println!("{:?}", pos);
43        });
44
45    println!();
46    println!("--- First iteration ---");
47    print_query(&query);
48
49    // Change the value of one entity, invalidating the order
50    entity.set(Position { x: 7.0, y: 0.0 });
51
52    // Iterate query again, printed values are still ordered
53    println!();
54    println!("--- Second iteration ---");
55    print_query(&query);
56
57    // Create new entity to show that data is also sorted for new entities
58    world.entity().set(Position { x: 3.0, y: 0.0 });
59
60    // Run system, printed values are ordered
61    println!();
62    println!("--- System iteration ---");
63    sys.run();
64
65    // Output:
66    //
67    //  --- First iteration ---
68    //  Position { x: 1.0, y: 0.0 }
69    //  Position { x: 2.0, y: 0.0 }
70    //  Position { x: 4.0, y: 0.0 }
71    //  Position { x: 5.0, y: 0.0 }
72    //  Position { x: 6.0, y: 0.0 }
73    //
74    //  --- Second iteration ---
75    //  Position { x: 2.0, y: 0.0 }
76    //  Position { x: 4.0, y: 0.0 }
77    //  Position { x: 5.0, y: 0.0 }
78    //  Position { x: 6.0, y: 0.0 }
79    //  Position { x: 7.0, y: 0.0 }
80    //
81    //  --- System iteration ---
82    //  Position { x: 2.0, y: 0.0 }
83    //  Position { x: 3.0, y: 0.0 }
84    //  Position { x: 4.0, y: 0.0 }
85    //  Position { x: 5.0, y: 0.0 }
86    //  Position { x: 6.0, y: 0.0 }
87    //  Position { x: 7.0, y: 0.0 }
88}
89
90#[cfg(feature = "flecs_nightly_tests")]
91#[test]
92fn test() {
93    let output_capture = OutputCapture::capture().unwrap();
94    main();
95    output_capture.test("query_sorting".to_string());
96}