Commit graph

5415 commits

Author SHA1 Message Date
Gino Valente
69541462c5
bevy_reflect: Add Reflectable trait (#5772)
# Objective

When deriving `Reflect`, users will notice that their generic arguments
also need to implement `Reflect`:

```rust
#[derive(Reflect)]
struct Foo<T: Reflect> {
  value: T
}
```

This works well for now. However, as we want to do more with `Reflect`,
these bounds might need to change. For example, to get #4154 working, we
likely need to enforce the `GetTypeRegistration` trait. So now we have:

```rust
#[derive(Reflect)]
struct Foo<T: Reflect + GetTypeRegistration> {
  value: T
}
```

Not great, but not horrible. However, we might then want to do something
as suggested in
[this](https://github.com/bevyengine/bevy/issues/5745#issuecomment-1221389131)
comment and add a `ReflectTypeName` trait for stable type name support.
Well now we have:

```rust
#[derive(Reflect)]
struct Foo<T: Reflect + GetTypeRegistration + ReflectTypeName> {
  value: T
}
```

Now imagine that for even two or three generic types. Yikes!

As the API changes it would be nice if users didn't need to manually
migrate their generic type bounds like this.

A lot of these traits are (or will/might be) core to the entire
reflection API. And although `Reflect` can't add them as supertraits for
object-safety reasons, they are still indirectly required for things to
function properly (manual implementors will know how easy it is to
forget to implement `GetTypeRegistration`). And they should all be
automatically implemented for user types anyways as long they're using
`#[derive(Reflect)]`.

## Solution

Add a "catch-all" trait called `Reflectable` whose supertraits are a
select handful of core reflection traits.

This allows us to consolidate all the examples above into this:

```rust
#[derive(Reflect)]
struct Foo<T: Reflectable> {
  value: T
}
```

And as we experiment with the API, users can rest easy knowing they
don't need to migrate dozens upon dozens of types. It should all be
automatic!

## Discussion

1. Thoughts on the name `Reflectable`? Is it too easily confused with
`Reflect`? Or does it at least accurately describe that this contains
the core traits? If not, maybe `BaseReflect`?

---

## Changelog

- Added the `Reflectable` trait

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-09-18 00:36:41 +00:00
JoshValjosh
8d78c37ce9
Use FloatOrd for sprite Z comparison and ignore sprites with NaN (#15267)
# Objective

Fixes #15258

## Solution

If my understanding is correct, sprites with NaN anywhere in their
transform won't even get onto the screen, so should not generate pick
events. This PR filters sprites with NaN in their transforms before
sorting by depth, then uses `FloatOrd` to simplify the comparison. Since
we're guaranteed to not have NaN values, it's technically unnecessary,
and we could instead sort with `a.partial_cmp(&b).unwrap()`, or even
`unwrap_unchecked()`.

## Testing

I ran the picking example to ensure Z sorting was working as intended.
2024-09-17 23:27:53 +00:00
Alice Cecile
e0d38a4a3b
Add basic docs explaining what asset processing is and where to look (#15058)
# Objective

Asset processing (added as part of #8624) is a powerful, high-impact
feature, but has been widely underused (and underdeveloped) due to poor
developer understanding.

## Solution

In this PR, I've documented what asset processing is, why it's useful,
and pointed users to the two primary entry points.

While I would like substantially more involved practical examples for
how to perform common asset-processing tasks, I've split them out from
this PR for ease of review (and actually submitting this for review
before the weekend).

We should add bread crumbs from the module docs to these docs, but
whether we add that here or in #15056 depends on which gets merged
first.

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2024-09-17 22:59:12 +00:00
Alice Cecile
23aca13609
Add module and supporting documentation to bevy_assets (#15056)
# Objective

Bevy's asset system is powerful and generally well-designed but very
opaque.

Beginners struggle to discover how to do simple tasks and grok the
fundamental data models, while more advanced users trip over the
assorted traits and their relation to each other.

Reverts #15054 ;)

## Solution

This PR adds module documentation to `bevy_assets`, tweaking the
associated documentation on the items as needed to provide further
details and bread crumbs.

If you have ideas for other important, hard-to-discover patterns or
functionality in this crate, please let me know.

That said, I've left out a section on asset preprocessing which *should*
eventually go here. That is substantially more uncertain, and requires
both more time to investigate and more expertise to review.

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
Co-authored-by: TrialDragon <31419708+TrialDragon@users.noreply.github.com>
Co-authored-by: NotAFile <notafile@gmail.com>
Co-authored-by: Zachary Harrold <zac@harrold.com.au>
Co-authored-by: JMS55 <47158642+JMS55@users.noreply.github.com>
Co-authored-by: Jan Hohenheim <jan@hohenheim.ch>
2024-09-17 22:07:37 +00:00
Wybe Westra
612731edfb
Add DynamicTyped link to TypeInfo docs (#15188) (#15259)
Also added a bit to the paragraph to explain when to use the new
function.
Fixes #15188.
2024-09-17 19:27:26 +00:00
Christian Hughes
378dcacf82
Group IntoSystemConfigs impls together (#15254)
# Objective

Two of the `IntoSystemConfigs` `impl`s are out of place near the top of
the file.

## Solution

Put them below the `IntoSystemConfigs` trait definition, alongside the
other `impl`.
2024-09-17 17:57:22 +00:00
no-materials
b884f96598
Implement enabled flag for fps overlay (#15246)
# Objective

Fixes #15223 

## Solution

Adds an `enabled` flag to the `FpsOverlayConfig` resource with a system
that detects it's change, and adjusts the visibility of the overlay text
entity.

## Testing

I extended the `fps_overlay` example with the option to toggle the
overlay. Run with:
```
cargo run --features="bevy_dev_tools" --example fps_overlay
```
2024-09-17 15:16:28 +00:00
Patrick Walton
3c41586154
Add EntityRefExcept and EntityMutExcept world queries, in preparation for generalized animation. (#15207)
This commit adds two new `WorldQuery` types: `EntityRefExcept` and
`EntityMutExcept`. These types work just like `EntityRef` and
`EntityMut`, but they prevent access to a statically-specified list of
components. For example, `EntityMutExcept<(AnimationPlayer,
Handle<AnimationGraph>)>` provides mutable access to all components
except for `AnimationPlayer` and `Handle<AnimationGraph>`. These types
are useful when you need to be able to process arbitrary queries while
iterating over the results of another `EntityMut` query.

The motivating use case is *generalized animation*, which is an upcoming
feature that allows animation of any component property, not just
rotation, translation, scaling, or morph weights. To implement this, we
must change the current `AnyOf<(&mut Transform, &mut MorphWeights)>` to
instead be `EntityMutExcept<(AnimationPlayer, Handle<AnimationGraph>)>`.
It's possible to use `FilteredEntityMut` in conjunction with a
dynamically-generated system instead, but `FilteredEntityMut` isn't
optimized for the use case of a large number of allowed components
coupled with a small set of disallowed components. No amount of
optimization of `FilteredEntityMut` produced acceptable performance on
the `many_foxes` benchmark. `Query<EntityMut, Without<AnimationPlayer>>`
will not suffice either, as it's legal and idiomatic for an
`AnimationTarget` and an `AnimationPlayer` to coexist on the same
entity.

An alternate proposal was to implement a somewhat-more-general
`Except<Q, CL>` feature, where Q is a `WorldQuery` and CL is a
`ComponentList`. I wasn't able to implement that proposal in a
reasonable way, because of the fact that methods like
`EntityMut::get_mut` and `EntityRef::get` are inherent methods instead
of methods on `WorldQuery`, and therefore there was no way to delegate
methods like `get` and `get_mut` to the inner query in a generic way.
Refactoring those methods into a trait would probably be possible.
However, I didn't see a use case for a hypothetical `Except` with
arbitrary queries: `Query<Except<(&Transform, &Visibility),
Visibility>>` would just be a complicated equivalent to
`Query<&Transform>`, for instance. So, out of a desire for simplicity, I
omitted a generic `Except` mechanism.

I've tested the performance of generalized animation on `many_foxes` and
found that, with this patch, `animate_targets` has a 7.4% slowdown over
`main`. With `FilteredEntityMut` optimized to use `Arc<Access>`, the
slowdown is 75.6%, due to contention on the reference count. Without
`Arc<Access>`, the slowdown is even worse, over 2x.

## Testing

New tests have been added that check that `EntityRefExcept` and
`EntityMutExcept` allow and disallow access to components properly and
that the query engine can correctly reject conflicting queries involving
those types.

A Tracy profile of `many_foxes` with 10,000 foxes showing generalized
animation using `FilteredEntityMut` (red) vs. main (yellow) is as
follows:

![Screenshot 2024-09-12
225914](https://github.com/user-attachments/assets/2993d74c-a513-4ba4-85bd-225672e7170a)

A Tracy profile of `many_foxes` with 10,000 foxes showing generalized
animation using this `EntityMutExcept` (yellow) vs. main (red) is as
follows:

![Screenshot 2024-09-14
205831](https://github.com/user-attachments/assets/4241015e-0c5d-44ef-835b-43f78a24e604)
2024-09-17 14:53:39 +00:00
Benjamin Brienen
b45d83ebda
Rename Add to Queue for methods with deferred semantics (#15234)
# Objective

- Fixes #15106

## Solution

- Trivial refactor to rename the method. The duplicate method `push` was
removed as well. This will simpify the API and make the semantics more
clear. `Add` implies that the action happens immediately, whereas in
reality, the command is queued to be run eventually.
- `ChildBuilder::add_command` has similarly been renamed to
`queue_command`.

## Testing

Unit tests should suffice for this simple refactor.

---

## Migration Guide

- `Commands::add` and `Commands::push` have been replaced with
`Commnads::queue`.
- `ChildBuilder::add_command` has been renamed to
`ChildBuilder::queue_command`.
2024-09-17 00:17:49 +00:00
Navneet Aman
c2d54f5f04
Don't leak SEND resource, even if thread is panicking. (#15247)
# Objective
Currently the resource doesn't get dropped if thread panics. This is
presumably to prevent !SEND resource from being dropped by wrong thread.
But, this logic is not needed for SEND resources. So we don't need this
check for SEND resource.

Fixes #15144 

## Solution

We check if resource is !SEND before, validating that correct thread is
dropping the resource.

## Testing

- Did you test these changes? If so, how?
I did run cargo test on bevy.
- Are there any parts that need more testing?
No
- How can other people (reviewers) test your changes? Is there anything
specific they need to know?
Nothing special
- If relevant, what platforms did you test these changes on, and are
there any important ones you can't test?
x86_64 desktop
2024-09-16 23:36:52 +00:00
dependabot[bot]
c3465a9676
Update gilrs requirement from 0.10.1 to 0.11.0 (#15245)
Updates the requirements on
[gilrs](https://gitlab.com/gilrs-project/gilrs) to permit the latest
version.
<details>
<summary>Commits</summary>
<ul>
<li><a
href="cbcff6a4cd"><code>cbcff6a</code></a>
Speed up CI by testing only on x86_64-pc-windows-msvc from Windows’
targets</li>
<li><a
href="78582dd9df"><code>78582dd</code></a>
Update deps and prepare for gilrs 0.11.0 and gilrs-core 0.6.0</li>
<li><a
href="aad5c1072d"><code>aad5c10</code></a>
Mark error enums, Event and EventType as non_exhaustive</li>
<li><a
href="ec5d668d6b"><code>ec5d668</code></a>
Fix potential overflow in btn_value()</li>
<li><a
href="59811ff850"><code>59811ff</code></a>
Prepare for gilrs-core 0.5.15 release</li>
<li><a
href="aeaeb747d7"><code>aeaeb74</code></a>
windows: Don’t panic on Reading::update() returning error</li>
<li><a
href="d26e37f121"><code>d26e37f</code></a>
windows: Remove event handlers on drop</li>
<li><a
href="daf263d3cc"><code>daf263d</code></a>
Prevent crash in WASM backend when browser assigns gamepad unexpected
ID</li>
<li><a
href="5f7b786f83"><code>5f7b786</code></a>
Upgrade SDL_GameControllerDB.</li>
<li><a
href="3d92b2e15a"><code>3d92b2e</code></a>
gilrs-core version 0.5.13</li>
<li>Additional commits viewable in <a
href="https://gitlab.com/gilrs-project/gilrs/compare/v0.10.1...v0.11.0">compare
view</a></li>
</ul>
</details>
<br />


Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-09-16 23:34:04 +00:00
Benjamin Brienen
29508f065f
Fix floating point math (#15239)
# Objective

- Fixes #15236

## Solution

- Use bevy_math::ops instead of std floating point operations.

## Testing

- Did you test these changes? If so, how?
Unit tests and `cargo run -p ci -- test`

- How can other people (reviewers) test your changes? Is there anything
specific they need to know?
Execute `cargo run -p ci -- test` on Windows.

- If relevant, what platforms did you test these changes on, and are
there any important ones you can't test?
Windows

## Migration Guide

- Not a breaking change
- Projects should use bevy math where applicable

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: IQuick 143 <IQuick143cz@gmail.com>
Co-authored-by: Joona Aalto <jondolf.dev@gmail.com>
2024-09-16 23:28:12 +00:00
Taylor Neal
23a77ca5eb
Rename push children to add children (#15196)
# Objective

- Makes naming between add_child and add_children more consistent
- Fixes #15101 

## Solution

renamed push_children to add_children

## Testing

- Did you test these changes? If so, how?
Ran tests + grep search for any instance of `push_child`

- Are there any parts that need more testing?

- How can other people (reviewers) test your changes? Is there anything
specific they need to know?

- If relevant, what platforms did you test these changes on, and are
there any important ones you can't test?
ran tests on WSL2

---

## Migration Guide

> This section is optional. If there are no breaking changes, you can
delete this section.

- If this PR is a breaking change (relative to the last release of
Bevy), describe how a user might need to migrate their code to support
these changes

rename any use of `push_children()` to the updated `add_children()`
2024-09-16 23:16:04 +00:00
patrickariel
3efef59d83
Enable/disable UI anti-aliasing (#15170)
# Objective

Currently, UI is always rendered with anti-aliasing. This makes bevy's
UI completely unsuitable for art-styles that demands hard pixelated
edges, such as retro-style games.

## Solution

Add a component for disabling anti-aliasing in UI.

## Testing

In
[`examples/ui/button.rs`](15e246eff8/examples/ui/button.rs),
add the component to the camera like this:

```rust
use bevy::{prelude::*, ui::prelude::*};

commands.spawn((Camera2dBundle::default(), UiAntiAlias::Off));
```

The rounded button will now render without anti-aliasing.

## Showcase

An example of a rounded UI node rendered without anti-aliasing, with and
without borders:


![image](https://github.com/user-attachments/assets/ea797e40-bdaa-4ede-a0d3-c9a7eab95b6e)
2024-09-16 23:06:23 +00:00
Robert Walter
29c4c79342
Rotation api extension (#15169)
# Objective

- Another way of specifying rotations was requested in
https://github.com/bevyengine/bevy/issues/11132#issuecomment-2344603178

## Solution

- Add methods on `Rot2`
  - `turn_fraction(fraction: f32) -> Self`
  - `as_turn_fraction(self) -> f32`
- Also add some documentation on range of rotation

## Testing

- extended existing tests
- added new tests

## Showcase 

```rust
let rotation1 = Rot2::degrees(90.0);
let rotation2 = Rot2::turn_fraction(0.25);

// rotations should be equal
assert_relative_eq!(rotation1, rotation2);

// The rotation should be 90 degrees
assert_relative_eq!(rotation2.as_radians(), FRAC_PI_2);
assert_relative_eq!(rotation2.as_degrees(), 90.0);

```

---------

Co-authored-by: Joona Aalto <jondolf.dev@gmail.com>
Co-authored-by: Jan Hohenheim <jan@hohenheim.ch>
2024-09-16 23:02:08 +00:00
Cole Varner
17b1bcde95
Add missing insert API commands (#15166)
# Objective

- Adds the missing API commands `insert_if_new_and` and
`try_insert_if_new_and` (resolves #15105)
- Adds some test coverage for existing insert commands

## Testing

- Implemented additional unit tests to add coverage
2024-09-16 23:00:00 +00:00
Chris Russell
382917fbb3
Improve type inference in DynSystemParam::downcast() by making the type parameter match the return value. (#15103)
# Objective

Right now, `DynSystemParam::downcast()` always requires the type
parameter to be specified with a turbofish. Make it so that it can be
inferred from the use of the return value, like:

```rust
fn expects_res_a(mut param: DynSystemParam) {
    let res: Res<A> = param.downcast().unwrap();
}
```

## Solution

The reason this doesn't currently work is that the type parameter is a
`'static` version of the `SystemParam` so that it can be used with
`Any::downcast_mut()`. Change the method signature so that the type
parameter matches the return type, and use `T::Item<'static, 'static>`
to get the `'static` version. That means we wind up returning a
`T::Item<'static, 'static>::Item<'w, 's>`, so constrain that to be equal
to `T`. That works with every `SystemParam` implementation, since they
have `T::Item == T` up to lifetimes.
2024-09-16 22:56:57 +00:00
Eero Lehtinen
db525e660e
Fix MeshAllocator panic (#14560)
# Objective

 Fixes #14540

## Solution

- Clean slab layouts from stale `SlabId`s when freeing meshes
- Technically performance requirements of freeing now increase based on
the number of existing meshes, but maybe it doesn't matter too much in
practice
- This was the case before this PR too, but it's technically possible to
free and allocate 2^32 times and overflow with `SlabId`s and cause
incorrect behavior. It looks like new meshes would then override old
ones.

## Testing

- Tested in `loading_screen` example and tapping keyboard 1 and 2.
2024-09-16 22:54:01 +00:00
Adam
9bda913e36
Remove redundent information and optimize dynamic allocations in Table (#12929)
# Objective

- fix #12853
- Make `Table::allocate` faster

## Solution
The PR consists of multiple steps:

1) For the component data: create a new data-structure that's similar to
`BlobVec` but doesn't store `len` & `capacity` inside of it: "BlobArray"
(name suggestions welcome)
2) For the `Tick` data: create a new data-structure that's similar to
`ThinSlicePtr` but supports dynamic reallocation: "ThinArrayPtr" (name
suggestions welcome)
3) Create a new data-structure that's very similar to `Column` that
doesn't store `len` & `capacity` inside of it: "ThinColumn"
4) Adjust the `Table` implementation to use `ThinColumn` instead of
`Column`

The result is that only one set of `len` & `capacity` is stored in
`Table`, in `Table::entities`

### Notes Regarding Performance
Apart from shaving off some excess memory in `Table`, the changes have
also brought noteworthy performance improvements:
The previous implementation relied on `Vec::reserve` &
`BlobVec::reserve`, but that redundantly repeated the same if statement
(`capacity` == `len`). Now that check could be made at the `Table` level
because the capacity and length of all the columns are synchronized;
saving N branches per allocation. The result is a respectable
performance improvement per every `Table::reserve` (and subsequently
`Table::allocate`) call.

I'm hesitant to give exact numbers because I don't have a lot of
experience in profiling and benchmarking, but these are the results I
got so far:

*`add_remove_big/table` benchmark after the implementation:*


![after_add_remove_big_table](https://github.com/bevyengine/bevy/assets/46227443/b667da29-1212-4020-8bb0-ec0f15bb5f8a)

*`add_remove_big/table` benchmark in main branch (measured in comparison
to the implementation):*


![main_add_remove_big_table](https://github.com/bevyengine/bevy/assets/46227443/41abb92f-3112-4e01-b935-99696eb2fe58)

*`add_remove_very_big/table` benchmark after the implementation:*


![after_add_remove_very_big](https://github.com/bevyengine/bevy/assets/46227443/f268a155-295b-4f55-ab02-f8a9dcc64fc2)

*`add_remove_very_big/table` benchmark in main branch (measured in
comparison to the implementation):*


![main_add_remove_very_big](https://github.com/bevyengine/bevy/assets/46227443/78b4e3a6-b255-47c9-baee-1a24c25b9aea)

cc @james7132 to verify

---

## Changelog

- New data-structure that's similar to `BlobVec` but doesn't store `len`
& `capacity` inside of it: `BlobArray`
- New data-structure that's similar to `ThinSlicePtr` but supports
dynamic allocation:`ThinArrayPtr`
- New data-structure that's very similar to `Column` that doesn't store
`len` & `capacity` inside of it: `ThinColumn`
- Adjust the `Table` implementation to use `ThinColumn` instead of
`Column`
- New benchmark: `add_remove_very_big` to benchmark the performance of
spawning a lot of entities with a lot of components (15) each

## Migration Guide

`Table` now uses `ThinColumn` instead of `Column`. That means that
methods that previously returned `Column`, will now return `ThinColumn`
instead.

`ThinColumn` has a much more limited and low-level API, but you can
still achieve the same things in `ThinColumn` as you did in `Column`.
For example, instead of calling `Column::get_added_tick`, you'd call
`ThinColumn::get_added_ticks_slice` and index it to get the specific
added tick.

---------

Co-authored-by: James Liu <contact@jamessliu.com>
2024-09-16 22:52:05 +00:00
Federico Rinaldi
262b068bc3
Substitute trivial fallible conversions with infallible function calls (#10846)
Clippy for rust 1.75 will introduce the
[`unnecessary_fallible_conversions`][1] lint. This PR solves the trivial
ones.

[1]:
https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_fallible_conversions
2024-09-16 22:46:54 +00:00
Blazepaws
5a0c09d38f
Reflect derived traits on all components and resources: bevy_transform (#15230)
Fixes https://github.com/bevyengine/bevy/issues/15187 for bevy_transform
2024-09-15 18:19:44 +00:00
Blazepaws
cb6ab16c97
Reflect derived traits on all components and resources: bevy_ui (#15231)
Solves https://github.com/bevyengine/bevy/issues/15187 for bevy_ui
2024-09-15 17:52:38 +00:00
Blazepaws
4d65757b3e
Reflect derived traits on all components and resources: bevy_window (#15233)
Solves https://github.com/bevyengine/bevy/issues/15187 for bevy_window.
This is the last one.
2024-09-15 17:49:00 +00:00
Blazepaws
1c2e1fc15a
Reflect derived traits on all components and resources: bevy_text (#15229)
Solves https://github.com/bevyengine/bevy/issues/15187 for bevy_text
2024-09-15 17:21:02 +00:00
Blazepaws
b38cc9e7b0
Reflect derived traits on all components and resources: bevy_state (#15228)
Solves https://github.com/bevyengine/bevy/issues/15187 for bevy_state
2024-09-15 17:16:45 +00:00
Blazepaws
07e79f3e9f
Reflect derived traits on all components and resources: bevy_sprite (#15227)
Solves https://github.com/bevyengine/bevy/issues/15187 for bevy_sprite
2024-09-15 17:10:53 +00:00
Blazepaws
274c97d415
Reflect derived traits on all components and resources: bevy_render (#15226)
Addresses https://github.com/bevyengine/bevy/issues/15187 for
bevy_render
2024-09-15 17:05:11 +00:00
Blazepaws
0c92908baf
Reflect derived traits on all components and resources: bevy_picking (#15225)
Solves https://github.com/bevyengine/bevy/issues/15187 for bevy_picking
2024-09-15 16:17:39 +00:00
Blazepaws
b6b28a621f
Reflect derived traits on all components and resources: bevy_pbr (#15224)
Solves https://github.com/bevyengine/bevy/issues/15187 for bevy_pbr
2024-09-15 16:07:30 +00:00
poopy
d878e2f8bd
add allow_all and deny_all methods to DynamicSceneBuilder (#15222)
# Objective

It would be convenient to be able to quickly deny or allow all
components and resources on a `DynamicSceneBuilder` with a single method
call.

Context: #15210 renamed `{allow/deny}_all` to
`{allow/deny}_all_components`.

## Solution

Added two new methods to `DynamicSceneBuilder`, `allow_all` and
`deny_all`, which affect both the component and resource filters.


## Showcase

### Before

```rust
let builder = DynamicSceneBuilder::from_world(world)
    .deny_all_components()
    .deny_all_resources();
```

### After

```rust
let builder = DynamicSceneBuilder::from_world(world).deny_all();
```
2024-09-15 15:30:53 +00:00
Blazepaws
228ce8170a
Use of deprecated function in example for ButtonInput (#15221)
The function `bevy_input::schedule::condition::Condition::or_else` has
been deprecated in favor of
`bevy_input::schedule::condition::Condition::or`. However the docs for
`ButtonInput` were still using the deprecated function in their example.
2024-09-15 15:22:39 +00:00
Blazepaws
62b2cdab32
Reflect derived traits on all components and resources: bevy_hierarchy (#15219)
Solves https://github.com/bevyengine/bevy/issues/15187 for
bevy_hierarchy
2024-09-15 15:09:28 +00:00
Blazepaws
e718bbd55c
Reflect derived traits on all components and resources: bevy_input (#15220)
Solves https://github.com/bevyengine/bevy/issues/15187 for bevy_input
2024-09-15 15:08:46 +00:00
Blazepaws
569f68f8a0
Reflect derived traits on all components and resources: bevy_gltf (#15218)
Solves https://github.com/bevyengine/bevy/issues/15187 for bevy_gltf
2024-09-15 14:47:43 +00:00
Blazepaws
379696a468
Reflect derived traits on all components and resources: bevy_gizmos (#15217)
Solves https://github.com/bevyengine/bevy/issues/15187 for bevy_gizmos
2024-09-15 14:41:49 +00:00
poopy
2ea8d35900
explicitly mention component in methods on DynamicSceneBuilder (#15210)
# Objective

The method names on `DynamicSceneBuilder` are misleading. Specifically,
`deny_all` and `allow_all` implies everything will be denied/allowed,
including all components and resources. In reality, these methods only
apply to components (which is mentioned in the docs).

## Solution

- change `deny_all` and `allow_all` to `deny_all_components` and
`allow_all_components`
- also, change the remaining methods to mention component where it makes
sense

We could also add the `deny_all` and `allow_all` methods back later,
only this time, they would deny/allow both resources and components.

## Showcase

### Before
```rust
let builder = DynamicSceneBuilder::from_world(world)
    .deny_all()
    .deny_all_resources()
    .allow::<MyComponent>();
```

### After
```rust
let builder = DynamicSceneBuilder::from_world(world)
    .deny_all_components()
    .deny_all_resources()
    .allow_component::<MyComponent>();
```

## Migration Guide

the following invocations on `DynamicSceneBuilder` should be changed by
users
- `with_filter` -> `with_component_filter`
- `allow` -> `allow_component`
- `deny` -> `deny_component`
- `allow_all` -> `allow_all_components`
- `deny_all` -> `deny_all_components`
2024-09-15 14:37:32 +00:00
Al M.
2ea51fc60f
Use FromReflect when extracting entities in dynamic scenes (#15174)
# Objective

Fix #10284.

## Solution

When `DynamicSceneBuilder` extracts entities, they are cloned via
`PartialReflect::clone_value`, making them into dynamic versions of the
original components. This loses any custom `ReflectSerialize` type data.
Dynamic scenes are deserialized with the original types, not the dynamic
versions, and so any component with a custom serialize may fail. In this
case `Rect` and `Vec2`. The dynamic version includes the field names 'x'
and 'y' but the `Serialize` impl doesn't, hence the "expect float"
error.

The solution here: Instead of using `clone_value` to clone the
components, `FromReflect` clones and retains the original information
needed to serialize with any custom `Serialize` impls. I think using
something like `reflect_clone` from
(https://github.com/bevyengine/bevy/pull/13432) might make this more
efficient.

I also did the same when deserializing dynamic scenes to appease some of
the round-trip tests which use `ReflectPartialEq`, which requires the
types be the same and not a unique/proxy pair. I'm not sure it's
otherwise necessary. Maybe this would also be more efficient when
spawning dynamic scenes with `reflect_clone` instead of `FromReflect`
again?

An alternative solution would be to fall back to the dynamic version
when deserializing `DynamicScene`s if the custom version fails. I think
that's possible. Or maybe simply always deserializing via the dynamic
route for dynamic scenes?

## Testing

This example is similar to the original test case in #10284:

``` rust
#![allow(missing_docs)]

use bevy::{prelude::*, scene::SceneInstanceReady};

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, (save, load).chain())
        .observe(check)
        .run();
}

static SAVEGAME_SAVE_PATH: &str = "savegame.scn.ron";

fn save(world: &mut World) {
    let entity = world.spawn(OrthographicProjection::default()).id();

    let scene = DynamicSceneBuilder::from_world(world)
        .extract_entity(entity)
        .build();

    if let Some(registry) = world.get_resource::<AppTypeRegistry>() {
        let registry = registry.read();
        let serialized_scene = scene.serialize(&registry).unwrap();
        // println!("{}", serialized_scene);
        std::fs::write(format!("assets/{SAVEGAME_SAVE_PATH}"), serialized_scene).unwrap();
    }

    world.entity_mut(entity).despawn_recursive();
}

fn load(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.spawn(DynamicSceneBundle {
        scene: asset_server.load(SAVEGAME_SAVE_PATH),
        ..default()
    });
}

fn check(_trigger: Trigger<SceneInstanceReady>, query: Query<&OrthographicProjection>) {
    dbg!(query.single());
}
```


## Migration Guide

The `DynamicScene` format is changed to use custom serialize impls so
old scene files will need updating:

Old: 

```ron
(
  resources: {},
  entities: {
    4294967299: (
      components: {
        "bevy_render:📷:projection::OrthographicProjection": (
          near: 0.0,
          far: 1000.0,
          viewport_origin: (
            x: 0.5,
            y: 0.5,
          ),
          scaling_mode: WindowSize(1.0),
          scale: 1.0,
          area: (
            min: (
              x: -1.0,
              y: -1.0,
            ),
            max: (
              x: 1.0,
              y: 1.0,
            ),
          ),
        ),
      },
    ),
  },
)
```

New:

```ron
(
  resources: {},
  entities: {
    4294967299: (
      components: {
        "bevy_render:📷:projection::OrthographicProjection": (
          near: 0.0,
          far: 1000.0,
          viewport_origin: (0.5, 0.5),
          scaling_mode: WindowSize(1.0),
          scale: 1.0,
          area: (
            min: (-1.0, -1.0),
            max: (1.0, 1.0),
          ),
        ),
      },
    ),
  },
)
```

---------

Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
2024-09-15 14:33:39 +00:00
Blazepaws
21e39360f7
Example for bevy_ecs::event::Events uses deprecated function get_reader (#15216)
Fixes https://github.com/bevyengine/bevy/issues/15214
2024-09-15 14:24:04 +00:00
Blazepaws
abac8c7b0f
Reflect derived traits on all components and resources: bevy_audio (#15211)
Solves https://github.com/bevyengine/bevy/issues/15187 for bevy_audio
2024-09-15 14:24:00 +00:00
Blazepaws
53d2bc9482
Reflect derived traits on all components and resources: bevy_ecs (#15215)
Solves https://github.com/bevyengine/bevy/issues/15187 for bevy_ecs
2024-09-15 14:23:54 +00:00
Blazepaws
df8cb3e5e2
Reflect derived traits on all components and resources: bevy_core_pipeline (#15213)
Solves https://github.com/bevyengine/bevy/issues/15187 for
bevy_core_pipeline
2024-09-15 14:23:41 +00:00
Blazepaws
c909a0572d
Reflect derived traits on all components and resources: bevy_animation (#15209)
Solves https://github.com/bevyengine/bevy/issues/15187 for the
bevy_animation subcrate
2024-09-15 11:58:51 +00:00
kivi
3f425da66e
Improve schedule note of .after/.before & encourage to use .chain ins… (#14986)
# Objective

- Fixes #14552 
- Make the current note of `before` and `after` understandable. 
- > The given set is not implicitly added to the schedule when this
system set is added.

## Solution

- Replace note in docs of [`after` and
`before`](https://docs.rs/bevy/latest/bevy/ecs/prelude/trait.IntoSystemConfigs.html#method.before)
- Note of after was removed completely, and links to `before`, because
they notes would be identical.
- Also encourage to use `.chain`, which is much simpler and safer to use

## Testing

- Checked the docs after running `cargo doc` and `cargo run -p ci --
lints`
- Are there any parts that need more testing?
- no need to test, but please review the text. If it is still including
the intended message and especially if its understandable.

---------

Co-authored-by: Jan Hohenheim <jan@hohenheim.ch>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-09-14 21:03:21 +00:00
Wybe Westra
70808af776
Added ordering information to observer tests (#14332) (#15178)
Fixes #14332 by recording the order in which the events occur.
2024-09-14 14:08:49 +00:00
Joona Aalto
b36443b6ed
Fix Capsule2d::sample_interior (#15191)
# Objective

`Capsule2d::sample_interior` uses the radius of the capsule for the
width of its rectangular section. It should be using two times the
radius for the full width!

I noticed this as I was getting incorrect results for angular inertia
approximated from a point cloud of points sampled on the capsule. This
hinted that something was wrong with the sampling.

## Solution

Multiply the radius by two to get the full width of the rectangular
section. With this, the sampling produces the correct result in my
tests.
2024-09-14 02:24:08 +00:00
Blazepaws
583e034796
Reflected traits for resources and components: bevy_a11y (#15192)
Solves https://github.com/bevyengine/bevy/issues/15187 for the bevy_a11y
subcrate.
2024-09-14 01:43:16 +00:00
Cole Varner
cf55e6cb22
ParsedPath::try_from<&str> (#15180)
# Objective

- implements ParsedPath::try_from<&str>
- resolves #14438

## Testing

- Added unit test for ParsedPath::try_from<&str>

Note: I don't claim to be an expert on lifetimes! That said I think it
makes sense that the error shares a lifetime with input string as deeper
down it is used to construct it.
2024-09-13 17:37:09 +00:00
Gino Valente
37443e0f3f
bevy_reflect: Add DynamicTyped trait (#15108)
# Objective

Thanks to #7207, we now have a way to validate at the type-level that a
reflected value is actually the type it says it is and not just a
dynamic representation of that type.

`dyn PartialReflect` values _might_ be a dynamic type, but `dyn Reflect`
values are guaranteed to _not_ be a dynamic type.

Therefore, we can start to add methods to `Reflect` that weren't really
possible before. For example, we should now be able to always get a
`&'static TypeInfo`, and not just an `Option<&'static TypeInfo>`.

## Solution

Add the `DynamicTyped` trait.

This trait is similar to `DynamicTypePath` in that it provides a way to
use the non-object-safe `Typed` trait in an object-safe way.

And since all types that derive `Reflect` will also derive `Typed`, we
can safely add `DynamicTyped` as a supertrait of `Reflect`. This allows
us to use it when just given a `dyn Reflect` trait object.

## Testing

You can test locally by running:

```
cargo test --package bevy_reflect
```

---

## Showcase

`Reflect` now has a supertrait of `DynamicTyped`, allowing `TypeInfo` to
be retrieved from a `dyn Reflect` trait object without having to unwrap
anything!

```rust
let value: Box<dyn Reflect> = Box::new(String::from("Hello!"));

// BEFORE
let info: &'static TypeInfo = value.get_represented_type_info().unwrap();

// AFTER
let info: &'static TypeInfo = value.reflect_type_info();
```

## Migration Guide

`Reflect` now has a supertrait of `DynamicTyped`. If you were manually
implementing `Reflect` and did not implement `Typed`, you will now need
to do so.
2024-09-13 17:17:10 +00:00
Wybe Westra
ae80a20690
Reccomend using AssetPlugin.file_path instead of CARGO_MANIFEST_DIR (#15176)
Fixes #15175.

One question I have: I see that the scene_viewer example uses the
CARGO_MANIFEST_DIR. Should that line be removed, or would that break the
tool?

1fd478277e/examples/tools/scene_viewer/main.rs (L40)
2024-09-13 16:16:23 +00:00
ickshonpe
1b1105e327
Remove border radius scaling (#15173)
# Objective

Fixes #15142

Split this off from #15163 as it's a very simple fix.

## Solution

UiScale was applied twice to border radius, remove the second
application.

## Testing

You can use this modified button example from the issue for testing:

```
use bevy::{color::palettes::basic::*, prelude::*, winit::WinitSettings};

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        // Only run the app when there is user input. This will significantly reduce CPU/GPU use.
        .insert_resource(UiScale(2.))
        .insert_resource(WinitSettings::desktop_app())
        .add_systems(Startup, setup)
        .add_systems(Update, button_system)
        .run();
}

const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);

fn button_system(
    mut interaction_query: Query<
        (
            &Interaction,
            &mut BackgroundColor,
            &mut BorderColor,
            &Children,
        ),
        (Changed<Interaction>, With<Button>),
    >,
    mut text_query: Query<&mut Text>,
) {
    for (interaction, mut color, mut border_color, children) in &mut interaction_query {
        let mut text = text_query.get_mut(children[0]).unwrap();
        match *interaction {
            Interaction::Pressed => {
                text.sections[0].value = "Press".to_string();
                *color = PRESSED_BUTTON.into();
                border_color.0 = RED.into();
            }
            Interaction::Hovered => {
                text.sections[0].value = "Hover".to_string();
                *color = HOVERED_BUTTON.into();
                border_color.0 = Color::WHITE;
            }
            Interaction::None => {
                text.sections[0].value = "Button".to_string();
                *color = NORMAL_BUTTON.into();
                border_color.0 = Color::BLACK;
            }
        }
    }
}

fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    // ui camera
    commands.spawn(Camera2dBundle::default());
    commands
        .spawn(NodeBundle {
            style: Style {
                width: Val::Percent(100.0),
                height: Val::Percent(100.0),
                align_items: AlignItems::Center,
                justify_content: JustifyContent::Center,
                ..default()
            },
            ..default()
        })
        .with_children(|parent| {
            parent
                .spawn(ButtonBundle {
                    style: Style {
                        width: Val::Px(250.0),
                        height: Val::Px(100.0),
                        border: UiRect::all(Val::Px(25.0)),
                        // horizontally center child text
                        justify_content: JustifyContent::Center,
                        // vertically center child text
                        align_items: AlignItems::Center,
                        ..default()
                    },
                    border_color: BorderColor(Color::BLACK),
                    border_radius: BorderRadius::all(Val::Px(25.)),
                    background_color: NORMAL_BUTTON.into(),
                    ..default()
                })
                .with_child(TextBundle::from_section(
                    "Button",
                    TextStyle {
                        font: asset_server.load("fonts/FiraSans-Bold.ttf"),
                        font_size: 40.0,
                        color: Color::srgb(0.9, 0.9, 0.9),
                    },
                ));
            parent
                .spawn(NodeBundle {
                    style: Style {
                        width: Val::Px(150.0),
                        padding: UiRect::vertical(Val::Px(25.)),
                        height: Val::Px(100.0),
                        align_items: AlignItems::Stretch,
                        justify_content: JustifyContent::Stretch,
                        ..Default::default()
                    },
                    ..default()
                })
                .with_child(NodeBundle {
                    style: Style {
                        flex_basis: Val::Percent(100.),
                        ..Default::default()
                    },
                    background_color: RED.into(),
                    ..Default::default()
                });
        });
}
```

## Showcase

Using the modified button example

### main

<img alt="366023197-e6124f07-e522-4514-bd8e-7986ac32890c"
src="https://github.com/user-attachments/assets/b7b909ed-1184-4d9d-b50b-e30f4c1f76b2">


### this PR

![image](https://github.com/user-attachments/assets/89b89a2f-533f-41bd-b2cb-4743aec6519e)
2024-09-13 15:52:42 +00:00