Commit graph

5922 commits

Author SHA1 Message Date
Benjamin Brienen
afd0f1322d
Move all_tuples to a new crate (#16161)
# Objective

Fixes #15941

## Solution

Created https://crates.io/crates/variadics_please and moved the code
there; updating references

`bevy_utils/macros` is deleted.

## Testing

cargo check

## Migration Guide

Use `variadics_please::{all_tuples, all_tuples_with_size}` instead of
`bevy::utils::{all_tuples, all_tuples_with_size}`.
2024-12-03 17:41:09 +00:00
eugineerd
2e267bba5a
Entity cloning (#16132)
## Objective

Fixes #1515 

This PR implements a flexible entity cloning system. The primary use
case for it is to clone dynamically-generated entities.

Example:
```rs
#[derive(Component, Clone)]
pub struct Projectile;

#[derive(Component, Clone)]
pub struct Damage {
    value: f32,
}

fn player_input(
    mut commands: Commands,
    projectiles: Query<Entity, With<Projectile>>,
    input: Res<ButtonInput<KeyCode>>,
) {
    // Fire a projectile
    if input.just_pressed(KeyCode::KeyF) {
        commands.spawn((Projectile, Damage { value: 10.0 }));
    }

    // Triplicate all active projectiles
    if input.just_pressed(KeyCode::KeyT) {
        for projectile in projectiles.iter() {
            // To triplicate a projectile we need to create 2 more clones
            for _ in 0..2{
                commands.clone_entity(projectile)
            }
        }
    }
}
```

## Solution

### Commands
Add a `clone_entity` command to create a clone of an entity with all
components that can be cloned. Components that can't be cloned will be
ignored.
```rs
commands.clone_entity(entity)
```
If there is a need to configure the cloning process (like set to clone
recursively), there is a second command:
```rs
commands.clone_entity_with(entity, |builder| {
    builder.recursive(true)
});
```
Both of these commands return `EntityCommands` of the cloned entity, so
the copy can be modified afterwards.

### Builder
All these commands use `EntityCloneBuilder` internally. If there is a
need to clone an entity using `World` instead, it is also possible:
```rs
let entity = world.spawn(Component).id();
let entity_clone = world.spawn_empty().id();
EntityCloneBuilder::new(&mut world).clone_entity(entity, entity_clone);
```

Builder has methods to `allow` or `deny` certain components during
cloning if required and can be extended by implementing traits on it.
This PR includes two `EntityCloneBuilder` extensions:
`CloneEntityWithObserversExt` to configure adding cloned entity to
observers of the original entity, and `CloneEntityRecursiveExt` to
configure cloning an entity recursively.

### Clone implementations
By default, all components that implement either `Clone` or `Reflect`
will be cloned (with `Clone`-based implementation preferred in case
component implements both).

This can be overriden on a per-component basis:
```rs
impl Component for SomeComponent {
    const STORAGE_TYPE: StorageType = StorageType::Table;

    fn get_component_clone_handler() -> ComponentCloneHandler {
        // Don't clone this component
        ComponentCloneHandler::Ignore
    }
}
```

### `ComponentCloneHandlers`
Clone implementation specified in `get_component_clone_handler` will get
registered in `ComponentCloneHandlers` (stored in
`bevy_ecs::component::Components`) at component registration time.

The clone handler implementation provided by a component can be
overriden after registration like so:
```rs
let component_id = world.components().component_id::<Component>().unwrap()
world.get_component_clone_handlers_mut()
     .set_component_handler(component_id, ComponentCloneHandler::Custom(component_clone_custom))
```
The default clone handler for all components that do not explicitly
define one (or don't derive `Component`) is
`component_clone_via_reflect` if `bevy_reflect` feature is enabled, and
`component_clone_ignore` (noop) otherwise.
Default handler can be overriden using
`ComponentCloneHandlers::set_default_handler`

### Handlers
Component clone handlers can be used to modify component cloning
behavior. The general signature for a handler that can be used in
`ComponentCloneHandler::Custom` is as follows:
```rs
pub fn component_clone_custom(
    world: &mut DeferredWorld,
    entity_cloner: &EntityCloner,
) {
    // implementation
}
```
The `EntityCloner` implementation (used internally by
`EntityCloneBuilder`) assumes that after calling this custom handler,
the `target` entity has the desired version of the component from the
`source` entity.

### Builder handler overrides
Besides component-defined and world-overriden handlers,
`EntityCloneBuilder` also has a way to override handlers locally. It is
mainly used to allow configuration methods like `recursive` and
`add_observers`.
```rs
// From observer clone handler implementation
impl CloneEntityWithObserversExt for EntityCloneBuilder<'_> {
    fn add_observers(&mut self, add_observers: bool) -> &mut Self {
        if add_observers {
            self.override_component_clone_handler::<ObservedBy>(ComponentCloneHandler::Custom(
                component_clone_observed_by,
            ))
        } else {
            self.remove_component_clone_handler_override::<ObservedBy>()
        }
    }
}
```

## Testing
Includes some basic functionality tests and doctests.

Performance-wise this feature is the same as calling `clone` followed by
`insert` for every entity component. There is also some inherent
overhead due to every component clone handler having to access component
data through `World`, but this can be reduced without breaking current
public API in a later PR.
2024-12-03 17:38:10 +00:00
JMS55
d221665386
Native unclipped depth on supported platforms (#16095)
# Objective
- Fixes #16078

## Solution

- Rename things to clarify that we _want_ unclipped depth for
directional light shadow views, and need some way of disabling the GPU's
builtin depth clipping
- Use DEPTH_CLIP_CONTROL instead of the fragment shader emulation on
supported platforms
- Pass only the clip position depth instead of the whole clip position
between vertex->fragment shader (no idea if this helps performance or
not, compiler might optimize it anyways)
- Meshlets
- HW raster always uses DEPTH_CLIP_CONTROL since it targets a more
limited set of platforms
- SW raster was not handling DEPTH_CLAMP_ORTHO correctly, it ended up
pretty much doing nothing.
- This PR made me realize that SW raster technically should have depth
clipping for all views that are not directional light shadows, but I
decided not to bother writing it. I'm not sure that it ever matters in
practice. If proven otherwise, I can add it.

## Testing

- Did you test these changes? If so, how?
- Lighting example. Both opaque (no fragment shader) and alpha masked
geometry (fragment shader emulation) are working with
depth_clip_control, and both work when it's turned off. Also tested
meshlet example.
- Are there any parts that need more testing?
  - Performance. I can't figure out a good test scene.
- How can other people (reviewers) test your changes? Is there anything
specific they need to know?
- Toggle depth_clip_control_supported in prepass/mod.rs line 323 to turn
this PR on or off.
- If relevant, what platforms did you test these changes on, and are
there any important ones you can't test?
  - Native

---

## Migration Guide
- `MeshPipelineKey::DEPTH_CLAMP_ORTHO` is now
`MeshPipelineKey::UNCLIPPED_DEPTH_ORTHO`
- The `DEPTH_CLAMP_ORTHO` shaderdef has been renamed to
`UNCLIPPED_DEPTH_ORTHO_EMULATION`
- `clip_position_unclamped: vec4<f32>` is now `unclipped_depth: f32`
2024-12-03 17:30:14 +00:00
Shane Celis
f375422ddd
Compute better smooth normals for cheaper, maybe (#16050)
# Objective

Avoid a premature normalize operation and get better smooth normals for
it.

## Inspiration

@IceSentry suggested `face_normal()` could have its normalize removed
based on [this article](https://iquilezles.org/articles/normals/) in PR
#16039.

## Solution

I did not want to change `face_normal()` to return a vector that's not
normalized. The name "normal" implies it'll be normalized. Instead I
added the `face_area_normal()` function, whose result is not normalized.
Its magnitude is equal two times the triangle's area. I've noted why
this is the case in its doc comment.

I changed `compute_smooth_normals()` from computing normals from
adjacent faces with equal weight to use the area of the faces as a
weight. This has the benefit of being cheaper computationally and
hopefully produces better normals.

The `compute_flat_normals()` is unchanged and still uses
`face_normal()`.

## Testing

One test was added which shows the bigger triangle having an effect on
the normal, but the previous test that uses the same size triangles is
unchanged.

**WARNING:** No visual test has been done yet. No example exists that
demonstrates the compute_smooth_normals(). Perhaps there's a good model
to demonstrate what the differences are. I would love to have some input
on this.

I'd suggest @IceSentry and @stepancheg to review this PR.

## Further Considerations

It's possible weighting normals by their area is not definitely better
than unweighted. It's possible there may be aesthetic reasons to prefer
one over the other. In such a case, we could offer two variants:
weighted or unweighted. Or we could offer another function perhaps like
this: `compute_smooth_normals_with_weights(|normal, area| 1.0)` which
would restore the original unweighted sum of normals.

---

## Showcase

Smooth normal calculation now weights adjacent face normals by their
area.

## Migration Guide
2024-12-03 17:25:10 +00:00
HugoPeters1024
b9cc6e16da
bevy_winit(emit raw winit events) (#15884)
# Objective

- Exposes raw winit events making Bevy even more modular and powerful
for custom plugin developers (e.g. a custom render plugin).

XRef: https://github.com/bevyengine/bevy/issues/5977
It doesn't quite close the issue as sending events is not supported (or
not very useful to be precise). I would think that supporting that
requires some extra considerations by someone a bit more familiar with
the `bevy_winit` crate. That said, this PR could be a nice step forward.

## Solution

Emit `RawWinitWindowEvent` objects for each received event.

## Testing

I verified that the events are emitted using a basic test app. I don't
think it makes sense to solidify this behavior in one of the examples.

---

## Showcase

My example usage for a custom `egui_winit` integration:

```rust
for ev in winit_events.read() {
    if ev.window_id == window.id {
        let _ = egui_winit.on_window_event(&window, &ev.event);
    }
}
```

---------

Co-authored-by: IceSentry <IceSentry@users.noreply.github.com>
2024-12-03 17:20:43 +00:00
Nico Burns
1fe38b85f1
Upgrade to Taffy 0.6 (#15844)
# Objective

- Keep Taffy version up to date

Taffy 0.6 doesn't include a huge amount relevant to Bevy. But it does:

- Add the `box_sizing` style
- Expose the computed `margin` in layout
- Traitifies the `Style` struct, which opens up the possibility of using
Bevy's `Style` struct directly (although Bevy currently does some style
resolution at conversion time which would no longer be cached if it was
used directly).
- Have a few bug fixes in the layout algorithms

## Solution

- Upgrade Taffy to `0.6.0`

## Testing

- I've run the `grid` example. All looks good.
- More testing is probably warranted. We have had regressions from Taffy
upgrades before
- Having said that, most of the algorithm changes this cycle were driven
by fixing WPT tests run through the new Servo integration. So they're
possibly less likely than usual to cause regressions.

## Breaking changes

The only "breaking" change is adding a field to `Style`. Probably
doesn't bear mentioning?

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-12-03 17:16:35 +00:00
Zachary Harrold
a8b9c945c7
Add no_std Support to bevy_math (#15810)
# Objective

- Contributes to #15460

## Solution

- Added two new features, `std` (default) and `alloc`, gating `std` and
`alloc` behind them respectively.
- Added missing `f32` functions to `std_ops` as required. These `f32`
methods have been added to the `clippy.toml` deny list to aid in
`no_std` development.

## Testing

- CI
- `cargo clippy -p bevy_math --no-default-features --features libm
--target "x86_64-unknown-none"`
- `cargo test -p bevy_math --no-default-features --features libm`
- `cargo test -p bevy_math --no-default-features --features "libm,
alloc"`
- `cargo test -p bevy_math --no-default-features --features "libm,
alloc, std"`
- `cargo test -p bevy_math --no-default-features --features "std"`

## Notes

The following items require the `alloc` feature to be enabled:

- `CubicBSpline`
- `CubicBezier`
- `CubicCardinalSpline`
- `CubicCurve`
- `CubicGenerator`
- `CubicHermite`
- `CubicNurbs`
- `CyclicCubicGenerator`
- `RationalCurve`
- `RationalGenerator`
- `BoxedPolygon`
- `BoxedPolyline2d`
- `BoxedPolyline3d`
- `SampleCurve`
- `SampleAutoCurve`
- `UnevenSampleCurve`
- `UnevenSampleAutoCurve`
- `EvenCore`
- `UnevenCore`
- `ChunkedUnevenCore`

This requirement could be relaxed in certain cases, but I had erred on
the side of gating rather than modifying. Since `no_std` is a new set of
platforms we are adding support to, and the `alloc` feature is enabled
by default, this is not a breaking change.

---------

Co-authored-by: Benjamin Brienen <benjamin.brienen@outlook.com>
Co-authored-by: Matty <2975848+mweatherley@users.noreply.github.com>
Co-authored-by: Joona Aalto <jondolf.dev@gmail.com>
2024-12-03 17:14:51 +00:00
Vic
aa600ae95e
implement the full set of sorts on QueryManyIter (#13443)
# Objective

~Blocked on #13417~

Motivation is the same as in #13417. If users can sort `QueryIter`, to
only makes sense to also allow them to use this functionality on
`QueryManyIter`.

## Solution

Also implement the sorts on `QueryManyIter`. 

The implementation of the sorts themselves are mostly the same as with
`QueryIter` in #13417.
They differ in that they re-use the `entity_iter` passed to the
`iter_many`, and internally call `iter_many_unchecked_manual` on the
lens `QueryState` with it.
These methods also return a different struct, `QuerySortedManyIter`,
because there is no longer a guarantee of unique entities.
`QuerySortedManyIter` implements the various `Iterator` traits for
read-only iteration, as `QueryManyIter` does + `DoubleEndedIterator`.
For mutable iteration, there is both a `fetch_next` and a
`fetch_next_back` method. However, they only become available after the
user calls `collect_inner` on `QuerySortedManyIter` first. This collects
the inner `entity_iter` (this is the sorted one, **not** the original
the user passed) to drop all query lens items to avoid aliasing.
When TAITs are available this `collect_inner` could be hidden away,
until then it is unfortunately not possible to elide this without either
regressing read-only iteration, or introducing a whole new type, mostly
being a copy of `QuerySortedIter`.

As a follow-up we could add a `entities_all_unique` method to check
whether the entity list consists of only unique entities, and then
return a `QuerySortedIter` from it (under opaque impl Trait if need be),
*allowing mutable `Iterator` trait iteration* over what was originally
an `iter_many` call.
Such a method can also be added to `QueryManyIter`, albeit needing a
separate, new return type.

## Testing

I've switched the third example/doc test under `sort` out for one that
shows the collect_inner/fetch_next_back functionality, otherwise the
examples are the same as in #13417, adjusted to use `iter_many` instead
of `iter`.

The `query-iter-many-sorts` test checks for equivalence to the
underlying sorts.
The test after shows that these sorts *do not* panic after
`fetch`/`fetch_next` calls.

## Changelog

Added `sort`, `sort_unstable`, `sort_by`, `sort_unstable_by`,
`sort_by_key`, `sort_by_cached_key` to `QueryManyIter`.
Added `QuerySortedManyIter`.
2024-12-03 17:02:37 +00:00
atlv
d4883a9b5f
switch bevy_image to use wgpu-types wherever possible instead of wgpu (#16620)
# Objective

- dont depend on wgpu if we dont have to

## Solution

- works towards this, but doesnt fully accomplish it. the remaining
types stopping us from doing this need to be moved upstream, i will PR
this

## Testing

- 3d_scene runs

---------

Co-authored-by: François Mockers <francois.mockers@vleue.com>
2024-12-03 11:46:10 +00:00
Zachary Harrold
c02696b609
Add Commands::run_schedule (#16537)
# Objective

- Fixes #16495

## Solution

- Added `Commands::run_schedule`, which internally calls
`World::try_run_schedule`, logging any issues.

## Testing

- Added doctest
- Ran CI

## Showcase

Instead of writing:

```rust
commands.queue(|world: &mut World| world.run_schedule(FooSchedule));
```

You can now write:

```rust
commands.run_schedule(FooSchedule);
```
2024-12-02 22:16:58 +00:00
ickshonpe
56d5591028
Multiple box shadow support (#16502)
# Objective

Add support for multiple box shadows on a single `Node`.

## Solution

* Rename `BoxShadow` to `ShadowStyle` and remove its `Component` derive.
* Create a new `BoxShadow` component that newtypes a `Vec<ShadowStyle>`.
* Add a `new` constructor method to `BoxShadow` for single shadows.
* Change `extract_shadows` to iterate through a list of shadows per
node.

Render order is determined implicitly from the order of the shadows
stored in the `BoxShadow` component, back-to-front.
Might be more efficient to use a `SmallVec<[ShadowStyle; 1]>` for the
list of shadows but not sure if the extra friction is worth it.

## Testing

Added a node with four differently coloured shadows to the `box_shadow`
example.

---

## Showcase

```
cargo run --example box_shadow
```

<img width="460" alt="four-shadow"
src="https://github.com/user-attachments/assets/2f728c47-33b4-42e1-96ba-28a774b94b24">

## Migration Guide

Bevy UI now supports multiple shadows per node. A new struct
`ShadowStyle` is used to set the style for each shadow. And the
`BoxShadow` component is changed to a tuple struct wrapping a vector
containing a list of `ShadowStyle`s. To spawn a node with a single
shadow you can use the `new` constructor function:
```rust
commands.spawn((
    Node::default(),
    BoxShadow::new(
        Color::BLACK.with_alpha(0.8),
        Val::Percent(offset.x),
        Val::Percent(offset.y),
        Val::Percent(spread),
        Val::Px(blur),
    )
));
```

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-12-01 21:30:08 +00:00
Sou1gh0st
206f4f7f5f
Add .contains_aabb for Frustum (#16022)
# Objective

- Fixes: #15663

## Solution

- Add an `is_forward_plane` method to `Aabb`, and a `contains_aabb`
method to `Frustum`.

## Test
- I have created a frustum with an offset along with three unit tests to
evaluate the `contains_aabb` algorithm.

## Explanation for the Test Cases
- To facilitate the code review, I will explain how the frustum is
created. Initially, we create a frustum without any offset and then
create a cuboid that is just contained within it.

<img width="714" alt="image"
src="https://github.com/user-attachments/assets/a9ac53a2-f8a3-4e09-b20b-4ee71b27a099">

- Secondly, we move the cuboid by 2 units along both the x-axis and the
y-axis to make it more general.


## Reference
- [Frustum
Culling](https://learnopengl.com/Guest-Articles/2021/Scene/Frustum-Culling#)
- [AABB Plane
intersection](https://gdbooks.gitbooks.io/3dcollisions/content/Chapter2/static_aabb_plane.html)

---------

Co-authored-by: IQuick 143 <IQuick143cz@gmail.com>
2024-12-01 21:30:01 +00:00
François Mockers
fcfb685821
enable_state_scoped_entities() as a derive attribute (#16180)
# Objective

- I got tired of calling `enable_state_scoped_entities`, and though it
would make more sense to define that at the place where the state is
defined

## Solution

- add a derive attribute `#[states(scoped_entities)]` when derive
`States` or `SubStates` that enables it automatically when adding the
state

## Testing

- Ran the examples using it, they still work
2024-12-01 20:09:36 +00:00
vil'mo
2a1064ec5e
Getting QueryState from immutable World reference (#16434)
# Objective

There is currently no way of getting `QueryState` from `&World`, so it
is hard to, for example, iterate over all entities with a component,
only having `&World`.

## Solution

Add `try_new` function to `QueryState` that internally uses
`WorldQuery`'s `get_state`.

## Testing

No testing
2024-12-01 20:09:29 +00:00
Christian Hughes
6fe4b1440c
Refactor FunctionSystem to use a single Option (#16514)
# Objective

Combine the `Option<_>` state in `FunctionSystem` into a single `Option`
to provide clarity and save space.

## Solution

Simplifies `FunctionSystem`'s layout by using a single
`Option<FunctionSystemState>` for state that must be initialized before
running, and saves a byte by removing the need to store an enum tag.
Additionally, calling `System::run` on an uninitialized `System` will
now give a more descriptive message prior to verifying the `WorldId`.

## Testing

Ran CI checks locally.
2024-12-01 20:09:22 +00:00
Arnav Mummineni
39842170a5
Update example link (#16581)
# Objective

Redirects broken example link to point to the most similar alternative
2024-12-01 09:47:22 +00:00
Rob Parrett
c425c32064
Fix a couple typos (#16573)
# Objective

Fix typo reported on
[discord](https://discord.com/channels/691052431525675048/743559241461399582/1312485153284558932).

## Solution

- Search for "will can."
- Fix typo
- Fix another related typo
2024-11-30 19:28:53 +00:00
Vic
eaa7dfedea
fix QueryIter::sort_unstable_by (#16565)
# Objective

`QueryIter::sort_unstable_by` is mistakenly using `slice::sort_by`.

## Solution

Use `slice::sort_unstable_by`.
2024-11-30 15:24:35 +00:00
Matty Weatherley
83b725f41e
Make bevy_gltf compile without bevy_animation feature (#16551)
# Objective

See title.

## Solution

Move `bevy_animation` import to where it is used.

## Testing

Compiled with and without `bevy_animation` feature enabled.
2024-11-30 00:04:30 +00:00
François Mockers
c1d392a5c6
Reduce iOS cpu usage (#16548)
# Objective

- Avoid recreating the monitor every loop (temp fix until it's done
properly on winit side)
- Add a new `WinitSettings` preset for mobile that makes the winit loop
wait more and recommend its usage
2024-11-29 00:34:40 +00:00
Alice Cecile
75c92fb47b
Clarify inheritance behavior of required components (#16546)
Co-authored by: @BenjaminBrienen

# Objective

Fixes #16494. Closes #16539, which this replaces. Suggestions alone
weren't enough, so now we have a new PR!

---------

Co-authored-by: Joona Aalto <jondolf.dev@gmail.com>
2024-11-28 21:09:26 +00:00
UkoeHB
696c00641f
Improve ZIndex docs (#16536)
# Objective

- In 0.14, ZIndex and GlobalZIndex where split from a shared enum into
separate components. There have been a few people confused by the
behavior of ZIndex when they really needed GlobalZIndex.

## Solution

- Update ZIndex docs to improve discoverability of GlobalZIndex.

---------

Co-authored-by: Benjamin Brienen <benjamin.brienen@outlook.com>
2024-11-28 17:31:03 +00:00
Alice Cecile
0438f78c94
Fix newline in AnimationEvaluationState docs (#16542)
# Objective

CI [is
broken](https://github.com/bevyengine/bevy/actions/runs/12070933255/job/33661528875)
by the new Rust version.

## Solution

Appease the crab gods by fixing our doc comments.

## Testing

CI has my back!
2024-11-28 17:13:21 +00:00
Kristoffer Søholm
3d72e08f32
Fix CAS toggle broken by retained render world (#16533)
# Objective

Fixes #16531

I also added change detection when creating the pipeline, which
technically isn't needed but it felt weird leaving it as is.

## Solution

Remove the pipeline if CAS is disabled. The uniform was already being
removed, which caused flickering / weirdness.

## Testing

Tested the anti_alias example by toggling CAS a bunch on/off.
2024-11-27 23:38:09 +00:00
Carter Anderson
af10aa38aa
AnimatedField and Rework Evaluators (#16484)
# Objective

Animating component fields requires too much boilerplate at the moment:

```rust
#[derive(Reflect)]
struct FontSizeProperty;

impl AnimatableProperty for FontSizeProperty {
    type Component = TextFont;

    type Property = f32;

    fn get_mut(component: &mut Self::Component) -> Option<&mut Self::Property> {
        Some(&mut component.font_size)
    }
}

animation_clip.add_curve_to_target(
    animation_target_id,
    AnimatableKeyframeCurve::new(
        [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
            .into_iter()
            .zip([24.0, 80.0, 24.0, 80.0, 24.0, 80.0, 24.0]),
    )
    .map(AnimatableCurve::<FontSizeProperty, _>::from_curve)
    .expect("should be able to build translation curve because we pass in valid samples"),
);
```

## Solution

This adds `AnimatedField` and an `animated_field!` macro, enabling the
following:

```rust
animation_clip.add_curve_to_target(
    animation_target_id,
    AnimatableCurve::new(
        animated_field!(TextFont::font_size),
        AnimatableKeyframeCurve::new(
            [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
                .into_iter()
                .zip([24.0, 80.0, 24.0, 80.0, 24.0, 80.0, 24.0]),
        )
        .expect(
            "should be able to build translation curve because we pass in valid samples",
        ),
    ),
);
```

This required reworking the internals a bit, namely stripping out a lot
of the `Reflect` usage, as that implementation was fundamentally
incompatible with the `AnimatedField` pattern. `Reflect` was being used
in this context just to downcast traits. But we can get downcasting
behavior without the `Reflect` requirement by implementing `Downcast`
for `AnimationCurveEvaluator`.

This also reworks "evaluator identity" to support either a (Component /
Field) pair, or a TypeId. This allows properties to reuse evaluators,
even if they have different accessor methods. The "contract" here is
that for a given (Component / Field) pair, the accessor will return the
same value. Fields are identified by their Reflect-ed field index. The
(TypeId, usize) is prehashed and cached to optimize for lookup speed.

This removes the built-in hard-coded TranslationCurve / RotationCurve /
ScaleCurve in favor of AnimatableField.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-11-27 22:19:55 +00:00
Carter Anderson
a6e13977d5
Fix CAS shader alpha accessor (#16530)
# Objective

Fixes #16528 

## Solution

Use `a` to access alpha instead of `w`
2024-11-27 21:51:29 +00:00
MichiRecRoom
2a66bf0909
Clarify that bevy_app::App.world() (and mut variant) returns the main SubApp's World (#16527)
# Objective
The documentation for `bevy_app::App.world()` (and its mut variant)
could confuse some into thinking that this is the only World that the
App will contain.

## Solution
Clarify the documentation for `bevy_app::App.world()` (and its mut
variant), to say that it returns the main subapp's world. This helps
imply that Apps can contain more than one world (albeit, only one per
SubApp).

## Testing
This is a documentation change, with no changes to doctests. Thus,
testing is not necessary beyond ensuring the link syntax is correct.
2024-11-27 16:09:09 +00:00
Carter Anderson
0a8e2a3c9d
Skip empty spans when updating text buffers (#16524)
# Objective

Fixes #16521

## Solution

If an empty span is encountered (such as the default `Text` value), we
skip it entirely when updating buffers. This prevents unnecessarily
bailing when the font doesn't exist (ex: when the default font is
disabled)
2024-11-27 03:28:43 +00:00
Carter Anderson
6659f37df1
Revert "Update sysinfo version to 0.32.1 (#16517)" (#16523)
This reverts commit 3476a9f3a658fe7c8326ca0e618ad543914ca7f4.

# Objective

#16517 makes it impossible to select a libc version, now that the
"breaking" libc release was yanked

## Solution

Revert the version bump so we can select a version of sysinfo that
builds (the previous version)
2024-11-26 22:44:23 +00:00
François Mockers
98d433a174
use scale factor for touches in UI focus (#16522)
# Objective

- Fix the issue mentioned on iOS in
https://github.com/bevyengine/bevy/issues/16363#issuecomment-2499766031
- touch on the button in the mobile example are not detected

## Solution

- UI focus now uses the window scale factor for touches
2024-11-26 21:23:12 +00:00
Guillaume Gomez
6ce566cb07
Update sysinfo version to 0.32.1 (#16517)
Fixes bug for new libc release.
2024-11-26 11:44:17 +00:00
François Mockers
ed8ac30836
use wgpu patch 23.0.1 (#16513)
# Objective

- Fixes #16363
- Ensure that someone using minimum version doesn't get the bugs that
were fixed in the 23.0.1 patch

## Solution

- Use wgpu 23.0.1
2024-11-25 22:47:31 +00:00
ickshonpe
efd2982a88
BorderRadius::percent fix (#16506)
# Objective

Fix the `BorderRadius::percent` function so that it sets percentage
values, not pixel.
2024-11-25 16:40:51 +00:00
Joona Aalto
da68bfe94b
Fix Single doc links (#16493)
# Objective

In the [*Similar parameters* section of
`Query`](https://dev-docs.bevyengine.org/bevy/ecs/prelude/struct.Query.html#similar-parameters),
the doc link for `Single` actually links to `Query::single`, and
`Option<Single>` just links to `Option`. They should both link to
`Single`!

The first link is broken because there is a reference-style link defined
for `single`, but not for `Single`, and rustdoc treats the link as
case-insensitive for some reason.

## Solution

Fix the links!

## Testing

I built the docs locally with `cargo doc` and tested the links.
2024-11-24 18:44:00 +00:00
atlv
636e99c9fb
cleanup bevy_render/lib.rs (#16481)
# Objective

- Refactor

## Solution

- Refactor

## Testing

- Ran 3d_scene

---

## Migration Guide

`RenderCreation::Manual` variant fields are now wrapped in a struct
called `RenderResources`
2024-11-22 22:32:04 +00:00
Rich Churcher
28efc1401a
and -> an (#16483)
Fix stray character in docs.
2024-11-22 22:16:26 +00:00
Rob Parrett
35de45277c
Use default storage for TemporaryRenderEntity (#16462)
# Objective

`TemporaryRenderEntity` currently uses `SparseSet` storage, but doesn't
seem to fit the criteria for a component that would benefit from this.

Typical usage of `TemporaryRenderEntity` (and all current usages of it
in engine as far as I can tell) would be to spawn an entity with it once
and then iterate over it once to despawn that entity.

`SparseSet` is said to be useful for insert/removal perf at the cost of
iteration perf.

## Solution

Use the default table storage

## Testing

Possibly this could show up in stress tests like `many_buttons`. I
didn't do any benchmarking.
2024-11-22 21:01:53 +00:00
DAA
7ff47a111f
feat: mark some functions in bevy_math as const (#16439)
# Objective

Mark simple functions as const in `bevy_math`
https://github.com/bevyengine/bevy/issues/16124

## Solution

- Make them const

## Testing

`cargo test -p bevy_math --all-features`
2024-11-22 18:26:47 +00:00
Marco Meijer
d82bbd8370
fix: setting content size to rect size if image has a rect (#16457)
# Objective

When using a rect for a ui image, its content size is still equal to the
size of the full image instead of the size of the rect.

## Solution

Use the rect size if it is present.

## Testing

I tested it using all 4 possible combinations of having a rect and
texture atlas or not. See the showcase section.

---

## Showcase

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

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

fn main() {
    App::new()
        .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest()))
        .add_systems(Startup, create_ui)
        .run();
}

fn create_ui(
    mut commands: Commands,
    assets: Res<AssetServer>,
    mut texture_atlas_layouts: ResMut<Assets<TextureAtlasLayout>>,
    mut ui_scale: ResMut<UiScale>,
) {
    let texture = assets.load("textures/fantasy_ui_borders/numbered_slices.png");
    let layout = TextureAtlasLayout::from_grid(UVec2::splat(16), 3, 3, None, None);
    let texture_atlas_layout = texture_atlas_layouts.add(layout);

    ui_scale.0 = 2.;

    commands.spawn(Camera2d::default());

    commands
        .spawn(Node {
            display: Display::Flex,
            align_items: AlignItems::Center,
            ..default()
        })
        .with_children(|parent| {
            // nothing
            parent.spawn(ImageNode::new(texture.clone()));

            // with rect
            parent.spawn(ImageNode::new(texture.clone()).with_rect(Rect::new(0., 0., 16., 16.)));

            // with rect and texture atlas
            parent.spawn(
                ImageNode::from_atlas_image(
                    texture.clone(),
                    TextureAtlas {
                        layout: texture_atlas_layout.clone(),
                        index: 1,
                    },
                )
                .with_rect(Rect::new(0., 0., 8., 8.)),
            );

            // with texture atlas
            parent.spawn(ImageNode::from_atlas_image(
                texture.clone(),
                TextureAtlas {
                    layout: texture_atlas_layout.clone(),
                    index: 2,
                },
            ));
        });
}
```

Before this change:
<img width="529" alt="Screenshot 2024-11-21 at 11 55 45"
src="https://github.com/user-attachments/assets/23196003-08ca-4049-8409-fe349bd5aa54">

After the change:
<img width="400" alt="Screenshot 2024-11-21 at 11 54 54"
src="https://github.com/user-attachments/assets/e2cd6ebf-859c-40a1-9fc4-43bb28b024e5">


</details>
2024-11-22 18:21:45 +00:00
Rob Parrett
984ff9ba88
Make render world sync marker components Copy (#16461)
# Objective

Original motivation was a bundle I am migrating that is `Copy` which
needs to be synced to the render world. It probably doesn't actually
*need* to be `Copy`, so this isn't critical or anything.

I am continuing to use this bundle while bundles still exist to give
users an easier migration path.

## Solution

These ZSTs might as well be `Copy`. Add `Copy` derives.
2024-11-22 18:18:59 +00:00
Patrick Walton
d80b809ea1
Only use the AABB center for mesh visibility range testing if specified. (#16468)
PR #15164 made Bevy consider the center of the mesh to be the center of
the axis-aligned bounding box (AABB). Unfortunately, this breaks
crossfading in many cases. LODs may have different AABBs and so the
center of the AABB may differ for different LODs of the same mesh. The
crossfading, however, relies on all LODs having *precisely* the same
position.

To address this problem, this PR adds a new field, `use_aabb`, to
`VisibilityRange`, which makes the AABB center point behavior opt-in.

@BenjaminBrienen first noticed this issue when reviewing PR #16286. That
PR contains a video showing the effects of this regression on the
`visibility_range` example. This commit fixes that example.

## Migration Guide

* The `VisibilityRange` component now has an extra field, `use_aabb`.
Generally, you can safely set it to false.
2024-11-22 18:18:20 +00:00
Patrick Walton
9fed566cf7
Refresh RenderVisibilityRanges when a visibility range is removed from the scene. (#16467)
We have an early-out to avoid updating `RenderVisibilityRanges` when a
`VisibilityRange` component is *modified*, but not when one is
*removed*. This means that removing `VisibilityRange` from an entity
might not update the rendering.

This PR fixes the issue by adding a check for removed
`VisibilityRange`s.
2024-11-22 18:17:17 +00:00
andriyDev
2fea36c1ad
Add flags to SpritePlugin and UiPlugin to allow disabling their picking backend (without needing to disable features). (#16473)
# Objective

- Fixes #16472.

## Solution

- Add flags to `SpritePlugin` and `UiPlugin` to disable their picking
backends.

## Testing

- The change is pretty trivial, so not much to test!

---

## Migration Guide

- `UiPlugin` now contains an extra `add_picking` field if
`bevy_ui_picking_backend` is enabled.
- `SpritePlugin` is no longer a unit struct, and has one field if
`bevy_sprite_picking_backend` is enabled (otherwise no fields).
2024-11-22 18:16:34 +00:00
andriyDev
2fbad7d845
Fix off-by-one error on Image::get_color_at and Image::set_color_at. (#16475)
# Objective

- Fixes #16474.

## Solution

- Check that the pixel x,y,z is less than width,height,depth.
    - Classic off-by-one.

## Testing

- Added a test.
2024-11-22 18:14:53 +00:00
andriyDev
b1e4512648
Fix the picking backend features not actually disabling the features (#16470)
# Objective

- Fixes #16469.

## Solution

- Make the picking backend features not enabled by default in each
sub-crate.
- Make features in `bevy_internal` to set the backend features
- Make the root `bevy` crate set the features by default.

## Testing

- The mesh and sprite picking examples still work correctly.
2024-11-22 18:14:16 +00:00
Patrick Walton
8bbc6b0139
Fix dynamic linking failures from the AnimationEventFn change. (#16476)
I'm not sure why, but somehow `#[derive(Reflect)]` on a tuple struct
with a boxed trait object can result in linker errors when dynamic
linking is used on Windows using `rust-lld`:

```
  = note: rust-lld: error: <root>: undefined symbol: bevy_animation::_::_$LT$impl$u20$bevy_reflect..reflect..PartialReflect$u20$for$u20$bevy_animation..AnimationEventFn$GT$::reflect_partial_eq::hc4cce1dc55e42e0b␍
          rust-lld: error: <root>: undefined symbol: bevy_animation::_::_$LT$impl$u20$bevy_reflect..from_reflect..FromReflect$u20$for$u20$bevy_animation..AnimationEventFn$GT$::from_reflect::hc2b1d575b8491092␍
          rust-lld: error: <root>: undefined symbol: bevy_animation::_::_$LT$impl$u20$bevy_reflect..tuple_struct..TupleStruct$u20$for$u20$bevy_animation..AnimationEventFn$GT$::clone_dynamic::hab42a4edc8d6b5c2␍
          rust-lld: error: <root>: undefined symbol: bevy_animation::_::_$LT$impl$u20$bevy_reflect..tuple_struct..TupleStruct$u20$for$u20$bevy_animation..AnimationEventFn$GT$::field::h729a3d6dd6a27a43␍
          rust-lld: error: <root>: undefined symbol: bevy_animation::_::_$LT$impl$u20$bevy_reflect..tuple_struct..TupleStruct$u20$for$u20$bevy_animation..AnimationEventFn$GT$::field_mut::hde1c34846d77344b␍
          rust-lld: error: <root>: undefined symbol: bevy_animation::_::_$LT$impl$u20$bevy_reflect..type_registry..GetTypeRegistration$u20$for$u20$bevy_animation..AnimationEventFn$GT$::get_type_registration::hb96eb543e403a132␍
          rust-lld: error: <root>: undefined symbol: bevy_animation::_::_$LT$impl$u20$bevy_reflect..type_registry..GetTypeRegistration$u20$for$u20$bevy_animation..AnimationEventFn$GT$::register_type_dependencies::hcf1a4b69bcfea6ae␍
          rust-lld: error: undefined symbol: bevy_animation::_::_$LT$impl$u20$bevy_reflect..reflect..PartialReflect$u20$for$u20$bevy_animation..AnimationEventFn$GT$::reflect_partial_eq::hc4cce1dc55e42e0b␍
```

etc.

Adding `#[reflect(opaque)]` to the `Reflect` derive fixes the problem,
and that's what this patch does. I think that adding
`#[reflect(opaque)]` is harmless, as there's little that reflection
allows with a boxed trait object anyhow.
2024-11-22 13:14:15 +00:00
andriyDev
6741e01dfa
Fix adding a subtree of required components to an existing tree replacing shallower required component constructors (#16441)
# Objective

- Fixes #16406 even more. The previous implementation did not take into
account the depth of the requiree when setting the depth relative to the
required_by component.

## Solution

- Add the depth of the requiree!

## Testing

- Added a test.

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2024-11-22 00:52:17 +00:00
ickshonpe
8a3a8b5cfb
Only use physical coords internally in bevy_ui (#16375)
# Objective

We switch back and forwards between logical and physical coordinates all
over the place. Systems have to query for cameras and the UiScale when
they shouldn't need to. It's confusing and fragile and new scale factor
bugs get found constantly.

## Solution

* Use physical coordinates whereever possible in `bevy_ui`. 
* Store physical coords in `ComputedNode` and tear out all the unneeded
scale factor calculations and queries.
* Add an `inverse_scale_factor` field to `ComputedNode` and set nodes
changed when their scale factor changes.

## Migration Guide

`ComputedNode`'s fields and methods now use physical coordinates.
`ComputedNode` has a new field `inverse_scale_factor`. Multiplying the
physical coordinates by the `inverse_scale_factor` will give the logical
values.

---------

Co-authored-by: atlv <email@atlasdostal.com>
2024-11-22 00:45:07 +00:00
Carter Anderson
513be52505
AnimationEvent -> Event and other improvements (#16440)
# Objective

Needing to derive `AnimationEvent` for `Event` is unnecessary, and the
trigger logic coupled to it feels like we're coupling "event producer"
logic with the event itself, which feels wrong. It also comes with a
bunch of complexity, which is again unnecessary. We can have the
flexibility of "custom animation event trigger logic" without this
coupling and complexity.

The current `animation_events` example is also needlessly complicated,
due to it needing to work around system ordering issues. The docs
describing it are also slightly wrong. We can make this all a non-issue
by solving the underlying ordering problem.

Related to this, we use the `bevy_animation::Animation` system set to
solve PostUpdate animation order-of-operations issues. If we move this
to bevy_app as part of our "core schedule", we can cut out needless
`bevy_animation` crate dependencies in these instances.

## Solution

- Remove `AnimationEvent`, the derive, and all other infrastructure
associated with it (such as the `bevy_animation/derive` crate)
- Replace all instances of `AnimationEvent` traits with `Event + Clone`
- Store and use functions for custom animation trigger logic (ex:
`clip.add_event_fn()`). For "normal" cases users dont need to think
about this and should use the simpler `clip.add_event()`
- Run the `Animation` system set _before_ updating text
- Move `bevy_animation::Animation` to `bevy_app::Animation`. Remove
unnecessary `bevy_animation` dependency from `bevy_ui`
- Adjust `animation_events` example to use the simpler `clip.add_event`
API, as the workarounds are no longer necessary

This is polishing work that will land in 0.15, and I think it is simple
enough and valuable enough to land in 0.15 with it, in the interest of
making the feature as compelling as possible.
2024-11-22 00:16:04 +00:00
Illus1on
a54d85bb2d
Correcting misspellings (#16443)
When I browsed the source code I found suspicious misspellings

# Objective

- Correcting misspelling

# Solution
- Change `doesnn't` to `doesn't`
2024-11-21 14:42:56 +00:00