-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
mod.rs
1749 lines (1500 loc) · 52.1 KB
/
mod.rs
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
//! Tools for controlling behavior in an ECS application.
//!
//! Systems define how an ECS based application behaves.
//! Systems are added to a [`Schedule`](crate::schedule::Schedule), which is then run.
//! A system is usually written as a normal function, which is automatically converted into a system.
//!
//! System functions can have parameters, through which one can query and mutate Bevy ECS state.
//! Only types that implement [`SystemParam`] can be used, automatically fetching data from
//! the [`World`].
//!
//! System functions often look like this:
//!
//! ```
//! # use bevy_ecs::prelude::*;
//! #
//! # #[derive(Component)]
//! # struct Player { alive: bool }
//! # #[derive(Component)]
//! # struct Score(u32);
//! # #[derive(Resource)]
//! # struct Round(u32);
//! #
//! fn update_score_system(
//! mut query: Query<(&Player, &mut Score)>,
//! mut round: ResMut<Round>,
//! ) {
//! for (player, mut score) in &mut query {
//! if player.alive {
//! score.0 += round.0;
//! }
//! }
//! round.0 += 1;
//! }
//! # bevy_ecs::system::assert_is_system(update_score_system);
//! ```
//!
//! # System ordering
//!
//! By default, the execution of systems is parallel and not deterministic.
//! Not all systems can run together: if a system mutably accesses data,
//! no other system that reads or writes that data can be run at the same time.
//! These systems are said to be **incompatible**.
//!
//! The relative order in which incompatible systems are run matters.
//! When this is not specified, a **system order ambiguity** exists in your schedule.
//! You can **explicitly order** systems:
//!
//! - by calling the `.before(this_system)` or `.after(that_system)` methods when adding them to your schedule
//! - by adding them to a [`SystemSet`], and then using `.configure_sets(ThisSet.before(ThatSet))` syntax to configure many systems at once
//! - through the use of `.add_systems((system_a, system_b, system_c).chain())`
//!
//! [`SystemSet`]: crate::schedule::SystemSet
//!
//! ## Example
//!
//! ```
//! # use bevy_ecs::prelude::*;
//! # let mut schedule = Schedule::default();
//! # let mut world = World::new();
//! // Configure these systems to run in order using `chain()`.
//! schedule.add_systems((print_first, print_last).chain());
//! // Prints "HelloWorld!"
//! schedule.run(&mut world);
//!
//! // Configure this system to run in between the other two systems
//! // using explicit dependencies.
//! schedule.add_systems(print_mid.after(print_first).before(print_last));
//! // Prints "Hello, World!"
//! schedule.run(&mut world);
//!
//! fn print_first() {
//! print!("Hello");
//! }
//! fn print_mid() {
//! print!(", ");
//! }
//! fn print_last() {
//! println!("World!");
//! }
//! ```
//!
//! # System parameter list
//! Following is the complete list of accepted types as system parameters:
//!
//! - [`Query`]
//! - [`Res`] and `Option<Res>`
//! - [`ResMut`] and `Option<ResMut>`
//! - [`Commands`]
//! - [`Local`]
//! - [`EventReader`](crate::event::EventReader)
//! - [`EventWriter`](crate::event::EventWriter)
//! - [`NonSend`] and `Option<NonSend>`
//! - [`NonSendMut`] and `Option<NonSendMut>`
//! - [`RemovedComponents`](crate::removal_detection::RemovedComponents)
//! - [`SystemName`]
//! - [`SystemChangeTick`]
//! - [`Archetypes`](crate::archetype::Archetypes) (Provides Archetype metadata)
//! - [`Bundles`](crate::bundle::Bundles) (Provides Bundles metadata)
//! - [`Components`](crate::component::Components) (Provides Components metadata)
//! - [`Entities`](crate::entity::Entities) (Provides Entities metadata)
//! - All tuples between 1 to 16 elements where each element implements [`SystemParam`]
//! - [`()` (unit primitive type)](https://doc.rust-lang.org/stable/std/primitive.unit.html)
mod adapter_system;
mod combinator;
mod commands;
mod exclusive_function_system;
mod exclusive_system_param;
mod function_system;
mod query;
#[allow(clippy::module_inception)]
mod system;
mod system_name;
mod system_param;
mod system_registry;
use std::borrow::Cow;
pub use adapter_system::*;
pub use combinator::*;
pub use commands::*;
pub use exclusive_function_system::*;
pub use exclusive_system_param::*;
pub use function_system::*;
pub use query::*;
pub use system::*;
pub use system_name::*;
pub use system_param::*;
pub use system_registry::*;
use crate::world::World;
/// Conversion trait to turn something into a [`System`].
///
/// Use this to get a system from a function. Also note that every system implements this trait as
/// well.
///
/// # Examples
///
/// ```
/// use bevy_ecs::prelude::*;
///
/// fn my_system_function(a_usize_local: Local<usize>) {}
///
/// let system = IntoSystem::into_system(my_system_function);
/// ```
// This trait has to be generic because we have potentially overlapping impls, in particular
// because Rust thinks a type could impl multiple different `FnMut` combinations
// even though none can currently
pub trait IntoSystem<In, Out, Marker>: Sized {
/// The type of [`System`] that this instance converts into.
type System: System<In = In, Out = Out>;
/// Turns this value into its corresponding [`System`].
fn into_system(this: Self) -> Self::System;
/// Pass the output of this system `A` into a second system `B`, creating a new compound system.
///
/// The second system must have [`In<T>`](crate::system::In) as its first parameter,
/// where `T` is the return type of the first system.
fn pipe<B, Final, MarkerB>(self, system: B) -> PipeSystem<Self::System, B::System>
where
B: IntoSystem<Out, Final, MarkerB>,
{
let system_a = IntoSystem::into_system(self);
let system_b = IntoSystem::into_system(system);
let name = format!("Pipe({}, {})", system_a.name(), system_b.name());
PipeSystem::new(system_a, system_b, Cow::Owned(name))
}
/// Pass the output of this system into the passed function `f`, creating a new system that
/// outputs the value returned from the function.
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut schedule = Schedule::default();
/// // Ignores the output of a system that may fail.
/// schedule.add_systems(my_system.map(drop));
/// # let mut world = World::new();
/// # world.insert_resource(T);
/// # schedule.run(&mut world);
///
/// # #[derive(Resource)] struct T;
/// # type Err = ();
/// fn my_system(res: Res<T>) -> Result<(), Err> {
/// // ...
/// # Err(())
/// }
/// ```
fn map<T, F>(self, f: F) -> AdapterSystem<F, Self::System>
where
F: Send + Sync + 'static + FnMut(Out) -> T,
{
let system = Self::into_system(self);
let name = system.name();
AdapterSystem::new(f, system, name)
}
}
// All systems implicitly implement IntoSystem.
impl<T: System> IntoSystem<T::In, T::Out, ()> for T {
type System = T;
fn into_system(this: Self) -> Self {
this
}
}
/// Wrapper type to mark a [`SystemParam`] as an input.
///
/// [`System`]s may take an optional input which they require to be passed to them when they
/// are being [`run`](System::run). For [`FunctionSystems`](FunctionSystem) the input may be marked
/// with this `In` type, but only the first param of a function may be tagged as an input. This also
/// means a system can only have one or zero input parameters.
///
/// # Examples
///
/// Here is a simple example of a system that takes a [`usize`] returning the square of it.
///
/// ```
/// use bevy_ecs::prelude::*;
///
/// fn main() {
/// let mut square_system = IntoSystem::into_system(square);
///
/// let mut world = World::default();
/// square_system.initialize(&mut world);
/// assert_eq!(square_system.run(12, &mut world), 144);
/// }
///
/// fn square(In(input): In<usize>) -> usize {
/// input * input
/// }
/// ```
pub struct In<In>(pub In);
/// Ensure that a given function is a [system](System).
///
/// This should be used when writing doc examples,
/// to confirm that systems used in an example are
/// valid systems.
///
/// # Examples
///
/// The following example will panic when run since the
/// system's parameters mutably access the same component
/// multiple times.
///
/// ```should_panic
/// # use bevy_ecs::{prelude::*, system::assert_is_system};
/// #
/// # #[derive(Component)]
/// # struct Transform;
/// #
/// fn my_system(query1: Query<&mut Transform>, query2: Query<&mut Transform>) {
/// // ...
/// }
///
/// assert_is_system(my_system);
/// ```
pub fn assert_is_system<In: 'static, Out: 'static, Marker>(
system: impl IntoSystem<In, Out, Marker>,
) {
let mut system = IntoSystem::into_system(system);
// Initialize the system, which will panic if the system has access conflicts.
let mut world = World::new();
system.initialize(&mut world);
}
/// Ensure that a given function is a [read-only system](ReadOnlySystem).
///
/// This should be used when writing doc examples,
/// to confirm that systems used in an example are
/// valid systems.
///
/// # Examples
///
/// The following example will fail to compile
/// since the system accesses a component mutably.
///
/// ```compile_fail
/// # use bevy_ecs::{prelude::*, system::assert_is_read_only_system};
/// #
/// # #[derive(Component)]
/// # struct Transform;
/// #
/// fn my_system(query: Query<&mut Transform>) {
/// // ...
/// }
///
/// assert_is_read_only_system(my_system);
/// ```
pub fn assert_is_read_only_system<In: 'static, Out: 'static, Marker, S>(system: S)
where
S: IntoSystem<In, Out, Marker>,
S::System: ReadOnlySystem,
{
assert_is_system(system);
}
/// Ensures that the provided system doesn't with itself.
///
/// This function will panic if the provided system conflict with itself.
///
/// Note: this will run the system on an empty world.
pub fn assert_system_does_not_conflict<Out, Params, S: IntoSystem<(), Out, Params>>(sys: S) {
let mut world = World::new();
let mut system = IntoSystem::into_system(sys);
system.initialize(&mut world);
system.run((), &mut world);
}
impl<T> std::ops::Deref for In<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> std::ops::DerefMut for In<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(test)]
mod tests {
use std::any::TypeId;
use bevy_utils::default;
use crate::{
self as bevy_ecs,
archetype::{ArchetypeComponentId, Archetypes},
bundle::Bundles,
change_detection::DetectChanges,
component::{Component, Components, Tick},
entity::{Entities, Entity},
prelude::AnyOf,
query::{Added, Changed, Or, With, Without},
removal_detection::RemovedComponents,
schedule::{
apply_deferred, common_conditions::resource_exists, Condition, IntoSystemConfigs,
Schedule,
},
system::{
Commands, In, IntoSystem, Local, NonSend, NonSendMut, ParamSet, Query, Res, ResMut,
Resource, StaticSystemParam, System, SystemState,
},
world::{FromWorld, World},
};
#[derive(Resource, PartialEq, Debug)]
enum SystemRan {
Yes,
No,
}
#[derive(Component, Resource, Debug, Eq, PartialEq, Default)]
struct A;
#[derive(Component, Resource)]
struct B;
#[derive(Component, Resource)]
struct C;
#[derive(Component, Resource)]
struct D;
#[derive(Component, Resource)]
struct E;
#[derive(Component, Resource)]
struct F;
#[derive(Component, Debug)]
struct W<T>(T);
#[test]
fn simple_system() {
fn sys(query: Query<&A>) {
for a in &query {
println!("{a:?}");
}
}
let mut system = IntoSystem::into_system(sys);
let mut world = World::new();
world.spawn(A);
system.initialize(&mut world);
system.run((), &mut world);
}
fn run_system<Marker, S: IntoSystem<(), (), Marker>>(world: &mut World, system: S) {
let mut schedule = Schedule::default();
schedule.add_systems(system);
schedule.run(world);
}
#[test]
fn query_system_gets() {
fn query_system(
mut ran: ResMut<SystemRan>,
entity_query: Query<Entity, With<A>>,
b_query: Query<&B>,
a_c_query: Query<(&A, &C)>,
d_query: Query<&D>,
) {
let entities = entity_query.iter().collect::<Vec<Entity>>();
assert!(
b_query.get_component::<B>(entities[0]).is_err(),
"entity 0 should not have B"
);
assert!(
b_query.get_component::<B>(entities[1]).is_ok(),
"entity 1 should have B"
);
assert!(
b_query.get_component::<A>(entities[1]).is_err(),
"entity 1 should have A, but b_query shouldn't have access to it"
);
assert!(
b_query.get_component::<D>(entities[3]).is_err(),
"entity 3 should have D, but it shouldn't be accessible from b_query"
);
assert!(
b_query.get_component::<C>(entities[2]).is_err(),
"entity 2 has C, but it shouldn't be accessible from b_query"
);
assert!(
a_c_query.get_component::<C>(entities[2]).is_ok(),
"entity 2 has C, and it should be accessible from a_c_query"
);
assert!(
a_c_query.get_component::<D>(entities[3]).is_err(),
"entity 3 should have D, but it shouldn't be accessible from b_query"
);
assert!(
d_query.get_component::<D>(entities[3]).is_ok(),
"entity 3 should have D"
);
*ran = SystemRan::Yes;
}
let mut world = World::default();
world.insert_resource(SystemRan::No);
world.spawn(A);
world.spawn((A, B));
world.spawn((A, C));
world.spawn((A, D));
run_system(&mut world, query_system);
assert_eq!(*world.resource::<SystemRan>(), SystemRan::Yes);
}
#[test]
fn get_many_is_ordered() {
use crate::system::Resource;
const ENTITIES_COUNT: usize = 1000;
#[derive(Resource)]
struct EntitiesArray(Vec<Entity>);
fn query_system(
mut ran: ResMut<SystemRan>,
entities_array: Res<EntitiesArray>,
q: Query<&W<usize>>,
) {
let entities_array: [Entity; ENTITIES_COUNT] =
entities_array.0.clone().try_into().unwrap();
for (i, w) in (0..ENTITIES_COUNT).zip(q.get_many(entities_array).unwrap()) {
assert_eq!(i, w.0);
}
*ran = SystemRan::Yes;
}
fn query_system_mut(
mut ran: ResMut<SystemRan>,
entities_array: Res<EntitiesArray>,
mut q: Query<&mut W<usize>>,
) {
let entities_array: [Entity; ENTITIES_COUNT] =
entities_array.0.clone().try_into().unwrap();
#[allow(unused_mut)]
for (i, mut w) in (0..ENTITIES_COUNT).zip(q.get_many_mut(entities_array).unwrap()) {
assert_eq!(i, w.0);
}
*ran = SystemRan::Yes;
}
let mut world = World::default();
world.insert_resource(SystemRan::No);
let entity_ids = (0..ENTITIES_COUNT)
.map(|i| world.spawn(W(i)).id())
.collect();
world.insert_resource(EntitiesArray(entity_ids));
run_system(&mut world, query_system);
assert_eq!(*world.resource::<SystemRan>(), SystemRan::Yes);
world.insert_resource(SystemRan::No);
run_system(&mut world, query_system_mut);
assert_eq!(*world.resource::<SystemRan>(), SystemRan::Yes);
}
#[test]
fn or_param_set_system() {
// Regression test for issue #762
fn query_system(
mut ran: ResMut<SystemRan>,
mut set: ParamSet<(
Query<(), Or<(Changed<A>, Changed<B>)>>,
Query<(), Or<(Added<A>, Added<B>)>>,
)>,
) {
let changed = set.p0().iter().count();
let added = set.p1().iter().count();
assert_eq!(changed, 1);
assert_eq!(added, 1);
*ran = SystemRan::Yes;
}
let mut world = World::default();
world.insert_resource(SystemRan::No);
world.spawn((A, B));
run_system(&mut world, query_system);
assert_eq!(*world.resource::<SystemRan>(), SystemRan::Yes);
}
#[test]
fn changed_resource_system() {
use crate::system::Resource;
#[derive(Resource)]
struct Flipper(bool);
#[derive(Resource)]
struct Added(usize);
#[derive(Resource)]
struct Changed(usize);
fn incr_e_on_flip(
value: Res<Flipper>,
mut changed: ResMut<Changed>,
mut added: ResMut<Added>,
) {
if value.is_added() {
added.0 += 1;
}
if value.is_changed() {
changed.0 += 1;
}
}
let mut world = World::default();
world.insert_resource(Flipper(false));
world.insert_resource(Added(0));
world.insert_resource(Changed(0));
let mut schedule = Schedule::default();
schedule.add_systems((incr_e_on_flip, apply_deferred, World::clear_trackers).chain());
schedule.run(&mut world);
assert_eq!(world.resource::<Added>().0, 1);
assert_eq!(world.resource::<Changed>().0, 1);
schedule.run(&mut world);
assert_eq!(world.resource::<Added>().0, 1);
assert_eq!(world.resource::<Changed>().0, 1);
world.resource_mut::<Flipper>().0 = true;
schedule.run(&mut world);
assert_eq!(world.resource::<Added>().0, 1);
assert_eq!(world.resource::<Changed>().0, 2);
}
#[test]
#[should_panic = "error[B0001]"]
fn option_has_no_filter_with() {
fn sys(_: Query<(Option<&A>, &mut B)>, _: Query<&mut B, Without<A>>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
fn option_doesnt_remove_unrelated_filter_with() {
fn sys(_: Query<(Option<&A>, &mut B, &A)>, _: Query<&mut B, Without<A>>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
#[should_panic = "error[B0001]"]
fn any_of_has_no_filter_with() {
fn sys(_: Query<(AnyOf<(&A, ())>, &mut B)>, _: Query<&mut B, Without<A>>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
fn any_of_has_filter_with_when_both_have_it() {
fn sys(_: Query<(AnyOf<(&A, &A)>, &mut B)>, _: Query<&mut B, Without<A>>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
fn any_of_doesnt_remove_unrelated_filter_with() {
fn sys(_: Query<(AnyOf<(&A, ())>, &mut B, &A)>, _: Query<&mut B, Without<A>>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
fn any_of_and_without() {
fn sys(_: Query<(AnyOf<(&A, &B)>, &mut C)>, _: Query<&mut C, (Without<A>, Without<B>)>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
#[should_panic = "error[B0001]"]
fn or_has_no_filter_with() {
fn sys(_: Query<&mut B, Or<(With<A>, With<B>)>>, _: Query<&mut B, Without<A>>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
fn or_has_filter_with_when_both_have_it() {
fn sys(_: Query<&mut B, Or<(With<A>, With<A>)>>, _: Query<&mut B, Without<A>>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
fn or_has_filter_with() {
fn sys(
_: Query<&mut C, Or<(With<A>, With<B>)>>,
_: Query<&mut C, (Without<A>, Without<B>)>,
) {
}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
fn or_expanded_with_and_without_common() {
fn sys(_: Query<&mut D, (With<A>, Or<(With<B>, With<C>)>)>, _: Query<&mut D, Without<A>>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
fn or_expanded_nested_with_and_without_common() {
fn sys(
_: Query<&mut E, (Or<((With<B>, With<C>), (With<C>, With<D>))>, With<A>)>,
_: Query<&mut E, (Without<B>, Without<D>)>,
) {
}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
#[should_panic = "error[B0001]"]
fn or_expanded_nested_with_and_disjoint_without() {
fn sys(
_: Query<&mut E, (Or<((With<B>, With<C>), (With<C>, With<D>))>, With<A>)>,
_: Query<&mut E, Without<D>>,
) {
}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
#[should_panic = "error[B0001]"]
fn or_expanded_nested_or_with_and_disjoint_without() {
fn sys(
_: Query<&mut D, Or<(Or<(With<A>, With<B>)>, Or<(With<A>, With<C>)>)>>,
_: Query<&mut D, Without<A>>,
) {
}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
fn or_expanded_nested_with_and_common_nested_without() {
fn sys(
_: Query<&mut D, Or<((With<A>, With<B>), (With<B>, With<C>))>>,
_: Query<&mut D, Or<(Without<D>, Without<B>)>>,
) {
}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
fn or_with_without_and_compatible_with_without() {
fn sys(
_: Query<&mut C, Or<(With<A>, Without<B>)>>,
_: Query<&mut C, (With<B>, Without<A>)>,
) {
}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
#[should_panic = "error[B0001]"]
fn with_and_disjoint_or_empty_without() {
fn sys(_: Query<&mut B, With<A>>, _: Query<&mut B, Or<((), Without<A>)>>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
#[should_panic = "error[B0001]"]
fn or_expanded_with_and_disjoint_nested_without() {
fn sys(
_: Query<&mut D, Or<(With<A>, With<B>)>>,
_: Query<&mut D, Or<(Without<A>, Without<B>)>>,
) {
}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
#[should_panic = "error[B0001]"]
fn or_expanded_nested_with_and_disjoint_nested_without() {
fn sys(
_: Query<&mut D, Or<((With<A>, With<B>), (With<B>, With<C>))>>,
_: Query<&mut D, Or<(Without<A>, Without<B>)>>,
) {
}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
fn or_doesnt_remove_unrelated_filter_with() {
fn sys(_: Query<&mut B, (Or<(With<A>, With<B>)>, With<A>)>, _: Query<&mut B, Without<A>>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
#[should_panic]
fn conflicting_query_mut_system() {
fn sys(_q1: Query<&mut A>, _q2: Query<&mut A>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
fn disjoint_query_mut_system() {
fn sys(_q1: Query<&mut A, With<B>>, _q2: Query<&mut A, Without<B>>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
fn disjoint_query_mut_read_component_system() {
fn sys(_q1: Query<(&mut A, &B)>, _q2: Query<&mut A, Without<B>>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
#[should_panic]
fn conflicting_query_immut_system() {
fn sys(_q1: Query<&A>, _q2: Query<&mut A>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
fn query_set_system() {
fn sys(mut _set: ParamSet<(Query<&mut A>, Query<&A>)>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
#[should_panic]
fn conflicting_query_with_query_set_system() {
fn sys(_query: Query<&mut A>, _set: ParamSet<(Query<&mut A>, Query<&B>)>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[test]
#[should_panic]
fn conflicting_query_sets_system() {
fn sys(_set_1: ParamSet<(Query<&mut A>,)>, _set_2: ParamSet<(Query<&mut A>, Query<&B>)>) {}
let mut world = World::default();
run_system(&mut world, sys);
}
#[derive(Default, Resource)]
struct BufferRes {
_buffer: Vec<u8>,
}
fn test_for_conflicting_resources<Marker, S: IntoSystem<(), (), Marker>>(sys: S) {
let mut world = World::default();
world.insert_resource(BufferRes::default());
world.insert_resource(A);
world.insert_resource(B);
run_system(&mut world, sys);
}
#[test]
#[should_panic]
fn conflicting_system_resources() {
fn sys(_: ResMut<BufferRes>, _: Res<BufferRes>) {}
test_for_conflicting_resources(sys);
}
#[test]
#[should_panic]
fn conflicting_system_resources_reverse_order() {
fn sys(_: Res<BufferRes>, _: ResMut<BufferRes>) {}
test_for_conflicting_resources(sys);
}
#[test]
#[should_panic]
fn conflicting_system_resources_multiple_mutable() {
fn sys(_: ResMut<BufferRes>, _: ResMut<BufferRes>) {}
test_for_conflicting_resources(sys);
}
#[test]
fn nonconflicting_system_resources() {
fn sys(_: Local<BufferRes>, _: ResMut<BufferRes>, _: Local<A>, _: ResMut<A>) {}
test_for_conflicting_resources(sys);
}
#[test]
fn local_system() {
let mut world = World::default();
world.insert_resource(ProtoFoo { value: 1 });
world.insert_resource(SystemRan::No);
struct Foo {
value: u32,
}
#[derive(Resource)]
struct ProtoFoo {
value: u32,
}
impl FromWorld for Foo {
fn from_world(world: &mut World) -> Self {
Foo {
value: world.resource::<ProtoFoo>().value + 1,
}
}
}
fn sys(local: Local<Foo>, mut system_ran: ResMut<SystemRan>) {
assert_eq!(local.value, 2);
*system_ran = SystemRan::Yes;
}
run_system(&mut world, sys);
// ensure the system actually ran
assert_eq!(*world.resource::<SystemRan>(), SystemRan::Yes);
}
#[test]
fn non_send_option_system() {
let mut world = World::default();
world.insert_resource(SystemRan::No);
struct NotSend1(std::rc::Rc<i32>);
struct NotSend2(std::rc::Rc<i32>);
world.insert_non_send_resource(NotSend1(std::rc::Rc::new(0)));
fn sys(
op: Option<NonSend<NotSend1>>,
mut _op2: Option<NonSendMut<NotSend2>>,
mut system_ran: ResMut<SystemRan>,
) {
op.expect("NonSend should exist");
*system_ran = SystemRan::Yes;
}
run_system(&mut world, sys);
// ensure the system actually ran
assert_eq!(*world.resource::<SystemRan>(), SystemRan::Yes);
}
#[test]
fn non_send_system() {
let mut world = World::default();
world.insert_resource(SystemRan::No);
struct NotSend1(std::rc::Rc<i32>);
struct NotSend2(std::rc::Rc<i32>);
world.insert_non_send_resource(NotSend1(std::rc::Rc::new(1)));
world.insert_non_send_resource(NotSend2(std::rc::Rc::new(2)));
fn sys(
_op: NonSend<NotSend1>,
mut _op2: NonSendMut<NotSend2>,
mut system_ran: ResMut<SystemRan>,
) {
*system_ran = SystemRan::Yes;
}
run_system(&mut world, sys);
assert_eq!(*world.resource::<SystemRan>(), SystemRan::Yes);
}
#[test]
fn removal_tracking() {
let mut world = World::new();
let entity_to_despawn = world.spawn(W(1)).id();
let entity_to_remove_w_from = world.spawn(W(2)).id();
let spurious_entity = world.spawn_empty().id();
// Track which entities we want to operate on
#[derive(Resource)]
struct Despawned(Entity);
world.insert_resource(Despawned(entity_to_despawn));
#[derive(Resource)]
struct Removed(Entity);
world.insert_resource(Removed(entity_to_remove_w_from));
// Verify that all the systems actually ran
#[derive(Default, Resource)]
struct NSystems(usize);
world.insert_resource(NSystems::default());
// First, check that removal detection is triggered if and only if we despawn an entity with the correct component
world.entity_mut(entity_to_despawn).despawn();
world.entity_mut(spurious_entity).despawn();
fn validate_despawn(
mut removed_i32: RemovedComponents<W<i32>>,
despawned: Res<Despawned>,
mut n_systems: ResMut<NSystems>,
) {
assert_eq!(
removed_i32.read().collect::<Vec<_>>(),
&[despawned.0],
"despawning causes the correct entity to show up in the 'RemovedComponent' system parameter."
);
n_systems.0 += 1;
}
run_system(&mut world, validate_despawn);
// Reset the trackers to clear the buffer of removed components
// Ordinarily, this is done in a system added by MinimalPlugins
world.clear_trackers();
// Then, try removing a component
world.spawn(W(3));
world.spawn(W(4));
world.entity_mut(entity_to_remove_w_from).remove::<W<i32>>();
fn validate_remove(
mut removed_i32: RemovedComponents<W<i32>>,
despawned: Res<Despawned>,
removed: Res<Removed>,
mut n_systems: ResMut<NSystems>,
) {
// The despawned entity from the previous frame was
// double buffered so we now have it in this system as well.
assert_eq!(
removed_i32.read().collect::<Vec<_>>(),