Skip to content

Commit

Permalink
Use impl Into<A> for Assets::add (#10878)
Browse files Browse the repository at this point in the history
# Motivation

When spawning entities into a scene, it is very common to create assets
like meshes and materials and to add them via asset handles. A common
setup might look like this:

```rust
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    commands.spawn(PbrBundle {
        mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
        material: materials.add(StandardMaterial::from(Color::RED)),
        ..default()
    });
}
```

Let's take a closer look at the part that adds the assets using `add`.

```rust
mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
material: materials.add(StandardMaterial::from(Color::RED)),
```

Here, "mesh" and "material" are both repeated three times. It's very
explicit, but I find it to be a bit verbose. In addition to being more
code to read and write, the extra characters can sometimes also lead to
the code being formatted to span multiple lines even though the core
task, adding e.g. a primitive mesh, is extremely simple.

A way to address this is by using `.into()`:

```rust
mesh: meshes.add(shape::Cube { size: 1.0 }.into()),
material: materials.add(Color::RED.into()),
```

This is fine, but from the names and the type of `meshes`, we already
know what the type should be. It's very clear that `Cube` should be
turned into a `Mesh` because of the context it's used in. `.into()` is
just seven characters, but it's so common that it quickly adds up and
gets annoying.

It would be nice if you could skip all of the conversion and let Bevy
handle it for you:

```rust
mesh: meshes.add(shape::Cube { size: 1.0 }),
material: materials.add(Color::RED),
```

# Objective

Make adding assets more ergonomic by making `Assets::add` take an `impl
Into<A>` instead of `A`.

## Solution

`Assets::add` now takes an `impl Into<A>` instead of `A`, so e.g. this
works:

```rust
    commands.spawn(PbrBundle {
        mesh: meshes.add(shape::Cube { size: 1.0 }),
        material: materials.add(Color::RED),
        ..default()
    });
```

I also changed all examples to use this API, which increases consistency
as well because `Mesh::from` and `into` were being used arbitrarily even
in the same file. This also gets rid of some lines of code because
formatting is nicer.

---

## Changelog

- `Assets::add` now takes an `impl Into<A>` instead of `A`
- Examples don't use `T::from(K)` or `K.into()` when adding assets

## Migration Guide

Some `into` calls that worked previously might now be broken because of
the new trait bounds. You need to either remove `into` or perform the
conversion explicitly with `from`:

```rust
// Doesn't compile
let mesh_handle = meshes.add(shape::Cube { size: 1.0 }.into()),

// These compile
let mesh_handle = meshes.add(shape::Cube { size: 1.0 }),
let mesh_handle = meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
```

## Concerns

I believe the primary concerns might be:

1. Is this too implicit?
2. Does this increase codegen bloat?

Previously, the two APIs were using `into` or `from`, and now it's
"nothing" or `from`. You could argue that `into` is slightly more
explicit than "nothing" in cases like the earlier examples where a
`Color` gets converted to e.g. a `StandardMaterial`, but I personally
don't think `into` adds much value even in this case, and you could
still see the actual type from the asset type.

As for codegen bloat, I doubt it adds that much, but I'm not very
familiar with the details of codegen. I personally value the user-facing
code reduction and ergonomics improvements that these changes would
provide, but it might be worth checking the other effects in more
detail.

Another slight concern is migration pain; apps might have a ton of
`into` calls that would need to be removed, and it did take me a while
to do so for Bevy itself (maybe around 20-40 minutes). However, I think
the fact that there *are* so many `into` calls just highlights that the
API could be made nicer, and I'd gladly migrate my own projects for it.
  • Loading branch information
Jondolf committed Jan 8, 2024
1 parent 54a943d commit a795de3
Show file tree
Hide file tree
Showing 69 changed files with 247 additions and 268 deletions.
4 changes: 2 additions & 2 deletions crates/bevy_asset/src/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -361,9 +361,9 @@ impl<A: Asset> Assets<A> {

/// Adds the given `asset` and allocates a new strong [`Handle`] for it.
#[inline]
pub fn add(&mut self, asset: A) -> Handle<A> {
pub fn add(&mut self, asset: impl Into<A>) -> Handle<A> {
let index = self.dense_storage.allocator.reserve();
self.insert_with_index(index, asset).unwrap();
self.insert_with_index(index, asset.into()).unwrap();
Handle::Strong(
self.handle_provider
.get_handle(index.into(), false, None, None),
Expand Down
8 changes: 4 additions & 4 deletions errors/B0004.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ fn setup_cube(
.with_children(|parent| {
// cube
parent.spawn(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
material: materials.add(Color::rgb(0.8, 0.7, 0.6).into()),
mesh: meshes.add(shape::Cube { size: 1.0 }),
material: materials.add(Color::rgb(0.8, 0.7, 0.6)),
transform: Transform::from_xyz(0.0, 0.5, 0.0),
..default()
});
Expand Down Expand Up @@ -80,8 +80,8 @@ fn setup_cube(
.with_children(|parent| {
// cube
parent.spawn(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
material: materials.add(Color::rgb(0.8, 0.7, 0.6).into()),
mesh: meshes.add(shape::Cube { size: 1.0 }),
material: materials.add(Color::rgb(0.8, 0.7, 0.6)),
transform: Transform::from_xyz(0.0, 0.5, 0.0),
..default()
});
Expand Down
8 changes: 3 additions & 5 deletions examples/2d/2d_shapes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ fn setup(

// Circle
commands.spawn(MaterialMesh2dBundle {
mesh: meshes.add(shape::Circle::new(50.).into()).into(),
mesh: meshes.add(shape::Circle::new(50.)).into(),
material: materials.add(ColorMaterial::from(Color::PURPLE)),
transform: Transform::from_translation(Vec3::new(-150., 0., 0.)),
..default()
Expand All @@ -37,17 +37,15 @@ fn setup(

// Quad
commands.spawn(MaterialMesh2dBundle {
mesh: meshes
.add(shape::Quad::new(Vec2::new(50., 100.)).into())
.into(),
mesh: meshes.add(shape::Quad::new(Vec2::new(50., 100.))).into(),
material: materials.add(ColorMaterial::from(Color::LIME_GREEN)),
transform: Transform::from_translation(Vec3::new(50., 0., 0.)),
..default()
});

// Hexagon
commands.spawn(MaterialMesh2dBundle {
mesh: meshes.add(shape::RegularPolygon::new(50., 6).into()).into(),
mesh: meshes.add(shape::RegularPolygon::new(50., 6)).into(),
material: materials.add(ColorMaterial::from(Color::TURQUOISE)),
transform: Transform::from_translation(Vec3::new(150., 0., 0.)),
..default()
Expand Down
6 changes: 2 additions & 4 deletions examples/2d/bloom_2d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ fn setup(

// Circle mesh
commands.spawn(MaterialMesh2dBundle {
mesh: meshes.add(shape::Circle::new(100.).into()).into(),
mesh: meshes.add(shape::Circle::new(100.)).into(),
// 4. Put something bright in a dark environment to see the effect
material: materials.add(ColorMaterial::from(Color::rgb(7.5, 0.0, 7.5))),
transform: Transform::from_translation(Vec3::new(-200., 0., 0.)),
Expand All @@ -57,9 +57,7 @@ fn setup(

// Hexagon mesh
commands.spawn(MaterialMesh2dBundle {
mesh: meshes
.add(shape::RegularPolygon::new(100., 6).into())
.into(),
mesh: meshes.add(shape::RegularPolygon::new(100., 6)).into(),
// 4. Put something bright in a dark environment to see the effect
material: materials.add(ColorMaterial::from(Color::rgb(6.25, 9.4, 9.1))),
transform: Transform::from_translation(Vec3::new(200., 0., 0.)),
Expand Down
2 changes: 1 addition & 1 deletion examples/2d/mesh2d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ fn setup(
) {
commands.spawn(Camera2dBundle::default());
commands.spawn(MaterialMesh2dBundle {
mesh: meshes.add(Mesh::from(shape::Quad::default())).into(),
mesh: meshes.add(shape::Quad::default()).into(),
transform: Transform::default().with_scale(Vec3::splat(128.)),
material: materials.add(ColorMaterial::from(Color::PURPLE)),
..default()
Expand Down
8 changes: 4 additions & 4 deletions examples/3d/3d_gizmos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ fn setup(
});
// plane
commands.spawn(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Plane::from_size(5.0))),
material: materials.add(Color::rgb(0.3, 0.5, 0.3).into()),
mesh: meshes.add(shape::Plane::from_size(5.0)),
material: materials.add(Color::rgb(0.3, 0.5, 0.3)),
..default()
});
// cube
commands.spawn(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
material: materials.add(Color::rgb(0.8, 0.7, 0.6).into()),
mesh: meshes.add(shape::Cube { size: 1.0 }),
material: materials.add(Color::rgb(0.8, 0.7, 0.6)),
transform: Transform::from_xyz(0.0, 0.5, 0.0),
..default()
});
Expand Down
8 changes: 4 additions & 4 deletions examples/3d/3d_scene.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@ fn setup(
) {
// circular base
commands.spawn(PbrBundle {
mesh: meshes.add(shape::Circle::new(4.0).into()),
material: materials.add(Color::WHITE.into()),
mesh: meshes.add(shape::Circle::new(4.0)),
material: materials.add(Color::WHITE),
transform: Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
..default()
});
// cube
commands.spawn(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
material: materials.add(Color::rgb_u8(124, 144, 255).into()),
mesh: meshes.add(shape::Cube { size: 1.0 }),
material: materials.add(Color::rgb_u8(124, 144, 255)),
transform: Transform::from_xyz(0.0, 0.5, 0.0),
..default()
});
Expand Down
18 changes: 9 additions & 9 deletions examples/3d/3d_shapes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,13 @@ fn setup(
});

let shapes = [
meshes.add(shape::Cube::default().into()),
meshes.add(shape::Box::default().into()),
meshes.add(shape::Capsule::default().into()),
meshes.add(shape::Torus::default().into()),
meshes.add(shape::Cylinder::default().into()),
meshes.add(shape::Icosphere::default().try_into().unwrap()),
meshes.add(shape::UVSphere::default().into()),
meshes.add(shape::Cube::default()),
meshes.add(shape::Box::default()),
meshes.add(shape::Capsule::default()),
meshes.add(shape::Torus::default()),
meshes.add(shape::Cylinder::default()),
meshes.add(Mesh::try_from(shape::Icosphere::default()).unwrap()),
meshes.add(shape::UVSphere::default()),
];

let num_shapes = shapes.len();
Expand Down Expand Up @@ -78,8 +78,8 @@ fn setup(

// ground plane
commands.spawn(PbrBundle {
mesh: meshes.add(shape::Plane::from_size(50.0).into()),
material: materials.add(Color::SILVER.into()),
mesh: meshes.add(shape::Plane::from_size(50.0)),
material: materials.add(Color::SILVER),
..default()
});

Expand Down
4 changes: 2 additions & 2 deletions examples/3d/3d_viewport_to_world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ fn setup(
// plane
commands.spawn((
PbrBundle {
mesh: meshes.add(shape::Plane::from_size(20.).into()),
material: materials.add(Color::rgb(0.3, 0.5, 0.3).into()),
mesh: meshes.add(shape::Plane::from_size(20.)),
material: materials.add(Color::rgb(0.3, 0.5, 0.3)),
..default()
},
Ground,
Expand Down
6 changes: 3 additions & 3 deletions examples/3d/anti_aliasing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,8 +260,8 @@ fn setup(
) {
// Plane
commands.spawn(PbrBundle {
mesh: meshes.add(shape::Plane::from_size(50.0).into()),
material: materials.add(Color::rgb(0.1, 0.2, 0.1).into()),
mesh: meshes.add(shape::Plane::from_size(50.0)),
material: materials.add(Color::rgb(0.1, 0.2, 0.1)),
..default()
});

Expand All @@ -273,7 +273,7 @@ fn setup(
// Cubes
for i in 0..5 {
commands.spawn(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Cube { size: 0.25 })),
mesh: meshes.add(shape::Cube { size: 0.25 }),
material: cube_material.clone(),
transform: Transform::from_xyz(i as f32 * 0.25 - 1.0, 0.125, -i as f32 * 0.5),
..default()
Expand Down
2 changes: 1 addition & 1 deletion examples/3d/atmospheric_fog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ fn setup_terrain_scene(
// Sky
commands.spawn((
PbrBundle {
mesh: meshes.add(Mesh::from(shape::Box::default())),
mesh: meshes.add(shape::Box::default()),
material: materials.add(StandardMaterial {
base_color: Color::hex("888888").unwrap(),
unlit: true,
Expand Down
6 changes: 3 additions & 3 deletions examples/3d/blend_modes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,10 @@ fn setup(
.id();

// Chessboard Plane
let black_material = materials.add(Color::BLACK.into());
let white_material = materials.add(Color::WHITE.into());
let black_material = materials.add(Color::BLACK);
let white_material = materials.add(Color::WHITE);

let plane_mesh = meshes.add(shape::Plane::from_size(2.0).into());
let plane_mesh = meshes.add(shape::Plane::from_size(2.0));

for x in -3..4 {
for z in -3..4 {
Expand Down
5 changes: 2 additions & 3 deletions examples/3d/bloom_3d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,10 @@ fn setup_scene(
});

let mesh = meshes.add(
shape::Icosphere {
Mesh::try_from(shape::Icosphere {
radius: 0.5,
subdivisions: 5,
}
.try_into()
})
.unwrap(),
);

Expand Down
10 changes: 5 additions & 5 deletions examples/3d/deferred_rendering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,16 +103,16 @@ fn setup(

// Plane
commands.spawn(PbrBundle {
mesh: meshes.add(shape::Plane::from_size(50.0).into()),
mesh: meshes.add(shape::Plane::from_size(50.0)),
material: forward_mat_h.clone(),
..default()
});

let cube_h = meshes.add(Mesh::from(shape::Cube { size: 0.1 }));
let sphere_h = meshes.add(Mesh::from(shape::UVSphere {
let cube_h = meshes.add(shape::Cube { size: 0.1 });
let sphere_h = meshes.add(shape::UVSphere {
radius: 0.125,
..default()
}));
});

// Cubes
commands.spawn(PbrBundle {
Expand Down Expand Up @@ -196,7 +196,7 @@ fn setup(
// sky
commands.spawn((
PbrBundle {
mesh: meshes.add(Mesh::from(shape::Box::default())),
mesh: meshes.add(shape::Box::default()),
material: materials.add(StandardMaterial {
base_color: Color::hex("888888").unwrap(),
unlit: true,
Expand Down
10 changes: 5 additions & 5 deletions examples/3d/fog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,14 @@ fn setup_pyramid_scene(
// pillars
for (x, z) in &[(-1.5, -1.5), (1.5, -1.5), (1.5, 1.5), (-1.5, 1.5)] {
commands.spawn(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Box {
mesh: meshes.add(shape::Box {
min_x: -0.5,
max_x: 0.5,
min_z: -0.5,
max_z: 0.5,
min_y: 0.0,
max_y: 3.0,
})),
}),
material: stone.clone(),
transform: Transform::from_xyz(*x, 0.0, *z),
..default()
Expand Down Expand Up @@ -97,14 +97,14 @@ fn setup_pyramid_scene(
let size = i as f32 / 2.0 + 3.0;
let y = -i as f32 / 2.0;
commands.spawn(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Box {
mesh: meshes.add(shape::Box {
min_x: -size,
max_x: size,
min_z: -size,
max_z: size,
min_y: 0.0,
max_y: 0.5,
})),
}),
material: stone.clone(),
transform: Transform::from_xyz(0.0, y, 0.0),
..default()
Expand All @@ -113,7 +113,7 @@ fn setup_pyramid_scene(

// sky
commands.spawn(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Box::default())),
mesh: meshes.add(shape::Box::default()),
material: materials.add(StandardMaterial {
base_color: Color::hex("888888").unwrap(),
unlit: true,
Expand Down
Loading

0 comments on commit a795de3

Please sign in to comment.