Commit graph

2180 commits

Author SHA1 Message Date
Gino Valente
3c2ac3651f bevy_reflect: Update Reflection documentation (#5841)
# Objective

The documentation on `Reflect` doesn't account for the recently added reflection traits: [`Array`](https://github.com/bevyengine/bevy/pull/4701) and [`Enum`](https://github.com/bevyengine/bevy/pull/4761).

## Solution

Updated the documentation for `Reflect` to account for the `Array` and `Enum`.


Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
2022-09-02 16:17:45 +00:00
Ixentus
17d84e8811 Update to notify 5.0 stable (#5865)
# Objective

- Update notify dependency to 5.0.0 stable
- Fix breaking changes
- Closes #5861

## Solution

- RecommendedWatcher now takes a Config argument. Giving it the default Config should be the same behavior as before (check every 30 seconds)
2022-09-02 15:54:54 +00:00
Ixentus
662c6e9a34 Update to ron 0.8 (#5864)
# Objective

- Update ron to 0.8.0
- Fix breaking changes
- Closes #5862

## Solution

- Removed now non-existing method call (behavior is now the same without it)
2022-09-02 14:20:49 +00:00
Federico Rinaldi
7511c9bfaa Update Query struct docs (#5741)
# Objective

- Update `Query` docs with better terminology
- add some performance remarks (Fixes #4742)

## Solution

- See #4989. This PR is derived from it. It just includes changes to the `Query` struct docs.
2022-09-02 12:57:39 +00:00
Federico Rinaldi
59bf3c4cc9 Improve WorldQuery docs (#5740)
# Objective

- Update docs to `WorldQuery`

## Solution

- See #4989. This PR is derived from it, and limited to the `WorldQuery` item docs.
2022-09-02 12:35:24 +00:00
Jerome Humbert
8b7b44d839 Move sprite::Rect into bevy_math (#5686)
# Objective

Promote the `Rect` utility of `sprite::Rect`, which defines a rectangle
by its minimum and maximum corners, to the `bevy_math` crate to make it
available as a general math type to all crates without the need to
depend on the `bevy_sprite` crate.

Fixes #5575

## Solution

Move `sprite::Rect` into `bevy_math` and fix all uses.

Implement `Reflect` for `Rect` directly into the `bevy_reflect` crate by
having `bevy_reflect` depend on `bevy_math`. This looks like a new
dependency, but the `bevy_reflect` was "cheating" for other math types
by directly depending on `glam` to reflect other math types, thereby
giving the illusion that there was no dependency on `bevy_math`. In
practice conceptually Bevy's math types are reflected into the
`bevy_reflect` crate to avoid a dependency of that crate to a "lower
level" utility crate like `bevy_math` (which in turn would make
`bevy_reflect` be a dependency of most other crates, and increase the
risk of circular dependencies). So this change simply formalizes that
dependency in `Cargo.toml`.

The `Rect` struct is also augmented in this change with a collection of
utility methods to improve its usability. A few uses cases are updated
to use those new methods, resulting is more clear and concise syntax.

---

## Changelog

### Changed

- Moved the `sprite::Rect` type into `bevy_math`.

### Added

- Added several utility methods to the `math::Rect` type.

## Migration Guide

The `bevy::sprite::Rect` type moved to the math utility crate as
`bevy::math::Rect`. You should change your imports from `use
bevy::sprite::Rect` to `use bevy::math::Rect`.
2022-09-02 12:35:23 +00:00
pwygab
6b87fb0bdb improve panic messages for add_system_to_stage and add_system_set_to_stage (#5847)
# Objective

- Make the panic messages more specific and understandable.
- Fixes #5811 
## Solution

- Edit the panic message.

---
2022-09-02 12:18:44 +00:00
François
480b3baa44 Helpers to check pipeline cache status (#5796)
# Objective

- In WASM, creating a pipeline can easily take 2 seconds, freezing the game while doing so
- Preloading pipelines can be done during a "loading" state, but it is not trivial to know which pipeline to preload, or when it's done

## Solution

- Add a log with shaders being loaded and their shader defs
- add a function on `PipelineCache` to return the number of ready pipelines
2022-09-02 12:18:43 +00:00
François
e8041150ee can clone a scene (#5855)
# Objective

- Easier to work with model assets
- Models are often one mesh, many textures. This can be hard to use in Bevy as it's not possible to clone the scene to have one scene for each material. It's still possible to instantiate the texture-less scene, then modify the texture material once spawned but that means happening during play and is quite more painful

## Solution

- Expose the code to clone a scene. This code already existed but was only possible to use to spawn the scene
2022-09-02 11:56:21 +00:00
Fishy
79e7c93060 Support for additional gamepad buttons and axis (#5853)
# Objective

Extend the scope of Gamepad to accommodate devices that have more inputs than a typical controller.

## Solution

Add additional enum variants to both _GamepadButtonType_ and _GamepadAxisType_ that supports up to 255 more non-standard buttons/axis respectively. 

## Personal motivation

I have been writing an alternative to the GILRS crate, and with this simple change to the source code, It will be a trivial thing to direct new devices through the bevy systems, even when they do not always behave exactly like your typical controller.
2022-09-02 02:16:18 +00:00
James O'Brien
f9853cbbc2 Add get_entity to Commands (#5854)
# Objective

- Fixes #5850 

## Solution

- As described in the issue, added a `get_entity` method on `Commands` that returns an `Option<EntityCommands>`

## Changelog
- Added the new method with a simple doc test
- I have re-used `get_entity` in `entity`, similarly to how `get_single` is used in `single` while additionally preserving the error message
- Add `#[inline]` to both functions

Entities that have commands queued to despawn system will still return commands when `get_entity` is called but that is representative of the fact that the entity is still around until those commands are flushed.

A potential `contains_entity` could also be added in this PR if desired, that would effectively be replacing Entities.contains but may be more discoverable if this is a common use case.


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-09-01 22:06:46 +00:00
John
9e34c748c6 Added the ability to get or set the last change tick of a system. (#5838)
# Objective
I'm build a UI system for bevy. In this UI system there is a concept of a system per UI entity. I had an issue where change detection wasn't working how I would expect and it's because when a function system is ran the `last_change_tick` is updated with the latest tick(from world). In my particular case I want to "wait" to update the `last_change_tick` until after my system runs for each entity.

## Solution
Initially I thought bypassing the change detection all together would be a good fix, but on talking to some users in discord a simpler fix is to just expose `last_change_tick` to the end users. This is achieved by adding the following to the `System` trait:
```rust
    /// Allows users to get the system's last change tick.
    fn get_last_change_tick(&self) -> u32;
    /// Allows users to set the system's last change tick.
    fn set_last_change_tick(&mut self, last_change_tick: u32);
```

This causes a bit of weirdness with two implementors of `System`. `FixedTimestep` and `ChainSystem` both implement system and thus it's required that some sort of implementation be given for the new functions. I solved this by outputting a warning and not doing anything for these systems. 

I think it's important to understand why I can't add the new functions only to the function system and not to the `System` trait. In my code I store the systems generically as `Box<dyn System<...>>`. I do this because I have differing parameters that are being passed in depending on the UI widget's system.  As far as I can tell there isn't a way to take a system trait and cast it into a specific type without knowing what those parameters are.

In my own code this ends up looking something like:
```rust
// Runs per entity.
let old_tick = widget_system.get_last_change_tick();
should_update_children = widget_system.run((widget_tree.clone(), entity.0), world);
widget_system.set_last_change_tick(old_tick);


// later on after all the entities have been processed:
for system in context.systems.values_mut() {
    system.set_last_change_tick(world.read_change_tick());
}
```

## Changelog

- Added `get_last_change_tick` and `set_last_change_tick` to `System`'s.
2022-08-31 01:53:15 +00:00
ira
b42f426fc3 Add associated constant IDENTITY to Transform and friends. (#5340)
# Objective
Since `identity` is a const fn that takes no arguments it seems logical to make it an associated constant.
This is also more in line with types from glam (eg. `Quat::IDENTITY`).

## Migration Guide

The method `identity()` on `Transform`, `GlobalTransform` and `TransformBundle` has been deprecated.
Use the associated constant `IDENTITY` instead.

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-08-30 22:10:24 +00:00
Boxy
ed773dbe30 Misc query.rs cleanup (#5591)
# Objective
- `for_each` methods inconsistently used an actual generic param or `impl Trait` change it to use `impl Trait` always, change them to be consistent
- some methods returned `'w 's` or `'_ '_`, change them to return `'_ 's`

## Solution

- Do what i just said

---

## Changelog

- `iter_unsafe` and `get_unchecked` no longer return borrows tied to `'w`

## Migration Guide

transmute the returned borrow from `iter_unsafe` and `get_unchecked` if this broke you (although preferably find a way to write your code that doesnt need to do this...)
2022-08-30 21:56:00 +00:00
Carter Anderson
dcdda4cb33 Remove extra spaces from Range reflect impls (#5839)
# Objective

Remove extra spaces from Range reflect impls. Follow up to #5763 

## Solution

Remove extra spaces from Range reflect impls.
2022-08-30 21:39:48 +00:00
Gino Valente
ecc584ff23 bevy_reflect: Get owned fields (#5728)
# Objective

Sometimes it's useful to be able to retrieve all the fields of a container type so that they may be processed separately. With reflection, however, we typically only have access to references.

The only alternative is to "clone" the value using `Reflect::clone_value`. This, however, returns a Dynamic type in most cases. The solution there would be to use `FromReflect` instead, but this also has a problem in that it means we need to add `FromReflect` as an additional bound.

## Solution

Add a `drain` method to all container traits. This returns a `Vec<Box<dyn Reflect>>` (except for `Map` which returns `Vec<(Box<dyn Reflect>, Box<dyn Reflect>)>`).

This allows us to do things a lot simpler. For example, if we finished processing a struct and just need a particular value:

```rust
// === OLD === //
/// May or may not return a Dynamic*** value (even if `container` wasn't a `DynamicStruct`)
fn get_output(container: Box<dyn Struct>, output_index: usize) -> Box<dyn Reflect> {
  container.field_at(output_index).unwrap().clone_value()
}

// === NEW === //
/// Returns _exactly_ whatever was in the given struct
fn get_output(container: Box<dyn Struct>, output_index: usize) -> Box<dyn Reflect> {
  container.drain().remove(output_index).unwrap()
}
```

### Discussion

* Is `drain` the best method name? It makes sense that it "drains" all the fields and that it consumes the container in the process, but I'm open to alternatives.

---

## Changelog

* Added a `drain` method to the following traits:
  * `Struct`
  * `TupleStruct`
  * `Tuple`
  * `Array`
  * `List`
  * `Map`
  * `Enum`
2022-08-30 21:20:58 +00:00
Nathan Ward
bb2303a654 Add pop method for List trait. (#5797)
# Objective

- The reflection `List` trait does not have a `pop` function.
- Popping elements off a list is a common use case and is almost always supported by `List`-like types.

## Solution

- Add the `pop()` method to the `List` trait and add the appropriate implementations of this function.

## Migration Guide

- Any custom type that implements the `List` trait will now need to implement the `pop` method.


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-08-30 21:06:32 +00:00
Marc-Stefan Cassola
e9661bea1a Implemented Reflect for all the ranges (#5806)
# Objective

Fixes #5763

## Solution

Implemented as reflect value like the current `Range`. Is there a benefit to changing everything to a reflect struct?
2022-08-30 20:51:21 +00:00
Boxy
df31b7d762 Remove insert_resource_with_id (#5608)
# Objective

remove `insert_resource_with_id` because `insert_resource_by_id` exists and does almost exactly the same thing

blocked on #5587 because otherwise we will leak a resource when it's inserted 

## Solution

remove the function and also add a safety invariant of to `insert_resource_by_id` that the id be valid for the world.

I didn't see any discussion in #4447 about this safety invariant being left off in favor of a panic so I'm curious if there was one or if it just seemed nicer to have less safety invariants for callers to uphold 😅 

---

## Changelog

- safety invariant added to `insert_resource_by_id` requiring the id to be valid for world

## Migration Guide

- audit any calls to `insert_resource_by_id` making sure that the id is valid for the world

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-08-30 20:32:15 +00:00
Rob Parrett
e874b91dda Fix window centering when scale_factor is not 1.0 (#5582)
# Objective

Fixes #5581

## Solution

`Window::scale_factor` already has logic for selecting the overridden or actual scale factor, so use it.

I tested this with the displays I have access to, but more testing would be nice. This seems like a pretty straightforward bug/fix though.

## Changelog

### Fixed

Fixed window centering on high-dpi displays.
2022-08-30 20:13:38 +00:00
Jerome Humbert
fe6246dac6 Make most Entity methods const (#5688)
# Objective

Fixes #5687

## Solution

Update the methods on the `Entity` struct to be `const`, so we can
define compile-time constants and more generally use them in a const
context.

---

## Changelog

### Added

- Most `Entity` methods are now `const fn`.
2022-08-30 03:16:22 +00:00
Lain-dono
24e5e10cd4 Use 3 bits of PipelineKey to store MSAA sample count (#5826)
Sample count always power of two. Thus, it is enough to store `log2(sample_count)`.
This can be implemented using [u32::trailing_zeros](https://doc.rust-lang.org/stable/std/primitive.u32.html#method.trailing_zeros). Then we can restore sample count with the `1 << stored`.
You get 3 bits instead of 6 and up to 128x MSAA. This is more than is supported by any common hardware.

Full table of possible variations:

```
    original MSAA sample count      stored    loaded
* 00000000000000000000000000000000 -> 000 -> 00000001  1
  00000000000000000000000000000001 -> 000 -> 00000001  1
  00000000000000000000000000000010 -> 001 -> 00000010  2
  00000000000000000000000000000100 -> 010 -> 00000100  4
  00000000000000000000000000001000 -> 011 -> 00001000  8
  00000000000000000000000000010000 -> 100 -> 00010000  16
  00000000000000000000000000100000 -> 101 -> 00100000  32
  00000000000000000000000001000000 -> 110 -> 01000000  64
  00000000000000000000000010000000 -> 111 -> 10000000  128
* 00000000000000000000000100000000 -> 000 -> 00000001  256
* 00000000000000000000001000000000 -> 001 -> 00000010  512
* 00000000000000000000010000000000 -> 010 -> 00000100  1024
* 00000000000000000000100000000000 -> 011 -> 00001000  2048
* 00000000000000000001000000000000 -> 100 -> 00010000  4096
* 00000000000000000010000000000000 -> 101 -> 00100000  8192
* 00000000000000000100000000000000 -> 110 -> 01000000  16384
* 00000000000000001000000000000000 -> 111 -> 10000000  32768
* 00000000000000010000000000000000 -> 000 -> 00000001  65536
* 00000000000000100000000000000000 -> 001 -> 00000010  131072
* 00000000000001000000000000000000 -> 010 -> 00000100  262144
* 00000000000010000000000000000000 -> 011 -> 00001000  524288
* 00000000000100000000000000000000 -> 100 -> 00010000  1048576
* 00000000001000000000000000000000 -> 101 -> 00100000  2097152
* 00000000010000000000000000000000 -> 110 -> 01000000  4194304
* 00000000100000000000000000000000 -> 111 -> 10000000  8388608
* 00000001000000000000000000000000 -> 000 -> 00000001  16777216
* 00000010000000000000000000000000 -> 001 -> 00000010  33554432
* 00000100000000000000000000000000 -> 010 -> 00000100  67108864
* 00001000000000000000000000000000 -> 011 -> 00001000  134217728
* 00010000000000000000000000000000 -> 100 -> 00010000  268435456
* 00100000000000000000000000000000 -> 101 -> 00100000  536870912
* 01000000000000000000000000000000 -> 110 -> 01000000  1073741824
* 10000000000000000000000000000000 -> 111 -> 10000000  2147483648
```
2022-08-30 03:00:39 +00:00
Robin KAY
9dd5b5354f Add note on ordering to AssetServerSettings docs. (#5706)
# Objective

It's not obvious that the `AssetServerSettings` resource must be added before the `AssetPlugin`.

## Solution

Add a doc comment to this effect.
2022-08-30 02:40:18 +00:00
Aceeri
d346274e32 Warning message for missing events (#5730)
# Objective
- Reduce debugging burden when using events by telling user when they missed an event.

## Solution

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-08-30 02:23:04 +00:00
Javier Goday
46f68161f7 #5817: derive_bundle macro is not hygienic (#5835)
# Objective
- Fixes #5817.
- Removes std::vec::Vec ambiguities in derive_bundle macro

## Solution
Prepend :: to standard library full Vec qualified type name (::std::vec::Vec)
2022-08-30 02:07:47 +00:00
Federico Rinaldi
5597fc54d2 Add documentation to QueryCombinationIter (#5739)
# Objective

- Document `QueryCombinationIter`

## Solution

- Describe the item, add usage and examples
- Copy notes about the number of query items generated from the corresponding query methods (they will be removed in #5742 ([motivation]))

## Additional notes

- Derived from #4989 

[motivation]: https://github.com/bevyengine/bevy/pull/4989#issuecomment-1208421496
2022-08-30 00:39:17 +00:00
JoJoJet
584d855fd1 Add a module for common system chain/pipe adapters (#5776)
# Objective

Right now, users have to implement basic system adapters such as `Option` <-> `Result` conversions by themselves. This is slightly annoying and discourages the use of system chaining.

## Solution

Add the module `system_adapter` to the prelude, which contains a collection of common adapters. This is very ergonomic in practice.

## Examples

Convenient early returning.

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

App::new()
    // If the system fails, just try again next frame.
    .add_system(pet_dog.chain(system_adapter::ignore))
    .run();

#[derive(Component)]
struct Dog;

fn pet_dog(dogs: Query<(&Name, Option<&Parent>), With<Dog>>) -> Option<()> {
    let (dog, dad) = dogs.iter().next()?;
    println!("You pet {dog}. He/she/they are a good boy/girl/pupper.");
    let (dad, _) = dogs.get(dad?.get()).ok()?;
    println!("Their dad's name is {dad}");
    Some(())
}
```

Converting the output of a system

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

App::new()
    .add_system(
        find_name
            .chain(system_adapter::new(String::from))
            .chain(spawn_with_name),
    )
    .run();

fn find_name() -> &'static str { /* ... */ }
fn spawn_with_name(In(name): In<String>, mut commands: Commands) {
    commands.spawn().insert(Name::new(name));
}
```
---

## Changelog

* Added the module `bevy_ecs::prelude::system_adapter`, which contains a collection of common system chaining adapters.
  * `new` - Converts a regular fn to a system adapter.
  * `unwrap` - Similar to `Result::unwrap`
  * `ignore` - Discards the output of the previous system.
2022-08-30 00:17:20 +00:00
Andreas Weibye
4fadd26168 Add UI scaling (#5814)
# Objective

- Allow users to change the scaling of the UI
- Adopted from #2808

## Solution

- This is an accessibility feature for fixed-size UI elements, allowing the developer to expose a range of UI scales for the player to set a scale that works for their needs.

> - The user can modify the UiScale struct to change the scaling at runtime. This multiplies the Px values by the scale given, while not touching any others.
> - The example showcases how this even allows for fluid transitions

> Here's how the example looks like:

https://user-images.githubusercontent.com/1631166/132979069-044161a9-8e85-45ab-9e93-fcf8e3852c2b.mp4

---

## Changelog

- Added a `UiScale` which can be used to scale all of UI


Co-authored-by: Andreas Weibye <13300393+Weibye@users.noreply.github.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-08-29 23:35:53 +00:00
harudagondi
8a1061209c Remove Sync requirement in Decodable::Decoder (#5819)
# Objective

- Allow non-`Sync` Decoders
- Unblocks #5422.
- Unblocks harudagondi/bevy_fundsp#1

## Solution

- Remove `Sync` requirement in `Decodable::Decoder`
- This aligns with kira's [`Sound`] and majority of [oddio]'s types (like [`Mixer`]).

[`Sound`]: https://docs.rs/kira/latest/kira/sound/trait.Sound.html
[oddio]: https://docs.rs/oddio/latest/oddio/index.html
[`Mixer`]: https://docs.rs/oddio/latest/oddio/struct.Mixer.html

---

## Changelog

### Changed

- `Decodable::Decoder` now no longer requires `Sync` types.
2022-08-29 23:02:12 +00:00
Rob Parrett
adf2475dab Add warning when using load_folder on web (#5827)
# Objective

Help users who are using `load_folder` in wasm builds to find a slightly shorter path to figuring out why their stuff is broken.

## Solution

Adds a warning to `read_directory` in the `WasmAssetIo`.

This is extremely similar to the warning already emitted a few lines below for `watch_for_changes`.
2022-08-29 22:26:43 +00:00
Ben Frankel
70106773f2 Fix example in AnyOf docs (#5798) 2022-08-25 20:31:51 +00:00
Gino Valente
7da97b4dee bevy_reflect: Remove unnecessary Clone bounds (#5783)
# Objective

Some of the reflection impls for container types had unnecessary `Clone` bounds on their generic arguments. These come from before `FromReflect` when types were instead bound by `Reflect + Clone`. With `FromReflect` this is no longer necessary.

## Solution

Removed all leftover `Clone` bounds from types that use `FromReflect` instead.

## Note

I skipped `Result<T, E>`, `HashSet<T>`, and `Range<T>` since those do not use `FromReflect`. This should probably be handled in a separate PR since it would be a breaking change.

---

## Changelog

- Remove unnecessary `Clone` bounds on reflected containers
2022-08-24 21:21:11 +00:00
Gino Valente
880ea5d4be bevy_reflect: Fix apply method for Option<T> (#5780)
# Objective

#5658 made it so that `FromReflect` was used as the bound for `T` in `Option<T>`. However, it did not use this change effectively for the implementation of `Reflect::apply` (it was still using `take`, which would fail for Dynamic types).

Additionally, the changes were not consistent with other methods within the file, such as the ones for `Vec<T>` and `HashMap<K, V>`.

## Solution

Update `Option<T>` to fallback on `FromReflect` if `take` fails, instead of wholly relying on one or the other.

I also chose to update the error messages, as they weren't all too descriptive before.

---

## Changelog

- Use `FromReflect::from_reflect` as a fallback in the `Reflect::apply` implementation for `Option<T>`
2022-08-24 20:44:35 +00:00
Gino Valente
886837d731 bevy_reflect: GetTypeRegistration for SmallVec<T> (#5782)
# Objective

`SmallVec<T>` was missing a `GetTypeRegistration` impl.

## Solution

Added a `GetTypeRegistration` impl.

---

## Changelog

* Added a `GetTypeRegistration` impl for `SmallVec<T>`
2022-08-24 20:25:52 +00:00
Ida Iyes
3d194a2160 Add missing type registrations for bevy_math types (#5758)
Type registrations were only present for some of the `bevy_math` types, and missing for others. This is a very strange inconsistency, given that they all impl `Reflect` and `FromReflect`. In practice, this means these types cannot be used in scenes.

In particular, this is especially problematic, because `Affine3A` is one of the missing types, and it is now used in `GlobalTransform`. Trying to create a bevy scene that contains `GlobalTransform`s results in an error due to the missing type registration.
2022-08-23 21:19:29 +00:00
Jakob Hellermann
3817afc1f4 register missing reflect types (#5747)
# Objective

- While generating https://github.com/jakobhellermann/bevy_reflect_ts_type_export/blob/main/generated/types.ts, I noticed that some types that implement `Reflect` did not register themselves
- `Viewport` isn't reflect but can be (there's a TODO)


## Solution

- register all reflected types
- derive `Reflect` for `Viewport`


## Changelog
- more types are not registered in the type registry
- remove `Serialize`, `Deserialize` impls from `Viewport`


I also decided to remove the `Serialize, Deserialize` from the `Viewport`, since they were (AFAIK) only used for reflection, which now is done without serde. So this is technically a breaking change for people who relied on that impl directly.
Personally I don't think that every bevy type should implement `Serialize, Deserialize`, as that would lead to a ton of code generation that mostly isn't necessary because we can do the same with `Reflect`, but if this is deemed controversial I can remove it from this PR.

## Migration Guide
- `KeyCode` now implements `Reflect` not as `reflect_value`, but with proper struct reflection. The `Serialize` and `Deserialize` impls were removed, now that they are no longer required for scene serialization.
2022-08-23 17:41:39 +00:00
TheRawMeatball
5e2d9b4ae4 Add explicit ordering between update_frusta and camera_system (#5757)
# Objective

Fix a nasty system ordering bug between `update_frusta` and `camera_system` that lead to incorrect frustum s, leading to excessive culling and extremely hard-to-debug visual glitches

## Solution

- add explicit system ordering
2022-08-23 09:40:06 +00:00
Andreas Weibye
675607a7e6 Add AUTO and UNDEFINED const constructors for Size (#5761)
# Objective

Very small convenience constructors added to `Size`. 

Does not change current examples too much but I'm working on a rather complex UI use-case where this cuts down on some extra typing :)
2022-08-22 23:08:08 +00:00
Ian Chamberlain
cde5ae8104 bevy_ecs: Use 32-bit entity ID cursor on platforms without AtomicI64 (#4452)
# Objective
- Fixes #4451

## Solution
- Conditionally compile entity ID cursor as `AtomicI32` when compiling on a platform that does not support 64-bit atomics.

- This effectively raises the MSRV to 1.60 as it uses a `#[cfg]` that was only just stabilized there. (should this be noted in changelog?)

---

## Changelog
- Added `bevy_ecs` support for platforms without 64-bit atomic ints


## Migration Guide
N/A
2022-08-21 00:45:49 +00:00
Robert Swain
681c9c6dc8 bevy_pbr: Fix tangent and normal normalization (#5666)
# Objective

- Morten Mikkelsen clarified that the world normal and tangent must be normalized in the vertex stage and the interpolated values must not be normalized in the fragment stage. This is in order to match the mikktspace approach exactly.
- Fixes #5514 by ensuring the tangent basis matrix (TBN) is orthonormal

## Solution

- Normalize the world normal in the vertex stage and not the fragment stage
- Normalize the world tangent xyz in the vertex stage
- Take into account the sign of the determinant of the local to world matrix when calculating the bitangent

---

## Changelog

- Fixed - scaling a model that uses normal mapping now has correct lighting again
2022-08-18 21:54:40 +00:00
pwygab
1c6be94f4f Correctly parse labels with '#' (#5729)
# Objective

- Fixes #5707 

## Solution

- Used `splitn` instead of `split` to collect the rest of the string into the label after the first '#'.

---
2022-08-18 18:53:09 +00:00
Nathan Ward
00323b3048 Better error message for World::resource_scope (#5727)
# Objective

- Fixes #5365 
- The `assert!()` when the resource from `World::resource_scope` is inserted into the world is not descriptive.

## Solution

- Add more context to the assert inside of `World::resource_scope` when the `FnOnce` param inserts the resource.
2022-08-18 18:53:08 +00:00
Gino Valente
00508d110a bevy_reflect: Add FromReflect to the prelude (#5720)
# Objective

`FromReflect` is a commonly used component to the Reflect API. It's required as a bound for reflecting things like `Vec<T>` and `HashMap<K, V>` and is generally useful (if not necessary) to derive on most structs or enums.

Currently, however, it is not exported in `bevy_reflect`'s prelude. This means a module that uses `bevy_reflect` might have the following two lines:

```rust
use bevy_reflect::prelude::*;
use bevy_reflect::FromReflect;
```

Additionally, users of the full engine might need to put:

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

## Solution

Add `FromReflect` to the prelude of `bevy_reflect`.

---

## Changelog

- Added `FromReflect` to the prelude of `bevy_reflect`
2022-08-18 18:53:07 +00:00
Aceeri
f0c512731b SystemParam for the name of the system you are currently in (#5731)
# Objective
- Similar to `SystemChangeTick`, probably somewhat useful for debugging messages.

---

## Changelog

- Added `SystemName` which copies the `SystemMeta::name` field so it can be accessed within a system.
2022-08-18 18:31:12 +00:00
Verte
56fc1dfe77 Correctly use as_hsla_f32 in Add<Color> and AddAssign<Color>, fixes #5543 (#5546)
Probably a copy-paste error, but `Add<Color>` and `AddAssign<Color>` should use `rhs.as_hlsa_f32()` instead of `rhs.as_linear_rgba_f32()` when the LHS is a `Color::Hsla`. Fixes #5543.



Co-authored-by: Verte <105466627+vertesians@users.noreply.github.com>
2022-08-17 14:00:10 +00:00
Gino Valente
aed3232e38 bevy_reflect: Relax bounds on Option<T> (#5658)
# Objective

The reflection impls on `Option<T>` have the bound `T: Reflect + Clone`. This means that using `FromReflect` requires `Clone` even though we can normally get away with just `FromReflect`.

## Solution

Update the bounds on `Option<T>` to match that of `Vec<T>`, where `T: FromReflect`. 

This helps remove a `Clone` implementation that may be undesired but added for the sole purpose of getting the code to compile.

---

## Changelog

* Reflection on `Option<T>` now has `T` bound by `FromReflect` rather than `Reflect + Clone`
* Added a `FromReflect` impl for `Instant`

## Migration Guide

If using `Option<T>` with Bevy's reflection API, `T` now needs to implement `FromReflect` rather than just `Clone`. This can be achieved easily by simply deriving `FromReflect`:

```rust

// OLD
#[derive(Reflect, Clone)]
struct Foo;

let reflected: Box<dyn Reflect> = Box::new(Some(Foo));

// NEW
#[derive(Reflect, FromReflect)]
struct Foo;

let reflected: Box<dyn Reflect> = Box::new(Some(Foo));
```
> Note: You can still derive `Clone`, but it's not required in order to compile.
2022-08-17 00:21:15 +00:00
JoJoJet
3221e569e0 Remove an outdated workaround for impl Trait (#5659)
# Objective

Rust 1.63 resolved [an issue](https://github.com/rust-lang/rust/issues/83701) that prevents you from combining explicit generic arguments with `impl Trait` arguments.

Now, we no longer need to use dynamic dispatch to work around this.

## Migration Guide

The methods `Schedule::get_stage` and `get_stage_mut` now accept `impl StageLabel` instead of `&dyn StageLabel`.

### Before
```rust
let stage = schedule.get_stage_mut::<SystemStage>(&MyLabel)?;
```

### After
```rust
let stage = schedule.get_stage_mut::<SystemStage>(MyLabel)?;
```
2022-08-16 23:40:24 +00:00
Alex
f20c9ee0f5 fix: grammar and typo fixes in rendergraph docs (#5710)
# Objective

- fix a typo on RendGraph Docs

## Solution

- fixed typo

---


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-08-16 20:46:46 +00:00
Jonas Wagner
110831150e Make vertex colors work without textures in bevy_sprite (#5685)
# Objective

This PR changes it possible to use vertex colors without a texture using the bevy_sprite ColorMaterial.

Fixes #5679 

## Solution

- Made multiplication of the output color independent of the COLOR_MATERIAL_FLAGS_TEXTURE_BIT bit
- Extended mesh2d_vertex_color_texture example to show off both vertex colors and tinting

Not sure if extending the existing example was the right call but it seems to be reasonable to me.

I couldn't find any tests for the shaders and I think adding shader testing would be beyond the scope of this PR. So no tests in this PR. 😬 

Co-authored-by: Jonas Wagner <jonas@29a.ch>
2022-08-16 20:46:45 +00:00
Marc-Stefan Cassola
bd317ea364 register Cow<'static, str> for reflection (#5664)
# Objective

Fixes #5597

## Solution

Registered type at suggested place.
2022-08-16 20:46:44 +00:00
Boutillier
a70b9c5969 Remove duplicate asserts in test (#5648)
# Objective

While poking around the hierarchy code, I wondered why some asserts in tests were duplicated.
Some git blame later, I found out that commit ( 8eb0440f1e ) added already existing asserts while removing others.

## Solution

Remove the duplicated asserts.
2022-08-15 23:03:42 +00:00
Charles
5ba5c8e375 insert_attribute panic with full message (#5651)
# Objective

When an invalid attribute is inserted and the LogPlugin is not enabled the full error is not printed which means makes it hard to diagnose.

## Solution

- Always print the full message in the panic.

## Notes

I originally had a separate error log because I wanted to make it clearer for users, but this is probably causing more issues than necessary.
2022-08-15 22:17:41 +00:00
Charlie Hills
f1be89d458 Remove unused DepthCalculation enum (#5684)
# Objective

Remove unused `enum DepthCalculation` and its usages. This was used to compute visible entities in the [old renderer](db665b96c0/crates/bevy_render/src/camera/visible_entities.rs), but is now unused.

## Solution

`sed 's/DepthCalculation//g'`

---

## Changelog
### Changed
Removed `bevy_render:📷:DepthCalculation`.

## Migration Guide
Remove references to `bevy_render:📷:DepthCalculation`, such as `use bevy_render:📷:DepthCalculation`. Remove `depth_calculation` fields from Projections.
2022-08-14 07:08:58 +00:00
Charlie Hills
0e46b04560 Grammar fixes in render graph doc (#5671)
# Objective

Fixing some grammar in the rustdoc for RenderGraph
2022-08-13 15:27:49 +00:00
Boutillier
de6bef72a1 Fix for bevy CI on main - clippy safety comments on trait. (#5665)
# Objective

Make CI pass on bevy main.

Update to rust-1.63, updated clippy to 1.63 which introduced the following enhancements:
- [undocumented_unsafe_blocks](https://rust-lang.github.io/rust-clippy/master/index.html#undocumented_unsafe_blocks): Now also lints on unsafe trait implementations

This caught two incorrectly written ( but existing) safety comments for unsafe  traits.

## Solution

Fix the comment to use `SAFETY:`
2022-08-13 10:51:19 +00:00
Jakob Hellermann
5595733035 drop old value in insert_resource_by_id if exists (#5587)
# Objective

While trying out the lint `unsafe_op_in_unsafe_fn` I noticed that `insert_resource_by_id` didn't drop the old value if it already existed, and reimplemented `Column::replace` manually for no apparent reason.

## Solution

- use `Column::replace` and add a test expecting the correct drop count

---

## Changelog

- `World::insert_resource_by_id` will now correctly drop the old resource value, if one already existed
2022-08-09 18:05:43 +00:00
Jakob Hellermann
166279e383 add some info from ReflectPathError to the error messages (#5626)
# Objective

- The `Display` impl for `ReflectPathError` is pretty unspecific (e.g. `the current struct doesn't have a field with the given name`
- it has info for better messages available

## Solution

- make the display impl more descriptive by including values from the type
2022-08-09 16:53:28 +00:00
Alex
fe97b384a5 fix: typo in system params docs (#5624)
# Objective

- Fix a typo on `SystemParam` docs

## Solution
- added 'be'.
- Hurray my first OSS PR! 

---
2022-08-09 16:53:27 +00:00
Jakob Hellermann
fcb77d6988 remove ReflectMut in favor of Mut<dyn Reflect> (#5630)
# Objective

- `ReflectMut` served no purpose that wasn't met by `Mut<dyn Reflect>` which is easier to understand since you have to deal with fewer types
- there is another `ReflectMut` type that could be confused with this one

## Solution/Changelog

- relax `T: ?Sized` bound in `Mut<T>`
- replace all instances of `ReflectMut` with `Mut<dyn Reflect>`
2022-08-09 16:19:34 +00:00
Nicola Papale
397b6df023 Add into_world_mut to EntityMut (#5586)
# Objective

Provide a safe API to access an `EntityMut`'s `World`.

## Solution

* Add `EntityMut::into_world_mut` for safe access to the entity's world.

---

## Changelog

* Add `EntityMut::into_world_mut` for safe access to the entity's world.
2022-08-08 22:59:18 +00:00
Jerome Humbert
a9634c7344 Make internal struct ShaderData non-pub (#5609)
# Objective

`ShaderData` is marked as public, but is an internal type only used by one other
internal type, so it should be made private.

## Solution

`ShaderData` is only used in `ShaderCache`, and the latter is private,
so there is no need to make the former public. This change removes the
`pub` keyword from `ShaderData`, hidding it as the implementation detail
it is.

Split from #5600
2022-08-08 22:46:04 +00:00
François
b80636b330 don't render completely transparent UI nodes (#5537)
# Objective

- I often have UI nodes that are completely transparent and just for organisation
- Don't render them
- I doesn't bring a lot of improvements, but it doesn't add a lot of complexity either
2022-08-08 21:58:20 +00:00
ira
992681b59b Make Resource trait opt-in, requiring #[derive(Resource)] V2 (#5577)
*This PR description is an edited copy of #5007, written by @alice-i-cecile.*
# Objective
Follow-up to https://github.com/bevyengine/bevy/pull/2254. The `Resource` trait currently has a blanket implementation for all types that meet its bounds.

While ergonomic, this results in several drawbacks:

* it is possible to make confusing, silent mistakes such as inserting a function pointer (Foo) rather than a value (Foo::Bar) as a resource
* it is challenging to discover if a type is intended to be used as a resource
* we cannot later add customization options (see the [RFC](https://github.com/bevyengine/rfcs/blob/main/rfcs/27-derive-component.md) for the equivalent choice for Component).
* dependencies can use the same Rust type as a resource in invisibly conflicting ways
* raw Rust types used as resources cannot preserve privacy appropriately, as anyone able to access that type can read and write to internal values
* we cannot capture a definitive list of possible resources to display to users in an editor
## Notes to reviewers
 * Review this commit-by-commit; there's effectively no back-tracking and there's a lot of churn in some of these commits.
   *ira: My commits are not as well organized :')*
 * I've relaxed the bound on Local to Send + Sync + 'static: I don't think these concerns apply there, so this can keep things simple. Storing e.g. a u32 in a Local is fine, because there's a variable name attached explaining what it does.
 * I think this is a bad place for the Resource trait to live, but I've left it in place to make reviewing easier. IMO that's best tackled with https://github.com/bevyengine/bevy/issues/4981.

## Changelog
`Resource` is no longer automatically implemented for all matching types. Instead, use the new `#[derive(Resource)]` macro.

## Migration Guide
Add `#[derive(Resource)]` to all types you are using as a resource.

If you are using a third party type as a resource, wrap it in a tuple struct to bypass orphan rules. Consider deriving `Deref` and `DerefMut` to improve ergonomics.

`ClearColor` no longer implements `Component`. Using `ClearColor` as a component in 0.8 did nothing.
Use the `ClearColorConfig` in the `Camera3d` and `Camera2d` components instead.


Co-authored-by: Alice <alice.i.cecile@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: devil-ira <justthecooldude@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-08-08 21:36:35 +00:00
Timo Kösters
2ac744331b Fix shader syntax (#5613) 2022-08-08 19:59:59 +00:00
Bleb1k
115211161b Added keyboard scan input event (#5495)
# Objective

- I wanted to have controls independent from keyboard layout and found that bevy doesn't have a proper implementation for that

## Solution

- I created a `ScanCode` enum with two hundreds scan codes and updated `keyboard_input_system` to include and update `ResMut<Input<ScanCode>>`
- closes both https://github.com/bevyengine/bevy/issues/2052 and https://github.com/bevyengine/bevy/issues/862

Co-authored-by: Bleb1k <91003089+Bleb1k@users.noreply.github.com>
2022-08-05 04:19:53 +00:00
ira
c37939d322 Make Children constructor pub(crate). (#5532)
#4197 intended to remove all `pub` constructors of `Children` and `Parent` and it seems like this one was missed.

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-08-05 03:49:12 +00:00
KDecay
54750deddd Document gamepad.rs (#5548)
# Objective

- Fixes #5544
- Part of the splitting process of #3692.

## Solution

- Document everything in the `gamepad.rs` file.
- Add a doc example for mocking gamepad input.

---

## Changelog

- Added and updated the documentation inside of the `gamepad.rs` file.
2022-08-05 02:28:07 +00:00
Robert Swain
704d8e251b Sync up bevy_sprite and bevy_ui shader View struct (#5531)
# Objective

- Similar to #5512 , the `View` struct definition in the shaders in `bevy_sprite` and `bevy_ui` were out of sync with the rust-side `ViewUniform`. Only `view_proj` was being used and is the first member and as those shaders are not customisable it makes little difference in practice, unlike for `Mesh2d`.

## Solution

- Sync shader `View` struct definition in `bevy_sprite` and `bevy_ui` with the correct definition that matches `ViewUniform`
2022-08-05 02:28:06 +00:00
github-actions[bot]
444150025d Bump Version after Release (#5576)
Bump version after release
This PR has been auto-generated
2022-08-05 02:03:05 +00:00
McSpidey
0ffb5441c3 changed diagnostics from seconds to milliseconds (#5554)
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>

# Objective

Change frametimediagnostic from seconds to milliseconds because this will always be less than one seconds and is the common diagnostic display unit for game engines.

## Solution

- multiplied the existing value by 1000

---

## Changelog

Frametimes are now reported in milliseconds

Co-authored-by: Syama Mishra <38512086+SyamaMishra@users.noreply.github.com>
Co-authored-by: McSpidey <mcspidey@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-08-04 22:27:14 +00:00
Peter Hebden
90d1dc8820 Add bevy_render::texture::ImageSettings to prelude (#5566)
# Objective

In Bevy 0.8, the default filter mode was changed to linear (#4465). I believe this is a sensible default, but it's also very common to want to use point filtering (e.g. for pixel art games). 

## Solution

I am proposing including `bevy_render::texture::ImageSettings` in the Bevy prelude so it is more ergonomic to change the filtering in such cases.

---

## Changelog

### Added
- Added `bevy_render::texture::ImageSettings` to prelude.
2022-08-04 22:09:52 +00:00
Marc-Stefan Cassola
765e8d7dca Fix lifetime bound on From impl for NonSendMut -> Mut (#5560)
# Objective

Fixes #5456
2022-08-04 22:09:51 +00:00
ira
13b4a7daaa Add Projection component to prelude. (#5557)
:)

Co-authored-by: Devil Ira <justthecooldude@gmail.com>
2022-08-04 22:09:50 +00:00
maxwellodri
97fdbad9db Added reflect/from reflect impls for NonZero integer types (#5556)
# Objective

Add reflect/from reflect impls for NonZero integer types. I'm guessing these haven't been added yet because no one has needed them as of yet.
2022-08-04 22:09:49 +00:00
Boxy
eabcd27d93 make WorldQuery very flat (#5205)
# Objective

Simplify the worldquery trait hierarchy as much as possible by putting it all in one trait. If/when gats are stabilised this can be trivially migrated over to use them, although that's not why I made this PR, those reasons are:
- Moves all of the conceptually related unsafe code for a worldquery next to eachother
- Removes now unnecessary traits simplifying the "type system magic" in bevy_ecs

---

## Changelog

All methods/functions/types/consts on `FetchState` and `Fetch` traits have been moved to the `WorldQuery` trait and the other traits removed. `WorldQueryGats` now only contains an `Item` and `Fetch` assoc type.

## Migration Guide
Implementors should move items in impls to the `WorldQuery/Gats` traits and remove any `Fetch`/`FetchState` impls
Any use sites of items in the `Fetch`/`FetchState` traits should be updated to use the `WorldQuery` trait items instead


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-08-04 21:51:02 +00:00
François
07d576987a fix order of exit/close window systems (#5558)
# Objective

Fixes #5384 and maybe other issues around window closing/app not exiting

## Solution

There are three systems involved in exiting when closing a window:
- `close_when_requested` asking Winit to close the window in stage `Update`
- `exit_on_all_closed` exiting when no window remains opened in stage `Update`
- `change_window` removing windows that are closed in stage `PostUpdate`

This ordering meant that when closing a window, we had to run one more frame to actually exit. As there was no window, panics could occur in systems assuming there was a window. In case of Bevy app using a low power options, that means waiting for the timeout before actually exiting the app (60 seconds by default)

This PR changes the ordering so that `exit_on_all_closed` happens after `change_window` in the same frame, so there isn't an extra frame without window
2022-08-03 20:03:34 +00:00
Gino Valente
bd008589f3 bevy_reflect: Update enum derives (#5473)
> In draft until #4761 is merged. See the relevant commits [here](a85fe94a18).

---

# Objective

Update enums across Bevy to use the new enum reflection and get rid of `#[reflect_value(...)]` usages.

## Solution

Find and replace all[^1] instances of `#[reflect_value(...)]` on enum types.

---

## Changelog

- Updated all[^1] reflected enums to implement `Enum` (i.e. they are no longer `ReflectRef::Value`)

## Migration Guide
Bevy-defined enums have been updated to implement `Enum` and are not considered value types (`ReflectRef::Value`) anymore. This means that their serialized representations will need to be updated. For example, given the Bevy enum:

```rust
pub enum ScalingMode {
  None,
  WindowSize,
  Auto { min_width: f32, min_height: f32 },
  FixedVertical(f32),
  FixedHorizontal(f32),
}
```

You will need to update the serialized versions accordingly.

```js
// OLD FORMAT
{
  "type": "bevy_render:📷:projection::ScalingMode",
  "value": FixedHorizontal(720),
},

// NEW FORMAT
{
  "type": "bevy_render:📷:projection::ScalingMode",
  "enum": {
    "variant": "FixedHorizontal",
    "tuple": [
      {
        "type": "f32",
        "value": 720,
      },
    ],
  },
},
```

This may also have other smaller implications (such as `Debug` representation), but serialization is probably the most prominent.

[^1]: All enums except `HandleId` as neither `Uuid` nor `AssetPathId` implement the reflection traits
2022-08-02 22:40:29 +00:00
Gino Valente
15826d6019 bevy_reflect: Reflect enums (#4761)
# Objective

> This is a revival of #1347. Credit for the original PR should go to @Davier.

Currently, enums are treated as `ReflectRef::Value` types by `bevy_reflect`. Obviously, there needs to be better a better representation for enums using the reflection API.

## Solution

Based on prior work from @Davier, an `Enum` trait has been added as well as the ability to automatically implement it via the `Reflect` derive macro. This allows enums to be expressed dynamically:

```rust
#[derive(Reflect)]
enum Foo {
  A,
  B(usize),
  C { value: f32 },
}

let mut foo = Foo::B(123);
assert_eq!("B", foo.variant_name());
assert_eq!(1, foo.field_len());

let new_value = DynamicEnum::from(Foo::C { value: 1.23 });
foo.apply(&new_value);
assert_eq!(Foo::C{value: 1.23}, foo);
```

### Features

#### Derive Macro

Use the `#[derive(Reflect)]` macro to automatically implement the `Enum` trait for enum definitions. Optionally, you can use `#[reflect(ignore)]` with both variants and variant fields, just like you can with structs. These ignored items will not be considered as part of the reflection and cannot be accessed via reflection.

```rust
#[derive(Reflect)]
enum TestEnum {
  A,
  // Uncomment to ignore all of `B`
  // #[reflect(ignore)]
  B(usize),
  C {
    // Uncomment to ignore only field `foo` of `C`
    // #[reflect(ignore)]
    foo: f32,
    bar: bool,
  },
}
```

#### Dynamic Enums

Enums may be created/represented dynamically via the `DynamicEnum` struct. The main purpose of this struct is to allow enums to be deserialized into a partial state and to allow dynamic patching. In order to ensure conversion from a `DynamicEnum` to a concrete enum type goes smoothly, be sure to add `FromReflect` to your derive macro.

```rust
let mut value = TestEnum::A;

// Create from a concrete instance
let dyn_enum = DynamicEnum::from(TestEnum::B(123));

value.apply(&dyn_enum);
assert_eq!(TestEnum::B(123), value);

// Create a purely dynamic instance
let dyn_enum = DynamicEnum::new("TestEnum", "A", ());

value.apply(&dyn_enum);
assert_eq!(TestEnum::A, value);
```

#### Variants

An enum value is always represented as one of its variants— never the enum in its entirety.

```rust
let value = TestEnum::A;
assert_eq!("A", value.variant_name());

// Since we are using the `A` variant, we cannot also be the `B` variant
assert_ne!("B", value.variant_name());
```

All variant types are representable within the `Enum` trait: unit, struct, and tuple.

You can get the current type like:

```rust
match value.variant_type() {
  VariantType::Unit => println!("A unit variant!"),
  VariantType::Struct => println!("A struct variant!"),
  VariantType::Tuple => println!("A tuple variant!"),
}
```

> Notice that they don't contain any values representing the fields. These are purely tags.

If a variant has them, you can access the fields as well:

```rust
let mut value = TestEnum::C {
  foo: 1.23,
  bar: false
};

// Read/write specific fields
*value.field_mut("bar").unwrap() = true;

// Iterate over the entire collection of fields
for field in value.iter_fields() {
  println!("{} = {:?}", field.name(), field.value());
}
```

#### Variant Swapping

It might seem odd to group all variant types under a single trait (why allow `iter_fields` on a unit variant?), but the reason this was done ~~is to easily allow *variant swapping*.~~ As I was recently drafting up the **Design Decisions** section, I discovered that other solutions could have been made to work with variant swapping. So while there are reasons to keep the all-in-one approach, variant swapping is _not_ one of them.

```rust
let mut value: Box<dyn Enum> = Box::new(TestEnum::A);
value.set(Box::new(TestEnum::B(123))).unwrap();
```

#### Serialization

Enums can be serialized and deserialized via reflection without needing to implement `Serialize` or `Deserialize` themselves (which can save thousands of lines of generated code). Below are the ways an enum can be serialized.

> Note, like the rest of reflection-based serialization, the order of the keys in these representations is important!

##### Unit

```json
{
  "type": "my_crate::TestEnum",
  "enum": {
    "variant": "A"
  }
}
```

##### Tuple

```json
{
  "type": "my_crate::TestEnum",
  "enum": {
    "variant": "B",
    "tuple": [
      {
        "type": "usize",
        "value": 123
      }
    ]
  }
}
```

<details>
<summary>Effects on Option</summary>

This ends up making `Option` look a little ugly:

```json
{
  "type": "core::option::Option<usize>",
  "enum": {
    "variant": "Some",
    "tuple": [
      {
        "type": "usize",
        "value": 123
      }
    ]
  }
}
```


</details>

##### Struct

```json
{
  "type": "my_crate::TestEnum",
  "enum": {
    "variant": "C",
    "struct": {
      "foo": {
        "type": "f32",
        "value": 1.23
      },
      "bar": {
        "type": "bool",
        "value": false
      }
    }
  }
}
```

## Design Decisions

<details>
<summary><strong>View Section</strong></summary>

This section is here to provide some context for why certain decisions were made for this PR, alternatives that could have been used instead, and what could be improved upon in the future.

### Variant Representation

One of the biggest decisions was to decide on how to represent variants. The current design uses a "all-in-one" design where unit, tuple, and struct variants are all simultaneously represented by the `Enum` trait. This is not the only way it could have been done, though.

#### Alternatives

##### 1. Variant Traits

One way of representing variants would be to define traits for each variant, implementing them whenever an enum featured at least one instance of them. This would allow us to define variants like:

```rust
pub trait Enum: Reflect {
  fn variant(&self) -> Variant;
}

pub enum Variant<'a> {
    Unit,
    Tuple(&'a dyn TupleVariant),
    Struct(&'a dyn StructVariant),
}

pub trait TupleVariant {
  fn field_len(&self) -> usize;
  // ...
}
```

And then do things like:

```rust
fn get_tuple_len(foo: &dyn Enum) -> usize {
  match foo.variant() {
    Variant::Tuple(tuple) => tuple.field_len(),
    _ => panic!("not a tuple variant!")
  }
}
```

The reason this PR does not go with this approach is because of the fact that variants are not separate types. In other words, we cannot implement traits on specific variants— these cover the *entire* enum. This means we offer an easy footgun:

```rust
let foo: Option<i32> = None;
let my_enum = Box::new(foo) as Box<dyn TupleVariant>;
```

Here, `my_enum` contains `foo`, which is a unit variant. However, since we need to implement `TupleVariant` for `Option` as a whole, it's possible to perform such a cast. This is obviously wrong, but could easily go unnoticed. So unfortunately, this makes it not a good candidate for representing variants.

##### 2. Variant Structs

To get around the issue of traits necessarily needing to apply to both the enum and its variants, we could instead use structs that are created on a per-variant basis. This was also considered but was ultimately [[removed](71d27ab3c6) due to concerns about allocations.

 Each variant struct would probably look something like:

```rust
pub trait Enum: Reflect {
  fn variant_mut(&self) -> VariantMut;
}

pub enum VariantMut<'a> {
    Unit,
    Tuple(TupleVariantMut),
    Struct(StructVariantMut),
}

struct StructVariantMut<'a> {
  fields: Vec<&'a mut dyn Reflect>,
  field_indices: HashMap<Cow<'static, str>, usize>
}
```

This allows us to isolate struct variants into their own defined struct and define methods specifically for their use. It also prevents users from casting to it since it's not a trait. However, this is not an optimal solution. Both `field_indices` and `fields` will require an allocation (remember, a `Box<[T]>` still requires a `Vec<T>` in order to be constructed). This *might* be a problem if called frequently enough.

##### 3. Generated Structs

The original design, implemented by @Davier, instead generates structs specific for each variant. So if we had a variant path like `Foo::Bar`, we'd generate a struct named `FooBarWrapper`. This would be newtyped around the original enum and forward tuple or struct methods to the enum with the chosen variant.

Because it involved using the `Tuple` and `Struct` traits (which are also both bound on `Reflect`), this meant a bit more code had to be generated. For a single struct variant with one field, the generated code amounted to ~110LoC. However, each new field added to that variant only added ~6 more LoC.

In order to work properly, the enum had to be transmuted to the generated struct:

```rust
fn variant(&self) -> crate::EnumVariant<'_> {
  match self {
    Foo::Bar {value: i32} => {
      let wrapper_ref = unsafe { 
        std::mem::transmute::<&Self, &FooBarWrapper>(self) 
      };
      crate::EnumVariant::Struct(wrapper_ref as &dyn crate::Struct)
    }
  }
}
```

This works because `FooBarWrapper` is defined as `repr(transparent)`.

Out of all the alternatives, this would probably be the one most likely to be used again in the future. The reasons for why this PR did not continue to use it was because:

* To reduce generated code (which would hopefully speed up compile times)
* To avoid cluttering the code with generated structs not visible to the user
* To keep bevy_reflect simple and extensible (these generated structs act as proxies and might not play well with current or future systems)
* To avoid additional unsafe blocks
* My own misunderstanding of @Davier's code

That last point is obviously on me. I misjudged the code to be too unsafe and unable to handle variant swapping (which it probably could) when I was rebasing it. Looking over it again when writing up this whole section, I see that it was actually a pretty clever way of handling variant representation.

#### Benefits of All-in-One

As stated before, the current implementation uses an all-in-one approach. All variants are capable of containing fields as far as `Enum` is concerned. This provides a few benefits that the alternatives do not (reduced indirection, safer code, etc.).

The biggest benefit, though, is direct field access. Rather than forcing users to have to go through pattern matching, we grant direct access to the fields contained by the current variant. The reason we can do this is because all of the pattern matching happens internally. Getting the field at index `2` will automatically return `Some(...)` for the current variant if it has a field at that index or `None` if it doesn't (or can't).

This could be useful for scenarios where the variant has already been verified or just set/swapped (or even where the type of variant doesn't matter):

```rust
let dyn_enum: &mut dyn Enum = &mut Foo::Bar {value: 123};
// We know it's the `Bar` variant
let field = dyn_enum.field("value").unwrap();
```

Reflection is not a type-safe abstraction— almost every return value is wrapped in `Option<...>`. There are plenty of places to check and recheck that a value is what Reflect says it is. Forcing users to have to go through `match` each time they want to access a field might just be an extra step among dozens of other verification processes.

 Some might disagree, but ultimately, my view is that the benefit here is an improvement to the ergonomics and usability of reflected enums.

</details>

---

## Changelog

### Added

* Added `Enum` trait
* Added `Enum` impl to `Reflect` derive macro
* Added `DynamicEnum` struct
  * Added `DynamicVariant`
* Added `EnumInfo`
  * Added `VariantInfo`
    * Added `StructVariantInfo`
    * Added `TupleVariantInfo`
    * Added `UnitVariantInfo`
* Added serializtion/deserialization support for enums
  * Added `EnumSerializer`

* Added `VariantType`
* Added `VariantFieldIter`
* Added `VariantField`
* Added `enum_partial_eq(...)`
* Added `enum_hash(...)`

### Changed

* `Option<T>` now implements `Enum`
* `bevy_window` now depends on `bevy_reflect`
  * Implemented `Reflect` and `FromReflect` for `WindowId`
* Derive `FromReflect` on `PerspectiveProjection`
* Derive `FromReflect` on `OrthographicProjection`
* Derive `FromReflect` on `WindowOrigin`
* Derive `FromReflect` on `ScalingMode`
* Derive `FromReflect` on `DepthCalculation`


## Migration Guide

* Enums no longer need to be treated as values and usages of `#[reflect_value(...)]` can be removed or replaced by `#[reflect(...)]`
* Enums (including `Option<T>`) now take a different format when serializing. The format is described above, but this may cause issues for existing scenes that make use of enums. 

---

Also shout out to @nicopap for helping clean up some of the code here! It's a big feature so help like this is really appreciated!

Co-authored-by: Gino Valente <gino.valente.code@gmail.com>
2022-08-02 22:14:41 +00:00
Josh Stratton
a9cb18eefc add default direction to DirectionalLight docs (#5188)
# Objective

- Adds a default direction to the documentation of DirectionalLight 

## Solution

Suggestion from Q&A answer: 
https://github.com/bevyengine/bevy/discussions/5186#discussioncomment-3073767
2022-08-02 18:13:21 +00:00
0x182d4454fb211940
fdcffb885f Remove duplicate RenderGraph insertion to render world (#5551)
# Objective

- Remove unnecessary duplicate `init_resource` call for `RenderGraph`.

## Solution

- Remove unnecessary duplicate `init_resource` call for `RenderGraph`.
2022-08-02 12:45:54 +00:00
Rob Parrett
825518564a Add docs for arguments of various color functions (#5533)
Fixes #5530
2022-08-02 00:04:49 +00:00
PROMETHIA-27
f3b5bf029c Add FromWorld bound to T in Local<T> (#5481)
# Objective

Currently, actually using a `Local` on a system requires that it be `T: FromWorld`, but that requirement is only expressed on the `SystemParam` machinery, which leads to the confusing error message for when the user attempts to add an invalid system. By adding these bounds to `Local` directly, it improves clarity on usage and semantics. 

## Solution

- Add `T: FromWorld` bound to `Local`'s definition

## Migration Guide

- It might be possible for references to `Local`s without `T: FromWorld` to exist, but these should be exceedingly rare and probably dead code. In the event that one of these is encountered, the easiest solutions are to delete the code or wrap the inner `T` in an `Option` to allow it to be default constructed to `None`.
2022-08-01 16:50:11 +00:00
KDecay
bf085ee1d2 Remove Size and UiRect generics (#5404)
# Objective

- Migrate changes from #3503.

## Solution

- Change `Size<T>` and `UiRect<T>` to `Size` and `UiRect` using `Val`.
- Implement `Sub`, `SubAssign`, `Mul`, `MulAssign`, `Div` and `DivAssign` for `Val`.
- Update tests for `Size`.

---

## Changelog

### Changed

- The generic `T` of `Size` and `UiRect` got removed and instead they both now always use `Val`.

## Migration Guide

- The generic `T` of `Size` and `UiRect` got removed and instead they both now always use `Val`. If you used a `Size<f32>` consider replacing it with a `Vec2` which is way more powerful.


Co-authored-by: KDecay <KDecayMusic@protonmail.com>
2022-08-01 16:27:16 +00:00
Azervu
6752c9c59b Fix View by adding missing fields present in ViewUniform (#5512)
# Objective

View mesh2d_view_types.wgsl was missing a couple of fields present in bevy::render::ViewUniform, causing rendering issues for shaders using later fields.

## Solution
Solved by adding the fields in question
2022-07-31 19:10:53 +00:00
github-actions[bot]
856588ed7c Release 0.8.0 (#5490)
Preparing next release
This PR has been auto-generated
2022-07-30 14:07:30 +00:00
Robert Swain
05e5008624 Support array / cubemap / cubemap array textures in KTX2 (#5325)
# Objective

- Fix / support KTX2 array / cubemap / cubemap array textures
- Fixes #4495 . Supersedes #4514 .

## Solution

- Add `Option<TextureViewDescriptor>` to `Image` to enable configuration of the `TextureViewDimension` of a texture.
  - This allows users to set `D2Array`, `D3`, `Cube`, `CubeArray` or whatever they need
  - Automatically configure this when loading KTX2
- Transcode all layers and faces instead of just one
- Use the UASTC block size of 128 bits, and the number of blocks in x/y for a given mip level in order to determine the offset of the layer and face within the KTX2 mip level data
- `wgpu` wants data ordered as layer 0 mip 0..n, layer 1 mip 0..n, etc. See https://docs.rs/wgpu/latest/wgpu/util/trait.DeviceExt.html#tymethod.create_texture_with_data
- Reorder the data KTX2 mip X layer Y face Z to `wgpu` layer Y face Z mip X order
- Add a `skybox` example to demonstrate / test loading cubemaps from PNG and KTX2, including ASTC 4x4, BC7, and ETC2 compression for support everywhere. Note that you need to enable the `ktx2,zstd` features to be able to load the compressed textures.

---

## Changelog

- Fixed: KTX2 array / cubemap / cubemap array textures
- Fixes: Validation failure for compressed textures stored in KTX2 where the width/height are not a multiple of the block dimensions.
- Added: `Image` now has an `Option<TextureViewDescriptor>` field to enable configuration of the texture view. This is useful for configuring the `TextureViewDimension` when it is not just a plain 2D texture and the loader could/did not identify what it should be.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-07-30 07:02:58 +00:00
ira
83a9e16158 Replace many_for_each_mut with iter_many_mut. (#5402)
# Objective
Replace `many_for_each_mut` with `iter_many_mut` using the same tricks to avoid aliased mutability that `iter_combinations_mut` uses.

<sub>I tried rebasing the draft PR I made for this before and it died. F</sub>
## Why
`many_for_each_mut` is worse for a few reasons:
1. The closure prevents the use of `continue`, `break`, and `return` behaves like a limited `continue`.
2. rustfmt will crumple it and double the indentation when the line gets too long.
    ```rust
    query.many_for_each_mut(
        &entity_list,
        |(mut transform, velocity, mut component_c)| {
            // Double trouble.
        },
    );
    ```
3. It is more surprising to have `many_for_each_mut` as a mutable counterpart to `iter_many` than `iter_many_mut`.
4. It required a separate unsafe fn; more unsafe code to maintain.
5. The `iter_many_mut` API matches the existing `iter_combinations_mut` API.

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-07-30 01:38:13 +00:00
Carter Anderson
418beffaec Revert "Recalculate entity aabbs when meshes change (#4944)" (#5489)
# Objective

Sadly, #4944 introduces a serious exponential despawn behavior, which cannot be included in 0.8. [Handling AABBs properly is a controversial topic](https://github.com/bevyengine/bevy/pull/5423#issuecomment-1199995825) and one that deserves more time than the day we have left before release.

## Solution

This reverts commit c2b332f98a.
2022-07-29 23:24:39 +00:00
François
4078273e93 fix bevy_reflect README (#5477)
# Objective

- Code in `bevy_reflect` README doesn't compile

## Solution

- Fix it
2022-07-29 20:01:51 +00:00
Brandon Reinhart
2d2ea337dd add a debug label to storage buffers (#5341)
# Objective

- Expose the wgpu debug label on storage buffer types.

## Solution

🐄

- Add an optional cow static string and pass that to the label field of create_buffer_with_data
- This pattern is already used by Bevy for debug tags on bind group and layout descriptors.

---

Example Usage:

A buffer is given a label using the label function. Alternatively a buffer may be labeled when it is created if the default() convention is not used.
![ray_buf](https://user-images.githubusercontent.com/106117615/179366494-f037bd8c-4d65-4b37-8135-01ac0c5c8ee0.png)

Here is the buffer appearing with the correct name in RenderDoc. Previously the buffer would have an anonymous name such as "Buffer223":
![buffer_named](https://user-images.githubusercontent.com/106117615/179366552-faeb6c27-5373-4e4e-a0e2-c04446f95a4b.png)



Co-authored-by: rebelroad-reinhart <reinhart@rebelroad.gg>
2022-07-28 20:37:49 +00:00
François
4e2600b788 text rendering: convert colours only once per section (#5474)
# Objective

- Improve performance when rendering text

## Solution

- While playing with example `many_buttons`, I noticed a lot of time was spent converting colours
- Investigating, the biggest culprit seems to be text colour. Each glyph in a text is an individual UI node for rendering, with a copy of the colour. Making the conversion to RGBA linear only once per text section reduces the number of conversion done once rendering.
- This improves FPS for example `many_buttons` from ~33 to ~42
- I did the same change for text 2d
2022-07-28 13:34:56 +00:00
Carter Anderson
c6a41cdd10 ImageSampler linear/nearest constructors (#5466)
# Objective

I found this small ux hiccup when writing the 0.8 blog post:

```rust
image.sampler = ImageSampler::Descriptor(ImageSampler::nearest_descriptor());
```

Not good!

## Solution

```rust
image.sampler = ImageSampler::nearest();
```

(there are Good Reasons to keep around the nearest_descriptor() constructor and I think it belongs on this type)
2022-07-27 06:49:37 +00:00
Boxy
be19c696bd Add missing ReadOnly = Self bound (#5462)
# Objective
`ReadOnlyWorldQuery` should have required `Self::ReadOnly = Self` so that calling `.iter()` on a readonly query is equivelent to calling `iter_mut()`.

## Solution

add `ReadOnly = Self` to the definition of `ReadOnlyWorldQuery`

---

## Changelog

ReadOnlyWorldQuery's `ReadOnly` assoc type is now always equal to `Self`

## Migration Guide

Make `Self::ReadOnly = Self` hold
2022-07-27 06:49:36 +00:00
robtfm
6a1ba9c456 Spotlight shadow bugfix (#5451)
# Objective

fix an error in shadow map indexing that occurs when point lights without shadows are used in conjunction with spotlights with shadows

## Solution

calculate point_light_count correctly
2022-07-25 16:24:54 +00:00
Jerome Humbert
d4787111a3 Conversion of ResMut and NonSendMut to Mut (#5438)
# Objective

Enable treating components and resources equally, which can
simplify the implementation of some systems where only the change
detection feature is relevant and not the kind of object (resource or
component).

## Solution

Implement `From<ResMut<T>>` and `From<NonSendMut<T>>` for
`Mut`. Since the 3 structs are similar, and only differ by their system
param role, the conversion is trivial.

---

## Changelog

Added - `From<ResMut>` and `From<NonSendMut>` for `Mut<T>`.
2022-07-25 16:11:29 +00:00
François
231894a3a6 Lighter no default features (#5447)
# Objective

- Even though it's marked as optional, it is no longer possible to not depend on `bevy_render` as it's a dependency of `bevy_scene`

## Solution

- Make `bevy_scene` optional
- For the minimalist among us, also make `bevy_asset` optional
2022-07-25 15:48:14 +00:00
eiei114
619c30c036 Fix comment typo (#5421)
# Objective

- Fix some typos

## Solution

For the first time in my life, I made a pull request to OSS.
Am I right?


Co-authored-by: eiei114 <60887155+eiei114@users.noreply.github.com>
2022-07-22 15:04:32 +00:00
Rob Parrett
cfee0e882e Fix various typos (#5417)
## Objective

- Fix some typos

## Solution

- Fix em. 
- My favorite was `maxizimed`
2022-07-21 20:46:54 +00:00
François
77894639f8 bevy_asset: add missing doc in wasm (#5407)
# Objective

- `#![warn(missing_docs)]` was added to bevy_asset in #3536
- A method was not documented when targeting wasm

## Solution

- Add documentation for it
2022-07-21 14:57:38 +00:00
Jakob Hellermann
4b191d968d remove blanket Serialize + Deserialize requirement for Reflect on generic types (#5197)
# Objective

Some generic types like `Option<T>`, `Vec<T>` and `HashMap<K, V>` implement `Reflect` when where their generic types `T`/`K`/`V` implement `Serialize + for<'de> Deserialize<'de>`.
This is so that in their `GetTypeRegistration` impl they can insert the `ReflectSerialize` and `ReflectDeserialize` type data structs.

This has the annoying side effect that if your struct contains a `Option<NonSerdeStruct>` you won't be able to derive reflect (https://github.com/bevyengine/bevy/issues/4054).

## Solution

- remove the `Serialize + Deserialize` bounds on wrapper types
  - this means that `ReflectSerialize` and `ReflectDeserialize` will no longer be inserted even for `.register::<Option<DoesImplSerde>>()`
- add `register_type_data<T, D>` shorthand for `registry.get_mut(T).insert(D::from_type<T>())`
- require users to register their specific generic types **and the serde types** separately like
```rust
        .register_type::<Option<String>>()
        .register_type_data::<Option<String>, ReflectSerialize>()
        .register_type_data::<Option<String>, ReflectDeserialize>()

```
I believe this is the best we can do for extensibility and convenience without specialization.


## Changelog

- `.register_type` for generic types like `Option<T>`, `Vec<T>`, `HashMap<K, V>` will no longer insert `ReflectSerialize` and `ReflectDeserialize` type data. Instead you need to register it separately for concrete generic types like so:
```rust
        .register_type::<Option<String>>()
        .register_type_data::<Option<String>, ReflectSerialize>()
        .register_type_data::<Option<String>, ReflectDeserialize>()
```

TODO: more docs and tweaks to the scene example to demonstrate registering generic types.
2022-07-21 14:57:37 +00:00
Robert Swain
1c23421f41 dds: Ensure the Extent3d for compressed textures represents the physical size (#5406)
# Objective

- wgpu 0.13 has validation to ensure that the width and height specified for a texture are both multiples of the respective block width and block height. This means validation fails for compressed textures with say a 4x4 block size, but non-modulo-4 image width/height.

## Solution

- Using `Extent3d`'s `physical_size()` method in the `dds` loader. It takes a `TextureFormat` argument and ensures the resolution is correct.

---

## Changelog

- Fixes: Validation failure for compressed textures stored in `dds` where the width/height are not a multiple of the block dimensions.
2022-07-20 22:43:36 +00:00
Nicola Papale
4b1f6f4ebb Add some documentation to standard material fields (#5323)
# Objective

the bevy pbr shader doesn't handle at all normal maps
if a mesh doesn't have backed tangents. This is a pitfall
(that I fell into) and needs to be documented.

# Solution

Document the behavior. (Also document a few other
`StandardMaterial` fields)

## Changelog

* Add documentation to `emissive`, `normal_map_texture` and `occlusion_texture` fields of `StandardMaterial`.
2022-07-20 22:00:59 +00:00
adsick
99440c11b3 removed duplicated doc line in material.rs (#5405)
# Objective

I've found there is a duplicated line, probably left after some copy paste.

## Solution

- removed it

---



Co-authored-by: adsick <vadimgangsta73@gmail.com>
2022-07-20 21:39:51 +00:00
Alice Cecile
01f5f8cbe3 Disable UI node Interaction when ComputedVisibility is false (#5361)
# Objective

UI nodes can be hidden by setting their `Visibility` property. Since #5310 was merged, this is now ergonomic to use, as visibility is now inherited.

However, UI nodes still receive (and store) interactions when hidden, resulting in surprising hidden state (and an inability to otherwise disable UI nodes.

## Solution

Fixes #5360.

I've updated the `ui_focus_system` to accomplish this in a minimally intrusive way, and updated the docs to match.

**NOTE:** I have not added automated tests to verify this behavior, as we do not currently have a good testing paradigm for `bevy_ui`. I'm not thrilled with that by any means, but I'm not sure fixing it is within scope.

## Paths not taken

### Separate `Disabled` component

This is a much larger and more controversial change, and not well-scoped to UI.
Furthermore, it is extremely rare that you want hidden UI elements to function: the most common cases are for things like changing tabs, collapsing elements or so on.
Splitting this behavior would be more complex, and substantially violate user expectations.

### A separate limbo world

Mentioned in the linked issue. Super cool, but all of the problems  of the `Disabled` component solution with a whole new RFC-worth of complexity.

### Using change detection to reduce the amount of redundant work

Adds a lot of complexity for questionable performance gains. Likely involves a complete refactor of the entire system.

We simply don't have the tests or benchmarks here to justify this.

## Changelog

- UI nodes are now always in an `Interaction::None` state while they are hidden (via the `ComputedVisibility` component).
2022-07-20 21:26:47 +00:00
François
c0b87d284f don't cull ui nodes that have a rotation (#5389)
# Objective

- Fixes #5293 
- UI nodes with a rotation that made the top left corner lower than the top right corner (z rotations greater than π/4) were culled

## Solution

- Do not cull nodes with a rotation, but don't do proper culling in this case



As a reminder, changing rotation and scale of UI nodes is not recommended as it won't impact layout. This is a quick fix but doesn't handle properly rotations and scale in clipping/culling. This would need a lot more work as mentioned here: c2b332f98a/crates/bevy_ui/src/render/mod.rs (L404-L405)
2022-07-20 20:03:13 +00:00
JoJoJet
56e9a3de88 improve documentation for macro-generated label types (#5367)
# Objective

I noticed while working on #5366 that the documentation for label types wasn't working correctly. Having experimented with this for a few weeks, I believe that generating docs in macros is more effort than it's worth.

## Solution

Add more boilerplate, copy-paste and edit the docs across types. This also lets us add custom doctests for specific types. Also, we don't need `concat_idents` as a dependency anymore.
2022-07-20 19:39:42 +00:00
Brian Merchant
433306b978 Documenting UniformBuffer, DynamicUniformBuffer, StorageBuffer and DynamicStorageBuffer. (#5223)
# Objective

Documents the `UniformBuffer`, `DynamicUniformBuffer`, `StorageBuffer` and `DynamicStorageBuffer` render resources.


## Solution

I looked through Discord discussion on these structures, and found [a comment](https://discord.com/channels/691052431525675048/953222550568173580/956596218857918464) to be particularly helpful, in the general discussion around encase. Other resources I have used are documented here:  https://discord.com/channels/691052431525675048/968333504838524958/991195474029715520


Co-authored-by: Brian Merchant <bhmerchant@gmail.com>
2022-07-20 17:24:34 +00:00
KDecay
60c6934f32 Document Size and UiRect (#5381)
# Objective

- Migrate changes from #3503.

## Solution

- Document `Size` and `UiRect`.
- I also removed the type alias from the `size_ops` test since it's unnecessary.

## Follow Up

After this change is merged I'd follow up with removing the generics from `Size` and `UiRect` since `Val` should be extensible enough. This was also discussed and decided on in #3503. let me know if this is not needed or wanted anymore!
2022-07-20 15:42:18 +00:00
Zicklag
ee3368b201 Update Notify Dependency (#5396)
# Objective

I want to use the `deno_runtime` crate in my game, but it has a conflict with the version of the `notify` crate that Bevy depends on.

## Solution

Updates the version of the `notify` crate the Bevy depends on.
2022-07-20 15:18:26 +00:00
sark
84bf6f611a Export anyhow::error for custom asset loaders (#5359)
If users try to implement a custom asset loader, they must manually import anyhow::error as it's used by the asset loader trait but not exported.

2b93ab5812/examples/asset/custom_asset.rs (L25)

Fixes #3138

Co-authored-by: sark <sarkahn@hotmail.com>
2022-07-20 14:14:30 +00:00
ira
9f906fdc8b Improve ergonomics and reduce boilerplate around creating text elements. (#5343)
# Objective

Creating UI elements is very boilerplate-y with lots of indentation.
This PR aims to reduce boilerplate around creating text elements.

## Changelog

* Renamed `Text::with_section` to `from_section`.
  It no longer takes a `TextAlignment` as argument, as the vast majority of cases left it `Default::default()`.
* Added `Text::from_sections` which creates a `Text` from a list of `TextSections`.
  Reduces line-count and reduces indentation by one level.
* Added `Text::with_alignment`.
  A builder style method for setting the `TextAlignment` of a `Text`.
* Added `TextSection::new`.
  Does not reduce line count, but reduces character count and made it easier to read. No more `.to_string()` calls!
* Added `TextSection::from_style` which creates an empty `TextSection` with a style.
  No more empty strings! Reduces indentation.
* Added `TextAlignment::CENTER` and friends.
* Added methods to `TextBundle`. `from_section`, `from_sections`, `with_text_alignment` and `with_style`.

## Note for reviewers.
Because of the nature of these changes I recommend setting diff view to 'split'.
~~Look for the book icon~~ cog in the top-left of the Files changed tab.

Have fun reviewing ❤️
<sup> >:D </sup>

## Migration Guide

`Text::with_section` was renamed to `from_section` and no longer takes a `TextAlignment` as argument.
Use `with_alignment` to set the alignment instead.

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-07-20 14:14:29 +00:00
KDecay
222f2dd32c Fix OwningPtr docs (#5391)
# Objective

- Fix some small errors in the documentation of the `OwningPtr` struct.

## Solution

- Change comments with 4 slashes `////` to doc comments with 3 slashes `///`.
- Fix typos.
2022-07-20 13:16:28 +00:00
Mark Lodato
c2b332f98a Recalculate entity aabbs when meshes change (#4944)
# Objective

Update the `calculate_bounds` system to update `Aabb`s
for entities who've either:
- gotten a new mesh
- had their mesh mutated

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

## Solution

There are two commits here to address the two issues above:

### Commit 1

**This Commit**
Updates the `calculate_bounds` system to operate not only on entities
without `Aabb`s but also on entities whose `Handle<Mesh>` has changed.

**Why?**
So if an entity gets a new mesh, its associated `Aabb` is properly
recalculated.

**Questions**
- This type is getting pretty gnarly - should I extract some types?
- This system is public - should I add some quick docs while I'm here?

### Commit 2

**This Commit**
Updates `calculate_bounds` to update `Aabb`s of entities whose meshes
have been directly mutated.

**Why?**
So if an entity's mesh gets updated, its associated `Aabb` is properly
recalculated.

**Questions**
- I think we should be using `ahash`. Do we want to do that with a
  direct `hashbrown` dependency or an `ahash` dependency that we
  configure the `HashMap` with?
- There is an edge case of duplicates with `Vec<Entity>` in the
  `HashMap`. If an entity gets its mesh handle changed and changed back
  again it'll be added to the list twice. Do we want to use a `HashSet`
  to avoid that? Or do a check in the list first (assuming iterating
  over the `Vec` is faster and this edge case is rare)?
- There is an edge case where, if an entity gets a new mesh handle and
  then its old mesh is updated, we'll update the entity's `Aabb` to the
  new geometry of the _old_ mesh. Do we want to remove items from the
  `Local<HashMap>` when handles change? Does the `Changed` event give us
  the old mesh handle? If not we might need to have a
  `HashMap<Entity, Handle<Mesh>>` or something so we can unlink entities
  from mesh handles when the handle changes.
- I did the `zip()` with the two `HashMap` gets assuming those would
  be faster than calculating the Aabb of the mesh (otherwise we could do
  `meshes.get(mesh_handle).and_then(Mesh::compute_aabb).zip(entity_mesh_map...)`
  or something). Is that assumption way off?

## Testing

I originally tried testing this with `bevy_mod_raycast` as mentioned in the
original issue but it seemed to work (maybe they are currently manually
updating the Aabbs?). I then tried doing it in 2D but it looks like
`Handle<Mesh>` is just for 3D. So I took [this example](https://github.com/bevyengine/bevy/blob/main/examples/3d/pbr.rs)
and added some systems to mutate/assign meshes:

<details>
<summary>Test Script</summary>

```rust
use bevy::prelude::*;
use bevy::render:📷:ScalingMode;
use bevy::render::primitives::Aabb;

/// Make sure we only mutate one mesh once.
#[derive(Eq, PartialEq, Clone, Debug, Default)]
struct MutateMeshState(bool);

/// Let's have a few global meshes that we can cycle between.
/// This way we can be assigned a new mesh, mutate the old one, and then get the old one assigned.
#[derive(Eq, PartialEq, Clone, Debug, Default)]
struct Meshes(Vec<Handle<Mesh>>);

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .init_resource::<MutateMeshState>()
        .init_resource::<Meshes>()
        .add_startup_system(setup)
        .add_system(assign_new_mesh)
        .add_system(show_aabbs.after(assign_new_mesh))
        .add_system(mutate_meshes.after(show_aabbs))
        .run();
}

fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut global_meshes: ResMut<Meshes>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    let m1 = meshes.add(Mesh::from(shape::Icosphere::default()));
    let m2 = meshes.add(Mesh::from(shape::Icosphere {
        radius: 0.90,
        ..Default::default()
    }));
    let m3 = meshes.add(Mesh::from(shape::Icosphere {
        radius: 0.80,
        ..Default::default()
    }));
    global_meshes.0.push(m1.clone());
    global_meshes.0.push(m2);
    global_meshes.0.push(m3);

    // add entities to the world
    // sphere
    commands.spawn_bundle(PbrBundle {
        mesh: m1,
        material: materials.add(StandardMaterial {
            base_color: Color::hex("ffd891").unwrap(),
            ..default()
        }),
        ..default()
    });
    // new 3d camera
    commands.spawn_bundle(Camera3dBundle {
        projection: OrthographicProjection {
            scale: 3.0,
            scaling_mode: ScalingMode::FixedVertical(1.0),
            ..default()
        }
        .into(),
        ..default()
    });

    // old 3d camera
    // commands.spawn_bundle(OrthographicCameraBundle {
    //     transform: Transform::from_xyz(0.0, 0.0, 8.0).looking_at(Vec3::default(), Vec3::Y),
    //     orthographic_projection: OrthographicProjection {
    //         scale: 0.01,
    //         ..default()
    //     },
    //     ..OrthographicCameraBundle::new_3d()
    // });
}
fn show_aabbs(query: Query<(Entity, &Handle<Mesh>, &Aabb)>) {
    for thing in query.iter() {
        println!("{thing:?}");
    }
}

/// For testing the second part - mutating a mesh.
///
/// Without the fix we should see this mutate an old mesh and it affects the new mesh that the
/// entity currently has.
/// With the fix, the mutation doesn't affect anything until the entity is reassigned the old mesh.
fn mutate_meshes(
    mut meshes: ResMut<Assets<Mesh>>,
    time: Res<Time>,
    global_meshes: Res<Meshes>,
    mut mutate_mesh_state: ResMut<MutateMeshState>,
) {
    let mutated = mutate_mesh_state.0;
    if time.seconds_since_startup() > 4.5 && !mutated {
        println!("Mutating {:?}", global_meshes.0[0]);
        let m = meshes.get_mut(&global_meshes.0[0]).unwrap();
        let mut p = m.attribute(Mesh::ATTRIBUTE_POSITION).unwrap().clone();
        use bevy::render::mesh::VertexAttributeValues;
        match &mut p {
            VertexAttributeValues::Float32x3(v) => {
                v[0] = [10.0, 10.0, 10.0];
            }
            _ => unreachable!(),
        }
        m.insert_attribute(Mesh::ATTRIBUTE_POSITION, p);
        mutate_mesh_state.0 = true;
    }
}

/// For testing the first part - assigning a new handle.
fn assign_new_mesh(
    mut query: Query<&mut Handle<Mesh>, With<Aabb>>,
    time: Res<Time>,
    global_meshes: Res<Meshes>,
) {
    let s = time.seconds_since_startup() as usize;
    let idx = s % global_meshes.0.len();
    for mut handle in query.iter_mut() {
        *handle = global_meshes.0[idx].clone_weak();
    }
}
```

</details>

## Changelog

### Fixed
Entity `Aabb`s not updating when meshes are mutated or re-assigned.
2022-07-20 07:05:29 +00:00
harudagondi
959f3b1186 Allows conversion of mutable queries to immutable queries (#5376)
# Objective

- Allows conversion of mutable queries to immutable queries.
- Fixes #4606

## Solution

- Add `to_readonly` method on `Query`, which uses `QueryState::as_readonly`
- `AsRef` is not feasible because creation of new queries is needed.

---

## Changelog

### Added

- Allows conversion of mutable queries to immutable queries using `Query::to_readonly`.
2022-07-20 01:09:45 +00:00
Jakob Hellermann
7dcfaaef67 bevy_reflect: ReflectFromPtr to create &dyn Reflect from a *const () (#4475)
# Objective

https://github.com/bevyengine/bevy/pull/4447 adds functions that can fetch resources/components as `*const ()` ptr by providing the `ComponentId`. This alone is not enough for them to be usable safely with reflection, because there is no general way to go from the raw pointer to a `&dyn Reflect` which is the pointer + a pointer to the VTable of the `Reflect` impl.

By adding a `ReflectFromPtr` type that is included in the type type registration when deriving `Reflect`, safe functions can be implemented in scripting languages that don't assume a type layout and can access the component data via reflection:

```rust
#[derive(Reflect)]
struct StringResource {
    value: String
}
```

```lua
local res_id = world:resource_id_by_name("example::StringResource")
local res = world:resource(res_id)

print(res.value)
```

## Solution

1. add a `ReflectFromPtr` type with a `FromType<T: Reflect>` implementation and the following methods:
- `     pub unsafe fn as_reflect_ptr<'a>(&self, val: Ptr<'a>) -> &'a dyn Reflect`
- `     pub unsafe fn as_reflect_ptr_mut<'a>(&self, val: PtrMut<'a>) -> &'a mud dyn Reflect`

Safety requirements of the methods are that you need to check that the `ReflectFromPtr` was constructed for the correct type.

2. add that type to the `TypeRegistration` in the `GetTypeRegistration` impl generated by `#[derive(Reflect)]`.
This is different to other reflected traits because it doesn't need `#[reflect(ReflectReflectFromPtr)]` which IMO should be there by default.

Co-authored-by: Jakob Hellermann <hellermann@sipgate.de>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-07-19 23:00:34 +00:00
François
0fa499a7d0 rename send_default_event to send_event_default on world (#5383)
after #5355, three methods were added on world:
* `send_event`
* `send_event_batch`
* `send_default_event`

rename `send_default_event` to `send_event_default` for better discoverability
2022-07-19 22:28:05 +00:00
Matthew Taylor
50a44417ba Derive AsBindGroup Improvements: Better errors, more options, update examples (#5364)
# Objective

- Provide better compile-time errors and diagnostics.
- Add more options to allow more textures types and sampler types.
- Update array_texture example to use upgraded AsBindGroup derive macro.

## Solution

Split out the parsing of the inner struct/field attributes (the inside part of a `#[foo(...)]` attribute) for better clarity

Parse the binding index for all inner attributes, as it is part of all attributes (`#[foo(0, ...)`), then allow each attribute implementer to parse the rest of the attribute metadata as needed. This should make it very trivial to extend/change if needed in the future.

Replaced invocations of `panic!` with the `syn::Error` type, providing fine-grained errors that retains span information. This provides much nicer compile-time errors, and even better IDE errors.

![image](https://user-images.githubusercontent.com/7478134/179452241-6d85d440-4b67-44da-80a7-9d47e8c88b8a.png)

Updated the array_texture example to demonstrate the new changes.

## New AsBindGroup attribute options


### `#[texture(u32, ...)]`
Where `...` is an optional list of arguments.
| Arguments    	| Values                                                         	| Default |
|--------------	|----------------------------------------------------------------	| ----------- |
| dimension = "..."    	| `"1d"`, `"2d"`, `"2d_array"`, `"3d"`, `"cube"`, `"cube_array"` 	|    `"2d"`    |
| sample_type = "..."  	| `"float"`, `"depth"`, `"s_int"` or `"u_int"`                   	|    `"float"`    |
| filterable = ...   	| `true`, `false`                                                	|    `true`     |
| multisampled = ... 	| `true`, `false`                                                	|    `false` |
| visibility(...) 	| `all`, `none`, or a list-combination of `vertex`, `fragment`, `compute` |   `vertex`, `fragment`   |

Example: `#[texture(0, dimension = "2d_array", visibility(vertex, fragment))]`


### `#[sampler(u32, ...)]`
Where `...` is an optional list of arguments.
| Arguments 	| Values                                            	| Default |
|-----------	|---------------------------------------------------	| ----------- |
| sampler_type = "..."   	| `"filtering"`, `"non_filtering"`, `"comparison"`. 	|  `"filtering"`  |
| visibility(...) 	| `all`, `none`, or a list-combination of `vertex`, `fragment`, `compute` |   `vertex`, `fragment`   |

Example: `#[sampler(0, sampler_type = "filtering", visibility(vertex, fragment)]`

## Changelog

- Added more options to `#[texture(...)]` and `#[sampler(...)]` attributes, supporting more kinds of materials. See above for details.
- Upgraded IDE and compile-time error messages.
- Updated array_texture example using the new options.
2022-07-19 22:05:43 +00:00
Aevyrie
282f8ed0b9 Add helpers to send Events from World (#5355)
# Objective

- With access to `World`, it's not obvious how to send an event.
- This is especially useful if you are writing a `Command` that needs to send an `Event`.
- `Events` are a first-class construct in bevy, even though they are just `Resources` under the hood. Their methods should be discoverable.

## Solution

- Provide a simple helpers to send events through `Res<Events<T>>`.
---

## Changelog

> `send_event`, `send_default_event`, and `send_event_batch` methods added to `World`.
2022-07-19 20:54:03 +00:00
JoJoJet
44e9cd4bfc Add attribute to ignore fields of derived labels (#5366)
# Objective

Fixes #5362 

## Solution

Add the attribute `#[label(ignore_fields)]` for `*Label` types.

```rust
#[derive(SystemLabel)]
pub enum MyLabel {
    One,

    // Previously this was not allowed since labels cannot contain data.
    #[system_label(ignore_fields)]
    Two(PhantomData<usize>),
}
```

## Notes

This label makes it possible for equality to behave differently depending on whether or not you are treating the type as a label. For example:

```rust
#[derive(SystemLabel, PartialEq, Eq)]
#[system_label(ignore_fields)]
pub struct Foo(usize);
```

If you compare it as a label, it will ignore the wrapped fields as the user requested. But if you compare it as a `Foo`, the derive will incorrectly compare the inner fields. I see a few solutions

1. Do nothing. This is technically intended behavior, but I think we should do our best to prevent footguns.
2. Generate impls of `PartialEq` and `Eq` along with the `#[derive(Label)]` macros. This is a breaking change as it requires all users to remove these derives from their types.
3. Only allow `PhantomData` to be used with `ignore_fields` -- seems needlessly prescriptive.

---

## Changelog

* Added the `ignore_fields` attribute to the derive macros for `*Label` types.
* Added an example showing off different forms of the derive macro.

<!--
## Migration Guide

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

- If this PR is a breaking change (relative to the last release of Bevy), describe how a user might need to migrate their code to support these changes
- Simply adding new functionality is not a breaking change.
- Fixing behavior that was definitely a bug, rather than a questionable design choice is not a breaking change.
-->
2022-07-19 05:21:19 +00:00
Boxy
1ac8a476cf remove QF generics from all Query/State methods and types (#5170)
# Objective

remove `QF` generics from a bunch of types and methods on query related items. this has a few benefits:
- simplifies type signatures `fn iter(&self) -> QueryIter<'_, 's, Q::ReadOnly, F::ReadOnly>` is (imo) conceptually simpler than `fn iter(&self) -> QueryIter<'_, 's, Q, ROQueryFetch<'_, Q>, F>`
- `Fetch` is mostly an implementation detail but previously we had to expose it on every `iter` `get` etc method
- Allows us to potentially in the future simplify the `WorldQuery` trait hierarchy by removing the `Fetch` trait

## Solution

remove the `QF` generic and add a way to (unsafely) turn `&QueryState<Q1, F1>` into `&QueryState<Q2, F2>`

---

## Changelog/Migration Guide

The `QF` generic was removed from various `Query` iterator types and some methods, you should update your code to use the type of the corresponding worldquery of the fetch type that was being used, or call `as_readonly`/`as_nop` to convert a querystate to the appropriate type. For example:
`.get_single_unchecked_manual::<ROQueryFetch<Q>>(..)` -> `.as_readonly().get_single_unchecked_manual(..)`
`my_field: QueryIter<'w, 's, Q, ROQueryFetch<'w, Q>, F>` -> `my_field: QueryIter<'w, 's, Q::ReadOnly, F::ReadOnly>`
2022-07-19 00:45:00 +00:00
François
4affc8cd93 add a SpatialBundle with visibility and transform components (#5344)
# Objective

- Help user when they need to add both a `TransformBundle` and a `VisibilityBundle`

## Solution

- Add a `SpatialBundle` adding all components
2022-07-18 23:27:30 +00:00
Christopher Biscardi
d4f8f88bb6 Don't panic when StandardMaterial normal_map hasn't loaded yet (#5307)
# Objective

[This unwrap()](de484c1e41/crates/bevy_pbr/src/pbr_material.rs (L195)) in pbr_material.rs will be hit if a StandardMaterial normal_map image has not finished loading, resulting in an error message that is hard to debug.

## Solution

~~This PR improves the error message including a potential indication of why the unwrap() could have panic'd by using expect() instead of unwrap().~~

This PR removes the panic by only proceeding if the image is found.

---

## Changelog

Don't panic when StandardMaterial normal_map images have not finished loading.
2022-07-16 21:50:19 +00:00
KDecay
f531a94370 Remove redundant Size import (#5339)
# Objective

- Fixes  #5338 
- Allow the usage of `use bevy::ui::Size` (see migration guide in #4285)

## Solution

- Remove the `use crate::Size` import so that the `pub use geometry::*` import also publicly uses the `Size` struct.
2022-07-16 13:53:41 +00:00
Daniel McNab
25d222b73e Minimally fix the known unsoundness in bevy_mikktspace (#5299)
# Objective

- 0.8 is coming soon, and our mikktspace implementation is unsound - see https://github.com/gltf-rs/mikktspace/issues/26
- Best not to ship that

## Solution

- Fix the unsoundness in a minimal way
- Obviously there might be others, but it seems unlikely we have any way to know about those
2022-07-16 08:37:18 +00:00
Rob Parrett
a63d761aa3 Add VisibilityBundle and use it to fix gltfs, scenes, and examples (#5335)
# Objective

Gltfs, and a few examples were broken by #5310. Fix em.

Closes #5334

## Solution

Add `VisibilityBundle` as described here: https://github.com/bevyengine/bevy/issues/5334#issuecomment-1186050778 and sprinkle it around where needed.
2022-07-16 02:47:23 +00:00
Dusty DeWeese
9f8bdeeeb9 Use Affine3A for GlobalTransform to allow any affine transformation (#4379)
# Objective

- Add capability to use `Affine3A`s for some `GlobalTransform`s. This allows affine transformations that are not possible using a single `Transform` such as shear and non-uniform scaling along an arbitrary axis.
- Related to #1755 and #2026

## Solution

- `GlobalTransform` becomes an enum wrapping either a `Transform` or an `Affine3A`.
- The API of `GlobalTransform` is minimized to avoid inefficiency, and to make it clear that operations should be performed using the underlying data types.
- using `GlobalTransform::Affine3A` disables transform propagation, because the main use is for cases that `Transform`s cannot support.

---

## Changelog

- `GlobalTransform`s can optionally support any affine transformation using an `Affine3A`.


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-07-16 00:51:12 +00:00
Johan Klokkhammer Helsing
8810a73e87 Support AsBindGroup for 2d materials as well (#5312)
Port changes made to Material in #5053 to Material2d as well.

This is more or less an exact copy of the implementation in bevy_pbr; I
simply pretended the API existed, then copied stuff over until it
started building and the shapes example was working again.

# Objective

The changes in #5053 makes it possible to add custom materials with a lot less boiler plate. However, the implementation isn't shared with Material 2d as it's a kind of fork of the bevy_pbr version. It should be possible to use AsBindGroup on the 2d version as well.

## Solution

This makes the same kind of changes in Material2d in bevy_sprite.

This makes the following work:

```rust
//! Draws a circular purple bevy in the middle of the screen using a custom shader

use bevy::{
    prelude::*,
    reflect::TypeUuid,
    render::render_resource::{AsBindGroup, ShaderRef},
    sprite::{Material2d, Material2dPlugin, MaterialMesh2dBundle},
};

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_plugin(Material2dPlugin::<CustomMaterial>::default())
        .add_startup_system(setup)
        .run();
}

/// set up a simple 2D scene
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<CustomMaterial>>,
    asset_server: Res<AssetServer>,
) {
    commands.spawn_bundle(MaterialMesh2dBundle {
        mesh: meshes.add(shape::Circle::new(50.).into()).into(),
        material: materials.add(CustomMaterial {
            color: Color::PURPLE,
            color_texture: Some(asset_server.load("branding/icon.png")),
        }),
        transform: Transform::from_translation(Vec3::new(-100., 0., 0.)),
        ..default()
    });

    commands.spawn_bundle(Camera2dBundle::default());
}

/// The Material2d trait is very configurable, but comes with sensible defaults for all methods.
/// You only need to implement functions for features that need non-default behavior. See the Material api docs for details!
impl Material2d for CustomMaterial {
    fn fragment_shader() -> ShaderRef {
        "shaders/custom_material.wgsl".into()
    }
}

// This is the struct that will be passed to your shader
#[derive(AsBindGroup, TypeUuid, Debug, Clone)]
#[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"]
pub struct CustomMaterial {
    #[uniform(0)]
    color: Color,
    #[texture(1)]
    #[sampler(2)]
    color_texture: Option<Handle<Image>>,
}
```
2022-07-16 00:20:04 +00:00
Carter Anderson
40d4992401 Visibilty Inheritance, universal ComputedVisibility and RenderLayers support (#5310)
# Objective

Fixes #4907. Fixes #838. Fixes #5089.
Supersedes #5146. Supersedes #2087. Supersedes #865. Supersedes #5114

Visibility is currently entirely local. Set a parent entity to be invisible, and the children are still visible. This makes it hard for users to hide entire hierarchies of entities.

Additionally, the semantics of `Visibility` vs `ComputedVisibility` are inconsistent across entity types. 3D meshes use `ComputedVisibility` as the "definitive" visibility component, with `Visibility` being just one data source. Sprites just use `Visibility`, which means they can't feed off of `ComputedVisibility` data, such as culling information, RenderLayers, and (added in this pr) visibility inheritance information.

## Solution

Splits `ComputedVisibilty::is_visible` into `ComputedVisibilty::is_visible_in_view` and `ComputedVisibilty::is_visible_in_hierarchy`. For each visible entity, `is_visible_in_hierarchy` is computed by propagating visibility down the hierarchy. The `ComputedVisibility::is_visible()` function combines these two booleans for the canonical "is this entity visible" function.

Additionally, all entities that have `Visibility` now also have `ComputedVisibility`.  Sprites, Lights, and UI entities now use `ComputedVisibility` when appropriate.

This means that in addition to visibility inheritance, everything using Visibility now also supports RenderLayers. Notably, Sprites (and other 2d objects) now support `RenderLayers` and work properly across multiple views.

Also note that this does increase the amount of work done per sprite. Bevymark with 100,000 sprites on `main` runs in `0.017612` seconds and this runs in `0.01902`. That is certainly a gap, but I believe the api consistency and extra functionality this buys us is worth it. See [this thread](https://github.com/bevyengine/bevy/pull/5146#issuecomment-1182783452) for more info. Note that #5146 in combination with #5114 _are_ a viable alternative to this PR and _would_ perform better, but that comes at the cost of api inconsistencies and doing visibility calculations in the "wrong" place. The current visibility system does have potential for performance improvements. I would prefer to evolve that one system as a whole rather than doing custom hacks / different behaviors for each feature slice.

Here is a "split screen" example where the left camera uses RenderLayers to filter out the blue sprite.

![image](https://user-images.githubusercontent.com/2694663/178814868-2e9a2173-bf8c-4c79-8815-633899d492c3.png)


Note that this builds directly on #5146 and that @james7132 deserves the credit for the baseline visibility inheritance work. This pr moves the inherited visibility field into `ComputedVisibility`, then does the additional work of porting everything to `ComputedVisibility`. See my [comments here](https://github.com/bevyengine/bevy/pull/5146#issuecomment-1182783452) for rationale. 

## Follow up work

* Now that lights use ComputedVisibility, VisibleEntities now includes "visible lights" in the entity list. Functionally not a problem as we use queries to filter the list down in the desired context. But we should consider splitting this out into a separate`VisibleLights` collection for both clarity and performance reasons. And _maybe_ even consider scoping `VisibleEntities` down to `VisibleMeshes`?.
* Investigate alternative sprite rendering impls (in combination with visibility system tweaks) that avoid re-generating a per-view fixedbitset of visible entities every frame, then checking each ExtractedEntity. This is where most of the performance overhead lives. Ex: we could generate ExtractedEntities per-view using the VisibleEntities list, avoiding the need for the bitset.
* Should ComputedVisibility use bitflags under the hood? This would cut down on the size of the component, potentially speed up the `is_visible()` function, and allow us to cheaply expand ComputedVisibility with more data (ex: split out local visibility and parent visibility, add more culling classes, etc).
---

## Changelog

* ComputedVisibility now takes hierarchy visibility into account.
* 2D, UI and Light entities now use the ComputedVisibility component.

## Migration Guide

If you were previously reading `Visibility::is_visible` as the "actual visibility" for sprites or lights, use `ComputedVisibilty::is_visible()` instead:

```rust
// before (0.7)
fn system(query: Query<&Visibility>) {
  for visibility in query.iter() {
    if visibility.is_visible {
       log!("found visible entity");
    }
  }
}

// after (0.8)
fn system(query: Query<&ComputedVisibility>) {
  for visibility in query.iter() {
    if visibility.is_visible() {
       log!("found visible entity");
    }
  }
}
``` 


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-07-15 23:24:42 +00:00
ira
56ee620495 Export and register Mat2. (#5324)
Export and register a missing type from `glam`.

Reflect impls were already present, but not registered.


Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-07-15 22:37:06 +00:00
François
44566dbab7 remove an unused import in release (#5320)
# Objective

- There is a warning when building in release:
```
warning: unused import: `Local`
 --> crates/bevy_render/src/extract_resource.rs:4:34
  |
4 | use bevy_ecs::system::{Commands, Local, Res, ResMut, Resource};
  |                                  ^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default
```
- It's used 814f8d1635/crates/bevy_render/src/extract_resource.rs (L45)
- Fix it

## Solution

- Gate the import
2022-07-14 23:43:57 +00:00
François
814f8d1635 update wgpu to 0.13 (#5168)
# Objective

- Update wgpu to 0.13
- ~~Wait, is wgpu 0.13 released? No, but I had most of the changes already ready since playing with webgpu~~ well it has been released now
- Also update parking_lot to 0.12 and naga to 0.9

## Solution

- Update syntax for wgsl shaders https://github.com/gfx-rs/wgpu/blob/master/CHANGELOG.md#wgsl-syntax
- Add a few options, remove some references: https://github.com/gfx-rs/wgpu/blob/master/CHANGELOG.md#other-breaking-changes
- fragment inputs should now exactly match vertex outputs for locations, so I added exports for those to be able to reuse them https://github.com/gfx-rs/wgpu/pull/2704
2022-07-14 21:17:16 +00:00
JoJoJet
c43295af80 Simplify design for *Labels (#4957)
# Objective

- Closes #4954 
- Reduce the complexity of the `{System, App, *}Label` APIs.

## Solution

For the sake of brevity I will only refer to `SystemLabel`, but everything applies to all of the other label types as well.

- Add `SystemLabelId`, a lightweight, `copy` struct.
- Convert custom types into `SystemLabelId` using the trait `SystemLabel`.

## Changelog

- String literals implement `SystemLabel` for now, but this should be changed with #4409 .

## Migration Guide

- Any previous use of `Box<dyn SystemLabel>` should be replaced with `SystemLabelId`.
- `AsSystemLabel` trait has been modified.
    - No more output generics.
    - Method `as_system_label` now returns `SystemLabelId`, removing an unnecessary level of indirection.
- If you *need* a label that is determined at runtime, you can use `Box::leak`. Not recommended.

## Questions for later

* Should we generate a `Debug` impl along with `#[derive(*Label)]`?
* Should we rename `as_str()`?
* Should we remove the extra derives (such as `Hash`) from builtin `*Label` types?
* Should we automatically derive types like `Clone, Copy, PartialEq, Eq`?
* More-ergonomic comparisons between `Label` and `LabelId`.
* Move `Dyn{Eq, Hash,Clone}` somewhere else.
* Some API to make interning dynamic labels easier.
* Optimize string representation
    * Empty string for unit structs -- no debug info but faster comparisons
    * Don't show enum types -- same tradeoffs as asbove.
2022-07-14 18:23:01 +00:00
ira
234e5af882 Implement From<bool> for ShouldRun. (#5306)
Make writing simple yes/no run criteria easier.


Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-07-14 17:26:40 +00:00
Ben Reeves
847f47d8d4 Remove rand crate from dependency tree (#3992)
This replaces `rand` with `fastrand` as the source of randomness for `HandleId::new()` in `bevy_asset`. This was the only crate with a dependency on `rand`, and now the dependency exists only as a dev-dependency.

`fastrand` was already in the dependency tree, thanks to `futures-lite`, `async-executor`, and `tempfile` to name a few.

## Changelog

Removed `rand` from dependencies in `bevy_asset` in favor of existing in-tree `fast-rand`
2022-07-14 17:00:01 +00:00
Daniel Liu
fe59fe5860 Add assert_is_exclusive_system function (#5275)
Add compile time check for if a system is an exclusive system. Resolves #4788 

Co-authored-by: Daniel Liu <mr.picklepinosaur@gmail.com>
Co-authored-by: Daniel Liu <danieliu3120@gmail.com>
2022-07-14 01:12:15 +00:00
Nicola Papale
6c06fc5b7c Add ExactSizeIterator implementation for QueryCombinatonIter (#5148)
Following https://github.com/bevyengine/bevy/pull/5124 I decided to add the `ExactSizeIterator` impl for `QueryCombinationIter`.

Also:
- Clean up the tests for `size_hint` and `len` for both the normal `QueryIter` and `QueryCombinationIter`.
- Add tests to `QueryCombinationIter` when it shouldn't be `ExactSizeIterator`

---

## Changelog

- Added `ExactSizeIterator` implementation for `QueryCombinatonIter`
2022-07-13 16:08:48 +00:00
harudagondi
1dbb1f7b20 Allow iter combinations on custom world queries (#5286)
# Objective

- `.iter_combinations_*()` cannot be used on custom derived `WorldQuery`, so this fixes that
- Fixes #5284

## Solution

- `#[derive(Clone)]` on the `Fetch` of the proc macro derive.
- `#[derive(Clone)]` for `AnyOf` to satisfy tests.
2022-07-13 15:37:27 +00:00
ira
56d69c1427 Fix incorrect rotation in Transform::rotate_around. (#5300)
Someone noted that the `rotate_around` method did not give the results they expected: [discord thread](https://discord.com/channels/691052431525675048/996497295325544479)
I tested `rotate_around` and their workaround and it seems like it was indeed incorrect.

Here is a scene with some cubes at different angles all being rotated around the center on the Y axis.

https://user-images.githubusercontent.com/29694403/178598432-407d7e80-1caf-4b17-b69b-66d9156c81e1.mp4

Interestingly, the middle cube rotates as you might expect. This threw me for a bit of a loop before I added the other cubes to the test haha.

Here is the same scene with the order multiplication of the quaternions flipped in `rotate_around`.

https://user-images.githubusercontent.com/29694403/178598446-a98026f3-524c-448b-8437-4d0d3175c6ca.mp4

That looks better :)

## Changelog

* Fixed `rotate_around` rotating the wrong way around
* Added `translate_around`. - Split out the translation code from `rotate_around`.
* Simplified/optimized `rotate_local_*` methods. - Yep, That works somehow.

<sup>Quaternions sure are wacky. Do not ask me how this works exactly, haha.</sup>

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-07-13 15:10:43 +00:00
Alice Cecile
2f9a886c55 Implement Debug for Gamepads (#5291)
Generally a good idea.

I ran into this because I wanted to store `Gamepads` in a wrapper struct in https://github.com/Leafwing-Studios/leafwing-input-manager/pull/168. 

This PR allows the `Debug` derive used there to continue working. I could workaround this with a custom impl, but a PR upstream seemed like the right fix.
2022-07-13 15:10:41 +00:00
JoJoJet
bb9706c96f Document exotic patterns for Commands and Events (#4840)
# Objective

Improve documentation, information users of the limitations in bevy's idiomatic patterns, and suggesting alternatives for when those limitations are encountered.

## Solution

* Add documentation to `Commands` informing the user of the option of writing one-shot commands with closures.
* Add documentation to `EventWriter` regarding the limitations of event types, and suggesting alternatives using commands.
2022-07-13 14:40:52 +00:00
Francesco Giordana
052de08e56 Enable loading textures of unlimited size (#5305)
# Objective

Fixes #5304 

## Solution

Instead of using a simple utility function for loading, which uses a default allocation limit of 512MB, we use a Reader object which can be configured ad hoc.

## Changelog

> This section is optional. If this was a trivial fix, or has no externally-visible impact, you can delete this section.

- Allows loading of textures larger than 512MB
2022-07-13 11:31:18 +00:00
Charles
de484c1e41 fix extract_wireframes (#5301)
# Objective

- Wireframes are currently not rendering on main because they aren't being extracted correctly

## Solution

- Extract the wireframes correctly
2022-07-13 04:53:50 +00:00
Nicola Papale
df7736c572 Alias world_to_viewport for easier migration (#5298)
# Objective

When someone searches in rustdoc for `world_to_screen`, they now will
find `world_to_viewport`. The method was renamed in 0.8, it would be
nice to allow users to find the new name more easily.

---
2022-07-12 18:57:19 +00:00
Mark Nokalt
f9c1a8a3d5 docs: Full documentation for bevy_asset (#3536)
# Objective

This PR aims to document the `bevy_asset` crate to complete coverage, while also trying to improve some bits of UX.

### Progress

- [x] Root items
- [x] `handle` module
- [x] `info` module
- [x] `path` module
- [x] `loader` module
- [x] `io` and `filesystem_watcher` module
- [x] `assets` module
- [x] `asset_server` module
- [x] `diagnostic` module
- [x] `debug_asset_server` module
- [x] Crate level documentation
- [x] Add `#![warn(missing_docs)]` lint

Coverage: 100%

## Migration Guide

- Rename `FileAssetIo::get_root_path` uses to `FileAssetIo::get_base_path`

    `FileAssetIo::root_path()` is a getter for the `root_path` field, while `FileAssetIo::get_root_path` returned the parent directory of the asset root path, which was the executable's directory unless `CARGO_MANIFEST_DIR` was set. This change solves the ambiguity between the two methods.
2022-07-12 15:44:09 +00:00
CGMossa
93a131661d Very minor doc formatting changes (#5287)
# Objective

- Added a bunch of backticks to things that should have them, like equations, abstract variable names,
- Changed all small x, y, and z to capitals X, Y, Z.

This might be more annoying than helpful; Feel free to refuse this PR.
2022-07-12 13:06:16 +00:00
Mike
a1d3f1b3b4 Update time by sending frame instant through a channel (#4744)
# Objective

- The time update is currently done in the wrong part of the schedule. For a single frame the current order of things is update input, update time (First stage), other stages, render stage (frame presentation). So when we update the time it includes the input processing of the current frame and the frame presentation of the previous frame. This is a problem when vsync is on. When input processing takes a longer amount of time for a frame, the vsync wait time gets shorter. So when these are not paired correctly we can potentially have a long input processing time added to the normal vsync wait time in the previous frame. This leads to inaccurate frame time reporting and more variance of the time than actually exists. For more details of why this is an issue see the linked issue below.
- Helps with https://github.com/bevyengine/bevy/issues/4669
- Supercedes https://github.com/bevyengine/bevy/pull/4728 and https://github.com/bevyengine/bevy/pull/4735. This PR should be less controversial than those because it doesn't add to the API surface.

## Solution

- The most accurate frame time would come from hardware. We currently don't have access to that for multiple reasons, so the next best thing we can do is measure the frame time as close to frame presentation as possible. This PR gets the Instant::now() for the time immediately after frame presentation in the render system and then sends that time to the app world through a channel.
- implements suggestion from @aevyrie from here https://github.com/bevyengine/bevy/pull/4728#discussion_r872010606

## Statistics

![image](https://user-images.githubusercontent.com/2180432/168410265-f249f66e-ea9d-45d1-b3d8-7207a7bc536c.png)


---

## Changelog

- Make frame time reporting more accurate.

## Migration Guide

`time.delta()` now reports zero for 2 frames on startup instead of 1 frame.
2022-07-11 23:19:00 +00:00
ira
4847f7e3ad Update codebase to use IntoIterator where possible. (#5269)
Remove unnecessary calls to `iter()`/`iter_mut()`.
Mainly updates the use of queries in our code, docs, and examples.

```rust
// From
for _ in list.iter() {
for _ in list.iter_mut() {

// To
for _ in &list {
for _ in &mut list {
```

We already enable the pedantic lint [clippy::explicit_iter_loop](https://rust-lang.github.io/rust-clippy/stable/) inside of Bevy. However, this only warns for a few known types from the standard library.

## Note for reviewers
As you can see the additions and deletions are exactly equal.
Maybe give it a quick skim to check I didn't sneak in a crypto miner, but you don't have to torture yourself by reading every line.
I already experienced enough pain making this PR :) 


Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-07-11 15:28:50 +00:00
Daniel Liu
3203a8585c Change window position types from tuple to vec (#5276)
Resolves #5004. As suggested in the original issue, change tuple types to their corresponding vector type.

## migration guide

Changed the following fields
- `WindowCommand::SetWindowMode.resolution` from `(u32, u32)` to `UVec2`
- `WindowCommand::SetResolution.logical_resolution` from `(f32, f32)` to `Vec2`

Co-authored-by: Daniel Liu <mr.picklepinosaur@gmail.com>
2022-07-11 14:36:23 +00:00
Charles
6c2f78f449 Validate vertex attribute format on insert (#5259)
# Objective

- Validate the format of the values with the expected attribute format.
- Currently, if you pass the wrong format, it will crash somewhere unrelated with a very cryptic error message, so it's really hard to debug for beginners.

## Solution

- Compare the format and panic when unexpected format is passed

## Note

- I used a separate `error!()` for a human friendly message because the panic message is very noisy and hard to parse for beginners. I don't mind changing this to only a panic if people prefer that.
- This could potentially be something that runs only in debug mode, but I don't think inserting attributes is done often enough for this to be an issue.


Co-authored-by: Charles <IceSentry@users.noreply.github.com>
2022-07-11 14:11:31 +00:00
Kornel
fda1fee1bb Use collect to build mesh attributes (#5255)
Small optimization. `.collect()` from arrays generates very nice code without reallocations: https://rust.godbolt.org/z/6E6c595bq

Co-authored-by: Kornel <kornel@geekhood.net>
2022-07-11 14:11:30 +00:00
Kurt Kühnert
8ea4a3decf TextureFormat::R16Unorm support for Image (#5249)
# Objective

Currently some TextureFormats are not supported by the Image type.
The `TextureFormat::R16Unorm` format is useful for storing heightmaps.
This small change would unblock releasing my terrain plugin on bevy 0.8.
 
## Solution

Added `TextureFormat::R16Unorm` support to Image.
This is an alternative (short term solution) to the large texture format issue https://github.com/bevyengine/bevy/pull/4124.
2022-07-11 14:11:29 +00:00
Zicklag
81bb4ef300 Document That FloatOrd Implements Hash and Eq Too (#5228)
# Objective

- Slight documentation tweak to make it more clear that `FloatOrd` also implements `Hash` and `Eq`, not just `Ord`.
- I know that it does show that Hash is implemented in the docs, but I had missed it after reading the description and assuming it didn't do it, so hopefully this helps other people who might miss it like I did. :)

## Solution

- Just mention in the Hash and Eq implementation in the docstring.
2022-07-11 14:11:27 +00:00
fadhliazhari
9b6253b769 Added multi windows check for bevy_ui Interaction. (#5225)
# Objective

- Currently bevy_ui only checks for primary window cursor position to determine `Interaction` behavior.
- Added checks for focused window where cursor position is available.
- Fixes #5224.

## Solution

- Added checks for focused windows in `Interaction` focus system.

## Follow Up

- All windows with camera will be rendering the UI elements right now.
- We will need some way to tell which camera to render which UI.

---

Co-authored-by: fadhliazhari <44402264+fadhliazhari@users.noreply.github.com>
2022-07-11 14:11:26 +00:00
Zicklag
1fccb99d3a Improve Gamepad DPad Button Detection (#5220)
# Objective

- Enable the `axis_dpad_to_button` gilrs filter to map hats to dpad buttons on supported remotes.
- Fixes https://github.com/Leafwing-Studios/leafwing-input-manager/issues/149
- Might have fixed the confusion related to https://github.com/bevyengine/bevy/issues/3229

## Solution

- Enables the `axis_dpad_to_button` filter in `gilrs` which will use it's remote mapping information to see if there are hats mapped to dpads for that remote model. I don't really understand the logic it uses exactly, but it is usually enabled by default in gilrs and I believe it probably leads to more intuitive mapping compared to the current situation of dpad buttons being mapped to an axis.
- Removes the `GamepadAxisType::DPadX` and `GamepadAxisType::DPadY` enum variants to avoid user confusion. Those variants should never be emitted anyway, for all supported remotes.

---

## Changelog

### Changed

- Removed `GamepadAxisType::DPadX` and `GamepadAxisType::DPadY` in favor of using `GamepadButtonType::DPad[Up/Down/Left/Right]` instead.

## Migration Guide

If your game reads gamepad events or queries the axis state of `GamePadAxisType::DPadX` or `GamePadAxisType::DPadY`, then you must migrate your code to check whether or not the `GamepadButtonType::DPadUp`, `GamepadButtonType::DPadDown`, etc. buttons were pressed instead.
2022-07-11 14:11:25 +00:00
Hennadii Chernyshchyk
1da6720132 Add apply_or_insert functions to reflected component and resources (#5201)
# Objective

`ReflectResource` and `ReflectComponent` will panic on `apply` method if there is no such component. It's not very ergonomic. And not very good for performance since I need to check if such component exists first.

## Solution

* Add `ReflectComponent::apply_or_insert` and `ReflectResource::apply_or_insert` functions.
* Rename `ReflectComponent::add` into `ReflectComponent::insert` for consistency.

---

## Changelog

### Added

* `ReflectResource::apply_or_insert` and `ReflectComponent::apply_on_insert`.

### Changed

* Rename `ReflectComponent::add` into `ReflectComponent::insert` for consistency.
* Use `ReflectComponent::apply_on_insert` in `DynamicScene` instead of manual checking.

## Migration Guide

* Rename `ReflectComponent::add` into `ReflectComponent::insert`.
2022-07-11 14:11:24 +00:00
Daniel McNab
8de03b0839 Extract resources into their target location (#5271)
# Objective

- Extracting resources currently always uses commands, which requires *at least* one additional move of the extracted value, as well as dynamic dispatch.
- Addresses https://github.com/bevyengine/bevy/pull/4402#discussion_r911634931

## Solution

- Write the resource into a `ResMut<R>` directly.
- Fall-back to commands if the resource hasn't been added yet.
2022-07-10 21:04:35 +00:00
James Liu
8eb0440f1e Hierarchy commandization (#4197)
## Objective
Implement absolute minimum viable product for the changes proposed in bevyengine/rfcs#53.

## Solution

 - Remove public mutative access to `Parent` (Children is already publicly read-only). This includes public construction methods like `Copy`, `Clone`, and `Default`.
 - Remove `PreviousParent`
 - Remove `parent_update_system`
 - Update all hierarchy related commands to immediately update both `Parent` and `Children` references.

## Remaining TODOs

 - [ ] Update documentation for both `Parent` and `Children`. Discourage using `EntityCommands::remove`
 - [x] Add `HierarchyEvent` to notify listeners of hierarchy updates. This is meant to replace listening on `PreviousParent`

## Followup

 - These changes should be best moved to the hooks mentioned in #3742.
 - Backing storage for both might be best moved to indexes mentioned in the same relations.
2022-07-10 20:29:06 +00:00
Daniel McNab
7b2cf98896 Make RenderStage::Extract run on the render world (#4402)
# Objective

- Currently, the `Extract` `RenderStage` is executed on the main world, with the render world available as a resource.
- However, when needing access to resources in the render world (e.g. to mutate them), the only way to do so was to get exclusive access to the whole `RenderWorld` resource.
- This meant that effectively only one extract which wrote to resources could run at a time.
- We didn't previously make `Extract`ing writing to the world a non-happy path, even though we want to discourage that.

## Solution

- Move the extract stage to run on the render world.
- Add the main world as a `MainWorld` resource.
- Add an `Extract` `SystemParam` as a convenience to access a (read only) `SystemParam` in the main world during `Extract`.

## Future work

It should be possible to avoid needing to use `get_or_spawn` for the render commands, since now the `Commands`' `Entities` matches up with the world being executed on.
We need to determine how this interacts with https://github.com/bevyengine/bevy/pull/3519
It's theoretically possible to remove the need for the `value` method on `Extract`. However, that requires slightly changing the `SystemParam` interface, which would make it more complicated. That would probably mess up the `SystemState` api too.

## Todo
I still need to add doc comments to `Extract`.

---

## Changelog

### Changed
- The `Extract` `RenderStage` now runs on the render world (instead of the main world as before).
   You must use the `Extract` `SystemParam` to access the main world during the extract phase.
   Resources on the render world can now be accessed using `ResMut` during extract.

### Removed
- `Commands::spawn_and_forget`. Use `Commands::get_or_spawn(e).insert_bundle(bundle)` instead

## Migration Guide

The `Extract` `RenderStage` now runs on the render world (instead of the main world as before).
You must use the `Extract` `SystemParam` to access the main world during the extract phase. `Extract` takes a single type parameter, which is any system parameter (such as `Res`, `Query` etc.). It will extract this from the main world, and returns the result of this extraction when `value` is called on it.

For example, if previously your extract system looked like:
```rust
fn extract_clouds(mut commands: Commands, clouds: Query<Entity, With<Cloud>>) {
    for cloud in clouds.iter() {
        commands.get_or_spawn(cloud).insert(Cloud);
    }
}
```
the new version would be:
```rust
fn extract_clouds(mut commands: Commands, mut clouds: Extract<Query<Entity, With<Cloud>>>) {
    for cloud in clouds.value().iter() {
        commands.get_or_spawn(cloud).insert(Cloud);
    }
}
```
The diff is:
```diff
--- a/src/clouds.rs
+++ b/src/clouds.rs
@@ -1,5 +1,5 @@
-fn extract_clouds(mut commands: Commands, clouds: Query<Entity, With<Cloud>>) {
-    for cloud in clouds.iter() {
+fn extract_clouds(mut commands: Commands, mut clouds: Extract<Query<Entity, With<Cloud>>>) {
+    for cloud in clouds.value().iter() {
         commands.get_or_spawn(cloud).insert(Cloud);
     }
 }
```
You can now also access resources from the render world using the normal system parameters during `Extract`:
```rust
fn extract_assets(mut render_assets: ResMut<MyAssets>, source_assets: Extract<Res<MyAssets>>) {
     *render_assets = source_assets.clone();
}
```
Please note that all existing extract systems need to be updated to match this new style; even if they currently compile they will not run as expected. A warning will be emitted on a best-effort basis if this is not met.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-07-08 23:56:33 +00:00
Robin KAY
e6faf993b0 Add support for removing attributes from meshes. (#5254)
# Objective

Support removing attributes from meshes. For an example use case, meshes created using the bevy::predule::shape types or loaded from external files may have attributes that are not needed for the materials they will be rendered with.

This was extracted from PR #5222.

## Solution

Implement Mesh::remove_attribute().
2022-07-08 21:18:32 +00:00
Robin KAY
3c51ad2764 Allow rendering meshes without UV coordinate data. (#5222)
# Objective

Bevy requires meshes to include UV coordinates, even if the material does not use any textures, and will fail with an error `ERROR bevy_pbr::material: Mesh is missing requested attribute: Vertex_Uv (MeshVertexAttributeId(2), pipeline type: Some("bevy_pbr::material::MaterialPipeline<bevy_pbr::pbr_material::StandardMaterial>"))` otherwise. The objective of this PR is to permit this.

## Solution

This PR follows the design of #4528, which added support for per-vertex colours. It adds a shader define called VERTEX_UVS which indicates the presence of UV coordinates to the shader.
2022-07-08 20:55:08 +00:00
robtfm
132950cd55 Spotlights (#4715)
# Objective

add spotlight support

## Solution / Changelog

- add spotlight angles (inner, outer) to ``PointLight`` struct. emitted light is linearly attenuated from 100% to 0% as angle tends from inner to outer. Direction is taken from the existing transform rotation.
- add spotlight direction (vec3) and angles (f32,f32) to ``GpuPointLight`` struct (60 bytes -> 80 bytes) in ``pbr/render/lights.rs`` and ``mesh_view_bind_group.wgsl``
- reduce no-buffer-support max point light count to 204 due to above
- use spotlight data to attenuate light in ``pbr.wgsl``
- do additional cluster culling on spotlights to minimise cost in ``assign_lights_to_clusters``
- changed one of the lights in the lighting demo to a spotlight
- also added a ``spotlight`` demo - probably not justified but so reviewers can see it more easily

## notes

increasing the size of the GpuPointLight struct on my machine reduces the FPS of ``many_lights -- sphere`` from ~150fps to 140fps. 

i thought this was a reasonable tradeoff, and felt better than handling spotlights separately which is possible but would mean introducing a new bind group, refactoring light-assignment code and adding new spotlight-specific code in pbr.wgsl. the FPS impact for smaller numbers of lights should be very small.

the cluster culling strategy reintroduces the cluster aabb code which was recently removed... sorry. the aabb is used to get a cluster bounding sphere, which can then be tested fairly efficiently using the strategy described at the end of https://bartwronski.com/2017/04/13/cull-that-cone/. this works well with roughly cubic clusters (where the cluster z size is close to the same as x/y size), less well for other cases like single Z slice / tiled forward rendering. In the worst case we will end up just keeping the culling of the equivalent point light.

Co-authored-by: François <mockersf@gmail.com>
2022-07-08 19:57:43 +00:00
Hennadii Chernyshchyk
17e87f116f Improve EntityMap API (#5231)
# Objective

`EntityMap` lacks documentation, don't have `len()` / `is_empty` and `insert` doesn't work as in the regular HashMap`.

## Solution

* Add `len()` method.
* Return previously mapped entity from `insert()` as in the regular `HashMap`.
* Add documentation.

---

## Changelog

* Add `EntityMap::len()`.
* Return previously mapped entity from `EntityMap::insert()` as in the regular `HashMap`.
* Add documentation for `EntityMap` methods.
2022-07-08 01:14:24 +00:00
Tethys Svensson
11c4514023 Move the configuration of the WindowPlugin to a resource (#5227)
# Objective

It is currently hard to configure the `WindowPlugin`, as it is added as part of the `DefaultPlugins`. Ideally this should not be difficult.

## Solution

Remove the configuration from the plugin itself and put it as a `Resource`, similar to how it is done for almost all other plugins.

## Migration Guide

If you are currently configuring the behavior of the `WindowPlugin`, by constructing it manually, then you will need to instead create add the `WindowSettings` as a resource.
2022-07-08 01:14:23 +00:00
Nicola Papale
4ee73ed904 Rename CameraUi (#5234)
# Objective

In bevy 0.7, `CameraUi` was a component specifically added to cameras
that display the UI. Since camera-driven rendering was merged, it
actually does the opposite! This will make it difficult for current
users to adapt to 0.8.

## Solution

To avoid unnecessary confusion, we rename `CameraUi` into
`UiCameraConfig`.

---

## Changelog

- Rename `CameraUi` to `UiCameraConfig`
2022-07-08 00:59:39 +00:00
Obdzen
cf200f09dd Fix typo in Word::get_by_id docs (#5246)
I believe this should read `immutable` not `mutable`



Co-authored-by: Obdzen <108854527+Obdzen@users.noreply.github.com>
2022-07-07 15:25:17 +00:00
Oliver Pauffley
bf1ca81779 remove component and resource suffixes from reflect structs (#5219)
# Objective

Remove suffixes from reflect component and resource methods to closer match bevy norms.

## Solution

removed suffixes and also fixed a spelling error

---
2022-07-06 02:59:51 +00:00
François
f73987ae84 add a more helpful error to help debug panicking command on despawned entity (#5198)
# Objective

- Help users fix issue when their app panic when executing a command on a despawned entity

## Solution

- Add an error code and a page describing how to debug the issue
2022-07-05 18:44:54 +00:00
Afonso Lage
40982cd0a2 Make reflect_partial_eq return more accurate results (#5210)
# Objective

Closes #5204

## Solution

- Followed @nicopap suggestion on https://github.com/bevyengine/bevy/pull/4761#discussion_r903982224

## Changelog

- [x] Updated [struct_trait](dfe9690052/crates/bevy_reflect/src/struct_trait.rs (L455-L457)), [tuple_struct](dfe9690052/crates/bevy_reflect/src/tuple_struct.rs (L366-L368)), [tuple](dfe9690052/crates/bevy_reflect/src/tuple.rs (L386)), [array](dfe9690052/crates/bevy_reflect/src/array.rs (L335-L337)), [list](dfe9690052/crates/bevy_reflect/src/list.rs (L309-L311)) and [map](dfe9690052/crates/bevy_reflect/src/map.rs (L361-L363)) to return `None` when comparison couldn't be performed.
- [x] Updated docs comments to reflect above changes.
2022-07-05 17:41:54 +00:00
Thierry Berger
faa40bfc82 Fix markdownlint privileges complaint (#5216)
# Objective

Fixes an annoying error message in CI.

more info at https://github.com/github/super-linter/pull/2464

![image](https://user-images.githubusercontent.com/2290685/177364755-fe607c9c-615e-477c-8e91-d35aae07ab0b.png)
2022-07-05 15:49:11 +00:00
Tethys Svensson
aa0cd7c7dc Make the fields of the Material2dKey public (#5212)
# Objective

Make it easier to create pipelines derived from the `Material2dPipeline`. Currently this is made difficult because the fields of `Material2dKey` are private.

## Solution

Make the fields public.
2022-07-05 14:02:00 +00:00
Maksymilian Mozolewski
61e5bfb2ed implement reflection for more glam types (#5194)
# Objective

- To implement `Reflect` for more glam types.  

## Solution

insert `impl_reflect_struct` invocations for more glam types. I am not sure about the boolean vectors, since none of them implement `Serde::Serialize/Deserialize`, and the SIMD versions don't have public fields. 
I do still think implementing reflection is useful for BVec's since then they can be incorporated into `Reflect`'ed components and set dynamically even if as a whole + it's more consistent.

## Changelog
Implemented `Reflect` for the following types
 - BVec2
 - BVec3
 - **BVec3A** (on simd supported platforms only)
 - BVec4
 - **BVec4A** (on simd supported platforms only)
 - Mat2
 - Mat3A
 - DMat2
 - Affine2
 - Affine3A
 - DAffine2
 - DAffine3
 - EulerRot
2022-07-05 13:38:47 +00:00
Robin KAY
5b5013d540 Add ViewRangefinder3d to reduce boilerplate when enqueuing standard 3D PhaseItems. (#5014)
# Objective

Reduce the boilerplate code needed to make draw order sorting work correctly when queuing items through new common functionality. Also fix several instances in the bevy code-base (mostly examples) where this boilerplate appears to be incorrect.

## Solution

- Moved the logic for handling back-to-front vs front-to-back draw ordering into the PhaseItems by inverting the sort key ordering of Opaque3d and AlphaMask3d. The means that all the standard 3d rendering phases measure distance in the same way. Clients of these structs no longer need to know to negate the distance.
- Added a new utility struct, ViewRangefinder3d, which encapsulates the maths needed to calculate a "distance" from an ExtractedView and a mesh's transform matrix.
- Converted all the occurrences of the distance calculations in Bevy and its examples to use ViewRangefinder3d. Several of these occurrences appear to be buggy because they don't invert the view matrix or don't negate the distance where appropriate. This leads me to the view that Bevy should expose a facility to correctly perform this calculation.

## Migration Guide

Code which creates Opaque3d, AlphaMask3d, or Transparent3d phase items _should_ use ViewRangefinder3d to calculate the distance value.

Code which manually calculated the distance for Opaque3d or AlphaMask3d phase items and correctly negated the z value will no longer depth sort correctly. However, incorrect depth sorting for these types will not impact the rendered output as sorting is only a performance optimisation when drawing with depth-testing enabled. Code which manually calculated the distance for Transparent3d phase items will continue to work as before.
2022-07-05 06:13:39 +00:00
Alice Cecile
2c9bc0b31f Remove dead SystemLabelMarker struct (#5190)
This struct had no internal use, docs, or intuitable external use.

It has been removed.
2022-07-04 15:12:35 +00:00
Jakob Hellermann
d38a8dfdd7 add more SAFETY comments and lint for missing ones in bevy_ecs (#4835)
# Objective

`SAFETY` comments are meant to be placed before `unsafe` blocks and should contain the reasoning of why in this case the usage of unsafe is okay. This is useful when reading the code because it makes it clear which assumptions are required for safety, and makes it easier to spot possible unsoundness holes. It also forces the code writer to think of something to write and maybe look at the safety contracts of any called unsafe methods again to double-check their correct usage.

There's a clippy lint called `undocumented_unsafe_blocks` which warns when using a block without such a comment. 

## Solution

- since clippy expects `SAFETY` instead of `SAFE`, rename those
- add `SAFETY` comments in more places
- for the last remaining 3 places, add an `#[allow()]` and `// TODO` since I wasn't comfortable enough with the code to justify their safety
- add ` #![warn(clippy::undocumented_unsafe_blocks)]` to `bevy_ecs`


### Note for reviewers

The first commit only renames `SAFETY` to `SAFE` so it doesn't need a thorough review.
cb042a416e..55cef2d6fa is the diff for all other changes.

### Safety comments where I'm not too familiar with the code

774012ece5/crates/bevy_ecs/src/entity/mod.rs (L540-L546)

774012ece5/crates/bevy_ecs/src/world/entity_ref.rs (L249-L252)

### Locations left undocumented with a `TODO` comment

5dde944a30/crates/bevy_ecs/src/schedule/executor_parallel.rs (L196-L199)

5dde944a30/crates/bevy_ecs/src/world/entity_ref.rs (L287-L289)

5dde944a30/crates/bevy_ecs/src/world/entity_ref.rs (L413-L415)

Co-authored-by: Jakob Hellermann <hellermann@sipgate.de>
2022-07-04 14:44:24 +00:00
Jakob Hellermann
4d05eb19be bevy_reflect: remove glam from a test which is active without the glam feature (#5195)
# Objective

`glam` is an optional feature in `bevy_reflect` and there is a separate `mod test { #[cfg(feature = "glam")] mod glam { .. }}`.
The `reflect_downcast` test is not in that module and doesn't depend on glam, which breaks `cargo test -p bevy_reflect` without the `glam` feature.

## Solution

- Remove the glam types from the test, they're not relevant to it
2022-07-04 14:17:46 +00:00
Hennadii Chernyshchyk
534cad611d Add reflection for resources (#5175)
# Objective

We don't have reflection for resources.

## Solution

Introduce reflection for resources.

Continues #3580 (by @Davier), related to #3576.

---

## Changelog

### Added

* Reflection on a resource type (by adding `ReflectResource`):

```rust
#[derive(Reflect)]
#[reflect(Resource)]
struct MyResourse;
```

### Changed

* Rename `ReflectComponent::add_component` into `ReflectComponent::insert_component` for consistency.

## Migration Guide

* Rename `ReflectComponent::add_component` into `ReflectComponent::insert_component`.
2022-07-04 13:04:20 +00:00
James Liu
5498ef81fb bevy_reflect: support map insertion (#5173)
# Objective

This is a rebase of #3701 which is currently scheduled for 0.8 but is marked for adoption.

> Fixes https://github.com/bevyengine/bevy/discussions/3609

## Solution
> - add an `insert_boxed()` method on the `Map` trait
> - implement it for `HashMap` using a new `FromReflect` generic bound
> - add a `map_apply()` helper method to implement `Map::apply()`, that inserts new values instead of ignoring them


---

## Changelog
TODO

Co-authored-by: james7132 <contact@jamessliu.com>
2022-07-04 13:04:19 +00:00
Daniel McNab
e64efd399e Remove the dependency cycles (#5171)
# Objective

- I think our codebase is hit badly by rust-lang/rust-analyzer#11410
- None of our uses of cyclic dependencies are remotely necessary
- Note that these are false positives in rust-analyzer, however it's probably easier for us to work around this
- Note also that I haven't confirmed that this is causing rust-analyzer to not work very well, but it's not a bad guess.

## Solution

- Remove our cyclic dependencies
- Import the trick from #2851 for no-op plugin groups.
2022-07-04 13:04:18 +00:00
Alice Cecile
3a102e7dc2 Add Events to bevy_ecs prelude (#5159)
# Objective

This is a common and useful type. I frequently use this when working with `Events` resource directly, typically when caching the data or manipulating the `World` directly.

This is also useful when manually configuring the cleanup strategy for events.
2022-07-04 13:04:17 +00:00
Elijah
5d3fa5e77b Add inverse_projection and inverse_view_proj fields to shader view uniform (#5119)
# Objective

Transform screen-space coordinates into world space in shaders. (My use case is for generating rays for ray tracing with the same perspective as the 3d camera).

## Solution

Add `inverse_projection` and `inverse_view_proj` fields to shader view uniform

---

## Changelog

### Added
`inverse_projection` and `inverse_view_proj` fields to shader view uniform

## Note

It'd probably be good to double-check that I did the matrix multiplication in the right order for `inverse_proj_view`. Thanks!
2022-07-04 21:04:16 +08:00
LoipesMas
49da4e741d Add option to center a window (#4999)
# Objective
- Fixes #4993 

## Solution

- ~~Add `centered` property to `WindowDescriptor`~~
- Add `WindowPosition` enum
- `WindowDescriptor.position` is now `WindowPosition` instead of `Option<Vec2>`
- Add `center_window` function to `Window`

## Migration Guide
- If using `WindowDescriptor`, replace `position: None` with `position: WindowPosition::Default` and `position: Some(vec2)`  with `WindowPosition::At(vec2)`.

I'm not sure if this is the best approach, so feel free to give any feedback.
Also I'm not sure how `Option`s should be handled in `bevy_winit/src/lib.rs:161`.

Also, on window creation we can't (or at least I couldn't) get `outer_size`, so this doesn't include decorations in calculations.
2022-07-04 13:04:14 +00:00
Nicola Papale
288765930f Rework extract_meshes (#4240)
* Cleanup redundant code
* Use a type alias to make sure the `caster_query` and
  `not_caster_query` really do the same thing and access the same things

**Objective**

Cleanup code that would otherwise be difficult to understand

**Solution**

* `extract_meshes` had two for loops which are functionally identical,
  just copy-pasted code. I extracted the common code between the two
  and put them into an anonymous function.
* I flattened the tuple literal for the bundle batch, it looks much
  less nested and the code is much more readable as a result.
* The parameters of `extract_meshes` were also very daunting, but they
  turned out to be the same query repeated twice. I extracted the query
  into a type alias.

EDIT: I reworked the PR to **not do anything breaking**, and keep the old allocation behavior. Removing the memorized length was clearly a performance loss, so I kept it.
2022-07-04 12:44:23 +00:00
Robert Swain
af48c10b3e Enable wgpu profiling spans when using bevy's trace feature (#5182)
# Objective

- Enable `wgpu` profiling spans

## Solution

- `wgpu` uses the `profiling` crate to add profiling span instrumentation to their code
- `profiling` offers multiple 'backends' for profiling, including `tracing`
- When the `bevy` `trace` feature is used, add the `profiling` crate with its `profile-with-tracing` feature to enable appropriate profiling spans in `wgpu` using `tracing` which fits nicely into our infrastructure
- Bump our default `tracing` subscriber filter to `wgpu=info` from `wgpu=error` so that the profiling spans are not filtered out as they are created at the `info` level.

---

## Changelog

- Added: `tracing` profiling support for `wgpu` when using bevy's `trace` feature
- Changed: The default `tracing` filter statement for `wgpu` has been changed from the `error` level to the `info` level to not filter out the wgpu profiling spans
2022-07-04 09:14:04 +00:00
CGMossa
33f9b3940d Updated glam to 0.21. (#5142)
Removed `const_vec2`/`const_vec3`
and replaced with equivalent `.from_array`.

# Objective

Fixes #5112 

## Solution

- `encase` needs to update to `glam` as well. See teoxoy/encase#4 on progress on that. 
- `hexasphere` also needs to be updated, see OptimisticPeach/hexasphere#12.
2022-07-03 19:55:33 +00:00
Alice Cecile
8f721d8d0a Move get_short_name utility method from bevy_reflect into bevy_utils (#5174)
# Summary

This method strips a long type name like `bevy::render:📷:PerspectiveCameraBundle` down into the bare type name (`PerspectiveCameraBundle`). This is generally useful utility method, needed by #4299 and #5121.

As a result:

- This method was moved to `bevy_utils` for easier reuse.
- The legibility and robustness of this method has been significantly improved.
- Harder test cases have been added.

This change was split out of #4299 to unblock it and make merging / reviewing the rest of those changes easier.

## Changelog

- added `bevy_utils::get_short_name`, which strips the path from a type name for convenient display.
- removed the `TypeRegistry::get_short_name` method. Use the function in `bevy_utils` instead.
2022-07-02 18:30:45 +00:00
LoipesMas
de92054bbe Improve Command(s) docs (#4994)
# Objective

- Improve Command(s) docs
- Fixes #4737 

## Solution

- Update and improve documentation.

---
- "list" -> "queue" in `Commands` doc (this better represents reality)
- expand `Command` doc
- update/improve `Commands::add` doc, as specified in linked issue

Let me know if you want any changes!
2022-07-02 09:49:20 +00:00
Jerome Humbert
382cd49c3b Add documentation to VisibleEntities and related (#5100)
# Objective

Add missing docs

## Solution

Add documentation to the `VisibleEntities` component, its related
`check_visibility()` system, and that system's label.

See Discord discussion here : https://discord.com/channels/691052431525675048/866787577687310356/990432663921901678
2022-07-02 07:00:04 +00:00
Boxy
a1a07945d6 fix some memory leaks detected by miri (#4959)
The first leak:
```rust
    #[test]
    fn blob_vec_drop_empty_capacity() {
        let item_layout = Layout:🆕:<Foo>();
        let drop = drop_ptr::<Foo>;
        let _ = unsafe { BlobVec::new(item_layout, Some(drop), 0) };
    }
```
this is because we allocate the swap scratch in blobvec regardless of what the capacity is, but we only deallocate if capacity is > 0

The second leak:
```rust
    #[test]
    fn panic_while_overwriting_component() {
        let helper = DropTestHelper::new();

        let res = panic::catch_unwind(|| {
            let mut world = World::new();
            world
                .spawn()
                .insert(helper.make_component(true, 0))
                .insert(helper.make_component(false, 1));

            println!("Done inserting! Dropping world...");
        });

        let drop_log = helper.finish(res);

        assert_eq!(
            &*drop_log,
            [
                DropLogItem::Create(0),
                DropLogItem::Create(1),
                DropLogItem::Drop(0),
            ]
        );
    }
```
this is caused by us not running the drop impl on the to-be-inserted component if the drop impl of the overwritten component panics

---

managed to figure out where the leaks were by using this 10/10 command
```
cargo --quiet test --lib -- --list | sed 's/: test$//' | MIRIFLAGS="-Zmiri-disable-isolation" xargs -n1 cargo miri test --lib -- --exact
```
which runs every test one by one rather than all at once which let miri actually tell me which test had the leak 🙃
2022-07-01 21:54:28 +00:00
SarthakSingh31
cdbabb7053 Removed world cell from places where split multable access is not needed (#5167)
Fixes #5109.
2022-07-01 17:03:32 +00:00
Jakob Hellermann
49ff42cc69 fix new clippy lints (#5160)
# Objective

- Nightly clippy lints should be fixed before they get stable and break CI
  
## Solution

- fix new clippy lints
- ignore `significant_drop_in_scrutinee` since it isn't relevant in our loop https://github.com/rust-lang/rust-clippy/issues/8987
```rust
for line in io::stdin().lines() {
    ...
}
```

Co-authored-by: Jakob Hellermann <hellermann@sipgate.de>
2022-07-01 13:41:23 +00:00
ira
ea13f0bddf Add helper methods for rotating Transforms (#5151)
# Objective
Users often ask for help with rotations as they struggle with `Quat`s.
`Quat` is rather complex and has a ton of verbose methods.

## Solution
Add rotation helper methods to `Transform`.


Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-07-01 03:58:54 +00:00
Rob Parrett
5e1756954f Derive default for enums where possible (#5158)
# Objective

Fixes #5153

## Solution

Search for all enums and manually check if they have default impls that can use this new derive.

By my reckoning:

| enum | num |
|-|-|
| total | 159 |
| has default impl | 29 |
| default is unit variant | 23 |
2022-07-01 03:42:15 +00:00
Carter Anderson
747b0c69b0 Better Materials: AsBindGroup trait and derive, simpler Material trait (#5053)
# Objective

This PR reworks Bevy's Material system, making the user experience of defining Materials _much_ nicer. Bevy's previous material system leaves a lot to be desired:
* Materials require manually implementing the `RenderAsset` trait, which involves manually generating the bind group, handling gpu buffer data transfer, looking up image textures, etc. Even the simplest single-texture material involves writing ~80 unnecessary lines of code. This was never the long term plan.
* There are two material traits, which is confusing, hard to document, and often redundant: `Material` and `SpecializedMaterial`. `Material` implicitly implements `SpecializedMaterial`, and `SpecializedMaterial` is used in most high level apis to support both use cases. Most users shouldn't need to think about specialization at all (I consider it a "power-user tool"), so the fact that `SpecializedMaterial` is front-and-center in our apis is a miss.
* Implementing either material trait involves a lot of "type soup". The "prepared asset" parameter is particularly heinous: `&<Self as RenderAsset>::PreparedAsset`. Defining vertex and fragment shaders is also more verbose than it needs to be. 

## Solution

Say hello to the new `Material` system:

```rust
#[derive(AsBindGroup, TypeUuid, Debug, Clone)]
#[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"]
pub struct CoolMaterial {
    #[uniform(0)]
    color: Color,
    #[texture(1)]
    #[sampler(2)]
    color_texture: Handle<Image>,
}
impl Material for CoolMaterial {
    fn fragment_shader() -> ShaderRef {
        "cool_material.wgsl".into()
    }
}
```

Thats it! This same material would have required [~80 lines of complicated "type heavy" code](https://github.com/bevyengine/bevy/blob/v0.7.0/examples/shader/shader_material.rs) in the old Material system. Now it is just 14 lines of simple, readable code.

This is thanks to a new consolidated `Material` trait and the new `AsBindGroup` trait / derive.

### The new `Material` trait

The old "split" `Material` and `SpecializedMaterial` traits have been removed in favor of a new consolidated `Material` trait. All of the functions on the trait are optional.

The difficulty of implementing `Material` has been reduced by simplifying dataflow and removing type complexity:

```rust
// Old
impl Material for CustomMaterial {
    fn fragment_shader(asset_server: &AssetServer) -> Option<Handle<Shader>> {
        Some(asset_server.load("custom_material.wgsl"))
    }

    fn alpha_mode(render_asset: &<Self as RenderAsset>::PreparedAsset) -> AlphaMode {
        render_asset.alpha_mode
    }
}

// New
impl Material for CustomMaterial {
    fn fragment_shader() -> ShaderRef {
        "custom_material.wgsl".into()
    }

    fn alpha_mode(&self) -> AlphaMode {
        self.alpha_mode
    }
}
```

Specialization is still supported, but it is hidden by default under the `specialize()` function (more on this later).

### The `AsBindGroup` trait / derive

The `Material` trait now requires the `AsBindGroup` derive. This can be implemented manually relatively easily, but deriving it will almost always be preferable. 

Field attributes like `uniform` and `texture` are used to define which fields should be bindings,
what their binding type is, and what index they should be bound at:

```rust
#[derive(AsBindGroup)]
struct CoolMaterial {
    #[uniform(0)]
    color: Color,
    #[texture(1)]
    #[sampler(2)]
    color_texture: Handle<Image>,
}
```

In WGSL shaders, the binding looks like this:

```wgsl
struct CoolMaterial {
    color: vec4<f32>;
};

[[group(1), binding(0)]]
var<uniform> material: CoolMaterial;
[[group(1), binding(1)]]
var color_texture: texture_2d<f32>;
[[group(1), binding(2)]]
var color_sampler: sampler;
```

Note that the "group" index is determined by the usage context. It is not defined in `AsBindGroup`. Bevy material bind groups are bound to group 1.

The following field-level attributes are supported:
* `uniform(BINDING_INDEX)`
    * The field will be converted to a shader-compatible type using the `ShaderType` trait, written to a `Buffer`, and bound as a uniform. It can also be derived for custom structs.
* `texture(BINDING_INDEX)`
    * This field's `Handle<Image>` will be used to look up the matching `Texture` gpu resource, which will be bound as a texture in shaders. The field will be assumed to implement `Into<Option<Handle<Image>>>`. In practice, most fields should be a `Handle<Image>` or `Option<Handle<Image>>`. If the value of an `Option<Handle<Image>>` is `None`, the new `FallbackImage` resource will be used instead. This attribute can be used in conjunction with a `sampler` binding attribute (with a different binding index).
* `sampler(BINDING_INDEX)`
    * Behaves exactly like the `texture` attribute, but sets the Image's sampler binding instead of the texture. 

Note that fields without field-level binding attributes will be ignored.
```rust
#[derive(AsBindGroup)]
struct CoolMaterial {
    #[uniform(0)]
    color: Color,
    this_field_is_ignored: String,
}
```

As mentioned above, `Option<Handle<Image>>` is also supported:
```rust
#[derive(AsBindGroup)]
struct CoolMaterial {
    #[uniform(0)]
    color: Color,
    #[texture(1)]
    #[sampler(2)]
    color_texture: Option<Handle<Image>>,
}
```
This is useful if you want a texture to be optional. When the value is `None`, the `FallbackImage` will be used for the binding instead, which defaults to "pure white".

Field uniforms with the same binding index will be combined into a single binding:
```rust
#[derive(AsBindGroup)]
struct CoolMaterial {
    #[uniform(0)]
    color: Color,
    #[uniform(0)]
    roughness: f32,
}
```

In WGSL shaders, the binding would look like this:
```wgsl
struct CoolMaterial {
    color: vec4<f32>;
    roughness: f32;
};

[[group(1), binding(0)]]
var<uniform> material: CoolMaterial;
```

Some less common scenarios will require "struct-level" attributes. These are the currently supported struct-level attributes:
* `uniform(BINDING_INDEX, ConvertedShaderType)`
    * Similar to the field-level `uniform` attribute, but instead the entire `AsBindGroup` value is converted to `ConvertedShaderType`, which must implement `ShaderType`. This is useful if more complicated conversion logic is required.
* `bind_group_data(DataType)`
    * The `AsBindGroup` type will be converted to some `DataType` using `Into<DataType>` and stored as `AsBindGroup::Data` as part of the `AsBindGroup::as_bind_group` call. This is useful if data needs to be stored alongside the generated bind group, such as a unique identifier for a material's bind group. The most common use case for this attribute is "shader pipeline specialization".

The previous `CoolMaterial` example illustrating "combining multiple field-level uniform attributes with the same binding index" can
also be equivalently represented with a single struct-level uniform attribute:
```rust
#[derive(AsBindGroup)]
#[uniform(0, CoolMaterialUniform)]
struct CoolMaterial {
    color: Color,
    roughness: f32,
}

#[derive(ShaderType)]
struct CoolMaterialUniform {
    color: Color,
    roughness: f32,
}

impl From<&CoolMaterial> for CoolMaterialUniform {
    fn from(material: &CoolMaterial) -> CoolMaterialUniform {
        CoolMaterialUniform {
            color: material.color,
            roughness: material.roughness,
        }
    }
}
```

### Material Specialization

Material shader specialization is now _much_ simpler:

```rust
#[derive(AsBindGroup, TypeUuid, Debug, Clone)]
#[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"]
#[bind_group_data(CoolMaterialKey)]
struct CoolMaterial {
    #[uniform(0)]
    color: Color,
    is_red: bool,
}

#[derive(Copy, Clone, Hash, Eq, PartialEq)]
struct CoolMaterialKey {
    is_red: bool,
}

impl From<&CoolMaterial> for CoolMaterialKey {
    fn from(material: &CoolMaterial) -> CoolMaterialKey {
        CoolMaterialKey {
            is_red: material.is_red,
        }
    }
}

impl Material for CoolMaterial {
    fn fragment_shader() -> ShaderRef {
        "cool_material.wgsl".into()
    }

    fn specialize(
        pipeline: &MaterialPipeline<Self>,
        descriptor: &mut RenderPipelineDescriptor,
        layout: &MeshVertexBufferLayout,
        key: MaterialPipelineKey<Self>,
    ) -> Result<(), SpecializedMeshPipelineError> {
        if key.bind_group_data.is_red {
            let fragment = descriptor.fragment.as_mut().unwrap();
            fragment.shader_defs.push("IS_RED".to_string());
        }
        Ok(())
    }
}
```

Setting `bind_group_data` is not required for specialization (it defaults to `()`). Scenarios like "custom vertex attributes" also benefit from this system:
```rust
impl Material for CustomMaterial {
    fn vertex_shader() -> ShaderRef {
        "custom_material.wgsl".into()
    }

    fn fragment_shader() -> ShaderRef {
        "custom_material.wgsl".into()
    }

    fn specialize(
        pipeline: &MaterialPipeline<Self>,
        descriptor: &mut RenderPipelineDescriptor,
        layout: &MeshVertexBufferLayout,
        key: MaterialPipelineKey<Self>,
    ) -> Result<(), SpecializedMeshPipelineError> {
        let vertex_layout = layout.get_layout(&[
            Mesh::ATTRIBUTE_POSITION.at_shader_location(0),
            ATTRIBUTE_BLEND_COLOR.at_shader_location(1),
        ])?;
        descriptor.vertex.buffers = vec![vertex_layout];
        Ok(())
    }
}
```

### Ported `StandardMaterial` to the new `Material` system

Bevy's built-in PBR material uses the new Material system (including the AsBindGroup derive):

```rust
#[derive(AsBindGroup, Debug, Clone, TypeUuid)]
#[uuid = "7494888b-c082-457b-aacf-517228cc0c22"]
#[bind_group_data(StandardMaterialKey)]
#[uniform(0, StandardMaterialUniform)]
pub struct StandardMaterial {
    pub base_color: Color,
    #[texture(1)]
    #[sampler(2)]
    pub base_color_texture: Option<Handle<Image>>,
    /* other fields omitted for brevity */
```

### Ported Bevy examples to the new `Material` system

The overall complexity of Bevy's "custom shader examples" has gone down significantly. Take a look at the diffs if you want a dopamine spike.

Please note that while this PR has a net increase in "lines of code", most of those extra lines come from added documentation. There is a significant reduction
in the overall complexity of the code (even accounting for the new derive logic).

---

## Changelog

### Added

* `AsBindGroup` trait and derive, which make it much easier to transfer data to the gpu and generate bind groups for a given type.

### Changed

* The old `Material` and `SpecializedMaterial` traits have been replaced by a consolidated (much simpler) `Material` trait. Materials no longer implement `RenderAsset`.
* `StandardMaterial` was ported to the new material system. There are no user-facing api changes to the `StandardMaterial` struct api, but it now implements `AsBindGroup` and `Material` instead of `RenderAsset` and `SpecializedMaterial`.

## Migration Guide
The Material system has been reworked to be much simpler. We've removed a lot of boilerplate with the new `AsBindGroup` derive and the `Material` trait is simpler as well!

### Bevy 0.7 (old)

```rust
#[derive(Debug, Clone, TypeUuid)]
#[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"]
pub struct CustomMaterial {
    color: Color,
    color_texture: Handle<Image>,
}

#[derive(Clone)]
pub struct GpuCustomMaterial {
    _buffer: Buffer,
    bind_group: BindGroup,
}

impl RenderAsset for CustomMaterial {
    type ExtractedAsset = CustomMaterial;
    type PreparedAsset = GpuCustomMaterial;
    type Param = (SRes<RenderDevice>, SRes<MaterialPipeline<Self>>);
    fn extract_asset(&self) -> Self::ExtractedAsset {
        self.clone()
    }

    fn prepare_asset(
        extracted_asset: Self::ExtractedAsset,
        (render_device, material_pipeline): &mut SystemParamItem<Self::Param>,
    ) -> Result<Self::PreparedAsset, PrepareAssetError<Self::ExtractedAsset>> {
        let color = Vec4::from_slice(&extracted_asset.color.as_linear_rgba_f32());

        let byte_buffer = [0u8; Vec4::SIZE.get() as usize];
        let mut buffer = encase::UniformBuffer::new(byte_buffer);
        buffer.write(&color).unwrap();

        let buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
            contents: buffer.as_ref(),
            label: None,
            usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
        });

        let (texture_view, texture_sampler) = if let Some(result) = material_pipeline
            .mesh_pipeline
            .get_image_texture(gpu_images, &Some(extracted_asset.color_texture.clone()))
        {
            result
        } else {
            return Err(PrepareAssetError::RetryNextUpdate(extracted_asset));
        };
        let bind_group = render_device.create_bind_group(&BindGroupDescriptor {
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 0,
                    resource: BindingResource::TextureView(texture_view),
                },
                BindGroupEntry {
                    binding: 1,
                    resource: BindingResource::Sampler(texture_sampler),
                },
            ],
            label: None,
            layout: &material_pipeline.material_layout,
        });

        Ok(GpuCustomMaterial {
            _buffer: buffer,
            bind_group,
        })
    }
}

impl Material for CustomMaterial {
    fn fragment_shader(asset_server: &AssetServer) -> Option<Handle<Shader>> {
        Some(asset_server.load("custom_material.wgsl"))
    }

    fn bind_group(render_asset: &<Self as RenderAsset>::PreparedAsset) -> &BindGroup {
        &render_asset.bind_group
    }

    fn bind_group_layout(render_device: &RenderDevice) -> BindGroupLayout {
        render_device.create_bind_group_layout(&BindGroupLayoutDescriptor {
            entries: &[
                BindGroupLayoutEntry {
                    binding: 0,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Buffer {
                        ty: BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: Some(Vec4::min_size()),
                    },
                    count: None,
                },
                BindGroupLayoutEntry {
                    binding: 1,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Texture {
                        multisampled: false,
                        sample_type: TextureSampleType::Float { filterable: true },
                        view_dimension: TextureViewDimension::D2Array,
                    },
                    count: None,
                },
                BindGroupLayoutEntry {
                    binding: 2,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Sampler(SamplerBindingType::Filtering),
                    count: None,
                },
            ],
            label: None,
        })
    }
}
```

### Bevy 0.8 (new)

```rust
impl Material for CustomMaterial {
    fn fragment_shader() -> ShaderRef {
        "custom_material.wgsl".into()
    }
}

#[derive(AsBindGroup, TypeUuid, Debug, Clone)]
#[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"]
pub struct CustomMaterial {
    #[uniform(0)]
    color: Color,
    #[texture(1)]
    #[sampler(2)]
    color_texture: Handle<Image>,
}
```

## Future Work

* Add support for more binding types (cubemaps, buffers, etc). This PR intentionally includes a bare minimum number of binding types to keep "reviewability" in check.
* Consider optionally eliding binding indices using binding names. `AsBindGroup` could pass in (optional?) reflection info as a "hint".
    * This would make it possible for the derive to do this:
        ```rust
        #[derive(AsBindGroup)]
        pub struct CustomMaterial {
            #[uniform]
            color: Color,
            #[texture]
            #[sampler]
            color_texture: Option<Handle<Image>>,
            alpha_mode: AlphaMode,
        }
        ```
    * Or this
        ```rust
        #[derive(AsBindGroup)]
        pub struct CustomMaterial {
            #[binding]
            color: Color,
            #[binding]
            color_texture: Option<Handle<Image>>,
            alpha_mode: AlphaMode,
        }
        ```
    * Or even this (if we flip to "include bindings by default")
        ```rust
        #[derive(AsBindGroup)]
        pub struct CustomMaterial {
            color: Color,
            color_texture: Option<Handle<Image>>,
            #[binding(ignore)]
            alpha_mode: AlphaMode,
        }
        ```
* If we add the option to define custom draw functions for materials (which could be done in a type-erased way), I think that would be enough to support extra non-material bindings. Worth considering!
2022-06-30 23:48:46 +00:00
François
d4e4a92982 android - fix issues other than the rendering (#5130)
# Objective

- Make Bevy work on android

## Solution

- Update android metadata and add a few more
- Set the target sdk to 31 as it will soon (in august) be the minimum sdk level for play store
- Remove the custom code to create an activity and use ndk-glue macro instead
- Delay window creation event on android
- Set the example with compatibility settings for wgpu. Those are needed for Bevy to work on my 2019 android tablet
- Add a few details on how to debug in case of failures
- Fix running the example on emulator. This was failing because of the name of the example

Bevy still doesn't work on android with this, audio features need to be disabled because of an ndk-glue version mismatch: rodio depends on 0.6.2, winit on 0.5.2. You can test with:
```
cargo apk run --release --example android_example --no-default-features --features "bevy_winit,render"
```
2022-06-30 19:42:45 +00:00
Carter Anderson
96f0ebb9af Fix rust 1.62 changes (#5154)
# Objective

CI is now failing with some changes that landed in 1.62.

## Solution

* Fix an unused lifetime by using it (we double-used the `w` lifetime).
* Update compile_fail error messages
* temporarily disable check-unused-dependencies
2022-06-30 19:24:28 +00:00
harudagondi
b3fa4790b7 Add ability to inspect entity's components (#5136)
# Objective

- Provide a way to see the components of an entity.
- Fixes #1467

## Solution

- Add `World::inspect_entity`. It accepts an `Entity` and returns a vector of `&ComponentInfo` that the entity has.
- Add `EntityCommands::log_components`. It logs the component names of the entity. (info level)

---

## Changelog

### Added
- Ability to inspect components of an entity through `World::inspect_entity` or `EntityCommands::log_components`
2022-06-30 15:23:09 +00:00
Jakob Hellermann
5b5660ea08 remove unnecessary unsafe impl of Send+Sync for ParallelSystemContainer (#5137)
`ParallelSystemContainer` has no `!Send` or `!Sync` fields, so it doesn't need unsafe impls of these traits.
2022-06-29 15:44:33 +00:00
grace125
7a42f7b3f9 Fix typos in bevy_reflect readme (#5134)
# Objective

Fix some typos in bevy_reflect's readme

## Solution

- Change `Foo`'s `d` field to be of type `Vec<Baz>`
- Format `&dyn Reflect` to be monospace
2022-06-29 02:48:47 +00:00
DGriffin91
072f2e17d3 Move texture sample out of branch in prepare_normal (#5129)
# Objective

This fixes https://github.com/bevyengine/bevy/issues/5127

## Solution

- Moved texture sample out of branch in `prepare_normal()`.


Co-authored-by: DGriffin91 <github@dgdigital.net>
2022-06-29 02:48:46 +00:00
Mike
510ce5e832 fix resource not found error message (#5128)
There are some outdated error messages for when a resource is not found. It references `add_resource` and `add_non_send_resource` which were renamed to `insert_resource` and `insert_non_send_resource`.
2022-06-29 02:29:51 +00:00