2024-07-08 01:09:04 +00:00
|
|
|
#[cfg(feature = "bevy_reflect")]
|
|
|
|
use bevy_ecs::reflect::ReflectComponent;
|
2024-09-24 11:42:59 +00:00
|
|
|
use bevy_ecs::{component::Component, entity::Entity, query::QueryData};
|
Split WorldQuery into WorldQueryData and WorldQueryFilter (#9918)
# Objective
- Fixes #7680
- This is an updated for https://github.com/bevyengine/bevy/pull/8899
which had the same objective but fell a long way behind the latest
changes
## Solution
The traits `WorldQueryData : WorldQuery` and `WorldQueryFilter :
WorldQuery` have been added and some of the types and functions from
`WorldQuery` has been moved into them.
`ReadOnlyWorldQuery` has been replaced with `ReadOnlyWorldQueryData`.
`WorldQueryFilter` is safe (as long as `WorldQuery` is implemented
safely).
`WorldQueryData` is unsafe - safely implementing it requires that
`Self::ReadOnly` is a readonly version of `Self` (this used to be a
safety requirement of `WorldQuery`)
The type parameters `Q` and `F` of `Query` must now implement
`WorldQueryData` and `WorldQueryFilter` respectively.
This makes it impossible to accidentally use a filter in the data
position or vice versa which was something that could lead to bugs.
~~Compile failure tests have been added to check this.~~
It was previously sometimes useful to use `Option<With<T>>` in the data
position. Use `Has<T>` instead in these cases.
The `WorldQuery` derive macro has been split into separate derive macros
for `WorldQueryData` and `WorldQueryFilter`.
Previously it was possible to derive both `WorldQuery` for a struct that
had a mixture of data and filter items. This would not work correctly in
some cases but could be a useful pattern in others. *This is no longer
possible.*
---
## Notes
- The changes outside of `bevy_ecs` are all changing type parameters to
the new types, updating the macro use, or replacing `Option<With<T>>`
with `Has<T>`.
- All `WorldQueryData` types always returned `true` for `IS_ARCHETYPAL`
so I moved it to `WorldQueryFilter` and
replaced all calls to it with `true`. That should be the only logic
change outside of the macro generation code.
- `Changed<T>` and `Added<T>` were being generated by a macro that I
have expanded. Happy to revert that if desired.
- The two derive macros share some functions for implementing
`WorldQuery` but the tidiest way I could find to implement them was to
give them a ton of arguments and ask clippy to ignore that.
## Changelog
### Changed
- Split `WorldQuery` into `WorldQueryData` and `WorldQueryFilter` which
now have separate derive macros. It is not possible to derive both for
the same type.
- `Query` now requires that the first type argument implements
`WorldQueryData` and the second implements `WorldQueryFilter`
## Migration Guide
- Update derives
```rust
// old
#[derive(WorldQuery)]
#[world_query(mutable, derive(Debug))]
struct CustomQuery {
entity: Entity,
a: &'static mut ComponentA
}
#[derive(WorldQuery)]
struct QueryFilter {
_c: With<ComponentC>
}
// new
#[derive(WorldQueryData)]
#[world_query_data(mutable, derive(Debug))]
struct CustomQuery {
entity: Entity,
a: &'static mut ComponentA,
}
#[derive(WorldQueryFilter)]
struct QueryFilter {
_c: With<ComponentC>
}
```
- Replace `Option<With<T>>` with `Has<T>`
```rust
/// old
fn my_system(query: Query<(Entity, Option<With<ComponentA>>)>)
{
for (entity, has_a_option) in query.iter(){
let has_a:bool = has_a_option.is_some();
//todo!()
}
}
/// new
fn my_system(query: Query<(Entity, Has<ComponentA>)>)
{
for (entity, has_a) in query.iter(){
//todo!()
}
}
```
- Fix queries which had filters in the data position or vice versa.
```rust
// old
fn my_system(query: Query<(Entity, With<ComponentA>)>)
{
for (entity, _) in query.iter(){
//todo!()
}
}
// new
fn my_system(query: Query<Entity, With<ComponentA>>)
{
for entity in query.iter(){
//todo!()
}
}
// old
fn my_system(query: Query<AnyOf<(&ComponentA, With<ComponentB>)>>)
{
for (entity, _) in query.iter(){
//todo!()
}
}
// new
fn my_system(query: Query<Option<&ComponentA>, Or<(With<ComponentA>, With<ComponentB>)>>)
{
for entity in query.iter(){
//todo!()
}
}
```
---------
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-11-28 03:56:07 +00:00
|
|
|
|
2024-09-27 00:59:59 +00:00
|
|
|
use alloc::borrow::Cow;
|
2024-07-08 01:09:04 +00:00
|
|
|
#[cfg(feature = "bevy_reflect")]
|
bevy_reflect: `FromReflect` Ergonomics Implementation (#6056)
# Objective
**This implementation is based on
https://github.com/bevyengine/rfcs/pull/59.**
---
Resolves #4597
Full details and motivation can be found in the RFC, but here's a brief
summary.
`FromReflect` is a very powerful and important trait within the
reflection API. It allows Dynamic types (e.g., `DynamicList`, etc.) to
be formed into Real ones (e.g., `Vec<i32>`, etc.).
This mainly comes into play concerning deserialization, where the
reflection deserializers both return a `Box<dyn Reflect>` that almost
always contain one of these Dynamic representations of a Real type. To
convert this to our Real type, we need to use `FromReflect`.
It also sneaks up in other ways. For example, it's a required bound for
`T` in `Vec<T>` so that `Vec<T>` as a whole can be made `FromReflect`.
It's also required by all fields of an enum as it's used as part of the
`Reflect::apply` implementation.
So in other words, much like `GetTypeRegistration` and `Typed`, it is
very much a core reflection trait.
The problem is that it is not currently treated like a core trait and is
not automatically derived alongside `Reflect`. This makes using it a bit
cumbersome and easy to forget.
## Solution
Automatically derive `FromReflect` when deriving `Reflect`.
Users can then choose to opt-out if needed using the
`#[reflect(from_reflect = false)]` attribute.
```rust
#[derive(Reflect)]
struct Foo;
#[derive(Reflect)]
#[reflect(from_reflect = false)]
struct Bar;
fn test<T: FromReflect>(value: T) {}
test(Foo); // <-- OK
test(Bar); // <-- Panic! Bar does not implement trait `FromReflect`
```
#### `ReflectFromReflect`
This PR also automatically adds the `ReflectFromReflect` (introduced in
#6245) registration to the derived `GetTypeRegistration` impl— if the
type hasn't opted out of `FromReflect` of course.
<details>
<summary><h4>Improved Deserialization</h4></summary>
> **Warning**
> This section includes changes that have since been descoped from this
PR. They will likely be implemented again in a followup PR. I am mainly
leaving these details in for archival purposes, as well as for reference
when implementing this logic again.
And since we can do all the above, we might as well improve
deserialization. We can now choose to deserialize into a Dynamic type or
automatically convert it using `FromReflect` under the hood.
`[Un]TypedReflectDeserializer::new` will now perform the conversion and
return the `Box`'d Real type.
`[Un]TypedReflectDeserializer::new_dynamic` will work like what we have
now and simply return the `Box`'d Dynamic type.
```rust
// Returns the Real type
let reflect_deserializer = UntypedReflectDeserializer::new(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input)?;
let output: SomeStruct = reflect_deserializer.deserialize(&mut deserializer)?.take()?;
// Returns the Dynamic type
let reflect_deserializer = UntypedReflectDeserializer::new_dynamic(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input)?;
let output: DynamicStruct = reflect_deserializer.deserialize(&mut deserializer)?.take()?;
```
</details>
---
## Changelog
* `FromReflect` is now automatically derived within the `Reflect` derive
macro
* This includes auto-registering `ReflectFromReflect` in the derived
`GetTypeRegistration` impl
* ~~Renamed `TypedReflectDeserializer::new` and
`UntypedReflectDeserializer::new` to
`TypedReflectDeserializer::new_dynamic` and
`UntypedReflectDeserializer::new_dynamic`, respectively~~ **Descoped**
* ~~Changed `TypedReflectDeserializer::new` and
`UntypedReflectDeserializer::new` to automatically convert the
deserialized output using `FromReflect`~~ **Descoped**
## Migration Guide
* `FromReflect` is now automatically derived within the `Reflect` derive
macro. Items with both derives will need to remove the `FromReflect`
one.
```rust
// OLD
#[derive(Reflect, FromReflect)]
struct Foo;
// NEW
#[derive(Reflect)]
struct Foo;
```
If using a manual implementation of `FromReflect` and the `Reflect`
derive, users will need to opt-out of the automatic implementation.
```rust
// OLD
#[derive(Reflect)]
struct Foo;
impl FromReflect for Foo {/* ... */}
// NEW
#[derive(Reflect)]
#[reflect(from_reflect = false)]
struct Foo;
impl FromReflect for Foo {/* ... */}
```
<details>
<summary><h4>Removed Migrations</h4></summary>
> **Warning**
> This section includes changes that have since been descoped from this
PR. They will likely be implemented again in a followup PR. I am mainly
leaving these details in for archival purposes, as well as for reference
when implementing this logic again.
* The reflect deserializers now perform a `FromReflect` conversion
internally. The expected output of `TypedReflectDeserializer::new` and
`UntypedReflectDeserializer::new` is no longer a Dynamic (e.g.,
`DynamicList`), but its Real counterpart (e.g., `Vec<i32>`).
```rust
let reflect_deserializer =
UntypedReflectDeserializer::new_dynamic(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input)?;
// OLD
let output: DynamicStruct = reflect_deserializer.deserialize(&mut
deserializer)?.take()?;
// NEW
let output: SomeStruct = reflect_deserializer.deserialize(&mut
deserializer)?.take()?;
```
Alternatively, if this behavior isn't desired, use the
`TypedReflectDeserializer::new_dynamic` and
`UntypedReflectDeserializer::new_dynamic` methods instead:
```rust
// OLD
let reflect_deserializer = UntypedReflectDeserializer::new(®istry);
// NEW
let reflect_deserializer =
UntypedReflectDeserializer::new_dynamic(®istry);
```
</details>
---------
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-06-29 01:31:34 +00:00
|
|
|
use bevy_reflect::std_traits::ReflectDefault;
|
2024-07-08 01:09:04 +00:00
|
|
|
#[cfg(feature = "bevy_reflect")]
|
bevy_reflect: `FromReflect` Ergonomics Implementation (#6056)
# Objective
**This implementation is based on
https://github.com/bevyengine/rfcs/pull/59.**
---
Resolves #4597
Full details and motivation can be found in the RFC, but here's a brief
summary.
`FromReflect` is a very powerful and important trait within the
reflection API. It allows Dynamic types (e.g., `DynamicList`, etc.) to
be formed into Real ones (e.g., `Vec<i32>`, etc.).
This mainly comes into play concerning deserialization, where the
reflection deserializers both return a `Box<dyn Reflect>` that almost
always contain one of these Dynamic representations of a Real type. To
convert this to our Real type, we need to use `FromReflect`.
It also sneaks up in other ways. For example, it's a required bound for
`T` in `Vec<T>` so that `Vec<T>` as a whole can be made `FromReflect`.
It's also required by all fields of an enum as it's used as part of the
`Reflect::apply` implementation.
So in other words, much like `GetTypeRegistration` and `Typed`, it is
very much a core reflection trait.
The problem is that it is not currently treated like a core trait and is
not automatically derived alongside `Reflect`. This makes using it a bit
cumbersome and easy to forget.
## Solution
Automatically derive `FromReflect` when deriving `Reflect`.
Users can then choose to opt-out if needed using the
`#[reflect(from_reflect = false)]` attribute.
```rust
#[derive(Reflect)]
struct Foo;
#[derive(Reflect)]
#[reflect(from_reflect = false)]
struct Bar;
fn test<T: FromReflect>(value: T) {}
test(Foo); // <-- OK
test(Bar); // <-- Panic! Bar does not implement trait `FromReflect`
```
#### `ReflectFromReflect`
This PR also automatically adds the `ReflectFromReflect` (introduced in
#6245) registration to the derived `GetTypeRegistration` impl— if the
type hasn't opted out of `FromReflect` of course.
<details>
<summary><h4>Improved Deserialization</h4></summary>
> **Warning**
> This section includes changes that have since been descoped from this
PR. They will likely be implemented again in a followup PR. I am mainly
leaving these details in for archival purposes, as well as for reference
when implementing this logic again.
And since we can do all the above, we might as well improve
deserialization. We can now choose to deserialize into a Dynamic type or
automatically convert it using `FromReflect` under the hood.
`[Un]TypedReflectDeserializer::new` will now perform the conversion and
return the `Box`'d Real type.
`[Un]TypedReflectDeserializer::new_dynamic` will work like what we have
now and simply return the `Box`'d Dynamic type.
```rust
// Returns the Real type
let reflect_deserializer = UntypedReflectDeserializer::new(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input)?;
let output: SomeStruct = reflect_deserializer.deserialize(&mut deserializer)?.take()?;
// Returns the Dynamic type
let reflect_deserializer = UntypedReflectDeserializer::new_dynamic(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input)?;
let output: DynamicStruct = reflect_deserializer.deserialize(&mut deserializer)?.take()?;
```
</details>
---
## Changelog
* `FromReflect` is now automatically derived within the `Reflect` derive
macro
* This includes auto-registering `ReflectFromReflect` in the derived
`GetTypeRegistration` impl
* ~~Renamed `TypedReflectDeserializer::new` and
`UntypedReflectDeserializer::new` to
`TypedReflectDeserializer::new_dynamic` and
`UntypedReflectDeserializer::new_dynamic`, respectively~~ **Descoped**
* ~~Changed `TypedReflectDeserializer::new` and
`UntypedReflectDeserializer::new` to automatically convert the
deserialized output using `FromReflect`~~ **Descoped**
## Migration Guide
* `FromReflect` is now automatically derived within the `Reflect` derive
macro. Items with both derives will need to remove the `FromReflect`
one.
```rust
// OLD
#[derive(Reflect, FromReflect)]
struct Foo;
// NEW
#[derive(Reflect)]
struct Foo;
```
If using a manual implementation of `FromReflect` and the `Reflect`
derive, users will need to opt-out of the automatic implementation.
```rust
// OLD
#[derive(Reflect)]
struct Foo;
impl FromReflect for Foo {/* ... */}
// NEW
#[derive(Reflect)]
#[reflect(from_reflect = false)]
struct Foo;
impl FromReflect for Foo {/* ... */}
```
<details>
<summary><h4>Removed Migrations</h4></summary>
> **Warning**
> This section includes changes that have since been descoped from this
PR. They will likely be implemented again in a followup PR. I am mainly
leaving these details in for archival purposes, as well as for reference
when implementing this logic again.
* The reflect deserializers now perform a `FromReflect` conversion
internally. The expected output of `TypedReflectDeserializer::new` and
`UntypedReflectDeserializer::new` is no longer a Dynamic (e.g.,
`DynamicList`), but its Real counterpart (e.g., `Vec<i32>`).
```rust
let reflect_deserializer =
UntypedReflectDeserializer::new_dynamic(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input)?;
// OLD
let output: DynamicStruct = reflect_deserializer.deserialize(&mut
deserializer)?.take()?;
// NEW
let output: SomeStruct = reflect_deserializer.deserialize(&mut
deserializer)?.take()?;
```
Alternatively, if this behavior isn't desired, use the
`TypedReflectDeserializer::new_dynamic` and
`UntypedReflectDeserializer::new_dynamic` methods instead:
```rust
// OLD
let reflect_deserializer = UntypedReflectDeserializer::new(®istry);
// NEW
let reflect_deserializer =
UntypedReflectDeserializer::new_dynamic(®istry);
```
</details>
---------
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-06-29 01:31:34 +00:00
|
|
|
use bevy_reflect::Reflect;
|
2020-12-31 20:52:02 +00:00
|
|
|
use bevy_utils::AHasher;
|
2024-09-27 00:59:59 +00:00
|
|
|
use core::{
|
2020-12-31 20:52:02 +00:00
|
|
|
hash::{Hash, Hasher},
|
|
|
|
ops::Deref,
|
|
|
|
};
|
|
|
|
|
2024-07-08 01:09:04 +00:00
|
|
|
#[cfg(all(feature = "serialize", feature = "bevy_reflect"))]
|
2024-01-21 18:04:13 +00:00
|
|
|
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
|
|
|
|
|
2023-01-27 17:49:11 +00:00
|
|
|
/// Component used to identify an entity. Stores a hash for faster comparisons.
|
|
|
|
///
|
2022-01-02 20:36:40 +00:00
|
|
|
/// The hash is eagerly re-computed upon each update to the name.
|
|
|
|
///
|
|
|
|
/// [`Name`] should not be treated as a globally unique identifier for entities,
|
2023-11-28 23:43:40 +00:00
|
|
|
/// as multiple entities can have the same name. [`Entity`] should be
|
2022-01-02 20:36:40 +00:00
|
|
|
/// used instead as the default unique identifier.
|
2024-07-08 01:09:04 +00:00
|
|
|
#[derive(Component, Clone)]
|
|
|
|
#[cfg_attr(
|
|
|
|
feature = "bevy_reflect",
|
|
|
|
derive(Reflect),
|
|
|
|
reflect(Component, Default, Debug)
|
|
|
|
)]
|
|
|
|
#[cfg_attr(
|
|
|
|
all(feature = "serialize", feature = "bevy_reflect"),
|
|
|
|
reflect(Deserialize, Serialize)
|
|
|
|
)]
|
2020-12-31 20:52:02 +00:00
|
|
|
pub struct Name {
|
2024-01-21 18:04:13 +00:00
|
|
|
hash: u64, // Won't be serialized (see: `bevy_core::serde` module)
|
2021-02-01 00:35:23 +00:00
|
|
|
name: Cow<'static, str>,
|
2020-12-31 20:52:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for Name {
|
|
|
|
fn default() -> Self {
|
2021-02-01 00:35:23 +00:00
|
|
|
Name::new("")
|
2020-12-31 20:52:02 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Name {
|
2022-01-02 20:36:40 +00:00
|
|
|
/// Creates a new [`Name`] from any string-like type.
|
|
|
|
///
|
|
|
|
/// The internal hash will be computed immediately.
|
2021-02-01 00:35:23 +00:00
|
|
|
pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
|
2021-01-22 22:13:26 +00:00
|
|
|
let name = name.into();
|
2020-12-31 20:52:02 +00:00
|
|
|
let mut name = Name { name, hash: 0 };
|
|
|
|
name.update_hash();
|
|
|
|
name
|
|
|
|
}
|
|
|
|
|
2022-01-02 20:36:40 +00:00
|
|
|
/// Sets the entity's name.
|
|
|
|
///
|
|
|
|
/// The internal hash will be re-computed.
|
2020-12-31 20:52:02 +00:00
|
|
|
#[inline(always)]
|
2021-02-01 00:35:23 +00:00
|
|
|
pub fn set(&mut self, name: impl Into<Cow<'static, str>>) {
|
2020-12-31 20:52:02 +00:00
|
|
|
*self = Name::new(name);
|
|
|
|
}
|
|
|
|
|
2022-01-02 20:36:40 +00:00
|
|
|
/// Updates the name of the entity in place.
|
|
|
|
///
|
|
|
|
/// This will allocate a new string if the name was previously
|
|
|
|
/// created from a borrow.
|
2020-12-31 20:52:02 +00:00
|
|
|
#[inline(always)]
|
|
|
|
pub fn mutate<F: FnOnce(&mut String)>(&mut self, f: F) {
|
2021-02-01 00:35:23 +00:00
|
|
|
f(self.name.to_mut());
|
2020-12-31 20:52:02 +00:00
|
|
|
self.update_hash();
|
|
|
|
}
|
|
|
|
|
2022-01-02 20:36:40 +00:00
|
|
|
/// Gets the name of the entity as a `&str`.
|
2020-12-31 20:52:02 +00:00
|
|
|
#[inline(always)]
|
|
|
|
pub fn as_str(&self) -> &str {
|
2021-02-01 00:35:23 +00:00
|
|
|
&self.name
|
2020-12-31 20:52:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn update_hash(&mut self) {
|
|
|
|
let mut hasher = AHasher::default();
|
|
|
|
self.name.hash(&mut hasher);
|
|
|
|
self.hash = hasher.finish();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-09-27 00:59:59 +00:00
|
|
|
impl core::fmt::Display for Name {
|
2022-02-04 03:07:20 +00:00
|
|
|
#[inline(always)]
|
2024-09-27 00:59:59 +00:00
|
|
|
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
|
|
|
|
core::fmt::Display::fmt(&self.name, f)
|
2022-02-04 03:07:20 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-09-27 00:59:59 +00:00
|
|
|
impl core::fmt::Debug for Name {
|
2023-04-26 20:00:03 +00:00
|
|
|
#[inline(always)]
|
2024-09-27 00:59:59 +00:00
|
|
|
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
|
|
|
|
core::fmt::Debug::fmt(&self.name, f)
|
2023-04-26 20:00:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-30 20:50:46 +00:00
|
|
|
/// Convenient query for giving a human friendly name to an entity.
|
|
|
|
///
|
2024-01-01 16:50:56 +00:00
|
|
|
/// ```
|
2023-01-30 20:50:46 +00:00
|
|
|
/// # use bevy_core::prelude::*;
|
|
|
|
/// # use bevy_ecs::prelude::*;
|
|
|
|
/// # #[derive(Component)] pub struct Score(f32);
|
2024-07-15 15:21:41 +00:00
|
|
|
/// fn increment_score(mut scores: Query<(NameOrEntity, &mut Score)>) {
|
2023-01-30 20:50:46 +00:00
|
|
|
/// for (name, mut score) in &mut scores {
|
|
|
|
/// score.0 += 1.0;
|
|
|
|
/// if score.0.is_nan() {
|
2024-06-25 12:58:53 +00:00
|
|
|
/// bevy_utils::tracing::error!("Score for {name} is invalid");
|
2023-01-30 20:50:46 +00:00
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
/// # bevy_ecs::system::assert_is_system(increment_score);
|
|
|
|
/// ```
|
2024-06-25 12:58:53 +00:00
|
|
|
///
|
|
|
|
/// # Implementation
|
|
|
|
///
|
2024-07-15 15:21:41 +00:00
|
|
|
/// The `Display` impl for `NameOrEntity` returns the `Name` where there is one
|
2024-06-25 12:58:53 +00:00
|
|
|
/// or {index}v{generation} for entities without one.
|
Rename `WorldQueryData` & `WorldQueryFilter` to `QueryData` & `QueryFilter` (#10779)
# Rename `WorldQueryData` & `WorldQueryFilter` to `QueryData` &
`QueryFilter`
Fixes #10776
## Solution
Traits `WorldQueryData` & `WorldQueryFilter` were renamed to `QueryData`
and `QueryFilter`, respectively. Related Trait types were also renamed.
---
## Changelog
- Trait `WorldQueryData` has been renamed to `QueryData`. Derive macro's
`QueryData` attribute `world_query_data` has been renamed to
`query_data`.
- Trait `WorldQueryFilter` has been renamed to `QueryFilter`. Derive
macro's `QueryFilter` attribute `world_query_filter` has been renamed to
`query_filter`.
- Trait's `ExtractComponent` type `Query` has been renamed to `Data`.
- Trait's `GetBatchData` types `Query` & `QueryFilter` has been renamed
to `Data` & `Filter`, respectively.
- Trait's `ExtractInstance` type `Query` has been renamed to `Data`.
- Trait's `ViewNode` type `ViewQuery` has been renamed to `ViewData`.
- Trait's `RenderCommand` types `ViewWorldQuery` & `ItemWorldQuery` has
been renamed to `ViewData` & `ItemData`, respectively.
## Migration Guide
Note: if merged before 0.13 is released, this should instead modify the
migration guide of #10776 with the updated names.
- Rename `WorldQueryData` & `WorldQueryFilter` trait usages to
`QueryData` & `QueryFilter` and their respective derive macro attributes
`world_query_data` & `world_query_filter` to `query_data` &
`query_filter`.
- Rename the following trait type usages:
- Trait's `ExtractComponent` type `Query` to `Data`.
- Trait's `GetBatchData` type `Query` to `Data`.
- Trait's `ExtractInstance` type `Query` to `Data`.
- Trait's `ViewNode` type `ViewQuery` to `ViewData`'
- Trait's `RenderCommand` types `ViewWolrdQuery` & `ItemWorldQuery` to
`ViewData` & `ItemData`, respectively.
```rust
// Before
#[derive(WorldQueryData)]
#[world_query_data(derive(Debug))]
struct EmptyQuery {
empty: (),
}
// After
#[derive(QueryData)]
#[query_data(derive(Debug))]
struct EmptyQuery {
empty: (),
}
// Before
#[derive(WorldQueryFilter)]
struct CustomQueryFilter<T: Component, P: Component> {
_c: With<ComponentC>,
_d: With<ComponentD>,
_or: Or<(Added<ComponentC>, Changed<ComponentD>, Without<ComponentZ>)>,
_generic_tuple: (With<T>, With<P>),
}
// After
#[derive(QueryFilter)]
struct CustomQueryFilter<T: Component, P: Component> {
_c: With<ComponentC>,
_d: With<ComponentD>,
_or: Or<(Added<ComponentC>, Changed<ComponentD>, Without<ComponentZ>)>,
_generic_tuple: (With<T>, With<P>),
}
// Before
impl ExtractComponent for ContrastAdaptiveSharpeningSettings {
type Query = &'static Self;
type Filter = With<Camera>;
type Out = (DenoiseCAS, CASUniform);
fn extract_component(item: QueryItem<Self::Query>) -> Option<Self::Out> {
//...
}
}
// After
impl ExtractComponent for ContrastAdaptiveSharpeningSettings {
type Data = &'static Self;
type Filter = With<Camera>;
type Out = (DenoiseCAS, CASUniform);
fn extract_component(item: QueryItem<Self::Data>) -> Option<Self::Out> {
//...
}
}
// Before
impl GetBatchData for MeshPipeline {
type Param = SRes<RenderMeshInstances>;
type Query = Entity;
type QueryFilter = With<Mesh3d>;
type CompareData = (MaterialBindGroupId, AssetId<Mesh>);
type BufferData = MeshUniform;
fn get_batch_data(
mesh_instances: &SystemParamItem<Self::Param>,
entity: &QueryItem<Self::Query>,
) -> (Self::BufferData, Option<Self::CompareData>) {
// ....
}
}
// After
impl GetBatchData for MeshPipeline {
type Param = SRes<RenderMeshInstances>;
type Data = Entity;
type Filter = With<Mesh3d>;
type CompareData = (MaterialBindGroupId, AssetId<Mesh>);
type BufferData = MeshUniform;
fn get_batch_data(
mesh_instances: &SystemParamItem<Self::Param>,
entity: &QueryItem<Self::Data>,
) -> (Self::BufferData, Option<Self::CompareData>) {
// ....
}
}
// Before
impl<A> ExtractInstance for AssetId<A>
where
A: Asset,
{
type Query = Read<Handle<A>>;
type Filter = ();
fn extract(item: QueryItem<'_, Self::Query>) -> Option<Self> {
Some(item.id())
}
}
// After
impl<A> ExtractInstance for AssetId<A>
where
A: Asset,
{
type Data = Read<Handle<A>>;
type Filter = ();
fn extract(item: QueryItem<'_, Self::Data>) -> Option<Self> {
Some(item.id())
}
}
// Before
impl ViewNode for PostProcessNode {
type ViewQuery = (
&'static ViewTarget,
&'static PostProcessSettings,
);
fn run(
&self,
_graph: &mut RenderGraphContext,
render_context: &mut RenderContext,
(view_target, _post_process_settings): QueryItem<Self::ViewQuery>,
world: &World,
) -> Result<(), NodeRunError> {
// ...
}
}
// After
impl ViewNode for PostProcessNode {
type ViewData = (
&'static ViewTarget,
&'static PostProcessSettings,
);
fn run(
&self,
_graph: &mut RenderGraphContext,
render_context: &mut RenderContext,
(view_target, _post_process_settings): QueryItem<Self::ViewData>,
world: &World,
) -> Result<(), NodeRunError> {
// ...
}
}
// Before
impl<P: CachedRenderPipelinePhaseItem> RenderCommand<P> for SetItemPipeline {
type Param = SRes<PipelineCache>;
type ViewWorldQuery = ();
type ItemWorldQuery = ();
#[inline]
fn render<'w>(
item: &P,
_view: (),
_entity: (),
pipeline_cache: SystemParamItem<'w, '_, Self::Param>,
pass: &mut TrackedRenderPass<'w>,
) -> RenderCommandResult {
// ...
}
}
// After
impl<P: CachedRenderPipelinePhaseItem> RenderCommand<P> for SetItemPipeline {
type Param = SRes<PipelineCache>;
type ViewData = ();
type ItemData = ();
#[inline]
fn render<'w>(
item: &P,
_view: (),
_entity: (),
pipeline_cache: SystemParamItem<'w, '_, Self::Param>,
pass: &mut TrackedRenderPass<'w>,
) -> RenderCommandResult {
// ...
}
}
```
2023-12-12 19:45:50 +00:00
|
|
|
#[derive(QueryData)]
|
2024-06-25 12:58:53 +00:00
|
|
|
#[query_data(derive(Debug))]
|
2024-07-15 15:21:41 +00:00
|
|
|
pub struct NameOrEntity {
|
2023-01-30 20:50:46 +00:00
|
|
|
/// A [`Name`] that the entity might have that is displayed if available.
|
|
|
|
pub name: Option<&'static Name>,
|
|
|
|
/// The unique identifier of the entity as a fallback.
|
|
|
|
pub entity: Entity,
|
|
|
|
}
|
|
|
|
|
2024-09-27 00:59:59 +00:00
|
|
|
impl<'a> core::fmt::Display for NameOrEntityItem<'a> {
|
2023-01-30 20:50:46 +00:00
|
|
|
#[inline(always)]
|
2024-09-27 00:59:59 +00:00
|
|
|
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
|
2023-01-30 20:50:46 +00:00
|
|
|
match self.name {
|
2024-09-27 00:59:59 +00:00
|
|
|
Some(name) => core::fmt::Display::fmt(name, f),
|
|
|
|
None => core::fmt::Display::fmt(&self.entity, f),
|
2023-01-30 20:50:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-09-24 11:42:59 +00:00
|
|
|
// Conversions from strings
|
2022-02-04 03:07:20 +00:00
|
|
|
|
2020-12-31 20:52:02 +00:00
|
|
|
impl From<&str> for Name {
|
|
|
|
#[inline(always)]
|
|
|
|
fn from(name: &str) -> Self {
|
|
|
|
Name::new(name.to_owned())
|
|
|
|
}
|
|
|
|
}
|
2022-02-04 03:07:20 +00:00
|
|
|
impl From<String> for Name {
|
|
|
|
#[inline(always)]
|
|
|
|
fn from(name: String) -> Self {
|
|
|
|
Name::new(name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-09-24 11:42:59 +00:00
|
|
|
// Conversions to strings
|
2022-02-04 03:07:20 +00:00
|
|
|
|
|
|
|
impl AsRef<str> for Name {
|
|
|
|
#[inline(always)]
|
|
|
|
fn as_ref(&self) -> &str {
|
|
|
|
&self.name
|
|
|
|
}
|
|
|
|
}
|
|
|
|
impl From<&Name> for String {
|
|
|
|
#[inline(always)]
|
|
|
|
fn from(val: &Name) -> String {
|
|
|
|
val.as_str().to_owned()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
impl From<Name> for String {
|
|
|
|
#[inline(always)]
|
|
|
|
fn from(val: Name) -> String {
|
|
|
|
val.name.into_owned()
|
|
|
|
}
|
|
|
|
}
|
2020-12-31 20:52:02 +00:00
|
|
|
|
|
|
|
impl Hash for Name {
|
|
|
|
fn hash<H: Hasher>(&self, state: &mut H) {
|
|
|
|
self.name.hash(state);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PartialEq for Name {
|
|
|
|
fn eq(&self, other: &Self) -> bool {
|
|
|
|
if self.hash != other.hash {
|
|
|
|
// Makes the common case of two strings not been equal very fast
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
self.name.eq(&other.name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Eq for Name {}
|
|
|
|
|
|
|
|
impl PartialOrd for Name {
|
2024-09-27 00:59:59 +00:00
|
|
|
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
|
2023-05-06 22:31:25 +00:00
|
|
|
Some(self.cmp(other))
|
2020-12-31 20:52:02 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Ord for Name {
|
2024-09-27 00:59:59 +00:00
|
|
|
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
|
2020-12-31 20:52:02 +00:00
|
|
|
self.name.cmp(&other.name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Deref for Name {
|
2022-01-17 21:30:17 +00:00
|
|
|
type Target = str;
|
2020-12-31 20:52:02 +00:00
|
|
|
|
|
|
|
fn deref(&self) -> &Self::Target {
|
2022-01-17 21:30:17 +00:00
|
|
|
self.name.as_ref()
|
2020-12-31 20:52:02 +00:00
|
|
|
}
|
|
|
|
}
|
2024-06-25 12:58:53 +00:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
use bevy_ecs::world::World;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_display_of_debug_name() {
|
|
|
|
let mut world = World::new();
|
|
|
|
let e1 = world.spawn_empty().id();
|
|
|
|
let name = Name::new("MyName");
|
|
|
|
let e2 = world.spawn(name.clone()).id();
|
2024-07-15 15:21:41 +00:00
|
|
|
let mut query = world.query::<NameOrEntity>();
|
2024-06-25 12:58:53 +00:00
|
|
|
let d1 = query.get(&world, e1).unwrap();
|
|
|
|
let d2 = query.get(&world, e2).unwrap();
|
2024-07-15 15:21:41 +00:00
|
|
|
// NameOrEntity Display for entities without a Name should be {index}v{generation}
|
2024-06-25 12:58:53 +00:00
|
|
|
assert_eq!(d1.to_string(), "0v1");
|
2024-07-15 15:21:41 +00:00
|
|
|
// NameOrEntity Display for entities with a Name should be the Name
|
2024-06-25 12:58:53 +00:00
|
|
|
assert_eq!(d2.to_string(), "MyName");
|
|
|
|
}
|
|
|
|
}
|