Commit graph

4695 commits

Author SHA1 Message Date
robtfm
8a8d43d224
fix asset loader preregistration for multiple assets (#9453)
# Objective

fix #9452

when multiple assets are queued to a preregistered loader, only one gets
unblocked when the real loader is registered.

## Solution

i thought async_channel receivers worked like broadcast channels, but in
fact the notification is only received by a single receiver, so only a
single waiting asset is unblocked. close the sender instead so that all
blocked receivers are unblocked.
2023-08-17 20:56:41 +00:00
ira
e2ed42fd75
Fix gizmo lines deforming or disappearing when partially behind the camera (#9470)
If a line has one point behind the camera(near plane) then it would
deform or, if the `depth_bias` setting was set to a negative value,
disappear.

## Solution

The issue is that performing a perspective divide does not work
correctly for points behind the near plane and a perspective divide is
used inside the shader to define the line width in screen space.
The solution is to perform near plane clipping manually inside the
shader before the perspective divide is done.
2023-08-17 20:09:19 +00:00
JMS55
5fac1fe0a9
Fix temporal jitter bug (#9462)
* Fixed jitter being applied in the wrong coordinate space, leading to
aliasing.
* Fixed incorrectly using the cached view_proj instead of account for
temporal jitter.
* Added a diagram to ensure the coordinate space is clear.

Before:

![image](https://github.com/bevyengine/bevy/assets/47158642/55b4bed4-4fb0-4fb2-a271-cc10a987e4d7)

After:

![image](https://github.com/bevyengine/bevy/assets/47158642/cbde4553-4e35-44d9-8ccf-f3a06e64a31f)
2023-08-17 19:46:43 +00:00
Tristan Guichaoua
9473726628
Fix Window::set_cursor_position (#9456)
# Objective

Fixes #9455

This change has probably been forgotten in
https://github.com/bevyengine/bevy/pull/8306.

## Solution

Remove the inversion of the Y axis when propagates window change back to
winit.
2023-08-17 16:59:07 +00:00
st0rmbtw
b6a9d8eba7
Change UiScale to a tuple struct (#9444)
# Objective

Inconvenient initialization of `UiScale`

## Solution

Change `UiScale` to a tuple struct

## Migration Guide

Replace initialization of `UiScale` like ```UiScale { scale: 1.0 }```
with ```UiScale(1.0)```
2023-08-16 18:18:50 +00:00
François
3aad5c6b99
animations: convert skinning weights from unorm8x4 to float32x4 (#9338)
# Objective

- Fixes part of  #9021 

## Solution

- Joint mesh are in format `Unorm8x4` in some gltf file, but Bevy
expects a `Float32x4`. Converts them. Also converts `Unorm16x4`
- According to gltf spec:
https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#skinned-mesh-attributes
> WEIGHTS_n: float, or normalized unsigned byte, or normalized unsigned
short
2023-08-16 07:27:58 +00:00
ira
cfa3303cf3
Fix crash when drawing line gizmo with less than 2 vertices (#9101)
# Objective

Fix #9089

## Solution

Don't try to draw lines with less than 2 vertices. These would not be
visible either way.

---------

Co-authored-by: François <mockersf@gmail.com>
2023-08-15 21:50:37 +00:00
radiish
632ef0c823
input: allow multiple gamepad inputs to be registered for one button in one frame (#9446)
# Objective

- Currently, (AFAIC, accidentally) after registering an event for a
Gilrs button event, we ignore all subsequent events for the same button
in the same frame, because we don't update our filter. This is rare, but
I noticed it while adding gamepad support to a terminal app rendering at
15fps.
- Related to #4664, but does not quite fix it.

## Solution

- Move the edit to the `Axis<GamepadButton>` resource to when we read
the events from Gilrs.
2023-08-15 21:50:29 +00:00
Joseph
f99dcadf8a
Add missing documentation to bevy_time (#9428)
# Objective

* Add documentation to undocumented items in `bevy_time`.
* Add a warning for undocumented items.

---------

Co-authored-by: Sélène Amanita <134181069+Selene-Amanita@users.noreply.github.com>
2023-08-15 21:48:37 +00:00
hesiod
6ccb26885f
Fix incorrect documentation link in DetectChangesMut (#9431)
# Objective

- Fix a trivial incorrect documentation link in  `DetectChangesMut`.
2023-08-15 21:48:12 +00:00
Hennadii Chernyshchyk
d60b715411
Add SceneInstanceReady (#9313)
# Objective

Closes #9115, replaces #9117.

## Solution

Emit event when scene is ready.

---

## Changelog

### Added

- `SceneInstanceReady` event when scene becomes ready.
2023-08-15 19:45:01 +00:00
张林伟
55a710995c
Move scene spawner systems to SpawnScene schedule (#9260)
# Objective

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

## Changelog

- Move scene spawner systems to a new SpawnScene schedule which is after
Update and before PostUpdate (schedule order:
[PreUpdate][Update][SpawnScene][PostUpdate])

## Migration Guide

- Move scene spawner systems to a new SpawnScene schedule which is after
Update and before PostUpdate (schedule order:
[PreUpdate][Update][SpawnScene][PostUpdate]), you might remove system
ordering code related to scene spawning as the execution order has been
guaranteed by bevy engine.

---------

Co-authored-by: Hennadii Chernyshchyk <genaloner@gmail.com>
2023-08-15 18:53:58 +00:00
dependabot[bot]
505b9a58bd
Update tracy-client requirement from 0.15 to 0.16 (#9436)
Updates the requirements on
[tracy-client](https://github.com/nagisa/rust_tracy_client) to permit
the latest version.
<details>
<summary>Commits</summary>
<ul>
<li><a
href="f38da93ff1"><code>f38da93</code></a>
Test with 1.63.0 for MSRV</li>
<li><a
href="3621e20ccd"><code>3621e20</code></a>
tracing-client-sys: 0.21.1</li>
<li><a
href="bccf04b152"><code>bccf04b</code></a>
tracing-tracy: 0.10.3</li>
<li><a
href="bff27b5218"><code>bff27b5</code></a>
tracy-client: 0.15.2 -&gt; 0.16.0 + fix auto update</li>
<li><a
href="9ed943bd6b"><code>9ed943b</code></a>
Add safe GPU API</li>
<li><a
href="60443cc55c"><code>60443cc</code></a>
Benches fell out of sync</li>
<li><a
href="c346a10998"><code>c346a10</code></a>
Fix version table typo</li>
<li><a
href="0763d2d16c"><code>0763d2d</code></a>
Bump MSRV to 1.60.0</li>
<li><a
href="d483998d48"><code>d483998</code></a>
Update Tracy client bindings to v0.9.1</li>
<li><a
href="dce363444f"><code>dce3634</code></a>
client-sys: 0.20.0, client: 0.15.1, tracing: 0.10.2</li>
<li>Additional commits viewable in <a
href="https://github.com/nagisa/rust_tracy_client/compare/tracy-client-v0.15.0...tracy-client-v0.16.0">compare
view</a></li>
</ul>
</details>
<br />


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

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

---

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

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


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-08-15 07:45:21 +00:00
James O'Brien
62ae660357
Fix shader_instancing example (#9448)
# Objective

- Fix shader compilation issue in `shader_instancing` example.

## Solution

- Fix typo in `instancing.wgsl`
2023-08-15 07:28:45 +00:00
Robert Swain
0a11af9375
Reduce the size of MeshUniform to improve performance (#9416)
# Objective

- Significantly reduce the size of MeshUniform by only including
necessary data.

## Solution

Local to world, model transforms are affine. This means they only need a
4x3 matrix to represent them.

`MeshUniform` stores the current, and previous model transforms, and the
inverse transpose of the current model transform, all as 4x4 matrices.
Instead we can store the current, and previous model transforms as 4x3
matrices, and we only need the upper-left 3x3 part of the inverse
transpose of the current model transform. This change allows us to
reduce the serialized MeshUniform size from 208 bytes to 144 bytes,
which is over a 30% saving in data to serialize, and VRAM bandwidth and
space.

## Benchmarks

On an M1 Max, running `many_cubes -- sphere`, main is in yellow, this PR
is in red:
<img width="1484" alt="Screenshot 2023-08-11 at 02 36 43"
src="https://github.com/bevyengine/bevy/assets/302146/7d99c7b3-f2bb-4004-a8d0-4c00f755cb0d">
A reduction in frame time of ~14%.

---

## Changelog

- Changed: Redefined `MeshUniform` to improve performance by using 4x3
affine transforms and reconstructing 4x4 matrices in the shader. Helper
functions were added to `bevy_pbr::mesh_functions` to unpack the data.
`affine_to_square` converts the packed 4x3 in 3x4 matrix data to a 4x4
matrix. `mat2x4_f32_to_mat3x3` converts the 3x3 in mat2x4 + f32 matrix
data back into a 3x3.

## Migration Guide

Shader code before:
```
var model = mesh[instance_index].model;
```

Shader code after:
```
#import bevy_pbr::mesh_functions affine_to_square

var model = affine_to_square(mesh[instance_index].model);
```
2023-08-15 06:00:23 +00:00
robtfm
b30ff2ab76
allow asset loader pre-registration (#9429)
# Objective

- When loading gltf files during app creation (for example using a
FromWorld impl and adding that as a resource), no loader was found.
- As the gltf loader can load compressed formats, it needs to know what
the GPU supports so it's not available at app creation time.

## Solution

alternative to #9426

- add functionality to preregister the loader. loading assets with
matching extensions will block until a real loader is registered.
- preregister "gltf" and "glb".
- prereigster image formats.

the way this is set up, if a set of extensions are all registered with a
single preregistration call, then later a loader is added that matches
some of the extensions, assets using the remaining extensions will then
fail. i think that should work well for image formats that we don't know
are supported until later.
2023-08-14 21:27:51 +00:00
Oli Wilkins
43fe83b7c6
Example Comment Typo Fix (#9427)
# Objective

Fixes a typo in one of the comments in an example.

## Solution

Fix the typo in the comment.
2023-08-12 21:06:15 +00:00
Seb Ospina
e489dcc9e8
webgl feature renamed to webgl2 (#9370)
Addresses:
```sh
$ cargo build --release --example lighting --target wasm32-unknown-unknown --features webgl
error: none of the selected packages contains these features: webgl, did you mean: webgl2, webp?
```

# Objective

- When following the instructions for the web examples.
- Document clearly the generated file `./target/wasm_example.js`, since
it didn't appear on `git grep` (missing extension)

## Solution

- Follow the feature rename on the docs.

---------

Signed-off-by: Seb Ospina <kraige@gmail.com>
2023-08-12 21:05:36 +00:00
Mike
ac8f36743e
enable multithreading on benches (#9388)
# Objective

- Enable the new multithreading feature on benches
2023-08-11 22:08:36 +00:00
urben1680
5b5806406d
Adding Copy, Clone, Debug to derived traits of ExecutorKind (#9385)
While being nobody other's issue as far I can tell, I want to create a
trait I plan to implement on `App` where more than one schedule is
modified.
My workaround so far was working with a closure that returns an
`ExecutorKind` from a match of the method variable.

It makes it easier for me to being able to clone `ExecutorKind` and I
don't see this being controversial for others working with Bevy.

I did nothing more than adding `Clone` to the derived traits, no
migration guide needed.

(If this worked out then the GitHub editor is not too shabby.)
2023-08-11 21:45:32 +00:00
Nicola Papale
da41aa35e8
Move window.rs to window/mod.rs in bevy_render (#9394)
# Objective

Bevy prefers `mod.rs` inside `module_name` files over `module_name.rs`
collocated with `module_name`. In `bevy_render`, it seems the `window`
modules didn't follow this convention

## Solution

- Follow the `mod.rs` convention.
2023-08-11 21:33:27 +00:00
François
47a5a16d8a
audio sinks don't need their custom drop anymore (#9336)
# Objective

- Fixes #9324 
- Audio sinks used to have a custom drop implementation to detach the
sinks because it was not required to keep a reference to it
- With the new audio api, a reference is kept as a component of an
entity

## Solution

- Remove that custom drop implementation, and the option wrapping that
was required for it.
2023-08-11 21:16:12 +00:00
ickshonpe
6a8fd54006
Unnecessary line in game_menu example (#9406)
# Objective

In the `game_menu` example:

```rust
let button_icon_style = Style {
            width: Val::Px(30.0),
            // This takes the icons out of the flexbox flow, to be positioned exactly
            position_type: PositionType::Absolute,
            // The icon will be close to the left border of the button
            left: Val::Px(10.0),
            right: Val::Auto,
            ..default()
        };
```

The default value for `right` is `Val::Auto` so that line is unnecessary
and can be removed.
2023-08-11 21:12:57 +00:00
Tristan Guichaoua
cfb65c1eaf
Add replace_if_neq to DetectChangesMut (#9418)
# Objective

Just like
[`set_if_neq`](https://docs.rs/bevy_ecs/latest/bevy_ecs/change_detection/trait.DetectChangesMut.html#method.set_if_neq),
being able to express the "I don't want to unnecessarily trigger the
change detection" but with the ability to handle the previous value if
change occurs.

## Solution

Add `replace_if_neq` to `DetectChangesMut`.

---

## Changelog

- Added `DetectChangesMut::replace_if_neq`: like `set_if_neq` change the
value only if the new value if different from the current one, but
return the previous value if the change occurs.
2023-08-11 21:10:16 +00:00
Hans Meine
1abb6b0758
elaborate on TaskPool and bevy tasks (#8750)
# Objective

I found it very difficult to understand how bevy tasks work, and I
concluded that the documentation should be improved for beginners like
me.

## Solution

These changes to the documentation were written from my beginner's
perspective after
some extremely helpful explanations by nil on Discord.

I am not familiar enough with rustdoc yet; when looking at the source, I
found the documentation at the very top of `usages.rs` helpful, but I
don't know where they are rendered. They should probably be linked to
from the main `bevy_tasks` README.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Mike <mike.hsu@gmail.com>
2023-08-11 21:07:28 +00:00
Nicola Papale
b7028110fa
Make Anchor Copy (#9327)
# Objective

In `bevy_sprite`, the `Anchor` type is not `Copy`. It makes interacting
with it more difficult than necessary.

## Solution

Derive `Copy` on it. The rust API guidelines are that you should derive
`Copy` when possible.
<https://rust-lang.github.io/api-guidelines/interoperability.html#types-eagerly-implement-common-traits-c-common-traits>
Regardless, `Anchor` is a very small `enum` which warrants `Copy`.

---

## Changelog

- In `bevy_sprite` `Anchor` is now `Copy`.

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-08-11 21:04:53 +00:00
jfaz
ad4ec145eb
Expose animation_clip paths (#9392)
Need this for a custom `AnimationPlayer` that I tick in `FixedUpdate`

# Objective

- Need access to an animation clip's `paths` from outside the module

## Solution

- Add a getter method to return a reference to `paths`

---------

Co-authored-by: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com>
2023-08-11 21:03:36 +00:00
Zeenobit
1e170d2e90
Add RunSystem (#9366)
Add a `RunSystem` extension trait to allow for immediate execution of
systems on a `World` for debugging and/or testing purposes.

# Objective

Fixes #6184

Initially, I made this CL as `ApplyCommands`. After a discussion with
@cart , we decided a more generic implementation would be better to
support all systems. This is the new revised CL. Sorry for the long
delay! 😅

This CL allows users to do this:
```rust
use bevy::prelude::*;
use bevy::ecs::system::RunSystem;

struct T(usize);

impl Resource for T {}

fn system(In(n): In<usize>, mut commands: Commands) -> usize {
    commands.insert_resource(T(n));
    n + 1
}

let mut world = World::default();
let n = world.run_system_with(1, system);
assert_eq!(n, 2);
assert_eq!(world.resource::<T>().0, 1);
```

## Solution

This is implemented as a trait extension and not included in any
preludes to ensure it's being used consciously.
Internally, it just initializes and runs a systems, and applies any
deferred parameters all "in place".
The trait has 2 functions (one of which calls the other by default):
- `run_system_with` is the general implementation, which allows user to
pass system input parameters
- `run_system` is the ergonomic wrapper for systems with no input
parameter (to avoid having the user pass `()` as input).

~~Additionally, this trait is also implemented for `&mut App`. I added
this mainly for ergonomics (`app.run_system` vs.
`app.world.run_system`).~~ (Removed based on feedback)

---------

Co-authored-by: Pascal Hertleif <killercup@gmail.com>
2023-08-11 20:41:48 +00:00
Tristan Guichaoua
37915e1d93
Add glam swizzles traits to prelude (#9387)
# Objective

Add possibility to use the glam's swizzles traits without having to
manually import them.

```diff
use bevy::prelude::*;
- use bevy::math::Vec3Swizzles;

fn foo(x: Vec3) {
    let y: Vec2 = x.xy();
}
```

## Solution

Add the swizzles traits to bevy's prelude.

---

## Changelog

- `Vec2Swizzles`, `Vec3Swizzles` and `Vec4Swizzles` are now part of the
prelude.
2023-08-10 17:05:01 +00:00
Ame :]
06f7f9640a
Use bevy crates imports instead of bevy internal. post_processing example (#9396)
# Objective

- I want to run the post_processing example in a new project, but I
can't because it uses bevy internal imports.

## Solution

- Change the bevy_internal imports to their respective bevy crates
imports
2023-08-10 02:02:30 +00:00
Gino Valente
f96cd758cd
bevy_reflect: Opt-out attribute for TypePath (#9140)
# Objective

Fixes #9094

## Solution

Takes a bit from
[this](https://github.com/bevyengine/bevy/issues/9094#issuecomment-1629333851)
comment as well as a
[comment](https://discord.com/channels/691052431525675048/1002362493634629796/1128024873260810271)
from @soqb.

This allows users to opt-out of the `TypePath` implementation that is
automatically generated by the `Reflect` derive macro, allowing custom
`TypePath` implementations.

```rust
#[derive(Reflect)]
#[reflect(type_path = false)]
struct Foo<T> {
    #[reflect(ignore)]
    _marker: PhantomData<T>,
}

struct NotTypePath;

impl<T: 'static> TypePath for Foo<T> {
    fn type_path() -> &'static str {
        std::any::type_name::<Self>()
    }

    fn short_type_path() -> &'static str {
        static CELL: GenericTypePathCell = GenericTypePathCell::new();
        CELL.get_or_insert::<Self, _>(|| {
            bevy_utils::get_short_name(std::any::type_name::<Self>())
        })
    }

    fn crate_name() -> Option<&'static str> {
        Some("my_crate")
    }

    fn module_path() -> Option<&'static str> {
        Some("my_crate::foo")
    }

    fn type_ident() -> Option<&'static str> {
        Some("Foo")
    }
}

// Can use `TypePath`
let _ = <Foo<NotTypePath> as TypePath>::type_path();

// Can register the type
let mut registry = TypeRegistry::default();
registry.register::<Foo<NotTypePath>>();
```

#### Type Path Stability

The stability of type paths mainly come into play during serialization.
If a type is moved between builds, an unstable type path may become
invalid.

Users that opt-out of `TypePath` and rely on something like
`std::any::type_name` as in the example above, should be aware that this
solution removes the stability guarantees. Deserialization thus expects
that type to never move. If it does, then the serialized type paths will
need to be updated accordingly.

If a user depends on stability, they will need to implement that
stability logic manually (probably by looking at the expanded output of
a typical `Reflect`/`TypePath` derive). This could be difficult for type
parameters that don't/can't implement `TypePath`, and will need to make
heavy use of string parsing and manipulation to achieve the same effect
(alternatively, they can choose to simply exclude any type parameter
that doesn't implement `TypePath`).

---

## Changelog

- Added the `#[reflect(type_path = false)]` attribute to opt out of the
`TypePath` impl when deriving `Reflect`

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-08-10 00:37:56 +00:00
Pascal Hertleif
2cc1068983
Rustdoc: Scrape examples (#9154)
# Objective

Provide more usage examples in API docs so that people can see methods
being used in context.

## Solution

Enable experimental rustdoc feature "scrape examples". See
<https://doc.rust-lang.org/nightly/rustdoc/scraped-examples.html> for
official docs.

## Example screenshots of examples :)

<img width="1013" alt="image"
src="https://github.com/bevyengine/bevy/assets/20063/7abc8baa-3149-476f-b2f2-ce7693758bee">

<img width="1033" alt="image"
src="https://github.com/bevyengine/bevy/assets/20063/163e7e22-c55e-46ab-8f3d-75fb97c3ad7a">

<img width="1009" alt="image"
src="https://github.com/bevyengine/bevy/assets/20063/a50b1147-e252-43f3-9adb-81960b8aa6c3">


## Limitations

- Only methods seem to show examples so far
- It may be confusing to have curated examples from doc comments
followed by snippets from `examples/`

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-08-10 00:27:39 +00:00
Sélène Amanita
77824b96ff
Update Camera's Frustum only when its GlobalTransform or CameraProjection changed (#9092)
# Objective

Update a camera's frustum only when needed.

- Maybe a performance gain from not having to compute frusta when not
needed, at the cost of change detection (?)
- Making "fighting" with `update_frusta` less tedious, see
https://github.com/bevyengine/bevy/issues/9077 and
https://discord.com/channels/691052431525675048/743663924229963868/1127566087966433322

## Solution

Add change detection filter for `GlobalTransform` or `T:
CameraProjection` in `update_frusta`, since those are the cases when the
frustum needs to be updated.

## Note

I don't think a migration guide and changelog are needed, but I'm not
100% sure, I could put something like "if you're fighting against
`update_frusta`, you can do it only when there is a change to
`GlobalTransform` or `CameraProjection` now", what do you think? It's
not really a breaking change with a normal use case.
2023-08-10 00:06:27 +00:00
Dimitri Belopopsky
b8695d06b1
Fix non-visible motion vector text in shader prepass example (#9155)
# Objective

In the shader prepass example, changing to the motion vector output
hides the text, because both it and the background are rendererd black.
Seems to have been caused by this commit?
71cf35ce42

## Solution

Make the text white on all outputs.
2023-08-10 00:01:23 +00:00
Rob Parrett
e87d3cccbe
Fix gamepad viewer being marked as a non-wasm example (#9399)
# Objective

This example stopped being built for the website after the
example-building was reworked in
(https://github.com/bevyengine/bevy-website/issues/720 + #9168).

This seems to have just been a mistake when defining this particular
example's metadata.

See https://github.com/bevyengine/bevy-website/issues/726

## Solution

Update its metadata to indicate that it works with wasm.
2023-08-09 21:06:16 +00:00
Robert Swain
c1a5428f8e
Work around naga/wgpu WGSL instance_index -> GLSL gl_InstanceID bug on WebGL2 (#9383)
naga and wgpu should polyfill WGSL instance_index functionality where it
is not available in GLSL. Until that is done, we can work around it in
bevy using a push constant which is converted to a uniform by naga and
wgpu.

# Objective

- Fixes #9375 

## Solution

- Use a push constant to pass in the base instance to the shader on
WebGL2 so that base instance + gl_InstanceID is used to correctly
represent the instance index.

## TODO

- [ ] Benchmark vs per-object dynamic offset MeshUniform as this will
now push a uniform value per-draw as well as update the dynamic offset
per-batch.
- [x] Test on DX12 AMD/NVIDIA to check that this PR does not regress any
problems that were observed there. (@Elabajaba @robtfm were testing that
last time - help appreciated. <3 )

---

## Changelog

- Added: `bevy_render::instance_index` shader import which includes a
workaround for the lack of a WGSL `instance_index` polyfill for WebGL2
in naga and wgpu for the time being. It uses a push_constant which gets
converted to a plain uniform by naga and wgpu.

## Migration Guide

Shader code before:

```
struct Vertex {
    @builtin(instance_index) instance_index: u32,
...
}

@vertex
fn vertex(vertex_no_morph: Vertex) -> VertexOutput {
...

    var model = mesh[vertex_no_morph.instance_index].model;
```

After:

```
#import bevy_render::instance_index

struct Vertex {
    @builtin(instance_index) instance_index: u32,
...
}

@vertex
fn vertex(vertex_no_morph: Vertex) -> VertexOutput {
...

    var model = mesh[bevy_render::instance_index::get_instance_index(vertex_no_morph.instance_index)].model;
```
2023-08-09 18:38:45 +00:00
Rob Parrett
9e8de2aa94
Slightly better message when contributor modifies examples template (#9372)
# Objective

Provide a slightly better message when a contributor needs to update the
generated example readme file for [any number of
reasons](https://github.com/bevyengine/bevy/pull/9372#discussion_r1285876202)
but hasn't added any examples.

This recently happened here:
https://github.com/bevyengine/bevy/pull/9370#issuecomment-1666776092

The contributor modified the readme template and is being told that they
added an example.

## Solution

The advice given is still correct. Just change the message so that it's
not accusing the contributor of adding an example.

It may be possible to instead add more specific messages instead if
someone is motivated to do that.

edit: reworked this whole PR text

---------

Co-authored-by: Nicola Papale <nicopap@users.noreply.github.com>
2023-08-07 23:08:19 +00:00
ickshonpe
fe37ba5360
Change the default for the measure_func field of ContentSize to None. (#9346)
# Objective

The default for `ContentSize` should have the `measure_func` field set
to `None`, instead of a fixed size of zero. This means that until a
measure func is set the size of the UI node will be determined by its
`Style` constraints. This is preferable as it allows users to specify
the space the Node should take up in the layout while waiting for
content to load.

## Solution

Derive `Default` for `ContentSize`.

The PR also adds a `fixed_size` helper function to make it a bit easier
to access the old behaviour.

## Changelog
* Derived `Default` for `ContentSize`
* Added a `fixed_size` helper function to `ContentSize` that creates a
new `ContentSize` with a `MeasureFunc` that always returns the same
value, regardless of layout constraints.

## Migration Guide
The default for `ContentSize` now sets its `measure_func` to `None`,
instead of a fixed size measure that returns `Vec2::ZERO`.
The helper function `fixed_size` can be called with
`ContentSize::fixed_size(Vec2::ZERO)` to get the previous behaviour.
2023-08-07 23:06:40 +00:00
Gino Valente
84f6b879ae
bevy_reflect: Fix combined field attributes (#9322)
# Objective

It seems the behavior of field attributes was accidentally broken at
some point. Take the following code:

```rust
#[derive(Reflect)]
struct Foo {
  #[reflect(ignore, default)]
  value: usize
}
```

The above code should simply mark `value` as ignored and specify a
default behavior. However, what this actually does is discard both.
That's especially a problem when we don't want the field to be be given
a `Reflect` or `FromReflect` bound (which is why we ignore it in the
first place).

This only happens when the attributes are combined into one. The
following code works properly:

```rust
#[derive(Reflect)]
struct Foo {
  #[reflect(ignore)]
  #[reflect(default)]
  value: usize
}
```

## Solution

Cleaned up the field attribute parsing logic to support combined field
attributes.

---

## Changelog

- Fixed a bug where `Reflect` derive attributes on fields are not able
to be combined into a single attribute
2023-08-07 23:04:00 +00:00
IceSentry
171ff1b1e1
use ViewNodeRunner in the post_processing example (#9127)
# Objective

- I forgot to update the example after the `ViewNodeRunner` was merged.
It was even partially mentioned in one of the comments.

## Solution

- Use the `ViewNodeRunner` in the post_processing example
- I also broke up a few lines that were a bit long

---------

Co-authored-by: JMS55 <47158642+JMS55@users.noreply.github.com>
2023-08-07 23:02:32 +00:00
张林伟
7ccb203b37
Prevent setting parent as itself (#8980)
# Objective

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

## Solution

- Panic when parent and child are same entity.
- Add checks into EntityCommands and EntityMut methods
2023-08-07 23:00:48 +00:00
Nicola Papale
10797d4f15
Refactor parsing in bevy_reflect path module (#9048)
# Objective

- Follow up to #8887
- The parsing code in `bevy_reflect/src/path/mod.rs` could also do with
some cleanup

## Solution

- Create the `parse.rs` module, move all parsing code to this module
- The parsing errors also now keep track of the whole parsed string, and
are much more fine-grained

### Detailed changes

- Move `PathParser` to `parse.rs` submodule
- Rename `token_to_access` to `access_following` (yep, goes from 132
lines to 16)
- Move parsing tests into the `parse.rs` file
2023-08-05 17:18:13 +00:00
ickshonpe
e52af83045
Improved text widget doc comments (#9344)
# Objective

The doc comment for `text_system` is not quite correct. It implies that
a new `TextLayoutInfo` is generated on changes to `Text` and `Style`.
While changes to those components might indirectly trigger a
regeneration of the text layout, `text_system` itself only queries for
changes to `Node`

Also added details to `measure_text_system`'s doc comments explaining
how it reacts to changes.

---------

Co-authored-by: François <mockersf@gmail.com>
2023-08-05 13:53:23 +00:00
Nicola Papale
60c6ca7699
Fix doc warning in bevy_tasks (#9348)
# Objective

- `bevy_tasks` emits warnings under certain conditions

When I run `cargo clippy -p bevy_tasks` the warning doesn't show up,
while if I run it with `cargo clippy -p bevy_asset` the warning shows
up.

## Solution

- Fix the warnings.

## Longer term solution

We should probably fix CI so that those warnings do not slip through.
But that's not the goal of this PR.
2023-08-05 13:53:05 +00:00
Rob Parrett
e1e2407091
Fix post_processing example on webgl2 (#9361)
# Objective

The `post_processing` example is currently broken when run with webgl2.

```
cargo run --example post_processing --target=wasm32-unknown-unknown
```

```
wasm.js:387 panicked at 'wgpu error: Validation Error

Caused by:
    In Device::create_render_pipeline
      note: label = `post_process_pipeline`
    In the provided shader, the type given for group 0 binding 2 has a size of 4. As the device does not support `DownlevelFlags::BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED`, the type must have a size that is a multiple of 16 bytes.
```

I bisected the breakage to c7eaedd6a1.

## Solution

Add padding when using webgl2
2023-08-04 17:44:29 +00:00
ickshonpe
9a87890d4c
Fix incorrent doc comment for the set method of ContentSize (#9345)
# Objective

This doc comment for the `set` method of `ContentSize`:

```
Set a `Measure` for this function
```
doesn't seem to make sense, `ContentSize` is not a function. 

# Solution

Replace it.
2023-08-04 01:24:42 +00:00
Ray Redondo
42098192c2
update documentation on AudioSink (#9332)
# Objective

When an `AudioSink` is removed from an entity, the audio player will
automatically start any `AudioSource` still attached, which normally is
the one used to start playback in the first place.

## Solution

Long story short, the default behavior is restarting the audio, and this
commit documents that.

---

## Changelog

Fixed documentation on `AudioSink` to clarify removal behavior.
2023-08-03 12:46:44 +00:00
François
b6a2fc5d80
Improve execution of examples in CI (#9331)
# Objective

- Some examples crash in CI because of needing too many resources for
the windows runner
- Some examples have random results making it hard to compare
screenshots

## Solution

- `bloom_3d`: reduce the number of spheres
- `pbr`:  use simpler spheres and reuse the mesh
- `tonemapping`: use simpler spheres and reuse the mesh
- `shadow_biases`: reduce the number of spheres
- `spotlight`: use a seeded rng, move more cubes in view while reducing
the total number of cubes, and reuse meshes and materials
- `external_source_external_thread`, `iter_combinations`,
`parallel_query`: use a seeded rng

Examples of errors encountered:
```
Caused by:
    In Device::create_bind_group
      note: label = `bloom_upsampling_bind_group`
    Not enough memory left
```

```
Caused by:
    In Queue::write_buffer
    Parent device is lost
```
```
ERROR wgpu_core::device::life: Mapping failed Device(Lost)
```
2023-08-03 12:45:28 +00:00
robtfm
db47ea2f27
include toplevel shader-associated defs (#9343)
# Objective

shader defs associated with a shader via `load_internal_asset!` or
`Shader::from_xxx_with_defs` were being accidentally ignored for
top-level shaders.

## Solution

include the defs for top level shaders.
2023-08-03 09:12:31 +00:00
Edgar Geier
731a6fbb92
Fix ambiguous_with breaking run conditions (#9253)
# Objective

- Fixes #9114

## Solution

Inside `ScheduleGraph::build_schedule()` the variable `node_count =
self.systems.len() + self.system_sets.len()` is used to calculate the
indices for the `reachable` bitset derived from `self.hierarchy.graph`.
However, the number of nodes inside `self.hierarchy.graph` does not
always correspond to `self.systems.len() + self.system_sets.len()` when
`ambiguous_with` is used, because an ambiguous set is added to
`system_sets` (because we need an `NodeId` for the ambiguity graph)
without adding a node to `self.hierarchy`.

In this PR, we rename `node_count` to the more descriptive name
`hg_node_count` and set it to `self.hierarchy.graph.node_count()`.

---------

Co-authored-by: James Liu <contact@jamessliu.com>
2023-08-03 07:53:20 +00:00