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

Add AssetChanged query filter #16810

Open
wants to merge 20 commits into
base: main
Choose a base branch
from

Conversation

tychedelia
Copy link
Contributor

@tychedelia tychedelia commented Dec 13, 2024

Objective

Implement a new AssetChanged query filter that allows users to query for entities whose related assets may have changed.

  • Closes A query filter for Asset updates #5069
  • Unblocks Cold specialization #16420. Currently, cold-specialization, a key rendering optimization for unlocking ancillary benefits of the retained render world, is blocked on being unable detect all scenarios in which an entity's mesh/material changes using events and observers. An AssetChanged filter will drastically simplify our implementation and be more robust to future changes.

Originally implemented by @nicopap in #5080.

Solution

  • Adds a new AssetChanged query filter that initializes a AssetChanges<A> resource that tracks changed assets and ticks in asset_events.
  • Reverts constrain WorldQuery::get_state to only use &Components #13343 and changes the api of get_state to accept impl Into<UnsafeWorldCell<'w>> to allow accessing the AssetChanges<A> resource.
  • Adds a AsAssetId trait used for newtype handle wrappers (e.g. Mesh3d) that allows associating a component with the underlying Asset it represents.

Testing

  • Tests are added for AssetChanged.
  • TBD on performance. We are going to add this Mesh3d and MeshMaterial3d (etc) in the renderer. Long term wins in render performance this unblocks should swamp tracking overhead for any realistic workload.

Migration Guide

  • The asset_events system is no longer public. Users should order their systems relative to the AssetEvents system set.

@tychedelia tychedelia added A-ECS Entities, components, systems, and events X-Contentious There are nontrivial implications that should be thought through S-Needs-Review Needs reviewer attention (from anyone!) to move forward S-Needs-SME Decision or review from an SME is required labels Dec 13, 2024
@tychedelia tychedelia changed the title Changed handle Add AssetChanged query filter Dec 13, 2024
@Victoronz
Copy link
Contributor

Victoronz commented Dec 13, 2024

Why does this revert the get_state PR? In the get_state impl of this PR, I only see a call to resource_id on world, which is already available on &Components.

@ItsDoot ItsDoot added the C-Usability A targeted quality-of-life change that makes Bevy easier to use label Dec 13, 2024
@tychedelia
Copy link
Contributor Author

Why does this revert the get_state PR? In the get_state impl of this PR, I only see a call to resource_id on world, which is already available on &Components.

Because I didn't know that. Will change it back!

@Victoronz
Copy link
Contributor

Victoronz commented Dec 13, 2024

Separately, how should the resource access in init_fetch be reasoned about?
A type being private means it cannot be mentioned in user code, however you do not have to mention a type to obtain it via public API! In this case, this is possible via id-based resource fetching.
UnsafeWorldCell::get_resource gives its caller the responsibility to ensure it has access to that resource, however this safety contract cannot be passed on to users of the filter.
For both users, libraries and other in-engine areas, how should we communicate about this?

@Victoronz Victoronz added the P-Unsound A bug that results in undefined compiler behavior label Dec 13, 2024
@@ -141,13 +141,15 @@
// FIXME(3492): remove once docs are ready
// FIXME(15321): solve CI failures, then replace with `#![expect()]`.
#![allow(missing_docs, reason = "Not all docs are written yet, see #3492.")]
#![allow(unsafe_code)]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we just #![allow(unsafe_code)] wherever we need it instead of throughout the crate?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's what the other crates seem to do, I'm not unsure about our policy here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Much prefer local allows here.


/// Filter that selects entities with a `A` for an asset that changed
/// after the system last ran, where `A` is a component that implements
/// [`AsAssetId`].
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about components that store handles to multiple assets of the same type? We don't need to do that right now, but we might have to revisit it later. In my app I have components with handles to dozens of AnimationClips for example. I think you could maybe just have AsAssetId's method return -> impl Iterator<Item = AssetId>.

This isn't blocking, just a suggestion.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The bigger issue is how to handle the associated type. We might have to use some kind of indirection via UntypedAssetId instead to be able to handle multiple kinds of assets.

crates/bevy_asset/src/asset_changed.rs Show resolved Hide resolved
crates/bevy_asset/src/asset_changed.rs Outdated Show resolved Hide resolved
crates/bevy_asset/src/lib.rs Outdated Show resolved Hide resolved
crates/bevy_asset/src/lib.rs Outdated Show resolved Hide resolved
crates/bevy_ecs/src/query/fetch.rs Outdated Show resolved Hide resolved
@tychedelia
Copy link
Contributor Author

In this case, this is possible via id-based resource fetching.

How would the user forge an id if they do not have access to the underlying type? UnsafeWorldCell::get_resource already documents the aliasing requirements as an unsafe API. If users are iterating or creating random opaque ComponentIds and getting mutable access they trivially violate that contract by not knowing what resource they are touching.

@pcwalton
Copy link
Contributor

Overall this looks fine to me, but as I mentioned we should have an ECS expert look over the get_state signature change.

#[inline]
fn update_component_access(state: &Self::State, access: &mut FilteredAccess<ComponentId>) {
<&A>::update_component_access(&state.asset_id, access);
access.add_resource_read(state.resource_id);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this line is quite enough. We need Query to report the access in Access<ArchetypeComponentId> for it to be used by the scheduler, and it currently does that in QueryState::update_archetype_component_access(), which only looks at component_reads_and_writes() and component_writes().

I think you need modify QueryState::new_with_access() to look at resource_reads_and_writes() and resource_writes() and convert them to ArchetypeComponentIds.

I think you also need to modify FilteredAccess::is_compatible() to consider resources to conflict even when the filters don't overlap. (That may need to get reworked in the future for resources-as-components, but the semantics seem reasonable.)

It would be good to add a unit test that verifies that the access is set up correctly. Maybe check that fn system(r: ResMut<AssetChanges<A>>, q: Query<Entity, AssetChanged<A>>) panics when passed to assert_system_does_not_conflict, and again with the parameters reversed.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright thanks for the close review. Will add a test to validate.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So just added a test and without making any other changes am getting the following error:

error[B0001]: Query<MyComponent, AssetChanged<MyComponent>> in system bevy_asset::asset_changed::tests::resource_conflict::system accesses component(s)AssetChanges<MyAsset> 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`. See: https://bevyengine.org/learn/errors/b0001

Thoughts?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, right, ResMut does unfiltered access, so FilteredAccess::is_compatible() will see that the filters overlap and catch it. Great! So that won't be a problem unless someone tries to do mutable resource access from a query.

I think it's just the Access<ArchetypeComponentId> that would be an issue, then. I'm not coming up with a simple way to write a test for that, though.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, I think it's just adding the following to QueryState::update_archetype_component_access? d0130a3

@alice-i-cecile alice-i-cecile added this to the 0.16 milestone Dec 13, 2024
@alice-i-cecile alice-i-cecile added D-Unsafe Touches with unsafe code in some way A-Assets Load files from disk to use for things like images, models, and sounds and removed P-Unsound A bug that results in undefined compiler behavior S-Needs-SME Decision or review from an SME is required labels Dec 13, 2024
@alice-i-cecile alice-i-cecile added the M-Needs-Release-Note Work that should be called out in the blog due to impact label Dec 14, 2024
@@ -583,6 +583,16 @@ impl<D: QueryData, F: QueryFilter> QueryState<D, F> {
{
access.add_component_write(archetype_component_id);
}
if self.component_access.access.has_resource_read(component_id) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh right, this is an existing soundness bug. Re-adding the tag.

@alice-i-cecile alice-i-cecile added the P-Unsound A bug that results in undefined compiler behavior label Dec 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-Assets Load files from disk to use for things like images, models, and sounds A-ECS Entities, components, systems, and events C-Usability A targeted quality-of-life change that makes Bevy easier to use D-Unsafe Touches with unsafe code in some way M-Needs-Release-Note Work that should be called out in the blog due to impact P-Unsound A bug that results in undefined compiler behavior S-Needs-Review Needs reviewer attention (from anyone!) to move forward X-Contentious There are nontrivial implications that should be thought through
Projects
None yet
Development

Successfully merging this pull request may close these issues.

A query filter for Asset updates
7 participants