Commit graph

3040 commits

Author SHA1 Message Date
ickshonpe
4580a91171
measure_text_system text query fix (#8466)
# Objective

The first query of `measure_text_system`'s `text_queries` `ParamSet`
queries for all changed `Text` meaning that non-UI `Text` entities could
be added to its queue.

## Solution

Add a `With<Node>` query filter.

---

## Changelog
changes:
* Added a `With<Node>` query filter to first query of
`measure_text_system`'s `text_queries` `ParamSet` to ensure that only UI
node entities are added to its local queue.
* Fixed comment (text is not computed on changes to style).
2023-04-22 21:30:38 +00:00
JohnTheCoolingFan
15a96adc01
ChildBuilder docs improvement (#8371)
# Objective

Fixes #7230 

## Solution

Documented some side-effects

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Nicola Papale <nicopap@users.noreply.github.com>
2023-04-22 20:43:13 +00:00
ira
6b774c0fda
Compute vertex_count for indexed meshes on GpuMesh (#8460)
# Objective

Compute the `vertex_count` for indexed meshes as well as non-indexed
meshes.

I will need this in a future PR based on #8427 that adds a gizmo
component that draws the normals of a mesh when attached to an entity
([branch](https://github.com/devil-ira/bevy/compare/instanced-line-rendering...devil-ira:bevy:instanced-line-rendering-normals)).

<details><summary>Example image</summary>
<p>


![image](https://user-images.githubusercontent.com/29694403/233789526-cb5feb47-0aa7-4e69-90a2-e31ec24aadff.png)

</p>
</details> 

## Solution

Move `vertex_count` field from `GpuBufferInfo::NonIndexed` to `GpuMesh`

## Migration Guide

`vertex_count` is now stored directly on `GpuMesh` instead of
`GpuBufferInfo::NonIndexed`.
2023-04-22 17:28:58 +00:00
François
149c86b2ae
also import the default handle when feature disabled (#8456)
# Objective

- Fix compilation issue when default font is not enabled

## Solution

- Fix import
2023-04-22 07:49:18 +00:00
Noah
a9f766ceb2
Fix Box<dyn Reflect> struct with a hashmap in it panicking when clone_value is called on it (#8184)
# Objective

- Fix the issue described in #8183: Box<dyn Reflect> structs with a
hashmap in them will panic when clone_value is called on it
- Fixes: #8183

## Solution

- Updates the implementation of Reflect for Hashmaps to make clone_value
call from_reflect on the key before inserting it into the new struct
2023-04-22 02:55:53 +00:00
François
e0e5f3acd4
add a default font (#8445)
# Objective

- Have a default font

## Solution

- Add a font based on FiraMono containing only ASCII characters and use
it as the default font
- It is behind a feature `default_font` enabled by default
- I also updated examples to use it, but not UI examples to still show
how to use a custom font

---

## Changelog

* If you display text without using the default handle provided by
`TextStyle`, the text will be displayed
2023-04-21 22:30:18 +00:00
Kjolnyr
ddefc246b2
Added arc_2d function for gizmos (#8448)
# Objective

Added the possibility to draw arcs in 2d via gizmos

## Solution

- Added `arc_2d` function to `Gizmos`
- Added `arc_inner` function
- Added `Arc2dBuilder<'a, 's>`
- Updated `2d_gizmos.rs` example to draw an arc

---------

Co-authored-by: kjolnyr <kjolnyr@protonmail.ch>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: ira <JustTheCoolDude@gmail.com>
2023-04-21 15:34:07 +00:00
ickshonpe
0cf3000ee0
Fix the double leaf node updates in flex_node_system (#8264)
# Objective

If a UI node has a changed `CalculatedSize` component and either the UI
does a full update or the node also has a changed `Style` component, the
node's corresponding Taffy node will be updated twice by
`flex_node_system`.

## Solution

Add a `Without<Calculated>` query filter so that the two changed node
queries in `flex_node_system` are mutually exclusive and move the
`CalculatedSize` node updater into the else block of the full-update if
conditional.
2023-04-21 14:23:46 +00:00
Nicola Papale
e900bd9e12
Fix 1.69 CI clippy lints (#8450)
- Fix CI by implementing changes recommended by clippy
- It uncovered a bug in a `bevy_ecs` test. Nice!
2023-04-20 16:51:21 +00:00
Robert Swain
d8102a0a04
bevy_pbr: Do not cull meshes without Aabbs from cascades (#8444)
# Objective

- Mesh entities should cast shadows when not having Aabbs and having
NoFrustumCulling
- Fixes #8442 

## Solution

- Mesh entities with NoFrustumCulling get no automatic Aabbs added
- Point and spot lights do not cull mesh entities for their shadow
mapping if they do not have an Aabb, but directional lights do
- Make directional lights not cull mesh entities from cascades if the do
not have Aabbs. So no Aabb as a consequence of a NoFrustumCulling
component will mean that those mesh entities are not culled and so are
visible to the light.

---

## Changelog

- Fixed: Mesh entities with NoFrustumCulling will cast shadows for
directional light shadow maps
2023-04-20 01:43:24 +00:00
Nile
9db70da96f
Add screenshot api (#7163)
Fixes https://github.com/bevyengine/bevy/issues/1207

# Objective

Right now, it's impossible to capture a screenshot of the entire window
without forking bevy. This is because
- The swapchain texture never has the COPY_SRC usage
- It can't be accessed without taking ownership of it
- Taking ownership of it breaks *a lot* of stuff

## Solution

- Introduce a dedicated api for taking a screenshot of a given bevy
window, and guarantee this screenshot will always match up with what
gets put on the screen.

---

## Changelog

- Added the `ScreenshotManager` resource with two functions,
`take_screenshot` and `save_screenshot_to_disk`
2023-04-19 21:28:42 +00:00
JoJoJet
9fd867aeba
Simplify world schedule methods (#8403)
# Objective

Methods for interacting with world schedules currently have two
variants: one that takes `impl ScheduleLabel` and one that takes `&dyn
ScheduleLabel`. Operations such as `run_schedule` or `schedule_scope`
only use the label by reference, so there is little reason to have an
owned variant of these functions.

## Solution

Decrease maintenance burden by merging the `ref` variants of these
functions with the owned variants.

---

## Changelog

- Deprecated `World::run_schedule_ref`. It is now redundant, since
`World::run_schedule` can take values by reference.

## Migration Guide

The method `World::run_schedule_ref` has been deprecated, and will be
removed in the next version of Bevy. Use `run_schedule` instead.
2023-04-19 19:48:35 +00:00
JoJoJet
fe852fd0ad
Fix boxed labels (#8436)
# Objective

Label traits such as `ScheduleLabel` currently have a major footgun: the
trait is implemented for `Box<dyn ScheduleLabel>`, but the
implementation does not function as one would expect since `Box<T>` is
considered to be a distinct type from `T`. This is because the behavior
of the `ScheduleLabel` trait is specified mainly through blanket
implementations, which prevents `Box<dyn ScheduleLabel>` from being
properly special-cased.

## Solution

Replace the blanket-implemented behavior with a series of methods
defined on `ScheduleLabel`. This allows us to fully special-case
`Box<dyn ScheduleLabel>` .

---

## Changelog

Fixed a bug where boxed label types (such as `Box<dyn ScheduleLabel>`)
behaved incorrectly when compared with concretely-typed labels.

## Migration Guide

The `ScheduleLabel` trait has been refactored to no longer depend on the
traits `std::any::Any`, `bevy_utils::DynEq`, and `bevy_utils::DynHash`.
Any manual implementations will need to implement new trait methods in
their stead.

```rust
impl ScheduleLabel for MyType {
    // Before:
    fn dyn_clone(&self) -> Box<dyn ScheduleLabel> { ... }

    // After:
    fn dyn_clone(&self) -> Box<dyn ScheduleLabel> { ... }

    fn as_dyn_eq(&self) -> &dyn DynEq {
        self
    }

    // No, `mut state: &mut` is not a typo.
    fn dyn_hash(&self, mut state: &mut dyn Hasher) {
        self.hash(&mut state);
        // Hashing the TypeId isn't strictly necessary, but it prevents collisions.
        TypeId::of::<Self>().hash(&mut state);
    }
}
```
2023-04-19 02:36:44 +00:00
Nico Burns
5ed6b628eb
Allow bevy_ui crate to compile without the text feature enabled (#8437)
# Objective

Allow `bevy_ui` crate to compile without the `text` feature enabled

## Solution

- Correctly conditionally compile `text_system`
2023-04-18 19:41:02 +00:00
François
3220ad6b0b
do not crash when rendering only one gizmo (#8434)
# Objective

- Fixes #8432

## Solution

- Do not even create mesh when one is not needed
2023-04-18 16:31:55 +00:00
Hennadii Chernyshchyk
315f3cab36
Add any_component_removed condition (#8326)
Added helper extracted from #7711. that PR contains some controversy
conditions, but this one should be good to go.

---

## Changelog

### Added

- `any_component_removed` condition.

---------

Co-authored-by: François <mockersf@gmail.com>
2023-04-18 14:18:09 +00:00
ickshonpe
09df19bcad
Split UI Overflow by axis (#8095)
# Objective

Split the UI overflow enum so that overflow can be set for each axis
separately.

## Solution

Change `Overflow` from an enum to a struct with `x` and `y`
`OverflowAxis` fields, where `OverflowAxis` is an enum with `Clip` and
`Visible` variants. Modify `update_clipping` to calculate clipping for
each axis separately. If only one axis is clipped, the other axis is
given infinite bounds.

<img width="642" alt="overflow"
src="https://user-images.githubusercontent.com/27962798/227592983-568cf76f-7e40-48c4-a511-43c886f5e431.PNG">

---

## Changelog
* Split the UI overflow implementation so overflow can be set for each
axis separately.
* Added the enum `OverflowAxis` with `Clip` and `Visible` variants.
* Changed `Overflow` to a struct with `x` and `y` fields of type
`OverflowAxis`.
* `Overflow` has new methods `visible()` and `hidden()` that replace its
previous `Clip` and `Visible` variants.
* Added `Overflow` helper methods `clip_x()` and `clip_y()` that return
a new `Overflow` value with the given axis clipped.
* Modified `update_clipping` so it calculates clipping for each axis
separately. If a node is only clipped on a single axis, the other axis
is given `-f32::INFINITY` to `f32::INFINITY` clipping bounds.


## Migration Guide

The `Style` property `Overflow` is now a struct with `x` and `y` fields,
that allow for per-axis overflow control.

Use these helper functions to replace the variants of `Overflow`:
* Replace `Overflow::Visible` with  `Overflow::visible()`
* Replace `Overflow::Hidden` with `Overflow::clip()`
2023-04-17 22:23:52 +00:00
ira
e54057c50d
Avoid spawning gizmo meshes when no gizmos are being drawn (#8180)
# Objective

Avoid queuing empty meshes for rendering.
Should prevent #8144 from triggering when no gizmos are in use. Not a
real fix, unfortunately.

## Solution

Add an `in_use` field to `GizmoStorage` and only set it to true when
there are gizmos to draw.
2023-04-17 21:20:29 +00:00
JoJoJet
ce252f8cf7
Reorganize system modules (#8419)
# Objective

Follow-up to #8377.

As the system module has been refactored, there are many types that no
longer make sense to live in the files that they do:
- The `IntoSystem` trait is in `function_system.rs`, even though this
trait is relevant to all kinds of systems. Same for the `In<T>` type.
- `PipeSystem` is now just an implementation of `CombinatorSystem`, so
`system_piping.rs` no longer needs its own file.

## Solution

- Move `IntoSystem`, `In<T>`, and system piping combinators & tests into
the top-level `mod.rs` file for `bevy_ecs::system`.
- Move `PipeSystem` into `combinator.rs`.
2023-04-17 21:10:57 +00:00
Eris
764961be22
Add Reflection Macros to TextureAtlasSprite (#8428)
# Objective

Add Reflection to `TextureAtlasSprite` to bring it inline with `Sprite`

## Solution

Addition of appropriate macros to the type

---

## Changelog

`#[reflect(Component)]` and derive `FromReflect` for
`TextureAtlasSprite`
Added `TextureAtlasSprite` to the TypeRegistry
2023-04-17 20:24:17 +00:00
InnocentusLime
30ac157b80
Register some extra types to type registry (#8430)
# Objective

Fixes #8415.

## Solution

I simply added the missing types to the type registry.

## Changelog

Added `#[reflect(Component]` to `bevi_ui::ui_node::ZIndex`, since it
impls `Component` and `Reflect.`

The following types have been added to the type registry:

1. `bevy_ui::ZIndex`
2. `bevy_math::Rect`
3. `bevy_text::BreakLineOn`
4. `bevy_text::Text2dBounds`
2023-04-17 20:05:59 +00:00
Nico Burns
919919c998
Fix text measurement algorithm (#8425)
# Objective

Followup to #7779 which tweaks the actual text measurement algorithm to
be more robust.

Before:

<img width="822" alt="Screenshot 2023-04-17 at 18 12 05"
src="https://user-images.githubusercontent.com/1007307/232566858-3d3f0fd5-f3d4-400a-8371-3c2a3f541e56.png">

After:

<img width="810" alt="Screenshot 2023-04-17 at 18 41 40"
src="https://user-images.githubusercontent.com/1007307/232566919-4254cbfa-1cc3-4ea7-91ed-8ca1b759bacf.png">

(note extra space taken up in header in before example)

## Solution

- Text layout of horizontal text (currently the only kind of text we
support) is now based solely on the layout constraints in the horizontal
axis. It ignores constraints in the vertical axis and computes vertical
size based on wrapping subject to the horizontal axis constraints.
- I've also added a paragraph to the `grid` example for testing / demo
purposes.
2023-04-17 19:59:42 +00:00
Bruce Reif (Buswolley)
7604464438
fix panic when moving child (#8346)
# Objective
When changing an Entity's `Parent` to a new one from an old `Parent`
that doesn't exist, Bevy panics. Fixes #8337.

## Solution

Use `get_entity_mut` instead of `entity_mut` in `remove_from_children`.

---------

Co-authored-by: James Liu <contact@jamessliu.com>
2023-04-17 18:03:47 +00:00
Nico Burns
fe0ad10b0c
Fix text systems broken when resolving merge conflicts in #8026 (#8422)
# Objective

- Incorrectly resolved merge conflicts in
https://github.com/bevyengine/bevy/pull/8026 have caused UI text to not
render at all.

## Solution

Restore correct system schedule for text systems
2023-04-17 17:29:44 +00:00
Nico Burns
363d0f0c7c
Add CSS Grid support to bevy_ui (#8026)
# Objective

An easy way to create 2D grid layouts

## Solution

Enable the `grid` feature in Taffy and add new style types for defining
grids.

## Notes

- ~I'm having a bit of trouble getting `#[derive(Reflect)]` to work
properly. Help with that would be appreciated (EDIT: got it to compile
by ignoring the problematic fields, but this presumably can't be
merged).~ This is now fixed
- ~The alignment types now have a `Normal` variant because I couldn't
get reflect to work with `Option`.~ I've decided to stick with the
flattened variant, as it saves a level of wrapping when authoring
styles. But I've renamed the variants from `Normal` to `Default`.
- ~This currently exposes a simplified API on top of grid. In particular
the following is not currently supported:~
   - ~Negative grid indices~ Now supported.
- ~Custom `end` values for grid placement (you can only use `start` and
`span`)~ Now supported
- ~`minmax()` track sizing functions~ minmax is now support through a
`GridTrack::minmax()` constructor
   - ~`repeat()`~ repeat is now implemented as `RepeatedGridTrack`

- ~Documentation still needs to be improved.~ An initial pass over the
documentation has been completed.

## Screenshot

<img width="846" alt="Screenshot 2023-03-10 at 17 56 21"
src="https://user-images.githubusercontent.com/1007307/224435332-69aa9eac-123d-4856-b75d-5449d3f1d426.png">

---

## Changelog

- Support for CSS Grid layout added to `bevy_ui`

---------

Co-authored-by: Rob Parrett <robparrett@gmail.com>
Co-authored-by: Andreas Weibye <13300393+Weibye@users.noreply.github.com>
2023-04-17 16:21:38 +00:00
Nicola Papale
ebc6446789
Fix get_vertex_buffer_data doc (#8400)
# Objective

- Fixes #8399

The documentation was out of date and misleading since #3959.
2023-04-17 16:12:12 +00:00
Mike
defc653528
Better error message when index does not exist in texture atlas (#8396)
# Objective

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

## Changelog

- Improve error message when `TextureAtlasSprite::index` does not exist
in texture atlas
2023-04-17 16:10:58 +00:00
JoJoJet
b03b7b557e
Simplify system piping and make it more flexible (#8377)
# Objective

- Currently, it is not possible to call `.pipe` on a system that takes
any input other than `()`.
- The `IntoPipeSystem` trait is currently very difficult to parse due to
its use of generics.

## Solution

Remove the `IntoPipeSystem` trait, and move the `pipe` method to
`IntoSystem`.

---

## Changelog

- System piping has been made more flexible: it is now possible to call
`.pipe` on a system that takes an input.

## Migration Guide

The `IntoPipeSystem` trait has been removed, and the `pipe` method has
been moved to the `IntoSystem` trait.

```rust

// Before:
use bevy_ecs::system::IntoPipeSystem;
schedule.add_systems(first.pipe(second));

// After:
use bevy_ecs::system::IntoSystem;
schedule.add_systems(first.pipe(second));
```
2023-04-17 16:08:32 +00:00
NiseVoid
65292fd559
Improve warning for Send resources marked as non_send (#8000)
# Objective

- Fixes unclear warning when `insert_non_send_resource` is called on a
Send resource

## Solution

- Add a message to the asssert statement that checks this

---------

Co-authored-by: James Liu <contact@jamessliu.com>
2023-04-17 16:06:00 +00:00
François
882c86eee3
add a feature for memory tracing with tracy (#8272)
# Objective

- Expose a feature for tracing with Tracy to profile memory
(https://docs.rs/tracy-client/0.15.2/tracy_client/struct.ProfiledAllocator.html)
- This is a separate feature than just tracing as it can have an
additional cost

<img width="1912" alt="Screenshot 2023-03-30 at 08 39 49"
src="https://user-images.githubusercontent.com/8672791/228985566-dd62fff8-1cbf-4f59-8a10-80c796daba0c.png">
2023-04-17 16:04:46 +00:00
ickshonpe
43d7184b35
Fix the UV calculations for clipped and flipped ImageNodes (#8195)
# Objective

Instead of flipping the entire image, `prepare_ui_nodes` only flips the
unclipped area.

<img width="652" alt="overflow_flipped_bug"
src="https://user-images.githubusercontent.com/27962798/227587867-1467c6ae-8693-45c3-87cb-793cc5b433e4.png">

## Solution

Whenever flip_x or flip_y is set swap the image rect coordinates and
invert the clipping coords along the flipped axes before the UVs are
calculated.

<img width="656" alt="overflow_fixed"
src="https://user-images.githubusercontent.com/27962798/227588839-e0dde3b9-dc26-4652-a129-2faab2d07281.PNG">

--

## Changelog

* Modified `prepare_uinodes` so that the UVs for clipped and flipped
image nodes are calculated correctly.
2023-04-17 15:58:34 +00:00
ickshonpe
ffc62c1a81
text_system split (#7779)
# Objective

`text_system` runs before the UI layout is calculated and the size of
the text node is determined, so it cannot correctly shape the text to
fit the layout, and has no way of determining if the text needs to be
wrapped.

The function `text_constraint` attempts to determine the size of the
node from the local size constraints in the `Style` component. It can't
be made to work, you have to compute the whole layout to get the correct
size. A simple example of where this fails completely is a text node set
to stretch to fill the empty space adjacent to a node with size
constraints set to `Val::Percent(50.)`. The text node will take up half
the space, even though its size constraints are `Val::Auto`

Also because the `text_system` queries for changes to the `Style`
component, when a style value is changed that doesn't affect the node's
geometry the text is recomputed unnecessarily.

Querying on changes to `Node` is not much better. The UI layout is
changed to fit the `CalculatedSize` of the text, so the size of the node
is changed and so the text and UI layout get recalculated multiple times
from a single change to a `Text`.

Also, the `MeasureFunc` doesn't work at all, it doesn't have enough
information to fit the text correctly and makes no attempt.
 
Fixes #7663,  #6717, #5834, #1490,

## Solution

Split the `text_system` into two functions:
* `measure_text_system` which calculates the size constraints for the
text node and runs before `UiSystem::Flex`
* `text_system` which runs after `UiSystem::Flex` and generates the
actual text.
* Fix the `MeasureFunc` calculations.
---

Text wrapping in main:
<img width="961" alt="Capturemain"
src="https://user-images.githubusercontent.com/27962798/220425740-4fe4bf46-24fb-4685-a1cf-bc01e139e72d.PNG">

With this PR:
<img width="961" alt="captured_wrap"
src="https://user-images.githubusercontent.com/27962798/220425807-949996b0-f127-4637-9f33-56a6da944fb0.PNG">

## Changelog

* Removed the previous fields from `CalculatedSize`. `CalculatedSize`
now contains a boxed `Measure`.
 * Added `measurement` module to `bevy_ui`.
* Added the method `create_text_measure` to `TextPipeline`.
* Added a new system `measure_text_system` that runs before
`UiSystem::Flex` that creates a `MeasureFunc` for the text.
* Rescheduled  `text_system` to run after `UiSystem::Flex`.
* Added a trait `Measure`. A `Measure` is used to compute the size of a
UI node when the size of that node is based on its content.
* Added `ImageMeasure` and `TextMeasure` which implement `Measure`.
* Added a new component `UiImageSize` which is used by
`update_image_calculated_size_system` to track image size changes.
* Added a `UiImageSize` component to `ImageBundle`.

## Migration Guide

`ImageBundle` has a new component `UiImageSize` which contains the size
of the image bundle's texture and is updated automatically by
`update_image_calculated_size_system`

---------

Co-authored-by: François <mockersf@gmail.com>
2023-04-17 15:23:21 +00:00
JoJoJet
328347f44c
Add a missing safety invariant to System::run_unsafe (#7778)
# Objective

The implementation of `System::run_unsafe` for `FunctionSystem` requires
that the world is the same one used to initialize the system. However,
the `System` trait has no requirements that the world actually matches,
which makes this implementation unsound.

This was previously mentioned in
https://github.com/bevyengine/bevy/pull/7605#issuecomment-1426491871

Fixes part of #7833.

## Solution

Add the safety invariant that
`System::update_archetype_component_access` must be called prior to
`System::run_unsafe`. Since
`FunctionSystem::update_archetype_component_access` properly validates
the world, this ensures that `run_unsafe` is not called with a
mismatched world.

Most exclusive systems are not required to be run on the same world that
they are initialized with, so this is not a concern for them. Systems
formed by combining an exclusive system with a regular system *do*
require the world to match, however the validation is done inside of
`System::run` when needed.
2023-04-17 15:20:42 +00:00
Vladyslav Batyrenko
71fccb2897
Improve or-with disjoint checks (#7085)
# Objective

This PR attempts to improve query compatibility checks in scenarios
involving `Or` filters.

Currently, for the following two disjoint queries, Bevy will throw a
panic:

```
fn sys(_: Query<&mut C, Or<(With<A>, With<B>)>>, _: Query<&mut C, (Without<A>, Without<B>)>) {}
``` 

This PR addresses this particular scenario.

## Solution

`FilteredAccess::with` now stores a vector of `AccessFilters`
(representing a pair of `with` and `without` bitsets), where each member
represents an `Or` "variant".
Filters like `(With<A>, Or<(With<B>, Without<C>)>` are expected to be
expanded into `A * B + A * !C`.

When calculating whether queries are compatible, every `AccessFilters`
of a query is tested for incompatibility with every `AccessFilters` of
another query.

---

## Changelog

- Improved system and query data access compatibility checks in
scenarios involving `Or` filters

---------

Co-authored-by: MinerSebas <66798382+MinerSebas@users.noreply.github.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-04-17 15:16:58 +00:00
Nicola Papale
c488b7089c
Fix pbr shader breaking on missing UVs (#8412)
# Objective

Fix #8409

Since `in` doesn't have a `uv` field when `VERTEX_UVS` is not defined,
it shouldn't be accessed outside of related `#ifdef`s
2023-04-17 06:22:34 +00:00
JoJoJet
0174d632a5
Add a scope API for world schedules (#8387)
# Objective

If you want to execute a schedule on the world using arbitrarily complex
behavior, you currently need to use "hokey-pokey strats": remove the
schedule from the world, do your thing, and add it back to the world.
Not only is this cumbersome, it's potentially error-prone as one might
forget to re-insert the schedule.

## Solution

Add the `World::{try}schedule_scope{ref}` family of functions, which is
a convenient abstraction over hokey pokey strats. This method
essentially works the same way as `World::resource_scope`.

### Example

```rust
// Run the schedule five times.
world.schedule_scope(MySchedule, |world, schedule| {
    for _ in 0..5 {
        schedule.run(world);
    }
});
```

---

## Changelog

Added the `World::schedule_scope` family of methods, which provide a way
to get mutable access to a world and one of its schedules at the same
time.

---------

Co-authored-by: James Liu <contact@jamessliu.com>
2023-04-16 05:09:33 +00:00
Nicola Papale
8df014fbaf
Add parallax mapping to bevy PBR (#5928)
# Objective

Add a [parallax mapping] shader to bevy. Please note that
this is a 3d technique, NOT a 2d sidescroller feature.

## Solution

- Add related fields to `StandardMaterial`
- update the pbr shader
- Add an example taking advantage of parallax mapping

A pre-existing implementation exists at:
https://github.com/nicopap/bevy_mod_paramap/

The implementation is derived from:

https://web.archive.org/web/20150419215321/http://sunandblackcat.com/tipFullView.php?l=eng&topicid=28

Further discussion on literature is found in the `bevy_mod_paramap`
README.

### Limitations

- The mesh silhouette isn't affected by the depth map.
- The depth of the pixel does not reflect its visual position, resulting
  in artifacts for depth-dependent features such as fog or SSAO
- GLTF does not define a height map texture, so somehow the user will
  always need to work around this limitation, though [an extension is in
  the works][gltf]

### Future work

- It's possible to update the depth in the depth buffer to follow the
  parallaxed texture. This would enable interop with depth-based
  visual effects, it also allows `discard`ing pixels of materials when
  computed depth is higher than the one in depth buffer
- Cheap lower quality single-sample method using [offset limiting]
- Add distance fading, to disable parallaxing (relatively expensive)
  on distant objects
- GLTF extension to allow defining height maps. Or a workaround
  implemented through a blender plugin to the GLTF exporter that
  uses the `extras` field to add height map.
- [Quadratic surface vertex attributes][oliveira_3] to enable parallax
  mapping on bending surfaces and allow clean silhouetting.
- noise based sampling, to limit the pancake artifacts.
- Cone mapping ([GPU gems], [Simcity (2013)][simcity]). Requires
  preprocessing, increase depth map size, reduces sample count greatly.
- [Quadtree parallax mapping][qpm] (also requires preprocessing)
- Self-shadowing of parallax-mapped surfaces by modifying the shadow map
- Generate depth map from normal map [link to slides], [blender
question]


https://user-images.githubusercontent.com/26321040/223563792-dffcc6ab-70e8-4ff9-90d1-b36c338695ad.mp4

[blender question]:
https://blender.stackexchange.com/questions/89278/how-to-get-a-smooth-curvature-map-from-a-normal-map
[link to slides]:
https://developer.download.nvidia.com/assets/gamedev/docs/nmap2displacement.pdf
[oliveira_3]:
https://www.inf.ufrgs.br/~oliveira/pubs_files/Oliveira_Policarpo_RP-351_Jan_2005.pdf
[GPU gems]:
https://developer.nvidia.com/gpugems/gpugems3/part-iii-rendering/chapter-18-relaxed-cone-stepping-relief-mapping
[simcity]:
https://community.simtropolis.com/omnibus/other-games/building-and-rendering-simcity-2013-r247/
[offset limiting]:
https://raw.githubusercontent.com/marcusstenbeck/tncg14-parallax-mapping/master/documents/Parallax%20Mapping%20with%20Offset%20Limiting%20-%20A%20Per-Pixel%20Approximation%20of%20Uneven%20Surfaces.pdf
[gltf]: https://github.com/KhronosGroup/glTF/pull/2196
[qpm]:
https://www.gamedevs.org/uploads/quadtree-displacement-mapping-with-height-blending.pdf

---

## Changelog

- Add a `depth_map` field to the `StandardMaterial`, it is a grayscale
  image where white represents bottom and black the top. If `depth_map`
  is set, bevy's pbr shader will use it to do [parallax mapping] to
  give an increased feel of depth to the material. This is similar to a
  displacement map, but with infinite precision at fairly low cost.
- The fields `parallax_mapping_method`, `parallax_depth_scale` and
  `max_parallax_layer_count` allow finer grained control over the
  behavior of the parallax shader.
- Add the `parallax_mapping` example to show off the effect.

[parallax mapping]: https://en.wikipedia.org/wiki/Parallax_mapping

---------

Co-authored-by: Robert Swain <robert.swain@gmail.com>
2023-04-15 10:25:14 +00:00
JoJoJet
1074a41b87
Fix docs for fixed timestep (#8363)
# Objective

The docs for `FixedTime::expend` are unfinished.
2023-04-14 19:41:31 +00:00
Jannik Obermann
d47bb3e6e9
Sync pbr_types.wgsl StandardMaterial values (#8380)
# Objective

The default StandardMaterial values of `pbr_material.rs` and
`pbr_types.wgsl` are out of sync.
I think they are out of sync since
https://github.com/bevyengine/bevy/pull/7664.

## Solution

Adapt the values: `metallic = 0.0`, `perceptual_roughness = 0.5`.
2023-04-14 05:52:57 +00:00
ickshonpe
0cbabefbad
UiRect axes constructor (#7656)
# Objective

We don't have a constructor function for `UiRect` that sets uniform
horizontal and vertical values, even though it is a common pattern.

## Solution

Add a constructor function to `UiRect` called `axes`, that sets both
`left` and `right` to the same given horizontal value,
and sets both `top` and `bottom` to same given vertical value.

## Changelog

* Added a constructor function `axes` to `UiRect`.
2023-04-13 20:52:21 +00:00
Sam T
b9f3272177
added multi-line string formatting (#8350)
# Objective

fixes #8348

## Solution

- Uses multi-line string with backslashes allowing rustfmt to work
properly in the surrounding area.

---------

Co-authored-by: François <mockersf@gmail.com>
2023-04-13 18:00:17 +00:00
JoJoJet
c37a53d52d
Add a regression test for change detection between piped systems (#8368)
# Objective

The behavior of change detection within `PipeSystem` is very tricky and
subtle, and is not currently covered by any of our tests as far as I'm
aware.
2023-04-13 17:59:29 +00:00
James Liu
2ec38d1467
Inline more ECS functions (#8083)
# Objective
Upon closer inspection, there are a few functions in the ECS that are
not being inlined, even with the highest optimizations and LTO enabled:

- Almost all
[WorldQuery::init_fetch](9fd5f20e25/results/query_get.s (L57))
calls. Affects `Query::get` calls in hot loops. In particular, the
`WorldQuery` implementation for `()` is used *everywhere* as the default
filter and is effectively a no-op.
-
[Entities::get](9fd5f20e25/results/query_get.s (L39)).
Affects `Query::get`, `World::get`, and any component insertion or
removal.
-
[Entities::set](9fd5f20e25/results/entity_remove.s (L2487)).
Affects any component insertion or removal.
-
[Tick::new](9fd5f20e25/results/entity_insert.s (L1368)).
I've only seen this in component insertion and spawning.
 - ArchetypeRow::new
 - BlobVec::set_len

Almost all of these have trivial or even empty implementations or have
significant opportunity to be optimized into surrounding code when
inlined with LTO enabled.

## Solution
Inline them
2023-04-12 19:52:06 +00:00
JoJoJet
f3c7ccefc6
Fix panics and docs when using World schedules (#8364)
# Objective

The method `World::try_run_schedule` currently panics if the `Schedules`
resource does not exist, but it should just return an `Err`. Similarly,
`World::add_schedule` panics unnecessarily if the resource does not
exist.

Also, the documentation for `World::add_schedule` is completely wrong.

## Solution

When the `Schedules` resource does not exist, we now treat it the same
as if it did exist but was empty. When calling `add_schedule`, we
initialize it if it does not exist.
2023-04-12 19:29:08 +00:00
Olle Lukowski
14abff99f6
Improved AnimationPlugin declaration. (#8361)
# Objective

Fixes #8347.

## Solution

Implemented the suggested change to the `AnimationPlugin` declaration.
2023-04-12 19:27:38 +00:00
Jonah Henriksson
55e9ab7c92
Cleaned up panic messages (#8219)
# Objective

Fixes #8215 and #8152. When systems panic, it causes the main thread to
panic as well, which clutters the output.

## Solution

Resolves the panic in the multi-threaded scheduler. Also adds an extra
message that tells the user the system that panicked.

Using the example from the issue, here is what the messages now look
like:

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

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Update, panicking_system)
        .run();
}

fn panicking_system() {
    panic!("oooh scary");
}
```
### Before
```
   Compiling bevy_test v0.1.0 (E:\Projects\Rust\bevy_test)
    Finished dev [unoptimized + debuginfo] target(s) in 2m 58s
     Running `target\debug\bevy_test.exe`
2023-03-30T22:19:09.234932Z  INFO bevy_diagnostic::system_information_diagnostics_plugin::internal: SystemInfo { os: "Windows 10 Pro", kernel: "19044", cpu: "AMD Ryzen 5 2600 Six-Core Processor", core_count: "6", memory: "15.9 GiB" }
thread 'Compute Task Pool (5)' panicked at 'oooh scary', src\main.rs:11:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'Compute Task Pool (5)' panicked at 'A system has panicked so the executor cannot continue.: RecvError', E:\Projects\Rust\bevy\crates\bevy_ecs\src\schedule\executor\multi_threaded.rs:194:60
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', E:\Projects\Rust\bevy\crates\bevy_tasks\src\task_pool.rs:376:49
error: process didn't exit successfully: `target\debug\bevy_test.exe` (exit code: 101)
```
### After
```
   Compiling bevy_test v0.1.0 (E:\Projects\Rust\bevy_test)
    Finished dev [unoptimized + debuginfo] target(s) in 2.39s
     Running `target\debug\bevy_test.exe`
2023-03-30T22:11:24.748513Z  INFO bevy_diagnostic::system_information_diagnostics_plugin::internal: SystemInfo { os: "Windows 10 Pro", kernel: "19044", cpu: "AMD Ryzen 5 2600 Six-Core Processor", core_count: "6", memory: "15.9 GiB" }
thread 'Compute Task Pool (5)' panicked at 'oooh scary', src\main.rs:11:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Encountered a panic in system `bevy_test::panicking_system`!
Encountered a panic in system `bevy_app::main_schedule::Main::run_main`!
error: process didn't exit successfully: `target\debug\bevy_test.exe` (exit code: 101)
```

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: François <mockersf@gmail.com>
2023-04-12 18:27:28 +00:00
JoJoJet
7ec89004dd
Only trigger state transitons if next_state != old_state (#8359)
# Objective

Fix #8191.

Currently, a state transition will be triggered whenever the `NextState`
resource has a value, even if that "transition" is to the same state as
the previous one. This caused surprising/meaningless behavior, such as
the existence of an `OnTransition { from: A, to: A }` schedule.

## Solution

State transition schedules now only run if the new state is not equal to
the old state. Change detection works the same way, only being triggered
when the states compare not equal.

---

## Changelog

- State transition schedules are no longer run when transitioning to and
from the same state.

## Migration Guide

State transitions are now only triggered when the exited and entered
state differ. This means that if the world is currently in state `A`,
the `OnEnter(A)` schedule (or `OnExit`) will no longer be run if you
queue up a state transition to the same state `A`.
2023-04-12 17:07:13 +00:00
James Liu
d623731e2c
Move event traces to detailed_trace! (#7732)
# Objective
Noticed while writing #7728 that we are using `trace!` logs in our event
functions. This has shown to have significant overhead, even trace level
logs are disabled globally, as seen in #7639.

## Solution
Use the `detailed_trace!` macro introduced in #7639. Also removed the
`event_trace` function that was only used in one location.

---

## Changelog
Changed: Event trace logs are now feature gated behind the
`detailed-trace` feature.
2023-04-11 03:37:58 +00:00
ira
52ee83e7e8
Fix viewport change detection (#8323)
# Objective

Fix #8321

## Solution

The `old_viewport_size` that is used to detect whether the viewport has
changed was not being updated and thus always `None`.
2023-04-10 20:41:32 +00:00
Liam Gallagher
dff071c2a8
Ability to set a Global Volume (#7706)
# Objective

Adds a new resource to control a global volume.
Fixes #7690

---

## Solution

Added a new resource to control global volume, this is then multiplied
with an audio sources volume to get the output volume, individual audio
sources can opt out of this my enabling the `absolute_volume` field in
`PlaybackSettings`.

---

## Changelog

### Added
- `GlobalVolume` a resource to control global volume (in prelude).
- `global_volume` field to `AudioPlugin` or setting the initial value of
`GlobalVolume`.
- `Volume` enum that can be `Relative` or `Absolute`.
- `VolumeLevel` struct for defining a volume level.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-04-10 14:08:43 +00:00
robtfm
cc8f023b3a
fix invalid bone weights (#8316)
# Objective

when a mesh uses zero for all bone weights, vertices end up in the
middle of the screen.

## Solution

we can address this by explicitly setting the first bone weight to 1
when the weights are given as zero. this is the approach taken by
[unity](https://forum.unity.com/threads/whats-the-problem-with-this-import-fbx-warning.133736/)
(although that also sets the bone index to zero) and
[three.js](94c1a4b86f/src/objects/SkinnedMesh.js (L98)),
and likely other engines.

## Alternatives

it does add a bit of overhead, and users can always fix this themselves,
though it's a bit awkward particularly with gltfs.

(note - this is for work so my sme status shouldn't apply)

---------

Co-authored-by: ira <JustTheCoolDude@gmail.com>
2023-04-10 07:49:53 +00:00
Nicola Papale
f32ee63fb1
Fix transform propagation of orphaned entities (#7264)
# Objective

- Fix #7263

This has nothing to do with #7024. This is for the case where the
user opted to **not** keep the same global transform on update.

## Solution

- Add a `RemovedComponent<Parent>` to `propagate_transforms`
- Add a `RemovedComponent<Parent>` and `Local<Vec<Entity>>` to
`sync_simple_transforms`
- Add test to make sure all of this works.

### Performance note

This should only incur a cost in cases where a parent is removed.

A minimal overhead (one look up in the `removed_components`
sparse set) per root entities without children which transform didn't
change. A `Vec` the size of the largest number of entities removed
with a `Parent` component in a single frame, and a binary search on
a `Vec` per root entities.

It could slow up considerably in situations where a lot of entities are
orphaned consistently during every frame, since
`sync_simple_transforms` is not parallel. But in this situation,
it is likely that the overhead of archetype updates overwhelms
everything.

---

## Changelog

- Fix the `GlobalTransform` not getting updated when `Parent` is removed

## Migration Guide

- If you called `bevy_transform::systems::sync_simple_transforms` and
`bevy_transform::systems::propagate_transforms` (which is not
re-exported by bevy) you need to account for the additional
`RemovedComponents<Parent>` parameter.

---------

Co-authored-by: vyb <vyb@users.noreply.github.com>
Co-authored-by: JoJoJet <21144246+JoJoJet@users.noreply.github.com>
2023-04-09 20:53:33 +00:00
Ashy
0d971a63e4
Added documentation to the fields within derived read-only types (#8334)
Fixes #8333

# Objective

Fixes issue which causes failure to compile if using
`#![deny(missing_docs)]`.

## Solution

Added some very basic commenting to the generated read-only fields.
honestly I feel this to be up for debate since the comments are very
basic and give very little useful information but the purpose of this PR
is to fix the issue at hand.

---

## Changelog

Added comments to the derive macro and the projects now successfully
compile.

---------

Co-authored-by: lupan <kallll5@hotmail.com>
2023-04-09 14:37:34 +00:00
Mikkel Rasmussen
e9312254d8
Non-breaking change* from UK spellings to US (#8291)
Fixes issue mentioned in PR #8285.

_Note: By mistake, this is currently dependent on #8285_
# Objective

Ensure consistency in the spelling of the documentation.

Exceptions:
`crates/bevy_mikktspace/src/generated.rs` - Has not been changed from
licence to license as it is part of a licensing agreement.

Maybe for further consistency,
https://github.com/bevyengine/bevy-website should also be given a look.

## Solution

### Changed the spelling of the current words (UK/CN/AU -> US) :
cancelled -> canceled (Breaking API changes in #8285)
behaviour -> behavior (Breaking API changes in #8285)
neighbour -> neighbor
grey -> gray
recognise -> recognize
centre -> center
metres -> meters
colour -> color

### ~~Update [`engine_style_guide.md`]~~ Moved to #8324 

---

## Changelog

Changed UK spellings in documentation to US

## Migration Guide

Non-breaking changes*

\* If merged after #8285
2023-04-08 16:22:46 +00:00
JoJoJet
3ead10a3e0
Suppress the clippy::type_complexity lint (#8313)
# Objective

The clippy lint `type_complexity` is known not to play well with bevy.
It frequently triggers when writing complex queries, and taking the
lint's advice of using a type alias almost always just obfuscates the
code with no benefit. Because of this, this lint is currently ignored in
CI, but unfortunately it still shows up when viewing bevy code in an
IDE.

As someone who's made a fair amount of pull requests to this repo, I
will say that this issue has been a consistent thorn in my side. Since
bevy code is filled with spurious, ignorable warnings, it can be very
difficult to spot the *real* warnings that must be fixed -- most of the
time I just ignore all warnings, only to later find out that one of them
was real after I'm done when CI runs.

## Solution

Suppress this lint in all bevy crates. This was previously attempted in
#7050, but the review process ended up making it more complicated than
it needs to be and landed on a subpar solution.

The discussion in https://github.com/rust-lang/rust-clippy/pull/10571
explores some better long-term solutions to this problem. Since there is
no timeline on when these solutions may land, we should resolve this
issue in the meantime by locally suppressing these lints.

### Unresolved issues

Currently, these lints are not suppressed in our examples, since that
would require suppressing the lint in every single source file. They are
still ignored in CI.
2023-04-06 21:27:36 +00:00
ira
585baf0a66
Consistent screen-space coordinates (#8306)
# Objective

Make the coordinate systems of screen-space items (cursor position, UI,
viewports, etc.) consistent.

## Solution

Remove the weird double inversion of the cursor position's Y origin.
Once in bevy_winit to the bottom and then again in bevy_ui back to the
top.
This leaves the origin at the top left like it is in every other popular
app framework.

Update the `world_to_viewport`, `viewport_to_world`, and
`viewport_to_world_2d` methods to flip the Y origin (as they should
since the viewport coordinates were always relative to the top left).

## Migration Guide

`Window::cursor_position` now returns the position of the cursor
relative to the top left instead of the bottom left.
This now matches other screen-space coordinates like
`RelativeCursorPosition`, UI, and viewports.

The `world_to_viewport`, `viewport_to_world`, and `viewport_to_world_2d`
methods on `Camera` now return/take the viewport position relative to
the top left instead of the bottom left.

If you were using `world_to_viewport` to position a UI node the returned
`y` value should now be passed into the `top` field on `Style` instead
of the `bottom` field.
Note that this might shift the position of the UI node as it is now
anchored at the top.

If you were passing `Window::cursor_position` to `viewport_to_world` or
`viewport_to_world_2d` no change is necessary.
2023-04-05 22:32:36 +00:00
ickshonpe
1a7f046c4d
Fix size of clipped text glyphs. (#8197)
# Objective

Text glyphs that were clipped were not sized correctly because the
transform extracted from the `extract_text_uinodes` had a scaling on it
that wasn't accounted for.

fixes #8167

## Solution

Remove the scaling from the transform and multiply the size of the
glyphs by the inverse of the scale factor.
2023-04-05 22:26:52 +00:00
ickshonpe
ff9f2234f3
UiImage helper functions (#8199)
# Objective

Add helper functions to `UiImage` for creating flipped images.

## Changelog

* Added `with_flip_x` and `with_flip_y` methods to `UiImage` that return
the `UiImage` flipped along the respective axis.
2023-04-05 22:19:46 +00:00
Hank Jordan
28046d5142
Expose AudioSink::empty() (#8145)
# Objective

Exposes `empty()` method for `AudioSink`.
Based on `0.10.0`, should be a non-breaking change.

---

## Changelog

- Expose `empty()` method for `AudioSink`
- Add `AudioSink::empty()` example

---------

Co-authored-by: hank <hank@hank.co.in>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-04-05 21:54:14 +00:00
ickshonpe
6e67d3e534
Remove the corresponding measure from Taffy when a CalculatedSize component is removed. (#8294)
# Objective

When a `CalculatedSize` component from a UI Node entity is removed, the
corresponding Taffy measure isn't removed which will mess up the layout
in confusing, unpredictable ways.

## Solution

Iterate through all the entities with removed `CalculatedSize`
components and remove the corresponding Taffy measures.
2023-04-05 21:29:29 +00:00
Mikkel Rasmussen
1575481429
Changed spelling linebreak_behaviour to linebreak_behavior (#8285)
# Objective

In the
[`Text`](3442a13d2c/crates/bevy_text/src/text.rs (L18))
struct the field is named: `linebreak_behaviour`, the British spelling
of _behavior_.
**Update**, also found: 
- `FileDragAndDrop::HoveredFileCancelled` 
- `TouchPhase::Cancelled`
- `Touches.just_cancelled`

The majority of all spelling is in the US but when you have a lot of
contributors across the world, sometimes
spelling differences can pop up in APIs such as in this case. 

For consistency, I think it would be worth a while to ensure that the
API is persistent.

Some examples:
`from_reflect.rs` has `DefaultBehavior`
TextStyle has `color` and uses the `Color` struct.
In `bevy_input/src/Touch.rs` `TouchPhase::Cancelled` and _canceled_ are
used interchangeably in the documentation

I've found that there is also the same type of discrepancies in the
documentation, though this is a low priority but is worth checking.
**Update**: I've now checked the documentation (See #8291)

## Solution

I've only renamed the inconsistencies that have breaking changes and
documentation pertaining to them. The rest of the documentation will be
changed via #8291.

Do note that the winit API is written with UK spelling, thus this may be
a cause for confusion:
`winit::event::TouchPhase::Cancelled => TouchPhase::Canceled`
`winit::event::WindowEvent::HoveredFileCancelled` -> Related to
`FileDragAndDrop::HoveredFileCanceled`

But I'm hoping to maybe outline other spelling inconsistencies in the
API, and maybe an addition to the contribution guide.

---

## Changelog

- `Text` field `linebreak_behaviour` has been renamed to
`linebreak_behavior`.
- Event `FileDragAndDrop::HoveredFileCancelled` has been renamed to
`HoveredFileCanceled`
- Function `Touches.just_cancelled` has been renamed to
`Touches.just_canceled`
- Event `TouchPhase::Cancelled` has been renamed to
`TouchPhase::Canceled`

## Migration Guide

Update where `linebreak_behaviour` is used to `linebreak_behavior`
Updated the event `FileDragAndDrop::HoveredFileCancelled` where used to
`HoveredFileCanceled`
Update `Touches.just_cancelled` where used as `Touches.just_canceled`
The event `TouchPhase::Cancelled` is now called `TouchPhase::Canceled`
2023-04-05 21:25:53 +00:00
IceSentry
c70776b3cf
Use RenderGraphApp in more places (#8298)
# Objective

- RenderGraphExt was merged, but only used in limited situations

## Solution

- Fix some remaining issues with the existing api
- Use the new api in the main pass and mass writeback
- Add CORE_2D and CORE_3D constant to make render_graph code shorter
2023-04-05 20:57:56 +00:00
Erik Šabič
0a17751d16
Minor mistake in Frustum::intersects_obb (#8305)
# Objective

Fix a minor mistake

## Solution

Replaced an extraction of a plane normal with an existing method
2023-04-05 19:37:59 +00:00
James Liu
21e1893c4f
Remove capacity fields from all Buffer wrapper types (#8301)
# Objective
While working on #8299, I noticed that we're using a `capacity` field,
even though `wgpu::Buffer` exposes a `size` accessor that does the same
thing.

## Solution
Remove it from all buffer wrappers. Use `wgpu::Buffer::size` instead.
Default to 0 if no buffer has been allocated yet.
2023-04-04 20:12:31 +00:00
James Liu
63d89d31ba
Remove unnecesssary values Vec from DynamicUniformBuffer and DynamicStorageBuffer (#8299)
# Objective
Fixes #8284. `values` is being pushed to separately from the actual
scratch buffer in `DynamicUniformBuffer::push` and
`DynamicStorageBuffer::push`. In both types, `values` is really only
used to track the number of elements being added to the buffer, yet is
causing extra allocations, size increments and excess copies.

## Solution
Remove it and its remaining uses. Replace it with accesses to `scratch`
instead.

I removed the `len` accessor, as it may be non-trivial to compute just
from `scratch`. If this is still desirable to have, we can keep a `len`
member field to track it instead of relying on `scratch`.
2023-04-04 20:12:19 +00:00
Aceeri
ed50c8b4d9
Make state private and only accessible through getter for State resource (#8009)
# Objective
State requires a kind of awkward `state.0` to get the current state and
exposes the field directly to manipulation.

## Solution
Make it accessible through a getter method as well as privatize the
field to make sure false assumptions about setting the state aren't
made.

## Migration Guide
- Use `State::get` instead of accessing the tuple field directly.
2023-04-04 01:25:54 +00:00
IceSentry
614de3019c
Add RenderGraphApp to simplify adding render nodes (#8007)
# Objective

- Adding a node to the render_graph can be quite verbose and error prone
because there's a lot of moving parts to it.

## Solution

- Encapsulate this in a simple utility method
	- Mostly intended for optional nodes that have specific ordering
- Requires that the `Node` impl `FromWorld`, but every internal node is
built using a new function taking a `&mut World` so it was essentially
already `FromWorld`
- Use it for the bloom, fxaa and taa, nodes. 
- The main nodes don't use it because they rely more on the order of
many nodes being added

---

## Changelog

- Impl `FromWorld` for `BloomNode`, `FxaaNode` and `TaaNode`
- Added `RenderGraph::add_node_edges()`
- Added `RenderGraph::sub_graph()`
- Added `RenderGraph::sub_graph_mut()`
- Added `RenderGraphApp`, `RenderGraphApp::add_render_graph_node`,
`RenderGraphApp::add_render_graph_edges`,
`RenderGraphApp::add_render_graph_edge`

## Notes

~~This was taken out of https://github.com/bevyengine/bevy/pull/7995
because it works on it's own. Once the linked PR is done, the new
`add_node()` will be simplified a bit since the input/output params
won't be necessary.~~

This feature will be useful in most of the upcoming render nodes so it's
impact will be more relevant at that point.

Partially fixes #7985 

## Future work

* Add a way to automatically label nodes or at least make it part of the
trait. This would remove one more field from the functions added in this
PR
* Use it in the main pass 2d/3d

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-04-04 00:50:22 +00:00
张林伟
5c7abb0579
Remove OnUpdate system set (#8260)
# Objective

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

## Solution

- Replace `OnUpdate` with `run_if(in_state(xxx))`.

---

## Migration Guide

- Replace `OnUpdate` with `run_if(in_state(xxx))`.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-04-04 00:49:41 +00:00
JoJoJet
b423e6ee15
Extend the WorldQuery macro to tuple structs (#8119)
# Objective

The `#[derive(WorldQuery)]` macro currently only supports structs with
named fields.

Same motivation as #6957. Remove sharp edges from the derive macro, make
it just work more often.

## Solution

Support tuple structs.

---

## Changelog

+ Added support for tuple structs to the `#[derive(WorldQuery)]` macro.
2023-04-04 00:49:03 +00:00
Zhixing Zhang
2aaaed7f69
Make bevy_render an optional dependency of bevy_scene (#8136)
# Objective

bevy-scene does not have a reason to depend on bevy-render except to
include the `Visibility` and `ComputedVisibility` components. Including
that in the dependency chain is unnecessary for people not using
`bevy_render`.

Also fixed a problem where compilation fails when the `serialize`
feature was not enabled.

## Solution

This was added in #5335 to address some of the problems caused by #5310.

Imo the user just always have to remember to include `VisibilityBundle`
when they spawn `SceneBundle` or `DynamicSceneBundle`, but that will be
a breaking change. This PR makes `bevy_render` an optional dependency of
`bevy_scene` instead to respect the existing behavior.
2023-04-03 21:23:26 +00:00
JoJoJet
086db6d22f
Update increment_change_tick to return a strongly-typed Tick (#8295)
# Objective

While migrating the engine to use the `Tick` type in #7905, I forgot to
update `UnsafeWorldCell::increment_change_tick`.

## Solution

Update the function.

---

## Changelog

- The function `UnsafeWorldCell::increment_change_tick` is now
strongly-typed, returning a value of type `Tick` instead of a raw `u32`.

## Migration Guide

The function `UnsafeWorldCell::increment_change_tick` is now
strongly-typed, returning a value of type `Tick` instead of a raw `u32`.
2023-04-03 17:42:27 +00:00
Elabajaba
09f1bd0be7
Add port of AMD's Robust Contrast Adaptive Sharpening (#7422)
# Objective

TAA, FXAA, and some other post processing effects can cause the image to
become blurry. Sharpening helps to counteract that.

## Solution

~~This is a port of AMD's Contrast Adaptive Sharpening (I ported it from
the
[SweetFX](https://github.com/CeeJayDK/SweetFX/blob/master/Shaders/CAS.fx)
version, which is still MIT licensed). CAS is a good sharpening
algorithm that is better at avoiding the full screen oversharpening
artifacts that simpler algorithms tend to create.~~

This is a port of AMD's Robust Contrast Adaptive Sharpening (RCAS) which
they developed for FSR 1 ([and continue to use in FSR
2](149cf26e12/src/ffx-fsr2-api/shaders/ffx_fsr1.h (L599))).
RCAS is a good sharpening algorithm that is better at avoiding the full
screen oversharpening artifacts that simpler algorithms tend to create.

---

## Future Work

- Consider porting this to a compute shader for potentially better
performance. (In my testing it is currently ridiculously cheap (0.01ms
in Bistro at 1440p where I'm GPU bound), so this wasn't a priority,
especially since it would increase complexity due to still needing the
non-compute version for webgl2 support).

---

## Changelog

- Added Contrast Adaptive Sharpening.

---------

Co-authored-by: JMS55 <47158642+JMS55@users.noreply.github.com>
2023-04-02 20:14:01 +00:00
JMS55
f0f5d79917
Built-in skybox (#8275)
# Objective

- Closes https://github.com/bevyengine/bevy/issues/8008

## Solution

- Add a skybox plugin that renders a fullscreen triangle, and then
modifies the vertices in a vertex shader to enforce that it renders as a
skybox background.
- Skybox is run at the end of MainOpaquePass3dNode.
- In the future, it would be nice to get something like bevy_atmosphere
built-in, and have a default skybox+environment map light.

---

## Changelog

- Added `Skybox`.
- `EnvironmentMapLight` now renders in the correct orientation.

## Migration Guide
- Flip `EnvironmentMapLight` maps if needed to match how they previously
rendered (which was backwards).

---------

Co-authored-by: Robert Swain <robert.swain@gmail.com>
Co-authored-by: robtfm <50659922+robtfm@users.noreply.github.com>
2023-04-02 10:57:12 +00:00
Gajo Petrovic
9079f6d976
Fix UI node docs (#8287)
# Objective

- Fix some (probably) incorrect docs.
2023-04-02 00:02:01 +00:00
Sludge
d193d7f537
Reflect Component and Default of BloomSettings (#8283)
These traits are both implemented, but not reflected, requiring user
code to do `app.register_type_data::<BloomSettings,
ReflectDefault>().register_type_data::<BloomSettings,
ReflectComponent>()` to make these usable via reflection.
2023-04-01 18:59:41 +00:00
JoJoJet
3442a13d2c
Use UnsafeWorldCell to increase code quality for SystemParam (#8174)
# Objective

The type `&World` is currently in an awkward place, since it has two
meanings:
1. Read-only access to the entire world.
2. Interior mutable access to the world; immutable and/or mutable access
to certain portions of world data.

This makes `&World` difficult to reason about, and surprising to see in
function signatures if one does not know about the interior mutable
property.

The type `UnsafeWorldCell` was added in #6404, which is meant to
alleviate this confusion by adding a dedicated type for interior mutable
world access. However, much of the engine still treats `&World` as an
interior mutable-ish type. One of those places is `SystemParam`.

## Solution

Modify `SystemParam::get_param` to accept `UnsafeWorldCell` instead of
`&World`. Simplify the safety invariants, since the `UnsafeWorldCell`
type encapsulates the concept of constrained world access.

---

## Changelog

`SystemParam::get_param` now accepts an `UnsafeWorldCell` instead of
`&World`. This type provides a high-level API for unsafe interior
mutable world access.

## Migration Guide

For manual implementers of `SystemParam`: the function `get_item` now
takes `UnsafeWorldCell` instead of `&World`. To access world data, use:

* `.get_entity()`, which returns an `UnsafeEntityCell` which can be used
to access component data.
* `get_resource()` and its variants, to access resource data.
2023-04-01 15:45:07 +00:00
fren_gor
253db50c63
Fix typo in bevy_reflect README (#8281)
# Objective

Fix typo in bevy_reflect README: `MyType` is a struct and not a trait,
so `&dyn MyType` is incorrect.

## Solution

Replace `&dyn MyType` with `&dyn DoThing`
2023-04-01 03:01:44 +00:00
JoJoJet
ae39b07d26
Replace some unsafe system executor code with safe code (#8274)
# Objective

The function `SyncUnsafeCell::from_mut` returns `&SyncUnsafeCell<T>`,
even though it could return `&mut SyncUnsafeCell<T>`. This means it is
not possible to call `get_mut` on the returned value, so you need to use
unsafe code to get exclusive access back.

## Solution

Return `&mut Self` instead of `&Self` in `SyncUnsafeCell::from_mut`.
This is consistent with my proposal for `UnsafeCell::from_mut`:
https://github.com/rust-lang/libs-team/issues/198.

Replace an unsafe pointer dereference with a safe call to `get_mut`.

---

## Changelog

+ The function `bevy_utils::SyncUnsafeCell::get_mut` now returns a value
of type `&mut SyncUnsafeCell<T>`. Previously, this returned an immutable
reference.

## Migration Guide

The function `bevy_utils::SyncUnsafeCell::get_mut` now returns a value
of type `&mut SyncUnsafeCell<T>`. Previously, this returned an immutable
reference.
2023-03-31 21:56:49 +00:00
JoJoJet
711efed018
Fix inaccurate documentation on `QueryState::for_each_unchecked (#8277)
# Objective

The documentation on `QueryState::for_each_unchecked` incorrectly says
that it can only be used with read-only queries.

## Solution

Remove the inaccurate sentence.
2023-03-31 16:54:36 +00:00
Jannik Obermann
f201a9df39
Fix CubicCurve::iter_samples iteration count (#8049)
# Objective

Fix `CubicCurve::iter_samples` iteration count.

## Solution

If I understand the function and the docs correctly, this should iterate
over `0..=subdivisions` instead of `0..subdivisions`.
For example: Now the iteration returns 3 points at `subdivisions = 2`,
as indicated in the documentation.
2023-03-31 08:15:21 +00:00
JoJoJet
a954f3e150
Remove #[system_param(ignore)] and #[world_query(ignore)] (#8265)
# Objective

Follow-up to #8030.

Now that `SystemParam` and `WorldQuery` are implemented for
`PhantomData`, the `ignore` attributes are now unnecessary.

---

## Changelog

- Removed the attributes `#[system_param(ignore)]` and
`#[world_query(ignore)]`.

## Migration Guide

The attributes `#[system_param(ignore)]` and `#[world_query]` ignore
have been removed. If you were using either of these with `PhantomData`
fields, you can simply remove the attribute:

```rust
#[derive(SystemParam)]
struct MyParam<'w, 's, Marker> {
    ...
    // Before:
    #[system_param(ignore)
    _marker: PhantomData<Marker>,

    // After:
    _marker: PhantomData<Marker>,
}
#[derive(WorldQuery)]
struct MyQuery<Marker> {
    ...
    // Before:
    #[world_query(ignore)
    _marker: PhantomData<Marker>,

    // After:
    _marker: PhantomData<Marker>,
}
```

If you were using this for another type that implements `Default`,
consider wrapping that type in `Local<>` (this only works for
`SystemParam`):

```rust
#[derive(SystemParam)]
struct MyParam<'w, 's> {
    // Before:
    #[system_param(ignore)]
    value: MyDefaultType, // This will be initialized using `Default` each time `MyParam` is created.

    // After:
    value: Local<MyDefaultType>, // This will be initialized using `Default` the first time `MyParam` is created.
}
```

If you are implementing either trait and need to preserve the exact
behavior of the old `ignore` attributes, consider manually implementing
`SystemParam` or `WorldQuery` for a wrapper struct that uses the
`Default` trait:

```rust
// Before:

#[derive(WorldQuery)
struct MyQuery {
   #[world_query(ignore)]
    str: String,
}

// After:

#[derive(WorldQuery)
struct MyQuery {
    str: DefaultQuery<String>,
}

pub struct DefaultQuery<T: Default>(pub T);

unsafe impl<T: Default> WorldQuery for DefaultQuery<T> {
    type Item<'w> = Self;
    ...
    unsafe fn fetch<'w>(...) -> Self::Item<'w> {
        Self(T::default())
    }
}
```
2023-03-30 23:02:25 +00:00
JoJoJet
98954311b3
Use actual tests for SystemParam regression tests (#8270)
# Objective

Our regression tests for `SystemParam` currently consist of a bunch of
loosely dispersed struct definitions. This is messy, and doesn't fully
test their functionality.

## Solution

Group the struct definitions into functions annotated with `#[test]`.
This not only makes the module more organized, but it allows us to call
`assert_is_system`, which has the potential to catch some bugs that
would have been missed with the old approach. Also, this approach is
consistent with how `WorldQuery` regression tests are organized.
2023-03-30 21:47:36 +00:00
Edgar Geier
300b275edc
run_if for SystemConfigs via anonymous system sets (#7676)
# Objective

- Fixes #7659

## Solution

The idea of anonymous system sets or "implicit hidden organizational
sets" was briefly mentioned by @cart here:
https://github.com/bevyengine/bevy/pull/7634#issuecomment-1428619449.

- `Schedule::add_systems` creates an implicit, anonymous system set of
all systems in `SystemConfigs`.
- All dependencies and conditions from the `SystemConfigs` are now
applied to the implicit system set, instead of being applied to each
individual system. This should not change the behavior, AFAIU, because
`before`, `after`, `run_if` and `ambiguous_with` are transitive
properties from a set to its members.
- The newly added `AnonymousSystemSet` stores the names of its members
to provide better error messages.
- The names are stored in a reference counted slice, allowing fast
clones of the `AnonymousSystemSet`.
- However, only the pointer of the slice is used for hash and equality
operations
- This ensures that two `AnonymousSystemSet` are not equal, even if they
have the same members / member names.
- So two identical `add_systems` calls will produce two different
`AnonymousSystemSet`s.
  - Clones of the same `AnonymousSystemSet` will be equal.

## Drawbacks
If my assumptions are correct, the observed behavior should stay the
same. But the number of system sets in the `Schedule` will increase with
each `add_systems` call. If this has negative performance implications,
`add_systems` could be changed to only create the implicit system set if
necessary / when a run condition was added.

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-03-30 21:39:10 +00:00
Edgar Geier
a1d771a772
Remove base set error variants of ScheduleBuildError (#8269)
# Objective

With the removal of base sets, some variants of `ScheduleBuildError` can
never occur and should be removed.

## Solution

- Remove the obsolete variants of `ScheduleBuildError`.
- Also fix a doc comment which mentioned base sets.

---

## Changelog

### Removed

- Remove `ScheduleBuildError::SystemInMultipleBaseSets` and
`ScheduleBuildError::SetInMultipleBaseSets`.
2023-03-30 20:32:50 +00:00
JoJoJet
3533c3dae9
Improve documentation for set_if_neq (#8254)
# Objective

Reword the documentation for `set_if_neq` and add a doctest.
2023-03-30 15:43:13 +00:00
JoJoJet
d9113cca6f
Make #[system_param(ignore)] and #[world_query(ignore)] unnecessary (#8030)
# Objective

When using `PhantomData` fields with the `#[derive(SystemParam)]` or
`#[derive(WorldQuery)]` macros, the user is required to add the
`#[system_param(ignore)]` attribute so that the macro knows to treat
that field specially. This is undesirable, since it makes the macro more
fragile and less consistent.

## Solution

Implement `SystemParam` and `WorldQuery` for `PhantomData`. This makes
the `ignore` attributes unnecessary.

Some internal changes make the derive macro compatible with types that
have invariant lifetimes, which fixes #8192. From what I can tell, this
fix requires `PhantomData` to implement `SystemParam` in order to ensure
that all of a type's generic parameters are always constrained.

---

## Changelog

+ Implemented `SystemParam` and `WorldQuery` for `PhantomData<T>`.
+ Fixed a miscompilation caused when invariant lifetimes were used with
the `SystemParam` macro.
2023-03-30 15:12:26 +00:00
JoJoJet
f219a08907
Simplify Clone for ThinSlicePtr (#8247)
# Objective

The type `ThinSlicePtr` has a manual implementation of `Clone` that
manually clones each field. Since this type implements `Copy`, we can
change this implementation to simply dereference `&self`.
2023-03-30 10:22:09 +00:00
JoJoJet
dbb9e428cd
Miscellaneous cleanups to World::resource_scope (#8256)
# Objective

* Make a safety comment less tautological.
* Clearly document that the function can run user code.
* Other small changes.
2023-03-30 10:17:08 +00:00
Rob Parrett
a141aed67d
Format SystemState doc example code (#8261)
# Objective

I noticed some funky whitespace in the examples in the
[`SystemState`](https://docs.rs/bevy/latest/bevy/ecs/system/struct.SystemState.html#example)
doc examples.

## Solution

Semi-manually reformatted these particular code blocks and hid some of
the imports and boilerplate not relevant to the example.


([format_code_in_doc_comments](https://rust-lang.github.io/rustfmt/?version=v1.5.1&search=#format_code_in_doc_comments)
seemingly has a bunch of issues and has not been stabilized)
2023-03-30 10:06:05 +00:00
Robert Walter
5f0abbfd15
Make standard commands more ergonomic (in niche cases) (#8249)
# Objective

I ran into a case where I need to create a `CommandQueue` and push
standard `Command` actions like `Insert` or `Remove` to it manually. I
saw that `Remove` looked as follows:

```rust
struct Remove<T> {
  entity: Entity,
  phantom: PhantomData<T>
}
```

so naturally, I tried to use `Remove::<Foo>::from(entity)` but it didn't
exist. We need to specify the `PhantomData` explicitly when creating
this command action. The same goes for `RemoveResource` and
`InitResource`

## Solution

This PR implements the following:

- `From<Entity>` for `Remove<T>`
- `Default` for `RemoveResource` and `InitResource`
- use these traits in the implementation of methods of `Commands`
- rename `phantom` field on the structs above to `_phantom` to have a
more uniform field naming scheme for the command actions

---

## Changelog

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

- Added: implemented `From<Entity>` for `Remove<T>` and `Default` for
`RemoveResource` and `InitResource` for ergonomics

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2023-03-29 18:27:48 +00:00
François
36ada9dd4e
Fix segfault with 2d gizmos (#8223)
# Objective

- Don't segfault with gizmos in 2d
- Fixes #8144, Fixes #8211 

## Solution

- Don't use depth in 2d
2023-03-29 18:05:03 +00:00
IceSentry
0859f675c3
Use the prepass normal texture in main pass when possible (#8231)
# Objective

- We support enabling a normal prepass, but the main pass never actually
uses it and recomputes the normals in the main pass. This isn't ideal
since it's doing redundant work.

## Solution

- Use the normal texture from the prepass in the main pass

## Notes

~~I used `NORMAL_PREPASS_ENABLED` as a shader_def because
`NORMAL_PREPASS` is currently used to signify that it is running in the
prepass while this shader_def need to indicate the prepass is done and
the normal prepass was ran before. I'm not sure if there's a better way
to name this.~~
2023-03-29 18:04:40 +00:00
ira
0893852c40
Document bevy_gizmos (#8186)
# Objective
Fix #8179

## Solution
- Added `#![warn(missing_docs)]` and document all public items. All
methods on `Gizmos` have doc examples.
- Expanded the docs on the module/crate. Some unfortunate duplication
there :/
- Moved the methods from `GizmoBuffer` to be directly on `Gizmos` and
made `GizmoBuffer` private. This means the methods on `Gizmos` will show
up on its doc page.

---------

Co-authored-by: James Liu <contact@jamessliu.com>
2023-03-28 20:58:02 +00:00
Ame
bb63ad7fab
Re-export glam_assert feature (#8232)
# Objective

- Allow the use of the "glam _assert" feature to help catch runtime
errors and validate the arguments passed to glam.

e.g.
```rs
// Will panic if self is zero length when glam_assert is enabled.
    pub fn normalize(self) -> Self {
        let normalized = self.mul(self.length_recip());
        glam_assert!(normalized.is_finite());
        normalized
    }
```

## Solution

- Re-export the optional feature glam_assert

---

## Changelog

Added: Optional feature "glam_assert"
2023-03-28 20:18:50 +00:00
Asier Illarramendi
e2b8cc836b
Improve UI update_clipping_system comments (#8147)
# Objective

- Improve `update_clipping_system` comments

## Solution

- Add extra comments
- Reorder `CalculatedClip` updating `match` so it's reads `(old, new)`
vs previous `(new, old)`
- Remove `clone` on children iteration

---------

Co-authored-by: ickshonpe <27962798+ickshonpe@users.noreply.github.com>
2023-03-28 20:18:02 +00:00
KernelUwU
95aa387cd0
Added WebP image format support (#8220)
# Objective

WebP is a modern image format developed by Google that offers a
significant reduction in file size compared to other image formats such
as PNG and JPEG, while still maintaining good image quality. This makes
it particularly useful for games with large numbers of images, such as
those with high-quality textures or detailed sprites, where file size
and loading times can have a significant impact on performance.

By adding support for WebP images in Bevy, game developers using this
engine can now take advantage of this modern image format and reduce the
memory usage and loading times of their games. This improvement can
ultimately result in a better gaming experience for players.

In summary, the objective of adding WebP image format support in Bevy is
to enable game developers to use a modern image format that provides
better compression rates and smaller file sizes, resulting in faster
loading times and reduced memory usage for their games.

## Solution

To add support for WebP images in Bevy, this pull request leverages the
existing `image` crate support for WebP. This implementation is easily
integrated into the existing Bevy asset-loading system. To maintain
compatibility with existing Bevy projects, WebP image support is
disabled by default, and developers can enable it by adding a feature
flag to their project's `Cargo.toml` file. With this feature, Bevy
becomes even more versatile for game developers and provides a valuable
addition to the game engine.

---

## Changelog

- Added support for WebP image format in Bevy game engine

## Migration Guide

To enable WebP image support in your Bevy project, add the following
line to your project's Cargo.toml file:

```toml
bevy = { version = "*", features = ["webp"]}
```
2023-03-28 19:53:55 +00:00
UncleScientist
90579933f8
Fix typo in condition.rs (#8238)
# Objective

- Fixes a typo in the docs

## Solution

- Corrected the wording
2023-03-28 17:03:39 +00:00
James O'Brien
ae31361949
Split opaque and transparent phases (#8090)
# Objective

Fixes #8089. 

## Solution

Splits the MainPass3dNode into 2 nodes, one for the opaque + alpha
passes and one for the transparent pass.

---

## Changelog
- Split MainPass3dNode into MainOpaquePass3dNode and
MainTransparentPass3dNode
- Combine opaque and alpha phases in MainOpaquePass3dNode into one pass
- Create `START_MAIN_PASS` and `END_MAIN_PASS` empty nodes as labels
- Main pass becomes `START_MAIN_PASS -> MAIN_OPAQUE_PASS ->
MAIN_TRANSPARENT_PASS -> END_MAIN_PASS`

## Migration Guide

Nodes that previously added edges involving `MAIN_PASS` should now add
edges to or from `START_MAIN_PASS` or `END_MAIN_PASS` respectively.
2023-03-28 06:35:16 +00:00
JMS55
53667dea56
Temporal Antialiasing (TAA) (#7291)
![image](https://user-images.githubusercontent.com/47158642/214374911-412f0986-3927-4f7a-9a6c-413bdee6b389.png)

# Objective

- Implement an alternative antialias technique
- TAA scales based off of view resolution, not geometry complexity
- TAA filters textures, firefly pixels, and other aliasing not covered
by MSAA
- TAA additionally will reduce noise / increase quality in future
stochastic rendering techniques
- Closes https://github.com/bevyengine/bevy/issues/3663

## Solution

- Add a temporal jitter component
- Add a motion vector prepass
- Add a TemporalAntialias component and plugin
- Combine existing MSAA and FXAA examples and add TAA

## Followup Work
- Prepass motion vector support for skinned meshes
- Move uniforms needed for motion vectors into a separate bind group,
instead of using different bind group layouts
- Reuse previous frame's GPU view buffer for motion vectors, instead of
recomputing
- Mip biasing for sharper textures, and or unjitter texture UVs
https://github.com/bevyengine/bevy/issues/7323
- Compute shader for better performance
- Investigate FSR techniques
  - Historical depth based disocclusion tests, for geometry disocclusion
  - Historical luminance/hue based tests, for shading disocclusion
- Pixel "locks" to reduce blending rate / revamp history confidence
mechanism
- Orthographic camera support for TemporalJitter
- Figure out COD's 1-tap bicubic filter

---

## Changelog

- Added MotionVectorPrepass and TemporalJitter
- Added TemporalAntialiasPlugin, TemporalAntialiasBundle, and
TemporalAntialiasSettings

---------

Co-authored-by: IceSentry <c.giguere42@gmail.com>
Co-authored-by: IceSentry <IceSentry@users.noreply.github.com>
Co-authored-by: Robert Swain <robert.swain@gmail.com>
Co-authored-by: Daniel Chia <danstryder@gmail.com>
Co-authored-by: robtfm <50659922+robtfm@users.noreply.github.com>
Co-authored-by: Brandon Dyer <brandondyer64@gmail.com>
Co-authored-by: Edgar Geier <geieredgar@gmail.com>
2023-03-27 22:22:40 +00:00
Testare
3d8c7681a7
Bugfix: Scene reload fix (nonbreaking) (#7951)
# Objective

Fix a bug with scene reload.

(This is a copy of #7570 but without the breaking API change, in order
to allow the bugfix to be introduced in 0.10.1)

When a scene was reloaded, it was corrupting components that weren't
native to the scene itself. In particular, when a DynamicScene was
created on Entity (A), all components in the scene without parents are
automatically added as children of Entity (A). But if that scene was
reloaded and the same ID of Entity (A) was a scene ID as well*, that
parent component was corrupted, causing the hierarchy to become
malformed and bevy to panic.


*For example, if Entity (A)'s ID was 3, and the scene contained an
entity with ID 3

This issue could affect any components that:
* Implemented `MapEntities`, basically components that contained
references to other entities
* Were added to entities from a scene file but weren't defined in the
scene file

- Fixes #7529 

## Solution

The solution was to keep track of entities+components that had
`MapEntities` functionality during scene load, and only apply the entity
update behavior to them. They were tracked with a HashMap from the
component's TypeID to a vector of entity ID's. Then the
`ReflectMapEntities` struct was updated to hold a function that took a
list of entities to be applied to, instead of naively applying itself to
all values in the EntityMap.

(See this PR comment
https://github.com/bevyengine/bevy/pull/7570#issuecomment-1432302796 for
a story-based explanation of this bug and solution)

## Changelog

### Fixed
- Components that implement `MapEntities` added to scene entities after
load are not corrupted during scene reload.
2023-03-27 22:18:45 +00:00