Skip to main content

elevator_core/
events.rs

1//! Simulation event bus and typed event channels.
2
3use crate::components::CallDirection;
4use crate::entity::EntityId;
5use crate::error::{RejectionContext, RejectionReason};
6use crate::ids::GroupId;
7use ordered_float::OrderedFloat;
8use serde::{Deserialize, Serialize};
9
10/// Events emitted by the simulation during ticks.
11///
12/// All entity references use `EntityId`. Games can look up additional
13/// component data on the referenced entity if needed.
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15#[non_exhaustive]
16pub enum Event {
17    // -- Elevator events --
18    /// An elevator departed from a stop.
19    ElevatorDeparted {
20        /// The elevator that departed.
21        elevator: EntityId,
22        /// The stop it departed from.
23        from_stop: EntityId,
24        /// The tick when departure occurred.
25        tick: u64,
26    },
27    /// An elevator arrived at a stop.
28    ElevatorArrived {
29        /// The elevator that arrived.
30        elevator: EntityId,
31        /// The stop it arrived at.
32        at_stop: EntityId,
33        /// The tick when arrival occurred.
34        tick: u64,
35    },
36    /// An elevator's doors finished opening.
37    DoorOpened {
38        /// The elevator whose doors opened.
39        elevator: EntityId,
40        /// The tick when the doors opened.
41        tick: u64,
42    },
43    /// An elevator's doors finished closing.
44    DoorClosed {
45        /// The elevator whose doors closed.
46        elevator: EntityId,
47        /// The tick when the doors closed.
48        tick: u64,
49    },
50    /// Emitted when an elevator passes a stop without stopping.
51    /// Games/dispatch can use this to decide whether to add stops mid-travel.
52    PassingFloor {
53        /// The elevator passing by.
54        elevator: EntityId,
55        /// The stop being passed.
56        stop: EntityId,
57        /// Direction: true = moving up, false = moving down.
58        moving_up: bool,
59        /// The tick when the pass occurred.
60        tick: u64,
61    },
62    /// An in-flight movement was aborted by
63    /// [`Simulation::abort_movement`](crate::sim::Simulation::abort_movement).
64    ///
65    /// The car brakes along its normal deceleration profile, re-targets to
66    /// the nearest reachable stop, and arrives there without opening doors
67    /// (onboard riders stay aboard). The pending destination queue is also
68    /// cleared as part of the abort.
69    ///
70    /// Emitted at abort time — the car is still in flight, decelerating
71    /// toward `brake_target`. A normal [`Event::ElevatorArrived`] fires
72    /// once the car actually reaches the stop.
73    MovementAborted {
74        /// The elevator whose trip was aborted.
75        elevator: EntityId,
76        /// The stop the car will brake to and park at.
77        brake_target: EntityId,
78        /// The tick when the abort was requested.
79        tick: u64,
80    },
81
82    // -- Rider events (unified: passengers, cargo, any rideable entity) --
83    /// A new rider appeared at a stop and wants to travel.
84    RiderSpawned {
85        /// The spawned rider entity.
86        rider: EntityId,
87        /// The stop where the rider appeared.
88        origin: EntityId,
89        /// The stop the rider wants to reach.
90        destination: EntityId,
91        /// The tick when the rider spawned.
92        tick: u64,
93    },
94    /// A rider boarded an elevator.
95    RiderBoarded {
96        /// The rider that boarded.
97        rider: EntityId,
98        /// The elevator the rider boarded.
99        elevator: EntityId,
100        /// The tick when boarding occurred.
101        tick: u64,
102    },
103    /// A rider exited an elevator at a stop.
104    #[serde(alias = "RiderAlighted")]
105    RiderExited {
106        /// The rider that exited.
107        rider: EntityId,
108        /// The elevator the rider exited.
109        elevator: EntityId,
110        /// The stop where the rider exited.
111        stop: EntityId,
112        /// The tick when exiting occurred.
113        tick: u64,
114    },
115    /// A rider was rejected from boarding (e.g., over capacity).
116    RiderRejected {
117        /// The rider that was rejected.
118        rider: EntityId,
119        /// The elevator that rejected the rider.
120        elevator: EntityId,
121        /// The reason for rejection.
122        reason: RejectionReason,
123        /// Additional numeric context for the rejection.
124        context: Option<RejectionContext>,
125        /// The tick when rejection occurred.
126        tick: u64,
127    },
128    /// A rider gave up waiting and left the stop.
129    RiderAbandoned {
130        /// The rider that abandoned.
131        rider: EntityId,
132        /// The stop the rider left.
133        stop: EntityId,
134        /// The tick when abandonment occurred.
135        tick: u64,
136    },
137
138    /// A rider was ejected from an elevator (due to disable or despawn).
139    ///
140    /// The rider is moved to `Waiting` phase at the nearest stop.
141    RiderEjected {
142        /// The rider that was ejected.
143        rider: EntityId,
144        /// The elevator the rider was ejected from.
145        elevator: EntityId,
146        /// The stop the rider was placed at.
147        stop: EntityId,
148        /// The tick when ejection occurred.
149        tick: u64,
150    },
151
152    // -- Dispatch events --
153    /// An elevator was assigned to serve a stop by the dispatcher.
154    ElevatorAssigned {
155        /// The elevator that was assigned.
156        elevator: EntityId,
157        /// The stop it was assigned to serve.
158        stop: EntityId,
159        /// The tick when the assignment occurred.
160        tick: u64,
161    },
162
163    // -- Topology lifecycle events --
164    /// A new stop was added to the simulation.
165    StopAdded {
166        /// The new stop entity.
167        stop: EntityId,
168        /// The line the stop was added to.
169        line: EntityId,
170        /// The group the stop was added to.
171        group: GroupId,
172        /// The tick when the stop was added.
173        tick: u64,
174    },
175    /// A new elevator was added to the simulation.
176    ElevatorAdded {
177        /// The new elevator entity.
178        elevator: EntityId,
179        /// The line the elevator was added to.
180        line: EntityId,
181        /// The group the elevator was added to.
182        group: GroupId,
183        /// The tick when the elevator was added.
184        tick: u64,
185    },
186    /// An entity was disabled.
187    EntityDisabled {
188        /// The entity that was disabled.
189        entity: EntityId,
190        /// The tick when it was disabled.
191        tick: u64,
192    },
193    /// An entity was re-enabled.
194    EntityEnabled {
195        /// The entity that was re-enabled.
196        entity: EntityId,
197        /// The tick when it was enabled.
198        tick: u64,
199    },
200    /// A rider's route was invalidated due to topology change.
201    ///
202    /// Emitted when a stop on a rider's route is disabled or removed.
203    /// If no alternative is found, the rider will abandon after a grace period.
204    RouteInvalidated {
205        /// The affected rider.
206        rider: EntityId,
207        /// The stop that caused the invalidation.
208        affected_stop: EntityId,
209        /// Why the route was invalidated.
210        reason: RouteInvalidReason,
211        /// The tick when invalidation occurred.
212        tick: u64,
213    },
214    /// A rider was manually rerouted via `sim.reroute()` or `sim.reroute_rider()`.
215    RiderRerouted {
216        /// The rerouted rider.
217        rider: EntityId,
218        /// The new destination stop.
219        new_destination: EntityId,
220        /// The tick when rerouting occurred.
221        tick: u64,
222    },
223
224    /// A rider settled at a stop, becoming a resident.
225    RiderSettled {
226        /// The rider that settled.
227        rider: EntityId,
228        /// The stop where the rider settled.
229        stop: EntityId,
230        /// The tick when settlement occurred.
231        tick: u64,
232    },
233    /// A rider was removed from the simulation.
234    RiderDespawned {
235        /// The rider that was removed.
236        rider: EntityId,
237        /// The tick when despawn occurred.
238        tick: u64,
239    },
240
241    // -- Line lifecycle events --
242    /// A line was added to the simulation.
243    LineAdded {
244        /// The new line entity.
245        line: EntityId,
246        /// The group the line was added to.
247        group: GroupId,
248        /// The tick when the line was added.
249        tick: u64,
250    },
251    /// A line was removed from the simulation.
252    LineRemoved {
253        /// The removed line entity.
254        line: EntityId,
255        /// The group the line belonged to.
256        group: GroupId,
257        /// The tick when the line was removed.
258        tick: u64,
259    },
260    /// A line was reassigned to a different group.
261    LineReassigned {
262        /// The line entity that was reassigned.
263        line: EntityId,
264        /// The group the line was previously in.
265        old_group: GroupId,
266        /// The group the line was moved to.
267        new_group: GroupId,
268        /// The tick when reassignment occurred.
269        tick: u64,
270    },
271    /// An elevator was reassigned to a different line.
272    ElevatorReassigned {
273        /// The elevator that was reassigned.
274        elevator: EntityId,
275        /// The line the elevator was previously on.
276        old_line: EntityId,
277        /// The line the elevator was moved to.
278        new_line: EntityId,
279        /// The tick when reassignment occurred.
280        tick: u64,
281    },
282
283    // -- Repositioning events --
284    /// An elevator is being repositioned to improve coverage.
285    ///
286    /// Emitted when an idle elevator begins moving to a new position
287    /// as decided by the [`RepositionStrategy`](crate::dispatch::RepositionStrategy).
288    ElevatorRepositioning {
289        /// The elevator being repositioned.
290        elevator: EntityId,
291        /// The stop it is being sent to.
292        to_stop: EntityId,
293        /// The tick when repositioning began.
294        tick: u64,
295    },
296    /// An elevator completed repositioning and arrived at its target.
297    ///
298    /// Note: this is detected by the movement system — the elevator
299    /// arrives just like any other movement. Games can distinguish
300    /// repositioning arrivals from dispatch arrivals by tracking
301    /// which elevators received `ElevatorRepositioning` events.
302    ElevatorRepositioned {
303        /// The elevator that completed repositioning.
304        elevator: EntityId,
305        /// The stop it arrived at.
306        at_stop: EntityId,
307        /// The tick when it arrived.
308        tick: u64,
309    },
310
311    /// An elevator's service mode was changed.
312    ServiceModeChanged {
313        /// The elevator whose mode changed.
314        elevator: EntityId,
315        /// The previous service mode.
316        from: crate::components::ServiceMode,
317        /// The new service mode.
318        to: crate::components::ServiceMode,
319        /// The tick when the change occurred.
320        tick: u64,
321    },
322
323    // -- Observability events --
324    /// Energy consumed/regenerated by an elevator this tick.
325    ///
326    /// Requires the `energy` feature.
327    #[cfg(feature = "energy")]
328    EnergyConsumed {
329        /// The elevator that consumed energy.
330        elevator: EntityId,
331        /// Energy consumed this tick.
332        consumed: OrderedFloat<f64>,
333        /// Energy regenerated this tick.
334        regenerated: OrderedFloat<f64>,
335        /// The tick when energy was recorded.
336        tick: u64,
337    },
338
339    /// An elevator's load changed (rider boarded or exited).
340    ///
341    /// Emitted immediately after [`RiderBoarded`](Self::RiderBoarded) or
342    /// [`RiderExited`](Self::RiderExited). Useful for real-time capacity
343    /// bar displays in game UIs.
344    ///
345    /// Load values use [`OrderedFloat`] for
346    /// `Eq` compatibility. Dereference to get the inner `f64`:
347    ///
348    /// ```rust,no_run
349    /// use elevator_core::events::Event;
350    /// # fn handle(event: Event) {
351    /// if let Event::CapacityChanged { current_load, capacity, .. } = event {
352    ///     let pct = *current_load / *capacity * 100.0;
353    ///     println!("Elevator at {pct:.0}% capacity");
354    /// }
355    /// # }
356    /// ```
357    CapacityChanged {
358        /// The elevator whose load changed.
359        elevator: EntityId,
360        /// Current total weight aboard after the change.
361        current_load: OrderedFloat<f64>,
362        /// Maximum weight capacity of the elevator.
363        capacity: OrderedFloat<f64>,
364        /// The tick when the change occurred.
365        tick: u64,
366    },
367
368    /// An elevator became idle (no more assignments or repositioning).
369    ElevatorIdle {
370        /// The elevator that became idle.
371        elevator: EntityId,
372        /// The stop where it became idle (if at a stop).
373        at_stop: Option<EntityId>,
374        /// The tick when it became idle.
375        tick: u64,
376    },
377
378    /// An elevator's direction indicator lamps changed.
379    ///
380    /// Emitted by the dispatch phase when the pair
381    /// `(going_up, going_down)` transitions to a new value — e.g. when
382    /// a car is assigned a target above it (up-only), below it (down-only),
383    /// or returns to idle (both lamps lit).
384    ///
385    /// Games can use this for UI (lighting up-arrow / down-arrow indicators
386    /// on a car) without polling the elevator each tick.
387    DirectionIndicatorChanged {
388        /// The elevator whose indicator lamps changed.
389        elevator: EntityId,
390        /// New state of the up-direction lamp.
391        going_up: bool,
392        /// New state of the down-direction lamp.
393        going_down: bool,
394        /// The tick when the change occurred.
395        tick: u64,
396    },
397
398    /// An elevator was permanently removed from the simulation.
399    ///
400    /// Distinct from [`Event::EntityDisabled`] — a disabled elevator can be
401    /// re-enabled, but a removed elevator is despawned.
402    ElevatorRemoved {
403        /// The elevator that was removed.
404        elevator: EntityId,
405        /// The line it belonged to.
406        line: EntityId,
407        /// The group it belonged to.
408        group: GroupId,
409        /// The tick when removal occurred.
410        tick: u64,
411    },
412
413    /// A stop was queued as a destination for an elevator.
414    ///
415    /// Emitted by [`Simulation::push_destination`](crate::sim::Simulation::push_destination),
416    /// [`Simulation::push_destination_front`](crate::sim::Simulation::push_destination_front),
417    /// and the built-in dispatch phase whenever it actually appends a stop
418    /// to an elevator's [`DestinationQueue`](crate::components::DestinationQueue).
419    /// Adjacent-duplicate pushes (that are deduplicated) do not emit.
420    DestinationQueued {
421        /// The elevator whose queue was updated.
422        elevator: EntityId,
423        /// The stop that was queued.
424        stop: EntityId,
425        /// The tick when the push occurred.
426        tick: u64,
427    },
428
429    /// A stop was permanently removed from the simulation.
430    ///
431    /// Distinct from [`Event::EntityDisabled`] — a disabled stop can be
432    /// re-enabled, but a removed stop is despawned.
433    StopRemoved {
434        /// The stop that was removed.
435        stop: EntityId,
436        /// The tick when removal occurred.
437        tick: u64,
438    },
439
440    /// A manual door-control command was received and either applied
441    /// immediately or stored for later.
442    ///
443    /// Emitted by
444    /// [`Simulation::open_door`](crate::sim::Simulation::open_door),
445    /// [`Simulation::close_door`](crate::sim::Simulation::close_door),
446    /// [`Simulation::hold_door`](crate::sim::Simulation::hold_door),
447    /// and [`Simulation::cancel_door_hold`](crate::sim::Simulation::cancel_door_hold)
448    /// when the command is accepted. Paired with
449    /// [`Event::DoorCommandApplied`] when the command eventually takes effect.
450    DoorCommandQueued {
451        /// The elevator targeted by the command.
452        elevator: EntityId,
453        /// The command that was queued.
454        command: crate::door::DoorCommand,
455        /// The tick when the command was submitted.
456        tick: u64,
457    },
458    /// A queued door-control command actually took effect — doors began
459    /// opening/closing or a hold was applied.
460    DoorCommandApplied {
461        /// The elevator the command applied to.
462        elevator: EntityId,
463        /// The command that was applied.
464        command: crate::door::DoorCommand,
465        /// The tick when the command was applied.
466        tick: u64,
467    },
468
469    /// An elevator parameter was mutated at runtime via one of the
470    /// `Simulation::set_*` upgrade setters (e.g. buying a speed upgrade
471    /// in an RPG, or a scripted event changing capacity mid-game).
472    ///
473    /// Emitted immediately when the setter succeeds. Games can use this
474    /// to trigger score popups, SFX, or UI updates.
475    ElevatorUpgraded {
476        /// The elevator whose parameter changed.
477        elevator: EntityId,
478        /// Which field was changed.
479        field: UpgradeField,
480        /// Previous value of the field.
481        old: UpgradeValue,
482        /// New value of the field.
483        new: UpgradeValue,
484        /// The tick when the upgrade was applied.
485        tick: u64,
486    },
487
488    /// A velocity command was submitted to an elevator running in
489    /// [`ServiceMode::Manual`](crate::components::ServiceMode::Manual).
490    ///
491    /// Emitted by
492    /// [`Simulation::set_target_velocity`](crate::sim::Simulation::set_target_velocity)
493    /// and [`Simulation::emergency_stop`](crate::sim::Simulation::emergency_stop).
494    ManualVelocityCommanded {
495        /// The elevator targeted by the command.
496        elevator: EntityId,
497        /// The new target velocity (clamped to `[-max_speed, max_speed]`),
498        /// or `None` when the command clears the target.
499        target_velocity: Option<ordered_float::OrderedFloat<f64>>,
500        /// The tick when the command was submitted.
501        tick: u64,
502    },
503
504    // -- Hall & car call events --
505    /// A hall button was pressed. Fires immediately, before any ack
506    /// latency delay. Games use this for button-light animations or SFX.
507    HallButtonPressed {
508        /// Stop where the press occurred.
509        stop: EntityId,
510        /// Direction the button requests service in.
511        direction: CallDirection,
512        /// Tick of the press.
513        tick: u64,
514    },
515    /// A hall call has elapsed its ack latency and is now visible to
516    /// dispatch. Useful for UI confirmations ("your call has been
517    /// received"). In groups with `ack_latency_ticks = 0` this fires on
518    /// the same tick as `HallButtonPressed`.
519    HallCallAcknowledged {
520        /// Stop the call was placed at.
521        stop: EntityId,
522        /// Direction of the call.
523        direction: CallDirection,
524        /// Tick acknowledgement completed.
525        tick: u64,
526    },
527    /// A hall call was cleared when an assigned car arrived at the stop
528    /// with matching direction indicators. Corresponds to the real-world
529    /// button-light turning off.
530    HallCallCleared {
531        /// Stop whose call was cleared.
532        stop: EntityId,
533        /// Direction of the cleared call.
534        direction: CallDirection,
535        /// Car that cleared the call by arriving.
536        car: EntityId,
537        /// Tick the call was cleared.
538        tick: u64,
539    },
540    /// A rider inside a car pressed a floor button (Classic mode only).
541    /// In Destination mode riders reveal destinations at the hall
542    /// kiosk, so no car buttons are pressed.
543    CarButtonPressed {
544        /// Elevator the button was pressed inside.
545        car: EntityId,
546        /// Floor the rider requested.
547        floor: EntityId,
548        /// Rider who pressed the button. `None` when the press is
549        /// synthetic — e.g. issued via
550        /// [`Simulation::press_car_button`](crate::sim::Simulation::press_car_button)
551        /// for scripted events, player input, or cutscene cues with no
552        /// associated rider entity.
553        rider: Option<EntityId>,
554        /// Tick of the press.
555        tick: u64,
556    },
557    /// A rider skipped boarding a car they considered too crowded
558    /// (their preferences filtered the car out). The rider remains
559    /// Waiting and may board a later car.
560    #[serde(alias = "RiderBalked")]
561    RiderSkipped {
562        /// Rider who skipped.
563        rider: EntityId,
564        /// Elevator they declined to board.
565        elevator: EntityId,
566        /// Stop where the skip happened.
567        at_stop: EntityId,
568        /// Tick of the skip.
569        tick: u64,
570    },
571    /// A snapshot restore encountered an entity reference that could not
572    /// be remapped. The original (now-invalid) ID was kept. This signals
573    /// a corrupted or hand-edited snapshot.
574    SnapshotDanglingReference {
575        /// The entity ID from the snapshot that had no mapping.
576        stale_id: EntityId,
577        /// Tick from the snapshot at restore time.
578        tick: u64,
579    },
580    /// A snapshot restore could not re-instantiate the reposition strategy
581    /// for a group (e.g. custom strategy not registered). Idle elevator
582    /// positioning will not work for this group until the game calls
583    /// [`Simulation::set_reposition`](crate::sim::Simulation::set_reposition).
584    RepositionStrategyNotRestored {
585        /// The group whose strategy was lost.
586        group: GroupId,
587    },
588    /// A stop was removed while resident riders were present.
589    /// The game must relocate or despawn these riders.
590    ResidentsAtRemovedStop {
591        /// The removed stop.
592        stop: EntityId,
593        /// Riders that were resident at the stop.
594        residents: Vec<EntityId>,
595    },
596}
597
598/// Identifies which elevator parameter was changed in an
599/// [`Event::ElevatorUpgraded`].
600#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
601#[non_exhaustive]
602pub enum UpgradeField {
603    /// Maximum travel speed (distance/tick).
604    MaxSpeed,
605    /// Acceleration rate (distance/tick^2).
606    Acceleration,
607    /// Deceleration rate (distance/tick^2).
608    Deceleration,
609    /// Maximum weight the car can carry.
610    WeightCapacity,
611    /// Ticks for a door open/close transition.
612    DoorTransitionTicks,
613    /// Ticks the door stays fully open.
614    DoorOpenTicks,
615}
616
617impl std::fmt::Display for UpgradeField {
618    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
619        match self {
620            Self::MaxSpeed => write!(f, "max_speed"),
621            Self::Acceleration => write!(f, "acceleration"),
622            Self::Deceleration => write!(f, "deceleration"),
623            Self::WeightCapacity => write!(f, "weight_capacity"),
624            Self::DoorTransitionTicks => write!(f, "door_transition_ticks"),
625            Self::DoorOpenTicks => write!(f, "door_open_ticks"),
626        }
627    }
628}
629
630/// Old-or-new value carried by [`Event::ElevatorUpgraded`].
631///
632/// Uses [`OrderedFloat`] for the float variant so the event enum
633/// remains `Eq`-comparable alongside the other observability events.
634#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
635#[non_exhaustive]
636pub enum UpgradeValue {
637    /// A floating-point parameter value (speed, accel, decel, capacity).
638    Float(OrderedFloat<f64>),
639    /// An integral tick-count parameter value (door timings).
640    Ticks(u32),
641}
642
643impl UpgradeValue {
644    /// Construct a float-valued upgrade payload.
645    #[must_use]
646    pub const fn float(v: f64) -> Self {
647        Self::Float(OrderedFloat(v))
648    }
649
650    /// Construct a tick-valued upgrade payload.
651    #[must_use]
652    pub const fn ticks(v: u32) -> Self {
653        Self::Ticks(v)
654    }
655}
656
657impl std::fmt::Display for UpgradeValue {
658    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
659        match self {
660            Self::Float(v) => write!(f, "{}", **v),
661            Self::Ticks(v) => write!(f, "{v}"),
662        }
663    }
664}
665
666/// Reason a rider's route was invalidated.
667#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
668#[non_exhaustive]
669pub enum RouteInvalidReason {
670    /// A stop on the route was disabled.
671    StopDisabled,
672    /// No alternative stop is available in the same group.
673    NoAlternative,
674}
675
676/// Coarse-grained classification of an [`Event`].
677///
678/// Exposes the same grouping that the `Event` variants are already
679/// commented under, so consumers can filter a drained event stream with
680/// one match arm per category rather than enumerating ~25 variants.
681#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
682#[non_exhaustive]
683pub enum EventCategory {
684    /// Elevator motion, arrival/departure, and door state.
685    Elevator,
686    /// Rider lifecycle: spawn, board, exit, reject, abandon, despawn, settle, reroute.
687    Rider,
688    /// Dispatch decisions and bookkeeping.
689    Dispatch,
690    /// Runtime topology mutations (entities/lines/groups added, removed, reassigned).
691    Topology,
692    /// Idle-elevator repositioning activity.
693    Reposition,
694    /// Direction indicator lamp state changes.
695    Direction,
696    /// Observability and misc signals (capacity, service mode, energy, etc.).
697    Observability,
698}
699
700impl Event {
701    /// Classify this event into a coarse-grained [`EventCategory`].
702    ///
703    /// Useful when a consumer only cares about, say, rider activity and
704    /// wants to skip elevator-motion and topology chatter without
705    /// enumerating every variant. The exhaustive match inside guarantees
706    /// the method stays in sync when new variants are added.
707    #[must_use]
708    pub const fn category(&self) -> EventCategory {
709        match self {
710            Self::ElevatorDeparted { .. }
711            | Self::ElevatorArrived { .. }
712            | Self::DoorOpened { .. }
713            | Self::DoorClosed { .. }
714            | Self::DoorCommandQueued { .. }
715            | Self::DoorCommandApplied { .. }
716            | Self::PassingFloor { .. }
717            | Self::MovementAborted { .. }
718            | Self::ElevatorIdle { .. } => EventCategory::Elevator,
719            Self::RiderSpawned { .. }
720            | Self::RiderBoarded { .. }
721            | Self::RiderExited { .. }
722            | Self::RiderRejected { .. }
723            | Self::RiderAbandoned { .. }
724            | Self::RiderEjected { .. }
725            | Self::RouteInvalidated { .. }
726            | Self::RiderRerouted { .. }
727            | Self::RiderSettled { .. }
728            | Self::RiderDespawned { .. } => EventCategory::Rider,
729            Self::ElevatorAssigned { .. } | Self::DestinationQueued { .. } => {
730                EventCategory::Dispatch
731            }
732            Self::StopAdded { .. }
733            | Self::StopRemoved { .. }
734            | Self::ElevatorAdded { .. }
735            | Self::ElevatorRemoved { .. }
736            | Self::EntityDisabled { .. }
737            | Self::EntityEnabled { .. }
738            | Self::LineAdded { .. }
739            | Self::LineRemoved { .. }
740            | Self::LineReassigned { .. }
741            | Self::ElevatorReassigned { .. } => EventCategory::Topology,
742            Self::ElevatorRepositioning { .. } | Self::ElevatorRepositioned { .. } => {
743                EventCategory::Reposition
744            }
745            Self::DirectionIndicatorChanged { .. } => EventCategory::Direction,
746            Self::ServiceModeChanged { .. }
747            | Self::CapacityChanged { .. }
748            | Self::ElevatorUpgraded { .. }
749            | Self::ManualVelocityCommanded { .. } => EventCategory::Observability,
750            #[cfg(feature = "energy")]
751            Self::EnergyConsumed { .. } => EventCategory::Observability,
752            Self::HallButtonPressed { .. }
753            | Self::HallCallAcknowledged { .. }
754            | Self::HallCallCleared { .. }
755            | Self::CarButtonPressed { .. } => EventCategory::Dispatch,
756            Self::RiderSkipped { .. } => EventCategory::Rider,
757            Self::SnapshotDanglingReference { .. } | Self::RepositionStrategyNotRestored { .. } => {
758                EventCategory::Observability
759            }
760            Self::ResidentsAtRemovedStop { .. } => EventCategory::Topology,
761        }
762    }
763}
764
765/// Collects simulation events for consumers to drain.
766#[derive(Debug, Default)]
767pub struct EventBus {
768    /// The pending events not yet consumed.
769    events: Vec<Event>,
770}
771
772impl EventBus {
773    /// Pushes a new event onto the bus.
774    pub fn emit(&mut self, event: Event) {
775        self.events.push(event);
776    }
777
778    /// Returns and clears all pending events.
779    pub fn drain(&mut self) -> Vec<Event> {
780        std::mem::take(&mut self.events)
781    }
782
783    /// Returns a slice of all pending events without clearing them.
784    #[must_use]
785    pub fn peek(&self) -> &[Event] {
786        &self.events
787    }
788}
789
790/// A typed event channel for game-specific events.
791///
792/// Games insert this as a global resource on `World`:
793///
794/// ```
795/// use elevator_core::world::World;
796/// use elevator_core::events::EventChannel;
797///
798/// #[derive(Debug)]
799/// enum MyGameEvent { Foo, Bar }
800///
801/// let mut world = World::new();
802/// world.insert_resource(EventChannel::<MyGameEvent>::new());
803/// // Later:
804/// world.resource_mut::<EventChannel<MyGameEvent>>().unwrap().emit(MyGameEvent::Foo);
805/// ```
806#[derive(Debug)]
807pub struct EventChannel<T> {
808    /// Pending events not yet consumed.
809    events: Vec<T>,
810}
811
812impl<T> EventChannel<T> {
813    /// Create an empty event channel.
814    #[must_use]
815    pub const fn new() -> Self {
816        Self { events: Vec::new() }
817    }
818
819    /// Emit an event into the channel.
820    pub fn emit(&mut self, event: T) {
821        self.events.push(event);
822    }
823
824    /// Drain and return all pending events.
825    pub fn drain(&mut self) -> Vec<T> {
826        std::mem::take(&mut self.events)
827    }
828
829    /// Peek at pending events without clearing.
830    #[must_use]
831    pub fn peek(&self) -> &[T] {
832        &self.events
833    }
834
835    /// Check if the channel has no pending events.
836    #[must_use]
837    pub const fn is_empty(&self) -> bool {
838        self.events.is_empty()
839    }
840
841    /// Number of pending events.
842    #[must_use]
843    pub const fn len(&self) -> usize {
844        self.events.len()
845    }
846}
847
848impl<T> Default for EventChannel<T> {
849    fn default() -> Self {
850        Self::new()
851    }
852}