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> toDeactivate;
private Array<Entity> toRemove;
private Array<Entity> removedEntities;
private ComponentBag[] components;
private Array<BaseSystem> 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();

View File

@ -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++;
}
}