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.
This commit is contained in:
Matt Low 2020-01-26 04:39:23 +04:00
parent 5d9d49971f
commit bd37d4fc65
2 changed files with 26 additions and 2 deletions

View File

@ -13,6 +13,7 @@ public class Engine {
private Array<Entity> toActivate; private Array<Entity> toActivate;
private Array<Entity> toDeactivate; private Array<Entity> toDeactivate;
private Array<Entity> toRemove; private Array<Entity> toRemove;
private Array<Entity> removedEntities;
private ComponentBag[] components; private ComponentBag[] components;
private Array<BaseSystem> systems; private Array<BaseSystem> systems;
@ -26,6 +27,7 @@ public class Engine {
this.toActivate = new Array<>(); this.toActivate = new Array<>();
this.toDeactivate = new Array<>(); this.toDeactivate = new Array<>();
this.toRemove = new Array<>(); this.toRemove = new Array<>();
this.removedEntities = new Array<>(false, 16);
this.systems = new Array<>(); this.systems = new Array<>();
this.listenerRegistry = new ListenerRegistry(); this.listenerRegistry = new ListenerRegistry();
@ -72,13 +74,19 @@ public class Engine {
} }
public Entity createEntity() { 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); entities.add(entity);
return entity; return entity;
} }
protected void removeEntity(Entity entity) { protected void removeEntity(Entity entity) {
entity.deactivate();
toRemove.add(entity); toRemove.add(entity);
} }
@ -117,6 +125,7 @@ public class Engine {
removeAllEntityComponents(entity.getId()); removeAllEntityComponents(entity.getId());
entities.removeValue(entity, true); entities.removeValue(entity, true);
removeEntityFromSystems(entity); removeEntityFromSystems(entity);
removedEntities.add(entity);
} }
toRemove.clear(); toRemove.clear();

View File

@ -3,10 +3,12 @@ package com.me.common.ecs;
public final class Entity { public final class Entity {
private static int nextId = 0; private static int nextId = 0;
private static long nextUniqueId = 0;
private Engine engine; private Engine engine;
private int id; private int id;
private long uniqueId;
private boolean active; private boolean active;
private long componentBits; private long componentBits;
@ -21,6 +23,10 @@ public final class Entity {
return id; return id;
} }
public long getUniqueId() {
return uniqueId;
}
public boolean isActive() { public boolean isActive() {
return active; return active;
} }
@ -71,4 +77,13 @@ public final class Entity {
return componentBits; return componentBits;
} }
protected void reset() {
componentBits = 0;
active = false;
}
protected void updateUniqueId() {
this.uniqueId = nextUniqueId++;
}
} }