Commit Graph

9188 Commits

Author SHA1 Message Date
Nicholas Nethercote
2d02f629b3
bevy_reflect: Remove unnecessary allow(unused_mut). (#19930)
# Objective

The generated `GetTypeRegistration::get_type_registration` method has an
unnecessary `allow(unused_mut)` attribute. It used to be necessary
because it was possible for `registration` to not be modified, but now
there is always at least one modification.

## Solution

Remove the attribute.

## Testing

I checked the `cargo expand` output.
2025-07-03 22:27:58 +00:00
robtfm
eed3085a37
fix panic looking for extension in multibyte unicode paths (#19933)
# Objective

```
2025-07-03T11:48:34.039501Z ERROR panic: thread 'IO Task Pool (6)' panicked at 'byte index 9 is not a char boundary; it is inside '个' (bytes 7..10) of `展示_个人收款码.png`': [...]\crates\bevy_asset\src\path.rs:475
```

## Solution

char_indices
2025-07-03 22:27:07 +00:00
charlotte 🌸
852fb84aa2
Add options for selecting adapter by name and forcing fallback (#19921)
Adds support for:
- `WGPU_ADAPTER_NAME` which will attempt to select a specific adapter
with a given name.
- `WGPU_FORCE_FALLBACK_ADAPTER` which will force fallback to a fallback
(software) renderer, if available.

The first has higher specificity than the second.
2025-07-03 22:26:34 +00:00
Chris Russell
6e918f56d8
Have System::run_unsafe return Result. (#19145)
# Objective

Allow combinator and pipe systems to delay validation of the second
system, while still allowing the second system to be skipped.

Fixes #18796

Allow fallible systems to be used as one-shot systems, reporting errors
to the error handler when used through commands.

Fixes #19722

Allow fallible systems to be used as run conditions, including when used
with combinators. Alternative to #19580.

Always validate parameters when calling the safe
`run_without_applying_deferred`, `run`, and `run_readonly` methods on a
`System`.

## Solution

Have `System::run_unsafe` return a `Result`.  

We want pipe systems to run the first system before validating the
second, since the first system may affect whether the second system has
valid parameters. But if the second system skips then we have no output
value to return! So, pipe systems must return a `Result` that indicates
whether the second system ran.

But if we just make pipe systems have `Out = Result<B::Out>`, then
chaining `a.pipe(b).pipe(c)` becomes difficult. `c` would need to accept
the `Result` from `a.pipe(b)`, which means it would likely need to
return `Result` itself, giving `Result<Result<Out>>`!

Instead, we make *all* systems return a `Result`! We move the handling
of fallible systems from `IntoScheduleConfigs` and `IntoObserverSystem`
to `SystemParamFunction` and `ExclusiveSystemParamFunction`, so that an
infallible system can be wrapped before being passed to a combinator.

As a side effect, this enables fallible systems to be used as run
conditions and one-shot systems.

Now that the safe `run_without_applying_deferred`, `run`, and
`run_readonly` methods return a `Result`, we can have them perform
parameter validation themselves instead of requiring each caller to
remember to call them. `run_unsafe` will continue to not validate
parameters, since it is used in the multi-threaded executor when we want
to validate and run in separate tasks.

Note that this makes type inference a little more brittle. A function
that returns `Result<T>` can be considered either a fallible system
returning `T` or an infallible system returning `Result<T>` (and this is
important to continue supporting `pipe`-based error handling)! So there
are some cases where the output type of a system can no longer be
inferred. It will work fine when directly adding to a schedule, since
then the output type is fixed to `()` (or `bool` for run conditions).
And it will work fine when `pipe`ing to a system with a typed input
parameter.

I used a dedicated `RunSystemError` for the error type instead of plain
`BevyError` so that skipping a system does not box an error or capture a
backtrace.
2025-07-03 21:48:09 +00:00
Vadim
ec825d135b
Remove leftover apply deferred example metadata from Cargo.toml (#19939)
I was a bit confused when searching for info about apply deferred, then
I found this metadata without the actual example in the manifest.
2025-07-03 20:42:51 +00:00
Wuketuke
4564a5ba0d
improved the entity_index_map unit test (#19936)
...which previously used a HashSet, whos iter has no ordering guarantee

fixes #19687
i also discovered that the asserted order in the unit test is reversed,
so i fixed that. I dont know if that reversed order is intentional

Edit: i referenced the wrong issue oops
2025-07-03 20:36:09 +00:00
theotherphil
4e32caf027
Fix docs typo (#19937)
Fix a doc comment typo.
2025-07-03 19:02:50 +00:00
Joe Buehler
d16d216083
Add support for returning all Component and values to query method in the Bevy Remote Protocol (#19857)
# Objective

We should have an API with filtering to allow BRP clients to retrieve
all relevant data from the world state. Currently working on adding
examples - but reviews are appreciated! Still semi-WIP while I get my
head around bevy’s reflection and implementation :)

## Solution

This change adds support to query all entities in the world, and returns
all of their Reflected Components with corresponding values. For custom
`Components` it's important to still implement `Reflect` so that this
endpoint returns these. This will be useful for the
`bevy_entity_inspector` so that we can easily get the current world
state. We have modified the existing query API
so that clients can now pass in an empty `components[]` on the JSON
request.

## Testing

Updated example to showcase how to use the new endpoint to get all data:
```rust
/// Create a query_all request to send to the remote Bevy app.
/// This request will return all entities in the app, their components, and their
/// component values.
fn run_query_all_components_and_entities(url: String) -> Result<(), anyhow::Error> {
    let query_all_req = BrpRequest {
        jsonrpc: String::from("2.0"),
        method: String::from(BRP_QUERY_METHOD),
        id: Some(serde_json::to_value(1)?),
        params: None,
    };
    println!("query_all req: {:#?}", query_all_req);
    let query_all_res = ureq::post(&url)
        .send_json(query_all_req)?
        .body_mut()
        .read_json::<serde_json::Value>()?;
    println!("{query_all_res:#}");
    Ok(())
}
```

---

## Showcase
In the `client.rs` example, we can clearly see (assuming the `server.rs`
is running) a query hit for all entities and components:
```text
query_all req: BrpRequest {
    jsonrpc: "2.0",
    method: "bevy/query",
    id: Some(
        Number(1),
    ),
    params: Some(
        Object {
            "data": Object {
                "components": Array [],
                "has": Array [],
                "option": Array [],
            },
            "filter": Object {
                "with": Array [],
                "without": Array [],
            },
            "strict": Bool(false),
        },
    ),
}
```

And in the massive response:
```text
.....
{
      "components": {
        "bevy_window::monitor::Monitor": {
          "name": "\\\\.\\DISPLAY1",
          "physical_height": 1080,
          "physical_position": [
            -1920,
            0
          ],
          "physical_width": 1920,
          "refresh_rate_millihertz": 240000,
          "scale_factor": 1.25,
          "video_modes": [
            {
              "bit_depth": 32,
              "physical_size": [
                1920,
                1080
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                1680,
                1050
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                1600,
                900
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                1440,
                900
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                1400,
                1050
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                1366,
                768
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                1360,
                768
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                1280,
                1024
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                1280,
                960
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                1280,
                800
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                1280,
                768
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                1280,
                720
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                1280,
                600
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                1152,
                864
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                1024,
                768
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                800,
                600
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                640,
                480
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                640,
                400
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                512,
                384
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                400,
                300
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                320,
                240
              ],
              "refresh_rate_millihertz": 240000
            },
            {
              "bit_depth": 32,
              "physical_size": [
                320,
                200
              ],
              "refresh_rate_millihertz": 240000
            }
          ]
        }
      },
      "entity": 4294967267
    },
....
```

What's also really cool about this and `bevy_reflect` is that we also
get custom components returned as well (see below for `"server::Cube":
1.0` as the custom reflected struct specified in `server.rs`:

```text
{
      "components": {
        "bevy_render::primitives::Aabb": {
          "center": [
            0.0,
            0.0,
            0.0
          ],
          "half_extents": [
            0.5,
            0.5,
            0.5
          ]
        },
        "bevy_render::view::visibility::InheritedVisibility": true,
        "bevy_render::view::visibility::ViewVisibility": true,
        "bevy_render::view::visibility::Visibility": "Inherited",
        "bevy_transform::components::global_transform::GlobalTransform": [
          1.0,
          0.0,
          0.0,
          0.0,
          1.0,
          0.0,
          0.0,
          0.0,
          1.0,
          0.0,
          2.4572744369506836,
          0.0
        ],
        "bevy_transform::components::transform::Transform": {
          "rotation": [
            0.0,
            0.0,
            0.0,
            1.0
          ],
          "scale": [
            1.0,
            1.0,
            1.0
          ],
          "translation": [
            0.0,
            2.4572744369506836,
            0.0
          ]
        },
        "bevy_transform::components::transform::TransformTreeChanged": null,
        "server::Cube": 1.0
      },
```

---------

Co-authored-by: Jan Hohenheim <jan@hohenheim.ch>
2025-07-03 18:51:32 +00:00
Christian Hughes
ebf87f56ef
Use SlotMaps to store systems and system sets in Schedules (#19352)
# Objective

- First step towards #279

## Solution

Makes the necessary internal data structure changes in order to allow
system removal to be added in a future PR: `Vec`s storing systems and
system sets in `ScheduleGraph` have been replaced with `SlotMap`s.

See the included migration guide for the required changes.

## Testing

Internal changes only and no new features *should* mean no new tests are
requried.
2025-07-03 18:50:54 +00:00
Emerson Coskey
bbf91a6964
spec_v2: minor revisions (#19923)
- renamed `spec_v2` related modules, that commit slipped through the
other pr #17373
- revised struct and trait docs for clarity, and gave a short intro to
specialization
- turns out the derive macro was broken, fixed that too
2025-07-03 17:49:04 +00:00
James Lucas
0f1eebed38
Fixing sprite pixel space point computation for sprites with zero custom_size (#19907)
# Objective

Current implementation of `Sprite::compute_pixel_space_point` always
returns the sprite centre as an `Ok` point when the `custom_size` is set
to `Vec2::ZERO`. This leads to unexpected behaviour. For example, it
causes these sprites to block all interactions with other sprites in the
picking backend (under default settings). This small PR:

- Fixes sprite pixel space point computation for sprites with zero
custom_size
- Resolves issue #19880.

## Solution

We handle the zero custom_size case explicitly and return
`Err(point_relative_to_sprite_center)` instead of
`Ok(point_relative_to_texture)`.

## Testing

Implemented a new test for zero custom_size sprites within the
`bevy_sprite::sprite` module. Also verified that the example from issue
#19880 is behaving as expected.

No further testing is required.

- How can other people (reviewers) test your changes? Is there anything
specific they need to know?

Can run the simple application example from the linked issue. Or
evaluate the implemented test.

---------

Co-authored-by: James Lucas <jalucas@nvidia.com>
2025-07-03 17:43:32 +00:00
Talin
870490808d
Feathers toggle switches. (#19928)
# Objective

This is the Feathers toggle switch widget (without animation).

Part of #19236 

### Showcase

<img width="143" alt="toggles"
src="https://github.com/user-attachments/assets/c04afc06-5a57-4bc6-8181-99efbd1bebef"
/>
2025-07-03 01:09:31 +00:00
Jordan Halase
0adbacd4c2
Set checkbox and radio fill color to gray when disabled in core widgets example (#19792)
Simple color change to the core widgets example. This sets the fill
colors of the elements to gray if they are selected but disabled. It was
hard to notice if they were disabled when they were still green.


![disabled_gray](https://github.com/user-attachments/assets/299f0700-9fab-4aa4-9076-f17859a60a5e)
2025-07-02 23:55:58 +00:00
Greeble
05d954e1ab
Add test that repros #11111 (different loader settings produce same asset) (#19094)
## Objective

Add a test that reproduces #11111 (and partially #18267). The bug is
that asset loader settings are effectively ignored if the same asset is
loaded multiple times with different settings.

## Solution

Add a unit test to `bevy_assets/lib.rs`. The test will be marked as
`#[ignore]` until #11111 is fixed.

```rust
// Load the same asset with different settings.

let handle_1 = load(asset_server, "test.u8", 1);
let handle_2 = load(asset_server, "test.u8", 2);

// Handles should be different.

assert_ne!(handle_1, handle_2);
```

## Concerns

I'm not 100% sure that the current behaviour is actually broken - I
can't see anything in the asset system design docs that explicitly says
different settings should create different asset ids.

UPDATE: Sentiment from issue comments and discord varies between "bug"
and "undesirable consequence of design decisions, alternatives should be
explored". So I've concluded that the test is valid and desirable.

## Testing

```sh
cargo test -p bevy_asset --features multi_threaded

# Or to repro the issue:
cargo test -p bevy_asset --features multi_threaded -- --ignored
```
2025-07-02 22:39:04 +00:00
andriyDev
8098cf21ca
Use RenderStartup in bevy_anti_aliasing. (#19897)
# Objective

- Progress towards #19887.

## Solution

- Rewrite the FromWorld impls to systems that create the pipeline
resources.

## Testing

- Ran the `anti_aliasing` example and it still works.
2025-07-02 22:38:44 +00:00
andriyDev
e70f84536a
Use RenderStartup in bevy_gizmos. (#19898)
# Objective

- Progress towards #19887.

## Solution

- Convert `FromWorld` impls into systems that run in `RenderStartup`.
- Add an ordering constraint to ensure that necessary resources exist.

## Testing

- Ran `2d_gizmos` and `3d_gizmos` examples and it still worked.
2025-07-02 20:38:37 +00:00
robtfm
b79b8133c8
fix skin uniform buffer size (#19888)
# Objective

for `BufferUsages::STORAGE` on webgpu (and maybe other contexts), buffer
sizes must be a multiple of 4. the skin uniform buffer starts at 16384
then increases by 1.5x, which eventually hits a number which isn't

## Solution

`.next_multiple_of(4)`
2025-07-02 20:06:27 +00:00
Greeble
861e778c4c
Add unit structs for each ease function (#18739)
## Objective

Allow users to directly call ease functions rather than going through
the `EaseFunction` struct. This is less verbose and more efficient when
the user doesn't need the data-driven aspects of `EaseFunction`.

## Background

`EaseFunction` is a flexible and data-driven way to apply easing. But
that has a price when a user just wants to call a specific ease
function:

```rust
EaseFunction::SmoothStep.sample(t);
```

This is a bit verbose, but also surprisingly inefficient. It calls the
general `EaseFunction::eval`, which won't be inlined and adds an
unnecessary branch. It can also increase code size since it pulls in all
ease functions even though the user might only require one. As far as I
can tell this is true even with `opt-level = 3` and `lto = "fat"`.

```asm
; EaseFunction::SmoothStep.sample_unchecked(t)
lea rcx, [rip + __unnamed_2] ; Load the disciminant for EaseFunction::SmoothStep.
movaps xmm1, xmm0
jmp bevy_math::curve::easing::EaseFunction::eval    
```

## Solution

This PR adds a struct for each ease function. Most are unit structs, but
a couple have parameters:

```rust
SmoothStep.sample(t);

Elastic(50.0).sample(t);

Steps(4, JumpAt::Start).sample(t)
```

The structs implement the `Curve<f32>` trait. This means they fit into
the broader `Curve` system, and the user can choose between `sample`,
`sample_unchecked`, and `sample_clamped`. The internals are a simple
function call so the compiler can easily estimate the cost of inlining:

```asm
; SmoothStep.sample_unchecked(t)
movaps xmm1, xmm0
addss xmm1, xmm0
movss xmm2, dword ptr [rip + __real@40400000] ; 3.0
subss xmm2, xmm1
mulss xmm2, xmm0
mulss xmm0, xmm2
```

In a microbenchmark this is around 4x faster. If inlining permits
auto-vectorization then it's 20-50x faster, but that's a niche case.

Adding unit structs is also a small boost to discoverability - the unit
struct can be found in VS Code via "Go To Symbol" -> "smoothstep", which
doesn't find `EaseFunction::SmoothStep`.

### Concerns

- While the unit structs have advantages, they add a lot of API surface
area.
- Another option would have been to expose the underlying functions.
  - But functions can't implement the `Curve` trait.
- And the underlying functions are unclamped, which could be a footgun.
- Or there have to be three functions to cover unchecked/checked/clamped
variants.
- The unit structs can't be used with `EasingCurve`, which requires
`EaseFunction`.
  - This might confuse users and limit optimisation.
    -  Wrong: `EasingCurve::new(a, b, SmoothStep)`.
    -  Right: `EasingCurve::new(a, b, EaseFunction::SmoothStep)`.
- In theory `EasingCurve` could be changed to support any `Curve<f32>`
or a more limited trait.
- But that's likely to be a breaking change and raises questions around
reflection and reliability.
- The unit structs don't have serialization.
- I don't know much about the motivations/requirements for
serialization.
- Each unit struct duplicates the documentation of `EaseFunction`.
- This is convenient for the user, but awkward for anyone updating the
code.
- Maybe better if each unit struct points to the matching
`EaseFunction`.
  - Might also make the module page less intimidating (see screenshot).


![image](https://github.com/user-attachments/assets/59d1cf1f-d136-437f-8ad6-fdae8ca7d57a)

## Testing

```
cargo test -p bevy_math
```
2025-07-02 19:18:20 +00:00
charlotte 🌸
18712f31f9
Make render and compute pipeline descriptors defaultable. (#19903)
A few versions ago, wgpu made it possible to set shader entry point to
`None`, which will select the correct entry point in file where only a
single entrypoint is specified. This makes it possible to implement
`Default` for pipeline descriptors. This PR does so and attempts to
`..default()` everything possible.
2025-07-02 18:47:27 +00:00
Nicholas Nethercote
1b4cf02fc8
bevy_reflect: streamline generated FromReflect::from_reflect (#19906)
# Objective

Generated `from_reflect` methods use closures in a weird way, e.g.:
```rust
    x: (|| {
        <f32 as ::bevy::reflect::FromReflect>::from_reflect(
            ::bevy::reflect::Struct::field(__ref_struct, "x")?,
        )   
    })()?,
```
The reason for this is because when `#[reflect(Default)]` is used, you
instead get stuff like this:
```rust
    if let ::core::option::Option::Some(__field) = (|| {
        <f32 as ::bevy::reflect::FromReflect>::from_reflect(
            ::bevy::reflect::Struct::field(__ref_struct, "x")?,
        )   
    })() {
        __this.x = __field;
    } 
```
and the closure is necessary to contain the scope of the `?`. But the
first case is more common.

Helps with #19873.

## Solution

Avoid the closure in the common case.

## Testing

I used cargo expand to confirm the closures are no longer produced in
the common case.

`-Zmacro-stats` output tells me this reduces the size of the `Reflect`
code produced for `bevy_ui` by 0.5%.
2025-07-02 14:59:20 +00:00
andriyDev
f95f42b44a
Allow calling add_render_graph_node on World. (#19912)
# Objective

- This unblocks some work I am doing for #19887.

## Solution

- Rename `RenderGraphApp` to `RenderGraphExt`.
- Implement `RenderGraphExt` for `World`.
- Change `SubApp` and `App` to call the `World` impl.
2025-07-02 14:56:18 +00:00
jf908
c8cdb1197e
Add instructions for GPU debugging in Xcode (#19915)
# Objective

- Using Xcode can be confusing to setup for rust projects.

# Solution

- Add instructions to docs/profiling.md for how to use start debugging a
bevy project with Xcode's GPU debugging/profiling tools.
2025-07-02 14:55:25 +00:00
François Mockers
e42d386625
set required-features for example light_textures & clustered_decals (#19913)
# Objective

- Example `light_textures` exit if feature `pbr_light_textures` is not
enabled. this is checked in code instead of using `required-features`
- Same for `clustered_decals` and `par_clustered_decals`
- Those examples are also using `eprintln`
- Those examples are using `process:exit` to exit

## Solution

- Use `required-features`
- Use logs
- Use `AppExit`
2025-07-02 14:54:10 +00:00
Nicholas Nethercote
607f9f24d3
Avoid unnecessary ReflectMeta arguments (#19919)
# Objective

`WhereClauseOption` contains a reference to a `ReflectMeta`. Oddly
enough, a bunch of functions that take a `WhereClauseOption` argument
also take a `ReflectMeta` reference argument, which is exactly the same
as the reference in the `WhereClauseOption`.

## Solution

This commit removes the redundant `ReflectMeta` argument from these
functions. This requires adding a `WhereClauseOption::meta` getter
method.

## Testing

`cargo run -p ci`
2025-07-02 14:53:52 +00:00
Alix Bott
ee1807395e
Implement MapEntities for arrays, HashMap, BTreeMap, IndexMap (#19908)
# Objective

- `MapEntities` is not implemented for arrays, `HashMap`, `BTreeMap`,
and `IndexMap`.

## Solution

- Implement `MapEntities` for arrays, `HashMap`, `BTreeMap`, `IndexMap`

## Testing

- I didn't add a test for this as the implementations seems pretty
trivial
2025-07-02 14:50:55 +00:00
SpecificProtagonist
9e0c66bd65
Ecs derive docs (#19892)
# Objective

Concise syntax docs on `Component`/`Event` derives. Partial fix for
#19537.

## Solution

Only document syntax. The doc tests are set to ignore because the macro
relies on the presence of `bevy_ecs`.
2025-07-02 14:44:18 +00:00
andriyDev
d05c435848
Replace Handle::Weak with Handle::Uuid. (#19896)
# Objective

- Progress towards #19024.

## Solution

- Remove `Handle::Weak`!

If users were relying on `Handle::Weak` for some purpose, they can
almost certainly replace it with raw `AssetId` instead. If they cannot,
they can make their own enum that holds either a Handle or an AssetId.
In either case, we don't need weak handles!

Sadly we still need Uuid handles since we rely on them for "default"
assets and "invalid" assets, as well as anywhere where a component wants
to impl default with a non-defaulted asset handle. One step at a time
though!
2025-07-02 14:40:35 +00:00
andriyDev
1a410efd24
Flatten PrepassPipelineInternal into PrepassPipeline. (#19909)
# Objective

- PrepassPipelineInternal used to exist to optimize compile time and
binary size when PrepassPipeline was generic over the material.
- After #19667, PrepassPipeline is no longer generic!

## Solution

- Flatten all the fields of `PrepassPipelineInternal` into
`PrepassPipeline`.
2025-07-01 19:27:42 +00:00
ickshonpe
a949867a1c
UI z-ordering fix (#19691)
# Objective

During the migration to required components a lot of things were changed
around and somehow the draw order for some UI elements ended up
depending on the system ordering in `RenderSystems::Queue`, which can
sometimes result in the elements being drawn in the wrong order.

Fixes #19674

## Solution

* Added some more `stack_z_offsets` constants and used them to enforce
an explicit ordering.
* Removed the `stack_index: u32` field from `ExtractedUiNodes` and
replaced it with a `z_order: f32` field.

These changes should fix all the ordering problems. 

## Testing

I added a nine-patched bordered node with a navy background color to the
slice section of the `testbed_ui` example.
The border should always be drawn above the background color.
2025-07-01 19:20:07 +00:00
ickshonpe
5e8aa7986b
Newtyped ScrollPosition (#19881)
# Objective

Change `ScrollPosition` to newtype `Vec2`. It's easier to work with a
`Vec2` wrapper than individual fields.

I'm not sure why this wasn't newtyped to start with. Maybe the intent
was to support responsive coordinates eventually but that probably isn't
very useful or straightforward to implement. And even if we do want to
support responsive coords in the future, it can newtype `Val2`.

## Solution

Change `ScrollPosition` to newtype `Vec2`. 

Also added some extra details to the doc comments.

## Testing

Try the `scroll` example.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2025-07-01 17:41:48 +00:00
Talin
b980d4ac22
Feathers checkbox (#19900)
Adds checkbox and radio buttons to feathers.

Showcase:

<img width="378" alt="feathers-checkbox-radio"
src="https://github.com/user-attachments/assets/76d35589-6400-49dd-bf98-aeca2f39a472"
/>
2025-07-01 06:59:14 +00:00
JMS55
8351da45f8
Solari: Merge reservoir file, reformulate confidence weight (#19895)
Some misc cleanup in preparation for future PRs.

* Merge reservoir.wgsl with restir_di.wgsl, as the reservoir is going to
be DI-specific and won't be reused for GI
* Reformulate confidence weights to not multiply by INITIAL_SAMPLES. The
multiplication cancels out, it doesn't matter.
2025-07-01 04:17:16 +00:00
charlotte 🌸
6ad93ede86
Correctly disable prepass/shadows when configured on MaterialPlugin<M> (#19890)
Previously, the specialize/queue systems were added per-material and the
plugin prepass/shadow enable flags controlled whether we added those
systems. Now, we make this a property of the material instance and check
for it when specializing. Fixes
https://github.com/bevyengine/bevy/issues/19850.
2025-07-01 03:24:58 +00:00
andriyDev
e072625264
Move ExtractInstancesPlugin<EnvironmentMapIds> init to app. (#19867)
# Objective

- This plugin currently does nothing. That's because we add the plugin
to the `RenderApp`. Inside the plugin it then looks for the `RenderApp`
itself, but since it was added **to** the `RenderApp`, it will never
find the `RenderApp`.

## Solution

- Move the plugin into build, and more importantly, add it to the app
not the render_app.
2025-07-01 03:24:41 +00:00
Talin
7b6c5f4431
Change core widgets to use callback enum instead of option (#19855)
# Objective

Because we want to be able to support more notification options in the
future (in addition to just using registered one-shot systems), the
`Option<SystemId>` notifications have been changed to a new enum,
`Callback`.

@alice-i-cecile
2025-07-01 03:23:38 +00:00
SpecificProtagonist
c6ba3d31cf
EntityEvent derive: Fix silent error (#19894)
# Objective
The `EntityEvent` derive macro only parsed the first `entity_event`
attr, resulting in the following event having auto propagation silently
turned off:
```rust
#[derive(Event, EntityEvent)]
#[entity_event(traversal = &'static ChildOf)]
#[entity_event(auto_propagate)]
struct MyEvent;
```

This should either fail to compile or be parsed correctly.

## Solution

Parse all `entity_event`.

## Testing

Cargo expand the snippet above. I haven't added an extra test for this.
2025-07-01 03:20:54 +00:00
Emerson Coskey
bdd3ef71b8
Composable Pipeline Specialization (#17373)
Currently, our specialization API works through a series of wrapper
structs and traits, which make things confusing to follow and difficult
to generalize.

This pr takes a different approach, where "specializers" (types that
implement `Specialize`) are composable, but "flat" rather than composed
of a series of wrappers. The key is that specializers don't *produce*
pipeline descriptors, but instead *modify* existing ones:

```rs
pub trait Specialize<T: Specializable> {
    type Key: SpecializeKey;
    
    fn specialize(
        &self, 
        key: Self::Key, 
        descriptor: &mut T::Descriptor
    ) -> Result<Canonical<Self::Key>, BevyError>;
}
```

This lets us use some derive magic to stick multiple specializers
together:

```rs
pub struct A;
pub struct B;

impl Specialize<RenderPipeline> for A { ... }
impl Specialize<RenderPipeline> for A { ... }

#[derive(Specialize)]
#[specialize(RenderPipeline)]
struct C {
    // specialization is applied in struct field order
    applied_first: A,
    applied_second: B,
}

type C::Key = (A::Key, B::Key);

```

This approach is much easier to understand, IMO, and also lets us
separate concerns better. Specializers can be placed in fully separate
crates/modules, and key computation can be shared as well.

The only real breaking change here is that since specializers only
modify descriptors, we need a "base" descriptor to work off of. This can
either be manually supplied when constructing a `Specializer` (the new
collection replacing `Specialized[Render/Compute]Pipelines`), or
supplied by implementing `HasBaseDescriptor` on a specializer. See
`examples/shader/custom_phase_item.rs` for an example implementation.

## Testing

- Did some simple manual testing of the derive macro, it seems robust.

---

## Showcase

```rs
#[derive(Specialize, HasBaseDescriptor)]
#[specialize(RenderPipeline)]
pub struct SpecializeMeshMaterial<M: Material> {
    // set mesh bind group layout and shader defs
    mesh: SpecializeMesh,
    // set view bind group layout and shader defs
    view: SpecializeView,
    // since type SpecializeMaterial::Key = (), 
    // we can hide it from the wrapper's external API
    #[key(default)]
    // defer to the GetBaseDescriptor impl of SpecializeMaterial, 
    // since it carries the vertex and fragment handles
    #[base_descriptor]
    // set material bind group layout, etc
    material: SpecializeMaterial<M>,
}

// implementation generated by the derive macro
impl <M: Material> Specialize<RenderPipeline> for SpecializeMeshMaterial<M> {
    type Key = (MeshKey, ViewKey);

    fn specialize(
        &self, 
        key: Self::Key, 
        descriptor: &mut RenderPipelineDescriptor
    ) -> Result<Canonical<Self::Key>, BevyError>  {
        let mesh_key = self.mesh.specialize(key.0, descriptor)?;
        let view_key = self.view.specialize(key.1, descriptor)?;
        let _ = self.material.specialize((), descriptor)?;
        Ok((mesh_key, view_key));
    }
}

impl <M: Material> HasBaseDescriptor<RenderPipeline> for SpecializeMeshMaterial<M> {
    fn base_descriptor(&self) -> RenderPipelineDescriptor {
        self.material.base_descriptor()
    }
}
```

---------

Co-authored-by: Tim Overbeek <158390905+Bleachfuel@users.noreply.github.com>
2025-07-01 01:32:44 +00:00
IceSentry
f98727c1b1
Use RenderStartup in MaterialPlugin (#19885)
# Objective

- The MaterialPlugin has some ugly code to initialize some data in the
render world
- #19887

## Solution

- Use the new RenderStartup schedule to use a system instead of using
the plugin `finish()`

## Testing

- Tested that the 3d_scene and shader_material example still work as
expected
2025-06-30 23:54:13 +00:00
IceSentry
735eb88db9
Use RenderStartup in custom_post_processing example (#19886)
# Objective

- This example uses a FromWorld impl to initialize a resource on startup
- #19887

## Solution

- Use RenderStartup instead

## Testing

- The example still works as expected
2025-06-30 23:54:05 +00:00
dependabot[bot]
83cd46a4dd
Update criterion requirement from 0.5.1 to 0.6.0 (#19879)
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>
2025-06-30 23:41:47 +00:00
dependabot[bot]
265fefb865
Bump cargo-bins/cargo-binstall from 1.12.5 to 1.14.1 (#19877)
Bumps
[cargo-bins/cargo-binstall](https://github.com/cargo-bins/cargo-binstall)
from 1.12.5 to 1.14.1.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/cargo-bins/cargo-binstall/releases">cargo-bins/cargo-binstall's
releases</a>.</em></p>
<blockquote>
<h2>v1.14.1</h2>
<p><em>Binstall is a tool to fetch and install Rust-based executables as
binaries. It aims to be a drop-in replacement for <code>cargo
install</code> in most cases. Install it today with <code>cargo install
cargo-binstall</code>, from the binaries below, or if you already have
it, upgrade with <code>cargo binstall cargo-binstall</code>.</em></p>
<h4>In this release:</h4>
<ul>
<li>Upgrade dependencies</li>
</ul>
<h2>v1.14.0</h2>
<p><em>Binstall is a tool to fetch and install Rust-based executables as
binaries. It aims to be a drop-in replacement for <code>cargo
install</code> in most cases. Install it today with <code>cargo install
cargo-binstall</code>, from the binaries below, or if you already have
it, upgrade with <code>cargo binstall cargo-binstall</code>.</em></p>
<h4>In this release:</h4>
<ul>
<li>Fix glibc detection on arm Fedora (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2205">#2205</a>)</li>
<li>Add support for repository host Codeberg (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2202">#2202</a>)</li>
<li>Fix error for missing binaries when <code>--bin</code> does not
include any of these missing bins (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/1888">#1888</a>
<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2199">#2199</a>)</li>
</ul>
<h4>Other changes:</h4>
<ul>
<li>Rm uninstalled crates from
<code>$CARGO_HOME/binstall/crates-v1.json</code> (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2197">#2197</a>)</li>
<li>Upgrade dependencies</li>
</ul>
<h2>v1.13.0</h2>
<p><em>Binstall is a tool to fetch and install Rust-based executables as
binaries. It aims to be a drop-in replacement for <code>cargo
install</code> in most cases. Install it today with <code>cargo install
cargo-binstall</code>, from the binaries below, or if you already have
it, upgrade with <code>cargo binstall cargo-binstall</code>.</em></p>
<h4>In this release:</h4>
<ul>
<li>Add a <code>--bin</code> argument to mirror cargo install
<code>--bin</code> (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/1961">#1961</a>
<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2189">#2189</a>)</li>
</ul>
<h4>Other changes:</h4>
<ul>
<li>Upgrade dependencies</li>
</ul>
<h2>v1.12.7</h2>
<p><em>Binstall is a tool to fetch and install Rust-based executables as
binaries. It aims to be a drop-in replacement for <code>cargo
install</code> in most cases. Install it today with <code>cargo install
cargo-binstall</code>, from the binaries below, or if you already have
it, upgrade with <code>cargo binstall cargo-binstall</code>.</em></p>
<h4>In this release:</h4>
<ul>
<li>Fix updating installed crates manifest for custom registry (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2175">#2175</a>
<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2178">#2178</a>)</li>
</ul>
<h4>Other changes:</h4>
<ul>
<li>Upgrade transitive dependencies</li>
<li>Ensure build script always waits for threads created (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2185">#2185</a>)</li>
<li>optimization</li>
</ul>
<h2>v1.12.6</h2>
<p><em>Binstall is a tool to fetch and install Rust-based executables as
binaries. It aims to be a drop-in replacement for <code>cargo
install</code> in most cases. Install it today with <code>cargo install
cargo-binstall</code>, from the binaries below, or if you already have
it, upgrade with <code>cargo binstall cargo-binstall</code>.</em></p>
<h4>In this release:</h4>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="8aac5aa2bf"><code>8aac5aa</code></a>
release: cargo-binstall v1.14.1 (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2211">#2211</a>)</li>
<li><a
href="e5b77406bb"><code>e5b7740</code></a>
chore: release (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2210">#2210</a>)</li>
<li><a
href="fe1c5ab94f"><code>fe1c5ab</code></a>
dep: Upgrade transitive dependencies (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2209">#2209</a>)</li>
<li><a
href="151e1ec8c4"><code>151e1ec</code></a>
ci: enable cache-workspace-crates (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2208">#2208</a>)</li>
<li><a
href="abb695a276"><code>abb695a</code></a>
build(deps): bump tj-actions/changed-files from
4140eb99d2cced9bfd78375c20883...</li>
<li><a
href="a1ca1a46ab"><code>a1ca1a4</code></a>
dep: Replace vergen with vergen-gitcl (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2207">#2207</a>)</li>
<li><a
href="f317ddf23a"><code>f317ddf</code></a>
release: cargo-binstall v1.14.0 (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2206">#2206</a>)</li>
<li><a
href="d47e67b010"><code>d47e67b</code></a>
chore: release (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2195">#2195</a>)</li>
<li><a
href="bb9211b72c"><code>bb9211b</code></a>
Fix glibc detection on Fedora (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2205">#2205</a>)</li>
<li><a
href="a90dd4569f"><code>a90dd45</code></a>
feat: Add repository host Codeberg (<a
href="https://redirect.github.com/cargo-bins/cargo-binstall/issues/2202">#2202</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/cargo-bins/cargo-binstall/compare/v1.12.5...v1.14.1">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=cargo-bins/cargo-binstall&package-manager=github_actions&previous-version=1.12.5&new-version=1.14.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

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>
Co-authored-by: François Mockers <francois.mockers@vleue.com>
2025-06-30 23:37:59 +00:00
Nicholas Nethercote
c7e28852cb
bevy_reflect: avoid duplicate type bounds in derived methods (#19876)
# Objective

Most of the impls derived for `#[derive(Reflect)]` have one set of type
bounds per field, like so:
```
        f32: ::bevy::reflect::FromReflect
            + ::bevy::reflect::TypePath
            + ::bevy::reflect::MaybeTyped
            + ::bevy::reflect::__macro_exports::RegisterForReflection,
```
If multiple fields have the same type, the bounds are repeated
uselessly. This can only hurt compile time and clogs up the `cargo
expand` output.

Avoiding this will help with
https://github.com/bevyengine/bevy/issues/19873.

## Solution

Use a hashset when collecting the bounds to eliminate duplicates.

## Testing

I used cargo expand to confirm the duplicate bounds are no longer
produced.

`-Zmacro-stats` outputs tells me this reduces the size of the `Reflect`
code produced for `bevy_ui` from 1_544_696 bytes to 1_467_967 bytes, a
5% drop.
2025-06-30 23:29:26 +00:00
Nicholas Nethercote
5aa520eac0
bevy_reflect: avoid useless with_{custom_attributes,docs} calls (#19875)
# Objective

`#[derive(Reflect)]` derives `Typed` impls whose `type_info` methods
contain useless calls to `with_custom_attributes` and `with_docs`, e.g.:
```
::bevy::reflect::NamedField:🆕:<f32>("x")
    .with_custom_attributes(
        ::bevy::reflect::attributes::CustomAttributes::default()
    )
    .with_docs(::core::option::Option::None),
```
This hurts compile times and makes the `cargo expand` output harder to
read. It might also hurt runtime speed, depending on whether the
compiler can optimize away the no-op methods.

Avoiding this will help with #19873.

## Solution

Check if the attributes/docs are empty before appending the method
calls.

## Testing

I used `cargo expand` to confirm the useless calls are no longer
produced.

`-Zmacro-stats` outputs tells me this reduces the size of the `Reflect`
impls produced for `bevy_ui` from 1_544_696 bytes to 1_511_214 bytes, a
2.2% drop. Only a small improvement, but it's a start.
2025-06-30 23:29:24 +00:00
Maxime Mulder
55c7766716
Update bevy website link in newer code (#19874)
# Objective

I was lurking and noticed that some links to the Bevy website were not
updated in newer code (`bevyengine.org` -> `bevy.org`).

## Solution

- Look for `bevyengine.org` occurrences in the current code, replace
them with `bevy.org`.

## Testing

- Did you test these changes? If so, how? I visited the Bevy website!
- Are there any parts that need more testing?
- How can other people (reviewers) test your changes? Is there anything
specific they need to know?
- If relevant, what platforms did you test these changes on, and are
there any important ones you can't test?

## Longer term

- Maybe add a lint to flag references to the old website but I don't
know how to do that. But not sure it's needed as the more time will pass
the less it will be relevant.
2025-06-30 23:24:36 +00:00
IceSentry
88c280b9d2
Split LatePrepassNode query in a few groups (#19840)
# Objective

- That node has a bunch of query items that are mostly ignored in a few
places
- Previously this lead to having a long chain of ignored params that was
replaced with `..,`. This works, but this seems a bit more likely to
break in a subtle way if new parameters are added

## Solution

- Split the query in a few groups based on how it was already structured
(Mandatory, Optional, Has<T>)

## Testing

- None, it's just code style changes
2025-06-30 23:08:27 +00:00
Talin
9be1c36391
CoreScrollbar widget. (#19803)
# Objective

Part of #19236 


## Demo


![image](https://github.com/user-attachments/assets/8607f672-de8f-4339-bdfc-817b39f32e3e)


https://discord.com/channels/691052431525675048/743663673393938453/1387110701386039317

---------

Co-authored-by: ickshonpe <david.curthoys@googlemail.com>
2025-06-30 23:02:03 +00:00
krunchington
70902413b2
Update log_layers_ecs example for children macro (#18293)
# Objective

Contributes to #18238 
Updates the `log_layers_ecs`, example to use the `children!` macro.

Note that I did not use a macro, nor `Children::spawn` for the outer
layer. Since the `EventReader` is borrowed mutably, any `.map` I did on
`events.read()` was going to have the reference outlive the function
body. I believe this scope of change is correct for the PR.

## Solution

Updates examples to use the Improved Spawning API merged in
https://github.com/bevyengine/bevy/pull/17521

## Testing

- Did you test these changes? If so, how?
- Opened the examples before and after and verified the same behavior
was observed. I did this on Ubuntu 24.04.2 LTS using `--features
wayland`.
- Are there any parts that need more testing?
- Other OS's and features can't hurt, but this is such a small change it
shouldn't be a problem.
- How can other people (reviewers) test your changes? Is there anything
specific they need to know?
  - Run the examples yourself with and without these changes.
- If relevant, what platforms did you test these changes on, and are
there any important ones you can't test?
  - see above

---

## Showcase

n/a

## Migration Guide

n/a

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2025-06-30 23:01:44 +00:00
Giacomo Stevanato
6367ad4c95
Add benchmarks for spawning and inserting bundles (#19762)
# Objective

- Splitted off from https://github.com/bevyengine/bevy/pull/19491
- Add some benchmarks for spawning and inserting components. Right now
these are pretty short, but it's expected that they will be extended
when different kinds of dynamic bundles will be implemented.
2025-06-30 22:50:39 +00:00
Jannik Obermann
83afcb5a2b
Fix ui picking outside the viewport (#19744)
# Objective

Fixes #19692 

## Solution

- Skip pointers outside the viewport.

## Testing

Tested with the following example:

<details>
<summary>Click to expand code</summary>

```rust
use bevy::{
    prelude::*, render:📷:Viewport, window::SystemCursorIcon, winit::cursor::CursorIcon,
};

fn main() -> AppExit {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .insert_resource(ClearColor(Color::BLACK))
        .run()
}

fn setup(mut commands: Commands, window: Single<&Window>) {
    //
    commands.spawn((
        Camera2d,
        Camera {
            clear_color: ClearColorConfig::Custom(Color::WHITE),
            viewport: Some(Viewport {
                physical_position: UVec2::new(
                    window.physical_width() / 4,
                    window.physical_height() / 4,
                ),
                physical_size: UVec2::new(
                    window.physical_width() / 2,
                    window.physical_height() / 2,
                ),
                ..default()
            }),
            ..default()
        },
    ));

    commands
        .spawn((
            Node {
                top: Val::Px(100.0),
                left: Val::Px(100.0),
                width: Val::Px(200.0),
                height: Val::Px(200.0),
                ..default()
            },
            BackgroundColor(Color::srgb(1.0, 0.0, 0.0)),
        ))
        .observe(|trigger: On<Pointer<Drag>>, mut node: Query<&mut Node>| {
            let mut node = node.get_mut(trigger.target()).unwrap();
            node.left = Val::Px(px(node.left) + trigger.delta.x);
            node.top = Val::Px(px(node.top) + trigger.delta.y);
        })
        .observe(
            |_: On<Pointer<DragStart>>,
             window: Single<Entity, With<Window>>,
             mut commands: Commands| {
                commands
                    .entity(*window)
                    .insert(CursorIcon::from(SystemCursorIcon::Grabbing));
            },
        )
        .observe(
            |_: On<Pointer<DragEnd>>,
             window: Single<Entity, With<Window>>,
             mut commands: Commands| {
                commands.entity(*window).remove::<CursorIcon>();
            },
        );
}

fn px(val: Val) -> f32 {
    match val {
        Val::Px(px) => px,
        _ => 0.0,
    }
}
```
</details>

## Additional information

This is at least also broken on the sprite picking backend. I guess the
fix for other backends are also trivial if this is correct.
(Sprite picking: #19747)
2025-06-30 22:46:56 +00:00
Jannik Obermann
169254b938
Fix sprite picking viewport (#19747)
# Objective

Fixes sprite picking when using a viewport. Related to #19744.

## Solution

- Do not substract `viewport.min` as `Camera::viewport_to_world` already
does that.
- Skip pointers outside the viewport.

## Testing

Tested with the following example:

<details>
<summary>Click to expand code</summary>

```rust
use bevy::{
    prelude::*, render:📷:Viewport, window::SystemCursorIcon, winit::cursor::CursorIcon,
};

fn main() -> AppExit {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .insert_resource(ClearColor(Color::BLACK))
        .run()
}

fn setup(mut commands: Commands, window: Single<&Window>) {
    commands.spawn((
        Camera2d,
        Camera {
            clear_color: ClearColorConfig::Custom(Color::WHITE),
            viewport: Some(Viewport {
                physical_position: UVec2::new(
                    window.physical_width() / 4,
                    window.physical_height() / 4,
                ),
                physical_size: UVec2::new(
                    window.physical_width() / 2,
                    window.physical_height() / 2,
                ),
                ..default()
            }),
            ..default()
        },
    ));

    commands
        .spawn((
            Transform::from_xyz(100.0, 100.0, 0.0),
            Sprite::from_color(Color::srgb(0.0, 1.0, 0.0), Vec2::new(200.0, 200.0)),
            Pickable::default(),
        ))
        .observe(
            |trigger: On<Pointer<Drag>>, mut transform: Query<&mut Transform>| {
                let mut transform = transform.get_mut(trigger.target()).unwrap();
                transform.translation.x += trigger.delta.x;
                transform.translation.y -= trigger.delta.y;
            },
        )
        .observe(
            |_: On<Pointer<DragStart>>,
             window: Single<Entity, With<Window>>,
             mut commands: Commands| {
                commands
                    .entity(*window)
                    .insert(CursorIcon::from(SystemCursorIcon::Grabbing));
            },
        )
        .observe(
            |_: On<Pointer<DragEnd>>,
             window: Single<Entity, With<Window>>,
             mut commands: Commands| {
                commands.entity(*window).remove::<CursorIcon>();
            },
        );
}
```
</details>
2025-06-30 22:46:44 +00:00