Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamic queries and builder API #9774

Merged
merged 57 commits into from
Jan 16, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
b56e1c7
Fully dynamic term based query builder
james-j-obrien Sep 11, 2023
5917065
System installation of dynamically built queries
james-j-obrien Sep 11, 2023
b7f04df
Fix change detection, add Changed and Added
james-j-obrien Sep 11, 2023
07dc116
Add additional tests, fix bugs and clean up
james-j-obrien Sep 11, 2023
a12b5dd
Add trivial examples
james-j-obrien Sep 11, 2023
f6382c1
Performance tweaks
james-j-obrien Sep 12, 2023
25623dc
Add dynamic reference methods
james-j-obrien Sep 12, 2023
c16e0ec
Fix rebase issue
james-j-obrien Sep 12, 2023
799b318
Remove examples so github is less angry, rename builder methods to be…
james-j-obrien Sep 12, 2023
711653b
Better builder method names
james-j-obrien Sep 12, 2023
ff1e33a
Major perf improvements, add additional dynamic builder methods
james-j-obrien Sep 12, 2023
40bd8c5
Remove closures from hot loop, remove more runtime checks
james-j-obrien Sep 12, 2023
d0736f5
Remove allocations from hot loop
james-j-obrien Sep 12, 2023
c3d37da
Minor cleanup
james-j-obrien Sep 12, 2023
353c248
Remove #[inline(always)] where it doesn't improve or degrades perform…
james-j-obrien Sep 13, 2023
40c1c62
Flatten terms
james-j-obrien Sep 13, 2023
7667c0a
Fix AnyOf issue
james-j-obrien Sep 13, 2023
031779c
Reorder impls to be more intuitive
james-j-obrien Sep 13, 2023
5494b28
Add dynamic_query example
james-j-obrien Sep 14, 2023
688459d
First docs pass, bug fixes and minor improvements
james-j-obrien Sep 15, 2023
666edb3
Improve documentation, add additional utility functions, add benches
james-j-obrien Sep 18, 2023
5ac0e50
Remove temporary test
james-j-obrien Sep 18, 2023
9d6382f
Minor cleanup
james-j-obrien Sep 18, 2023
f7abf12
First CI pass
james-j-obrien Sep 18, 2023
5c880e9
Second CI pass
james-j-obrien Sep 18, 2023
7680abd
Third times the charm
james-j-obrien Sep 18, 2023
7bd46ab
Add comments
james-j-obrien Sep 18, 2023
db48ac8
Flatten terms, remove branching where possible
james-j-obrien Sep 29, 2023
02091d9
Fix example
james-j-obrien Sep 29, 2023
9a3f5b3
Static iteration, remove FetchedTerm and FetchBuffer
james-j-obrien Sep 30, 2023
88ba5e3
Cleanup component ptr access
james-j-obrien Sep 30, 2023
2cf8f1e
Tidy docs slightly
james-j-obrien Sep 30, 2023
9c65312
Swap to constants to speed up dense iteration, minor API cleanup
james-j-obrien Sep 30, 2023
e9c7861
Consistency pass
james-j-obrien Sep 30, 2023
c674c4a
Move to pointers from iterators, split fetch and filter terms
james-j-obrien Oct 4, 2023
5952756
Add From<Mut<T>> For MutUntyped
james-j-obrien Oct 7, 2023
a76370c
FilteredAccess based implementation
james-j-obrien Nov 14, 2023
323cc74
Merge branch 'dynamic-term-builder' into query-builder
james-j-obrien Nov 14, 2023
ce0ea41
Merge branch 'bevyengine:main' into dynamic-term-builder
james-j-obrien Nov 14, 2023
89f1eac
Doc fixes
james-j-obrien Nov 14, 2023
bf9cee7
Merge branch 'dynamic-term-builder' of https://github.com/james-j-obr…
james-j-obrien Nov 14, 2023
32a6796
Add compile fail tests, add safety comments to example
james-j-obrien Nov 20, 2023
289ca79
Merge main
james-j-obrien Nov 22, 2023
52e0391
Learn how to spell required correctly
james-j-obrien Nov 22, 2023
fecd6bc
Merge main, incorporate feedback
james-j-obrien Nov 30, 2023
04d88cc
Fix doc test
james-j-obrien Nov 30, 2023
3bfcc3f
Fix docs and compile fail tests
james-j-obrien Nov 30, 2023
60c006f
Fix trailing newline
james-j-obrien Nov 30, 2023
b59bb38
Fix trailing whitespace...
james-j-obrien Nov 30, 2023
cf951bb
Merge branch 'main' into dynamic-term-builder
james-j-obrien Dec 2, 2023
2e8a197
Remove unused import
james-j-obrien Dec 2, 2023
5c98ef4
Improve safety comments
james-j-obrien Dec 15, 2023
6f6a0cc
Merge main
james-j-obrien Dec 15, 2023
63f97a3
Address remaining feedback
james-j-obrien Jan 16, 2024
056ff2a
Merge branch 'main' into dynamic-term-builder
james-j-obrien Jan 16, 2024
a3ab076
Fix panic strings
james-j-obrien Jan 16, 2024
8c1bbb0
Fix doc test
james-j-obrien Jan 16, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/bevy_ecs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ rustc-hash = "1.1"
downcast-rs = "1.2"
serde = "1"
thiserror = "1.0"
smallvec = "1.6"

[dev-dependencies]
rand = "0.8"
Expand Down
4 changes: 3 additions & 1 deletion crates/bevy_ecs/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#![warn(clippy::undocumented_unsafe_blocks)]
#![warn(missing_docs)]
#![allow(missing_docs)]
james-j-obrien marked this conversation as resolved.
Show resolved Hide resolved
#![allow(clippy::type_complexity)]
#![doc = include_str!("../README.md")]

Expand All @@ -19,6 +19,7 @@ pub mod removal_detection;
pub mod schedule;
pub mod storage;
pub mod system;
pub mod term_query;
pub mod world;

use std::any::TypeId;
Expand Down Expand Up @@ -52,6 +53,7 @@ pub mod prelude {
Commands, Deferred, In, IntoSystem, Local, NonSend, NonSendMut, ParallelCommands,
ParamSet, Query, ReadOnlySystem, Res, ResMut, Resource, System, SystemParamFunction,
},
term_query::{TermQuery, TermQueryState},
world::{EntityMut, EntityRef, EntityWorldMut, FromWorld, World},
};
}
Expand Down
18 changes: 18 additions & 0 deletions crates/bevy_ecs/src/storage/sparse_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,24 @@ impl ComponentSparseSet {
}
}

/// Returns an [`UnsafeCell`] to the "added" and "changed" ticks of the entity's component value.
///
/// Returns `None` if `entity` does not have a component in the sparse set.
#[inline]
pub fn get_tick_cells(&self, entity: Entity) -> Option<TickCells<'_>> {
let dense_index = *self.sparse.get(entity.index())? as usize;
#[cfg(debug_assertions)]
assert_eq!(entity, self.entities[dense_index]);
let row = TableRow::new(dense_index);
// SAFETY: if the sparse index points to something in the dense vec, it exists
unsafe {
Some(TickCells {
added: self.dense.get_added_tick_unchecked(row),
changed: self.dense.get_changed_tick_unchecked(row),
})
}
}

/// Returns a reference to the "added" and "changed" ticks of the entity's component value.
///
/// Returns `None` if `entity` does not have a component in the sparse set.
Expand Down
9 changes: 9 additions & 0 deletions crates/bevy_ecs/src/system/function_system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,15 @@ where
marker: PhantomData<fn() -> Marker>,
}

impl<Marker, F> FunctionSystem<Marker, F>
where
F: SystemParamFunction<Marker>,
{
pub unsafe fn state_mut(&mut self) -> &mut <F::Param as SystemParam>::State {
self.param_state.as_mut().unwrap()
}
}

// De-initializes the cloned system.
impl<Marker, F> Clone for FunctionSystem<Marker, F>
where
Expand Down
43 changes: 43 additions & 0 deletions crates/bevy_ecs/src/system/system_param.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use crate::{
Access, FilteredAccess, FilteredAccessSet, QueryState, ReadOnlyWorldQuery, WorldQuery,
},
system::{Query, SystemMeta},
term_query::{QueryTermGroup, TermQuery, TermQueryState},
world::{unsafe_world_cell::UnsafeWorldCell, FromWorld, World},
};
use bevy_ecs_macros::impl_param_set;
Expand Down Expand Up @@ -225,6 +226,48 @@ fn assert_component_access_compatibility(
panic!("error[B0001]: Query<{query_type}, {filter_type}> in system {system_name} accesses component(s) {accesses} in a way that conflicts with a previous system parameter. Consider using `Without<T>` to create disjoint Queries or merging conflicting Queries into a `ParamSet`.");
}

unsafe impl<Q: QueryTermGroup + 'static, F: QueryTermGroup + 'static> SystemParam
for TermQuery<'_, '_, Q, F>
{
type State = TermQueryState<Q, F>;
type Item<'w, 's> = TermQuery<'w, 's, Q, F>;

fn init_state(world: &mut World, system_meta: &mut crate::system::SystemMeta) -> Self::State {
let state = TermQueryState::new(world);
assert_component_access_compatibility(
&system_meta.name,
"term_query",
"term_query",
james-j-obrien marked this conversation as resolved.
Show resolved Hide resolved
&system_meta.component_access_set,
&state.component_access,
world,
);
system_meta
.component_access_set
.add(state.component_access.clone());
system_meta
.archetype_component_access
.extend(&state.archetype_component_access);
state
}

fn new_archetype(state: &mut Self::State, archetype: &Archetype, system_meta: &mut SystemMeta) {
state.new_archetype(archetype);
system_meta
.archetype_component_access
.extend(&state.archetype_component_access);
}

unsafe fn get_param<'world, 'state>(
state: &'state mut Self::State,
system_meta: &crate::system::SystemMeta,
world: UnsafeWorldCell<'world>,
change_tick: Tick,
) -> Self::Item<'world, 'state> {
TermQuery::new(world, state, system_meta.last_run, change_tick)
}
}

/// A collection of potentially conflicting [`SystemParam`]s allowed by disjoint access.
///
/// Allows systems to safely access and interact with up to 8 mutually exclusive [`SystemParam`]s, such as
Expand Down
84 changes: 84 additions & 0 deletions crates/bevy_ecs/src/term_query/builder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
use std::marker::PhantomData;

use crate::{
component::ComponentId,
prelude::{Component, With, Without, World},
};

use super::{ComponentTerm, QueryTermGroup, Term, TermQueryState, TermVec};

pub struct QueryBuilder<'w, Q: QueryTermGroup = ()> {
terms: TermVec<Term>,
current_term: usize,
world: &'w mut World,
_marker: PhantomData<Q>,
}

impl<'w, Q: QueryTermGroup> QueryBuilder<'w, Q> {
james-j-obrien marked this conversation as resolved.
Show resolved Hide resolved
pub fn new(world: &'w mut World) -> Self {
let mut terms = TermVec::new();
Q::init_terms(world, &mut terms);
Self {
current_term: terms.len(),
terms,
world,
_marker: PhantomData::default(),
}
}

pub fn term<T: QueryTermGroup>(&mut self) -> &mut Self {
T::init_terms(self.world, &mut self.terms);
self
}

pub unsafe fn term_at(&mut self, index: usize) -> &mut Self {
james-j-obrien marked this conversation as resolved.
Show resolved Hide resolved
self.current_term = index;
self
}

pub fn with<T: Component>(&mut self) -> &mut Self {
self.term::<With<T>>()
}

pub fn with_component(&mut self, id: ComponentId) -> &mut Self {
james-j-obrien marked this conversation as resolved.
Show resolved Hide resolved
self.terms.push(Term::Component(ComponentTerm::with(id)));
self
}

pub fn without<T: Component>(&mut self) -> &mut Self {
self.term::<Without<T>>()
}

pub fn without_component(&mut self, id: ComponentId) -> &mut Self {
self.terms.push(Term::Component(ComponentTerm::without(id)));
self
}

pub fn ref_component(&mut self, id: ComponentId) -> &mut Self {
self.terms.push(Term::Component(ComponentTerm::read_id(id)));
self
}

pub fn mut_id(&mut self, id: ComponentId) -> &mut Self {
self.terms
.push(Term::Component(ComponentTerm::write_id(id)));
self
}

pub fn set_dynamic<T: Component>(&mut self) -> &mut Self {
let id = self.world.init_component::<T>();
self.set_dynamic_component(id);
self
}

pub fn set_dynamic_component(&mut self, id: ComponentId) -> &mut Self {
if let Term::Component(term) = &mut self.terms[self.current_term] {
term.set_id(id)
}
self
}

pub fn build(&mut self) -> TermQueryState<Q> {
TermQueryState::<Q>::from_terms(self.world, self.terms.clone())
}
}
Loading
Loading