//! Shows how to modify mesh assets after spawning.12use bevy::{3asset::RenderAssetUsages, gltf::GltfLoaderSettings,4input::common_conditions::input_just_pressed, mesh::VertexAttributeValues, prelude::*,5};67fn main() {8App::new()9.add_plugins(DefaultPlugins)10.add_systems(Startup, (setup, spawn_text))11.add_systems(12Update,13alter_handle.run_if(input_just_pressed(KeyCode::Space)),14)15.add_systems(16Update,17alter_mesh.run_if(input_just_pressed(KeyCode::Enter)),18)19.run();20}2122#[derive(Component, Debug)]23enum Shape {24Cube,25Sphere,26}2728impl Shape {29fn get_model_path(&self) -> String {30match self {31Shape::Cube => "models/cube/cube.gltf".into(),32Shape::Sphere => "models/sphere/sphere.gltf".into(),33}34}3536fn set_next_variant(&mut self) {37*self = match self {38Shape::Cube => Shape::Sphere,39Shape::Sphere => Shape::Cube,40}41}42}4344#[derive(Component, Debug)]45struct Left;4647fn setup(48mut commands: Commands,49asset_server: Res<AssetServer>,50mut materials: ResMut<Assets<StandardMaterial>>,51) {52let left_shape = Shape::Cube;53let right_shape = Shape::Cube;5455// In normal use, you can call `asset_server.load`, however see below for an explanation of56// `RenderAssetUsages`.57let left_shape_model = asset_server.load_with_settings(58GltfAssetLabel::Primitive {59mesh: 0,60// This field stores an index to this primitive in its parent mesh. In this case, we61// want the first one. You might also have seen the syntax:62//63// models/cube/cube.gltf#Scene064//65// which accomplishes the same thing.66primitive: 0,67}68.from_asset(left_shape.get_model_path()),69// `RenderAssetUsages::all()` is already the default, so the line below could be omitted.70// It's helpful to know it exists, however.71//72// `RenderAssetUsages` tell Bevy whether to keep the data around:73// - for the GPU (`RenderAssetUsages::RENDER_WORLD`),74// - for the CPU (`RenderAssetUsages::MAIN_WORLD`),75// - or both.76// `RENDER_WORLD` is necessary to render the mesh, `MAIN_WORLD` is necessary to inspect77// and modify the mesh (via `ResMut<Assets<Mesh>>`).78//79// Since most games will not need to modify meshes at runtime, many developers opt to pass80// only `RENDER_WORLD`. This is more memory efficient, as we don't need to keep the mesh in81// RAM. For this example however, this would not work, as we need to inspect and modify the82// mesh at runtime.83|settings: &mut GltfLoaderSettings| settings.load_meshes = RenderAssetUsages::all(),84);8586// Here, we rely on the default loader settings to achieve a similar result to the above.87let right_shape_model = asset_server.load(88GltfAssetLabel::Primitive {89mesh: 0,90primitive: 0,91}92.from_asset(right_shape.get_model_path()),93);9495// Add a material asset directly to the materials storage96let material_handle = materials.add(StandardMaterial {97base_color: Color::srgb(0.6, 0.8, 0.6),98..default()99});100101commands.spawn((102Left,103Name::new("Left Shape"),104Mesh3d(left_shape_model),105MeshMaterial3d(material_handle.clone()),106Transform::from_xyz(-3.0, 0.0, 0.0),107left_shape,108));109110commands.spawn((111Name::new("Right Shape"),112Mesh3d(right_shape_model),113MeshMaterial3d(material_handle),114Transform::from_xyz(3.0, 0.0, 0.0),115right_shape,116));117118commands.spawn((119Name::new("Point Light"),120PointLight::default(),121Transform::from_xyz(4.0, 5.0, 4.0),122));123124commands.spawn((125Name::new("Camera"),126Camera3d::default(),127Transform::from_xyz(0.0, 3.0, 20.0).looking_at(Vec3::ZERO, Vec3::Y),128));129}130131fn spawn_text(mut commands: Commands) {132commands.spawn((133Name::new("Instructions"),134Text::new(135"Space: swap meshes by mutating a Handle<Mesh>\n\136Return: mutate the mesh itself, changing all copies of it",137),138Node {139position_type: PositionType::Absolute,140top: px(12),141left: px(12),142..default()143},144));145}146147fn alter_handle(148asset_server: Res<AssetServer>,149right_shape: Single<(&mut Mesh3d, &mut Shape), Without<Left>>,150) {151// Mesh handles, like other parts of the ECS, can be queried as mutable and modified at152// runtime. We only spawned one shape without the `Left` marker component.153let (mut mesh, mut shape) = right_shape.into_inner();154155// Switch to a new Shape variant156shape.set_next_variant();157158// Modify the handle associated with the Shape on the right side. Note that we will only159// have to load the same path from storage media once: repeated attempts will re-use the160// asset.161mesh.0 = asset_server.load(162GltfAssetLabel::Primitive {163mesh: 0,164primitive: 0,165}166.from_asset(shape.get_model_path()),167);168}169170fn alter_mesh(171mut is_mesh_scaled: Local<bool>,172left_shape: Single<&Mesh3d, With<Left>>,173mut meshes: ResMut<Assets<Mesh>>,174) {175// Obtain a mutable reference to the Mesh asset.176let Some(mesh) = meshes.get_mut(*left_shape) else {177return;178};179180// Now we can directly manipulate vertices on the mesh. Here, we're just scaling in and out181// for demonstration purposes. This will affect all entities currently using the asset.182//183// To do this, we need to grab the stored attributes of each vertex. `Float32x3` just describes184// the format in which the attributes will be read: each position consists of an array of three185// f32 corresponding to x, y, and z.186//187// `ATTRIBUTE_POSITION` is a constant indicating that we want to know where the vertex is188// located in space (as opposed to which way its normal is facing, vertex color, or other189// details).190if let Some(VertexAttributeValues::Float32x3(positions)) =191mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION)192{193// Check a Local value (which only this system can make use of) to determine if we're194// currently scaled up or not.195let scale_factor = if *is_mesh_scaled { 0.5 } else { 2.0 };196197for position in positions.iter_mut() {198// Apply the scale factor to each of x, y, and z.199position[0] *= scale_factor;200position[1] *= scale_factor;201position[2] *= scale_factor;202}203204// Flip the local value to reverse the behavior next time the key is pressed.205*is_mesh_scaled = !*is_mesh_scaled;206}207}208209210