Commit graph

4159 commits

Author SHA1 Message Date
Joona Aalto
c62ad4b2c4
Implement bounding volumes for primitive shapes (#11336)
# Objective

Closes #10570.

#10946 added bounding volume types and traits, but didn't use them for
anything yet. This PR implements `Bounded2d` and `Bounded3d` for Bevy's
primitive shapes.

## Solution

Implement `Bounded2d` and `Bounded3d` for primitive shapes. This allows
computing AABBs and bounding circles/spheres for them.

For most shapes, there are several ways of implementing bounding
volumes. I took inspiration from [Parry's bounding
volumes](https://github.com/dimforge/parry/tree/master/src/bounding_volume),
[Inigo Quilez](http://iquilezles.org/articles/diskbbox/), and figured
out the rest myself using geometry. I tried to comment all slightly
non-trivial or unclear math to make it understandable.

Parry uses support mapping (finding the farthest point in some direction
for convex shapes) for some AABBs like cones, cylinders, and line
segments. This involves several quat operations and normalizations, so I
opted for the simpler and more efficient geometric approaches shown in
[Quilez's article](http://iquilezles.org/articles/diskbbox/).

Below you can see some of the bounding volumes working in 2D and 3D.
Note that I can't conveniently add these examples yet because they use
primitive shape meshing, which is still WIP.


https://github.com/bevyengine/bevy/assets/57632562/4465cbc6-285b-4c71-b62d-a2b3ee16f8b4


https://github.com/bevyengine/bevy/assets/57632562/94b4ac84-a092-46d7-b438-ce2e971496a4

---

## Changelog

- Implemented `Bounded2d`/`Bounded3d` for primitive shapes
- Added `from_point_cloud` method for bounding volumes (used by many
bounding implementations)
- Added `point_cloud_2d/3d_center` and `rotate_vec2` utility functions
- Added `RegularPolygon::vertices` method (used in regular polygon AABB
construction)
- Added `Triangle::circumcenter` method (used in triangle bounding
circle construction)
- Added bounding circle/sphere creation from AABBs and vice versa

## Extra

Do we want to implement `Bounded2d` for some "3D-ish" shapes too? For
example, capsules are sort of dimension-agnostic and useful for 2D, so I
think that would be good to implement. But a cylinder in 2D is just a
rectangle, and a cone is a triangle, so they wouldn't make as much sense
to me. A conical frustum would be an isosceles trapezoid, which could be
useful, but I'm not sure if computing the 2D AABB of a 3D frustum makes
semantic sense.
2024-01-18 15:55:36 +00:00
jeliag
f6b40a6e43
Multiple Configurations for Gizmos (#10342)
# Objective

This PR aims to implement multiple configs for gizmos as discussed in
#9187.

## Solution

Configs for the new `GizmoConfigGroup`s are stored in a
`GizmoConfigStore` resource and can be accesses using a type based key
or iterated over. This type based key doubles as a standardized location
where plugin authors can put their own configuration not covered by the
standard `GizmoConfig` struct. For example the `AabbGizmoGroup` has a
default color and toggle to show all AABBs. New configs can be
registered using `app.init_gizmo_group::<T>()` during startup.

When requesting the `Gizmos<T>` system parameter the generic type
determines which config is used. The config structs are available
through the `Gizmos` system parameter allowing for easy access while
drawing your gizmos.

Internally, resources and systems used for rendering (up to an including
the extract system) are generic over the type based key and inserted on
registering a new config.

## Alternatives

The configs could be stored as components on entities with markers which
would make better use of the ECS. I also implemented this approach
([here](https://github.com/jeliag/bevy/tree/gizmo-multiconf-comp)) and
believe that the ergonomic benefits of a central config store outweigh
the decreased use of the ECS.

## Unsafe Code

Implementing system parameter by hand is unsafe but seems to be required
to access the config store once and not on every gizmo draw function
call. This is critical for performance. ~Is there a better way to do
this?~

## Future Work

New gizmos (such as #10038, and ideas from #9400) will require custom
configuration structs. Should there be a new custom config for every
gizmo type, or should we group them together in a common configuration?
(for example `EditorGizmoConfig`, or something more fine-grained)

## Changelog

- Added `GizmoConfigStore` resource and `GizmoConfigGroup` trait
- Added `init_gizmo_group` to `App`
- Added early returns to gizmo drawing increasing performance when
gizmos are disabled
- Changed `GizmoConfig` and aabb gizmos to use new `GizmoConfigStore`
- Changed `Gizmos` system parameter to use type based key to retrieve
config
- Changed resources and systems used for gizmo rendering to be generic
over type based key
- Changed examples (3d_gizmos, 2d_gizmos) to showcase new API

## Migration Guide

- `GizmoConfig` is no longer a resource and has to be accessed through
`GizmoConfigStore` resource. The default config group is
`DefaultGizmoGroup`, but consider using your own custom config group if
applicable.

---------

Co-authored-by: Nicola Papale <nicopap@users.noreply.github.com>
2024-01-18 15:52:50 +00:00
Brian Reavis
c9e1fcdb35
Added AssetLoadFailedEvent, UntypedAssetLoadFailedEvent (#11369)
# Objective

This adds events for assets that fail to load along with minor utility
methods to make them useful. This paves the way for users writing their
own error handling and retry systems, plus Bevy including robust retry
handling: #11349.

* Addresses #11288
* Needed for #11349

# Solution

```rust
/// An event emitted when a specific [`Asset`] fails to load.
#[derive(Event, Clone, Debug)]
pub struct AssetLoadFailedEvent<A: Asset> {
    pub id: AssetId<A>,
    /// The original handle returned when the asset load was requested.
    pub handle: Option<Handle<A>>,
    /// The asset path that was attempted.
    pub path: AssetPath<'static>,
    /// Why the asset failed to load.
    pub error: AssetLoadError,
}
```

I started implementing `AssetEvent::Failed` like suggested in #11288,
but decided it was better as its own type because:

* I think it makes sense for `AssetEvent` to only refer to assets that
actually exist.
* In order to return `AssetLoadError` in the event (which is useful
information for error handlers that might attempt a retry) we would have
to remove `Copy` from `AssetEvent`.
* There are numerous places in the render app that match against
`AssetEvent`, and I don't think it's worth introducing extra noise about
assets that don't exist.

I also introduced `UntypedAssetLoadErrorEvent`, which is very useful in
places that need to support type flexibility, like an Asset-agnostic
retry plugin.

# Changelog

* **Added:** `AssetLoadFailedEvent<A>`
* **Added**: `UntypedAssetLoadFailedEvent`
* **Added:** `AssetReaderError::Http` for status code information on
HTTP errors. Before this, status codes were only available by parsing
the error message of generic `Io` errors.
* **Added:** `asset_server.get_path_id(path)`. This method simply gets
the asset id for the path. Without this, one was left using
`get_path_handle(path)`, which has the overhead of returning a strong
handle.
* **Fixed**: Made `AssetServer` loads return the same handle for assets
that already exist in a failed state. Now, when you attempt a `load`
that's in a `LoadState::Failed` state, it'll re-use the original asset
id. The advantage of this is that any dependent assets created using the
original handle will "unbreak" if a retry succeeds.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-01-17 21:12:00 +00:00
robtfm
30940e5cb4
fix occasional crash moving ui root nodes (#11371)
# Objective

fix an occasional crash when moving ui root nodes between cameras.

occasionally, updating the TargetCamera of a ui element and then
removing the element causes a crash.

i believe that is because when we assign a child in taffy, the old
parent doesn't remove that child from it's children, so we have:

```
user: create root node N1, camera A
-> layout::set_camera_children(A) : 
	- create implicit node A1
	- assign 1 as child -> taffy.children[A1] = [N1], taffy.parents[1] = A1

user: move root node N1 to camera B
-> layout::set_camera_children(B) :
	- create implicit node B1
	- assign 1 as child -> taffy.children[A1] = [N1], taffy.children[B1] = [N1], taffy.parents[1] = B1
-> layout::set_camera_children(A) :
	- remove implicit node A1 (which still has N1 as a child) -> 
		-> taffy sets parent[N1] = None ***
		-> taffy.children[B1] = [N1], taffy.parents[1] = None

user: remove N1
-> layout::remove_entities(N1)
	- since parent[N1] is None, it's not removed from B1 -> taffy.children[B1] = [N1], taffy.parents[1] is removed
-> layout::set_camera_children(B)
	- remove implicit node B1
	- taffy crash accessing taffy.parents[N1]
```

## Solution

we can work around this by making sure to remove the child from the old
parent if one exists (this pr).

i think a better fix may be for taffy to check in `Taffy::remove` and
only set the child's parent to None if it is currently equal to the node
being removed but i'm not sure if there's an explicit assumption we're
violating here (@nicoburns).
2024-01-17 16:53:27 +00:00
wackbyte
43f83d5e7c
Remove duplicate #[automatically_derived] in ECS macro (#11388)
# Objective

It's already provided by `item_attrs`, so it can be removed.

# Solution

Remove the extra `#[automatically_derived]`.
2024-01-17 16:52:45 +00:00
Giacomo Stevanato
39cca41f3f
Make DynamicUniformBuffer::push accept an &T instead of T (#11373)
# Objective

- `DynamicUniformBuffer::push` takes an owned `T` but only uses a shared
reference to it
- This in turn requires users of `DynamicUniformBuffer::push` to
potentially unecessarily clone data

## Solution

- Have `DynamicUniformBuffer::push` take a shared reference to `T`

---

## Changelog

- `DynamicUniformBuffer::push` now takes a `&T` instead of `T`

## Migration Guide

- Users of `DynamicUniformBuffer::push` now need to pass references to
`DynamicUniformBuffer::push` (e.g. existing `uniforms.push(value)` will
now become `uniforms.push(&value)`)
2024-01-16 20:51:56 +00:00
James O'Brien
ea42d14344
Dynamic queries and builder API (#9774)
# Objective
Expand the existing `Query` API to support more dynamic use cases i.e.
scripting.

## Prior Art
 - #6390 
 - #8308 
- #10037

## Solution
- Create a `QueryBuilder` with runtime methods to define the set of
component accesses for a built query.
- Create new `WorldQueryData` implementations `FilteredEntityMut` and
`FilteredEntityRef` as variants of `EntityMut` and `EntityRef` that
provide run time checked access to the components included in a given
query.
- Add new methods to `Query` to create "query lens" with a subset of the
access of the initial query.

### Query Builder
The `QueryBuilder` API allows you to define a query at runtime. At it's
most basic use it will simply create a query with the corresponding type
signature:
```rust
let query = QueryBuilder::<Entity, With<A>>::new(&mut world).build();
// is equivalent to
let query = QueryState::<Entity, With<A>>::new(&mut world);
```
Before calling `.build()` you also have the opportunity to add
additional accesses and filters. Here is a simple example where we add
additional filter terms:
```rust
let entity_a = world.spawn((A(0), B(0))).id();
let entity_b = world.spawn((A(0), C(0))).id();

let mut query_a = QueryBuilder::<Entity>::new(&mut world)
    .with::<A>()
    .without::<C>()
    .build();
            
assert_eq!(entity_a, query_a.single(&world));
```
This alone is useful in that allows you to decide which archetypes your
query will match at runtime. However it is also very limited, consider a
case like the following:
```rust
let query_a = QueryBuilder::<&A>::new(&mut world)
// Add an additional access
    .data::<&B>()
    .build();
```
This will grant the query an additional read access to component B
however we have no way of accessing the data while iterating as the type
signature still only includes &A. For an even more concrete example of
this consider dynamic components:
```rust
let query_a = QueryBuilder::<Entity>::new(&mut world)
// Adding a filter is easy since it doesn't need be read later
    .with_id(component_id_a)
// How do I access the data of this component?
    .ref_id(component_id_b)
    .build();
```
With this in mind the `QueryBuilder` API seems somewhat incomplete by
itself, we need some way method of accessing the components dynamically.
So here's one:
### Query Transmutation
If the problem is not having the component in the type signature why not
just add it? This PR also adds transmute methods to `QueryBuilder` and
`QueryState`. Here's a simple example:
```rust
world.spawn(A(0));
world.spawn((A(1), B(0)));
let mut query = QueryBuilder::<()>::new(&mut world)
    .with::<B>()
    .transmute::<&A>()
    .build();

query.iter(&world).for_each(|a| assert_eq!(a.0, 1));
```
The `QueryState` and `QueryBuilder` transmute methods look quite similar
but are different in one respect. Transmuting a builder will always
succeed as it will just add the additional accesses needed for the new
terms if they weren't already included. Transmuting a `QueryState` will
panic in the case that the new type signature would give it access it
didn't already have, for example:
```rust
let query = QueryState::<&A, Option<&B>>::new(&mut world);
/// This is fine, the access for Option<&A> is less restrictive than &A
query.transmute::<Option<&A>>(&world);
/// Oh no, this would allow access to &B on entities that might not have it, so it panics
query.transmute::<&B>(&world);
/// This is right out
query.transmute::<&C>(&world);
```
This is quite an appealing API to also have available on `Query` however
it does pose one additional wrinkle: In order to to change the iterator
we need to create a new `QueryState` to back it. `Query` doesn't own
it's own state though, it just borrows it, so we need a place to borrow
it from. This is why `QueryLens` exists, it is a place to store the new
state so it can be borrowed when you call `.query()` leaving you with an
API like this:
```rust
fn function_that_takes_a_query(query: &Query<&A>) {
    // ...
}

fn system(query: Query<(&A, &B)>) {
    let lens = query.transmute_lens::<&A>();
    let q = lens.query();
    function_that_takes_a_query(&q);
}
```
Now you may be thinking: Hey, wait a second, you introduced the problem
with dynamic components and then described a solution that only works
for static components! Ok, you got me, I guess we need a bit more:
### Filtered Entity References
Currently the only way you can access dynamic components on entities
through a query is with either `EntityMut` or `EntityRef`, however these
can access all components and so conflict with all other accesses. This
PR introduces `FilteredEntityMut` and `FilteredEntityRef` as
alternatives that have additional runtime checking to prevent accessing
components that you shouldn't. This way you can build a query with a
`QueryBuilder` and actually access the components you asked for:
```rust
let mut query = QueryBuilder::<FilteredEntityRef>::new(&mut world)
    .ref_id(component_id_a)
    .with(component_id_b)
    .build();

let entity_ref = query.single(&world);

// Returns Some(Ptr) as we have that component and are allowed to read it
let a = entity_ref.get_by_id(component_id_a);
// Will return None even though the entity does have the component, as we are not allowed to read it
let b = entity_ref.get_by_id(component_id_b);
```
For the most part these new structs have the exact same methods as their
non-filtered equivalents.

Putting all of this together we can do some truly dynamic ECS queries,
check out the `dynamic` example to see it in action:
```
Commands:
    comp, c   Create new components
    spawn, s  Spawn entities
    query, q  Query for entities
Enter a command with no parameters for usage.

> c A, B, C, Data 4  
Component A created with id: 0
Component B created with id: 1
Component C created with id: 2
Component Data created with id: 3

> s A, B, Data 1
Entity spawned with id: 0v0

> s A, C, Data 0
Entity spawned with id: 1v0

> q &Data
0v0: Data: [1, 0, 0, 0]
1v0: Data: [0, 0, 0, 0]

> q B, &mut Data                                                                                     
0v0: Data: [2, 1, 1, 1]

> q B || C, &Data 
0v0: Data: [2, 1, 1, 1]
1v0: Data: [0, 0, 0, 0]
```
## Changelog
 - Add new `transmute_lens` methods to `Query`.
- Add new types `QueryBuilder`, `FilteredEntityMut`, `FilteredEntityRef`
and `QueryLens`
- `update_archetype_component_access` has been removed, archetype
component accesses are now determined by the accesses set in
`update_component_access`
- Added method `set_access` to `WorldQuery`, this is called before
`update_component_access` for queries that have a restricted set of
accesses, such as those built by `QueryBuilder` or `QueryLens`. This is
primarily used by the `FilteredEntity*` variants and has an empty trait
implementation.
- Added method `get_state` to `WorldQuery` as a fallible version of
`init_state` when you don't have `&mut World` access.

## Future Work
Improve performance of `FilteredEntityMut` and `FilteredEntityRef`,
currently they have to determine the accesses a query has in a given
archetype during iteration which is far from ideal, especially since we
already did the work when matching the archetype in the first place. To
avoid making more internal API changes I have left it out of this PR.

---------

Co-authored-by: Mike Hsu <mike.hsu@gmail.com>
2024-01-16 19:16:49 +00:00
vero
54a54d4c10
Remove Vec from GpuArrayBuffer (#11368)
# Objective

- Remove Vec as described in
https://github.com/bevyengine/bevy/pull/11290#issuecomment-1890315650

## Solution

- Rely on StorageBuffer's backing Vec instead

---

## Changelog

- GpuArrayBuffer no longer has a redundant backing Vec
2024-01-16 16:09:17 +00:00
Shane Celis
b6e154fc64
Fix embedded watcher to work with external crates (#11370)
# Objective

Tried using "embedded_watcher" feature and `embedded_asset!()` from
another crate. The assets embedded fine but were not "watched." The
problem appears to be that checking for the feature was done inside the
macro, so rather than checking if "embedded_watcher" was enabled for
bevy, it would check if it was enabled for the current crate.

## Solution

I extracted the checks for the "embedded_watcher" feature into its own
function called `watched_path()`. No external changes.

### Alternative Solution

An alternative fix would be to not do any feature checking in
`embedded_asset!()` or an extracted function and always send the
full_path to `insert_asset()` where it's promptly dropped when the
feature isn't turned on. That would be simpler.

```
    ($app: ident, $source_path: expr, $path: expr) => {{
        let mut embedded = $app
            .world
            .resource_mut::<$crate::io::embedded::EmbeddedAssetRegistry>();
        let path = $crate::embedded_path!($source_path, $path);
        //#[cfg(feature = "embedded_watcher")]
        let full_path = std::path::Path::new(file!()).parent().unwrap().join($path);
        //#[cfg(not(feature = "embedded_watcher"))]
        //let full_path = std::path::PathBuf::new();
        embedded.insert_asset(full_path, &path, include_bytes!($path));
    }};
```

## Changelog

> Fix embedded_watcher feature to work with external crates
2024-01-16 15:18:16 +00:00
JMS55
fcd7c0fc3d
Exposure settings (adopted) (#11347)
Rebased and finished version of
https://github.com/bevyengine/bevy/pull/8407. Huge thanks to @GitGhillie
for adjusting all the examples, and the many other people who helped
write this PR (@superdump , @coreh , among others) :)

Fixes https://github.com/bevyengine/bevy/issues/8369

---

## Changelog
- Added a `brightness` control to `Skybox`.
- Added an `intensity` control to `EnvironmentMapLight`.
- Added `ExposureSettings` and `PhysicalCameraParameters` for
controlling exposure of 3D cameras.
- Removed the baked-in `DirectionalLight` exposure Bevy previously
hardcoded internally.

## Migration Guide
- If using a `Skybox` or `EnvironmentMapLight`, use the new `brightness`
and `intensity` controls to adjust their strength.
- All 3D scene will now have different apparent brightnesses due to Bevy
implementing proper exposure controls. You will have to adjust the
intensity of your lights and/or your camera exposure via the new
`ExposureSettings` component to compensate.

---------

Co-authored-by: Robert Swain <robert.swain@gmail.com>
Co-authored-by: GitGhillie <jillisnoordhoek@gmail.com>
Co-authored-by: Marco Buono <thecoreh@gmail.com>
Co-authored-by: vero <email@atlasdostal.com>
Co-authored-by: atlas dostal <rodol@rivalrebels.com>
2024-01-16 14:53:21 +00:00
Richard Hozák
184f233a67
Use glam for computing gLTF node transform (#11361)
# Objective

gltf-rs does its own computations when accessing `transform.matrix()`
which does not use glam types, rendering #11238 useless if people were
to load gltf models and expecting the results to be deterministic across
platforms.

## Solution

Move the computation to bevy side which uses glam types, it was already
used in one place, so I created one common function to handle the two
cases.

The added benefit this has, is that some gltf files can have
translation, rotation and scale directly instead of matrix which skips
the transform computation completely, win-win.
2024-01-16 14:33:19 +00:00
Félix Lescaudey de Maneville
135c7240f1
Texture Atlas rework (#5103)
# Objective

> Old MR: #5072 
> ~~Associated UI MR: #5070~~
> Adresses #1618

Unify sprite management

## Solution

- Remove the `Handle<Image>` field in `TextureAtlas` which is the main
cause for all the boilerplate
- Remove the redundant `TextureAtlasSprite` component
- Renamed `TextureAtlas` asset to `TextureAtlasLayout`
([suggestion](https://github.com/bevyengine/bevy/pull/5103#discussion_r917281844))
- Add a `TextureAtlas` component, containing the atlas layout handle and
the section index

The difference between this solution and #5072 is that instead of the
`enum` approach is that we can more easily manipulate texture sheets
without any breaking changes for classic `SpriteBundle`s (@mockersf
[comment](https://github.com/bevyengine/bevy/pull/5072#issuecomment-1165836139))

Also, this approach is more *data oriented* extracting the
`Handle<Image>` and avoiding complex texture atlas manipulations to
retrieve the texture in both applicative and engine code.
With this method, the only difference between a `SpriteBundle` and a
`SpriteSheetBundle` is an **additional** component storing the atlas
handle and the index.

~~This solution can be applied to `bevy_ui` as well (see #5070).~~

EDIT: I also applied this solution to Bevy UI

## Changelog

- (**BREAKING**) Removed `TextureAtlasSprite`
- (**BREAKING**) Renamed `TextureAtlas` to `TextureAtlasLayout`
- (**BREAKING**) `SpriteSheetBundle`:
  - Uses a  `Sprite` instead of a `TextureAtlasSprite` component
- Has a `texture` field containing a `Handle<Image>` like the
`SpriteBundle`
- Has a new `TextureAtlas` component instead of a
`Handle<TextureAtlasLayout>`
- (**BREAKING**) `DynamicTextureAtlasBuilder::add_texture` takes an
additional `&Handle<Image>` parameter
- (**BREAKING**) `TextureAtlasLayout::from_grid` no longer takes a
`Handle<Image>` parameter
- (**BREAKING**) `TextureAtlasBuilder::finish` now returns a
`Result<(TextureAtlasLayout, Handle<Image>), _>`
- `bevy_text`:
  - `GlyphAtlasInfo` stores the texture `Handle<Image>`
  - `FontAtlas` stores the texture `Handle<Image>`
- `bevy_ui`:
- (**BREAKING**) Removed `UiAtlasImage` , the atlas bundle is now
identical to the `ImageBundle` with an additional `TextureAtlas`

## Migration Guide

* Sprites

```diff
fn my_system(
  mut images: ResMut<Assets<Image>>, 
-  mut atlases: ResMut<Assets<TextureAtlas>>, 
+  mut atlases: ResMut<Assets<TextureAtlasLayout>>, 
  asset_server: Res<AssetServer>
) {
    let texture_handle: asset_server.load("my_texture.png");
-   let layout = TextureAtlas::from_grid(texture_handle, Vec2::new(25.0, 25.0), 5, 5, None, None);
+   let layout = TextureAtlasLayout::from_grid(Vec2::new(25.0, 25.0), 5, 5, None, None);
    let layout_handle = atlases.add(layout);
    commands.spawn(SpriteSheetBundle {
-      sprite: TextureAtlasSprite::new(0),
-      texture_atlas: atlas_handle,
+      atlas: TextureAtlas {
+         layout: layout_handle,
+         index: 0
+      },
+      texture: texture_handle,
       ..Default::default()
     });
}
```
* UI


```diff
fn my_system(
  mut images: ResMut<Assets<Image>>, 
-  mut atlases: ResMut<Assets<TextureAtlas>>, 
+  mut atlases: ResMut<Assets<TextureAtlasLayout>>, 
  asset_server: Res<AssetServer>
) {
    let texture_handle: asset_server.load("my_texture.png");
-   let layout = TextureAtlas::from_grid(texture_handle, Vec2::new(25.0, 25.0), 5, 5, None, None);
+   let layout = TextureAtlasLayout::from_grid(Vec2::new(25.0, 25.0), 5, 5, None, None);
    let layout_handle = atlases.add(layout);
    commands.spawn(AtlasImageBundle {
-      texture_atlas_image: UiTextureAtlasImage {
-           index: 0,
-           flip_x: false,
-           flip_y: false,
-       },
-      texture_atlas: atlas_handle,
+      atlas: TextureAtlas {
+         layout: layout_handle,
+         index: 0
+      },
+      image: UiImage {
+           texture: texture_handle,
+           flip_x: false,
+           flip_y: false,
+       },
       ..Default::default()
     });
}
```

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: François <mockersf@gmail.com>
Co-authored-by: IceSentry <IceSentry@users.noreply.github.com>
2024-01-16 13:59:08 +00:00
BD103
9f8db0de0d
Bump toml_edit in build-template-pages tool (#11342)
# Objective

- The
[`build-templated-pages`](4778fbeb65/tools/build-templated-pages)
tool is used to render the Markdown templates in the
[docs-template](4778fbeb65/docs-template)
folder.
- It depends on out outdated version of `toml_edit`.

## Solution

- Bump `toml_edit` to 0.21, disabling all features except `parse`.
2024-01-16 05:23:18 +00:00
Roman Salnikov
eb9db21113
Camera-driven UI (#10559)
# Objective

Add support for presenting each UI tree on a specific window and
viewport, while making as few breaking changes as possible.

This PR is meant to resolve the following issues at once, since they're
all related.

- Fixes #5622 
- Fixes #5570 
- Fixes #5621 

Adopted #5892 , but started over since the current codebase diverged
significantly from the original PR branch. Also, I made a decision to
propagate component to children instead of recursively iterating over
nodes in search for the root.


## Solution

Add a new optional component that can be inserted to UI root nodes and
propagate to children to specify which camera it should render onto.
This is then used to get the render target and the viewport for that UI
tree. Since this component is optional, the default behavior should be
to render onto the single camera (if only one exist) and warn of
ambiguity if multiple cameras exist. This reduces the complexity for
users with just one camera, while giving control in contexts where it
matters.

## Changelog

- Adds `TargetCamera(Entity)` component to specify which camera should a
node tree be rendered into. If only one camera exists, this component is
optional.
- Adds an example of rendering UI to a texture and using it as a
material in a 3D world.
- Fixes recalculation of physical viewport size when target scale factor
changes. This can happen when the window is moved between displays with
different DPI.
- Changes examples to demonstrate assigning UI to different viewports
and windows and make interactions in an offset viewport testable.
- Removes `UiCameraConfig`. UI visibility now can be controlled via
combination of explicit `TargetCamera` and `Visibility` on the root
nodes.

---------

Co-authored-by: davier <bricedavier@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
2024-01-16 00:39:10 +00:00
Mike
ee9a1503ed
Async channel v2 (#10692)
# Objective

- Update async channel to v2.

## Solution

- async channel doesn't support `send_blocking` on wasm anymore. So
don't compile the pipelined rendering plugin on wasm anymore.
- Replaces https://github.com/bevyengine/bevy/pull/10405

## Migration Guide
- The `PipelinedRendering` plugin is no longer exported on wasm. If you
are including it in your wasm builds you should remove it.

```rust
#[cfg(all(not(target_arch = "wasm32"))]
app.add_plugins(bevy_render::pipelined_rendering::PipelinedRenderingPlugin);
```

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-01-15 19:23:00 +00:00
Turki Al-Marri
fcc1113ec8
Fix doc of [Schedules] to mention exclusion of current schedule. (#11360)
Document that [`Schedules`] resource does not include the current
schedule.
2024-01-15 19:13:13 +00:00
Cameron
aeab690fdb
Change WinitPlugin defaults to limit game update rate when window is not visible (for real this time) (#11305)
# Objective

I goofed. #7611 forgot to change the default update modes set by the
`WinitPlugin`.


<ce5bae55f6/crates/bevy_winit/src/winit_config.rs (L53-L60)>


<ce5bae55f6/crates/bevy_winit/src/lib.rs (L127)>

## Solution

Change `Default` impl for `WinitSettings` to return the `game` settings
that limit FPS when the app runs in the background.
2024-01-15 17:53:35 +00:00
Aevyrie
839d2f8353
Approximate indirect specular occlusion (#11152)
# Objective

- The current PBR renderer over-brightens indirect specular reflections,
which tends to cause objects to appear to glow, because specular
occlusion is not accounted for.

## Solution

- Attenuate indirect specular term with an approximation for specular
occlusion, using [[Lagarde et al., 2014] (pg.
76)](https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf).

| Before | After | Animation |
| --- | --- | --- |
| <img width="1840" alt="before bike"
src="https://github.com/bevyengine/bevy/assets/2632925/b6e10d15-a998-4a94-875a-1c2b1e98348a">
| <img width="1840" alt="after bike"
src="https://github.com/bevyengine/bevy/assets/2632925/53b1479c-b1e4-427f-b140-53df26ca7193">
|
![ezgif-1-fbcbaf272b](https://github.com/bevyengine/bevy/assets/2632925/c2dece1c-eb3d-4e05-92a2-46cf83052c7c)
|
| <img width="1840" alt="classroom before"
src="https://github.com/bevyengine/bevy/assets/2632925/b16c0e74-741e-4f40-a7df-8863eaa62596">
| <img width="1840" alt="classroom after"
src="https://github.com/bevyengine/bevy/assets/2632925/26f9e971-0c63-4ee9-9544-964e5703d65e">
|
![ezgif-1-0f390edd06](https://github.com/bevyengine/bevy/assets/2632925/d8894e52-380f-4528-aa0d-1ca249108178)
|

---

## Changelog

- Ambient occlusion now applies to indirect specular reflections to
approximate how objects occlude specular light.

## Migration Guide

- Renamed `PbrInput::occlusion` to `diffuse_occlusion`, and added
`specular_occlusion`.
2024-01-15 16:10:55 +00:00
vero
4695b82f6b
Use EntityHashMap whenever possible (#11353)
# Objective

Fixes #11352

## Solution

- Use `EntityHashMap<Entity, T>` instead of `HashMap<Entity, T>`

---

## Changelog

Changed
- Use `EntityHashMap<Entity, T>` instead of `HashMap<Entity, T>`
whenever possible

## Migration Guide

TODO
2024-01-15 15:51:17 +00:00
François
3d628a8191
Fix Reactive and ReactiveLowPower update modes (#11325)
# Objective

- Partial fix for #11235 
- Fixes #11274 
- Fixes #11320 
- Fixes #11273

## Solution

- check update mode to trigger redraw request, instead of once a redraw
request has been triggered
- don't ignore device event in case of `Reactive` update mode
- make sure that at least 5 updates are triggered on application start
to ensure everything is correctly initialized
- trigger manual updates instead of relying on redraw requests when
there are no window or they are not visible
2024-01-15 15:46:11 +00:00
Félix Lescaudey de Maneville
01139b3472
Sprite slicing and tiling (#10588)
> Replaces #5213

# Objective

Implement sprite tiling and [9 slice
scaling](https://en.wikipedia.org/wiki/9-slice_scaling) for
`bevy_sprite`.
Allowing slice scaling and texture tiling.

Basic scaling vs 9 slice scaling:


![Traditional_scaling_vs_9-slice_scaling](https://user-images.githubusercontent.com/26703856/177335801-27f6fa27-c569-4ce6-b0e6-4f54e8f4e80a.svg)

Slicing example:

<img width="481" alt="Screenshot 2022-07-05 at 15 05 49"
src="https://user-images.githubusercontent.com/26703856/177336112-9e961af0-c0af-4197-aec9-430c1170a79d.png">

Tiling example:

<img width="1329" alt="Screenshot 2023-11-16 at 13 53 32"
src="https://github.com/bevyengine/bevy/assets/26703856/14db39b7-d9e0-4bc3-ba0e-b1f2db39ae8f">

# Solution

- `SpriteBundlue` now has a `scale_mode` component storing a
`SpriteScaleMode` enum with three variants:
  - `Stretched` (default) 
  - `Tiled` to have sprites tile horizontally and/or vertically
- `Sliced` allowing 9 slicing the texture and optionally tile some
sections with a `Textureslicer`.
- `bevy_sprite` has two extra systems to compute a
`ComputedTextureSlices` if necessary,:
- One system react to changes on `Sprite`, `Handle<Image>` or
`SpriteScaleMode`
- The other listens to `AssetEvent<Image>` to compute slices on sprites
when the texture is ready or changed
- I updated the `bevy_sprite` extraction stage to extract potentially
multiple textures instead of one, depending on the presence of
`ComputedTextureSlices`
- I added two examples showcasing the slicing and tiling feature.

The addition of `ComputedTextureSlices` as a cache is to avoid querying
the image data, to retrieve its dimensions, every frame in a extract or
prepare stage. Also it reacts to changes so we can have stuff like this
(tiling example):


https://github.com/bevyengine/bevy/assets/26703856/a349a9f3-33c3-471f-8ef4-a0e5dfce3b01

# Related 

- [ ] Once #5103 or #10099 is merged I can enable tiling and slicing for
texture sheets as ui

# To discuss

There is an other option, to consider slice/tiling as part of the asset,
using the new asset preprocessing but I have no clue on how to do it.

Also, instead of retrieving the Image dimensions, we could use the same
system as the sprite sheet and have the user give the image dimensions
directly (grid). But I think it's less user friendly

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: ickshonpe <david.curthoys@googlemail.com>
Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
2024-01-15 15:40:06 +00:00
Cornelius
a7b99f0500
GLTF extension support (#11138)
# Objective
Adds support for accessing raw extension data of loaded GLTF assets

## Solution
Via the GLTF loader settings, you can specify whether or not to include
the GLTF source. While not the ideal way of solving this problem,
modeling all of GLTF within Bevy just for extensions adds a lot of
complexity to the way Bevy handles GLTF currently. See the example GLTF
meta file and code
```
(
    meta_format_version: "1.0",
    asset: Load(
        loader: "bevy_gltf::loader::GltfLoader",
        settings: (
            load_meshes: true,
            load_cameras: true,
            load_lights: true,
            include_source: true,
        ),
    ),
)
```
```rs
pub fn load_gltf(mut commands: Commands, assets: Res<AssetServer>) {
    let my_gltf = assets.load("test_platform.gltf");

    commands.insert_resource(MyAssetPack {
        spawned: false,
        handle: my_gltf,
    });
}

#[derive(Resource)]
pub struct MyAssetPack {
    pub spawned: bool,
    pub handle: Handle<Gltf>,
}

pub fn spawn_gltf_objects(
    mut commands: Commands,
    mut my: ResMut<MyAssetPack>,
    assets_gltf: Res<Assets<Gltf>>,
) {
    // This flag is used to because this system has to be run until the asset is loaded.
    // If there's a better way of going about this I am unaware of it.
    if my.spawned {
        return;
    }

    if let Some(gltf) = assets_gltf.get(&my.handle) {
        info!("spawn");
        my.spawned = true;
        // spawn the first scene in the file
        commands.spawn(SceneBundle {
            scene: gltf.scenes[0].clone(),
            ..Default::default()
        });

        let source = gltf.source.as_ref().unwrap();
        info!("materials count {}", &source.materials().size_hint().0);
        info!(
            "materials ext is some {}",
            &source.materials().next().unwrap().extensions().is_some()
        );
    }
}
```

---

## Changelog
Added support for GLTF extensions through including raw GLTF source via
loader flag `GltfLoaderSettings::include_source == true`, stored in
`Gltf::source: Option<gltf::Gltf>`

## Migration Guide
This will have issues with "asset migrations", as there is currently no
way for .meta files to be migrated. Attempting to migrate .meta files
without the new flag will yield the following error:
```
bevy_asset::server: Failed to deserialize meta for asset test_platform.gltf: Failed to deserialize asset meta: SpannedError { code: MissingStructField { field: "include_source", outer: Some("GltfLoaderSettings") }, position: Position { line: 9, col: 9 } }
```
This means users who want to migrate their .meta files will have to add
the `include_source: true,` setting to their meta files by hand.
2024-01-15 15:38:01 +00:00
irate
c29a9729a4
Remove the ability to ignore global volume (#11092)
# Objective

The ability to ignore the global volume doesn't seem desirable and
complicates the API.

#7706 added global volume and the ability to ignore it, but there was no
further discussion about whether that's useful. Feel free to discuss
here :)

## Solution

Replace the `Volume` type's functionality with the `VolumeLevel`. Remove
`VolumeLevel`.

I also removed `DerefMut` derive that effectively made the volume `pub`
and actually ensured that the volume isn't set below `0` even in release
builds.

## Migration Guide

The option to ignore the global volume using `Volume::Absolute` has been
removed and `Volume` now stores the volume level directly, removing the
need for the `VolumeLevel` struct.
2024-01-15 15:31:54 +00:00
Charles Bournhonesque
8c6d9b8103
Add support for updating the tracing subscriber in LogPlugin (#10822)
# Objective

This PR is heavily inspired by
https://github.com/bevyengine/bevy/pull/7682
It aims to solve the same problem: allowing the user to extend the
tracing subscriber with extra layers.

(in my case, I'd like to use `use
metrics_tracing_context::{MetricsLayer, TracingContextLayer};`)


## Solution

I'm proposing a different api where the user has the opportunity to take
the existing `subscriber` and apply any transformations on it.

---

## Changelog

- Added a `update_subscriber` option on the `LogPlugin` that lets the
user modify the `subscriber` (for example to extend it with more tracing
`Layers`


## Migration Guide

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

- Added a new field `update_subscriber` in the `LogPlugin`

---------

Co-authored-by: Charles Bournhonesque <cbournhonesque@snapchat.com>
2024-01-15 15:26:13 +00:00
Mateusz Wachowiak
8a523de8db
Describe purpose of bevy_diagnostic (#11327)
# Objective

- Explain purpose of bevy_diagnostic, see:
https://github.com/bevyengine/bevy/issues/11309#issuecomment-1889896308

## Solution

- Add doc comment
2024-01-14 20:17:26 +00:00
Torstein Grindvik
4778fbeb65
Make sure tracy deps conform to compatibility table (#11331)
# Objective

The table [here](https://github.com/nagisa/rust_tracy_client) shows
which versions of [Tracy](https://github.com/wolfpld/tracy) should be
used combined with which Rust deps.

Reading `bevy_log`'s `Cargo.toml` can be slightly confusing since the
exact versions are not picked from the same row.

Reading the produced `Cargo.lock` when building a Bevy example shows
that it's the most recent row that is resolved, but this should be more
clearly understood without needing to check the lock file.


## Solution

- Specify versions from the compatibility table including patch version

Signed-off-by: Torstein Grindvik <torstein.grindvik@muybridge.com>
Co-authored-by: Torstein Grindvik <torstein.grindvik@muybridge.com>
2024-01-14 13:51:28 +00:00
BD103
b2d417b03d
Warn when bevy_sprite and bevy_pbr are not enabled with bevy_gizmos (#11296)
# Objective

- `bevy_gizmos` cannot work if both `bevy_sprite` and `bevy_pbr` are
disabled.
- It silently fails to render, making it difficult to debug.
- Fixes #10984

## Solution

- Log an error message when `GizmoPlugin` is registered.

## Alternatives

I chose to log an error message, since it seemed the least intrusive of
potential solutions. Some alternatives include:

- Choosing one dependency as the default, neglecting the other. (#11035)
- Raising a compile error when neither dependency is enabled. ([See my
original
comment](https://github.com/bevyengine/bevy/issues/10984#issuecomment-1873420426))
- Raising a compile warning using a macro hack. ([Pre-RFC - Add
compile_warning!
macro](https://internals.rust-lang.org/t/pre-rfc-add-compile-warning-macro/9370/7?u=bd103))
- Logging a warning instead of an error.
- _This might be the better option. Let me know if I should change it._

---

## Changelog

- `bevy_gizmos` will now log an error if neither `bevy_pbr` nor
`bevy_sprite` are enabled.
2024-01-14 13:51:14 +00:00
BD103
6f6269e195
Remove Default impl for CubicCurve (#11335)
# Objective

- Implementing `Default` for
[`CubicCurve`](https://docs.rs/bevy/latest/bevy/math/cubic_splines/struct.CubicCurve.html)
does not make sense because it cannot be mutated after creation.
- Closes #11209.
- Alternative to #11211.

## Solution

- Remove `Default` from `CubicCurve`'s derive statement.

Based off of @mockersf comment
(https://github.com/bevyengine/bevy/pull/11211#issuecomment-1880088036):

> CubicCurve can't be updated once created... I would prefer to remove
the Default impl as it doesn't make sense

---

## Changelog

- Removed the `Default` implementation for `CubicCurve`.

## Migration Guide

- Remove `CubicCurve` from any structs that implement `Default`.
- Wrap `CubicCurve` in a new type and provide your own default.

```rust
#[derive(Deref)]
struct MyCubicCurve<P: Point>(pub CubicCurve<P>);

impl Default for MyCubicCurve<Vec2> {
    fn default() -> Self {
        let points = [[
            vec2(-1.0, -20.0),
            vec2(3.0, 2.0),
            vec2(5.0, 3.0),
            vec2(9.0, 8.0),
        ]];

        Self(CubicBezier::new(points).to_curve())
    }
}
```
2024-01-14 04:40:37 +00:00
SpecificProtagonist
cd12e7c836
Make TypeId::hash more robust in case of upstream rustc changes (#11334)
Based on discussion after #11268 was merged:
Instead of panicking should the impl of `TypeId::hash` change
significantly, have a fallback and detect this in a test.
2024-01-14 04:07:14 +00:00
ickshonpe
03404c48ca
UI text rotation and scaling fix (#11326)
# Objective

UI node text is drawn in the wrong position after rotation or scaling.


![294723406-d031a3e6-a4f9-48b4-a66a-ee963100a8b9](https://github.com/bevyengine/bevy/assets/27962798/2755e2e3-6a03-4ee8-8676-bdcaa72ec678)

## Solution
In `extract_text_uinodes` to set the text's offset create a translation
matrix and multiply it by the UI node's transform.

Previously the offset was just added directly to the translation of the
Node's `GlobalTransform`, which meant no scaling or rotation would be
applied to the offset.

<img width="961" alt="296440025-537ec11c-1ea1-469c-8eec-2ad4ae012095"
src="https://github.com/bevyengine/bevy/assets/27962798/eae1a1d2-1369-47ad-8963-3862d03ec0bf">

<img width="961" alt="296440156-dd04029d-8112-4fa5-89a2-56d7acab66df"
src="https://github.com/bevyengine/bevy/assets/27962798/90b1b6db-13f4-4745-9f14-7c1661baad50">

Fixes #11241
2024-01-13 22:21:40 +00:00
Nicola Papale
a634075a39
Inline trivial methods in bevy_hierarchy (#11332)
# Objective

In #11330 I found out that `Parent::get` didn't get inlined, **even with
LTO on**!

This means that just to access a field, we have an instruction cache
invalidation, we will move some registers to the stack, will jump to new
instructions, move the field into a register, then do the same dance in
the other direction to go back to the call site.

## Solution

Mark trivial functions as `#[inline]`.

`inline(always)` may increase compilation time proportional to how many
time the function is called **and the size of the function marked with
`inline`**. Since we mark as `inline` functions that consists in a
single instruction, the cost is absolutely negligible.

I also took the opportunity to `inline` other functions. I'm not as
confident that marking functions calling other functions as `inline`
works similarly to very simple functions, so I used `inline` over
`inline(always)`, which doesn't have the same downsides as
`inline(always)`.

More information on inlining in rust:
https://nnethercote.github.io/perf-book/inlining.html
2024-01-13 22:20:50 +00:00
Nicola Papale
78b5f323f8
Skip alloc when updating animation path cache (#11330)
Not always, but skip it if the new length is smaller.

For context, `path_cache` is a `Vec<Vec<Option<Entity>>>`.

# Objective

Previously, when setting a new length to the `path_cache`, we would:

1. Deallocate all existing `Vec<Option<Entity>>`
2. Deallocate the `path_cache`
3. Allocate a new `Vec<Vec<Option<Entity>>>`, where each item is an
empty `Vec`, and would have to be allocated when pushed to.

This is a lot of allocations!

## Solution

Use
[`Vec::resize_with`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.resize_with).

With this change, what occurs is:

1. We `clear` each `Vec<Option<Entity>>`, keeping the allocation, but
making the memory of each `Vec` re-usable
2. We only append new `Vec` to `path_cache` when it is too small.

* Fixes #11328 

### Note on performance

I didn't benchmark it, I just ran a diff on the generated assembly (ran
with `--profile stress-test` and `--native`). I found this PR has 20
less instructions in `apply_animation` (out of 2504).

Though on a purely abstract level, I can deduce this leads to less
allocation.

More information on profiling allocations in rust:
https://nnethercote.github.io/perf-book/heap-allocations.html

## Future work

I think a [jagged vec](https://en.wikipedia.org/wiki/Jagged_array) would
be much more pertinent. Because it allocates everything in a single
contiguous buffer.

This would avoid dancing around allocations, and reduces the overhead of
one `*mut T` and two `usize` per row, also removes indirection,
improving cache efficiency. I think it would both improve code quality
and performance.
2024-01-13 19:33:11 +00:00
SpecificProtagonist
69760c78cf
Skip rehashing TypeIds (#11268)
# Objective

`TypeId` contains a high-quality hash. Whenever a lookup based on a
`TypeId` is performed (e.g. to insert/remove components), the hash is
run through a second hash function. This is unnecessary.

## Solution

Skip re-hashing `TypeId`s.

In my
[testing](https://gist.github.com/SpecificProtagonist/4b49ad74c6b82b0aedd3b4ea35121be8),
this improves lookup performance consistently by 10%-15% (of course, the
lookup is only a small part of e.g. a bundle insertion).
2024-01-13 13:26:43 +00:00
Alice Cecile
98b62e829d
Clean up code to find the current keyframe (#11306)
# Objective

While working on #10832, I found this code very dense and hard to
understand.

I was not confident in my fix (or the correctness of the existing code).

## Solution

Clean up, test and document the code used in the `apply_animation`
system.

I also added a pair of length-related utility methods to `Keyframes` for
easier testing. They seemed generically useful, so I made them pub.

## Changelog

- Added `VariableCurve::find_current_keyframe` method.
- Added `Keyframes::len` and `is_empty` methods.

---------

Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
2024-01-13 13:25:28 +00:00
BD103
99261232f1
Add example using State in docs (#11319)
# Objective

- It may be confusing whether
[`State`](https://docs.rs/bevy_ecs/latest/bevy_ecs/schedule/struct.State.html)
is a `Resource` or a `SystemParam`.
- Fixes #11312.

## Solution

- Add an example using `State` in a system in the docs, to clarify that
it is a `Resource`.

---

I basically copied the example from
[`States`](https://docs.rs/bevy_ecs/latest/bevy_ecs/schedule/trait.States.html)
and added a system beside it. I don't have a strong opinion on what the
example should look like, so please comment if you have a better idea.
:)
2024-01-13 13:24:00 +00:00
Ixentus
e2fd63104d
Simplify conditions (#11316)
# Objective

- Conditions don't have to be closures unless they have state or mutate.

## Solution

- Simplify conditions when possible.

---

## Changelog

The following run conditions are now regular systems:
- resource_exists<T>
- resource_added<T>
- resource_changed<T>
- resource_exists_and_changed<T>
- state_exists<S: States>
- state_changed<S: States>
- any_with_component<T: Component>

## Migration Guide

- resource_exists<T>() -> resource_exists<T>
- resource_added<T>() -> resource_added<T>
- resource_changed<T>() -> resource_changed<T>
- resource_exists_and_changed<T>() -> resource_exists_and_changed<T>
- state_exists<S: States>() -> state_exists<S: States>
- state_changed<S: States>() -> state_changed<S: States>
- any_with_component<T: Component>() -> any_with_component<T: Component>
2024-01-13 13:22:17 +00:00
Gonçalo Rica Pais da Silva
e6a324a11a
Unified identifer for entities & relations (#9797)
# Objective

The purpose of this PR is to begin putting together a unified identifier
structure that can be used by entities and later components (as
entities) as well as relationship pairs for relations, to enable all of
these to be able to use the same storages. For the moment, to keep
things small and focused, only `Entity` is being changed to make use of
the new `Identifier` type, keeping `Entity`'s API and
serialization/deserialization the same. Further changes are for
follow-up PRs.

## Solution

`Identifier` is a wrapper around `u64` split into two `u32` segments
with the idea of being generalised to not impose restrictions on
variants. That is for `Entity` to do. Instead, it is a general API for
taking bits to then merge and map into a `u64` integer. It exposes
low/high methods to return the two value portions as `u32` integers,
with then the MSB masked for usage as a type flag, enabling entity kind
discrimination and future activation/deactivation semantics.

The layout in this PR for `Identifier` is described as below, going from
MSB -> LSB.

```
|F| High value                    | Low value                      |
|_|_______________________________|________________________________|
|1| 31                            | 32                             |

F = Bit Flags
```

The high component in this implementation has only 31 bits, but that
still leaves 2^31 or 2,147,483,648 values that can be stored still, more
than enough for any generation/relation kinds/etc usage. The low part is
a full 32-bit index. The flags allow for 1 bit to be used for
entity/pair discrimination, as these have different usages for the
low/high portions of the `Identifier`. More bits can be reserved for
more variants or activation/deactivation purposes, but this currently
has no use in bevy.

More bits could be reserved for future features at the cost of bits for
the high component, so how much to reserve is up for discussion. Also,
naming of the struct and methods are also subject to further
bikeshedding and feedback.

Also, because IDs can have different variants, I wonder if
`Entity::from_bits` needs to return a `Result` instead of potentially
panicking on receiving an invalid ID.

PR is provided as an early WIP to obtain feedback and notes on whether
this approach is viable.

---

## Changelog

### Added

New `Identifier` struct for unifying IDs.

### Changed

`Entity` changed to use new `Identifier`/`IdentifierMask` as the
underlying ID logic.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: vero <email@atlasdostal.com>
2024-01-13 01:09:32 +00:00
Ixentus
5c6b7d5883
Add paused run condition (#11313)
# Objective

- It is common to run a system only when the clock is paused or not
paused, but this run condition doesn't exist.

## Solution

- Add the "paused" run condition.

---

## Changelog

- Systems can now be scheduled to run only if the clock is paused or not
using `.run_if(paused())` or `.run_if(not(paused()))`.

---------

Co-authored-by: radiish <cb.setho@gmail.com>
2024-01-12 22:18:57 +00:00
François
3d996639a0
Revert "Implement minimal reflection probes. (#10057)" (#11307)
# Objective

- Fix working on macOS, iOS, Android on main 
- Fixes #11281 
- Fixes #11282 
- Fixes #11283 
- Fixes #11299

## Solution

- Revert #10057
2024-01-12 20:41:51 +00:00
Elabajaba
64a15f1b10
Fix ssao only sampling mip 0 (#11292)
# Objective

Fixes https://github.com/bevyengine/bevy/issues/11222

## Solution

SSAO's sample_mip_level was always giving negative values because it was
in UV space (0..1) when it needed to be in pixel units (0..resolution).

Fixing it so it properly samples lower mip levels when appropriate is a
pretty large speedup (~3.2ms -> ~1ms at 4k, ~507us-> 256us at 1080p on a
6800xt), and I didn't notice any obvious visual quality differences.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-01-12 05:33:26 +00:00
NiseVoid
c4e479a2d4
Implement bounding volume types (#10946)
# Objective

Implement bounding volume trait and the 4 types from
https://github.com/bevyengine/bevy/issues/10570. I will add intersection
tests in a future PR.

## Solution

Implement mostly everything as written in the issue, except:
- Intersection is no longer a method on the bounding volumes, but a
separate trait.
- I implemented a `visible_area` since it's the most common usecase to
care about the surface that could collide with cast rays.
  - Maybe we want both?

---

## Changelog

- Added bounding volume types to bevy_math

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-01-10 23:18:51 +00:00
Jakob Hellermann
a657478675
resolve all internal ambiguities (#10411)
- ignore all ambiguities that are not a problem
- remove `.before(Assets::<Image>::track_assets),` that points into a
different schedule (-> should this be caught?)
- add some explicit orderings:
- run `poll_receivers` and `update_accessibility_nodes` after
`window_closed` in `bevy_winit::accessibility`
  - run `bevy_ui::accessibility::calc_bounds` after `CameraUpdateSystem`
- run ` bevy_text::update_text2d_layout` and `bevy_ui::text_system`
after `font_atlas_set::remove_dropped_font_atlas_sets`
- add `app.ignore_ambiguity(a, b)` function for cases where you want to
ignore an ambiguity between two independent plugins `A` and `B`
- add `IgnoreAmbiguitiesPlugin` in `DefaultPlugins` that allows
cross-crate ambiguities like `bevy_animation`/`bevy_ui`
- Fixes https://github.com/bevyengine/bevy/issues/9511

## Before
**Render**
![render_schedule_Render
dot](https://github.com/bevyengine/bevy/assets/22177966/1c677968-7873-40cc-848c-91fca4c8e383)

**PostUpdate**
![schedule_PostUpdate
dot](https://github.com/bevyengine/bevy/assets/22177966/8fc61304-08d4-4533-8110-c04113a7367a)

## After
**Render**
![render_schedule_Render
dot](https://github.com/bevyengine/bevy/assets/22177966/462f3b28-cef7-4833-8619-1f5175983485)
**PostUpdate**
![schedule_PostUpdate
dot](https://github.com/bevyengine/bevy/assets/22177966/8cfb3d83-7842-4a84-9082-46177e1a6c70)

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
Co-authored-by: François <mockersf@gmail.com>
2024-01-09 19:08:15 +00:00
Ian Kettlewell
13d3de8ee1
Remove unnecessary unsafe impls for WinitWindows on Wasm (#11270)
# Objective

In the past `winit:🪟:Window` was not Send + Sync on web.
https://github.com/rust-windowing/winit/pull/2834 made
`winit:🪟:Window` Sync + Send so Bevy's `unsafe impl` is no longer
necessary.

## Solution

Remove the unsafe impls.
2024-01-09 18:31:55 +00:00
Rob Parrett
69016885c2
Remove unused event-listener dependency (#11269)
# Objective

This dependency is seemingly no longer used directly after #7267.

Unfortunately, this doesn't fix us having versions of `event-listener`
in our tree.

Closes #10654

## Solution

Remove it, see if anything breaks.
2024-01-09 15:59:56 +00:00
François
0e61435521
mobile and webgpu: trigger redraw request when needed and improve window creation (#11245)
# Objective

- Since #11227, Bevy doesn't work on mobile anymore. Windows are not
created.

## Solution

- Create initial window on mobile after the initial `Resume` event.
macOS is included because it's excluded from the other initial window
creation and I didn't want it to feel alone. Also, it makes sense. this
is needed for Android

cfcb6885e3/crates/bevy_winit/src/lib.rs (L152)
- request redraw during plugin initialisation (needed for WebGPU)
- request redraw when receiving `AboutToWait` instead of at the end of
the event handler. request to redraw during a `RedrawRequested` event
are ignored on iOS
2024-01-09 15:41:46 +00:00
Stepan Koltsov
06bf928927
Option to enable deterministic rendering (#11248)
# Objective

Issue #10243: rendering multiple triangles in the same place results in
flickering.

## Solution

Considered these alternatives:
- `depth_bias` may not work, because of high number of entities, so
creating a material per entity is practically not possible
- rendering at slightly different positions does not work, because when
camera is far, float rounding causes the same issues (edit: assuming we
have to use the same `depth_bias`)
- considered implementing deterministic operation like
`query.par_iter().flat_map(...).collect()` to be used in
`check_visibility` system (which would solve the issue since query is
deterministic), and could not figure out how to make it as cheap as
current approach with thread-local collectors (#11249)

So adding an option to sort entities after `check_visibility` system
run.

Should not be too bad, because after visibility check, only a handful
entities remain.

This is probably not the only source of non-determinism in Bevy, but
this is one I could find so far. At least it fixes the repro example.

## Changelog

- `DeterministicRenderingConfig` option to enable deterministic
rendering

## Test

<img width="1392" alt="image"
src="https://github.com/bevyengine/bevy/assets/28969/c735bce1-3a71-44cd-8677-c19f6c0ee6bd">

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-01-09 00:46:01 +00:00
Stepan Koltsov
9813e39f90
Rustdoc examples for OrthographicProjection (#11031)
Minimal working examples are helpful.

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-01-09 00:08:58 +00:00
TimJentzsch
cf3105a0db
Add run conditions for executing a system after a delay (#11095)
# Objective

I want to run a system once after a given delay.

- First, I tried using the `on_timer` run condition, but it uses a
repeating timer, causing the system to run multiple times.
- Next, I tried combining the `on_timer` with the `run_once` run
condition. However, this causes the timer to *tick* only once, so the
system is never executed.

## Solution

- ~~Replace `on_timer` by `on_time_interval` and `on_real_timer` by
`on_real_time_interval` to clarify the meaning (the old ones are
deprecated to avoid a breaking change).~~ (Reverted according to
feedback)
- Add `once_after_delay` and `once_after_real_delay` to run the system
exactly once after the delay, using `TimerMode::Once`.
- Add `repeating_after_delay` and `repeating_after_real_delay` to run
the system indefinitely after the delay, using `Timer::finished` instead
of `Timer::just_finished`.

---

## Changelog

### Added

- `once_after_delay` and `once_after_real_delay` run conditions to run
the system exactly once after the delay, using `TimerMode::Once`.
- `repeating_after_delay` and `repeating_after_real_delay` run
conditions to run the system indefinitely after the delay, using
`Timer::finished` instead of `Timer::just_finished`.
2024-01-08 23:52:16 +00:00
Natalie Bonnibel Baker
b257fffef8
Change Entity::generation from u32 to NonZeroU32 for niche optimization (#9907)
# Objective

- Implements change described in
https://github.com/bevyengine/bevy/issues/3022
- Goal is to allow Entity to benefit from niche optimization, especially
in the case of Option<Entity> to reduce memory overhead with structures
with empty slots

## Discussion
- First PR attempt: https://github.com/bevyengine/bevy/pull/3029
- Discord:
https://discord.com/channels/691052431525675048/1154573759752183808/1154573764240093224

## Solution

- Change `Entity::generation` from u32 to NonZeroU32 to allow for niche
optimization.
- The reason for changing generation rather than index is so that the
costs are only encountered on Entity free, instead of on Entity alloc
- There was some concern with generations being used, due to there being
some desire to introduce flags. This was more to do with the original
retirement approach, however, in reality even if generations were
reduced to 24-bits, we would still have 16 million generations available
before wrapping and current ideas indicate that we would be using closer
to 4-bits for flags.
- Additionally, another concern was the representation of relationships
where NonZeroU32 prevents us using the full address space, talking with
Joy it seems unlikely to be an issue. The majority of the time these
entity references will be low-index entries (ie. `ChildOf`, `Owes`),
these will be able to be fast lookups, and the remainder of the range
can use slower lookups to map to the address space.
- It has the additional benefit of being less visible to most users,
since generation is only ever really set through `from_bits` type
methods.
- `EntityMeta` was changed to match
- On free, generation now explicitly wraps:
- Originally, generation would panic in debug mode and wrap in release
mode due to using regular ops.
- The first attempt at this PR changed the behavior to "retire" slots
and remove them from use when generations overflowed. This change was
controversial, and likely needs a proper RFC/discussion.
- Wrapping matches current release behaviour, and should therefore be
less controversial.
- Wrapping also more easily migrates to the retirement approach, as
users likely to exhaust the exorbitant supply of generations will code
defensively against aliasing and that defensive code is less likely to
break than code assuming that generations don't wrap.
- We use some unsafe code here when wrapping generations, to avoid
branch on NonZeroU32 construction. It's guaranteed safe due to how we
perform wrapping and it results in significantly smaller ASM code.
    - https://godbolt.org/z/6b6hj8PrM 

## Migration

- Previous `bevy_scene` serializations have a high likelihood of being
broken, as they contain 0th generation entities.

## Current Issues
 
- `Entities::reserve_generations` and `EntityMapper` wrap now, even in
debug - although they technically did in release mode already so this
probably isn't a huge issue. It just depends if we need to change
anything here?

---------

Co-authored-by: Natalie Baker <natalie.baker@advancednavigation.com>
2024-01-08 23:03:00 +00:00
Stepan Koltsov
dfa1a5e547
Explain where rendering is (#11018)
It was not easy to find. Add some pointers to the comment.
2024-01-08 23:02:46 +00:00
irate
ec14e946b8
Update glam, encase and hexasphere (#11082)
Update to `glam` 0.25, `encase` 0.7 and `hexasphere` to 10.0

## Changelog
Added the `FloatExt` trait to the `bevy_math` prelude which adds `lerp`,
`inverse_lerp` and `remap` methods to the `f32` and `f64` types.
2024-01-08 22:58:45 +00:00
Stepan Koltsov
c0f8338697
Better error message on incorrect asset label (#11254)
# Objective

When you have no idea what to put after `#` when loading an asset, error
message may help.

## Solution

Add all labels to the error message.

## Test plan

Modified `anti_alias` example to put incorrect label, the error is:

```
2024-01-08T07:41:25.462287Z ERROR bevy_asset::server: The file at 'models/FlightHelmet/FlightHelmet.gltf' does not contain the labeled asset 'Rrrr'; it contains the following 25 assets: 'Material0', 'Material1', 'Material2', 'Material3', 'Material4', 'Material5', 'Mesh0', 'Mesh0/Primitive0', 'Mesh1', 'Mesh1/Primitive0', 'Mesh2', 'Mesh2/Primitive0', 'Mesh3', 'Mesh3/Primitive0', 'Mesh4', 'Mesh4/Primitive0', 'Mesh5', 'Mesh5/Primitive0', 'Node0', 'Node1', 'Node2', 'Node3', 'Node4', 'Node5', 'Scene0'
```
2024-01-08 22:45:07 +00:00
James Liu
13570cd4c8
Minimize small allocations by dropping the tick Vecs from Resources (#11226)
# Objective
`Column` unconditionally requires three separate allocations: one for
the data, and two for the tick Vecs. The tick Vecs aren't really needed
for Resources, so we're allocating a bunch of one-element Vecs, and it
costs two extra dereferences when fetching/inserting/removing resources.

## Solution
Drop one level lower in `ResourceData` and directly store a `BlobVec`
and two `UnsafeCell<Tick>`s. This should significantly shrink
`ResourceData` (exchanging 6 usizes for 2 u32s), removes the need to
dereference two separate ticks when inserting/removing/fetching
resources, and can significantly decrease the number of small
allocations the ECS makes by default.

This tentatively might have a non-insignificant impact on the CPU cost
for rendering since we're constantly fetching resources in draw
functions, depending on how aggressively inlined the functions are.

This requires reimplementing some of the unsafe functions that `Column`
wraps, but it also allows us to delete a few Column APIs that were only
used for Resources, so the total amount of unsafe we're maintaining
shouldn't change significantly.

---------

Co-authored-by: Joseph <21144246+JoJoJet@users.noreply.github.com>
2024-01-08 22:39:47 +00:00
Joona Aalto
bcbb7bb9dd
Add new_and_length method to Direction2d and Direction3d (#11172)
# Objective

When creating a normalized direction from a vector, it can be useful to
get both the direction *and* the original length of the vector.

This came up when I was recreating some Parry APIs using bevy_math, and
doing it manually is quite painful. Nalgebra calls this method
[`Unit::try_new_and_get`](https://docs.rs/nalgebra/latest/nalgebra/base/struct.Unit.html#method.try_new_and_get).

## Solution

Add a `new_and_length` method to `Direction2d` and `Direction3d`.

Usage:

```rust
if let Ok((direction, length)) = Direction2d::new_and_length(Vec2::X * 10.0) {
    assert_eq!(direction, Vec2::X);
    assert_eq!(length, 10.0);
}
```

I'm open to different names, couldn't come up with a perfectly clear one
that isn't too long. My reasoning with the current name is that it's
like using `new` and calling `length` on the original vector.
2024-01-08 22:36:56 +00:00
Joseph
df2ba09989
Restore support for running fn EntityCommands on entities that might be despawned (#11107)
# Objective

In #9604 we removed the ability to define an `EntityCommand` as
`fn(Entity, &mut World)`. However I have since realized that `fn(Entity,
&mut World)` is an incredibly expressive and powerful way to define a
command for an entity that may or may not exist (`fn(EntityWorldMut)`
only works on entities that are alive).

## Solution

Support `EntityCommand`s in the style of `fn(Entity, &mut World)`, as
well as `fn(EntityWorldMut)`. Use a marker generic on the
`EntityCommand` trait to allow multiple impls.

The second commit in this PR replaces all of the internal command
definitions with ones using `fn` definitions. This is mostly just to
show off how expressive this style of command is -- we can revert this
commit if we'd rather avoid breaking changes.

---

## Changelog

Re-added support for expressively defining an `EntityCommand` as a
function that takes `Entity, &mut World`.

## Migration Guide

All `Command` types in `bevy_ecs`, such as `Spawn`, `SpawnBatch`,
`Insert`, etc., have been made private. Use the equivalent methods on
`Commands` or `EntityCommands` instead.
2024-01-08 22:32:28 +00:00
Connor King
1260b7bcf1
StateTransitionEvent (#11089)
# Objective

- Make it possible to react to arbitrary state changes
- this will be useful regardless of the other changes to states
currently being discussed

## Solution

- added `StateTransitionEvent<S>` struct
- previously, this would have been impossible:

```rs
#[derive(States, Eq, PartialEq, Hash, Copy, Clone, Default)]
enum MyState {
  #[default]
  Foo,
  Bar(MySubState),
}

enum MySubState {
  Spam,
  Eggs,
}

app.add_system(Update, on_enter_bar);

fn on_enter_bar(trans: EventReader<StateTransition<MyState>>){
  for (befoare, after) in trans.read() {
    match before, after {
      MyState::Foo, MyState::Bar(_) => info!("detected transition foo => bar");
      _, _ => ();
    }
  }
}
```

---

## Changelog

- Added
  - `StateTransitionEvent<S>` - Fired on state changes of `S`

## Migration Guide

N/A no breaking changes

---------

Co-authored-by: Federico Rinaldi <gisquerin@gmail.com>
2024-01-08 22:27:00 +00:00
Stepan Koltsov
8d9a0a883f
Mul<f32> for ScalingMode (#11030)
Complement to https://github.com/bevyengine/bevy/pull/11022: if
`OrthographicProjection.scale` is removed, this can be used instead.

CC @doonv @Davier
2024-01-08 22:24:32 +00:00
Stepan Koltsov
38ef170b86
Explain OrthographicProjection.scale (#11023)
Alternative to https://github.com/bevyengine/bevy/pull/11022.

(Also remove "in world units", it is probably a mistake.)
2024-01-08 22:22:03 +00:00
andriyDev
da485c29b3
Add reserve_handle to Assets. (#10939)
# Objective

Fixes #10938.

## Solution

Adds `reserve_handle` to `Assets`.

---

## Changelog

- Added `reserve_handle` to `Assets`.
2024-01-08 22:17:29 +00:00
Joona Aalto
a795de30b4
Use impl Into<A> for Assets::add (#10878)
# Motivation

When spawning entities into a scene, it is very common to create assets
like meshes and materials and to add them via asset handles. A common
setup might look like this:

```rust
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    commands.spawn(PbrBundle {
        mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
        material: materials.add(StandardMaterial::from(Color::RED)),
        ..default()
    });
}
```

Let's take a closer look at the part that adds the assets using `add`.

```rust
mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
material: materials.add(StandardMaterial::from(Color::RED)),
```

Here, "mesh" and "material" are both repeated three times. It's very
explicit, but I find it to be a bit verbose. In addition to being more
code to read and write, the extra characters can sometimes also lead to
the code being formatted to span multiple lines even though the core
task, adding e.g. a primitive mesh, is extremely simple.

A way to address this is by using `.into()`:

```rust
mesh: meshes.add(shape::Cube { size: 1.0 }.into()),
material: materials.add(Color::RED.into()),
```

This is fine, but from the names and the type of `meshes`, we already
know what the type should be. It's very clear that `Cube` should be
turned into a `Mesh` because of the context it's used in. `.into()` is
just seven characters, but it's so common that it quickly adds up and
gets annoying.

It would be nice if you could skip all of the conversion and let Bevy
handle it for you:

```rust
mesh: meshes.add(shape::Cube { size: 1.0 }),
material: materials.add(Color::RED),
```

# Objective

Make adding assets more ergonomic by making `Assets::add` take an `impl
Into<A>` instead of `A`.

## Solution

`Assets::add` now takes an `impl Into<A>` instead of `A`, so e.g. this
works:

```rust
    commands.spawn(PbrBundle {
        mesh: meshes.add(shape::Cube { size: 1.0 }),
        material: materials.add(Color::RED),
        ..default()
    });
```

I also changed all examples to use this API, which increases consistency
as well because `Mesh::from` and `into` were being used arbitrarily even
in the same file. This also gets rid of some lines of code because
formatting is nicer.

---

## Changelog

- `Assets::add` now takes an `impl Into<A>` instead of `A`
- Examples don't use `T::from(K)` or `K.into()` when adding assets

## Migration Guide

Some `into` calls that worked previously might now be broken because of
the new trait bounds. You need to either remove `into` or perform the
conversion explicitly with `from`:

```rust
// Doesn't compile
let mesh_handle = meshes.add(shape::Cube { size: 1.0 }.into()),

// These compile
let mesh_handle = meshes.add(shape::Cube { size: 1.0 }),
let mesh_handle = meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
```

## Concerns

I believe the primary concerns might be:

1. Is this too implicit?
2. Does this increase codegen bloat?

Previously, the two APIs were using `into` or `from`, and now it's
"nothing" or `from`. You could argue that `into` is slightly more
explicit than "nothing" in cases like the earlier examples where a
`Color` gets converted to e.g. a `StandardMaterial`, but I personally
don't think `into` adds much value even in this case, and you could
still see the actual type from the asset type.

As for codegen bloat, I doubt it adds that much, but I'm not very
familiar with the details of codegen. I personally value the user-facing
code reduction and ergonomics improvements that these changes would
provide, but it might be worth checking the other effects in more
detail.

Another slight concern is migration pain; apps might have a ton of
`into` calls that would need to be removed, and it did take me a while
to do so for Bevy itself (maybe around 20-40 minutes). However, I think
the fact that there *are* so many `into` calls just highlights that the
API could be made nicer, and I'd gladly migrate my own projects for it.
2024-01-08 22:14:43 +00:00
Patrick Walton
54a943d232
Implement minimal reflection probes. (#10057)
# Objective

This pull request implements *reflection probes*, which generalize
environment maps to allow for multiple environment maps in the same
scene, each of which has an axis-aligned bounding box. This is a
standard feature of physically-based renderers and was inspired by [the
corresponding feature in Blender's Eevee renderer].

## Solution

This is a minimal implementation of reflection probes that allows
artists to define cuboid bounding regions associated with environment
maps. For every view, on every frame, a system builds up a list of the
nearest 4 reflection probes that are within the view's frustum and
supplies that list to the shader. The PBR fragment shader searches
through the list, finds the first containing reflection probe, and uses
it for indirect lighting, falling back to the view's environment map if
none is found. Both forward and deferred renderers are fully supported.

A reflection probe is an entity with a pair of components, *LightProbe*
and *EnvironmentMapLight* (as well as the standard *SpatialBundle*, to
position it in the world). The *LightProbe* component (along with the
*Transform*) defines the bounding region, while the
*EnvironmentMapLight* component specifies the associated diffuse and
specular cubemaps.

A frequent question is "why two components instead of just one?" The
advantages of this setup are:

1. It's readily extensible to other types of light probes, in particular
*irradiance volumes* (also known as ambient cubes or voxel global
illumination), which use the same approach of bounding cuboids. With a
single component that applies to both reflection probes and irradiance
volumes, we can share the logic that implements falloff and blending
between multiple light probes between both of those features.

2. It reduces duplication between the existing *EnvironmentMapLight* and
these new reflection probes. Systems can treat environment maps attached
to cameras the same way they treat environment maps applied to
reflection probes if they wish.

Internally, we gather up all environment maps in the scene and place
them in a cubemap array. At present, this means that all environment
maps must have the same size, mipmap count, and texture format. A
warning is emitted if this restriction is violated. We could potentially
relax this in the future as part of the automatic mipmap generation
work, which could easily do texture format conversion as part of its
preprocessing.

An easy way to generate reflection probe cubemaps is to bake them in
Blender and use the `export-blender-gi` tool that's part of the
[`bevy-baked-gi`] project. This tool takes a `.blend` file containing
baked cubemaps as input and exports cubemap images, pre-filtered with an
embedded fork of the [glTF IBL Sampler], alongside a corresponding
`.scn.ron` file that the scene spawner can use to recreate the
reflection probes.

Note that this is intentionally a minimal implementation, to aid
reviewability. Known issues are:

* Reflection probes are basically unsupported on WebGL 2, because WebGL
2 has no cubemap arrays. (Strictly speaking, you can have precisely one
reflection probe in the scene if you have no other cubemaps anywhere,
but this isn't very useful.)

* Reflection probes have no falloff, so reflections will abruptly change
when objects move from one bounding region to another.

* As mentioned before, all cubemaps in the world of a given type
(diffuse or specular) must have the same size, format, and mipmap count.

Future work includes:

* Blending between multiple reflection probes.

* A falloff/fade-out region so that reflected objects disappear
gradually instead of vanishing all at once.

* Irradiance volumes for voxel-based global illumination. This should
reuse much of the reflection probe logic, as they're both GI techniques
based on cuboid bounding regions.

* Support for WebGL 2, by breaking batches when reflection probes are
used.

These issues notwithstanding, I think it's best to land this with
roughly the current set of functionality, because this patch is useful
as is and adding everything above would make the pull request
significantly larger and harder to review.

---

## Changelog

### Added

* A new *LightProbe* component is available that specifies a bounding
region that an *EnvironmentMapLight* applies to. The combination of a
*LightProbe* and an *EnvironmentMapLight* offers *reflection probe*
functionality similar to that available in other engines.

[the corresponding feature in Blender's Eevee renderer]:
https://docs.blender.org/manual/en/latest/render/eevee/light_probes/reflection_cubemaps.html

[`bevy-baked-gi`]: https://github.com/pcwalton/bevy-baked-gi

[glTF IBL Sampler]: https://github.com/KhronosGroup/glTF-IBL-Sampler
2024-01-08 22:09:17 +00:00
Kyle
2847cc6933
Don't auto create assets folder (#11218)
# Objective

- Don't automatically create an assets folder
- resolves #11208

## Solution

- Removes directory creation from file reader.
- Clearer panic when using file watcher and asset folder doesn't exist

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Nicola Papale <nicopap@users.noreply.github.com>
2024-01-08 21:45:26 +00:00
re0312
101037d0c2
update Outdated comment (#11243)
# Objective

- since #9236 queue_mesh_bind_group has been renamed to
prepare_mesh_bind_group,but the comment referring to it has not been
updated. .
2024-01-07 15:02:43 +00:00
thebluefish
cfcb6885e3
Change SceneSpawner::spawn_dynamic_sync to return InstanceID (#11239)
# Objective

`SceneSpawner::spawn_dynamic_sync` currently returns `()` on success,
which is inconsistent with the other `SceneSpawner::spawn_` methods that
all return an `InstanceId`. We need this ID to do useful work with the
newly-created data.

## Solution

Updated `SceneSpawner::spawn_dynamic_sync` to return `Result<InstanceId,
SceneSpawnError>` instead of `Result<(), SceneSpawnError>`
2024-01-06 22:26:32 +00:00
Joona Aalto
0349809420
Add libm feature to bevy_math (#11238)
# Objective

Different platforms use their own implementations of several
mathematical functions (especially transcendental functions like sin,
cos, tan, atan, and so on) to provide hardware-level optimization using
intrinsics. This is good for performance, but bad when you expect
consistent outputs across machines.

[`libm`](https://github.com/rust-lang/libm) is a widely used crate that
provides mathematical functions that don't use intrinsics like `std`
functions. This allows bit-for-bit deterministic math across hardware,
which is crucial for things like cross-platform deterministic physics
simulation.

Glam has the `libm` feature for using [`libm` for the
math](d2871a151b/src/f32/math.rs (L35))
in its own types. This would be nice to expose as a feature in
`bevy_math`.

## Solution

Add `libm` feature to `bevy_math`. We could name it something like
`enhanced-determinism`, but this wouldn't be accurate for the rest of
Bevy, so I think just `libm` is more fitting and explicit.
2024-01-06 22:01:57 +00:00
Nicola Papale
79021c78c6
Fix perf degradation on web builds (#11227)
# Objective

- Since #10702, the way bevy updates the window leads to major slowdowns
as seen in
    - #11122 
    - #11220
- Slow is bad, furthermore, _very_ slow is _very_ bad. We should fix
this issue.

## Solution

- Move the app update code into the `Event::WindowEvent { event:
WindowEvent::RedrawRequested }` branch of the event loop.
- Run `window.request_redraw()` When `runner_state.redraw_requested`
- Instead of swapping `ControlFlow` between `Poll` and `Wait`, we always
keep it at `Wait`, and use `window.request_redraw()` to schedule an
immediate call to the event loop.
- `runner_state.redraw_requested` is set to `true` when
`UpdateMode::Continuous` and when a `RequestRedraw` event is received.
- Extract the redraw code into a separate function, because otherwise
I'd go crazy with the indentation level.
- Fix #11122.

## Testing

I tested the WASM builds as follow:

```sh
cargo run -p build-wasm-example -- --api webgl2 bevymark
python -m http.server --directory examples/wasm/ 8080
# Open browser at http://localhost:8080
```

On main, even spawning a couple sprites is super choppy. Even if it says
"300 FPS". While on this branch, it is smooth as butter.

I also found that it fixes all choppiness on window resize (tested on
Linux/X11). This was another issue from #10702 IIRC.

So here is what I tested:

- On `wasm`: `many_foxes` and `bevymark`, with `argh::from_env()`
commented out, otherwise we get a cryptic error.
- Both with `PresentMode::AutoVsync` and `PresentMode::AutoNoVsync`
  - On main, it is consistently choppy.
- With this PR, the visible frame rate is consistent with the diagnostic
numbers
- On native (linux/x11) I ran similar tests, making sure that
`AutoVsync` limits to monitor framerate, and `AutoNoVsync` doesn't.

## Future work

Code could be improved, I wanted a quick solution easy to review, but we
really need to make the code more accessible.

- #9768
- ~~**`WinitSettings::desktop_app()` is completely borked.**~~ actually
broken on main as well

### Review guide

Consider enable the non-whitespace diff to see the _real_ change set.
2024-01-06 19:40:13 +00:00
Stepan Koltsov
a35a151f47
Fix integer overflow in BlobVec::reserve_exact (#11234)
# Objective

When `BlobVec::reserve` is called with an argument causing capacity
overflow, in release build capacity overflow is ignored, and capacity is
decreased.

I'm not sure it is possible to exploit this issue using public API of
`bevy_ecs`, but better fix it anyway.

## Solution

Check for capacity overflow.
2024-01-06 17:31:01 +00:00
François
425570aa75
assets should be kept on CPU by default (#11212)
# Objective

- Since #10520, assets are unloaded from RAM by default. This breaks a
number of scenario:
  - using `load_folder`
- loading a gltf, then going through its mesh to transform them /
compute a collider / ...
- any assets/subassets scenario should be `Keep` as you can't know what
the user will do with the assets
  - android suspension, where GPU memory is unloaded

- Alternative to #11202 

## Solution

- Keep assets on CPU memory by default
2024-01-05 05:53:47 +00:00
Mateusz Wachowiak
759b3985d8
Extend Touches with clear and reset methods (#10930)
# Objective

- Resolves #10913.
- Extend `Touches` with methods that are implemented on `ButtonInput`.

## Solution

- Add function `clear_just_pressed` that clears the `just_pressed` state
of the touch input.
- Add function `clear_just_released` that clears the `just_released`
state of the touch input.
- Add function `clear_just_canceled` that clears the `just_canceled`
state of the touch input.
- Add function `release` that changes state of the touch input from
`pressed` to `just_released`.
- Add function `release_all` that changes state of every touch input
from `pressed` to `just_released`
- Add function `clear` that clears `just_pressed`, `just_released` and
`just_canceled` data for every input.
- Add function `reset_all` that clears `pressed`, `just_pressed`,
`just_released` and `just_canceled` data for every input.
- Add tests for functions above.
2024-01-04 23:13:29 +00:00
Stepan Koltsov
cf70f53227
Fix integer overflow in BlobVec::push for ZST (#10799)
`reserve_exact` is no-op for ZST because `self.item_layout.size() > 0`
is always `false`.


daa8bf20df/crates/bevy_ecs/src/storage/blob_vec.rs (L112-L120)

Then in `push` we just increase `.len` ignoring integer overflow.


daa8bf20df/crates/bevy_ecs/src/storage/blob_vec.rs (L232-L237)
2024-01-04 21:32:05 +00:00
Stepan Koltsov
cc2a77b5c5
Explain Camera physical size is in pixel (#11189)
# Objective

It may be not be obviously clear what is physical size. Is it inches? Is
it scaled somehow?

## Solution

Add rustdoc comments.
2024-01-04 18:28:36 +00:00
Adam
fe68005f71
Implement TypePath for EntityHash (#11195)
# Objective

- Fix #11117 by implementing `Reflect` for `EntityHashMap`

## Solution

- By implementing `TypePath` for `EntityHash`, Bevy will automatically
implement `Reflect` for `EntityHashMap`

---

## Changelog

- `TypePath` is implemented for `EntityHash`
- A test called `entity_hashmap_should_impl_reflect` was created to
verify that #11117 was solved.
2024-01-04 18:28:31 +00:00
Torstein Grindvik
99c43fabdf
Usability methods for RenderTargets and image handles (#10736)
# Objective

In my code I use a lot of images as render targets.
I'd like some convenience methods for working with this type.

## Solution

- Allow `.into()` to construct a `RenderTarget`
- Add `.as_image()` 

---

## Changelog

### Added

- `RenderTarget` can be constructed via `.into()` on a `Handle<Image>`
- `RenderTarget` new method: `as_image`

---------

Signed-off-by: Torstein Grindvik <torstein.grindvik@muybridge.com>
Co-authored-by: Torstein Grindvik <torstein.grindvik@muybridge.com>
2024-01-04 17:01:04 +00:00
Chia-Hsiang Cheng
93c7e7cf4d
Rename "AddChild" to "PushChild" (#11194)
# Objective

- Fixes #11187 

## Solution

- Rename the `AddChild` struct to `PushChild`
- Rename the `AddChildInPlace` struct to `PushChildInPlace`

## Migration Guide

The struct `AddChild` has been renamed to `PushChild`, and the struct
`AddChildInPlace` has been renamed to `PushChildInPlace`.
2024-01-04 16:06:14 +00:00
François
5511483408
missed negation during accessibility refactor (#11206)
# Objective

- Since #10911, example `button` crashes when clicking the button
```
thread 'main' panicked at .cargo/registry/src/index.crates.io-6f17d22bba15001f/accesskit_consumer-0.16.1/src/tree.rs:139:9:
assertion `left == right` failed
  left: 1
 right: 0
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Encountered a panic in system `bevy_winit::accessibility::update_accessibility_nodes`!
Encountered a panic in system `bevy_app::main_schedule::Main::run_main`!
```


## Solution

- Re-add lost negation
2024-01-03 23:14:22 +00:00
Atomei Alexandru
3f535d54eb
Made the remaining types from bevy_ui to reflect the Default trait if… (#11199)
# Objective

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

## Solution

- Made the remaining types from bevy_ui that do not reflect the Default
trait to do it if possible.
2024-01-03 18:57:05 +00:00
pablo-lua
41c362051c
Create serialize feature for bevy_ui (#11188)
# Objective

- Fixes #11119  

## Solution

- Creation of the serialize feature to ui

---

## Changelog

### Changed
- Changed all the structs that implement Serialize and Deserialize to
only implement when feature is on

## Migration Guide

- If you want to use serialize and deserialize with types from bevy_ui,
you need to use the feature serialize in your TOML
```toml
[dependencies.bevy]
features = ["serialize"]
```
2024-01-03 17:52:16 +00:00
Chia-Hsiang Cheng
b6da40cfe6
Print a warning for un-applied commands being dropped from a CommandQueue (#11146)
# Objective

- Fixes #11125 
## Solution

Add a warning for un-applied commands to the `drop` function.
2024-01-03 15:32:57 +00:00
TheBlckbird
19f5222c29
Fix typos plugin.rs (#11193)
# Objective

- There are multiple grammar mistakes in the `plugin.rs` file.

## Solution

- Corrects the grammar and spelling in the docs of `plugin.rs`
2024-01-03 15:30:35 +00:00
Eye
07cd955c02
Fix: Gizmos crash due to the persistence policy being set to Unload. Change it to Keep (#11192)
# Objective

Fixes Gizmos crash due to the persistence policy being set to `Unload`

## Solution

Change it to `Keep`

Co-authored-by: rqg <ranqingguo318@gmail.com>
2024-01-03 11:03:18 +00:00
Patrick Walton
5697fee3ad
Bump the vertex attribute index for prepass joints. (#11191)
This was missed in #10231.

Fixes #11190.
2024-01-03 10:35:39 +00:00
JMS55
44424391fe
Unload render assets from RAM (#10520)
# Objective
- No point in keeping Meshes/Images in RAM once they're going to be sent
to the GPU, and kept in VRAM. This saves a _significant_ amount of
memory (several GBs) on scenes like bistro.
- References
  - https://github.com/bevyengine/bevy/pull/1782
  - https://github.com/bevyengine/bevy/pull/8624 

## Solution
- Augment RenderAsset with the capability to unload the underlying asset
after extracting to the render world.
- Mesh/Image now have a cpu_persistent_access field. If this field is
RenderAssetPersistencePolicy::Unload, the asset will be unloaded from
Assets<T>.
- A new AssetEvent is sent upon dropping the last strong handle for the
asset, which signals to the RenderAsset to remove the GPU version of the
asset.

---

## Changelog
- Added `AssetEvent::NoLongerUsed` and
`AssetEvent::is_no_longer_used()`. This event is sent when the last
strong handle of an asset is dropped.
- Rewrote the API for `RenderAsset` to allow for unloading the asset
data from the CPU.
- Added `RenderAssetPersistencePolicy`.
- Added `Mesh::cpu_persistent_access` for memory savings when the asset
is not needed except for on the GPU.
- Added `Image::cpu_persistent_access` for memory savings when the asset
is not needed except for on the GPU.
- Added `ImageLoaderSettings::cpu_persistent_access`.
- Added `ExrTextureLoaderSettings`.
- Added `HdrTextureLoaderSettings`.

## Migration Guide
- Asset loaders (GLTF, etc) now load meshes and textures without
`cpu_persistent_access`. These assets will be removed from
`Assets<Mesh>` and `Assets<Image>` once `RenderAssets<Mesh>` and
`RenderAssets<Image>` contain the GPU versions of these assets, in order
to reduce memory usage. If you require access to the asset data from the
CPU in future frames after the GLTF asset has been loaded, modify all
dependent `Mesh` and `Image` assets and set `cpu_persistent_access` to
`RenderAssetPersistencePolicy::Keep`.
- `Mesh` now requires a new `cpu_persistent_access` field. Set it to
`RenderAssetPersistencePolicy::Keep` to mimic the previous behavior.
- `Image` now requires a new `cpu_persistent_access` field. Set it to
`RenderAssetPersistencePolicy::Keep` to mimic the previous behavior.
- `MorphTargetImage::new()` now requires a new `cpu_persistent_access`
parameter. Set it to `RenderAssetPersistencePolicy::Keep` to mimic the
previous behavior.
- `DynamicTextureAtlasBuilder::add_texture()` now requires that the
`TextureAtlas` you pass has an `Image` with `cpu_persistent_access:
RenderAssetPersistencePolicy::Keep`. Ensure you construct the image
properly for the texture atlas.
- The `RenderAsset` trait has significantly changed, and requires
adapting your existing implementations.
  - The trait now requires `Clone`.
- The `ExtractedAsset` associated type has been removed (the type itself
is now extracted).
  - The signature of `prepare_asset()` is slightly different
- A new `persistence_policy()` method is now required (return
RenderAssetPersistencePolicy::Unload to match the previous behavior).
- Match on the new `NoLongerUsed` variant for exhaustive matches of
`AssetEvent`.
2024-01-03 03:31:04 +00:00
Charles Bournhonesque
02755086e8
Add static assertions to bevy_utils for compile-time checks (#11182)
# Objective

- We want to use `static_assertions` to perform precise compile time
checks at testing time. In this PR, we add those checks to make sure
that `EntityHashMap` and `PreHashMap` are `Clone` (and we replace the
more clumsy previous tests)
- Fixes #11181 

(will need to be rebased once
https://github.com/bevyengine/bevy/pull/11178 is merged)

---------

Co-authored-by: Charles Bournhonesque <cbournhonesque@snapchat.com>
2024-01-02 22:08:30 +00:00
Patrick Walton
dd14f3a477
Implement lightmaps. (#10231)
![Screenshot](https://i.imgur.com/A4KzWFq.png)

# Objective

Lightmaps, textures that store baked global illumination, have been a
mainstay of real-time graphics for decades. Bevy currently has no
support for them, so this pull request implements them.

## Solution

The new `Lightmap` component can be attached to any entity that contains
a `Handle<Mesh>` and a `StandardMaterial`. When present, it will be
applied in the PBR shader. Because multiple lightmaps are frequently
packed into atlases, each lightmap may have its own UV boundaries within
its texture. An `exposure` field is also provided, to control the
brightness of the lightmap.

Note that this PR doesn't provide any way to bake the lightmaps. That
can be done with [The Lightmapper] or another solution, such as Unity's
Bakery.

---

## Changelog

### Added
* A new component, `Lightmap`, is available, for baked global
illumination. If your mesh has a second UV channel (UV1), and you attach
this component to the entity with that mesh, Bevy will apply the texture
referenced in the lightmap.

[The Lightmapper]: https://github.com/Naxela/The_Lightmapper

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2024-01-02 20:38:47 +00:00
Federico Rinaldi
2440aa8475
Add bevy_hierarchy Crate and plugin documentation (#10951)
This PR is part of a project aimed at improving the API documentation of
`bevy_hierarchy`. Other PRs will be based on this.

This PR in particular is also an experiment in providing a high level
overview of the tools provided by a Bevy plugin/crate. It also provides
general information about universal invariants, so statement repetition
in crate items can be dramatically reduced.

## Other changes

The other PRs of this project that expand on this one:

- #10952
- #10953
- #10954
- #10955
- #10956
- #10957

---------

Co-authored-by: GitGhillie <jillisnoordhoek@gmail.com>
2024-01-02 19:40:14 +00:00
Charles Bournhonesque
ab10e85558
Enable cloning EntityHashMap and PreHashMap (#11178)
# Objective

- `EntityHashMap`, `EntityHashSet` and `PreHashMap` are currently not
Cloneable because of a missing trivial `Clone` bound for `EntityHash`
and `PreHash`. This PR makes them Cloneable.

(the parent struct `hashbrown::HashMap` requires the `HashBuilder` to be
`Clone` for the `HashMap` to be `Clone`, see:
https://github.com/rust-lang/hashbrown/blob/master/src/map.rs#L195)


## Solution

- Add a `Clone` bound to `PreHash` and `EntityHash`

---------

Co-authored-by: Charles Bournhonesque <cbournhonesque@snapchat.com>
2024-01-02 18:11:47 +00:00
Joona Aalto
536a7bd810
Add approx feature to bevy_math (#11176)
# Objective

`bevy_math` re-exports Glam, but doesn't have a feature for enabling
`approx` for it. Many projects (including some of Bevy's own crates)
need `approx`, and it'd be nice if you didn't have to manually add Glam
to specify the feature for it.

## Solution

Add an `approx` feature to `bevy_math`.
2024-01-02 18:10:44 +00:00
Joona Aalto
2c5439b25e
Add constants for Direction2d and Direction3d (#11180)
# Objective

I often need a direction along one of the cartesian XYZ axes, and it
currently requires e.g. `Direction2d::from_normalized(Vec2::X)`, which
isn't ideal.

## Solution

Add direction constants that are the same as the ones on Glam types. I
also copied the doc comment format "A unit vector pointing along the ...
axis", but I can change it if there's a better wording for directions.
2024-01-02 17:00:23 +00:00
Joona Aalto
6086d4193e
Implement Neg for Direction2d and Direction3d (#11179)
# Objective

I frequently encounter cases where I need to get the opposite direction.
This currently requires something like
`Direction2d::from_normalized(-*direction)`, which is very inconvenient.

## Solution

Implement `Neg` for `Direction2d` and `Direction3d`.
2024-01-02 16:46:03 +00:00
Miles Silberling-Cook
4034740396
Add window entity to TouchInput events (#11128)
# Objective

If you have multiple windows, there is no way to determine which window
a `TouchInput` event applies to. This fixes that.

## Solution

- Add the window entity directly to `TouchInput`, just like the other
input events.
- Fixes #6011.

## Migration Guide

+ Add a `window` field when constructing or destructuring a `TouchInput`
struct.
2024-01-02 03:03:05 +00:00
Brian Reavis
846a871cb2
Export tonemapping_pipeline_key (2d), alpha_mode_pipeline_key (#11166)
This expands upon https://github.com/bevyengine/bevy/pull/11134.

I found myself needing `tonemapping_pipeline_key` for some custom 2d
draw functions. #11134 exported the 3d version of
`tonemapping_pipeline_key` and this PR exports the 2d version. I also
made `alpha_mode_pipeline_key` public for good measure.
2024-01-01 23:57:12 +00:00
Stepan Koltsov
443b64a612
Print to stderr from panic handler in LogPlugin (#11170)
# Objective

When panic handler prints to stdout instead of stderr, I've observed two
outcomes with this PR test #11169:
- Sometimes output is mixed up, so it is not clear where one record ends
and another stards
- Sometimes output is lost

## Solution

Print to stderr.

## Changelog

- Panic handler in `LogPlugin` writes to stderr instead of stdin.
2024-01-01 17:10:20 +00:00
Stepan Koltsov
6bc2686a7a
impl ExclusiveSystemParam for SystemName (#11163)
# Objective

`SystemName` might be useful in systems which accept `&mut World`.

## Solution

- `impl ExclusiveSystemParam for SystemName`
- move `SystemName` into a separate file, because it no longer belongs
to a file which defines `SystemParam`
- add a test for new impl, and for existing impl

## Changelog

- `impl ExclusiveSystemParam for SystemName`
2024-01-01 17:08:29 +00:00
Marco Buono
c2ab3a0402
Do not load prepass normals for transmissive materials (#11140)
Turns out whenever a normal prepass was active (which includes whenever
you use SSAO) we were attempting to read the normals from the prepass
for the specular transmissive material. Since transmissive materials
don't participate in the prepass (unlike opaque materials) we were
reading the normals from “behind” the mesh, producing really weird
visual results.

# Objective

- Fixes #11112.

## Solution

- We introduce a new `READS_VIEW_TRANSMISSION_TEXTURE` mesh pipeline
key;
- We set it whenever the material properties has the
`reads_view_transmission_texture` flag set; (i.e. the material is
transmissive)
- If this key is set we prevent the reading of normals from the prepass,
by not setting the `LOAD_PREPASS_NORMALS` shader def.

---

## Changelog

### Fixed

- Specular transmissive materials no longer attempt to erroneously load
prepass normals, and now work correctly even with the normal prepass
active (e.g. when using SSAO)
2024-01-01 17:04:20 +00:00
Stepan Koltsov
17ef73199b
Fix Mesh::ATTRIBUTE_UV_0 documentation (#11110)
Comment incorrect suggests that texture is clamped outside of `0..=1`
range, while it can actually be configured.

CC https://github.com/bevyengine/bevy/pull/11109
2024-01-01 16:58:48 +00:00
Tygyh
55c9958dd0
refactor collide code (Adopted) (#11106)
# Objective

- Refactor collide code and add tests.

## Solution

- Rebase the changes made in #4485.

Co-authored-by: Eduardo Canellas de Oliveira <eduardo.canellas@bemobi.com>
2024-01-01 16:57:27 +00:00
Adam
8baefa1570
Implement Deref and DerefMut for In (#11104)
# Objective

Implement Deref and DerefMut for In<T>

makes it so the user doesn't have to add ".0" in most cases
2024-01-01 16:55:07 +00:00
Kees van Beilen
2fd0043cfd
Fixed Typo in the description of EntityMut (#11103)
# Objective
Fix a typo in the description of the  `EntityMut` struct
2024-01-01 16:51:25 +00:00
Doonv
189ceaf0d3
Replace or document ignored doctests (#11040)
# Objective

There are a lot of doctests that are `ignore`d for no documented reason.
And that should be fixed.

## Solution

I searched the bevy repo with the regex ` ```[a-z,]*ignore ` in order to
find all `ignore`d doctests. For each one of the `ignore`d doctests, I
did the following steps:
1. Attempt to remove the `ignored` attribute while still passing the
test. I did this by adding hidden dummy structs and imports.
2. If step 1 doesn't work, attempt to replace the `ignored` attribute
with the `no_run` attribute while still passing the test.
3. If step 2 doesn't work, keep the `ignored` attribute but add
documentation for why the `ignored` attribute was added.

---------

Co-authored-by: François <mockersf@gmail.com>
2024-01-01 16:50:56 +00:00
capt-glorypants
ffded5b78e
Rename ArchetypeEntity::entity into ArchetypeEntity::id (#11118)
# Objective

Fixes #11050

Rename ArchetypeEntity::entity to ArchetypeEntity::id to be consistent
with `EntityWorldMut`, `EntityMut` and `EntityRef`.

## Migration Guide

The method `ArchetypeEntity::entity` has been renamed to
`ArchetypeEntity::id`
2024-01-01 16:12:24 +00:00
pablo-lua
bf0be9cc2c
Remove little warn on bevy_ecs (#11149)
# Objective

- There is an warning about non snake case on system_param.rs generated
by a macro

## Solution

- Allow non snake case on the function at fault
2024-01-01 16:03:25 +00:00
Stepan Koltsov
4fba03b529
impl ExclusiveSystemParam for PhantomData (#11153)
# Objective

Implement `ExclusiveSystemParam` for `PhantomData`.

For the same reason `SystemParam` impl exists: to simplify writing
generic code.


786abbf3f5/crates/bevy_ecs/src/system/system_param.rs (L1557)

Also for consistency.

## Solution

`impl ExclusiveSystemParam for PhantomData`.

## Changelog
Added: PhantomData<T> now implements ExclusiveSystemParam.
2024-01-01 16:02:21 +00:00
Stepan Koltsov
9f397d0cb6
impl ExclusiveSystemParam for WorldId (#11164)
# Objective

Mostly for consistency.

## Solution

```rust
impl ExclusiveSystemParam for WorldId
```

- Also add a test for `SystemParam for WorldId`

## Changelog
Added: Worldd now implements ExclusiveSystemParam.
2024-01-01 15:59:53 +00:00
François
71adb77a2e
support all types of animation interpolation from gltf (#10755)
# Objective

- Support step and cubic spline interpolation from gltf

## Solution

- Support step and cubic spline interpolation from gltf

Tested with
https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0/InterpolationTest
expected: 

![](https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/InterpolationTest/screenshot/screenshot.gif)
result: 

![output](https://github.com/bevyengine/bevy/assets/8672791/e7f1afd5-20c9-4921-97d4-8d0c82203068)

---

## Migration Guide

When manually specifying an animation `VariableCurve`, the interpolation
type must be specified:

- Bevy 0.12
```rust
        VariableCurve {
            keyframe_timestamps: vec![0.0, 1.0, 2.0, 3.0, 4.0],
            keyframes: Keyframes::Rotation(vec![
                Quat::IDENTITY,
                Quat::from_axis_angle(Vec3::Y, PI / 2.),
                Quat::from_axis_angle(Vec3::Y, PI / 2. * 2.),
                Quat::from_axis_angle(Vec3::Y, PI / 2. * 3.),
                Quat::IDENTITY,
            ]),
        },
```

- Bevy 0.13
```rust
        VariableCurve {
            keyframe_timestamps: vec![0.0, 1.0, 2.0, 3.0, 4.0],
            keyframes: Keyframes::Rotation(vec![
                Quat::IDENTITY,
                Quat::from_axis_angle(Vec3::Y, PI / 2.),
                Quat::from_axis_angle(Vec3::Y, PI / 2. * 2.),
                Quat::from_axis_angle(Vec3::Y, PI / 2. * 3.),
                Quat::IDENTITY,
            ]),
            interpolation: Interpolation::Linear,
        },
```
2023-12-31 18:01:50 +00:00
JMS55
70b0eacc3b
Keep track of when a texture is first cleared (#10325)
# Objective
- Custom render passes, or future passes in the engine (such as
https://github.com/bevyengine/bevy/pull/10164) need a better way to know
and indicate to the core passes whether the view color/depth/prepass
attachments have been cleared or not yet this frame, to know if they
should clear it themselves or load it.

## Solution

- For all render targets (depth textures, shadow textures, prepass
textures, main textures) use an atomic bool to track whether or not each
texture has been cleared this frame. Abstracted away in the new
ColorAttachment and DepthAttachment wrappers.

---

## Changelog
- Changed `ViewTarget::get_color_attachment()`, removed arguments.
- Changed `ViewTarget::get_unsampled_color_attachment()`, removed
arguments.
- Removed `Camera3d::clear_color`.
- Removed `Camera2d::clear_color`.
- Added `Camera::clear_color`.
- Added `ExtractedCamera::clear_color`.
- Added `ColorAttachment` and `DepthAttachment` wrappers.
- Moved `ClearColor` and `ClearColorConfig` from
`bevy::core_pipeline::clear_color` to `bevy::render::camera`.
- Core render passes now track when a texture is first bound as an
attachment in order to decide whether to clear or load it.

## Migration Guide
- Remove arguments to `ViewTarget::get_color_attachment()` and
`ViewTarget::get_unsampled_color_attachment()`.
- Configure clear color on `Camera` instead of on `Camera3d` and
`Camera2d`.
- Moved `ClearColor` and `ClearColorConfig` from
`bevy::core_pipeline::clear_color` to `bevy::render::camera`.
- `ViewDepthTexture` must now be created via the `new()` method

---------

Co-authored-by: vero <email@atlasdostal.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-12-31 00:37:37 +00:00
JMS55
3d3a065820
Misc cleanup (#11134)
Re-exports a few types/functions I need that have no reason to be
private, and some minor code quality changes.
2023-12-30 23:27:48 +00:00
Mike
786abbf3f5
Fix ci xvfb (#11143)
# Objective

Fix ci hang, so we can merge pr's again.

## Solution

- switch ppa action to use mesa stable versions
https://launchpad.net/~kisak/+archive/ubuntu/turtle
- use commit from #11123

---------

Co-authored-by: Stepan Koltsov <stepan.koltsov@gmail.com>
2023-12-30 09:07:31 +00:00
Stepan Koltsov
ac58a5fe57
Better doc for SystemName (#11084)
Compared to [current
documentation](https://docs.rs/bevy/latest/bevy/ecs/system/struct.SystemName.html)
it is now immediately clear that it is `SystemParam` readily available
to user, and not just some accidentally exposed internal data type.
2023-12-25 05:09:15 +00:00
radiish
13feac6721
reflect: maximally relax TypePath bounds (#11037)
# Objective

- Provides an alternate solution to the one implemented in #10791
without breaking changes.

## Solution

- Changes the bounds of macro-generated `TypePath` implementations to
universally ignore the types of fields, rather than use the same bounds
as other implementations. I think this is a more holistic solution than
#10791 because it totally erases the finicky bounds we currently
generate, helping to untangle the reflection trait system.
2023-12-24 17:45:46 +00:00
Stepan Koltsov
c6b32a2140
Explain EventWriter limits concurrency (#11063)
Co-authored-by: François <mockersf@gmail.com>
Co-authored-by: James Liu <contact@jamessliu.com>
2023-12-24 17:45:21 +00:00
daxpedda
dc698f0174
Use WindowBuilder::with_append() to append canvas (#11065)
# Objective

Replace the canvas appending code with a simpler version provided by
Winit v0.29.

Related: #11052.

## Solution

Use
[`WindowBuilder::with_append()`](https://docs.rs/winit/0.29.5/wasm32-unknown-unknown/winit/platform/web/trait.WindowBuilderExtWebSys.html#tymethod.with_append).
2023-12-24 17:44:50 +00:00
Tygyh
1568d4a415
Reorder impl to be the same as the trait (#11076)
# Objective

- Make the implementation order consistent between all sources to fit
the order in the trait.

## Solution

- Change the implementation order.
2023-12-24 17:43:55 +00:00
Tygyh
7b8305e5b4
Remove unnecessary parens (#11075)
# Objective

- Increase readability.

## Solution

- Remove unnecessary parens.
2023-12-24 17:43:01 +00:00
David Cosby
42b737878f
Re-export smallvec crate from bevy_utils (#11006)
Matches versioning & features from other Cargo.toml files in the
project.

# Objective
Resolves #10932 

## Solution
Added smallvec to the bevy_utils cargo.toml and added a line to
re-export the crate. Target version and features set to match what's
used in the other bevy crates.
2023-12-24 15:35:09 +00:00
Anish Bhobe
7374e58e78
Register Camera types. (#11069)
# Objective

Register and Serialize `Camera3dDepthTextureUsage` and
`ScreenSpaceTransmissionQuality`.

Fixes: #11036

## Solution

Added the relevant derives for reflection and serialization and type
registrations.
2023-12-23 17:33:37 +00:00
Guillaume Gomez
e360763b47
Update sysinfo version to 0.30.0 (#11071)
New version comes with a lot of improvements. Full list is available
there:
https://github.com/GuillaumeGomez/sysinfo/blob/master/migration_guide.md
2023-12-23 17:33:15 +00:00
Tygyh
22acd62dbf
Replace calculation with function call (#11077)
# Objective

- Simplify execution.

## Solution

- Replace degrees to radians calculation with function call.
2023-12-23 17:32:26 +00:00
ickshonpe
efb4fa5d61
Give UI nodes with Display::None an empty clipping rect (#10942)
# Objective
Outlines are drawn for UI nodes with `Display::None` set and their
descendants. They should not be visible.

## Solution

Make all Nodes with `Display::None` inherit an empty clipping rect,
ensuring that the outlines are not visible.

Fixes #10940

---

## Changelog
* In `update_clipping_system` if a node has `Display::None` set, clip
the entire node and all its descendants by replacing the inherited clip
with a default rect (which is empty)
2023-12-23 05:07:30 +00:00
Valentine Briese
1142d53a99
Add missing colon in States documentation (#11064)
# Objective

The documentation for the `States` trait contains an error! There is a
single colon missing from `OnExit<T:Variant>`.

## Solution

Replace `OnExit<T:Variant>` with `OnExit<T::Variant>`. (Notice the added
colon.)

---

## Changelog

### Added

- Added missing colon in `States` documentation.

---

Bevy community, you may now rest easy.
2023-12-22 17:19:31 +00:00
Nicola Papale
fcb49a5d80
Document None conditions on compute_aabb (#11051)
The error conditions were not documented, this requires the user to
inspect the source code to know when to expect a `None`.

Error conditions should always be documented, so we document them.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-12-21 23:29:43 +00:00
Thierry Berger
80f15e0dbb
Remove CanvasParentResizePlugin (#11057)
Improves #11052

# Changelog
- Remove `Window::fit_canvas_to_parent`, as its resizing on wasm now
respects its CSS configuration.

## Migration Guide
- Remove uses of `Window::fit_canvas_to_parent` in favor of CSS
properties, for example:
  ```css
  canvas {
    width: 100%;
    height: 100%;
  }
  ```
2023-12-21 20:01:22 +00:00
Stepan Koltsov
b27f74911a
Explain Changed, Added are not archetype filters (#11049)
Explain potential footgun.
2023-12-21 20:01:03 +00:00
François
8666b076d8
fix base64 padding when loading a gltf file (#11053)
# Objective

- After #10336, some gltf files fail to load (examples
custom_gltf_vertex_attribute, gltf_skinned_mesh, ...)
- Fix them

## Solution

- Allow padding in base 64 decoder
2023-12-21 20:00:51 +00:00
Sludge
37e80745d2
Derive Debug for BloomCompositeMode (#11041)
# Objective

- API guidelines recommend that every type should implement `Debug`
where possible.

## Solution

- Do that.
2023-12-21 19:59:46 +00:00
Doonv
ba0f8f996f
Add insert_state to App. (#11043)
# Objective

Fix #10731.

## Solution

Rename `App::add_state<T>(&mut self)` to `init_state`, and add
`App::insert_state<T>(&mut self, state: T)`. I decided on these names
because they are more similar to `init_resource` and `insert_resource`.

I also removed the `States` trait's requirement for `Default`. Instead,
`init_state` requires `FromWorld`.

---

## Changelog

- Renamed `App::add_state` to `init_state`.
- Added `App::insert_state`.
- Removed the `States` trait's requirement for `Default`.

## Migration Guide

- Renamed `App::add_state` to `init_state`.
2023-12-21 14:09:24 +00:00
Doonv
42f721382c
Add SystemTime to bevy_utils (#11054)
# Objective

https://github.com/bevyengine/bevy/pull/10702 has overridden the changes
that https://github.com/bevyengine/bevy/pull/10980 did.

## Solution

Re-add `SystemTime` to `bevy_utils`, along with a few other types.

---

## Changelog

- Rexported `SystemTime`, `SystemTimeError`, and `TryFromFloatSecsError`
from `bevy_utils`.
2023-12-21 14:05:27 +00:00
Thierry Berger
ced216f59a
Update winit dependency to 0.29 (#10702)
# Objective

- Update winit dependency to 0.29

## Changelog

### KeyCode changes

- Removed `ScanCode`, as it was [replaced by
KeyCode](https://github.com/rust-windowing/winit/blob/master/CHANGELOG.md#0292).
- `ReceivedCharacter.char` is now a `SmolStr`, [relevant
doc](https://docs.rs/winit/latest/winit/event/struct.KeyEvent.html#structfield.text).
- Changed most `KeyCode` values, and added more.

KeyCode has changed meaning. With this PR, it refers to physical
position on keyboard rather than the printed letter on keyboard keys.

In practice this means:
- On QWERTY keyboard layouts, nothing changes
- On any other keyboard layout, `KeyCode` no longer reflects the label
on key.
- This is "good". In bevy 0.12, when you used WASD for movement, users
with non-QWERTY keyboards couldn't play your game! This was especially
bad for non-latin keyboards. Now, WASD represents the physical keys. A
French player will press the ZQSD keys, which are near each other,
Kyrgyz players will use "Цфыв".
- This is "bad" as well. You can't know in advance what the label of the
key for input is. Your UI says "press WASD to move", even if in reality,
they should be pressing "ZQSD" or "Цфыв". You also no longer can use
`KeyCode` for text inputs. In any case, it was a pretty bad API for text
input. You should use `ReceivedCharacter` now instead.

### Other changes
- Use `web-time` rather than `instant` crate.
(https://github.com/rust-windowing/winit/pull/2836)
- winit did split `run_return` in `run_onDemand` and `pump_events`, I
did the same change in bevy_winit and used `pump_events`.
- Removed `return_from_run` from `WinitSettings` as `winit::run` now
returns on supported platforms.
- I left the example "return_after_run" as I think it's still useful.
- This winit change is done partly to allow to create a new window after
quitting all windows: https://github.com/emilk/egui/issues/1918 ; this
PR doesn't address.
- added `width` and `height` properties in the `canvas` from wasm
example
(https://github.com/bevyengine/bevy/pull/10702#discussion_r1420567168)

## Known regressions (important follow ups?)
- Provide an API for reacting when a specific key from current layout
was released.
- possible solutions: use winit::Key from winit::KeyEvent ; mapping
between KeyCode and Key ; or .
- We don't receive characters through alt+numpad (e.g. alt + 151 = "ù")
anymore ; reproduced on winit example "ime". maybe related to
https://github.com/rust-windowing/winit/issues/2945
- (windows) Window content doesn't refresh at all when resizing. By
reading https://github.com/rust-windowing/winit/issues/2900 ; I suspect
we should just fire a `window.request_redraw();` from `AboutToWait`, and
handle actual redrawing within `RedrawRequested`. I'm not sure how to
move all that code so I'd appreciate it to be a follow up.
- (windows) unreleased winit fix for using set_control_flow in
AboutToWait https://github.com/rust-windowing/winit/issues/3215 ; ⚠️ I'm
not sure what the implications are, but that feels bad 🤔

## Follow up 

I'd like to avoid bloating this PR, here are a few follow up tasks
worthy of a separate PR, or new issue to track them once this PR is
closed, as they would either complicate reviews, or at risk of being
controversial:
- remove CanvasParentResizePlugin
(https://github.com/bevyengine/bevy/pull/10702#discussion_r1417068856)
- avoid mentionning explicitly winit in docs from bevy_window ?
- NamedKey integration on bevy_input:
https://github.com/rust-windowing/winit/pull/3143 introduced a new
NamedKey variant. I implemented it only on the converters but we'd
benefit making the same changes to bevy_input.
- Add more info in KeyboardInput
https://github.com/bevyengine/bevy/pull/10702#pullrequestreview-1748336313
- https://github.com/bevyengine/bevy/pull/9905 added a workaround on a
bug allegedly fixed by winit 0.29. We should check if it's still
necessary.
- update to raw_window_handle 0.6
  - blocked by wgpu
- Rename `KeyCode` to `PhysicalKeyCode`
https://github.com/bevyengine/bevy/pull/10702#discussion_r1404595015
- remove `instant` dependency, [replaced
by](https://github.com/rust-windowing/winit/pull/2836) `web_time`), we'd
need to update to :
  - fastrand >= 2.0
- [`async-executor`](https://github.com/smol-rs/async-executor) >= 1.7
    - [`futures-lite`](https://github.com/smol-rs/futures-lite) >= 2.0
- Verify license, see
[discussion](https://github.com/bevyengine/bevy/pull/8745#discussion_r1402439800)
  - we might be missing a short notice or description of changes made
- Consider using https://github.com/rust-windowing/cursor-icon directly
rather than vendoring it in bevy.
- investigate [this
unwrap](https://github.com/bevyengine/bevy/pull/8745#discussion_r1387044986)
(`winit_window.canvas().unwrap();`)
- Use more good things about winit's update
- https://github.com/bevyengine/bevy/pull/10689#issuecomment-1823560428
## Migration Guide

This PR should have one.
2023-12-21 07:40:47 +00:00
Martín Maita
3b59dbd772
Update base64 requirement from 0.13.0 to 0.21.5 (#10336)
# Objective

- Update base64 requirement from 0.13.0 to 0.21.5.
- Closes #10317.

## Solution

- Bumped `base64` requirement and manually migrated code to fix a
breaking change after updating.
2023-12-21 00:55:54 +00:00
Pablo García Ruiz
dc8fc6cb34
Reexport winit::platform::android::activity::* in bevy_winit (#11011)
# Objective

- Fixes #10630

## Solution

- Reexport winit::platform::android::activity::* in bevy_init

---------

Co-authored-by: François <mockersf@gmail.com>
2023-12-19 20:15:03 +00:00
Stepan Koltsov
4852233298
OrthographicProjection.scaling_mode is not just for resize (#11024)
Current comment is somewhat misleading: one may assume the field is used
only when window is resized.
2023-12-19 18:01:53 +00:00
Rob Parrett
7d2e6cb468
Fix typo in docs for Has (#11028)
# Objective

Fix typo

## Solution

Put the letter `i` in there.
2023-12-19 17:59:34 +00:00
Nicola Papale
d64e148e4e
Add non-existent entity behavior to Has doc (#11025)
# Objective

`Has<T>` in some niche cases may behave in an unexpected way.

Specifically, when using `Query::get` on a `Has<T>` with a despawned
entity.

## Solution

Add precision about cases wehre `Query::get` could return an `Err`.
2023-12-19 16:34:55 +00:00
Stepan Koltsov
0c2df27930
Rename some lifetimes (ResMut etc) for clarity (#11021)
Use `'w` for world lifetime consistently.

When implementing system params, useful to look at how other params are
implemented. `'w` makes it clear it is world, not state.
2023-12-19 15:22:25 +00:00
Stepan Koltsov
05b00267c6
Some doc to bevy_diagnostic (#11020) 2023-12-19 08:16:22 +00:00
Matthew Gries
d99053cc8a
Update AABB when Sprite component changes in calculate_bounds_2d() (#11016)
# Objective

- Fixes #10587, where the `Aabb` component of entities with `Sprite` and
`Handle<Image>` components was not automatically updated when
`Sprite::custom_size` changed.

## Solution

- In the query for entities with `Sprite` components in
`calculate_bounds_2d`, use the `Changed` filter to detect for `Sprites`
that changed as well as sprites that do not have `Aabb` components. As
noted in the issue, this will cause the `Aabb` to be recalculated when
other fields of the `Sprite` component change, but calculating the
`Aabb` for sprites is trivial.

---

## Changelog
- Modified query for entities with `Sprite` components in
`calculate_bounds_2d`, so that entities with `Sprite` components that
changed will also have their AABB recalculated.
2023-12-18 20:55:12 +00:00
Mateusz Wachowiak
2c7eab1b4c
Add method to check if all inputs are pressed (#11010)
# Objective

- Provide way to check whether multiple inputs are pressed.

## Solution

- Add `all_pressed` method that checks if all inputs are currently being
pressed.
2023-12-18 01:45:43 +00:00
JMS55
9a89fc44f4
Add is_resource_changed_by_id + is_resource_added_by_id (#11012)
# Objective

- Allow checking if a resource has changed by its ComponentId

---

## Changelog
- Added `World::is_resource_changed_by_id()` and
`World::is_resource_added_by_id()`.
2023-12-18 01:44:33 +00:00
daxpedda
9249856da3
Implement Std traits for SceneInstanceReady (#11003)
# Objective

Being able to do:
```rust
ev_scene_ready.read().next().unwrap();
```
Which currently isn't possible because `SceneInstanceReady` doesn't
implement `Debug`.

## Solution

Implement `Debug` for `SceneInstanceReady`.

---

## Changelog

### Added
- Implement Std traits for `SceneInstanceReady`.
2023-12-17 15:39:13 +00:00
Olle Lukowski
6b9cd57956
Introduce AspectRatio struct (#10368)
# Objective

- Fix an inconsistency in the calculation of aspect ratio's. 
- Fixes #10288 

## Solution

- Created an intermediate `AspectRatio` struct, as suggested in the
issue. This is currently just used in any places where aspect ratio
calculations happen, to prevent doing it wrong. In my and @mamekoro 's
opinion, it would be better if this was used instead of a normal `f32`
in various places, but I didn't want to make too many changes to begin
with.

## Migration Guide
- Anywhere where you are currently expecting a f32 when getting aspect
ratios, you will now receive a `AspectRatio` struct. this still holds
the same value.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-12-17 02:01:26 +00:00
Tygyh
63d17e8494
Simplify equality assertions (#10988)
# Objective

- Shorten assertions.

## Solution

- Replace '==' assertions with 'assert_eq()' and '!=' assertions with
'assert_ne()' .
2023-12-16 23:58:41 +00:00
Tygyh
645625b789
Replace deprecated elements (#10999)
# Objective

- Replace deprecated elements.

## Solution

- Remove 'std::' from constants.
2023-12-16 23:24:49 +00:00
Tygyh
696af48416
Remove unnecessary parentheses (#10990)
# Objective

- Increase readability.

## Solution

- Remove unnecessary parentheses.
2023-12-16 02:26:18 +00:00
Tygyh
d3e96abadc
Replace deprecated elements (#10991)
# Objective

- Replace deprecated elements.

## Solution

- Replace 'u8::max_value()' with 'u8::MAX'.
2023-12-16 02:25:12 +00:00
Torstein Grindvik
16c5a4b7cd
Fix BindingType import warning (#10818)
# Objective

Fix this warning

```
warning: unused import: `BindingType`
  --> ...bevy/crates/bevy_pbr/src/render/mesh_view_bindings.rs:23:88
   |
23 |         BindGroup, BindGroupLayout, BindGroupLayoutEntry, BindGroupLayoutEntryBuilder, BindingType,
   |                                                                                        ^^^^^^^^^^^
   |
   = note: `#[warn(unused_imports)]` on by default
```

## Solution

- Import via globstar

Signed-off-by: Torstein Grindvik <torstein.grindvik@muybridge.com>
Co-authored-by: Torstein Grindvik <torstein.grindvik@muybridge.com>
2023-12-14 18:48:20 +00:00
Joseph
11065974d4
Simplify lifetimes in QueryState methods (#10937)
# Objective

The definition of several `QueryState` methods use unnecessary explicit
lifetimes, which adds to visual noise.

## Solution

Elide the lifetimes.
2023-12-14 17:26:03 +00:00
akimakinai
83fbf48238
Add docs to bevy_sprite a little (#10947)
# Objective

- bevy_sprite crate is missing docs for important types. `Sprite` being
undocumented was especially confusing for me even though it is one of
the first types I need to learn.
 
## Solution

- Improves the situation a little by adding some documentations.
I'm unsure about my understanding of functionality and writing. I'm
happy to be pointed out any mistakes.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Federico Rinaldi <gisquerin@gmail.com>
2023-12-14 17:25:55 +00:00
Nathan Fox
381277d6c3
Fix typo in docs for ViewVisibility (#10979)
Simple doc fix.
2023-12-14 17:25:48 +00:00
Charles Bournhonesque
c4aea07753
Make SystemTime available in both native and wasm (#10980)
# Objective

`Instant` and `Duration` from the `instant` crate are exposed in
`bevy_utils` to have a single abstraction for native/wasm.
It would be useful to have the same thing for
[`SystemTime`](https://doc.rust-lang.org/std/time/struct.SystemTime.html).


---

## Changelog

### Added
- `bevy_utils` now re-exposes the `instant::SystemTime` struct

Co-authored-by: Charles Bournhonesque <cbournhonesque@snapchat.com>
2023-12-14 16:36:24 +00:00
Mike
6b84ba97a3
Auto insert sync points (#9822)
# Objective

- Users are often confused when their command effects are not visible in
the next system. This PR auto inserts sync points if there are deferred
buffers on a system and there are dependents on that system (systems
with after relationships).
- Manual sync points can lead to users adding more than needed and it's
hard for the user to have a global understanding of their system graph
to know which sync points can be merged. However we can easily calculate
which sync points can be merged automatically.

## Solution

1. Add new edge types to allow opting out of new behavior
2. Insert an sync point for each edge whose initial node has deferred
system params.
3. Reuse nodes if they're at the number of sync points away.

* add opt outs for specific edges with `after_ignore_deferred`,
`before_ignore_deferred` and `chain_ignore_deferred`. The
`auto_insert_apply_deferred` boolean on `ScheduleBuildSettings` can be
set to false to opt out for the whole schedule.

## Perf
This has a small negative effect on schedule build times.
```text
group                                           auto-sync                              main-for-auto-sync
-----                                           -----------                            ------------------
build_schedule/1000_schedule                    1.06       2.8±0.15s        ? ?/sec    1.00       2.7±0.06s        ? ?/sec
build_schedule/1000_schedule_noconstraints      1.01     26.2±0.88ms        ? ?/sec    1.00     25.8±0.36ms        ? ?/sec
build_schedule/100_schedule                     1.02     13.1±0.33ms        ? ?/sec    1.00     12.9±0.28ms        ? ?/sec
build_schedule/100_schedule_noconstraints       1.08   505.3±29.30µs        ? ?/sec    1.00   469.4±12.48µs        ? ?/sec
build_schedule/500_schedule                     1.00    485.5±6.29ms        ? ?/sec    1.00    485.5±9.80ms        ? ?/sec
build_schedule/500_schedule_noconstraints       1.00      6.8±0.10ms        ? ?/sec    1.02      6.9±0.16ms        ? ?/sec
```
---

## Changelog

- Auto insert sync points and added `after_ignore_deferred`,
`before_ignore_deferred`, `chain_no_deferred` and
`auto_insert_apply_deferred` APIs to opt out of this behavior

## Migration Guide

- `apply_deferred` points are added automatically when there is ordering
relationship with a system that has deferred parameters like `Commands`.
If you want to opt out of this you can switch from `after`, `before`,
and `chain` to the corresponding `ignore_deferred` API,
`after_ignore_deferred`, `before_ignore_deferred` or
`chain_ignore_deferred` for your system/set ordering.
- You can also set `ScheduleBuildSettings::auto_insert_sync_points` to
`false` if you want to do it for the whole schedule. Note that in this
mode you can still add `apply_deferred` points manually.
- For most manual insertions of `apply_deferred` you should remove them
as they cannot be merged with the automatically inserted points and
might reduce parallelizability of the system graph.

## TODO
- [x] remove any apply_deferred used in the engine
- [x] ~~decide if we should deprecate manually using apply_deferred.~~
We'll still allow inserting manual sync points for now for whatever edge
cases users might have.
- [x] Update migration guide
- [x] rerun schedule build benchmarks

---------

Co-authored-by: Joseph <21144246+JoJoJet@users.noreply.github.com>
2023-12-14 16:34:01 +00:00
Tygyh
720d6dab82
Change Window scale factor to f32 (adopted) (#10897)
# Objective

- Finish the work done in #8942 .

## Solution

- Rebase the changes made in #8942 and fix the issues stopping it from
being merged earlier

---------

Co-authored-by: Thomas <1234328+thmsgntz@users.noreply.github.com>
2023-12-14 14:56:40 +00:00
Joona Aalto
029dd06f7d
Add Direction2d::from_xy and Direction3d::from_xyz (#10882)
# Objective

Make direction construction a bit more ergonomic.

## Solution

Add `Direction2d::from_xy` and `Direction3d::from_xyz`, similar to
`Transform::from_xyz`:

```rust
let dir2 = Direction2d::from_xy(0.5, 0.5).unwrap();
let dir3 = Direction3d::from_xyz(0.5, 0.5, 0.5).unwrap();
```

This can be a bit cleaner than using `new`:

```rust
let dir2 = Direction2d::new(Vec2::new(0.5, 0.5)).unwrap();
let dir3 = Direction3d::new(Vec3::new(0.5, 0.5, 0.5)).unwrap();
```
2023-12-14 14:56:07 +00:00
Aceeri
fe28e0ec32
Add First/Pre/Post/Last schedules to the Fixed timestep (#10977)
Fixes https://github.com/bevyengine/bevy/issues/10974

# Objective
Duplicate the ordering logic of the `Main` schedule into the `FixedMain`
schedule.

---

## Changelog
- `FixedUpdate` is no longer the main schedule ran in
`RunFixedUpdateLoop`, `FixedMain` has replaced this and has a similar
structure to `Main`.

## Migration Guide
- Usage of `RunFixedUpdateLoop` should be renamed to `RunFixedMainLoop`.
2023-12-14 04:35:40 +00:00
Christian Hughes
a4e0a0c0b9
Allow the editing of startup schedules (#10969)
# Objective

Fixes #10968 

## Solution

Pull startup schedules from a list of `ScheduleLabel`s in the same way
the update schedules are handled.

---

## Changelog

- Added `MainScheduleOrder::startup_labels` to allow the editing of the
startup schedule order.

## Migration Guide

- Added a new field to `MainScheduleOrder`, `startup_labels`, for
editing the startup schedule order.
2023-12-14 04:34:54 +00:00
Elabajaba
70a592f31a
Update to wgpu 0.18 (#10266)
# Objective

Keep up to date with wgpu.

## Solution

Update the wgpu version.

Currently blocked on naga_oil updating to naga 0.14 and releasing a new
version.

3d scenes (or maybe any scene with lighting?) currently don't render
anything due to
```
error: naga_oil bug, please file a report: composer failed to build a valid header: Type [2] '' is invalid
 = Capability Capabilities(CUBE_ARRAY_TEXTURES) is required
 ```

I'm not sure what should be passed in for `wgpu::InstanceFlags`, or if we want to make the gles3minorversion configurable (might be useful for debugging?)

Currently blocked on https://github.com/bevyengine/naga_oil/pull/63, and https://github.com/gfx-rs/wgpu/issues/4569 to be fixed upstream in wgpu first.

## Known issues

Amd+windows+vulkan has issues with texture_binding_arrays (see the image [here](https://github.com/bevyengine/bevy/pull/10266#issuecomment-1819946278)), but that'll be fixed in the next wgpu/naga version, and you can just use dx12 as a workaround for now (Amd+linux mesa+vulkan texture_binding_arrays are fixed though).

---

## Changelog

Updated wgpu to 0.18, naga to 0.14.2, and naga_oil to 0.11.
- Windows desktop GL should now be less painful as it no longer requires Angle.
- You can now toggle shader validation and debug information for debug and release builds using `WgpuSettings.instance_flags` and [InstanceFlags](https://docs.rs/wgpu/0.18.0/wgpu/struct.InstanceFlags.html)

## Migration Guide

- `RenderPassDescriptor` `color_attachments`  (as well as `RenderPassColorAttachment`, and `RenderPassDepthStencilAttachment`) now use `StoreOp::Store` or `StoreOp::Discard` instead of a `boolean` to declare whether or not they should be stored.
- `RenderPassDescriptor` now have `timestamp_writes` and `occlusion_query_set` fields. These can safely be set to `None`.
- `ComputePassDescriptor` now have a `timestamp_writes` field. This can be set to `None` for now.
- See the [wgpu changelog](https://github.com/gfx-rs/wgpu/blob/trunk/CHANGELOG.md#v0180-2023-10-25) for additional details
2023-12-14 02:45:47 +00:00
Tygyh
b2661ea73d
Reorder impl to be the same as the trait (#10964)
# Objective

- Make the implementation order consistent between all sources to fit
the order in the trait.

## Solution

- Change the implementation order.
2023-12-13 21:19:49 +00:00
davier
2b9c97d203
Fix Mesh2d normals on webgl (#10967)
# Objective

A workaround for a webgl issue was introduced in #9383 but one function
for mesh2d was missed.

## Solution

Applied the migration guide from #9383 in
`mesh2d_normal_local_to_world()

Note: I'm not using normals so I have not tested the bug & fix
2023-12-13 20:26:17 +00:00
Tim Siegel
1ab0f28acd
docs: AnimationPlayer::play doesn't have transition_duration arg (#10970)
# Objective

The documentation for `AnimationPlayer::play` mentions a non-existent
`transition_duration` argument from an old iteration of the API. It's
confusing.

## Solution

Remove the offending sentence.
2023-12-13 18:51:34 +00:00
Federico Rinaldi
9c78128e8f
Rename Q type parameter to D when referring to WorldQueryData (#10782)
# Objective

Since #10776 split `WorldQuery` to `WorldQueryData` and
`WorldQueryFilter`, it should be clear that the query is actually
composed of two parts. It is not factually correct to call "query" only
the data part. Therefore I suggest to rename the `Q` parameter to `D` in
`Query` and related items.

As far as I know, there shouldn't be breaking changes from renaming
generic type parameters.

## Solution

I used a combination of rust-analyzer go to reference and `Ctrl-F`ing
various patterns to catch as many cases as possible. Hopefully I got
them all. Feel free to check if you're concerned of me having missed
some.

## Notes

This and #10779 have many lines in common, so merging one will cause a
lot of merge conflicts to the other.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-12-13 18:50:46 +00:00
Stepan Koltsov
12a11e2fd0
Actually check alignment in BlobVec test aligned_zst (#10885)
Do not rely on Miri.

---------

Co-authored-by: James Liu <contact@jamessliu.com>
2023-12-13 02:36:49 +00:00
Sludge
41db723c5c
Fix soundness of UnsafeWorldCell usage example (#10941)
# Objective

- The example in the docs is unsound.

Demo:

```rust
#[derive(Resource)]
struct MyRes(u32);

fn main() {
    let mut w = World::new();
    w.insert_resource(MyRes(0));

    let (mut res, comp) = split_world_access(&mut w);
    let mut r1 = res.get_resource_mut::<MyRes>().unwrap();
    let mut r2 = res.get_resource_mut::<MyRes>().unwrap();

    *r1 = MyRes(1);
    *r2 = MyRes(2);
}
```

The API in the example allows aliasing mutable references to the same
resource. Miri also complains when running this.

## Solution

- Change the example API to make the returned `Mut` borrow from the
`OnlyResourceAccessWorld` instead of borrowing from the world via `'w`.
This prevents obtaining more than one `Mut` at the same time from it.
2023-12-13 00:55:30 +00:00
Stepan Koltsov
ff7497cb9a
Explain how RegularPolygon mesh is generated (#10927)
I didn't notice minus where vertices are generated, so could not
understand the order there.

Adding a comment to help the next person who is going to understand Bevy
by reading its code.
2023-12-12 21:40:33 +00:00
Mateusz Wachowiak
a7a5d17ae1
Refactor process_handle_drop_internal() in bevy_asset (#10920)
# Objective

- Reduce nesting in `process_handle_drop_internal()`.
- Related to #10896.

## Solution

- Use early returns when possible.
- Reduced from 9 levels of indents to 4.
2023-12-12 19:46:37 +00:00
Mantas
5af2f022d8
Rename WorldQueryData & WorldQueryFilter to QueryData & QueryFilter (#10779)
# Rename `WorldQueryData` & `WorldQueryFilter` to `QueryData` &
`QueryFilter`

Fixes #10776 

## Solution

Traits `WorldQueryData` & `WorldQueryFilter` were renamed to `QueryData`
and `QueryFilter`, respectively. Related Trait types were also renamed.

---

## Changelog

- Trait `WorldQueryData` has been renamed to `QueryData`. Derive macro's
`QueryData` attribute `world_query_data` has been renamed to
`query_data`.
- Trait `WorldQueryFilter` has been renamed to `QueryFilter`. Derive
macro's `QueryFilter` attribute `world_query_filter` has been renamed to
`query_filter`.
- Trait's `ExtractComponent` type `Query` has been renamed to `Data`.
- Trait's `GetBatchData` types `Query` & `QueryFilter` has been renamed
to `Data` & `Filter`, respectively.
- Trait's `ExtractInstance` type `Query` has been renamed to `Data`.
- Trait's `ViewNode` type `ViewQuery` has been renamed to `ViewData`.
- Trait's `RenderCommand` types `ViewWorldQuery` & `ItemWorldQuery` has
been renamed to `ViewData` & `ItemData`, respectively.

## Migration Guide

Note: if merged before 0.13 is released, this should instead modify the
migration guide of #10776 with the updated names.

- Rename `WorldQueryData` & `WorldQueryFilter` trait usages to
`QueryData` & `QueryFilter` and their respective derive macro attributes
`world_query_data` & `world_query_filter` to `query_data` &
`query_filter`.
- Rename the following trait type usages:
  - Trait's `ExtractComponent` type `Query` to `Data`.
  - Trait's `GetBatchData` type `Query` to `Data`.
  - Trait's `ExtractInstance` type `Query` to `Data`.
  - Trait's `ViewNode` type `ViewQuery` to `ViewData`'
- Trait's `RenderCommand` types `ViewWolrdQuery` & `ItemWorldQuery` to
`ViewData` & `ItemData`, respectively.

```rust
// Before
#[derive(WorldQueryData)]
#[world_query_data(derive(Debug))]
struct EmptyQuery {
    empty: (),
}

// After
#[derive(QueryData)]
#[query_data(derive(Debug))]
struct EmptyQuery {
    empty: (),
}

// Before
#[derive(WorldQueryFilter)]
struct CustomQueryFilter<T: Component, P: Component> {
    _c: With<ComponentC>,
    _d: With<ComponentD>,
    _or: Or<(Added<ComponentC>, Changed<ComponentD>, Without<ComponentZ>)>,
    _generic_tuple: (With<T>, With<P>),
}

// After
#[derive(QueryFilter)]
struct CustomQueryFilter<T: Component, P: Component> {
    _c: With<ComponentC>,
    _d: With<ComponentD>,
    _or: Or<(Added<ComponentC>, Changed<ComponentD>, Without<ComponentZ>)>,
    _generic_tuple: (With<T>, With<P>),
}

// Before
impl ExtractComponent for ContrastAdaptiveSharpeningSettings {
    type Query = &'static Self;
    type Filter = With<Camera>;
    type Out = (DenoiseCAS, CASUniform);

    fn extract_component(item: QueryItem<Self::Query>) -> Option<Self::Out> {
        //...
    }
}

// After
impl ExtractComponent for ContrastAdaptiveSharpeningSettings {
    type Data = &'static Self;
    type Filter = With<Camera>;
    type Out = (DenoiseCAS, CASUniform);

    fn extract_component(item: QueryItem<Self::Data>) -> Option<Self::Out> {
        //...
    }
}

// Before
impl GetBatchData for MeshPipeline {
    type Param = SRes<RenderMeshInstances>;
    type Query = Entity;
    type QueryFilter = With<Mesh3d>;
    type CompareData = (MaterialBindGroupId, AssetId<Mesh>);
    type BufferData = MeshUniform;

    fn get_batch_data(
        mesh_instances: &SystemParamItem<Self::Param>,
        entity: &QueryItem<Self::Query>,
    ) -> (Self::BufferData, Option<Self::CompareData>) {
        // ....
    }
}

// After
impl GetBatchData for MeshPipeline {
    type Param = SRes<RenderMeshInstances>;
    type Data = Entity;
    type Filter = With<Mesh3d>;
    type CompareData = (MaterialBindGroupId, AssetId<Mesh>);
    type BufferData = MeshUniform;

    fn get_batch_data(
        mesh_instances: &SystemParamItem<Self::Param>,
        entity: &QueryItem<Self::Data>,
    ) -> (Self::BufferData, Option<Self::CompareData>) {
        // ....
    }
}

// Before
impl<A> ExtractInstance for AssetId<A>
where
    A: Asset,
{
    type Query = Read<Handle<A>>;
    type Filter = ();

    fn extract(item: QueryItem<'_, Self::Query>) -> Option<Self> {
        Some(item.id())
    }
}

// After
impl<A> ExtractInstance for AssetId<A>
where
    A: Asset,
{
    type Data = Read<Handle<A>>;
    type Filter = ();

    fn extract(item: QueryItem<'_, Self::Data>) -> Option<Self> {
        Some(item.id())
    }
}

// Before
impl ViewNode for PostProcessNode {
    type ViewQuery = (
        &'static ViewTarget,
        &'static PostProcessSettings,
    );

    fn run(
        &self,
        _graph: &mut RenderGraphContext,
        render_context: &mut RenderContext,
        (view_target, _post_process_settings): QueryItem<Self::ViewQuery>,
        world: &World,
    ) -> Result<(), NodeRunError> {
        // ...
    }
}

// After
impl ViewNode for PostProcessNode {
    type ViewData = (
        &'static ViewTarget,
        &'static PostProcessSettings,
    );

    fn run(
        &self,
        _graph: &mut RenderGraphContext,
        render_context: &mut RenderContext,
        (view_target, _post_process_settings): QueryItem<Self::ViewData>,
        world: &World,
    ) -> Result<(), NodeRunError> {
        // ...
    }
}

// Before
impl<P: CachedRenderPipelinePhaseItem> RenderCommand<P> for SetItemPipeline {
    type Param = SRes<PipelineCache>;
    type ViewWorldQuery = ();
    type ItemWorldQuery = ();
    #[inline]
    fn render<'w>(
        item: &P,
        _view: (),
        _entity: (),
        pipeline_cache: SystemParamItem<'w, '_, Self::Param>,
        pass: &mut TrackedRenderPass<'w>,
    ) -> RenderCommandResult {
        // ...
    }
}

// After
impl<P: CachedRenderPipelinePhaseItem> RenderCommand<P> for SetItemPipeline {
    type Param = SRes<PipelineCache>;
    type ViewData = ();
    type ItemData = ();
    #[inline]
    fn render<'w>(
        item: &P,
        _view: (),
        _entity: (),
        pipeline_cache: SystemParamItem<'w, '_, Self::Param>,
        pass: &mut TrackedRenderPass<'w>,
    ) -> RenderCommandResult {
        // ...
    }
}
```
2023-12-12 19:45:50 +00:00
Stepan Koltsov
79641c7f08
Reorder fields in SystemSchedule (#10764)
Make more clear what is going on there.
2023-12-12 19:45:44 +00:00
robtfm
67d92e9b85
light renderlayers (#10742)
# Objective

add `RenderLayers` awareness to lights. lights default to
`RenderLayers::layer(0)`, and must intersect the camera entity's
`RenderLayers` in order to affect the camera's output.

note that lights already use renderlayers to filter meshes for shadow
casting. this adds filtering lights per view based on intersection of
camera layers and light layers.

fixes #3462 

## Solution

PointLights and SpotLights are assigned to individual views in
`assign_lights_to_clusters`, so we simply cull the lights which don't
match the view layers in that function.

DirectionalLights are global, so we 
- add the light layers to the `DirectionalLight` struct
- add the view layers to the `ViewUniform` struct
- check for intersection before processing the light in
`apply_pbr_lighting`

potential issue: when mesh/light layers are smaller than the view layers
weird results can occur. e.g:
camera = layers 1+2
light = layers 1
mesh = layers 2

the mesh does not cast shadows wrt the light as (1 & 2) == 0.
the light affects the view as (1+2 & 1) != 0. 
the view renders the mesh as (1+2 & 2) != 0.

so the mesh is rendered and lit, but does not cast a shadow. 

this could be fixed (so that the light would not affect the mesh in that
view) by adding the light layers to the point and spot light structs,
but i think the setup is pretty unusual, and space is at a premium in
those structs (adding 4 bytes more would reduce the webgl point+spot
light max count to 240 from 256).

I think typical usage is for cameras to have a single layer, and
meshes/lights to maybe have multiple layers to render to e.g. minimaps
as well as primary views.

if there is a good use case for the above setup and we should support
it, please let me know.

---

## Migration Guide

Lights no longer affect all `RenderLayers` by default, now like cameras
and meshes they default to `RenderLayers::layer(0)`. To recover the
previous behaviour and have all lights affect all views, add a
`RenderLayers::all()` component to the light entity.
2023-12-12 19:45:37 +00:00
davier
55402bdf2e
Fix debug printing for dynamic types (#10740)
# Objective

Printing `DynamicStruct` with a debug format does not show the contained
type anymore. For instance, in `examples/reflection/reflection.rs`,
adding `dbg!(&reflect_value);` to line 96 will print:
```rust
[examples/reflection/reflection.rs:96] &reflect_value = DynamicStruct(bevy_reflect::DynamicStruct {
    a: 4,
    nested: DynamicStruct(bevy_reflect::DynamicStruct {
        b: 8,
    }),
})
```

## Solution

Show the represented type instead (`reflection::Foo` and
`reflection::Bar` in this case):
```rust
[examples/reflection/reflection.rs:96] &reflect_value = DynamicStruct(reflection::Foo {
    a: 4,
    nested: DynamicStruct(reflection::Bar {
        b: 8,
    }),
})
```

---------

Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
2023-12-12 19:44:43 +00:00
Ben Frankel
9c8576996f
Add a doc note about despawn footgun (#10889)
# Objective

The `Despawn` command breaks the hierarchy whenever you use it if the
despawned entity has a parent or any children. This is a serious footgun
because the `Despawn` command has the shortest name, the behavior is
unexpected and not likely to be what you want, and the crash that it
causes can be very difficult to track down.

## Solution

Until this can be fixed by relations, add a note mentioning the footgun
in the documentation.
2023-12-12 19:44:05 +00:00
TheBigCheese
6a15ed564d
Improve EntityWorldMut.remove, retain and despawn docs by linking to more detail (#10943)
## Solution

`Commands.remove` and `.retain` (because I copied `remove`s doc)
referenced `EntityWorldMut.remove` and `retain` for more detail but the
`Commands` docs are much more detailed (which makes sense because it is
the most common api), so I have instead inverted this so that
`EntityWorldMut` docs link to `Commands`.

I also made `EntityWorldMut.despawn` reference `World.despawn` for more
details, like `Commands.despawn` does.
2023-12-12 19:27:11 +00:00
Joona Aalto
4b1865f8bd
Normalize only nonzero normals for mikktspace normal maps (#10905)
# Objective

Fixes #5891.

For mikktspace normal maps, normals must be renormalized in vertex
shaders to match the way mikktspace bakes vertex tangents and normal
maps so that the exact inverse process is applied when shading.

However, for invalid normals like `vec3<f32>(0.0, 0.0, 0.0)`, this
normalization causes NaN values, and because it's in the vertex shader,
it affects the entire triangle and causes it to be shaded as black:

![incorrectly shaded
cone](https://github.com/bevyengine/bevy/assets/57632562/3334b3a9-f72a-4a08-853e-8077a346f5c9)

*A cone with a tip that has a vertex normal of [0, 0, 0], causing the
mesh to be shaded as black.*

In some cases, normals of zero are actually *useful*. For example, a
smoothly shaded cone without creases requires the apex vertex normal to
be zero, because there is no singular normal that works correctly, so
the apex shouldn't contribute to the overall shading. Duplicate vertices
for the apex fix some shading issues, but it causes visible creases and
is more expensive. See #5891 and #10298 for more details.

For correctly shaded cones and other similar low-density shapes with
sharp tips, vertex normals of zero can not be normalized in the vertex
shader.

## Solution

Only normalize the vertex normals and tangents in the vertex shader if
the normal isn't [0, 0, 0]. This way, mikktspace normal maps should
still work for everything except the zero normals, and the zero normals
will only be normalized in the fragment shader.

This allows us to render cones correctly:

![smooth cone with some
banding](https://github.com/bevyengine/bevy/assets/57632562/6b36e264-22c6-453b-a6de-c404b314ca1a)

Notice how there is still a weird shadow banding effect in one area. I
noticed that it can be fixed by normalizing
[here](d2614f2d80/crates/bevy_pbr/src/render/pbr_functions.wgsl (L51)),
which produces a perfectly smooth cone without duplicate vertices:

![smooth
cone](https://github.com/bevyengine/bevy/assets/57632562/64f9ad5d-b249-4eae-880b-a1e61e07ae73)

I didn't add this change yet, because it seems a bit arbitrary. I can
add it here if that'd be useful or make another PR though.
2023-12-10 11:42:47 +00:00
Federico Rinaldi
47fa620034
Refactor function update_accessibility_nodes (#10911)
# Objective

`update_accessibility_nodes` is one of the most nested functions in the
entire Bevy repository, with a maximum of 9 levels of indentations. This
PR refactors it down to 3 levels of indentations, while improving
readability on other fronts. The result is a function that is actually
understandable at a first glance.

- This is a proof of concept to demonstrate that it is possible to
gradually lower the nesting limit proposed by #10896.

PS: I read AccessKit's documentation, but I don't have experience with
it. Therefore, naming of variables and subroutines may be a bit off.

PS2: I don't know if the test suite covers the functionality of this
system, but since I've spent quite some time on it and the changes were
simple, I'm pretty confident the refactor is functionally equivalent to
the original.

## Solution

I documented each change with a commit, but as a summary I did the
following to reduce nesting:

- I moved from `if-let` blocks to `let-else` statements where
appropriate to reduce rightward shift
- I extracted the closure body to a new function `update_adapter`
- I factored out parts of `update_adapter` into new functions
`queue_node_for_update` and `add_children_nodes`

**Note for reviewers:** GitHub's diff viewer is not the greatest in
showing horizontal code shifts, therefore you may want to use a
different tool like VSCode to review some commits, especially the second
one (anyway, that commit is very straightforward, despite changing many
lines).
2023-12-10 00:52:16 +00:00
ickshonpe
4a46f273a1
Clip outlines by the node's own clipping rect, not the parent's. (#10922)
# Objective

A nodes outline should be clipped using its own clipping rect, not its
parents.

fixes #10921

## Solution

Clip outlines by the node's own clipping rect, not the parent's.

If you compare the `overflow` ui example in main with this PR, you'll
see that the outlines that appear when you hover above the images are
now clipped along with the images.

---

## Changelog

* Outlines are now clipped using the node's own clipping rect, not the
parent's.
2023-12-10 00:51:19 +00:00
Mateusz Wachowiak
1523e8c409
Non-Intrusive refactor of play_queued_audio_system() (#10910)
# Objective

- Improve readability.
- Somewhat relates to #10896.

## Solution

- Use early returns to minimize nesting.
- Change `emitter_translation` to use `if let` instead of `map`.
2023-12-09 14:27:39 +00:00
Fratiman Bogdan - Gabriel
24060213b5
Renamed Accessibility plugin to AccessKitPlugin in bevy_winit (#10914)
# Objective
- Fixes #10901 

## Solution
- `bevy::a11y::AccessibilityPlugin` remains unchanged.
- Renamed `bevy::winit::accessibility::AccessibilityPlugin` to
`bevy::winit::accessibility::AccessKitPlugin`.
2023-12-09 14:22:33 +00:00
Federico Rinaldi
d4b21d0dea
Remove reference to default schedule (#10918)
Simple doc change since there is no more a default schedule after #8079.
2023-12-09 14:21:43 +00:00
irate
a4c27288c7
Deduplicate systems in bevy_audio (#10906)
# Objective
The `update_emitter_positions`, and `update_listener_positions` systems
are added for every call to `add_audio_source`.
Instead, add them once in the `AudioPlugin` directly.

Also merged the calls to `add_systems`.


Caught while working on my schedule visualizer c:
2023-12-07 19:43:16 +00:00
Nicola Papale
d2614f2d80
Add a couple assertions for system types (#10893)
# Objective

Test more complex function signatures for exclusive systems, and test
that `StaticSystemParam` is indeed a `SystemParam`.

I mean, it currently works, but might as well add a test for it.
2023-12-06 20:35:46 +00:00
Mateusz Wachowiak
1f97717a3d
Rename Input to ButtonInput (#10859)
# Objective

- Resolves #10853 

## Solution

- ~~Changed the name of `Input` struct to `PressableInput`.~~
- Changed the name of `Input` struct to `ButtonInput`.

## Migration Guide

- Breaking Change: Users need to rename `Input` to `ButtonInput` in
their projects.
2023-12-06 20:32:34 +00:00
Joona Aalto
d9aac887b5
Split Ray into Ray2d and Ray3d and simplify plane construction (#10856)
# Objective

A better alternative version of #10843.

Currently, Bevy has a single `Ray` struct for 3D. To allow better
interoperability with Bevy's primitive shapes (#10572) and some third
party crates (that handle e.g. spatial queries), it would be very useful
to have separate versions for 2D and 3D respectively.

## Solution

Separate `Ray` into `Ray2d` and `Ray3d`. These new structs also take
advantage of the new primitives by using `Direction2d`/`Direction3d` for
the direction:

```rust
pub struct Ray2d {
    pub origin: Vec2,
    pub direction: Direction2d,
}

pub struct Ray3d {
    pub origin: Vec3,
    pub direction: Direction3d,
}
```

and by using `Plane2d`/`Plane3d` in `intersect_plane`:

```rust
impl Ray2d {
    // ...
    pub fn intersect_plane(&self, plane_origin: Vec2, plane: Plane2d) -> Option<f32> {
        // ...
    }
}
```

---

## Changelog

### Added

- `Ray2d` and `Ray3d`
- `Ray2d::new` and `Ray3d::new` constructors
- `Plane2d::new` and `Plane3d::new` constructors

### Removed

- Removed `Ray` in favor of `Ray3d`

### Changed

- `direction` is now a `Direction2d`/`Direction3d` instead of a vector,
which provides guaranteed normalization
- `intersect_plane` now takes a `Plane2d`/`Plane3d` instead of just a
vector for the plane normal
- `Direction2d` and `Direction3d` now derive `Serialize` and
`Deserialize` to preserve ray (de)serialization

## Migration Guide

`Ray` has been renamed to `Ray3d`.

### Ray creation

Before:

```rust
Ray {
    origin: Vec3::ZERO,
    direction: Vec3::new(0.5, 0.6, 0.2).normalize(),
}
```

After:

```rust
// Option 1:
Ray3d {
    origin: Vec3::ZERO,
    direction: Direction3d::new(Vec3::new(0.5, 0.6, 0.2)).unwrap(),
}

// Option 2:
Ray3d::new(Vec3::ZERO, Vec3::new(0.5, 0.6, 0.2))
```

### Plane intersections

Before:

```rust
let result = ray.intersect_plane(Vec2::X, Vec2::Y);
```

After:

```rust
let result = ray.intersect_plane(Vec2::X, Plane2d::new(Vec2::Y));
```
2023-12-06 14:09:04 +00:00
Joona Aalto
f683b802f1
Impl TryFrom vector for directions and add InvalidDirectionError (#10884)
# Objective

Implement `TryFrom<Vec2>`/`TryFrom<Vec3>` for direction primitives as
considered in #10857.

## Solution

Implement `TryFrom` for the direction primitives.

These are all equivalent:

```rust
let dir2d = Direction2d::try_from(Vec2::new(0.5, 0.5)).unwrap();
let dir2d = Vec2::new(0.5, 0.5).try_into().unwrap(); // (assumes that the type is inferred)
let dir2d = Direction2d::new(Vec2::new(0.5, 0.5)).unwrap();
```

For error cases, an `Err(InvalidDirectionError)` is returned. It
contains the type of failure:

```rust
/// An error indicating that a direction is invalid.
#[derive(Debug, PartialEq)]
pub enum InvalidDirectionError {
    /// The length of the direction vector is zero or very close to zero.
    Zero,
    /// The length of the direction vector is `std::f32::INFINITY`.
    Infinite,
    /// The length of the direction vector is `NaN`.
    NaN,
}
```
2023-12-06 00:05:37 +00:00
Mateusz Wachowiak
5508915e9b
Add comment about scale factor in WindowMode (#10872)
# Objective

- Resolves #10784 

## Solution

- As @ickshonpe mentioned in #10784, this is intended behavior but could
benefit from mentioning it in docs.
- I'm also thinking about adding a helper function to disable os scaling
such as `disable_os_scaling()`, but not sure if it's needed.

---

## Changelog

> Add a comment about scaling behavior that happens, and point user to
how he can avoid that behavior.
2023-12-05 21:42:34 +00:00
TheBigCheese
9da65b10b4
Add EntityCommands.retain and EntityWorldMut.retain (#10873)
# Objective
Adds `EntityCommands.retain` and `EntityWorldMut.retain` to remove all
components except the given bundle from the entity.
Fixes #10865.

## Solution

I added a private unsafe function in `EntityWorldMut` called
`remove_bundle_info` which performs the shared behaviour of `remove` and
`retain`, namely taking a `BundleInfo` of components to remove, and
removing them from the given entity. Then `retain` simply gets all the
components on the entity and filters them by whether they are in the
bundle it was passed, before passing this `BundleInfo` into
`remove_bundle_info`.

`EntityCommands.retain` just creates a new type `Retain` which runs
`EntityWorldMut.retain` when run.

---

## Changelog

Added `EntityCommands.retain` and `EntityWorldMut.retain`, which remove
all components except the given bundle from the entity, they can also be
used to remove all components by passing `()` as the bundle.
2023-12-05 15:37:33 +00:00
ickshonpe
166686e0f2
Rename TextAlignment to JustifyText. (#10854)
# Objective

The name `TextAlignment` is really deceptive and almost every new user
gets confused about the differences between aligning text with
`TextAlignment`, aligning text with `Style` and aligning text with
anchor (when using `Text2d`).

## Solution

* Rename `TextAlignment` to `JustifyText`. The associated helper methods
are also renamed.
* Improve the doc comments for text explaining explicitly how the
`JustifyText` component affects the arrangement of text.
* Add some extra cases to the `text_debug` example that demonstate the
differences between alignment using `JustifyText` and alignment using
`Style`.
<img width="757" alt="text_debug_2"
src="https://github.com/bevyengine/bevy/assets/27962798/9d53e647-93f9-4bc7-8a20-0d9f783304d2">

---

## Changelog
* `TextAlignment` has been renamed to `JustifyText`
* `TextBundle::with_text_alignment` has been renamed to
`TextBundle::with_text_justify`
* `Text::with_alignment` has been renamed to `Text::with_justify`
* The `text_alignment` field of `TextMeasureInfo` has been renamed to
`justification`

## Migration Guide
* `TextAlignment` has been renamed to `JustifyText`
* `TextBundle::with_text_alignment` has been renamed to
`TextBundle::with_text_justify`
* `Text::with_alignment` has been renamed to `Text::with_justify`
* The `text_alignment` field of `TextMeasureInfo` has been renamed to
`justification`
2023-12-05 03:00:41 +00:00
Zachary Harrold
72adf2ae2a
Reduced TableRow as Casting (#10811)
# Objective

- Fixes #10806

## Solution

Replaced `new` and `index` methods for both `TableRow` and `TableId`
with `from_*` and `as_*` methods. These remove the need to perform
casting at call sites, reducing the total number of casts in the Bevy
codebase. Within these methods, an appropriate `debug_assertion` ensures
the cast will behave in an expected manner (no wrapping, etc.). I am
using a `debug_assertion` instead of an `assert` to reduce any possible
runtime overhead, however minimal. This choice is something I am open to
changing (or leaving up to another PR) if anyone has any strong
arguments for it.

---

## Changelog

- `ComponentSparseSet::sparse` stores a `TableRow` instead of a `u32`
(private change)
- Replaced `TableRow::new` and `TableRow::index` methods with
`TableRow::from_*` and `TableRow::as_*`, with `debug_assertions`
protecting any internal casting.
- Replaced `TableId::new` and `TableId::index` methods with
`TableId::from_*` and `TableId::as_*`, with `debug_assertions`
protecting any internal casting.
- All `TableId` methods are now `const`

## Migration Guide

- `TableRow::new` -> `TableRow::from_usize`
- `TableRow::index` -> `TableRow::as_usize`
- `TableId::new` -> `TableId::from_usize`
- `TableId::index` -> `TableId::as_usize`

---

## Notes

I have chosen to remove the `index` and `new` methods for the following
chain of reasoning:

- Across the codebase, `new` was called with a mixture of `u32` and
`usize` values. Likewise for `index`.
- Choosing `new` to either be `usize` or `u32` would break half of these
call-sites, requiring `as` casting at the site.
- Adding a second method `new_u32` or `new_usize` avoids the above, bu
looks visually inconsistent.
- Therefore, they should be replaced with `from_*` and `as_*` methods
instead.

Worth noting is that by updating `ComponentSparseSet`, there are now
zero instances of interacting with the inner value of `TableRow` as a
`u32`, it is exclusively used as a `usize` value (due to interactions
with methods like `len` and slice indexing). I have left the `as_u32`
and `from_u32` methods as the "proper" constructors/getters.
2023-12-05 02:44:33 +00:00
irate
83ee6de1da
Remove From implementations from the direction types (#10857)
This removes the `From<Vec2/3>` implementations for the direction types.
It doesn't seem right to have when it only works if the vector is
nonzero and finite and produces NaN otherwise.

Added `Direction2d/3d::new` which uses `Vec2/3::try_normalize` to
guarantee it returns either a valid direction or `None`.

This should make it impossible to create an invalid direction, which I
think was the intention with these types.
2023-12-05 02:44:27 +00:00
Jos Feenstra
18ac125997
Add helper macro's for logging only once (#10808)
# Objective

Fixes #10291

This adds a way to easily log messages once within system which are
called every frame.

## Solution

Opted for a macro-based approach. The fact that the 'once' call is
tracked per call site makes the `log_once!()` macro very versatile and
easy-to-use. I suspect it will be very handy for all of us, but
especially beginners, to get some initial feedback from systems without
spamming up the place!

I've made the macro's return its internal `has_fired` state, for
situations in which that might be useful to know (trigger something else
alongside the log, for example).

Please let me know if I placed the macro's in the right location, and if
you would like me to do something more clever with the macro's
themselves, since its looking quite copy-pastey at the moment. I've
tried ways to replace 5 with 1 macro's, but no success yet.

One downside of this approach is: Say you wish to warn the user if a
resource is invalid. In this situation, the
`resource.is_valid()` check would still be performed every frame:
```rust
fn my_system(my_res: Res<MyResource>) {
   if !my_res.is_valid() {
      warn_once!("resource is invalid!");
   }
}
```
If you want to prevent that, you would still need to introduce a local
boolean. I don't think this is a very big deal, as expensive checks
shouldn't be called every frame in any case.


## Changelog
Added: `trace_once!()`, `debug_once!()`, `info_once!()`, `warn_once!()`,
and `error_once!()` log macros which fire only once per call site.
2023-12-05 01:56:40 +00:00
Stepan Koltsov
2653adf5d8
Make ComponentId typed in Components (#10770)
Trying to understand code. Types help.
2023-12-05 01:54:27 +00:00
Federico Rinaldi
c9368734d2
Remove identity map calls (#10848)
Removes calls to `Iterator::map` that don't do any work.
2023-12-04 20:44:53 +00:00
Federico Rinaldi
0400ef059b
Substitute get(0) with first() (#10847)
Substitute calls to `get(0)` with `first()`, improving readability.
2023-12-02 22:13:42 +00:00
Nathan
24c6a7df05
Clarifying Commands' purpose (#10837)
# Objective
As described in [Issue
#10805](https://github.com/bevyengine/bevy/issues/10805) I have changed
"impactful changes" to "structural changes"

## Solution
Updated the text "impactful" to "structural"
2023-12-02 10:07:19 +00:00
AxiomaticSemantics
b4c33da149
Fix typos in safety comment (#10827)
# Objective

- Minor fix for typos in safety comment

- Fix the typos.

Co-authored-by: ebola <dev@axiomatic>
2023-12-01 18:07:16 +00:00
Aldrich Suratos
cbf39b7eab
Deprecate QueryState::for_each_unchecked (#10815)
# Objective

Resolves Issue #10772.

## Solution

Added the deprecated warning for QueryState::for_each_unchecked, as
noted in the comments of PR #6773.
Followed the wording in the deprecation messages for `for_each` and
`for_each_mut`
2023-12-01 09:48:16 +00:00
James Liu
2148518758
Override QueryIter::fold to port Query::for_each perf gains to select Iterator combinators (#6773)
# Objective
After #6547, `Query::for_each` has been capable of automatic
vectorization on certain queries, which is seeing a notable (>50% CPU
time improvements) for iteration. However, `Query::for_each` isn't
idiomatic Rust, and lacks the flexibility of iterator combinators.

Ideally, `Query::iter` and friends should be able to achieve the same
results. However, this does seem to blocked upstream
(rust-lang/rust#104914) by Rust's loop optimizations.

## Solution
This is an intermediate solution and refactor. This moves the
`Query::for_each` implementation onto the `Iterator::fold`
implementation for `QueryIter` instead. This should result in the same
automatic vectorization optimization on all `Iterator` functions that
internally use fold, including `Iterator::for_each`, `Iterator::count`,
etc.

With this, it should close the gap between the two completely.
Internally, this PR changes `Query::for_each` to use
`query.iter().for_each(..)` instead of the duplicated implementation.

Separately, the duplicate implementations of internal iteration (i.e.
`Query::par_for_each`) now use portions of the current `Query::for_each`
implementation factored out into their own functions.

This also massively cleans up our internal fragmentation of internal
iteration options, deduplicating the iteration code used in `for_each`
and `par_iter().for_each()`.

---

## Changelog
Changed: `Query::for_each`, `Query::for_each_mut`, `Query::for_each`,
and `Query::for_each_mut` have been moved to `QueryIter`'s
`Iterator::for_each` implementation, and still retains their performance
improvements over normal iteration. These APIs are deprecated in 0.13
and will be removed in 0.14.

---------

Co-authored-by: JoJoJet <21144246+JoJoJet@users.noreply.github.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-12-01 09:09:55 +00:00
robtfm
74ead1eb80
Add GltfLoaderSettings (#10804)
# Objective

when loading gltfs we may want to filter the results. in particular, i
need to be able to exclude cameras.

i can do this already by modifying the gltf after load and before
spawning, but it seems like a useful general option.

## Solution

add `GltfLoaderSettings` struct with bool members:
- `load_cameras` : checked before processing camera nodes.
- `load_lights` : checked before processing light nodes
- `load_meshes` : checked before loading meshes, materials and morph
weights

Existing code will work as before. Now you also have the option to
restrict what parts of the gltf are loaded. For example, to load a gltf
but exclude the cameras, replace a call to
`asset_server.load("my.gltf")` with:
```rust
asset_server.load_with_settings(
    "my.gltf",
    |s: &mut GltfLoaderSettings| {
        s.load_cameras = false;
    }
);
```

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-11-30 00:34:45 +00:00
Carter Anderson
0a588dbfd9
Allow removing and reloading assets with live handles (#10785)
# Objective

Fixes #10444 

Currently manually removing an asset prevents it from being reloaded
while there are still active handles. Doing so will result in a panic,
because the storage entry has been marked as "empty / None" but the ID
is still assumed to be active by the asset server.

Patterns like `images.remove() -> asset_server.reload()` and
`images.remove() -> images.insert()` would fail if the handle was still
alive.

## Solution

Most of the groundwork for this was already laid in Bevy Asset V2. This
is largely just a matter of splitting out `remove` into two separate
operations:

* `remove_dropped`: remove the stored asset, invalidate the internal
Assets entry (preventing future insertions with the old id), and recycle
the id
* `remove_still_alive`: remove the stored asset, but leave the entry
otherwise untouched (and dont recycle the id).

`remove_still_alive` and `insert` can be called any number of times (in
any order) for an id until `remove_dropped` has been called, which will
invalidate the id.

From a user-facing perspective, there are no API changes and this is non
breaking. The public `Assets::remove` will internally call
`remove_still_alive`. `remove_dropped` can only be called by the
internal "handle management" system.

---

## Changelog

- Fix a bug preventing `Assets::remove` from blocking future inserts for
a specific `AssetIndex`.
2023-11-29 23:32:13 +00:00
Elabajaba
0f5d8128c9
Fix prepass binding issues causing crashes when not all prepass bindings are used (#10788)
# Objective

Fixes https://github.com/bevyengine/bevy/issues/10786

## Solution

The bind_group_layout entries for the prepass were wrong when not all 4
prepass textures were used, as it just zipped [17, 18, 19, 20] with the
smallvec of prepass `bind_group_layout` entries that potentially didn't
contain 4 entries. (eg. if you had a depth and motion vector prepass but
no normal prepass, then depth would be correct but the entry for the
motion vector prepass would be 18 (normal prepass' spot) instead of 19).

Change the prepass `get_bind_group_layout_entries` function to return an
array of `[Option<BindGroupLayoutEntryBuilder>; 4]` and only add the
layout entry if it exists.
2023-11-29 23:11:12 +00:00
robtfm
47447beb93
try_insert Aabbs (#10801)
# Objective

avoid panics from `calculate_bounds` systems if entities are despawned
in PostUpdate.

there's a running general discussion (#10166) about command panicking.
in the meantime we may as well fix up some cases where it's clear a
failure to insert is safe.

## Solution

change `.insert(aabb)` to `.try_insert(aabb)`
2023-11-29 15:00:50 +00:00
Stepan Koltsov
d04a2204f5
Make IntoSystemConfigs::into_configs public API (visible in docs) (#10624)
`IntoSystemConfigs::into_configs` function is public, but hidden from
documentation. This PR makes it visible.

Fixes #10622.
2023-11-29 14:38:37 +00:00
Gino Valente
daa8bf20df
Fix nested generics in Reflect derive (#10791)
# Objective

> Issue raised on
[Discord](https://discord.com/channels/691052431525675048/1002362493634629796/1179182488787103776)

Currently the following code fails due to a missing `TypePath` bound:

```rust
#[derive(Reflect)] struct Foo<T>(T);
#[derive(Reflect)] struct Bar<T>(Foo<T>);
#[derive(Reflect)] struct Baz<T>(Bar<Foo<T>>);
```

## Solution

Add `TypePath` to the per-field bounds instead of _just_ the generic
type parameter bounds.

### Related Work

It should be noted that #9046 would help make these kinds of issues
easier to work around and/or avoid entirely.

---

## Changelog

- Fixes missing `TypePath` requirement when deriving `Reflect` on nested
generics
2023-11-29 01:46:09 +00:00
Carter Anderson
4221f7e7e9
Print precise and correct watch warnings (and only when necessary) (#10787)
# Objective

Fixes #10401 

## Solution

* Allow sources to register specific processed/unprocessed watch
warnings.
* Specify per-platform watch warnings. This removes the need to cover
all platform cases in one warning message.
* Only register watch warnings for the _processed_ embedded source, as
warning about watching unprocessed embedded isn't helpful.

---

## Changelog

- Asset sources can now register specific watch warnings.
2023-11-29 00:35:13 +00:00
Stepan Koltsov
506bdc5e68
Remove pointless trait implementation exports in bevy_reflect (#10771)
Trait implementations do not need to be reexported to be used.

```
warning: unused import: `self::std::*`
   --> crates/bevy_reflect/src/lib.rs:502:13
    |
502 |     pub use self::std::*;
    |             ^^^^^^^^^^^^
    |
    = note: `#[warn(unused_imports)]` on by default

warning: unused import: `self::uuid::*`
   --> crates/bevy_reflect/src/lib.rs:503:13
    |
503 |     pub use self::uuid::*;
    |             ^^^^^^^^^^^^^

warning: unused import: `impls::*`
   --> crates/bevy_reflect/src/lib.rs:525:9
    |
525 | pub use impls::*;
    |         ^^^^^^^^
```
2023-11-29 00:11:06 +00:00
Mateusz Wachowiak
3ec1b5c323
Mention DynamicSceneBuilder in doc comment (#10780)
# Objective

Resolves #10773

## Solution

Added comment mentioning DynamicSceneBuilder
2023-11-28 23:45:00 +00:00
tygyh
fd308571c4
Remove unnecessary path prefixes (#10749)
# Objective

- Shorten paths by removing unnecessary prefixes

## Solution

- Remove the prefixes from many paths which do not need them. Finding
the paths was done automatically using built-in refactoring tools in
Jetbrains RustRover.
2023-11-28 23:43:40 +00:00
Sludge
b19ea0dd1d
Reflect and register audio-related types (#10484)
# Objective

These type are unavailable to editors and scripting interfaces making
use of reflection.

## Solution

`#[derive(Reflect)]` and call `.register_type` during plugin
initialization.

---

## Changelog

### Added

- Implement `Reflect` for audio-related types, and register them.
2023-11-28 22:26:58 +00:00
JMS55
4bf20e7d27
Swap material and mesh bind groups (#10485)
# Objective
- Materials should be a more frequent rebind then meshes (due to being
able to use a single vertex buffer, such as in #10164) and therefore
should be in a higher bind group.

---

## Changelog
- For 2d and 3d mesh/material setups (but not UI materials, or other
rendering setups such as gizmos, sprites, or text), mesh data is now in
bind group 1, and material data is now in bind group 2, which is swapped
from how they were before.

## Migration Guide
- Custom 2d and 3d mesh/material shaders should now use bind group 2
`@group(2) @binding(x)` for their bound resources, instead of bind group
1.
- Many internal pieces of rendering code have changed so that mesh data
is now in bind group 1, and material data is now in bind group 2.
Semi-custom rendering setups (that don't use the Material or Material2d
APIs) should adapt to these changes.
2023-11-28 22:26:22 +00:00
scottmcm
a902ea6f85
Save an instruction in EntityHasher (#10648)
# Objective

Keep essentially the same structure of `EntityHasher` from #9903, but
rephrase the multiplication slightly to save an instruction.

cc @superdump 
Discord thread:
https://discord.com/channels/691052431525675048/1172033156845674507/1174969772522356756

## Solution

Today, the hash is
```rust
        self.hash = i | (i.wrapping_mul(FRAC_U64MAX_PI) << 32);
```
with `i` being `(generation << 32) | index`.

Expanding things out, we get
```rust
i | ( (i * CONST) << 32 )
= (generation << 32) | index | ((((generation << 32) | index) * CONST) << 32)
= (generation << 32) | index | ((index * CONST) << 32)  // because the generation overflowed
= (index * CONST | generation) << 32 | index
```

What if we do the same thing, but with `+` instead of `|`? That's almost
the same thing, except that it has carries, which are actually often
better in a hash function anyway, since it doesn't saturate. (`|` can be
dangerous, since once something becomes `-1` it'll stay that, and
there's no mixing available.)

```rust
(index * CONST + generation) << 32 + index
= (CONST << 32 + 1) * index + generation << 32
= (CONST << 32 + 1) * index + (WHATEVER << 32 + generation) << 32 // because the extra overflows and thus can be anything
= (CONST << 32 + 1) * index + ((CONST * generation) << 32 + generation) << 32 // pick "whatever" to be something convenient
= (CONST << 32 + 1) * index + ((CONST << 32 + 1) * generation) << 32
= (CONST << 32 + 1) * index +((CONST << 32 + 1) * (generation << 32)
= (CONST << 32 + 1) * (index + generation << 32)
= (CONST << 32 + 1) * (generation << 32 | index)
= (CONST << 32 + 1) * i
```

So we can do essentially the same thing using a single multiplication
instead of doing multiply-shift-or.

LLVM was already smart enough to merge the shifting into a
multiplication, but this saves the extra `or`:

![image](https://github.com/bevyengine/bevy/assets/18526288/d9396614-2326-4730-abbe-4908c01b5ace)
<https://rust.godbolt.org/z/MEvbz4eo4>

It's a very small change, and often will disappear in load latency
anyway, but it's a couple percent faster in lookups:

![image](https://github.com/bevyengine/bevy/assets/18526288/c365ec85-6adc-4f6d-8fa6-a65146f55a75)

(There was more of an improvement here before #10558, but with `to_bits`
being a single `qword` load now, keeping things mostly as it is turned
out to be better than the bigger changes I'd tried in #10605.)

---

## Changelog

(Probably skip it)

## Migration Guide

(none needed)
2023-11-28 12:37:30 +00:00
robtfm
d95d20f4b1
prepass vertex shader always outputs world position (#10657)
# Objective

the pbr prepass vertex shader currently only sets
`VertexOutput::world_position` when deferred or motion prepasses are
enabled.
the field is always in the vertex output so is otherwise undetermined,
and the calculation is very cheap.

## Solution

always set the world position in the pbr prepass vert shader.
2023-11-28 12:13:28 +00:00
davier
e44b74fb6a
Provide GlobalsUniform in UiMaterial shaders (#10739)
# Objective

`GlobalsUniform` provides the current time to shaders, which is useful
for animations. `UiMaterial` is an abstraction that makes it easier to
write custom shaders for UI elements.
This PR makes it possible to use the `GlobalsUniform` in `UiMaterial`
shaders.

## Solution

The `GlobalsUniform` is bound to `@group(0) @binding(1)`. It is
accessible in shaders with:
```wgsl
#import bevy_render::globals::Globals

@group(0) @binding(1)
var<uniform> globals: Globals;
```

---

## Changelog

Added `GlobalsUniform` in `UiMaterial` shaders

## Discussion

Should I modify the existing ui_material example to showcase this?
2023-11-28 12:08:28 +00:00
Kanabenki
0e9f6e92ea
Add clippy::manual_let_else at warn level to lints (#10684)
# Objective

Related to #10612.

Enable the
[`clippy::manual_let_else`](https://rust-lang.github.io/rust-clippy/master/#manual_let_else)
lint as a warning. The `let else` form seems more idiomatic to me than a
`match`/`if else` that either match a pattern or diverge, and from the
clippy doc, the lint doesn't seem to have any possible false positive.

## Solution

Add the lint as warning in `Cargo.toml`, refactor places where the lint
triggers.
2023-11-28 04:15:27 +00:00
IceSentry
6d0c11a28f
Bind group layout entries (#10224)
# Objective

- Follow up to #9694

## Solution

- Same api as #9694 but adapted for `BindGroupLayoutEntry`
- Use the same `ShaderStages` visibilty for all entries by default
- Add `BindingType` helper function that mirror the wgsl equivalent and
that make writing layouts much simpler.

Before:
```rust
let layout = render_device.create_bind_group_layout(&BindGroupLayoutDescriptor {
    label: Some("post_process_bind_group_layout"),
    entries: &[
        BindGroupLayoutEntry {
            binding: 0,
            visibility: ShaderStages::FRAGMENT,
            ty: BindingType::Texture {
                sample_type: TextureSampleType::Float { filterable: true },
                view_dimension: TextureViewDimension::D2,
                multisampled: false,
            },
            count: None,
        },
        BindGroupLayoutEntry {
            binding: 1,
            visibility: ShaderStages::FRAGMENT,
            ty: BindingType::Sampler(SamplerBindingType::Filtering),
            count: None,
        },
        BindGroupLayoutEntry {
            binding: 2,
            visibility: ShaderStages::FRAGMENT,
            ty: BindingType::Buffer {
                ty: bevy::render::render_resource::BufferBindingType::Uniform,
                has_dynamic_offset: false,
                min_binding_size: Some(PostProcessSettings::min_size()),
            },
            count: None,
        },
    ],
});
```
After:
```rust
let layout = render_device.create_bind_group_layout(
    "post_process_bind_group_layout"),
    &BindGroupLayoutEntries::sequential(
        ShaderStages::FRAGMENT,
        (
            texture_2d_f32(),
            sampler(SamplerBindingType::Filtering),
            uniform_buffer(false, Some(PostProcessSettings::min_size())),
        ),
    ),
);
```

Here's a more extreme example in bevy_solari:
86dab7f5da

---

## Changelog

- Added `BindGroupLayoutEntries` and all `BindingType` helper functions.

## Migration Guide

`RenderDevice::create_bind_group_layout()` doesn't take a
`BindGroupLayoutDescriptor` anymore. You need to provide the parameters
separately

```rust
// 0.12
let layout = render_device.create_bind_group_layout(&BindGroupLayoutDescriptor {
    label: Some("post_process_bind_group_layout"),
    entries: &[
        BindGroupLayoutEntry {
			// ...
        },
    ],
});

// 0.13
let layout = render_device.create_bind_group_layout(
	"post_process_bind_group_layout",
    &[
        BindGroupLayoutEntry {
			// ...
        },
    ],
);
```

## TODO

- [x] implement a `Dynamic` variant
- [x] update the `RenderDevice::create_bind_group_layout()` api to match
the one from `RenderDevice::creat_bind_group()`
- [x] docs
2023-11-28 04:00:49 +00:00
Mark Wainwright
f0a8994f55
Split WorldQuery into WorldQueryData and WorldQueryFilter (#9918)
# Objective

- Fixes #7680
- This is an updated for https://github.com/bevyengine/bevy/pull/8899
which had the same objective but fell a long way behind the latest
changes


## Solution

The traits `WorldQueryData : WorldQuery` and `WorldQueryFilter :
WorldQuery` have been added and some of the types and functions from
`WorldQuery` has been moved into them.

`ReadOnlyWorldQuery` has been replaced with `ReadOnlyWorldQueryData`. 

`WorldQueryFilter` is safe (as long as `WorldQuery` is implemented
safely).

`WorldQueryData` is unsafe - safely implementing it requires that
`Self::ReadOnly` is a readonly version of `Self` (this used to be a
safety requirement of `WorldQuery`)

The type parameters `Q` and `F` of `Query` must now implement
`WorldQueryData` and `WorldQueryFilter` respectively.

This makes it impossible to accidentally use a filter in the data
position or vice versa which was something that could lead to bugs.
~~Compile failure tests have been added to check this.~~

It was previously sometimes useful to use `Option<With<T>>` in the data
position. Use `Has<T>` instead in these cases.

The `WorldQuery` derive macro has been split into separate derive macros
for `WorldQueryData` and `WorldQueryFilter`.

Previously it was possible to derive both `WorldQuery` for a struct that
had a mixture of data and filter items. This would not work correctly in
some cases but could be a useful pattern in others. *This is no longer
possible.*

---

## Notes

- The changes outside of `bevy_ecs` are all changing type parameters to
the new types, updating the macro use, or replacing `Option<With<T>>`
with `Has<T>`.

- All `WorldQueryData` types always returned `true` for `IS_ARCHETYPAL`
so I moved it to `WorldQueryFilter` and
replaced all calls to it with `true`. That should be the only logic
change outside of the macro generation code.

- `Changed<T>` and `Added<T>` were being generated by a macro that I
have expanded. Happy to revert that if desired.

- The two derive macros share some functions for implementing
`WorldQuery` but the tidiest way I could find to implement them was to
give them a ton of arguments and ask clippy to ignore that.

## Changelog

### Changed
- Split `WorldQuery` into `WorldQueryData` and `WorldQueryFilter` which
now have separate derive macros. It is not possible to derive both for
the same type.
- `Query` now requires that the first type argument implements
`WorldQueryData` and the second implements `WorldQueryFilter`

## Migration Guide

- Update derives

```rust
// old
#[derive(WorldQuery)]
#[world_query(mutable, derive(Debug))]
struct CustomQuery {
    entity: Entity,
    a: &'static mut ComponentA
}

#[derive(WorldQuery)]
struct QueryFilter {
    _c: With<ComponentC>
}

// new 
#[derive(WorldQueryData)]
#[world_query_data(mutable, derive(Debug))]
struct CustomQuery {
    entity: Entity,
    a: &'static mut ComponentA,
}

#[derive(WorldQueryFilter)]
struct QueryFilter {
    _c: With<ComponentC>
}
```
- Replace `Option<With<T>>` with `Has<T>`

```rust
/// old
fn my_system(query: Query<(Entity, Option<With<ComponentA>>)>)
{
  for (entity, has_a_option) in query.iter(){
    let has_a:bool = has_a_option.is_some();
    //todo!()
  }
}

/// new
fn my_system(query: Query<(Entity, Has<ComponentA>)>)
{
  for (entity, has_a) in query.iter(){
    //todo!()
  }
}
```

- Fix queries which had filters in the data position or vice versa.

```rust
// old
fn my_system(query: Query<(Entity, With<ComponentA>)>)
{
  for (entity, _) in query.iter(){
  //todo!()
  }
}

// new
fn my_system(query: Query<Entity, With<ComponentA>>)
{
  for entity in query.iter(){
  //todo!()
  }
}

// old
fn my_system(query: Query<AnyOf<(&ComponentA, With<ComponentB>)>>)
{
  for (entity, _) in query.iter(){
  //todo!()
  }
}

// new
fn my_system(query: Query<Option<&ComponentA>, Or<(With<ComponentA>, With<ComponentB>)>>)
{
  for entity in query.iter(){
  //todo!()
  }
}

```

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-11-28 03:56:07 +00:00
Carter Anderson
90958104cb
Ensure instance_index push constant is always used in prepass.wgsl (#10706)
# Objective

 Kind of helps #10509 

## Solution

Add a line to `prepass.wgsl` that ensure the `instance_index` push
constant is always used on WebGL 2. This is not a full fix, as the
_second_ a custom shader is used that doesn't use the push constant, the
breakage will resurface. We have satisfying medium term and long term
solutions. This is just a short term hack for 0.12.1 that will make more
cases work. See #10509 for more details.
2023-11-28 01:13:25 +00:00
Helix
879893c30a
fix insert_reflect panic caused by clone_value (#10627)
# Objective

- `insert_reflect` relies on `reflect_type_path`, which doesn't gives
the actual type path for object created by `clone_value`, leading to an
unexpected panic. This is a workaround for it.
- Fix #10590 

## Solution

- Tries to get type path from `get_represented_type_info` if get failed
from `reflect_type_path`.

---

## Defect remaining

- `get_represented_type_info` implies a shortage on performance than
using `TypeRegistry`.
2023-11-28 00:17:10 +00:00
Carter Anderson
cc6c4d65ed
Fix GLTF scene dependencies and make full scene renders predictable (#10745)
# Objective

Fixes #10688

There were a number of issues at play:

1. The GLTF loader was not registering Scene dependencies properly. They
were being registered at the root instead of on the scene assets. This
made `LoadedWithDependencies` fire immediately on load.
2. Recursive labeled assets _inside_ of labeled assets were not being
loaded. This only became relevant for scenes after fixing (1) because we
now add labeled assets to the nested scene `LoadContext` instead of the
root load context. I'm surprised nobody has hit this yet. I'm glad I
caught it before somebody hit it.
3. Accessing "loaded with dependencies" state on the Asset Server is
boilerplatey + error prone (because you need to manually query two
states).

## Solution

1. In GltfLoader, use a nested LoadContext for scenes and load
dependencies through that context.
2. In the `AssetServer`, load labeled assets recursively.
3. Added a simple `asset_server.is_loaded_with_dependencies(id)`

I also added some docs to `LoadContext` to help prevent this problem in
the future.

---

## Changelog

- Added `AssetServer::is_loaded_with_dependencies`
- Fixed GLTF Scene dependencies
- Fixed nested labeled assets not being loaded

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-11-27 22:42:28 +00:00
Zachary Harrold
6e871ab919
Implement Drop for CommandQueue (#10746)
# Objective

- Fixes #10676, preventing a possible memory leak for commands which
owned resources.

## Solution

Implemented `Drop` for `CommandQueue`. This has been done entirely in
the private API of `CommandQueue`, ensuring no breaking changes. Also
added a unit test, `test_command_queue_inner_drop_early`, based on the
reproduction steps as outlined in #10676.

## Notes

I believe this can be applied to `0.12.1` as well, but I am uncertain of
the process to make that kind of change. Please let me know if there's
anything I can do to help with the back-porting of this change.

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-11-27 22:35:36 +00:00
Carter Anderson
fa903a122f
AssetMetaMode (#10623)
# Objective

Fixes #10157

## Solution

Add `AssetMetaCheck` resource which can configure when/if asset meta
files will be read:

```rust
app
  // Never attempts to look up meta files. The default meta configuration will be used for each asset.
  .insert_resource(AssetMetaCheck::Never)
  .add_plugins(DefaultPlugins)
```


This serves as a band-aid fix for the issue with wasm's
`HttpWasmAssetReader` creating a bunch of requests for non-existent
meta, which can slow down asset loading (by waiting for the 404
response) and creates a bunch of noise in the logs. This also provides a
band-aid fix for the more serious issue of itch.io deployments returning
403 responses, which results in full failure of asset loads.

If users don't want to include meta files for all deployed assets for
web builds, and they aren't using meta files at all, they should set
this to `AssetMetaCheck::Never`.

If users do want to include meta files for specific assets, they can use
`AssetMetaCheck::Paths`, which will only look up meta for those paths.

Currently, this defaults to `AssetMetaCheck::Always`, which makes this
fully non-breaking for the `0.12.1` release. _**However it _is_ worth
discussing making this `AssetMetaCheck::Never` by default**_, given that
I doubt most people are using meta files without the Asset Processor
enabled. This would be a breaking change, but it would make WASM / Itch
deployments work by default, which is a pretty big win imo. The downside
is that people using meta files _without_ processing would need to
manually enable `AssetMetaCheck::Always`, which is also suboptimal.

When in `AssetMetaCheck::Processed`, the meta check resource is ignored,
as processing requires asset meta files to function.

In general, I don't love adding this knob as things should ideally "just
work" in all cases. But this is the reality of the current situation.

---

## Changelog

- Added `AssetMetaCheck` resource, which can configure when/if asset
meta files will be read
2023-11-27 22:32:36 +00:00
Aldrich Suratos
1e2132672e
Copy over docs for Condition trait from PR #10718 (#10748)
# Objective

Resolves #10743.

## Solution

Copied over the documentation written by @stepancheng from PR #10718.

I left out the lines from the doctest where `<()>` is removed, as that
seemed to be the part people couldn't decide on whether to keep or not.
2023-11-27 16:33:22 +00:00
Cameron
53919c3e70
Wait until FixedUpdate can see events before dropping them (#10077)
## Objective
 
Currently, events are dropped after two frames. This cadence wasn't
*chosen* for a specific reason, double buffering just lets events
persist for at least two frames. Events only need to be dropped at a
predictable point so that the event queues don't grow forever (i.e.
events should never cause a memory leak).
 
Events (and especially input events) need to be observable by systems in
`FixedUpdate`, but as-is events are dropped before those systems even
get a chance to see them.
 
## Solution
 
Instead of unconditionally dropping events in `First`, require
`FixedUpdate` to first queue the buffer swap (if the `TimePlugin` has
been installed). This way, events are only dropped after a frame that
runs `FixedUpdate`.
 
## Future Work

In the same way we have independent copies of `Time` for tracking time
in `Main` and `FixedUpdate`, we will need independent copies of `Input`
for tracking press/release status correctly in `Main` and `FixedUpdate`.

--
 
Every run of `FixedUpdate` covers a specific timespan. For example, if
the fixed timestep `Δt` is 10ms, the first three `FixedUpdate` runs
cover `[0ms, 10ms)`, `[10ms, 20ms)`, and `[20ms, 30ms)`.
 
`FixedUpdate` can run many times in one frame. For truly
framerate-independent behavior, each `FixedUpdate` should only see the
events that occurred in its covered timespan, but what happens right now
is the first step in the frame reads all pending events.

Fixing that will require timestamped events.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-11-26 23:04:41 +00:00
extrawurst
9849221522
add new event WindowOccluded from winit (#10735)
forward for bevy user to consume

# Objective

- since winit 0.27 an event WindowOccluded will be produced:
https://docs.rs/winit/latest/winit/event/enum.WindowEvent.html#variant.Occluded
- on ios this is currently the only way to know if an app comes back
from the background which is an important time to to things (like
resetting the badge)

## Solution

- pick up the winit event and forward it to a new `EventWriter`

---

## Changelog

### Added
- new Event `WindowOccluded` added allowing to hook into
`WindowEvent::Occluded` of winit
2023-11-26 21:58:54 +00:00
Torstein Grindvik
73bb310304
impl From<Color> for ClearColorConfig (#10734)
# Objective

I tried setting `ClearColorConfig` in my app via `Color::FOO.into()`
expecting it to work, but the impl was missing.

## Solution

- Add `impl From<Color> for ClearColorConfig`
- Change examples to use this impl

## Changelog

### Added

- `ClearColorConfig` can be constructed via `.into()` on a `Color`

---------

Signed-off-by: Torstein Grindvik <torstein.grindvik@muybridge.com>
Co-authored-by: Torstein Grindvik <torstein.grindvik@muybridge.com>
2023-11-26 20:48:03 +00:00
Torstein Grindvik
4788315fd0
Use as_image_copy where possible (#10733)
# Objective

`wgpu` has a helper method `texture.as_image_copy()` for a common
pattern when making a default-like `ImageCopyTexture` from a texture.

This is used in various places in Bevy for texture copy operations, but
it was not used where `write_texture` is called.

## Solution

- Replace struct `ImageCopyTexture` initialization with
`texture.as_image_copy()` where appropriate

Signed-off-by: Torstein Grindvik <torstein.grindvik@muybridge.com>
Co-authored-by: Torstein Grindvik <torstein.grindvik@muybridge.com>
2023-11-26 19:24:32 +00:00
François
89d652ba3a
don't run update before window creation in winit (#10741)
# Objective

- Window size, scale and position are not correct on the first execution
of the systems
- Fixes #10407,  fixes #10642

## Solution

- Don't run `update` before we get a chance to create the window in
winit
- Finish reverting #9826 after #10389
2023-11-26 01:26:44 +00:00
Gino Valente
13f2749021
bevy_utils: Export generate_composite_uuid utility function (#10496)
# Objective

The `generate_composite_uuid` utility function hidden in
`bevy_reflect::__macro_exports` could be generally useful to users.

For example, I previously relied on `Hash` to generate a `u64` to create
a deterministic `HandleId`. In v0.12, `HandleId` has been replaced by
`AssetId` which now requires a `Uuid`, which I could generate with this
function.

## Solution

Relocate `generate_composite_uuid` from `bevy_reflect::__macro_exports`
to `bevy_utils::uuid`.

It is still re-exported under `bevy_reflect::__macro_exports` so there
should not be any breaking changes (although, users should generally not
rely on pseudo-private/hidden modules like `__macro_exports`).

I chose to keep it in `bevy_reflect::__macro_exports` so as to not
clutter up our public API and to reduce the number of changes in this
PR. We could have also marked the export as `#[doc(hidden)]`, but
personally I like that we have a dedicated module for this (makes it
clear what is public and what isn't when just looking at the macro
code).

---

## Changelog

- Moved `generate_composite_uuid` to `bevy_utils::uuid` and made it
public
  - Note: it was technically already public, just hidden
2023-11-25 23:21:35 +00:00
Stepan Koltsov
c454b26c38
Some explanations for Window component (#10714) 2023-11-25 21:13:27 +00:00
Sludge
3c8c257fa3
Add a depth_bias to Material2d (#10683)
# Objective

It is currently impossible to control the relative ordering of two 2D
materials at the same depth. This is required to implement wireframes
for 2D meshes correctly
(https://github.com/bevyengine/bevy/issues/5881).

## Solution

Add a `Material2d::depth_bias` function that mirrors the existing 3D
`Material::depth_bias` function.

(this is pulled out of https://github.com/bevyengine/bevy/pull/10489)

---

## Changelog

### Added

- Added `Material2d::depth_bias`

## Migration Guide

`PreparedMaterial2d` has a new `depth_bias` field. A value of 0.0 can be
used to get the previous behavior.
2023-11-25 21:12:46 +00:00
Aldrich Suratos
a84d8c3239
Fix typo in resolve_outlines_system (#10730)
# Objective

Resolves  #10727.

`outline.width` was being assigned to `node.outline_offset` instead of
`outline.offset`.

## Solution

Changed `.width` to `.offset` in line 413.
2023-11-25 14:23:17 +00:00
wgxer
4eafd60ce9
Add wgpu_pass method to TrackedRenderPass (#10722)
# Objective

- Fixes  #10707 

## Solution

- Add a method to obtain `RenderPass` to `TrackedRenderPass` simillar to
`RenderDevice::wgpu_device`

---

## Changelog

Added `wgpu_pass` method to `TrackedRenderPass`
2023-11-25 03:11:24 +00:00
Mincong Lu
c33bacd5fd
Make bevy_app and reflect opt-out for bevy_hierarchy. (#10721)
# Objective

Bevy_hierarchy is very useful for ECS only usages of bevy_ecs, but it
currently pulls in bevy_reflect, bevy_app and bevy_core with no way to
opt out.

## Solution

This PR provides features `bevy_app` and `reflect` that are enabled by
default. If disabled, they should remove these dependencies from
bevy_hierarchy.

---

## Changelog

Added features `bevy_app` and `reflect` to bevy_hierarchy.
2023-11-25 03:05:38 +00:00
Alice Cecile
1065028154
Remove trailing whitespace (#10723)
# Objective

- Make CI green.

## Solution

- Remove one (1) space.

---------

Co-authored-by: Alice Cecile <alice.i.cecil@gmail.com>
2023-11-24 16:31:55 +00:00
Mike
11b1b3a24f
delete methods deprecated in 0.12 (#10693)
## Changelog

- delete methods deprecated in 0.12
2023-11-24 16:15:47 +00:00
Trent
6f56380826
bump bevy_tasks futures-lite to 2.0.1 (#10675)
# Objective

Updates [`futures-lite`](https://github.com/smol-rs/futures-lite) in
bevy_tasks to the next major version (1 -> 2).

Also removes the duplication of `futures-lite`, as `async-fs` requires v
2, so there are currently 2 copies of futures-lite in the dependency
tree.

Futures-lite has received [a number of
updates](https://github.com/smol-rs/futures-lite/blob/master/CHANGELOG.md)
since bevy's current version `1.4`.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Mike <mike.hsu@gmail.com>
2023-11-24 00:11:02 +00:00
Stepan Koltsov
790fafdbb0
Explain how AmbientLight is inserted and configured (#10712) 2023-11-24 00:07:58 +00:00
Hank Jordan
e85af0e366
Fix issue with Option serialization (#10705)
# Objective

- Fix #10499 

## Solution

- Use `.get_represented_type_info()` module path and type ident instead
of `.reflect_*` module path and type ident when serializing the `Option`
enum

---

## Changelog

- Fix serialization bug
- Add simple test
  - Add `serde_json` dev dependency
- Add `serde` with `derive` feature dev dependency (wouldn't compile for
me without it)

---------

Co-authored-by: hank <hank@hank.co.in>
Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
2023-11-23 14:04:51 +00:00
Stepan Koltsov
48af029f7b
Warn that Added/Changed filters do not see deferred changes (#10681)
Explain https://github.com/bevyengine/bevy/issues/10625.

This might be obvious to those familiar with Bevy internals, but it
surprised me.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-11-23 14:04:07 +00:00
Lixou
960f6e9131
remove double-hasing of typeid for handle (#10699)
# Objective

There is a double hash for the typeid for asset handles. (see
[this](https://github.com/bevyengine/bevy/issues/10695#issuecomment-1822340727)
for more info)

## Solution

- Remove the second hash of the typeid
2023-11-23 01:04:37 +00:00
Stepan Koltsov
85b6326970
Link to Main schedule docs from other schedules (#10691)
I incorrectly assumed that moving a system from `Update` to
`FixedUpdate` would simplify logic without hurting performance.

But this is not the case: if there's single-threaded long computation in
the `FixedUpdate`, the machine won't do anything else in parallel with
it. Which might be not what users expect.

So this PR adds a note. But maybe it is obvious, I don't know.
2023-11-22 20:50:37 +00:00
Stepan Koltsov
b0cc6bfd7e
Rustdoc example for Ref (#10682) 2023-11-22 20:20:39 +00:00
robtfm
ea01c3e387
Non uniform transmission samples (#10674)
# Objective

fix webgpu+chrome(119) textureSample in non-uniform control flow error

## Solution

modify view transmission texture sampling to use textureSampleLevel.
there are no mips for the view transmission texture, so this doesn't
change the result, but it removes the need for the samples to be in
uniform control flow.

note: in future we may add a mipchain to the transmission texture to
improve the blur effect. if uniformity analysis hasn't improved, this
would require switching to manual derivative calculations (which is
something we plan to do anyway).
2023-11-22 18:54:45 +00:00
Connor King
daf3547636
move gizmo arcs to their own file (#10660)
## Objective

- Split different types of gizmos into their own files

## Solution

- Move `arc_2d` and `Arc2dBuilder` into `arcs.rs`
- turns out there's no 3d arc function! I'll add one Soon(TM) in another
MR

## Changelog

- Changed
  - moved `gizmos::Arc2dBuilder` to `gizmos::arcs::Arc2dBuilder`

## Migration Guide

- `gizmos::Arc2dBuilder` -> `gizmos::arcs::Arc2dBuilder`
2023-11-22 14:58:34 +00:00
ickshonpe
bca057d7ec
Make clipped areas of UI nodes non-interactive (#10454)
# Objective

Problems:

* The clipped, non-visible regions of UI nodes are interactive.
* `RelativeCursorPostion` is set relative to the visible part of the
node. It should be relative to the whole node.
* The `RelativeCursorPostion::mouse_over` method returns `true` when the
mouse is over a clipped part of a node.

fixes #10470

## Solution

Intersect a node's bounding rect with its clipping rect before checking
if it contains the cursor.

Added the field `normalized_visible_node_rect` to
`RelativeCursorPosition`. This is set to the bounds of the unclipped
area of the node rect by `ui_focus_system` expressed in normalized
coordinates relative to the entire node.

Instead of checking if the normalized cursor position lies within a unit
square, it instead checks if it is contained by
`normalized_visible_node_rect`.

Added outlines to the `overflow` example that appear when the cursor is
over the visible part of the images, but not the clipped area.

---

## Changelog

* `ui_focus_system` intersects a node's bounding rect with its clipping
rect before checking if mouse over.
* Added the field `normalized_visible_node_rect` to
`RelativeCursorPosition`. This is set to the bounds of the unclipped
area of the node rect by `ui_focus_system` expressed in normalized
coordinates relative to the entire node.
* `RelativeCursorPostion` is calculated relative to the whole node's
position and size, not only the visible part.
* `RelativeCursorPosition::mouse_over` only returns true when the mouse
is over an unclipped region of the UI node.
* Removed the `Deref` and `DerefMut` derives from
`RelativeCursorPosition` as it is no longer a single field struct.
* Added some outlines to the `overflow` example that respond to
`Interaction` changes.

## Migration Guide

The clipped areas of UI nodes are no longer interactive.

`RelativeCursorPostion` is now calculated relative to the whole node's
position and size, not only the visible part. Its `mouse_over` method
only returns true when the cursor is over an unclipped part of the node.

`RelativeCursorPosition` no longer implements `Deref` and `DerefMut`.
2023-11-22 14:30:38 +00:00
Martín Maita
4ffd5104f3
Bumps async crates requirements to latest major version (#10370)
# Objective

- Closes #10316

## Solution

- Grouped a bunch of version requirement bumps for most of the `async`
crates.
2023-11-22 13:41:48 +00:00
Zachary Harrold
f613c450bc
Fix Asset Loading Bug (#10698)
# Objective

- Fixes #10695

## Solution

Fixed obvious blunder in `PartialEq` implementation for
`UntypedAssetId`'s where the `TypeId` was not included in the
comparison. This was not picked up in the unit tests I added because
they only tested over a single asset type.
2023-11-22 13:39:44 +00:00
Mike
208ecb53dc
Append commands (#10400)
# Objective

- I've been experimenting with different patterns to try and make async
tasks more convenient. One of the better ones I've found is to return a
command queue to allow for deferred &mut World access. It can be
convenient to check for task completion in a normal system, but it is
hard to do something with the command queue after getting it back. This
pr adds a `append` to Commands. This allows appending the returned
command queue onto the system's commands.

## Solution

- I edited the async compute example to use the new `append`, but not
sure if I should keep the example changed as this might be too
opinionated.

## Future Work

- It would be very easy to pull the pattern used in the example out into
a plugin or a external crate, so users wouldn't have to add the checking
system.

---

## Changelog

- add `append` to `Commands` and `CommandQueue`
2023-11-22 00:04:37 +00:00
BD103
3578eec351
Re-export futures_lite in bevy_tasks (#10670)
# Objective

- Fixes #10664

## Solution

- `pub use futures_lite as future` :)

---

## Changelog

- Made `futures_lite` available as `future` in the `bevy_tasks` module.

## Migration Guide

- Remove `futures_lite` from `Cargo.toml`.

```diff
[dependencies]
bevy = "0.12.0"
- futures-lite = "1.4.0"
```

- Replace `futures_lite` imports with `bevy::tasks::future`.

```diff
- use futures_lite::poll_once;
+ use bevy::tasks::future::poll_once;
```
2023-11-21 16:51:13 +00:00
TheBigCheese
e67cfdf82b
Enable clippy::undocumented_unsafe_blocks warning across the workspace (#10646)
# Objective

Enables warning on `clippy::undocumented_unsafe_blocks` across the
workspace rather than only in `bevy_ecs`, `bevy_transform` and
`bevy_utils`. This adds a little awkwardness in a few areas of code that
have trivial safety or explain safety for multiple unsafe blocks with
one comment however automatically prevents these comments from being
missed.

## Solution

This adds `undocumented_unsafe_blocks = "warn"` to the workspace
`Cargo.toml` and fixes / adds a few missed safety comments. I also added
`#[allow(clippy::undocumented_unsafe_blocks)]` where the safety is
explained somewhere above.

There are a couple of safety comments I added I'm not 100% sure about in
`bevy_animation` and `bevy_render/src/view` and I'm not sure about the
use of `#[allow(clippy::undocumented_unsafe_blocks)]` compared to adding
comments like `// SAFETY: See above`.
2023-11-21 02:06:24 +00:00
Joona Aalto
897b13bf9d
Use minor and major radii for Torus primitive shape (#10643)
# Objective

First, some terminology:

- **Minor radius**: The radius of the tube of a torus, i.e. the
"half-thickness"
- **Major radius**: The distance from the center of the tube to the
center of the torus
- **Inner radius**: The radius of the hole (if it exists), `major_radius
- minor_radius`
- **Outer radius**: The radius of the overall shape, `major_radius +
minor_radius`
- **Ring torus**: The familiar donut shape with a hole in the center,
`major_radius > minor_radius`
- **Horn torus**: A torus that doesn't have a hole but also isn't
self-intersecting, `major_radius == minor_radius`
- **Spindle torus**: A self-intersecting torus, `major_radius <
minor_radius`

Different tori from [Wikipedia](https://en.wikipedia.org/wiki/Torus),
where *R* is the major radius and *r* is the minor radius:


![kuva](https://github.com/bevyengine/bevy/assets/57632562/53ead786-2402-43a7-ae8a-5720e6e54dcc)

Currently, Bevy's torus is represented by a `radius` and `ring_radius`.
I believe these correspond to the outer radius and minor radius, but
they are rather confusing and inconsistent names, and they make the
assumption that the torus always has a ring.

I also couldn't find any other big engines using this representation;
[Godot](https://docs.godotengine.org/en/stable/classes/class_torusmesh.html)
and [Unity
ProBuilder](https://docs.unity3d.com/Packages/com.unity.probuilder@4.0/manual/Torus.html)
use the inner and outer radii, while
[Unreal](https://docs.unrealengine.com/5.3/en-US/BlueprintAPI/GeometryScript/Primitives/AppendTorus/)
uses the minor and major radii.
[Blender](https://docs.blender.org/manual/en/latest/modeling/meshes/primitives.html#torus)
supports both, but defaults to minor/major.

Bevy's `Torus` primitive should have an efficient, consistent, clear and
flexible representation, and the current `radius` and `ring_radius`
properties are not ideal for that.

## Solution

Change `Torus` to be represented by a `minor_radius` and `major_radius`.

- Mathematically correct and consistent
- Flexible, not restricted to ring tori
- Computations and conversions are efficient
  - `inner_radius = major_radius - minor_radius`
  - `outer_radius = major_radius + minor_radius`
- Mathematical formulae for things like area and volume rely on the
minor and major radii, no conversion needed

Perhaps the primary issue with this representation is that "minor
radius" and "major radius" are rather mathematical, and an inner/outer
radius can be more intuitive in some cases. However, this can be
mitigated with constructors and helpers.
2023-11-21 01:49:35 +00:00
Andrew Safigan
a22020bf5c
Make impl block for RemovedSystem generic (#10651)
# Objective

Make the impl block for RemovedSystem generic so that the methods can be
called for systems that have inputs or outputs.

## Solution

Simply adding generics to the impl block.
2023-11-21 01:27:29 +00:00
TheBigCheese
865041de74
Add an Entry api to EntityWorldMut. (#10650)
# Objective

Adds `.entry` to `EntityWorldMut` with `Entry`, `OccupiedEntry` and
`VacantEntry` for easier in-situ modification, based on `HashMap.entry`.

Fixes #10635

## Solution

This adds the `entry` method to `EntityWorldMut` which returns an
`Entry`. This is an enum of `OccupiedEntry` and `VacantEntry` and has
the methods `and_modify`, `insert_entry`, `or_insert`, `or_insert_with`
and `or_default`. The only difference between `OccupiedEntry` and
`VacantEntry` is the type, they are both a mutable reference to the
`EntityWorldMut` and a marker for the component type, `HashMap` also
stores things to make it quicker to access the data in `OccupiedEntry`
but I wasn't sure if we had anything it would be logical to store to
make accessing/modifying the component faster? As such, the differences
are that `OccupiedEntry` assumes the entity has the component (because
nothing else can have an `EntityWorldMut` so it can't be changed outside
the entry api) and has different methods.

All the methods are based very closely off `hashbrown::HashMap` (because
its easier to read the source of) with a couple of quirks like
`OccupiedEntry.insert` doesn't return the old value because we don't
appear to have an api for mem::replacing components.

---

## Changelog

- Added a new function `EntityWorldMut.entry` which returns an `Entry`,
allowing easier in-situ modification of a component.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Pascal Hertleif <killercup@gmail.com>
2023-11-21 01:26:06 +00:00
Zachary Harrold
57a175f546
Ensure consistency between Un/Typed AssetId and Handle (#10628)
# Objective

- Fixes #10629
- `UntypedAssetId` and `AssetId` (along with `UntypedHandle` and
`Handle`) do not hash to the same values when pointing to the same
`Asset`. Additionally, comparison and conversion between these types
does not follow idiomatic Rust standards.

## Solution

- Added new unit tests to validate/document expected behaviour
- Added trait implementations to make working with Un/Typed values more
ergonomic
- Ensured hashing and comparison between Un/Typed values is consistent
- Removed `From` trait implementations that panic, and replaced them
with `TryFrom`

---

## Changelog

- Ensured `Handle::<A>::hash` and `UntypedHandle::hash` will produce the
same value for the same `Asset`
- Added non-panicing `Handle::<A>::try_typed`
- Added `PartialOrd` to `UntypedHandle` to match `Handle<A>` (this will
return `None` for `UntypedHandles` for differing `Asset` types)
- Added `TryFrom<UntypedHandle>` for `Handle<A>`
- Added `From<Handle<A>>` for `UntypedHandle`
- Removed panicing `From<Untyped...>` implementations. These are
currently unused within the Bevy codebase, and shouldn't be used
externally, hence removal.
- Added cross-implementations of `PartialEq` and `PartialOrd` for
`UntypedHandle` and `Handle<A>` allowing direct comparison when
`TypeId`'s match.
- Near-identical changes to `AssetId` and `UntypedAssetId`

## Migration Guide

If you relied on any of the panicing `From<Untyped...>` implementations,
simply call the existing `typed` methods instead. Alternatively, use the
new `TryFrom` implementation instead to directly expose possible
mistakes.

## Notes

I've made these changes since `Handle` is such a fundamental type to the
entire `Asset` ecosystem within Bevy, and yet it had pretty unclear
behaviour with no direct testing. The fact that hashing untyped vs typed
versions of the same handle would produce different values is something
I expect to cause a very subtle bug for someone else one day.

I haven't included it in this PR to avoid any controversy, but I also
believe the `typed_unchecked` methods should be removed from these
types, or marked as `unsafe`. The `texture_atlas` example currently uses
it, and I believe it is a bad choice. The performance gained by not
type-checking before conversion would be entirely dwarfed by the act of
actually loading an asset and creating its handle anyway. If an end user
is in a tight loop repeatedly calling `typed_unchecked` on an
`UntypedHandle` for the entire runtime of their application, I think the
small performance drop caused by that safety check is ~~a form of cosmic
justice~~ reasonable.
2023-11-21 01:13:36 +00:00
Stepan Koltsov
1da0afa3aa
bevy_hierarchy: add some docs (#10598)
Just adding comments to code I did not understand before and I hope
understand now.

---------

Co-authored-by: Kristoffer Søholm <k.soeholm@gmail.com>
2023-11-21 01:11:20 +00:00
Konstantin Kostiuk
eeb0c2f2e4
Allow #[derive(Bundle)] on tuple structs (take 3) (#10561)
- rework of old @Veykril's work in
[2499](https://github.com/bevyengine/bevy/pull/2499)
- Fixes [3537](https://github.com/bevyengine/bevy/issues/3537)
2023-11-21 01:09:16 +00:00