Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add no_std support to bevy_ecs #16758

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 62 additions & 16 deletions crates/bevy_ecs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,39 +11,85 @@ categories = ["game-engines", "data-structures"]
rust-version = "1.81.0"

[features]
default = ["bevy_reflect"]
trace = []
default = ["std", "bevy_reflect", "async_executor"]
std = [
"bevy_reflect?/std",
"bevy_tasks/std",
"bevy_utils/std",
"bitflags/std",
"concurrent-queue/std",
"disqualified/alloc",
"fixedbitset/std",
"indexmap/std",
"serde?/std",
"nonmax/std",
"arrayvec?/std",
"log/std",
]
trace = ["std", "dep:tracing", "bevy_utils/tracing"]
multi_threaded = ["bevy_tasks/multi_threaded", "arrayvec"]
bevy_debug_stepping = []
serialize = ["dep:serde"]
serialize = ["dep:serde", "bevy_utils/serde"]
track_change_detection = []
reflect_functions = ["bevy_reflect", "bevy_reflect/functions"]
detailed_trace = []
detailed_trace = ["trace"]
arrayvec = ["dep:arrayvec"]
async_executor = ["bevy_tasks/async_executor"]
edge_executor = ["bevy_tasks/edge_executor"]
critical-section = [
"dep:critical-section",
"bevy_tasks/critical-section",
"portable-atomic?/critical-section",
]
portable-atomic = [
"dep:portable-atomic",
"dep:portable-atomic-util",
"bevy_tasks/portable-atomic",
"concurrent-queue/portable-atomic",
]
Comment on lines +39 to +49
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These features allow compiling on platforms without full support for atomics. Currently, they just enable features in our other dependencies and provide a couple of shims for things like Arc. In the future, we may be able to better leverage critical-section for other operations synchronisation areas.


[dependencies]
bevy_ptr = { path = "../bevy_ptr", version = "0.15.0-dev" }
bevy_reflect = { path = "../bevy_reflect", version = "0.15.0-dev", optional = true }
bevy_tasks = { path = "../bevy_tasks", version = "0.15.0-dev" }
bevy_utils = { path = "../bevy_utils", version = "0.15.0-dev" }
bevy_reflect = { path = "../bevy_reflect", version = "0.15.0-dev", default-features = false, optional = true }
bevy_tasks = { path = "../bevy_tasks", version = "0.15.0-dev", default-features = false }
bevy_utils = { path = "../bevy_utils", version = "0.15.0-dev", default-features = false, features = [
"alloc",
] }
bevy_ecs_macros = { path = "macros", version = "0.15.0-dev" }

bitflags = "2.3"
concurrent-queue = "2.5.0"
disqualified = "1.0"
fixedbitset = "0.5"
serde = { version = "1", optional = true, default-features = false }
bitflags = { version = "2.3", default-features = false }
concurrent-queue = { version = "2.5.0", default-features = false }
disqualified = { version = "1.0", default-features = false }
fixedbitset = { version = "0.5", default-features = false }
serde = { version = "1", default-features = false, features = [
"alloc",
], optional = true }
thiserror = { version = "2", default-features = false }
derive_more = { version = "1", default-features = false, features = [
"from",
"display",
"into",
"as_ref",
] }
nonmax = "0.5"
arrayvec = { version = "0.7.4", optional = true }
nonmax = { version = "0.5", default-features = false }
arrayvec = { version = "0.7.4", default-features = false, optional = true }
smallvec = { version = "1", features = ["union"] }
indexmap = { version = "2.5.0", default-features = false, features = ["std"] }
variadics_please = "1.0"
indexmap = { version = "2.5.0", default-features = false }
variadics_please = { version = "1.0", default-features = false }
critical-section = { version = "1.2.0", optional = true }
portable-atomic = { version = "1", default-features = false, features = [
"fallback",
], optional = true }
portable-atomic-util = { version = "0.2.4", features = [
"alloc",
], optional = true }
spin = { version = "0.9.8", default-features = false, features = [
"spin_mutex",
"rwlock",
"once",
] }
tracing = { version = "0.1", default-features = false, optional = true }
log = { version = "0.4", default-features = false }
Comment on lines +91 to +92
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previously, tracing was being brought in via a re-export from bevy_utils. I have opted to flatten this dependency, as in general flatter dependency graphs yield faster compilation times. Additionally, I'm bringing in log to allow the basic logging (warn!, trace!, etc.) to work on platforms tracing does not support.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should swap to a workspace dependency IMO: synchronizing these manually is silly. But that probably warrants its own independent discussion.


[dev-dependencies]
rand = "0.8"
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_ecs/macros/src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ pub fn derive_component(input: TokenStream) -> TokenStream {
storages: &mut #bevy_ecs_path::storage::Storages,
required_components: &mut #bevy_ecs_path::component::RequiredComponents,
inheritance_depth: u16,
recursion_check_stack: &mut Vec<#bevy_ecs_path::component::ComponentId>
recursion_check_stack: &mut #bevy_ecs_path::__macro_exports::Vec<#bevy_ecs_path::component::ComponentId>
) {
#bevy_ecs_path::component::enforce_no_required_components_recursion(components, recursion_check_stack);
let self_id = components.register_component::<Self>(storages);
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_ecs/src/archetype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use crate::{
observer::Observers,
storage::{ImmutableSparseSet, SparseArray, SparseSet, SparseSetIndex, TableId, TableRow},
};
use alloc::{boxed::Box, vec::Vec};
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Most files have changed that look like this; just including items that were previously implicitly available.

use bevy_utils::HashMap;
use core::{
hash::Hash,
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_ecs/src/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use crate::{
storage::{SparseSetIndex, SparseSets, Storages, Table, TableRow},
world::{unsafe_world_cell::UnsafeWorldCell, ON_ADD, ON_INSERT, ON_REPLACE},
};
use alloc::{boxed::Box, vec, vec::Vec};
use bevy_ptr::{ConstNonNull, OwningPtr};
use bevy_utils::{HashMap, HashSet, TypeIdMap};
#[cfg(feature = "track_change_detection")]
Expand Down
100 changes: 70 additions & 30 deletions crates/bevy_ecs/src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::{
system::{Local, Resource, SystemParam},
world::{DeferredWorld, FromWorld, World},
};
use alloc::{borrow::Cow, sync::Arc};
use alloc::{borrow::Cow, format, vec::Vec};
pub use bevy_ecs_macros::Component;
use bevy_ptr::{OwningPtr, UnsafeCellDeref};
#[cfg(feature = "bevy_reflect")]
Expand All @@ -30,6 +30,12 @@ use core::{
use disqualified::ShortName;
use thiserror::Error;

#[cfg(feature = "portable-atomic")]
use portable_atomic_util::Arc;

#[cfg(not(feature = "portable-atomic"))]
use alloc::sync::Arc;
Comment on lines +33 to +37
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For a handful of atomic types, this kind of feature gating is required to support platforms without full native atomic support. In general, portable-atomic is a drop-in replacement for alloc::sync.


pub use bevy_ecs_macros::require;

/// A data type that can be used to store data for an [entity].
Expand Down Expand Up @@ -2005,35 +2011,69 @@ impl RequiredComponents {
constructor: fn() -> C,
inheritance_depth: u16,
) {
let erased: RequiredComponentConstructor = RequiredComponentConstructor(Arc::new(
move |table,
sparse_sets,
change_tick,
table_row,
entity,
#[cfg(feature = "track_change_detection")] caller| {
OwningPtr::make(constructor(), |ptr| {
// SAFETY: This will only be called in the context of `BundleInfo::write_components`, which will
// pass in a valid table_row and entity requiring a C constructor
// C::STORAGE_TYPE is the storage type associated with `component_id` / `C`
// `ptr` points to valid `C` data, which matches the type associated with `component_id`
unsafe {
BundleInfo::initialize_required_component(
table,
sparse_sets,
change_tick,
table_row,
entity,
component_id,
C::STORAGE_TYPE,
ptr,
#[cfg(feature = "track_change_detection")]
caller,
);
}
});
},
));
let erased: RequiredComponentConstructor = RequiredComponentConstructor({
// `portable-atomic-util` `Arc` is not able to coerce an unsized
// type like `std::sync::Arc` can. Creating a `Box` first does the
// coercion.
//
// This would be resolved by https://github.com/rust-lang/rust/issues/123430
Comment on lines +2015 to +2019
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This area is a little frustrating. In short, std::sync::Arc has certain privileges that portable_atomic_util::Arc doesn't, the key one being unsized coercion. To work around this, we first create a Box (which can do the coercion), and then create an Arc from that box. This code is a little verbose to handle the 2×2 feature matrix of tracking changes and portable atomics while also ensuring the Box workaround is only used when portable-atomic is enabled.


#[cfg(feature = "portable-atomic")]
use alloc::boxed::Box;

#[cfg(feature = "track_change_detection")]
type Constructor = dyn for<'a, 'b> Fn(
&'a mut Table,
&'b mut SparseSets,
Tick,
TableRow,
Entity,
&'static Location<'static>,
);

#[cfg(not(feature = "track_change_detection"))]
type Constructor =
dyn for<'a, 'b> Fn(&'a mut Table, &'b mut SparseSets, Tick, TableRow, Entity);

#[cfg(feature = "portable-atomic")]
type Intermediate<T> = Box<T>;

#[cfg(not(feature = "portable-atomic"))]
type Intermediate<T> = Arc<T>;

let boxed: Intermediate<Constructor> = Intermediate::new(
move |table,
sparse_sets,
change_tick,
table_row,
entity,
#[cfg(feature = "track_change_detection")] caller| {
OwningPtr::make(constructor(), |ptr| {
// SAFETY: This will only be called in the context of `BundleInfo::write_components`, which will
// pass in a valid table_row and entity requiring a C constructor
// C::STORAGE_TYPE is the storage type associated with `component_id` / `C`
// `ptr` points to valid `C` data, which matches the type associated with `component_id`
unsafe {
BundleInfo::initialize_required_component(
table,
sparse_sets,
change_tick,
table_row,
entity,
component_id,
C::STORAGE_TYPE,
ptr,
#[cfg(feature = "track_change_detection")]
caller,
);
}
});
},
);

Arc::from(boxed)
});

// SAFETY:
// `component_id` matches the type initialized by the `erased` constructor above.
// `erased` initializes a component for `component_id` in such a way that
Expand Down
8 changes: 7 additions & 1 deletion crates/bevy_ecs/src/entity/clone_entities.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::any::TypeId;

use bevy_utils::{HashMap, HashSet};

#[cfg(feature = "portable-atomic")]
use portable_atomic_util::Arc;

#[cfg(not(feature = "portable-atomic"))]
use alloc::sync::Arc;

use crate::{
bundle::Bundle,
component::{component_clone_ignore, Component, ComponentCloneHandler, ComponentId},
Expand Down
19 changes: 15 additions & 4 deletions crates/bevy_ecs/src/entity/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ pub use visit_entities::*;
mod hash;
pub use hash::*;

use bevy_utils::tracing::warn;
use alloc::vec::Vec;
use log::warn;

use crate::{
archetype::{ArchetypeId, ArchetypeRow},
Expand All @@ -61,20 +62,30 @@ use crate::{
},
storage::{SparseSetIndex, TableId, TableRow},
};
use core::{fmt, hash::Hash, mem, num::NonZero, sync::atomic::Ordering};
use core::{fmt, hash::Hash, mem, num::NonZero};
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};

#[cfg(target_has_atomic = "64")]
#[cfg(not(feature = "portable-atomic"))]
use core::sync::atomic::Ordering;

#[cfg(feature = "portable-atomic")]
use portable_atomic::Ordering;

#[cfg(all(target_has_atomic = "64", not(feature = "portable-atomic")))]
use core::sync::atomic::AtomicI64 as AtomicIdCursor;
#[cfg(all(target_has_atomic = "64", feature = "portable-atomic"))]
use portable_atomic::AtomicI64 as AtomicIdCursor;
#[cfg(target_has_atomic = "64")]
type IdCursor = i64;

/// Most modern platforms support 64-bit atomics, but some less-common platforms
/// do not. This fallback allows compilation using a 32-bit cursor instead, with
/// the caveat that some conversions may fail (and panic) at runtime.
#[cfg(not(target_has_atomic = "64"))]
#[cfg(all(not(target_has_atomic = "64"), not(feature = "portable-atomic")))]
use core::sync::atomic::AtomicIsize as AtomicIdCursor;
#[cfg(all(not(target_has_atomic = "64"), feature = "portable-atomic"))]
use portable_atomic::AtomicIsize as AtomicIdCursor;
Comment on lines -76 to +88
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't tried it, but I believe using portable-atomic may allow access to an AtomicI64 on all platforms, removing the possible panic. This should be investigated in a follow-up PR.

#[cfg(not(target_has_atomic = "64"))]
type IdCursor = isize;

Expand Down
8 changes: 5 additions & 3 deletions crates/bevy_ecs/src/event/collections.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use crate as bevy_ecs;
use alloc::vec::Vec;
use bevy_ecs::{
event::{Event, EventCursor, EventId, EventInstance},
system::Resource,
};
use bevy_utils::detailed_trace;
use core::{
marker::PhantomData,
ops::{Deref, DerefMut},
Expand Down Expand Up @@ -125,7 +125,8 @@ impl<E: Event> Events<E> {
id: self.event_count,
_marker: PhantomData,
};
detailed_trace!("Events::send() -> id: {}", event_id);
#[cfg(feature = "detailed_trace")]
tracing::trace!("Events::send() -> id: {}", event_id);

let event_instance = EventInstance { event_id, event };

Expand Down Expand Up @@ -318,7 +319,8 @@ impl<E: Event> Extend<E> for Events<E> {
self.events_b.extend(events);

if old_count != event_count {
detailed_trace!(
#[cfg(feature = "detailed_trace")]
tracing::trace!(
"Events::extend() -> ids: ({}..{})",
self.event_count,
event_count
Expand Down
4 changes: 2 additions & 2 deletions crates/bevy_ecs/src/event/iterators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use crate as bevy_ecs;
#[cfg(feature = "multi_threaded")]
use bevy_ecs::batching::BatchingStrategy;
use bevy_ecs::event::{Event, EventCursor, EventId, EventInstance, Events};
use bevy_utils::detailed_trace;
use core::{iter::Chain, slice::Iter};

/// An iterator that yields any unread events from an [`EventReader`](super::EventReader) or [`EventCursor`].
Expand Down Expand Up @@ -92,7 +91,8 @@ impl<'a, E: Event> Iterator for EventIteratorWithId<'a, E> {
.map(|instance| (&instance.event, instance.event_id))
{
Some(item) => {
detailed_trace!("EventReader::iter() -> {}", item.1);
#[cfg(feature = "detailed_trace")]
tracing::trace!("EventReader::iter() -> {}", item.1);
self.reader.last_event_count += 1;
self.unread -= 1;
Some(item)
Expand Down
4 changes: 2 additions & 2 deletions crates/bevy_ecs/src/event/mut_iterators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use crate as bevy_ecs;
#[cfg(feature = "multi_threaded")]
use bevy_ecs::batching::BatchingStrategy;
use bevy_ecs::event::{Event, EventCursor, EventId, EventInstance, Events};
use bevy_utils::detailed_trace;
use core::{iter::Chain, slice::IterMut};

/// An iterator that yields any unread events from an [`EventMutator`] or [`EventCursor`].
Expand Down Expand Up @@ -95,7 +94,8 @@ impl<'a, E: Event> Iterator for EventMutIteratorWithId<'a, E> {
.map(|instance| (&mut instance.event, instance.event_id))
{
Some(item) => {
detailed_trace!("EventMutator::iter() -> {}", item.1);
#[cfg(feature = "detailed_trace")]
tracing::trace!("EventMutator::iter() -> {}", item.1);
self.mutator.last_event_count += 1;
self.unread -= 1;
Some(item)
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_ecs/src/event/registry.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate as bevy_ecs;
use alloc::vec::Vec;
use bevy_ecs::{
change_detection::{DetectChangesMut, MutUntyped},
component::{ComponentId, Tick},
Expand Down
Loading
Loading