From a8e5e723b7e1891c9b352261a3ee4c3d3563e8cf Mon Sep 17 00:00:00 2001 From: Elizabeth Hunt Date: Sun, 26 Oct 2025 21:38:22 -0700 Subject: Checkpoint two --- .../commonMain/kotlin/coffee/liz/ecs/DAGWorld.kt | 29 ++++++++++------------ 1 file changed, 13 insertions(+), 16 deletions(-) (limited to 'composeApp/src/commonMain/kotlin/coffee/liz/ecs/DAGWorld.kt') diff --git a/composeApp/src/commonMain/kotlin/coffee/liz/ecs/DAGWorld.kt b/composeApp/src/commonMain/kotlin/coffee/liz/ecs/DAGWorld.kt index 77cb30b..c6303d3 100644 --- a/composeApp/src/commonMain/kotlin/coffee/liz/ecs/DAGWorld.kt +++ b/composeApp/src/commonMain/kotlin/coffee/liz/ecs/DAGWorld.kt @@ -7,19 +7,20 @@ import kotlin.reflect.KClass import kotlin.time.Duration /** - * [World] that updates in [System.dependencies] DAG order. + * [World] that updates in [System.dependencies] topological order. */ @OptIn(ExperimentalAtomicApi::class) -class DAGWorld(systems: List>) : World { +class DAGWorld( + systems: List>, +) : World { private val entities = mutableSetOf() private val componentCache = mutableMapOf, MutableSet>() private val systemExecutionOrder: List> = buildExecutionOrder(systems) private val nextEntityId = AtomicInt(0) - override fun createEntity(): Entity { - return Entity(nextEntityId.incrementAndFetch()) + override fun createEntity(): Entity = + Entity(nextEntityId.incrementAndFetch()) .also { entities.add(it) } - } override fun removeEntity(entity: Entity) { entity.componentTypes().forEach { componentType -> @@ -31,17 +32,18 @@ class DAGWorld(systems: List>) : World { override fun query(vararg componentTypes: KClass): Set { if (componentTypes.isEmpty()) return entities.toSet() - // Start with entities that have the first component type val firstType = componentTypes[0] val candidates = componentCache[firstType] ?: return emptySet() - // Filter to entities that have all component types - return candidates.filter { entity -> - componentTypes.all { entity.has(it) } - }.toSet() + return candidates + .filter { entity -> componentTypes.all { entity.has(it) } } + .toSet() } - override fun update(state: Outside, deltaTime: Duration) { + override fun update( + state: Outside, + deltaTime: Duration, + ) { refreshComponentCache() systemExecutionOrder.forEach { system -> system.update(this, state, deltaTime) @@ -57,9 +59,6 @@ class DAGWorld(systems: List>) : World { } } - /** - * Build a topologically sorted execution order from system dependencies. - */ private fun buildExecutionOrder(systems: List>): List> { if (systems.isEmpty()) return emptyList() @@ -88,7 +87,6 @@ class DAGWorld(systems: List>) : World { val queue = ArrayDeque>>() val result = mutableListOf>() - // Add all systems with no dependencies to queue queue.addAll(inDegree.filterValues { it == 0 }.keys) while (queue.isNotEmpty()) { @@ -104,7 +102,6 @@ class DAGWorld(systems: List>) : World { } } - // Check for cycles if (result.size != systems.size) { error("Circular dependency detected in systems") } -- cgit v1.2.3-70-g09d2