Movatterモバイル変換


[0]ホーム

URL:


Docs.rs

Crate bevy_ecs

Cratebevy_ecs 

Source
Expand description

§Bevy ECS

LicenseCrates.ioDownloadsDocsDiscord

§What is Bevy ECS?

Bevy ECS is an Entity Component System custom-built for theBevy game engine.It aims to be simple to use, ergonomic, fast, massively parallel, opinionated, and featureful.It was created specifically for Bevy’s needs, but it can easily be used as a standalone crate in other projects.

§ECS

All app logic in Bevy uses the Entity Component System paradigm, which is often shortened to ECS. ECS is a software pattern that involves breaking your program up into Entities, Components, and Systems. Entities are unique “things” that are assigned groups of Components, which are then processed using Systems.

For example, one entity might have aPosition andVelocity component, whereas another entity might have aPosition andUI component. You might have a movement system that runs on all entities with a Position and Velocity component.

The ECS pattern encourages clean, decoupled designs by forcing you to break up your app data and logic into its core components. It also helps make your code faster by optimizing memory access patterns and making parallelism easier.

§Concepts

Bevy ECS is Bevy’s implementation of the ECS pattern. Unlike other Rust ECS implementations, which often require complex lifetimes, traits, builder patterns, or macros, Bevy ECS uses normal Rust data types for all of these concepts:

§Components

Components are normal Rust structs. They are data stored in aWorld and specific instances of Components correlate to Entities.

usebevy_ecs::prelude::*;#[derive(Component)]structPosition { x: f32, y: f32 }

§Worlds

Entities, Components, and Resources are stored in aWorld. Worlds, much likestd::collections’sHashSet andVec, expose operations to insert, read, write, and remove the data they store.

usebevy_ecs::world::World;letworld = World::default();

§Entities

Entities are unique identifiers that correlate to zero or more Components.

usebevy_ecs::prelude::*;#[derive(Component)]structPosition { x: f32, y: f32 }#[derive(Component)]structVelocity { x: f32, y: f32 }letmutworld = World::new();letentity = world    .spawn((Position { x:0.0, y:0.0}, Velocity { x:1.0, y:0.0}))    .id();letentity_ref = world.entity(entity);letposition = entity_ref.get::<Position>().unwrap();letvelocity = entity_ref.get::<Velocity>().unwrap();

§Systems

Systems are normal Rust functions. Thanks to the Rust type system, Bevy ECS can use function parameter types to determine what data needs to be sent to the system. It also uses this “data access” information to determine what Systems can run in parallel with each other.

usebevy_ecs::prelude::*;#[derive(Component)]structPosition { x: f32, y: f32 }fnprint_position(query: Query<(Entity,&Position)>) {for(entity, position)in&query {println!("Entity {} is at position: x {}, y {}", entity, position.x, position.y);    }}

§Resources

Apps often require unique resources, such as asset collections, renderers, audio servers, time, etc. Bevy ECS makes this pattern a first class citizen.Resource is a special kind of component that does not belong to any entity. Instead, it is identified uniquely by its type:

usebevy_ecs::prelude::*;#[derive(Resource, Default)]structTime {    seconds: f32,}letmutworld = World::new();world.insert_resource(Time::default());lettime = world.get_resource::<Time>().unwrap();// You can also access resources from Systemsfnprint_time(time: Res<Time>) {println!("{}", time.seconds);}

§Schedules

Schedules run a set of Systems according to some execution strategy.Systems can be added to any number of System Sets, which are used to control their scheduling metadata.

The built in “parallel executor” considers dependencies between systems and (by default) run as many of them in parallel as possible. This maximizes performance, while keeping the system execution safe. To control the system ordering, define explicit dependencies between systems and their sets.

§Using Bevy ECS

Bevy ECS should feel very natural for those familiar with Rust syntax:

usebevy_ecs::prelude::*;#[derive(Component)]structPosition { x: f32, y: f32 }#[derive(Component)]structVelocity { x: f32, y: f32 }// This system moves each entity with a Position and Velocity componentfnmovement(mutquery: Query<(&mutPosition,&Velocity)>) {for(mutposition, velocity)in&mutquery {        position.x += velocity.x;        position.y += velocity.y;    }}fnmain() {// Create a new empty World to hold our Entities and Componentsletmutworld = World::new();// Spawn an entity with Position and Velocity componentsworld.spawn((        Position { x:0.0, y:0.0},        Velocity { x:1.0, y:0.0},    ));// Create a new Schedule, which defines an execution strategy for Systemsletmutschedule = Schedule::default();// Add our system to the scheduleschedule.add_systems(movement);// Run the schedule once. If your app has a "loop", you would run this once per loopschedule.run(&mutworld);}

§Features

§Query Filters

usebevy_ecs::prelude::*;#[derive(Component)]structPosition { x: f32, y: f32 }#[derive(Component)]structPlayer;#[derive(Component)]structAlive;// Gets the Position component of all Entities with Player component and without the Alive// component.fnsystem(query: Query<&Position, (With<Player>, Without<Alive>)>) {forpositionin&query {    }}

§Change Detection

Bevy ECS tracksall changes to Components and Resources.

Queries can filter for changed Components:

usebevy_ecs::prelude::*;#[derive(Component)]structPosition { x: f32, y: f32 }#[derive(Component)]structVelocity { x: f32, y: f32 }// Gets the Position component of all Entities whose Velocity has changed since the last run of the Systemfnsystem_changed(query: Query<&Position, Changed<Velocity>>) {forpositionin&query {    }}// Gets the Position component of all Entities that had a Velocity component added since the last run of the Systemfnsystem_added(query: Query<&Position, Added<Velocity>>) {forpositionin&query {    }}

Resources also expose change state:

usebevy_ecs::prelude::*;#[derive(Resource)]structTime(f32);// Prints "time changed!" if the Time resource has changed since the last run of the Systemfnsystem(time: Res<Time>) {iftime.is_changed() {println!("time changed!");    }}

§Component Storage

Bevy ECS supports multiple component storage types.

Components can be stored in:

  • Tables: Fast and cache friendly iteration, but slower adding and removing of components. This is the default storage type.
  • Sparse Sets: Fast adding and removing of components, but slower iteration.

Component storage types are configurable, and they default to table storage if the storage is not manually defined.

usebevy_ecs::prelude::*;#[derive(Component)]structTableStoredComponent;#[derive(Component)]#[component(storage ="SparseSet")]structSparseStoredComponent;

§Component Bundles

Define sets of Components that should be added together.

usebevy_ecs::prelude::*;#[derive(Default, Component)]structPlayer;#[derive(Default, Component)]structPosition { x: f32, y: f32 }#[derive(Default, Component)]structVelocity { x: f32, y: f32 }#[derive(Bundle, Default)]structPlayerBundle {    player: Player,    position: Position,    velocity: Velocity,}letmutworld = World::new();// Spawn a new entity and insert the default PlayerBundleworld.spawn(PlayerBundle::default());// Bundles play well with Rust's struct update syntaxworld.spawn(PlayerBundle {    position: Position { x:1.0, y:1.0},    ..Default::default()});

§Messages

Messages offer a communication channel between one or more systems.They can be sent using theMessageWriter system parameter and received withMessageReader.

usebevy_ecs::prelude::*;#[derive(Message)]structMessage(String);fnwriter(mutwriter: MessageWriter<Message>) {    writer.write(Message("Hello!".to_string()));}fnreader(mutreader: MessageReader<Message>) {forMessage(message)inreader.read() {println!("{}", message);    }}

§Observers

Observers are systems that watch for a “trigger” of a specificEvent:

usebevy_ecs::prelude::*;#[derive(Event)]structSpeak {    message: String}letmutworld = World::new();world.add_observer(|event: On<Speak>| {println!("{}", event.message);});world.trigger(Speak {    message:"Hello!".to_string(),});

These differ fromMessageReader andMessageWriter in that they are “reactive”.Rather than happening at a specific point in a schedule, they happenimmediately whenever a trigger happens.Triggers can trigger other triggers, and they all will be evaluated at the same time!

If the event is anEntityEvent, it can also be triggered to target specific entities:

usebevy_ecs::prelude::*;#[derive(EntityEvent)]structExplode {    entity: Entity,}letmutworld = World::new();letentity = world.spawn_empty().id();world.add_observer(|explode: On<Explode>,mutcommands: Commands| {println!("Entity {} goes BOOM!", explode.entity);    commands.entity(explode.entity).despawn();});world.trigger(Explode { entity });

Re-exports§

pub usebevy_ptr as ptr;

Modules§

archetype
Types for definingArchetypes, collections of entities that have the same set ofcomponents.
batching
Types for controlling batching behavior during parallel processing.
bundle
Types for handlingBundles.
change_detection
Types that detect when their internal data mutate.
component
Types for declaring and storingComponents.
entity
Entity handling types.
entity_disabling
Disabled entities do not show up in queries unless the query explicitly mentions them.
error
Error handling for Bevy systems, commands, and observers.
event
Event functionality.
hierarchy
The canonical “parent-child”Relationship for entities, driven bytheChildOfRelationship and theChildrenRelationshipTarget.
intern
Provides types used to statically intern immutable values.
label
Traits used by label implementations
lifecycle
This module contains various tools to allow you to react to component insertion or removal,as well as entity spawning and despawning.
message
Message functionality.
name
Provides theNameComponent, used for identifying anEntity.
never
A workaround for the! type in stable Rust.
observer
Observers are a push-based tool for responding toEvents. TheObserver component holds aSystem that runs whenever a matchingEventis triggered.
prelude
The ECS prelude.
query
Contains APIs for retrieving component data from the world.
reflectbevy_reflect
Types that enable reflection support.
relationship
This module provides functionality to link entities to each other using specialized components called “relationships”. See theRelationship trait for more info.
resource
Resources are unique, singleton-like data types that can be accessed from systems and stored in theWorld.
schedule
Contains APIs for ordering systems and executing them on aWorld
spawn
Entity spawning abstractions, largely focused on spawning related hierarchies of entities. Seerelated andSpawnRelatedfor the best entry points into these APIs and examples of how to use them.
storage
Storage layouts for ECS data.
system
Tools for controlling behavior in an ECS application.
traversal
A trait for components that let you traverse the ECS.
world
Defines theWorld and APIs for accessing it directly.

Macros§

children
Returns aSpawnRelatedBundle that will insert theChildren component, spawn aSpawnableList of entities with given bundles thatrelate to theChildren entity via theChildOf component, and reserve space in theChildren for each spawned entity.
define_label
Macro to define a new label trait
related
Returns aSpawnRelatedBundle that will insert the givenRelationshipTarget, spawn aSpawnableList of entities with given bundles thatrelate to theRelationshipTarget entity via theRelationshipTarget::Relationship component, and reserve space in theRelationshipTarget for each spawned entity.

Structs§

HotPatchChangeshotpatching
Resource which “changes” when a hotpatch happens.
HotPatchedhotpatching
Event sent when a hotpatch happens.

[8]ページ先頭

©2009-2025 Movatter.jp