Commit Graph

6865 Commits

Author SHA1 Message Date
François Mockers
c4b3d75b46 Release 0.16.0-rc.4 2025-04-11 09:12:55 +02:00
Zachary Harrold
c5365509bf Allow partial support for bevy_log in no_std (#18782)
- Fixes #18781

- Moved `LogPlugin` into its own file gated behind a new `tracing`
feature.
- Used `log` instead of `tracing` where possible.
- Exposed a new `tracing` feature in `bevy` which enables
`bevy_log/tracing`.
- Gated `LogPlugin` from `DefaultPlugins` on `tracing` feature.

- CI

---

- If you were previously using `bevy_log` with default features
disabled, enable the new `std` and `tracing` features.
- If you were using `bevy` with the default features disabled, enable
the new `tracing` feature.

Almost all of the diffs in this PR come from moving `LogPlugin` into its
own file. This just makes the PR less noisy, since the alternative is
excessive `#[cfg(feature = "tracing")]` directives all over the plugin.

---------

Co-authored-by: François Mockers <francois.mockers@vleue.com>
2025-04-11 09:03:12 +02:00
charlotte
3c5eb4473f Allowlist mali drivers for gpu preprocessing support. (#18769)
Fixes #17591

Looking at the arm downloads page, "r48p0" is a version number that
increments, where rXX is the major version and pX seems to be a patch
version. Take the conservative approach here that we know gpu
preprocessing is working on at least version 48 and presumably higher.
The assumption here is that the driver_info string will be reported
similarly on non-pixel devices.
2025-04-11 08:59:57 +02:00
Alice Cecile
89c02ef296 Fix system param validation for piped systems (#18785)
# Objective

- Piped systems are an edge case that we missed when reworking system
parameter validation.
- Fixes #18755.

## Solution

- Validate the parameters for both systems, ~~combining the errors if
both failed validation~~ by simply using an early out.
- ~~Also fix the same bug for combinator systems while we're here.~~

## Testing

I've added a large number of tests checking the behavior under various
permutations. These are separate tests, rather than one mega test
because a) it's easier to track down bugs that way and b) many of these
are `should_panic` tests, which will halt the evaluation of the rest of
the test!

I've also added a test for exclusive systems being pipeable because we
don't have one and I was very surprised that that works!

---------

Co-authored-by: Chris Russell <8494645+chescock@users.noreply.github.com>
2025-04-11 08:59:57 +02:00
Carter Anderson
5db383ca9c Ignore RenderEntity during entity clones (#18798)
# Objective

Fixes #18795

## Solution

Ignore RenderEntity during entity clones
2025-04-10 23:16:19 +02:00
Gilles Henaux
9ef8d19590 Fix documentation: incorrect references to the Update schedule in ExitCondition (#18438)
# Objective

- The referenced `ScheduleLabel` for `OnPrimaryClosed` and `OnAllClosed`
in `ExitCondition` was incorrect

## Solution

- Changed `Update` to `PostUpdate`
2025-04-10 23:16:19 +02:00
Greeble
1c3a63ad47 Fix newline in PointLightShadowMap comment (#18791)
A clippy failure slipped into #18768, although I'm not sure why CI
didn't catch it.

```sh
> cargo clippy --version
clippy 0.1.85 (4eb161250e 2025-03-15)

> cargo run -p ci
...
error: empty line after doc comment
   --> crates\bevy_pbr\src\light\mod.rs:105:5
    |
105 | /     /// The width and height of each of the 6 faces of the cubemap.
106 | |
    | |_^
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#empty_line_after_doc_comments
    = note: `-D clippy::empty-line-after-doc-comments` implied by `-D warnings`
    = help: to override `-D warnings` add `#[allow(clippy::empty_line_after_doc_comments)]`
    = help: if the empty line is unintentional remove it
help: if the documentation should include the empty line include it in the comment
    |
106 |     ///
    |
```
2025-04-10 22:29:10 +02:00
Zachary Harrold
c56d9a3c1b Add ? (#18783)
# Objective

- Fixes #18780

## Solution

- Add `?`

## Testing

- CI

---

## Notes

_smol_
2025-04-10 22:29:09 +02:00
jf908
50b00c8dc2 Small docs PR for PointLightShadowMap/DirectionalLightShadowMap (#18768)
# Objective

- Improve the docs for `PointLightShadowMap` and
`DirectionalLightShadowMap`

## Solution

- Add example for how to use `PointLightShadowMap` and move the
`DirectionalLightShadowMap` example from `DirectionalLight`.
- Match `PointLight` and `DirectionalLight` docs about shadows.
- Describe what `size` means.

---------

Co-authored-by: Robert Swain <robert.swain@gmail.com>
2025-04-10 01:19:35 +02:00
charlotte
ef8a4e0100 Fix forward decal depth_fade_factor. (#18772)
Fixes #18758
2025-04-10 01:19:34 +02:00
charlotte
8c2ef6bf43 Add binned 2d/3d Wireframe render phase (#18587)
# Objective

Fixes #16896
Fixes #17737

## Solution

Adds a new render phase, including all the new cold specialization
patterns, for wireframes. There's a *lot* of regrettable duplication
here between 3d/2d.

## Testing

All the examples.

## Migration Guide
- `WireframePlugin` must now be created with
`WireframePlugin::default()`.
2025-04-10 01:19:34 +02:00
Patrick Walton
d55f47d00a Unify RenderMaterialInstances and RenderMeshMaterialIds, and fix an associated race condition. (#18734)
Currently, `RenderMaterialInstances` and `RenderMeshMaterialIds` are
very similar render-world resources: the former maps main world meshes
to typed material asset IDs, and the latter maps main world meshes to
untyped material asset IDs. This is needlessly-complex and wasteful, so
this patch unifies the two in favor of a single untyped
`RenderMaterialInstances` resource.

This patch also fixes a subtle issue that could cause mesh materials to
be incorrect if a `MeshMaterial3d<A>` was removed and replaced with a
`MeshMaterial3d<B>` material in the same frame. The problematic pattern
looks like:

1. `extract_mesh_materials<B>` runs and, seeing the
`Changed<MeshMaterial3d<B>>` condition, adds an entry mapping the mesh
to the new material to the untyped `RenderMeshMaterialIds`.

2. `extract_mesh_materials<A>` runs and, seeing that the entity is
present in `RemovedComponents<MeshMaterial3d<A>>`, removes the entry
from `RenderMeshMaterialIds`.

3. The material slot is now empty, and the mesh will show up as whatever
material happens to be in slot 0 in the material data slab.

This commit fixes the issue by splitting out `extract_mesh_materials`
into *three* phases: *extraction*, *early sweeping*, and *late
sweeping*, which run in that order:

1. The *extraction* system, which runs for each material, updates
`RenderMaterialInstances` records whenever `MeshMaterial3d` components
change, and updates a change tick so that the following system will know
not to remove it.

2. The *early sweeping* system, which runs for each material, processes
entities present in `RemovedComponents<MeshMaterial3d>` and removes each
such entity's record from `RenderMeshInstances` only if the extraction
system didn't update it this frame. This system runs after *all*
extraction systems have completed, fixing the race condition.

3. The *late sweeping* system, which runs only once regardless of the
number of materials in the scene, processes entities present in
`RemovedComponents<ViewVisibility>` and, as in the early sweeping phase,
removes each such entity's record from `RenderMeshInstances` only if the
extraction system didn't update it this frame. At the end, the late
sweeping system updates the change tick.

Because this pattern happens relatively frequently, I think this PR
should land for 0.16.
2025-04-10 01:19:34 +02:00
charlotte
553c322d54 Initialize pre-processing pipelines only when culling is enabled. (#18759)
Better fix for #18463 that still allows enabling mesh preprocessing on
webgpu.

Fixes #18463
2025-04-10 01:19:34 +02:00
Patrick Walton
76422f71cd Make the StandardMaterial bindless index table have a fixed size regardless of the features that are enabled. (#18771)
Due to the preprocessor usage in the shader, different combinations of
features could cause the fields of `StandardMaterialBindings` to shift
around. In certain cases, this could cause them to not line up with the
bindings specified in `StandardMaterial`. This resulted in #18104.

This commit fixes the issue by making `StandardMaterialBindings` have a
fixed size. On the CPU side, it uses the
`#[bindless(index_table(range(M..N)))]` feature I added to `AsBindGroup`
in #18025 to do so. Thus this patch has a dependency on #18025.

Closes #18104.

---------

Co-authored-by: Robert Swain <robert.swain@gmail.com>
2025-04-10 01:19:34 +02:00
Brian Reavis
8eb85ea720 Fix get_render_pipeline_state / get_compute_pipeline_state panic (#18752)
This fixes a panic that occurs if one calls
`PipelineCache::get_render_pipeline_state(id)` or
`PipelineCache::get_compute_pipeline_state(id)` with a queued pipeline
id that has not yet been processed by `PipelineCache::process_queue()`.

```
thread 'Compute Task Pool (0)' panicked at [...]/bevy/crates/bevy_render/src/render_resource/pipeline_cache.rs:611:24:
index out of bounds: the len is 0 but the index is 20
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```
2025-04-10 01:19:33 +02:00
charlotte
1830a99785 Fix unbatchable meshes. (#18761)
# Objective

Fixes #18550.

Because bin state for unbatchable meshes wasn't being cleared each
frame, the buffer indices for unbatchable meshes would demote from
sparse to dense storage and aggressively leak memory, with all kinds of
weird consequences downstream, namely supplying invalid instance ranges
for render.

## Solution

Clear out the unbatchable mesh bin state when we start a new frame.
2025-04-10 01:19:33 +02:00
Patrick Walton
8a066faea9 Add bindless support back to ExtendedMaterial. (#18025)
PR #17898 disabled bindless support for `ExtendedMaterial`. This commit
adds it back. It also adds a new example, `extended_material_bindless`,
showing how to use it.
2025-04-10 01:19:33 +02:00
Freyja-moth
772524b3a6 Change with_related to work with a Bundle and added with_relationships method (#18699)
# Objective

Fixes #18678

## Solution

Moved the current `with_related` method to `with_relationships` and
added a new `with_related` that uses a bundle.

I'm not entirely sold on the name just yet, if anyone has any ideas let
me know.

## Testing

I wasn't able to test these changes because it crashed my computer every
time I tried (fun). But there don't seem to be any tests that use the
old `with_related` method so it should be fine, hopefully

## Showcase

```rust
commands.spawn_empty()
    .with_related::<Relationship>(Name::new("Related thingy"))
    .with_relationships(|rel| {
        rel.spawn(Name::new("Second related thingy"));
    });
```

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2025-04-10 01:19:33 +02:00
Moony
83a78d8583 Expose the added tick for change detection, both getting and setting. (#18746)
# Objective

- Allow viewing and setting the added tick for change detection aware
data, to allow operations like checking if the value has been modified
since first being added, and spoofing that state (i.e. returning the
value to default in place without a remove/insert dance)

## Solution

- Added corresponding functions matching the existing `changed` API:
  - `fn added(&self) -> Tick`
  - `fn set_added(&mut self)`
  - `fn set_last_added(&mut self, last_added: Tick)`

Discussed on discord @
https://canary.discord.com/channels/691052431525675048/749335865876021248/1358718892465193060

## Testing

- Running the bevy test suite by.. making a PR, heck.
- No new tests were introduced due to triviality (i.e. I don't know what
to test about this API, and the corresponding API for `changed` is
similarly lacking tests.)

---------

Co-authored-by: moonheart08 <moonheart08@users.noreply.github.com>
Co-authored-by: SpecificProtagonist <vincentjunge@posteo.net>
Co-authored-by: Chris Russell <8494645+chescock@users.noreply.github.com>
2025-04-09 00:21:42 +02:00
ickshonpe
3cd83031e1 Fix AccessKit node bounds (#18706)
# Objective

Fixes #18685

## Solution

* Don't apply the camera translation.
* Calculate the min and max bounds of the accessibility node rect taking
the UI translation relative to its center not the top-left corner.

## Testing

Install [NVDA](https://www.nvaccess.org/). In NVDA set `Preferences ->
Settings -> Vision -> Enable Highlighting`.

Then run bevy's `tab_navigation` example:
```
cargo run --example tab_navigation
```
If everything is working correctly, NVDA should draw a border around the
currently selected tab button:

![Screenshot 2025-04-07
130523](https://github.com/user-attachments/assets/07d9a795-5d55-4b61-9602-2e8917020245)
2025-04-09 00:21:41 +02:00
Jaso333
c439fdb34c clarified docs for bundle removal commands (#18754)
# Objective

Clarify information in the docs about the bundle removal commands.

## Solution

Added information about how the intersection of components are removed.
2025-04-09 00:21:41 +02:00
Máté Homolya
6e147d35f2 Web support for atmosphere (#18582)
# Objective

Add web support to atmosphere by gating dual source blending and using a
macro to determine the target platform.
The main objective of this PR is to ensure that users of Bevy's
atmosphere feature can also run it in a web-based context where WebGPU
support is enabled.

## Solution

- Make use of the `#[cfg(not(target_arch = "wasm32"))]` macro to gate
the dual source blending, as this is not (yet) supported in web
browsers.
- Rename the function `sample_sun_illuminance` to `sample_sun_radiance`
and move calls out of conditionals to ensure the shader compiles and
runs in both native and web-based contexts.
- Moved the multiplication of the transmittance out when calculating the
sun color, because calling the `sample_sun_illuminance` function was
causing issues in web. Overall this results in cleaner code and more
readable.

## Testing

- Tested by building a wasm target and loading it in a web page with
Vite dev server using `mate-h/bevy-webgpu` repo template.
- Tested the native build with `cargo run --example atmosphere` to
ensure it still works with dual source blending.

---

## Showcase

Screenshots show the atmosphere example running in two different
contexts:

<img width="1281" alt="atmosphere-web-showcase"
src="https://github.com/user-attachments/assets/40b1ee91-89ae-41a6-8189-89630d1ca1a6"
/>

---------

Co-authored-by: JMS55 <47158642+JMS55@users.noreply.github.com>
2025-04-09 00:21:41 +02:00
Greeble
8f083307c3 Remove WebGL padding from MotionBlur (#18727)
## Objective

The `MotionBlur` component exposes renderer internals. Users shouldn't
have to deal with this.

```rust
MotionBlur {
    shutter_angle: 1.0,
    samples: 2,
    #[cfg(all(feature = "webgl2", target_arch = "wasm32", not(feature = "webgpu")))]
    _webgl2_padding: Default::default(),
},
```

## Solution

The renderer now uses a separate `MotionBlurUniform` struct for its
internals. `MotionBlur` no longer needs padding.

I was a bit unsure about the name `MotionBlurUniform`. Other modules use
a mix of `Uniform` and `Uniforms`.

## Testing

```
cargo run --example motion_blur
```

Tested on Win10/Nvidia across Vulkan, WebGL/Chrome, WebGPU/Chrome.
2025-04-09 00:21:41 +02:00
Zachary Harrold
f3f4e80d87 Newtype hashbrown (#18694)
# Objective

- Fixes #18690
- Closes [#2065](https://github.com/bevyengine/bevy-website/pull/2065)
- Alternative to #18691

The changes to the Hash made in #15801 to the
[BuildHasher](https://doc.rust-lang.org/std/hash/trait.BuildHasher.html)
resulted in serious migration problems and downgraded UX for users of
Bevy's re-exported hashmaps. Once merged, we need to go in and remove
the migration guide added as part of #15801.

## Solution

- Newtype `HashMap` and `HashSet` instead of type aliases
- Added `Deref/Mut` to allow accessing future `hashbrown` methods
without maintenance from Bevy
- Added bidirectional `From` implementations to provide escape hatch for
API incompatibility
- Added inlinable re-exports of all methods directly to Bevy's types.
This ensures `HashMap::new()` works (since the `Deref` implementation
wont cover these kinds of invocations).

## Testing

- CI

---

## Migration Guide

- If you relied on Bevy's `HashMap` and/or `HashSet` types to be
identical to `hashbrown`, consider using `From` and `Into` to convert
between the `hashbrown` and Bevy types as required.
- If you relied on `hashbrown/serde` or `hashbrown/rayon` features, you
may need to enable `bevy_platform_support/serialize` and/or
`bevy_platform_support/rayon` respectively.

---

## Notes

- Did not replicate the Rayon traits, users will need to rely on the
`Deref/Mut` or `From` implementations for those methods.
- Did not re-expose the `unsafe` methods from `hashbrown`. In most cases
users will still have access via `Deref/Mut` anyway.
- I have added `inline` to all methods as they are trivial wrappings of
existing methods.
- I chose to make `HashMap::new` and `HashSet::new` const, which is
different to `hashbrown`. We can do this because we default to a
fixed-state build-hasher. Mild ergonomic win over using
`HashMap::with_hasher(FixedHasher)`.
2025-04-09 00:21:41 +02:00
Greeble
3d17865c2e Fix many_foxes + motion blur = crash on WebGL (#18715)
## Objective

Fix  #18714.

## Solution

Make sure `SkinUniforms::prev_buffer` is resized at the same time as
`current_buffer`.

There will be a one frame visual glitch when the buffers are resized,
since `prev_buffer` is incorrectly initialised with the current joint
transforms.

Note that #18074 includes the same fix. I'm assuming this smaller PR
will land first.

## Testing

See repro instructions in #18714. Tested on `animated_mesh`,
`many_foxes`, `custom_skinned_mesh`, Win10/Nvidia with Vulkan,
WebGL/Chrome, WebGPU/Chrome.
2025-04-09 00:21:40 +02:00
Hennadii Chernyshchyk
0c831d2caa Add Default for all schedule labels (#18731)
# Objective

In `bevy_enhanced_input`, I'm trying to associate `Actions` with a
schedule. I can do this via an associated type on a trait, but there's
no way to construct the associated label except by requiring a `Default`
implementation. However, Bevy labels don't implement `Default`.

## Solution

Add `Default` to all built-in labels. I think it should be useful in
general.
2025-04-09 00:21:40 +02:00
Brian Reavis
3b1cda2ebd Expose TextureFormatFeatureFlags, TextureFormatFeatures from wgpu (#18721)
# Objective

This PR exposes the wgpu types necessary to use the result of
`RenderAdapter::get_texture_format_features`:

```rust
use bevy::render::render_resource::TextureFormatFeatureFlags;
// ^ now available

let adapter = world.resource::<RenderAdapter>();
let flags = adapter.get_texture_format_features(TextureFormat::R32Float).flags;
let filtering = flags.contains(TextureFormatFeatureFlags::FILTERABLE);
```

## Solution

- Expose `TextureFormatFeatureFlags`, `TextureFormatFeatures` like other
wgpu types in bevy_render
2025-04-09 00:21:40 +02:00
person93
f3323f8b14 Add accessors to DynamicEnum for the DynamicVariant (#18693)
# Objective

- Closes https://github.com/bevyengine/bevy/issues/18692

## Solution

Add the methods as described
```rust
impl DynamicEnum {
    fn variant(&self) -> &DynamicVariant;
    fn variant_mut(&mut self) -> &mut DynamicVariant;
}
```
2025-04-09 00:21:40 +02:00
Greeble
76318d99d7 Fix motion blur on skinned meshes (#18712)
## Objective

Fix motion blur not working on skinned meshes.

## Solution

`set_mesh_motion_vector_flags` can set
`RenderMeshInstanceFlags::HAS_PREVIOUS_SKIN` after specialization has
already cached the material. This can lead to
`MeshPipelineKey::HAS_PREVIOUS_SKIN` never getting set, disabling motion
blur.

The fix is to make sure `set_mesh_motion_vector_flags` happens before
specialization.

Note that the bug is fixed in a different way by #18074, which includes
other fixes but is a much larger change.

## Testing

Open the `animated_mesh` example and add these components to the
`Camera3d` entity:

```rust
MotionBlur {
    shutter_angle: 5.0,
    samples: 2,
    #[cfg(all(feature = "webgl2", target_arch = "wasm32", not(feature = "webgpu")))]
    _webgl2_padding: Default::default(),
},
#[cfg(all(feature = "webgl2", target_arch = "wasm32", not(feature = "webgpu")))]
Msaa::Off,
```

Tested on `animated_mesh`, `many_foxes`, `custom_skinned_mesh`,
Win10/Nvidia with Vulkan, WebGL/Chrome, WebGPU/Chrome. Note that testing
`many_foxes` WebGL requires #18715.
2025-04-05 01:08:55 +02:00
Lucas Franca
ded663b9b9 Add PartialEq and Hash reflections for AnimationNodeIndex (#18718)
# Objective

Fixes #18701

## Solution

Add reflection of `PartialEq` and `Hash` to `AnimationNodeIndex`

## Testing

Added a new `#[test]` with the minimal reproduction posted on #18701.
2025-04-04 23:16:49 +02:00
BD103
0b3a51bd7e Add #[deprecated(since = "0.16.0", ...)] to items missing it (#18702)
- The `#[deprecated]` attributes supports a `since` field, which
documents in which version an item was deprecated. This field is visible
in `rustdoc`.
- We inconsistently use `since` throughout the project.

For an example of what `since` renders as, take a look at
`ChildOf::get()`:

```rust
/// The parent entity of this child entity.
pub fn get(&self) -> Entity {
    self.0
}
```

![image](https://github.com/user-attachments/assets/2ea5d8c9-2eab-430a-9a1c-421f315ff123)

- Add `since = "0.16.0"` to all `#[deprecated]` attributes that do not
already use it.
- Add an example of deprecating a struct with the `since` field in the
migration guide document.

I would appreciate if this could be included in 0.16's release, as its a
low-risk documentation improvement that is valuable for the release, but
I'd understand if this was cut.

You can use `cargo doc` to inspect the rendered form of
`#[deprecated(since = "0.16.0", ...)]`.
2025-04-03 21:46:46 +02:00
Vic
c9fb956058 use entity set collections type aliases instead of defaults (#18695)
# Objective

Newest installment of the #16547 series.

In #18319 we introduced `Entity` defaults to accomodate the most common
use case for these types, however that resulted in the switch of the `T`
and `N` generics of `UniqueEntityArray`.
Swapping generics might be somewhat acceptable for `UniqueEntityArray`,
it is not at all acceptable for map and set types, which we would make
generic over `T: EntityEquivalent` in #18408.

Leaving these defaults in place would result in a glaring inconsistency
between these set collections and the others.

Additionally, the current standard in the engine is for "entity" to mean
`Entity`. APIs could be changed to accept `EntityEquivalent`, however
that is a separate and contentious discussion.

## Solution

Name these set collections `UniqueEntityEquivalent*`, and retain the
`UniqueEntity*` name for an alias of the `Entity` case.
While more verbose, this allows for all generics to be in proper order,
full consistency between all set types*, and the "entity" name to be
restricted to `Entity`.
On top of that, `UniqueEntity*` now always have 1 generic less, when
previously this was not enforced for the default case.

*`UniqueEntityIter<I: Iterator<T: EntityEquivalent>>` is the sole
exception to this. Aliases are unable to enforce bounds
(`lazy_type_alias` is needed for this), so for this type, doing this
split would be a mere suggestion, and in no way enforced.
Iterator types are rarely ever named, and this specific one is intended
to be aliased when it sees more use, like we do for the corresponding
set collection iterators.
Furthermore, the `EntityEquivalent` precursor `Borrow<Entity>` was used
exactly because of such iterator bounds!
Because of that, we leave it as is.

While no migration guide for 0.15 users, for those that upgrade from
main:
`UniqueEntityVec<T>` -> `UniqueEntityEquivalentVec<T>`
`UniqueEntitySlice<T>` -> `UniqueEntityEquivalentSlice<T>`
`UniqueEntityArray<N, T>` -> `UniqueEntityEquivalentArray<T, N>`
2025-04-03 21:45:44 +02:00
Periwink
2771803cbd add reflect for SocketAddr (#18676) 2025-04-03 21:45:43 +02:00
Chris Russell
ed28b5ccf7 Improve error message for missing events (#18683)
# Objective

Improve the parameter validation error message for
`Event(Reader|Writer|Mutator)`.

System parameters defined using `#[derive(SystemParam)]`, including the
parameters for events, currently propagate the validation errors from
their subparameters. The error includes the type of the failing
parameter, so the resulting error includes the type of the failing
subparameter instead of the derived parameter.

In particular, `EventReader<T>` will report an error from a
`Res<Events<T>>`, even though the user has no parameter of that type!

This is a follow-up to #18593.

## Solution

Have `#[derive]`d system parameters map errors during propagation so
that they report the outer parameter type.

To continue to provide context, add a field to
`SystemParamValidationError` that identifies the subparameter by name,
and is empty for non-`#[derive]`d parameters.

Allow them to override the failure message for individual parameters.
Use this to convert "Resource does not exist" to "Event not initialized"
for `Event(Reader|Writer|Mutator)`.

## Showcase

The validation error for a `EventReader<SomeEvent>` parameter when
`add_event` has not been called changes from:

Before: 
```
Parameter `Res<Events<SomeEvent>>` failed validation: Resource does not exist
```

After
```
Parameter `EventReader<SomeEvent>::events` failed validation: Event not initialized
```
2025-04-03 21:45:43 +02:00
BD103
4b5df0f1ab Fix indentation of bevy/query strict parameter in docs (#18681)
# Objective

- The `strict` field of
[`BrpQueryParams`](https://dev-docs.bevyengine.org/bevy/remote/builtin_methods/struct.BrpQueryParams.html)
was newly added as part of 0.16.
- Its documentation in `lib.rs` improperly indents `strict`, making look
like its part of
[`BrpQueryFilter`](https://dev-docs.bevyengine.org/bevy/remote/builtin_methods/struct.BrpQueryFilter.html):


![image](https://github.com/user-attachments/assets/f49521da-36d3-4d5d-a7ea-f7a44ddaf195)

## Solution

- Fix `strict`'s indentation so its clear that it is a field of
`BrpQueryParams`, not `BrpQueryFilter`.

I would like this to be included in 0.16, since it's a trivial
documentation change that fixes an error, but if it needs to be removed
from the milestone that's fine.

## Testing

Run `cargo doc -p bevy_remote --no-deps` and verify the indentation is
fixed. :)
2025-04-03 21:45:43 +02:00
JaySpruce
deba691fff Implement insert_children for EntityCommands (#18675)
Extension of #18409.

I was updating a migration guide for hierarchy commands and realized
`insert_children` wasn't added to `EntityCommands`, only
`EntityWorldMut`.

This adds that and `insert_related` (basically just some
copy-and-pasting).
2025-04-03 21:45:43 +02:00
Carter Anderson
1553ee98ff Switch ChildOf back to tuple struct (#18672)
# Objective

In #17905 we swapped to a named field on `ChildOf` to help resolve
variable naming ambiguity of child vs parent (ex: `child_of.parent`
clearly reads as "I am accessing the parent of the child_of
relationship", whereas `child_of.0` is less clear).

Unfortunately this has the side effect of making initialization less
ideal. `ChildOf { parent }` reads just as well as `ChildOf(parent)`, but
`ChildOf { parent: root }` doesn't read nearly as well as
`ChildOf(root)`.

## Solution

Move back to `ChildOf(pub Entity)` but add a `child_of.parent()`
function and use it for all accesses. The downside here is that users
are no longer "forced" to access the parent field with `parent`
nomenclature, but I think this strikes the right balance.

Take a look at the diff. I think the results provide strong evidence for
this change. Initialization has the benefit of reading much better _and_
of taking up significantly less space, as many lines go from 3 to 1, and
we're cutting out a bunch of syntax in some cases.

Sadly I do think this should land in 0.16 as the cost of doing this
_after_ the relationships migration is high.
2025-04-03 21:45:43 +02:00
JaySpruce
5cbc20f787 Update relationship commands to use EntityCommands instead of Commands (#18667)
These should use `EntityCommands` so that the entity existence check is
hooked up to the default error handler, rather than only panicking.
2025-04-03 21:45:43 +02:00
ickshonpe
8be04958c1 Remove the visited local system param from update_ui_context_system. (#18664)
# Objective

The `visited: Local<HashSet<Entity>>` system param is meant to track
which entities `update_contexts_recursively` has visited and updated but
when the reparent_nodes_query isn't ordered descending from parent to
child nodes can get marked as visited even though their camera target is
unset and if the camera target is unset then the node won't be rendered.

Fixes #18616

## Solution

Remove the `visited` system param from `update_ui_context_system` and
the associated visited check from `update_contexts_recursively`. It was
redundant anyway since the set_if_neq check is sufficient to track
already updated nodes.

## Testing

The example from #18616 can be used for testing.
2025-04-03 21:45:42 +02:00
Chris Russell
9d4d110704 Include SystemParamValidationError in RunSystemError and RegisteredSystemError (#18666)
# Objective

Provide more useful errors when `World::run_system` and related methods
fail parameter validation.

Let callers determine whether the validation failure would have skipped
or failed the system.

Follow-up to #18541.

## Solution

Add a `SystemParamValidationError` value to the
`RunSystemError::InvalidParams` and
`RegisteredSystemError::InvalidParams` variants. That includes the
complete context of the parameter validation error, including the
`skipped` flag.
2025-04-03 21:45:42 +02:00
JaySpruce
4ad5f464ea Add notes to fallible commands (#18649)
Follow-up to #18639.

Fallible commands should have notes explaining how they can fail, what
error they return, and how it's handled.
2025-04-03 21:45:42 +02:00
Eagster
11ad3b6dde Finish #17558, re-adding insert_children (#18409)
fixes #17478

# Objective

- Complete #17558.
- the `insert_children` method was previously removed, and as #17478
points out, needs to be added back.

## Solution

- Add a `OrderedRelationshipSourceCollection`, which allows sorting,
ordering, rearranging, etc of a `RelationshipSourceCollection`.
- Implement `insert_related`
- Implement `insert_children`
- Tidy up some docs while I'm here.

## Testing

@bjoernp116 set up a unit test, and I added a doc test to
`OrderedRelationshipSourceCollection`.

---------

Co-authored-by: bjoernp116 <bjoernpollen@gmail.com>
Co-authored-by: Dmytro Banin <banind@cs.washington.edu>
Co-authored-by: Talin <viridia@gmail.com>
2025-04-03 21:45:42 +02:00
Eagster
202faf6a1c Get names of queued components (#18451)
# Objective

#18173 allows components to be queued without being fully registered.
But much of bevy's debug logging contained
`components.get_name(id).unwrap()`. However, this panics when the id is
queued. This PR fixes this, allowing names to be retrieved for debugging
purposes, etc, even while they're still queued.

## Solution

We change `ComponentInfo::descriptor` to be `Arc<ComponentDescriptor>`
instead of not arc'd. This lets us pass the descriptor around (as a name
or otherwise) as needed. The alternative would require some form of
`MappedRwLockReadGuard`, which is unstable, and would be terribly
blocking. Putting it in an arc also signifies that it doesn't change,
which is a nice signal to users. This does mean there's an extra pointer
dereference, but I don't think that's an issue here, as almost all paths
that use this are for debugging purposes or one-time set ups.

## Testing

Existing tests.

## Migration Guide

`Components::get_name` now returns `Option<Cow<'_, str>` instead of
`Option<&str>`. This is because it now returns results for queued
components. If that behavior is not desired, or you know the component
is not queued, you can use
`components.get_info().map(ComponentInfo::name)` instead.

Similarly, `ScheduleGraph::conflicts_to_string` now returns `impl
Iterator<Item = (String, String, Vec<Cow<str>>)>` instead of `impl
Iterator<Item = (String, String, Vec<&str>)>`. Because `Cow<str>` derefs
to `&str`, most use cases can remain unchanged.

---------

Co-authored-by: Chris Russell <8494645+chescock@users.noreply.github.com>
2025-04-03 21:45:42 +02:00
Zachary Harrold
7925e03f7f Add sleep based on spin to bevy_platform_support (#18633)
# Objective

- Fixes #18617

## Solution

- Added `thread::sleep` to `bevy_platform_support` using a spin-based
fallback.
- Fixed bug in `bevy_platform_support::time::Instant::elapsed`
(comparison was backwards)
- Switched `ScheduleRunnerPlugin` to use
`bevy_platform_support:🧵:sleep` on `std` and `no_std` platforms
(WASM + Browser excluded)

## Testing

- Ran reproduction code from @mockersf in linked issue and confirmed a
consistent 60 counts per `println!`.

---

## Notes

- I chose to add `bevy_platform_support:🧵:sleep` instead of
putting the fix in-line within `ScheduleRunnerPlugin` to keep the
separation of concerns clean. `sleep` is only used in one other location
in Bevy, `bevy_asset`, but I have decided to leave that as-is since
`bevy_asset` isn't `no_std` compatible anyway.
- The bug in `bevy_platform_support::time::Instant::elapsed` wasn't the
cause of this issue, but it did prevent this fix from working so I have
included the it in this PR.
2025-04-03 21:45:42 +02:00
François Mockers
bdfd7a3443 Release 0.16.0-rc.3 2025-03-31 23:07:43 +02:00
JaySpruce
735c43390c bevy_ecs/system/commands/ folder docs pass (#18639)
- Lots of nits, formatting, and rephrasing, with the goal of making
things more consistent.
- Fix outdated error handler explanation in `Commands` and
`EntityCommands` docs.
- Expand docs for system-related commands.
- Remove panic notes if the command only panics with the default error
handler.
- Update error handling notes for `try_` variants.
- Hide `prelude` import in most doctest examples, unless the example
uses something that people might not realize is in the prelude (like
`Name`).
- Remove a couple doctest examples that (in my opinion) didn't make
sense.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Chris Russell <8494645+chescock@users.noreply.github.com>
2025-03-31 22:36:30 +02:00
charlotte
831c57d8b1 Fix no indirect drawing (#18628)
# Objective

The `NoIndirectDrawing` wasn't working and was causing the scene not to
be rendered.

## Solution

Check the configured preprocessing mode when adding new batch sets and
mark them as batchable instead of muli-drawable if indirect rendering
has been disabled.

## Testing

`cargo run --example many_cubes -- --no-indirect-drawing`
2025-03-31 22:36:30 +02:00
Zachary Harrold
a2b14983f4 Upgrade to Glam 0.29.3 and Simplify Feature Gating (#18638)
- Fixes #18397
- Supersedes #18474
- Simplifies 0.16 migration

- Upgrade to Glam 0.29.3, which has backported the `nostd-libm` feature.
- Expose a similar feature in `bevy_math` and enable it in
`bevy_internal`, allowing `bevy_math`, `bevy_input`, and
`bevy_transform` to be unconditional dependencies again.

- CI

---

- This includes `libm` as a dependency, but this was already the case in
the common scenario where `rand` or many other features were enabled.
Considering `libm` is an official Rust crate, it's a very low-risk
dependency to unconditionally include.
- For users who do not want `libm` included, simply import Bevy's
subcrates directly, since `bevy_math/nostd-libm` will not be enabled.
- I know we are _very_ late in the RC cycle for 0.16, but this has a
substantial impact on the usability of `bevy` that I consider worth
including.
2025-03-31 22:36:16 +02:00
Beni Bachmann
10daca0947 Return triangle index instead of vertex index (Fixes #18081) (#18647)
# Objective

- Fixes #18081
- Enable use-cases like getting UVs or texture colors for the hit point
(which are currently not possible due to this bug).

## Solution

- Return the triangle index instead of the first vertex index of the
triangle.

## Testing

Tested successfully with my project which does a raycast to get the UV
coordinates of the hit. My code:
```rust
fn get_uv(
    mesh: &Mesh,
    attribute: &MeshVertexAttribute,
    hit: &RayMeshHit,
    _gizmos: &mut Gizmos,
) -> Result<Vec2> {
    let (a, b, c) = get_indices(mesh, hit)?;

    let attrs = mesh
        .attribute(*attribute)
        .ok_or_eyre(format!("Attribute {:?} not found", &attribute))?;
    let all_uvs: &Vec<[f32; 2]> = match &attrs {
        VertexAttributeValues::Float32x2(positions) => positions,
        _ => bail!("Unexpected types in {:?}", Mesh::ATTRIBUTE_UV_0),
    };

    let bary = hit.barycentric_coords;

    Ok(Vec2::from_array(all_uvs[a]) * bary.x
        + Vec2::from_array(all_uvs[b]) * bary.y
        + Vec2::from_array(all_uvs[c]) * bary.z)
}

fn get_indices(mesh: &Mesh, hit: &RayMeshHit) -> Result<(usize, usize, usize)> {
    let i = hit
        .triangle_index
        .ok_or_eyre("Intersection Index not found")?;

    Ok(mesh.indices().map_or_else(
        || (i, i + 1, i + 2),
        |indices| match indices {
            Indices::U16(indices) => (
                indices[i * 3] as usize,
                indices[i * 3 + 1] as usize,
                indices[i * 3 + 2] as usize,
            ),
            Indices::U32(indices) => (
                indices[i * 3] as usize,
                indices[i * 3 + 1] as usize,
                indices[i * 3 + 2] as usize,
            ),
        },
    ))
}
```

PS: created a new PR because the old one was coming from and targeting
the wrong branches
2025-03-31 22:33:28 +02:00
Lucas Franca
eb37e86a1f Make bindings behind pbr_specular_textures flag consistent with other gated fields (#18645)
# Objective

Make all feature gated bindings consistent with each other

## Solution

Make the bindings of fields gated by `pbr_specular_textures` feature
consistent with the other gated bindings
2025-03-31 22:33:28 +02:00
HugoPeters1024
3e7c6a6e9e 0.16 Regression fix: re-expose the display handle via a wrapper resource (#18644)
# Objective

- In the latest released version (15.3) I am able to obtain this
information by getting the actual `EventLoop` via `non_send_resource`.
Now that this object has (probably rightfully so) been replaced by the
`EventLoopProxy`, I can no longer maintain my custom render backend:
https://github.com/HugoPeters1024/bevy_vulkan. I also need the display
handle for a custom winit integration, for which I've made patches to
bevy before: XREF: https://github.com/bevyengine/bevy/pull/15884


## Solution

- Luckily, all that is required is exposing the `OwnedDisplayHandle` in
its own wrapper resource.

## Testing

- Aforementioned custom rendering backend works on this commit.

---------

Co-authored-by: HugoPeters1024 <hugopeters1024@gmail.com>
2025-03-31 22:33:28 +02:00
andriyDev
4fc4fa4559 Delete unused weak handle and remove duplicate loads. (#18635)
# Objective

- Cleanup

## Solution

- Remove completely unused weak_handle
(`MESH_PREPROCESS_TYPES_SHADER_HANDLE`). This value is not used
directly, and is never populated.
- Delete multiple loads of `BUILD_INDIRECT_PARAMS_SHADER_HANDLE`. We
load it three times right after one another. This looks to be a
copy-paste error.

## Testing

- None.
2025-03-31 22:33:28 +02:00
Aevyrie
cba6698033 Parallelize bevy 0.16-rc bottlenecks (#18632)
# Objective

- Found stuttering and performance degradation while updating big_space
stress tests.

## Solution

- Identify and fix slow spots using tracy. Patch to verify fixes.

## Testing

- Tracy
- Before: 

![image](https://github.com/user-attachments/assets/ab7f440d-88c1-4ad9-9ad9-dca127c9421f)
- prev_gt parallelization and mutating instead of component insertion: 

![image](https://github.com/user-attachments/assets/9279a663-c0ba-4529-b709-d0f81f2a1d8b)
- parallelize visibility ranges and mesh specialization

![image](https://github.com/user-attachments/assets/25b70e7c-5d30-48ab-9bb2-79211d4d672f)

---------

Co-authored-by: Zachary Harrold <zac@harrold.com.au>
2025-03-31 22:33:28 +02:00
Chris Russell
d5c5de20b1 Use Display instead of Debug in the default error handler (#18629)
# Objective

Improve error messages for missing resources.  

The default error handler currently prints the `Debug` representation of
the error type instead of `Display`. Most error types use
`#[derive(Debug)]`, resulting in a dump of the structure, but will have
a user-friendly message for `Display`.

Follow-up to #18593

## Solution

Change the default error handler to use `Display` instead of `Debug`.  

Change `BevyError` to include the backtrace in the `Display` format in
addition to `Debug` so that it is still included.

## Showcase

Before: 

```
Encountered an error in system `system_name`: SystemParamValidationError { skipped: false, message: "Resource does not exist", param: "bevy_ecs::change_detection::Res<app_name::ResourceType>" }

Encountered an error in system `other_system_name`: "String message with\nmultiple lines."
```

After

```
Encountered an error in system `system_name`: Parameter `Res<ResourceType>` failed validation: Resource does not exist

Encountered an error in system `other_system_name`: String message with
multiple lines.
```
2025-03-31 22:33:28 +02:00
Robin KAY
d5d57bbd26 Expose symbols needed to replicate SetMeshBindGroup in ecosystem crates. (#18613)
# Objective

My ecosystem crate, bevy_mod_outline, currently uses `SetMeshBindGroup`
as part of its custom rendering pipeline. I would like to allow for
possibility that, due to changes in 0.16, I need to customise the
behaviour of `SetMeshBindGroup` in order to make it work. However, not
all of the symbol needed to implement this render command are public
outside of Bevy.

## Solution

- Include `MorphIndices` in re-export list. I feel this is morally
equivalent to `SkinUniforms` already being exported.
- Change `MorphIndex::index` field to be public. I feel this is morally
equivalent to the `SkinByteOffset::byte_offset` field already being
public.
- Change `RenderMeshIntances::mesh_asset_id()` to be public (although
since all the fields of `RenderMeshInstances` are public it's possible
to work around this one by reimplementing).

These changes exclude:
- Making any change to the `RenderLightmaps` type as I don't need to
bind the light-maps for my use-case and I wanted to keep these changes
minimal. It has a private field which would need to be public or have
access methods.
- The changes already included in #18612.

## Testing

Confirmed that a copy of `SetMeshBindGroup` can be compiled outside of
Bevy with these changes, provided that the light-map code is removed.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2025-03-31 22:33:28 +02:00
charlotte
754d1fa7ca Remove entities from specialization caches when despawned. (#18627)
# Objective

Fixes #17872 

## Solution

This should have basically no impact on static scenes. We can optimize
more later if anything comes up. Needing to iterate the two level bin is
a bit unfortunate but shouldn't matter for apps that use a single
camera.
2025-03-31 22:33:27 +02:00
BD103
4dcee649eb Improve Query's top-level documentation (#18622)
# Objective

- There's been several changes to `Query` for this release cycle, and
`Query`'s top-level documentation has gotten slightly out-of-date.
- Alternative to #18615.

## Solution

- Edit `Query`'s docs for consistency, clarity, and correctness.
- Make sure to group `get()` and `get_many()` together instead of
`single()` and `get_many()`, to enforce the distinction from
https://github.com/bevyengine/bevy/pull/18615#issuecomment-2764355672.
- Reformat doc tests so they would be readable if extracted into their
own file. (Which mainly involves adding more spacing.)
- Move link definitions to be nearer where they are used.
- Fix the tables so they are up-to-date and correctly escape square
brackets `\[ \]`.

## Testing

I ran `cargo doc -p bevy_ecs --no-deps` to view the docs and `cargo test
-p bevy_ecs --doc` to test the doc comments.

## Reviewing

The diff is difficult to read, so I don't recommend _just_ looking at
that. Instead, run `cargo doc -p bevy_ecs --no-deps` locally and read
through the new version. It should theoretically read smoother with less
super-technical jargon. :)

## Follow-up

I want to go through some of `Query`'s methods, such as `single()`,
`get()`, and `get_many()`, but I'll leave that for another PR.

---------

Co-authored-by: Chris Russell <8494645+chescock@users.noreply.github.com>
2025-03-31 22:33:27 +02:00
charlotte
3d1335aeed Use GpuPreprocessingMode::None if features not supported. (#18630)
# Objective

Fixes #18463 

## Solution

The features didn't seem to be getting checked for selecting
`GpuPreprocessingMode::None`.
2025-03-31 22:33:27 +02:00
charlotte
8edeb85f01 Fix mesh extraction for meshes without associated material. (#18631)
# Objective

Fixes #17986
Fixes #18608

## Solution

Guard against situations where an extracted mesh does not have an
associated material. The way that mesh is dependent on the material api
(although decoupled) here is a bit unfortunate and we might consider
ways in the future to support these material features without this
indirect dependency.
2025-03-31 22:33:27 +02:00
charlotte
4ddab0af39 Add required shader defs for environment map binding arrays in deferred (#18634)
# Objective

Fixes #18468

## Solution

Missing shader defs caused shader compilation failure.
2025-03-31 22:33:27 +02:00
charlotte
d9c62c043e Fix mesh tag feature for 2d. (#18636)
# Objective

Fixes #18564
2025-03-31 22:33:27 +02:00
charlotte
52e314c68d Fix AsBindGroup hygenic issues with storage texture. (#18640)
# Objective

Fixes #18573
2025-03-31 22:33:27 +02:00
charlotte
b9ee68a5bb Only send unused event when final handle is dropped. (#18641)
# Objective

Fixes #18457

## Solution

Move the Unused even after the check for existing strong handles.
2025-03-31 22:33:27 +02:00
François Mockers
3bc61a54be remove bevy_log as a dev-dependency from bevy_asset (#18619)
- the bevy workspace fails to publish
```
   Packaging bevy_asset v0.16.0-dev (/home/runner/work/bevy-releasability/bevy-releasability/crates/bevy_asset)
    Updating crates.io index
    Updating `kellnr` index
error: failed to prepare local package for uploading

Caused by:
  no matching package named `bevy_log` found
  location searched: `kellnr` index
  required by package `bevy_asset v0.16.0-dev (/home/runner/work/bevy-releasability/bevy-releasability/crates/bevy_asset)`
```
-
https://github.com/TheBevyFlock/bevy-releasability/actions/runs/14153238476/job/39649160443

- Remove bevy_log dev-dependency from bevy_asset
- Not sure of why this is a problem, but the dev-dependency is not
really needed so... 🤷
2025-03-31 22:33:24 +02:00
Vic
10da4dc9ae Rename EntityBorrow/TrustedEntityBorrow to ContainsEntity/EntityEquivalent (#18470)
# Objective

Fixes #9367.

Yet another follow-up to #16547.

These traits were initially based on `Borrow<Entity>` because that trait
was what they were replacing, and it felt close enough in meaning.
However, they ultimately don't quite match: `borrow` always returns
references, whereas `EntityBorrow` always returns a plain `Entity`.
Additionally, `EntityBorrow` can imply that we are borrowing an `Entity`
from the ECS, which is not what it does.

Due to its safety contract, `TrustedEntityBorrow` is important an
important and widely used trait for `EntitySet` functionality.
In contrast, the safe `EntityBorrow` does not see much use, because even
outside of `EntitySet`-related functionality, it is a better idea to
accept `TrustedEntityBorrow` over `EntityBorrow`.

Furthermore, as #9367 points out, abstracting over returning `Entity`
from pointers/structs that contain it can skip some ergonomic friction.

On top of that, there are aspects of #18319 and #18408 that are relevant
to naming:
We've run into the issue that relying on a type default can switch
generic order. This is livable in some contexts, but unacceptable in
others.

To remedy that, we'd need to switch to a type alias approach: 
The "defaulted" `Entity` case becomes a
`UniqueEntity*`/`Entity*Map`/`Entity*Set` alias, and the base type
receives a more general name. `TrustedEntityBorrow` does not mesh
clearly with sensible base type names.

## Solution
Replace any `EntityBorrow` bounds with `TrustedEntityBorrow`.
+
Rename them as such:
`EntityBorrow` -> `ContainsEntity`
`TrustedEntityBorrow` -> `EntityEquivalent`

For `EntityBorrow` we produce a change in meaning; We designate it for
types that aren't necessarily strict wrappers around `Entity` or some
pointer to `Entity`, but rather any of the myriad of types that contain
a single associated `Entity`.
This pattern can already be seen in the common `entity`/`id` methods
across the engine.
We do not mean for `ContainsEntity` to be a trait that abstracts input
API (like how `AsRef<T>` is often used, f.e.), because eliding
`entity()` would be too implicit in the general case.

We prefix "Contains" to match the intuition of a struct with an `Entity`
field, like some contain a `length` or `capacity`.
It gives the impression of structure, which avoids the implication of a
relationship to the `ECS`.
`HasEntity` f.e. could be interpreted as "a currently live entity", 

As an input trait for APIs like #9367 envisioned, `TrustedEntityBorrow`
is a better fit, because it *does* restrict itself to strict wrappers
and pointers. Which is why we replace any
`EntityBorrow`/`ContainsEntity` bounds with
`TrustedEntityBorrow`/`EntityEquivalent`.

Here, the name `EntityEquivalent` is a lot closer to its actual meaning,
which is "A type that is both equivalent to an `Entity`, and forms the
same total order when compared".
Prior art for this is the
[`Equivalent`](https://docs.rs/hashbrown/latest/hashbrown/trait.Equivalent.html)
trait in `hashbrown`, which utilizes both `Borrow` and `Eq` for its one
blanket impl!

Given that we lose the `Borrow` moniker, and `Equivalent` can carry
various meanings, we expand on the safety comment of `EntityEquivalent`
somewhat. That should help prevent the confusion we saw in
[#18408](https://github.com/bevyengine/bevy/pull/18408#issuecomment-2742094176).

The new name meshes a lot better with the type aliasing approach in
#18408, by aligning with the base name `EntityEquivalentHashMap`.
For a consistent scheme among all set types, we can use this scheme for
the `UniqueEntity*` wrapper types as well!
This allows us to undo the switched generic order that was introduced to
`UniqueEntityArray` by its `Entity` default.

Even without the type aliases, I think these renames are worth doing!

## Migration Guide

Any use of `EntityBorrow` becomes `ContainsEntity`.
Any use of `TrustedEntityBorrow` becomes `EntityEquivalent`.
2025-03-30 10:24:00 +02:00
Vic
8723096d57 reexport entity set collections in entity module (#18413)
# Objective

Unlike for their helper typers, the import paths for
`unique_array::UniqueEntityArray`, `unique_slice::UniqueEntitySlice`,
`unique_vec::UniqueEntityVec`, `hash_set::EntityHashSet`,
`hash_map::EntityHashMap`, `index_set::EntityIndexSet`,
`index_map::EntityIndexMap` are quite redundant.

When looking at the structure of `hashbrown`, we can also see that while
both `HashSet` and `HashMap` have their own modules, the main types
themselves are re-exported to the crate level.

## Solution

Re-export the types in their shared `entity` parent module, and simplify
the imports where they're used.
2025-03-30 10:24:00 +02:00
François Mockers
c946b9d827 bevy_image: derive TypePath when Reflect is not available (#18501)
- bevy_image fails to build without default features:
```
error[E0277]: `image::Image` does not implement `TypePath` so cannot provide static type path information
   --> crates/bevy_image/src/image.rs:341:12
    |
341 | pub struct Image {
    |            ^^^^^ the trait `bevy_reflect::type_path::TypePath` is not implemented for `image::Image`
    |
    = note: consider annotating `image::Image` with `#[derive(Reflect)]` or `#[derive(TypePath)]`
    = help: the following other types implement trait `bevy_reflect::type_path::TypePath`:
              &'static Location<'static>
              &'static T
              &'static mut T
              ()
              (P,)
              (P1, P0)
              (P1, P2, P0)
              (P1, P2, P3, P0)
            and 146 others
note: required by a bound in `Asset`
   --> /home/runner/work/bevy-releasability/bevy-releasability/crates/bevy_asset/src/lib.rs:415:43
    |
415 | pub trait Asset: VisitAssetDependencies + TypePath + Send + Sync + 'static {}
    |                                           ^^^^^^^^ required by this bound in `Asset`
    = note: `Asset` is a "sealed trait", because to implement it you also need to implement `bevy_reflect::type_path::TypePath`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it
    = help: the following types implement the trait:
              bevy_asset::AssetIndex
              bevy_asset::LoadedUntypedAsset
              bevy_asset::AssetEvent<A>
              bevy_asset::LoadedFolder
              bevy_asset::StrongHandle
              bevy_asset::Handle<A>
              bevy_asset::AssetId<A>
              bevy_asset::AssetPath<'a>
            and 148 others

error[E0277]: `image::Image` does not implement `TypePath` so cannot provide static type path information
   --> crates/bevy_image/src/image_loader.rs:121:18
    |
121 |     type Asset = Image;
    |                  ^^^^^ the trait `bevy_reflect::type_path::TypePath` is not implemented for `image::Image`
    |
    = note: consider annotating `image::Image` with `#[derive(Reflect)]` or `#[derive(TypePath)]`
    = help: the following other types implement trait `bevy_reflect::type_path::TypePath`:
              &'static Location<'static>
              &'static T
              &'static mut T
              ()
              (P,)
              (P1, P0)
              (P1, P2, P0)
              (P1, P2, P3, P0)
            and 146 others
    = note: required for `<ImageLoader as AssetLoader>::Asset` to implement `Asset`
note: required by a bound in `bevy_asset::AssetLoader::Asset`
   --> /home/runner/work/bevy-releasability/bevy-releasability/crates/bevy_asset/src/loader.rs:33:17
    |
33  |     type Asset: Asset;
    |                 ^^^^^ required by this bound in `AssetLoader::Asset`

error[E0277]: `texture_atlas::TextureAtlasLayout` does not implement `TypePath` so cannot provide static type path information
   --> crates/bevy_image/src/texture_atlas.rs💯12
    |
100 | pub struct TextureAtlasLayout {
    |            ^^^^^^^^^^^^^^^^^^ the trait `bevy_reflect::type_path::TypePath` is not implemented for `texture_atlas::TextureAtlasLayout`
    |
    = note: consider annotating `texture_atlas::TextureAtlasLayout` with `#[derive(Reflect)]` or `#[derive(TypePath)]`
    = help: the following other types implement trait `bevy_reflect::type_path::TypePath`:
              &'static Location<'static>
              &'static T
              &'static mut T
              ()
              (P,)
              (P1, P0)
              (P1, P2, P0)
              (P1, P2, P3, P0)
            and 146 others
note: required by a bound in `Asset`
   --> /home/runner/work/bevy-releasability/bevy-releasability/crates/bevy_asset/src/lib.rs:415:43
    |
415 | pub trait Asset: VisitAssetDependencies + TypePath + Send + Sync + 'static {}
    |                                           ^^^^^^^^ required by this bound in `Asset`
    = note: `Asset` is a "sealed trait", because to implement it you also need to implement `bevy_reflect::type_path::TypePath`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it
    = help: the following types implement the trait:
              bevy_asset::AssetIndex
              bevy_asset::LoadedUntypedAsset
              bevy_asset::AssetEvent<A>
              bevy_asset::LoadedFolder
              bevy_asset::StrongHandle
              bevy_asset::Handle<A>
              bevy_asset::AssetId<A>
              bevy_asset::AssetPath<'a>
            and 148 others
```
- `Asset` trait depends on `TypePath` which is in bevy_reflect. it's
usually implemented by the `Reflect` derive

- make bevy_reflect not an optional dependency
- when feature `bevy_reflect` is not enabled, derive `TypePath` directly
2025-03-30 10:23:55 +02:00
Aevyrie
c4139fe296 Transform Propagation Optimization: Static Subtree Marking (#18589)
# Objective

- Optimize static scene performance by marking unchanged subtrees.
-
[bef0209](bef0209de1)
fixes #18255 and #18363.
- Closes #18365 
- Includes change from #18321

## Solution

- Mark hierarchy subtrees with dirty bits to avoid transform propagation
where not needed
- This causes a performance regression when spawning many entities, or
when the scene is entirely dynamic.
- This results in massive speedups for largely static scenes.
- In the future we could allow the user to change this behavior, or add
some threshold based on how dynamic the scene is?

## Testing

- Caldera Hotel scene
2025-03-30 10:21:20 +02:00
JMS55
f8f7dfe792 Fix diffuse transmission for anisotropic materials (#18610)
Expand the diff, this was obviously just a copy paste bug at some point.
2025-03-30 10:21:20 +02:00
Chris Russell
ac04ec0075 Improve error message for missing resources (#18593)
# Objective

Fixes #18515 

After the recent changes to system param validation, the panic message
for a missing resource is currently:

```
Encountered an error in system `missing_resource_error::res_system`: SystemParamValidationError { skipped: false }
```

Add the parameter type name and a descriptive message, improving the
panic message to:

```
Encountered an error in system `missing_resource_error::res_system`: SystemParamValidationError { skipped: false, message: "Resource does not exist", param: "bevy_ecs::change_detection::Res<missing_resource_error::MissingResource>" }
```

## Solution

Add fields to `SystemParamValidationError` for error context. Include
the `type_name` of the param and a message.

Store them as `Cow<'static, str>` and only format them into a friendly
string in the `Display` impl. This lets us create errors using a
`&'static str` with no allocation or formatting, while still supporting
runtime `String` values if necessary.

Add a unit test that verifies the panic message.

## Future Work

If we change the default error handling to use `Display` instead of
`Debug`, and to use `ShortName` for the system name, the panic message
could be further improved to:

```
Encountered an error in system `res_system`: Parameter `Res<MissingResource>` failed validation: Resource does not exist
```

However, `BevyError` currently includes the backtrace in `Debug` but not
`Display`, and I didn't want to try to change that in this PR.
2025-03-30 10:21:20 +02:00
Brian Reavis
03e299b455 Fix NonMesh draw command item queries (#17893)
# Objective

This fixes `NonMesh` draw commands not receiving render-world entities
since
- https://github.com/bevyengine/bevy/pull/17698

This unbreaks item queries for queued non-mesh entities:

```rust
struct MyDrawCommand {
    type ItemQuery = Read<DynamicUniformIndex<SomeUniform>>;
    // ...
}
```

### Solution

Pass render entity to `NonMesh` draw commands instead of
`Entity::PLACEHOLDER`. This PR also introduces sorting of the `NonMesh`
bin keys like other types, which I assume is the intended behavior.
@pcwalton

## Testing

- Tested on a local project that extensively uses `NonMesh` items.
2025-03-30 10:21:20 +02:00
Robin KAY
d0c92de937 Expose skins_use_uniform_buffers() necessary to use pre-existing setup_morph_and_skinning_defs() API. (#18612)
# Objective

As of bevy 0.16-dev, the pre-existing public function
`bevy::pbr::setup_morph_and_skinning_defs()` is now passed a boolean
flag called `skins_use_uniform_buffers`. The value of this boolean is
computed by the function
`bevy_pbr::render::skin::skins_use_uniform_buffers()`, but it is not
exported publicly.

Found while porting
[bevy_mod_outline](https://github.com/komadori/bevy_mod_outline) to
0.16.

## Solution

Add `skin::skins_use_uniform_buffers` to the re-export list of
`bevy_pbr::render`.

## Testing

Confirmed test program can access public API.
2025-03-30 10:21:20 +02:00
aloucks
002cb73e38 Fix shader pre-pass compile failure when using AlphaMode::Blend and a Mesh without UVs (0.16.0-rc.2) (#18602)
# Objective

The flags are referenced later outside of the VERTEX_UVS ifdef/endif
block. The current behavior causes the pre-pass shader to fail to
compile when UVs are not present in the mesh, such as when using a
`LineStrip` to render a grid.

Fixes #18600

## Solution

Move the definition of the `flags` outside of the ifdef/endif block.

## Testing

Ran a modified `3d_example` that used a mesh and material with
alpha_mode blend, `LineStrip` topology, and no UVs.
2025-03-30 10:21:20 +02:00
Gino Valente
39745eb069 bevy_reflect: Fix TypePath string concatenation (#18609)
# Objective

Fixes #18606

When a type implements `Add` for `String`, the compiler can get confused
when attempting to add a `&String` to a `String`.

Unfortunately, this seems to be [expected
behavior](https://github.com/rust-lang/rust/issues/77143#issuecomment-698369286)
which causes problems for generic types since the current `TypePath`
derive generates code that appends strings in this manner.

## Solution

Explicitly use the `Add<&str>` implementation in the `TypePath` derive
macro.

## Testing

You can test locally by running:

```
cargo check -p bevy_reflect --tests
```
2025-03-30 10:21:19 +02:00
Satellile
c5aca5bca3 Fix LogDiagnosticsPlugin log target typo (#18534)
# Objective

For the LogDiagnosticsPlugin, the log target is "bevy diagnostic" with a
space; I think it may (?) be a typo intended to be "bevy_diagnostic"
with an underline.

I couldn't get filtering INFO level logs with work with this plugin,
changing this seems to produce the expected behavior.
2025-03-30 10:21:19 +02:00
François Mockers
0ab477e266 Fix wesl in wasm and webgl2 (#18591)
# Objective

- feature `shader_format_wesl` doesn't compile in Wasm
- once fixed, example `shader_material_wesl` doesn't work in WebGL2

## Solution

- remove special path handling when loading shaders. this seems like a
way to escape the asset folder which we don't want to allow, and can't
compile on android or wasm, and can't work on iOS (filesystem is rooted
there)
- pad material so that it's 16 bits. I couldn't get conditional
compilation to work in wesl for type declaration, it fails to parse
- the shader renders the color `(0.0, 0.0, 0.0, 0.0)` when it's not a
polka dot. this renders as black on WebGPU/metal/..., and white on
WebGL2. change it to `(0.0, 0.0, 0.0, 1.0)` so that it's black
everywhere
2025-03-28 23:33:00 +01:00
JMS55
a143a499c2 Fix and improve tracy rendering spans (#18588)
* `submit_graph_commands` was incorrectly timing the command buffer
generation tasks as well, and not only the queue submission. Moved the
span to fix that.
* Added a new `command_buffer_generation_tasks` span as a parent for all
the individual command buffer generation tasks that don't run as part of
the Core3d span.


![image](https://github.com/user-attachments/assets/5a20c2f5-f1df-4c03-afbb-4865327aea33)
2025-03-28 23:33:00 +01:00
JMS55
7bcacb6609 Tracy GPU support (#18490)
# Objective

- Add tracy GPU support

## Solution

- Build on top of the existing render diagnostics recording to also
upload gpu timestamps to tracy
- Copy code from https://github.com/Wumpf/wgpu-profiler

## Showcase

![image](https://github.com/user-attachments/assets/4dd7a7cd-bc0b-43c3-8390-6783dfda6473)
2025-03-28 23:33:00 +01:00
Nick
11b3525065 Fix misleading documentation of Main schedule (#18579)
# Objective

Fixes #18562.

## Solution

- Specified that `StateTransition` is actually run before `PreStartup`.
- Specified consequences of this and how to actually run systems before
any game logic regardless of state.
- Updated docs of `StateTransition` to reflect that it is run before
`PreStartup` in addition to being run after `PreUpdate`.

## Testing

- `cargo doc`
- `cargo test --doc`
2025-03-28 23:33:00 +01:00
Guillaume Gomez
67811be308 Update sysinfo version to 0.34.0 (#18581)
Lot of improvements and stuff. You can see the full list
[here](https://github.com/GuillaumeGomez/sysinfo/blob/master/CHANGELOG.md).
:)
2025-03-28 23:33:00 +01:00
JMS55
5e8dec8a90 Have the mesh allocator handle modified meshes (#18531)
# Objective
Fixes https://github.com/bevyengine/bevy/issues/16586.

## Solution
- Free meshes before allocating new ones (so hopefully the existing
allocation is used, but it's not guaranteed since it might end up
getting used by a smaller mesh first).
- Keep track of modified render assets, and have the mesh allocator free
their allocations.
- Cleaned up some render asset code to make it more understandable,
since it took me several minutes to reverse engineer/remember how it was
supposed to work.

Long term we'll probably want to explicitly reusing allocations for
modified meshes that haven't grown in size, or do delta uploads using a
compute shader or something, but this is an easy fix for the near term.

## Testing
Ran the example provided in the issue. No crash after a few minutes, and
memory usage remains steady.
2025-03-27 23:31:05 +01:00
krunchington
96d5f1e5de Fix relationship macro for multiple named members fields (#18530)
# Objective

Fixes #18466 

## Solution

Updated the macro generation pattern to place the comma in the correct
place in the pattern.

## Testing

- Tried named and unnamed fields in combination, and used rust expand
macro tooling to see the generated code and verify its correctness (see
screenshots in example below)

---

## Showcase

Screenshot showing expanded macro with multiple named fields

![image](https://github.com/user-attachments/assets/7ecd324c-10ba-4b23-9b53-b94da03567d3)

Screenshot showing expanded macro with single unnamed field

![image](https://github.com/user-attachments/assets/be72f061-5f07-4d19-b5f6-7ff6c35ec679)

## Migration Guide

n/a
2025-03-27 22:58:21 +01:00
Greeble
bf915012ff Fix animation transitions affecting other entities (#18572)
## Objective

 Fix #18557.

## Solution

As described in the bug, `remaining_weight` should have been inside the
loop.

## Testing

Locally changed the `animated_mesh_control` example to spawn multiple
meshes and play different transitions.
2025-03-27 22:58:21 +01:00
andriyDev
fe3656fa8b Revert PR #15481 to resolve a regression. (#18567)
- Fixes #18010.

- Revert the offending PRs! These are #15481 and #18013. We now no
longer get an error if there are duplicate subassets.
- In theory we could untangle #18013 from #15481, but that may be
tricky, and may still introduce regressions. To avoid this worry (since
we're already in RC mode), I am just reverting both.

- This is just a revert.

---

<Remove the migration guides for #15481 and #18013>

I will make a PR to the bevy_website repo after this is merged.
2025-03-27 22:58:18 +01:00
Carter Anderson
1a6b480ba2 Required Components: pass through all tokens in {} and () syntax (#18578)
# Objective

#18555 added improved require syntax, but inline structs didn't support
`..Default::default()` syntax (for technical reasons we can't parse the
struct directly, so there is manual logic that missed this case).

## Solution

When a `{}` or `()` section is encountered for a required component,
rather than trying to parse the fields directly, just pass _all_ of the
tokens through. This ensures no tokens are dropped, protects us against
any future syntax changes, and optimizes our parsing logic (as we're
dropping the field parsing logic entirely).
2025-03-27 22:56:49 +01:00
François Mockers
1f44b56310 Release 0.16.0-rc.2 2025-03-26 19:18:20 +01:00
Carter Anderson
f647482237 Improved Require Syntax (#18555)
# Objective

Requires are currently more verbose than they need to be. People would
like to define inline component values. Additionally, the current
`#[require(Foo(custom_constructor))]` and `#[require(Foo(|| Foo(10))]`
syntax doesn't really make sense within the context of the Rust type
system. #18309 was an attempt to improve ergonomics for some cases, but
it came at the cost of even more weirdness / unintuitive behavior. Our
approach as a whole needs a rethink.

## Solution

Rework the `#[require()]` syntax to make more sense. This is a breaking
change, but I think it will make the system easier to learn, while also
improving ergonomics substantially:

```rust
#[derive(Component)]
#[require(
    A, // this will use A::default()
    B(1), // inline tuple-struct value
    C { value: 1 }, // inline named-struct value
    D::Variant, // inline enum variant
    E::SOME_CONST, // inline associated const
    F::new(1), // inline constructor
    G = returns_g(), // an expression that returns G
    H = SomethingElse::new(), // expression returns SomethingElse, where SomethingElse: Into<H> 
)]
struct Foo;
```

## Migration Guide

Custom-constructor requires should use the new expression-style syntax:

```rust
// before
#[derive(Component)]
#[require(A(returns_a))]
struct Foo;

// after
#[derive(Component)]
#[require(A = returns_a())]
struct Foo;
```

Inline-closure-constructor requires should use the inline value syntax
where possible:

```rust
// before
#[derive(Component)]
#[require(A(|| A(10))]
struct Foo;

// after
#[derive(Component)]
#[require(A(10)]
struct Foo;
```

In cases where that is not possible, use the expression-style syntax:

```rust
// before
#[derive(Component)]
#[require(A(|| A(10))]
struct Foo;

// after
#[derive(Component)]
#[require(A = A(10)]
struct Foo;
```

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: François Mockers <mockersf@gmail.com>
2025-03-26 19:07:30 +01:00
Greeble
9a3baa7dc0 Update AnimatableProperty documentation, reduce crate dependencies (#18543)
## Objective

- Remove the second to last `bevy_animation` dependency on
`bevy_render`.
- Update some older documentation to reflect later changes to the crate.

## Narrative

I'm trying to make `bevy_animation` independent of `bevy_render`. The
documentation for `bevy_animation::AnimatableProperty` is one of the
last few dependencies. It uses `bevy_render::Projection` to demonstrate
animating an arbitrary value, but I thought that could be easily swapped
for something else.

I then realised that the rest of the documentation was a bit out of
date. Originally `AnimatableProperty` was the only way to animate a
property and so the documentation was quite detailed. But over time the
crate has gained more documentation and other ways to hook up
properties, leaving parts of the docs stale or covered elsewhere. So
I've slimmed down the `AnimatableProperty` docs and added a link to the
main alternative (`animated_field`).

I've probably swung too far towards brevity, so I can build them back up
if preferred. Also the example is kinda contrived and doesn't show the
range of `AnimatableProperty`, like being able to choose different
components. And finally the memes might be a bit stale?

## Showcase


![image](https://github.com/user-attachments/assets/23f1c0bf-10ea-4602-a566-673abe5dace7)

## Testing

```
cargo doc -p bevy_animation --no-deps --all-features
cargo test -p bevy_animation --doc --all-features
```
2025-03-26 19:06:51 +01:00
Chris Russell
4bc4f93f5b Fix run_system for adapter systems wrapping exclusive systems (#18406)
# Objective

Fix panic in `run_system` when running an exclusive system wrapped in a
`PipeSystem` or `AdapterSystem`.

#18076 introduced a `System::run_without_applying_deferred` method. It
normally calls `System::run_unsafe`, but
`ExclusiveFunctionSystem::run_unsafe` panics, so it was overridden for
that type. Unfortunately, `PipeSystem::run_without_applying_deferred`
still calls `PipeSystem::run_unsafe`, which can then call
`ExclusiveFunctionSystem::run_unsafe` and panic.

## Solution

Make `ExclusiveFunctionSystem::run_unsafe` work instead of panicking.
Clarify the safety requirements that make this sound.

The alternative is to override `run_without_applying_deferred` in
`PipeSystem`, `CombinatorSystem`, `AdapterSystem`,
`InfallibleSystemWrapper`, and `InfallibleObserverWrapper`. That seems
like a lot of extra code just to preserve a confusing special case!

Remove some implementations of `System::run` that are no longer
necessary with this change. This slightly changes the behavior of
`PipeSystem` and `CombinatorSystem`: Currently `run` will call
`apply_deferred` on the first system before running the second, but
after this change it will only call it after *both* systems have run.
The new behavior is consistent with `run_unsafe` and
`run_without_applying_deferred`, and restores the behavior prior to
#11823.

The panic was originally necessary because [`run_unsafe` took
`&World`](https://github.com/bevyengine/bevy/pull/6083/files#diff-708dfc60ec5eef432b20a6f471357a7ea9bfb254dc2f918d5ed4a66deb0e85baR90).
Now that it takes `UnsafeWorldCell`, it is possible to make it work. See
also Cart's concerns at
https://github.com/bevyengine/bevy/pull/4166#discussion_r979140356,
although those also predate `UnsafeWorldCell`.

And see #6698 for a previous bug caused by this panic.
2025-03-26 19:06:51 +01:00
Chris Russell
765e5842cd Replace ValidationOutcome with Result (#18541)
# Objective

Make it easier to short-circuit system parameter validation.  

Simplify the API surface by combining `ValidationOutcome` with
`SystemParamValidationError`.

## Solution

Replace `ValidationOutcome` with `Result<(),
SystemParamValidationError>`. Move the docs from `ValidationOutcome` to
`SystemParamValidationError`.

Add a `skipped` field to `SystemParamValidationError` to distinguish the
`Skipped` and `Invalid` variants.

Use the `?` operator to short-circuit validation in tuples of system
params.
2025-03-26 09:01:42 +01:00
Zachary Harrold
9705eaef02 Add methods to work with dynamic immutable components (#18532)
# Objective

- Fixes #16861

## Solution

- Added: 
  - `UnsafeEntityCell::get_mut_assume_mutable_by_id`
  - `EntityMut::get_mut_assume_mutable_by_id`
  - `EntityMut::get_mut_assume_mutable_by_id_unchecked`
  - `EntityWorldMut::into_mut_assume_mutable_by_id`
  - `EntityWorldMut::into_mut_assume_mutable`
  - `EntityWorldMut::get_mut_assume_mutable_by_id`
  - `EntityWorldMut::into_mut_assume_mutable_by_id`
  - `EntityWorldMut::modify_component_by_id`
  - `World::modify_component_by_id`
  - `DeferredWorld::modify_component_by_id`
- Added `fetch_mut_assume_mutable` to `DynamicComponentFetch` trait
(this is a breaking change)

## Testing

- CI

---

## Migration Guide

If you had previously implemented `DynamicComponentFetch` you must now
include a definition for `fetch_mut_assume_mutable`. In general this
will be identical to `fetch_mut` using the relevant alternatives for
actually getting a component.

---

## Notes

All of the added methods are minor variations on existing functions and
should therefore be of low risk for inclusion during the RC process.
2025-03-25 23:01:22 +01:00
aloucks
8dc1a7cd81 Fix UpdateMode::Reactive behavior on Windows (#18493)
# Objective

The fix in #17488 forced Windows to always behave as if it were in
`UpdateMode::Continuous`.

CC https://github.com/bevyengine/bevy/pull/17991

## Solution

Removed the unconditional `redraw_requested = true` and added a check
for `Reactive` in `about_to_wait`.

## Testing

- Verified that the `low_power` example worked as expected with all
`UpdateMode` options.
- Verified that animation continued in both `eased_motion ` and
`low_power` examples when in `Continuous` update mode while:
  - Resizing the Window
  - Moving the window via clicking and dragging the title bar
- Verified that `window_settings` example still worked as expected.
- Verified that `monitor_info` example still worked as expected.
2025-03-25 23:01:22 +01:00
Eagster
b1c1aac1b3 Ensure spawning related entities in an OnAdd observer downstream of a World::spawn in a Command does not cause a crash (#18545)
# Objective

fixes #18452.

## Solution

Spawning used to flush commands only, but those commands can reserve
entities. Now, spawning flushes everything, including reserved entities.
I checked, and this was the only place where `flush_commands` is used
instead of `flush` by mistake.

## Testing

I simplified the MRE from #18452 into its own test, which fails on main,
but passes on this branch.
2025-03-25 22:59:05 +01:00
Sorseg
30a022feae Make RayMap map public (#18544)
Migration guide:
# Objective

Currently there seems to be no way to enable picking through
render-to-texture cameras

## Solution

This PR allows casting rays from the game code quite easily.

## Testing

- I've tested these in my game and it seems to work
- I haven't tested edge cases

--- 

## Showcase

<details>
  <summary>Click to view showcase</summary>

```rust

fn cast_rays_from_additional_camera(
    cameras: Query<(&GlobalTransform, &Camera, Entity), With<RenderToTextureCamera>>,
    mut rays: ResMut<RayMap>,
    pointers: Query<(&PointerId, &PointerLocation)>,
) {
    for (camera_global_transform, camera, camera_entity) in &cameras {
        for (pointer_id, pointer_loc) in &pointers {
            let Some(viewport_pos) = pointer_loc.location() else {
                continue;
            };
            // if camera result is transformed in any way, the reverse transformation
            // should be applied somewhere here
            let ray = camera
                .viewport_to_world(camera_global_transform, viewport_pos.position)
                .ok();
            if let Some(r) = ray {
                rays.map.insert(RayId::new(camera_entity, *pointer_id), r);
            }
        }
    }
}

```

</details>

## Migration Guide
The `bevy_picking::backend::ray::RayMap::map` method is removed as
redundant,
In systems using `Res<RayMap>` replace `ray_map.map()` with
`&ray_map.map`
2025-03-25 22:59:05 +01:00
IceSentry
af9fd4e939 Move non-generic parts of the PrepassPipeline to internal field (#18322)
# Objective

- The prepass pipeline has a generic bound on the specialize function
but 95% of it doesn't need it

## Solution

- Move most of the fields to an internal struct and use a separate
specialize function for those fields

## Testing

- Ran the 3d_scene and it worked like before

---

## Migration Guide

If you were using a field of the `PrepassPipeline`, most of them have
now been move to `PrepassPipeline::internal`.

## Notes

Here's the cargo bloat size comparison (from this tool
https://github.com/bevyengine/bevy/discussions/14864):

```
before:
    (
        "<bevy_pbr::prepass::PrepassPipeline<M> as bevy_render::render_resource::pipeline_specializer::SpecializedMeshPipeline>::specialize",
        25416,
        0.05582993,
    ),

after:
    (
        "<bevy_pbr::prepass::PrepassPipeline<M> as bevy_render::render_resource::pipeline_specializer::SpecializedMeshPipeline>::specialize",
        2496,
        0.005490916,
    ),
    (
        "bevy_pbr::prepass::PrepassPipelineInternal::specialize",
        11444,
        0.025175499,
    ),
```

The size for the specialize function that is generic is now much
smaller, so users won't need to recompile it for every material.
2025-03-25 22:59:04 +01:00
IQuick 143
a021ed1ce8 Fix mesh_picking not working due to mixing vertex and triangle indices. (#18533)
# Objective

- #18495 

## Solution

- The code in the PR #18232 accidentally used a vertex index as a
triangle index, causing the wrong triangle to be used for normal
computation and if the triangle went out of bounds, it would skip the
ray-hit.
- Don't do that.

## Testing

- Run `cargo run --example mesh_picking`
2025-03-25 22:59:04 +01:00
François Mockers
38743a8ff1 don't flip sprites twice (#18535)
# Objective

- After #17041, sprite flipping doesn't work

## Solution

- Sprite flipping is applied twice:

b6ccc2a2a0/crates/bevy_sprite/src/render/mod.rs (L766-L773)

b6ccc2a2a0/crates/bevy_sprite/src/render/mod.rs (L792-L799)
- Keep one
2025-03-25 22:59:04 +01:00
Zachary Harrold
398350906c Fix bevy_math/transform/input Improper Inclusion (#18526)
# Objective

Enabling `serialize`, `critical-section`, or `async-executor` would
improperly enable `bevy_math`, `bevy_input`, and/or `bevy_transform`.
This was caused by those crates previously being required but are now
optional (gated behind `std` and/or `libm`).

## Solution

- Added `?` to features not intended to enable those crates

## Testing

- CI
2025-03-25 22:59:04 +01:00
HugoPeters1024
df26bc3387 bugfix(frustra of point lights were not recalculated when a camera changes) (#18519)
# Objective

- Fixes https://github.com/bevyengine/bevy/issues/11682

## Solution

- https://github.com/bevyengine/bevy/pull/4086 introduced an
optimization to not do redundant calculations, but did not take into
account changes to the resource `global_lights`. I believe that my patch
includes the optimization benefit but adds the required nuance to fix
said bug.

## Testing

The example originally given by
[@kirillsurkov](https://github.com/kirillsurkov) and then updated by me
to bevy 15.3 here:
https://github.com/bevyengine/bevy/issues/11682#issuecomment-2746287416
will not have shadows without this patch:

```rust
use bevy::prelude::*;

#[derive(Resource)]
struct State {
    x: f32,
}

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, update)
        .insert_resource(State { x: -40.0 })
        .run();
}

fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    commands.spawn((
        Mesh3d(meshes.add(Circle::new(4.0))),
        MeshMaterial3d(materials.add(Color::WHITE)),
    ));
    commands.spawn((
        Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
        MeshMaterial3d(materials.add(Color::linear_rgb(0.0, 1.0, 0.0))),
    ));
    commands.spawn((
        PointLight {
            shadows_enabled: true,
            ..default()
        },
        Transform::from_xyz(4.0, 8.0, 4.0),
    ));
    commands.spawn(Camera3d::default());
}

fn update(mut state: ResMut<State>, mut camera: Query<&mut Transform, With<Camera3d>>) {
    let mut camera = camera.single_mut().unwrap();

    let t = Vec3::new(state.x, 0.0, 10.0);
    camera.translation = t;
    camera.look_at(t - Vec3::Z, Vec3::Y);

    state.x = 0.0;
}
```

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: JMS55 <47158642+JMS55@users.noreply.github.com>
2025-03-25 22:59:04 +01:00
Joona Aalto
bdf6f3d5f1 Add no_std compatible ceil method (#18498)
# Objective


[`f32::ceil`](https://doc.rust-lang.org/std/primitive.f32.html#method.ceil)
is not available in `core`. We have `floor` in `bevy_math::ops`, but no
equivalent for `floor`.

## Solution

Add `ops::ceil` for `no_std` compatibility.
2025-03-25 22:59:04 +01:00