The Observer serializer tracks the addition and removal of entities and components. It is designed to work in tandem with an SoA (Structure of Arrays) serializer for efficient network synchronization: the Observer serializer handles the presence/absence of entities and components, while the SoA serializer handles the actual component data.
To use it, you must provide a networkTag component. Only entities possessing this tag will be tracked and included in the serialization process. The components array specifies which components' additions and removals should be monitored.
import { addComponent, removeComponent, hasComponent, addEntity, createWorld } from 'bitecs'
import { createObserverSerializer, createObserverDeserializer } from 'bitecs/serialization'
const world = createWorld()
const eid = addEntity(world)
const Position = { x: [] as number[], y: [] as number[] }
const Health = [] as number[]
const Networked = {}
// Create serializers
const serializer = createObserverSerializer(world, Networked, [Position, Health])
const deserializer = createObserverDeserializer(world, Networked, [Position, Health])
// Add some components
addComponent(world, eid, Networked)
addComponent(world, eid, Position)
addComponent(world, eid, Health)
// Serialize changes
const buffer = serializer()
// Reset the state
removeComponent(world, eid, Position)
removeComponent(world, eid, Health)
// Deserialize changes back
deserializer(buffer)
// Verify components were restored
console.assert(hasComponent(world, eid, Position))
console.assert(hasComponent(world, eid, Health))