From fff400d2cdd5ee7082f71a303aed6d555062d398 Mon Sep 17 00:00:00 2001 From: Rich Churcher Date: Thu, 19 Sep 2024 16:09:06 +1200 Subject: [PATCH 01/12] Add (better) example for handle/asset manipulation --- Cargo.toml | 22 ++++++ examples/asset/alter_mesh.rs | 109 ++++++++++++++++++++++++++ examples/asset/alter_sprite.rs | 137 +++++++++++++++++++++++++++++++++ 3 files changed, 268 insertions(+) create mode 100644 examples/asset/alter_mesh.rs create mode 100644 examples/asset/alter_sprite.rs diff --git a/Cargo.toml b/Cargo.toml index 0d6a58c11803c..794d89b3dba47 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1354,6 +1354,28 @@ category = "Application" wasm = false # Assets +[[example]] +name = "alter_mesh" +path = "examples/asset/alter_mesh.rs" +doc-scrape-examples = true + +[package.metadata.example.alter_mesh] +name = "Alter Mesh" +description = "Shows how to modify the underlying asset of a Mesh after spawning." +category = "Assets" +wasm = false + +[[example]] +name = "alter_sprite" +path = "examples/asset/alter_sprite.rs" +doc-scrape-examples = true + +[package.metadata.example.alter_sprite] +name = "Alter Sprite" +description = "Shows how to modify texture assets after spawning." +category = "Assets" +wasm = false + [[example]] name = "asset_loading" path = "examples/asset/asset_loading.rs" diff --git a/examples/asset/alter_mesh.rs b/examples/asset/alter_mesh.rs new file mode 100644 index 0000000000000..f30342a124ba5 --- /dev/null +++ b/examples/asset/alter_mesh.rs @@ -0,0 +1,109 @@ +//! PLACEHOLDER + +use bevy::{asset::LoadedFolder, prelude::*}; + +fn main() { + App::new() + .add_plugins(DefaultPlugins) + .add_systems(Startup, setup) + .run(); +} + +fn setup( + mut commands: Commands, + asset_server: Res, + meshes: Res>, + mut materials: ResMut>, +) { + // By default AssetServer will load assets from inside the "assets" folder. + // For example, the next line will load GltfAssetLabel::Primitive{mesh:0,primitive:0}.from_asset("ROOT/assets/models/cube/cube.gltf"), + // where "ROOT" is the directory of the Application. + // + // This can be overridden by setting the "CARGO_MANIFEST_DIR" environment variable (see + // https://doc.rust-lang.org/cargo/reference/environment-variables.html) + // to another directory. When the Application is run through Cargo, "CARGO_MANIFEST_DIR" is + // automatically set to your crate (workspace) root directory. + let cube_handle = asset_server.load( + GltfAssetLabel::Primitive { + mesh: 0, + primitive: 0, + } + .from_asset("models/cube/cube.gltf"), + ); + let sphere_handle = asset_server.load( + GltfAssetLabel::Primitive { + mesh: 0, + primitive: 0, + } + .from_asset("models/sphere/sphere.gltf"), + ); + + // All assets end up in their Assets collection once they are done loading: + if let Some(sphere) = meshes.get(&sphere_handle) { + // You might notice that this doesn't run! This is because assets load in parallel without + // blocking. When an asset has loaded, it will appear in relevant Assets + // collection. + info!("{:?}", sphere.primitive_topology()); + } else { + info!("sphere hasn't loaded yet"); + } + + // You can load all assets in a folder like this. They will be loaded in parallel without + // blocking. The LoadedFolder asset holds handles to each asset in the folder. These are all + // dependencies of the LoadedFolder asset, meaning you can wait for the LoadedFolder asset to + // fire AssetEvent::LoadedWithDependencies if you want to wait for all assets in the folder + // to load. + // If you want to keep the assets in the folder alive, make sure you store the returned handle + // somewhere. + let _loaded_folder: Handle = asset_server.load_folder("models/torus"); + + // If you want a handle to a specific asset in a loaded folder, the easiest way to get one is to call load. + // It will _not_ be loaded a second time. + // The LoadedFolder asset will ultimately also hold handles to the assets, but waiting for it to load + // and finding the right handle is more work! + let torus_handle = asset_server.load( + GltfAssetLabel::Primitive { + mesh: 0, + primitive: 0, + } + .from_asset("models/torus/torus.gltf"), + ); + + // You can also add assets directly to their Assets storage: + let material_handle = materials.add(StandardMaterial { + base_color: Color::srgb(0.8, 0.7, 0.6), + ..default() + }); + + // torus + commands.spawn(PbrBundle { + mesh: torus_handle, + material: material_handle.clone(), + transform: Transform::from_xyz(-3.0, 0.0, 0.0), + ..default() + }); + // cube + commands.spawn(PbrBundle { + mesh: cube_handle, + material: material_handle.clone(), + transform: Transform::from_xyz(0.0, 0.0, 0.0), + ..default() + }); + // sphere + commands.spawn(PbrBundle { + mesh: sphere_handle, + material: material_handle, + transform: Transform::from_xyz(3.0, 0.0, 0.0), + ..default() + }); + // light + commands.spawn(PointLightBundle { + transform: Transform::from_xyz(4.0, 5.0, 4.0), + ..default() + }); + // camera + commands.spawn(Camera3dBundle { + transform: Transform::from_xyz(0.0, 3.0, 10.0).looking_at(Vec3::ZERO, Vec3::Y), + ..default() + }); +} diff --git a/examples/asset/alter_sprite.rs b/examples/asset/alter_sprite.rs new file mode 100644 index 0000000000000..14dd709ad104b --- /dev/null +++ b/examples/asset/alter_sprite.rs @@ -0,0 +1,137 @@ +//! Shows how to modify texture assets after spawning. + +use bevy::prelude::*; + +fn main() { + App::new() + .add_plugins(DefaultPlugins) + .add_systems(Startup, (setup, instructions)) + .add_systems(Update, keyboard_controls) + .run(); +} + +#[derive(Component, Debug)] +enum Bird { + Normal, + Logo, +} + +#[derive(Component, Debug)] +struct Left; + +impl Bird { + fn get_texture_path(&self) -> String { + match self { + Bird::Normal => "branding/bevy_bird_dark.png".into(), + Bird::Logo => "branding/bevy_logo_dark.png".into(), + } + } + + fn set_next_variant(&mut self) { + *self = match self { + Bird::Normal => Bird::Logo, + Bird::Logo => Bird::Normal, + } + } +} + +fn setup(mut commands: Commands, asset_server: Res) { + let bird_left = Bird::Normal; + let bird_right = Bird::Normal; + commands.spawn(Camera2dBundle::default()); + + commands.spawn(( + Name::new("Bird Left"), + // This marker component ensures we can easily find either of the Birds by using With and + // Without query filters. + Left, + SpriteBundle { + texture: asset_server.load(bird_left.get_texture_path()), + transform: Transform::from_xyz(-200.0, 0.0, 0.0), + ..default() + }, + bird_left, + )); + + commands.spawn(( + Name::new("Bird Right"), + SpriteBundle { + texture: asset_server.load(bird_right.get_texture_path()), + transform: Transform::from_xyz(200.0, 0.0, 0.0), + ..default() + }, + bird_right, + )); +} + +fn instructions(mut commands: Commands) { + commands + .spawn(( + Name::new("Instructions"), + NodeBundle { + style: Style { + align_items: AlignItems::Start, + flex_direction: FlexDirection::Column, + justify_content: JustifyContent::Start, + width: Val::Percent(100.), + ..default() + }, + ..default() + }, + )) + .with_children(|parent| { + parent.spawn(TextBundle::from_section( + "Space: swap image texture paths by mutating a Handle", + TextStyle::default(), + )); + parent.spawn(TextBundle::from_section( + "Return: mutate the image Asset itself, changing all copies of it", + TextStyle::default(), + )); + }); +} + +fn keyboard_controls( + asset_server: Res, + mut images: ResMut>, + left_bird: Query<&Handle, With>, + mut right_bird: Query<(&mut Bird, &mut Handle), Without>, + keyboard_input: Res>, +) { + if keyboard_input.just_pressed(KeyCode::Space) { + // Image handles, like other parts of the ECS, can be queried as mutable and modified at + // runtime. We only spawned one bird with the `Right` marker component. + let Ok((mut bird, mut handle)) = right_bird.get_single_mut() else { + return; + }; + + // Switch to a new Bird variant + bird.set_next_variant(); + + // Modify the handle associated with the Bird on the right side. Note that we will only + // have to load the same path from storage media once: repeated attempts will re-use the + // asset. + *handle = asset_server.load(bird.get_texture_path()); + } + + if keyboard_input.just_pressed(KeyCode::Enter) { + // It's convenient to retrieve the asset handle stored with the bird on the left. However, + // we could just as easily have retained this in a resource or a dedicated component. + let Ok(handle) = left_bird.get_single() else { + return; + }; + + // Obtain a mutable reference to the Image asset. + let Some(image) = images.get_mut(handle) else { + return; + }; + + for pixel in &mut image.data { + // Directly modify the asset data, which will affect all users of this asset. By + // contrast, mutating the handle (as we did above) affects only one copy. In this case, + // we'll just invert the colors, by way of demonstration. Notice that both uses of the + // asset show the change, not just the one on the left. + *pixel = 255 - *pixel; + } + } +} From 814242518b6ad85a67f20e91afd6895115b53b73 Mon Sep 17 00:00:00 2001 From: Rich Churcher Date: Thu, 19 Sep 2024 17:14:12 +1200 Subject: [PATCH 02/12] Add a mesh example. --- examples/asset/alter_mesh.rs | 251 ++++++++++++++++++++++----------- examples/asset/alter_sprite.rs | 8 +- 2 files changed, 175 insertions(+), 84 deletions(-) diff --git a/examples/asset/alter_mesh.rs b/examples/asset/alter_mesh.rs index f30342a124ba5..bdebd8d061e20 100644 --- a/examples/asset/alter_mesh.rs +++ b/examples/asset/alter_mesh.rs @@ -1,109 +1,200 @@ -//! PLACEHOLDER +//! Shows how to modify mesh assets after spawning. -use bevy::{asset::LoadedFolder, prelude::*}; +use bevy::prelude::*; +use bevy_render::mesh::VertexAttributeValues; fn main() { App::new() .add_plugins(DefaultPlugins) - .add_systems(Startup, setup) + .add_systems(Startup, (setup, instructions)) + .add_systems(Update, keyboard_controls) .run(); } +#[derive(Component, Debug)] +enum Shape { + Cube, + Sphere, +} + +impl Shape { + fn get_model_path(&self) -> String { + match self { + Shape::Cube => "models/cube/cube.gltf".into(), + Shape::Sphere => "models/sphere/sphere.gltf".into(), + } + } + + fn set_next_variant(&mut self) { + *self = match self { + Shape::Cube => Shape::Sphere, + Shape::Sphere => Shape::Cube, + } + } +} + +#[derive(Component, Debug)] +struct Left; + fn setup( mut commands: Commands, asset_server: Res, - meshes: Res>, mut materials: ResMut>, ) { - // By default AssetServer will load assets from inside the "assets" folder. - // For example, the next line will load GltfAssetLabel::Primitive{mesh:0,primitive:0}.from_asset("ROOT/assets/models/cube/cube.gltf"), - // where "ROOT" is the directory of the Application. - // - // This can be overridden by setting the "CARGO_MANIFEST_DIR" environment variable (see - // https://doc.rust-lang.org/cargo/reference/environment-variables.html) - // to another directory. When the Application is run through Cargo, "CARGO_MANIFEST_DIR" is - // automatically set to your crate (workspace) root directory. - let cube_handle = asset_server.load( - GltfAssetLabel::Primitive { - mesh: 0, - primitive: 0, - } - .from_asset("models/cube/cube.gltf"), - ); - let sphere_handle = asset_server.load( + let left_shape = Shape::Cube; + let right_shape = Shape::Cube; + + let left_shape_model = asset_server.load( GltfAssetLabel::Primitive { mesh: 0, primitive: 0, } - .from_asset("models/sphere/sphere.gltf"), + .from_asset(left_shape.get_model_path()), ); - - // All assets end up in their Assets collection once they are done loading: - if let Some(sphere) = meshes.get(&sphere_handle) { - // You might notice that this doesn't run! This is because assets load in parallel without - // blocking. When an asset has loaded, it will appear in relevant Assets - // collection. - info!("{:?}", sphere.primitive_topology()); - } else { - info!("sphere hasn't loaded yet"); - } - - // You can load all assets in a folder like this. They will be loaded in parallel without - // blocking. The LoadedFolder asset holds handles to each asset in the folder. These are all - // dependencies of the LoadedFolder asset, meaning you can wait for the LoadedFolder asset to - // fire AssetEvent::LoadedWithDependencies if you want to wait for all assets in the folder - // to load. - // If you want to keep the assets in the folder alive, make sure you store the returned handle - // somewhere. - let _loaded_folder: Handle = asset_server.load_folder("models/torus"); - - // If you want a handle to a specific asset in a loaded folder, the easiest way to get one is to call load. - // It will _not_ be loaded a second time. - // The LoadedFolder asset will ultimately also hold handles to the assets, but waiting for it to load - // and finding the right handle is more work! - let torus_handle = asset_server.load( + let right_shape_model = asset_server.load( GltfAssetLabel::Primitive { mesh: 0, primitive: 0, } - .from_asset("models/torus/torus.gltf"), + .from_asset(right_shape.get_model_path()), ); - // You can also add assets directly to their Assets storage: + // Add a material asset directly to the materials storage let material_handle = materials.add(StandardMaterial { - base_color: Color::srgb(0.8, 0.7, 0.6), + base_color: Color::srgb(0.6, 0.8, 0.6), ..default() }); - // torus - commands.spawn(PbrBundle { - mesh: torus_handle, - material: material_handle.clone(), - transform: Transform::from_xyz(-3.0, 0.0, 0.0), - ..default() - }); - // cube - commands.spawn(PbrBundle { - mesh: cube_handle, - material: material_handle.clone(), - transform: Transform::from_xyz(0.0, 0.0, 0.0), - ..default() - }); - // sphere - commands.spawn(PbrBundle { - mesh: sphere_handle, - material: material_handle, - transform: Transform::from_xyz(3.0, 0.0, 0.0), - ..default() - }); - // light - commands.spawn(PointLightBundle { - transform: Transform::from_xyz(4.0, 5.0, 4.0), - ..default() - }); - // camera - commands.spawn(Camera3dBundle { - transform: Transform::from_xyz(0.0, 3.0, 10.0).looking_at(Vec3::ZERO, Vec3::Y), - ..default() - }); + commands.spawn(( + Left, + Name::new("Left Shape"), + PbrBundle { + mesh: left_shape_model, + material: material_handle.clone(), + transform: Transform::from_xyz(-3.0, 0.0, 0.0), + ..default() + }, + left_shape, + )); + + commands.spawn(( + Name::new("Right Shape"), + PbrBundle { + mesh: right_shape_model, + material: material_handle, + transform: Transform::from_xyz(3.0, 0.0, 0.0), + ..default() + }, + right_shape, + )); + + commands.spawn(( + Name::new("Point Light"), + PointLightBundle { + transform: Transform::from_xyz(4.0, 5.0, 4.0), + ..default() + }, + )); + + commands.spawn(( + Name::new("Camera"), + Camera3dBundle { + transform: Transform::from_xyz(0.0, 3.0, 20.0).looking_at(Vec3::ZERO, Vec3::Y), + ..default() + }, + )); +} + +fn instructions(mut commands: Commands) { + commands + .spawn(( + Name::new("Instructions"), + NodeBundle { + style: Style { + align_items: AlignItems::Start, + flex_direction: FlexDirection::Column, + justify_content: JustifyContent::Start, + width: Val::Percent(100.), + ..default() + }, + ..default() + }, + )) + .with_children(|parent| { + parent.spawn(TextBundle::from_section( + "Space: swap meshes by mutating a Handle", + TextStyle::default(), + )); + parent.spawn(TextBundle::from_section( + "Return: mutate the mesh itself, changing all copies of it", + TextStyle::default(), + )); + }); +} + +#[derive(Default)] +struct IsMeshScaled(bool); + +fn keyboard_controls( + asset_server: Res, + mut is_mesh_scaled: Local, + mut meshes: ResMut>, + keyboard_input: Res>, + left_shape: Query<&Handle, With>, + mut right_shape: Query<(&mut Handle, &mut Shape), Without>, +) { + if keyboard_input.just_pressed(KeyCode::Space) { + // Mesh handles, like other parts of the ECS, can be queried as mutable and modified at + // runtime. We only spawned one shape without the `Left` marker component. + let Ok((mut handle, mut shape)) = right_shape.get_single_mut() else { + return; + }; + + // Switch to a new Shape variant + shape.set_next_variant(); + + // Modify the handle associated with the Shape on the right side. Note that we will only + // have to load the same path from storage media once: repeated attempts will re-use the + // asset. + *handle = asset_server.load( + GltfAssetLabel::Primitive { + mesh: 0, + primitive: 0, + } + .from_asset(shape.get_model_path()), + ); + } + + if keyboard_input.just_pressed(KeyCode::Enter) { + // It's convenient to retrieve the asset handle stored with the shape on the left. However, + // we could just as easily have retained this in a resource or a dedicated component. + let Ok(handle) = left_shape.get_single() else { + return; + }; + + // Obtain a mutable reference to the Mesh asset. + let Some(mesh) = meshes.get_mut(handle) else { + return; + }; + + // Now we can directly manipulate vertices on the mesh. Here, we're just scaling in and out + // for demonstration purposes. This will affect all entities currently using the asset. + if let Some(VertexAttributeValues::Float32x3(positions)) = + mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION) + { + // Check a Local value (which only this system can make use of) to determine if we're + // currently scaled up or not. + let scale_factor = if is_mesh_scaled.0 { 0.5 } else { 2.0 }; + + for position in positions.iter_mut() { + // Apply the scale factor to each of x, y, and z. + position[0] *= scale_factor; + position[1] *= scale_factor; + position[2] *= scale_factor; + } + + // Flip the local value to reverse the behaviour next time the key is pressed. + is_mesh_scaled.0 = !is_mesh_scaled.0; + } + } } diff --git a/examples/asset/alter_sprite.rs b/examples/asset/alter_sprite.rs index 14dd709ad104b..251568d566d1d 100644 --- a/examples/asset/alter_sprite.rs +++ b/examples/asset/alter_sprite.rs @@ -16,9 +16,6 @@ enum Bird { Logo, } -#[derive(Component, Debug)] -struct Left; - impl Bird { fn get_texture_path(&self) -> String { match self { @@ -35,6 +32,9 @@ impl Bird { } } +#[derive(Component, Debug)] +struct Left; + fn setup(mut commands: Commands, asset_server: Res) { let bird_left = Bird::Normal; let bird_right = Bird::Normal; @@ -100,7 +100,7 @@ fn keyboard_controls( ) { if keyboard_input.just_pressed(KeyCode::Space) { // Image handles, like other parts of the ECS, can be queried as mutable and modified at - // runtime. We only spawned one bird with the `Right` marker component. + // runtime. We only spawned one bird without the `Left` marker component. let Ok((mut bird, mut handle)) = right_bird.get_single_mut() else { return; }; From 40d679bd61c3d9a44fa4aa1b4fb94be885c6a643 Mon Sep 17 00:00:00 2001 From: Rich Churcher Date: Thu, 19 Sep 2024 18:20:48 +1200 Subject: [PATCH 03/12] Update docs --- examples/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/README.md b/examples/README.md index cd8c7edcccd22..fb03438de3c9e 100644 --- a/examples/README.md +++ b/examples/README.md @@ -219,6 +219,8 @@ Example | Description Example | Description --- | --- +[Alter Mesh](../examples/asset/alter_mesh.rs) | Shows how to modify the underlying asset of a Mesh after spawning. +[Alter Sprite](../examples/asset/alter_sprite.rs) | Shows how to modify texture assets after spawning. [Asset Decompression](../examples/asset/asset_decompression.rs) | Demonstrates loading a compressed asset [Asset Loading](../examples/asset/asset_loading.rs) | Demonstrates various methods to load assets [Asset Processing](../examples/asset/processing/asset_processing.rs) | Demonstrates how to process and load custom assets From 3399291c78b9ef39990ee04ab87cd05b8369c1a9 Mon Sep 17 00:00:00 2001 From: Rich Churcher Date: Fri, 20 Sep 2024 15:13:53 +1200 Subject: [PATCH 04/12] PR feedback --- examples/asset/alter_mesh.rs | 142 ++++++++++++++++++--------------- examples/asset/alter_sprite.rs | 86 ++++++++++---------- 2 files changed, 123 insertions(+), 105 deletions(-) diff --git a/examples/asset/alter_mesh.rs b/examples/asset/alter_mesh.rs index bdebd8d061e20..e793422c4db60 100644 --- a/examples/asset/alter_mesh.rs +++ b/examples/asset/alter_mesh.rs @@ -1,13 +1,20 @@ //! Shows how to modify mesh assets after spawning. -use bevy::prelude::*; +use bevy::{input::common_conditions::input_just_pressed, prelude::*}; use bevy_render::mesh::VertexAttributeValues; fn main() { App::new() .add_plugins(DefaultPlugins) - .add_systems(Startup, (setup, instructions)) - .add_systems(Update, keyboard_controls) + .add_systems(Startup, (setup, spawn_text)) + .add_systems( + Update, + alter_handle.run_if(input_just_pressed(KeyCode::Space)), + ) + .add_systems( + Update, + alter_mesh.run_if(input_just_pressed(KeyCode::Enter)), + ) .run(); } @@ -47,6 +54,12 @@ fn setup( let left_shape_model = asset_server.load( GltfAssetLabel::Primitive { mesh: 0, + // This field stores an index to this primitive in its parent mesh. In this case, we + // want the first one. You might also have seen the syntax: + // + // models/cube/cube.gltf#Scene0 + // + // which accomplishes the same thing. primitive: 0, } .from_asset(left_shape.get_model_path()), @@ -105,7 +118,7 @@ fn setup( )); } -fn instructions(mut commands: Commands) { +fn spawn_text(mut commands: Commands) { commands .spawn(( Name::new("Instructions"), @@ -132,69 +145,72 @@ fn instructions(mut commands: Commands) { }); } -#[derive(Default)] -struct IsMeshScaled(bool); - -fn keyboard_controls( +fn alter_handle( asset_server: Res, - mut is_mesh_scaled: Local, - mut meshes: ResMut>, - keyboard_input: Res>, - left_shape: Query<&Handle, With>, mut right_shape: Query<(&mut Handle, &mut Shape), Without>, ) { - if keyboard_input.just_pressed(KeyCode::Space) { - // Mesh handles, like other parts of the ECS, can be queried as mutable and modified at - // runtime. We only spawned one shape without the `Left` marker component. - let Ok((mut handle, mut shape)) = right_shape.get_single_mut() else { - return; - }; - - // Switch to a new Shape variant - shape.set_next_variant(); - - // Modify the handle associated with the Shape on the right side. Note that we will only - // have to load the same path from storage media once: repeated attempts will re-use the - // asset. - *handle = asset_server.load( - GltfAssetLabel::Primitive { - mesh: 0, - primitive: 0, - } - .from_asset(shape.get_model_path()), - ); - } + // Mesh handles, like other parts of the ECS, can be queried as mutable and modified at + // runtime. We only spawned one shape without the `Left` marker component. + let Ok((mut handle, mut shape)) = right_shape.get_single_mut() else { + return; + }; + + // Switch to a new Shape variant + shape.set_next_variant(); + + // Modify the handle associated with the Shape on the right side. Note that we will only + // have to load the same path from storage media once: repeated attempts will re-use the + // asset. + *handle = asset_server.load( + GltfAssetLabel::Primitive { + mesh: 0, + primitive: 0, + } + .from_asset(shape.get_model_path()), + ); +} - if keyboard_input.just_pressed(KeyCode::Enter) { - // It's convenient to retrieve the asset handle stored with the shape on the left. However, - // we could just as easily have retained this in a resource or a dedicated component. - let Ok(handle) = left_shape.get_single() else { - return; - }; - - // Obtain a mutable reference to the Mesh asset. - let Some(mesh) = meshes.get_mut(handle) else { - return; - }; - - // Now we can directly manipulate vertices on the mesh. Here, we're just scaling in and out - // for demonstration purposes. This will affect all entities currently using the asset. - if let Some(VertexAttributeValues::Float32x3(positions)) = - mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION) - { - // Check a Local value (which only this system can make use of) to determine if we're - // currently scaled up or not. - let scale_factor = if is_mesh_scaled.0 { 0.5 } else { 2.0 }; - - for position in positions.iter_mut() { - // Apply the scale factor to each of x, y, and z. - position[0] *= scale_factor; - position[1] *= scale_factor; - position[2] *= scale_factor; - } - - // Flip the local value to reverse the behaviour next time the key is pressed. - is_mesh_scaled.0 = !is_mesh_scaled.0; +fn alter_mesh( + mut is_mesh_scaled: Local, + left_shape: Query<&Handle, With>, + mut meshes: ResMut>, +) { + // It's convenient to retrieve the asset handle stored with the shape on the left. However, + // we could just as easily have retained this in a resource or a dedicated component. + let Ok(handle) = left_shape.get_single() else { + return; + }; + + // Obtain a mutable reference to the Mesh asset. + let Some(mesh) = meshes.get_mut(handle) else { + return; + }; + + // Now we can directly manipulate vertices on the mesh. Here, we're just scaling in and out + // for demonstration purposes. This will affect all entities currently using the asset. + // + // To do this, we need to grab the stored attributes of each vertex. `Float32x3` just describes + // the format in which the attributes will be read: each position consists of an array of three + // f32 corresponding to x, y, and z. + // + // `ATTRIBUTE_POSITION` is a constant indicating that we want to know where the vertex is + // located in space (as opposed to which way its normal is facing, vertex color, or other + // details). + if let Some(VertexAttributeValues::Float32x3(positions)) = + mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION) + { + // Check a Local value (which only this system can make use of) to determine if we're + // currently scaled up or not. + let scale_factor = if *is_mesh_scaled { 0.5 } else { 2.0 }; + + for position in positions.iter_mut() { + // Apply the scale factor to each of x, y, and z. + position[0] *= scale_factor; + position[1] *= scale_factor; + position[2] *= scale_factor; } + + // Flip the local value to reverse the behaviour next time the key is pressed. + *is_mesh_scaled = !*is_mesh_scaled; } } diff --git a/examples/asset/alter_sprite.rs b/examples/asset/alter_sprite.rs index 251568d566d1d..b51e71b693b18 100644 --- a/examples/asset/alter_sprite.rs +++ b/examples/asset/alter_sprite.rs @@ -1,12 +1,19 @@ //! Shows how to modify texture assets after spawning. -use bevy::prelude::*; +use bevy::{input::common_conditions::input_just_pressed, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) - .add_systems(Startup, (setup, instructions)) - .add_systems(Update, keyboard_controls) + .add_systems(Startup, (setup, spawn_text)) + .add_systems( + Update, + alter_handle.run_if(input_just_pressed(KeyCode::Space)), + ) + .add_systems( + Update, + alter_asset.run_if(input_just_pressed(KeyCode::Enter)), + ) .run(); } @@ -64,7 +71,7 @@ fn setup(mut commands: Commands, asset_server: Res) { )); } -fn instructions(mut commands: Commands) { +fn spawn_text(mut commands: Commands) { commands .spawn(( Name::new("Instructions"), @@ -91,47 +98,42 @@ fn instructions(mut commands: Commands) { }); } -fn keyboard_controls( +fn alter_handle( asset_server: Res, - mut images: ResMut>, - left_bird: Query<&Handle, With>, mut right_bird: Query<(&mut Bird, &mut Handle), Without>, - keyboard_input: Res>, ) { - if keyboard_input.just_pressed(KeyCode::Space) { - // Image handles, like other parts of the ECS, can be queried as mutable and modified at - // runtime. We only spawned one bird without the `Left` marker component. - let Ok((mut bird, mut handle)) = right_bird.get_single_mut() else { - return; - }; - - // Switch to a new Bird variant - bird.set_next_variant(); - - // Modify the handle associated with the Bird on the right side. Note that we will only - // have to load the same path from storage media once: repeated attempts will re-use the - // asset. - *handle = asset_server.load(bird.get_texture_path()); - } + // Image handles, like other parts of the ECS, can be queried as mutable and modified at + // runtime. We only spawned one bird without the `Left` marker component. + let Ok((mut bird, mut handle)) = right_bird.get_single_mut() else { + return; + }; + + // Switch to a new Bird variant + bird.set_next_variant(); + + // Modify the handle associated with the Bird on the right side. Note that we will only + // have to load the same path from storage media once: repeated attempts will re-use the + // asset. + *handle = asset_server.load(bird.get_texture_path()); +} - if keyboard_input.just_pressed(KeyCode::Enter) { - // It's convenient to retrieve the asset handle stored with the bird on the left. However, - // we could just as easily have retained this in a resource or a dedicated component. - let Ok(handle) = left_bird.get_single() else { - return; - }; - - // Obtain a mutable reference to the Image asset. - let Some(image) = images.get_mut(handle) else { - return; - }; - - for pixel in &mut image.data { - // Directly modify the asset data, which will affect all users of this asset. By - // contrast, mutating the handle (as we did above) affects only one copy. In this case, - // we'll just invert the colors, by way of demonstration. Notice that both uses of the - // asset show the change, not just the one on the left. - *pixel = 255 - *pixel; - } +fn alter_asset(mut images: ResMut>, left_bird: Query<&Handle, With>) { + // It's convenient to retrieve the asset handle stored with the bird on the left. However, + // we could just as easily have retained this in a resource or a dedicated component. + let Ok(handle) = left_bird.get_single() else { + return; + }; + + // Obtain a mutable reference to the Image asset. + let Some(image) = images.get_mut(handle) else { + return; + }; + + for pixel in &mut image.data { + // Directly modify the asset data, which will affect all users of this asset. By + // contrast, mutating the handle (as we did above) affects only one copy. In this case, + // we'll just invert the colors, by way of demonstration. Notice that both uses of the + // asset show the change, not just the one on the left. + *pixel = 255 - *pixel; } } From a4de40e8039845ec10948d3e5dcae6b80adbdce1 Mon Sep 17 00:00:00 2001 From: Rich Churcher Date: Fri, 20 Sep 2024 18:18:39 +1200 Subject: [PATCH 05/12] Add a note on RenderAssetUsages::all() --- examples/asset/alter_mesh.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/examples/asset/alter_mesh.rs b/examples/asset/alter_mesh.rs index e793422c4db60..5aa544986e302 100644 --- a/examples/asset/alter_mesh.rs +++ b/examples/asset/alter_mesh.rs @@ -1,7 +1,7 @@ //! Shows how to modify mesh assets after spawning. -use bevy::{input::common_conditions::input_just_pressed, prelude::*}; -use bevy_render::mesh::VertexAttributeValues; +use bevy::{gltf::GltfLoaderSettings, input::common_conditions::input_just_pressed, prelude::*}; +use bevy_render::{mesh::VertexAttributeValues, render_asset::RenderAssetUsages}; fn main() { App::new() @@ -51,7 +51,9 @@ fn setup( let left_shape = Shape::Cube; let right_shape = Shape::Cube; - let left_shape_model = asset_server.load( + // In normal use, you can call `asset_server.load`, however see below for an explanation of + // `RenderAssetUsages`. + let left_shape_model = asset_server.load_with_settings( GltfAssetLabel::Primitive { mesh: 0, // This field stores an index to this primitive in its parent mesh. In this case, we @@ -63,7 +65,17 @@ fn setup( primitive: 0, } .from_asset(left_shape.get_model_path()), + // This is the default loader setting, ensuring both `RENDER_WORLD` and `MAIN_WORLD` are + // enabled. It's provided explicitly here only by way of demonstration. + // + // A common mistake is to use `RENDER_WORLD` by itself, which can cause a confusing lack of + // assets available in `Res>`. `RENDER_WORLD` alone will cause the asset to be + // unloaded from the asset server after it's been sent to the GPU. Unless you have a clear + // reason not to do so, it's best to use `RenderAssetUsages::all(). + |settings: &mut GltfLoaderSettings| settings.load_meshes = RenderAssetUsages::all(), ); + + // Here, we rely on the default loader settings to achieve a similar result to the above. let right_shape_model = asset_server.load( GltfAssetLabel::Primitive { mesh: 0, From f95757c6418ae2aa910f55600d3caf56fe9e9ff3 Mon Sep 17 00:00:00 2001 From: Rich Churcher Date: Fri, 20 Sep 2024 18:21:36 +1200 Subject: [PATCH 06/12] Missing backtick. --- examples/asset/alter_mesh.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/asset/alter_mesh.rs b/examples/asset/alter_mesh.rs index 5aa544986e302..b01731d6f38e5 100644 --- a/examples/asset/alter_mesh.rs +++ b/examples/asset/alter_mesh.rs @@ -71,7 +71,7 @@ fn setup( // A common mistake is to use `RENDER_WORLD` by itself, which can cause a confusing lack of // assets available in `Res>`. `RENDER_WORLD` alone will cause the asset to be // unloaded from the asset server after it's been sent to the GPU. Unless you have a clear - // reason not to do so, it's best to use `RenderAssetUsages::all(). + // reason not to do so, it's best to use `RenderAssetUsages::all()`. |settings: &mut GltfLoaderSettings| settings.load_meshes = RenderAssetUsages::all(), ); From 759a564f806adb41389c51548531a7109ceb3ee2 Mon Sep 17 00:00:00 2001 From: Rich Churcher Date: Sat, 21 Sep 2024 12:27:58 +1200 Subject: [PATCH 07/12] Clarify explanation --- examples/asset/alter_mesh.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/examples/asset/alter_mesh.rs b/examples/asset/alter_mesh.rs index b01731d6f38e5..63d44a6be4287 100644 --- a/examples/asset/alter_mesh.rs +++ b/examples/asset/alter_mesh.rs @@ -66,12 +66,13 @@ fn setup( } .from_asset(left_shape.get_model_path()), // This is the default loader setting, ensuring both `RENDER_WORLD` and `MAIN_WORLD` are - // enabled. It's provided explicitly here only by way of demonstration. + // enabled. It's provided explicitly here only by way of demonstration. Unless you have + // specific requirements, it's usually safe to use the default. // - // A common mistake is to use `RENDER_WORLD` by itself, which can cause a confusing lack of - // assets available in `Res>`. `RENDER_WORLD` alone will cause the asset to be - // unloaded from the asset server after it's been sent to the GPU. Unless you have a clear - // reason not to do so, it's best to use `RenderAssetUsages::all()`. + // When needing to access a `Mesh` asset via `Res>`, a common mistake is to + // use `RENDER_WORLD` by itself, which can cause the asset to be missing from the resource. + // (`RENDER_WORLD` without `MAIN_WORLD` will result in the asset being unloaded from the + // asset server after it's been sent to the GPU.) |settings: &mut GltfLoaderSettings| settings.load_meshes = RenderAssetUsages::all(), ); From 3ee33af0886270f0255c3ff382c5709be4f332d4 Mon Sep 17 00:00:00 2001 From: Rich Churcher Date: Sat, 21 Sep 2024 13:20:30 +1200 Subject: [PATCH 08/12] Avoid internal imports --- examples/asset/alter_mesh.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/asset/alter_mesh.rs b/examples/asset/alter_mesh.rs index 63d44a6be4287..84672a29d84f5 100644 --- a/examples/asset/alter_mesh.rs +++ b/examples/asset/alter_mesh.rs @@ -1,7 +1,9 @@ //! Shows how to modify mesh assets after spawning. -use bevy::{gltf::GltfLoaderSettings, input::common_conditions::input_just_pressed, prelude::*}; -use bevy_render::{mesh::VertexAttributeValues, render_asset::RenderAssetUsages}; +use bevy::{ + gltf::GltfLoaderSettings, input::common_conditions::input_just_pressed, prelude::*, + render::mesh::VertexAttributeValues, render::render_asset::RenderAssetUsages, +}; fn main() { App::new() From 5f936db9fce6a9c40c1e9995ba90f5e0a1e9f05a Mon Sep 17 00:00:00 2001 From: Rich Churcher Date: Sun, 22 Sep 2024 10:30:16 +1200 Subject: [PATCH 09/12] Reword comment Co-authored-by: Jan Hohenheim --- examples/asset/alter_mesh.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/examples/asset/alter_mesh.rs b/examples/asset/alter_mesh.rs index 84672a29d84f5..3b347a6afd4e5 100644 --- a/examples/asset/alter_mesh.rs +++ b/examples/asset/alter_mesh.rs @@ -67,14 +67,15 @@ fn setup( primitive: 0, } .from_asset(left_shape.get_model_path()), - // This is the default loader setting, ensuring both `RENDER_WORLD` and `MAIN_WORLD` are - // enabled. It's provided explicitly here only by way of demonstration. Unless you have - // specific requirements, it's usually safe to use the default. - // - // When needing to access a `Mesh` asset via `Res>`, a common mistake is to - // use `RENDER_WORLD` by itself, which can cause the asset to be missing from the resource. - // (`RENDER_WORLD` without `MAIN_WORLD` will result in the asset being unloaded from the - // asset server after it's been sent to the GPU.) + // `RenderAssetUsages::all()` is already the default, so this line could be omitted. + // We leave it in for explicitness however. The `RenderAssetUsages` tell Bevy whether to + // keep the data around for the GPU, which corresponds to `RenderAssetUsages::RENDER_WORLD`, + // or for the CPU, which corresponds to `RenderAssetUsages::MAIN_WORLD`. + // `RENDER_WORLD` is necessary to render the mesh, `MAIN_WORLD` is necessary to inspect + // and modify the mesh. Since most games will not need to modify meshes at runtime, many users + // opt to pass only `RENDER_WORLD`. That is more memory efficient, as we don't need to keep the mesh + // in the RAM. For this example however, this would not work, as we need to inspect and modify the mesh + // via `Res>` at runtime. That's the entire point of the example, after all! |settings: &mut GltfLoaderSettings| settings.load_meshes = RenderAssetUsages::all(), ); From 94e7b3cfb1a2c8c63a9048e0fcf5b9daedab0dfb Mon Sep 17 00:00:00 2001 From: Rich Churcher Date: Sun, 22 Sep 2024 10:44:33 +1200 Subject: [PATCH 10/12] Refine comments and demonstrate loader settings in other e.g. --- examples/asset/alter_mesh.rs | 21 +++++++++++++-------- examples/asset/alter_sprite.rs | 24 +++++++++++++++++++++++- 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/examples/asset/alter_mesh.rs b/examples/asset/alter_mesh.rs index 3b347a6afd4e5..5bd3053af3b8c 100644 --- a/examples/asset/alter_mesh.rs +++ b/examples/asset/alter_mesh.rs @@ -67,15 +67,20 @@ fn setup( primitive: 0, } .from_asset(left_shape.get_model_path()), - // `RenderAssetUsages::all()` is already the default, so this line could be omitted. - // We leave it in for explicitness however. The `RenderAssetUsages` tell Bevy whether to - // keep the data around for the GPU, which corresponds to `RenderAssetUsages::RENDER_WORLD`, - // or for the CPU, which corresponds to `RenderAssetUsages::MAIN_WORLD`. + // `RenderAssetUsages::all()` is already the default, so the line below could be omitted. + // It's helpful to know it exists, however. + // + // `RenderAssetUsages` tell Bevy whether to keep the data around: + // - for the GPU (`RenderAssetUsages::RENDER_WORLD`), + // - for the CPU (`RenderAssetUsages::MAIN_WORLD`), + // - or both. // `RENDER_WORLD` is necessary to render the mesh, `MAIN_WORLD` is necessary to inspect - // and modify the mesh. Since most games will not need to modify meshes at runtime, many users - // opt to pass only `RENDER_WORLD`. That is more memory efficient, as we don't need to keep the mesh - // in the RAM. For this example however, this would not work, as we need to inspect and modify the mesh - // via `Res>` at runtime. That's the entire point of the example, after all! + // and modify the mesh (via `ResMut>`). + // + // Since most games will not need to modify meshes at runtime, many developers opt to pass + // only `RENDER_WORLD`. This is more memory efficient, as we don't need to keep the mesh in + // RAM. For this example however, this would not work, as we need to inspect and modify the + // mesh at runtime. |settings: &mut GltfLoaderSettings| settings.load_meshes = RenderAssetUsages::all(), ); diff --git a/examples/asset/alter_sprite.rs b/examples/asset/alter_sprite.rs index b51e71b693b18..9c5df5f941ab2 100644 --- a/examples/asset/alter_sprite.rs +++ b/examples/asset/alter_sprite.rs @@ -1,6 +1,7 @@ //! Shows how to modify texture assets after spawning. use bevy::{input::common_conditions::input_just_pressed, prelude::*}; +use bevy_render::{render_asset::RenderAssetUsages, texture::ImageLoaderSettings}; fn main() { App::new() @@ -47,13 +48,32 @@ fn setup(mut commands: Commands, asset_server: Res) { let bird_right = Bird::Normal; commands.spawn(Camera2dBundle::default()); + let texture_left = asset_server.load_with_settings( + bird_left.get_texture_path(), + // `RenderAssetUsages::all()` is already the default, so the line below could be omitted. + // It's helpful to know it exists, however. + // + // `RenderAssetUsages` tell Bevy whether to keep the data around: + // - for the GPU (`RenderAssetUsages::RENDER_WORLD`), + // - for the CPU (`RenderAssetUsages::MAIN_WORLD`), + // - or both. + // `RENDER_WORLD` is necessary to render the mesh, `MAIN_WORLD` is necessary to inspect + // and modify the mesh (via `ResMut>`). + // + // Since most games will not need to modify textures at runtime, many developers opt to pass + // only `RENDER_WORLD`. This is more memory efficient, as we don't need to keep the image in + // RAM. For this example however, this would not work, as we need to inspect and modify the + // image at runtime. + |settings: &mut ImageLoaderSettings| settings.asset_usage = RenderAssetUsages::all(), + ); + commands.spawn(( Name::new("Bird Left"), // This marker component ensures we can easily find either of the Birds by using With and // Without query filters. Left, SpriteBundle { - texture: asset_server.load(bird_left.get_texture_path()), + texture: texture_left, transform: Transform::from_xyz(-200.0, 0.0, 0.0), ..default() }, @@ -63,6 +83,8 @@ fn setup(mut commands: Commands, asset_server: Res) { commands.spawn(( Name::new("Bird Right"), SpriteBundle { + // In contrast to the above, here we rely on the default `RenderAssetUsages` loader + // setting. texture: asset_server.load(bird_right.get_texture_path()), transform: Transform::from_xyz(200.0, 0.0, 0.0), ..default() From 77019263060ae8d797570173d40d604460796ed0 Mon Sep 17 00:00:00 2001 From: Rich Churcher Date: Sun, 22 Sep 2024 10:48:07 +1200 Subject: [PATCH 11/12] Copy/paste errors --- examples/asset/alter_sprite.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/asset/alter_sprite.rs b/examples/asset/alter_sprite.rs index 9c5df5f941ab2..9b4a8b64b7569 100644 --- a/examples/asset/alter_sprite.rs +++ b/examples/asset/alter_sprite.rs @@ -57,8 +57,8 @@ fn setup(mut commands: Commands, asset_server: Res) { // - for the GPU (`RenderAssetUsages::RENDER_WORLD`), // - for the CPU (`RenderAssetUsages::MAIN_WORLD`), // - or both. - // `RENDER_WORLD` is necessary to render the mesh, `MAIN_WORLD` is necessary to inspect - // and modify the mesh (via `ResMut>`). + // `RENDER_WORLD` is necessary to render the image, `MAIN_WORLD` is necessary to inspect + // and modify the image (via `ResMut>`). // // Since most games will not need to modify textures at runtime, many developers opt to pass // only `RENDER_WORLD`. This is more memory efficient, as we don't need to keep the image in From cf8569e1b410dc16286543da81f5041ef3640ef5 Mon Sep 17 00:00:00 2001 From: Rich Churcher Date: Sun, 22 Sep 2024 12:02:24 +1200 Subject: [PATCH 12/12] Fix internal imports (again) --- examples/asset/alter_sprite.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/examples/asset/alter_sprite.rs b/examples/asset/alter_sprite.rs index 9b4a8b64b7569..7725ad36eb8f2 100644 --- a/examples/asset/alter_sprite.rs +++ b/examples/asset/alter_sprite.rs @@ -1,7 +1,10 @@ //! Shows how to modify texture assets after spawning. -use bevy::{input::common_conditions::input_just_pressed, prelude::*}; -use bevy_render::{render_asset::RenderAssetUsages, texture::ImageLoaderSettings}; +use bevy::{ + input::common_conditions::input_just_pressed, + prelude::*, + render::{render_asset::RenderAssetUsages, texture::ImageLoaderSettings}, +}; fn main() { App::new()