Skip to main content

sim_logic/ecs/
commands.rs

1//! Bounded managed structural, World-transition, and application-control commands.
2
3use std::{
4    collections::{HashMap, HashSet},
5    error::Error,
6    fmt,
7};
8
9use bevy_ecs::{
10    bundle::{Bundle, NoBundleEffect},
11    component::ComponentId,
12    entity::Entity,
13    entity_disabling::Disabled,
14    prelude::{ResMut, Resource},
15    system::SystemParam,
16    world::World,
17};
18
19use crate::{
20    component::{ApprovedComponents, ComponentApprovalError},
21    identity::{
22        ApplicationId, LogicEntity, ManagedEntity, TransitionIntentToken, WorldFactoryId,
23        WorldGeneration,
24    },
25    transition::TransitionRequest,
26    visual::{ActiveCamera2d, Transform2d},
27};
28
29/// Failure to create an intent or request another bounded stage command.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum CommandEnqueueError {
33    /// The configured command-count limit has been reached.
34    LimitExceeded {
35        /// Frozen maximum command count for one stage.
36        limit: usize,
37    },
38    /// The queue could not reserve storage for one more command.
39    AllocationFailed,
40    /// The direct intent occurrence counter is exhausted.
41    IntentIdentityExhausted,
42    /// Direct intents are unavailable outside an active application frame.
43    IntentUnavailable,
44    /// Application exit cannot be requested during isolated World Startup.
45    ExitUnavailable,
46    /// Fixed simulation pause cannot be changed during isolated World Startup.
47    PauseUnavailable,
48}
49
50impl fmt::Display for CommandEnqueueError {
51    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match self {
53            Self::LimitExceeded { limit } => {
54                write!(formatter, "stage command limit of {limit} was exceeded")
55            }
56            Self::AllocationFailed => {
57                formatter.write_str("failed to reserve storage for a stage command")
58            }
59            Self::IntentIdentityExhausted => {
60                formatter.write_str("direct transition intent identity space is exhausted")
61            }
62            Self::IntentUnavailable => {
63                formatter.write_str("direct transition intents are unavailable in this stage")
64            }
65            Self::ExitUnavailable => {
66                formatter.write_str("application exit is unavailable during World Startup")
67            }
68            Self::PauseUnavailable => {
69                formatter.write_str("fixed simulation pause is unavailable during World Startup")
70            }
71        }
72    }
73}
74
75impl Error for CommandEnqueueError {}
76
77/// Reason an entire structural stage batch was rejected before entity mutation.
78#[derive(Debug, Clone, PartialEq, Eq)]
79#[non_exhaustive]
80pub enum CommandBatchError {
81    /// At least one System attempted to exceed the configured command limit.
82    LimitExceeded {
83        /// Frozen maximum command count for one stage.
84        limit: usize,
85    },
86    /// Command queue storage could not be reserved.
87    AllocationFailed,
88    /// A structural-command target belongs to another application or World generation.
89    ForeignEntity {
90        /// Rejected opaque entity handle.
91        entity: LogicEntity,
92    },
93    /// A structural-command target no longer names a live entity.
94    MissingEntity {
95        /// Rejected opaque entity handle.
96        entity: LogicEntity,
97    },
98    /// The same entity was scheduled for despawn more than once.
99    DuplicateDespawn {
100        /// Duplicated opaque entity handle.
101        entity: LogicEntity,
102    },
103    /// One stage batch attempted to structurally change and despawn the same entity.
104    ConflictingEntityCommands {
105        /// Conflicted opaque entity handle.
106        entity: LogicEntity,
107    },
108    /// Applying every spawn would exceed the active-entity limit.
109    EntityLimitExceeded {
110        /// Frozen maximum live entity count.
111        limit: usize,
112        /// Live entity count the batch would produce.
113        requested: usize,
114    },
115    /// A retained component would lose one of its registered required components.
116    RequiredComponentWouldBeMissing {
117        /// Rejected opaque entity handle.
118        entity: LogicEntity,
119        /// Diagnostic name of the component that would be absent.
120        required: String,
121        /// Diagnostic name of the retained component that requires it.
122        required_by: String,
123    },
124    /// A structural bundle fell outside the frozen approved component set.
125    Component(ComponentApprovalError),
126}
127
128impl fmt::Display for CommandBatchError {
129    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
130        match self {
131            Self::LimitExceeded { limit } => {
132                write!(formatter, "stage command limit of {limit} was exceeded")
133            }
134            Self::AllocationFailed => {
135                formatter.write_str("failed to reserve command validation storage")
136            }
137            Self::ForeignEntity { entity } => {
138                write!(formatter, "entity {entity:?} belongs to another World")
139            }
140            Self::MissingEntity { entity } => {
141                write!(formatter, "entity {entity:?} is not alive")
142            }
143            Self::DuplicateDespawn { entity } => {
144                write!(
145                    formatter,
146                    "entity {entity:?} was scheduled for despawn twice"
147                )
148            }
149            Self::ConflictingEntityCommands { entity } => write!(
150                formatter,
151                "entity {entity:?} cannot be structurally changed and despawned in one stage"
152            ),
153            Self::EntityLimitExceeded { limit, requested } => write!(
154                formatter,
155                "structural batch would create {requested} live entities, above limit {limit}"
156            ),
157            Self::RequiredComponentWouldBeMissing {
158                entity,
159                required,
160                required_by,
161            } => write!(
162                formatter,
163                "entity {entity:?} would retain {required_by} without required component {required}"
164            ),
165            Self::Component(error) => write!(formatter, "structural bundle was rejected: {error}"),
166        }
167    }
168}
169
170impl Error for CommandBatchError {
171    fn source(&self) -> Option<&(dyn Error + 'static)> {
172        match self {
173            Self::Component(error) => Some(error),
174            _ => None,
175        }
176    }
177}
178
179trait ErasedSpawn: Send + Sync + 'static {
180    fn validate(
181        &self,
182        world: &mut World,
183        approved: &mut ApprovedComponents,
184    ) -> Result<(), ComponentApprovalError>;
185
186    fn apply(self: Box<Self>, world: &mut World, generation: WorldGeneration);
187}
188
189trait ErasedInsert: Send + Sync + 'static {
190    fn validate(
191        &self,
192        world: &mut World,
193        approved: &mut ApprovedComponents,
194    ) -> Result<(), ComponentApprovalError>;
195
196    fn record_presence(
197        &self,
198        world: &mut World,
199        entity: Entity,
200        overrides: &mut PresenceOverrides,
201        inserted_components: &mut Vec<(Entity, ComponentId)>,
202    ) -> Result<(), CommandBatchError>;
203
204    fn apply(self: Box<Self>, world: &mut World, entity: Entity);
205}
206
207type PresenceOverrides = HashMap<(Entity, ComponentId), bool>;
208type RemoveValidation =
209    fn(&mut World, &mut ApprovedComponents) -> Result<(), ComponentApprovalError>;
210type PresenceRecorder = fn(
211    &mut World,
212    Entity,
213    &mut PresenceOverrides,
214    &mut Vec<(Entity, ComponentId)>,
215) -> Result<(), CommandBatchError>;
216type RemoveApply = fn(&mut World, Entity);
217
218#[derive(Clone, Copy)]
219struct RemoveDescriptor {
220    validate: RemoveValidation,
221    record_presence: PresenceRecorder,
222    apply: RemoveApply,
223}
224
225impl RemoveDescriptor {
226    const fn new<B>() -> Self
227    where
228        B: Bundle<Effect: NoBundleEffect>,
229    {
230        Self {
231            validate: validate_remove_bundle::<B>,
232            record_presence: record_removed_bundle::<B>,
233            apply: apply_remove_bundle::<B>,
234        }
235    }
236}
237
238fn validate_remove_bundle<B>(
239    world: &mut World,
240    approved: &mut ApprovedComponents,
241) -> Result<(), ComponentApprovalError>
242where
243    B: Bundle<Effect: NoBundleEffect>,
244{
245    approved.validate_bundle::<B>(world)
246}
247
248fn record_removed_bundle<B>(
249    world: &mut World,
250    entity: Entity,
251    overrides: &mut PresenceOverrides,
252    _inserted_components: &mut Vec<(Entity, ComponentId)>,
253) -> Result<(), CommandBatchError>
254where
255    B: Bundle<Effect: NoBundleEffect>,
256{
257    let bundle = world.register_bundle::<B>();
258    overrides
259        .try_reserve(bundle.explicit_components().len())
260        .map_err(|_| CommandBatchError::AllocationFailed)?;
261    for component in bundle.explicit_components() {
262        overrides.insert((entity, *component), false);
263    }
264    Ok(())
265}
266
267fn apply_remove_bundle<B>(world: &mut World, entity: Entity)
268where
269    B: Bundle<Effect: NoBundleEffect>,
270{
271    world.entity_mut(entity).remove::<B>();
272}
273
274struct TypedSpawn<B>(B);
275
276impl<B> ErasedSpawn for TypedSpawn<B>
277where
278    B: Bundle<Effect: NoBundleEffect>,
279{
280    fn validate(
281        &self,
282        world: &mut World,
283        approved: &mut ApprovedComponents,
284    ) -> Result<(), ComponentApprovalError> {
285        approved.validate_bundle::<B>(world)
286    }
287
288    fn apply(self: Box<Self>, world: &mut World, generation: WorldGeneration) {
289        let _identity = apply_typed_spawn(world, self.0, generation);
290    }
291}
292
293struct TypedSpawnCopies<B> {
294    bundle: B,
295    count: usize,
296}
297
298impl<B> ErasedSpawn for TypedSpawnCopies<B>
299where
300    B: Bundle<Effect: NoBundleEffect> + Copy,
301{
302    fn validate(
303        &self,
304        world: &mut World,
305        approved: &mut ApprovedComponents,
306    ) -> Result<(), ComponentApprovalError> {
307        approved.validate_bundle::<B>(world)
308    }
309
310    fn apply(self: Box<Self>, world: &mut World, generation: WorldGeneration) {
311        for _ in 0..self.count {
312            let _identity = apply_typed_spawn(world, self.bundle, generation);
313        }
314    }
315}
316
317fn apply_typed_spawn<B>(world: &mut World, bundle: B, generation: WorldGeneration) -> LogicEntity
318where
319    B: Bundle<Effect: NoBundleEffect>,
320{
321    let managed = ManagedEntity::for_generation(generation);
322    let entity = world.spawn((bundle, managed)).id();
323    let identity = managed.handle(entity);
324    let mut entity = world.entity_mut(entity);
325    if let Some(mut transform) = entity.get_mut::<Transform2d>() {
326        transform.snap_interpolation();
327    }
328    if let Some(mut camera) = entity.get_mut::<ActiveCamera2d>() {
329        camera.snap_interpolation();
330    }
331    identity
332}
333
334struct TypedInsert<B>(B);
335
336impl<B> ErasedInsert for TypedInsert<B>
337where
338    B: Bundle<Effect: NoBundleEffect>,
339{
340    fn validate(
341        &self,
342        world: &mut World,
343        approved: &mut ApprovedComponents,
344    ) -> Result<(), ComponentApprovalError> {
345        approved.validate_bundle::<B>(world)
346    }
347
348    fn record_presence(
349        &self,
350        world: &mut World,
351        entity: Entity,
352        overrides: &mut PresenceOverrides,
353        inserted_components: &mut Vec<(Entity, ComponentId)>,
354    ) -> Result<(), CommandBatchError> {
355        let bundle = world.register_bundle::<B>();
356        overrides
357            .try_reserve(bundle.contributed_components().len())
358            .map_err(|_| CommandBatchError::AllocationFailed)?;
359        inserted_components
360            .try_reserve(bundle.contributed_components().len())
361            .map_err(|_| CommandBatchError::AllocationFailed)?;
362        for component in bundle.contributed_components() {
363            overrides.insert((entity, *component), true);
364            inserted_components.push((entity, *component));
365        }
366        Ok(())
367    }
368
369    fn apply(self: Box<Self>, world: &mut World, entity: Entity) {
370        let transform = world.component_id::<Transform2d>();
371        let camera = world.component_id::<ActiveCamera2d>();
372        let (explicit_transform, required_transform, explicit_camera, required_camera) = {
373            let info = world.register_bundle::<B>();
374            (
375                transform.is_some_and(|id| info.explicit_components().contains(&id)),
376                transform.is_some_and(|id| info.required_components().contains(&id)),
377                camera.is_some_and(|id| info.explicit_components().contains(&id)),
378                camera.is_some_and(|id| info.required_components().contains(&id)),
379            )
380        };
381        let target = world.entity(entity);
382        let snap_transform = explicit_transform
383            || required_transform && transform.is_some_and(|id| !target.contains_id(id));
384        let snap_camera =
385            explicit_camera || required_camera && camera.is_some_and(|id| !target.contains_id(id));
386
387        let mut target = world.entity_mut(entity);
388        target.insert(self.0);
389        if snap_transform && let Some(mut transform) = target.get_mut::<Transform2d>() {
390            transform.snap_interpolation();
391        }
392        if snap_camera && let Some(mut camera) = target.get_mut::<ActiveCamera2d>() {
393            camera.snap_interpolation();
394        }
395    }
396}
397
398enum QueuedCommand {
399    Spawn {
400        count: usize,
401        operation: Box<dyn ErasedSpawn>,
402    },
403    Insert {
404        entity: LogicEntity,
405        bundle: Box<dyn ErasedInsert>,
406    },
407    Remove {
408        entity: LogicEntity,
409        descriptor: RemoveDescriptor,
410    },
411    Despawn(LogicEntity),
412    ReplaceWorld(TransitionRequest),
413    SetPaused(bool),
414    Exit,
415}
416
417impl QueuedCommand {
418    fn spawn<B>(bundle: B) -> Self
419    where
420        B: Bundle<Effect: NoBundleEffect>,
421    {
422        Self::Spawn {
423            count: 1,
424            operation: Box::new(TypedSpawn(bundle)),
425        }
426    }
427}
428
429#[derive(Default)]
430struct CommandCounts {
431    spawns: usize,
432    removals: usize,
433    despawns: usize,
434    transitions: usize,
435    pause: Option<bool>,
436    exit_requested: bool,
437}
438
439#[derive(Debug, Clone, Copy, PartialEq, Eq)]
440enum QueuePoison {
441    LimitExceeded,
442    AllocationFailed,
443}
444
445#[derive(Resource)]
446pub(crate) struct CommandQueue {
447    commands: Vec<QueuedCommand>,
448    used_slots: usize,
449    despawns: HashSet<LogicEntity>,
450    component_targets: HashSet<Entity>,
451    component_target_order: Vec<Entity>,
452    inserted_components: Vec<(Entity, ComponentId)>,
453    presence_overrides: PresenceOverrides,
454    limit: usize,
455    poison: Option<QueuePoison>,
456}
457
458impl CommandQueue {
459    pub(crate) fn new(limit: usize) -> Self {
460        Self {
461            commands: Vec::new(),
462            used_slots: 0,
463            despawns: HashSet::new(),
464            component_targets: HashSet::new(),
465            component_target_order: Vec::new(),
466            inserted_components: Vec::new(),
467            presence_overrides: HashMap::new(),
468            limit,
469            poison: None,
470        }
471    }
472
473    fn push(&mut self, command: QueuedCommand) -> Result<(), CommandEnqueueError> {
474        self.push_weighted(command, 1)
475    }
476
477    fn push_weighted(
478        &mut self,
479        command: QueuedCommand,
480        slots: usize,
481    ) -> Result<(), CommandEnqueueError> {
482        let requested = self.prepare_push(slots)?;
483        self.commands.push(command);
484        self.used_slots = requested;
485        Ok(())
486    }
487
488    fn push_spawn_copies<B>(&mut self, bundle: B, count: usize) -> Result<(), CommandEnqueueError>
489    where
490        B: Bundle<Effect: NoBundleEffect> + Copy,
491    {
492        let requested = self.prepare_push(count)?;
493        self.commands.push(QueuedCommand::Spawn {
494            count,
495            operation: Box::new(TypedSpawnCopies { bundle, count }),
496        });
497        self.used_slots = requested;
498        Ok(())
499    }
500
501    fn prepare_push(&mut self, slots: usize) -> Result<usize, CommandEnqueueError> {
502        debug_assert_ne!(slots, 0);
503        let Some(requested) = self.used_slots.checked_add(slots) else {
504            self.poison = Some(QueuePoison::LimitExceeded);
505            return Err(CommandEnqueueError::LimitExceeded { limit: self.limit });
506        };
507        if requested > self.limit {
508            self.poison = Some(QueuePoison::LimitExceeded);
509            return Err(CommandEnqueueError::LimitExceeded { limit: self.limit });
510        }
511        if self.commands.try_reserve(1).is_err() {
512            self.poison = Some(QueuePoison::AllocationFailed);
513            return Err(CommandEnqueueError::AllocationFailed);
514        }
515        Ok(requested)
516    }
517
518    pub(crate) fn transition_requests(&self) -> impl Iterator<Item = TransitionRequest> + '_ {
519        self.commands.iter().filter_map(|command| match command {
520            QueuedCommand::ReplaceWorld(request) => Some(*request),
521            QueuedCommand::Spawn { .. }
522            | QueuedCommand::Insert { .. }
523            | QueuedCommand::Remove { .. }
524            | QueuedCommand::Despawn(_)
525            | QueuedCommand::SetPaused(_)
526            | QueuedCommand::Exit => None,
527        })
528    }
529
530    pub(crate) fn discard(&mut self) {
531        self.clear_reusing_storage();
532    }
533
534    pub(crate) fn validate_and_apply(
535        &mut self,
536        world: &mut World,
537        approved: &mut ApprovedComponents,
538        application: ApplicationId,
539        generation: WorldGeneration,
540        managed_entities: usize,
541        entity_limit: usize,
542    ) -> Result<CommittedCommands, CommandCommitError> {
543        let result = self.validate_and_apply_inner(
544            world,
545            approved,
546            application,
547            generation,
548            managed_entities,
549            entity_limit,
550        );
551        self.clear_reusing_storage();
552        result
553    }
554
555    fn validate_and_apply_inner(
556        &mut self,
557        world: &mut World,
558        approved: &mut ApprovedComponents,
559        application: ApplicationId,
560        generation: WorldGeneration,
561        managed_entities: usize,
562        entity_limit: usize,
563    ) -> Result<CommittedCommands, CommandCommitError> {
564        match self.poison {
565            Some(QueuePoison::LimitExceeded) => {
566                return Err(CommandBatchError::LimitExceeded { limit: self.limit }.into());
567            }
568            Some(QueuePoison::AllocationFailed) => {
569                return Err(CommandBatchError::AllocationFailed.into());
570            }
571            None => {}
572        }
573
574        let counts = self
575            .commands
576            .iter()
577            .fold(CommandCounts::default(), |mut counts, command| {
578                match command {
579                    QueuedCommand::Spawn { count, .. } => counts.spawns += count,
580                    QueuedCommand::Insert { .. } => {}
581                    QueuedCommand::Remove { .. } => counts.removals += 1,
582                    QueuedCommand::Despawn(_) => counts.despawns += 1,
583                    QueuedCommand::ReplaceWorld(_) => counts.transitions += 1,
584                    QueuedCommand::SetPaused(paused) => counts.pause = Some(*paused),
585                    QueuedCommand::Exit => counts.exit_requested = true,
586                }
587                counts
588            });
589
590        if counts.despawns != 0 {
591            self.despawns
592                .try_reserve(counts.despawns)
593                .map_err(|_| CommandBatchError::AllocationFailed)?;
594
595            for command in &self.commands {
596                if let QueuedCommand::Despawn(entity) = command {
597                    validate_target(world, application, generation, *entity)?;
598                    if !self.despawns.insert(*entity) {
599                        return Err(CommandBatchError::DuplicateDespawn { entity: *entity }.into());
600                    }
601                }
602            }
603        }
604
605        for command in &self.commands {
606            match command {
607                QueuedCommand::Spawn { operation, .. } => operation
608                    .validate(world, approved)
609                    .map_err(CommandBatchError::Component)?,
610                QueuedCommand::Insert { entity, bundle } => {
611                    validate_target(world, application, generation, *entity)?;
612                    if self.despawns.contains(entity) {
613                        return Err(CommandBatchError::ConflictingEntityCommands {
614                            entity: *entity,
615                        }
616                        .into());
617                    }
618                    bundle
619                        .validate(world, approved)
620                        .map_err(CommandBatchError::Component)?;
621                }
622                QueuedCommand::Remove { entity, descriptor } => {
623                    validate_target(world, application, generation, *entity)?;
624                    if self.despawns.contains(entity) {
625                        return Err(CommandBatchError::ConflictingEntityCommands {
626                            entity: *entity,
627                        }
628                        .into());
629                    }
630                    (descriptor.validate)(world, approved).map_err(CommandBatchError::Component)?;
631                }
632                QueuedCommand::Despawn(_) => {}
633                QueuedCommand::ReplaceWorld(_) => {}
634                QueuedCommand::SetPaused(_) => {}
635                QueuedCommand::Exit => {}
636            }
637        }
638
639        if counts.removals != 0 {
640            self.plan_component_presence(world, counts.removals)?;
641            validate_required_components(
642                world,
643                application,
644                generation,
645                &self.component_target_order,
646                &self.inserted_components,
647                &self.presence_overrides,
648            )?;
649        }
650
651        let retained = managed_entities
652            .checked_sub(counts.despawns)
653            .ok_or(CommandCommitError::RuntimeInvariant)?;
654        let requested =
655            retained
656                .checked_add(counts.spawns)
657                .ok_or(CommandBatchError::EntityLimitExceeded {
658                    limit: entity_limit,
659                    requested: usize::MAX,
660                })?;
661        if requested > entity_limit {
662            return Err(CommandBatchError::EntityLimitExceeded {
663                limit: entity_limit,
664                requested,
665            }
666            .into());
667        }
668
669        let mut spawned = 0;
670        let mut despawned = 0;
671        let mut transitions = Vec::new();
672        transitions
673            .try_reserve(counts.transitions)
674            .map_err(|_| CommandBatchError::AllocationFailed)?;
675
676        for command in self.commands.drain(..) {
677            match command {
678                QueuedCommand::Spawn { count, operation } => {
679                    operation.apply(world, generation);
680                    spawned += count;
681                }
682                QueuedCommand::Insert { entity, bundle } => {
683                    bundle.apply(world, entity.entity());
684                }
685                QueuedCommand::Remove { entity, descriptor } => {
686                    (descriptor.apply)(world, entity.entity());
687                }
688                QueuedCommand::Despawn(entity) => {
689                    let removed = world.despawn(entity.entity());
690                    debug_assert!(
691                        removed,
692                        "validated entity disappeared during command commit"
693                    );
694                    despawned += 1;
695                }
696                QueuedCommand::ReplaceWorld(request) => transitions.push(request),
697                QueuedCommand::SetPaused(_) => {}
698                QueuedCommand::Exit => {}
699            }
700        }
701
702        Ok(CommittedCommands {
703            spawned,
704            despawned,
705            live_entities: requested,
706            transitions,
707            pause: counts.pause,
708            exit_requested: counts.exit_requested,
709        })
710    }
711
712    fn plan_component_presence(
713        &mut self,
714        world: &mut World,
715        removal_count: usize,
716    ) -> Result<(), CommandBatchError> {
717        debug_assert_ne!(removal_count, 0);
718        self.component_targets
719            .try_reserve(removal_count)
720            .map_err(|_| CommandBatchError::AllocationFailed)?;
721        self.component_target_order
722            .try_reserve(removal_count)
723            .map_err(|_| CommandBatchError::AllocationFailed)?;
724
725        for command in &self.commands {
726            if let QueuedCommand::Remove { entity, .. } = command {
727                let raw = entity.entity();
728                if self.component_targets.insert(raw) {
729                    self.component_target_order.push(raw);
730                }
731            }
732        }
733
734        for command in &self.commands {
735            match command {
736                QueuedCommand::Insert { entity, bundle }
737                    if self.component_targets.contains(&entity.entity()) =>
738                {
739                    let raw = entity.entity();
740                    bundle.record_presence(
741                        world,
742                        raw,
743                        &mut self.presence_overrides,
744                        &mut self.inserted_components,
745                    )?;
746                }
747                QueuedCommand::Remove { entity, descriptor } => {
748                    let raw = entity.entity();
749                    (descriptor.record_presence)(
750                        world,
751                        raw,
752                        &mut self.presence_overrides,
753                        &mut self.inserted_components,
754                    )?;
755                }
756                QueuedCommand::Insert { .. }
757                | QueuedCommand::Spawn { .. }
758                | QueuedCommand::Despawn(_)
759                | QueuedCommand::ReplaceWorld(_)
760                | QueuedCommand::SetPaused(_)
761                | QueuedCommand::Exit => {}
762            }
763        }
764        Ok(())
765    }
766
767    fn clear_reusing_storage(&mut self) {
768        self.commands.clear();
769        self.used_slots = 0;
770        self.despawns.clear();
771        self.component_targets.clear();
772        self.component_target_order.clear();
773        self.inserted_components.clear();
774        self.presence_overrides.clear();
775        self.poison = None;
776    }
777
778    #[cfg(test)]
779    fn command_capacity(&self) -> usize {
780        self.commands.capacity()
781    }
782
783    #[cfg(test)]
784    fn despawn_capacity(&self) -> usize {
785        self.despawns.capacity()
786    }
787
788    #[cfg(test)]
789    fn component_target_capacity(&self) -> usize {
790        self.component_targets.capacity()
791    }
792
793    #[cfg(test)]
794    fn presence_override_capacity(&self) -> usize {
795        self.presence_overrides.capacity()
796    }
797
798    #[cfg(test)]
799    fn is_clean(&self) -> bool {
800        self.commands.is_empty()
801            && self.used_slots == 0
802            && self.despawns.is_empty()
803            && self.component_targets.is_empty()
804            && self.component_target_order.is_empty()
805            && self.inserted_components.is_empty()
806            && self.presence_overrides.is_empty()
807            && self.poison.is_none()
808    }
809}
810
811fn validate_required_components(
812    world: &World,
813    application: ApplicationId,
814    generation: WorldGeneration,
815    component_targets: &[Entity],
816    inserted_components: &[(Entity, ComponentId)],
817    overrides: &PresenceOverrides,
818) -> Result<(), CommandBatchError> {
819    for entity in component_targets {
820        let target = world.entity(*entity);
821        for component in target.archetype().iter_components() {
822            if final_component_presence(world, *entity, component, overrides) {
823                validate_retained_requirements(
824                    world,
825                    application,
826                    generation,
827                    *entity,
828                    component,
829                    overrides,
830                )?;
831            }
832        }
833    }
834
835    for &(entity, component) in inserted_components {
836        if final_component_presence(world, entity, component, overrides) {
837            validate_retained_requirements(
838                world,
839                application,
840                generation,
841                entity,
842                component,
843                overrides,
844            )?;
845        }
846    }
847    Ok(())
848}
849
850fn validate_retained_requirements(
851    world: &World,
852    application: ApplicationId,
853    generation: WorldGeneration,
854    entity: Entity,
855    component: ComponentId,
856    overrides: &PresenceOverrides,
857) -> Result<(), CommandBatchError> {
858    let Some(required) = world.get_required_components_by_id(component) else {
859        return Ok(());
860    };
861    let Some(missing) = required
862        .iter_ids()
863        .find(|required| !final_component_presence(world, entity, *required, overrides))
864    else {
865        return Ok(());
866    };
867
868    Err(CommandBatchError::RequiredComponentWouldBeMissing {
869        entity: LogicEntity::new(application, generation, entity),
870        required: component_diagnostic_name(world, missing),
871        required_by: component_diagnostic_name(world, component),
872    })
873}
874
875fn final_component_presence(
876    world: &World,
877    entity: Entity,
878    component: ComponentId,
879    overrides: &PresenceOverrides,
880) -> bool {
881    overrides
882        .get(&(entity, component))
883        .copied()
884        .unwrap_or_else(|| world.entity(entity).contains_id(component))
885}
886
887fn component_diagnostic_name(world: &World, component: ComponentId) -> String {
888    world
889        .components()
890        .get_info(component)
891        .map(|info| info.name().to_string())
892        .unwrap_or_else(|| format!("{component:?}"))
893}
894
895fn validate_target(
896    world: &World,
897    application: ApplicationId,
898    generation: WorldGeneration,
899    entity: LogicEntity,
900) -> Result<(), CommandBatchError> {
901    if entity.application() != application || entity.world_generation() != generation {
902        return Err(CommandBatchError::ForeignEntity { entity });
903    }
904    if !world
905        .get::<ManagedEntity>(entity.entity())
906        .is_some_and(|managed| managed.handle(entity.entity()) == entity)
907    {
908        return Err(CommandBatchError::MissingEntity { entity });
909    }
910    Ok(())
911}
912
913#[derive(Resource)]
914pub(crate) struct DirectIntentIssuer {
915    application: ApplicationId,
916    generation: WorldGeneration,
917    frame: u64,
918    next_occurrence: u64,
919    enabled: bool,
920}
921
922impl DirectIntentIssuer {
923    pub(crate) const fn new(application: ApplicationId, generation: WorldGeneration) -> Self {
924        Self {
925            application,
926            generation,
927            frame: 0,
928            next_occurrence: 1,
929            enabled: false,
930        }
931    }
932
933    pub(crate) fn set_frame(&mut self, frame: u64, generation: WorldGeneration) {
934        self.frame = frame;
935        self.generation = generation;
936        self.enabled = true;
937    }
938
939    pub(crate) fn disable(&mut self) {
940        self.enabled = false;
941    }
942
943    fn issue(&mut self) -> Result<TransitionIntentToken, CommandEnqueueError> {
944        if !self.enabled {
945            return Err(CommandEnqueueError::IntentUnavailable);
946        }
947        let occurrence = self.next_occurrence;
948        self.next_occurrence = self
949            .next_occurrence
950            .checked_add(1)
951            .ok_or(CommandEnqueueError::IntentIdentityExhausted)?;
952        Ok(TransitionIntentToken::direct(
953            self.application,
954            self.generation,
955            self.frame,
956            occurrence,
957        ))
958    }
959
960    const fn application_control_is_available(&self) -> bool {
961        self.enabled
962    }
963}
964
965/// Managed, stage-deferred command access for ordinary Sim;Logic Systems.
966///
967/// Commands are retained in deterministic call order and become visible only
968/// after the current stage passes whole-batch validation.
969#[derive(SystemParam)]
970pub struct LogicCommands<'w> {
971    queue: ResMut<'w, CommandQueue>,
972    intents: ResMut<'w, DirectIntentIssuer>,
973}
974
975impl LogicCommands<'_> {
976    /// Queues one approved, side-effect-free bundle for deferred spawn.
977    ///
978    /// Approved required components are materialized at the stage barrier. An
979    /// explicit value in `bundle` takes precedence over its required default.
980    ///
981    /// No entity handle is returned. The runtime assigns it at the stage
982    /// barrier after the complete batch succeeds.
983    pub fn spawn<B>(&mut self, bundle: B) -> Result<(), CommandEnqueueError>
984    where
985        B: Bundle<Effect: NoBundleEffect>,
986    {
987        self.queue.push(QueuedCommand::spawn(bundle))
988    }
989
990    /// Queues `count` copies of one approved bundle for consecutive deferred spawn.
991    ///
992    /// Every eventual entity consumes one slot from the bounded stage command
993    /// budget even though the runtime retains only one erased bundle template.
994    /// A request that does not fit poisons the complete stage batch just like
995    /// repeated [`Self::spawn`] calls that cross the limit, and no prefix from
996    /// this call is retained. At the stage barrier the bundle type is validated
997    /// once, the entity limit is checked for every copy before mutation, and
998    /// then distinct managed entities are created consecutively at this
999    /// command's position in queue order.
1000    ///
1001    /// `count == 0` is an immediate successful no-op: it occupies no command
1002    /// slot, retains no value, and does not validate or register `B`. Required
1003    /// components, explicit-over-required precedence, Disabled accounting, and
1004    /// Transform or camera interpolation snapping otherwise match singular
1005    /// spawn exactly. No handles are returned because identities do not become
1006    /// live until the stage barrier.
1007    ///
1008    /// `Copy` deliberately excludes user-defined cloning work and destructors.
1009    /// Application remains linear in `count`; this method does not promise a
1010    /// native bulk ECS insertion.
1011    pub fn spawn_copies<B>(&mut self, bundle: B, count: usize) -> Result<(), CommandEnqueueError>
1012    where
1013        B: Bundle<Effect: NoBundleEffect> + Copy,
1014    {
1015        if count == 0 {
1016            return Ok(());
1017        }
1018        self.queue.push_spawn_copies(bundle, count)
1019    }
1020
1021    /// Queues approved components to be added to or replaced on one entity.
1022    ///
1023    /// Existing explicit component types are replaced. Required components are
1024    /// materialized only when absent. The target and complete bundle are
1025    /// validated at the stage barrier before any structural command is
1026    /// applied. Inserting into and despawning the same entity in one stage is
1027    /// a batch conflict regardless of enqueue order.
1028    ///
1029    /// Multiple inserts apply in call order, so the last explicit value of one
1030    /// component type wins. An explicit or newly required [`Transform2d`] or
1031    /// [`ActiveCamera2d`] starts snapped; a required Transform that already
1032    /// exists keeps its interpolation history. The standard Bevy `Disabled`
1033    /// component may also be inserted directly, though [`Self::disable`] names
1034    /// that whole-entity operation more clearly.
1035    pub fn insert<B>(&mut self, entity: LogicEntity, bundle: B) -> Result<(), CommandEnqueueError>
1036    where
1037        B: Bundle<Effect: NoBundleEffect>,
1038    {
1039        self.queue.push(QueuedCommand::Insert {
1040            entity,
1041            bundle: Box::new(TypedInsert(bundle)),
1042        })
1043    }
1044
1045    /// Queues approved explicit component types for removal from one entity.
1046    ///
1047    /// Removal is visible only after the current stage barrier. Required
1048    /// components are never removed implicitly, and naming an approved
1049    /// component that is absent is a successful no-op. Insert and remove
1050    /// commands apply in call order, but removing a component still required
1051    /// by the entity's final component set rejects the complete structural
1052    /// batch before mutation. Removing and despawning the same entity in one
1053    /// stage is likewise a batch conflict.
1054    ///
1055    /// Removing the standard Bevy `Disabled` component re-enables the entity
1056    /// after the barrier, though [`Self::enable`] names that operation more
1057    /// clearly. Retain its [`LogicEntity`] handle before disabling it: ordinary
1058    /// managed queries deliberately exclude disabled entities.
1059    pub fn remove<B>(&mut self, entity: LogicEntity) -> Result<(), CommandEnqueueError>
1060    where
1061        B: Bundle<Effect: NoBundleEffect>,
1062    {
1063        self.queue.push(QueuedCommand::Remove {
1064            entity,
1065            descriptor: RemoveDescriptor::new::<B>(),
1066        })
1067    }
1068
1069    /// Queues an entity to become inactive after the current stage barrier.
1070    ///
1071    /// The entity keeps its identity, components, interpolation history, and
1072    /// place in the managed entity limit. Subsequent stages and same-frame
1073    /// extraction exclude it. Systems in the current stage continue to see
1074    /// the pre-barrier state. Repeated calls remain disabled, and this command
1075    /// has the same validation, ordering, atomicity, and despawn-conflict rules
1076    /// as [`Self::insert`]. Every call occupies one bounded Command slot,
1077    /// including a repeated disable.
1078    ///
1079    /// Retain the entity's [`LogicEntity`] before disabling it: ordinary
1080    /// managed queries deliberately cannot rediscover disabled entities. Pass
1081    /// that saved handle to [`Self::enable`] later.
1082    pub fn disable(&mut self, entity: LogicEntity) -> Result<(), CommandEnqueueError> {
1083        self.insert(entity, Disabled)
1084    }
1085
1086    /// Queues a disabled entity to become active after the stage barrier.
1087    ///
1088    /// Subsequent stages and same-frame extraction can observe the entity
1089    /// again. Enabling an already enabled entity is a successful no-op. This
1090    /// command has the same validation, ordering, atomicity, and
1091    /// despawn-conflict rules as [`Self::remove`]. It requires a handle saved
1092    /// before the entity became unavailable to ordinary managed queries. Every
1093    /// call occupies one bounded Command slot, including a no-op enable.
1094    pub fn enable(&mut self, entity: LogicEntity) -> Result<(), CommandEnqueueError> {
1095        self.remove::<Disabled>(entity)
1096    }
1097
1098    /// Queues a managed entity for deferred despawn.
1099    pub fn despawn(&mut self, entity: LogicEntity) -> Result<(), CommandEnqueueError> {
1100        self.queue.push(QueuedCommand::Despawn(entity))
1101    }
1102
1103    /// Requests successful application exit after the current stage barrier.
1104    ///
1105    /// All Systems in the current stage still run. The request takes effect
1106    /// only if the complete command batch passes validation; repeated requests
1107    /// coalesce in the result, but each call still consumes one command slot. A
1108    /// fixed-stage request stops remaining catch-up ticks, and no new render
1109    /// extraction is produced. Pending input edges are discarded and
1110    /// interpolation endpoints are snapped, so a headless host that deliberately
1111    /// continues does not replay pre-exit input or display pre-exit state. If
1112    /// World replacement is requested in the same batch, exit takes precedence.
1113    ///
1114    /// This method is unavailable during isolated World Startup. It does not
1115    /// terminate the process itself: the desktop host exits its event loop,
1116    /// while headless hosts inspect the resulting frame report. It produces no
1117    /// `WorldExit` lifecycle record and promises neither a cleanup hook nor one
1118    /// final presentation.
1119    pub fn request_exit(&mut self) -> Result<(), CommandEnqueueError> {
1120        if !self.intents.application_control_is_available() {
1121            return Err(CommandEnqueueError::ExitUnavailable);
1122        }
1123        self.queue.push(QueuedCommand::Exit)
1124    }
1125
1126    /// Queues a change to fixed-simulation pause at the stage barrier.
1127    ///
1128    /// FrameUpdate, input collection, extraction, and presentation continue
1129    /// while fixed simulation is paused. Every successfully enqueued call
1130    /// consumes one bounded command slot, including a request for the current
1131    /// value. Multiple calls in one successful stage are last-write-wins after
1132    /// every System in that stage has observed its entry-time clock state.
1133    /// A failed System or rejected command batch discards the pause request.
1134    ///
1135    /// Entering pause stops remaining fixed catch-up work without discarding
1136    /// its accumulated simulation time, clears undelivered fixed input edges,
1137    /// and snaps managed interpolation. Resume makes retained work eligible on
1138    /// the next application frame; paused wall time and input edges are not
1139    /// replayed. Pause is Application-owned and survives World replacement.
1140    /// Replacement keeps its own stronger time cleanup and stage-skipping
1141    /// rules; a rejected transition does not undo an otherwise committed pause.
1142    /// Application exit suppresses a pause change from the same batch.
1143    ///
1144    /// This method is unavailable during isolated World Startup. It does not
1145    /// bind an input action or implement toggle policy.
1146    pub fn set_paused(&mut self, paused: bool) -> Result<(), CommandEnqueueError> {
1147        if !self.intents.application_control_is_available() {
1148            return Err(CommandEnqueueError::PauseUnavailable);
1149        }
1150        self.queue.push(QueuedCommand::SetPaused(paused))
1151    }
1152
1153    /// Issues a direct causal token valid during the current application frame.
1154    pub fn new_transition_intent(&mut self) -> Result<TransitionIntentToken, CommandEnqueueError> {
1155        self.intents.issue()
1156    }
1157
1158    /// Queues a no-payload replacement request for stage-end arbitration.
1159    pub fn replace_world(
1160        &mut self,
1161        intent: TransitionIntentToken,
1162        target: WorldFactoryId,
1163    ) -> Result<(), CommandEnqueueError> {
1164        self.queue
1165            .push(QueuedCommand::ReplaceWorld(TransitionRequest::new(
1166                intent, target,
1167            )))
1168    }
1169}
1170
1171pub(crate) struct CommittedCommands {
1172    pub(crate) spawned: usize,
1173    pub(crate) despawned: usize,
1174    pub(crate) live_entities: usize,
1175    pub(crate) transitions: Vec<TransitionRequest>,
1176    pub(crate) pause: Option<bool>,
1177    pub(crate) exit_requested: bool,
1178}
1179
1180#[derive(Debug)]
1181pub(crate) enum CommandCommitError {
1182    Batch(CommandBatchError),
1183    RuntimeInvariant,
1184}
1185
1186impl From<CommandBatchError> for CommandCommitError {
1187    fn from(error: CommandBatchError) -> Self {
1188        Self::Batch(error)
1189    }
1190}
1191
1192#[cfg(test)]
1193fn managed_entity_count(world: &World) -> usize {
1194    world
1195        .iter_entities()
1196        .filter(|entity| entity.contains::<ManagedEntity>())
1197        .count()
1198}
1199
1200#[cfg(test)]
1201mod tests {
1202    use std::sync::{
1203        Arc,
1204        atomic::{AtomicUsize, Ordering},
1205    };
1206
1207    use bevy_ecs::{entity_disabling::Disabled, prelude::Component};
1208
1209    use crate::component::ComponentRegistry;
1210
1211    use super::*;
1212
1213    #[derive(Component, Clone, Copy)]
1214    struct Marker(u8);
1215
1216    #[derive(Component, Debug, PartialEq, Eq)]
1217    struct Added(u8);
1218
1219    #[derive(Bundle)]
1220    struct RemovableBundle {
1221        marker: Marker,
1222        added: Added,
1223    }
1224
1225    #[derive(Component, Default, Clone, Copy)]
1226    #[require(Transform2d)]
1227    struct NeedsTransform;
1228
1229    #[derive(Component, Clone, Copy)]
1230    struct Unapproved;
1231
1232    static NEXT_FRESH_REQUIRED: AtomicUsize = AtomicUsize::new(1);
1233
1234    #[derive(Component, Debug, PartialEq, Eq)]
1235    struct FreshRequired(usize);
1236
1237    impl Default for FreshRequired {
1238        fn default() -> Self {
1239            Self(NEXT_FRESH_REQUIRED.fetch_add(1, Ordering::SeqCst))
1240        }
1241    }
1242
1243    #[derive(Component, Clone, Copy)]
1244    #[require(FreshRequired)]
1245    struct NeedsFreshRequired;
1246
1247    #[derive(Component, Clone, Copy)]
1248    #[require(Disabled)]
1249    struct NeedsDisabled;
1250
1251    #[derive(Component)]
1252    struct DropMarker(Arc<AtomicUsize>);
1253
1254    impl Drop for DropMarker {
1255        fn drop(&mut self) {
1256            self.0.fetch_add(1, Ordering::SeqCst);
1257        }
1258    }
1259
1260    fn setup() -> (World, ApprovedComponents, ApplicationId, WorldGeneration) {
1261        let application = ApplicationId::from_raw(1);
1262        let generation = WorldGeneration::new(application, 1);
1263        let mut registry = ComponentRegistry::default();
1264        assert!(registry.approve::<Marker>().is_ok());
1265        assert!(registry.approve::<Added>().is_ok());
1266        assert!(registry.approve::<DropMarker>().is_ok());
1267        assert!(registry.approve::<Disabled>().is_ok());
1268        assert!(registry.approve::<Transform2d>().is_ok());
1269        assert!(registry.approve::<ActiveCamera2d>().is_ok());
1270        assert!(registry.approve::<NeedsTransform>().is_ok());
1271        assert!(registry.approve::<FreshRequired>().is_ok());
1272        assert!(registry.approve::<NeedsFreshRequired>().is_ok());
1273        assert!(registry.approve::<NeedsDisabled>().is_ok());
1274        let mut world = World::new();
1275        let approved = match registry.install(&mut world) {
1276            Ok(approved) => approved,
1277            Err(error) => panic!("unexpected approval error: {error}"),
1278        };
1279        (world, approved, application, generation)
1280    }
1281
1282    #[test]
1283    fn spawn_is_invisible_until_whole_batch_commit() {
1284        let (mut world, mut approved, application, generation) = setup();
1285        let mut queue = CommandQueue::new(4);
1286        assert!(queue.push(QueuedCommand::spawn(Marker(7))).is_ok());
1287        let command_capacity = queue.command_capacity();
1288        assert_eq!(managed_entity_count(&world), 0);
1289
1290        let result =
1291            queue.validate_and_apply(&mut world, &mut approved, application, generation, 0, 8);
1292        let committed = result.expect("valid spawn batch should commit");
1293        assert_eq!(committed.live_entities, 1);
1294        let values: Vec<_> = world.query::<&Marker>().iter(&world).map(|m| m.0).collect();
1295        assert_eq!(values, [7]);
1296        let marker = world
1297            .component_id::<Marker>()
1298            .expect("Marker should be registered");
1299        let managed = world
1300            .component_id::<ManagedEntity>()
1301            .expect("ManagedEntity should be registered");
1302        assert!(
1303            !world
1304                .archetypes()
1305                .iter()
1306                .any(|archetype| archetype.contains(marker) && !archetype.contains(managed))
1307        );
1308        assert!(queue.is_clean());
1309        assert_eq!(queue.command_capacity(), command_capacity);
1310    }
1311
1312    #[test]
1313    fn copy_spawns_use_logical_slots_and_preserve_consecutive_order() {
1314        let (mut world, mut approved, application, generation) = setup();
1315        let mut queue = CommandQueue::new(6);
1316        assert!(queue.push(QueuedCommand::spawn(Marker(1))).is_ok());
1317        assert!(queue.push_spawn_copies(Marker(2), 3).is_ok());
1318        assert!(queue.push(QueuedCommand::spawn(Marker(3))).is_ok());
1319        assert!(queue.push(QueuedCommand::Exit).is_ok());
1320        assert_eq!(queue.commands.len(), 4);
1321        assert_eq!(queue.used_slots, 6);
1322
1323        let committed = queue
1324            .validate_and_apply(&mut world, &mut approved, application, generation, 0, 5)
1325            .expect("exactly fitting repeated spawns should commit");
1326
1327        assert_eq!(committed.spawned, 5);
1328        assert_eq!(committed.live_entities, 5);
1329        assert!(committed.exit_requested);
1330        let values: Vec<_> = world
1331            .iter_entities()
1332            .filter_map(|entity| {
1333                let marker = entity.get::<Marker>()?;
1334                let managed = entity
1335                    .get::<ManagedEntity>()
1336                    .expect("every copy should be managed");
1337                assert_eq!(managed.handle(entity.id()).world_generation(), generation);
1338                Some(marker.0)
1339            })
1340            .collect();
1341        assert_eq!(values, [1, 2, 2, 2, 3]);
1342        assert!(queue.is_clean());
1343    }
1344
1345    #[test]
1346    fn despawn_and_copy_spawn_use_the_net_entity_count_atomically() {
1347        let (mut world, mut approved, application, generation) = setup();
1348        let removed_raw = world.spawn(Marker(1)).id();
1349        let retained_raw = world.spawn(Marker(2)).id();
1350        for raw in [removed_raw, retained_raw] {
1351            let entity = LogicEntity::new(application, generation, raw);
1352            world.entity_mut(raw).insert(ManagedEntity::new(entity));
1353        }
1354        let removed = LogicEntity::new(application, generation, removed_raw);
1355
1356        let mut rejected = CommandQueue::new(4);
1357        assert!(rejected.push(QueuedCommand::Despawn(removed)).is_ok());
1358        assert!(rejected.push_spawn_copies(Marker(3), 3).is_ok());
1359        assert!(matches!(
1360            rejected.validate_and_apply(&mut world, &mut approved, application, generation, 2, 3,),
1361            Err(CommandCommitError::Batch(
1362                CommandBatchError::EntityLimitExceeded {
1363                    limit: 3,
1364                    requested: 4,
1365                }
1366            ))
1367        ));
1368        assert!(world.entities().contains(removed_raw));
1369        assert!(world.entities().contains(retained_raw));
1370        assert_eq!(managed_entity_count(&world), 2);
1371
1372        let mut exact = CommandQueue::new(3);
1373        assert!(exact.push(QueuedCommand::Despawn(removed)).is_ok());
1374        assert!(exact.push_spawn_copies(Marker(4), 2).is_ok());
1375        let committed = exact
1376            .validate_and_apply(&mut world, &mut approved, application, generation, 2, 3)
1377            .expect("net entity count at the limit should commit");
1378        assert_eq!(committed.despawned, 1);
1379        assert_eq!(committed.spawned, 2);
1380        assert_eq!(committed.live_entities, 3);
1381        assert!(!world.entities().contains(removed_raw));
1382        assert!(world.entities().contains(retained_raw));
1383        assert_eq!(managed_entity_count(&world), 3);
1384    }
1385
1386    #[test]
1387    fn copy_spawn_limit_failures_poison_without_a_retained_prefix_and_then_reuse() {
1388        let (mut world, mut approved, application, generation) = setup();
1389        let mut queue = CommandQueue::new(3);
1390        assert!(queue.push(QueuedCommand::spawn(Marker(1))).is_ok());
1391        assert!(matches!(
1392            queue.push_spawn_copies(Marker(2), 3),
1393            Err(CommandEnqueueError::LimitExceeded { limit: 3 })
1394        ));
1395        assert_eq!(queue.commands.len(), 1);
1396        assert_eq!(queue.used_slots, 1);
1397        assert!(matches!(
1398            queue.validate_and_apply(&mut world, &mut approved, application, generation, 0, 8),
1399            Err(CommandCommitError::Batch(
1400                CommandBatchError::LimitExceeded { limit: 3 }
1401            ))
1402        ));
1403        assert_eq!(managed_entity_count(&world), 0);
1404        assert!(queue.is_clean());
1405
1406        assert!(queue.push_spawn_copies(Marker(4), 3).is_ok());
1407        assert!(matches!(
1408            queue.push(QueuedCommand::spawn(Marker(5))),
1409            Err(CommandEnqueueError::LimitExceeded { limit: 3 })
1410        ));
1411        queue.discard();
1412        assert!(queue.is_clean());
1413
1414        assert!(queue.push_spawn_copies(Marker(6), 3).is_ok());
1415        let committed = queue
1416            .validate_and_apply(&mut world, &mut approved, application, generation, 0, 8)
1417            .expect("discarded poison should not affect a later batch");
1418        assert_eq!(committed.spawned, 3);
1419    }
1420
1421    #[test]
1422    fn copy_spawn_logical_slot_overflow_uses_the_bounded_limit_error() {
1423        let (mut world, mut approved, application, generation) = setup();
1424        let mut queue = CommandQueue::new(usize::MAX);
1425        assert!(queue.push(QueuedCommand::spawn(Marker(1))).is_ok());
1426        assert!(matches!(
1427            queue.push_spawn_copies(Marker(2), usize::MAX),
1428            Err(CommandEnqueueError::LimitExceeded { limit }) if limit == usize::MAX
1429        ));
1430        assert!(matches!(
1431            queue.validate_and_apply(&mut world, &mut approved, application, generation, 0, 1),
1432            Err(CommandCommitError::Batch(
1433                CommandBatchError::LimitExceeded { limit }
1434            )) if limit == usize::MAX
1435        ));
1436        assert_eq!(managed_entity_count(&world), 0);
1437        assert!(queue.is_clean());
1438    }
1439
1440    #[test]
1441    fn copy_spawn_validates_once_and_preflights_the_complete_entity_count() {
1442        let (mut world, mut approved, application, generation) = setup();
1443        let mut over_capacity = CommandQueue::new(3);
1444        assert!(over_capacity.push_spawn_copies(Marker(1), 3).is_ok());
1445        assert!(matches!(
1446            over_capacity.validate_and_apply(
1447                &mut world,
1448                &mut approved,
1449                application,
1450                generation,
1451                0,
1452                2,
1453            ),
1454            Err(CommandCommitError::Batch(
1455                CommandBatchError::EntityLimitExceeded {
1456                    limit: 2,
1457                    requested: 3,
1458                }
1459            ))
1460        ));
1461        assert_eq!(managed_entity_count(&world), 0);
1462
1463        let mut unapproved = CommandQueue::new(3);
1464        assert!(unapproved.push_spawn_copies(Unapproved, 3).is_ok());
1465        assert!(matches!(
1466            unapproved
1467                .validate_and_apply(&mut world, &mut approved, application, generation, 0, 0,),
1468            Err(CommandCommitError::Batch(CommandBatchError::Component(
1469                ComponentApprovalError::UnapprovedBundleComponent { .. }
1470            )))
1471        ));
1472        assert_eq!(managed_entity_count(&world), 0);
1473    }
1474
1475    #[test]
1476    fn copy_spawn_entity_count_overflow_rejects_before_mutation() {
1477        let (mut world, mut approved, application, generation) = setup();
1478        let mut queue = CommandQueue::new(2);
1479        assert!(queue.push_spawn_copies(Marker(1), 2).is_ok());
1480
1481        assert!(matches!(
1482            queue.validate_and_apply(
1483                &mut world,
1484                &mut approved,
1485                application,
1486                generation,
1487                usize::MAX - 1,
1488                usize::MAX,
1489            ),
1490            Err(CommandCommitError::Batch(
1491                CommandBatchError::EntityLimitExceeded {
1492                    limit,
1493                    requested: usize::MAX,
1494                }
1495            )) if limit == usize::MAX
1496        ));
1497        assert_eq!(managed_entity_count(&world), 0);
1498        assert!(queue.is_clean());
1499    }
1500
1501    #[test]
1502    fn every_copy_gets_fresh_requirements_and_snapped_spatial_state() {
1503        let (mut world, mut approved, application, generation) = setup();
1504        let mut transform = Transform2d::default();
1505        transform.begin_fixed_tick();
1506        assert!(
1507            transform
1508                .set_translation(sim_engine::Vec2::new(4.0, -2.0))
1509                .is_ok()
1510        );
1511        let mut camera = ActiveCamera2d::new(
1512            sim_engine::Camera2d::new(sim_engine::Vec2::ZERO, 12.0)
1513                .expect("finite camera should construct"),
1514        );
1515        camera.begin_fixed_tick();
1516        assert!(camera.set_center(sim_engine::Vec2::new(-3.0, 5.0)).is_ok());
1517
1518        let mut queue = CommandQueue::new(2);
1519        assert!(
1520            queue
1521                .push_spawn_copies((NeedsFreshRequired, NeedsDisabled, transform, camera), 2)
1522                .is_ok()
1523        );
1524        let committed = queue
1525            .validate_and_apply(&mut world, &mut approved, application, generation, 0, 2)
1526            .expect("approved repeated spatial bundle should commit");
1527        assert_eq!(committed.spawned, 2);
1528        assert_eq!(committed.live_entities, 2);
1529
1530        let mut fresh_values = Vec::new();
1531        for entity in world
1532            .iter_entities()
1533            .filter(|entity| entity.contains::<NeedsFreshRequired>())
1534        {
1535            assert!(entity.contains::<Disabled>());
1536            let transform = entity
1537                .get::<Transform2d>()
1538                .expect("explicit Transform should remain");
1539            assert_eq!(transform.previous_translation(), transform.translation());
1540            let camera = entity
1541                .get::<ActiveCamera2d>()
1542                .expect("explicit camera should remain");
1543            assert_eq!(camera.previous_center(), camera.center());
1544            fresh_values.push(
1545                entity
1546                    .get::<FreshRequired>()
1547                    .expect("required value should materialize per entity")
1548                    .0,
1549            );
1550        }
1551        assert_eq!(fresh_values.len(), 2);
1552        assert_ne!(fresh_values[0], fresh_values[1]);
1553    }
1554
1555    #[test]
1556    fn committed_live_count_tracks_despawns_and_spawns_in_one_batch() {
1557        let (mut world, mut approved, application, generation) = setup();
1558        let removed_raw = world.spawn(Marker(1)).id();
1559        let retained_raw = world.spawn((Marker(2), Disabled)).id();
1560        for raw in [removed_raw, retained_raw] {
1561            let entity = LogicEntity::new(application, generation, raw);
1562            world.entity_mut(raw).insert(ManagedEntity::new(entity));
1563        }
1564
1565        let removed = LogicEntity::new(application, generation, removed_raw);
1566        let mut queue = CommandQueue::new(4);
1567        assert!(queue.push(QueuedCommand::Despawn(removed)).is_ok());
1568        assert!(queue.push(QueuedCommand::spawn(Marker(3))).is_ok());
1569
1570        let committed = queue
1571            .validate_and_apply(&mut world, &mut approved, application, generation, 2, 2)
1572            .expect("balanced batch should preserve the live count");
1573
1574        assert_eq!(committed.live_entities, 2);
1575        assert_eq!(managed_entity_count(&world), 2);
1576        assert!(!world.entities().contains(removed_raw));
1577        assert!(world.entities().contains(retained_raw));
1578        assert!(queue.is_clean());
1579        assert!(queue.despawn_capacity() >= 1);
1580    }
1581
1582    #[test]
1583    fn insert_adds_and_replaces_in_command_order_without_changing_live_count() {
1584        let (mut world, mut approved, application, generation) = setup();
1585        let raw = world.spawn(Marker(1)).id();
1586        let entity = LogicEntity::new(application, generation, raw);
1587        world.entity_mut(raw).insert(ManagedEntity::new(entity));
1588        let mut queue = CommandQueue::new(3);
1589        for command in [
1590            QueuedCommand::Insert {
1591                entity,
1592                bundle: Box::new(TypedInsert(Added(3))),
1593            },
1594            QueuedCommand::Insert {
1595                entity,
1596                bundle: Box::new(TypedInsert(Marker(7))),
1597            },
1598            QueuedCommand::Insert {
1599                entity,
1600                bundle: Box::new(TypedInsert(Marker(9))),
1601            },
1602        ] {
1603            assert!(queue.push(command).is_ok());
1604        }
1605
1606        let committed = queue
1607            .validate_and_apply(&mut world, &mut approved, application, generation, 1, 1)
1608            .expect("approved inserts should commit");
1609
1610        assert_eq!(committed.spawned, 0);
1611        assert_eq!(committed.despawned, 0);
1612        assert_eq!(committed.live_entities, 1);
1613        assert_eq!(world.get::<Added>(raw), Some(&Added(3)));
1614        assert_eq!(world.get::<Marker>(raw).map(|marker| marker.0), Some(9));
1615        assert!(queue.is_clean());
1616    }
1617
1618    #[test]
1619    fn remove_is_explicit_idempotent_and_ordered_with_insert() {
1620        let (mut world, mut approved, application, generation) = setup();
1621        let raw = world
1622            .spawn(RemovableBundle {
1623                marker: Marker(1),
1624                added: Added(2),
1625            })
1626            .id();
1627        let entity = LogicEntity::new(application, generation, raw);
1628        world.entity_mut(raw).insert(ManagedEntity::new(entity));
1629        let mut queue = CommandQueue::new(5);
1630        for command in [
1631            QueuedCommand::Remove {
1632                entity,
1633                descriptor: RemoveDescriptor::new::<Added>(),
1634            },
1635            QueuedCommand::Remove {
1636                entity,
1637                descriptor: RemoveDescriptor::new::<Added>(),
1638            },
1639            QueuedCommand::Remove {
1640                entity,
1641                descriptor: RemoveDescriptor::new::<Marker>(),
1642            },
1643            QueuedCommand::Insert {
1644                entity,
1645                bundle: Box::new(TypedInsert(Marker(9))),
1646            },
1647            QueuedCommand::Remove {
1648                entity,
1649                descriptor: RemoveDescriptor::new::<Added>(),
1650            },
1651        ] {
1652            assert!(queue.push(command).is_ok());
1653        }
1654
1655        let committed = queue
1656            .validate_and_apply(&mut world, &mut approved, application, generation, 1, 1)
1657            .expect("approved removals and later insert should commit in order");
1658
1659        assert_eq!(committed.spawned, 0);
1660        assert_eq!(committed.despawned, 0);
1661        assert_eq!(committed.live_entities, 1);
1662        assert_eq!(world.get::<Marker>(raw).map(|marker| marker.0), Some(9));
1663        assert!(world.get::<Added>(raw).is_none());
1664        assert!(world.get::<ManagedEntity>(raw).is_some());
1665        assert!(queue.is_clean());
1666        assert!(queue.component_target_capacity() >= 1);
1667        assert!(queue.presence_override_capacity() >= 2);
1668
1669        let mut tuple_queue = CommandQueue::new(1);
1670        assert!(
1671            tuple_queue
1672                .push(QueuedCommand::Remove {
1673                    entity,
1674                    descriptor: RemoveDescriptor::new::<(Marker, Added)>(),
1675                })
1676                .is_ok()
1677        );
1678        tuple_queue
1679            .validate_and_apply(&mut world, &mut approved, application, generation, 1, 1)
1680            .expect("tuple removal should remove only explicit members");
1681        assert!(world.get::<Marker>(raw).is_none());
1682        assert!(world.get::<ManagedEntity>(raw).is_some());
1683
1684        world.entity_mut(raw).insert(RemovableBundle {
1685            marker: Marker(4),
1686            added: Added(5),
1687        });
1688        let mut derived_queue = CommandQueue::new(1);
1689        assert!(
1690            derived_queue
1691                .push(QueuedCommand::Remove {
1692                    entity,
1693                    descriptor: RemoveDescriptor::new::<RemovableBundle>(),
1694                })
1695                .is_ok()
1696        );
1697        derived_queue
1698            .validate_and_apply(&mut world, &mut approved, application, generation, 1, 1)
1699            .expect("derived bundle removal should remove its explicit members");
1700        assert!(world.get::<Marker>(raw).is_none());
1701        assert!(world.get::<Added>(raw).is_none());
1702        assert!(world.get::<ManagedEntity>(raw).is_some());
1703    }
1704
1705    #[test]
1706    fn removal_planner_ignores_inserts_on_unaffected_entities() {
1707        let (mut world, _approved, application, generation) = setup();
1708        let affected_raw = world.spawn((Marker(1), Added(1))).id();
1709        let affected = LogicEntity::new(application, generation, affected_raw);
1710        world
1711            .entity_mut(affected_raw)
1712            .insert(ManagedEntity::new(affected));
1713        let unrelated_raw = world.spawn(Marker(2)).id();
1714        let unrelated = LogicEntity::new(application, generation, unrelated_raw);
1715        world
1716            .entity_mut(unrelated_raw)
1717            .insert(ManagedEntity::new(unrelated));
1718        let mut queue = CommandQueue::new(3);
1719        assert!(
1720            queue
1721                .push(QueuedCommand::Insert {
1722                    entity: unrelated,
1723                    bundle: Box::new(TypedInsert(Added(8))),
1724                })
1725                .is_ok()
1726        );
1727        assert!(
1728            queue
1729                .push(QueuedCommand::Remove {
1730                    entity: affected,
1731                    descriptor: RemoveDescriptor::new::<Added>(),
1732                })
1733                .is_ok()
1734        );
1735        assert!(
1736            queue
1737                .push(QueuedCommand::Insert {
1738                    entity: affected,
1739                    bundle: Box::new(TypedInsert(Marker(9))),
1740                })
1741                .is_ok()
1742        );
1743
1744        queue
1745            .plan_component_presence(&mut world, 1)
1746            .expect("presence planning should fit its bounded storage");
1747
1748        assert_eq!(queue.component_target_order, [affected_raw]);
1749        assert!(
1750            queue
1751                .presence_overrides
1752                .keys()
1753                .all(|(entity, _)| *entity == affected_raw)
1754        );
1755        assert!(
1756            queue
1757                .inserted_components
1758                .iter()
1759                .all(|(entity, _)| *entity == affected_raw)
1760        );
1761        assert_eq!(queue.inserted_components.len(), 1);
1762    }
1763
1764    #[test]
1765    fn removal_validates_the_final_required_component_set() {
1766        let (mut world, mut approved, application, generation) = setup();
1767        let raw = world.spawn(NeedsTransform).id();
1768        let entity = LogicEntity::new(application, generation, raw);
1769        world.entity_mut(raw).insert(ManagedEntity::new(entity));
1770
1771        let mut invalid = CommandQueue::new(1);
1772        assert!(
1773            invalid
1774                .push(QueuedCommand::Remove {
1775                    entity,
1776                    descriptor: RemoveDescriptor::new::<Transform2d>(),
1777                })
1778                .is_ok()
1779        );
1780        let invalid_result =
1781            invalid.validate_and_apply(&mut world, &mut approved, application, generation, 1, 1);
1782        let Err(CommandCommitError::Batch(CommandBatchError::RequiredComponentWouldBeMissing {
1783            entity: rejected,
1784            required,
1785            required_by,
1786        })) = invalid_result
1787        else {
1788            panic!("removing a retained requirement should reject the batch");
1789        };
1790        assert_eq!(rejected, entity);
1791        assert!(required.ends_with("Transform2d"), "{required}");
1792        assert!(required_by.ends_with("NeedsTransform"), "{required_by}");
1793        assert!(invalid.is_clean());
1794        assert!(invalid.component_target_capacity() >= 1);
1795        assert!(invalid.presence_override_capacity() >= 1);
1796        assert!(world.get::<NeedsTransform>(raw).is_some());
1797        assert!(world.get::<Transform2d>(raw).is_some());
1798
1799        let mut remove_both = CommandQueue::new(2);
1800        assert!(
1801            remove_both
1802                .push(QueuedCommand::Remove {
1803                    entity,
1804                    descriptor: RemoveDescriptor::new::<Transform2d>(),
1805                })
1806                .is_ok()
1807        );
1808        assert!(
1809            remove_both
1810                .push(QueuedCommand::Remove {
1811                    entity,
1812                    descriptor: RemoveDescriptor::new::<NeedsTransform>(),
1813                })
1814                .is_ok()
1815        );
1816        remove_both
1817            .validate_and_apply(&mut world, &mut approved, application, generation, 1, 1)
1818            .expect("removing the requiree and requirement should be valid");
1819        assert!(world.get::<NeedsTransform>(raw).is_none());
1820        assert!(world.get::<Transform2d>(raw).is_none());
1821
1822        let materialize_raw = world.spawn(Marker(2)).id();
1823        let materialize = LogicEntity::new(application, generation, materialize_raw);
1824        world
1825            .entity_mut(materialize_raw)
1826            .insert(ManagedEntity::new(materialize));
1827        let mut materialize_required = CommandQueue::new(2);
1828        assert!(
1829            materialize_required
1830                .push(QueuedCommand::Remove {
1831                    entity: materialize,
1832                    descriptor: RemoveDescriptor::new::<Transform2d>(),
1833                })
1834                .is_ok()
1835        );
1836        assert!(
1837            materialize_required
1838                .push(QueuedCommand::Insert {
1839                    entity: materialize,
1840                    bundle: Box::new(TypedInsert(NeedsTransform)),
1841                })
1842                .is_ok()
1843        );
1844        materialize_required
1845            .validate_and_apply(&mut world, &mut approved, application, generation, 2, 2)
1846            .expect("later requiree insert should rematerialize its Transform");
1847        let transform = world
1848            .get::<Transform2d>(materialize_raw)
1849            .expect("required Transform should exist");
1850        assert_eq!(transform.previous_translation(), transform.translation());
1851
1852        let existing_raw = world.spawn(NeedsTransform).id();
1853        let existing = LogicEntity::new(application, generation, existing_raw);
1854        world
1855            .entity_mut(existing_raw)
1856            .insert(ManagedEntity::new(existing));
1857        let mut rematerialize_existing = CommandQueue::new(2);
1858        assert!(
1859            rematerialize_existing
1860                .push(QueuedCommand::Remove {
1861                    entity: existing,
1862                    descriptor: RemoveDescriptor::new::<Transform2d>(),
1863                })
1864                .is_ok()
1865        );
1866        assert!(
1867            rematerialize_existing
1868                .push(QueuedCommand::Insert {
1869                    entity: existing,
1870                    bundle: Box::new(TypedInsert(NeedsTransform)),
1871                })
1872                .is_ok()
1873        );
1874        rematerialize_existing
1875            .validate_and_apply(&mut world, &mut approved, application, generation, 3, 3)
1876            .expect("reinserting a retained requiree should rematerialize its requirement");
1877        assert!(world.get::<NeedsTransform>(existing_raw).is_some());
1878        assert!(world.get::<Transform2d>(existing_raw).is_some());
1879
1880        let reject_raw = world.spawn(Marker(3)).id();
1881        let reject = LogicEntity::new(application, generation, reject_raw);
1882        world
1883            .entity_mut(reject_raw)
1884            .insert(ManagedEntity::new(reject));
1885        let mut invalid_order = CommandQueue::new(2);
1886        assert!(
1887            invalid_order
1888                .push(QueuedCommand::Insert {
1889                    entity: reject,
1890                    bundle: Box::new(TypedInsert(NeedsTransform)),
1891                })
1892                .is_ok()
1893        );
1894        assert!(
1895            invalid_order
1896                .push(QueuedCommand::Remove {
1897                    entity: reject,
1898                    descriptor: RemoveDescriptor::new::<Transform2d>(),
1899                })
1900                .is_ok()
1901        );
1902        assert!(matches!(
1903            invalid_order.validate_and_apply(
1904                &mut world,
1905                &mut approved,
1906                application,
1907                generation,
1908                4,
1909                4,
1910            ),
1911            Err(CommandCommitError::Batch(
1912                CommandBatchError::RequiredComponentWouldBeMissing { .. }
1913            ))
1914        ));
1915        assert!(world.get::<NeedsTransform>(reject_raw).is_none());
1916        assert!(world.get::<Transform2d>(reject_raw).is_none());
1917    }
1918
1919    #[test]
1920    fn remove_and_despawn_conflict_is_symmetric_and_atomic() {
1921        for remove_first in [true, false] {
1922            let (mut world, mut approved, application, generation) = setup();
1923            let drops = Arc::new(AtomicUsize::new(0));
1924            let raw = world
1925                .spawn((Marker(1), DropMarker(Arc::clone(&drops))))
1926                .id();
1927            let entity = LogicEntity::new(application, generation, raw);
1928            world.entity_mut(raw).insert(ManagedEntity::new(entity));
1929            let mut queue = CommandQueue::new(2);
1930            let remove = || QueuedCommand::Remove {
1931                entity,
1932                descriptor: RemoveDescriptor::new::<DropMarker>(),
1933            };
1934            if remove_first {
1935                assert!(queue.push(remove()).is_ok());
1936                assert!(queue.push(QueuedCommand::Despawn(entity)).is_ok());
1937            } else {
1938                assert!(queue.push(QueuedCommand::Despawn(entity)).is_ok());
1939                assert!(queue.push(remove()).is_ok());
1940            }
1941
1942            assert!(matches!(
1943                queue.validate_and_apply(
1944                    &mut world,
1945                    &mut approved,
1946                    application,
1947                    generation,
1948                    1,
1949                    1,
1950                ),
1951                Err(CommandCommitError::Batch(
1952                    CommandBatchError::ConflictingEntityCommands {
1953                        entity: conflicted
1954                    }
1955                )) if conflicted == entity
1956            ));
1957            assert_eq!(drops.load(Ordering::SeqCst), 0);
1958            assert!(world.get::<DropMarker>(raw).is_some());
1959            assert!(world.entities().contains(raw));
1960        }
1961    }
1962
1963    #[test]
1964    fn successful_and_repeated_remove_drop_the_stored_value_exactly_once() {
1965        let (mut world, mut approved, application, generation) = setup();
1966        let drops = Arc::new(AtomicUsize::new(0));
1967        let raw = world
1968            .spawn((Marker(1), DropMarker(Arc::clone(&drops))))
1969            .id();
1970        let entity = LogicEntity::new(application, generation, raw);
1971        world.entity_mut(raw).insert(ManagedEntity::new(entity));
1972        let mut queue = CommandQueue::new(2);
1973        for _ in 0..2 {
1974            assert!(
1975                queue
1976                    .push(QueuedCommand::Remove {
1977                        entity,
1978                        descriptor: RemoveDescriptor::new::<DropMarker>(),
1979                    })
1980                    .is_ok()
1981            );
1982        }
1983
1984        queue
1985            .validate_and_apply(&mut world, &mut approved, application, generation, 1, 1)
1986            .expect("repeated removal should be an idempotent successful batch");
1987        assert_eq!(drops.load(Ordering::SeqCst), 1);
1988        assert!(world.get::<DropMarker>(raw).is_none());
1989        assert!(world.get::<Marker>(raw).is_some());
1990        assert!(world.get::<ManagedEntity>(raw).is_some());
1991    }
1992
1993    #[test]
1994    fn invalid_remove_target_or_type_rejects_without_mutation() {
1995        let (mut world, mut approved, application, generation) = setup();
1996        let raw = world.spawn((Marker(1), Added(2))).id();
1997        let entity = LogicEntity::new(application, generation, raw);
1998        world.entity_mut(raw).insert(ManagedEntity::new(entity));
1999        let foreign = LogicEntity::new(application, WorldGeneration::new(application, 9), raw);
2000
2001        for (target, descriptor) in [
2002            (foreign, RemoveDescriptor::new::<Added>()),
2003            (entity, RemoveDescriptor::new::<Unapproved>()),
2004            (entity, RemoveDescriptor::new::<ManagedEntity>()),
2005        ] {
2006            let mut queue = CommandQueue::new(2);
2007            assert!(queue.push(QueuedCommand::spawn(Marker(8))).is_ok());
2008            assert!(
2009                queue
2010                    .push(QueuedCommand::Remove {
2011                        entity: target,
2012                        descriptor,
2013                    })
2014                    .is_ok()
2015            );
2016            assert!(
2017                queue
2018                    .validate_and_apply(&mut world, &mut approved, application, generation, 1, 4,)
2019                    .is_err()
2020            );
2021            assert_eq!(managed_entity_count(&world), 1);
2022            assert_eq!(world.get::<Added>(raw), Some(&Added(2)));
2023        }
2024
2025        let missing_raw = world.spawn(Marker(0)).id();
2026        let missing = LogicEntity::new(application, generation, missing_raw);
2027        world
2028            .entity_mut(missing_raw)
2029            .insert(ManagedEntity::new(missing));
2030        assert!(world.despawn(missing_raw));
2031        let mut missing_queue = CommandQueue::new(1);
2032        assert!(
2033            missing_queue
2034                .push(QueuedCommand::Remove {
2035                    entity: missing,
2036                    descriptor: RemoveDescriptor::new::<Added>(),
2037                })
2038                .is_ok()
2039        );
2040        assert!(matches!(
2041            missing_queue.validate_and_apply(
2042                &mut world,
2043                &mut approved,
2044                application,
2045                generation,
2046                1,
2047                4,
2048            ),
2049            Err(CommandCommitError::Batch(
2050                CommandBatchError::MissingEntity { entity: rejected }
2051            )) if rejected == missing
2052        ));
2053        assert_eq!(world.get::<Added>(raw), Some(&Added(2)));
2054    }
2055
2056    #[test]
2057    fn insert_and_despawn_conflict_is_symmetric_and_atomic() {
2058        for insert_first in [true, false] {
2059            let (mut world, mut approved, application, generation) = setup();
2060            let raw = world.spawn(Marker(1)).id();
2061            let entity = LogicEntity::new(application, generation, raw);
2062            world.entity_mut(raw).insert(ManagedEntity::new(entity));
2063            let mut queue = CommandQueue::new(2);
2064            let insert = || QueuedCommand::Insert {
2065                entity,
2066                bundle: Box::new(TypedInsert(Marker(2))),
2067            };
2068            if insert_first {
2069                assert!(queue.push(insert()).is_ok());
2070                assert!(queue.push(QueuedCommand::Despawn(entity)).is_ok());
2071            } else {
2072                assert!(queue.push(QueuedCommand::Despawn(entity)).is_ok());
2073                assert!(queue.push(insert()).is_ok());
2074            }
2075
2076            let result =
2077                queue.validate_and_apply(&mut world, &mut approved, application, generation, 1, 1);
2078
2079            assert!(matches!(
2080                result,
2081                Err(CommandCommitError::Batch(
2082                    CommandBatchError::ConflictingEntityCommands { entity: conflicted }
2083                )) if conflicted == entity
2084            ));
2085            assert_eq!(world.get::<Marker>(raw).map(|marker| marker.0), Some(1));
2086            assert!(world.entities().contains(raw));
2087            assert!(queue.is_clean());
2088        }
2089    }
2090
2091    #[test]
2092    fn invalid_insert_target_and_bundle_reject_before_any_structural_mutation() {
2093        let (mut world, mut approved, application, generation) = setup();
2094        let raw = world.spawn(Marker(1)).id();
2095        let entity = LogicEntity::new(application, generation, raw);
2096        world.entity_mut(raw).insert(ManagedEntity::new(entity));
2097        let foreign = LogicEntity::new(application, WorldGeneration::new(application, 7), raw);
2098        let mut foreign_queue = CommandQueue::new(1);
2099        assert!(
2100            foreign_queue
2101                .push(QueuedCommand::Insert {
2102                    entity: foreign,
2103                    bundle: Box::new(TypedInsert(Added(2))),
2104                })
2105                .is_ok()
2106        );
2107        assert!(matches!(
2108            foreign_queue.validate_and_apply(
2109                &mut world,
2110                &mut approved,
2111                application,
2112                generation,
2113                1,
2114                2,
2115            ),
2116            Err(CommandCommitError::Batch(
2117                CommandBatchError::ForeignEntity { entity }
2118            )) if entity == foreign
2119        ));
2120
2121        let missing_raw = world.spawn(Marker(8)).id();
2122        let missing = LogicEntity::new(application, generation, missing_raw);
2123        world
2124            .entity_mut(missing_raw)
2125            .insert(ManagedEntity::new(missing));
2126        assert!(world.despawn(missing_raw));
2127        let mut missing_queue = CommandQueue::new(1);
2128        assert!(
2129            missing_queue
2130                .push(QueuedCommand::Insert {
2131                    entity: missing,
2132                    bundle: Box::new(TypedInsert(Added(3))),
2133                })
2134                .is_ok()
2135        );
2136        assert!(matches!(
2137            missing_queue.validate_and_apply(
2138                &mut world,
2139                &mut approved,
2140                application,
2141                generation,
2142                1,
2143                2,
2144            ),
2145            Err(CommandCommitError::Batch(
2146                CommandBatchError::MissingEntity { entity }
2147            )) if entity == missing
2148        ));
2149
2150        let mut identity_queue = CommandQueue::new(1);
2151        assert!(
2152            identity_queue
2153                .push(QueuedCommand::Insert {
2154                    entity,
2155                    bundle: Box::new(TypedInsert(ManagedEntity::new(entity))),
2156                })
2157                .is_ok()
2158        );
2159        assert!(matches!(
2160            identity_queue.validate_and_apply(
2161                &mut world,
2162                &mut approved,
2163                application,
2164                generation,
2165                1,
2166                2,
2167            ),
2168            Err(CommandCommitError::Batch(CommandBatchError::Component(
2169                ComponentApprovalError::RuntimeIdentityInBundle
2170            )))
2171        ));
2172
2173        let mut bundle_queue = CommandQueue::new(2);
2174        assert!(bundle_queue.push(QueuedCommand::spawn(Added(4))).is_ok());
2175        assert!(
2176            bundle_queue
2177                .push(QueuedCommand::Insert {
2178                    entity,
2179                    bundle: Box::new(TypedInsert(Unapproved)),
2180                })
2181                .is_ok()
2182        );
2183        assert!(matches!(
2184            bundle_queue.validate_and_apply(
2185                &mut world,
2186                &mut approved,
2187                application,
2188                generation,
2189                1,
2190                2,
2191            ),
2192            Err(CommandCommitError::Batch(CommandBatchError::Component(_)))
2193        ));
2194        assert_eq!(managed_entity_count(&world), 1);
2195        assert_eq!(world.get::<Marker>(raw).map(|marker| marker.0), Some(1));
2196        assert!(world.get::<Added>(raw).is_none());
2197    }
2198
2199    #[test]
2200    fn insert_snaps_only_explicit_or_newly_required_interpolation_values() {
2201        let (mut world, mut approved, application, generation) = setup();
2202        let mut moving = Transform2d::from_xy(1.0, 0.0).expect("finite transform");
2203        moving.begin_fixed_tick();
2204        moving
2205            .set_translation(sim_engine::Vec2::new(2.0, 0.0))
2206            .expect("finite movement");
2207        let raw = world.spawn((Marker(1), moving)).id();
2208        let entity = LogicEntity::new(application, generation, raw);
2209        world.entity_mut(raw).insert(ManagedEntity::new(entity));
2210        let mut preserve_queue = CommandQueue::new(1);
2211        assert!(
2212            preserve_queue
2213                .push(QueuedCommand::Insert {
2214                    entity,
2215                    bundle: Box::new(TypedInsert(NeedsTransform)),
2216                })
2217                .is_ok()
2218        );
2219        preserve_queue
2220            .validate_and_apply(&mut world, &mut approved, application, generation, 1, 1)
2221            .expect("required transform insertion should commit");
2222        let preserved = world.get::<Transform2d>(raw).expect("transform remains");
2223        assert_eq!(
2224            preserved.previous_translation(),
2225            sim_engine::Vec2::new(1.0, 0.0)
2226        );
2227        assert_eq!(preserved.translation(), sim_engine::Vec2::new(2.0, 0.0));
2228
2229        let mut replacement = Transform2d::from_xy(8.0, 0.0).expect("finite replacement transform");
2230        replacement.begin_fixed_tick();
2231        replacement
2232            .set_translation(sim_engine::Vec2::new(9.0, 0.0))
2233            .expect("finite replacement movement");
2234        let mut replace_queue = CommandQueue::new(1);
2235        assert!(
2236            replace_queue
2237                .push(QueuedCommand::Insert {
2238                    entity,
2239                    bundle: Box::new(TypedInsert(replacement)),
2240                })
2241                .is_ok()
2242        );
2243        replace_queue
2244            .validate_and_apply(&mut world, &mut approved, application, generation, 1, 1)
2245            .expect("explicit transform replacement should commit");
2246        let replaced = world.get::<Transform2d>(raw).expect("transform remains");
2247        assert_eq!(
2248            replaced.previous_translation(),
2249            sim_engine::Vec2::new(9.0, 0.0)
2250        );
2251        assert_eq!(replaced.translation(), sim_engine::Vec2::new(9.0, 0.0));
2252
2253        let plain_raw = world.spawn(Marker(2)).id();
2254        let plain = LogicEntity::new(application, generation, plain_raw);
2255        world
2256            .entity_mut(plain_raw)
2257            .insert(ManagedEntity::new(plain));
2258        let mut required_queue = CommandQueue::new(1);
2259        assert!(
2260            required_queue
2261                .push(QueuedCommand::Insert {
2262                    entity: plain,
2263                    bundle: Box::new(TypedInsert(NeedsTransform)),
2264                })
2265                .is_ok()
2266        );
2267        required_queue
2268            .validate_and_apply(&mut world, &mut approved, application, generation, 2, 2)
2269            .expect("missing required transform should materialize");
2270        let materialized = world
2271            .get::<Transform2d>(plain_raw)
2272            .expect("required transform exists");
2273        assert_eq!(
2274            materialized.previous_translation(),
2275            materialized.translation()
2276        );
2277
2278        let mut replacement_camera = ActiveCamera2d::new(
2279            sim_engine::Camera2d::new(sim_engine::Vec2::ZERO, 16.0)
2280                .expect("valid replacement camera"),
2281        );
2282        replacement_camera
2283            .set_center(sim_engine::Vec2::new(7.0, -2.0))
2284            .expect("finite replacement center");
2285        let mut camera_queue = CommandQueue::new(1);
2286        assert!(
2287            camera_queue
2288                .push(QueuedCommand::Insert {
2289                    entity: plain,
2290                    bundle: Box::new(TypedInsert(replacement_camera)),
2291                })
2292                .is_ok()
2293        );
2294        camera_queue
2295            .validate_and_apply(&mut world, &mut approved, application, generation, 2, 2)
2296            .expect("explicit camera insertion should commit");
2297        let camera = world
2298            .get::<ActiveCamera2d>(plain_raw)
2299            .expect("camera should be inserted");
2300        assert_eq!(camera.previous_center(), sim_engine::Vec2::new(7.0, -2.0));
2301        assert_eq!(camera.center(), sim_engine::Vec2::new(7.0, -2.0));
2302
2303        let precedence_raw = world.spawn(Marker(3)).id();
2304        let precedence = LogicEntity::new(application, generation, precedence_raw);
2305        world
2306            .entity_mut(precedence_raw)
2307            .insert(ManagedEntity::new(precedence));
2308        let mut explicit = Transform2d::from_xy(3.0, 0.0).expect("finite explicit transform");
2309        explicit.begin_fixed_tick();
2310        explicit
2311            .set_translation(sim_engine::Vec2::new(4.0, 0.0))
2312            .expect("finite explicit movement");
2313        let mut precedence_queue = CommandQueue::new(1);
2314        assert!(
2315            precedence_queue
2316                .push(QueuedCommand::Insert {
2317                    entity: precedence,
2318                    bundle: Box::new(TypedInsert((NeedsTransform, explicit))),
2319                })
2320                .is_ok()
2321        );
2322        precedence_queue
2323            .validate_and_apply(&mut world, &mut approved, application, generation, 3, 3)
2324            .expect("explicit Transform should satisfy the required component");
2325        let explicit = world
2326            .get::<Transform2d>(precedence_raw)
2327            .expect("explicit Transform should be retained");
2328        assert_eq!(
2329            explicit.previous_translation(),
2330            sim_engine::Vec2::new(4.0, 0.0)
2331        );
2332        assert_eq!(explicit.translation(), sim_engine::Vec2::new(4.0, 0.0));
2333    }
2334
2335    #[test]
2336    fn rejected_insert_drops_new_payload_once_without_replacing_old_value() {
2337        let (mut world, mut approved, application, generation) = setup();
2338        let old_drops = Arc::new(AtomicUsize::new(0));
2339        let new_drops = Arc::new(AtomicUsize::new(0));
2340        let raw = world
2341            .spawn((Marker(1), DropMarker(Arc::clone(&old_drops))))
2342            .id();
2343        let entity = LogicEntity::new(application, generation, raw);
2344        world.entity_mut(raw).insert(ManagedEntity::new(entity));
2345        let mut queue = CommandQueue::new(2);
2346        assert!(
2347            queue
2348                .push(QueuedCommand::Insert {
2349                    entity,
2350                    bundle: Box::new(TypedInsert(DropMarker(Arc::clone(&new_drops)))),
2351                })
2352                .is_ok()
2353        );
2354        assert!(queue.push(QueuedCommand::Despawn(entity)).is_ok());
2355
2356        assert!(matches!(
2357            queue.validate_and_apply(&mut world, &mut approved, application, generation, 1, 1),
2358            Err(CommandCommitError::Batch(
2359                CommandBatchError::ConflictingEntityCommands { .. }
2360            ))
2361        ));
2362        assert_eq!(new_drops.load(Ordering::SeqCst), 1);
2363        assert_eq!(old_drops.load(Ordering::SeqCst), 0);
2364        assert!(world.get::<DropMarker>(raw).is_some());
2365
2366        let discarded_drops = Arc::new(AtomicUsize::new(0));
2367        let mut discarded = CommandQueue::new(1);
2368        assert!(
2369            discarded
2370                .push(QueuedCommand::Insert {
2371                    entity,
2372                    bundle: Box::new(TypedInsert(DropMarker(Arc::clone(&discarded_drops)))),
2373                })
2374                .is_ok()
2375        );
2376        discarded.discard();
2377        assert_eq!(discarded_drops.load(Ordering::SeqCst), 1);
2378        assert_eq!(old_drops.load(Ordering::SeqCst), 0);
2379        assert!(world.get::<DropMarker>(raw).is_some());
2380    }
2381
2382    #[test]
2383    fn insert_obeys_queue_poison_and_reuses_command_storage() {
2384        let (mut world, mut approved, application, generation) = setup();
2385        let raw = world.spawn(Marker(1)).id();
2386        let entity = LogicEntity::new(application, generation, raw);
2387        world.entity_mut(raw).insert(ManagedEntity::new(entity));
2388        let retained_drops = Arc::new(AtomicUsize::new(0));
2389        let rejected_drops = Arc::new(AtomicUsize::new(0));
2390        let mut queue = CommandQueue::new(1);
2391        assert!(
2392            queue
2393                .push(QueuedCommand::Insert {
2394                    entity,
2395                    bundle: Box::new(TypedInsert(DropMarker(Arc::clone(&retained_drops)))),
2396                })
2397                .is_ok()
2398        );
2399        let capacity = queue.command_capacity();
2400        assert!(matches!(
2401            queue.push(QueuedCommand::Insert {
2402                entity,
2403                bundle: Box::new(TypedInsert(DropMarker(Arc::clone(&rejected_drops)))),
2404            }),
2405            Err(CommandEnqueueError::LimitExceeded { limit: 1 })
2406        ));
2407        assert_eq!(rejected_drops.load(Ordering::SeqCst), 1);
2408        assert_eq!(retained_drops.load(Ordering::SeqCst), 0);
2409
2410        assert!(matches!(
2411            queue.validate_and_apply(&mut world, &mut approved, application, generation, 1, 1),
2412            Err(CommandCommitError::Batch(
2413                CommandBatchError::LimitExceeded { limit: 1 }
2414            ))
2415        ));
2416        assert_eq!(retained_drops.load(Ordering::SeqCst), 1);
2417        assert!(world.get::<DropMarker>(raw).is_none());
2418        assert!(queue.is_clean());
2419        assert_eq!(queue.command_capacity(), capacity);
2420    }
2421
2422    #[test]
2423    fn repeated_exit_requests_coalesce_without_changing_entities() {
2424        let (mut world, mut approved, application, generation) = setup();
2425        let mut queue = CommandQueue::new(2);
2426        assert!(queue.push(QueuedCommand::Exit).is_ok());
2427        assert!(queue.push(QueuedCommand::Exit).is_ok());
2428        let capacity = queue.command_capacity();
2429
2430        let committed = queue
2431            .validate_and_apply(&mut world, &mut approved, application, generation, 0, 1)
2432            .expect("repeated exit requests should form one valid terminal request");
2433
2434        assert!(committed.exit_requested);
2435        assert_eq!(committed.spawned, 0);
2436        assert_eq!(committed.despawned, 0);
2437        assert_eq!(committed.live_entities, 0);
2438        assert!(committed.transitions.is_empty());
2439        assert!(queue.is_clean());
2440        assert_eq!(queue.command_capacity(), capacity);
2441
2442        assert!(queue.push(QueuedCommand::Exit).is_ok());
2443        assert!(queue.push(QueuedCommand::Exit).is_ok());
2444        assert!(matches!(
2445            queue.push(QueuedCommand::Exit),
2446            Err(CommandEnqueueError::LimitExceeded { limit: 2 })
2447        ));
2448        assert!(matches!(
2449            queue.validate_and_apply(&mut world, &mut approved, application, generation, 0, 1),
2450            Err(CommandCommitError::Batch(
2451                CommandBatchError::LimitExceeded { limit: 2 }
2452            ))
2453        ));
2454        assert!(queue.is_clean());
2455    }
2456
2457    #[test]
2458    fn pause_requests_are_inline_last_write_wins_and_use_exact_slots() {
2459        let (mut world, mut approved, application, generation) = setup();
2460        let mut queue = CommandQueue::new(3);
2461        assert!(queue.push(QueuedCommand::SetPaused(true)).is_ok());
2462        assert!(queue.push(QueuedCommand::spawn(Marker(4))).is_ok());
2463        assert!(queue.push(QueuedCommand::SetPaused(false)).is_ok());
2464        let capacity = queue.command_capacity();
2465
2466        let committed = queue
2467            .validate_and_apply(&mut world, &mut approved, application, generation, 0, 1)
2468            .expect("an exactly fitting pause/spawn batch should commit");
2469
2470        assert_eq!(committed.pause, Some(false));
2471        assert!(!committed.exit_requested);
2472        assert_eq!(committed.spawned, 1);
2473        assert!(matches!(
2474            world.query::<&Marker>().single(&world).map(|value| value.0),
2475            Ok(4)
2476        ));
2477        assert!(queue.is_clean());
2478        assert_eq!(queue.command_capacity(), capacity);
2479
2480        assert!(queue.push(QueuedCommand::SetPaused(true)).is_ok());
2481        assert!(queue.push(QueuedCommand::SetPaused(true)).is_ok());
2482        assert!(queue.push(QueuedCommand::SetPaused(true)).is_ok());
2483        assert!(matches!(
2484            queue.push(QueuedCommand::SetPaused(false)),
2485            Err(CommandEnqueueError::LimitExceeded { limit: 3 })
2486        ));
2487        assert!(matches!(
2488            queue.validate_and_apply(&mut world, &mut approved, application, generation, 1, 1),
2489            Err(CommandCommitError::Batch(
2490                CommandBatchError::LimitExceeded { limit: 3 }
2491            ))
2492        ));
2493        assert!(queue.is_clean());
2494    }
2495
2496    #[test]
2497    fn tracked_count_underflow_rejects_before_mutation() {
2498        let (mut world, mut approved, application, generation) = setup();
2499        let raw = world.spawn(Marker(1)).id();
2500        let entity = LogicEntity::new(application, generation, raw);
2501        world.entity_mut(raw).insert(ManagedEntity::new(entity));
2502        let mut queue = CommandQueue::new(1);
2503        assert!(queue.push(QueuedCommand::Despawn(entity)).is_ok());
2504        let command_capacity = queue.command_capacity();
2505
2506        let result =
2507            queue.validate_and_apply(&mut world, &mut approved, application, generation, 0, 1);
2508
2509        assert!(matches!(result, Err(CommandCommitError::RuntimeInvariant)));
2510        assert!(world.entities().contains(raw));
2511        assert_eq!(managed_entity_count(&world), 1);
2512        assert!(queue.is_clean());
2513        assert_eq!(queue.command_capacity(), command_capacity);
2514        assert!(queue.despawn_capacity() >= 1);
2515    }
2516
2517    #[test]
2518    fn duplicate_despawn_rejects_spawn_too() {
2519        let (mut world, mut approved, application, generation) = setup();
2520        let raw = world.spawn(Marker(1)).id();
2521        let entity = LogicEntity::new(application, generation, raw);
2522        world.entity_mut(raw).insert(ManagedEntity::new(entity));
2523        let mut queue = CommandQueue::new(4);
2524        assert!(queue.push(QueuedCommand::Despawn(entity)).is_ok());
2525        assert!(queue.push(QueuedCommand::Despawn(entity)).is_ok());
2526        assert!(queue.push(QueuedCommand::spawn(Marker(2))).is_ok());
2527        let command_capacity = queue.command_capacity();
2528
2529        let result =
2530            queue.validate_and_apply(&mut world, &mut approved, application, generation, 1, 8);
2531        assert!(matches!(
2532            result,
2533            Err(CommandCommitError::Batch(
2534                CommandBatchError::DuplicateDespawn { .. }
2535            ))
2536        ));
2537        assert_eq!(managed_entity_count(&world), 1);
2538        assert_eq!(world.get::<Marker>(raw).map(|marker| marker.0), Some(1));
2539        assert!(queue.is_clean());
2540        assert_eq!(queue.command_capacity(), command_capacity);
2541        assert!(queue.despawn_capacity() >= 2);
2542    }
2543
2544    #[test]
2545    fn foreign_generation_is_rejected() {
2546        let (mut world, mut approved, application, generation) = setup();
2547        let raw = world.spawn(Marker(1)).id();
2548        world
2549            .entity_mut(raw)
2550            .insert(ManagedEntity::new(LogicEntity::new(
2551                application,
2552                generation,
2553                raw,
2554            )));
2555        let foreign = LogicEntity::new(application, WorldGeneration::new(application, 2), raw);
2556        let mut queue = CommandQueue::new(2);
2557        assert!(queue.push(QueuedCommand::Despawn(foreign)).is_ok());
2558        let command_capacity = queue.command_capacity();
2559
2560        let result =
2561            queue.validate_and_apply(&mut world, &mut approved, application, generation, 1, 8);
2562        assert!(matches!(
2563            result,
2564            Err(CommandCommitError::Batch(
2565                CommandBatchError::ForeignEntity { .. }
2566            ))
2567        ));
2568        assert_eq!(managed_entity_count(&world), 1);
2569        assert!(queue.is_clean());
2570        assert_eq!(queue.command_capacity(), command_capacity);
2571        assert!(queue.despawn_capacity() >= 1);
2572    }
2573
2574    #[test]
2575    fn target_validation_rejects_mismatched_private_provenance() {
2576        let (mut world, mut approved, application, generation) = setup();
2577        let corrupted = WorldGeneration::new(application, 99);
2578        let raw = world
2579            .spawn((Marker(1), ManagedEntity::for_generation(corrupted)))
2580            .id();
2581        let entity = LogicEntity::new(application, generation, raw);
2582        let mut queue = CommandQueue::new(1);
2583        assert!(queue.push(QueuedCommand::Despawn(entity)).is_ok());
2584
2585        assert!(matches!(
2586            queue.validate_and_apply(
2587                &mut world,
2588                &mut approved,
2589                application,
2590                generation,
2591                1,
2592                8,
2593            ),
2594            Err(CommandCommitError::Batch(CommandBatchError::MissingEntity {
2595                entity: rejected
2596            })) if rejected == entity
2597        ));
2598        assert!(world.entities().contains(raw));
2599        assert_eq!(managed_entity_count(&world), 1);
2600    }
2601
2602    #[test]
2603    fn overflow_poison_rejects_retained_commands() {
2604        let (mut world, mut approved, application, generation) = setup();
2605        let mut queue = CommandQueue::new(1);
2606        let retained_drops = Arc::new(AtomicUsize::new(0));
2607        let rejected_drops = Arc::new(AtomicUsize::new(0));
2608        assert!(
2609            queue
2610                .push(QueuedCommand::spawn(DropMarker(Arc::clone(
2611                    &retained_drops,
2612                ))))
2613                .is_ok()
2614        );
2615        let command_capacity = queue.command_capacity();
2616        assert!(matches!(
2617            queue.push(QueuedCommand::spawn(DropMarker(Arc::clone(
2618                &rejected_drops,
2619            )))),
2620            Err(CommandEnqueueError::LimitExceeded { limit: 1 })
2621        ));
2622        assert_eq!(rejected_drops.load(Ordering::SeqCst), 1);
2623        assert_eq!(retained_drops.load(Ordering::SeqCst), 0);
2624
2625        let result =
2626            queue.validate_and_apply(&mut world, &mut approved, application, generation, 0, 8);
2627        assert!(matches!(
2628            result,
2629            Err(CommandCommitError::Batch(
2630                CommandBatchError::LimitExceeded { limit: 1 }
2631            ))
2632        ));
2633        assert_eq!(managed_entity_count(&world), 0);
2634        assert_eq!(retained_drops.load(Ordering::SeqCst), 1);
2635        assert!(queue.is_clean());
2636        assert_eq!(queue.command_capacity(), command_capacity);
2637    }
2638
2639    #[test]
2640    fn disabled_entities_still_consume_the_hard_command_limit() {
2641        let (mut world, mut approved, application, generation) = setup();
2642        let raw = world.spawn((Marker(1), Disabled)).id();
2643        let entity = LogicEntity::new(application, generation, raw);
2644        world.entity_mut(raw).insert(ManagedEntity::new(entity));
2645        let mut queue = CommandQueue::new(1);
2646        assert!(queue.push(QueuedCommand::spawn(Marker(2))).is_ok());
2647        let command_capacity = queue.command_capacity();
2648
2649        let result =
2650            queue.validate_and_apply(&mut world, &mut approved, application, generation, 1, 1);
2651
2652        assert!(matches!(
2653            result,
2654            Err(CommandCommitError::Batch(
2655                CommandBatchError::EntityLimitExceeded {
2656                    limit: 1,
2657                    requested: 2,
2658                }
2659            ))
2660        ));
2661        assert_eq!(managed_entity_count(&world), 1);
2662        assert!(queue.is_clean());
2663        assert_eq!(queue.command_capacity(), command_capacity);
2664    }
2665
2666    #[test]
2667    fn successful_batches_reuse_command_and_despawn_capacity() {
2668        let (mut world, mut approved, application, generation) = setup();
2669        let mut entities = Vec::new();
2670        for value in 0..4 {
2671            let raw = world.spawn(Marker(value)).id();
2672            let entity = LogicEntity::new(application, generation, raw);
2673            world.entity_mut(raw).insert(ManagedEntity::new(entity));
2674            entities.push(entity);
2675        }
2676        let mut queue = CommandQueue::new(4);
2677
2678        for entity in &entities {
2679            assert!(queue.push(QueuedCommand::Despawn(*entity)).is_ok());
2680        }
2681        let command_capacity = queue.command_capacity();
2682        let first = queue
2683            .validate_and_apply(&mut world, &mut approved, application, generation, 4, 4)
2684            .expect("first warmed batch should commit");
2685        let despawn_capacity = queue.despawn_capacity();
2686        assert_eq!(first.despawned, 4);
2687        assert!(queue.is_clean());
2688        assert!(despawn_capacity >= 4);
2689
2690        let mut second_entities = Vec::new();
2691        for value in 4..8 {
2692            let raw = world.spawn(Marker(value)).id();
2693            let entity = LogicEntity::new(application, generation, raw);
2694            world.entity_mut(raw).insert(ManagedEntity::new(entity));
2695            second_entities.push(entity);
2696        }
2697        for entity in second_entities {
2698            assert!(queue.push(QueuedCommand::Despawn(entity)).is_ok());
2699        }
2700        assert_eq!(queue.command_capacity(), command_capacity);
2701        let second = queue
2702            .validate_and_apply(&mut world, &mut approved, application, generation, 4, 4)
2703            .expect("second equal-sized batch should commit");
2704        assert_eq!(second.despawned, 4);
2705        assert!(queue.is_clean());
2706        assert_eq!(queue.command_capacity(), command_capacity);
2707        assert_eq!(queue.despawn_capacity(), despawn_capacity);
2708    }
2709
2710    #[test]
2711    fn discard_drops_payloads_and_retains_command_capacity() {
2712        let drops = Arc::new(AtomicUsize::new(0));
2713        let mut queue = CommandQueue::new(2);
2714        assert!(
2715            queue
2716                .push(QueuedCommand::spawn(DropMarker(Arc::clone(&drops))))
2717                .is_ok()
2718        );
2719        let command_capacity = queue.command_capacity();
2720
2721        queue.discard();
2722
2723        assert_eq!(drops.load(Ordering::SeqCst), 1);
2724        assert!(queue.is_clean());
2725        assert_eq!(queue.command_capacity(), command_capacity);
2726    }
2727}