Skip to content

Commit be1c317

Browse files
committed
Resolve (most) internal system ambiguities (#1606)
* Adds labels and orderings to systems that need them (uses the new many-to-many labels for InputSystem) * Removes the Event, PreEvent, Scene, and Ui stages in favor of First, PreUpdate, and PostUpdate (there is more collapsing potential, such as the Asset stages and _maybe_ removing First, but those have more nuance so they should be handled separately) * Ambiguity detection now prints component conflicts * Removed broken change filters from flex calculation (which implicitly relied on the z-update system always modifying translation.z). This will require more work to make it behave as expected so i just removed it (and it was already doing this work every frame).
1 parent 1e42de6 commit be1c317

File tree

23 files changed

+242
-131
lines changed

23 files changed

+242
-131
lines changed

crates/bevy_app/src/app_builder.rs

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -211,29 +211,27 @@ impl AppBuilder {
211211
}
212212

213213
pub fn add_default_stages(&mut self) -> &mut Self {
214-
self.add_stage(
215-
CoreStage::Startup,
216-
Schedule::default()
217-
.with_run_criteria(RunOnce::default())
218-
.with_stage(StartupStage::PreStartup, SystemStage::parallel())
219-
.with_stage(StartupStage::Startup, SystemStage::parallel())
220-
.with_stage(StartupStage::PostStartup, SystemStage::parallel()),
221-
)
222-
.add_stage(CoreStage::First, SystemStage::parallel())
223-
.add_stage(CoreStage::PreEvent, SystemStage::parallel())
224-
.add_stage(CoreStage::Event, SystemStage::parallel())
225-
.add_stage(CoreStage::PreUpdate, SystemStage::parallel())
226-
.add_stage(CoreStage::Update, SystemStage::parallel())
227-
.add_stage(CoreStage::PostUpdate, SystemStage::parallel())
228-
.add_stage(CoreStage::Last, SystemStage::parallel())
214+
self.add_stage(CoreStage::First, SystemStage::parallel())
215+
.add_stage(
216+
CoreStage::Startup,
217+
Schedule::default()
218+
.with_run_criteria(RunOnce::default())
219+
.with_stage(StartupStage::PreStartup, SystemStage::parallel())
220+
.with_stage(StartupStage::Startup, SystemStage::parallel())
221+
.with_stage(StartupStage::PostStartup, SystemStage::parallel()),
222+
)
223+
.add_stage(CoreStage::PreUpdate, SystemStage::parallel())
224+
.add_stage(CoreStage::Update, SystemStage::parallel())
225+
.add_stage(CoreStage::PostUpdate, SystemStage::parallel())
226+
.add_stage(CoreStage::Last, SystemStage::parallel())
229227
}
230228

231229
pub fn add_event<T>(&mut self) -> &mut Self
232230
where
233231
T: Component,
234232
{
235233
self.insert_resource(Events::<T>::default())
236-
.add_system_to_stage(CoreStage::Event, Events::<T>::update_system.system())
234+
.add_system_to_stage(CoreStage::First, Events::<T>::update_system.system())
237235
}
238236

239237
/// Inserts a resource to the current [App] and overwrites any resource previously added of the same type.

crates/bevy_app/src/event.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@ use bevy_ecs::{
33
system::{Local, Res, ResMut, SystemParam},
44
};
55
use bevy_utils::tracing::trace;
6-
use std::{fmt, marker::PhantomData};
6+
use std::{
7+
fmt::{self},
8+
hash::Hash,
9+
marker::PhantomData,
10+
};
711

812
/// An `EventId` uniquely identifies an event.
913
///

crates/bevy_app/src/lib.rs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,6 @@ pub enum CoreStage {
3131
Startup,
3232
/// Name of app stage that runs before all other app stages
3333
First,
34-
/// Name of app stage that runs before EVENT
35-
PreEvent,
36-
/// Name of app stage that updates events. Runs before UPDATE
37-
Event,
3834
/// Name of app stage responsible for performing setup before an update. Runs before UPDATE.
3935
PreUpdate,
4036
/// Name of app stage responsible for doing most app logic. Systems should be registered here by default.

crates/bevy_core/src/lib.rs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,24 @@ pub mod prelude {
1717
}
1818

1919
use bevy_app::prelude::*;
20-
use bevy_ecs::{entity::Entity, system::IntoSystem};
20+
use bevy_ecs::{
21+
entity::Entity,
22+
schedule::{ExclusiveSystemDescriptorCoercion, SystemLabel},
23+
system::{IntoExclusiveSystem, IntoSystem},
24+
};
2125
use bevy_utils::HashSet;
2226
use std::ops::Range;
2327

2428
/// Adds core functionality to Apps.
2529
#[derive(Default)]
2630
pub struct CorePlugin;
2731

32+
#[derive(Debug, PartialEq, Eq, Clone, Hash, SystemLabel)]
33+
pub enum CoreSystem {
34+
/// Updates the elapsed time. Any system that interacts with [Time] component should run after this.
35+
Time,
36+
}
37+
2838
impl Plugin for CorePlugin {
2939
fn build(&self, app: &mut AppBuilder) {
3040
// Setup the default bevy task pools
@@ -44,7 +54,11 @@ impl Plugin for CorePlugin {
4454
.register_type::<Labels>()
4555
.register_type::<Range<f32>>()
4656
.register_type::<Timer>()
47-
.add_system_to_stage(CoreStage::First, time_system.system())
57+
// time system is added as an "exclusive system" to ensure it runs before other systems in CoreStage::First
58+
.add_system_to_stage(
59+
CoreStage::First,
60+
time_system.exclusive_system().label(CoreSystem::Time),
61+
)
4862
.add_startup_system_to_stage(StartupStage::PostStartup, entity_labels_system.system())
4963
.add_system_to_stage(CoreStage::PostUpdate, entity_labels_system.system());
5064

crates/bevy_ecs/src/query/access.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,3 +198,35 @@ impl<T: SparseSetIndex> Default for FilteredAccessSet<T> {
198198
}
199199
}
200200
}
201+
202+
#[cfg(test)]
203+
mod tests {
204+
use crate::query::Access;
205+
206+
#[test]
207+
fn access_get_conflicts() {
208+
let mut access_a = Access::<usize>::default();
209+
access_a.add_read(0);
210+
access_a.add_read(1);
211+
212+
let mut access_b = Access::<usize>::default();
213+
access_b.add_read(0);
214+
access_b.add_write(1);
215+
216+
assert_eq!(access_a.get_conflicts(&access_b), vec![1]);
217+
218+
let mut access_c = Access::<usize>::default();
219+
access_c.add_write(0);
220+
access_c.add_write(1);
221+
222+
assert_eq!(access_a.get_conflicts(&access_c), vec![0, 1]);
223+
assert_eq!(access_b.get_conflicts(&access_c), vec![0, 1]);
224+
225+
let mut access_d = Access::<usize>::default();
226+
access_d.add_read(0);
227+
228+
assert_eq!(access_d.get_conflicts(&access_a), vec![]);
229+
assert_eq!(access_d.get_conflicts(&access_b), vec![]);
230+
assert_eq!(access_d.get_conflicts(&access_c), vec![0]);
231+
}
232+
}

crates/bevy_ecs/src/schedule/stage.rs

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::{
2+
component::ComponentId,
23
schedule::{
34
BoxedSystemLabel, ExclusiveSystemContainer, InsertionPoint, ParallelExecutor,
45
ParallelSystemContainer, ParallelSystemExecutor, RunCriteria, ShouldRun,
@@ -263,22 +264,30 @@ impl SystemStage {
263264
}
264265

265266
/// Logs execution order ambiguities between systems. System orders must be fresh.
266-
fn report_ambiguities(&self) {
267+
fn report_ambiguities(&self, world: &World) {
267268
debug_assert!(!self.systems_modified);
268269
use std::fmt::Write;
269270
fn write_display_names_of_pairs(
270271
string: &mut String,
271272
systems: &[impl SystemContainer],
272-
mut ambiguities: Vec<(usize, usize)>,
273+
mut ambiguities: Vec<(usize, usize, Vec<ComponentId>)>,
274+
world: &World,
273275
) {
274-
for (index_a, index_b) in ambiguities.drain(..) {
276+
for (index_a, index_b, conflicts) in ambiguities.drain(..) {
275277
writeln!(
276278
string,
277279
" -- {:?} and {:?}",
278280
systems[index_a].name(),
279281
systems[index_b].name()
280282
)
281283
.unwrap();
284+
if !conflicts.is_empty() {
285+
let names = conflicts
286+
.iter()
287+
.map(|id| world.components().get_info(*id).unwrap().name())
288+
.collect::<Vec<_>>();
289+
writeln!(string, " conflicts: {:?}", names).unwrap();
290+
}
282291
}
283292
}
284293
let parallel = find_ambiguities(&self.parallel);
@@ -295,23 +304,29 @@ impl SystemStage {
295304
.to_owned();
296305
if !parallel.is_empty() {
297306
writeln!(string, " * Parallel systems:").unwrap();
298-
write_display_names_of_pairs(&mut string, &self.parallel, parallel);
307+
write_display_names_of_pairs(&mut string, &self.parallel, parallel, world);
299308
}
300309
if !at_start.is_empty() {
301310
writeln!(string, " * Exclusive systems at start of stage:").unwrap();
302-
write_display_names_of_pairs(&mut string, &self.exclusive_at_start, at_start);
311+
write_display_names_of_pairs(
312+
&mut string,
313+
&self.exclusive_at_start,
314+
at_start,
315+
world,
316+
);
303317
}
304318
if !before_commands.is_empty() {
305319
writeln!(string, " * Exclusive systems before commands of stage:").unwrap();
306320
write_display_names_of_pairs(
307321
&mut string,
308322
&self.exclusive_before_commands,
309323
before_commands,
324+
world,
310325
);
311326
}
312327
if !at_end.is_empty() {
313328
writeln!(string, " * Exclusive systems at end of stage:").unwrap();
314-
write_display_names_of_pairs(&mut string, &self.exclusive_at_end, at_end);
329+
write_display_names_of_pairs(&mut string, &self.exclusive_at_end, at_end, world);
315330
}
316331
info!("{}", string);
317332
}
@@ -454,9 +469,10 @@ fn topological_order(
454469
Ok(sorted)
455470
}
456471

457-
/// Returns vector containing all pairs of indices of systems with ambiguous execution order.
472+
/// Returns vector containing all pairs of indices of systems with ambiguous execution order,
473+
/// along with specific components that have triggered the warning.
458474
/// Systems must be topologically sorted beforehand.
459-
fn find_ambiguities(systems: &[impl SystemContainer]) -> Vec<(usize, usize)> {
475+
fn find_ambiguities(systems: &[impl SystemContainer]) -> Vec<(usize, usize, Vec<ComponentId>)> {
460476
let mut ambiguity_set_labels = HashMap::default();
461477
for set in systems.iter().flat_map(|c| c.ambiguity_sets()) {
462478
let len = ambiguity_set_labels.len();
@@ -511,9 +527,17 @@ fn find_ambiguities(systems: &[impl SystemContainer]) -> Vec<(usize, usize)> {
511527
{
512528
if !processed.contains(index_b)
513529
&& all_ambiguity_sets[index_a].is_disjoint(&all_ambiguity_sets[index_b])
514-
&& !systems[index_a].is_compatible(&systems[index_b])
515530
{
516-
ambiguities.push((index_a, index_b));
531+
let a_access = systems[index_a].component_access();
532+
let b_access = systems[index_b].component_access();
533+
if let (Some(a), Some(b)) = (a_access, b_access) {
534+
let conflicts = a.get_conflicts(b);
535+
if !conflicts.is_empty() {
536+
ambiguities.push((index_a, index_b, conflicts))
537+
}
538+
} else {
539+
ambiguities.push((index_a, index_b, Vec::new()));
540+
}
517541
}
518542
}
519543
processed.insert(index_a);
@@ -549,7 +573,7 @@ impl Stage for SystemStage {
549573
self.executor.rebuild_cached_data(&self.parallel);
550574
self.executor_modified = false;
551575
if world.contains_resource::<ReportExecutionOrderAmbiguities>() {
552-
self.report_ambiguities();
576+
self.report_ambiguities(world);
553577
}
554578
} else if self.executor_modified {
555579
self.executor.rebuild_cached_data(&self.parallel);
@@ -1184,7 +1208,7 @@ mod tests {
11841208
) -> Vec<(BoxedSystemLabel, BoxedSystemLabel)> {
11851209
find_ambiguities(systems)
11861210
.drain(..)
1187-
.map(|(index_a, index_b)| {
1211+
.map(|(index_a, index_b, _conflicts)| {
11881212
(
11891213
systems[index_a].labels()[0].clone(),
11901214
systems[index_b].labels()[0].clone(),

crates/bevy_ecs/src/schedule/system_container.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
use crate::{
2+
component::ComponentId,
3+
query::Access,
24
schedule::{
35
BoxedAmbiguitySetLabel, BoxedSystemLabel, ExclusiveSystemDescriptor,
46
ParallelSystemDescriptor,
@@ -16,7 +18,7 @@ pub(super) trait SystemContainer {
1618
fn before(&self) -> &[BoxedSystemLabel];
1719
fn after(&self) -> &[BoxedSystemLabel];
1820
fn ambiguity_sets(&self) -> &[BoxedAmbiguitySetLabel];
19-
fn is_compatible(&self, other: &Self) -> bool;
21+
fn component_access(&self) -> Option<&Access<ComponentId>>;
2022
}
2123

2224
pub(super) struct ExclusiveSystemContainer {
@@ -81,8 +83,8 @@ impl SystemContainer for ExclusiveSystemContainer {
8183
&self.ambiguity_sets
8284
}
8385

84-
fn is_compatible(&self, _: &Self) -> bool {
85-
false
86+
fn component_access(&self) -> Option<&Access<ComponentId>> {
87+
None
8688
}
8789
}
8890

@@ -178,9 +180,7 @@ impl SystemContainer for ParallelSystemContainer {
178180
&self.ambiguity_sets
179181
}
180182

181-
fn is_compatible(&self, other: &Self) -> bool {
182-
self.system()
183-
.component_access()
184-
.is_compatible(other.system().component_access())
183+
fn component_access(&self) -> Option<&Access<ComponentId>> {
184+
Some(self.system().component_access())
185185
}
186186
}

crates/bevy_ecs/src/system/mod.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ pub use system_param::*;
1717

1818
#[cfg(test)]
1919
mod tests {
20+
use std::any::TypeId;
21+
2022
use crate::{
2123
archetype::Archetypes,
2224
bundle::Bundles,
@@ -415,4 +417,25 @@ mod tests {
415417
// ensure the system actually ran
416418
assert_eq!(*world.get_resource::<bool>().unwrap(), true);
417419
}
420+
421+
#[test]
422+
fn get_system_conflicts() {
423+
fn sys_x(_: Res<A>, _: Res<B>, _: Query<(&C, &D)>) {}
424+
425+
fn sys_y(_: Res<A>, _: ResMut<B>, _: Query<(&C, &mut D)>) {}
426+
427+
let mut world = World::default();
428+
let mut x = sys_x.system();
429+
let mut y = sys_y.system();
430+
x.initialize(&mut world);
431+
y.initialize(&mut world);
432+
433+
let conflicts = x.component_access().get_conflicts(y.component_access());
434+
let b_id = world
435+
.components()
436+
.get_resource_id(TypeId::of::<B>())
437+
.unwrap();
438+
let d_id = world.components().get_id(TypeId::of::<D>()).unwrap();
439+
assert_eq!(conflicts, vec![b_id, d_id]);
440+
}
418441
}

crates/bevy_ecs/src/system/system_param.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,7 @@ impl<'a, T: Component> SystemParam for Option<Res<'a, T>> {
248248

249249
unsafe impl<T: Component> SystemParamState for OptionResState<T> {
250250
type Config = ();
251+
251252
fn init(world: &mut World, system_state: &mut SystemState, _config: Self::Config) -> Self {
252253
Self(ResState::init(world, system_state, ()))
253254
}
@@ -383,6 +384,7 @@ impl<'a, T: Component> SystemParam for Option<ResMut<'a, T>> {
383384

384385
unsafe impl<T: Component> SystemParamState for OptionResMutState<T> {
385386
type Config = ();
387+
386388
fn init(world: &mut World, system_state: &mut SystemState, _config: Self::Config) -> Self {
387389
Self(ResMutState::init(world, system_state, ()))
388390
}

crates/bevy_gilrs/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ impl Plugin for GilrsPlugin {
2424
gilrs_event_startup_system.exclusive_system(),
2525
)
2626
.add_system_to_stage(
27-
CoreStage::PreEvent,
27+
CoreStage::PreUpdate,
2828
gilrs_event_system.exclusive_system(),
2929
);
3030
}

0 commit comments

Comments
 (0)