## Owns every entity. IDs count up from 1 and are never reused within a match, and ## iteration is always in ascending ID order. class_name EntityRegistry extends RefCounted ## Reserved: no entity has this ID. const NONE: int = 0 var _next_id: int = 1 var _by_id: Dictionary = {} func create(archetype: int) -> SimEntity: var entity: SimEntity = SimEntity.new(_next_id, archetype) _next_id += 1 # Dictionaries keep insertion order, and IDs only grow, so this stays sorted. _by_id[entity.id] = entity return entity ## Creates an entity under an ID chosen elsewhere: a network client's copy of one the ## server made. Iteration stays in ascending ID order. func restore(id: int, archetype: int) -> SimEntity: var entity: SimEntity = SimEntity.new(id, archetype) var newest: bool = id >= _next_id _by_id[id] = entity _next_id = maxi(_next_id, id + 1) if not newest: var ids: Array = _by_id.keys() ids.sort() var sorted: Dictionary = {} for key: int in ids: sorted[key] = _by_id[key] _by_id = sorted return entity ## Returns the entity, or null if it doesn't exist or has been removed. func find(id: int) -> SimEntity: return _by_id.get(id) func remove(id: int) -> bool: return _by_id.erase(id) func contains(id: int) -> bool: return _by_id.has(id) func count() -> int: return _by_id.size() func next_id() -> int: return _next_id ## All entities in ascending ID order. Safe to modify the registry while looping over this. func entities() -> Array[SimEntity]: var all: Array[SimEntity] = [] for entity: SimEntity in _by_id.values(): all.append(entity) return all