Sprite keeps drawing an image's old texture after the image is replaced with one of a different size

Aperta
#26,702 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 2 giorni

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
45/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
rust
Ambito
game-dev

Direzione di ricerca

Start by reading bevy_render/src/texture/gpu_image.rs around GpuImage::prepare_asset, then inspect bevy_sprite_render/src/sprite_mesh/mod.rs and add_material to see how the sprite material cache uses the image AssetId. The fix should ensure that replacing an image with a differently sized texture refreshes the sprite bind group and stops it using the old texture view. Verify that size changes and later same-size pixel updates are rendered correctly, using the issue's reproduction as the starting point.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

C-Bug S-Needs-Triage

Bevy version and features

  • 0.20.1
  • Default features

[Optional] Relevant system information

  • cargo 1.102.0-nightly (ede6cefea 2026-11-11)
  • Fedora Linux 44 (Workstation Edition), kernel 7.3.4
AdapterInfo { name: "NVIDIA GeForce RTX 2080", vendor: 4318, device: 7810, device_type: DiscreteGpu, device_pci_bus_id: "0000:01:00.0", driver: "NVIDIA", driver_info: "620.70.06", backend: Vulkan, subgroup_min_size: 32, subgroup_max_size: 32, transient_saves_memory: Some(false), limit_bucket: None }

What you did

Changed a sprite's image in place with Assets<Image>::get_mut, replacing it with an image of a different size, without changing the Sprite itself:

use bevy::asset::RenderAssetUsages;
use bevy::prelude::*;
use bevy::render::render_resource::{Extent3d, TextureDimension, TextureFormat};

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, replace_image)
        .run();
}

#[derive(Resource)]
struct SpriteImage(Handle<Image>);

fn solid_image(size: u32, color: [u8; 4]) -> Image {
    Image::new_fill(
        Extent3d {
            width: size,
            height: size,
            depth_or_array_layers: 1,
        },
        TextureDimension::D2,
        &color,
        TextureFormat::Rgba8UnormSrgb,
        RenderAssetUsages::default(),
    )
}

fn setup(mut commands: Commands, mut images: ResMut<Assets<Image>>) {
    commands.spawn(Camera2d);
    let image = images.add(solid_image(100, [255, 0, 0, 255]));
    commands.spawn(Sprite::from_image(image.clone()));
    commands.insert_resource(SpriteImage(image));
}

/// Once a second, replaces the image: red 100×100, then green 200×200,
/// then blue 200×200, then red 100×100 again, and so on.
fn replace_image(
    time: Res<Time>,
    mut timer: Local<Option<Timer>>,
    mut step: Local<u32>,
    image: Res<SpriteImage>,
    mut images: ResMut<Assets<Image>>,
) {
    let timer = timer.get_or_insert_with(|| Timer::from_seconds(1.0, TimerMode::Repeating));
    if !timer.tick(time.delta()).just_finished() {
        return;
    }
    *step += 1;
    let (size, color) = match *step % 3 {
        0 => (100, [255, 0, 0, 255]),
        1 => (200, [0, 255, 0, 255]),
        _ => (200, [0, 0, 255, 255]),
    };
    *images.get_mut(&image.0).unwrap() = solid_image(size, color);
}

What went wrong

  • Expected: the sprite cycles through a red 100×100 square, a green 200×200 square and a blue 200×200 square, one second each.
  • Actual: the sprite stays a red 100×100 square.

The same happens with any change that gives the image a new GPU texture. A change that keeps the size (and the rest of the texture descriptor) shows up, because the new pixels are written into the existing texture. Once the size has changed, though, the sprite never shows the image again, not even later same-size changes, because those are written into the new texture.

Additional information

Where it goes wrong
  • GpuImage::prepare_asset (bevy_render/src/texture/gpu_image.rs) writes the new pixels into the previous texture and keeps its view when the texture descriptor is unchanged. Otherwise it creates a new texture and view. It also creates a new sampler on every prepare when the image has an ImageSampler::Descriptor.
  • In 0.20, a Sprite is drawn with a Mesh2d and a SpriteMeshMaterial. add_material (bevy_sprite_render/src/sprite_mesh/mod.rs) takes that material from a cache keyed by the Sprite's fields, including the image's AssetId, and only runs when the Sprite or Anchor changes. The material's bind group holds the image's texture view and sampler from when the material was prepared.
  • Nothing prepares the material again when its image's GpuImage gets a new texture. The bind group keeps the old texture view, so the sprite keeps drawing the old texture.

The legacy sprite path did handle this: prepare_sprite_image_bind_groups (bevy_sprite_render/src/render/mod.rs) drops its cached bind group for an image on AssetEvent::Modified.

Workarounds
  • Add the changed image as a new asset (Assets::add) instead of replacing it in place, when its size changes. The sprite then gets a new AssetId, and so a new material.
  • Changing a Sprite field that is part of the material cache key, such as color, also gives the sprite a new material.
Related issues
  • #26398: the TextureAtlasLayout is copied into the SpriteMeshMaterial when the material is made, so later changes to the layout asset aren't shown either. The NOTE on add_material mentions this for atlas layouts.
  • #17854 (Bevy 0.15): sprites disappear after Assets<Image>::get_mut. That was the legacy sprite path, with a different symptom.
Lingua principale
Rust
Stelle
50k
Fork
5.1k
Merge medio
2g 20h
PR unite (30g)
129

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di bevyengine/bevy

Tutte le issue di bevyengine/bevy

Issue simili

Altre issue su Rust

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.