alter_sprite/
alter_sprite.rs

1//! Shows how to modify texture assets after spawning.
2
3use bevy::{
4    asset::RenderAssetUsages, image::ImageLoaderSettings,
5    input::common_conditions::input_just_pressed, prelude::*,
6};
7
8fn main() {
9    App::new()
10        .add_plugins(DefaultPlugins)
11        .add_systems(Startup, (setup, spawn_text))
12        .add_systems(
13            Update,
14            alter_handle.run_if(input_just_pressed(KeyCode::Space)),
15        )
16        .add_systems(
17            Update,
18            alter_asset.run_if(input_just_pressed(KeyCode::Enter)),
19        )
20        .run();
21}
22
23#[derive(Component, Debug)]
24enum Bird {
25    Normal,
26    Logo,
27}
28
29impl Bird {
30    fn get_texture_path(&self) -> String {
31        match self {
32            Bird::Normal => "branding/bevy_bird_dark.png".into(),
33            Bird::Logo => "branding/bevy_logo_dark.png".into(),
34        }
35    }
36
37    fn set_next_variant(&mut self) {
38        *self = match self {
39            Bird::Normal => Bird::Logo,
40            Bird::Logo => Bird::Normal,
41        }
42    }
43}
44
45#[derive(Component, Debug)]
46struct Left;
47
48fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
49    let bird_left = Bird::Normal;
50    let bird_right = Bird::Normal;
51    commands.spawn(Camera2d);
52
53    let texture_left = asset_server.load_with_settings(
54        bird_left.get_texture_path(),
55        // `RenderAssetUsages::all()` is already the default, so the line below could be omitted.
56        // It's helpful to know it exists, however.
57        //
58        // `RenderAssetUsages` tell Bevy whether to keep the data around:
59        //   - for the GPU (`RenderAssetUsages::RENDER_WORLD`),
60        //   - for the CPU (`RenderAssetUsages::MAIN_WORLD`),
61        //   - or both.
62        // `RENDER_WORLD` is necessary to render the image, `MAIN_WORLD` is necessary to inspect
63        // and modify the image (via `ResMut<Assets<Image>>`).
64        //
65        // Since most games will not need to modify textures at runtime, many developers opt to pass
66        // only `RENDER_WORLD`. This is more memory efficient, as we don't need to keep the image in
67        // RAM. For this example however, this would not work, as we need to inspect and modify the
68        // image at runtime.
69        |settings: &mut ImageLoaderSettings| settings.asset_usage = RenderAssetUsages::all(),
70    );
71
72    commands.spawn((
73        Name::new("Bird Left"),
74        // This marker component ensures we can easily find either of the Birds by using With and
75        // Without query filters.
76        Left,
77        Sprite::from_image(texture_left),
78        Transform::from_xyz(-200.0, 0.0, 0.0),
79        bird_left,
80    ));
81
82    commands.spawn((
83        Name::new("Bird Right"),
84        // In contrast to the above, here we rely on the default `RenderAssetUsages` loader setting
85        Sprite::from_image(asset_server.load(bird_right.get_texture_path())),
86        Transform::from_xyz(200.0, 0.0, 0.0),
87        bird_right,
88    ));
89}
90
91fn spawn_text(mut commands: Commands) {
92    commands.spawn((
93        Name::new("Instructions"),
94        Text::new(
95            "Space: swap the right sprite's image handle\n\
96            Return: modify the image Asset of the left sprite, affecting all uses of it",
97        ),
98        Node {
99            position_type: PositionType::Absolute,
100            top: px(12),
101            left: px(12),
102            ..default()
103        },
104    ));
105}
106
107fn alter_handle(
108    asset_server: Res<AssetServer>,
109    right_bird: Single<(&mut Bird, &mut Sprite), Without<Left>>,
110) {
111    // Image handles, like other parts of the ECS, can be queried as mutable and modified at
112    // runtime. We only spawned one bird without the `Left` marker component.
113    let (mut bird, mut sprite) = right_bird.into_inner();
114
115    // Switch to a new Bird variant
116    bird.set_next_variant();
117
118    // Modify the handle associated with the Bird on the right side. Note that we will only
119    // have to load the same path from storage media once: repeated attempts will re-use the
120    // asset.
121    sprite.image = asset_server.load(bird.get_texture_path());
122}
123
124fn alter_asset(mut images: ResMut<Assets<Image>>, left_bird: Single<&Sprite, With<Left>>) {
125    // Obtain a mutable reference to the Image asset.
126    let Some(image) = images.get_mut(&left_bird.image) else {
127        return;
128    };
129
130    for pixel in image.data.as_mut().unwrap() {
131        // Directly modify the asset data, which will affect all users of this asset. By
132        // contrast, mutating the handle (as we did above) affects only one copy. In this case,
133        // we'll just invert the colors, by way of demonstration. Notice that both uses of the
134        // asset show the change, not just the one on the left.
135        *pixel = 255 - *pixel;
136    }
137}