From bd37d4fc651eae718c1556fca6abe7c6a48306c5 Mon Sep 17 00:00:00 2001 From: Matt Low Date: Sun, 26 Jan 2020 04:39:23 +0400 Subject: [PATCH] Reuse removed entities - prevents massive entity component arrays. Assign each entity a uniqueId as well as their regular ID. The uniqueID of an entity is always difference from past or present active entities. --- core/src/com/me/common/ecs/Engine.java | 13 +++++++++++-- core/src/com/me/common/ecs/Entity.java | 15 +++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/core/src/com/me/common/ecs/Engine.java b/core/src/com/me/common/ecs/Engine.java index 7bf4d65..d9dd968 100644 --- a/core/src/com/me/common/ecs/Engine.java +++ b/core/src/com/me/common/ecs/Engine.java @@ -13,6 +13,7 @@ public class Engine { private Array toActivate; private Array toDeactivate; private Array toRemove; + private Array removedEntities; private ComponentBag[] components; private Array systems; @@ -26,6 +27,7 @@ public class Engine { this.toActivate = new Array<>(); this.toDeactivate = new Array<>(); this.toRemove = new Array<>(); + this.removedEntities = new Array<>(false, 16); this.systems = new Array<>(); this.listenerRegistry = new ListenerRegistry(); @@ -72,13 +74,19 @@ public class Engine { } public Entity createEntity() { - Entity entity = new Entity(this); + Entity entity; + if (!removedEntities.isEmpty()) { + entity = removedEntities.removeIndex(0); + entity.reset(); + } else { + entity = new Entity(this); + } + entity.updateUniqueId(); entities.add(entity); return entity; } protected void removeEntity(Entity entity) { - entity.deactivate(); toRemove.add(entity); } @@ -117,6 +125,7 @@ public class Engine { removeAllEntityComponents(entity.getId()); entities.removeValue(entity, true); removeEntityFromSystems(entity); + removedEntities.add(entity); } toRemove.clear(); diff --git a/core/src/com/me/common/ecs/Entity.java b/core/src/com/me/common/ecs/Entity.java index 3645169..a4aa5e0 100644 --- a/core/src/com/me/common/ecs/Entity.java +++ b/core/src/com/me/common/ecs/Entity.java @@ -3,10 +3,12 @@ package com.me.common.ecs; public final class Entity { private static int nextId = 0; + private static long nextUniqueId = 0; private Engine engine; private int id; + private long uniqueId; private boolean active; private long componentBits; @@ -21,6 +23,10 @@ public final class Entity { return id; } + public long getUniqueId() { + return uniqueId; + } + public boolean isActive() { return active; } @@ -71,4 +77,13 @@ public final class Entity { return componentBits; } + protected void reset() { + componentBits = 0; + active = false; + } + + protected void updateUniqueId() { + this.uniqueId = nextUniqueId++; + } + }