Commit graph

5546 commits

Author SHA1 Message Date
Carter Anderson
abb8c353f4
Release 0.13.0 (#11920)
Bump Bevy crates to 0.13.0 in preparation for release.

(Note that we accidentally skipped the `0.13.0-dev` step this cycle)
2024-02-17 09:24:25 +00:00
Carter Anderson
4e20e4a151
0.13 changelog (#11918)
# Objective

Add 0.13 changelog
2024-02-17 07:22:02 +00:00
Rob Parrett
e6e25dead4
Fix duplicate encase_derive_impl dependency (#11915)
# Objective

Another PR failed CI due to duplicate deps, and I noticed this one in
particular while scanning through the error messages.

I think this was missed in #11082.

## Solution

Bump `encase_derive_impl` dep in `bevy_encase_derive` to same version as
`encase` dep for `bevy_render`.

I spot-checked a few examples, and glanced at the
[changelog](<https://github.com/teoxoy/encase/blob/main/CHANGELOG.md#v070-2024-01-02>)
and I don't think there's anything to be concerned about, but I barely
know what this thing does.
2024-02-17 02:55:21 +00:00
Evgeny Kropotin
1076bd4b9e
Remove map_flatten from linting rules (#11913)
# Objective
Remove `map_flatten` rule from Cargo.toml

fixes #11912
2024-02-17 02:54:32 +00:00
Rob Parrett
756535bacc
Remove naga_oil dependency from bevy_pbr (#11914)
# Objective

Fixes #11908

## Solution

- Remove the `naga_oil` dependency from `bevy_pbr`.
- We were doing a little dance to disable `glsl` support on not-wasm, so
incorporate that dance into `bevy_render`'s `Cargo.toml`.
2024-02-17 02:22:49 +00:00
Patrick Walton
3058c17d6a
Disable irradiance volumes on WebGL and WebGPU. (#11909)
They cause the number of texture bindings to overflow on those
platforms. Ultimately, we shouldn't unconditionally disable them, but
this fixes a crash blocking 0.13.

Closes #11885.
2024-02-17 01:49:46 +00:00
Carter Anderson
8127d44daa
Irradiance volume example tweaks (#11911)
# Objective

Fixes two small quality issues:

1. With the new default ev100 exposure value, the irradiance intensity
was too low
2. The camera was rotating at a fixed speed (instead of a speed
multiplied by delta time), resulting in frame-rate dependent rotation
speed.
2024-02-17 01:24:50 +00:00
Patrick Walton
7883eea54f
Add MeshPipelineKey::LIGHTMAPPED as applicable during the shadow map pass. (#11910)
I did this during the prepass, but I neglected to do it during the
shadow map pass, causing a panic when directional lights with shadows
were enabled with lightmapped meshes present. This patch fixes the
issue.

Closes #11898.
2024-02-17 00:25:32 +00:00
IceSentry
f81aa64ca4
Derive Reflect for Exposure (#11907)
# Objective

- Don't crash when loading a scene with a camera

## Solution

- Derive Reflect for Exposure

Closes https://github.com/bevyengine/bevy/issues/11905
2024-02-16 19:03:46 +00:00
François
80f2ee2910
WebGPU: fix web-sys version (#11894)
# Objective

- Being able to build for WebGPU

```
error[E0061]: this function takes 1 argument but 3 arguments were supplied
   --> .cargo/registry/src/index.crates.io-6f17d22bba15001f/wgpu-0.19.1/src/backend/webgpu.rs:375:22
    |
375 |     let mut mapped = web_sys::GpuDepthStencilState::new(
    |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
376 |         map_compare_function(desc.depth_compare),
    |         ---------------------------------------- unexpected argument of type `GpuCompareFunction`
377 |         desc.depth_write_enabled,
    |         ------------------------ unexpected argument of type `bool`
    |
note: associated function defined here
   --> .cargo/registry/src/index.crates.io-6f17d22bba15001f/web-sys-0.3.68/src/features/gen_GpuDepthStencilState.rs:27:12
    |
27  |     pub fn new(format: GpuTextureFormat) -> Self {
    |            ^^^
help: remove the extra arguments
    |
376 -         map_compare_function(desc.depth_compare),
376 +         map_texture_format(desc.format),
    |

error[E0061]: this function takes 1 argument but 2 arguments were supplied
    --> .cargo/registry/src/index.crates.io-6f17d22bba15001f/wgpu-0.19.1/src/backend/webgpu.rs:1693:13
     |
1693 |             web_sys::GpuVertexState::new(desc.vertex.entry_point, &module.0);
     |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -------------------------
     |                                          |
     |                                          unexpected argument of type `&str`
     |                                          help: remove the extra argument
     |
note: associated function defined here
    --> .cargo/registry/src/index.crates.io-6f17d22bba15001f/web-sys-0.3.68/src/features/gen_GpuVertexState.rs:27:12
     |
27   |     pub fn new(module: &GpuShaderModule) -> Self {
     |            ^^^

error[E0061]: this function takes 2 arguments but 3 arguments were supplied
    --> .cargo/registry/src/index.crates.io-6f17d22bba15001f/wgpu-0.19.1/src/backend/webgpu.rs:1768:17
     |
1768 |                 web_sys::GpuFragmentState::new(frag.entry_point, &module.0, &targets);
     |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ----------------             -------- unexpected argument of type `&js_sys::Array`
     |                                                |
     |                                                expected `&GpuShaderModule`, found `&str`
     |
     = note: expected reference `&GpuShaderModule`
                found reference `&str`
note: associated function defined here
    --> .cargo/registry/src/index.crates.io-6f17d22bba15001f/web-sys-0.3.68/src/features/gen_GpuFragmentState.rs:27:12
     |
27   |     pub fn new(module: &GpuShaderModule, targets: &::wasm_bindgen::JsValue) -> Self {
     |            ^^^
help: remove the extra argument
     |
1768 -                 web_sys::GpuFragmentState::new(frag.entry_point, &module.0, &targets);
1768 +                 web_sys::GpuFragmentState::new(/* &GpuShaderModule */, &module.0);
     |

error[E0061]: this function takes 1 argument but 2 arguments were supplied
    --> .cargo/registry/src/index.crates.io-6f17d22bba15001f/wgpu-0.19.1/src/backend/webgpu.rs:1793:13
     |
1793 |             web_sys::GpuProgrammableStage::new(desc.entry_point, &shader_module.0);
     |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ------------------
     |                                                |
     |                                                unexpected argument of type `&str`
     |                                                help: remove the extra argument
     |
note: associated function defined here
    --> .cargo/registry/src/index.crates.io-6f17d22bba15001f/web-sys-0.3.68/src/features/gen_GpuProgrammableStage.rs:27:12
     |
27   |     pub fn new(module: &GpuShaderModule) -> Self {
     |            ^^^

error[E0599]: no method named `write_timestamp` found for struct `GpuCommandEncoder` in the current scope
    --> .cargo/registry/src/index.crates.io-6f17d22bba15001f/wgpu-0.19.1/src/backend/webgpu.rs:2505:14
     |
2503 | /         encoder_data
2504 | |             .0
2505 | |             .write_timestamp(&query_set_data.0, query_index);
     | |             -^^^^^^^^^^^^^^^ method not found in `GpuCommandEncoder`
     | |_____________|
     |

Some errors have detailed explanations: E0061, E0599.
For more information about an error, try `rustc --explain E0061`.
```

## Solution

- `web-sys` doesn't follow semver for the WebGPU APIs as they are
unstable. Force using a compatible version

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-02-16 17:45:29 +00:00
thepackett
16d710cb3f
Fix asset loader registration warning (#11870)
# Objective

When registering and preregistering asset loaders, there would be a
`warn!` if multiple asset loaders use a given extension, and an `info!`
if multiple asset loaders load the same asset type. Since both of these
situations are individually fine, it was decided that these messages
should be removed.

## Solution

Replace both of these messages with a new `warn!` that notes that if
multiple asset loaders share the same asset type _and_ share extensions,
that the loader must be specified in the `.meta` file for those assets
in order to solve the ambiguity. This is a more useful message, since it
notes when a user must take special action / consideration.
2024-02-16 16:30:10 +00:00
Rob Parrett
ebaa347afe
Add configuration for async pipeline creation on RenderPlugin (#11847)
# Objective

Fixes #11846

## Solution

Add a `synchronous_pipeline_compilation ` field to `RenderPlugin`,
defaulting to `false`.

Most of the diff is whitespace.

## Changelog

Added `synchronous_pipeline_compilation ` to `RenderPlugin` for
disabling async pipeline creation.

## Migration Guide

TODO: consider combining this with the guide for #11846

`RenderPlugin` has a new `synchronous_pipeline_compilation ` property.
The default value is `false`. Set this to `true` if you want to retain
the previous synchronous behavior.

---------

Co-authored-by: JMS55 <47158642+JMS55@users.noreply.github.com>
Co-authored-by: François <mockersf@gmail.com>
2024-02-16 13:35:47 +00:00
François
9a2ce8e31b
irradiance: use textureSampleLevel for WebGPU support (#11893)
# Objective

- Fixes #11879 

## Solution

- Use `textureSampleLevel` instead of `textureSample`

Co-authored-by: Griffin <33357138+DGriffin91@users.noreply.github.com>
2024-02-16 13:35:16 +00:00
charlotte
9505f6e6a9
Support optional clear color in ColorAttachment. (#11884)
This represents when the user has configured `ClearColorConfig::None` in
their application. If the clear color is `None`, we will always `Load`
instead of attempting to clear the attachment on the first call.

Fixes #11883.
2024-02-16 13:25:55 +00:00
Evgeny Kropotin
149d48f586
Add type registrations for animation types (#11889)
# Objective
Adds type registrations for some animation and math types

Fixes #11848
2024-02-16 13:17:42 +00:00
Carter Anderson
fe777d5c3f
Implement and register Reflect (value) for CameraRenderGraph and CameraMainTextureUsages (#11878)
# Objective

The new render graph labels do not (and cannot) implement normal
Reflect, which breaks spawning scenes with cameras (including GLTF
scenes). Likewise, the new `CameraMainTextureUsages` also does not (and
cannot) implement normal Reflect because it uses `wgpu::TextureUsages`
under the hood.

Fixes #11852

## Solution

This implements minimal "reflect value" for `CameraRenderGraph` and
`CameraMainTextureUsages` and registers the types, which satisfies our
spawn logic.

Note that this _does not_ fix scene serialization for these types, which
will require more significant changes. We will especially need to think
about how (and if) "interned labels" will fit into the scene system. For
the purposes of 0.13, I think this is the best we can do. Given that
this serialization issue is prevalent throughout Bevy atm, I'm ok with
adding a couple more to the pile. When we roll out the new scene system,
we will be forced to solve these on a case-by-case basis.

---

## Changelog

- Implement Reflect (value) for `CameraMainTextureUsages` and
`CameraRenderGraph`, and register those types.
2024-02-15 23:56:37 +00:00
Carter Anderson
f83de49b7a
Rename Core Render Graph Labels (#11882)
# Objective

#10644 introduced nice "statically typed" labels that replace the old
strings. I would like to propose some changes to the names introduced:

* `SubGraph2d` -> `Core2d` and `SubGraph3d` -> `Core3d`. The names of
these graphs have been / should continue to be the "core 2d" graph not
the "sub graph 2d" graph. The crate is called `bevy_core_pipeline`, the
modules are still `core_2d` and `core_3d`, etc.
* `Labels2d` and `Labels3d`, at the very least, should not be plural to
follow naming conventions. A Label enum is not a "collection of labels",
it is a _specific_ Label. However I think `Label2d` and `Label3d` is
significantly less clear than `Node2d` and `Node3d`, so I propose those
changes here. I've done the same for `LabelsPbr` -> `NodePbr` and
`LabelsUi` -> `NodeUi`

Additionally, #10644 accidentally made one of the Camera2dBundle
constructors use the 3D graph instead of the 2D graph. I've fixed that
here.
 
---

## Changelog

* Renamed `SubGraph2d` -> `Core2d`, `SubGraph3d` -> `Core3d`, `Labels2d`
-> `Node2d`, `Labels3d` -> `Node3d`, `LabelsUi` -> `NodeUi`, `LabelsPbr`
-> `NodePbr`
2024-02-15 23:15:16 +00:00
Robin KAY
4ebc560dfb
Change MeshUniform::new() to be public. (#11880)
# Objective

Provide a public replacement for `Into<MeshUniform>` trait impl which
was removed by #10231.

I made use of this in the `bevy_mod_outline` crate and will have to
duplicate this function if it's not accessible.

## Solution

Change the MeshUniform::new() method to be public.
2024-02-15 22:13:17 +00:00
Carter Anderson
dd619a1087
New Exposure and Lighting Defaults (and calibrate examples) (#11868)
# Objective

After adding configurable exposure, we set the default ev100 value to
`7` (indoor). This brought us out of sync with Blender's configuration
and defaults. This PR changes the default to `9.7` (bright indoor or
very overcast outdoors), as I calibrated in #11577. This feels like a
very reasonable default.

The other changes generally center around tweaking Bevy's lighting
defaults and examples to play nicely with this number, alongside a few
other tweaks and improvements.

Note that for artistic reasons I have reverted some examples, which
changed to directional lights in #11581, back to point lights.
 
Fixes #11577 

---

## Changelog

- Changed `Exposure::ev100` from `7` to `9.7` to better match Blender
- Renamed `ExposureSettings` to `Exposure`
- `Camera3dBundle` now includes `Exposure` for discoverability
- Bumped `FULL_DAYLIGHT ` and `DIRECT_SUNLIGHT` to represent the
middle-to-top of those ranges instead of near the bottom
- Added new `AMBIENT_DAYLIGHT` constant and set that as the new
`DirectionalLight` default illuminance.
- `PointLight` and `SpotLight` now have a default `intensity` of
1,000,000 lumens. This makes them actually useful in the context of the
new "semi-outdoor" exposure and puts them in the "cinema lighting"
category instead of the "common household light" category. They are also
reasonably close to the Blender default.
- `AmbientLight` default has been bumped from `20` to `80`.

## Migration Guide

- The increased `Exposure::ev100` means that all existing 3D lighting
will need to be adjusted to match (DirectionalLights, PointLights,
SpotLights, EnvironmentMapLights, etc). Or alternatively, you can adjust
the `Exposure::ev100` on your cameras to work nicely with your current
lighting values. If you are currently relying on default intensity
values, you might need to change the intensity to achieve the same
effect. Note that in Bevy 0.12, point/spot lights had a different hard
coded ev100 value than directional lights. In Bevy 0.13, they use the
same ev100, so if you have both in your scene, the _scale_ between these
light types has changed and you will likely need to adjust one or both
of them.
2024-02-15 20:42:48 +00:00
Rob Parrett
1d5388eded
Un-hardcode positions and colors in 2d_shapes example (#11867)
# Objective

We recently got some neat new 2d shapes and the shapes are no longer
centered on the screen.

The hardcoded positions and colors are a pain to deal with when a new
shape is added.

## Solution

Delete a bunch of code and position shapes evenly. Assign colors evenly
too.

## Before

<img width="1280" alt="Screenshot 2024-02-14 at 3 17 40 PM"
src="https://github.com/bevyengine/bevy/assets/200550/cc9fd9a8-4019-4907-a50e-621cb656c20a">

## After

<img width="1280" alt="Screenshot 2024-02-14 at 3 17 24 PM"
src="https://github.com/bevyengine/bevy/assets/200550/033a3f91-d3bc-4ec8-af59-42a221f8b8e7">

---------

Co-authored-by: BD103 <59022059+BD103@users.noreply.github.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Joona Aalto <jondolf.dev@gmail.com>
2024-02-14 23:36:18 +00:00
Doonv
dc9b486650
Change light defaults & fix light examples (#11581)
# Objective

Fix https://github.com/bevyengine/bevy/issues/11577.

## Solution

Fix the examples, add a few constants to make setting light values
easier, and change the default lighting settings to be more realistic.
(Now designed for an overcast day instead of an indoor environment)

---

I did not include any example-related changes in here.

## Changelogs (not including breaking changes)

### bevy_pbr

- Added `light_consts` module (included in prelude), which contains
common lux and lumen values for lights.
- Added `AmbientLight::NONE` constant, which is an ambient light with a
brightness of 0.
- Added non-EV100 variants for `ExposureSettings`'s EV100 constants,
which allow easier construction of an `ExposureSettings` from a EV100
constant.

## Breaking changes

### bevy_pbr

The several default lighting values were changed:

- `PointLight`'s default `intensity` is now `2000.0`
- `SpotLight`'s default `intensity` is now `2000.0`
- `DirectionalLight`'s default `illuminance` is now
`light_consts::lux::OVERCAST_DAY` (`1000.`)
- `AmbientLight`'s default `brightness` is now `20.0`
2024-02-14 20:43:10 +00:00
BD103
bc98333d7c
Fix a few Clippy lints (#11866)
# Objective

- The current implementations for `&Visibility == Visibility` and
`Visibility == &Visibility` are ambiguous, so they raise a warning for
being unconditionally recursive.
- `TaskPool`'s `LOCAL_EXECUTOR` thread local calls a `const` constructor
in a non-`const` context.

## Solution

- Make `&Visibility == Visibility` and `Visibility == &Visibility`
implementations use `Visibility == Visibility`.
- Wrap `LocalExecutor::new` in a special `const` block supported by
[`thread_local`](https://doc.rust-lang.org/stable/std/macro.thread_local.html).

---

This lints were found by running:

```shell
$ cargo clippy --workspace
```

There are a few other warnings that were more complicated, so I chose
not to include them in this PR.

<details>
  <summary>Here they are...</summary>

```shell
warning: function cannot return without recursing
  --> crates/bevy_utils/src/cow_arc.rs:92:5
   |
92 | /     fn eq(&self, other: &Self) -> bool {
93 | |         self.deref().eq(other.deref())
94 | |     }
   | |_____^
   |
note: recursive call site
  --> crates/bevy_utils/src/cow_arc.rs:93:9
   |
93 |         self.deref().eq(other.deref())
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

warning: method `get_path` is never used
  --> crates/bevy_reflect/src/serde/de.rs:26:8
   |
25 | trait StructLikeInfo {
   |       -------------- method in this trait
26 |     fn get_path(&self) -> &str;
   |        ^^^^^^^^
   |
   = note: `#[warn(dead_code)]` on by default

warning: methods `get_path` and `get_field` are never used
  --> crates/bevy_reflect/src/serde/de.rs:34:8
   |
33 | trait TupleLikeInfo {
   |       ------------- methods in this trait
34 |     fn get_path(&self) -> &str;
   |        ^^^^^^^^
35 |     fn get_field(&self, index: usize) -> Option<&UnnamedField>;
   |        ^^^^^^^^^
```

The other warnings are fixed by #11865.

</details>
2024-02-14 19:07:18 +00:00
BD103
8018d62e41
Use question mark operator when possible (#11865)
# Objective

- There are multiple instances of `let Some(x) = ... else { None };`
throughout the project.
- Because `Option<T>` implements
[`Try`](https://doc.rust-lang.org/stable/std/ops/trait.Try.html), it can
use the question mark `?` operator.

## Solution

- Use question mark operator instead of `let Some(x) = ... else { None
}`.

---

There was another PR that did a similar thing a few weeks ago, but I
couldn't find it.
2024-02-14 18:44:33 +00:00
Robert Walter
b446374392
Dedicated primitive example (#11697)
I just implemented this to record a video for the new blog post, but I
figured it would also make a good dedicated example. This also allows us
to remove a lot of code from the 2d/3d gizmo examples since it
supersedes this portion of code.

Depends on: https://github.com/bevyengine/bevy/pull/11699
2024-02-14 16:55:44 +00:00
Joona Aalto
8cf3447343
Overwrite gizmo group in insert_gizmo_group (#11860)
# Objective

I tried using `insert_gizmo_group` to configure my physics gizmos in a
bevy_xpbd example, but was surprised to see that nothing happened. I
found out that the method does *not* overwrite gizmo groups that have
already been initialized (with `init_gizmo_group`). This is unexpected,
since methods like `insert_resource` *do* overwrite.

## Solution

Insert the configuration even if it has already been initialized.
2024-02-14 16:20:16 +00:00
Marco Buono
0354ce4450
FilteredEntityRef conversions (#11838)
# Objective

Right now, it's a bit cumbersome to write code that simultaneously deals
with both `FilteredEntityRef`/`EntityRef` or with
`FilteredEntityMut`/`EntityMut`. This PR aims to make it easier by
allowing conversions (both infallible and fallible) between them.

## Solution

- Added infallible conversions from unfiltered into filtered entity refs
- Added fallible conversions from filtered into unfiltered entity refs

---

## Changelog

- Added the following infallible conversions: (`From`)
  - `EntityRef<'a>` → `FilteredEntityRef<'a>`
  - `&'a EntityRef` → `FilteredEntityRef<'a>`
  - `EntityMut<'a>` → `FilteredEntityRef<'a>`
  - `&'a EntityMut` → `FilteredEntityRef<'a>`
  - `EntityWorldMut<'a>` → `FilteredEntityRef<'a>`
  - `&'a EntityWorldMut` → `FilteredEntityRef<'a>`
  - `EntityMut<'a>` → `FilteredEntityMut<'a>`
  - `&'a mut EntityMut` → `FilteredEntityMut<'a>`
  - `EntityWorldMut<'a>` → `FilteredEntityMut<'a>`
  - `&'a mut EntityWorldMut` → `FilteredEntityMut<'a>`
- Added the following _fallible_ conversions: (`TryFrom`)
  - `FilteredEntityRef<'a>` → `EntityRef<'a>`
  - `&'a FilteredEntityRef` → `EntityRef<'a>`
  - `FilteredEntityMut<'a>` → `EntityRef<'a>`
  - `&'a FilteredEntityMut` → `EntityRef<'a>`
  - `FilteredEntityMut<'a>` → `EntityMut<'a>`
  - `&'a mut FilteredEntityMut` → `EntityMut<'a>`
2024-02-14 12:29:58 +00:00
BD103
ebf81c609f
Use std:🧵:sleep instead of spin-waiting in the async_compute example (#11856)
# Objective

- The [`async_compute`
example](77c26f64ce/examples/async_tasks/async_compute.rs (L65-L68))
uses a busy loop.
- It's good practice to mark busy loops with the
[`std::hint::spin_loop`](https://doc.rust-lang.org/stable/std/hint/fn.spin_loop.html)
function.

## Solution

- Call
[`std::hint::spin_loop`](https://doc.rust-lang.org/stable/std/hint/fn.spin_loop.html)
within the busy loop.

## Discussion

- While it is good practice to mark busy loops with `spin_loop`, it does
somewhat increase cognitive complexity. Since it is an example, it does
not matter too much.
- This is somewhat mitigated by the fact that it is within
[`std::hint`](https://doc.rust-lang.org/stable/std/hint/index.html),
which only affects compilation and doesn't do anything.
- Should I add a comment on what `spin_loop` does?
- Should the `while` loop just be replaced with `std:🧵:sleep`?
2024-02-14 02:29:26 +00:00
robtfm
73bf730da9
fix shadow batching (#11645)
# Objective

`RenderMeshInstance::material_bind_group_id` is only set from
`queue_material_meshes::<M>`. this field is used (only) for determining
batch groups, so some items may be batched incorrectly if they have
never been in the camera's view or if they don't use the Material
abstraction.

in particular, shadow views render more meshes than the main camera, and
currently batch some meshes where the object has never entered the
camera view together. this is quite hard to trigger, but should occur in
a scene with out-of-view alpha-mask materials (so that the material
instance actually affects the shadow) in the path of a light.

this is also a footgun for custom pipelines: failing to set the
material_bind_group_id will result in all meshes being batched together
and all using the closest/furthest material to the camera (depending on
sort order).

## Solution

- queue_shadows now sets the material_bind_group_id correctly
- `MeshPipeline` doesn't attempt to batch meshes if the
material_bind_group_id has not been set. custom pipelines still need to
set this field to take advantage of batching, but will at least render
correctly if it is not set
2024-02-14 00:31:45 +00:00
Adam
d3c9c61d86
Fix small docs misformat in BundleInfo::new (#11855)
# Objective

- Fix misformatted section in `BundleInfo::new`

## Solution

- Format it correctly
2024-02-13 22:14:05 +00:00
Friz64
77c26f64ce
Fix sysinfo CPU brand output (#11850)
# Objective

sysinfo was updated to 0.30 in #11071. Ever since then the `cpu` field
of the `SystemInfo` struct that gets printed every time one starts an
bevy app has been empty. This is because the following part of the
sysinfo migration guide was overlooked:

---

### `Cpu` changes

Information like `Cpu::brand`, `Cpu::vendor_id` or `Cpu::frequency` are
not set on the "global" CPU.

---

## Solution

- Get the CPU brand information from a specific CPU instead. In this
case, just choose the first one. It's theoretically possible for
different CPUs to have different names, but in practice this doesn't
really happen I think. Even Intel's newer hybrid processors use a
uniform name for all CPUs in my experience.
- We can use this opportunity to also update our `sysinfo::System`
initialization here to only fetch the information we're interested in.
2024-02-13 19:26:20 +00:00
Niklas Eicker
aca71d09b1
Call a TextureAtlasLayout a layout and not an atlas (#11783)
Make the renamings/changes regarding texture atlases a bit less
confusing by calling `TextureAtlasLayout` a layout, not a texture atlas.

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-02-13 16:08:03 +00:00
Joona Aalto
f1f83bf5bc
Add Mesh::merge (#11456)
# Objective

It can sometimes be useful to combine several meshes into one. This
allows constructing more complex meshes out of simple primitives without
needing to use a 3D modeling program or entity hierarchies.

This could also be used internally to increase code reuse by using
existing mesh generation logic for e.g. circles and using that in
cylinder mesh generation logic to add the top and bottom of the
cylinder.

**Note**: This is *not* implementing CSGs (Constructive Solid Geometry)
or any boolean operations, as that is much more complex. This is simply
adding the mesh data of another mesh to a mesh.

## Solution

Add a `merge` method to `Mesh`. It appends the vertex attributes and
indices of `other` to `self`, resulting in a `Mesh` that is the
combination of the two.

For example, you could do this:

```rust
let mut cuboid = Mesh::from(shape::Box::default());
let mut cylinder = Mesh::from(shape::Cylinder::default());
let mut torus = Mesh::from(shape::Torus::default());

cuboid.merge(cylinder);
cuboid.merge(torus);
```

This would result in `cuboid` being a `Mesh` that also has the cylinder
mesh and torus mesh. In this case, they would just be placed on top of
each other, but by utilizing #11454 we can transform the cylinder and
torus to get a result like this:


https://github.com/bevyengine/bevy/assets/57632562/557402c6-b896-4aba-bd95-312e7d1b5238

This is just a single entity and a single mesh.
2024-02-12 22:04:33 +00:00
Kanabenki
2d90b2093a
Fix global wireframe behavior not being applied on new meshes (#11792)
# Objective

- Fixes #11782.

## Solution

- Remove the run condition for `apply_global_wireframe_material`, since
it prevent detecting when meshes are added or the `NoWireframe` marker
component is removed from an entity. Alternatively this could be done by
using a run condition like "added `Handle<Mesh>` or removed
`NoWireframe` or `WireframeConfig` changed" but this seems less clear to
me than directly letting the queries on
`apply_global_wireframe_material` do the filtering.
2024-02-12 19:48:45 +00:00
BD103
b721aaa9d3
Replace crossbeam::scope reference with thread::scope in docs (#11832)
# Objective

-
[`crossbeam::scope`](https://docs.rs/crossbeam/latest/crossbeam/fn.scope.html)
is soft-deprecated in favor of the standard library's implementation.

## Solution

- Replace reference in `TaskPool`'s docs to mention `std:🧵:scope`
instead.
2024-02-12 19:29:29 +00:00
Lynn
2bc48254b8
Add delta to CursorMoved event (#11710)
# Objective

- Fixes #11695

## Solution

- Added `delta: Option<Vec2>` to `bevy_window::CursorMoved`. `delta` is
an `Option` because the `CursorMoved` event does get fired when the
cursor was outside the window area in the last frame. In that case there
is no cursor position from the last frame to compare with the current
cursor position.

---

## Changelog

- Added `delta: Option<Vec2>` to `bevy_window::CursorMoved`. 

## Migration Guide

- You need to add `delta` to any manually created `CursorMoved` struct.

---------

Co-authored-by: Kanabenki <lucien.menassol@gmail.com>
Co-authored-by: James Liu <contact@jamessliu.com>
2024-02-12 18:14:22 +00:00
Zachary Harrold
7b5a4ec4ed
Use Asset Path Extension for AssetLoader Disambiguation (#11644)
# Objective

- Fixes #11638
- See
[here](https://github.com/bevyengine/bevy/issues/11638#issuecomment-1920508465)
for details on the cause of this issue.

## Solution

- Modified `AssetLoaders` to capture possibility of multiple
`AssetLoader` registrations operating on the same `Asset` type, but
different extensions.
- Added an algorithm which will attempt to resolve via `AssetLoader`
name, then `Asset` type, then by extension. If at any point multiple
loaders fit a particular criteria, the next criteria is used as a tie
breaker.
2024-02-12 15:44:55 +00:00
James Liu
87add5660f
Immediately poll the executor once before spawning it as a task (#11801)
# Objective
At the start of every schedule run, there's currently a guaranteed piece
of overhead as the async executor spawns the MultithreadeExecutor task
onto one of the ComputeTaskPool threads.

## Solution
Poll the executor once to immediately schedule systems without waiting
for the async executor, then spawn the task if and only if the executor
does not immediately terminate.

On a similar note, having the executor task immediately start executing
a system in the same async task might yield similar results over a
broader set of cases. However, this might be more involved, and may need
a solution like #8304.
2024-02-12 15:33:35 +00:00
Joseph
bd25135330
Fix double indirection when applying command queues (#11822)
# Objective

When applying a command, we currently use double indirection for the
world reference `&mut Option<&mut World>`. Since this is used across a
`fn` pointer boundary, this can't get optimized away.

## Solution

Reborrow the world reference and pass `Option<&mut World>` instead.
2024-02-12 15:27:18 +00:00
James Liu
eee71bfa93
Put asset_events behind a run condition (#11800)
# Objective
Scheduling low cost systems has significant overhead due to task pool
contention and the extra machinery to schedule and run them. Following
the example of #7728, `asset_events` is good example of this kind of
system, where there is no work to be done when there are no queued asset
events.

## Solution
Put a run condition on it that checks if there are any queued events.

## Performance
Tested against `many_foxes`, we can see a slight improvement in the
total time spent in `UpdateAssets`. Also noted much less volatility due
to not being at the whim of the OS thread scheduler.

![image](https://github.com/bevyengine/bevy/assets/3137680/e0b282bf-27d0-4fe4-81b9-ecd72ab258e5)

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-02-12 15:19:36 +00:00
Gino Valente
9e30aa7c92
bevy_reflect_derive: Clean up attribute logic (#11777)
# Objective

The code in `bevy_reflect_derive` could use some cleanup.

## Solution

Took some of the changes in #11659 to create a dedicated PR for cleaning
up the field and container attribute logic.

#### Updated Naming

I renamed `ReflectTraits` and `ReflectFieldAttr` to
`ContainerAttributes` and `FieldAttributes`, respectively. I think these
are clearer.

#### Updated Parsing

##### Readability

The parsing logic wasn't too bad before, but it was getting difficult to
read. There was some duplicated logic between `Meta::List` and
`Meta::Path` attributes. Additionally, all the logic was kept inside a
large method.

To simply things, I replaced the nested meta parsing with `ParseStream`
parsing. In my opinion, this is easier to follow since it breaks up the
large match statement into a small set of single-line if statements,
where each if-block contains a single call to the appropriate attribute
parsing method.

##### Flexibility

On top of the added simplicity, this also makes our attribute parsing
much more flexible. It allows us to more elegantly handle custom where
clauses (i.e. `#[reflect(where T: Foo)]`) and it opens the door for more
non-standard attribute syntax (e.g. #11659).

##### Errors

This also allows us to automatically provide certain errors when
parsing. For example, since we can use `stream.lookahead1()`, we get
errors like the following for free:

```
error: expected one of: `ignore`, `skip_serializing`, `default`
    --> crates/bevy_reflect/src/lib.rs:1988:23
     |
1988 |             #[reflect(foo)]
     |                       ^^^
```

---

## Changelog

> [!note]
> All changes are internal to `bevy_reflect_derive` and should not
affect the public API[^1].

- Renamed `ReflectTraits` to `ContainerAttributes`
  - Renamed `ReflectMeta::traits` to `ReflectMeta::attrs`
- Renamed `ReflectFieldAttr` to `FieldAttributes`
- Updated parsing logic for field/container attribute parsing
  - Now uses a `ParseStream` directly instead of nested meta parsing
- General code cleanup of the field/container attribute modules for
`bevy_reflect_derive`


[^1]: Does not include errors, which may look slightly different.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-02-12 15:16:27 +00:00
Joseph
9c2257332a
Add a method for detecting changes within a certain scope (#11687)
# Objective

Bevy's change detection functionality is invaluable for writing robust
apps, but it only works in the context of systems and exclusive systems.
Oftentimes it is necessary to detect changes made in earlier code
without having to place the code in separate systems, but it is not
currently possible to do so since there is no way to set the value of
`World::last_change_tick`.

`World::clear_trackers` allows you to update the change tick, but this
has unintended side effects, since it irreversibly affects the behavior
of change and removal detection for the entire app.

## Solution

Add a method `World::last_change_tick_scope`. This allows you to set
`last_change_tick` to a specific value for a region of code. To ensure
that misuse doesn't break unrelated functions, we restore the world's
original change tick at the end of the provided scope.

### Example

A function that uses this to run an update loop repeatedly, allowing
each iteration of the loop to react to changes made in the previous loop
iteration.

```rust
fn update_loop(
    world: &mut World,
    mut update_fn: impl FnMut(&mut World) -> std::ops::ControlFlow<()>,
) {
    let mut last_change_tick = world.last_change_tick();

    // Repeatedly run the update function until it requests a break.
    loop {
        // Update once.
        let control_flow = world.last_change_tick_scope(last_change_tick, |world| {
            update_fn(world)
        });

        // End the loop when the closure returns `ControlFlow::Break`.
        if control_flow.is_break() {
            break;
        }

        // Increment the change tick so the next update can detect changes from this update.
        last_change_tick = world.change_tick();
        world.increment_change_tick();
    }
}
```

---

## Changelog

+ Added `World::last_change_tick_scope`, which allows you to specify the
reference for change detection within a certain scope.
2024-02-12 15:09:11 +00:00
BD103
078dd061a7
bevy_dynamic_plugin: fix unsafe_op_in_unsafe_fn lint (#11622)
# Objective

- Part of #11590.

## Solution

- Fix `unsafe_op_in_unsafe_fn` for `bevy_dynamic_plugin`.

---

## Changelog

- Added further restrictions to the safety requirements of
`bevy_dynamic_plugin::dynamically_load_plugin`.

---

I had a few issues, specifically with the safety comment on
`dynamically_load_plugin`. There are three different unsafe functions
called within the function body, and they all need their own
justification / message.

Also, would it be unsound to call `dynamically_load_plugin` multiple
times on the same file? I feel the documentation needs to be more clear.
2024-02-12 15:06:00 +00:00
Doonv
1c67e020f7
Move EntityHash related types into bevy_ecs (#11498)
# Objective

Reduce the size of `bevy_utils`
(https://github.com/bevyengine/bevy/issues/11478)

## Solution

Move `EntityHash` related types into `bevy_ecs`. This also allows us
access to `Entity`, which means we no longer need `EntityHashMap`'s
first generic argument.

---

## Changelog

- Moved `bevy::utils::{EntityHash, EntityHasher, EntityHashMap,
EntityHashSet}` into `bevy::ecs::entity::hash` .
- Removed `EntityHashMap`'s first generic argument. It is now hardcoded
to always be `Entity`.

## Migration Guide

- Uses of `bevy::utils::{EntityHash, EntityHasher, EntityHashMap,
EntityHashSet}` now have to be imported from `bevy::ecs::entity::hash`.
- Uses of `EntityHashMap` no longer have to specify the first generic
parameter. It is now hardcoded to always be `Entity`.
2024-02-12 15:02:24 +00:00
Tristan Guichaoua
c1a4e29a1e
Replace pointer castings (as) by their API equivalent (#11818)
# Objective

Since rust `1.76`,
[`ptr::from_ref`](https://doc.rust-lang.org/stable/std/ptr/fn.from_ref.html)
and
[`ptr::from_mut`](https://doc.rust-lang.org/stable/std/ptr/fn.from_mut.html)
are stable.

This PR replaces code that use `as` casting by one of `ptr::from_ref`,
`ptr::from_mut`, `cast_mut`, `cast_const`, or `cast` methods, which are
less error-prone.

## Solution

- Bump MSRV to `1.76.0`
- Enables the following clippy lints:
-
[`ptr_as_ptr`](https://rust-lang.github.io/rust-clippy/master/index.html#/ptr_as_ptr)
-
[`ptr_cast_constness`](https://rust-lang.github.io/rust-clippy/master/index.html#/ptr_cast_constness)
-
[`ref_as_ptr`](https://rust-lang.github.io/rust-clippy/master/index.html#/ref_as_ptr)
(I fix all warnings for this one, but it requires rust 1.77 to be
enabled)
- Fix the lints mentioned above
2024-02-11 23:19:36 +00:00
anarelion
94ab84e915
mipmap levels can be 0 and they should be interpreted as 1 (#11767)
# Objective

Loading some textures from the days of yonder give me errors cause the
mipmap level is 0

## Solution

Set a minimum of 1

## Changelog

Make mipmap level at least 1
2024-02-11 22:00:07 +00:00
Shane Celis
61e01e46b5
Derive Ord for GamepadButtonType. (#11791)
# Objective

Use `GamepadButtonType` with library that requires `Ord`.

## Motivation

`KeyCode` derives `Ord` that I'm using with a trie for recognizing
[input
sequences](https://github.com/shanecelis/bevy-input-sequence/tree/trie).
I would like to do the same for `GamepadButtonType` but am stymied by it
not deriving `Ord`.

## Solution

This PR add derivations PartialOrd and Ord for `GamepadButtonType`.

## Workaround

If deriving `Ord` is not possible, I'd be happy to know how I might
coerce `GamepadButtonType` into a `u32` or something else that is `Ord`,
so I can wrap `GamepadButtonType` in a newtype. I suppose serializing
with serde may work or reflect?
2024-02-11 09:03:06 +00:00
Friz64
d939c4402d
Avoid unwraps in winit fullscreen handling code (#11735)
# Objective

- Get rid of unwraps in winit fullscreen handling code, which are the
source of some crashes.
- Fix #11275

## Solution

- Replace the unwraps with warnings. Ignore the fullscreen request, do
nothing instead.
2024-02-10 20:17:04 +00:00
Patrick Walton
b6945e5332
Stop copying the light probe array to the stack in the shader. (#11805)
This was causing a severe performance regression when light probes were
enabled.

Fixes #11787.
2024-02-10 15:47:29 +00:00
Joseph
2e2f89869b
Expose query accesses (#11700)
# Objective

It would be useful to be able to inspect a `QueryState`'s accesses so we
can detect when the data it accesses changes without having to iterate
it. However there are two things preventing this:

* These accesses are unnecessarily encapsulated.
* `Has<T>` indirectly accesses `T`, but does not register it.

## Solution

* Expose accesses and matches used by `QueryState`.
* Add the notion of "archetypal" accesses, which are not accessed
directly, but whose presence in an archetype affects a query result.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-02-10 15:22:07 +00:00
Tristan Guichaoua
33676112da
doc(bevy_reflect): add note about trait bounds on impl_type_path (#11810)
# Objective

- fixes #11651
2024-02-10 15:18:16 +00:00