src/bin/lesson07b_mini_bevy.rs

教程导航 · 代码索引

src/bin/lesson07b_mini_bevy.rs

教程导航 · 代码索引

原文件:Doc/tutorial/src/bin/lesson07b_mini_bevy.rs。

阅读快照 以下内容来自 2026-11-17 导入时的本地源码,后续不会自动同步。编辑、编译和运行请回到原项目;本页 Markdown 不是可直接编译的源文件。

在原项目根目录运行:

cargo run --manifest-path Doc/tutorial/Cargo.toml --bin lesson07b_mini_bevy
//! 不使用 bevy_immediate API,手写最小 Bevy 实体复用与清理。
use std::collections::{HashMap, HashSet};

use bevy::prelude::*;
use bevy_immediate_tutorial::{app, camera, panel};

#[derive(Resource, Default)]
struct MiniMemory {
    nodes: HashMap<String, Entity>,
    visited: HashSet<String>,
}

impl MiniMemory {
    fn node(
        &mut self,
        id: &str,
        parent: Option<Entity>,
        commands: &mut Commands,
        existing: &Query<()>,
    ) -> (Entity, bool) {
        assert!(self.visited.insert(id.to_owned()), "duplicate id: {id}");
        if let Some(&entity) = self.nodes.get(id)
            && existing.contains(entity)
        {
            return (entity, false);
        }
        let mut new_entity = commands.spawn_empty();
        if let Some(parent) = parent {
            new_entity.insert(ChildOf(parent));
        }
        let entity = new_entity.id();
        self.nodes.insert(id.to_owned(), entity);
        println!("spawn {id}: {entity}");
        (entity, true)
    }
}

struct MiniImmediatePlugin;

impl Plugin for MiniImmediatePlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<MiniMemory>()
            .add_systems(First, begin_frame)
            .add_systems(PostUpdate, cleanup.before(bevy::ui::UiSystems::Prepare));
    }
}

fn begin_frame(mut memory: ResMut<MiniMemory>) {
    memory.visited.clear();
}

fn cleanup(mut memory: ResMut<MiniMemory>, mut commands: Commands) {
    let unused: Vec<String> = memory
        .nodes
        .keys()
        .filter(|id| !memory.visited.contains(*id))
        .cloned()
        .collect();
    for id in unused {
        if let Some(entity) = memory.nodes.remove(&id) {
            commands.entity(entity).try_despawn();
            println!("remove {id}: {entity}");
        }
    }
}

#[derive(Resource, Default)]
struct ScreenState {
    show_help: bool,
}

fn draw(
    mut memory: ResMut<MiniMemory>,
    mut commands: Commands,
    existing: Query<()>,
    keys: Res<ButtonInput<KeyCode>>,
    mut state: ResMut<ScreenState>,
) {
    if keys.just_pressed(KeyCode::Space) {
        state.show_help = !state.show_help;
    }
    let (root, is_new) = memory.node("panel", None, &mut commands, &existing);
    if is_new {
        commands.entity(root).insert(panel());
    }
    let (title, is_new) = memory.node("panel/title", Some(root), &mut commands, &existing);
    if is_new {
        commands
            .entity(title)
            .insert(Text::new("Press Space to toggle help"));
    }
    if state.show_help {
        let (help, is_new) = memory.node("panel/help", Some(root), &mut commands, &existing);
        if is_new {
            commands
                .entity(help)
                .insert(Text::new("Built by our own tiny Bevy plugin."));
        }
    }
}

fn main() {
    app("07b - Our tiny Bevy core")
        .add_plugins(MiniImmediatePlugin)
        .init_resource::<ScreenState>()
        .add_systems(Startup, camera)
        .add_systems(Update, draw)
        .run();
}