Commit Graph

7914 Commits

Author SHA1 Message Date
Tristan Murphy
afed4e27d1
small documentation update and issue template fix (#17054)
# Objective
Fix some outdated `bevy_state` documentation examples.

## Solution
- updated some doc examples in `bevy_state` that hadn't been updated
with the API.
- fixed an outdated link in the documentation issue template that
referred to a 404 page instead of the contribution guide.

## Testing
No necessary testing aside from the usual doctests.

---

## Showcase
N/A

## Migration Guide
N/A

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2025-01-01 23:09:17 +00:00
Zachary Harrold
10e113d641
Add no_std support to bevy_window (#17031)
# Objective

- Contributes to #15460

## Solution

- Added the following features:
  - `std` (default)
  - `bevy_reflect` (default)
  - `libm`

## Testing

- CI

## Notes

- `bevy_reflect` was previously always enabled, which isn't how most
other crates handle reflection. I've brought this in line with how most
crates gate `bevy_reflect`. This is where the majority of the changes
come from in this PR.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2025-01-01 23:05:25 +00:00
Benjamin Brienen
4058bfa47c
Fix clippy::precedence (#17080)
# Objective

Nightly clippy warnings

## Solution

Add parens

## Testing

```
PS C:\Users\BenjaminBrienen\source\bevy> cargo +nightly clippy
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.44s
```
2025-01-01 22:11:22 +00:00
Aevyrie
bed9ddf3ce
Refactor and simplify custom projections (#17063)
# Objective

- Fixes https://github.com/bevyengine/bevy/issues/16556
- Closes https://github.com/bevyengine/bevy/issues/11807

## Solution

- Simplify custom projections by using a single source of truth -
`Projection`, removing all existing generic systems and types.
- Existing perspective and orthographic structs are no longer components
- I could dissolve these to simplify further, but keeping them around
was the fast way to implement this.
- Instead of generics, introduce a third variant, with a trait object.
- Do an object safety dance with an intermediate trait to allow cloning
boxed camera projections. This is a normal rust polymorphism papercut.
You can do this with a crate but a manual impl is short and sweet.

## Testing

- Added a custom projection example

---

## Showcase

- Custom projections and projection handling has been simplified.
- Projection systems are no longer generic, with the potential for many
different projection components on the same camera.
- Instead `Projection` is now the single source of truth for camera
projections, and is the only projection component.
- Custom projections are still supported, and can be constructed with
`Projection::custom()`.

## Migration Guide

- `PerspectiveProjection` and `OrthographicProjection` are no longer
components. Use `Projection` instead.
- Custom projections should no longer be inserted as a component.
Instead, simply set the custom projection as a value of `Projection`
with `Projection::custom()`.
2025-01-01 20:44:24 +00:00
Sean Kim
294e0db719
Rename track_change_detection flag to track_location (#17075)
# Objective

- As stated in the related issue, this PR is to better align the feature
flag name with what it actually does and the plans for the future.
- Fixes #16852 

## Solution

- Simple find / replace

## Testing

- Local run of `cargo run -p ci`

## Migration Guide

The `track_change_detection` feature flag has been renamed to
`track_location` to better reflect its extended capabilities.
2025-01-01 18:43:47 +00:00
Robert Swain
fd330c834f
Fix sprite performance regression since retained render world (#17078)
# Objective

- Fix sprite rendering performance regression since retained render
world changes
- The retained render world changes moved `ExtractedSprites` from using
the highly-optimised `EntityHasher` with an `Entity` to using
`FixedHasher` with `(Entity, MainEntity)`. This was enough to regress
framerate in bevymark by 25%.

## Solution

- Move the render world entity into a member of `ExtractedSprite` and
change `ExtractedSprites` to use `MainEntityHashMap` for its storage
- Disable sprite picking in bevymark

## Testing

M4 Max. `bevymark --waves 100 --per-wave 1000 --benchmark`. main in
yellow vs PR in red:

<img width="590" alt="Screenshot 2025-01-01 at 16 36 22"
src="https://github.com/user-attachments/assets/1e4ed6ec-3811-4abf-8b30-336153737f89"
/>

20.2% median frame time reduction.

<img width="594" alt="Screenshot 2025-01-01 at 16 38 37"
src="https://github.com/user-attachments/assets/157c2022-cda6-4cf2-bc63-d0bc40528cf0"
/>

49.7% median extract_sprites execution time reduction.

Comparing 0.14.2 yellow vs PR red:
<img width="593" alt="Screenshot 2025-01-01 at 16 40 06"
src="https://github.com/user-attachments/assets/abd59b6f-290a-4eb6-8835-ed110af995f3"
/>

~6.1% median frame time reduction.

---

## Migration Guide

- `ExtractedSprites` is now using `MainEntityHashMap` for storage, which
is keyed on `MainEntity`.
- The render world entity corresponding to an `ExtractedSprite` is now
stored in the `render_entity` member of it.
2025-01-01 18:40:11 +00:00
ickshonpe
0141bd01b3
Remove the atlas_scaling field from ExtractedUiItem::Gylphs. (#17047)
# Objective

Remove the `atlas_scaling` field from `ExtractedUiItem::Gylphs`. 

It's only ever set to `Vec2::ONE`. I don't remember why/if this field
was ever needed, maybe it was useful before the scale factor clean up.

## Migration Guide

The `atlas_scaling` field from `ExtractedUiItem::Gylphs` has been
removed. This shouldn't affect any existing code as it wasn't used for
anything.
2025-01-01 04:06:53 +00:00
Alice Cecile
5f1e762f19
Return Result from tab navigation API (#17071)
# Objective

Tab navigation can fail in all manner of ways. The current API
recognizes this, but merely logs a warning and returns `None`.

We should supply the actual reason for failure to the caller, so they
can handle it in whatever fashion they please (including logging a
warning!).

Swapping to a Result-oriented pattern is also a bit more idiomatic and
makes the code's control flow easier to follow.

## Solution

- Refactor the `tab_navigation` module to return a `Result` rather than
an `Option` from its key APIs.
- Move the logging to the provided prebuilt observer. This leaves the
default behavior largely unchanged, but allows for better user control.
- Make the case where no tab group was found for the currently focused
entity an error branch, but provide enough information that we can still
recover from it.

## Testing

The `tab_navigation` example continues to function as intended.
2025-01-01 04:05:48 +00:00
ickshonpe
c817864e4f
Replace map_or(true, _) with is_none_or(_) (#17073)
# Objective

Replace uses of `map_or(true, _)` with the equivalent `is_none_or(_)`.
2025-01-01 04:05:26 +00:00
Niklas Eicker
7302e7c9e0
Do not lowercase asset file extensions (#17065)
# Objective

Resolves #17064

## Solution

- Bevy no longer converts asset file extensions to lowercase before
trying to resolve an asset loader

## Testing

- I adapted the `custom_asset` example (see comment in #17064)
- The changes were tested on Linux

As far as I know, Windows has a case-insensitive file system by default,
so case-sensitive asset file extensions are probably bad practice in a
game. But we should be case-sensitive everywhere or handle asset paths
completely case-insensitive.

Before this PR:
* asset loader extensions are case-sensitive
* asset file names are case-sensitive
* asset file extensions are converted to lowercase  

Now everything should be case-sensitive
2025-01-01 00:42:56 +00:00
ickshonpe
9b4e6b345f
Replace map_or(false, _) with is_some_and(_) (#17074)
# Objective

Replace `map_or(false, _)` with `is_some_and(_)`
2024-12-31 21:13:13 +00:00
ickshonpe
7a5a734452
Replace map + unwrap_or(false) with is_some_and (#17067)
# Objective

The `my_option.map(|inner| inner.is_whatever).unwrap_or(false)` pattern
is fragile and ugly.

Replace it with `is_some_and` everywhere.
2024-12-31 20:28:02 +00:00
ickshonpe
c73daea341
Replace map + unwrap_or(true) with is_none_or (#17070)
# Objective

Reduce all varieties of `my_maybe.map(|x| x.is_true).unwrap_or(true)`
using `is_none_or`.
2024-12-31 20:17:03 +00:00
Alice Cecile
d502796a41
Make the input focus docs less keyboard-centric (#17069)
# Objective

Following #16876, `bevy_input_focus` works with more than just keyboard
inputs! The docs should reflect that.

## Solution

Fix a few missed mentions in the documentation.

Also add a brief reference to navigation frameworks within the module
docs to help give more breadcrumbs.
2024-12-31 18:37:48 +00:00
Jonathan Chan Kwan Yin
3c7fbee2d8
Add Mut::clone_from_if_neq (#17019)
# Objective

- Support more ergonomic conditional updates for types that can be
modified by `clone_into`.

## Solution

- Use `ToOwned::clone_into` to copy a reference provided by the caller
in `Mut::clone_from_if_neq`.

## Testing

- See doc tests.
2024-12-31 16:23:01 +00:00
Benjamin Brienen
c93217b966
Fix compilation error (#17060)
Small follow-up to #17011 

Please don't merge until the CI passes all checks
2024-12-31 16:22:19 +00:00
Aevyrie
63634fd408
Update picking docs (#17057)
More updates to picking docs. Addresses some nits with wording, and
fixes some out of date information.
2024-12-31 01:56:45 +00:00
Aevyrie
f3da36c181
Update picking::events module docs (#17055)
Updates some out of date docs.
2024-12-31 00:46:15 +00:00
Mike
ac43d5c94f
Convert to fallible system in IntoSystemConfigs (#17051)
# Objective

- #16589 added an enum to switch between fallible and infallible system.
This branching should be unnecessary if we wrap infallible systems in a
function to return `Ok(())`.

## Solution

- Create a wrapper system for `System<(), ()>`s that returns `Ok` on the
call to `run` and `run_unsafe`. The wrapper should compile out, but I
haven't checked.
- I removed the `impl IntoSystemConfigs for BoxedSystem<(), ()>` as I
couldn't figure out a way to keep the impl without double boxing.

## Testing

- ran `many_foxes` example to check if it still runs.

## Migration Guide

- `IntoSystemConfigs` has been removed for `BoxedSystem<(), ()>`. Either
use `InfallibleSystemWrapper` before boxing or make your system return
`bevy::ecs::prelude::Result`.
2024-12-31 00:39:29 +00:00
Jer
33afd38ee1
show these 'fully qualified paths' for bevy_remote's rpc (#16944)
# Objective

It is not obvious that one would know these:
```json
{
  "id": 1,
  "jsonrpc": "2.0",
  "result": [
    "bevy_animation::AnimationPlayer",
    "bevy_animation::AnimationTarget",
    "bevy_animation::graph::AnimationGraphHandle",
    "bevy_animation::transition::AnimationTransitions",
    "bevy_audio::audio::PlaybackSettings",
    "bevy_audio::audio::SpatialListener",
    "bevy_core_pipeline::bloom::settings::Bloom",
    "bevy_core_pipeline::contrast_adaptive_sharpening::ContrastAdaptiveSharpening",
   **... snipping for brevity ...**
    "bevy_ui::ui_node::Node",
    "bevy_ui::ui_node::Outline",
    "bevy_ui::ui_node::ScrollPosition",
    "bevy_ui::ui_node::TargetCamera",
    "bevy_ui::ui_node::UiAntiAlias",
    "bevy_ui::ui_node::ZIndex",
    "bevy_ui::widget::button::Button",
    "bevy_window::monitor::Monitor",
    "bevy_window:🪟:PrimaryWindow",
    "bevy_window:🪟:Window",
    "bevy_winit::cursor::CursorIcon",
    "server::Cube"
  ]
}
```
Especially if you for example, are reading the GH examples because:

![image](https://github.com/user-attachments/assets/46c9c983-4bf9-4e70-9d6e-8de936505fbb)
If you for example expand these things, due to the number of places bevy
re-exports things you'll find it difficult to find the true path of
something.
i.e you'd probably be forgiven for writing a query (using the
`client.rs` example):
```sh
$ cargo run --example client --  bevy_pbr::mesh_material::MeshMaterial3d | jq
{
  "error": {
    "code": -23402,
    "message": "Unknown component type: `bevy_pbr::mesh_material::MeshMaterial3d`"
  },
  "id": 1,
  "jsonrpc": "2.0"
}
```
which is where
8d9a00f548/crates/bevy_pbr/src/mesh_material.rs (L41)
would lead you to believe it is...

I've worked with bevy a lot, so it's no issue for me, but for others...
?

## Solution

- Add some more docs, including a sample request (`json` and `rust`)

## Testing

N/A

---

## Showcase
N/A

---------

Co-authored-by: Benjamin Brienen <benjamin.brienen@outlook.com>
2024-12-31 00:29:27 +00:00
Zachary Harrold
3f19997096
Added modify_component to EntityWorldMut, DeferredWorld, and World (#16668)
# Objective

- Make working with immutable components more ergonomic
- Assist #16662

## Solution

Added `modify_component` to `World` and `EntityWorldMut`. This method
"removes" a component from an entity, gives a mutable reference to it to
a provided closure, and then "re-inserts" the component back onto the
entity. This replacement triggers the `OnReplace` and `OnInsert` hooks,
but does _not_ cause an archetype move, as the removal is purely
simulated.

## Testing

- Added doc-tests and a unit test.

---

## Showcase

```rust
use bevy_ecs::prelude::*;

/// An immutable component.
#[derive(Component, PartialEq, Eq, Debug)]
#[component(immutable)]
struct Foo(bool);

let mut world = World::default();

let mut entity = world.spawn(Foo(false));

assert_eq!(entity.get::<Foo>(), Some(&Foo(false)));

// Before the closure is executed, the `OnReplace` hooks/observers are triggered
entity.modify_component(|foo: &mut Foo| {
    foo.0 = true;
});
// After the closure is executed, `OnInsert` hooks/observers are triggered

assert_eq!(entity.get::<Foo>(), Some(&Foo(true)));
```

## Notes

- If the component is not available on the entity, the closure and hooks
aren't executed, and `None` is returned. I chose this as an alternative
to returning an error or panicking, but I'm open to changing that based
on feedback.
- This relies on `unsafe`, in particular for accessing the `Archetype`
to trigger hooks. All the unsafe operations are contained within
`DeferredWorld::modify_component`, and I would appreciate that this
function is given special attention to ensure soundness.
- The `OnAdd` hook can never be triggered by this method, since the
component must already be inserted. I have chosen to not trigger
`OnRemove`, as I believe it makes sense that this method is purely a
replacement operation, not an actual removal/insertion.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Malek <50841145+MalekiRe@users.noreply.github.com>
2024-12-31 00:23:44 +00:00
Benjamin Brienen
4460a4d9ed
Use -D warnings in all relevant CI (#17011)
# Objective

Fixes #17009

See:
https://doc.rust-lang.org/stable/clippy/continuous_integration/index.html

## Solution

Add the env

## Testing

CI should start to fail, then I'll fix it.

## Showcase


![image](https://github.com/user-attachments/assets/acd2888f-9fc0-445a-a96a-842ba9f1c6aa)
2024-12-31 00:15:28 +00:00
Benjamin Brienen
9e4c07238b
Fix logic error in loading_screen.rs (#16989)
# Objective

Fix #16792

## Solution

Fix the logic to retain loaded ones

## Testing

Unable to test due to #16988
2024-12-31 00:04:38 +00:00
Zhixing Zhang
9cebc66486
Make 8 methods public and updated input parameter generics for SystemState::build_system_with_input (#17034)
# Objective

- Made certain methods public for advanced use cases. Methods that
returns mutable references are marked as unsafe due to the possibility
of violating internal lifetime constraint assumptions.
- Fixes an issue introduced by #15184
2024-12-30 23:04:14 +00:00
Zachary Harrold
5f42c9ab6d
Fix no_std CI Warnings and WASM Compatibility (#17049)
# Objective

- Resolve several warnings encountered when compiling for `no_std`
around `dead_code`
- Fix compatibility with `wasm32-unknown-unknown` when using `no_std`
(identified by Sachymetsu on
[Discord](https://discord.com/channels/691052431525675048/692572690833473578/1323365426901549097))

## Solution

- Removed some unused imports
- Added `allow(dead_code)` for certain private items when compiling on
`no_std`
- Fixed `bevy_app` and `bevy_tasks` compatibility with WASM when
compiling without `std` by appropriately importing `Box` and feature
gating panic unwinding

## Testing

- CI
2024-12-30 23:01:27 +00:00
Vic
b78efd339d
Simplify sort/max_by calls (#17048)
# Objective

Some sort calls and `Ord` impls are unnecessarily complex.

## Solution

Rewrite the "match on cmp, if equal do another cmp" as either a
comparison on tuples, or `Ordering::then_with`, depending on whether the
compare keys need construction.

`sort_by` -> `sort_by_key` when symmetrical. Do the same for
`min_by`/`max_by`.

Note that `total_cmp` can only work with `sort_by`, and not on tuples.

When sorting collected query results that contain
`Entity`/`MainEntity`/`RenderEntity` in their `QueryData`, with that
`Entity` in the sort key:
stable -> unstable sort (all queried entities are unique)

If key construction is not simple, switch to `sort_by_cached_key` when
possible.

Sorts that are only performed to discover the maximal element are
replaced by `max_by_key`.

Dedicated comparison functions and structs are removed where simple.

Derive `PartialOrd`/`Ord` when useful.

Misc. closure style inconsistencies.

## Testing
- Existing tests.
2024-12-30 22:59:36 +00:00
ickshonpe
1e9f647b33
prepare_sprite_image_bind_groups refactor (#17045)
# Objective

In `prepare_sprite_image_bind_groups` the `batch_image_changed`
condition is checked twice but the second if-block seems unnecessary.

# Solution

Queue new `SpriteBatch`es inside the first if-block and remove the
second if-block.
2024-12-30 22:54:04 +00:00
ickshonpe
d522c47dbe
many_glyphs no-ui and no-text2d commandline arguments (#17046)
# Objective

Add commandline options to `many_glyphs` to disable the `Text2d` or `UI`
text for more targeted benching.

## Solution
* Use `Argh` to manage the commandline options for `many_glyphs`.
* Added `no-ui` and `no-text2d` commandline options.
2024-12-30 21:25:33 +00:00
ickshonpe
d2f61e24e7
get_glyph_atlas_info refactor (#17044)
# Objective

Return a `GlyphAtlasInfo` instead of a tuple from the inner block so we
can remove the outer mapping.
2024-12-30 21:08:12 +00:00
BD103
c890cc9dc3
Overhaul picking benchmarks (#17033)
# Objective

- Part of #16647.
- This PR goes through our `ray_cast::ray_mesh_intersection()`
benchmarks and overhauls them with more comments and better
extensibility. The code is also a lot less duplicated!

## Solution

- Create a `Benchmarks` enum that describes all of the different kind of
scenarios we want to benchmark.
- Merge all of our existing benchmark functions into a single one,
`bench()`, which sets up the scenarios all at once.
- Add comments to `mesh_creation()` and `ptoxznorm()`, and move some
lines around to be a bit clearer.
- Make the benchmarks use the new `bench!` macro, as part of #16647.
- Rename many functions and benchmarks to be clearer.

## For reviewers

I split this PR up into several, easier to digest commits. You might
find it easier to review by looking through each commit, instead of the
complete file changes.

None of my changes actually modifies the behavior of the benchmarks;
they still track the exact same test cases. There shouldn't be
significant changes in benchmark performance before and after this PR.

## Testing

List all picking benchmarks: `cargo bench -p benches --bench picking --
--list`

Run the benchmarks once in debug mode: `cargo test -p benches --bench
picking`

Run the benchmarks and analyze their performance: `cargo bench -p
benches --bench picking`

- Check out the generated HTML report in
`./target/criterion/report/index.html` once you're done!

---

## Showcase

List of all picking benchmarks, after having been renamed:

<img width="524" alt="image"
src="https://github.com/user-attachments/assets/a1b53daf-4a8b-4c45-a25a-c6306c7175d1"
/>

Example report for
`picking::ray_mesh_intersection::cull_intersect/100_vertices`:

<img width="992" alt="image"
src="https://github.com/user-attachments/assets/a1aaf53f-ce21-4bef-89c4-b982bb158f5d"
/>
2024-12-30 21:04:24 +00:00
Zachary Harrold
db5c31e1c4
Add no_std support to bevy_transform (#17030)
# Objective

- Contributes to #15460

## Solution

- Added the following features:
  - `std` (default)
  - `alloc` (default)
  - `bevy_reflect` (default)
  - `libm`

## Testing

- CI

## Notes

- `alloc` feature added to allow using this crate in `no_alloc`
environments.
- `bevy_reflect` was previously always enabled when `bevy-support` was
enabled, which isn't how most other crates handle reflection. I've
brought this in line with how most crates gate `bevy_reflect`.
2024-12-30 21:01:13 +00:00
JaySpruce
9ac7e17f2e
Refactor hierarchy-related commands to remove structs (#17029)
## Objective

Continuation of #16999.

This PR handles the following:
- Many hierarchy-related commands are wrappers around `World` and
`EntityWorldMut` methods and can be moved to closures:
  - `AddChild`
  - `InsertChildren`
  - `AddChildren`
  - `RemoveChildren`
  - `ClearChildren`
  - `ReplaceChildren`
  - `RemoveParent`
  - `DespawnRecursive`
  - `DespawnChildrenRecursive`
  - `AddChildInPlace`
  - `RemoveParentInPlace`
- `SendEvent` is a wrapper around `World` methods and can be moved to a
closure (and its file deleted).

## Migration Guide

If you were queuing the structs of hierarchy-related commands or
`SendEvent` directly, you will need to change them to the methods
implemented on `EntityCommands` (or `Commands` for `SendEvent`):

| Struct | Method |

|--------------------------------------------------------------------|---------------------------------------------------------------------------------------------|
| `commands.queue(AddChild { child, parent });` |
`commands.entity(parent).add_child(child);` OR
`commands.entity(child).set_parent(parent);` |
| `commands.queue(AddChildren { children, parent });` |
`commands.entity(parent).add_children(children);` |
| `commands.queue(InsertChildren { children, parent });` |
`commands.entity(parent).insert_children(children);` |
| `commands.queue(RemoveChildren { children, parent });` |
`commands.entity(parent).remove_children(children);` |
| `commands.queue(ReplaceChildren { children, parent });` |
`commands.entity(parent).replace_children(children);` |
| `commands.queue(ClearChildren { parent });` |
`commands.entity(parent).clear_children();` |
| `commands.queue(RemoveParent { child });` |
`commands.entity(child).remove_parent()` |
| `commands.queue(DespawnRecursive { entity, warn: true });` |
`commands.entity(entity).despawn_recursive();` |
| `commands.queue(DespawnRecursive { entity, warn: false });` |
`commands.entity(entity).try_despawn_recursive();` |
| `commands.queue(DespawnChildrenRecursive { entity, warn: true });` |
`commands.entity(entity).despawn_descendants();` |
| `commands.queue(DespawnChildrenRecursive { entity, warn: false});` |
`commands.entity(entity).try_despawn_descendants();` |
| `commands.queue(SendEvent { event });` | `commands.send_event(event);`
|
2024-12-30 20:58:03 +00:00
Ethereumdegen
4f9dc6534b
fix visibility propagation during reparenting (#17025)
# Objective
Fixes #17024 

## Solution
 

## Testing
 By adding 

```
if let Some(mut cmd) = commands.get_entity( *equipment_link_node ){
                         cmd.insert(Visibility::Inherited); // a hack for now 
                     }

```
in my build after .set_parent() , this fixes the issue. This is why i
think that this change will fix the issue. Unfortunately i was not able
to test the Changed (parent ) , this actual code change, because no
matter how i 'patch', it breaks my project. I got super close but still
had 23 errors due to Reflect being angry.


---
2024-12-30 20:55:44 +00:00
Brezak
ae16bdf172
Add fallible add methods to PluginGroupBuilder (#17005)
# Objective

Make working with `PluginGroupBuilder` less panicky.
Fixes #17001

## Solution

Expand the `PluginGroupBuilder` api with fallible add methods + a
contains method.
Also reorder the `PluginGroupBuilder` tests because before should come
before after.

## Testing

Ran the `PluginGroupBuilder` tests which call into all the newly added
methods.
2024-12-30 20:14:02 +00:00
Patrick Walton
7767a8d161
Refactor batch_and_prepare_binned_render_phase in preparation for bin retention. (#16922)
This commit makes the following changes:

* `IndirectParametersBuffer` has been changed from a `BufferVec` to a
`RawBufferVec`. This won about 20us or so on Bistro by avoiding `encase`
overhead.

* The methods on the `GetFullBatchData` trait no longer have the
`entity` parameter, as it was unused.

* `PreprocessWorkItem`, which specifies a transform-and-cull operation,
now supplies the mesh instance uniform output index directly instead of
having the shader look it up from the indirect draw parameters.
Accordingly, the responsibility of writing the output index to the
indirect draw parameters has been moved from the CPU to the GPU. This is
in preparation for retained indirect instance draw commands, where the
mesh instance uniform output index may change from frame to frame, while
the indirect instance draw commands will be cached. We won't want the
CPU to have to upload the same indirect draw parameters again and again
if a batch didn't change from frame to frame.

* `batch_and_prepare_binned_render_phase` and
`batch_and_prepare_sorted_render_phase` now allocate indirect draw
commands for an entire batch set at a time when possible, instead of one
batch at a time. This change will allow us to retain the indirect draw
commands for whole batch sets.

* `GetFullBatchData::get_batch_indirect_parameters_index` has been
replaced with `GetFullBatchData::write_batch_indirect_parameters`, which
takes an offset and writes into it instead of allocating. This is
necessary in order to use the optimization mentioned in the previous
point.

* At the WGSL level, `IndirectParameters` has been factored out into
`mesh_preprocess_types.wgsl`. This is because we'll need a new compute
shader that zeroes out the instance counts in preparation for a new
frame. That shader will need to access `IndirectParameters`, so it was
moved to a separate file.

* Bins are no longer raw vectors but are instances of a separate type,
`RenderBin`. This is so that the bin can eventually contain its retained
batches.
2024-12-30 20:11:31 +00:00
Patrick Walton
fde7968168
Unbreak shadows by retaining work item buffers corresponding to ExtractedViews, not ViewTargets. (#17039)
OK, so this is tricky. Every frame, `delete_old_work_item_buffers`
deletes the mesh preprocessing index buffers (a.k.a. work item buffers)
for views that don't have `ViewTarget`s. This was always wrong for
shadow map views, as shadow maps only have `ExtractedView` components,
not `ViewTarget`s. However, before #16836, the problem was masked,
because uploading the mesh preprocessing index buffers for shadow views
had already completed by the time `delete_old_work_item_buffers` ran.
But PR #16836 moved `delete_old_work_item_buffers` from the
`ManageViews` phase to `PrepareResources`, which runs before
`write_batched_instance_buffers` uploads the work item buffers to the
GPU.

This itself isn't wrong, but it exposed the bug, because now it's
possible for work item buffers to get deleted before they're uploaded in
`write_batched_instance_buffers`. This is actually intermittent! It's
possible for the old work item buffers to get deleted, and then
*recreated* in `batch_and_prepare_binned_render_phase`, which runs
during `PrepareResources` as well, and under that system ordering, there
will be no problem other than a little inefficiency arising from
recreating the buffers every frame. But, if
`delete_old_work_item_buffers` runs *after*
`batch_and_prepare_render_phase`, then the work item buffers
corresponding to shadow views will get deleted, and then the shadows
will disappear.

The fact that this is racy is what made it look like #16922 solved the
issue. In fact, it didn't: it just perturbed the ordering on the build
bots enough that the issue stopped appearing. However, on my system, the
shadows still don't appear with #16922.

This commit solves the problem by making `delete_old_work_item_buffers`
look at `ExtractedView`s, not `ViewTarget`s, preventing work item
buffers corresponding to live shadow map views from being deleted.
2024-12-30 20:06:40 +00:00
Benjamin Brienen
0362abd4f4
Make extract_mesh_materials and MaterialBindGroupAllocator public (#16982)
# Objective

Fixes #16730

## Solution

Make the relevant functions public. (`MaterialBindGroupAllocator` itself
was already `pub`)
2024-12-30 05:57:11 +00:00
Brezak
54a3fd7754
Don't overalign aligned values in gpu_readback::align_byte_size (#17007)
# Objective

Fix alignment calculations in our rendering code.
Fixes #16992 

The `gpu_readback::align_byte_size` function incorrectly rounds aligned
values to the next alignment.
If we assume the alignment to be 256 (because that's what wgpu says it
its) the function would align 0 to 256, 256 to 512, etc...

## Solution

Forward the `gpu_readback::align_byte_size` to
`RenderDevice::align_copy_bytes_per_row` so we don't implement the same
method twice.
Simplify `RenderDevice::align_copy_bytes_per_row`.

## Testing

Ran the code provided in #16992 to see if the issue has been solved +
added a test to check if `align_copy_bytes_per_row` returns the correct
values.
2024-12-30 05:51:37 +00:00
Christian Hughes
b09bbfa905
Remove unsound Clone impl for EntityMutExcept (#17032)
# Objective

`EntityMutExcept` can currently be cloned, which can easily violate
aliasing rules.

## Solution

- Remove the `Clone` impl for `EntityMutExcept`
- Also manually derived `Clone` impl for `EntityRefExcept` so that `B:
Clone` isn't required, and also impl'd `Copy`

## Testing

Compile failure tests would be good for this, but I'm not exactly sure
how to set that up.

## Migration Guide

- `EntityMutExcept` can no-longer be cloned, as this violates Rust's
memory safety rules.
2024-12-30 05:17:46 +00:00
Zachary Harrold
79a367db16
Add no_std support to bevy_state (#17028)
# Objective

- Contributes to #15460

## Solution

- Added the following features:
  - `std` (default)
  - `portable-atomic`
  - `critical-section`

## Testing

- CI

## Notes

- `portable-atomic`, and `critical-section` are shortcuts to enable the
relevant features in dependencies, making the usage of this crate on
atomically challenged platforms possible and simpler.
- This PR is blocked until #17027 is merged (as it depends on fixes for
the `once!` macro). Once merged, the change-count for this PR should
reduce.
2024-12-29 23:28:18 +00:00
Rob Parrett
150eec7535
Fix Text2d performance regression (#16991)
# Objective

Probably fixes #16972

## Solution

With 100k text2d, tracy was showing most time being spent in
`extract_components<bevy_sprite::SpriteSource>`.


![image](https://github.com/user-attachments/assets/e82d5d4e-bb39-4d7e-ab7f-47a5466cb74f)

Browsing Bevy's code, this `SpriteSource` component is seemingly not
even used in the render world. So I just ~~deleted the code that was
extracting it~~ it.

## Testing

`cargo run --example text2d` still seems to work.

The example from [my
comment](https://github.com/bevyengine/bevy/issues/16972#issuecomment-2562680876)
in the linked issue shows a ~50x speedup.
2024-12-29 23:14:33 +00:00
Lyndon-Mackay
1614b213f1
Basic filtering examples for users of the bevy_log. (#16455)
# Objective

Give users a quick example on how to control logging so they can filter
out library logs while reading their own
This is intended to fix issue #15957.

## Solution

Added some examples

## Testing

I created project and tested the examples work

###
This is purely a documentation change.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Andres O. Vela <andresovela@users.noreply.github.com>
Co-authored-by: Benjamin Brienen <benjamin.brienen@outlook.com>
2024-12-29 22:56:40 +00:00
Zachary Harrold
c8110f5f86
Add portable-atomic support to bevy_utils for once! (#17027)
# Objective

- Improves platform compatibility for `bevy_utils`

## Solution

- Added `portable-atomic` to allow using the `once!` macro on more
platforms (e.g., Raspberry Pi Pico)

## Testing

- CI

## Notes

- This change should be entirely hidden thanks to the use of
`doc(hidden)`. Enabling the new `portable-atomic` feature just allows
using the `once!` macro on platforms which previously could not.
- I took the liberty of updating the feature documentation to be more in
line with how I've documented features in `bevy_ecs`/`bevy_app`/etc. for
their `no_std` updates.
2024-12-29 22:50:08 +00:00
Rob Parrett
ad9f946201
Add many_text2d stress test (#16997)
# Objective

Make it easier to test for `Text2d` performance regressions.

Related to #16972

## Solution

Add a new `stress_test`, based on `many_sprites` and other existing
stress tests.

The `many-glyphs` option is inspired by
https://github.com/bevyengine/bevy/issues/16901#issuecomment-2558572382.

## Testing

```bash
cargo run --release --example many_text2d -- --help
cargo run --release --example many_text2d
cargo run --release --example many_text2d -- --many_glyphs
```

etc
2024-12-29 22:47:01 +00:00
Zachary Harrold
46af46695b
Add no_std support to bevy_input (#16995)
# Objective

- Contributes to #15460

## Solution

- Added the following features:
  - `std` (default)
  - `smol_str` (default)
  - `portable-atomic`
  - `critical-section`
  - `libm`
- Fixed an existing issue where `bevy_reflect` wasn't properly feature
gated.

## Testing

- CI

## Notes

- There were some minor issues with `bevy_math` and `bevy_ecs` noticed
in this PR which I have also resolved here. I can split these out if
desired, but I've left them here for now as they're very small changes
and I don't consider this PR itself to be very controversial.
- `libm`, `portable-atomic`, and `critical-section` are shortcuts to
enable the relevant features in dependencies, making the usage of this
crate on atomically challenged platforms possible and simpler.
- `smol_str` is gated as it doesn't support atomically challenged
platforms (e.g., Raspberry Pi Pico). I have an issue and a
[PR](https://github.com/rust-analyzer/smol_str/pull/91) to discuss this
upstream.
2024-12-29 22:46:30 +00:00
Martin Dickopp
6114347bc4
Fix confusing comment in pbr example (#16996)
# Objective

After a recent fix for a panic in the pbr example (#16976), the code
contains the following comment:

```rust
// This system relies on system parameters that are not available at start
// Ignore parameter failures so that it will run when possible
.add_systems(Update, environment_map_load_finish.never_param_warn())
```

However, this explanation is incorrect. `EnvironmentMapLabel` is
available at start. The real issue is that it is no longer available
once it has been removed by `environment_map_load_finish`.

## Solution

- Remove confusing/incorrect comment and `never_param_warn()`.
- Make `Single<Entity, With<EnvironmentMapLabel>>` optional in
`environment_map_load_finish`, and check that the entity has not yet
been despawned.

Since it is expected that an entity is no longer there once it has been
despawned, it seems better to me to handle this case in
`environment_map_load_finish`.

## Testing

Ran `cargo run --example pbr`.
2024-12-29 22:45:17 +00:00
JaySpruce
0f2b2de333
Move some structs that impl Command to methods on World and EntityWorldMut (#16999)
## Objective

Commands were previously limited to structs that implemented `Command`.
Now there are blanket implementations for closures, which (in my
opinion) are generally preferable.

Internal commands within `commands/mod.rs` have been switched from
structs to closures, but there are a number of internal commands in
other areas of the engine that still use structs. I'd like to tidy these
up by moving their implementations to methods on
`World`/`EntityWorldMut` and changing `Commands` to use those methods
through closures.

This PR handles the following:
- `TriggerEvent` and `EmitDynamicTrigger` double as commands and helper
structs, and can just be moved to `World` methods.
- Four structs that enabled insertion/removal of components via
reflection. This functionality shouldn't be exclusive to commands, and
can be added to `EntityWorldMut`.
- Five structs that mostly just wrapped `World` methods, and can be
replaced with closures that do the same thing.

## Solution

- __Observer Triggers__ (`observer/trigger_event.rs` and
`observer/mod.rs`)
- Moved the internals of `TriggerEvent` to the `World` methods that used
it.
  - Replaced `EmitDynamicTrigger` with two `World` methods:
    - `trigger_targets_dynamic`
    - `trigger_targets_dynamic_ref`
- `TriggerTargets` was now the only thing in
`observer/trigger_event.rs`, so it's been moved to `observer/mod.rs` and
`trigger_event.rs` was deleted.
- __Reflection Insert/Remove__ (`reflect/entity_commands.rs`)
- Replaced the following `Command` impls with equivalent methods on
`EntityWorldMut`:
    - `InsertReflect` -> `insert_reflect`
    - `InsertReflectWithRegistry` -> `insert_reflect_with_registry`
    - `RemoveReflect` -> `remove_reflect`
    - `RemoveReflectWithRegistry` -> `remove_reflect_with_registry`
- __System Registration__ (`system/system_registry.rs`)
- The following `Command` impls just wrapped a `World` method and have
been replaced with closures:
    - `RunSystemWith`
    - `UnregisterSystem`
    - `RunSystemCachedWith`
    - `UnregisterSystemCached`
- `RegisterSystem` called a helper function that basically worked as a
constructor for `RegisteredSystem` and made sure it came with a marker
component. That helper function has been replaced with
`RegisteredSystem::new` and a `#[require]`.

## Possible Addition

The extension trait that adds the reflection commands,
`ReflectCommandExt`, isn't strictly necessary; we could just `impl
EntityCommands`. We could even move them to the same files as the main
impls and put it behind a `#[cfg]`.

The PR that added it [had a similar
conversation](https://github.com/bevyengine/bevy/pull/8895#discussion_r1234713671)
and decided to stick with the trait, but we could revisit it here if so
desired.
2024-12-29 22:18:53 +00:00
BD103
291cb31798
Overhaul bezier curve benchmarks (#17016)
# Objective

- Part of #16647.
- The benchmarks for bezier curves have several issues and do not yet
use the new `bench!` naming scheme.

## Solution

- Make all `bevy_math` benchmarks use the `bench!` macro for their name.
- Delete the `build_accel_cubic()` benchmark, since it was an exact
duplicate of `build_pos_cubic()`.
- Remove `collect::<Vec<_>>()` call in `build_pos_cubic()` and replace
it with a `for` loop.
- Combine all of the benchmarks that measure `curve.position()` under a
single group, `curve_position`, and extract the common bench routine
into a helper function.
- Move the time calculation for the `curve.ease()` benchmark into the
setup closure so it is not tracked.
- Rename the benchmarks to be more descriptive on what they do.
  - `easing_1000` -> `segment_ease`
  - `cubic_position_Vec2` -> `curve_position/vec2`
  - `cubic_position_Vec3A` -> `curve_position/vec3a`
  - `cubic_position_Vec3` -> `curve_position/vec3`
  - `build_pos_cubic_100_points` -> `curve_iter_positions`

## Testing

- `cargo test -p benches --bench math`
- `cargo bench -p benches --bench math`
  - Then open `./target/criterion/report/index.html` to see the report!

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-12-29 20:55:08 +00:00
Benjamin Brienen
8c34f00deb
Fix msrvs (#17012)
# Objective

The rust-versions are out of date.
Fixes #17008

## Solution

Update the values

Cherry-picked from #17006 in case it is controversial

## Testing

Validated locally and in #17006

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-12-29 20:00:19 +00:00
Brezak
dc2cd71dc8
Make RawHandleWrapper fields private to save users from themselves (#16968)
# Objective

Fixes #16683

## Solution

Make all fields ine `RawHandleWrapper` private.

## Testing

- CI
- `cargo clippy`
- The lightmaps example
---

## Migration Guide

The `window_handle` and `dispay_handle` fields on `RawHandleWrapper` are
no longer public. Use the newly added getters and setters to manipulate
them instead.
2024-12-29 19:54:57 +00:00