Commit graph

1672 commits

Author SHA1 Message Date
Francesco Giordana
dbd5e7ab6b Fixed case of R == G, following original conversion formula (#4383)
https://en.wikipedia.org/wiki/HSL_and_HSV#From_RGB

# Objective
Fixes #4382

## Solution

- Describe the solution used to achieve the objective above.
Fixed conversion formula to account for red and green component being max and equal
---

## Changelog
Fixed RGB -> HSL colorspace conversion

## Migration Guide


Co-authored-by: Francesco Giordana <fgiordana@netflix.com>
2022-04-04 18:59:00 +00:00
KDecay
f90da74e32 Remove face_toward.rs (#4277)
# Objective

- Part of the splitting process of #3503.

## Solution

- Remove the `face_toward.rs` file containing the `FaceToward` trait.

## Reasons

- It is unused inside of `bevy`.
- The method `Mat4::face_toward` of the trait is identical to `Mat4::look_at_rh` (see https://docs.rs/glam/latest/glam/f32/struct.Mat4.html#method.look_at_rh).
- Discussion in #3503.

## Changelog

### Removed

- The `FaceToward` trait got removed.

## Migration Guide

-  The `FaceToward` trait got removed. To migrate you just have to change every occurrence of `Mat4::face_toward` to `Mat4::look_at_rh`.
2022-04-03 14:40:46 +00:00
François
449a1d223c animation player (#4375)
# Objective

- Add a basic animation player
  - Single track
  - Not generic, can only animate `Transform`s
  - With plenty of possible optimisations available
  - Close-ish to https://github.com/bevyengine/rfcs/pull/49
- https://discord.com/channels/691052431525675048/774027865020039209/958820063148929064

## Solution

- Can play animations
  - looping or not
- Can pause animations
- Can seek in animation
- Can alter speed of animation
- I also removed the previous gltf animation example

https://user-images.githubusercontent.com/8672791/161051887-e79283f0-9803-448a-93d0-5f7a62acb02d.mp4
2022-04-02 22:36:02 +00:00
Daniel McNab
c26be39719 Remove unnecessary system labels (#4340)
# Objective

- Since #4224, using labels which only refer to one system doesn't make sense.

## Solution

- Remove some of those.

## Future work

- We should remove the ability to use strings as system labels entirely. I haven't in this PR because there are tests which use this, and that's a lot of code to change.
   - The only use cases for labels are either intra-crate, which use #4224, or inter-crate, which should either use #4224 or explicit types. Neither of those should use strings.
2022-04-01 21:11:05 +00:00
Light Ning
dd2001f2f1 bevy_render: add a small color box to each color (#4387)
# Objective

- bevy_render: add a small color box to each color

## Solution

![bevy_color_doc](https://user-images.githubusercontent.com/1318472/161241226-e7632a90-f526-44de-a68e-ff63b848164b.png)

---

## Changelog
2022-04-01 20:52:22 +00:00
Alice Cecile
b33dae31ec Rename get_multiple APIs to get_many (#4384)
# Objective

-  std's new APIs do the same thing as `Query::get_multiple_mut`, but are called `get_many`: https://github.com/rust-lang/rust/pull/83608

## Solution

- Find and replace `get_multiple` with `get_many`
2022-03-31 20:59:26 +00:00
devil ira
48ac955afd Fix loading non-TriangleList meshes without normals in gltf loader (#4376)
# Objective
Make it so that loading in a mesh without normals that is not a `TriangleList` succeeds.

## Solution
Flat normals can only be calculated on a mesh made of triangles.
Check whether the mesh is a `TriangleList` before trying to compute missing normals.

## Additional changes
The panic condition in `duplicate_vertices` did not make sense to me. I moved it to `compute_flat_normals` where the algorithm would produce incorrect results if the mesh is not a `TriangleList`.

Co-authored-by: devil-ira <justthecooldude@gmail.com>
2022-03-31 20:43:01 +00:00
Daniel McNab
aca7fc1854 Remove outdated perf comments (#4374)
# Objective

- The perf comments, added (by me) in https://github.com/bevyengine/bevy/pull/1349, became outdated once the initialisation call started to take an exclusive reference, (presumably in https://github.com/bevyengine/bevy/pull/1525).
- They have been naïvely transferred along ever since

## Solution

- Remove them
2022-03-31 20:43:00 +00:00
SecretPocketCat
3af90b67a6 Update RemovedComponents doc comment (#4373)
# Objective

- Clarify `RemovedComponents` are flushed in `CoreStage::Last` and systems relying on that should run before that stage

## Solution

- Update `RemovedComponents` doc comment
2022-03-31 20:24:32 +00:00
Boxy
637a149910 unsafeify World::entities_mut (#4093)
# Objective
make bevy ecs a lil bit less unsound

## Solution
make unsound API unsafe so that there is an unsafe block to blame:

```rust
use bevy_ecs::prelude::*;

#[derive(Debug, Component)]
struct Foo(u8);

fn main() {
    let mut world = World::new();
    let e1 = world.spawn().id();
    let e2 = world.spawn().insert(Foo(2)).id();
    world.entities_mut().meta[0] = world.entities_mut().meta[1].clone();
    let foo = world.entity(e1).get::<Foo>().unwrap();
    // whoo i love having components i dont have
    dbg!(foo);
}
```

This is not _strictly_ speaking UB, however: 
- `Query::get_multiple` cannot work if this is allowed
- bevy_ecs is a pile of unsafe code whose soundness generally depends on the world being in a "correct" state with "no funny business" so it seems best to disallow this
- it is trivial to get bevy to panic inside of functions with safety invariants that have been violated (the entity location is not valid)
- it seems to violate what the safety invariant on `Entities::flush` is trying to ensure
2022-03-30 23:52:45 +00:00
Chris Russell
2b35dbabfd impl Reflect and Debug for Mesh2dHandle (#4368)
# Objective

An entity spawned with `MaterialMesh2dBundle<M>` cannot be saved and spawned using `DynamicScene` because the `Mesh2dHandle` component does not `impl Reflect`.  

## Solution

Add `#[derive(Reflect)]` and `#[reflect(Component)]` to `Mesh2dHandle`, and call `register_type` in `SpritePlugin`.  Also add `#[derive(Debug)]` since I'm touching the `derive`s anyway.
2022-03-30 19:56:17 +00:00
François
3537c6ae2d Fix animation: shadow and wireframe support (#4367)
# Objective

Animation with shadows crashes with:
```
thread 'main' panicked at 'wgpu error: Validation Error

Caused by:
    In Device::create_render_pipeline
      note: label = `shadow_pipeline`
    error matching VERTEX shader requirements against the pipeline
    shader global ResourceBinding { group: 1, binding: 1 } is not available in the layout pipeline layout
    visibility flags don't include the shader stage
```


Animation with wireframe crashes with:
```
thread 'main' panicked at 'wgpu error: Validation Error

Caused by:
    In Device::create_render_pipeline
      note: label = `opaque_mesh_pipeline`
    error matching VERTEX shader requirements against the pipeline
    shader global ResourceBinding { group: 2, binding: 0 } is not available in the layout pipeline layout
    binding is missing from the pipeline layout
```

## Solution

- Fix the bindings
2022-03-30 19:56:16 +00:00
François
f6bc9a022d Sprites - keep color as 4 f32 (#4361)
# Objective

- Fix #4356

## Solution

- Do not reduce the color of sprites to 4 u8
2022-03-30 19:38:24 +00:00
Alice Cecile
509548190b Add get_multiple and get_multiple_mut APIs for Query and QueryState (#4298)
# Objective

- The inability to have multiple active mutable borrows into a query is a common source of borrow-checker pain for users.
- This is a pointless restriction if and only if we can guarantee that the entities they are accessing are unique.
- This could already by bypassed with get_unchecked, but that is an extremely unsafe API.
- Closes https://github.com/bevyengine/bevy/issues/2042.

## Solution

- Add `get_multiple`, `get_multiple_mut` and their unchecked equivalents (`multiple` and `multiple_mut`) to `Query` and `QueryState`.
- Improve the `QueryEntityError` type to provide more useful error information.

## Changelog

- Added `get_multiple`, `get_multiple_mut` and their unchecked equivalents (`multiple` and `multiple_mut`) to Query and QueryState.

## Migration Guide

- The `QueryEntityError` enum now has a `AliasedMutability variant, and returns the offending entity.

## Context

This is a fresh attempt at #3333; rebasing was behaving very badly and it was important to rebase on top of the recent query soundness fixes. Many thanks to all the reviewers in that thread, especially @BoxyUwU for the help with lifetimes.

## To-do

- [x] Add compile fail tests
- [x] Successfully deduplicate code
- [x] Decide what to do about failing doc tests
- [x] Get some reviews for lifetime soundness
2022-03-30 19:16:48 +00:00
bilsen
63fee2572b ParamSet for conflicting SystemParam:s (#2765)
# Objective
Add a system parameter `ParamSet` to be used as container for conflicting parameters.

## Solution
Added two methods to the SystemParamState trait, which gives the access used by the parameter. Did the implementation. Added some convenience methods to FilteredAccessSet. Changed `get_conflicts` to return every conflicting component instead of breaking on the first conflicting `FilteredAccess`.


Co-authored-by: bilsen <40690317+bilsen@users.noreply.github.com>
2022-03-29 23:39:38 +00:00
Rob Parrett
7ff3d876fa Clean up duplicated color conversion code (#4360)
# Objective

Cleans up some duplicated color -> u32 conversion code in `bevy_sprite` and `bevy_ui`

## Solution

Use `as_linear_rgba_u32` which was added recently by #4088
2022-03-29 23:03:22 +00:00
Yutao Yuan
954022c799 Add text wrapping support to Text2d (#4347)
# Objective

Fixes #4344.

## Solution

Add a new component `Text2dBounds` to `Text2dBundle` that specifies the maximum width and height of text. Text will wrap according to this size.
2022-03-29 23:03:20 +00:00
KDecay
c7c08f95cb Fix gamepad connection system ordering (#4313)
# Objective

- Part of the splitting process of #3692.

## Solution

- Change the `gamepad_connection_system` to run after the `InputSystem` label.

## Reasons

I changed the `gamepad_connection_system` to run after the `InputSystem` instead of in parallel, because this system checks the `GamepadEvent`s which get send inside of the `gamepad_event_system`. This means that the `gamepad_connection_system` could respond to the events one frame later, instead of instantly resulting in one frame lag.

Old possible case:
1. `gamepad_connection_system` (reacts to the `GamepadEvent`s too early)
2. `gamepad_event_system` (sends the `GamepadEvent`s)

New fixed ordering:
1. `gamepad_event_system` (sends the `GamepadEvent`s)
2. `gamepad_connection_system` (reacts to the `GamepadEvent`s)
2022-03-29 22:39:21 +00:00
KDecay
f3a61327a4 Remove margins.rs (#4284)
# Objective

- Closes #335.
- Part of the splitting process of #3503.

## Solution

- Remove the `margins.rs` file containing the `Margins` type.

## Reasons

- It is unused inside of `bevy`.
- The `Rect`/`UiRect` is identical to the `Margins` type and is also used for margins inside of `bevy` (rename of `Rect` happens in #4276)
- Discussion in #3503.

## Changelog

### Removed

- The `Margins` type got removed.

## Migration Guide

- The `Margins` type got removed. To migrate you just have to change every occurrence of `Margins` to `UiRect`.
2022-03-29 22:39:18 +00:00
KDecay
f5e53ba6f5 Only insert or remove input if needed (#4273)
# Objective

We are currently inserting an `input` into `pressed` even if it is already pressed. This also applies to releasing an input. This is not a big deal, but since we are already checking if the `input` is pressed or not we might as well remove the cost of the value update caused by the `pressed.insert` method.

Related to #4209

## Solution

Only insert or remove input if needed.
2022-03-29 22:39:16 +00:00
Jakob Hellermann
551d9f6cd7 use error scope to handle errors on shader module creation (#3675)
related: https://github.com/bevyengine/bevy/pull/3289

In addition to validating shaders early when debug assertions are enabled, use the new [error scopes](https://gpuweb.github.io/gpuweb/#error-scopes) API when creating a shader module.

I chose to keep the early validation (and thereby parsing twice) when debug assertions are enabled in, because it lets as handle errors ourselves and display them with pretty colors, while the error scopes API just gives us a string we can display.



This change pulls in `futures-util` as a new dependency for `future.now_or_never()`. I can inline that part of futures-lite into `bevy_render` to keep the compilation time lower if that's preferred.
2022-03-29 22:39:14 +00:00
Mika
6844a6f4fd Introduce SystemLabel's for RenderAssetPlugin, and change Image preparation system to run before others (#3917)
# Objective

Fixes `StandardMaterial` texture update (see sample code below).

Most probably fixes #3674 (did not test)

## Solution

Material updates, such as PBR update, reference the underlying `GpuImage`. Like here: 9a7852db0f/crates/bevy_pbr/src/pbr_material.rs (L177)

However, currently the `GpuImage` update may actually happen *after* the material update fetches the gpu image. Resulting in the material actually not being updated for the correct gpu image.

In this pull req, I introduce new systemlabels for the renderassetplugin. Also assigned the RenderAssetPlugin::<Image> to the `PreAssetExtract` stage, so that it is executed before any material updates.

Code to test.

Expected behavior:
* should update to red texture

Unexpected behavior (before this merge):
* texture stays randomly as green one (depending on the execution order of systems)

```rust
use bevy::{
    prelude::*,
    render::render_resource::{Extent3d, TextureDimension, TextureFormat},
};

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_startup_system(setup)
        .add_system(changes)
        .run();
}

struct Iteration(usize);

#[derive(Component)]
struct MyComponent;

fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut images: ResMut<Assets<Image>>,
) {
    commands.spawn_bundle(PointLightBundle {
        point_light: PointLight {
            ..Default::default()
        },
        transform: Transform::from_xyz(4.0, 8.0, 4.0),
        ..Default::default()
    });

    commands.spawn_bundle(PerspectiveCameraBundle {
        transform: Transform::from_xyz(-2.0, 0.0, 5.0)
            .looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
        ..Default::default()
    });

    commands.insert_resource(Iteration(0));

    commands
        .spawn_bundle(PbrBundle {
            mesh: meshes.add(Mesh::from(shape::Quad::new(Vec2::new(3., 2.)))),
            material: materials.add(StandardMaterial {
                base_color_texture: Some(images.add(Image::new(
                    Extent3d {
                        width: 600,
                        height: 400,
                        depth_or_array_layers: 1,
                    },
                    TextureDimension::D2,
                    [0, 255, 0, 128].repeat(600 * 400), // GREEN
                    TextureFormat::Rgba8Unorm,
                ))),
                ..Default::default()
            }),
            ..Default::default()
        })
        .insert(MyComponent);
}

fn changes(
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut images: ResMut<Assets<Image>>,
    mut iteration: ResMut<Iteration>,
    webview_query: Query<&Handle<StandardMaterial>, With<MyComponent>>,
) {
    if iteration.0 == 2 {
        let material = materials.get_mut(webview_query.single()).unwrap();

        let image = images
            .get_mut(material.base_color_texture.as_ref().unwrap())
            .unwrap();

        image
            .data
            .copy_from_slice(&[255, 0, 0, 255].repeat(600 * 400));
    }

    iteration.0 += 1;
}
```

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-03-29 19:44:45 +00:00
James Liu
31bd4ecbbc Mesh Skinning. Attempt #3 (#4238)
# Objective
Load skeletal weights and indices from GLTF files. Animate meshes.

## Solution
 - Load skeletal weights and indices from GLTF files.
 - Added `SkinnedMesh` component and ` SkinnedMeshInverseBindPose` asset
 - Added `extract_skinned_meshes` to extract joint matrices.
 - Added queue phase systems for enqueuing the buffer writes.

Some notes:

 -  This ports part of # #2359 to the current main.
 -  This generates new `BufferVec`s and bind groups every frame. The expectation here is that the number of `Query::get` calls during extract is probably going to be the stronger bottleneck, with up to 256 calls per skinned mesh. Until that is optimized, caching buffers and bind groups is probably a non-concern.
 - Unfortunately, due to the uniform size requirements, this means a 16KB buffer is allocated for every skinned mesh every frame. There's probably a few ways to get around this, but most of them require either compute shaders or storage buffers, which are both incompatible with WebGL2.

Co-authored-by: james7132 <contact@jamessliu.com>
Co-authored-by: François <mockersf@gmail.com>
Co-authored-by: James Liu <contact@jamessliu.com>
2022-03-29 18:31:13 +00:00
Robert Swain
54d2e86afc bevy_transform: Use Changed in the query for much faster transform_propagate_system (#4180)
# Objective

- Improve transform propagation performance

## Solution

- Use `Changed<Transform>` as part of the `root_query` and `transform_query` to avoid the indirection of having to look up the `Entity` in the `changed_transform_query`
- Get rid of the `changed_transform_query` entirely
- `transform_propagate_system` execution time for `many_cubes -- sphere` dropped from 1.07ms to 0.159ms, an 85% reduction for this system. Frame rate increased from ~42fps to ~44fps
2022-03-29 03:05:01 +00:00
MrGVSV
f16768d868 bevy_derive: Add derives for Deref and DerefMut (#4328)
# Objective

A common pattern in Rust is the [newtype](https://doc.rust-lang.org/rust-by-example/generics/new_types.html). This is an especially useful pattern in Bevy as it allows us to give common/foreign types different semantics (such as allowing it to implement `Component` or `FromWorld`) or to simply treat them as a "new type" (clever). For example, it allows us to wrap a common `Vec<String>` and do things like:

```rust
#[derive(Component)]
struct Items(Vec<String>);

fn give_sword(query: Query<&mut Items>) { 
  query.single_mut().0.push(String::from("Flaming Poisoning Raging Sword of Doom"));
}
```

> We could then define another struct that wraps `Vec<String>` without anything clashing in the query.

However, one of the worst parts of this pattern is the ugly `.0` we have to write in order to access the type we actually care about. This is why people often implement `Deref` and `DerefMut` in order to get around this.

Since it's such a common pattern, especially for Bevy, it makes sense to add a derive macro to automatically add those implementations.


## Solution

Added a derive macro for `Deref` and another for `DerefMut` (both exported into the prelude). This works on all structs (including tuple structs) as long as they only contain a single field:

```rust
#[derive(Deref)]
struct Foo(String);

#[derive(Deref, DerefMut)]
struct Bar {
  name: String,
}
```

This allows us to then remove that pesky `.0`:

```rust
#[derive(Component, Deref, DerefMut)]
struct Items(Vec<String>);

fn give_sword(query: Query<&mut Items>) { 
  query.single_mut().push(String::from("Flaming Poisoning Raging Sword of Doom"));
}
```

### Alternatives

There are other alternatives to this such as by using the [`derive_more`](https://crates.io/crates/derive_more) crate. However, it doesn't seem like we need an entire crate just yet since we only need `Deref` and `DerefMut` (for now).

### Considerations

One thing to consider is that the Rust std library recommends _not_ using `Deref` and `DerefMut` for things like this: "`Deref` should only be implemented for smart pointers to avoid confusion" ([reference](https://doc.rust-lang.org/std/ops/trait.Deref.html)). Personally, I believe it makes sense to use it in the way described above, but others may disagree.

### Additional Context

Discord: https://discord.com/channels/691052431525675048/692572690833473578/956648422163746827 (controversiality discussed [here](https://discord.com/channels/691052431525675048/692572690833473578/956711911481835630))

---

## Changelog

- Add `Deref` derive macro (exported to prelude)
- Add `DerefMut` derive macro (exported to prelude)
- Updated most newtypes in examples to use one or both derives

Co-authored-by: MrGVSV <49806985+MrGVSV@users.noreply.github.com>
2022-03-29 02:10:06 +00:00
Boxy
28ba87e6c8 CI runs cargo miri test -p bevy_ecs (#4310)
# Objective

Fixes #1529
Run bevy_ecs in miri

## Solution

- Don't set thread names when running in miri rust-lang/miri/issues/1717
- Update `event-listener` to `2.5.2` as previous versions have UB that is detected by miri: [event-listener commit](1fa31c553e)
- Ignore memory leaks when running in miri as they are impossible to track down rust-lang/miri/issues/1481
- Make `table_add_remove_many` test less "many" because miri is really quite slow :)
- Make CI run `RUSTFLAGS="-Zrandomize-layout" MIRIFLAGS="-Zmiri-ignore-leaks -Zmiri-tag-raw-pointers -Zmiri-disable-isolation" cargo +nightly miri test -p bevy_ecs`
2022-03-25 00:26:07 +00:00
Carter Anderson
207ebde020 Always update clusters and remove per-frame allocations (#4169)
* Refactor assign_lights_to_clusters to always clear + update clusters, even if the screen size isn't available yet / is zero. This fixes #4167. We still avoid the "expensive" per-light work when the screen size isn't available yet. I also consolidated some logic to eliminate some redundancies.
* Removed _a ton_ of (potentially very large) per-frame reallocations
  * Removed `Res<VisiblePointLights>` (a vec) in favor of  `Res<GlobalVisiblePointLights>` (a hashmap). We were allocating a new hashmap every frame, the collecting it into a vec every frame, then in another system _re-generating the hashmap_. It is always used like a hashmap, might as well embrace that. We now reuse the same hashmap every frame and dont use any intermediate collections.
  * We were re-allocating Clusters aabb and light vectors every frame by re-constructing Clusters every frame. We now re-use the existing collections.
  * Reuse per-camera VisiblePointLight vecs when possible instead of allocating them every frame. We now only insert VisiblePointLights if the component doesn't exist yet.
2022-03-24 00:20:27 +00:00
Carter Anderson
b1c3e9862d Auto-label function systems with SystemTypeIdLabel (#4224)
This adds the concept of "default labels" for systems (currently scoped to "parallel systems", but this could just as easily be implemented for "exclusive systems"). Function systems now include their function's `SystemTypeIdLabel` by default.

This enables the following patterns:

```rust
// ordering two systems without manually defining labels
app
  .add_system(update_velocity)
  .add_system(movement.after(update_velocity))

// ordering sets of systems without manually defining labels
app
  .add_system(foo)
  .add_system_set(
    SystemSet::new()
      .after(foo)
      .with_system(bar)
      .with_system(baz)
  )
```

Fixes: #4219
Related to: #4220 

Credit to @aevyrie @alice-i-cecile @DJMcNab (and probably others) for proposing (and supporting) this idea about a year ago. I was a big dummy that both shut down this (very good) idea and then forgot I did that. Sorry. You all were right!
2022-03-23 22:53:56 +00:00
Kurt Kühnert
9e450f2827 Compute Pipeline Specialization (#3979)
# Objective

- Fixes #3970
- To support Bevy's shader abstraction(shader defs, shader imports and hot shader reloading) for compute shaders, I have followed carts advice and change the `PipelinenCache` to accommodate both compute and render pipelines.

## Solution

- renamed `RenderPipelineCache` to `PipelineCache`
- Cached Pipelines are now represented by an enum (render, compute)
- split the `SpecializedPipelines` into `SpecializedRenderPipelines` and `SpecializedComputePipelines`
- updated the game of life example

## Open Questions

- should `SpecializedRenderPipelines` and `SpecializedComputePipelines` be merged and how would we do that?
- should the `get_render_pipeline` and `get_compute_pipeline` methods be merged?
- is pipeline specialization for different entry points a good pattern




Co-authored-by: Kurt Kühnert <51823519+Ku95@users.noreply.github.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-03-23 00:27:26 +00:00
Robert Swain
0a4136d266 Add a helper for storage buffers similar to UniformVec (#4079)
# Objective

- Add a helper for storage buffers similar to `UniformVec`

## Solution

- Add a `StorageBuffer<T, U>` where `T` is the main body of the shader struct without any final variable-sized array member, and `U` is the type of the items in a variable-sized array.
- Use `()` as the type for unwanted parts, e.g. `StorageBuffer<(), Vec4>::default()` would construct a binding that would work with `struct MyType { data: array<vec4<f32>>; }` in WGSL and `StorageBuffer<MyType, ()>::default()` would work with `struct MyType { ... }` in WGSL as long as there are no variable-sized arrays.
- Std430 requires that there is at most one variable-sized array in a storage buffer, that if there is one it is the last member of the binding, and that it has at least one item. `StorageBuffer` handles all of these constraints.
2022-03-22 21:23:50 +00:00
Boxy
024d98457c yeet unsound lifetime annotations on Query methods (#4243)
# Objective
Continuation of #2964 (I really should have checked other methods when I made that PR)

yeet unsound lifetime annotations on `Query` methods.
Example unsoundness:
```rust
use bevy::prelude::*;

fn main() {
    App::new().add_startup_system(bar).add_system(foo).run();
}

pub fn bar(mut cmds: Commands) {
    let e = cmds.spawn().insert(Foo { a: 10 }).id();
    cmds.insert_resource(e);
}

#[derive(Component, Debug, PartialEq, Eq)]
pub struct Foo {
    a: u32,
}
pub fn foo(mut query: Query<&mut Foo>, e: Res<Entity>) {
    dbg!("hi");
    {
        let data: &Foo = query.get(*e).unwrap();
        let data2: Mut<Foo> = query.get_mut(*e).unwrap();
        assert_eq!(data, &*data2); // oops UB
    }

    {
        let data: &Foo = query.single();
        let data2: Mut<Foo> = query.single_mut();
        assert_eq!(data, &*data2); // oops UB
    }

    {
        let data: &Foo = query.get_single().unwrap();
        let data2: Mut<Foo> = query.get_single_mut().unwrap();
        assert_eq!(data, &*data2); // oops UB
    }

    {
        let data: &Foo = query.iter().next().unwrap();
        let data2: Mut<Foo> = query.iter_mut().next().unwrap();
        assert_eq!(data, &*data2); // oops UB
    }

    {
        let mut opt_data: Option<&Foo> = None;
        let mut opt_data_2: Option<Mut<Foo>> = None;
        query.for_each(|data| opt_data = Some(data));
        query.for_each_mut(|data| opt_data_2 = Some(data));
        assert_eq!(opt_data.unwrap(), &*opt_data_2.unwrap()); // oops UB
    }
    dbg!("bye");
}

```

## Solution
yeet unsound lifetime annotations on `Query` methods

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-03-22 02:49:41 +00:00
François
fbe7a49d5b Gltf animations (#3751)
# Objective

- Load informations for animations from GLTF
- Make experimenting on animations easier

# Non Objective

- Implement a solutions for all animations in Bevy. This would need a discussion / RFC. The goal here is only to have the information available to try different APIs

## Solution

- Load animations with a representation close to the GLTF spec
- Add an example to display animations. There is an animation driver in the example, not in Bevy code, to show how it can be used. The example is cycling between examples from the official gltf sample ([AnimatedTriangle](https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0/AnimatedTriangle), [BoxAnimated](https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0/BoxAnimated)), and one from me with some cases not present in the official examples.


https://user-images.githubusercontent.com/8672791/150696656-073403f0-d921-43b6-beaf-099c7aee16ed.mp4




Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-03-22 02:26:34 +00:00
Robert Swain
6c085cba47 bevy_render: Support removal of nodes, edges, subgraphs (#3048)
Add support for removing nodes, edges, and subgraphs. This enables live re-wiring of the render graph.

This was something I did to support the MSAA implementation, but it turned out to be unnecessary there. However, it is still useful so here it is in its own PR.

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-03-21 23:58:37 +00:00
Boxy
050d2b7f00 yeet World::components_mut >:( (#4092)
# Objective
make bevy ecs a lil bit less unsound
## Solution
yeet unsound API `World::components_mut`:
```rust
use bevy_ecs::prelude::*;

#[derive(Component)]
struct Foo(u8);

#[derive(Debug, Component)]
struct Bar([u8; 100]);

fn main() {
    let mut world = World::new();
    let e = world.spawn().insert(Foo(0)).id();
    *world.components_mut() = Default::default();
    let bar = world.entity_mut(e).remove::<Bar>().unwrap();
    // oopsies reading memory copied from outside allocation
    dbg!(bar);
}
```
2022-03-21 23:43:08 +00:00
James Liu
4c1678c78d Hide docs for concrete impls of Fetch, FetchState, and SystemParamState (#4250)
# Objective
 The following pages in the docs are rather noisy, and the types they point to are not particularly useful by themselves:

 - http://dev-docs.bevyengine.org/bevy/ecs/query/index.html
 - http://dev-docs.bevyengine.org/bevy/ecs/system/index.html

## Solution
 
- Replace docs on these types with `#[doc(hidden)]`.
- Hide `InputMarker`  too.
2022-03-21 05:23:36 +00:00
Jakob Hellermann
685b6e59be register Camera{2,3}d components for reflection (#4269)
# Objective

When loading a gltf scene with a camera, bevy will panic at ``thread 'main' panicked at 'scene contains the unregistered type `bevy_render:📷:bundle::Camera3d`. consider registering the type using `app.register_type::<T>()`', /home/jakob/dev/rust/contrib/bevy/bevy/crates/bevy_scene/src/scene_spawner.rs:332:35``.

## Solution

Register the camera types to fix the panic.
2022-03-20 21:54:11 +00:00
Mathis
cd694c0d08 Prevent event from getting registered twice (#4258)
# Objective

As described in  #4257, registering an Event twice would cause some systems to miss events on some starts, since the event buffer is cleared + swapped multiple times.

Fixes #4257

## Solution

A simple check whether the event is already registered is added, making adding an Event a second time a no-op.
2022-03-20 21:54:10 +00:00
Chris Foster
b0ddce36bd Check an Input's pressed set before adding to just_released. (#4209)
# Objective

- Fixes #4208

## Solution

- Adds a check before inserting into an `Input`'s `just_released` set, in the same way that one exists for adding into the `just_pressed` set.
2022-03-20 21:54:09 +00:00
Jakob Hellermann
3e631e6234 gltf-loader: disable backface culling if material is double-sided (#4270)
# Objective

The  [glTF spec](8e798b02d2/specification/2.0/Specification.adoc (395-double-sided)) the `doubleSided` has the following to say about the `doubleSided` boolean:

> When this value is false, back-face culling is enabled, i.e., only front-facing triangles are rendered.
> When this value is true, back-face culling is disabled and double sided lighting is enabled. The back-face MUST have its normals reversed before the lighting equation is evaluated.

## Solution
Disable backface culling when `doubleSided: true`.
2022-03-20 21:32:38 +00:00
Robert Swain
fee7a26137 Tracy spans around main 3D passes (#4182)
# Objective

- Make visible how much time is spent building the Opaque3d, AlphaMask3d, and Transparent3d passes

## Solution

- Add a `trace` feature to `bevy_core_pipeline`
- Add tracy spans around the three passes
- I didn't do this for shadows, sprites, etc as they are only one pass in the node. Perhaps it should be split into 3 nodes to allow insertion of other nodes between...?
2022-03-19 12:57:47 +00:00
Robert Swain
ac8bbafc5c Faster view frustum culling (#4181)
# Objective

- Reduce time spent in the `check_visibility` system

## Solution

- Use `Vec3A` for all bounding volume types to leverage SIMD optimisations and to avoid repeated runtime conversions from `Vec3` to `Vec3A`
- Inline all bounding volume intersection methods
- Add on-the-fly calculated `Aabb` -> `Sphere` and do `Sphere`-`Frustum` intersection tests before `Aabb`-`Frustum` tests. This is faster for `many_cubes` but could be slower in other cases where the sphere test gives a false-positive that the `Aabb` test discards. Also, I tested precalculating the `Sphere`s and inserting them alongside the `Aabb` but this was slower. 
- Do not test meshes against the far plane. Apparently games don't do this anymore with infinite projections, and it's one fewer plane to test against. I made it optional and still do the test for culling lights but that is up for discussion.
- These collectively reduce `check_visibility` execution time in `many_cubes -- sphere` from 2.76ms to 1.48ms and increase frame rate from ~42fps to ~44fps
2022-03-19 04:41:28 +00:00
Boxy
e7a9420443 Change Cow<[ComponentId]> to Box<[ComponentId]> (#4185)
`Cow::Borrowed` was never used
2022-03-19 04:14:27 +00:00
Alice Cecile
7ce3ae43e3 Bump Bevy to 0.7.0-dev (#4230)
# Objective

- The [dev docs](https://dev-docs.bevyengine.org/bevy/index.html#) show version 0.6.0, which is actively misleading.

[Image of the problem](https://cdn.discordapp.com/attachments/695741366520512563/953513612943704114/Screenshot_20220316-154100_Firefox-01.jpeg)

Noticed by @ickk, fix proposed by @mockersf.

## Solution

- Bump the version across all Bevy crates to 0.7.0 dev.
- Set a reminder in the Release Checklist to remember to do this each release.
2022-03-19 03:54:15 +00:00
Carter Anderson
de677dbfc9 Use more ergonomic span syntax (#4246)
Tracing added support for "inline span entering", which cuts down on a lot of complexity:

```rust
let span = info_span!("my_span").entered();
```

This adapts our code to use this pattern where possible, and updates our docs to recommend it.

This produces equivalent tracing behavior. Here is a side by side profile of "before" and "after" these changes.
![image](https://user-images.githubusercontent.com/2694663/158912137-b0aa6dc8-c603-425f-880f-6ccf5ad1b7ef.png)
2022-03-18 04:19:21 +00:00
Robert Swain
0529f633f9 KTX2/DDS/.basis compressed texture support (#3884)
# Objective

- Support compressed textures including 'universal' formats (ETC1S, UASTC) and transcoding of them to 
- Support `.dds`, `.ktx2`, and `.basis` files

## Solution

- Fixes https://github.com/bevyengine/bevy/issues/3608 Look there for more details.
- Note that the functionality is all enabled through non-default features. If it is desirable to enable some by default, I can do that.
- The `basis-universal` crate, used for `.basis` file support and for transcoding, is built on bindings against a C++ library. It's not feasible to rewrite in Rust in a short amount of time. There are no Rust alternatives of which I am aware and it's specialised code. In its current state it doesn't support the wasm target, but I don't know for sure. However, it is possible to build the upstream C++ library with emscripten, so there is perhaps a way to add support for web too with some shenanigans.
- There's no support for transcoding from BasisLZ/ETC1S in KTX2 files as it was quite non-trivial to implement and didn't feel important given people could use `.basis` files for ETC1S.
2022-03-15 22:26:46 +00:00
Daniel McNab
6e61fef67d Obviate the need for RunSystem, and remove it (#3817)
# Objective

- Fixes #3300
- `RunSystem` is messy

## Solution

- Adds the trick theorised in https://github.com/bevyengine/bevy/issues/3300#issuecomment-991791234

P.S. I also want this for an experimental refactoring of `Assets`, to remove the duplication of `Events<AssetEvent<T>>`


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-03-15 02:16:55 +00:00
Alice Cecile
a304fd9a99 Split bevy_hierarchy out from bevy_transform (#4168)
# Objective

- Hierarchy tools are not just used for `Transform`: they are also used for scenes.
- In the future there's interest in using them for other features, such as visiibility inheritance.
- The fact that these tools are found in `bevy_transform` causes a great deal of user and developer confusion
- Fixes #2758.

## Solution

- Split `bevy_transform` into two!
- Make everything work again.

Note that this is a very tightly scoped PR: I *know* there are code quality and docs issues that existed in bevy_transform that I've just moved around. We should fix those in a seperate PR and try to merge this ASAP to reduce the bitrot involved in splitting an entire crate.

## Frustrations

The API around `GlobalTransform` is a mess: we have massive code and docs duplication, no link between the two types and no clear way to extend this to other forms of inheritance.

In the medium-term, I feel pretty strongly that `GlobalTransform` should be replaced by something like `Inherited<Transform>`, which lives in `bevy_hierarchy`:

- avoids code duplication
- makes the inheritance pattern extensible
- links the types at the type-level
- allows us to remove all references to inheritance from `bevy_transform`, making it more useful as a standalone crate and cleaning up its docs

## Additional context

- double-blessed by @cart in https://github.com/bevyengine/bevy/issues/4141#issuecomment-1063592414 and https://github.com/bevyengine/bevy/issues/2758#issuecomment-913810963
- preparation for more advanced / cleaner hierarchy tools: go read https://github.com/bevyengine/rfcs/pull/53 !
- originally attempted by @finegeometer in #2789. It was a great idea, just needed more discussion!

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-03-15 01:54:05 +00:00
Jakob Hellermann
bf6de89622 use marker components for cameras instead of name strings (#3635)
**Problem**
- whenever you want more than one of the builtin cameras (for example multiple windows, split screen, portals), you need to add a render graph node that executes the correct sub graph, extract the camera into the render world and add the correct `RenderPhase<T>` components
- querying for the 3d camera is annoying because you need to compare the camera's name to e.g. `CameraPlugin::CAMERA_3d`

**Solution**
- Introduce the marker types `Camera3d`, `Camera2d` and `CameraUi`
-> `Query<&mut Transform, With<Camera3d>>` works
- `PerspectiveCameraBundle::new_3d()` and `PerspectiveCameraBundle::<Camera3d>::default()` contain the `Camera3d` marker
- `OrthographicCameraBundle::new_3d()` has `Camera3d`, `OrthographicCameraBundle::new_2d()` has `Camera2d`
- remove `ActiveCameras`, `ExtractedCameraNames`
- run 2d, 3d and ui passes for every camera of their respective marker
-> no custom setup for multiple windows example needed

**Open questions**
- do we need a replacement for `ActiveCameras`? What about a component `ActiveCamera { is_active: bool }` similar to `Visibility`?

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-03-12 00:41:06 +00:00
Robert Swain
0e821da704 bevy_render: Batch insertion for prepare_uniform_components (#4179)
# Objective

- Make insertion of uniform components faster

## Solution

- Use batch insertion in the prepare_uniform_components system
- Improves `many_cubes -- sphere` from ~42fps to ~43fps


Co-authored-by: François <mockersf@gmail.com>
2022-03-11 23:20:18 +00:00
robtfm
5af746457e fix cluster tiling calculations (#4148)
# Objective

fix cluster tilesize and tilecount calculations.
Fixes https://github.com/bevyengine/bevy/issues/4127 & https://github.com/bevyengine/bevy/issues/3596

## Solution

- calculate tilesize as smallest integers such that dimensions.xy() tiles will cover the screen
- calculate final dimensions as smallest integers such that final dimensions * tilesize will cover the screen

there is more cleanup that could be done in these functions. a future PR will likely remove the tilesize completely, so this is just a minimal change set to fix the current bug at small screen sizes

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-03-10 01:14:21 +00:00
Roman
2b11202614 fix mul_vec3 tranformation order: should be scale -> rotate -> translate (#3811)
# Objective

Lets say we need to rotate stretched object for this purpose we can created stretched `Child` and add as child to `Parent`, later we can rotate `Parent`, `Child` in this situation should rotate keeping it form, it is not the case with `SpriteBundle` currently. If you try to do it with `SpriteBundle` it will deform.

## Solution

My pull request fixes order of transformations to scale -> rotate -> translate, with this fix `SpriteBundle` behaves as expected in described rotation, without deformation. Here is quote from "Essential Mathematics for Games":

> Generally, the desired order we wish to use for these transforms is to scale first, then rotate, then translate. Scaling first gives us the scaling along the axes we expect. We can then rotate around the origin of the frame, and then translate it into place.

I'm must say when I was using `MaterialMesh2dBundle` it behaves correctly in both cases with `bevy main` and with my fix, don't know why, was not able to figure it out why there is difference.

here is code I was using for testing:
```rust
use bevy::{
    prelude::*,
    render::render_resource::{Extent3d, TextureDimension, TextureFormat},
    sprite::{MaterialMesh2dBundle, Mesh2dHandle},
};

fn main() {
    let mut app = App::new();
    app.insert_resource(ClearColor(Color::rgb(0.1, 0.2, 0.3)))
        .add_plugins(DefaultPlugins)
        .add_startup_system(setup);
    app.run();
}

fn setup(
    mut commands: Commands,
    mut images: ResMut<Assets<Image>>,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<ColorMaterial>>,
) {
    let mut c = OrthographicCameraBundle::new_2d();
    c.orthographic_projection.scale = 1.0 / 10.0;
    commands.spawn_bundle(c);
    // note: mesh somehow works for both variants
    // let quad: Mesh2dHandle = meshes.add(Mesh::from(shape::Quad::default())).into();
    // let child = commands
    //     .spawn_bundle(MaterialMesh2dBundle {
    //         mesh: quad.clone(),
    //         transform: Transform::from_translation(Vec3::new(0.0, 0.0, -1.0))
    //             .with_scale(Vec3::new(10.0, 1.0, 1.0)),
    //         material: materials.add(ColorMaterial::from(Color::BLACK)),
    //         ..Default::default()
    //     })
    //     .id();
    // commands
    //     .spawn_bundle(MaterialMesh2dBundle {
    //         mesh: quad,
    //         transform: Transform::from_rotation(Quat::from_rotation_z(0.78))
    //             .with_translation(Vec3::new(0.0, 0.0, 10.0)),
    //         material: materials.add(ColorMaterial::from(Color::WHITE)),
    //         ..Default::default()
    //     })
    //     .push_children(&[child]);

    let white = images.add(get_image(Color::rgb(1.0, 1.0, 1.0)));
    let black = images.add(get_image(Color::rgb(0.0, 0.0, 0.0)));
    let child = commands
        .spawn_bundle(SpriteBundle {
            texture: black,
            transform: Transform::from_translation(Vec3::new(0.0, 0.0, -1.0))
                .with_scale(Vec3::new(10.0, 1.0, 1.0)),
            ..Default::default()
        })
        .id();
    commands
        .spawn_bundle(SpriteBundle {
            texture: white,
            transform: Transform::from_rotation(Quat::from_rotation_z(0.78))
                .with_translation(Vec3::new(0.0, 0.0, 10.0)),
            ..Default::default()
        })
        .push_children(&[child]);
}

fn get_image(color: Color) -> Image {
    let mut bytes = Vec::with_capacity((1 * 1 * 4 * 4) as usize);
    let color = color.as_rgba_f32();
    bytes.extend(color[0].to_le_bytes());
    bytes.extend(color[1].to_le_bytes());
    bytes.extend(color[2].to_le_bytes());
    bytes.extend(1.0_f32.to_le_bytes());
    Image::new(
        Extent3d {
            width: 1,
            height: 1,
            depth_or_array_layers: 1,
        },
        TextureDimension::D2,
        bytes,
        TextureFormat::Rgba32Float,
    )
}

```

here is screenshot with `bevy main` and my fix:
![examples](https://user-images.githubusercontent.com/816292/151708304-c07c891e-da70-43f4-9c41-f85fa166a96d.png)
2022-03-08 05:47:36 +00:00
robtfm
244687a0bb Dynamic light clusters (#3968)
# Objective

provide some customisation for default cluster setup
avoid "cluster index lists is full" in all cases (using a strategy outlined by @superdump)

## Solution

Add ClusterConfig enum (which can be inserted into a view at any time) to allow specifying cluster setup with variants:
- None (do not do any light assignment - for views which do not require light info, e.g. minimaps etc)
- Single (one cluster)
- XYZ (explicit cluster counts in each dimension)
- FixedZ (most similar to current - specify Z-slices and total, then x and y counts are dynamically determined to give approximately square clusters based on current aspect ratio)
Defaults to FixedZ { total: 4096, z: 24 } which is similar to the current setup.

Per frame, estimate the number of indices that would be required for the current config and decrease the cluster counts / increase the cluster sizes in the x and y dimensions if the index list would be too small.

notes:

- I didn't put ClusterConfig in the camera bundles to avoid introducing a dependency from bevy_render to bevy_pbr. the ClusterConfig enum comes with a pbr-centric impl block so i didn't want to move that into bevy_render either.
- ~Might want to add None variant to cluster config for views that don't care about lights?~
- Not well tested for orthographic
- ~there's a cluster_muck branch on my repo which includes some diagnostics / a modified lighting example which may be useful for tyre-kicking~ (outdated, i will bring it up to date if required)

anecdotal timings:

FPS on the lighting demo is negligibly better (~5%), maybe due to a small optimisation constraining the light aabb to be in front of the camera
FPS on the lighting demo with 100 extra lights added is ~33% faster, and also renders correctly as the cluster index count is no longer exceeded
2022-03-08 04:56:42 +00:00
François
4add96b1be Cleanup doc / comments about changed defaults (#4144)
# Objective

- Update comment about default audio format
- remove doc about msaa in wasm
2022-03-08 02:11:59 +00:00
François
de2a47c2ba export TaskPoolThreadAssignmentPolicy (#4145)
# Objective

- Fix #2163
- Allow configuration of thread pools through `DefaultTaskPoolOptions`

## Solution

- `TaskPoolThreadAssignmentPolicy` was already public but not exported. Export it.
2022-03-08 01:54:36 +00:00
Gabriel Bourgeois
e41c5c212c Fix UI node Transform change detection (#4138)
# Objective

Fixes #4133 

## Solution

Add comparisons to make sure we don't dereference `Mut<>` in the two places where `Transform` is being mutated. `GlobalTransform` implementation already works properly so fixing Transform automatically fixed that as well.
2022-03-08 01:00:23 +00:00
dataphract
b4483dbfc8 perf: only recalculate frusta of changed lights (#4086)
## Objective

Currently, all directional and point lights have their viewing frusta recalculated every frame, even if they have not moved or been disabled/enabled.

## Solution

The relevant systems now make use of change detection to only update those lights whose viewing frusta may have changed.
2022-03-08 01:00:22 +00:00
Aevyrie
b3aff9a7b1 Add docs and common helper functions to Windows (#4107)
# Objective

- Improve documentation.
- Provide helper functions for common uses of `Windows` relating to getting the primary `Window`.
- Reduce repeated `Window` code.

# Solution

- Adds infallible `primary()` and `primary_mut()` functions with standard error text. This replaces the commonly used `get_primary().unwrap()` seen throughout bevy which has inconsistent or nonexistent error messages.
- Adds `scale_factor(WindowId)` to replace repeated code blocks throughout.

# Considerations

- The added functions can panic if the primary window does not exist.
    - It is very uncommon for the primary window to not exist, as seen by the regular use of `get_primary().unwrap()`. Most users will have a single window and will need to reference the primary window in their code multiple times.
    - The panic provides a consistent error message to make this class of error easy to spot from the panic text.
    - This follows the established standard of short names for infallible-but-unlikely-to-panic functions in bevy.
- Removes line noise for common usage of `Windows`.
2022-03-08 00:46:04 +00:00
Alix Bott
e36c9b6cf0 Add conversions from Color to u32 (#4088)
# Objective

- `Mesh::ATTRIBUTE_COLOR` expects colors as `u32`s but there is no function for easy conversion.
- See https://github.com/bevyengine/bevy/pull/4037#pullrequestreview-894448677

## Solution

- Added `Color::as_rgba_u32` and `Color::as_linear_rgba_u32`
2022-03-08 00:46:03 +00:00
josh65536
e3a3b5b9c2 Fixed the frustum-sphere collision and added tests (#4035)
# Objective

Fixes #3744 

## Solution

The old code used the formula `normal . center + d + radius <= 0` to determine if the sphere with center `center` and radius `radius` is outside the plane with normal `normal` and distance from origin `d`. This only works if `normal` is normalized, which is not necessarily the case. Instead, `normal` and `d` are both multiplied by some factor that `radius` isn't multiplied by. So the additional code multiplied `radius` by that factor.
2022-03-08 00:30:41 +00:00
Christian Hughes
c05ba23703 Add Reflect support for DMat3, DMat4, DQuat (#4128)
## Objective

A step towards `f64` `Transform`s (#1680). For now, I am rolling my own `Transform`. But in order to derive Reflect, I specifically need `DQuat` to be reflectable.

```rust
#[derive(Component, Reflect, Copy, Clone, PartialEq, Debug)]
#[reflect(Component, PartialEq)]
pub struct Transform {
    pub translation: DVec3,
    pub rotation: DQuat, // error: the trait `bevy::prelude::Reflect` is not implemented for `DQuat`
    pub scale: DVec3,
}
```

## Solution

I have added a `DQuat` impl for `Reflect` alongside the other glam impls. I've also added impls for `DMat3` and `DMat4` to match.
2022-03-08 00:14:21 +00:00
Aevyrie
2d674e7c3e Reduce power usage with configurable event loop (#3974)
# Objective

- Reduce power usage for games when not focused.
- Reduce power usage to ~0 when a desktop application is minimized (opt-in).
- Reduce power usage when focused, only updating on a `winit` event, or the user sends a redraw request. (opt-in)

https://user-images.githubusercontent.com/2632925/156904387-ec47d7de-7f06-4c6f-8aaf-1e952c1153a2.mp4

Note resource usage in the Task Manager in the above video.

## Solution

- Added a type `UpdateMode` that allows users to specify how the winit event loop is updated, without exposing winit types.
- Added two fields to `WinitConfig`, both with the `UpdateMode` type. One configures how the application updates when focused, and the other configures how the application behaves when it is not focused. Users can modify this resource manually to set the type of event loop control flow they want.
- For convenience, two functions were added to `WinitConfig`, that provide reasonable presets: `game()` (default) and `desktop_app()`.
    - The `game()` preset, which is used by default, is unchanged from current behavior with one exception: when the app is out of focus the app updates at a minimum of 10fps, or every time a winit event is received. This has a huge positive impact on power use and responsiveness on my machine, which will otherwise continue running the app at many hundreds of fps when out of focus or minimized.
    - The `desktop_app()` preset is fully reactive, only updating when user input (winit event) is supplied or a `RedrawRequest` event is sent. When the app is out of focus, it only updates on `Window` events - i.e. any winit event that directly interacts with the window. What this means in practice is that the app uses *zero* resources when minimized or not interacted with, but still updates fluidly when the app is out of focus and the user mouses over the application.
- Added a `RedrawRequest` event so users can force an update even if there are no events. This is useful in an application when you want to, say, run an animation even when the user isn't providing input.
- Added an example `low_power` to demonstrate these changes

## Usage

Configuring the event loop:
```rs
use bevy::winit::{WinitConfig};
// ...
.insert_resource(WinitConfig::desktop_app()) // preset
// or
.insert_resource(WinitConfig::game()) // preset
// or
.insert_resource(WinitConfig{ .. }) // manual
```

Requesting a redraw:
```rs
use bevy:🪟:RequestRedraw;
// ...
fn request_redraw(mut event: EventWriter<RequestRedraw>) {
    event.send(RequestRedraw);
}
```

## Other details

- Because we have a single event loop for multiple windows, every time I've mentioned "focused" above, I more precisely mean, "if at least one bevy window is focused".
- Due to a platform bug in winit (https://github.com/rust-windowing/winit/issues/1619), we can't simply use `Window::request_redraw()`. As a workaround, this PR will temporarily set the window mode to `Poll` when a redraw is requested. This is then reset to the user's `WinitConfig` setting on the next frame.
2022-03-07 23:32:05 +00:00
dataphract
cba9bcc7ba improve error messages for render graph runner (#3930)
# Objective

Currently, errors in the render graph runner are exposed via a `Result::unwrap()` panic message, which dumps the debug representation of the error.

## Solution

This PR updates `render_system` to log the chain of errors, followed by an explicit panic:

```
ERROR bevy_render::renderer: Error running render graph:
ERROR bevy_render::renderer: > encountered an error when running a sub-graph
ERROR bevy_render::renderer: > tried to pass inputs to sub-graph "outline_graph", which has no input slots
thread 'main' panicked at 'Error running render graph: encountered an error when running a sub-graph', /[redacted]/bevy/crates/bevy_render/src/renderer/mod.rs:44:9
```

Some errors' `Display` impls (via `thiserror`) have also been updated to provide more detail about the cause of the error.
2022-03-07 09:09:24 +00:00
Harry Barber
cf46baa172 Add clear_schedule (#3941)
# Objective

Adds `clear_schedule` method to `State`.

Closes #3932
2022-03-05 21:53:17 +00:00
François
baae97d002 iter_mut on Assets: send modified event only when asset is iterated over (#3565)
# Objective

- `Assets<T>::iter_mut` sends `Modified` event for all assets first, then returns the iterator
- This means that events could be sent for assets that would not have been mutated if iteration was stopped before

## Solution

- Send `Modified` event when assets are iterated over.


Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
2022-03-05 21:25:30 +00:00
Robert Bragg
1d5145fd64 StandardMaterial: expose a cull_mode option (#3982)
This makes it possible for materials to configure front or
back face culling, or disable culling.

Initially I looked at specializing the Mesh which currently
controls this state but conceptually it seems more appropriate
to control this at the material level, not the mesh level.

_Just for reference this also seems to be consistent with Unity
where materials/shaders can configure the culling mode between
front/back/off - as opposed to configuring any culling state
when importing a mesh._

After some archaeology, trying to understand how this might
relate to the existing 'double_sided' option, it was determined
that double_sided is a more high level lighting option originally
from Filament that will cause the normals for back faces to be
flipped.

For sake of avoiding complexity, but keeping control this
currently keeps the options orthogonal, and adds some clarifying
documentation for `double_sided`. This won't affect any existing
apps since there hasn't been a way to disable backface culling
up until now, so the option was essentially redundant.

double_sided support could potentially be updated to imply
disabling of backface culling.

For reference https://github.com/bevyengine/bevy/pull/3734/commits also looks at exposing cull mode control. I think the main difference here is that this patch handles RenderPipelineDescriptor specialization directly within the StandardMaterial implementation instead of communicating info back to the Mesh via the `queue_material_meshes` system.

With the way material.rs builds up the final RenderPipelineDescriptor first by calling specialize for the MeshPipeline followed by specialize for the material then it seems like we have a natural place to override anything in the descriptor that's first configured for the mesh state.
2022-03-05 03:37:23 +00:00
robtfm
575ea81d7b add Visibility for lights (#3958)
# Objective

Add Visibility for lights

## Solution

- add Visibility to PointLightBundle and DirectionLightBundle
- filter lights used by Visibility.is_visible

note: includes changes from #3916 due to overlap, will be cleaner after that is merged
2022-03-05 03:23:01 +00:00
Mika
72bb38cad5 Example of module-level log usage and RUST_LOG usage in main doc (#3919)
# Objective

When developing plugins, I very often come up to the need to have logging information printed out. The exact syntax is a bit cryptic, and takes some time to find the documentation.

Also a minor typo fix in `It has the same syntax as` part

## Solution

Adding a direct example in the module level information for both:

1. Enabling a specific level (`trace` in the example) for a module and all its subsystems at App init 
2. Doing the same from console, when launching the application
2022-03-05 03:00:31 +00:00
Carter Anderson
b6a647cc01 default() shorthand (#4071)
Adds a `default()` shorthand for `Default::default()` ... because life is too short to constantly type `Default::default()`.

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

#[derive(Default)]
struct Foo {
  bar: usize,
  baz: usize,
}

// Normally you would do this:
let foo = Foo {
  bar: 10,
  ..Default::default()
};

// But now you can do this:
let foo = Foo {
  bar: 10,
  ..default()
};
```

The examples have been adapted to use `..default()`. I've left internal crates as-is for now because they don't pull in the bevy prelude, and the ergonomics of each case should be considered individually.
2022-03-01 20:52:09 +00:00
pubrrr
caf6611c62 remove Events from bevy_app, they now live in bevy_ecs (#4066)
# Objective

Fixes #4064.

## Solution

- remove Events from bevy_app
2022-03-01 19:33:56 +00:00
robtfm
3f6068da3d fix issues with too many point lights (#3916)
# Objective

fix #3915 

## Solution

the issues are caused by
- lights are assigned to clusters before being filtered down to MAX_POINT_LIGHTS, leading to cluster counts potentially being too high
- after fixing the above, packing the count into 8 bits still causes overflow with exactly 256 lights affecting a cluster

to fix:

```assign_lights_to_clusters```
- limit extracted lights to MAX_POINT_LIGHTS, selecting based on shadow-caster & intensity (if required)
- warn if MAX_POINT_LIGHT count is exceeded

```prepare_lights```
- limit the lights assigned to a cluster to CLUSTER_COUNT_MASK (which is 1 less than MAX_POINT_LIGHTS) to avoid overflowing into the offset bits

notes:
- a better solution to the overflow may be to use more than 8 bits for cluster_count (the comment states only 14 of the remaining 24 bits are used for the offset). this would touch more of the code base but i'm happy to try if it has some benefit.
- intensity is only one way to select lights. it may be worth allowing user configuration of the light filtering, but i can't see a clean way to do that
2022-03-01 10:17:41 +00:00
François
b21c69c60e Audio control - play, pause, volume, speed, loop (#3948)
# Objective

- Add ways to control how audio is played

## Solution

- playing a sound will return a (weak) handle to an asset that can be used to control playback
- if the asset is dropped, it will detach the sink (same behaviour as now)
2022-03-01 01:12:11 +00:00
François
258f495352 log spans on panic when trace is enabled (#3848)
# Objective

- Help debug panics

## Solution

- Insert a custom panic hook when trace is enabled that will log spans

example when running a command on a despawned entity

before:
```
thread 'main' panicked at 'Could not add a component (of type `panic::Marker`) to entity 1v0 because it doesn't exist in this World.
If this command was added to a newly spawned entity, ensure that you have not despawned that entity within the same stage.
This may have occurred due to system order ambiguity, or if the spawning system has multiple command buffers', /bevy/crates/bevy_ecs/src/system/commands/mod.rs:664:13
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```


after:
```
   0: bevy_ecs::schedule::stage::system_commands
           with name="panic::my_bad_system"
             at crates/bevy_ecs/src/schedule/stage.rs:871
   1: bevy_ecs::schedule::stage
           with name=Update
             at crates/bevy_ecs/src/schedule/mod.rs:340
   2: bevy_app::app::frame
             at crates/bevy_app/src/app.rs:111
   3: bevy_app::app::bevy_app
             at crates/bevy_app/src/app.rs:126
thread 'main' panicked at 'Could not add a component (of type `panic::Marker`) to entity 1v0 because it doesn't exist in this World.
If this command was added to a newly spawned entity, ensure that you have not despawned that entity within the same stage.
This may have occurred due to system order ambiguity, or if the spawning system has multiple command buffers', /bevy/crates/bevy_ecs/src/system/commands/mod.rs:664:13
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```
2022-02-28 22:27:20 +00:00
Robert Swain
786654307d bevy_pbr: Optimize assign_lights_to_clusters (#3984)
# Objective

- Optimize assign_lights_to_clusters

## Solution

- Avoid inserting entities into hash sets in inner loops when it is known they will be inserted in at least one iteration of the loop.
- Use a Vec instead of a hash set where the set is not needed
- Avoid explicit calculation of the cluster_index from x,y,z coordinates, instead using row and column offsets and just adding z in the inner loop 
- These changes cut the time spent in the system roughly in half
2022-02-28 22:02:06 +00:00
Kurt Kühnert
40b36927f5 Expose draw indirect (#4056)
# Objective

- Currently there is now way of making an indirect draw call from a tracked render pass.
- This is a very useful feature for GPU based rendering.

## Solution

- Expose the `draw_indirect` and `draw_indexed_indirect` methods from the wgpu `RenderPass` in the `TrackedRenderPass`.

## Alternative

- #3595: Expose the underlying `RenderPass` directly
2022-02-28 10:26:49 +00:00
Alice Cecile
557ab9897a Make get_resource (and friends) infallible (#4047)
# Objective

- In the large majority of cases, users were calling `.unwrap()` immediately after `.get_resource`.
- Attempting to add more helpful error messages here resulted in endless manual boilerplate (see #3899 and the linked PRs).

## Solution

- Add an infallible variant named `.resource` and so on.
- Use these infallible variants over `.get_resource().unwrap()` across the code base.

## Notes

I did not provide equivalent methods on `WorldCell`, in favor of removing it entirely in #3939.

## Migration Guide

Infallible variants of `.get_resource` have been added that implicitly panic, rather than needing to be unwrapped.

Replace `world.get_resource::<Foo>().unwrap()` with `world.resource::<Foo>()`.

## Impact

- `.unwrap` search results before: 1084
- `.unwrap` search results after: 942
- internal `unwrap_or_else` calls added: 4
- trivial unwrap calls removed from tests and code: 146
- uses of the new `try_get_resource` API: 11
- percentage of the time the unwrapping API was used internally: 93%
2022-02-27 22:37:18 +00:00
Jupp56
b697e73c3d Enhanced par_for_each and par_for_each_mut docs (#4039)
# Objective
Continuation of  #2663 due to git problems - better documentation for Query::par_for_each and par_for_each_mut

## Solution
Going into more detail about the function parameters
2022-02-25 23:57:01 +00:00
MrGVSV
1fa54c200f Updated visibility of reflected trait (#4034)
# Objective

The `#[reflect_trait]` macro did not maintain the visibility of its trait. It also did not make its accessor methods public, which made them inaccessible outside the current module.

## Solution

Made the `Reflect***` struct match the visibility of its trait and made both the `get` and `get_mut` methods always public.
2022-02-25 07:05:51 +00:00
Daniel McNab
c1a4a2f6c5 Remove the config api (#3633)
# Objective

- Fix the ugliness of the `config` api. 
- Supercedes #2440, #2463, #2491

## Solution

- Since #2398, capturing closure systems have worked.
- Use those instead where we needed config before
- Remove the rest of the config api. 
- Related: #2777
2022-02-25 03:10:59 +00:00
James Liu
95bc99fd37 Implement Reflect for missing Vec* types (#4028)
# Objective
`Vec3A` is does not implement `Reflect`. This is generally useful for `Reflect` derives using `Vec3A` fields, and may speed up some animation blending use cases.

## Solution
Extend the existing macro uses to include `Vec3A`.
2022-02-24 08:12:27 +00:00
Aevyrie
a2d49f4a69 Make WinitWindows non send (#4027)
# Objective

- Fixes #4010, as well as any similar issues in this class.
- Winit functions used outside of the main thread can cause the application to unexpectedly hang.

## Solution

- Make the `WinitWindows` resource `!Send`.
- This ensures that any systems that use `WinitWindows` must either be exclusive (run on the main thread), or the resource is explicitly marked with the `NonSend` parameter in user systems.
2022-02-24 01:40:02 +00:00
Dusty DeWeese
81d57e129b Add capability to render to a texture (#3412)
# Objective

Will fix #3377 and #3254

## Solution

Use an enum to represent either a `WindowId` or `Handle<Image>` in place of `Camera::window`.


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-02-24 00:40:24 +00:00
Vladyslav Batyrenko
ba6b74ba20 Implement WorldQuery derive macro (#2713)
# Objective

- Closes #786
- Closes #2252
- Closes #2588

This PR implements a derive macro that allows users to define their queries as structs with named fields.

## Example

```rust
#[derive(WorldQuery)]
#[world_query(derive(Debug))]
struct NumQuery<'w, T: Component, P: Component> {
    entity: Entity,
    u: UNumQuery<'w>,
    generic: GenericQuery<'w, T, P>,
}

#[derive(WorldQuery)]
#[world_query(derive(Debug))]
struct UNumQuery<'w> {
    u_16: &'w u16,
    u_32_opt: Option<&'w u32>,
}

#[derive(WorldQuery)]
#[world_query(derive(Debug))]
struct GenericQuery<'w, T: Component, P: Component> {
    generic: (&'w T, &'w P),
}

#[derive(WorldQuery)]
#[world_query(filter)]
struct NumQueryFilter<T: Component, P: Component> {
    _u_16: With<u16>,
    _u_32: With<u32>,
    _or: Or<(With<i16>, Changed<u16>, Added<u32>)>,
    _generic_tuple: (With<T>, With<P>),
    _without: Without<Option<u16>>,
    _tp: PhantomData<(T, P)>,
}

fn print_nums_readonly(query: Query<NumQuery<u64, i64>, NumQueryFilter<u64, i64>>) {
    for num in query.iter() {
        println!("{:#?}", num);
    }
}

#[derive(WorldQuery)]
#[world_query(mutable, derive(Debug))]
struct MutNumQuery<'w, T: Component, P: Component> {
    i_16: &'w mut i16,
    i_32_opt: Option<&'w mut i32>,
}

fn print_nums(mut query: Query<MutNumQuery, NumQueryFilter<u64, i64>>) {
    for num in query.iter_mut() {
        println!("{:#?}", num);
    }
}
```

## TODOs:
- [x] Add support for `&T` and `&mut T`
  - [x] Test
- [x] Add support for optional types
  - [x] Test
- [x] Add support for `Entity`
  - [x] Test
- [x] Add support for nested `WorldQuery`
  - [x] Test
- [x] Add support for tuples
  - [x] Test
- [x] Add support for generics
  - [x] Test
- [x] Add support for query filters
  - [x] Test
- [x] Add support for `PhantomData`
  - [x] Test
- [x] Refactor `read_world_query_field_type_info`
- [x] Properly document `readonly` attribute for nested queries and the static assertions that guarantee safety
  - [x] Test that we never implement `ReadOnlyFetch` for types that need mutable access
  - [x] Test that we insert static assertions for nested `WorldQuery` that a user marked as readonly
2022-02-24 00:19:49 +00:00
Carter Anderson
e369a8ad51 Mesh vertex buffer layouts (#3959)
This PR makes a number of changes to how meshes and vertex attributes are handled, which the goal of enabling easy and flexible custom vertex attributes:
* Reworks the `Mesh` type to use the newly added `VertexAttribute` internally
  * `VertexAttribute` defines the name, a unique `VertexAttributeId`, and a `VertexFormat`
  *  `VertexAttributeId` is used to produce consistent sort orders for vertex buffer generation, replacing the more expensive and often surprising "name based sorting"  
  * Meshes can be used to generate a `MeshVertexBufferLayout`, which defines the layout of the gpu buffer produced by the mesh. `MeshVertexBufferLayouts` can then be used to generate actual `VertexBufferLayouts` according to the requirements of a specific pipeline. This decoupling of "mesh layout" vs "pipeline vertex buffer layout" is what enables custom attributes. We don't need to standardize _mesh layouts_ or contort meshes to meet the needs of a specific pipeline. As long as the mesh has what the pipeline needs, it will work transparently. 
* Mesh-based pipelines now specialize on `&MeshVertexBufferLayout` via the new `SpecializedMeshPipeline` trait (which behaves like `SpecializedPipeline`, but adds `&MeshVertexBufferLayout`). The integrity of the pipeline cache is maintained because the `MeshVertexBufferLayout` is treated as part of the key (which is fully abstracted from implementers of the trait ... no need to add any additional info to the specialization key).    
* Hashing `MeshVertexBufferLayout` is too expensive to do for every entity, every frame. To make this scalable, I added a generalized "pre-hashing" solution to `bevy_utils`: `Hashed<T>` keys and `PreHashMap<K, V>` (which uses `Hashed<T>` internally) . Why didn't I just do the quick and dirty in-place "pre-compute hash and use that u64 as a key in a hashmap" that we've done in the past? Because its wrong! Hashes by themselves aren't enough because two different values can produce the same hash. Re-hashing a hash is even worse! I decided to build a generalized solution because this pattern has come up in the past and we've chosen to do the wrong thing. Now we can do the right thing! This did unfortunately require pulling in `hashbrown` and using that in `bevy_utils`, because avoiding re-hashes requires the `raw_entry_mut` api, which isn't stabilized yet (and may never be ... `entry_ref` has favor now, but also isn't available yet). If std's HashMap ever provides the tools we need, we can move back to that. Note that adding `hashbrown` doesn't increase our dependency count because it was already in our tree. I will probably break these changes out into their own PR.
* Specializing on `MeshVertexBufferLayout` has one non-obvious behavior: it can produce identical pipelines for two different MeshVertexBufferLayouts. To optimize the number of active pipelines / reduce re-binds while drawing, I de-duplicate pipelines post-specialization using the final `VertexBufferLayout` as the key.  For example, consider a pipeline that needs the layout `(position, normal)` and is specialized using two meshes: `(position, normal, uv)` and `(position, normal, other_vec2)`. If both of these meshes result in `(position, normal)` specializations, we can use the same pipeline! Now we do. Cool!

To briefly illustrate, this is what the relevant section of `MeshPipeline`'s specialization code looks like now:

```rust
impl SpecializedMeshPipeline for MeshPipeline {
    type Key = MeshPipelineKey;

    fn specialize(
        &self,
        key: Self::Key,
        layout: &MeshVertexBufferLayout,
    ) -> RenderPipelineDescriptor {
        let mut vertex_attributes = vec![
            Mesh::ATTRIBUTE_POSITION.at_shader_location(0),
            Mesh::ATTRIBUTE_NORMAL.at_shader_location(1),
            Mesh::ATTRIBUTE_UV_0.at_shader_location(2),
        ];

        let mut shader_defs = Vec::new();
        if layout.contains(Mesh::ATTRIBUTE_TANGENT) {
            shader_defs.push(String::from("VERTEX_TANGENTS"));
            vertex_attributes.push(Mesh::ATTRIBUTE_TANGENT.at_shader_location(3));
        }

        let vertex_buffer_layout = layout
            .get_layout(&vertex_attributes)
            .expect("Mesh is missing a vertex attribute");
```

Notice that this is _much_ simpler than it was before. And now any mesh with any layout can be used with this pipeline, provided it has vertex postions, normals, and uvs. We even got to remove `HAS_TANGENTS` from MeshPipelineKey and `has_tangents` from `GpuMesh`, because that information is redundant with `MeshVertexBufferLayout`.

This is still a draft because I still need to:

* Add more docs
* Experiment with adding error handling to mesh pipeline specialization (which would print errors at runtime when a mesh is missing a vertex attribute required by a pipeline). If it doesn't tank perf, we'll keep it.
* Consider breaking out the PreHash / hashbrown changes into a separate PR.
* Add an example illustrating this change
* Verify that the "mesh-specialized pipeline de-duplication code" works properly

Please dont yell at me for not doing these things yet :) Just trying to get this in peoples' hands asap.

Alternative to #3120
Fixes #3030


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-02-23 23:21:13 +00:00
François
b3a2cbbc98 remove external_type_uuid macro (#4018)
# Objective

- Macro `external_type_uuid` seems unused
- https://docs.rs/bevy/latest/bevy/reflect/macro.external_type_uuid.html

## Solution

- Remove it and see if it was? There is a derive for the same trait that is used everywhere (`#[derive(TypeUuid)]`) and is a better api
2022-02-22 23:21:39 +00:00
François
e4203c3925 shader preprocessor - do not import if scope is not valid (#4012)
# Objective

- fix #4011 
- imports are not limited by the current `ifdef` they are in

## Solution

- process imports only if the current scope is enabled
2022-02-22 20:21:04 +00:00
James Liu
5afda8df6f Fix all_tuples macro for non-0/1 starts (#4002)
# Objective
`all_tuples` panics when the start count is set to anything other than 0 or 1. Fix this bug.

## Solution
Originally part of #2381, this PR fixes the slice indexing used by the proc macro.
2022-02-21 23:49:08 +00:00
Patrik Buhring
fb8af3aec3 Update Hexasphere to 7.0.0 (#4001)
The new update includes wireframe generation capabilities. 

I didn't integrate that in this PR, however with some guidance, I'd be happy to do so.
2022-02-21 23:49:07 +00:00
Kirillov Kirill
b4bf5b5d87 Fix glTF perspective camera projection (#4006)
# Objective

- Fixes #4005 

## Solution

- Include the `near` and `far` clipping values from the perspective projection in the `Camera` struct; before that, they were both being defaulted to 0.
2022-02-21 23:29:32 +00:00
KDecay
544b6dfb86 Change default ColorMaterial color to white (#3981)
# Context

I wanted to add a `texture` to my `ColorMaterial` without explicitly adding a `color`. To do this I used `..Default::default()` which in turn gave me unexpected results. I was expecting that my texture would render without any color modifications, but to my surprise it got rendered in a purple tint (`Color::rgb(1.0, 0.0, 1.0)`). To fix this I had to explicitly define the `color` using `color: Color::WHITE`.

## What I wanted to use

```rust
commands
    .spawn_bundle(MaterialMesh2dBundle {
        mesh: mesh_handle.clone().into(),
        transform: Transform::default().with_scale(Vec3::splat(8.)),
        material: materials.add(ColorMaterial {
            texture: Some(texture_handle.clone()),
            ..Default::default() // here
        }),
        ..Default::default()
    })
```

![image](https://user-images.githubusercontent.com/75334794/154765141-4a8161ce-4ec8-4687-b7d5-18ddf1b58660.png)

## What I had to use instead

```rust
commands
    .spawn_bundle(MaterialMesh2dBundle {
        mesh: mesh_handle.clone().into(),
        transform: Transform::default().with_scale(Vec3::splat(8.)),
        material: materials.add(ColorMaterial {
            texture: Some(texture_handle.clone()),
            color: Color::WHITE, // here
        }),
        ..Default::default()
    })
```

![image](https://user-images.githubusercontent.com/75334794/154765225-f1508b41-9d5b-4f0c-af7b-e89c1a82d85b.png)
2022-02-19 22:12:13 +00:00
Carter Anderson
98938a8555 Internal Asset Hot Reloading (#3966)
Adds "hot reloading" of internal assets, which is normally not possible because they are loaded using `include_str` / direct Asset collection access.

This is accomplished via the following:
* Add a new `debug_asset_server` feature flag
* When that feature flag is enabled, create a second App with a second AssetServer that points to a configured location (by default the `crates` folder). Plugins that want to add hot reloading support for their assets can call the new `app.add_debug_asset::<T>()` and `app.init_debug_asset_loader::<T>()` functions.
* Load "internal" assets using the new `load_internal_asset` macro. By default this is identical to the current "include_str + register in asset collection" approach. But if the `debug_asset_server` feature flag is enabled, it will also load the asset dynamically in the debug asset server using the file path. It will then set up a correlation between the "debug asset" and the "actual asset" by listening for asset change events.

This is an alternative to #3673. The goal was to keep the boilerplate and features flags to a minimum for bevy plugin authors, and allow them to home their shaders near relevant code. 

This is a draft because I haven't done _any_ quality control on this yet. I'll probably rename things and remove a bunch of unwraps. I just got it working and wanted to use it to start a conversation.

Fixes #3660
2022-02-18 22:56:57 +00:00
Carter Anderson
e9f52b9dd2 Move import_path definitions into shader source (#3976)
This enables shaders to (optionally) define their import path inside their source. This has a number of benefits:

1. enables users to define their own custom paths directly in their assets
2. moves the import path "close" to the asset instead of centralized in the plugin definition, which seems "better" to me. 
3. makes "internal hot shader reloading" way more reasonable (see #3966)
4. logically opens the door to importing "parts" of a shader by defining "import_path blocks".

```rust
#define_import_path bevy_pbr::mesh_struct

struct Mesh {
    model: mat4x4<f32>;
    inverse_transpose_model: mat4x4<f32>;
    // 'flags' is a bit field indicating various options. u32 is 32 bits so we have up to 32 options.
    flags: u32;
};

let MESH_FLAGS_SHADOW_RECEIVER_BIT: u32 = 1u;
```
2022-02-18 21:54:03 +00:00
Carter Anderson
b3a1db60f2 Proper prehashing (#3963)
For some keys, it is too expensive to hash them on every lookup. Historically in Bevy, we have regrettably done the "wrong" thing in these cases (pre-computing hashes, then re-hashing them) because Rust's built in hashed collections don't give us the tools we need to do otherwise. Doing this is "wrong" because two different values can result in the same hash. Hashed collections generally get around this by falling back to equality checks on hash collisions. You can't do that if the key _is_ the hash. Additionally, re-hashing a hash increase the odds of collision!
 
#3959 needs pre-hashing to be viable, so I decided to finally properly solve the problem. The solution involves two different changes:

1. A new generalized "pre-hashing" solution in bevy_utils: `Hashed<T>` types, which store a value alongside a pre-computed hash. And `PreHashMap<K, V>` (which uses `Hashed<T>` internally) . `PreHashMap` is just an alias for a normal HashMap that uses `Hashed<T>` as the key and a new `PassHash` implementation as the Hasher. 
2. Replacing the `std::collections` re-exports in `bevy_utils` with equivalent `hashbrown` impls. Avoiding re-hashes requires the `raw_entry_mut` api, which isn't stabilized yet (and may never be ... `entry_ref` has favor now, but also isn't available yet). If std's HashMap ever provides the tools we need, we can move back to that. The latest version of `hashbrown` adds support for the `entity_ref` api, so we can move to that in preparation for an std migration, if thats the direction they seem to be going in. Note that adding hashbrown doesn't increase our dependency count because it was already in our tree.

In addition to providing these core tools, I also ported the "table identity hashing" in `bevy_ecs` to `raw_entry_mut`, which was a particularly egregious case.

The biggest outstanding case is `AssetPathId`, which stores a pre-hash. We need AssetPathId to be cheaply clone-able (and ideally Copy), but `Hashed<AssetPath>` requires ownership of the AssetPath, which makes cloning ids way more expensive. We could consider doing `Hashed<Arc<AssetPath>>`, but cloning an arc is still a non-trivial expensive that needs to be considered. I would like to handle this in a separate PR. And given that we will be re-evaluating the Bevy Assets implementation in the very near future, I'd prefer to hold off until after that conversation is concluded.
2022-02-18 03:26:01 +00:00
Robert Swain
936468aa1e bevy_render: Use RenderDevice to get limits/features and expose AdapterInfo (#3931)
# Objective

- `WgpuOptions` is mutated to be updated with the actual device limits and features, but this information is readily available to both the main and render worlds through the `RenderDevice` which has .limits() and .features() methods
- Information about the adapter in terms of its name, the backend in use, etc were not being exposed but have clear use cases for being used to take decisions about what rendering code to use. For example, if something works well on AMD GPUs but poorly on Intel GPUs. Or perhaps something works well in Vulkan but poorly in DX12.

## Solution

- Stop mutating `WgpuOptions `and don't insert the updated values into the main and render worlds
- Return `AdapterInfo` from `initialize_renderer` and insert it into the main and render worlds
- Use `RenderDevice` limits in the lighting code that was using `WgpuOptions.limits`.
- Renamed `WgpuOptions` to `WgpuSettings`
2022-02-16 21:17:37 +00:00
Sliman4
d3e526bfc0 Add FocusPolicy to NodeBundle and ImageBundle (#3952)
# Objective
`FocusPolicy` allows tracking `Interaction` of a parent node when a player hovers/clicks at the child node, and I see no reason why it shouldn't exist in these 2 nodes.

Resolves #2488

## Solution
Add it!

In the tracking system it's used as `Option`: e749ee786c/crates/bevy_ui/src/focus.rs (L71) and then it treats it as `Block` if it's not present: e749ee786c/crates/bevy_ui/src/focus.rs (L162) and the default value is e749ee786c/crates/bevy_ui/src/focus.rs (L47-L51) so it should be compatible with all existing UIs that use `..Default::default()`
2022-02-15 22:31:51 +00:00
Alice Cecile
330160cf14 SystemState usage docs (#3783)
# Objective

- `SystemStates` rock for dealing with exclusive world access, but are hard to figure out how to use.
- Fixes #3341.

## Solution

- Clearly document how to use `SystemState`, and why they're useful as an end-user.
2022-02-15 21:53:52 +00:00
danieleades
d8974e7c3d small and mostly pointless refactoring (#2934)
What is says on the tin.

This has got more to do with making `clippy` slightly more *quiet* than it does with changing anything that might greatly impact readability or performance.

that said, deriving `Default` for a couple of structs is a nice easy win
2022-02-13 22:33:55 +00:00
Robert Swain
803e8cdf80 bevy_render: Support overriding wgpu features and limits (#3912)
# Objective

- Support overriding wgpu features and limits that were calculated from default values or queried from the adapter/backend.
- Fixes #3686

## Solution

- Add `disabled_features: Option<wgpu::Features>` to `WgpuOptions`
- Add `constrained_limits: Option<wgpu::Limits>` to `WgpuOptions`
- After maybe obtaining updated features and limits from the adapter/backend in the case of `WgpuOptionsPriority::Functionality`, enable the `WgpuOptions` `features`, disable the `disabled_features`, and constrain the `limits` by `constrained_limits`.
  - Note that constraining the limits means for `wgpu::Limits` members named `max_.*` we take the minimum of that which was configured/queried for the backend/adapter and the specified constrained limit value. This means the configured/queried value is used if the constrained limit is larger as that is as much as the device/API supports, or the constrained limit value is used if it is smaller as we are imposing an artificial constraint. For members named `min_.*` we take the maximum instead. For example, a minimum stride might be 256 but we set constrained limit value of 1024, then 1024 is the more conservative value. If the constrained limit value were 16, then 256 would be the more conservative.
2022-02-13 04:24:52 +00:00
Carter Anderson
e749ee786c Fix ui interactions when cursor disappears suddenly (#3926)
On platforms like wasm (on mobile) the cursor can disappear suddenly (ex: the user releases their finger from the screen). This causes the undesirable behavior in #3752. These changes make the UI handler properly handle this case.

Fixes #3752
Alternative to #3599
2022-02-13 01:49:34 +00:00
dataphract
5bb4201f2e add informative panic message when adding render commands to a DrawFunctions that does not exist (#3924)
# Objective

If a user attempts to `.add_render_command::<P, C>()` on a world that does not contain `DrawFunctions<P>`, the engine panics with a generic `Option::unwrap` message:

```
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', /[redacted]/bevy/crates/bevy_render/src/render_phase/draw.rs:318:76
```

## Solution

This PR adds a panic message describing the problem:

```
thread 'main' panicked at 'DrawFunctions<outline::MeshStencil> must be added to the world as a resource before adding render commands to it', /[redacted]/bevy/crates/bevy_render/src/render_phase/draw.rs:322:17
```
2022-02-13 00:14:37 +00:00
Jakob Hellermann
d305e4f026 only use unique type UUIDs (#3579)
Out of curiosity I ran `rg -F -I '#[uuid = "' | sort` to see if there were any duplicate UUIDs, and they were. Now there aren't any.
2022-02-12 19:58:02 +00:00
ShadowCurse
62329f7fda Useful error message when two assets have the save UUID (#3739)
# Objective
Fixes #2610 and #3731

## Solution

Added check for TYPE_UUID duplication in  `register_asset_type` with an error message
2022-02-12 19:41:35 +00:00
Robert Swain
0ccb9dd07e bevy_render: Fix Quad flip (#3741)
# Objective

The documentation was unclear but it seemed like it was intended to _only_ flip the texture coordinates of the quad. However, it was also swapping the vertex positions, which resulted in inverted winding order so the front became a back face, and the normal was pointing into the face instead of out of it.

## Solution

- This change makes the only difference the UVs being horizontally flipped.
2022-02-12 00:46:04 +00:00
Rob Parrett
6475268351 Fix hardcoded texture bind group index in bevy_ui (#3905)
# Objective

While looking at #3896, I noticed the same error in the equivalent location in `bevy_ui`.

## Solution

Fix it in the same way.
2022-02-12 00:22:10 +00:00
devjobe
9a7852db0f Fix SetSpriteTextureBindGroup to use index (#3896)
# Objective

Fix `SetSpriteTextureBindGroup` to use index instead of hard coded 1.
Fixes #3895 

## Solution

1 -> I


Co-authored-by: devjobe <git@devjobe.com>
2022-02-08 23:18:11 +00:00
Alice Cecile
bdbf626341 Implement init_resource for Commands and World (#3079)
# Objective

- Fixes #3078
- Fixes #1397

## Solution

- Implement Commands::init_resource.
- Also implement for World, for consistency and to simplify internal structure.
- While we're here, clean up some of the docs for Command and World resource modification.
2022-02-08 23:04:19 +00:00
Loch Wansbrough
56b0e88b53 Add view transform to view uniform (#3885)
(cherry picked from commit de943381bd2a8b242c94db99e6c7bbd70006d7c3)

# Objective

The view uniform lacks view transform information. The inverse transform is currently provided but this is not sufficient if you do not have access to an `inverse` function (such as in WGSL).

## Solution

Grab the view transform, put it in the view uniform, use the same matrix to compute the inverse as well.
2022-02-08 04:14:34 +00:00
Ryo Hirayama
1e049a651b Fix type mismatch error with latest winit (#3883)
# Objective

When I use the latest winit with bevy main, I got this error.
```
error[E0308]: mismatched types
   --> /Users/ryo/.cargo/git/checkouts/bevy-f7ffde730c324c74/b13f238/crates/bevy_winit/src/lib.rs:191:5
    |
191 |     event_loop.run_return(event_handler)
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found `i32`
    |
help: consider using a semicolon here
    |
191 |     event_loop.run_return(event_handler);
    |                                         +
help: try adding a return type
    |
187 | -> i32 where
    | ++++++
```

In [this commit](a52f755ce8), the signature of `run_return` was changed in winit.

## Solution

This tiny PR does not add support for exit code, but makes compilation successful.
2022-02-08 04:14:33 +00:00
Daniel McNab
6615b7bf64 Deprecate .system (#3302)
# Objective

- Using `.system()` is no longer idiomatic.

## Solution

- Give a warning when using it
2022-02-08 04:00:58 +00:00
Gingeh
2f11c9dca8 Add Query::contains (#3090)
# Objective

- Fixes #3089
2022-02-08 03:37:34 +00:00
François
1468211e2b fix unreachable macro calls for rust 2021 (#3889)
# Objective

- It was decided in Rust 2021 to make macro like `panic` require a string literal to format instead of directly an object
- `unreachable` was missed during the first pass but it was decided to go for it anyway now: https://github.com/rust-lang/rust/issues/92137#issuecomment-1019519285
- this is making Bevy CI fail now: https://github.com/bevyengine/bevy/runs/5102586734?check_suite_focus=true

## Solution

- Fix calls to `unreachable`
2022-02-08 02:59:54 +00:00
MinerSebas
b3462428c9 Move the CoreStage::Startup to a seperate StartupSchedule label (#2434)
# Objective

- `CoreStage::Startup` is unique in the `CoreStage` enum, in that it represents a `Schedule` and not a `SystemStage`.
- This can lead to confusion about how `CoreStage::Startup` and the `StartupStage` enum are related.
- Beginners sometimes try `.add_system_to_stage(CoreStage::Startup, setup.system())` instead of `.add_startup_system(setup.system())`, which causes a Panic:
```
thread 'main' panicked at 'Stage 'Startup' does not exist or is not a SystemStage', crates\bevy_ecs\src\schedule\mod.rs:153:13
stack backtrace:
   0: std::panicking::begin_panic_handler
             at /rustc/53cb7b09b00cbea8754ffb78e7e3cb521cb8af4b\/library\std\src\panicking.rs:493
   1: std::panicking::begin_panic_fmt
             at /rustc/53cb7b09b00cbea8754ffb78e7e3cb521cb8af4b\/library\std\src\panicking.rs:435
   2: bevy_ecs::schedule::{{impl}}::add_system_to_stage::stage_not_found
             at .\crates\bevy_ecs\src\schedule\mod.rs:153
   3: bevy_ecs::schedule::{{impl}}::add_system_to_stage::{{closure}}<tuple<bevy_ecs::system::function_system::IsFunctionSystem, tuple<bevy_ecs::system::commands::Commands, bevy_ecs::change_detection::ResMut<bevy_asset::assets::Assets<bevy_render::mesh::mesh::Me
             at .\crates\bevy_ecs\src\schedule\mod.rs:161
   4: core::option::Option<mut bevy_ecs::schedule::stage::SystemStage*>::unwrap_or_else<mut bevy_ecs::schedule::stage::SystemStage*,closure-0>
             at C:\Users\scher\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\core\src\option.rs:427
   5: bevy_ecs::schedule::Schedule::add_system_to_stage<tuple<bevy_ecs::system::function_system::IsFunctionSystem, tuple<bevy_ecs::system::commands::Commands, bevy_ecs::change_detection::ResMut<bevy_asset::assets::Assets<bevy_render::mesh::mesh::Mesh>>, bevy_ec
             at .\crates\bevy_ecs\src\schedule\mod.rs:159
   6: bevy_app::app_builder::AppBuilder::add_system_to_stage<tuple<bevy_ecs::system::function_system::IsFunctionSystem, tuple<bevy_ecs::system::commands::Commands, bevy_ecs::change_detection::ResMut<bevy_asset::assets::Assets<bevy_render::mesh::mesh::Mesh>>, be
             at .\crates\bevy_app\src\app_builder.rs:196
   7: 3d_scene::main
             at .\examples\3d\3d_scene.rs:4
   8: core::ops::function::FnOnce::call_once<fn(),tuple<>>
             at C:\Users\scher\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\core\src\ops\function.rs:227
```

## Solution

- Replace the `CoreStage::Startup` Label with the new `StartupSchedule` unit type.


Resolves #2229
2022-02-08 00:03:50 +00:00
dataphract
f7478f448a doc: remove mention of void return type in entry_point docs (#3881)
# Objective

The docs for `{VertexState, FragmentState}::entry_point` stipulate that the entry point function in the shader must return void. This seems to be specific to GLSL; WGSL has no `void` type and its entry point functions return values that describe their output.

## Solution

Remove the mention of the `void` return type.
2022-02-07 22:07:43 +00:00
François
3d6e4893f6 reverse how diagnostic values are saved (#3056)
# Objective

- Currently, when getting a diagnostic value, the oldest value is returned. This is not the best for a diagnostic with a large history, as you could get a value from several frames away

## Solution

- I changed the order in which the history is used to follow ["The “default” usage of this type as a queue is to use push_back to add to the queue, and pop_front to remove from the queue."](https://doc.rust-lang.org/std/collections/vec_deque/struct.VecDeque.html)
2022-02-07 21:50:52 +00:00
Delphine
b13f238fc7 allow Entity to be deserialized with serde_json (#3873)
# Objective

- `serde_json` assumes that numbers being deserialized are either u64 or i64.
- `Entity` serializes and deserializes as a u32.
- Deserializing an `Entity` with `serde_json` fails with: `Error("invalid type: integer 10947, expected expected Entity"`

## Solution

- Implemented a visitor for u64 that allows an `Entity` to be deserialized in this case.
- While I was here, also fixed the redundant "expected expected Entity" in the error message
- Tested the change in a local project which now correctly deserializes `Entity` structs with `serde_json` when it couldn't before
2022-02-06 04:16:16 +00:00
François
75286b8540 check if resource for asset already exists before adding it (#3560)
# Objective

- Fix #3559 
- Avoid erasing existing resource `Assets<T>` when adding it twice

## Solution

- Before creating a new `Assets<T>`, check if it has already been added to the world


Co-authored-by: François <8672791+mockersf@users.noreply.github.com>
Co-authored-by: Aevyrie Roessler <aevyrie@gmail.com>
2022-02-06 01:07:56 +00:00
MinerSebas
59ee512292 Add TransformBundle (#3054)
# Objective

- Bevy currently has no simple way to make an "empty" Entity work correctly in a Hierachy.
  - The current Solution is to insert a Tuple instead: 

```rs
.insert_bundle((Transform::default(), GlobalTransform::default()))
```

## Solution

* Add a `TransformBundle` that combines the Components:

```rs
.insert_bundle(TransformBundle::default())
```

* The code is based on #2331, except for missing the more controversial usage of `TransformBundle` as a Sub-bundle in preexisting Bundles.

Co-authored-by: MinerSebas <66798382+MinerSebas@users.noreply.github.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-02-06 01:07:55 +00:00
TheRawMeatball
7604665880 Implement AnyOf queries (#2889)
Implements a new Queryable called AnyOf, which will return an item as long as at least one of it's requested Queryables returns something. For example, a `Query<AnyOf<(&A, &B, &C)>>` will return items with type `(Option<&A>, Option<&B>, Option<&C>)`, and will guarantee that for every element at least one of the option s is Some. This is a shorthand for queries like `Query<(Option<&A>, Option<&B>, Option<&C>), Or<(With<A>, With<B>, With&C>)>>`.


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-02-06 00:52:47 +00:00
Pocket7878
a0af066af7 fix typo in bevy_ecs/README.md (#3869)
# Objective

Fixes #3866

## Solution

Fix comment in bevy_ecs/README.md
2022-02-05 17:21:00 +00:00
TheRawMeatball
865698548f Fix HDR asset support (#3795)
The HDR texture loader was never added to the app, this PR makes sure it is added when the relevant feature is enabled.
2022-02-04 21:22:12 +00:00
Jakob Hellermann
3431335ee9 add missing into_inner to ReflectMut (#3841)
`Mut<T>`, `ResMut<T>` etc. have `.into_inner()` methods, but `ReflectMut` doesn't for some reason.
2022-02-04 03:37:45 +00:00
aloucks
1477765f62 Replace VSync with PresentMode (#3812)
# Objective

Enable the user to specify any presentation modes (including `Mailbox`).

Fixes #3807

## Solution

I've added a new `PresentMode` enum in `bevy_window` that mirrors the `wgpu` enum 1:1. Alternatively, I could add a new dependency on `wgpu-types` if that would be preferred.
2022-02-04 03:37:44 +00:00
Mika
fe0e5580db Fix node update (#3785)
# Objective

Fixes #3784

## Solution

Check if the node size is actually different from previous
2022-02-04 03:37:42 +00:00
Jakob Hellermann
b7dfe1677f include sources in shader validation error (#3724)
## Objective

When print shader validation error messages, we didn't print the sources and error message text, which led to some confusing error messages.

```cs
error: 
   ┌─ wgsl:15:11
   │
15 │     return material.color + 1u;
   │           ^^^^^^^^^^^^^^^^^^^^ naga::Expression [11]
```

## Solution

New error message:
```cs
error: Entry point fragment at Vertex is invalid
   ┌─ wgsl:15:11
   │
15 │     return material.color + 1u;
   │           ^^^^^^^^^^^^^^^^^^^^ naga::Expression [11]
   │
   = Expression [11] is invalid
   = Operation Add can't work with [8] and [10]
```
2022-02-04 03:37:38 +00:00
Boutillier
aa7b158893 Add a size method on Image. (#3696)
# Objective

Add a simple way for user to get the size of a loaded texture in an Image object.
Aims to solve #3689

## Solution

Add a `size() -> Vec2` method
Add two simple tests for this method.

Updates:
. method named changed from `size_2d` to `size`
2022-02-04 03:21:33 +00:00
TheRawMeatball
142e7f3c50 Backport soundness fix (#3685)
#3001 discovered a soundness bug in World::resource_scope, this PR backports the fix with a smaller PR to patch out the bug sooner.

Fixes #3147
2022-02-04 03:21:31 +00:00
Robert Swain
e928acb9ff bevy_asset: Add AssetServerSettings watch_for_changes member (#3643)
# Objective

- `asset_server.watch_for_changes().unwrap()` only watches changes for assets loaded **_after_** that call.
- Technically, the `hot_asset_reloading` example is racey as the watch on the asset path is set up in an async task scheduled from the asset `load()`, but the filesystem watcher is only constructed in a call that comes **_after_** the call to `load()`.

## Solution

-  It feels safest to allow enabling watching the filesystem for changes on the asset server from the point of its construction. Therefore, adding such an option to `AssetServerSettings` seemed to be the correct solution.
- Fix `hot_asset_reloading` by inserting the `AssetServerSettings` resource with `watch_for_changes: true` instead of calling `asset_server.watch_for_changes().unwrap()`.
- Document the shortcomings of `.watch_for_changes()`
2022-02-04 03:21:29 +00:00
dataphract
ca83e8a6de fix: remove unneeded filter in check_light_mesh_visibility (#3861)
# Objective

The query for `VisiblePointLights` in `check_light_mesh_visibility` has a `Without<DirectionalLight>` filter. However, because `VisiblePointLights` is no longer an alias for `VisibleEntities`, the query won't conflict with the query for `DirectionalLight`s and thus the filter is unnecessary.

## Solution

Remove the filter and the outdated comment explaining its purpose.
2022-02-04 03:07:22 +00:00
Daniel Bearden
fe4a42a648 Mut to immut impls (#3621)
# Objective
- Provide impls for mutable types to relevant immutable types. 
- Closes #2005 

## Solution

- impl From<ResMut> for Res
- impl From<NonSendMut> for NonSend
- Mut to &/&mut already impl'd in change_detection_impl! macro
2022-02-04 03:07:21 +00:00
JoJoJet
6b8d64cd01 impl more traits for bevy_core::Name (#3611)
# Objective

- `Name` component is missing some useful trait impls.

## Solution

- Implement the missing traits. `Display`, `AsRef<str>`, and several other conversions to and from strings.
2022-02-04 03:07:20 +00:00
MrGVSV
f00aec2454 Added method to restart the current state (#3328)
# Objective

It would be useful to be able to restart a state (such as if an operation fails and needs to be retried from `on_enter`). Currently, it seems the way to restart a state is to transition to a dummy state and then transition back.

## Solution

The solution is to add a `restart` method on `State<T>` that allows for transitioning to the already-active state.

## Context

Based on [this](https://discord.com/channels/691052431525675048/742884593551802431/920335041756815441) question from the Discord.

Closes #2385


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-02-04 03:07:18 +00:00
rezural
e2cce092d7 derive clone for Input (#3569)
# Objective

- As part of exploring input event suppression in bevy_egui here: 53c1773583
- I found that the only way to suppress events properly, is to allow to clone the relevant Input<Whatever>, and update with events manually from within the system. This cloned Input then is discarded, the Events<*> structs are cleared, and bevy_input's normal update of Input proceeds, without the events that have been suppressed.

## Solution

- This enables Input to be cloned, allowing it to be manually updated with events.
2022-02-04 02:42:59 +00:00
ickk
ef65548fba Change default window title to "app" (#3417)
Implements the changes cart decided on in https://github.com/bevyengine/bevy/pull/3404#issuecomment-999806086

> - The default title should be changed to app so we don't leak the "bevy context" by default. app is generic enough that most people building real games will probably want to change it, but also generic enough that if someone doesn't manually set it, users won't bat an eye. I prefer this to binary names because they won't be consistent on all platforms / setups. A user (or developer) renaming a binary would implicitly rename the window title, which feels odd to me.
> - No debug info in the title by default. An opt in plugin for that would be nice though.

closes #3404 ?
2022-02-04 02:42:58 +00:00
Kevin King
bb1538a139 improve error message for attempting to add systems using add_system_to_stage (#3287)
# Objective

Fixes #3250

## Solution

Since this panic occurs in bevy_ecs, and StartupStage is part of
bevy_app, we really only have access to the Debug string of the
`stage_label` parameter.  This led me to the hacky solution of
comparing the debug output of the label the user provides with the known
variants of StartupStage.

An alternative would be to do this error handling further up in
bevy_app, where we can access StartupStage's typeid, but I don't think
it is worth having a panic in 2 places (_ecs, and _app).
2022-02-04 02:26:18 +00:00
James Beilby
f584e72953 Add Transform::rotate_around method (#3107)
# Objective

- Missing obvious way to rotate a transform around a point. This is popularly used for rotation of an object in world space ("orbiting" a point), or for local rotation of an object around a pivot point on that object.
- Present in other (not to be named) game engines
- Was question from user on Discord today (thread "object rotation")

## Solution

- Added Transform::rotate_around method where point is specified in reference frame of the parent (if any) or in world space.
2022-02-04 02:09:24 +00:00
François
37a7be56db Make transform builder methods const (#3045)
# Objective

- Make transform builder methods `const`

## Solution

- I made them `const`
2022-02-04 01:46:35 +00:00
Charles
7d712406fe Simplify sending empty events (#2935)
# Objective

When using empty events, it can feel redundant to have to specify the type of the event when sending it.

## Solution

Add a new `fire()` function that sends the default value of the event. This requires that the event derives Default.


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-02-04 01:24:47 +00:00
Daniel McNab
6f111136b9 Cleanup some things which shouldn't be components (#2982)
# Objective

- Using `Stopwatch` and `Timer` as raw components is a footgun.

## Solution

- Stop them from being components
2022-02-03 23:56:57 +00:00
bilsen
1f99363de9 Add &World as SystemParam (#2923)
# Objective
Make it possible to use `&World` as a system parameter

## Solution
It seems like all the pieces were already in place, very simple impl


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-02-03 23:43:25 +00:00
Garett Cooper
c216738b33 Implement len and is_empty for EventReaders (#2969)
# Objective

Provide a non-consuming method of checking if there are events in an `EventReader`.

Fixes #2967

## Solution

Implements the `len` and `is_empty` functions for `EventReader` and `ManualEventReader`, giving users the ability to check for the presence of new events without consuming any.


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-02-03 23:22:08 +00:00
bjorn3
af22cc1dc3 Use ManuallyDrop instead of forget in insert_resource_with_id (#2947)
# Objective

Calling forget would invalidate the data pointer before it is used.

## Solution

Use `ManuallyDrop` to prevent the value from being dropped without moving it.
2022-02-03 22:34:31 +00:00
François
19bd6b9c32 Update rodio 0.15 (#3846)
# Objective

- Update rodio to 0.15
- Replace #3828
2022-02-03 04:25:44 +00:00
Stefan Seemayer
21ac4bc0ae impl Command for <impl FnOnce(&mut World)> (#2996)
This is my first contribution to this exciting project! Thanks so much for your wonderful work. If there is anything that I can improve about this PR, please let me know :)

# Objective

- Fixes #2899
- If a simple one-off command is needed to be added within a System, this simplifies that process so that we can simply do `commands.add(|world: &mut World| { /* code here */ })` instead of defining a custom type implementing `Command`.

## Solution

- This is achieved by `impl Command for F where F: FnOnce(&mut World) + Send + Sync + 'static` as just calling the function.

I am not sure if the bounds can be further relaxed but needed the whole `Send`, `Sync`, and `'static` to get it to compile.
2022-02-03 04:11:19 +00:00
MinerSebas
69e9a47d92 SystemParam Derive fixes (#2838)
# Objective

A user on Discord couldn't derive SystemParam for this Struct:

```rs
#[derive(SystemParam)]
pub struct SpatialQuery<'w, 's, Q: WorldQuery + Send + Sync + 'static, F: WorldQuery + Send + Sync + 'static = ()>
where
    F::Fetch: FilterFetch,
{
    query: Query<'w, 's, (C, &'static Transform), F>,
}
```

## Solution

1. The `where`-clause is now also copied to the `SystemParamFetch` impl Block.
2. The `SystemParamState` impl Block no longer gets any defaults for generics


Co-authored-by: MinerSebas <66798382+MinerSebas@users.noreply.github.com>
2022-02-03 03:32:02 +00:00
dataphract
b506c30cd3 fix: only init_resource() once for AmbientLight (#3853)
# Objective

`PbrPlugin` calls `app.init_resource::<AmbientLight>()` twice. The second call won't do anything.

## Solution

Remove the second call.
2022-02-03 00:43:37 +00:00
KDecay
506642744c docs: Fix private doc links and enable CI test (#3743)
# Objective

Fixes #3566

## Solution

- [x] Fix broken links in private docs.
- [x] Add the `--document-private-items` flag to the CI.

## Note

The following was said by @killercup in #3566:

> I don't have time to confirm this but I assume that linking to private items throws an error/warning when just running cargo doc, and --document-private-item might actually hide that warning. So to test this, you'd have to run it twice.

I tested this and this is thankfully not the case. If you are linking to a private item you will get a warning no matter if you run `cargo doc` or `cargo doc --document-private-items`.

### Example

I added `struct Test;` to `bevy_core/src/name.rs` and linked to it inside of a doc comment using ``[`Test`]``. After that I ran `cargo doc -p bevy_core --document-private-items` using `RUSTDOCFLAGS="-D warnings"` and got the following output (note the last sentence):

```rust
error: public documentation for `Name` links to private item `Test`
  --> crates/bevy_core/src/name.rs:11:82
   |
11 | /// Component used to identify an entity. Stores a hash for faster comparisons [`Test`]
   |                                                                                  ^^^^ this item is private
   |
   = note: `-D rustdoc::private-intra-doc-links` implied by `-D warnings`
   = note: this link resolves only because you passed `--document-private-items`, but will break without
```
2022-02-02 21:47:29 +00:00
Andrew Jackson
6cab36165f Update ClearColor Resource docs (#3842)
# Objective
- Update the `ClearColor` resource docs as described in #3837  so new users (like me) understand it better

## Solution
- Update the docs to use what @alice-i-cecile described in #3837 


I took this one up because I got confused by it this weekend. I didn't understand why the  "background" was being set by a `ClearColor` resource.
2022-02-02 21:29:48 +00:00
TheRawMeatball
ce752d2522 Increment last event count on next instead of iter (#2382)
# Objective

Currently, simply calling `iter` on an event reader will mark all of it's events as read, even if the returned iterator is never used

## Solution

With this, the cursor will simply move to the last unread, but available event when iter is called, and incremented by one per `next` call.


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-02-02 02:29:33 +00:00
dependabot[bot]
6a499b125b Update gltf requirement from 0.16.0 to 1.0.0 (#3826)
Updates the requirements on [gltf](https://github.com/gltf-rs/gltf) to permit the latest version.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a href="https://github.com/gltf-rs/gltf/blob/master/CHANGELOG.md">gltf's changelog</a>.</em></p>
<blockquote>
<h2>[1.0.0] - 2022-01-29</h2>
<h3>Added</h3>
<ul>
<li>Support for the <code>KHR_materials_specular</code> extension.</li>
<li>Support for the <code>KHR_materials_variants</code> extension.</li>
<li>Support for the <code>KHR_materials_volume</code> extension.</li>
<li><code>ExactSizeIterator</code> implementation for <code>Joints</code> iterator.</li>
</ul>
<h3>Changed</h3>
<ul>
<li>The <code>mesh.primitives</code> property is now always serialized.</li>
</ul>
<h3>Fixed</h3>
<ul>
<li>Incorrect implementation of <code>Normalize&lt;u16&gt;</code> and <code>Normalize&lt;f32&gt;</code> for <code>u16</code>.</li>
</ul>
<h2>[0.16.0] - 2021-05-13</h2>
<h3>Added</h3>
<ul>
<li>Support for the <code>KHR_texture_transform</code> extension.</li>
<li>Support for the <code>KHR_materials_transmission_ior</code> extension.</li>
</ul>
<h3>Changed</h3>
<ul>
<li><code>Material::alpha_cutoff</code> is now optional.</li>
</ul>
<h3>Fixed</h3>
<ul>
<li>URIs with embedded data failing to import when using <code>import_slice</code>.</li>
<li>Serialization of empty primitives object being skipped.</li>
</ul>
<h2>[0.15.2] - 2020-03-29</h2>
<h3>Changed</h3>
<ul>
<li>All features are now exposed in the <a href="http://docs.rs/gltf">online documentation</a>.</li>
<li>Primary iterators now implement <code>Iterator::nth</code> explicitly for improved performance.</li>
</ul>
<h3>Fixed</h3>
<ul>
<li>Compiler warnings regarding deprecation of <code>std::error::Error::description</code>.</li>
</ul>
<h2>[0.15.1] - 2020-03-15</h2>
<h3>Added</h3>
<ul>
<li>New feature <code>guess_mime_type</code> which, as the name suggests, attempts to guess
the MIME type of an image if it doesn't exactly match the standard.</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a href="https://github.com/gltf-rs/gltf/commits">compare view</a></li>
</ul>
</details>
<br />


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

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

---

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

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


</details>
2022-02-02 00:25:39 +00:00
Horváth Bálint
c285a69f76 Add the Inside version to the Collision enum (#2489)
# Objective
I think the 'collide' function inside the 'bevy/crates/bevy_sprite/src/collide_aabb.rs' file should return 'Some' if the two rectangles are fully overlapping or one is inside the other. This can happen on low-end machines when a lot of time passes between two frames because of a stutter, so a bullet for example gets inside its target. I can also think of situations where this is a valid use case even without stutters. 

## Solution
I added an 'Inside' version to the Collision enum declared in the file. And I use it, when the two rectangles are overlapping, but we can't say from which direction it happened. I gave a 'penetration depth' of minus Infinity to these cases, so that this variant only appears, when the two rectangles overlap from each side fully. I am not sure if this is the right thing to do.

Fixes #1980

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-02-01 22:40:25 +00:00
Robert Swain
33ef5b5039 bevy_render: Only auto-disable mappable primary buffers for discrete GPUs (#3803)
# Objective

- While it is not safe to enable mappable primary buffers for all GPUs, it should be preferred for integrated GPUs where an integrated GPU is one that is sharing system memory.

## Solution

- Auto-disable mappable primary buffers only for discrete GPUs. If the GPU is integrated and mappable primary buffers are supported, use them.
2022-01-31 01:22:17 +00:00