๐ EventBus architecture in SS14
EventBus is the central nervous system of the Space Station 14 (RobustToolbox) engine. It orchestrates communication between systems and entities, implementing a highly optimized dispatch mechanism without unnecessary allocations. ๐ง
๐๏ธ Basic Architecture
EventBus is implemented through the IEventBus interface and combines two different event paradigms:
- Broadcast Events: Global events sent to all subscribers of a certain type. ๐
- Directed Events: Events targeting a specific entity are sent only to components on that entity. ๐ฏ
๐พ Internal Storage
To achieve high performance, EventBus supports several specialized data structures:
- Broadcast Subscriptions (
_eventData): - Dictionary
Type->EventData. - Stores a list of all global subscribers for each event type.
- Used for broadcast events and system notifications.
- Directed Subscriptions (
_eventSubsand_compEventSubs): - Array structure of arrays (jagged array), indexed by
CompIdx(Component Index). _eventSubs[CompIdx]: MapsEventType->Handler.- Allows you to search for component handlers for a specific event in O(1). โก
- Divided into general events and optimized Component Events (see below).
- Entity Event Tables (
_entEventTables): - Dictionary stored for each active
EntityUid. - Displays
EventType->LinkedList<CompIdx>. - Keeps track of which components on a specific entity are listening to a specific event.
- This prevents iterating through all entity components to find listeners. ๐ซ๐
๐ญ Event Paradigms
1. Broadcast Events (`RaiseEvent`) ๐ข
- Target: No specific entity. Global scope.
- Uses: Communication between systems, global game state changes (for example,
GameRunLevelChangedEvent), round notifications. - Dispatching:
- Looks up
EventDatafor the event type. - Iterates over all registered
IEntityEventSubscriber(mostly EntitySystems). - Supports
ByRefevents for performance with zero allocations.
2. Directed Events (`RaiseLocalEvent`) ๐ฏ
- Target: Specific
EntityUid. - Usage: Interactions, damage, UI clicks, anything that happens to the entity.
- Dispatching:
1. Finds EventTable for the target entity.
2. Finds a list of component indices (CompIdx) subscribed to this event type.
3. Gets the actual component instances from EntityManager.
4. Calls the cached handler delegate for each component.
- Performance: Highly optimized. Uses
refstructures andUnsafe.Asto avoid boxingstructevents. ๐
3. Component Events (`RaiseComponentEvent`) ๐งฉ
- Target: A specific instance of
IComponenton an entity. - Application: Network processing, specialized component updates.
- Optimization:
- Bypasses the search in the
EventTableentity. - Directly calls a handler for a specific component instance.
- Used internally for
HandleComponentStateand network replication to minimize overhead.
๐ Mechanics of Subscriptions
Registration ๐
Subscriptions are usually registered during EntitySystem.Initialize():
- Directed:
SubscribeLocalEvent<TComp, TEvent>(Handler)-> RegistersHandlerin_eventSubsforTComp. - Broadcast:
SubscribeEvent<TEvent>(Handler)-> RegistersHandlerto_eventData.
###Ordering ๐ข
Events/Subscriptions support explicit ordering using the before and after types.
- EventBus topologically sorts handlers based on these constraints.
- This ensures a deterministic order of execution (e.g. the armor system handles damage before the health system).
- โ ๏ธ Warning: Circular dependencies in order will throw an exception on initialization.
๐ ๏ธ Optimization Techniques
EventBus uses aggressive optimization to support thousands of events per tick:
- Ref Events (
ByRefEventAttribute): Events can be marked for passing by reference. This avoids copying large structures. ๐ฆโก๏ธ - Unit Structs: Internally, the bus uses the
ref UnitandUnsafe.Aspointers to erase event argument types without boxing them intoobject. ๐งโโ๏ธ - Frozen Collections: After initialization, subscription dictionaries are "frozen" (
FrozenDictionary) to optimize read performance. โ๏ธ - Struct Events: Most events are structures (
struct) rather than classes (class) to eliminate pressure on the garbage collector (GC). ๐๏ธ
โ Critical Limitations
- Lock Subscriptions: You cannot subscribe/unsubscribe while dispatching events (unless you use options with
Queue). The bus is blocked during iteration. ๐ - Overhead of Generics: The bus minimizes the use of generics in hot paths to avoid JIT overhead for each event type.
- Thread Safety: EventBus is not thread safe. All events must be raised on the main thread. ๐งต