Commit graph

8304 commits

Author SHA1 Message Date
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
super-saturn
2dcf6bcfd7
Fix path checking for FileWatcher for virtual workspace projects (#16958)
# Objective

Fixes #16879

## Solution

Moved the construction of the root path of the assets folder out of
`FileWatcher::new()` and into `source.rs`, as the path is checked there
with `path.exists()` and fails in certain configurations eg., virtual
workspaces.

## Testing

Applied fix to a private fork and tested against both standard project
setups and virtual workspaces. Works without issue on both. Have tested
under macOS and Arch Linux.

---------

Co-authored-by: JP Stringham <jp@bloomdigital.to>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-12-29 19:43:42 +00:00
BD103
17ad855653
Migrate to core::hint::black_box() (#16980)
# Objective

Many of our benchmarks use
[`criterion::black_box()`](https://docs.rs/criterion/latest/criterion/fn.black_box.html),
which is used to prevent the compiler from optimizing away computation
that we're trying to time. This can be slow, though, because
`criterion::black_box()` forces a point read each time it is called
through
[`ptr::road_volatile()`](https://doc.rust-lang.org/stable/std/ptr/fn.read_volatile.html).

In Rust 1.66, the standard library introduced
[`core::hint::black_box()`](https://doc.rust-lang.org/nightly/std/hint/fn.black_box.html)
(and `std::hint::black_box()`). This is an intended replacement for
`criterion`'s version that uses compiler intrinsics instead of volatile
pointer reads, and thus has no runtime overhead. This increases
benchmark accuracy, which is always nice 👍

Note that benchmarks may _appear_ to improve in performance after this
change, but that's just because we are eliminating the pointer read
overhead.

## Solution

- Deny `criterion::black_box` in `clippy.toml`.
- Fix all imports.

## Testing

- `cargo clippy -p benches --benches`
2024-12-29 19:33:42 +00:00
BD103
f391522483
Test benchmarks in CI (#16987)
# Objective

- This reverts #16833, and completely goes against #16803.
- Turns out running `cargo test --benches` runs each benchmark once,
without timing it, just to ensure nothing panics. This is actually
desired because we can use it to verify benchmarks are working correctly
without all the time constraints of actual benchmarks.

## Solution

- Add the `--benches` flag to the CI test command.

## Testing

- `cargo run -p ci -- test`
2024-12-29 19:33:06 +00:00
Satellile
58a84d965e
Fix Docs // incorrect default value for ChromaticAberration intensity (#16994)
# Objective

Incorrect default value for ChromatticAberration intensity, missing a
zero. Bevy 0.15
2024-12-29 19:32:44 +00:00
Martín Maita
5157c78651
Move futures.rs, ConditionalSend and BoxedFuture types to bevy_tasks (#16951)
# Objective

- Related to https://github.com/bevyengine/bevy/issues/11478

## Solution

- Moved `futures.rs`, `ConditionalSend` `ConditionalSendFuture` and
`BoxedFuture` from `bevy_utils` to `bevy_tasks`.

## Testing

- CI checks

## Migration Guide

- Several modules were moved from `bevy_utils` into `bevy_tasks`:
  - Replace `bevy_utils::futures` imports with `bevy_tasks::futures`.
- Replace `bevy_utils::ConditionalSend` with
`bevy_tasks::ConditionalSend`.
- Replace `bevy_utils::ConditionalSendFuture` with
`bevy_tasks::ConditionalSendFuture`.
  - Replace `bevy_utils::BoxedFuture` with `bevy_tasks::BoxedFuture`.
2024-12-29 19:29:53 +00:00
Benjamin Brienen
847c3a1719
Fix random clippy warning (#17010)
# Objective

Follow-up to #16984 

## Solution

Fix the lint

## Testing

```
PS C:\Users\BenjaminBrienen\source\bevy> cargo clippy
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.71s
PS C:\Users\BenjaminBrienen\source\bevy> cargo clippy -p bevy_ecs
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.21s
```
2024-12-29 19:28:59 +00:00
Matty Weatherley
97909df6c0
Refactor non-core Curve methods into extension traits (#16930)
# Objective

The way `Curve` presently achieves dyn-compatibility involves shoving
`Self: Sized` bounds on a bunch of methods to forbid them from appearing
in vtables. (This is called *explicit non-dispatchability*.) The `Curve`
trait probably also just has way too many methods on its own.

In the past, using extension traits instead to achieve similar
functionality has been discussed. The upshot is that this would allow
the "core" of the curve trait, on which all the automatic methods rely,
to live in a very simple dyn-compatible trait, while other functionality
is implemented by extensions. For instance, `dyn Curve<T>` cannot use
the `Sized` methods, but `Box<dyn Curve<T>>` is `Sized`, hence would
automatically implement the extension trait, containing the methods
which are currently non-dispatchable.

Other motivations for this include modularity and code organization: the
`Curve` trait itself has grown quite large with the addition of numerous
adaptors, and refactoring it to demonstrate the separation of
functionality that is already present makes a lot of sense. Furthermore,
resampling behavior in particular is dependent on special traits that
may be mimicked or analogized in user-space, and creating extension
traits to achieve similar behavior in user-space is something we ought
to encourage by example.

## Solution

`Curve` now contains only `domain` and the `sample` methods. 

`CurveExt` has been created, and it contains all adaptors, along with
the other sampling convenience methods (`samples`, `sample_iter`, etc.).
It is implemented for all `C` where `C: Curve<T> + Sized`.

`CurveResampleExt` has been created, and it contains all resampling
methods. It is implemented for all `C` where `C: Curve<T> + ?Sized`.

## Testing

It compiles and `cargo doc` succeeds.

---

## Future work

- Consider writing extension traits for resampling curves in related
domains (e.g. resampling for `Curve<T>` where `T: Animatable` into an
`AnimatableKeyframeCurve`).
- `CurveExt` might be further broken down to separate the adaptor and
sampling methods.

---

## Migration Guide

`Curve` has been refactored so that much of its functionality is now in
extension traits. Adaptors such as `map`, `reparametrize`, `reverse`,
and so on now require importing `CurveExt`, while the resampling methods
`resample_*` require importing `CurveResampleExt`. Both of these new
traits are exported through `bevy::math::curve` and through
`bevy::math::prelude`.
2024-12-29 19:26:49 +00:00
to-bak
31367108f7
Update linux dependency documentation for NixOS (and nix) (#16881)
# Objective
- Updates the linux-dependencies docs to 1) fix problems with nix
`alsa-lib`, and 2) include additional documentation to run bevy with nix
on non NixOS systems. (nix is a package manager that can be run outside
of NixOS).

## Solution
1. the nix `alsa-lib` package doesn't include `alsa-plugins`, which bevy
depends on. Instead, use the `alsa-lib-with-plugins` package, which
wraps `alsa-plugins` into `alsa-lib`. For more information see:
https://github.com/NixOS/nixpkgs/pull/277180
2. using nix on non NixOS systems, software like `nixGL` is required to
correctly link graphics drivers.

## Testing
- Tested on ubuntu 22.04 with nix.
2024-12-29 19:20:51 +00:00
Zachary Harrold
3d280ec37b
Add no_std support to bevy_hierarchy (#16998)
# Objective

- Contributes to #15460

## Solution

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

## Testing

- CI

## Notes

- There was a minor issue with `bevy_reflect`'s `smallvec` feature
noticed in this PR which I have also resolved here. I can split this out
if desired, but I've left it here for now as it's a very small change
and I don't consider this PR itself to be very controversial.
2024-12-29 19:12:29 +00:00
Benjamin Brienen
64efd08e13
Prefer Display over Debug (#16112)
# Objective

Fixes #16104

## Solution

I removed all instances of `:?` and put them back one by one where it
caused an error.

I removed some bevy_utils helper functions that were only used in 2
places and don't add value. See: #11478

## Testing

CI should catch the mistakes

## Migration Guide

`bevy::utils::{dbg,info,warn,error}` were removed. Use
`bevy::utils::tracing::{debug,info,warn,error}` instead.

---------

Co-authored-by: SpecificProtagonist <vincentjunge@posteo.net>
2024-12-27 00:40:06 +00:00