flecs_ecs 0.2.2

Rust API for the C/CPP flecs ECS library <https://github.com/SanderMertens/flecs>
Documentation
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
//! Builder for constructing complex queries with additional conditions and configuration.
//!
//!
//! The [`QueryBuilder`] provides a fluent interface for building queries incrementally,
//! allowing you to add terms, configure caching behavior, and apply advanced filtering
//! before creating the final [`Query`] object.
//!
//! > **For comprehensive documentation**, see the [Flecs Query Manual](https://www.flecs.dev/flecs/md_docs_2Queries.html)
//!
//! > **See also**: The `query!` macro from the [DSL module](crate::dsl) provides
//! > a declarative syntax for creating queries that closely mirrors the Flecs Query Language.
//!
//! # Quick Start
//!
//! ```
//! # use flecs_ecs::prelude::*;
//! #
//! # #[derive(Component)]
//! # struct Position { x: f32, y: f32 }
//! #
//! # #[derive(Component)]
//! # struct Velocity { x: f32, y: f32 }
//! #
//! # #[derive(Component)]
//! # struct Enemy;
//! #
//! # #[derive(Component)]
//! # struct Mars;
//! #
//! # #[derive(Component)]
//! # struct Planet;
//! # let world = World::new();
//!
//! // Build a query with additional conditions
//! let query = world
//!     .query::<(&Position, &Velocity)>()
//!     .with(Enemy)
//!     .without((Planet, Mars))
//!     .build();
//!
//! query.each(|(pos, vel)| {
//!     // Only processes enemies with Position and Velocity, but not those who are on Mars
//! });
//! ```
//!
//! # Builder vs Direct Creation
//!
//! There are two ways to create queries:
//!
//! ## Direct Creation (Simple Queries)
//!
//! Use [`World::new_query()`] for simple queries with just component types:
//!
//! ```
//! # use flecs_ecs::prelude::*;
//! # #[derive(Component)] struct Position { x: f32, y: f32 }
//! # #[derive(Component)] struct Velocity { x: f32, y: f32 }
//! # let world = World::new();
//! // Fast and simple - creates uncached query immediately
//! let query = world.new_query::<(&Position, &Velocity)>();
//! ```
//!
//! ## Builder Pattern (Complex Queries)
//!
//! Use [`World::query()`] to get a builder when you need:
//! - Additional filtering with `with()` / `without()`
//! - Relationship conditions
//! - Cache configuration
//! - Ordering or grouping
//! - Variables and query DSL features
//!
//! ```
//! # use flecs_ecs::prelude::*;
//! # #[derive(Component)] struct Position { x: f32, y: f32 }
//! # #[derive(Component)] struct Velocity { x: f32, y: f32 }
//! # #[derive(Component)] struct Enemy;
//! # let world = World::new();
//! let query = world
//!     .query::<(&Position, &Velocity)>()
//!     .with(Enemy)
//!     .set_cache_kind(QueryCacheKind::Auto)
//!     .build();
//! ```
//!
//! # Common Builder Methods
//!
//! ## Adding Terms with `with()`
//!
//! Add components that must be present but aren't needed in the iteration:
//!
//! ```
//! # use flecs_ecs::prelude::*;
//! # #[derive(Component)] struct Position { x: f32, y: f32 }
//! # #[derive(Component)] struct Enemy;
//! # let world = World::new();
//! // Query Position but only for entities with Enemy tag
//! let query = world.query::<&Position>().with(Enemy).build();
//!
//! // Enemy tag is required but not part of iteration
//! query.each(|pos| {
//!     println!("Enemy at ({}, {})", pos.x, pos.y);
//! });
//! ```
//!
//! ## Filtering with `without()`
//!
//! Exclude entities that have certain components:
//!
//! ```
//! # use flecs_ecs::prelude::*;
//! # #[derive(Component)] struct Position { x: f32, y: f32 }
//! # #[derive(Component)] struct Dead;
//! # let world = World::new();
//! // Query Position but exclude dead entities
//! let query = world.query::<&Position>().without(&Dead).build();
//!
//! query.each(|pos| {
//!     println!("Living entity at ({}, {})", pos.x, pos.y);
//! });
//! ```
//!
//! ## Relationship Queries
//!
//! Query entities based on their relationships:
//!
//! ```
//! # use flecs_ecs::prelude::*;
//! # #[derive(Component)] struct Position { x: f32, y: f32 }
//! #[derive(Component)]
//! struct Likes;
//!
//! # let world = World::new();
//! let apples = world.entity_named("Apples");
//!
//! // Query entities that like apples
//! let query = world.query::<&Position>().with((Likes, apples)).build();
//! ```
//!
//! ## Cache Control
//!
//! Configure query caching behavior:
//!
//! ```
//! # use flecs_ecs::prelude::*;
//! # #[derive(Component)] struct Position { x: f32, y: f32 }
//! # let world = World::new();
//! // Explicitly set cache kind
//! let cached = world
//!     .query::<&Position>()
//!     .set_cache_kind(QueryCacheKind::Auto)
//!     .build();
//!
//! let uncached = world
//!     .query::<&Position>()
//!     .set_cache_kind(QueryCacheKind::None)
//!     .build();
//! ```
//!
//! # Advanced Features
//!
//! ## Variables
//!
//! Use query variables to match related entities:
//!
//! ```
//! # use flecs_ecs::prelude::*;
//! #[derive(Component)]
//! struct Eats;
//!
//! #[derive(Component)]
//! struct Healthy;
//!
//! # let world = World::new();
//! // Find entities that eat healthy food
//! let query = world
//!     .query::<()>()
//!     .with((Eats, "$food"))
//!     .with(Healthy)
//!     .set_src("$food")
//!     .build();
//!
//! let food_var = query.find_var("food").unwrap();
//!
//! query.each_iter(|it, _, _| {
//!     println!("Eats {}", it.get_var(food_var).name());
//! });
//! ```
//!
//! ## Optional Components
//!
//! Match components that may or may not be present:
//!
//! ```
//! # use flecs_ecs::prelude::*;
//! # #[derive(Component)] struct Position { x: f32, y: f32 }
//! # #[derive(Component)] struct Health(i32);
//! # let world = World::new();
//! let query = world.query::<(&Position, Option<&Health>)>().build();
//!
//! query.each(|(pos, health)| {
//!     if let Some(health) = health {
//!         println!("Entity at ({}, {}) has {} health", pos.x, pos.y, health.0);
//!     }
//! });
//! ```
//!
//! ## Ordering
//!
//! Sort query results by component values:
//!
//! ```
//! # use flecs_ecs::prelude::*;
//! # #[derive(Component)] struct Position { x: f32, y: f32 }
//! # let world = World::new();
//! let query = world
//!     .query::<&Position>()
//!     .order_by::<Position>(|_e1, p1: &Position, _e2, p2: &Position| {
//!         if p1.x < p2.x {
//!             -1
//!         } else if p1.x > p2.x {
//!             1
//!         } else {
//!             0
//!         }
//!     })
//!     .build();
//!
//! // Entities are now iterated in order of Position.x
//! query.each(|pos| {
//!     println!("Position: ({}, {})", pos.x, pos.y);
//! });
//! ```
//!
//! ## Grouping
//!
//! Group query results by relationship target for better cache locality.
//! This groups entities that share the same relationship target together:
//!
//! ```
//! # use flecs_ecs::prelude::*;
//! # #[derive(Component)] struct Position { x: f32, y: f32 }
//! #[derive(Component)]
//! struct Group;
//!
//! #[derive(Component)]
//! struct Team1;
//!
//! #[derive(Component)]
//! struct Team2;
//!
//! # let world = World::new();
//! // Create a query grouped by the Group relationship
//! let query = world.query::<&Position>().group_by(Group).build();
//!
//! // Create entities with different group targets
//! world
//!     .entity()
//!     .add((Group, Team1))
//!     .set(Position { x: 1.0, y: 1.0 });
//!
//! world
//!     .entity()
//!     .add((Group, Team2))
//!     .set(Position { x: 2.0, y: 2.0 });
//!
//! // Entities with the same (Group, Target) are iterated together
//! query.run(|mut it| {
//!     while it.next() {
//!         let world = it.world();
//!         let group = world.entity_from_id(it.group_id());
//!         println!("Group: {}", group.name());
//!     }
//! });
//! ```
//!
//! # Performance Considerations
//!
//! ## Cached vs Uncached
//!
//! - **Cached queries** ([`QueryCacheKind::Auto`] or [`QueryCacheKind::All`]):
//!   - Faster iteration (very fast)
//!   - Slower creation
//!   - Higher memory usage
//!   - Best for: Queries evaluated every frame (e.g. systems)
//!
//! - **Uncached queries** ([`QueryCacheKind::None`]):
//!   - Faster creation
//!   - Slower iteration
//!   - Minimal memory overhead
//!   - Best for: Ad-hoc queries, one-time lookups
//!
//! # See Also
//!
//! - [`Query`] for the resulting query object
//! - [`World::query()`] to create a query builder
//! - [`World::new_query()`] to create queries directly
//! - [Query module documentation](crate::core::query) for iteration examples
//! - [Flecs Query Manual](https://www.flecs.dev/flecs/md_docs_2Queries.html) for comprehensive documentation
//!
//! [`QueryCacheKind::Auto`]
//! [`QueryCacheKind::All`]
//! [`QueryCacheKind::None`]

use core::ffi::c_void;
use core::mem::ManuallyDrop;

use crate::core::internals::*;
use crate::core::*;
use crate::sys;

#[cfg(feature = "std")]
extern crate std;

extern crate alloc;
use alloc::{format, vec::Vec};
use flecs_ecs_derive::extern_abi;

/// Builder for constructing complex [`Query`] objects.
///
/// `QueryBuilder` provides a fluent interface for incrementally building queries with
/// additional terms, filters, and configuration options. It's created via [`World::query()`]
/// and finalized with [`.build()`](QueryBuilder::build).
///
/// # Basic Usage
///
/// ```
/// use flecs_ecs::prelude::*;
///
/// #[derive(Component)]
/// struct Position {
///     x: f32,
///     y: f32,
/// }
///
/// #[derive(Component)]
/// struct Velocity {
///     x: f32,
///     y: f32,
/// }
///
/// #[derive(Component)]
/// struct Enemy;
///
/// let world = World::new();
///
/// // Build a query with additional filtering
/// let query = world.query::<(&Position, &Velocity)>().with(Enemy).build();
///
/// query.each(|(pos, vel)| {
///     // Only processes enemies with Position and Velocity
/// });
/// ```
///
/// # Common Patterns
///
/// ## Returning from Functions
///
/// When returning queries from functions, use `'static` lifetime for component types
/// to ensure they outlive the function scope:
///
/// ```
/// use flecs_ecs::prelude::*;
///
/// #[derive(Component)]
/// struct Foo(u8);
///
/// fn foo_query(world: &World) -> Query<&'static Foo> {
///     world.query::<&Foo>().build()
/// }
///
/// let world = World::new();
/// let query = foo_query(&world);
/// query.each(|foo| { /* ... */ });
/// ```
///
/// ## Use in Systems
///
/// Queries can be stored and reused within systems:
///
/// ```
/// use flecs_ecs::prelude::*;
///
/// #[derive(Component)]
/// struct Foo(u8);
///
/// fn plugin(world: &World) {
///     let foos = world.query::<&Foo>().build();
///
///     world.system::<()>().each(move |_| {
///         foos.each(|foo| {
///             // Reuse query each frame
///         });
///     });
/// }
/// ```
///
/// # Builder Methods
///
/// The builder provides many methods for configuring queries. See the
/// [module documentation](crate::core::query_builder) for comprehensive examples of:
///
/// - [`with()`](QueryBuilder::with) / [`without()`](QueryBuilder::without) - Add/exclude components
/// - [`set_cache_kind()`](QueryBuilder::set_cache_kind) - Control caching behavior
/// - [`order_by()`](QueryBuilder::order_by) - Sort results
/// - [`group_by()`](QueryBuilder::group_by) - Group results
///
/// # See Also
///
/// - [Module documentation](crate::core::query_builder) for detailed examples
/// - [`Query`] for the resulting query object
/// - [`World::query()`] to create a builder
/// - [`World::new_query()`] for simple queries without a builder
pub struct QueryBuilder<'a, T>
where
    T: QueryTuple,
{
    pub(crate) desc: sys::ecs_query_desc_t,
    pub(crate) term_builder: TermBuilder,
    world: WorldRef<'a>,
    _phantom: core::marker::PhantomData<T>,
}

bitflags::bitflags! {
    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
    pub struct QueryFlags: u32 {
        const MatchPrefab = sys::EcsQueryMatchPrefab;
        const MatchDisabled = sys::EcsQueryMatchDisabled;
        const MatchEmptyTables = sys::EcsQueryMatchEmptyTables;
        const AllowUnresolvedByName = sys::EcsQueryAllowUnresolvedByName;
        const TableOnly = sys::EcsQueryTableOnly;
    }
}

bitflags::bitflags! {
    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
    pub struct ObserverFlags: u32 {
        const BypassQuery = sys::EcsObserverBypassQuery;
        const YieldOnCreate = sys::EcsObserverYieldOnCreate;
        const YieldOnDelete = sys::EcsObserverYieldOnDelete;
    }
}

impl<'a, T> QueryBuilder<'a, T>
where
    T: QueryTuple,
{
    /// Create a new query builder
    ///
    /// # Arguments
    ///
    /// * `world` - The world to create the observer in
    pub fn new(world: &'a World) -> Self {
        let mut obj = Self {
            desc: Default::default(),
            world: world.world(),
            term_builder: Default::default(),
            _phantom: core::marker::PhantomData,
        };

        T::populate(&mut obj);

        obj
    }

    /// Create a new query builder with a name
    ///
    /// # Arguments
    ///
    /// * `world` - The world to create the observer in
    /// * `name` - The name of the observer
    pub fn new_named(world: &'a World, name: &str) -> Self {
        let name = compact_str::format_compact!("{}\0", name);

        let desc = Default::default();

        let mut obj = Self {
            desc,
            term_builder: Default::default(),
            world: world.world(),
            _phantom: core::marker::PhantomData,
        };

        let entity_desc = sys::ecs_entity_desc_t {
            name: name.as_ptr() as *const _,
            sep: SEPARATOR.as_ptr(),
            root_sep: SEPARATOR.as_ptr(),
            ..Default::default()
        };

        obj.desc.entity = unsafe { sys::ecs_entity_init(world.world_ptr_mut(), &entity_desc) };

        T::populate(&mut obj);
        obj
    }

    /// Create a new query builder from an existing descriptor
    ///
    /// # Arguments
    ///
    /// * `world` - The world to create the observer in
    /// * `desc` - The descriptor to create the observer from
    #[allow(dead_code)] // this may be used in the future
    pub(crate) fn new_from_desc(
        world: impl WorldProvider<'a>,
        desc: &mut sys::ecs_query_desc_t,
    ) -> Self {
        Self {
            desc: *desc,
            term_builder: Default::default(),
            world: world.world(),
            _phantom: core::marker::PhantomData,
        }
    }

    /// Create a new query builder from an existing descriptor with a term index
    ///
    /// # Arguments
    ///
    /// * `world` - The world to create the observer in
    /// * `desc` - The descriptor to create the observer from
    /// * `term_index` - The index of the term to create the observer from
    #[expect(dead_code, reason = "possibly used in the future")]
    pub(crate) fn new_from_desc_term_index(
        world: &'a World,
        desc: &mut sys::ecs_query_desc_t,
        term_index: i32,
    ) -> Self {
        let mut obj = Self {
            desc: *desc,
            term_builder: TermBuilder {
                current_term_index: term_index,
                next_term_index: term_index,
                expr_count: 0,
                term_ref_mode: TermRefMode::Src,
                str_ptrs_to_free: Vec::new(),
            },
            world: world.world(),
            _phantom: core::marker::PhantomData,
        };

        T::populate(&mut obj);
        obj
    }
}

#[doc(hidden)]
impl<'a, T: QueryTuple> internals::QueryConfig<'a> for QueryBuilder<'a, T> {
    #[inline(always)]
    fn term_builder(&self) -> &TermBuilder {
        &self.term_builder
    }

    #[inline(always)]
    fn term_builder_mut(&mut self) -> &mut TermBuilder {
        &mut self.term_builder
    }

    #[inline(always)]
    fn query_desc(&self) -> &sys::ecs_query_desc_t {
        &self.desc
    }

    #[inline(always)]
    fn query_desc_mut(&mut self) -> &mut sys::ecs_query_desc_t {
        &mut self.desc
    }

    #[inline(always)]
    fn count_generic_terms(&self) -> i32 {
        T::COUNT
    }
}

impl<'a, T: QueryTuple> TermBuilderImpl<'a> for QueryBuilder<'a, T> {}

impl<'a, T: QueryTuple> QueryBuilderImpl<'a> for QueryBuilder<'a, T> {}

impl<'a, T: QueryTuple> WorldProvider<'a> for QueryBuilder<'a, T> {
    fn world(&self) -> WorldRef<'a> {
        self.world
    }
}

impl<'a, T> Builder<'a> for QueryBuilder<'a, T>
where
    T: QueryTuple,
{
    type BuiltType = Query<T>;

    /// Build the `query_builder` into an query
    ///
    /// # Returns
    ///
    /// The built query
    ///
    /// # Example
    ///
    /// * how to return a query / query builder from a function see example in [`QueryBuilder`]
    fn build(&mut self) -> Self::BuiltType {
        let world = self.world;
        let query = Query::<T>::new_from_desc(world, &mut self.desc);
        for s in self.term_builder.str_ptrs_to_free.iter_mut() {
            unsafe { ManuallyDrop::drop(s) };
        }
        self.term_builder.str_ptrs_to_free.clear();
        query
    }
}

impl<'a, T: QueryTuple> QueryBuilder<'a, T> {
    /// Attempts to build the query, returning `None` if the query is invalid.
    ///
    /// This is a fallible version of [`build()`](Builder::build) that returns `None`
    /// instead of panicking when query creation fails. Query creation can fail for
    /// several reasons, most commonly:
    /// - Invalid query expression syntax (when using `expr()`)
    /// - Malformed query terms
    ///
    /// # Returns
    ///
    /// * `Some(Query<T>)` - Successfully created query
    /// * `None` - Query creation failed
    ///
    /// # Example
    ///
    /// ```
    /// use flecs_ecs::prelude::*;
    ///
    /// #[derive(Component)]
    /// struct Position { x: f32, y: f32 }
    ///
    /// let world = World::new();
    ///
    /// // Valid query
    /// let valid_query = world.query::<&Position>()
    ///     .try_build();
    /// assert!(valid_query.is_some());
    ///
    /// // Invalid query expression
    /// let invalid_query = world.query::<()>()
    ///     .expr("invalid syntax!!!")
    ///     .try_build();
    /// assert!(invalid_query.is_none());
    /// ```
    ///
    /// # See also
    ///
    /// * [`build()`](Builder::build) - Panicking version that fails fast on invalid queries
    pub fn try_build(&mut self) -> Option<Query<T>> {
        let world = self.world;
        let query = Query::<T>::try_new_from_desc(world, &mut self.desc)?;
        for s in self.term_builder.str_ptrs_to_free.iter_mut() {
            unsafe { ManuallyDrop::drop(s) };
        }
        self.term_builder.str_ptrs_to_free.clear();
        Some(query)
    }
}

//this doesn't work because world ptr gets misaligned
// Assuming some imports and definitions from your previous example, and adding the required ones for this example.
// #[cfg(not(target_family = "wasm"))]
// type GroupByFn = extern "C-unwind" fn(
//     *mut sys::ecs_world_t,
//     *mut sys::ecs_table_t,
//     sys::ecs_id_t,
//     *mut c_void,
// ) -> u64;

// #[cfg(target_family = "wasm")]
// type GroupByFn =
//     extern "C" fn(*mut sys::ecs_world_t, *mut sys::ecs_table_t, sys::ecs_id_t, *mut c_void) -> u64;

// Type definitions for OrderBy function pointers
#[cfg(not(target_family = "wasm"))]
type OrderByFnPtr<T> = extern "C-unwind" fn(Entity, &T, Entity, &T) -> i32;
#[cfg(target_family = "wasm")]
type OrderByFnPtr<T> = extern "C" fn(Entity, &T, Entity, &T) -> i32;

#[cfg(not(target_family = "wasm"))]
type OrderByFnPtrUnsafe = unsafe extern "C-unwind" fn(
    u64,
    *const core::ffi::c_void,
    u64,
    *const core::ffi::c_void,
) -> i32;
#[cfg(target_family = "wasm")]
type OrderByFnPtrUnsafe =
    unsafe extern "C" fn(u64, *const core::ffi::c_void, u64, *const core::ffi::c_void) -> i32;

#[cfg(not(target_family = "wasm"))]
type OrderByFnVoidPtr = extern "C-unwind" fn(Entity, *const c_void, Entity, *const c_void) -> i32;
#[cfg(target_family = "wasm")]
type OrderByFnVoidPtr = extern "C" fn(Entity, *const c_void, Entity, *const c_void) -> i32;

#[cfg(not(target_family = "wasm"))]
type OrderByFnVoidPtrUnsafe = unsafe extern "C-unwind" fn(
    u64,
    *const core::ffi::c_void,
    u64,
    *const core::ffi::c_void,
) -> i32;
#[cfg(target_family = "wasm")]
type OrderByFnVoidPtrUnsafe =
    unsafe extern "C" fn(u64, *const core::ffi::c_void, u64, *const core::ffi::c_void) -> i32;

/// Functions to build a query using terms.
pub trait QueryBuilderImpl<'a>: TermBuilderImpl<'a> {
    /// set the name of the query-like object
    fn named(&mut self, name: &str) -> &mut Self {
        let name = compact_str::format_compact!("{}\0", name);
        let world_ptr = self.world_ptr_mut();

        let entity_desc: sys::ecs_entity_desc_t = sys::ecs_entity_desc_t {
            name: name.as_ptr() as *const _,
            sep: SEPARATOR.as_ptr(),
            root_sep: SEPARATOR.as_ptr(),
            ..core::default::Default::default()
        };
        let entity_field_ref = &mut self.query_desc_mut().entity;
        if *entity_field_ref != 0 {
            unsafe { sys::ecs_delete(world_ptr, *entity_field_ref) };
        }

        *entity_field_ref = unsafe { sys::ecs_entity_init(world_ptr, &entity_desc) };
        self
    }

    /// set querylags
    ///
    /// # Arguments
    ///
    /// * `flags` - the flags to set
    fn query_flags(&mut self, flags: QueryFlags) -> &mut Self {
        self.query_desc_mut().flags |= flags.bits();
        self
    }

    /// Set what cache method to use for the query
    ///
    /// # Arguments
    ///
    /// * `kind` - the cache kind to set
    fn set_cache_kind(&mut self, kind: QueryCacheKind) -> &mut Self {
        self.query_desc_mut().cache_kind = kind as sys::ecs_query_cache_kind_t;
        self
    }

    /// Set the cache method to cached
    fn set_cached(&mut self) -> &mut Self {
        self.set_cache_kind(QueryCacheKind::Auto)
    }

    fn detect_changes(&mut self) -> &mut Self {
        self.query_desc_mut().flags |= sys::EcsQueryDetectChanges;
        self
    }

    /// set expression
    ///
    /// # Arguments
    ///
    /// * `expr` - the expression to set
    fn expr(&mut self, expr: &'a str) -> &mut Self {
        let expr = ManuallyDrop::new(format!("{expr}\0"));
        ecs_assert!(
            *self.expr_count_mut() == 0,
            FlecsErrorCode::InvalidOperation,
            "query_builder::expr() called more than once"
        );

        self.query_desc_mut().expr = expr.as_ptr() as *const _;
        *self.expr_count_mut() += 1;
        self.term_builder_mut().str_ptrs_to_free.push(expr);
        self
    }

    fn with<T>(&mut self, id: T) -> &mut Self
    where
        Access: FromAccessArg<T>,
    {
        let access = <Access as FromAccessArg<T>>::from_access_arg(id, self.world());
        self.term();

        match access.target {
            AccessTarget::Entity(entity) => {
                self.init_current_term(entity);
            }
            AccessTarget::Pair(rel, target) => {
                self.init_current_term(ecs_pair(*rel, *target));
            }
            AccessTarget::Name(name) => {
                self.set_first::<&'static str>(name);
            }
            AccessTarget::PairName(rel, target) => {
                self.set_first::<&'static str>(rel)
                    .set_second::<&'static str>(target);
            }
            AccessTarget::PairEntityName(rel, target) => {
                self.init_current_term(rel);
                self.set_second::<&'static str>(target);
            }
            AccessTarget::PairNameEntity(rel, target) => {
                self.set_first::<&'static str>(rel);
                self.set_second::<Entity>(target);
            }
        }

        match access.mode {
            AccessMode::Read => {
                self.current_term_mut().inout = InOutKind::In as i16;
            }
            AccessMode::ReadWrite => {
                self.current_term_mut().inout = InOutKind::InOut as i16;
            }
            AccessMode::Write => {
                self.current_term_mut().inout = InOutKind::Out as i16;
            }
            _ => {}
        }
        self
    }

    /// set term with enum
    fn with_enum<T: ComponentId + ComponentType<Enum> + EnumComponentInfo>(
        &mut self,
        value: T,
    ) -> &mut Self {
        let enum_id = T::entity_id(self.world());
        let enum_field_id = value.id_variant(self.world());
        self.with((enum_id, enum_field_id))
    }

    /// set term with enum wildcard
    fn with_enum_wildcard<T: ComponentType<Enum> + ComponentId>(&mut self) -> &mut Self
    where
        (crate::core::utility::id::Id<T>, u64): InternalIntoEntity,
    {
        self.with((T::id(), flecs::Wildcard::ID))
    }

    /* Without methods, shorthand for .with(...).not() */

    /// set term without Id
    fn without<T>(&mut self, id: T) -> &mut Self
    where
        Access: FromAccessArg<T>,
    {
        self.with(id).not()
    }

    /// set term without enum
    fn without_enum<T: ComponentId + ComponentType<Enum> + EnumComponentInfo>(
        &mut self,
        value: T,
    ) -> &mut Self {
        self.with_enum(value).not()
    }

    /// set term without enum wildcard
    fn without_enum_wildcard<T: ComponentId + ComponentType<Enum> + EnumComponentInfo>(
        &mut self,
    ) -> &mut Self
    where
        (crate::core::utility::id::Id<T>, u64): InternalIntoEntity,
    {
        self.with_enum_wildcard::<T>().not()
    }

    /// Term notation for more complex query features
    ///
    /// sets the current term to next one in term list
    fn term(&mut self) -> &mut Self {
        let current_index = self.current_term_index();
        let next_index = self.next_term_index();

        if current_index != next_index {
            *self.current_term_index_mut() = next_index;
        }
        *self.next_term_index_mut() = next_index + 1;

        ecs_assert!(
            current_index < sys::FLECS_TERM_COUNT_MAX as i32,
            FlecsErrorCode::InvalidParameter,
            "Maximum number of terms reached in query builder",
        );

        self
    }

    /// Sets the current term to the one with the provided type.
    /// This loops over all terms to find the one with the provided type.
    /// For performance-critical paths, use `term_at(index: u32)` instead.
    fn term_at_type<T: ComponentId>(&mut self) -> &mut Self {
        let term_id = T::entity_id(self.world());
        let world_ptr = self.world_ptr_mut();

        for i in 0..=self.term_builder().next_term_index - 1 {
            let desc = self.query_desc();
            let cur_term = desc.terms[i as usize];
            let cur_term_id = cur_term.id;
            let cur_term_pair = ecs_pair(cur_term.first.id, cur_term.second.id);

            if (term_id == cur_term_id
                || (cur_term_id != 0
                    && term_id == unsafe { sys::ecs_get_typeid(world_ptr, cur_term_id) }))
                || (term_id == cur_term_pair
                    || (cur_term_pair != 0
                        && term_id == unsafe { sys::ecs_get_typeid(world_ptr, cur_term_pair) }))
            {
                return self.term_at(i as u32);
            }
        }

        panic!("term_at_type() called with type that is not in query",);
    }

    /// Sets the current term to the one at the provided index.
    fn term_at(&mut self, index: u32) -> &mut Self {
        ecs_assert!(
            index < sys::FLECS_TERM_COUNT_MAX,
            FlecsErrorCode::InvalidParameter,
            "term_at() called with invalid index"
        );

        self.set_term_ref_mode(TermRefMode::Src);

        *self.current_term_index_mut() = index as i32;

        self
    }

    //flecs_force_build_debug_c || flecs_force_enable_ecs_asserts

    /*
            /** Sets the current term to the one at the provided index and asserts that the type matches.
         */
        template <typename T>
        Base& term_at(int32_t term_index) {
            this->term_at(term_index);
    #if !defined(FLECS_NDEBUG) || defined(FLECS_KEEP_ASSERT)
            flecs::id_t term_id = _::type<T>::id(this->world_v());
            ecs_term_t cur_term = *this->term_;
            ecs_id_t cur_term_id = cur_term.id;
            ecs_id_t cur_term_pair = ecs_pair(cur_term.first.id, cur_term.second.id);

            ecs_assert((term_id == cur_term_id || (cur_term_id != 0 && term_id == ecs_get_typeid(this->world_v(), cur_term_id))) ||
                (term_id == cur_term_pair || (cur_term_pair != 0 && term_id == ecs_get_typeid(this->world_v(), cur_term_pair))),
                ECS_INVALID_PARAMETER, "term type mismatch");
    #endif
            return *this;
        }
         */

    /// Set the current term to the one with the provided id and assert that the type matches.
    /// this does not do the type checking in release unless `flecs_force_build_debug_c` or `flecs_force_enable_ecs_asserts` is enabled.
    fn term_at_checked<T: ComponentId>(&mut self, index: u32) -> &mut Self {
        ecs_assert!(
            index < sys::FLECS_TERM_COUNT_MAX,
            FlecsErrorCode::InvalidParameter,
            "term_at() called with invalid index"
        );

        self.set_term_ref_mode(TermRefMode::Src);

        *self.current_term_index_mut() = index as i32;

        #[cfg(any(
            feature = "flecs_force_build_debug_c",
            feature = "flecs_force_enable_ecs_asserts",
            debug_assertions
        ))]
        {
            let term_id = T::entity_id(self.world());
            let cur_term = self.current_term();
            let cur_term_id = cur_term.id;
            let cur_term_pair = ecs_pair(cur_term.first.id, cur_term.second.id);

            ecs_assert!(
                (term_id == cur_term_id
                    || (cur_term_id != 0
                        && term_id
                            == unsafe { sys::ecs_get_typeid(self.world_ptr_mut(), cur_term_id) }))
                    || (term_id == cur_term_pair
                        || (cur_term_pair != 0
                            && term_id
                                == unsafe {
                                    sys::ecs_get_typeid(self.world_ptr_mut(), cur_term_pair)
                                })),
                FlecsErrorCode::InvalidParameter,
                "term type mismatch"
            );
        }

        self
    }

    /// Set the id as current term and in mode out
    fn write<T>(&mut self, id: T) -> &mut Self
    where
        Access: FromAccessArg<T>,
    {
        self.with(id);
        TermBuilderImpl::write_curr(self)
    }

    /// Set the type as current term and in mode out
    fn write_enum<T: ComponentId + ComponentType<Enum> + EnumComponentInfo>(
        &mut self,
        value: T,
    ) -> &mut Self {
        self.with_enum(value);
        TermBuilderImpl::write_curr(self)
    }

    /// Set the id as current term and in mode in
    fn read<T>(&mut self, id: T) -> &mut Self
    where
        Access: FromAccessArg<T>,
    {
        self.with(id);
        TermBuilderImpl::read_curr(self)
    }

    /// Set the type as current term and in mode in
    fn read_enum<T: ComponentId + ComponentType<Enum> + EnumComponentInfo>(
        &mut self,
        value: T,
    ) -> &mut Self {
        self.with_enum(value);
        TermBuilderImpl::read_curr(self)
    }

    /* scope_open/scope_close shorthand notation. */

    /// Open a scope for the query
    fn scope_open(&mut self) -> &mut Self {
        self.with(flecs::ScopeOpen::ID).entity(0)
    }

    /// Close a scope for the query
    fn scope_close(&mut self) -> &mut Self {
        self.with(flecs::ScopeClose::ID).entity(0)
    }

    /// Sorts the output of a query.
    ///
    /// This enables sorting of entities across matched tables. As a result of this
    /// operation, the order of entities in the matched tables may change.
    /// Resorting occurs when a query iterator is obtained, and only if the table
    /// data has changed.
    ///
    /// If multiple queries that match the same (down)set of tables specify different
    /// sorting functions, resorting is likely to occur every time an iterator is
    /// obtained, potentially slowing down iterations significantly.
    ///
    /// The sorting function will be applied to the specified component. Resorting
    /// only occurs if that component has changed, or when the entity order in the
    /// table changes. If no component is provided, resorting only occurs when
    /// the entity order changes.
    ///
    /// # Type Parameters
    ///
    /// * `T`: The component used to sort.
    ///
    /// # Arguments
    ///
    /// * `compare`: The compare function used to sort the components.
    ///   The signature of the function must be `fn(Entity, &T, Entity, &T) -> i32`.
    fn order_by<T>(&mut self, compare: impl OrderByFn<T>) -> &mut Self
    where
        T: ComponentId,
        Self: QueryBuilderImpl<'a>,
    {
        const {
            assert!(
                !(T::IS_REF || T::IS_MUT),
                "order_by<T> requires T to not be a reference"
            );
        }

        let cmp: sys::ecs_order_by_action_t = Some(unsafe {
            core::mem::transmute::<OrderByFnPtr<T>, OrderByFnPtrUnsafe>(compare.to_extern_fn())
        });

        self.__internal_order_by_id(T::entity_id(self.world()), cmp);
        self
    }

    #[doc(hidden)]
    fn __internal_order_by_id(
        &mut self,
        component: impl Into<Entity>,
        compare: sys::ecs_order_by_action_t,
    ) {
        let desc = self.query_desc_mut();
        desc.order_by_callback = compare;
        desc.order_by = *component.into();
    }

    /// Sorts the output of a query.
    ///
    /// This is similar to `order_by<T>`, but uses a component identifier instead.
    ///
    /// # Arguments
    ///
    /// * `component`: The component used to sort.
    /// * `compare`: The compare function used to sort the components.
    fn order_by_id(
        &mut self,
        component: impl Into<Entity>,
        compare: impl OrderByFnVoid,
    ) -> &mut Self {
        let desc = self.query_desc_mut();
        let cmp: sys::ecs_order_by_action_t = Some(unsafe {
            core::mem::transmute::<OrderByFnVoidPtr, OrderByFnVoidPtrUnsafe>(compare.to_extern_fn())
        });
        desc.order_by_callback = cmp;
        desc.order_by = *component.into();
        self
    }

    /// Group and sort matched tables.
    ///
    /// This function is similar to `order_by`, but instead of sorting individual entities,
    /// it only sorts matched tables. This can be useful if a query needs to enforce a
    /// certain iteration order upon the tables it is iterating, for example by giving
    /// a certain component or tag a higher priority.
    ///
    /// The sorting function assigns a "rank" to each type, which is then used to sort
    /// the tables. Tables with higher ranks will appear later in the iteration.
    ///
    /// Resorting happens when a query iterator is obtained, and only if the set of
    /// matched tables for a query has changed. If table sorting is enabled together
    /// with entity sorting, table sorting takes precedence, and entities will be sorted
    /// within each set of tables that are assigned the same rank.
    ///
    /// # Arguments
    ///
    /// * `component`: The component used to determine the group rank.
    /// * `group_by_action`: Callback that determines group id for table.
    fn group_by_fn(
        &mut self,
        component: impl IntoEntity,
        group_by_action: sys::ecs_group_by_action_t,
    ) -> &mut Self {
        let world = self.world();
        let desc = self.query_desc_mut();
        desc.group_by_callback = group_by_action;
        desc.group_by = *component.into_entity(world);
        self
    }

    /// Group and sort matched tables.
    ///
    /// This is similar to `group_by_default<T>`, but uses a component identifier instead.
    ///
    /// # Arguments
    ///
    /// * `component`: The component used to determine the group rank.
    fn group_by(&mut self, component: impl IntoEntity) -> &mut Self {
        self.group_by_fn(component, None)
    }

    /// Specify context to be passed to the `group_by` function.
    ///
    /// # Arguments
    ///
    /// * `ctx`: Context to pass to the `group_by` function.
    /// * `ctx_free`: Function to clean up the context (called when the query is deleted).
    fn group_by_ctx(&mut self, ctx: *mut c_void, ctx_free: sys::ecs_ctx_free_t) -> &mut Self {
        let desc = self.query_desc_mut();
        desc.group_by_ctx = ctx;
        desc.group_by_ctx_free = ctx_free;
        self
    }

    /// Specify the `on_group_create` action.
    ///
    /// # Arguments
    ///
    /// * `action`: The action to execute when a group is created.
    fn on_group_create(&mut self, action: sys::ecs_group_create_action_t) -> &mut Self {
        let desc = self.query_desc_mut();
        desc.on_group_create = action;
        self
    }

    /// Specify the `on_group_delete` action.
    ///
    /// # Arguments
    ///
    /// * `action`: The action to execute when a group is deleted.
    fn on_group_delete(&mut self, action: sys::ecs_group_delete_action_t) -> &mut Self {
        let desc = self.query_desc_mut();
        desc.on_group_delete = action;
        self
    }
}

pub trait OrderByFn<T>
where
    T: ComponentId,
{
    fn to_extern_fn(self) -> OrderByFnPtr<T>;
}

impl<F, T: ComponentId> OrderByFn<T> for F
where
    F: Fn(Entity, &T, Entity, &T) -> i32,
{
    fn to_extern_fn(self) -> OrderByFnPtr<T> {
        const {
            assert!(core::mem::size_of::<Self>() == 0);
        }
        core::mem::forget(self);

        #[extern_abi]
        fn output<F, T>(e1: Entity, e1_data: &T, e2: Entity, e2_data: &T) -> i32
        where
            F: Fn(Entity, &T, Entity, &T) -> i32,
        {
            (unsafe { core::mem::transmute_copy::<_, F>(&()) })(e1, e1_data, e2, e2_data)
        }

        output::<F, T>
    }
}

pub trait OrderByFnVoid {
    fn to_extern_fn(self) -> OrderByFnVoidPtr;
}

impl<F> OrderByFnVoid for F
where
    F: Fn(Entity, *const c_void, Entity, *const c_void) -> i32,
{
    fn to_extern_fn(self) -> OrderByFnVoidPtr {
        const {
            assert!(core::mem::size_of::<Self>() == 0);
        }
        core::mem::forget(self);

        #[extern_abi]
        fn output<F>(e1: Entity, e1_data: *const c_void, e2: Entity, e2_data: *const c_void) -> i32
        where
            F: Fn(Entity, *const c_void, Entity, *const c_void) -> i32,
        {
            (unsafe { core::mem::transmute_copy::<_, F>(&()) })(e1, e1_data, e2, e2_data)
        }

        output::<F>
    }
}