1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
//! Renderer-independent application runner and its public frame diagnostics.
//!
//! The runner owns application state; private runtime modules coordinate frame
//! stages, World lifecycle, input publication, and CPU rendering snapshots.
use crate::{
ExtractedFrame,
app::RegisteredWorldFactory,
assets::{ImageAsset, ImageAssetId, ImageAssetRegistry},
component::ComponentRegistry,
events::EventRegistry,
extraction::ExtractionBuffers,
identity::{ApplicationId, LogicEntity, ManagedEntity, WorldFactoryId, WorldGeneration},
input::{Action, InputState},
query::QueryEntityError,
resources::ApplicationResourceRegistry,
system::StageFactories,
time::{TimeConfigurationError, TimeState},
};
#[path = "runtime/mod.rs"]
mod runtime;
use runtime::RuntimeWorld;
pub use runtime::reports::{
BeginFrameRejection, CandidateFailure, FrameFailure, FrameOutcome, FrameRequest,
FrameTransition, LifecycleEvent, LifecycleRecord, LogicFrameReport, RunnerBuildError,
TransitionRequestFailure,
};
/// Renderer-independent Sim;Logic runner used by tests and desktop adapters.
pub struct HeadlessRunner<A: Action> {
application: ApplicationId,
config: crate::app::AppConfig,
components: ComponentRegistry,
events: EventRegistry,
application_resources: ApplicationResourceRegistry,
images: ImageAssetRegistry,
#[cfg(feature = "headless-text")]
texts: crate::text::TextRegistry,
factories: Vec<RegisteredWorldFactory>,
startup_factories: StageFactories,
fixed_factories: StageFactories,
frame_factories: StageFactories,
active: RuntimeWorld,
input: InputState<A>,
time: TimeState,
frame_index: u64,
next_generation: u64,
extraction: ExtractionBuffers,
lifecycle: Vec<LifecycleRecord>,
dropped_lifecycle_records: u64,
}
impl<A: Action> HeadlessRunner<A> {
/// Reads registered immutable pixels, including assets not currently drawn.
///
/// Foreign handles return None. Asset identity and contents survive World
/// replacement; inspection never initializes a renderer or decodes a file.
pub fn image_asset(&self, image: ImageAssetId) -> Option<&ImageAsset> {
self.images.get(image)
}
/// Returns immutable setup-time image registrations, including unused assets.
pub fn image_asset_count(&self) -> usize {
self.images.len()
}
/// Returns CPU pixel Vec capacity retained by registered image assets.
///
/// This excludes bounded registry metadata and the desktop renderer's
/// separate recovery copies and GPU textures. It is not total process memory.
pub fn image_pixel_bytes(&self) -> usize {
self.images.pixel_bytes()
}
/// Returns setup-time font registrations, including fonts not drawn.
#[cfg(feature = "headless-text")]
pub fn text_font_count(&self) -> usize {
self.texts.len()
}
/// Returns source font Vec capacity, excluding parser metadata and GPU caches.
#[cfg(feature = "headless-text")]
pub fn text_font_bytes(&self) -> usize {
self.texts.font_bytes()
}
#[cfg(feature = "desktop")]
pub(crate) const fn image_assets(&self) -> &ImageAssetRegistry {
&self.images
}
/// Returns the last atomically published CPU snapshot.
///
/// The value may belong to a retired generation and is then diagnostic
/// history only. A renderer must compare its generation immediately before
/// submission.
pub const fn extracted_frame(&self) -> Option<&ExtractedFrame> {
self.extraction.published()
}
/// Returns the currently active World generation.
pub const fn world_generation(&self) -> WorldGeneration {
self.active.generation
}
/// Returns application-owned WorldEnter/WorldExit trace records.
pub fn lifecycle(&self) -> &[LifecycleRecord] {
&self.lifecycle
}
/// Returns records evicted from the bounded lifecycle trace.
pub const fn dropped_lifecycle_records(&self) -> u64 {
self.dropped_lifecycle_records
}
/// Resolves a factory handle to its bounded human-readable route name.
///
/// The name is diagnostic metadata only; transition identity continues to
/// use the opaque [`WorldFactoryId`]. Foreign or stale handles return
/// `None`.
pub fn factory_name(&self, factory: WorldFactoryId) -> Option<&str> {
self.factories
.iter()
.find(|registered| registered.id == factory)
.map(|registered| registered.diagnostic_name.as_str())
}
/// Returns the diagnostic route name of the active World.
pub fn active_world_name(&self) -> &str {
self.factory_name(self.active.factory)
.unwrap_or("<runtime-invariant-violation>")
}
/// Reads one typed Resource without exposing the raw Bevy World.
pub fn resource<R: bevy_ecs::prelude::Resource>(&self) -> Option<&R> {
self.active.world.get_resource::<R>()
}
/// Reads one Application Resource without exposing its private ECS slot.
///
/// Unlike [`Self::resource`], this value survives successful World
/// replacement. Inspection is read-only so tests cannot bypass normal
/// System ordering and mutation rules.
pub fn app_resource<T: Send + Sync + 'static>(&self) -> Option<&T> {
self.application_resources.get::<T>(&self.active.world)
}
// Only the runtime/desktop boundary acknowledges capture. This is not a
// public escape hatch for mutating arbitrary resources outside scheduling.
pub(crate) fn with_pointer_capture<R>(
&mut self,
update: impl FnOnce(&mut crate::input::PointerCapture) -> R,
) -> Option<R> {
self.application_resources
.with_mut(&mut self.active.world, update)
}
#[cfg(feature = "desktop")]
pub(crate) fn with_presentation_feedback<R>(
&mut self,
update: impl FnOnce(&mut crate::render::PresentationFeedback) -> R,
) -> Option<R> {
self.application_resources
.with_mut(&mut self.active.world, update)
}
#[cfg(feature = "desktop")]
pub(crate) fn with_window_controls<R>(
&mut self,
update: impl FnOnce(&mut crate::window::WindowControls) -> R,
) -> Option<R> {
self.application_resources
.with_mut(&mut self.active.world, update)
}
/// Iterates over one component type for read-only headless inspection.
///
/// Results include only managed logical entities, including entities with
/// the standard Bevy [`Disabled`](bevy_ecs::entity_disabling::Disabled)
/// component. Their order is not a
/// deterministic API; tests with order-dependent assertions must sort by
/// their own stable application data.
pub fn components<T: bevy_ecs::prelude::Component>(
&self,
) -> impl Iterator<Item = (crate::identity::LogicEntity, &T)> {
self.active.world.iter_entities().filter_map(|entity| {
let identity = entity.get::<ManagedEntity>()?.handle(entity.id());
let component = entity.get::<T>()?;
Some((identity, component))
})
}
/// Reads one component from a managed entity in the active World.
///
/// Application and World-generation provenance are checked before the raw
/// ECS slot is touched, and the private runtime identity in that slot must
/// still equal `entity`. Disabled managed entities remain inspectable here,
/// matching [`Self::components`]. A missing entity or component returns
/// [`QueryEntityError::DoesNotMatch`].
pub fn component<T: bevy_ecs::prelude::Component>(
&self,
entity: LogicEntity,
) -> Result<&T, QueryEntityError> {
if entity.application() != self.application
|| entity.world_generation() != self.active.generation
{
return Err(QueryEntityError::ForeignWorld {
entity,
active: self.active.generation,
});
}
let managed_matches = self
.active
.world
.get::<ManagedEntity>(entity.entity())
.is_some_and(|managed| managed.handle(entity.entity()) == entity);
if !managed_matches {
return Err(QueryEntityError::DoesNotMatch { entity });
}
self.active
.world
.get::<T>(entity.entity())
.ok_or(QueryEntityError::DoesNotMatch { entity })
}
/// Pauses or resumes fixed simulation. FrameUpdate and FrameInput continue.
///
/// Entering pause snaps visual interpolation to current canonical entity
/// translations and camera centers, and discards undelivered fixed-input
/// edges. Accumulated fixed time is preserved and becomes eligible again
/// after resume; wall time supplied while paused is not accumulated.
pub fn set_paused(&mut self, paused: bool) {
let entering_pause = paused && !self.time.is_paused();
self.time.set_paused(paused);
if entering_pause {
self.input.discard_fixed_edges();
self.active.snap_interpolation();
}
}
/// Returns whether fixed simulation is currently paused.
pub const fn is_paused(&self) -> bool {
self.time.is_paused()
}
/// Changes the multiplier applied to future fixed-time accumulation.
///
/// FrameUpdate continues to receive unscaled wall time.
pub fn set_time_scale(&mut self, time_scale: f64) -> Result<(), TimeConfigurationError> {
self.time.set_time_scale(time_scale)
}
}