Skip to content

Observers

Observers run in response to events.

They are useful when work should happen because something changed, rather than because every frame passed.

SIECS has built-in events for component and relation operations and supports custom event ids.

Observers can also include a query filter so only matching entities receive the callback.

static void OnPositionSet(ecs_observer_event_t *event) {
const Position *p = event->trigger_data;
printf("entity %llu -> %f, %f\n",
(unsigned long long)event->entity,
p->x, p->y);
}
ecs_observer({
.on = EcsOnSet,
.query.components = { ecs_in(Position) },
.callback = OnPositionSet,
});

An observer descriptor contains:

  • one event id;
  • an optional target entity;
  • a query filter;
  • a callback;
  • user data.

The query determines which entity tables are eligible for the event.

An observer without an entity-specific filter can listen globally.

A targeted observer uses .entity to focus on one entity and, for supported inheritance behavior, its direct or indirect IsA instances.

Observers are synchronous reactions to ECS events.

They should not be treated as an unlimited replacement for systems.

Important constraints:

  • callbacks execute as part of the operation/event flow;
  • event payload pointers are borrowed and temporary;
  • excessive observer chains can make control flow hard to follow;
  • observer work still consumes the cost of every emitted matching event;
  • structural changes inside callbacks may be deferred depending on execution context.

SIECS observers do not currently implement multi-event descriptors, monitors, yield-existing or general query-variable binding.

Observers fit well for:

  • initialize derived data when a component is added;
  • validate/log explicit component writes;
  • update an external index on relation changes;
  • mark caches dirty;
  • create tool notifications;
  • react to a custom application event.

Avoid observers for:

  • large per-frame transforms over many entities;
  • work that naturally batches over contiguous data;
  • long event chains where ordering becomes a hidden dependency graph;
  • gameplay logic that is easier to reason about as scheduled systems.

A system is usually better when the same category of entity work happens every frame.

Component hooks belong to one component type and are part of that component’s lifecycle behavior.

Observers are world registrations that react to events and can include query filters.

Use a hook when the behavior is intrinsic to the component’s storage/lifecycle.

Use an observer when a subsystem wants to react externally to an event.

EcsOnAdd fires after a component has been added.

ecs_observer({
.on = EcsOnAdd,
.query.components = { ecs_in(Position) },
.callback = OnAddPosition,
});

The component’s storage exists by the time the event is observed.

For data components, the value may still be in its initial/constructed state if no explicit set has happened yet.

EcsOnSet fires when a component value is explicitly set or replaced through the ECS set path.

ecs_set(e, Position, {10, 20});

can produce an EcsOnSet event for matching observers.

The observer payload is the set value for the duration of the callback.

Do not retain trigger_data after the callback returns.

Inherited values require distinguishing between:

  • the base owning/shared value;
  • an instance receiving effective data;
  • an instance creating an override.

An explicit set on an instance creates/writes local state according to normal component semantics and observer matching is evaluated for the concrete entity.

Observers should not assume that every effective inherited read corresponds to a set event on the instance.

If a shared inherited component is only visible through a base, a write should first establish local writable ownership/override as required by SIECS inheritance semantics.

This prevents an instance write from silently changing the base for all instances.

EcsOnRemove fires when a component is removed.

The removed value is available during the callback, before its storage is fully discarded.

This makes the event suitable for releasing associated external objects, removing registrations or recording final state.

Do not store the component pointer beyond the callback.

SIECS has dedicated relation transition events:

  • EcsOnRelationSet;
  • EcsOnRelationRemove.

EcsOnRelationSet covers a new relation and retargeting an existing relation.

Calling ecs_relate() with the relation already pointing to the same target is a no-op and does not produce a meaningful target transition.

Relation event data contains old/new target information.

Deferred relation changes emit when the command buffer is flushed. Multiple deferred changes to the same relation can collapse to the final structural result.

Observer queries can use component filters and relation constraints.

Example: only react to position writes on entities that are enemies:

ecs_observer({
.on = EcsOnSet,
.query.components = {
ecs_in(Position),
ecs_filter(Enemy),
},
.callback = OnEnemyPositionSet,
});

The event component should be part of the matching model when the observer needs component-specific semantics.

Disabled and Abstract are excluded by default unless mentioned explicitly.

A descriptor can set .entity.

This limits observation to that entity, with SIECS’s inheritance propagation rules allowing targeted observation of concrete IsA instances where documented by the API.

Targeted observers are useful for watching one prototype/base or one important runtime entity without scanning all world events manually.

Allocate/register a custom event id and trigger it:

ecs_event_t DamageEvent = ecs_event();
ecs_observer({
.on = DamageEvent,
.query.components = { ecs_in(Health) },
.callback = OnDamage,
});
DamagePayload payload = { .amount = 10 };
ecs_observer_trigger(entity, DamageEvent, &payload);

The payload type is defined by the application.

C++ custom events use their payload type as the event identity. The compiler checks that ecs::event<T> matches ecs::observe<T>(). Emission is synchronous; the payload view is borrowed until the callback returns. Callbacks can capture state, including move-only values. The world owns that state until the observer is removed, its target is destroyed, or the world shuts down.

SIECS also supports process-wide typed event id registration through ecs_event_register() so C/C++ code can share stable event storage.

A custom event is triggered for a concrete live entity. The observer query is matched against that entity’s current table.

The event does not by itself alter ECS state.

Observers are enabled by default.

ecs_observer_disable(observer);
ecs_observer_enable(observer);

Disabling preserves the registration and id.

Modules use this when disabling all observers captured during module import.

Disabled observers receive no callbacks but remain allocated.

Use ecs_observer_fini() in C or observer.remove() in C++ to destroy a registration completely. C++ observer handles are non-owning; letting a handle go out of scope leaves the registration active.

Do not depend on unspecified ordering between independent observers unless the API explicitly guarantees it.

If application correctness requires a sequence of multi-step work, a scheduled system pipeline is usually a better fit.

Events caused by structural operations on multiple entities should not be used as a global sorting mechanism.

Packed-table mutation, deferred command flushing and recursive relation cleanup can produce an order that is an implementation detail.

A component may have both hooks and observers.

Hooks belong to the component lifecycle. Observer events expose world-level reactions.

Keep both small and avoid building circular mutation chains where a hook triggers an event observer that writes the same component repeatedly.

When a hierarchy is deleted, child cleanup can emit removal events while the tree is being destroyed.

Observer code should treat entity handles defensively and check liveness before performing work on related entities whose lifetime may also be ending.

ecs_observer_desc_t contains:

on
entity
query
callback
user_data

on is one event id.

entity optionally targets observation.

query filters the concrete entity that receives/emits the event.

callback receives ecs_observer_event_t.

user_data carries registration-specific application state.

Because one observer descriptor has one event id, use separate observer registrations when the same callback needs to handle multiple event kinds.

The add event is about structural presence.

The component storage has been introduced.

If application semantics require a fully user-initialized value, OnSet is usually the more precise signal than OnAdd.

The set payload represents the value supplied to the set operation.

Component hooks may also participate in the write.

Observer code should not assume the payload pointer is the forever-stable table address of the component.

Use the payload during the callback; reacquire normal component storage later if needed.

Removal callbacks happen while the removed value is still available for cleanup/inspection.

After the event completes and removal proceeds, the old pointer must be treated as invalid.

Relation observers receive transition information rather than component bytes.

Important cases:

old target = none
new target = X
old target = X
new target = Y
old target = X
new target = none

A same-target ecs_relate(source, R, X) does not represent a meaningful transition and should not be used to manufacture redundant events.

Inside a defer scope:

ecs_defer_begin();
ecs_set(entity, Position, {1, 2});
/* observer may not have run yet */
ecs_defer_end();
/* command flush has applied events */

This is essential to safe system iteration.

Do not write logic that assumes every observer callback has executed at the exact source line of a deferred mutation request.

If code must observe the final world after deferred operations, do it after the flush/scheduler sync boundary.

When multiple deferred structural commands target the same entity/relation, the command buffer can reduce them to the final intended result.

Application observer logic should focus on meaningful state transitions, not use deferred commands as a guaranteed journal of every intermediate API call.

If every intermediate command must be audited, build a dedicated application event/log stream rather than depending on structural command internals.

Observer filters are evaluated against the relevant entity/table state for the event semantics.

This matters around add/remove:

  • adding a component changes which filters are satisfied;
  • removing it changes which filters are satisfied;
  • relation retarget can change target-filtered matches.

Write filters around the state the observer is intended to react to.

Test edge cases when combining required/excluded terms with add/remove events.

Default query exclusions also affect observers.

A global observer using ordinary component filters will not accidentally process disabled/template entities unless those tags are explicitly included in its query logic.

Tooling/cleanup observers that need those populations should mention the tags explicitly.

When .entity targets a base, SIECS can forward relevant events from concrete direct/indirect IsA instances according to observer semantics.

The callback entity remains the concrete entity that emitted the event.

This lets a subsystem observe a template family without manually registering one observer per instance.

Do not confuse this with shared inherited component storage: event target propagation and field ownership are distinct concepts.

ecs_observer_init() validates the descriptor and returns an observer id.

Toggling preserves the registration/query metadata.

ecs_observer_fini() releases the observer registration.

Do not use an observer id after finalization.

Module disable uses enable/disable, not finalization, so re-enabling the module restores the captured observer.

A custom event id has no built-in payload schema.

Define one clearly:

typedef struct {
ecs_entity_t attacker;
float amount;
} DamageEvent;

All triggers/observers for that id must agree.

A custom event payload can be NULL if the event is only a signal.

If asynchronous persistence is needed, copy the payload into application-owned storage. The observer trigger data pointer is borrowed.

Observers answer:

"Something happened; react now."

Systems answer:

"What is the current world state; transform all matching data."

Use observers for transition side effects.

Use systems for state evolution.

Example:

  • observer marks NavDirty when obstacle data changes;
  • system rebuilds all dirty navigation chunks in a controlled phase.

This combines event responsiveness with batch-friendly expensive work.

Observer cost is approximately tied to event frequency and filter work.

A low-frequency expensive initialization observer may be fine.

A tiny observer that fires millions of times during bulk loading can still become expensive due to call/event overhead.

For bulk initialization:

  • defer/batch structural work;
  • keep hooks/observers small;
  • consider a post-load system for derived bulk processing.

If observer A must always run before B for correctness, separate synchronous callbacks may be the wrong abstraction.

Prefer:

  1. observer records/marks state;
  2. scheduled system A processes it;
  3. system B depends on A with phase/.after.

This makes order visible to the scheduler and documentation.

An observer can trigger ECS mutations that produce more events.

Design against accidental recursion:

OnSet(Position)
-> set Position again
-> OnSet(Position)
-> ...

Use guards, compare old/new data, defer a different operation, or restructure the logic as a system.

The same caution applies to relation observers that retarget the same relation.